@eduardo191labs/opencode-free-pi 0.3.2 → 0.3.4
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 +42 -3
- package/dist/catalog/catalog.js +12 -2
- package/dist/catalog/models.d.ts +7 -3
- package/dist/catalog/models.js +44 -47
- package/dist/catalog/v2.js +15 -4
- package/dist/constants.d.ts +32 -0
- package/dist/constants.js +37 -0
- package/dist/errors/limit.d.ts +7 -0
- package/dist/errors/limit.js +67 -0
- package/dist/plugin.js +3 -2
- package/dist/session/cache.d.ts +15 -0
- package/dist/session/cache.js +57 -0
- package/dist/session/events.js +10 -1
- package/dist/session/hooks.js +50 -4
- package/dist/session/notices.d.ts +7 -0
- package/dist/session/notices.js +34 -0
- package/dist/session/tools.d.ts +28 -0
- package/dist/session/tools.js +112 -0
- package/dist/state.d.ts +3 -1
- package/dist/state.js +2 -0
- package/dist/types.d.ts +17 -0
- package/package.json +1 -1
- package/src/catalog/catalog.ts +11 -1
- package/src/catalog/models.ts +59 -67
- package/src/catalog/v2.ts +16 -3
- package/src/constants.ts +43 -0
- package/src/errors/limit.ts +73 -0
- package/src/plugin.ts +3 -2
- package/src/session/cache.ts +82 -0
- package/src/session/events.ts +15 -1
- package/src/session/hooks.ts +92 -3
- package/src/session/notices.ts +40 -0
- package/src/session/tools.ts +150 -0
- package/src/state.ts +6 -0
- package/src/types.ts +19 -0
package/src/errors/limit.ts
CHANGED
|
@@ -22,6 +22,22 @@ const LONG_LIMIT_CODES = new Set([
|
|
|
22
22
|
"region_unavailable",
|
|
23
23
|
]);
|
|
24
24
|
|
|
25
|
+
const CONTEXT_OVERFLOW_CODES = new Set([
|
|
26
|
+
"context_too_long",
|
|
27
|
+
"context_too_long_for_fallback",
|
|
28
|
+
"context_ceiling",
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* OpenCode classifies HTTP 413 as `payload-too-large` before it looks at the
|
|
33
|
+
* message, so free-pi's `context_too_long` 413 never reaches the compaction
|
|
34
|
+
* recovery path. Rewriting it to a 400 whose message matches OpenCode's
|
|
35
|
+
* `prompt is too long` overflow pattern lets the runner compact and retry the
|
|
36
|
+
* turn instead of failing it with the raw server message.
|
|
37
|
+
*/
|
|
38
|
+
const CONTEXT_OVERFLOW_MESSAGE =
|
|
39
|
+
"prompt is too long for this model's context window; run /compact or start a new session";
|
|
40
|
+
|
|
25
41
|
type LimitInfo = {
|
|
26
42
|
code?: string;
|
|
27
43
|
retryAfterSeconds?: number;
|
|
@@ -85,6 +101,63 @@ function friendlyBody(body: string, info: LimitInfo): string {
|
|
|
85
101
|
}
|
|
86
102
|
}
|
|
87
103
|
|
|
104
|
+
function contextOverflowCode(body: string): string | undefined {
|
|
105
|
+
try {
|
|
106
|
+
const data = JSON.parse(body);
|
|
107
|
+
const raw = data?.code ?? data?.error?.code ?? data?.limit;
|
|
108
|
+
if (typeof raw === "string" && CONTEXT_OVERFLOW_CODES.has(raw)) return raw;
|
|
109
|
+
} catch {}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Returns a replacement response when `response` is a free-pi context overflow.
|
|
115
|
+
* The replacement is a 400 with a message OpenCode recognizes as context
|
|
116
|
+
* overflow, so the session runner compacts and retries instead of surfacing
|
|
117
|
+
* the fatal "conversation is too long" error.
|
|
118
|
+
*/
|
|
119
|
+
export async function rewriteContextOverflowResponse(
|
|
120
|
+
response: Response,
|
|
121
|
+
): Promise<Response | undefined> {
|
|
122
|
+
if (
|
|
123
|
+
response.status !== 413 &&
|
|
124
|
+
response.status !== 429 &&
|
|
125
|
+
response.status !== 400
|
|
126
|
+
)
|
|
127
|
+
return undefined;
|
|
128
|
+
const body = await response
|
|
129
|
+
.clone()
|
|
130
|
+
.text()
|
|
131
|
+
.catch(() => "");
|
|
132
|
+
if (!body) return undefined;
|
|
133
|
+
const code = contextOverflowCode(body);
|
|
134
|
+
if (!code) return undefined;
|
|
135
|
+
|
|
136
|
+
const headers = new Headers(response.headers);
|
|
137
|
+
headers.delete("retry-after");
|
|
138
|
+
headers.delete("retry-after-ms");
|
|
139
|
+
headers.set("x-free-pi-original-status", String(response.status));
|
|
140
|
+
headers.set("x-free-pi-original-code", code);
|
|
141
|
+
|
|
142
|
+
let data: any;
|
|
143
|
+
try {
|
|
144
|
+
data = JSON.parse(body);
|
|
145
|
+
} catch {
|
|
146
|
+
data = {};
|
|
147
|
+
}
|
|
148
|
+
if (data && typeof data === "object") {
|
|
149
|
+
data.message = CONTEXT_OVERFLOW_MESSAGE;
|
|
150
|
+
if (data.error && typeof data.error === "object") {
|
|
151
|
+
data.error.message = CONTEXT_OVERFLOW_MESSAGE;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return new Response(JSON.stringify(data), {
|
|
155
|
+
status: 400,
|
|
156
|
+
statusText: "Bad Request",
|
|
157
|
+
headers,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
88
161
|
/**
|
|
89
162
|
* Returns a replacement response when `response` is a 429 that represents a
|
|
90
163
|
* long-lived limit. The replacement is a 400 with the same body but a friendly
|
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
|
|
68
|
-
const
|
|
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
|
+
}
|
package/src/session/events.ts
CHANGED
|
@@ -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,
|
|
@@ -63,7 +65,15 @@ async function handleEvent(
|
|
|
63
65
|
endExecution(deps, event.data?.sessionID);
|
|
64
66
|
return;
|
|
65
67
|
}
|
|
66
|
-
case "session.usage.updated":
|
|
68
|
+
case "session.usage.updated": {
|
|
69
|
+
recordUsage(
|
|
70
|
+
deps,
|
|
71
|
+
event.data?.sessionID,
|
|
72
|
+
event.data?.cost,
|
|
73
|
+
event.data?.tokens,
|
|
74
|
+
);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
67
77
|
case "session.step.ended": {
|
|
68
78
|
recordUsage(
|
|
69
79
|
deps,
|
|
@@ -71,6 +81,8 @@ async function handleEvent(
|
|
|
71
81
|
event.data?.cost,
|
|
72
82
|
event.data?.tokens,
|
|
73
83
|
);
|
|
84
|
+
// Step tokens are per request; usage.updated is cumulative.
|
|
85
|
+
observeStepUsage(deps, event.data?.sessionID, event.data?.tokens);
|
|
74
86
|
return;
|
|
75
87
|
}
|
|
76
88
|
case "session.deleted": {
|
|
@@ -78,6 +90,8 @@ async function handleEvent(
|
|
|
78
90
|
if (typeof sessionID !== "string") return;
|
|
79
91
|
await finalizeFreePiSession(deps, sessionID);
|
|
80
92
|
forgetFreePiSession(deps, sessionID);
|
|
93
|
+
forgetCacheMiss(deps, sessionID);
|
|
94
|
+
forgetToolStats(deps, sessionID);
|
|
81
95
|
return;
|
|
82
96
|
}
|
|
83
97
|
case "location.shutdown": {
|
package/src/session/hooks.ts
CHANGED
|
@@ -11,11 +11,24 @@ 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,
|
|
14
17
|
} from "../constants.js";
|
|
15
18
|
import type { Deps } from "../deps.js";
|
|
16
|
-
import {
|
|
19
|
+
import {
|
|
20
|
+
rewriteContextOverflowResponse,
|
|
21
|
+
rewriteLimitResponse,
|
|
22
|
+
} from "../errors/limit.js";
|
|
17
23
|
import { trimMap } from "../utils/async.js";
|
|
24
|
+
import { watchFreePiNotice } from "./notices.js";
|
|
18
25
|
import { rememberFreePiSession } from "./track.js";
|
|
26
|
+
import {
|
|
27
|
+
recordCompaction,
|
|
28
|
+
recordToolEnd,
|
|
29
|
+
recordToolStart,
|
|
30
|
+
toolHeaders,
|
|
31
|
+
} from "./tools.js";
|
|
19
32
|
import { rememberTrackedModel } from "./usage.js";
|
|
20
33
|
|
|
21
34
|
type Registration = { dispose: () => Promise<void> };
|
|
@@ -25,7 +38,8 @@ type SessionHookName =
|
|
|
25
38
|
| "generate"
|
|
26
39
|
| "title"
|
|
27
40
|
| "model.request"
|
|
28
|
-
| "http.response"
|
|
41
|
+
| "http.response"
|
|
42
|
+
| "retry";
|
|
29
43
|
type RequestKind = "primary" | "compaction" | "generate" | "title";
|
|
30
44
|
|
|
31
45
|
const PENDING_LIMIT = 400;
|
|
@@ -74,6 +88,16 @@ async function applyGeneration(
|
|
|
74
88
|
if (current === undefined || current > cap) event.options.maxTokens = cap;
|
|
75
89
|
}
|
|
76
90
|
|
|
91
|
+
if (kind === "compaction") {
|
|
92
|
+
// OpenCode sends the messages it is folding into the summary, which is the
|
|
93
|
+
// same set pi reports through `session_before_compact`.
|
|
94
|
+
recordCompaction(
|
|
95
|
+
deps,
|
|
96
|
+
event.sessionID,
|
|
97
|
+
Array.isArray(event.messages) ? event.messages.length : 0,
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
77
101
|
if (deps.state.costExperimentArm === "efficiency") {
|
|
78
102
|
const system = Array.isArray(event.system) ? event.system : [];
|
|
79
103
|
if (
|
|
@@ -119,6 +143,11 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
119
143
|
// an impression the user never sees.
|
|
120
144
|
if (event.kind === "title") return;
|
|
121
145
|
|
|
146
|
+
Object.assign(
|
|
147
|
+
event.headers,
|
|
148
|
+
toolHeaders(deps, event.sessionID, event.kind !== "compaction"),
|
|
149
|
+
);
|
|
150
|
+
|
|
122
151
|
const pending = deps.state.pendingAdTurns.get(
|
|
123
152
|
pendingKeyOf(event.sessionID, agent, event.kind),
|
|
124
153
|
);
|
|
@@ -142,6 +171,47 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
142
171
|
}
|
|
143
172
|
}
|
|
144
173
|
|
|
174
|
+
/**
|
|
175
|
+
* pi retries at most three times with `min(2s * 2^(n-1), 60s)`. OpenCode's
|
|
176
|
+
* `attempt` counts the initial call as 1, so pi's attempt is `attempt - 1`.
|
|
177
|
+
* Non-retryable decisions are left alone.
|
|
178
|
+
*/
|
|
179
|
+
function applyRetryPolicy(event: any): void {
|
|
180
|
+
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
181
|
+
event.decision = { retry: false };
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (!event.decision?.retry) return;
|
|
185
|
+
const attempt = Math.max(1, event.attempt - 1);
|
|
186
|
+
event.decision.delay = Math.min(
|
|
187
|
+
RETRY_BASE_DELAY_MS * 2 ** (attempt - 1),
|
|
188
|
+
RETRY_MAX_DELAY_MS,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function registerToolHooks(
|
|
193
|
+
ctx: Plugin.Context,
|
|
194
|
+
deps: Deps,
|
|
195
|
+
registrations: Registration[],
|
|
196
|
+
): Promise<void> {
|
|
197
|
+
if (!ctx.tool?.hook) return;
|
|
198
|
+
registrations.push(
|
|
199
|
+
await ctx.tool.hook("execute.before", (event) => {
|
|
200
|
+
recordToolStart(deps, event.sessionID, event.id);
|
|
201
|
+
}),
|
|
202
|
+
);
|
|
203
|
+
registrations.push(
|
|
204
|
+
await ctx.tool.hook("execute.after", (event) => {
|
|
205
|
+
recordToolEnd(deps, event.sessionID, {
|
|
206
|
+
id: event.id,
|
|
207
|
+
tool: event.tool,
|
|
208
|
+
status: event.status,
|
|
209
|
+
...(event.status === "completed" ? { result: event.result } : {}),
|
|
210
|
+
});
|
|
211
|
+
}),
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
145
215
|
async function hookForProviders(
|
|
146
216
|
ctx: Plugin.Context,
|
|
147
217
|
name: SessionHookName,
|
|
@@ -184,13 +254,32 @@ export async function registerSessionHooks(
|
|
|
184
254
|
ctx,
|
|
185
255
|
"http.response",
|
|
186
256
|
async (event: any) => {
|
|
257
|
+
// Context overflow has to be handled first: a 429 context ceiling must
|
|
258
|
+
// become a 400 overflow, not a friendly long-lived limit.
|
|
259
|
+
const overflow = await rewriteContextOverflowResponse(
|
|
260
|
+
event.response,
|
|
261
|
+
).catch(() => undefined);
|
|
262
|
+
if (overflow) {
|
|
263
|
+
event.response = watchFreePiNotice(deps, overflow);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
187
266
|
const rewritten = await rewriteLimitResponse(event.response).catch(
|
|
188
267
|
() => undefined,
|
|
189
268
|
);
|
|
190
|
-
|
|
269
|
+
event.response = watchFreePiNotice(
|
|
270
|
+
deps,
|
|
271
|
+
rewritten ?? event.response,
|
|
272
|
+
);
|
|
191
273
|
},
|
|
192
274
|
registrations,
|
|
193
275
|
);
|
|
276
|
+
await hookForProviders(
|
|
277
|
+
ctx,
|
|
278
|
+
"retry",
|
|
279
|
+
(event: any) => applyRetryPolicy(event),
|
|
280
|
+
registrations,
|
|
281
|
+
);
|
|
282
|
+
await registerToolHooks(ctx, deps, registrations);
|
|
194
283
|
|
|
195
284
|
return registrations;
|
|
196
285
|
}
|
|
@@ -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,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
|
|
|
@@ -54,6 +56,8 @@ export type RuntimeState = {
|
|
|
54
56
|
pendingAdTurns: Map<string, AdTurn>;
|
|
55
57
|
adImpressions: Map<string, Promise<void>>;
|
|
56
58
|
trackedModels: Map<string, TrackedModel>;
|
|
59
|
+
cacheMisses: Map<string, CacheMissState>;
|
|
60
|
+
toolStats: Map<string, ToolStats>;
|
|
57
61
|
};
|
|
58
62
|
|
|
59
63
|
export function createRuntimeState(): RuntimeState {
|
|
@@ -78,5 +82,7 @@ export function createRuntimeState(): RuntimeState {
|
|
|
78
82
|
pendingAdTurns: new Map(),
|
|
79
83
|
adImpressions: new Map(),
|
|
80
84
|
trackedModels: new Map(),
|
|
85
|
+
cacheMisses: new Map(),
|
|
86
|
+
toolStats: new Map(),
|
|
81
87
|
};
|
|
82
88
|
}
|
package/src/types.ts
CHANGED
|
@@ -86,6 +86,9 @@ export type ModelDefinition = {
|
|
|
86
86
|
reasoning: boolean;
|
|
87
87
|
reasoning_options?: ReasoningOption[];
|
|
88
88
|
variants: Record<string, Record<string, unknown>>;
|
|
89
|
+
/** Model-level provider options, such as the default reasoning effort. */
|
|
90
|
+
settings?: Record<string, unknown>;
|
|
91
|
+
enabled: boolean;
|
|
89
92
|
temperature: boolean;
|
|
90
93
|
tool_call: boolean;
|
|
91
94
|
attachment: boolean;
|
|
@@ -233,6 +236,22 @@ export type TrackedModel = {
|
|
|
233
236
|
modelID: string;
|
|
234
237
|
};
|
|
235
238
|
|
|
239
|
+
export type CacheMissState = {
|
|
240
|
+
promptTokens: number;
|
|
241
|
+
at: number;
|
|
242
|
+
modelKey: string;
|
|
243
|
+
reportedCache: boolean;
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
export type ToolStats = {
|
|
247
|
+
meta: string[];
|
|
248
|
+
metaBytes: number;
|
|
249
|
+
failed: string[];
|
|
250
|
+
evicted: boolean;
|
|
251
|
+
started: Map<string, number>;
|
|
252
|
+
compacted: number;
|
|
253
|
+
};
|
|
254
|
+
|
|
236
255
|
export type TokenUsageLike = {
|
|
237
256
|
input?: number;
|
|
238
257
|
output?: number;
|