@eduardo191labs/opencode-free-pi 0.7.26 → 0.7.29

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.
Files changed (48) hide show
  1. package/README.md +60 -105
  2. package/dist/catalog/live.js +4 -1
  3. package/dist/catalog/models.d.ts +1 -1
  4. package/dist/catalog/models.js +14 -3
  5. package/dist/constants.d.ts +15 -35
  6. package/dist/constants.js +15 -35
  7. package/dist/index.d.ts +1 -1
  8. package/dist/plugin.js +14 -46
  9. package/dist/session/events.js +5 -12
  10. package/dist/session/hooks.js +83 -348
  11. package/dist/session/overflow.d.ts +7 -28
  12. package/dist/session/overflow.js +7 -73
  13. package/dist/session/replay.d.ts +8 -41
  14. package/dist/session/replay.js +9 -148
  15. package/dist/session/tools.d.ts +2 -7
  16. package/dist/session/tools.js +3 -18
  17. package/dist/session/trace.js +0 -1
  18. package/dist/session/track.d.ts +2 -0
  19. package/dist/session/track.js +5 -0
  20. package/dist/state.d.ts +1 -6
  21. package/dist/state.js +0 -2
  22. package/dist/tools/vision.js +1 -0
  23. package/dist/types.d.ts +0 -1
  24. package/package.json +2 -2
  25. package/src/catalog/live.ts +4 -1
  26. package/src/catalog/models.ts +20 -3
  27. package/src/constants.ts +16 -38
  28. package/src/index.ts +0 -1
  29. package/src/plugin.ts +12 -52
  30. package/src/session/events.ts +5 -12
  31. package/src/session/hooks.ts +109 -431
  32. package/src/session/overflow.ts +7 -77
  33. package/src/session/replay.ts +12 -188
  34. package/src/session/tools.ts +1 -22
  35. package/src/session/trace.ts +0 -1
  36. package/src/session/track.ts +11 -0
  37. package/src/state.ts +0 -8
  38. package/src/tools/vision.ts +2 -0
  39. package/src/types.ts +0 -1
  40. package/dist/session/diet.d.ts +0 -23
  41. package/dist/session/diet.js +0 -176
  42. package/dist/session/title.d.ts +0 -18
  43. package/dist/session/title.js +0 -81
  44. package/dist/session/usage.d.ts +0 -5
  45. package/dist/session/usage.js +0 -32
  46. package/src/session/diet.ts +0 -201
  47. package/src/session/title.ts +0 -90
  48. package/src/session/usage.ts +0 -46
@@ -1,4 +1,5 @@
1
1
  /** Subscribes to core events that affect free-pi state. */
2
+ import { fetchQuota } from "../api/quota.js";
2
3
  import { closeFreePiSession } from "../api/session.js";
3
4
  import { readCredentialsToken } from "../auth/credentials.js";
4
5
  import { tokenFromCredential } from "../auth/credential.js";
@@ -10,7 +11,6 @@ import { forgetToolStats, isFreePiSession } from "./tools.js";
10
11
  import { trimSet } from "../utils/async.js";
11
12
  import { beginExecution, cancelAllFinalizeTimers, endExecution, finalizeFreePiSession, forgetFreePiSession, } from "./track.js";
12
13
  import { markWireSessionDirty, } from "./wire.js";
