@eduardo191labs/opencode-free-pi 0.5.5 → 0.5.6

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
@@ -98,12 +98,27 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
98
98
  - **Pensamiento por defecto**: el plugin pide `reasoning_effort: "medium"`
99
99
  cuando el modelo no trae variante elegida. Dejarlo sin definir hacía que los
100
100
  modelos gratuitos respondieran con prisa, gastando apenas unas decenas de
101
- tokens de razonamiento incluso en tareas que requieren planificar. Si el
102
- catálogo del modelo solo anuncia `low`/`high`, se usa `high`. El selector
103
- sigue ofreciendo `none`, `minimal`, `low`, `medium` y `high`, y la opción
104
- `reasoningEffort: false` del plugin recupera el comportamiento anterior (nivel
105
- del servidor). No se anuncian `thinking_budget` ni `thinking`, porque la ruta
106
- `openai-compatible` de OpenCode los descarta.
101
+ tokens de razonamiento incluso en tareas que requieren planificar. El
102
+ selector ofrece siempre `none`, `minimal`, `low`, `medium` y `high`, igual
103
+ que los niveles del CLI, y añade `max` cuando el catálogo lo declara; los
104
+ modelos de presupuesto usan `high`. La opción `reasoningEffort: false` del
105
+ plugin recupera el nivel del servidor. No se anuncian `thinking_budget` ni
106
+ `thinking`, porque la ruta `openai-compatible` de OpenCode los descarta.
107
+ - **Capacidades iguales al CLI**: todos los modelos se registran con
108
+ razonamiento activo, entrada solo de texto, coste cero y la misma ventana de
109
+ 200k con 32k de salida que usa `pi`. No se fuerza temperatura ni `top_p`: la
110
+ petición real no los incluye, así que el gateway aplica su propio valor. El
111
+ prompt se envía con rol `system`, no `developer`.
112
+ - **Reglas de trabajo en el prompt**: cada petición principal de free-pi añade
113
+ un bloque corto al system prompt con lo que los modelos gratuitos suelen
114
+ omitir: leer antes de editar, ejecutar las comprobaciones de verdad, no
115
+ afirmar que algo pasó si no se ejecutó, reutilizar las decisiones y rutas ya
116
+ establecidas en la conversación y no fingir que se compactó el contexto.
117
+ - **Compactación con instrucciones**: el resumen de compactación recibe además
118
+ un bloque que le pide conservar requisitos sin resolver, decisiones y sus
119
+ motivos, rutas y símbolos exactos, comandos con su resultado, errores y
120
+ trabajo pendiente. Sin eso, los modelos gratuitos producían resúmenes
121
+ demasiado escuetos para continuar la tarea.
107
122
  - **Solo modelos utilizables**: al arrancar se consulta `/me` y el selector
108
123
  `/model` incluye únicamente lo que la cuenta puede usar: los modelos
109
124
  `free: true` siempre, los de pago mientras queden créditos de la cuota o
@@ -126,25 +126,21 @@ function budgetVariants(variants) {
126
126
  variants.max = { reasoningEffort: "max" };
127
127
  }
