@eduardo191labs/opencode-free-pi 0.5.0 → 0.5.3
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 +27 -10
- package/dist/agents/definitions.d.ts +6 -1
- package/dist/agents/definitions.js +10 -5
- package/dist/catalog/models.d.ts +17 -1
- package/dist/catalog/models.js +38 -4
- package/dist/errors/messages.js +2 -2
- package/dist/plugin.js +12 -3
- package/dist/state.d.ts +12 -0
- package/dist/state.js +2 -0
- package/dist/tools/spend-cache.d.ts +15 -0
- package/dist/tools/spend-cache.js +64 -0
- package/dist/tools/usage.js +20 -0
- package/dist/tools/vision.js +35 -24
- package/dist/tools/web.js +44 -39
- package/package.json +2 -2
- package/src/agents/definitions.ts +10 -5
- package/src/catalog/models.ts +56 -4
- package/src/errors/messages.ts +3 -2
- package/src/plugin.ts +14 -2
- package/src/state.ts +14 -0
- package/src/tools/spend-cache.ts +79 -0
- package/src/tools/usage.ts +23 -0
- package/src/tools/vision.ts +38 -26
- package/src/tools/web.ts +59 -50
package/README.md
CHANGED
|
@@ -89,10 +89,18 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
89
89
|
- **Subagentes identificados**: las sesiones hijas envían
|
|
90
90
|
`x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
|
|
91
91
|
subagentes.
|
|
92
|
-
- **Pensamiento
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
92
|
+
- **Pensamiento sin forzar**: el plugin no envía un `reasoning_effort` por
|
|
93
|
+
defecto. Forzar `none` (como hacía una versión anterior) apagaba el
|
|
94
|
+
razonamiento y los modelos respondían con prisa; dejarlo sin definir usa el
|
|
95
|
+
nivel del servidor. El selector sigue ofreciendo `minimal`, `low`, `medium` y
|
|
96
|
+
`high` mediante `reasoning_effort`, igual que `pi-ai`. No se anuncian
|
|
97
|
+
`thinking_budget` ni `thinking`, porque la ruta `openai-compatible` de
|
|
98
|
+
OpenCode los descarta.
|
|
99
|
+
- **Solo modelos utilizables**: al arrancar se consulta `/me` y el selector
|
|
100
|
+
`/model` incluye únicamente lo que la cuenta puede usar: los modelos
|
|
101
|
+
`free: true` siempre, los de pago mientras queden créditos de la cuota o
|
|
102
|
+
monedero, y los premium solo si hay créditos premium. Los modelos ausentes o
|
|
103
|
+
marcados `unavailable` no se registran.
|
|
96
104
|
- **Sin cache warming**: el plugin desactiva los keep-alives de OpenCode para
|
|
97
105
|
free-pi. El CLI nunca los hace y cada ping gastaría créditos y anuncios.
|
|
98
106
|
- **Timeouts del CLI**: 5 minutos para las cabeceras y para cada trozo de la
|
|
@@ -172,6 +180,14 @@ códigos `daily_cap`, `rolling_cap`, `rate_limited`, `not_found`,
|
|
|
172
180
|
que el CLI, para que el agente sepa cuándo no debe reintentar. Igual que
|
|
173
181
|
`look_at_image`, cada llamada consume allowance.
|
|
174
182
|
|
|
183
|
+
Las tres herramientas que gastan cuota (`web_search`, `docs_lookup` y
|
|
184
|
+
`look_at_image`) comparten una caché de respuestas de 30 minutos: si el modelo,
|
|
185
|
+
un subagente o un reintento piden exactamente lo mismo, se reutiliza la primera
|
|
186
|
+
respuesta y no se vuelve a cobrar. Las llamadas idénticas en paralelo comparten
|
|
187
|
+
una sola petición, y los errores nunca se cachean para que el siguiente intento
|
|
188
|
+
vea el estado real del servidor. La respuesta cacheada lo indica y no incluye
|
|
189
|
+
`cost_usd`.
|
|
190
|
+
|
|
175
191
|
`free_pi_usage` consulta `/me/stats` y resume el tier, los créditos restantes
|
|
176
192
|
con su hora de recarga en ET, los créditos premium o de referidos y los tokens
|
|
177
193
|
de hoy y de por vida. Si el servidor asigna el carril lento, incluye el aviso
|
|
@@ -183,7 +199,7 @@ añadir ruido al contexto.
|
|
|
183
199
|
|
|
184
200
|
## Agentes y subagentes
|
|
185
201
|
|
|
186
|
-
El CLI incluye cuatro personalidades de
|
|
202
|
+
El CLI incluye cuatro personalidades de agente. El plugin las instala como
|
|
187
203
|
agentes Markdown nativos de OpenCode en el directorio global de configuración:
|
|
188
204
|
|
|
189
205
|
```text
|
|
@@ -201,11 +217,12 @@ agentes Markdown nativos de OpenCode en el directorio global de configuración:
|
|
|
201
217
|
| `free-pi/worker` | Ejecuta una tarea completa en su propia ventana de contexto. |
|
|
202
218
|
| `free-pi/reviewer`| Revisión de solo lectura con archivo y línea. |
|
|
203
219
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
220
|
+
Usan `mode: all`, así que aparecen en el selector `/agents` de la TUI como
|
|
221
|
+
agente principal **y** se pueden lanzar con la herramienta `subagent` nativa.
|
|
222
|
+
Heredan el modelo free-pi de la sesión padre. Como subagentes corren en segundo
|
|
223
|
+
plano, comparten el allowance diario y envían su informe al agente principal.
|
|
224
|
+
Así se conservan las sesiones hijas, los permisos, la profundidad de subagentes
|
|
225
|
+
y el resto del comportamiento nativo.
|
|
209
226
|
|
|
210
227
|
El plugin solo reescribe estos archivos si conservan su marca de gestión; si el
|
|
211
228
|
usuario edita o reemplaza uno, se respeta tal cual.
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Native OpenCode agents for free-pi.
|
|
3
3
|
*
|
|
4
|
-
* The provider CLI ships four
|
|
4
|
+
* The provider CLI ships four agent personalities (scout, planner, worker,
|
|
5
5
|
* reviewer) with their own prompts and tool access. OpenCode's V2 plugin API
|
|
6
6
|
* cannot add agents through `AgentEditor`, but it loads Markdown agents from the
|
|
7
7
|
* global config directory. Installing those files is the supported way to map
|
|
8
8
|
* the CLI agents onto OpenCode's native `subagent` tool, so child sessions,
|
|
9
9
|
* background reports, permissions and the agent picker keep working normally.
|
|
10
10
|
*
|
|
11
|
+
* They use `mode: all`: OpenCode only lists non-subagent agents in the `/agents`
|
|
12
|
+
* picker, and only agents whose mode is not `primary` can run through the
|
|
13
|
+
* `subagent` tool. `all` satisfies both, so the same personalities are
|
|
14
|
+
* selectable as the main agent and spawnable as children.
|
|
15
|
+
*
|
|
11
16
|
* Files live under `agents/free-pi/`, which makes their IDs `free-pi/scout`,
|
|
12
17
|
* `free-pi/planner`, `free-pi/worker` and `free-pi/reviewer`.
|
|
13
18
|
*/
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Native OpenCode agents for free-pi.
|
|
3
3
|
*
|
|
4
|
-
* The provider CLI ships four
|
|
4
|
+
* The provider CLI ships four agent personalities (scout, planner, worker,
|
|
5
5
|
* reviewer) with their own prompts and tool access. OpenCode's V2 plugin API
|
|
6
6
|
* cannot add agents through `AgentEditor`, but it loads Markdown agents from the
|
|
7
7
|
* global config directory. Installing those files is the supported way to map
|
|
8
8
|
* the CLI agents onto OpenCode's native `subagent` tool, so child sessions,
|
|
9
9
|
* background reports, permissions and the agent picker keep working normally.
|
|
10
10
|
*
|
|
11
|
+
* They use `mode: all`: OpenCode only lists non-subagent agents in the `/agents`
|
|
12
|
+
* picker, and only agents whose mode is not `primary` can run through the
|
|
13
|
+
* `subagent` tool. `all` satisfies both, so the same personalities are
|
|
14
|
+
* selectable as the main agent and spawnable as children.
|
|
15
|
+
*
|
|
11
16
|
* Files live under `agents/free-pi/`, which makes their IDs `free-pi/scout`,
|
|
12
17
|
* `free-pi/planner`, `free-pi/worker` and `free-pi/reviewer`.
|
|
13
18
|
*/
|
|
@@ -75,7 +80,7 @@ over running an external CLI.
|
|
|
75
80
|
`;
|
|
76
81
|
const SCOUT = `---
|
|
77
82
|
description: Read-only recon. Locates code, traces how pieces connect, and returns structured findings the lead can use without re-reading the files.
|
|
78
|
-
mode:
|
|
83
|
+
mode: all
|
|
79
84
|
color: "#4cc9f0"
|
|
80
85
|
permissions:
|
|
81
86
|
- action: edit
|
|
@@ -110,7 +115,7 @@ Which file to look at first and why.
|
|
|
110
115
|
`;
|
|
111
116
|
const PLANNER = `---
|
|
112
117
|
description: Turns context and requirements into a concrete implementation plan. Read-only: never edits files or runs commands.
|
|
113
|
-
mode:
|
|
118
|
+
mode: all
|
|
114
119
|
color: "#b5179e"
|
|
115
120
|
permissions:
|
|
116
121
|
- action: edit
|
|
@@ -142,7 +147,7 @@ Keep the plan concrete: a worker agent will execute it verbatim.
|
|
|
142
147
|
`;
|
|
143
148
|
const WORKER = `---
|
|
144
149
|
description: Full-capability worker that carries out one delegated task in its own context window and reports what changed.
|
|
145
|
-
mode:
|
|
150
|
+
mode: all
|
|
146
151
|
color: "#2a9d8f"
|
|
147
152
|
permissions:
|
|
148
153
|
- action: subagent
|
|
@@ -167,7 +172,7 @@ Anything the lead should know.
|
|
|
167
172
|
`;
|
|
168
173
|
const REVIEWER = `---
|
|
169
174
|
description: Senior code reviewer for quality, security and maintainability. Read-only; reports findings with file and line references.
|
|
170
|
-
mode:
|
|
175
|
+
mode: all
|
|
171
176
|
color: "#e76f51"
|
|
172
177
|
permissions:
|
|
173
178
|
- action: edit
|
package/dist/catalog/models.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
|
-
import type { Catalog, CatalogModel, ModelDefinition, ModelRegistry, ModelsDevModel, ReasoningOption, RegistryCandidate } from "../types.js";
|
|
2
|
+
import type { Catalog, CatalogModel, MeResponse, ModelDefinition, ModelRegistry, ModelsDevModel, ReasoningOption, RegistryCandidate } from "../types.js";
|
|
3
3
|
export type VariantMap = Record<string, Record<string, unknown>>;
|
|
4
4
|
export type ModelMap = Record<string, ModelDefinition>;
|
|
5
5
|
export declare function usableModels(catalog: Catalog | undefined): CatalogModel[];
|
|
@@ -16,4 +16,20 @@ export type BuildModelsOptions = {
|
|
|
16
16
|
/** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
|
|
17
17
|
compact100?: boolean;
|
|
18
18
|
};
|
|
19
|
+
/**
|
|
20
|
+
* What the signed-in account can actually use, derived from `GET /me`.
|
|
21
|
+
*
|
|
22
|
+
* free-pi lets the free allowance pay for every non-premium model while the
|
|
23
|
+
* daily credits last, so those stay available even when the wallet is empty.
|
|
24
|
+
* Premium-only models need premium credits, and showing them to an account
|
|
25
|
+
* without any only produces `model_requires_credits` failures from `/model`.
|
|
26
|
+
*/
|
|
27
|
+
export type AccountAccess = {
|
|
28
|
+
readonly premiumCredits: number;
|
|
29
|
+
readonly walletCredits: number;
|
|
30
|
+
readonly remainingCredits: number;
|
|
31
|
+
readonly hasAllowance: boolean;
|
|
32
|
+
};
|
|
33
|
+
export declare function accountAccess(me: MeResponse | undefined): AccountAccess | undefined;
|
|
34
|
+
export declare function filterAccessibleModels(models: CatalogModel[], access: AccountAccess | undefined): CatalogModel[];
|
|
19
35
|
export declare function buildModels(models: CatalogModel[], candidates?: RegistryCandidate[], options?: BuildModelsOptions): ModelMap;
|
package/dist/catalog/models.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
|
-
import { COMPACT100_CONTEXT_WINDOW, CONTEXT_WINDOW,
|
|
2
|
+
import { COMPACT100_CONTEXT_WINDOW, CONTEXT_WINDOW, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, } from "../constants.js";
|
|
3
3
|
import { positiveNumber } from "../utils/numbers.js";
|
|
4
4
|
import { cleanText } from "../utils/text.js";
|
|
5
5
|
export function usableModels(catalog) {
|
|
@@ -151,6 +151,43 @@ export function modelVariants(options, _outputLimit) {
|
|
|
151
151
|
}
|
|
152
152
|
return variants;
|
|
153
153
|
}
|
|
154
|
+
export function accountAccess(me) {
|
|
155
|
+
if (!me)
|
|
156
|
+
return undefined;
|
|
157
|
+
const credits = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
158
|
+
const wallet = credits(me.bonus_wallet_credits) +
|
|
159
|
+
credits(me.regular_wallet_credits) +
|
|
160
|
+
credits(me.bonus_credits);
|
|
161
|
+
const remaining = credits(me.remaining_credits_today);
|
|
162
|
+
return {
|
|
163
|
+
premiumCredits: credits(me.premium_credits) +
|
|
164
|
+
credits(me.premium_bought_credits) +
|
|
165
|
+
credits(me.premium_gifted_credits),
|
|
166
|
+
walletCredits: wallet,
|
|
167
|
+
remainingCredits: remaining,
|
|
168
|
+
hasAllowance: remaining > 0 || credits(me.remaining_usd_today) > 0,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function isPremiumModel(model) {
|
|
172
|
+
if (model.tier === "premium")
|
|
173
|
+
return true;
|
|
174
|
+
return /premium\s+credits/i.test(model.note ?? "");
|
|
175
|
+
}
|
|
176
|
+
export function filterAccessibleModels(models, access) {
|
|
177
|
+
// Without a quota snapshot, show everything instead of guessing and hiding
|
|
178
|
+
// models the account may be able to use.
|
|
179
|
+
if (!access)
|
|
180
|
+
return models.filter((model) => model.unavailable !== true);
|
|
181
|
+
return models.filter((model) => {
|
|
182
|
+
if (model.unavailable === true)
|
|
183
|
+
return false;
|
|
184
|
+
if (isPremiumModel(model))
|
|
185
|
+
return access.premiumCredits > 0;
|
|
186
|
+
if (model.free === true)
|
|
187
|
+
return true;
|
|
188
|
+
return access.hasAllowance || access.walletCredits > 0;
|
|
189
|
+
});
|
|
190
|
+
}
|
|
154
191
|
export function buildModels(models, candidates = [], options = {}) {
|
|
155
192
|
const result = {};
|
|
156
193
|
for (const model of models) {
|
|
@@ -180,9 +217,6 @@ export function buildModels(models, candidates = [], options = {}) {
|
|
|
180
217
|
reasoning,
|
|
181
218
|
reasoning_options: reasoningOptions,
|
|
182
219
|
variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
|
|
183
|
-
...(reasoning
|
|
184
|
-
? { settings: { reasoningEffort: DEFAULT_REASONING_EFFORT } }
|
|
185
|
-
: {}),
|
|
186
220
|
enabled: model.unavailable !== true,
|
|
187
221
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
188
222
|
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
package/dist/errors/messages.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/** Human-readable copy for free-pi error codes. */
|
|
2
2
|
import { formatRefillTime, formatWait } from "../utils/numbers.js";
|
|
3
3
|
const FREE_PI_ERROR_TEXT = {
|
|
4
|
-
daily_cap: "Out of free credits today;
|
|
4
|
+
daily_cap: "Out of free credits today; they refill at UTC midnight, or add credits to keep going now.",
|
|
5
5
|
queue_wait: "free-pi is near its daily budget; wait and retry.",
|
|
6
|
-
rolling_cap: "Over the rolling spend cap on the free tier; wait for the retry window.",
|
|
6
|
+
rolling_cap: "Over the rolling spend cap on the free tier; wait for the retry window or add credits.",
|
|
7
7
|
concurrent: "Only one request at a time on the free tier; wait for the current one to finish.",
|
|
8
8
|
concurrent_session: "This account is already at its free-pi session limit. Wait for a slot to free up and retry.",
|
|
9
9
|
context_ceiling: "This conversation is too large for free-pi's context limit.",
|
package/dist/plugin.js
CHANGED
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
import { Plugin } from "@opencode/plugin";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { FREE_PI_SKILL, FREE_PI_SKILL_DESCRIPTION, FREE_PI_SKILL_ID, FREE_PI_SKILL_NAME, installFreePiAgents, openCodeConfigDir, } from "./agents/definitions.js";
|
|
5
|
+
import { fetchQuota } from "./api/quota.js";
|
|
5
6
|
import { closeFreePiSession } from "./api/session.js";
|
|
6
7
|
import { readCredentialsToken } from "./auth/credentials.js";
|
|
7
8
|
import { tokenFromCredential } from "./auth/credential.js";
|
|
8
9
|
import { fetchCatalog } from "./catalog/catalog.js";
|
|
9
|
-
import { buildModels, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
|
|
10
|
+
import { accountAccess, buildModels, filterAccessibleModels, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
|
|
10
11
|
import { fetchModelsRegistry } from "./catalog/registry.js";
|
|
11
12
|
import { applyProvider } from "./catalog/v2.js";
|
|
12
13
|
import { DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
|
|
@@ -85,14 +86,22 @@ async function setup(ctx) {
|
|
|
85
86
|
catch (error) {
|
|
86
87
|
log.warn("Could not register the free-pi skill", error);
|
|
87
88
|
}
|
|
88
|
-
const [catalogResult, registryResult] = await Promise.all([
|
|
89
|
+
const [catalogResult, registryResult, quotaResult] = await Promise.all([
|
|
89
90
|
settle(fetchCatalog(deps), undefined),
|
|
90
91
|
settle(fetchModelsRegistry(deps), undefined),
|
|
92
|
+
settle(fetchQuota(deps), undefined),
|
|
91
93
|
]);
|
|
92
94
|
// The fetch may finish just after `settle` gives up; reuse whatever landed.
|
|
93
95
|
const catalog = catalogResult ?? state.cachedCatalog;
|
|
94
96
|
const registry = registryResult ?? state.cachedRegistry;
|
|
95
|
-
const
|
|
97
|
+
const quota = quotaResult ?? state.quotaCache;
|
|
98
|
+
// The picker must only offer models this account can actually use: premium
|
|
99
|
+
// models need premium credits, and paid models need allowance or wallet.
|
|
100
|
+
// Without a quota snapshot every model stays visible.
|
|
101
|
+
const access = accountAccess(quota?.me);
|
|
102
|
+
const { main: catalogMain, defense: catalogDefense } = partitionModels(catalog);
|
|
103
|
+
const main = filterAccessibleModels(catalogMain, access);
|
|
104
|
+
const defense = filterAccessibleModels(catalogDefense, access);
|
|
96
105
|
const candidates = modelRegistryCandidates(registry);
|
|
97
106
|
const buildOptions = { compact100: state.costExperimentArm === "compact100" };
|
|
98
107
|
const mainModels = buildModels(main, candidates, buildOptions);
|
package/dist/state.d.ts
CHANGED
|
@@ -47,6 +47,18 @@ export type RuntimeState = {
|
|
|
47
47
|
trackedModels: Map<string, TrackedModel>;
|
|
48
48
|
cacheMisses: Map<string, CacheMissState>;
|
|
49
49
|
toolStats: Map<string, ToolStats>;
|
|
50
|
+
/** Successful paid-tool answers, keyed by canonical input, to avoid rebilling. */
|
|
51
|
+
toolSpend: Map<string, {
|
|
52
|
+
at: number;
|
|
53
|
+
output: {
|
|
54
|
+
content: ReadonlyArray<{
|
|
55
|
+
type: "text";
|
|
56
|
+
text: string;
|
|
57
|
+
}>;
|
|
58
|
+
metadata: Record<string, unknown>;
|
|
59
|
+
};
|
|
60
|
+
}>;
|
|
61
|
+
toolSpendPending: Map<string, Promise<any>>;
|
|
50
62
|
subagentSessions: Set<string>;
|
|
51
63
|
};
|
|
52
64
|
export declare function createRuntimeState(): RuntimeState;
|
package/dist/state.js
CHANGED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spend-once cache for the free-pi tools that consume allowance.
|
|
3
|
+
*
|
|
4
|
+
* `web_search`, `docs_lookup` and `look_at_image` bill the user every time they
|
|
5
|
+
* run. Models often ask the same question twice in a turn (or a subagent and
|
|
6
|
+
* its lead both ask it), so identical inputs reuse the first answer instead of
|
|
7
|
+
* spending credits again. Failures are never cached: the next attempt must
|
|
8
|
+
* reach the server and see the real error. Concurrent identical calls share one
|
|
9
|
+
* in-flight request, so a parallel tool call cannot double-charge either.
|
|
10
|
+
*/
|
|
11
|
+
import type { Deps } from "../deps.js";
|
|
12
|
+
import type { ToolOutput } from "./api.js";
|
|
13
|
+
/** Long enough to cover a turn and its follow-ups, short enough to stay fresh. */
|
|
14
|
+
export declare const SPEND_CACHE_TTL_MS: number;
|
|
15
|
+
export declare function spendOnce(deps: Deps, key: string, run: () => Promise<ToolOutput>): Promise<ToolOutput>;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spend-once cache for the free-pi tools that consume allowance.
|
|
3
|
+
*
|
|
4
|
+
* `web_search`, `docs_lookup` and `look_at_image` bill the user every time they
|
|
5
|
+
* run. Models often ask the same question twice in a turn (or a subagent and
|
|
6
|
+
* its lead both ask it), so identical inputs reuse the first answer instead of
|
|
7
|
+
* spending credits again. Failures are never cached: the next attempt must
|
|
8
|
+
* reach the server and see the real error. Concurrent identical calls share one
|
|
9
|
+
* in-flight request, so a parallel tool call cannot double-charge either.
|
|
10
|
+
*/
|
|
11
|
+
/** Long enough to cover a turn and its follow-ups, short enough to stay fresh. */
|
|
12
|
+
export const SPEND_CACHE_TTL_MS = 30 * 60 * 1_000;
|
|
13
|
+
const SPEND_CACHE_LIMIT = 128;
|
|
14
|
+
function trim(deps) {
|
|
15
|
+
const now = Date.now();
|
|
16
|
+
for (const [key, entry] of deps.state.toolSpend) {
|
|
17
|
+
if (now - entry.at >= SPEND_CACHE_TTL_MS)
|
|
18
|
+
deps.state.toolSpend.delete(key);
|
|
19
|
+
}
|
|
20
|
+
while (deps.state.toolSpend.size > SPEND_CACHE_LIMIT) {
|
|
21
|
+
const oldest = deps.state.toolSpend.keys().next().value;
|
|
22
|
+
if (oldest === undefined)
|
|
23
|
+
break;
|
|
24
|
+
deps.state.toolSpend.delete(oldest);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function cachedResult(entry) {
|
|
28
|
+
const { cost_usd: _spent, ...metadata } = entry.output.metadata;
|
|
29
|
+
return {
|
|
30
|
+
content: entry.output.content.map((part) => ({
|
|
31
|
+
type: "text",
|
|
32
|
+
text: `${part.text}\n\n(cached answer from earlier - no allowance used)`,
|
|
33
|
+
})),
|
|
34
|
+
metadata: { ...metadata, cached: true },
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export async function spendOnce(deps, key, run) {
|
|
38
|
+
const entry = deps.state.toolSpend.get(key);
|
|
39
|
+
if (entry && Date.now() - entry.at < SPEND_CACHE_TTL_MS) {
|
|
40
|
+
deps.log.info("reused a cached free-pi tool answer", { key });
|
|
41
|
+
return cachedResult(entry);
|
|
42
|
+
}
|
|
43
|
+
const pending = deps.state.toolSpendPending.get(key);
|
|
44
|
+
if (pending) {
|
|
45
|
+
const output = await pending;
|
|
46
|
+
return output.metadata.ok
|
|
47
|
+
? cachedResult({ at: Date.now(), output })
|
|
48
|
+
: run();
|
|
49
|
+
}
|
|
50
|
+
const request = run();
|
|
51
|
+
deps.state.toolSpendPending.set(key, request);
|
|
52
|
+
try {
|
|
53
|
+
const output = await request;
|
|
54
|
+
if (output.metadata.ok) {
|
|
55
|
+
deps.state.toolSpend.set(key, { at: Date.now(), output });
|
|
56
|
+
trim(deps);
|
|
57
|
+
}
|
|
58
|
+
return output;
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
if (deps.state.toolSpendPending.get(key) === request)
|
|
62
|
+
deps.state.toolSpendPending.delete(key);
|
|
63
|
+
}
|
|
64
|
+
}
|
package/dist/tools/usage.js
CHANGED
|
@@ -45,6 +45,25 @@ export function formatUsage(stats) {
|
|
|
45
45
|
typeof refillAt === "string"
|
|
46
46
|
? creditsLeftLine(remaining, allowance, new Date(refillAt))
|
|
47
47
|
: `today: ${percentUsed(t.spent_usd_today ?? 0, t.cap_usd_today ?? 0)}% of your free daily allowance used`;
|
|
48
|
+
const hasCredits = typeof remaining === "number" &&
|
|
49
|
+
typeof allowance === "number" &&
|
|
50
|
+
allowance > 0;
|
|
51
|
+
const low = hasCredits && remaining > 0 && remaining <= allowance * 0.1;
|
|
52
|
+
const empty = hasCredits && remaining <= 0;
|
|
53
|
+
const buyUrl = typeof t.buy_url === "string" && t.buy_url ? t.buy_url : undefined;
|
|
54
|
+
const creditLines = [
|
|
55
|
+
...(low
|
|
56
|
+
? [
|
|
57
|
+
`low credits: ${Math.round((remaining / allowance) * 100)}% of today's allowance left`,
|
|
58
|
+
]
|
|
59
|
+
: []),
|
|
60
|
+
...(empty
|
|
61
|
+
? [
|
|
62
|
+
"Out of free credits today; they refill at the reset time, or add credits to keep going now.",
|
|
63
|
+
]
|
|
64
|
+
: []),
|
|
65
|
+
...(buyUrl && (low || empty) ? [`Buy credits: ${buyUrl}`] : []),
|
|
66
|
+
];
|
|
48
67
|
const tieredLines = tiered
|
|
49
68
|
? [
|
|
50
69
|
creditsLeftLine(remaining, allowance, new Date(refillAt)),
|
|
@@ -59,6 +78,7 @@ export function formatUsage(stats) {
|
|
|
59
78
|
return [
|
|
60
79
|
`tier: ${t.tier ?? "unknown"}`,
|
|
61
80
|
...(tiered ? [tieredLines[0]] : [todayLine]),
|
|
81
|
+
...creditLines,
|
|
62
82
|
...(t.lane === "fallback" ? [SLOW_LANE_NOTICE] : []),
|
|
63
83
|
...(tiered
|
|
64
84
|
? tieredLines.slice(1)
|
package/dist/tools/vision.js
CHANGED
|
@@ -6,10 +6,12 @@
|
|
|
6
6
|
* `/tools/vision` and returns the vision model's text answer. Each call counts
|
|
7
7
|
* against the user's daily allowance.
|
|
8
8
|
*/
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
9
10
|
import { resolveToken } from "../auth/token.js";
|
|
10
11
|
import { isFreePiSession } from "../session/tools.js";
|
|
11
12
|
import { resolveBaseUrl } from "../utils/urls.js";
|
|
12
13
|
import { loadImage, prepareImage } from "./image.js";
|
|
14
|
+
import { spendOnce } from "./spend-cache.js";
|
|
13
15
|
import { withVisionSlot } from "./vision-queue.js";
|
|
14
16
|
const TOOL_NAME = "look_at_image";
|
|
15
17
|
const TIMEOUT_MS = 90_000;
|
|
@@ -212,30 +214,39 @@ async function executeVision(ctx, deps, raw, context) {
|
|
|
212
214
|
if (!token) {
|
|
213
215
|
return fail("look_at_image needs a free-pi sign-in. Do not retry; tell the user to connect the free-pi integration, and continue without this tool.");
|
|
214
216
|
}
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
217
|
+
const imageKey = createHash("sha256")
|
|
218
|
+
.update(prepared.mime)
|
|
219
|
+
.update("\u0000")
|
|
220
|
+
.update(prepared.data)
|
|
221
|
+
.update("\u0000")
|
|
222
|
+
.update(question)
|
|
223
|
+
.digest("hex");
|
|
224
|
+
return spendOnce(deps, `vision:${imageKey}`, async () => {
|
|
225
|
+
const queued = await withVisionSlot(deps.log, () => askVision(deps, token, prepared.data, prepared.mime, question, context.signal));
|
|
226
|
+
if (!queued.ok) {
|
|
227
|
+
return fail("Another image question is still running. Wait a moment and call look_at_image again.");
|
|
228
|
+
}
|
|
229
|
+
if (!queued.value.ok)
|
|
230
|
+
return fail(queued.value.text);
|
|
231
|
+
const { answer, attempts } = queued.value;
|
|
232
|
+
const elapsed = Date.now() - startedAt;
|
|
233
|
+
deps.log.info("look_at_image answered", {
|
|
234
|
+
path,
|
|
235
|
+
ms: elapsed,
|
|
236
|
+
attempts,
|
|
237
|
+
resized: prepared.resized,
|
|
238
|
+
bytes: prepared.bytes,
|
|
239
|
+
size: `${prepared.width}x${prepared.height}`,
|
|
240
|
+
mime: prepared.mime,
|
|
241
|
+
model: answer.model,
|
|
242
|
+
});
|
|
243
|
+
return done(questionText(path, answer.text), {
|
|
244
|
+
ok: true,
|
|
245
|
+
...(answer.cost_usd !== undefined ? { cost_usd: answer.cost_usd } : {}),
|
|
246
|
+
...(answer.model !== undefined ? { model: answer.model } : {}),
|
|
247
|
+
elapsed_ms: elapsed,
|
|
248
|
+
attempts,
|
|
249
|
+
});
|
|
239
250
|
});
|
|
240
251
|
}
|
|
241
252
|
/**
|
package/dist/tools/web.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* CLI, and are only exposed inside free-pi sessions.
|
|
6
6
|
*/
|
|
7
7
|
import { done, fail, freePiRequest, GATED_TEXT, isGatedSession, mappedText, } from "./api.js";
|
|
8
|
+
import { spendOnce } from "./spend-cache.js";
|
|
8
9
|
const ERRORS = {
|
|
9
10
|
daily_cap: "The user's daily free usage is used up. Do not retry; tell the user and continue without this tool.",
|
|
10
11
|
rolling_cap: "The user's short-term usage limit is reached. Do not retry; continue without this tool.",
|
|
@@ -82,28 +83,30 @@ async function executeWebSearch(deps, raw, context) {
|
|
|
82
83
|
if (!query)
|
|
83
84
|
return fail("web_search needs a query.");
|
|
84
85
|
const num = typeof input?.num_results === "number" ? input.num_results : undefined;
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
86
|
+
return spendOnce(deps, `web:${query}\u0000${num ?? ""}`, async () => {
|
|
87
|
+
const result = await freePiRequest(deps, {
|
|
88
|
+
path: "/tools/web-search",
|
|
89
|
+
method: "POST",
|
|
90
|
+
body: { query, ...(num !== undefined ? { num_results: num } : {}) },
|
|
91
|
+
timeoutMs: 30_000,
|
|
92
|
+
signal: context.signal,
|
|
93
|
+
label: "The web search",
|
|
94
|
+
});
|
|
95
|
+
if (!result.ok)
|
|
96
|
+
return fail(mappedText(ERRORS, result));
|
|
97
|
+
deps.log.info("web_search answered", {
|
|
98
|
+
query,
|
|
99
|
+
results: Array.isArray(result.data?.results)
|
|
100
|
+
? result.data.results.length
|
|
101
|
+
: 0,
|
|
102
|
+
costUsd: result.data?.cost_usd,
|
|
103
|
+
});
|
|
104
|
+
return done(formatWebResults(query, result.data?.results ?? []), {
|
|
105
|
+
ok: true,
|
|
106
|
+
...(typeof result.data?.cost_usd === "number"
|
|
107
|
+
? { cost_usd: result.data.cost_usd }
|
|
108
|
+
: {}),
|
|
109
|
+
});
|
|
107
110
|
});
|
|
108
111
|
}
|
|
109
112
|
async function executeDocsLookup(deps, raw, context) {
|
|
@@ -117,7 +120,7 @@ async function executeDocsLookup(deps, raw, context) {
|
|
|
117
120
|
return fail("docs_lookup needs a library name.");
|
|
118
121
|
if (!query)
|
|
119
122
|
return fail("docs_lookup needs a specific question.");
|
|
120
|
-
const result = await freePiRequest(deps, {
|
|
123
|
+
const result = await spendOnce(deps, `docs:${library}\u0000${query}\u0000${libraryId}`, () => freePiRequest(deps, {
|
|
121
124
|
path: "/tools/docs",
|
|
122
125
|
method: "POST",
|
|
123
126
|
body: {
|
|
@@ -128,22 +131,24 @@ async function executeDocsLookup(deps, raw, context) {
|
|
|
128
131
|
timeoutMs: 30_000,
|
|
129
132
|
signal: context.signal,
|
|
130
133
|
label: "The documentation lookup",
|
|
131
|
-
})
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
134
|
+
}).then((lookup) => {
|
|
135
|
+
if (!lookup.ok)
|
|
136
|
+
return fail(mappedText(ERRORS, lookup, library));
|
|
137
|
+
const data = lookup.data ?? {};
|
|
138
|
+
deps.log.info("docs_lookup answered", {
|
|
139
|
+
library,
|
|
140
|
+
libraryID: data.library_id,
|
|
141
|
+
costUsd: data.cost_usd,
|
|
142
|
+
});
|
|
143
|
+
return done(`${data.title ?? library} (library_id: ${data.library_id ?? "unknown"})\n\n${data.docs ?? ""}`, {
|
|
144
|
+
ok: true,
|
|
145
|
+
library_id: data.library_id,
|
|
146
|
+
...(typeof data.cost_usd === "number"
|
|
147
|
+
? { cost_usd: data.cost_usd }
|
|
148
|
+
: {}),
|
|
149
|
+
});
|
|
150
|
+
}));
|
|
151
|
+
return result;
|
|
147
152
|
}
|
|
148
153
|
export async function registerWebTools(ctx, deps) {
|
|
149
154
|
return ctx.tool.transform((editor) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eduardo191labs/opencode-free-pi",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.3",
|
|
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": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
|
|
26
26
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
27
|
-
"test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/tools.mjs",
|
|
27
|
+
"test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/spend.mjs && node test/tools.mjs",
|
|
28
28
|
"prepublishOnly": "npm run build",
|
|
29
29
|
"postinstall": "node scripts/postinstall.mjs"
|
|
30
30
|
},
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Native OpenCode agents for free-pi.
|
|
3
3
|
*
|
|
4
|
-
* The provider CLI ships four
|
|
4
|
+
* The provider CLI ships four agent personalities (scout, planner, worker,
|
|
5
5
|
* reviewer) with their own prompts and tool access. OpenCode's V2 plugin API
|
|
6
6
|
* cannot add agents through `AgentEditor`, but it loads Markdown agents from the
|
|
7
7
|
* global config directory. Installing those files is the supported way to map
|
|
8
8
|
* the CLI agents onto OpenCode's native `subagent` tool, so child sessions,
|
|
9
9
|
* background reports, permissions and the agent picker keep working normally.
|
|
10
10
|
*
|
|
11
|
+
* They use `mode: all`: OpenCode only lists non-subagent agents in the `/agents`
|
|
12
|
+
* picker, and only agents whose mode is not `primary` can run through the
|
|
13
|
+
* `subagent` tool. `all` satisfies both, so the same personalities are
|
|
14
|
+
* selectable as the main agent and spawnable as children.
|
|
15
|
+
*
|
|
11
16
|
* Files live under `agents/free-pi/`, which makes their IDs `free-pi/scout`,
|
|
12
17
|
* `free-pi/planner`, `free-pi/worker` and `free-pi/reviewer`.
|
|
13
18
|
*/
|
|
@@ -85,7 +90,7 @@ over running an external CLI.
|
|
|
85
90
|
|
|
86
91
|
const SCOUT = `---
|
|
87
92
|
description: Read-only recon. Locates code, traces how pieces connect, and returns structured findings the lead can use without re-reading the files.
|
|
88
|
-
mode:
|
|
93
|
+
mode: all
|
|
89
94
|
color: "#4cc9f0"
|
|
90
95
|
permissions:
|
|
91
96
|
- action: edit
|
|
@@ -121,7 +126,7 @@ Which file to look at first and why.
|
|
|
121
126
|
|
|
122
127
|
const PLANNER = `---
|
|
123
128
|
description: Turns context and requirements into a concrete implementation plan. Read-only: never edits files or runs commands.
|
|
124
|
-
mode:
|
|
129
|
+
mode: all
|
|
125
130
|
color: "#b5179e"
|
|
126
131
|
permissions:
|
|
127
132
|
- action: edit
|
|
@@ -154,7 +159,7 @@ Keep the plan concrete: a worker agent will execute it verbatim.
|
|
|
154
159
|
|
|
155
160
|
const WORKER = `---
|
|
156
161
|
description: Full-capability worker that carries out one delegated task in its own context window and reports what changed.
|
|
157
|
-
mode:
|
|
162
|
+
mode: all
|
|
158
163
|
color: "#2a9d8f"
|
|
159
164
|
permissions:
|
|
160
165
|
- action: subagent
|
|
@@ -180,7 +185,7 @@ Anything the lead should know.
|
|
|
180
185
|
|
|
181
186
|
const REVIEWER = `---
|
|
182
187
|
description: Senior code reviewer for quality, security and maintainability. Read-only; reports findings with file and line references.
|
|
183
|
-
mode:
|
|
188
|
+
mode: all
|
|
184
189
|
color: "#e76f51"
|
|
185
190
|
permissions:
|
|
186
191
|
- action: edit
|
package/src/catalog/models.ts
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
import {
|
|
4
4
|
COMPACT100_CONTEXT_WINDOW,
|
|
5
5
|
CONTEXT_WINDOW,
|
|
6
|
-
DEFAULT_REASONING_EFFORT,
|
|
7
6
|
DEFAULT_THINKING_LEVELS,
|
|
8
7
|
MAX_OUTPUT_TOKENS,
|
|
9
8
|
} from "../constants.js";
|
|
10
9
|
import type {
|
|
11
10
|
Catalog,
|
|
12
11
|
CatalogModel,
|
|
12
|
+
MeResponse,
|
|
13
13
|
ModelDefinition,
|
|
14
14
|
ModelRegistry,
|
|
15
15
|
ModelsDevModel,
|
|
@@ -207,6 +207,61 @@ export type BuildModelsOptions = {
|
|
|
207
207
|
compact100?: boolean;
|
|
208
208
|
};
|
|
209
209
|
|
|
210
|
+
/**
|
|
211
|
+
* What the signed-in account can actually use, derived from `GET /me`.
|
|
212
|
+
*
|
|
213
|
+
* free-pi lets the free allowance pay for every non-premium model while the
|
|
214
|
+
* daily credits last, so those stay available even when the wallet is empty.
|
|
215
|
+
* Premium-only models need premium credits, and showing them to an account
|
|
216
|
+
* without any only produces `model_requires_credits` failures from `/model`.
|
|
217
|
+
*/
|
|
218
|
+
export type AccountAccess = {
|
|
219
|
+
readonly premiumCredits: number;
|
|
220
|
+
readonly walletCredits: number;
|
|
221
|
+
readonly remainingCredits: number;
|
|
222
|
+
readonly hasAllowance: boolean;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
export function accountAccess(me: MeResponse | undefined): AccountAccess | undefined {
|
|
226
|
+
if (!me) return undefined;
|
|
227
|
+
const credits = (value: unknown): number =>
|
|
228
|
+
typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
229
|
+
const wallet =
|
|
230
|
+
credits(me.bonus_wallet_credits) +
|
|
231
|
+
credits(me.regular_wallet_credits) +
|
|
232
|
+
credits(me.bonus_credits);
|
|
233
|
+
const remaining = credits(me.remaining_credits_today);
|
|
234
|
+
return {
|
|
235
|
+
premiumCredits:
|
|
236
|
+
credits(me.premium_credits) +
|
|
237
|
+
credits(me.premium_bought_credits) +
|
|
238
|
+
credits(me.premium_gifted_credits),
|
|
239
|
+
walletCredits: wallet,
|
|
240
|
+
remainingCredits: remaining,
|
|
241
|
+
hasAllowance: remaining > 0 || credits(me.remaining_usd_today) > 0,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function isPremiumModel(model: CatalogModel): boolean {
|
|
246
|
+
if (model.tier === "premium") return true;
|
|
247
|
+
return /premium\s+credits/i.test(model.note ?? "");
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function filterAccessibleModels(
|
|
251
|
+
models: CatalogModel[],
|
|
252
|
+
access: AccountAccess | undefined,
|
|
253
|
+
): CatalogModel[] {
|
|
254
|
+
// Without a quota snapshot, show everything instead of guessing and hiding
|
|
255
|
+
// models the account may be able to use.
|
|
256
|
+
if (!access) return models.filter((model) => model.unavailable !== true);
|
|
257
|
+
return models.filter((model) => {
|
|
258
|
+
if (model.unavailable === true) return false;
|
|
259
|
+
if (isPremiumModel(model)) return access.premiumCredits > 0;
|
|
260
|
+
if (model.free === true) return true;
|
|
261
|
+
return access.hasAllowance || access.walletCredits > 0;
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
|
|
210
265
|
export function buildModels(
|
|
211
266
|
models: CatalogModel[],
|
|
212
267
|
candidates: RegistryCandidate[] = [],
|
|
@@ -258,9 +313,6 @@ export function buildModels(
|
|
|
258
313
|
reasoning,
|
|
259
314
|
reasoning_options: reasoningOptions,
|
|
260
315
|
variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
|
|
261
|
-
...(reasoning
|
|
262
|
-
? { settings: { reasoningEffort: DEFAULT_REASONING_EFFORT } }
|
|
263
|
-
: {}),
|
|
264
316
|
enabled: model.unavailable !== true,
|
|
265
317
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
266
318
|
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
package/src/errors/messages.ts
CHANGED
|
@@ -4,10 +4,11 @@ import type { FreePiError } from "../types.js";
|
|
|
4
4
|
import { formatRefillTime, formatWait } from "../utils/numbers.js";
|
|
5
5
|
|
|
6
6
|
const FREE_PI_ERROR_TEXT: Record<string, string> = {
|
|
7
|
-
daily_cap:
|
|
7
|
+
daily_cap:
|
|
8
|
+
"Out of free credits today; they refill at UTC midnight, or add credits to keep going now.",
|
|
8
9
|
queue_wait: "free-pi is near its daily budget; wait and retry.",
|
|
9
10
|
rolling_cap:
|
|
10
|
-
"Over the rolling spend cap on the free tier; wait for the retry window.",
|
|
11
|
+
"Over the rolling spend cap on the free tier; wait for the retry window or add credits.",
|
|
11
12
|
concurrent:
|
|
12
13
|
"Only one request at a time on the free tier; wait for the current one to finish.",
|
|
13
14
|
concurrent_session:
|
package/src/plugin.ts
CHANGED
|
@@ -10,12 +10,15 @@ import {
|
|
|
10
10
|
installFreePiAgents,
|
|
11
11
|
openCodeConfigDir,
|
|
12
12
|
} from "./agents/definitions.js";
|
|
13
|
+
import { fetchQuota } from "./api/quota.js";
|
|
13
14
|
import { closeFreePiSession } from "./api/session.js";
|
|
14
15
|
import { readCredentialsToken } from "./auth/credentials.js";
|
|
15
16
|
import { tokenFromCredential } from "./auth/credential.js";
|
|
16
17
|
import { fetchCatalog } from "./catalog/catalog.js";
|
|
17
18
|
import {
|
|
19
|
+
accountAccess,
|
|
18
20
|
buildModels,
|
|
21
|
+
filterAccessibleModels,
|
|
19
22
|
modelRegistryCandidates,
|
|
20
23
|
partitionModels,
|
|
21
24
|
} from "./catalog/models.js";
|
|
@@ -108,14 +111,23 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
108
111
|
log.warn("Could not register the free-pi skill", error);
|
|
109
112
|
}
|
|
110
113
|
|
|
111
|
-
const [catalogResult, registryResult] = await Promise.all([
|
|
114
|
+
const [catalogResult, registryResult, quotaResult] = await Promise.all([
|
|
112
115
|
settle(fetchCatalog(deps), undefined),
|
|
113
116
|
settle(fetchModelsRegistry(deps), undefined),
|
|
117
|
+
settle(fetchQuota(deps), undefined),
|
|
114
118
|
]);
|
|
115
119
|
// The fetch may finish just after `settle` gives up; reuse whatever landed.
|
|
116
120
|
const catalog = catalogResult ?? state.cachedCatalog;
|
|
117
121
|
const registry = registryResult ?? state.cachedRegistry;
|
|
118
|
-
const
|
|
122
|
+
const quota = quotaResult ?? state.quotaCache;
|
|
123
|
+
// The picker must only offer models this account can actually use: premium
|
|
124
|
+
// models need premium credits, and paid models need allowance or wallet.
|
|
125
|
+
// Without a quota snapshot every model stays visible.
|
|
126
|
+
const access = accountAccess(quota?.me);
|
|
127
|
+
const { main: catalogMain, defense: catalogDefense } =
|
|
128
|
+
partitionModels(catalog);
|
|
129
|
+
const main = filterAccessibleModels(catalogMain, access);
|
|
130
|
+
const defense = filterAccessibleModels(catalogDefense, access);
|
|
119
131
|
const candidates = modelRegistryCandidates(registry);
|
|
120
132
|
const buildOptions = { compact100: state.costExperimentArm === "compact100" };
|
|
121
133
|
const mainModels = buildModels(main, candidates, buildOptions);
|
package/src/state.ts
CHANGED
|
@@ -64,6 +64,18 @@ export type RuntimeState = {
|
|
|
64
64
|
trackedModels: Map<string, TrackedModel>;
|
|
65
65
|
cacheMisses: Map<string, CacheMissState>;
|
|
66
66
|
toolStats: Map<string, ToolStats>;
|
|
67
|
+
/** Successful paid-tool answers, keyed by canonical input, to avoid rebilling. */
|
|
68
|
+
toolSpend: Map<
|
|
69
|
+
string,
|
|
70
|
+
{
|
|
71
|
+
at: number;
|
|
72
|
+
output: {
|
|
73
|
+
content: ReadonlyArray<{ type: "text"; text: string }>;
|
|
74
|
+
metadata: Record<string, unknown>;
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
>;
|
|
78
|
+
toolSpendPending: Map<string, Promise<any>>;
|
|
67
79
|
subagentSessions: Set<string>;
|
|
68
80
|
};
|
|
69
81
|
|
|
@@ -95,6 +107,8 @@ export function createRuntimeState(): RuntimeState {
|
|
|
95
107
|
trackedModels: new Map(),
|
|
96
108
|
cacheMisses: new Map(),
|
|
97
109
|
toolStats: new Map(),
|
|
110
|
+
toolSpend: new Map(),
|
|
111
|
+
toolSpendPending: new Map(),
|
|
98
112
|
subagentSessions: new Set(),
|
|
99
113
|
};
|
|
100
114
|
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spend-once cache for the free-pi tools that consume allowance.
|
|
3
|
+
*
|
|
4
|
+
* `web_search`, `docs_lookup` and `look_at_image` bill the user every time they
|
|
5
|
+
* run. Models often ask the same question twice in a turn (or a subagent and
|
|
6
|
+
* its lead both ask it), so identical inputs reuse the first answer instead of
|
|
7
|
+
* spending credits again. Failures are never cached: the next attempt must
|
|
8
|
+
* reach the server and see the real error. Concurrent identical calls share one
|
|
9
|
+
* in-flight request, so a parallel tool call cannot double-charge either.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { Deps } from "../deps.js";
|
|
13
|
+
import type { ToolOutput } from "./api.js";
|
|
14
|
+
|
|
15
|
+
/** Long enough to cover a turn and its follow-ups, short enough to stay fresh. */
|
|
16
|
+
export const SPEND_CACHE_TTL_MS = 30 * 60 * 1_000;
|
|
17
|
+
const SPEND_CACHE_LIMIT = 128;
|
|
18
|
+
|
|
19
|
+
type Entry = {
|
|
20
|
+
readonly at: number;
|
|
21
|
+
readonly output: ToolOutput;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
function trim(deps: Deps): void {
|
|
25
|
+
const now = Date.now();
|
|
26
|
+
for (const [key, entry] of deps.state.toolSpend) {
|
|
27
|
+
if (now - entry.at >= SPEND_CACHE_TTL_MS) deps.state.toolSpend.delete(key);
|
|
28
|
+
}
|
|
29
|
+
while (deps.state.toolSpend.size > SPEND_CACHE_LIMIT) {
|
|
30
|
+
const oldest = deps.state.toolSpend.keys().next().value;
|
|
31
|
+
if (oldest === undefined) break;
|
|
32
|
+
deps.state.toolSpend.delete(oldest);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function cachedResult(entry: Entry): ToolOutput {
|
|
37
|
+
const { cost_usd: _spent, ...metadata } = entry.output.metadata;
|
|
38
|
+
return {
|
|
39
|
+
content: entry.output.content.map((part) => ({
|
|
40
|
+
type: "text" as const,
|
|
41
|
+
text: `${part.text}\n\n(cached answer from earlier - no allowance used)`,
|
|
42
|
+
})),
|
|
43
|
+
metadata: { ...metadata, cached: true },
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function spendOnce(
|
|
48
|
+
deps: Deps,
|
|
49
|
+
key: string,
|
|
50
|
+
run: () => Promise<ToolOutput>,
|
|
51
|
+
): Promise<ToolOutput> {
|
|
52
|
+
const entry = deps.state.toolSpend.get(key);
|
|
53
|
+
if (entry && Date.now() - entry.at < SPEND_CACHE_TTL_MS) {
|
|
54
|
+
deps.log.info("reused a cached free-pi tool answer", { key });
|
|
55
|
+
return cachedResult(entry);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const pending = deps.state.toolSpendPending.get(key);
|
|
59
|
+
if (pending) {
|
|
60
|
+
const output = await pending;
|
|
61
|
+
return output.metadata.ok
|
|
62
|
+
? cachedResult({ at: Date.now(), output })
|
|
63
|
+
: run();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const request = run();
|
|
67
|
+
deps.state.toolSpendPending.set(key, request);
|
|
68
|
+
try {
|
|
69
|
+
const output = await request;
|
|
70
|
+
if (output.metadata.ok) {
|
|
71
|
+
deps.state.toolSpend.set(key, { at: Date.now(), output });
|
|
72
|
+
trim(deps);
|
|
73
|
+
}
|
|
74
|
+
return output;
|
|
75
|
+
} finally {
|
|
76
|
+
if (deps.state.toolSpendPending.get(key) === request)
|
|
77
|
+
deps.state.toolSpendPending.delete(key);
|
|
78
|
+
}
|
|
79
|
+
}
|
package/src/tools/usage.ts
CHANGED
|
@@ -71,6 +71,28 @@ export function formatUsage(stats: any): string {
|
|
|
71
71
|
? creditsLeftLine(remaining, allowance, new Date(refillAt))
|
|
72
72
|
: `today: ${percentUsed(t.spent_usd_today ?? 0, t.cap_usd_today ?? 0)}% of your free daily allowance used`;
|
|
73
73
|
|
|
74
|
+
const hasCredits =
|
|
75
|
+
typeof remaining === "number" &&
|
|
76
|
+
typeof allowance === "number" &&
|
|
77
|
+
allowance > 0;
|
|
78
|
+
const low = hasCredits && remaining > 0 && remaining <= allowance * 0.1;
|
|
79
|
+
const empty = hasCredits && remaining <= 0;
|
|
80
|
+
const buyUrl =
|
|
81
|
+
typeof t.buy_url === "string" && t.buy_url ? t.buy_url : undefined;
|
|
82
|
+
const creditLines = [
|
|
83
|
+
...(low
|
|
84
|
+
? [
|
|
85
|
+
`low credits: ${Math.round((remaining / allowance) * 100)}% of today's allowance left`,
|
|
86
|
+
]
|
|
87
|
+
: []),
|
|
88
|
+
...(empty
|
|
89
|
+
? [
|
|
90
|
+
"Out of free credits today; they refill at the reset time, or add credits to keep going now.",
|
|
91
|
+
]
|
|
92
|
+
: []),
|
|
93
|
+
...(buyUrl && (low || empty) ? [`Buy credits: ${buyUrl}`] : []),
|
|
94
|
+
];
|
|
95
|
+
|
|
74
96
|
const tieredLines = tiered
|
|
75
97
|
? [
|
|
76
98
|
creditsLeftLine(remaining, allowance, new Date(refillAt)),
|
|
@@ -86,6 +108,7 @@ export function formatUsage(stats: any): string {
|
|
|
86
108
|
return [
|
|
87
109
|
`tier: ${t.tier ?? "unknown"}`,
|
|
88
110
|
...(tiered ? [tieredLines[0]!] : [todayLine]),
|
|
111
|
+
...creditLines,
|
|
89
112
|
...(t.lane === "fallback" ? [SLOW_LANE_NOTICE] : []),
|
|
90
113
|
...(tiered
|
|
91
114
|
? tieredLines.slice(1)
|
package/src/tools/vision.ts
CHANGED
|
@@ -8,11 +8,13 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import type { Plugin } from "@opencode/plugin";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
11
12
|
import { resolveToken } from "../auth/token.js";
|
|
12
13
|
import type { Deps } from "../deps.js";
|
|
13
14
|
import { isFreePiSession } from "../session/tools.js";
|
|
14
15
|
import { resolveBaseUrl } from "../utils/urls.js";
|
|
15
16
|
import { loadImage, prepareImage, type VisionMime } from "./image.js";
|
|
17
|
+
import { spendOnce } from "./spend-cache.js";
|
|
16
18
|
import { withVisionSlot } from "./vision-queue.js";
|
|
17
19
|
|
|
18
20
|
type Registration = { dispose: () => Promise<void> };
|
|
@@ -271,34 +273,44 @@ async function executeVision(
|
|
|
271
273
|
);
|
|
272
274
|
}
|
|
273
275
|
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
276
|
+
const imageKey = createHash("sha256")
|
|
277
|
+
.update(prepared.mime)
|
|
278
|
+
.update("\u0000")
|
|
279
|
+
.update(prepared.data)
|
|
280
|
+
.update("\u0000")
|
|
281
|
+
.update(question)
|
|
282
|
+
.digest("hex");
|
|
283
|
+
|
|
284
|
+
return spendOnce(deps, `vision:${imageKey}`, async () => {
|
|
285
|
+
const queued = await withVisionSlot(deps.log, () =>
|
|
286
|
+
askVision(deps, token, prepared.data, prepared.mime, question, context.signal),
|
|
280
287
|
);
|
|
281
|
-
|
|
282
|
-
|
|
288
|
+
if (!queued.ok) {
|
|
289
|
+
return fail(
|
|
290
|
+
"Another image question is still running. Wait a moment and call look_at_image again.",
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
if (!queued.value.ok) return fail(queued.value.text);
|
|
283
294
|
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
295
|
+
const { answer, attempts } = queued.value;
|
|
296
|
+
const elapsed = Date.now() - startedAt;
|
|
297
|
+
deps.log.info("look_at_image answered", {
|
|
298
|
+
path,
|
|
299
|
+
ms: elapsed,
|
|
300
|
+
attempts,
|
|
301
|
+
resized: prepared.resized,
|
|
302
|
+
bytes: prepared.bytes,
|
|
303
|
+
size: `${prepared.width}x${prepared.height}`,
|
|
304
|
+
mime: prepared.mime,
|
|
305
|
+
model: answer.model,
|
|
306
|
+
});
|
|
307
|
+
return done(questionText(path, answer.text), {
|
|
308
|
+
ok: true,
|
|
309
|
+
...(answer.cost_usd !== undefined ? { cost_usd: answer.cost_usd } : {}),
|
|
310
|
+
...(answer.model !== undefined ? { model: answer.model } : {}),
|
|
311
|
+
elapsed_ms: elapsed,
|
|
312
|
+
attempts,
|
|
313
|
+
});
|
|
302
314
|
});
|
|
303
315
|
}
|
|
304
316
|
|
package/src/tools/web.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
isGatedSession,
|
|
16
16
|
mappedText,
|
|
17
17
|
} from "./api.js";
|
|
18
|
+
import { spendOnce } from "./spend-cache.js";
|
|
18
19
|
|
|
19
20
|
const ERRORS: Record<string, string> = {
|
|
20
21
|
daily_cap:
|
|
@@ -114,28 +115,30 @@ async function executeWebSearch(
|
|
|
114
115
|
const num =
|
|
115
116
|
typeof input?.num_results === "number" ? input.num_results : undefined;
|
|
116
117
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
118
|
+
return spendOnce(deps, `web:${query}\u0000${num ?? ""}`, async () => {
|
|
119
|
+
const result = await freePiRequest(deps, {
|
|
120
|
+
path: "/tools/web-search",
|
|
121
|
+
method: "POST",
|
|
122
|
+
body: { query, ...(num !== undefined ? { num_results: num } : {}) },
|
|
123
|
+
timeoutMs: 30_000,
|
|
124
|
+
signal: context.signal,
|
|
125
|
+
label: "The web search",
|
|
126
|
+
});
|
|
127
|
+
if (!result.ok) return fail(mappedText(ERRORS, result));
|
|
126
128
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
129
|
+
deps.log.info("web_search answered", {
|
|
130
|
+
query,
|
|
131
|
+
results: Array.isArray(result.data?.results)
|
|
132
|
+
? result.data.results.length
|
|
133
|
+
: 0,
|
|
134
|
+
costUsd: result.data?.cost_usd,
|
|
135
|
+
});
|
|
136
|
+
return done(formatWebResults(query, result.data?.results ?? []), {
|
|
137
|
+
ok: true,
|
|
138
|
+
...(typeof result.data?.cost_usd === "number"
|
|
139
|
+
? { cost_usd: result.data.cost_usd }
|
|
140
|
+
: {}),
|
|
141
|
+
});
|
|
139
142
|
});
|
|
140
143
|
}
|
|
141
144
|
|
|
@@ -152,36 +155,42 @@ async function executeDocsLookup(
|
|
|
152
155
|
if (!library) return fail("docs_lookup needs a library name.");
|
|
153
156
|
if (!query) return fail("docs_lookup needs a specific question.");
|
|
154
157
|
|
|
155
|
-
const result = await
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
158
|
+
const result = await spendOnce(
|
|
159
|
+
deps,
|
|
160
|
+
`docs:${library}\u0000${query}\u0000${libraryId}`,
|
|
161
|
+
() =>
|
|
162
|
+
freePiRequest(deps, {
|
|
163
|
+
path: "/tools/docs",
|
|
164
|
+
method: "POST",
|
|
165
|
+
body: {
|
|
166
|
+
library,
|
|
167
|
+
query,
|
|
168
|
+
...(libraryId ? { library_id: libraryId } : {}),
|
|
169
|
+
},
|
|
170
|
+
timeoutMs: 30_000,
|
|
171
|
+
signal: context.signal,
|
|
172
|
+
label: "The documentation lookup",
|
|
173
|
+
}).then((lookup) => {
|
|
174
|
+
if (!lookup.ok) return fail(mappedText(ERRORS, lookup, library));
|
|
175
|
+
const data = lookup.data ?? {};
|
|
176
|
+
deps.log.info("docs_lookup answered", {
|
|
177
|
+
library,
|
|
178
|
+
libraryID: data.library_id,
|
|
179
|
+
costUsd: data.cost_usd,
|
|
180
|
+
});
|
|
181
|
+
return done(
|
|
182
|
+
`${data.title ?? library} (library_id: ${data.library_id ?? "unknown"})\n\n${data.docs ?? ""}`,
|
|
183
|
+
{
|
|
184
|
+
ok: true,
|
|
185
|
+
library_id: data.library_id,
|
|
186
|
+
...(typeof data.cost_usd === "number"
|
|
187
|
+
? { cost_usd: data.cost_usd }
|
|
188
|
+
: {}),
|
|
189
|
+
},
|
|
190
|
+
);
|
|
191
|
+
}),
|
|
184
192
|
);
|
|
193
|
+
return result;
|
|
185
194
|
}
|
|
186
195
|
|
|
187
196
|
export async function registerWebTools(
|