@eduardo191labs/opencode-free-pi 0.3.3 → 0.3.5

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/src/plugin.ts CHANGED
@@ -64,8 +64,9 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
64
64
  const registry = registryResult ?? state.cachedRegistry;
65
65
  const { main, defense } = partitionModels(catalog);
66
66
  const candidates = modelRegistryCandidates(registry);
67
- const mainModels = buildModels(main, candidates);
68
- const defenseModels = buildModels(defense, candidates);
67
+ const buildOptions = { compact100: state.costExperimentArm === "compact100" };
68
+ const mainModels = buildModels(main, candidates, buildOptions);
69
+ const defenseModels = buildModels(defense, candidates, buildOptions);
69
70
 
70
71
  for (const [id, model] of Object.entries(mainModels)) {
71
72
  state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Prompt-cache miss notices, mirroring pi's `cache-stats` detector.
3
+ *
4
+ * free-pi reports no per-token cost, so only the token threshold applies. The
5
+ * notices are opt-in because OpenCode has no toast surface for them.
6
+ */
7
+
8
+ import {
9
+ CACHE_MISS_NOISE_FLOOR_TOKENS,
10
+ CACHE_MISS_NOTICE_TOKENS,
11
+ CACHE_TTL_MS,
12
+ DEFENSE_PROVIDER_ID,
13
+ PROVIDER_ID,
14
+ } from "../constants.js";
15
+ import type { Deps } from "../deps.js";
16
+ import type { TokenUsageLike } from "../types.js";
17
+
18
+ function noticesEnabled(): boolean {
19
+ const value = process.env.FREE_PI_CACHE_MISS_NOTICES?.trim().toLowerCase();
20
+ return value === "1" || value === "true" || value === "yes";
21
+ }
22
+
23
+ function idleText(idleMs: number): string {
24
+ const minutes = Math.round(idleMs / 60_000);
25
+ return idleMs > CACHE_TTL_MS ? ` after ${minutes}m idle` : "";
26
+ }
27
+
28
+ /**
29
+ * Records one step's usage and logs a miss when the prompt was re-billed.
30
+ * `session.step.ended` carries per-step tokens; `session.usage.updated` is a
31
+ * cumulative total and must not be fed here.
32
+ */
33
+ export function observeStepUsage(
34
+ deps: Deps,
35
+ sessionID: string | undefined,
36
+ tokens: TokenUsageLike | undefined,
37
+ ): void {
38
+ if (!noticesEnabled() || typeof sessionID !== "string" || !sessionID) return;
39
+ const tracked = deps.state.trackedModels.get(sessionID);
40
+ if (
41
+ tracked?.providerID !== PROVIDER_ID &&
42
+ tracked?.providerID !== DEFENSE_PROVIDER_ID
43
+ )
44
+ return;
45
+
46
+ const cacheRead = tokens?.cache?.read ?? 0;
47
+ const cacheWrite = tokens?.cache?.write ?? 0;
48
+ const promptTokens = (tokens?.input ?? 0) + cacheRead + cacheWrite;
49
+ if (promptTokens <= 0) return;
50
+
51
+ const now = Date.now();
52
+ const modelKey = `${tracked.providerID}/${tracked.modelID}`;
53
+ const previous = deps.state.cacheMisses.get(sessionID);
54
+ if (previous) {
55
+ const reportedCache =
56
+ previous.reportedCache || cacheRead + cacheWrite > 0;
57
+ if (reportedCache) {
58
+ const missedTokens =
59
+ Math.min(previous.promptTokens, promptTokens) - cacheRead;
60
+ if (missedTokens > CACHE_MISS_NOISE_FLOOR_TOKENS) {
61
+ const modelChanged = previous.modelKey !== modelKey;
62
+ if (missedTokens >= CACHE_MISS_NOTICE_TOKENS) {
63
+ deps.log.info(
64
+ `cache miss: ${missedTokens} tokens re-billed${idleText(now - previous.at)}${modelChanged ? " (model changed)" : ""}`,
65
+ { sessionID, model: modelKey },
66
+ );
67
+ }
68
+ }
69
+ }
70
+ }
71
+
72
+ deps.state.cacheMisses.set(sessionID, {
73
+ promptTokens,
74
+ at: now,
75
+ modelKey,
76
+ reportedCache: cacheRead + cacheWrite > 0 || (previous?.reportedCache ?? false),
77
+ });
78
+ }
79
+
80
+ export function forgetCacheMiss(deps: Deps, sessionID: string): void {
81
+ deps.state.cacheMisses.delete(sessionID);
82
+ }
@@ -6,6 +6,8 @@ import { readCredentialsToken } from "../auth/credentials.js";
6
6
  import { tokenFromCredential } from "../auth/credential.js";
7
7
  import type { Deps } from "../deps.js";
8
8
  import { handleFreePiError } from "../errors/handle.js";
9
+ import { forgetCacheMiss, observeStepUsage } from "./cache.js";
10
+ import { forgetToolStats } from "./tools.js";
9
11
  import {
10
12
  beginExecution,
11
13
  cancelAllFinalizeTimers,
@@ -18,6 +20,7 @@ import { recordUsage } from "./usage.js";
18
20
  const EVENT_TYPES = [
19
21
  "credential.updated",
20
22
  "credential.switched",
23
+ "session.created",
21
24
  "session.execution.started",
22
25
  "session.execution.succeeded",
23
26
  "session.execution.failed",
@@ -44,6 +47,16 @@ async function handleEvent(
44
47
  await ctx.provider.reload().catch(() => undefined);
45
48
  return;
46
49
  }
50
+ case "session.created": {
51
+ // The CLI marks requests from its own subagents so the server can bill
52
+ // and rate-limit them separately; OpenCode's children map the same way.
53
+ const sessionID = event.data?.sessionID;
54
+ if (typeof sessionID !== "string") return;
55
+ if (typeof event.data?.parentID === "string") {
56
+ deps.state.subagentSessions.add(sessionID);
57
+ }
58
+ return;
59
+ }
47
60
  case "session.execution.started": {
48
61
  beginExecution(deps, event.data?.sessionID);
49
62
  return;
@@ -63,7 +76,15 @@ async function handleEvent(
63
76
  endExecution(deps, event.data?.sessionID);
64
77
  return;
65
78
  }
66
- case "session.usage.updated":
79
+ case "session.usage.updated": {
80
+ recordUsage(
81
+ deps,
82
+ event.data?.sessionID,
83
+ event.data?.cost,
84
+ event.data?.tokens,
85
+ );
86
+ return;
87
+ }
67
88
  case "session.step.ended": {
68
89
  recordUsage(
69
90
  deps,
@@ -71,6 +92,8 @@ async function handleEvent(
71
92
  event.data?.cost,
72
93
  event.data?.tokens,
73
94
  );
95
+ // Step tokens are per request; usage.updated is cumulative.
96
+ observeStepUsage(deps, event.data?.sessionID, event.data?.tokens);
74
97
  return;
75
98
  }
76
99
  case "session.deleted": {
@@ -78,6 +101,9 @@ async function handleEvent(
78
101
  if (typeof sessionID !== "string") return;
79
102
  await finalizeFreePiSession(deps, sessionID);
80
103
  forgetFreePiSession(deps, sessionID);
104
+ forgetCacheMiss(deps, sessionID);
105
+ forgetToolStats(deps, sessionID);
106
+ deps.state.subagentSessions.delete(sessionID);
81
107
  return;
82
108
  }
83
109
  case "location.shutdown": {
@@ -11,6 +11,10 @@ import {
11
11
  EFFICIENCY_RULE,
12
12
  MAX_OUTPUT_TOKENS,
13
13
  PROVIDER_ID,
14
+ RETRY_BASE_DELAY_MS,
15
+ RETRY_MAX_DELAY_MS,
16
+ RETRY_MAX_RETRIES,
17
+ SUBAGENT_HEADER,
14
18
  } from "../constants.js";
15
19
  import type { Deps } from "../deps.js";
16
20
  import {
@@ -18,7 +22,15 @@ import {
18
22
  rewriteLimitResponse,
19
23
  } from "../errors/limit.js";
20
24
  import { trimMap } from "../utils/async.js";
25
+ import { watchFreePiNotice } from "./notices.js";
26
+ import { localTitle } from "./title.js";
21
27
  import { rememberFreePiSession } from "./track.js";
28
+ import {
29
+ recordCompaction,
30
+ recordToolEnd,
31
+ recordToolStart,
32
+ toolHeaders,
33
+ } from "./tools.js";
22
34
  import { rememberTrackedModel } from "./usage.js";
23
35
 
24
36
  type Registration = { dispose: () => Promise<void> };
@@ -28,7 +40,8 @@ type SessionHookName =
28
40
  | "generate"
29
41
  | "title"
30
42
  | "model.request"
31
- | "http.response";
43
+ | "http.response"
44
+ | "retry";
32
45
  type RequestKind = "primary" | "compaction" | "generate" | "title";
33
46
 
34
47
  const PENDING_LIMIT = 400;
@@ -60,10 +73,11 @@ async function applyGeneration(
60
73
  if (!isFreePiProvider(event.model?.providerID)) return;
61
74
  rememberFreePiSession(deps, event.sessionID);
62
75
 
63
- // V1 disabled the title agent. Returning an empty result keeps the title
64
- // request off the free-pi account, which also avoids an extra session slot.
76
+ // V1 disabled the title agent. OpenCode still asks for a title, so answer
77
+ // from the first user message: no free-pi request, no ad impression, and the
78
+ // session leaves the "New session" state immediately.
65
79
  if (kind === "title") {
66
- event.result = "";
80
+ event.result = localTitle(event.messages);
67
81
  return;
68
82
  }
69
83
 
@@ -77,6 +91,16 @@ async function applyGeneration(
77
91
  if (current === undefined || current > cap) event.options.maxTokens = cap;
78
92
  }
79
93
 
94
+ if (kind === "compaction") {
95
+ // OpenCode sends the messages it is folding into the summary, which is the
96
+ // same set pi reports through `session_before_compact`.
97
+ recordCompaction(
98
+ deps,
99
+ event.sessionID,
100
+ Array.isArray(event.messages) ? event.messages.length : 0,
101
+ );
102
+ }
103
+
80
104
  if (deps.state.costExperimentArm === "efficiency") {
81
105
  const system = Array.isArray(event.system) ? event.system : [];
82
106
  if (
@@ -114,6 +138,9 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
114
138
  if (token) event.headers.authorization = `Bearer ${token}`;
115
139
  event.headers["x-session-id"] = event.sessionID;
116
140
  event.headers["x-client-version"] = deps.state.latestClientVersion;
141
+ if (deps.state.subagentSessions.has(event.sessionID)) {
142
+ event.headers[SUBAGENT_HEADER] = "1";
143
+ }
117
144
  if (deps.state.costExperimentArm) {
118
145
  event.headers[COST_EXPERIMENT_HEADER] = deps.state.costExperimentArm;
119
146
  }
@@ -122,6 +149,11 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
122
149
  // an impression the user never sees.
123
150
  if (event.kind === "title") return;
124
151
 
152
+ Object.assign(
153
+ event.headers,
154
+ toolHeaders(deps, event.sessionID, event.kind !== "compaction"),
155
+ );
156
+
125
157
  const pending = deps.state.pendingAdTurns.get(
126
158
  pendingKeyOf(event.sessionID, agent, event.kind),
127
159
  );
@@ -145,6 +177,47 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
145
177
  }
146
178
  }
147
179
 
180
+ /**
181
+ * pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
182
+ * `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
183
+ * Non-retryable decisions are left alone.
184
+ */
185
+ function applyRetryPolicy(event: any): void {
186
+ if (event.attempt > RETRY_MAX_RETRIES + 1) {
187
+ event.decision = { retry: false };
188
+ return;
189
+ }
190
+ if (!event.decision?.retry) return;
191
+ const attempt = Math.max(1, event.attempt - 1);
192
+ event.decision.delay = Math.min(
193
+ RETRY_BASE_DELAY_MS * 2 ** (attempt - 1),
194
+ RETRY_MAX_DELAY_MS,
195
+ );
196
+ }
197
+
198
+ async function registerToolHooks(
199
+ ctx: Plugin.Context,
200
+ deps: Deps,
201
+ registrations: Registration[],
202
+ ): Promise<void> {
203
+ if (!ctx.tool?.hook) return;
204
+ registrations.push(
205
+ await ctx.tool.hook("execute.before", (event) => {
206
+ recordToolStart(deps, event.sessionID, event.id);
207
+ }),
208
+ );
209
+ registrations.push(
210
+ await ctx.tool.hook("execute.after", (event) => {
211
+ recordToolEnd(deps, event.sessionID, {
212
+ id: event.id,
213
+ tool: event.tool,
214
+ status: event.status,
215
+ ...(event.status === "completed" ? { result: event.result } : {}),
216
+ });
217
+ }),
218
+ );
219
+ }
220
+
148
221
  async function hookForProviders(
149
222
  ctx: Plugin.Context,
150
223
  name: SessionHookName,
@@ -193,16 +266,26 @@ export async function registerSessionHooks(
193
266
  event.response,
194
267
  ).catch(() => undefined);
195
268
  if (overflow) {
196
- event.response = overflow;
269
+ event.response = watchFreePiNotice(deps, overflow);
197
270
  return;
198
271
  }
199
272
  const rewritten = await rewriteLimitResponse(event.response).catch(
200
273
  () => undefined,
201
274
  );
202
- if (rewritten) event.response = rewritten;
275
+ event.response = watchFreePiNotice(
276
+ deps,
277
+ rewritten ?? event.response,
278
+ );
203
279
  },
204
280
  registrations,
205
281
  );
282
+ await hookForProviders(
283
+ ctx,
284
+ "retry",
285
+ (event: any) => applyRetryPolicy(event),
286
+ registrations,
287
+ );
288
+ await registerToolHooks(ctx, deps, registrations);
206
289
 
207
290
  return registrations;
208
291
  }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Logs the two server notices the free-pi CLI watches for: the
3
+ * `x-freepi-notice` header and the `: freepi_notice` SSE marker sent when the
4
+ * server restarts.
5
+ */
6
+
7
+ import type { Deps } from "../deps.js";
8
+
9
+ const NOTICE_HEADER = "x-freepi-notice";
10
+ const SSE_NOTICE = "freepi_notice";
11
+
12
+ export function watchFreePiNotice(deps: Deps, response: Response): Response {
13
+ const notice = response.headers.get(NOTICE_HEADER);
14
+ if (notice) deps.log.info("free-pi server notice", { notice });
15
+
16
+ const type = response.headers.get("content-type") ?? "";
17
+ if (!response.body || !type.includes("text/event-stream")) return response;
18
+
19
+ const decoder = new TextDecoder();
20
+ let reported = false;
21
+ const body = response.body.pipeThrough(
22
+ new TransformStream<Uint8Array, Uint8Array>({
23
+ transform(chunk, controller) {
24
+ if (!reported) {
25
+ const text = decoder.decode(chunk, { stream: true });
26
+ if (text.includes(SSE_NOTICE)) {
27
+ reported = true;
28
+ deps.log.warn("free-pi server sent a restart notice");
29
+ }
30
+ }
31
+ controller.enqueue(chunk);
32
+ },
33
+ }),
34
+ );
35
+ return new Response(body, {
36
+ status: response.status,
37
+ statusText: response.statusText,
38
+ headers: response.headers,
39
+ });
40
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Builds session titles locally.
3
+ *
4
+ * free-pi charges credits and shows ads per model request, and the CLI never
5
+ * spends a turn on a title. OpenCode asks the selected model for a title, so
6
+ * the title hook answers from the first user message instead: the session gets
7
+ * a real name immediately, no ad is fetched, and a failed title request can
8
+ * never leave the session stuck on "New session".
9
+ */
10
+
11
+ const MAX_TITLE_LENGTH = 60;
12
+ const MAX_SOURCE_LENGTH = 4_000;
13
+ const MESSAGE_BLOCK = /<message>([\s\S]*?)<\/message>/i;
14
+ const CONVERSATION_BLOCK = /<conversation>([\s\S]*?)<\/conversation>/i;
15
+ const PREFIX = /^(?:original request|recent conversation|user|assistant)\s*:\s*/i;
16
+ const NOISE = /^(?:```[\w-]*|---+|===+|\*\*\*+)$/;
17
+ const XML_LINE = /^<\/?[a-z][^>]*>$/i;
18
+ const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
19
+
20
+ type TitleMessage = {
21
+ role?: unknown;
22
+ type?: unknown;
23
+ text?: unknown;
24
+ content?: unknown;
25
+ };
26
+
27
+ function textOf(content: unknown): string {
28
+ if (typeof content === "string") return content;
29
+ if (!Array.isArray(content)) return "";
30
+ return content
31
+ .filter(
32
+ (part: any) => part?.type === "text" && typeof part.text === "string",
33
+ )
34
+ .map((part: any) => part.text)
35
+ .join("\n");
36
+ }
37
+
38
+ function latestUserText(messages: readonly TitleMessage[]): string {
39
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
40
+ const message = messages[index];
41
+ const role = message?.role ?? message?.type;
42
+ if (role !== "user") continue;
43
+ const text =
44
+ typeof message?.text === "string"
45
+ ? message.text
46
+ : textOf(message?.content);
47
+ if (text.trim()) return text;
48
+ }
49
+ return "";
50
+ }
51
+
52
+ /** OpenCode wraps the source in `<message>` or `<conversation>` tags. */
53
+ function sourceText(messages: readonly TitleMessage[]): string {
54
+ const raw = latestUserText(messages);
55
+ const block =
56
+ MESSAGE_BLOCK.exec(raw)?.[1] ?? CONVERSATION_BLOCK.exec(raw)?.[1] ?? raw;
57
+ return block.slice(0, MAX_SOURCE_LENGTH);
58
+ }
59
+
60
+ function cleanLine(line: string): string | undefined {
61
+ let value = line.replace(CONTROL, " ").trim();
62
+ if (!value) return undefined;
63
+ value = value
64
+ .replace(/^#{1,6}\s+/, "")
65
+ .replace(/^[-*+>]\s+/, "")
66
+ .trim();
67
+ value = value.replace(PREFIX, "").trim();
68
+ if (!value || NOISE.test(value) || XML_LINE.test(value)) return undefined;
69
+ value = value.replace(/^["'`]+|["'`]+$/g, "").trim();
70
+ return value || undefined;
71
+ }
72
+
73
+ function truncate(value: string): string {
74
+ if (value.length <= MAX_TITLE_LENGTH) return value;
75
+ const cut = value.slice(0, MAX_TITLE_LENGTH - 3);
76
+ const space = cut.lastIndexOf(" ");
77
+ return `${(space >= 20 ? cut.slice(0, space) : cut).trimEnd()}...`;
78
+ }
79
+
80
+ /** Derives a title from the first meaningful line of the title request. */
81
+ export function localTitle(messages: readonly TitleMessage[] | undefined): string {
82
+ if (!Array.isArray(messages) || messages.length === 0) return "Session";
83
+ const lines = sourceText(messages)
84
+ .split(/\r?\n/)
85
+ .map(cleanLine)
86
+ .filter((line): line is string => Boolean(line));
87
+ const first = lines[0];
88
+ if (!first) return "Session";
89
+ return truncate(first.replace(/[\s:;,\-]+$/g, "").trim()) || "Session";
90
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Tool outcome headers, mirroring the free-pi provider CLI's
3
+ * `free-pi-tool-outcomes` extension:
4
+ *
5
+ * - `x-freepi-tool-meta: v1:<id>~<ms>~<exit>~<truncated>,...`
6
+ * - `x-freepi-tool-errors: v1:<ids>` (`v1x:` once old IDs were evicted)
7
+ * - `x-freepi-compacted: v1:<dropped messages>` on the request after compaction
8
+ */
9
+
10
+ import {
11
+ COMPACTED_HEADER,
12
+ DEFENSE_PROVIDER_ID,
13
+ PROVIDER_ID,
14
+ TOOL_ERRORS_HEADER,
15
+ TOOL_ID_LIMIT,
16
+ TOOL_META_BUDGET,
17
+ TOOL_META_HEADER,
18
+ } from "../constants.js";
19
+ import type { Deps } from "../deps.js";
20
+ import type { ToolStats } from "../types.js";
21
+ import { trimMap } from "../utils/async.js";
22
+
23
+ const ID_PATTERN = /^[\w.:-]{1,100}$/;
24
+ const MAX_ENTRY_LENGTH = 150;
25
+ const MAX_STARTED = 200;
26
+
27
+ type ToolResultLike = {
28
+ metadata?: Record<string, unknown>;
29
+ };
30
+
31
+ type ToolEnd = {
32
+ id: string;
33
+ tool: string;
34
+ status: "completed" | "error";
35
+ result?: ToolResultLike;
36
+ };
37
+
38
+ function isFreePiSession(deps: Deps, sessionID: string): boolean {
39
+ if (deps.state.freePiSessions.has(sessionID)) return true;
40
+ const tracked = deps.state.trackedModels.get(sessionID);
41
+ return (
42
+ tracked?.providerID === PROVIDER_ID ||
43
+ tracked?.providerID === DEFENSE_PROVIDER_ID
44
+ );
45
+ }
46
+
47
+ function statsFor(deps: Deps, sessionID: string): ToolStats {
48
+ let stats = deps.state.toolStats.get(sessionID);
49
+ if (!stats) {
50
+ stats = {
51
+ meta: [],
52
+ metaBytes: 3,
53
+ failed: [],
54
+ evicted: false,
55
+ started: new Map(),
56
+ compacted: 0,
57
+ };
58
+ trimMap(deps.state.toolStats, 200);
59
+ deps.state.toolStats.set(sessionID, stats);
60
+ }
61
+ return stats;
62
+ }
63
+
64
+ function shellExit(stats: ToolEnd): string {
65
+ if (stats.status === "error") return "-";
66
+ const exit = stats.result?.metadata?.exit;
67
+ return typeof exit === "number" ? String(exit) : "0";
68
+ }
69
+
70
+ function truncated(stats: ToolEnd): boolean {
71
+ const metadata = stats.result?.metadata;
72
+ if (metadata?.truncated === true) return true;
73
+ const truncation = metadata?.truncation;
74
+ return Boolean(
75
+ truncation &&
76
+ typeof truncation === "object" &&
77
+ (truncation as Record<string, unknown>).truncated === true,
78
+ );
79
+ }
80
+
81
+ export function recordToolStart(
82
+ deps: Deps,
83
+ sessionID: string,
84
+ id: string,
85
+ ): void {
86
+ if (!isFreePiSession(deps, sessionID) || !ID_PATTERN.test(id)) return;
87
+ const stats = statsFor(deps, sessionID);
88
+ stats.started.set(id, Date.now());
89
+ if (stats.started.size <= MAX_STARTED) return;
90
+ const oldest = stats.started.keys().next().value;
91
+ if (oldest !== undefined) stats.started.delete(oldest);
92
+ }
93
+
94
+ export function recordToolEnd(deps: Deps, sessionID: string, end: ToolEnd): void {
95
+ if (!isFreePiSession(deps, sessionID) || !ID_PATTERN.test(end.id)) return;
96
+ const stats = statsFor(deps, sessionID);
97
+ const startedAt = stats.started.get(end.id);
98
+ stats.started.delete(end.id);
99
+ const duration = startedAt === undefined ? 0 : Date.now() - startedAt;
100
+ const entry = `${end.id}~${Math.max(0, Math.round(duration))}~${shellExit(end)}~${truncated(end) ? 1 : 0}`;
101
+ if (entry.length <= MAX_ENTRY_LENGTH) {
102
+ stats.meta.push(entry);
103
+ stats.metaBytes += entry.length + 1;
104
+ while (stats.metaBytes > TOOL_META_BUDGET && stats.meta.length > 1) {
105
+ const removed = stats.meta.shift();
106
+ stats.metaBytes -= (removed?.length ?? 0) + 1;
107
+ }
108
+ }
109
+ if (end.status !== "error") return;
110
+ stats.failed.push(end.id);
111
+ if (stats.failed.length <= TOOL_ID_LIMIT) return;
112
+ stats.failed.shift();
113
+ stats.evicted = true;
114
+ }
115
+
116
+ export function recordCompaction(
117
+ deps: Deps,
118
+ sessionID: string,
119
+ droppedMessages: number,
120
+ ): void {
121
+ if (!isFreePiSession(deps, sessionID) || droppedMessages <= 0) return;
122
+ const stats = statsFor(deps, sessionID);
123
+ stats.compacted += droppedMessages;
124
+ }
125
+
126
+ /**
127
+ * Headers for the outgoing request. `consumeCompacted` is false for the
128
+ * compaction request itself so the marker lands on the request that follows.
129
+ */
130
+ export function toolHeaders(
131
+ deps: Deps,
132
+ sessionID: string,
133
+ consumeCompacted: boolean,
134
+ ): Record<string, string> {
135
+ const stats = deps.state.toolStats.get(sessionID);
136
+ const headers: Record<string, string> = {};
137
+ if (stats?.meta.length) {
138
+ headers[TOOL_META_HEADER] = `v1:${stats.meta.join(",")}`;
139
+ }
140
+ if (stats && consumeCompacted && stats.compacted > 0) {
141
+ headers[COMPACTED_HEADER] = `v1:${stats.compacted}`;
142
+ stats.compacted = 0;
143
+ }
144
+ headers[TOOL_ERRORS_HEADER] = `${stats?.evicted ? "v1x" : "v1"}:${(stats?.failed ?? []).join(",")}`;
145
+ return headers;
146
+ }
147
+
148
+ export function forgetToolStats(deps: Deps, sessionID: string): void {
149
+ deps.state.toolStats.delete(sessionID);
150
+ }
package/src/state.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  import { DEFAULT_CLIENT_VERSION } from "./constants.js";
4
4
  import type {
5
5
  AdTurn,
6
+ CacheMissState,
6
7
  Catalog,
7
8
  FreePiError,
8
9
  ModelRegistry,
@@ -10,6 +11,7 @@ import type {
10
11
  RequestUsage,
11
12
  SessionResetOutcome,
12
13
  TokenCheckState,
14
+ ToolStats,
13
15
  TrackedModel,
14
16
  } from "./types.js";
15
17
 
@@ -25,6 +27,8 @@ export type RuntimeState = {
25
27
  registryAttemptAt: number;
26
28
  registryPromise?: Promise<ModelRegistry | undefined>;
27
29
  costExperimentArm?: string;
30
+ lastCatalogNotice?: string;
31
+ lastQuotaNotice?: string;
28
32
  catalogModels: Catalog;
29
33
  outputLimits: Map<string, number>;
30
34
 
@@ -54,6 +58,9 @@ export type RuntimeState = {
54
58
  pendingAdTurns: Map<string, AdTurn>;
55
59
  adImpressions: Map<string, Promise<void>>;
56
60
  trackedModels: Map<string, TrackedModel>;
61
+ cacheMisses: Map<string, CacheMissState>;
62
+ toolStats: Map<string, ToolStats>;
63
+ subagentSessions: Set<string>;
57
64
  };
58
65
 
59
66
  export function createRuntimeState(): RuntimeState {
@@ -78,5 +85,8 @@ export function createRuntimeState(): RuntimeState {
78
85
  pendingAdTurns: new Map(),
79
86
  adImpressions: new Map(),
80
87
  trackedModels: new Map(),
88
+ cacheMisses: new Map(),
89
+ toolStats: new Map(),
90
+ subagentSessions: new Set(),
81
91
  };
82
92
  }
package/src/types.ts CHANGED
@@ -71,8 +71,10 @@ export type RegistryCandidate = {
71
71
  };
72
72
 
73
73
  export type Catalog = {
74
+ min?: string;
74
75
  latest?: string;
75
76
  default_model?: string;
77
+ notice?: string;
76
78
  models?: CatalogModel[];
77
79
  cost_experiment?: { arm?: string };
78
80
  };
@@ -86,6 +88,9 @@ export type ModelDefinition = {
86
88
  reasoning: boolean;
87
89
  reasoning_options?: ReasoningOption[];
88
90
  variants: Record<string, Record<string, unknown>>;
91
+ /** Model-level provider options, such as the default reasoning effort. */
92
+ settings?: Record<string, unknown>;
93
+ enabled: boolean;
89
94
  temperature: boolean;
90
95
  tool_call: boolean;
91
96
  attachment: boolean;
@@ -233,6 +238,22 @@ export type TrackedModel = {
233
238
  modelID: string;
234
239
  };
235
240
 
241
+ export type CacheMissState = {
242
+ promptTokens: number;
243
+ at: number;
244
+ modelKey: string;
245
+ reportedCache: boolean;
246
+ };
247
+
248
+ export type ToolStats = {
249
+ meta: string[];
250
+ metaBytes: number;
251
+ failed: string[];
252
+ evicted: boolean;
253
+ started: Map<string, number>;
254
+ compacted: number;
255
+ };
256
+
236
257
  export type TokenUsageLike = {
237
258
  input?: number;
238
259
  output?: number;