@eduardo191labs/opencode-free-pi 0.5.6 → 0.6.0
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 +33 -39
- package/dist/catalog/catalog.js +1 -21
- package/dist/catalog/live.d.ts +55 -0
- package/dist/catalog/live.js +229 -0
- package/dist/catalog/models.d.ts +7 -2
- package/dist/catalog/models.js +10 -10
- package/dist/catalog/registry.js +5 -15
- package/dist/constants.d.ts +7 -15
- package/dist/constants.js +7 -15
- package/dist/logging.js +2 -2
- package/dist/plugin.js +14 -2
- package/dist/session/events.js +2 -3
- package/dist/session/hooks.js +1 -11
- package/dist/state.d.ts +1 -15
- package/dist/state.js +0 -3
- package/dist/tools/vision-queue.d.ts +1 -1
- package/dist/tools/vision-queue.js +5 -5
- package/dist/tools/vision.js +24 -35
- package/dist/tools/web.js +39 -44
- package/dist/types.d.ts +5 -9
- package/dist/utils/data-dir.d.ts +3 -0
- package/dist/utils/data-dir.js +12 -0
- package/package.json +2 -2
- package/src/catalog/catalog.ts +0 -25
- package/src/catalog/live.ts +277 -0
- package/src/catalog/models.ts +19 -12
- package/src/catalog/registry.ts +6 -21
- package/src/constants.ts +7 -18
- package/src/logging.ts +2 -2
- package/src/plugin.ts +20 -2
- package/src/session/events.ts +6 -3
- package/src/session/hooks.ts +0 -17
- package/src/state.ts +0 -18
- package/src/tools/vision-queue.ts +5 -5
- package/src/tools/vision.ts +26 -38
- package/src/tools/web.ts +49 -59
- package/src/types.ts +5 -8
- package/src/utils/data-dir.ts +14 -0
- package/dist/session/cache.d.ts +0 -15
- package/dist/session/cache.js +0 -57
- package/dist/tools/spend-cache.d.ts +0 -15
- package/dist/tools/spend-cache.js +0 -64
- package/dist/utils/cache.d.ts +0 -7
- package/dist/utils/cache.js +0 -45
- package/src/session/cache.ts +0 -82
- package/src/tools/spend-cache.ts +0 -79
- package/src/utils/cache.ts +0 -49
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live limits and capabilities.
|
|
3
|
+
*
|
|
4
|
+
* free-pi's HTTP API never publishes per-model limits: `/client-version` only
|
|
5
|
+
* carries id/name/free/section/note/stats_id, `/me` carries the quota, and chat
|
|
6
|
+
* responses carry usage but no window. The gateway does enforce a real ceiling,
|
|
7
|
+
* so the plugin verifies the advertised window against the gateway itself and
|
|
8
|
+
* remembers what it learned. The measured value replaces the compiled default
|
|
9
|
+
* on the next start; a probe failure leaves the previous value untouched.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
13
|
+
import { dirname } from "node:path";
|
|
14
|
+
import { resolveToken } from "../auth/token.js";
|
|
15
|
+
import {
|
|
16
|
+
CONTEXT_WINDOW,
|
|
17
|
+
VERIFY_LIMITS_TTL_MS,
|
|
18
|
+
} from "../constants.js";
|
|
19
|
+
import type { Deps } from "../deps.js";
|
|
20
|
+
import type { TokenUsageLike } from "../types.js";
|
|
21
|
+
import { dataPath } from "../utils/data-dir.js";
|
|
22
|
+
import { completionsBaseUrl } from "../utils/urls.js";
|
|
23
|
+
|
|
24
|
+
const FILE = "live-limits.json";
|
|
25
|
+
const WRITE_DEBOUNCE_MS = 2_000;
|
|
26
|
+
/** Verification stops shrinking here instead of advertising a useless window. */
|
|
27
|
+
const MIN_WINDOW = 32_768;
|
|
28
|
+
|
|
29
|
+
export type ModelObservation = {
|
|
30
|
+
/** Largest prompt the gateway accepted for this model. */
|
|
31
|
+
maxPromptTokens?: number;
|
|
32
|
+
/** Whether a real response carried reasoning tokens. */
|
|
33
|
+
reasoning?: boolean;
|
|
34
|
+
updatedAt: number;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export type LiveLimits = {
|
|
38
|
+
version: 1;
|
|
39
|
+
/** Window verified against the gateway, used for the next catalog build. */
|
|
40
|
+
window?: { tokens: number; verifiedAt: number; model?: string };
|
|
41
|
+
/** What real traffic showed for each model. */
|
|
42
|
+
models: Record<string, ModelObservation>;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
let cached: LiveLimits | undefined;
|
|
46
|
+
let loaded = false;
|
|
47
|
+
let writeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
48
|
+
|
|
49
|
+
function emptyLimits(): LiveLimits {
|
|
50
|
+
return { version: 1, models: {} };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function sanitize(value: unknown): LiveLimits {
|
|
54
|
+
if (!value || typeof value !== "object") return emptyLimits();
|
|
55
|
+
const limits = value as Partial<LiveLimits>;
|
|
56
|
+
const models: Record<string, ModelObservation> = {};
|
|
57
|
+
for (const [id, entry] of Object.entries(limits.models ?? {})) {
|
|
58
|
+
if (!entry || typeof entry !== "object") continue;
|
|
59
|
+
const observation: ModelObservation = {
|
|
60
|
+
updatedAt:
|
|
61
|
+
typeof entry.updatedAt === "number" ? entry.updatedAt : Date.now(),
|
|
62
|
+
};
|
|
63
|
+
if (Number.isFinite(entry.maxPromptTokens) && entry.maxPromptTokens! > 0) {
|
|
64
|
+
observation.maxPromptTokens = Math.floor(entry.maxPromptTokens!);
|
|
65
|
+
}
|
|
66
|
+
if (typeof entry.reasoning === "boolean") {
|
|
67
|
+
observation.reasoning = entry.reasoning;
|
|
68
|
+
}
|
|
69
|
+
models[id] = observation;
|
|
70
|
+
}
|
|
71
|
+
const window = limits.window;
|
|
72
|
+
return {
|
|
73
|
+
version: 1,
|
|
74
|
+
models,
|
|
75
|
+
...(window &&
|
|
76
|
+
Number.isFinite(window.tokens) &&
|
|
77
|
+
window.tokens > 0 &&
|
|
78
|
+
Number.isFinite(window.verifiedAt)
|
|
79
|
+
? {
|
|
80
|
+
window: {
|
|
81
|
+
tokens: Math.floor(window.tokens),
|
|
82
|
+
verifiedAt: window.verifiedAt,
|
|
83
|
+
...(typeof window.model === "string" ? { model: window.model } : {}),
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
: {}),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Reads the persisted measurements once per process. Never throws. */
|
|
91
|
+
export async function loadLiveLimits(): Promise<LiveLimits> {
|
|
92
|
+
if (loaded && cached) return cached;
|
|
93
|
+
try {
|
|
94
|
+
cached = sanitize(JSON.parse(await readFile(dataPath(FILE), "utf8")));
|
|
95
|
+
} catch {
|
|
96
|
+
cached = emptyLimits();
|
|
97
|
+
}
|
|
98
|
+
loaded = true;
|
|
99
|
+
return cached;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The measurements loaded for this process. */
|
|
103
|
+
export function currentLiveLimits(): LiveLimits | undefined {
|
|
104
|
+
return cached;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function persist(): Promise<void> {
|
|
108
|
+
if (!cached) return;
|
|
109
|
+
try {
|
|
110
|
+
const file = dataPath(FILE);
|
|
111
|
+
await mkdir(dirname(file), { recursive: true });
|
|
112
|
+
await writeFile(file, JSON.stringify(cached), "utf8");
|
|
113
|
+
} catch {
|
|
114
|
+
// Measurements are an optimization; failing to persist changes nothing.
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function scheduleWrite(): void {
|
|
119
|
+
if (writeTimer) return;
|
|
120
|
+
writeTimer = setTimeout(() => {
|
|
121
|
+
writeTimer = undefined;
|
|
122
|
+
void persist();
|
|
123
|
+
}, WRITE_DEBOUNCE_MS);
|
|
124
|
+
writeTimer.unref?.();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function observation(modelID: string): ModelObservation {
|
|
128
|
+
const limits = (cached ??= emptyLimits());
|
|
129
|
+
limits.models[modelID] ??= { updatedAt: Date.now() };
|
|
130
|
+
return limits.models[modelID]!;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Folds a real step's usage into the model's record: the prompt size proves the
|
|
135
|
+
* gateway accepted at least that much context, and reasoning tokens prove the
|
|
136
|
+
* model really reasoned for this account.
|
|
137
|
+
*/
|
|
138
|
+
export function noteStepTokens(
|
|
139
|
+
_deps: Deps,
|
|
140
|
+
modelID: string,
|
|
141
|
+
tokens: TokenUsageLike | undefined,
|
|
142
|
+
): void {
|
|
143
|
+
if (!modelID || !tokens) return;
|
|
144
|
+
const prompt =
|
|
145
|
+
(tokens.input ?? 0) + (tokens.cache?.read ?? 0) + (tokens.cache?.write ?? 0);
|
|
146
|
+
const entry = observation(modelID);
|
|
147
|
+
let changed = false;
|
|
148
|
+
if (prompt > 0 && prompt >= (entry.maxPromptTokens ?? 0)) {
|
|
149
|
+
entry.maxPromptTokens = Math.floor(prompt);
|
|
150
|
+
changed = true;
|
|
151
|
+
}
|
|
152
|
+
if ((tokens.reasoning ?? 0) > 0 && entry.reasoning !== true) {
|
|
153
|
+
entry.reasoning = true;
|
|
154
|
+
changed = true;
|
|
155
|
+
}
|
|
156
|
+
if (!changed) return;
|
|
157
|
+
entry.updatedAt = Date.now();
|
|
158
|
+
scheduleWrite();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Whether the persisted window is old enough to verify again. */
|
|
162
|
+
export function shouldVerifyWindow(limits: LiveLimits | undefined): boolean {
|
|
163
|
+
const verifiedAt = limits?.window?.verifiedAt;
|
|
164
|
+
if (!verifiedAt) return true;
|
|
165
|
+
return Date.now() - verifiedAt > VERIFY_LIMITS_TTL_MS;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function filler(chars: number): string {
|
|
169
|
+
const unit =
|
|
170
|
+
"the quick brown fox jumps over the lazy dog while maintainers review the patch and debate naming ";
|
|
171
|
+
return unit.repeat(Math.ceil(chars / unit.length)).slice(0, chars);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
type ProbeResult =
|
|
175
|
+
| { status: "ok"; promptTokens?: number }
|
|
176
|
+
| { status: "too_long" }
|
|
177
|
+
| { status: "failed" };
|
|
178
|
+
|
|
179
|
+
async function sendProbe(
|
|
180
|
+
deps: Deps,
|
|
181
|
+
modelID: string,
|
|
182
|
+
chars: number,
|
|
183
|
+
): Promise<ProbeResult> {
|
|
184
|
+
const token = await resolveToken(deps).catch(() => undefined);
|
|
185
|
+
if (!token) return { status: "failed" };
|
|
186
|
+
const content = `${filler(chars)}\n\nIgnore the filler and reply with OK.`;
|
|
187
|
+
let response: Response;
|
|
188
|
+
try {
|
|
189
|
+
response = await fetch(`${completionsBaseUrl()}/chat/completions`, {
|
|
190
|
+
method: "POST",
|
|
191
|
+
headers: {
|
|
192
|
+
accept: "application/json",
|
|
193
|
+
"content-type": "application/json",
|
|
194
|
+
authorization: `Bearer ${token}`,
|
|
195
|
+
"x-client-version": deps.state.latestClientVersion,
|
|
196
|
+
"x-session-id": `free-pi-window-${Date.now().toString(36)}`,
|
|
197
|
+
"x-ad-context": "none",
|
|
198
|
+
},
|
|
199
|
+
body: JSON.stringify({
|
|
200
|
+
model: modelID,
|
|
201
|
+
messages: [{ role: "user", content }],
|
|
202
|
+
stream: false,
|
|
203
|
+
max_tokens: 256,
|
|
204
|
+
}),
|
|
205
|
+
signal: AbortSignal.timeout(180_000),
|
|
206
|
+
});
|
|
207
|
+
} catch {
|
|
208
|
+
return { status: "failed" };
|
|
209
|
+
}
|
|
210
|
+
if (response.status === 413 || response.status === 400) {
|
|
211
|
+
const body = await response.text().catch(() => "");
|
|
212
|
+
if (/context_too_long|too long|context_ceiling/i.test(body)) {
|
|
213
|
+
return { status: "too_long" };
|
|
214
|
+
}
|
|
215
|
+
return { status: "failed" };
|
|
216
|
+
}
|
|
217
|
+
if (!response.ok) return { status: "failed" };
|
|
218
|
+
const payload = (await response.json().catch(() => undefined)) as
|
|
219
|
+
| { usage?: { prompt_tokens?: number } }
|
|
220
|
+
| undefined;
|
|
221
|
+
const promptTokens = payload?.usage?.prompt_tokens;
|
|
222
|
+
return {
|
|
223
|
+
status: "ok",
|
|
224
|
+
...(typeof promptTokens === "number" ? { promptTokens } : {}),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export type VerifyLimitsOptions = {
|
|
229
|
+
/** A free model to probe with; paid models would spend credits. */
|
|
230
|
+
model?: string;
|
|
231
|
+
/** Window to check. Defaults to the compiled one. */
|
|
232
|
+
window?: number;
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Checks the compiled window against the gateway by sending the largest prompt
|
|
237
|
+
* that window allows. On rejection it steps down until the gateway accepts, so
|
|
238
|
+
* the next catalog build advertises what the server really takes. Returns the
|
|
239
|
+
* verified window, or `undefined` when nothing could be learned.
|
|
240
|
+
*/
|
|
241
|
+
export async function verifyGatewayWindow(
|
|
242
|
+
deps: Deps,
|
|
243
|
+
options: VerifyLimitsOptions = {},
|
|
244
|
+
): Promise<number | undefined> {
|
|
245
|
+
const modelID = options.model;
|
|
246
|
+
if (!modelID) return undefined;
|
|
247
|
+
const window = options.window ?? CONTEXT_WINDOW;
|
|
248
|
+
// OpenCode budgets a token as ~4 characters. The gateway rejects by its own
|
|
249
|
+
// prompt size, so aim just under what the window allows in characters; the
|
|
250
|
+
// reported prompt_tokens are logged for comparison but do not decide the
|
|
251
|
+
// result.
|
|
252
|
+
const targetChars = Math.max(MIN_WINDOW * 4, Math.floor(window * 4 * 0.99));
|
|
253
|
+
for (const factor of [1, 0.85, 0.7, 0.55]) {
|
|
254
|
+
const chars = Math.floor(targetChars * factor);
|
|
255
|
+
if (chars < MIN_WINDOW) break;
|
|
256
|
+
const result = await sendProbe(deps, modelID, chars);
|
|
257
|
+
if (result.status === "failed") return undefined;
|
|
258
|
+
if (result.status === "too_long") continue;
|
|
259
|
+
// Passing the full target confirms the compiled window. After a rejection,
|
|
260
|
+
// only the reduced target is proven, so advertise that instead.
|
|
261
|
+
const verified =
|
|
262
|
+
factor === 1 ? window : Math.max(MIN_WINDOW, Math.floor(window * factor));
|
|
263
|
+
const limits = (cached ??= emptyLimits());
|
|
264
|
+
limits.window = { tokens: verified, verifiedAt: Date.now(), model: modelID };
|
|
265
|
+
loaded = true;
|
|
266
|
+
await persist();
|
|
267
|
+
deps.log.info("free-pi verified the gateway context window", {
|
|
268
|
+
model: modelID,
|
|
269
|
+
window: verified,
|
|
270
|
+
compiled: window,
|
|
271
|
+
probedChars: chars,
|
|
272
|
+
probedTokens: result.promptTokens,
|
|
273
|
+
});
|
|
274
|
+
return verified;
|
|
275
|
+
}
|
|
276
|
+
return undefined;
|
|
277
|
+
}
|
package/src/catalog/models.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
|
-
COMPACT100_CONTEXT_WINDOW,
|
|
5
4
|
CONTEXT_WINDOW,
|
|
6
5
|
DEFAULT_REASONING_EFFORT,
|
|
7
6
|
DEFAULT_THINKING_LEVELS,
|
|
@@ -18,6 +17,7 @@ import type {
|
|
|
18
17
|
ReasoningOption,
|
|
19
18
|
RegistryCandidate,
|
|
20
19
|
} from "../types.js";
|
|
20
|
+
import type { LiveLimits } from "./live.js";
|
|
21
21
|
import { positiveNumber } from "../utils/numbers.js";
|
|
22
22
|
import { cleanText } from "../utils/text.js";
|
|
23
23
|
|
|
@@ -226,14 +226,18 @@ export function preferredReasoningEffort(
|
|
|
226
226
|
}
|
|
227
227
|
|
|
228
228
|
export type BuildModelsOptions = {
|
|
229
|
-
/** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
|
|
230
|
-
compact100?: boolean;
|
|
231
229
|
/**
|
|
232
230
|
* Effort sent when the user has not picked a variant. `false` keeps the
|
|
233
231
|
* gateway default. Defaults to `medium` because an unset effort makes the
|
|
234
232
|
* free models answer before they reason.
|
|
235
233
|
*/
|
|
236
234
|
reasoningEffort?: string | false;
|
|
235
|
+
/**
|
|
236
|
+
* Limits and capabilities observed from the live gateway. The verified
|
|
237
|
+
* window replaces the compiled one, and per-model observations prove what the
|
|
238
|
+
* server really accepted for this account.
|
|
239
|
+
*/
|
|
240
|
+
live?: LiveLimits;
|
|
237
241
|
};
|
|
238
242
|
|
|
239
243
|
/**
|
|
@@ -306,15 +310,18 @@ export function buildModels(
|
|
|
306
310
|
const reasoning = model.reasoning ?? true;
|
|
307
311
|
const reasoningOptions =
|
|
308
312
|
model.reasoning_options ?? capability?.reasoning_options;
|
|
309
|
-
// free-pi enforces a
|
|
310
|
-
//
|
|
311
|
-
//
|
|
312
|
-
//
|
|
313
|
-
//
|
|
314
|
-
//
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
313
|
+
// free-pi enforces a context window on every model regardless of what
|
|
314
|
+
// models.dev reports for the upstream provider. The provider CLI starts at
|
|
315
|
+
// 200k, but the gateway does not publish its ceiling: `verifyGatewayWindow`
|
|
316
|
+
// measures it and the result is used here from the next start. Real steps
|
|
317
|
+
// also prove the gateway accepted at least their prompt size. A published
|
|
318
|
+
// catalog field still wins, but only inside that measured ceiling, so an
|
|
319
|
+
// advertised 1M window can never push a session past what the gateway takes.
|
|
320
|
+
const observed = options.live?.models[model.id]?.maxPromptTokens ?? 0;
|
|
321
|
+
const contextCeiling = Math.min(
|
|
322
|
+
1_000_000,
|
|
323
|
+
Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed),
|
|
324
|
+
);
|
|
318
325
|
const limitContext = Math.min(
|
|
319
326
|
positiveNumber(
|
|
320
327
|
model.context_window,
|
package/src/catalog/registry.ts
CHANGED
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
4
|
REGISTRY_ATTEMPTS,
|
|
5
|
-
REGISTRY_DISK_TTL_MS,
|
|
6
5
|
REGISTRY_RETRY_MS,
|
|
7
6
|
REGISTRY_TIMEOUT_MS,
|
|
8
7
|
REGISTRY_TTL_MS,
|
|
@@ -10,11 +9,8 @@ import {
|
|
|
10
9
|
import type { Deps } from "../deps.js";
|
|
11
10
|
import type { ModelRegistry } from "../types.js";
|
|
12
11
|
import { sleep } from "../utils/async.js";
|
|
13
|
-
import { readCache, writeCache } from "../utils/cache.js";
|
|
14
12
|
import { modelsRegistryUrl } from "../utils/urls.js";
|
|
15
13
|
|
|
16
|
-
const CACHE_FILE = "models-dev.json";
|
|
17
|
-
|
|
18
14
|
function isRegistry(value: unknown): value is ModelRegistry {
|
|
19
15
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
20
16
|
}
|
|
@@ -66,7 +62,6 @@ export function refreshModelsRegistry(
|
|
|
66
62
|
}
|
|
67
63
|
state.cachedRegistry = registry;
|
|
68
64
|
state.cachedRegistryAt = Date.now();
|
|
69
|
-
void writeCache(CACHE_FILE, registry);
|
|
70
65
|
return registry;
|
|
71
66
|
} catch (error) {
|
|
72
67
|
const cached = state.cachedRegistry;
|
|
@@ -98,24 +93,14 @@ export async function fetchModelsRegistry(
|
|
|
98
93
|
}
|
|
99
94
|
|
|
100
95
|
if (!state.cachedRegistry) {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
)
|
|
105
|
-
|
|
106
|
-
state.cachedRegistry = disk;
|
|
107
|
-
state.cachedRegistryAt = Date.now();
|
|
108
|
-
// Serve the cached copy immediately and refresh it in the background.
|
|
109
|
-
void refreshModelsRegistry(deps);
|
|
110
|
-
return disk;
|
|
96
|
+
if (
|
|
97
|
+
state.registryAttemptAt &&
|
|
98
|
+
Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS
|
|
99
|
+
) {
|
|
100
|
+
return state.cachedRegistry;
|
|
111
101
|
}
|
|
112
|
-
}
|
|
113
102
|
|
|
114
|
-
|
|
115
|
-
state.registryAttemptAt &&
|
|
116
|
-
Date.now() - state.registryAttemptAt < REGISTRY_RETRY_MS
|
|
117
|
-
) {
|
|
118
|
-
return state.cachedRegistry;
|
|
103
|
+
return refreshModelsRegistry(deps);
|
|
119
104
|
}
|
|
120
105
|
|
|
121
106
|
return refreshModelsRegistry(deps);
|
package/src/constants.ts
CHANGED
|
@@ -11,8 +11,15 @@ export const DEFAULT_BASE_URL = "https://api.freepi.ai";
|
|
|
11
11
|
export const DEFAULT_CLIENT_VERSION = "0.6.25";
|
|
12
12
|
export const CONSENT_VERSION = "4";
|
|
13
13
|
|
|
14
|
+
/**
|
|
15
|
+
* The provider CLI's window. The gateway enforces its own ceiling but does not
|
|
16
|
+
* publish it, so this is the starting point; `verifyGatewayWindow` replaces it
|
|
17
|
+
* with what the server actually accepts.
|
|
18
|
+
*/
|
|
14
19
|
export const CONTEXT_WINDOW = 200_000;
|
|
15
20
|
export const MAX_OUTPUT_TOKENS = 32_768;
|
|
21
|
+
/** How long a measured gateway window is trusted before checking again. */
|
|
22
|
+
export const VERIFY_LIMITS_TTL_MS = 7 * 24 * 60 * 60 * 1_000;
|
|
16
23
|
|
|
17
24
|
export const AD_CONTEXT_HEADER = "x-ad-context";
|
|
18
25
|
/**
|
|
@@ -21,9 +28,6 @@ export const AD_CONTEXT_HEADER = "x-ad-context";
|
|
|
21
28
|
*/
|
|
22
29
|
export const AD_CONTEXT_OPT_OUT = "none";
|
|
23
30
|
export const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
24
|
-
export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
25
|
-
export const EFFICIENCY_RULE =
|
|
26
|
-
"- When several independent reads or searches are needed, issue them in the same turn.";
|
|
27
31
|
|
|
28
32
|
/**
|
|
29
33
|
* The provider CLI starts with thinking off, but leaving `reasoning_effort`
|
|
@@ -94,11 +98,6 @@ export const CONCURRENT_RETRY_MAX = 6;
|
|
|
94
98
|
export const CONCURRENT_RETRY_BASE_MS = 1_000;
|
|
95
99
|
export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
|
|
96
100
|
|
|
97
|
-
/** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
|
|
98
|
-
export const CACHE_TTL_MS = 5 * 60_000;
|
|
99
|
-
export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
|
|
100
|
-
export const CACHE_MISS_NOTICE_TOKENS = 20_000;
|
|
101
|
-
|
|
102
101
|
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
103
102
|
export const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
104
103
|
export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
@@ -106,14 +105,6 @@ export const COMPACTED_HEADER = "x-freepi-compacted";
|
|
|
106
105
|
export const TOOL_META_BUDGET = 1_500;
|
|
107
106
|
export const TOOL_ID_LIMIT = 50;
|
|
108
107
|
|
|
109
|
-
/**
|
|
110
|
-
* The `compact100` cost experiment reserves 100k tokens, so pi compacts when
|
|
111
|
-
* the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
|
|
112
|
-
* 117_647 is the smallest window that keeps that trigger at 100k.
|
|
113
|
-
*/
|
|
114
|
-
export const COMPACT100_TRIGGER_TOKENS = 100_000;
|
|
115
|
-
export const COMPACT100_CONTEXT_WINDOW = 117_647;
|
|
116
|
-
|
|
117
108
|
export const SESSION_TRACK_LIMIT = 200;
|
|
118
109
|
export const AUTH_SKEW_MS = 60_000;
|
|
119
110
|
export const AUTH_TIMEOUT_MS = 15 * 60_000;
|
|
@@ -130,10 +121,8 @@ export const AD_IMPRESSION_LIMIT = 200;
|
|
|
130
121
|
export const CREDITS_PER_USD = 40_000 / 3;
|
|
131
122
|
|
|
132
123
|
export const CATALOG_TTL_MS = 10 * 60_000;
|
|
133
|
-
export const CATALOG_DISK_TTL_MS = 24 * 60 * 60_000;
|
|
134
124
|
export const CATALOG_TIMEOUT_MS = 8_000;
|
|
135
125
|
export const REGISTRY_TTL_MS = 5 * 60_000;
|
|
136
|
-
export const REGISTRY_DISK_TTL_MS = 7 * 24 * 60 * 60_000;
|
|
137
126
|
export const REGISTRY_RETRY_MS = 60_000;
|
|
138
127
|
export const REGISTRY_TIMEOUT_MS = 3_500;
|
|
139
128
|
export const REGISTRY_ATTEMPTS = 2;
|
package/src/logging.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
|
-
import {
|
|
5
|
+
import { dataDir } from "./utils/data-dir.js";
|
|
6
6
|
|
|
7
7
|
export type LogLevel = "info" | "warn" | "error" | "debug";
|
|
8
8
|
|
|
@@ -19,7 +19,7 @@ let fileFailureReported = false;
|
|
|
19
19
|
|
|
20
20
|
function logFile(): string {
|
|
21
21
|
const configured = process.env.FREE_PI_LOG_FILE?.trim();
|
|
22
|
-
return configured || join(
|
|
22
|
+
return configured || join(dataDir(), "plugin.log");
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
function rotate(file: string): void {
|
package/src/plugin.ts
CHANGED
|
@@ -15,6 +15,11 @@ import { closeFreePiSession } from "./api/session.js";
|
|
|
15
15
|
import { readCredentialsToken } from "./auth/credentials.js";
|
|
16
16
|
import { tokenFromCredential } from "./auth/credential.js";
|
|
17
17
|
import { fetchCatalog } from "./catalog/catalog.js";
|
|
18
|
+
import {
|
|
19
|
+
loadLiveLimits,
|
|
20
|
+
shouldVerifyWindow,
|
|
21
|
+
verifyGatewayWindow,
|
|
22
|
+
} from "./catalog/live.js";
|
|
18
23
|
import {
|
|
19
24
|
accountAccess,
|
|
20
25
|
buildModels,
|
|
@@ -130,9 +135,10 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
130
135
|
const main = filterAccessibleModels(catalogMain, access);
|
|
131
136
|
const defense = filterAccessibleModels(catalogDefense, access);
|
|
132
137
|
const candidates = modelRegistryCandidates(registry);
|
|
138
|
+
const live = await loadLiveLimits();
|
|
133
139
|
const configuredEffort = ctx.options?.reasoningEffort;
|
|
134
140
|
const buildOptions = {
|
|
135
|
-
|
|
141
|
+
live,
|
|
136
142
|
...(configuredEffort === false
|
|
137
143
|
? { reasoningEffort: false as const }
|
|
138
144
|
: isReasoningEffort(configuredEffort)
|
|
@@ -174,6 +180,19 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
174
180
|
}
|
|
175
181
|
});
|
|
176
182
|
|
|
183
|
+
// The gateway does not publish its context ceiling. Verify the compiled
|
|
184
|
+
// window against it once a week with a free model, in the background, and
|
|
185
|
+
// persist the result for the next catalog build.
|
|
186
|
+
if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
|
|
187
|
+
const probe =
|
|
188
|
+
main.find((model) => model.free === true)?.id ??
|
|
189
|
+
catalog?.default_model ??
|
|
190
|
+
Object.keys(mainModels)[0];
|
|
191
|
+
if (probe) {
|
|
192
|
+
void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
177
196
|
// V1 selected the catalog default when the user had no model configured.
|
|
178
197
|
await ctx.model.transform((editor) => {
|
|
179
198
|
if (editor.default.get()) return;
|
|
@@ -211,7 +230,6 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
211
230
|
defaultModel: catalog?.default_model,
|
|
212
231
|
clientVersion: state.latestClientVersion,
|
|
213
232
|
capabilities: candidates.length,
|
|
214
|
-
costArm: state.costExperimentArm,
|
|
215
233
|
models: main.map((model) => model.id),
|
|
216
234
|
},
|
|
217
235
|
);
|
package/src/session/events.ts
CHANGED
|
@@ -6,7 +6,7 @@ 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 {
|
|
9
|
+
import { noteStepTokens } from "../catalog/live.js";
|
|
10
10
|
import { forgetToolStats } from "./tools.js";
|
|
11
11
|
import {
|
|
12
12
|
beginExecution,
|
|
@@ -113,7 +113,11 @@ async function handleEvent(
|
|
|
113
113
|
event.data?.tokens,
|
|
114
114
|
);
|
|
115
115
|
// Step tokens are per request; usage.updated is cumulative.
|
|
116
|
-
|
|
116
|
+
noteStepTokens(
|
|
117
|
+
deps,
|
|
118
|
+
deps.state.trackedModels.get(event.data?.sessionID)?.modelID ?? "",
|
|
119
|
+
event.data?.tokens,
|
|
120
|
+
);
|
|
117
121
|
return;
|
|
118
122
|
}
|
|
119
123
|
case "session.deleted": {
|
|
@@ -121,7 +125,6 @@ async function handleEvent(
|
|
|
121
125
|
if (typeof sessionID !== "string") return;
|
|
122
126
|
await finalizeFreePiSession(deps, sessionID);
|
|
123
127
|
forgetFreePiSession(deps, sessionID);
|
|
124
|
-
forgetCacheMiss(deps, sessionID);
|
|
125
128
|
forgetToolStats(deps, sessionID);
|
|
126
129
|
deps.state.subagentSessions.delete(sessionID);
|
|
127
130
|
return;
|
package/src/session/hooks.ts
CHANGED
|
@@ -8,12 +8,10 @@ import { resolveToken } from "../auth/token.js";
|
|
|
8
8
|
import {
|
|
9
9
|
AD_CONTEXT_HEADER,
|
|
10
10
|
AD_CONTEXT_OPT_OUT,
|
|
11
|
-
COST_EXPERIMENT_HEADER,
|
|
12
11
|
CONCURRENT_RETRY_BASE_MS,
|
|
13
12
|
CONCURRENT_RETRY_MAX,
|
|
14
13
|
CONCURRENT_RETRY_MAX_DELAY_MS,
|
|
15
14
|
DEFENSE_PROVIDER_ID,
|
|
16
|
-
EFFICIENCY_RULE,
|
|
17
15
|
FREE_PI_COMPACTION_GUIDANCE,
|
|
18
16
|
FREE_PI_COMPACTION_MARKER,
|
|
19
17
|
FREE_PI_GUIDANCE,
|
|
@@ -163,18 +161,6 @@ async function applyGeneration(
|
|
|
163
161
|
appendSystemGuidance(event, FREE_PI_GUIDANCE, FREE_PI_GUIDANCE_MARKER);
|
|
164
162
|
}
|
|
165
163
|
|
|
166
|
-
if (deps.state.costExperimentArm === "efficiency") {
|
|
167
|
-
const system = Array.isArray(event.system) ? event.system : [];
|
|
168
|
-
if (
|
|
169
|
-
!system.some(
|
|
170
|
-
(part: any) => part?.type === "text" && part.text === EFFICIENCY_RULE,
|
|
171
|
-
)
|
|
172
|
-
) {
|
|
173
|
-
system.push({ type: "text", text: EFFICIENCY_RULE });
|
|
174
|
-
event.system = system;
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
164
|
const agent = event.agent;
|
|
179
165
|
const turn = await resolveAdTurn(deps, {
|
|
180
166
|
sessionID: event.sessionID,
|
|
@@ -222,9 +208,6 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
222
208
|
if (deps.state.subagentSessions.has(event.sessionID)) {
|
|
223
209
|
event.headers[SUBAGENT_HEADER] = "1";
|
|
224
210
|
}
|
|
225
|
-
if (deps.state.costExperimentArm) {
|
|
226
|
-
event.headers[COST_EXPERIMENT_HEADER] = deps.state.costExperimentArm;
|
|
227
|
-
}
|
|
228
211
|
|
|
229
212
|
// Title requests are suppressed by the title hook, so an ad for them would be
|
|
230
213
|
// an impression the user never sees.
|
package/src/state.ts
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
import { DEFAULT_CLIENT_VERSION } from "./constants.js";
|
|
4
4
|
import type {
|
|
5
5
|
AdTurn,
|
|
6
|
-
CacheMissState,
|
|
7
6
|
Catalog,
|
|
8
7
|
FreePiError,
|
|
9
8
|
ModelRegistry,
|
|
@@ -26,7 +25,6 @@ export type RuntimeState = {
|
|
|
26
25
|
cachedRegistryAt: number;
|
|
27
26
|
registryAttemptAt: number;
|
|
28
27
|
registryPromise?: Promise<ModelRegistry | undefined>;
|
|
29
|
-
costExperimentArm?: string;
|
|
30
28
|
lastCatalogNotice?: string;
|
|
31
29
|
lastQuotaNotice?: string;
|
|
32
30
|
catalogModels: Catalog;
|
|
@@ -64,20 +62,7 @@ export type RuntimeState = {
|
|
|
64
62
|
pendingAdTurns: Map<string, AdTurn>;
|
|
65
63
|
adImpressions: Map<string, Promise<void>>;
|
|
66
64
|
trackedModels: Map<string, TrackedModel>;
|
|
67
|
-
cacheMisses: Map<string, CacheMissState>;
|
|
68
65
|
toolStats: Map<string, ToolStats>;
|
|
69
|
-
/** Successful paid-tool answers, keyed by canonical input, to avoid rebilling. */
|
|
70
|
-
toolSpend: Map<
|
|
71
|
-
string,
|
|
72
|
-
{
|
|
73
|
-
at: number;
|
|
74
|
-
output: {
|
|
75
|
-
content: ReadonlyArray<{ type: "text"; text: string }>;
|
|
76
|
-
metadata: Record<string, unknown>;
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
>;
|
|
80
|
-
toolSpendPending: Map<string, Promise<any>>;
|
|
81
66
|
subagentSessions: Set<string>;
|
|
82
67
|
};
|
|
83
68
|
|
|
@@ -108,10 +93,7 @@ export function createRuntimeState(): RuntimeState {
|
|
|
108
93
|
pendingAdTurns: new Map(),
|
|
109
94
|
adImpressions: new Map(),
|
|
110
95
|
trackedModels: new Map(),
|
|
111
|
-
cacheMisses: new Map(),
|
|
112
96
|
toolStats: new Map(),
|
|
113
|
-
toolSpend: new Map(),
|
|
114
|
-
toolSpendPending: new Map(),
|
|
115
97
|
subagentSessions: new Set(),
|
|
116
98
|
};
|
|
117
99
|
}
|
|
@@ -4,14 +4,14 @@
|
|
|
4
4
|
* free-pi answers one `/tools/vision` request at a time: a second concurrent
|
|
5
5
|
* question gets `rate_limited`. OpenCode can run several sessions, and users can
|
|
6
6
|
* run several OpenCode processes, so calls are queued in-process and coordinated
|
|
7
|
-
* through a lock directory in the free-pi
|
|
7
|
+
* through a lock directory in the free-pi data directory.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { randomUUID } from "node:crypto";
|
|
11
11
|
import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
12
12
|
import { join } from "node:path";
|
|
13
13
|
import type { Logger } from "../logging.js";
|
|
14
|
-
import {
|
|
14
|
+
import { dataDir } from "../utils/data-dir.js";
|
|
15
15
|
|
|
16
16
|
type Owner = { pid: number; startedAt: number; id: string };
|
|
17
17
|
|
|
@@ -24,7 +24,7 @@ const MAX_WAIT_MS = 120_000;
|
|
|
24
24
|
let chain: Promise<void> = Promise.resolve();
|
|
25
25
|
|
|
26
26
|
function lockDir(): string {
|
|
27
|
-
return join(
|
|
27
|
+
return join(dataDir(), "vision.lock");
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
function pidAlive(pid: number): boolean {
|
|
@@ -87,9 +87,9 @@ async function acquire(log: Logger): Promise<Slot | undefined> {
|
|
|
87
87
|
const startedAt = Date.now();
|
|
88
88
|
|
|
89
89
|
try {
|
|
90
|
-
await mkdir(
|
|
90
|
+
await mkdir(dataDir(), { recursive: true });
|
|
91
91
|
} catch {
|
|
92
|
-
// Without a
|
|
92
|
+
// Without a data directory the file lock is unavailable; the in-process
|
|
93
93
|
// queue still serializes calls, so keep going.
|
|
94
94
|
}
|
|
95
95
|
|