128
128
  export function modelVariants(options, _outputLimit) {
129
+ // The provider CLI registers every model with `reasoning: true` and an unset
130
+ // `thinkingLevelMap`, so it offers these levels to every model. models.dev
131
+ // lists fewer levels for some upstream models, but the gateway accepts the
132
+ // CLI's set, and hiding levels only makes the picker disagree with the CLI.
129
133
  const variants = {};
130
- // The provider CLI offers these levels to every reasoning model because its
131
- // `thinkingLevelMap` is unset; `xhigh` and `max` stay opt-in.
132
- if (!options || options.length === 0) {
133
- for (const level of DEFAULT_THINKING_LEVELS) {
134
- variants[level] = { reasoningEffort: level };
135
- }
136
- return variants;
134
+ for (const level of DEFAULT_THINKING_LEVELS) {
135
+ variants[level] = { reasoningEffort: level };
137
136
  }
137
+ if (!options || options.length === 0)
138
+ return variants;
138
139
  const effort = options.find((option) => option.type === "effort");
139
140
  if (effort) {
140
141
  for (const value of effort.values) {
141
142
  variants[value] = { reasoningEffort: value };
142
143
  }
143
- return variants;
144
- }
145
- if (options.some((option) => option.type === "toggle")) {
146
- variants.none = { reasoningEffort: "none" };
147
- variants.high = { reasoningEffort: "high" };
148
144
  }
149
145
  if (options.some((option) => option.type === "budget_tokens")) {
150
146
  budgetVariants(variants);
@@ -166,19 +162,10 @@ export function preferredReasoningEffort(options, configured) {
166
162
  return undefined;
167
163
  if (configured)
168
164
  return configured;
169
- if (!options || options.length === 0)
170
- return DEFAULT_REASONING_EFFORT;
171
- const effort = options.find((option) => option.type === "effort");
172
- if (effort) {
173
- if (effort.values.includes(DEFAULT_REASONING_EFFORT))
174
- return DEFAULT_REASONING_EFFORT;
175
- if (effort.values.includes("high"))
176
- return "high";
177
- return effort.values[effort.values.length - 1];
178
- }
179
- if (options.some((option) => option.type === "toggle"))
180
- return "high";
181
- if (options.some((option) => option.type === "budget_tokens"))
165
+ // The provider CLI's levels are the source of truth: models.dev often lists
166
+ // only a subset, but the gateway accepts the CLI set. `medium` is the sane
167
+ // middle ground between the CLI's off default and burning tokens on `high`.
168
+ if (options?.some((option) => option.type === "budget_tokens"))
182
169
  return "high";
183
170
  return DEFAULT_REASONING_EFFORT;
184
171
  }
@@ -225,7 +212,10 @@ export function buildModels(models, candidates = [], options = {}) {
225
212
  if (!model.id)
226
213
  continue;
227
214
  const capability = modelCapability(model, candidates);
228
- const reasoning = model.reasoning ?? capability?.reasoning ?? true;
215
+ // The provider CLI registers every model as `reasoning: true`; models.dev
216
+ // sometimes omits or disagrees for the upstream alias. Trust the catalog's
217
+ // explicit answer, otherwise keep reasoning on like the CLI does.
218
+ const reasoning = model.reasoning ?? true;
229
219
  const reasoningOptions = model.reasoning_options ?? capability?.reasoning_options;
230
220
  // free-pi enforces a 200k input window and 32k output cap on every model,
231
221
  // regardless of what models.dev reports for the upstream provider. The
@@ -28,6 +28,21 @@ export declare const EFFICIENCY_RULE = "- When several independent reads or sear
28
28
  export declare const DEFAULT_REASONING_EFFORT = "medium";
29
29
  export declare const REASONING_EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "max"];
30
30
  export declare const DEFAULT_THINKING_LEVELS: readonly ["none", "minimal", "low", "medium", "high"];
31
+ /**
32
+ * Injected into every primary free-pi request. OpenCode already supplies the
33
+ * coding instructions; this block covers the failure modes the weaker free
34
+ * models show: skipping analysis, inventing verification, and ignoring the
35
+ * context the conversation already established.
36
+ */
37
+ export declare const FREE_PI_GUIDANCE = "# free-pi working rules\n- Answer the user's latest request and keep their constraints; do not switch to a different task.\n- Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.\n- Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.\n- Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.\n- Never claim to have compacted, summarized or cleared context unless that actually happened.\n- Continue until the request is finished, then report concisely what changed and what you verified.";
38
+ export declare const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
39
+ /**
40
+ * Appended to OpenCode's compaction request. Its default summary prompt asks
41
+ * for terse checkpoints, which is fine for strong models but loses the exact
42
+ * facts the free models need; spell out what must survive the rewrite.
43
+ */
44
+ export declare const FREE_PI_COMPACTION_GUIDANCE = "# free-pi compaction rules\n- Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.\n- Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.\n- Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.\n- Do not invent progress or results that are not in the conversation.";
45
+ export declare const FREE_PI_COMPACTION_MARKER = "# free-pi compaction rules";
31
46
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
32
47
  export declare const HEADER_TIMEOUT_MS = 300000;
33
48
  export declare const CHUNK_TIMEOUT_MS = 300000;
package/dist/constants.js CHANGED
@@ -41,6 +41,31 @@ export const DEFAULT_THINKING_LEVELS = [
41
41
  "medium",
42
42
  "high",
43
43
  ];
44
+ /**
45
+ * Injected into every primary free-pi request. OpenCode already supplies the
46
+ * coding instructions; this block covers the failure modes the weaker free
47
+ * models show: skipping analysis, inventing verification, and ignoring the
48
+ * context the conversation already established.
49
+ */
50
+ export const FREE_PI_GUIDANCE = `# free-pi working rules
51
+ - Answer the user's latest request and keep their constraints; do not switch to a different task.
52
+ - Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.
53
+ - Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
54
+ - Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
55
+ - Never claim to have compacted, summarized or cleared context unless that actually happened.
56
+ - Continue until the request is finished, then report concisely what changed and what you verified.`;
57
+ export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
58
+ /**
59
+ * Appended to OpenCode's compaction request. Its default summary prompt asks
60
+ * for terse checkpoints, which is fine for strong models but loses the exact
61
+ * facts the free models need; spell out what must survive the rewrite.
62
+ */
63
+ export const FREE_PI_COMPACTION_GUIDANCE = `# free-pi compaction rules
64
+ - Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.
65
+ - Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.
66
+ - Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.
67
+ - Do not invent progress or results that are not in the conversation.`;
68
+ export const FREE_PI_COMPACTION_MARKER = "# free-pi compaction rules";
44
69
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
45
70
  export const HEADER_TIMEOUT_MS = 300_000;
46
71
  export const CHUNK_TIMEOUT_MS = 300_000;
@@ -2,7 +2,7 @@
2
2
  import { ensureAdImpression } from "../ads/impression.js";
3
3
  import { resolveAdTurn } from "../ads/resolve.js";
4
4
  import { resolveToken } from "../auth/token.js";
5
- import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, COST_EXPERIMENT_HEADER, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, DEFENSE_PROVIDER_ID, EFFICIENCY_RULE, MAX_OUTPUT_TOKENS, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
5
+ import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, COST_EXPERIMENT_HEADER, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, DEFENSE_PROVIDER_ID, EFFICIENCY_RULE, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER, MAX_OUTPUT_TOKENS, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
6
6
  import { closeFreePiSession } from "../api/session.js";
7
7
  import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
8
8
  import { parseFreePiError } from "../errors/parse.js";
@@ -27,6 +27,17 @@ function rememberPending(deps, key, turn) {
27
27
  trimMap(deps.state.pendingAdTurns, PENDING_LIMIT);
28
28
  deps.state.pendingAdTurns.set(key, turn);
29
29
  }
30
+ /** Adds a system block once, even when OpenCode reuses the same event. */
31
+ function appendSystemGuidance(event, text, marker) {
32
+ const system = Array.isArray(event.system) ? event.system : [];
33
+ if (system.some((part) => part?.type === "text" &&
34
+ typeof part.text === "string" &&
35
+ part.text.startsWith(marker))) {
36
+ return;
37
+ }
38
+ system.push({ type: "text", text });
39
+ event.system = system;
40
+ }
30
41
  /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
31
42
  async function applyGeneration(deps, event, kind) {
32
43
  if (!isFreePiProvider(event.model?.providerID))
@@ -48,10 +59,16 @@ async function applyGeneration(deps, event, kind) {
48
59
  event.options.maxTokens = cap;
49
60
  }
50
61
  if (kind === "compaction") {
62
+ appendSystemGuidance(event, FREE_PI_COMPACTION_GUIDANCE, FREE_PI_COMPACTION_MARKER);
51
63
  // OpenCode sends the messages it is folding into the summary, which is the
52
64
  // same set pi reports through `session_before_compact`.
53
65
  recordCompaction(deps, event.sessionID, Array.isArray(event.messages) ? event.messages.length : 0);
54
66
  }
67
+ else if (kind === "primary") {
68
+ // The free models tend to skip planning and claim work they did not do;
69
+ // the CLI gets a much larger agent prompt. This is the compact equivalent.
70
+ appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
71
+ }
55
72
  if (deps.state.costExperimentArm === "efficiency") {
56
73
  const system = Array.isArray(event.system) ? event.system : [];
57
74
  if (!system.some((part) => part?.type === "text" && part.text === EFFICIENCY_RULE)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.5.5",
3
+ "version": "0.5.6",
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",
@@ -175,15 +175,15 @@ export function modelVariants(
175
175
  options: ReasoningOption[] | undefined,
176
176
  _outputLimit: number,
177
177
  ): VariantMap {
178
+ // The provider CLI registers every model with `reasoning: true` and an unset
179
+ // `thinkingLevelMap`, so it offers these levels to every model. models.dev
180
+ // lists fewer levels for some upstream models, but the gateway accepts the
181
+ // CLI's set, and hiding levels only makes the picker disagree with the CLI.
178
182
  const variants: VariantMap = {};
179
- // The provider CLI offers these levels to every reasoning model because its
180
- // `thinkingLevelMap` is unset; `xhigh` and `max` stay opt-in.
181
- if (!options || options.length === 0) {
182
- for (const level of DEFAULT_THINKING_LEVELS) {
183
- variants[level] = { reasoningEffort: level };
184
- }
185
- return variants;
183
+ for (const level of DEFAULT_THINKING_LEVELS) {
184
+ variants[level] = { reasoningEffort: level };
186
185
  }
186
+ if (!options || options.length === 0) return variants;
187
187
  const effort = options.find(
188
188
  (option): option is Extract<ReasoningOption, { type: "effort" }> =>
189
189
  option.type === "effort",
@@ -192,11 +192,6 @@ export function modelVariants(
192
192
  for (const value of effort.values) {
193
193
  variants[value] = { reasoningEffort: value };
194
194
  }
195
- return variants;
196
- }
197
- if (options.some((option) => option.type === "toggle")) {
198
- variants.none = { reasoningEffort: "none" };
199
- variants.high = { reasoningEffort: "high" };
200
195
  }
201
196
  if (options.some((option) => option.type === "budget_tokens")) {
202
197
  budgetVariants(variants);
@@ -223,19 +218,10 @@ export function preferredReasoningEffort(
223
218
  ): string | undefined {
224
219
  if (configured === false) return undefined;
225
220
  if (configured) return configured;
226
- if (!options || options.length === 0) return DEFAULT_REASONING_EFFORT;
227
- const effort = options.find(
228
- (option): option is Extract<ReasoningOption, { type: "effort" }> =>
229
- option.type === "effort",
230
- );
231
- if (effort) {
232
- if (effort.values.includes(DEFAULT_REASONING_EFFORT))
233
- return DEFAULT_REASONING_EFFORT;
234
- if (effort.values.includes("high")) return "high";
235
- return effort.values[effort.values.length - 1];
236
- }
237
- if (options.some((option) => option.type === "toggle")) return "high";
238
- if (options.some((option) => option.type === "budget_tokens")) return "high";
221
+ // The provider CLI's levels are the source of truth: models.dev often lists
222
+ // only a subset, but the gateway accepts the CLI set. `medium` is the sane
223
+ // middle ground between the CLI's off default and burning tokens on `high`.
224
+ if (options?.some((option) => option.type === "budget_tokens")) return "high";
239
225
  return DEFAULT_REASONING_EFFORT;
240
226
  }
241
227
 
@@ -314,7 +300,10 @@ export function buildModels(
314
300
  for (const model of models) {
315
301
  if (!model.id) continue;
316
302
  const capability = modelCapability(model, candidates);
317
- const reasoning = model.reasoning ?? capability?.reasoning ?? true;
303
+ // The provider CLI registers every model as `reasoning: true`; models.dev
304
+ // sometimes omits or disagrees for the upstream alias. Trust the catalog's
305
+ // explicit answer, otherwise keep reasoning on like the CLI does.
306
+ const reasoning = model.reasoning ?? true;
318
307
  const reasoningOptions =
319
308
  model.reasoning_options ?? capability?.reasoning_options;
320
309
  // free-pi enforces a 200k input window and 32k output cap on every model,
package/src/constants.ts CHANGED
@@ -49,6 +49,33 @@ export const DEFAULT_THINKING_LEVELS = [
49
49
  "high",
50
50
  ] as const;
51
51
 
52
+ /**
53
+ * Injected into every primary free-pi request. OpenCode already supplies the
54
+ * coding instructions; this block covers the failure modes the weaker free
55
+ * models show: skipping analysis, inventing verification, and ignoring the
56
+ * context the conversation already established.
57
+ */
58
+ export const FREE_PI_GUIDANCE = `# free-pi working rules
59
+ - Answer the user's latest request and keep their constraints; do not switch to a different task.
60
+ - Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.
61
+ - Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
62
+ - Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
63
+ - Never claim to have compacted, summarized or cleared context unless that actually happened.
64
+ - Continue until the request is finished, then report concisely what changed and what you verified.`;
65
+ export const FREE_PI_GUIDANCE_MARKER = "# free-pi working rules";
66
+
67
+ /**
68
+ * Appended to OpenCode's compaction request. Its default summary prompt asks
69
+ * for terse checkpoints, which is fine for strong models but loses the exact
70
+ * facts the free models need; spell out what must survive the rewrite.
71
+ */
72
+ export const FREE_PI_COMPACTION_GUIDANCE = `# free-pi compaction rules
73
+ - Keep every unresolved user requirement and constraint, using their wording when a later agent must act on them.
74
+ - Keep decisions and their reasons, exact file paths and symbols, commands with the observed result, error strings, and work still pending.
75
+ - Preserve details that explain why the current state looks the way it does; the next agent cannot re-read the history this summary replaces.
76
+ - Do not invent progress or results that are not in the conversation.`;
77
+ export const FREE_PI_COMPACTION_MARKER = "# free-pi compaction rules";
78
+
52
79
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
53
80
  export const HEADER_TIMEOUT_MS = 300_000;
54
81
  export const CHUNK_TIMEOUT_MS = 300_000;
@@ -14,6 +14,10 @@ import {
14
14
  CONCURRENT_RETRY_MAX_DELAY_MS,
15
15
  DEFENSE_PROVIDER_ID,
16
16
  EFFICIENCY_RULE,
17
+ FREE_PI_COMPACTION_GUIDANCE,
18
+ FREE_PI_COMPACTION_MARKER,
19
+ FREE_PI_GUIDANCE,
20
+ FREE_PI_GUIDANCE_MARKER,
17
21
  MAX_OUTPUT_TOKENS,
18
22
  PROVIDER_ID,
19
23
  RETRY_BASE_DELAY_MS,
@@ -92,6 +96,27 @@ function rememberPending(deps: Deps, key: string, turn: AdTurn): void {
92
96
  deps.state.pendingAdTurns.set(key, turn);
93
97
  }
94
98
 
99
+ /** Adds a system block once, even when OpenCode reuses the same event. */
100
+ function appendSystemGuidance(
101
+ event: any,
102
+ text: string,
103
+ marker: string,
104
+ ): void {
105
+ const system = Array.isArray(event.system) ? event.system : [];
106
+ if (
107
+ system.some(
108
+ (part: any) =>
109
+ part?.type === "text" &&
110
+ typeof part.text === "string" &&
111
+ part.text.startsWith(marker),
112
+ )
113
+ ) {
114
+ return;
115
+ }
116
+ system.push({ type: "text", text });
117
+ event.system = system;
118
+ }
119
+
95
120
  /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
96
121
  async function applyGeneration(
97
122
  deps: Deps,
@@ -120,6 +145,11 @@ async function applyGeneration(
120
145
  }
121
146
 
122
147
  if (kind === "compaction") {
148
+ appendSystemGuidance(
149
+ event,
150
+ FREE_PI_COMPACTION_GUIDANCE,
151
+ FREE_PI_COMPACTION_MARKER,
152
+ );
123
153
  // OpenCode sends the messages it is folding into the summary, which is the
124
154
  // same set pi reports through `session_before_compact`.
125
155
  recordCompaction(
@@ -127,6 +157,10 @@ async function applyGeneration(
127
157
  event.sessionID,
128
158
  Array.isArray(event.messages) ? event.messages.length : 0,
129
159
  );
160
+ } else if (kind === "primary") {
161
+ // The free models tend to skip planning and claim work they did not do;
162
+ // the CLI gets a much larger agent prompt. This is the compact equivalent.
163
+ appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
130
164
  }
131
165
 
132
166
  if (deps.state.costExperimentArm === "efficiency") {