@eduardo191labs/opencode-free-pi 0.5.4 → 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
@@ -95,13 +95,30 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
95
95
  - **Subagentes identificados**: las sesiones hijas envían
96
96
  `x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
97
97
  subagentes.
98
- - **Pensamiento sin forzar**: el plugin no envía un `reasoning_effort` por
99
- defecto. Forzar `none` (como hacía una versión anterior) apagaba el
100
- razonamiento y los modelos respondían con prisa; dejarlo sin definir usa el
101
- nivel del servidor. El selector sigue ofreciendo `minimal`, `low`, `medium` y
102
- `high` mediante `reasoning_effort`, igual que `pi-ai`. No se anuncian
103
- `thinking_budget` ni `thinking`, porque la ruta `openai-compatible` de
104
- OpenCode los descarta.
98
+ - **Pensamiento por defecto**: el plugin pide `reasoning_effort: "medium"`
99
+ cuando el modelo no trae variante elegida. Dejarlo sin definir hacía que los
100
+ modelos gratuitos respondieran con prisa, gastando apenas unas decenas de
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.
105
122
  - **Solo modelos utilizables**: al arrancar se consulta `/me` y el selector
106
123
  `/model` incluye únicamente lo que la cuenta puede usar: los modelos
107
124
  `free: true` siempre, los de pago mientras queden créditos de la cuota o
@@ -12,9 +12,23 @@ export declare function modelCost(_model: CatalogModel, _capability?: ModelsDevM
12
12
  export declare function modelRegistryCandidates(registry: ModelRegistry | undefined): RegistryCandidate[];
13
13
  export declare function modelCapability(model: CatalogModel, candidates: RegistryCandidate[]): ModelsDevModel | undefined;
14
14
  export declare function modelVariants(options: ReasoningOption[] | undefined, _outputLimit: number): VariantMap;
15
+ export declare function isReasoningEffort(value: unknown): value is string;
16
+ /**
17
+ * The effort sent when no variant is selected. `false` leaves the gateway's
18
+ * own default untouched; otherwise the catalog's supported levels win over
19
+ * `medium`, so a model that only accepts `low`/`high` never gets an effort it
20
+ * would reject.
21
+ */
22
+ export declare function preferredReasoningEffort(options: ReasoningOption[] | undefined, configured?: string | false): string | undefined;
15
23
  export type BuildModelsOptions = {
16
24
  /** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
17
25
  compact100?: boolean;
26
+ /**
27
+ * Effort sent when the user has not picked a variant. `false` keeps the
28
+ * gateway default. Defaults to `medium` because an unset effort makes the
29
+ * free models answer before they reason.
30
+ */
31
+ reasoningEffort?: string | false;
18
32
  };
19
33
  /**
20
34
  * What the signed-in account can actually use, derived from `GET /me`.
@@ -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, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, } from "../constants.js";
2
+ import { COMPACT100_CONTEXT_WINDOW, CONTEXT_WINDOW, DEFAULT_REASONING_EFFORT, DEFAULT_THINKING_LEVELS, MAX_OUTPUT_TOKENS, REASONING_EFFORTS, } 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) {
@@ -126,31 +126,49 @@ 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);
151
147
  }
152
148
  return variants;
153
149
  }
150
+ export function isReasoningEffort(value) {
151
+ return (typeof value === "string" &&
152
+ REASONING_EFFORTS.includes(value));
153
+ }
154
+ /**
155
+ * The effort sent when no variant is selected. `false` leaves the gateway's
156
+ * own default untouched; otherwise the catalog's supported levels win over
157
+ * `medium`, so a model that only accepts `low`/`high` never gets an effort it
158
+ * would reject.
159
+ */
160
+ export function preferredReasoningEffort(options, configured) {
161
+ if (configured === false)
162
+ return undefined;
163
+ if (configured)
164
+ return configured;
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"))
169
+ return "high";
170
+ return DEFAULT_REASONING_EFFORT;
171
+ }
154
172
  export function accountAccess(me) {
155
173
  if (!me)
156
174
  return undefined;
@@ -194,7 +212,10 @@ export function buildModels(models, candidates = [], options = {}) {
194
212
  if (!model.id)
195
213
  continue;
196
214
  const capability = modelCapability(model, candidates);
197
- 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;
198
219
  const reasoningOptions = model.reasoning_options ?? capability?.reasoning_options;
199
220
  // free-pi enforces a 200k input window and 32k output cap on every model,
200
221
  // regardless of what models.dev reports for the upstream provider. The
@@ -207,6 +228,9 @@ export function buildModels(models, candidates = [], options = {}) {
207
228
  : CONTEXT_WINDOW;
208
229
  const limitContext = Math.min(positiveNumber(model.context_window, model.contextWindow, model.limit?.context, capability?.limit?.context) ?? contextCeiling, contextCeiling);
209
230
  const limitOutput = Math.min(positiveNumber(model.max_tokens, model.maxTokens, model.max_output_tokens, model.limit?.output, capability?.limit?.output) ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS);
231
+ const defaultEffort = reasoning
232
+ ? preferredReasoningEffort(reasoningOptions, options.reasoningEffort)
233
+ : undefined;
210
234
  result[model.id] = {
211
235
  id: model.id,
212
236
  name: displayName(model),
@@ -217,6 +241,7 @@ export function buildModels(models, candidates = [], options = {}) {
217
241
  reasoning,
218
242
  reasoning_options: reasoningOptions,
219
243
  variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
244
+ ...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
220
245
  enabled: model.unavailable !== true,
221
246
  temperature: model.temperature ?? capability?.temperature ?? true,
222
247
  tool_call: model.tool_call ?? capability?.tool_call ?? true,
@@ -19,13 +19,30 @@ export declare const SUBAGENT_HEADER = "x-freepi-subagent";
19
19
  export declare const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
20
20
  export declare const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
21
21
  /**
22
- * The provider CLI registers every free-pi model with reasoning enabled and
23
- * defaults to thinking off. OpenCode only sends `reasoning_effort` when a
24
- * variant or model setting provides one, so the model carries the off default
25
- * and the picker offers the levels the CLI would.
22
+ * The provider CLI starts with thinking off, but leaving `reasoning_effort`
23
+ * unset makes the gateway answer in a hurry: the free models spend only a few
24
+ * dozen reasoning tokens even on tasks that need planning. The plugin therefore
25
+ * asks for `medium` by default and keeps the CLI's levels as variants, so
26
+ * `none`/`minimal` are still one pick away when speed matters more than care.
26
27
  */
27
- export declare const DEFAULT_REASONING_EFFORT = "none";
28
- export declare const DEFAULT_THINKING_LEVELS: readonly ["minimal", "low", "medium", "high"];
28
+ export declare const DEFAULT_REASONING_EFFORT = "medium";
29
+ export declare const REASONING_EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "max"];
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";
29
46
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
30
47
  export declare const HEADER_TIMEOUT_MS = 300000;
31
48
  export declare const CHUNK_TIMEOUT_MS = 300000;
package/dist/constants.js CHANGED
@@ -19,18 +19,53 @@ export const SUBAGENT_HEADER = "x-freepi-subagent";
19
19
  export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
20
20
  export const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
21
21
  /**
22
- * The provider CLI registers every free-pi model with reasoning enabled and
23
- * defaults to thinking off. OpenCode only sends `reasoning_effort` when a
24
- * variant or model setting provides one, so the model carries the off default
25
- * and the picker offers the levels the CLI would.
22
+ * The provider CLI starts with thinking off, but leaving `reasoning_effort`
23
+ * unset makes the gateway answer in a hurry: the free models spend only a few
24
+ * dozen reasoning tokens even on tasks that need planning. The plugin therefore
25
+ * asks for `medium` by default and keeps the CLI's levels as variants, so
26
+ * `none`/`minimal` are still one pick away when speed matters more than care.
26
27
  */
27
- export const DEFAULT_REASONING_EFFORT = "none";
28
+ export const DEFAULT_REASONING_EFFORT = "medium";
29
+ export const REASONING_EFFORTS = [
30
+ "none",
31
+ "minimal",
32
+ "low",
33
+ "medium",
34
+ "high",
35
+ "max",
36
+ ];
28
37
  export const DEFAULT_THINKING_LEVELS = [
38
+ "none",
29
39
  "minimal",
30
40
  "low",
31
41
  "medium",
32
42
  "high",
33
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";
34
69
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
35
70
  export const HEADER_TIMEOUT_MS = 300_000;
36
71
  export const CHUNK_TIMEOUT_MS = 300_000;
package/dist/plugin.js CHANGED
@@ -7,7 +7,7 @@ import { closeFreePiSession } from "./api/session.js";
7
7
  import { readCredentialsToken } from "./auth/credentials.js";
8
8
  import { tokenFromCredential } from "./auth/credential.js";
9
9
  import { fetchCatalog } from "./catalog/catalog.js";
10
- import { accountAccess, buildModels, filterAccessibleModels, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
10
+ import { accountAccess, buildModels, filterAccessibleModels, isReasoningEffort, modelRegistryCandidates, partitionModels, } from "./catalog/models.js";
11
11
  import { fetchModelsRegistry } from "./catalog/registry.js";
12
12
  import { applyProvider } from "./catalog/v2.js";
13
13
  import { DEFENSE_PROVIDER_ID, PROVIDER_ID, } from "./constants.js";
@@ -103,7 +103,15 @@ async function setup(ctx) {
103
103
  const main = filterAccessibleModels(catalogMain, access);
104
104
  const defense = filterAccessibleModels(catalogDefense, access);
105
105
  const candidates = modelRegistryCandidates(registry);
106
- const buildOptions = { compact100: state.costExperimentArm === "compact100" };
106
+ const configuredEffort = ctx.options?.reasoningEffort;
107
+ const buildOptions = {
108
+ compact100: state.costExperimentArm === "compact100",
109
+ ...(configuredEffort === false
110
+ ? { reasoningEffort: false }
111
+ : isReasoningEffort(configuredEffort)
112
+ ? { reasoningEffort: configuredEffort }
113
+ : {}),
114
+ };
107
115
  const mainModels = buildModels(main, candidates, buildOptions);
108
116
  const defenseModels = buildModels(defense, candidates, buildOptions);
109
117
  for (const [id, model] of Object.entries(mainModels)) {
@@ -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/dist/types.d.ts CHANGED
@@ -133,6 +133,11 @@ export type ModelDefinition = {
133
133
  export type ModelMap = Record<string, ModelDefinition>;
134
134
  export type FreePiOptions = {
135
135
  includeDefense?: boolean;
136
+ /**
137
+ * Effort used when no variant is picked. Defaults to `medium` so the free
138
+ * models plan before answering. Set `false` to keep the gateway default.
139
+ */
140
+ reasoningEffort?: string | false;
136
141
  };
137
142
  export type MeResponse = {
138
143
  handle?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.5.4",
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",
@@ -3,8 +3,10 @@
3
3
  import {
4
4
  COMPACT100_CONTEXT_WINDOW,
5
5
  CONTEXT_WINDOW,
6
+ DEFAULT_REASONING_EFFORT,
6
7
  DEFAULT_THINKING_LEVELS,
7
8
  MAX_OUTPUT_TOKENS,
9
+ REASONING_EFFORTS,
8
10
  } from "../constants.js";
9
11
  import type {
10
12
  Catalog,
@@ -173,15 +175,15 @@ export function modelVariants(
173
175
  options: ReasoningOption[] | undefined,
174
176
  _outputLimit: number,
175
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.
176
182
  const variants: VariantMap = {};
177
- // The provider CLI offers these levels to every reasoning model because its
178
- // `thinkingLevelMap` is unset; `xhigh` and `max` stay opt-in.
179
- if (!options || options.length === 0) {
180
- for (const level of DEFAULT_THINKING_LEVELS) {
181
- variants[level] = { reasoningEffort: level };
182
- }
183
- return variants;
183
+ for (const level of DEFAULT_THINKING_LEVELS) {
184
+ variants[level] = { reasoningEffort: level };
184
185
  }
186
+ if (!options || options.length === 0) return variants;
185
187
  const effort = options.find(
186
188
  (option): option is Extract<ReasoningOption, { type: "effort" }> =>
187
189
  option.type === "effort",
@@ -190,11 +192,6 @@ export function modelVariants(
190
192
  for (const value of effort.values) {
191
193
  variants[value] = { reasoningEffort: value };
192
194
  }
193
- return variants;
194
- }
195
- if (options.some((option) => option.type === "toggle")) {
196
- variants.none = { reasoningEffort: "none" };
197
- variants.high = { reasoningEffort: "high" };
198
195
  }
199
196
  if (options.some((option) => option.type === "budget_tokens")) {
200
197
  budgetVariants(variants);
@@ -202,9 +199,41 @@ export function modelVariants(
202
199
  return variants;
203
200
  }
204
201
 
202
+ export function isReasoningEffort(value: unknown): value is string {
203
+ return (
204
+ typeof value === "string" &&
205
+ (REASONING_EFFORTS as readonly string[]).includes(value)
206
+ );
207
+ }
208
+
209
+ /**
210
+ * The effort sent when no variant is selected. `false` leaves the gateway's
211
+ * own default untouched; otherwise the catalog's supported levels win over
212
+ * `medium`, so a model that only accepts `low`/`high` never gets an effort it
213
+ * would reject.
214
+ */
215
+ export function preferredReasoningEffort(
216
+ options: ReasoningOption[] | undefined,
217
+ configured?: string | false,
218
+ ): string | undefined {
219
+ if (configured === false) return undefined;
220
+ if (configured) return configured;
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";
225
+ return DEFAULT_REASONING_EFFORT;
226
+ }
227
+
205
228
  export type BuildModelsOptions = {
206
229
  /** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
207
230
  compact100?: boolean;
231
+ /**
232
+ * Effort sent when the user has not picked a variant. `false` keeps the
233
+ * gateway default. Defaults to `medium` because an unset effort makes the
234
+ * free models answer before they reason.
235
+ */
236
+ reasoningEffort?: string | false;
208
237
  };
209
238
 
210
239
  /**
@@ -271,7 +300,10 @@ export function buildModels(
271
300
  for (const model of models) {
272
301
  if (!model.id) continue;
273
302
  const capability = modelCapability(model, candidates);
274
- 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;
275
307
  const reasoningOptions =
276
308
  model.reasoning_options ?? capability?.reasoning_options;
277
309
  // free-pi enforces a 200k input window and 32k output cap on every model,
@@ -302,6 +334,9 @@ export function buildModels(
302
334
  ) ?? MAX_OUTPUT_TOKENS,
303
335
  MAX_OUTPUT_TOKENS,
304
336
  );
337
+ const defaultEffort = reasoning
338
+ ? preferredReasoningEffort(reasoningOptions, options.reasoningEffort)
339
+ : undefined;
305
340
  result[model.id] = {
306
341
  id: model.id,
307
342
  name: displayName(model),
@@ -313,6 +348,7 @@ export function buildModels(
313
348
  reasoning,
314
349
  reasoning_options: reasoningOptions,
315
350
  variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
351
+ ...(defaultEffort ? { settings: { reasoningEffort: defaultEffort } } : {}),
316
352
  enabled: model.unavailable !== true,
317
353
  temperature: model.temperature ?? capability?.temperature ?? true,
318
354
  tool_call: model.tool_call ?? capability?.tool_call ?? true,
package/src/constants.ts CHANGED
@@ -26,19 +26,56 @@ export const EFFICIENCY_RULE =
26
26
  "- When several independent reads or searches are needed, issue them in the same turn.";
27
27
 
28
28
  /**
29
- * The provider CLI registers every free-pi model with reasoning enabled and
30
- * defaults to thinking off. OpenCode only sends `reasoning_effort` when a
31
- * variant or model setting provides one, so the model carries the off default
32
- * and the picker offers the levels the CLI would.
29
+ * The provider CLI starts with thinking off, but leaving `reasoning_effort`
30
+ * unset makes the gateway answer in a hurry: the free models spend only a few
31
+ * dozen reasoning tokens even on tasks that need planning. The plugin therefore
32
+ * asks for `medium` by default and keeps the CLI's levels as variants, so
33
+ * `none`/`minimal` are still one pick away when speed matters more than care.
33
34
  */
34
- export const DEFAULT_REASONING_EFFORT = "none";
35
+ export const DEFAULT_REASONING_EFFORT = "medium";
36
+ export const REASONING_EFFORTS = [
37
+ "none",
38
+ "minimal",
39
+ "low",
40
+ "medium",
41
+ "high",
42
+ "max",
43
+ ] as const;
35
44
  export const DEFAULT_THINKING_LEVELS = [
45
+ "none",
36
46
  "minimal",
37
47
  "low",
38
48
  "medium",
39
49
  "high",
40
50
  ] as const;
41
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
+
42
79
  /** pi-ai's HTTP idle timeout for headers and body chunks. */
43
80
  export const HEADER_TIMEOUT_MS = 300_000;
44
81
  export const CHUNK_TIMEOUT_MS = 300_000;
package/src/plugin.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  accountAccess,
20
20
  buildModels,
21
21
  filterAccessibleModels,
22
+ isReasoningEffort,
22
23
  modelRegistryCandidates,
23
24
  partitionModels,
24
25
  } from "./catalog/models.js";
@@ -129,7 +130,15 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
129
130
  const main = filterAccessibleModels(catalogMain, access);
130
131
  const defense = filterAccessibleModels(catalogDefense, access);
131
132
  const candidates = modelRegistryCandidates(registry);
132
- const buildOptions = { compact100: state.costExperimentArm === "compact100" };
133
+ const configuredEffort = ctx.options?.reasoningEffort;
134
+ const buildOptions = {
135
+ compact100: state.costExperimentArm === "compact100",
136
+ ...(configuredEffort === false
137
+ ? { reasoningEffort: false as const }
138
+ : isReasoningEffort(configuredEffort)
139
+ ? { reasoningEffort: configuredEffort }
140
+ : {}),
141
+ };
133
142
  const mainModels = buildModels(main, candidates, buildOptions);
134
143
  const defenseModels = buildModels(defense, candidates, buildOptions);
135
144
 
@@ -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") {
package/src/types.ts CHANGED
@@ -110,6 +110,11 @@ export type ModelMap = Record<string, ModelDefinition>;
110
110
 
111
111
  export type FreePiOptions = {
112
112
  includeDefense?: boolean;
113
+ /**
114
+ * Effort used when no variant is picked. Defaults to `medium` so the free
115
+ * models plan before answering. Set `false` to keep the gateway default.
116
+ */
117
+ reasoningEffort?: string | false;
113
118
  };
114
119
 
115
120
  export type MeResponse = {