13
- import { recordUsage } from "./usage.js";
14
14
  function isAbortLike(error) {
15
15
  if (!error)
16
16
  return false;
@@ -26,7 +26,6 @@ const EVENT_TYPES = [
26
26
  "session.execution.succeeded",
27
27
  "session.execution.failed",
28
28
  "session.execution.interrupted",
29
- "session.usage.updated",
30
29
  "session.step.ended",
31
30
  "session.deleted",
32
31
  "location.shutdown",
@@ -103,6 +102,9 @@ async function handleEvent(ctx, deps, event) {
103
102
  }
104
103
  case "session.execution.succeeded": {
105
104
  endExecution(deps, event.data?.sessionID);
105
+ // Usage and cost are OpenCode's; the free-pi account quota is not, so a
106
+ // finished turn is the moment to refresh the picker's access filter.
107
+ void fetchQuota(deps).catch(() => undefined);
106
108
  return;
107
109
  }
108
110
  case "session.execution.interrupted": {
@@ -113,21 +115,12 @@ async function handleEvent(ctx, deps, event) {
113
115
  endExecution(deps, sessionID);
114
116
  return;
115
117
  }
116
- case "session.usage.updated": {
117
- const sessionID = event.data?.sessionID;
118
- if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
119
- return;
120
- }
121
- recordUsage(deps, sessionID, event.data?.cost, event.data?.tokens);
122
- return;
123
- }
124
118
  case "session.step.ended": {
125
119
  const sessionID = event.data?.sessionID;
126
120
  if (typeof sessionID !== "string" || !isFreePiSession(deps, sessionID)) {
127
121
  return;
128
122
  }
129
- recordUsage(deps, sessionID, event.data?.cost, event.data?.tokens);
130
- // Step tokens are per request; usage.updated is cumulative.
123
+ // Step tokens are per request; OpenCode owns cumulative usage.
131
124
  noteStepTokens(deps, deps.state.trackedModels.get(sessionID)?.modelID ?? "", event.data?.tokens);
132
125
  return;
133
126
  }
@@ -2,22 +2,17 @@
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, CONCURRENT_RETRY_BASE_MS, CONCURRENT_RETRY_MAX, CONCURRENT_RETRY_MAX_DELAY_MS, CONTEXT_DIET_MIN_TOKENS, CONTEXT_DIET_SHARE, DEFENSE_PROVIDER_ID, MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, TRANSPORT_RETRY_BASE_MS, TRANSPORT_RETRY_MAX, TRANSPORT_RETRY_MAX_DELAY_MS, } from "../constants.js";
6
- import { currentLiveLimits, learnedContextWindow, noteRejectedPrompt, } from "../catalog/live.js";
5
+ import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONTEXT_WINDOW, DEFENSE_PROVIDER_ID, PROVIDER_ID, SUBAGENT_HEADER, } from "../constants.js";
6
+ import { currentLiveLimits, noteRejectedPrompt } from "../catalog/live.js";
7
7
  import { closeFreePiSession } from "../api/session.js";
8
8
  import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
9
- import { parseFreePiError } from "../errors/parse.js";
10
9
  import { trimMap } from "../utils/async.js";
11
- import { pruneStaleToolResults } from "./diet.js";
12
- import { trimMessagesForBudget, estimateMessageTokens } from "./overflow.js";
13
10
  import { watchFreePiNotice } from "./notices.js";
14
- import { clearSpuriousOverflows, noteSpuriousOverflow, overflowingSpuriously, spuriousOverflowResponse, } from "./overflow.js";
15
- import { rememberReplayBody, replayConcurrentResponse, replaySpuriousOverflow, } from "./replay.js";
16
- import { localTitle } from "./title.js";
17
- import { rememberFreePiSession } from "./track.js";
11
+ import { noteSpuriousOverflow, overflowingSpuriously, profileRequest, SPURIOUS_OVERFLOW_SHARE, spuriousOverflowResponse, } from "./overflow.js";
12
+ import { rememberReplayBody, storedBody } from "./replay.js";
13
+ import { rememberFreePiSession, rememberTrackedModel } from "./track.js";
18
14
  import { hydrateWireSessionID, markWireSessionDirty, rotateWireSessionID, takeWireSessionDirty, wireSessionID, } from "./wire.js";
19
- import { FREE_PI_TOOL_NAMES, isFreePiSession, recordCompaction, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
20
- import { rememberTrackedModel } from "./usage.js";
15
+ import { FREE_PI_TOOL_NAMES, isFreePiSession, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
21
16
  const PENDING_LIMIT = 400;
22
17
  /** Each agent gets its own ad turn, so a subagent never reuses the parent's. */
23
18
  function pendingKeyOf(sessionID, agent, kind) {
@@ -30,169 +25,25 @@ function rememberPending(deps, key, turn) {
30
25
  trimMap(deps.state.pendingAdTurns, PENDING_LIMIT);
31
26
  deps.state.pendingAdTurns.set(key, turn);
32
27
  }
33
- /**
34
- * Fits the compaction request inside the ceiling the gateway has already
35
- * proven. OpenCode aborts the turn ("the compaction request cannot be reduced
36
- * further") when the summarizer request is rejected too, so the plugin drops
37
- * the oldest user turns before that can happen.
38
- */
39
- function fitCompactionMessages(deps, event, reserveTokens = 0) {
40
- const modelID = typeof event.model?.id === "string" ? event.model.id : "";
41
- const ceiling = learnedContextWindow(currentLiveLimits(), modelID);
42
- if (!ceiling)
43
- return;
44
- const messages = event.messages;
45
- if (!Array.isArray(messages) || messages.length === 0)
46
- return;
47
- const budget = Math.max(1_000, Math.floor(ceiling * 0.9) - Math.max(0, reserveTokens));
48
- const trimmed = trimMessagesForBudget(messages, budget);
49
- if (trimmed.dropped === 0)
50
- return;
51
- event.messages = [...trimmed.messages];
52
- deps.log.warn("free-pi trimmed the compaction request to fit the learned window", {
53
- sessionID: event.sessionID,
54
- model: modelID,
55
- window: ceiling,
56
- droppedMessages: trimmed.dropped,
57
- promptTokens: trimmed.tokens,
58
- });
59
- }
60
- /**
61
- * Collapses stale tool payloads before a request goes out. Long free-pi
62
- * sessions reach 100k-170k token prompts, and at that size the free models
63
- * lose the middle of the conversation even though the gateway accepts the
64
- * request. User wording, assistant text and the newest messages are never
65
- * touched; only old `read`/`grep`/`shell` results are shortened, with a note
66
- * that says they were pruned.
67
- */
68
- function applyContextDiet(deps, event) {
69
- const providerID = event.model?.providerID;
70
- const modelID = event.model?.id;
71
- if (typeof providerID !== "string" || typeof modelID !== "string")
72
- return;
73
- const context = deps.state.contextLimits.get(`${providerID}/${modelID}`);
74
- if (!context || context <= CONTEXT_DIET_MIN_TOKENS)
75
- return;
76
- const budget = Math.max(CONTEXT_DIET_MIN_TOKENS, Math.floor(context * CONTEXT_DIET_SHARE));
77
- if (budget >= context)
78
- return;
79
- const messages = event.messages;
80
- if (!Array.isArray(messages) || messages.length === 0)
81
- return;
82
- const result = pruneStaleToolResults(messages, budget, estimateMessageTokens);
83
- if (result.pruned === 0)
84
- return;
85
- event.messages = [...result.messages];
86
- deps.log.info("free-pi pruned stale tool results so the prompt stays attended", {
87
- sessionID: event.sessionID,
88
- model: modelID,
89
- context,
90
- budget,
91
- pruned: result.pruned,
92
- tokensBefore: result.tokensBefore,
93
- tokensAfter: result.tokensAfter,
94
- });
95
- }
96
- /**
97
- * Drops the reasoning OpenCode stores and echoes back inside assistant
98
- * messages.
99
- *
100
- * The provider request carries it as `reasoning_content`, but it is not input:
101
- * the gateway billed it on some models (a measured glm-5.3-flash request went
102
- * from 27 to 188 prompt tokens with the same answer) and the token estimate used
103
- * for diet/compaction assumes it is not sent. Removing it keeps the request
104
- * identical in behavior and smaller in credits.
105
- */
106
- function stripAssistantReasoning(deps, event) {
107
- const messages = event.messages;
108
- if (!Array.isArray(messages) || messages.length === 0)
109
- return;
110
- let chars = 0;
111
- let changed = false;
112
- const next = messages.map((message) => {
113
- if (!message || message.role !== "assistant")
114
- return message;
115
- let copy;
116
- const ensureCopy = () => {
117
- if (!copy)
118
- copy = { ...message };
119
- return copy;
120
- };
121
- for (const key of ["reasoning_content", "reasoning"]) {
122
- if (!(key in message))
123
- continue;
124
- const value = message[key];
125
- if (typeof value === "string")
126
- chars += value.length;
127
- ensureCopy();
128
- delete copy[key];
129
- changed = true;
130
- }
131
- if (Array.isArray(message.content)) {
132
- const kept = message.content.filter((part) => part?.type !== "reasoning" && part?.type !== "thinking");
133
- if (kept.length !== message.content.length) {
134
- ensureCopy();
135
- copy.content = kept;
136
- changed = true;
137
- }
138
- }
139
- return copy ?? message;
140
- });
141
- if (!changed)
142
- return;
143
- event.messages = next;
144
- if (chars > 0) {
145
- deps.log.info("free-pi dropped stored reasoning from the request", {
146
- sessionID: event.sessionID,
147
- chars,
148
- });
149
- }
150
- }
151
28
  /** Caps output tokens, applies the efficiency rule and derives the ad turn. */
152
29
  async function applyGeneration(deps, event, kind) {
153
30
  if (!isFreePiProvider(event.model?.providerID))
154
31
  return;
155
32
  rememberFreePiSession(deps, event.sessionID);
156
- // V1 disabled the title agent. OpenCode still asks for a title, so answer
157
- // from the first user message: no free-pi request, no ad impression, and the
158
- // session leaves the "New session" state immediately.
159
- if (kind === "title") {
160
- event.result = localTitle(event.messages);
161
- return;
162
- }
163
- stripAssistantReasoning(deps, event);
164
33
  const modelID = event.model?.id;
165
34
  // Remember the choice so a `model_requires_credits` failure can hide exactly
166
35
  // the model that was rejected instead of the whole provider.
167
36
  if (typeof event.sessionID === "string" && typeof modelID === "string") {
168
37
  deps.state.lastModelBySession.set(event.sessionID, `${event.model.providerID}/${modelID}`);
169
38
  }
170
- const limit = deps.state.outputLimits.get(`${event.model.providerID}/${modelID}`);
171
- // The compaction summary is the one response that must never be cut: a
172
- // summary that reaches the output limit fails the whole compaction and the
173
- // turn stops with nothing but the checkpoint. Leave OpenCode's own budget
174
- // for it and only cap the answers the user reads.
175
- const cap = Math.min(limit ?? MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_CEILING);
176
- if (event.options && kind !== "compaction") {
177
- const current = event.options.maxTokens;
178
- if (current === undefined || current > cap)
179
- event.options.maxTokens = cap;
180
- }
39
+ // Compaction is OpenCode's own: it decides when to summarize and what to
40
+ // keep, and the plugin does not measure, trim or rewrite the history. The
41
+ // only thing done here is rotating the wire session id for the request that
42
+ // follows, because the compaction request and the next turn overlap and the
43
+ // gateway holds one request slot per wire session.
181
44
  if (kind === "compaction") {
182
- fitCompactionMessages(deps, event);
183
- // OpenCode sends the messages it is folding into the summary, which is the
184
- // same set pi reports through `session_before_compact`.
185
- recordCompaction(deps, event.sessionID, Array.isArray(event.messages) ? event.messages.length : 0);
186
- // The compaction request and the next turn overlap: the runner starts the
187
- // next step while the gateway still holds this wire session's request slot,
188
- // which costs a `429 concurrent` and a full replay every time. Rotating the
189
- // id for the next request avoids that round trip without changing what the
190
- // model receives (the whole compacted history goes out every time).
191
45
  markWireSessionDirty(deps, event.sessionID);
192
46
  }
193
- else {
194
- applyContextDiet(deps, event);
195
- }
196
47
  const agent = event.agent;
197
48
  const turn = await resolveAdTurn(deps, {
198
49
  sessionID: event.sessionID,
@@ -241,7 +92,7 @@ async function applyModelRequest(deps, event) {
241
92
  // an impression the user never sees.
242
93
  if (event.kind === "title")
243
94
  return;
244
- Object.assign(event.headers, toolHeaders(deps, event.sessionID, event.kind !== "compaction"));
95
+ Object.assign(event.headers, toolHeaders(deps, event.sessionID));
245
96
  const pending = deps.state.pendingAdTurns.get(pendingKeyOf(event.sessionID, agent, event.kind));
246
97
  const turn = pending ??
247
98
  (await resolveAdTurn(deps, {
@@ -267,141 +118,17 @@ async function applyModelRequest(deps, event) {
267
118
  await ensureAdImpression(deps, token, event.sessionID, turn).catch(() => undefined);
268
119
  }
269
120
  }
270
- /** `concurrent` is free-pi's per-session 429 ("one request at a time"). */
271
- function isConcurrentFailure(error) {
272
- if (!error)
273
- return false;
274
- const body = typeof error.response?.body === "string" ? error.response.body : "";
275
- const message = typeof error.message === "string" ? error.message : "";
276
- return (/one request at a time/i.test(message) ||
277
- /one request at a time/i.test(body) ||
278
- /"concurrent"/.test(body));
279
- }
280
121
  /**
281
- * Limits and account blocks do not recover by retrying. pi's own retry helper
282
- * treats them as terminal (`NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN`), but
283
- * OpenCode retries every 429 by default, which surfaces as an endless
284
- * "Retrying…". The response rewrite turns most of these into a 400; this guard
285
- * covers the rest and keeps the CLI's behavior.
286
- */
287
- const TERMINAL_RETRY_CODES = new Set([
288
- "daily_cap",
289
- "hourly_ceiling",
290
- "rolling_cap",
291
- "global_cap",
292
- "account_ceiling",
293
- "free_usage_limit",
294
- "premium_allowance",
295
- "guest_allowance",
296
- "model_requires_credits",
297
- "insufficient_credits",
298
- "ads_required",
299
- "account_review",
300
- "region_unavailable",
301
- "unauthorized",
302
- "expired_token",
303
- "guest_login_required",
304
- "consent_required",
305
- "upgrade_required",
306
- "reward_required",
307
- "content_filter",
308
- "subagents_unavailable",
309
- ]);
310
- const TERMINAL_RETRY_PATTERN = /free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
311
- /**
312
- * A request that never reached the gateway. `provider.transport` covers the
313
- * typed path, while the pattern catches bare fetch errors. These are worth
314
- * retrying beyond the usual budget: a brief offline moment or a background
315
- * service restart is not a provider limit.
316
- */
317
- const TRANSPORT_RETRY_PATTERN = /ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|EPIPE|socket hang up|fetch failed|Unable to connect|connection (?:refused|reset)/i;
318
- function isTransportFailure(error) {
319
- const type = typeof error?.type === "string" ? error.type : "";
320
- if (/transport|network|connection/i.test(type))
321
- return true;
322
- const message = `${error?.message ?? ""}\n${error?.cause?.message ?? ""}`;
323
- return TRANSPORT_RETRY_PATTERN.test(message);
324
- }
325
- function isTerminalFailure(error) {
326
- if (error?.type === "aborted" ||
327
- /aborted|cancelled|canceled|interrupted|AbortError/i.test(`${error?.message ?? ""}`)) {
328
- return true;
329
- }
330
- const parsed = parseFreePiError(error, true);
331
- if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code))
332
- return true;
333
- const body = typeof error?.response?.body === "string" ? error.response.body : "";
334
- const message = typeof error?.message === "string" ? error.message : "";
335
- return TERMINAL_RETRY_PATTERN.test(`${message}\n${body}`);
336
- }
337
- /**
338
- * pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
339
- * `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
340
- * Non-retryable decisions are left alone.
341
- *
342
- * The one exception is `concurrent`: OpenCode treats the free-pi 429 as fatal,
343
- * and the server can leave a per-session lock behind that resets do not clear.
344
- * Rotating the wire session id and retrying turns that into a normal retry.
122
+ * Retries belong to OpenCode's session runner: it decides whether an error is
123
+ * retryable, how many times, and the delay. The one thing the runner cannot
124
+ * know is that free-pi holds a per-session request slot and that a failed
125
+ * attempt can leave it marked busy, so the next attempt must use a fresh wire
126
+ * id. This hook only arms that rotation and never touches `decision`.
345
127
  */
346
128
  function applyRetryPolicy(deps, event) {
347
- if (isConcurrentFailure(event.error)) {
348
- if (event.attempt > CONCURRENT_RETRY_MAX) {
349
- event.decision = { retry: false };
350
- return;
351
- }
352
- const previous = wireSessionID(deps, event.sessionID);
353
- const next = rotateWireSessionID(deps, event.sessionID);
354
- // Releasing the old id cleans up an orphaned slot; a leaked live lock
355
- // ignores reset, which is exactly why the next request uses a fresh id.
356
- void closeFreePiSession(deps, previous).catch(() => undefined);
357
- deps.log.info("free-pi session busy; retrying with a fresh session id", {
358
- sessionID: event.sessionID,
359
- from: previous,
360
- to: next,
361
- attempt: event.attempt,
362
- });
363
- event.decision = {
364
- retry: true,
365
- delay: Math.min(CONCURRENT_RETRY_BASE_MS * 2 ** (event.attempt - 1), CONCURRENT_RETRY_MAX_DELAY_MS),
366
- };
367
- return;
368
- }
369
- if (isTerminalFailure(event.error)) {
370
- // Remember the broken stream too, so the next turn rotates its wire id
371
- // instead of running into the stale per-session lock.
372
- markWireSessionDirty(deps, event.sessionID);
373
- event.decision = { retry: false };
374
- return;
375
- }
376
- if (isTransportFailure(event.error)) {
377
- if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
378
- event.decision = { retry: false };
379
- return;
380
- }
381
- // A connection that dropped mid-turn can leave the gateway's per-session
382
- // slot marked busy, so the next attempt should not reuse the wire id.
383
- markWireSessionDirty(deps, event.sessionID);
384
- const attempt = Math.max(1, event.attempt - 1);
385
- event.decision = {
386
- retry: true,
387
- delay: Math.min(TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1), TRANSPORT_RETRY_MAX_DELAY_MS),
388
- };
389
- deps.log.warn("free-pi could not be reached; retrying", {
390
- sessionID: event.sessionID,
391
- attempt: event.attempt,
392
- delay: event.decision.delay,
393
- error: typeof event.error?.message === "string" ? event.error.message : undefined,
394
- });
395
- return;
396
- }
397
- if (event.attempt > RETRY_MAX_RETRIES + 1) {
398
- event.decision = { retry: false };
399
- return;
400
- }
401
- if (!event.decision?.retry)
129
+ if (event.decision?.retry !== true)
402
130
  return;
403
- const attempt = Math.max(1, event.attempt - 1);
404
- event.decision.delay = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), RETRY_MAX_DELAY_MS);
131
+ markWireSessionDirty(deps, event.sessionID);
405
132
  }
406
133
  /**
407
134
  * Removes this plugin's tools from a request served by another provider. The
@@ -526,13 +253,75 @@ async function hookForProviders(ctx, name, callback, registrations) {
526
253
  }));
527
254
  }
528
255
  }
256
+ /**
257
+ * Handles every free-pi HTTP response: replays a busy session, rewrites
258
+ * context overflows into something OpenCode compacts on, turns long-lived
259
+ * limits into readable messages and watches for server notices.
260
+ *
261
+ * Split from `registerSessionHooks` because the response path is the plugin's
262
+ * most intricate logic and it was buried mid-function.
263
+ */
264
+ async function handleProviderResponse(ctx, deps, event) {
265
+ const response = event.response;
266
+ // Context overflow has to be handled first: a 429 context ceiling must
267
+ // become a 400 overflow, not a friendly long-lived limit.
268
+ const overflow = await rewriteContextOverflowResponse(response).catch(() => undefined);
269
+ if (overflow) {
270
+ const code = overflow.headers.get("x-free-pi-original-code") ?? "context_overflow";
271
+ // A gateway failure can report "too long" for a request that fits the
272
+ // model's window; compacting then loops (summarize, retry, rejected
273
+ // again). The plugin never re-sends the request itself: it only
274
+ // classifies the failure.
275
+ const body = await storedBody(deps, event).catch(() => undefined);
276
+ const profile = body ? profileRequest(body) : undefined;
277
+ const tokens = profile?.tokens;
278
+ const limits = currentLiveLimits();
279
+ const window = (profile?.model
280
+ ? limits?.models[profile.model]?.maxPromptTokens
281
+ : undefined) ??
282
+ limits?.window?.tokens ??
283
+ CONTEXT_WINDOW;
284
+ // A rejection is real when the request is at least as large as the window
285
+ // the gateway has already accepted for this model; anything meaningfully
286
+ // smaller is a provider failure, not an overflow.
287
+ const fitsWindow = typeof tokens === "number" &&
288
+ tokens < window * SPURIOUS_OVERFLOW_SHARE;
289
+ if (typeof tokens === "number" &&
290
+ !fitsWindow &&
291
+ profile?.model &&
292
+ profile.hasMedia !== true) {
293
+ // A rejection of a real prompt is the only free measurement of the
294
+ // gateway's ceiling. Attachments inflate the estimate and say nothing
295
+ // about the text window, so they are not learned from.
296
+ const learned = noteRejectedPrompt(deps, profile.model, tokens);
297
+ // Re-run the provider transform so this session's next compaction
298
+ // already targets the smaller window; no restart needed.
299
+ if (learned) {
300
+ void ctx.provider.reload().catch(() => undefined);
301
+ }
302
+ }
303
+ else if (fitsWindow) {
304
+ const count = noteSpuriousOverflow(deps, event.sessionID);
305
+ deps.log.info("free-pi rejected a request as too long that fits the model window", { sessionID: event.sessionID, code, tokens, window, rejections: count });
306
+ if (overflowingSpuriously(deps, event.sessionID)) {
307
+ markWireSessionDirty(deps, event.sessionID);
308
+ deps.log.warn("compact loop stopped: free-pi keeps rejecting a request that fits", { sessionID: event.sessionID, code, tokens, window });
309
+ event.response = watchFreePiNotice(deps, spuriousOverflowResponse(overflow));
310
+ return;
311
+ }
312
+ }
313
+ event.response = watchFreePiNotice(deps, overflow);
314
+ return;
315
+ }
316
+ const rewritten = await rewriteLimitResponse(response).catch(() => undefined);
317
+ event.response = watchFreePiNotice(deps, rewritten ?? response);
318
+ }
529
319
  export async function registerSessionHooks(ctx, deps) {
530
320
  const registrations = [];
531
321
  const generation = (kind) => (event) => applyGeneration(deps, event, kind);
532
322
  await hookForProviders(ctx, "context", generation("primary"), registrations);
533
323
  await hookForProviders(ctx, "compaction", generation("compaction"), registrations);
534
324
  await hookForProviders(ctx, "generate", generation("generate"), registrations);
535
- await hookForProviders(ctx, "title", generation("title"), registrations);
536
325
  // The generation hooks above only run for free-pi providers. These unscoped
537
326
  // ones strip the plugin's tools from every other provider's requests.
538
327
  for (const name of ["context", "compaction", "generate"]) {
@@ -553,61 +342,7 @@ export async function registerSessionHooks(ctx, deps) {
553
342
  })));
554
343
  await hookForProviders(ctx, "model.request", (event) => applyModelRequest(deps, event), registrations);
555
344
  await hookForProviders(ctx, "http.request", (event) => rememberReplayBody(deps, event), registrations);
556
- await hookForProviders(ctx, "http.response", async (event) => {
557
- // Recover a per-session `429 concurrent` before OpenCode sees it: the
558
- // step's prepared request is reused on retry, so rotating the id in the
559
- // retry hook is too late for the failed attempt.
560
- const replayed = await replayConcurrentResponse(deps, event).catch(() => undefined);
561
- const response = replayed ?? event.response;
562
- // Context overflow has to be handled first: a 429 context ceiling must
563
- // become a 400 overflow, not a friendly long-lived limit.
564
- const overflow = await rewriteContextOverflowResponse(response).catch(() => undefined);
565
- if (overflow) {
566
- const code = overflow.headers.get("x-free-pi-original-code") ?? "context_overflow";
567
- // A gateway failure can report "too long" for a request that fits the
568
- // window. Compacting then loops, so retry on a fresh wire session
569
- // first, and stop compacting once the session has seen a few.
570
- const reviewed = await replaySpuriousOverflow(deps, event).catch(() => ({}));
571
- // A rejection of a real prompt is the only free measurement of the
572
- // gateway's ceiling. Attachments inflate the estimate and say nothing
573
- // about the text window, so they are not learned from.
574
- if (reviewed.spurious === false &&
575
- typeof reviewed.tokens === "number" &&
576
- reviewed.model &&
577
- reviewed.hasMedia !== true) {
578
- const learned = noteRejectedPrompt(deps, reviewed.model, reviewed.tokens);
579
- // Re-run the provider transform so this session's next compaction
580
- // already targets the smaller window; no restart needed.
581
- if (learned) {
582
- void ctx.provider.reload().catch(() => undefined);
583
- }
584
- }
585
- if (reviewed.response) {
586
- clearSpuriousOverflows(deps, event.sessionID);
587
- event.response = watchFreePiNotice(deps, reviewed.response);
588
- return;
589
- }
590
- if (reviewed.spurious) {
591
- const count = noteSpuriousOverflow(deps, event.sessionID);
592
- deps.log.info("free-pi rejected a request as too long that fits the model window", {
593
- sessionID: event.sessionID,
594
- code,
595
- tokens: reviewed.tokens,
596
- rejections: count,
597
- });
598
- if (overflowingSpuriously(deps, event.sessionID)) {
599
- markWireSessionDirty(deps, event.sessionID);
600
- deps.log.warn("compact loop stopped: free-pi keeps rejecting a request that fits", { sessionID: event.sessionID, code, tokens: reviewed.tokens });
601
- event.response = watchFreePiNotice(deps, spuriousOverflowResponse(overflow));
602
- return;
603
- }
604
- }
605
- event.response = watchFreePiNotice(deps, overflow);
606
- return;
607
- }
608
- const rewritten = await rewriteLimitResponse(response).catch(() => undefined);
609
- event.response = watchFreePiNotice(deps, rewritten ?? response);
610
- }, registrations);
345
+ await hookForProviders(ctx, "http.response", (event) => handleProviderResponse(ctx, deps, event), registrations);
611
346
  await hookForProviders(ctx, "retry", (event) => applyRetryPolicy(deps, event), registrations);
612
347
  await registerToolHooks(ctx, deps, registrations);
613
348
  return registrations;
@@ -14,8 +14,13 @@
14
14
  * compaction.
15
15
  */
16
16
  import type { Deps } from "../deps.js";
17
- /** A request below this many tokens cannot exhaust a 200k window on its own. */
18
- export declare const SPURIOUS_OVERFLOW_TOKENS = 60000;
17
+ /**
18
+ * A request smaller than this share of the model's window cannot be a real
19
+ * overflow: the gateway has accepted prompts up to the window for that model,
20
+ * so a rejection well below it is a provider failure and compacting again
21
+ * cannot help.
22
+ */
23
+ export declare const SPURIOUS_OVERFLOW_SHARE = 0.75;
19
24
  export declare const SPURIOUS_OVERFLOW_MESSAGE: string;
20
25
  export type RequestProfile = {
21
26
  /** Approximate token count of the whole body. */
@@ -35,32 +40,6 @@ export type RequestProfile = {
35
40
  * the model's text window, so callers must not learn a ceiling from it.
36
41
  */
37
42
  export declare function profileRequest(body: string): RequestProfile;
38
- /** Token count of a request body, without the extra facts. */
39
- export declare function measureRequestTokens(body: string): number;
40
- /**
41
- * Cheap per-message estimate; the body is serialized once per message.
42
- *
43
- * Assistant reasoning is stored in the session but the provider lowering drops
44
- * it before the request (`FREE_PI_TRACE` shows `reasoningChars: 0`). Counting it
45
- * made the diet and the compaction trim believe a prompt was 30-50k tokens
46
- * larger than the wire, so they pruned or dropped turns the model never saw.
47
- */
48
- export declare function estimateMessageTokens(message: unknown): number;
49
- /**
50
- * Keeps the newest part of a message list inside `budget` tokens, cutting only
51
- * at user turns so an assistant tool call never loses its results.
52
- *
53
- * OpenCode refuses to compact when the summarization request itself is still
54
- * too large, and then the turn dies with nothing but the checkpoint shown. The
55
- * gateway's real ceiling is lower than the advertised window, so the plugin
56
- * trims the oldest turns it can spare before the summarizer is asked to read
57
- * them.
58
- */
59
- export declare function trimMessagesForBudget(messages: readonly unknown[], budget: number): {
60
- readonly messages: readonly unknown[];
61
- readonly dropped: number;
62
- readonly tokens: number;
63
- };
64
43
  /**
65
44
  * Records a rejection of a request that fits, and returns the number of them
66
45
  * seen for the session inside the current window. A run of them means the