@eduardo191labs/opencode-free-pi 0.3.3 → 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 +23 -0
- package/dist/catalog/catalog.js +12 -2
- package/dist/catalog/models.d.ts +6 -2
- package/dist/catalog/models.js +30 -22
- package/dist/catalog/v2.js +15 -4
- package/dist/constants.d.ts +32 -0
- package/dist/constants.js +37 -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 +43 -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 +39 -37
- package/src/catalog/v2.ts +16 -3
- package/src/constants.ts +43 -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 +80 -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
|
@@ -0,0 +1,112 @@
|
|
|
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
|
+
import { COMPACTED_HEADER, DEFENSE_PROVIDER_ID, PROVIDER_ID, TOOL_ERRORS_HEADER, TOOL_ID_LIMIT, TOOL_META_BUDGET, TOOL_META_HEADER, } from "../constants.js";
|
|
10
|
+
import { trimMap } from "../utils/async.js";
|
|
11
|
+
const ID_PATTERN = /^[\w.:-]{1,100}$/;
|
|
12
|
+
const MAX_ENTRY_LENGTH = 150;
|
|
13
|
+
const MAX_STARTED = 200;
|
|
14
|
+
function isFreePiSession(deps, sessionID) {
|
|
15
|
+
if (deps.state.freePiSessions.has(sessionID))
|
|
16
|
+
return true;
|
|
17
|
+
const tracked = deps.state.trackedModels.get(sessionID);
|
|
18
|
+
return (tracked?.providerID === PROVIDER_ID ||
|
|
19
|
+
tracked?.providerID === DEFENSE_PROVIDER_ID);
|
|
20
|
+
}
|
|
21
|
+
function statsFor(deps, sessionID) {
|
|
22
|
+
let stats = deps.state.toolStats.get(sessionID);
|
|
23
|
+
if (!stats) {
|
|
24
|
+
stats = {
|
|
25
|
+
meta: [],
|
|
26
|
+
metaBytes: 3,
|
|
27
|
+
failed: [],
|
|
28
|
+
evicted: false,
|
|
29
|
+
started: new Map(),
|
|
30
|
+
compacted: 0,
|
|
31
|
+
};
|
|
32
|
+
trimMap(deps.state.toolStats, 200);
|
|
33
|
+
deps.state.toolStats.set(sessionID, stats);
|
|
34
|
+
}
|
|
35
|
+
return stats;
|
|
36
|
+
}
|
|
37
|
+
function shellExit(stats) {
|
|
38
|
+
if (stats.status === "error")
|
|
39
|
+
return "-";
|
|
40
|
+
const exit = stats.result?.metadata?.exit;
|
|
41
|
+
return typeof exit === "number" ? String(exit) : "0";
|
|
42
|
+
}
|
|
43
|
+
function truncated(stats) {
|
|
44
|
+
const metadata = stats.result?.metadata;
|
|
45
|
+
if (metadata?.truncated === true)
|
|
46
|
+
return true;
|
|
47
|
+
const truncation = metadata?.truncation;
|
|
48
|
+
return Boolean(truncation &&
|
|
49
|
+
typeof truncation === "object" &&
|
|
50
|
+
truncation.truncated === true);
|
|
51
|
+
}
|
|
52
|
+
export function recordToolStart(deps, sessionID, id) {
|
|
53
|
+
if (!isFreePiSession(deps, sessionID) || !ID_PATTERN.test(id))
|
|
54
|
+
return;
|
|
55
|
+
const stats = statsFor(deps, sessionID);
|
|
56
|
+
stats.started.set(id, Date.now());
|
|
57
|
+
if (stats.started.size <= MAX_STARTED)
|
|
58
|
+
return;
|
|
59
|
+
const oldest = stats.started.keys().next().value;
|
|
60
|
+
if (oldest !== undefined)
|
|
61
|
+
stats.started.delete(oldest);
|
|
62
|
+
}
|
|
63
|
+
export function recordToolEnd(deps, sessionID, end) {
|
|
64
|
+
if (!isFreePiSession(deps, sessionID) || !ID_PATTERN.test(end.id))
|
|
65
|
+
return;
|
|
66
|
+
const stats = statsFor(deps, sessionID);
|
|
67
|
+
const startedAt = stats.started.get(end.id);
|
|
68
|
+
stats.started.delete(end.id);
|
|
69
|
+
const duration = startedAt === undefined ? 0 : Date.now() - startedAt;
|
|
70
|
+
const entry = `${end.id}~${Math.max(0, Math.round(duration))}~${shellExit(end)}~${truncated(end) ? 1 : 0}`;
|
|
71
|
+
if (entry.length <= MAX_ENTRY_LENGTH) {
|
|
72
|
+
stats.meta.push(entry);
|
|
73
|
+
stats.metaBytes += entry.length + 1;
|
|
74
|
+
while (stats.metaBytes > TOOL_META_BUDGET && stats.meta.length > 1) {
|
|
75
|
+
const removed = stats.meta.shift();
|
|
76
|
+
stats.metaBytes -= (removed?.length ?? 0) + 1;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (end.status !== "error")
|
|
80
|
+
return;
|
|
81
|
+
stats.failed.push(end.id);
|
|
82
|
+
if (stats.failed.length <= TOOL_ID_LIMIT)
|
|
83
|
+
return;
|
|
84
|
+
stats.failed.shift();
|
|
85
|
+
stats.evicted = true;
|
|
86
|
+
}
|
|
87
|
+
export function recordCompaction(deps, sessionID, droppedMessages) {
|
|
88
|
+
if (!isFreePiSession(deps, sessionID) || droppedMessages <= 0)
|
|
89
|
+
return;
|
|
90
|
+
const stats = statsFor(deps, sessionID);
|
|
91
|
+
stats.compacted += droppedMessages;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Headers for the outgoing request. `consumeCompacted` is false for the
|
|
95
|
+
* compaction request itself so the marker lands on the request that follows.
|
|
96
|
+
*/
|
|
97
|
+
export function toolHeaders(deps, sessionID, consumeCompacted) {
|
|
98
|
+
const stats = deps.state.toolStats.get(sessionID);
|
|
99
|
+
const headers = {};
|
|
100
|
+
if (stats?.meta.length) {
|
|
101
|
+
headers[TOOL_META_HEADER] = `v1:${stats.meta.join(",")}`;
|
|
102
|
+
}
|
|
103
|
+
if (stats && consumeCompacted && stats.compacted > 0) {
|
|
104
|
+
headers[COMPACTED_HEADER] = `v1:${stats.compacted}`;
|
|
105
|
+
stats.compacted = 0;
|
|
106
|
+
}
|
|
107
|
+
headers[TOOL_ERRORS_HEADER] = `${stats?.evicted ? "v1x" : "v1"}:${(stats?.failed ?? []).join(",")}`;
|
|
108
|
+
return headers;
|
|
109
|
+
}
|
|
110
|
+
export function forgetToolStats(deps, sessionID) {
|
|
111
|
+
deps.state.toolStats.delete(sessionID);
|
|
112
|
+
}
|
package/dist/state.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Per-plugin-instance mutable state. */
|
|
2
|
-
import type { AdTurn, Catalog, FreePiError, ModelRegistry, QuotaSnapshot, RequestUsage, SessionResetOutcome, TokenCheckState, TrackedModel } from "./types.js";
|
|
2
|
+
import type { AdTurn, CacheMissState, Catalog, FreePiError, ModelRegistry, QuotaSnapshot, RequestUsage, SessionResetOutcome, TokenCheckState, ToolStats, TrackedModel } from "./types.js";
|
|
3
3
|
export type RuntimeState = {
|
|
4
4
|
latestClientVersion: string;
|
|
5
5
|
providerToken?: string;
|
|
@@ -39,5 +39,7 @@ export type RuntimeState = {
|
|
|
39
39
|
pendingAdTurns: Map<string, AdTurn>;
|
|
40
40
|
adImpressions: Map<string, Promise<void>>;
|
|
41
41
|
trackedModels: Map<string, TrackedModel>;
|
|
42
|
+
cacheMisses: Map<string, CacheMissState>;
|
|
43
|
+
toolStats: Map<string, ToolStats>;
|
|
42
44
|
};
|
|
43
45
|
export declare function createRuntimeState(): RuntimeState;
|
package/dist/state.js
CHANGED
package/dist/types.d.ts
CHANGED
|
@@ -103,6 +103,9 @@ export type ModelDefinition = {
|
|
|
103
103
|
reasoning: boolean;
|
|
104
104
|
reasoning_options?: ReasoningOption[];
|
|
105
105
|
variants: Record<string, Record<string, unknown>>;
|
|
106
|
+
/** Model-level provider options, such as the default reasoning effort. */
|
|
107
|
+
settings?: Record<string, unknown>;
|
|
108
|
+
enabled: boolean;
|
|
106
109
|
temperature: boolean;
|
|
107
110
|
tool_call: boolean;
|
|
108
111
|
attachment: boolean;
|
|
@@ -237,6 +240,20 @@ export type TrackedModel = {
|
|
|
237
240
|
providerID: string;
|
|
238
241
|
modelID: string;
|
|
239
242
|
};
|
|
243
|
+
export type CacheMissState = {
|
|
244
|
+
promptTokens: number;
|
|
245
|
+
at: number;
|
|
246
|
+
modelKey: string;
|
|
247
|
+
reportedCache: boolean;
|
|
248
|
+
};
|
|
249
|
+
export type ToolStats = {
|
|
250
|
+
meta: string[];
|
|
251
|
+
metaBytes: number;
|
|
252
|
+
failed: string[];
|
|
253
|
+
evicted: boolean;
|
|
254
|
+
started: Map<string, number>;
|
|
255
|
+
compacted: number;
|
|
256
|
+
};
|
|
240
257
|
export type TokenUsageLike = {
|
|
241
258
|
input?: number;
|
|
242
259
|
output?: number;
|
package/package.json
CHANGED
package/src/catalog/catalog.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/** Fetches the live free-pi model catalog. */
|
|
2
2
|
|
|
3
|
+
import { resolveToken } from "../auth/token.js";
|
|
3
4
|
import {
|
|
4
5
|
CATALOG_DISK_TTL_MS,
|
|
5
6
|
CATALOG_TIMEOUT_MS,
|
|
6
7
|
CATALOG_TTL_MS,
|
|
8
|
+
COST_EXPERIMENT_HEADER,
|
|
7
9
|
} from "../constants.js";
|
|
8
10
|
import type { Deps } from "../deps.js";
|
|
9
11
|
import type { Catalog } from "../types.js";
|
|
@@ -44,8 +46,16 @@ export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
|
|
|
44
46
|
if (state.catalogPromise) return state.catalogPromise;
|
|
45
47
|
const pending = (async () => {
|
|
46
48
|
try {
|
|
49
|
+
// The CLI asks for the catalog with its JWT and the cost-experiment
|
|
50
|
+
// header; without both the server may omit `cost_experiment`.
|
|
51
|
+
const token = await resolveToken(deps).catch(() => undefined);
|
|
52
|
+
const headers: Record<string, string> = {
|
|
53
|
+
accept: "application/json",
|
|
54
|
+
[COST_EXPERIMENT_HEADER]: "1",
|
|
55
|
+
};
|
|
56
|
+
if (token) headers.authorization = `Bearer ${token}`;
|
|
47
57
|
const response = await fetch(`${resolveBaseUrl()}/client-version`, {
|
|
48
|
-
headers
|
|
58
|
+
headers,
|
|
49
59
|
signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
|
|
50
60
|
});
|
|
51
61
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
package/src/catalog/models.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
/** Turns the free-pi catalog and models.dev registry into model definitions. */
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
|
+
COMPACT100_CONTEXT_WINDOW,
|
|
4
5
|
CONTEXT_WINDOW,
|
|
6
|
+
DEFAULT_REASONING_EFFORT,
|
|
7
|
+
DEFAULT_THINKING_LEVELS,
|
|
5
8
|
MAX_OUTPUT_TOKENS,
|
|
6
9
|
} from "../constants.js";
|
|
7
10
|
import type {
|
|
@@ -155,42 +158,30 @@ export function modelCapability(
|
|
|
155
158
|
return best;
|
|
156
159
|
}
|
|
157
160
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
outputLimit - 1024,
|
|
168
|
-
MAX_OUTPUT_TOKENS - 1024,
|
|
169
|
-
),
|
|
170
|
-
);
|
|
171
|
-
const floor = Math.min(positiveNumber(option.min) ?? 0, ceiling);
|
|
172
|
-
const high = Math.min(
|
|
173
|
-
Math.max(floor, Math.floor((ceiling + 1) / 2)),
|
|
174
|
-
ceiling,
|
|
175
|
-
);
|
|
176
|
-
for (const [level, budget] of [
|
|
177
|
-
["high", high],
|
|
178
|
-
["max", ceiling],
|
|
179
|
-
] as const) {
|
|
180
|
-
variants[level] = {
|
|
181
|
-
reasoningEffort: level,
|
|
182
|
-
thinking_budget: budget,
|
|
183
|
-
thinking: { type: "enabled", budget_tokens: budget },
|
|
184
|
-
};
|
|
185
|
-
}
|
|
161
|
+
/**
|
|
162
|
+
* free-pi's openai-compatible route only understands `reasoning_effort`.
|
|
163
|
+
* pi's `thinking_budget` and `thinking` fields are dropped by OpenCode's
|
|
164
|
+
* lowering, so advertising them would be inert. Budget-style catalogs still
|
|
165
|
+
* expose their top levels as effort variants.
|
|
166
|
+
*/
|
|
167
|
+
function budgetVariants(variants: VariantMap): void {
|
|
168
|
+
variants.high = { reasoningEffort: "high" };
|
|
169
|
+
variants.max = { reasoningEffort: "max" };
|
|
186
170
|
}
|
|
187
171
|
|
|
188
172
|
export function modelVariants(
|
|
189
173
|
options: ReasoningOption[] | undefined,
|
|
190
|
-
|
|
174
|
+
_outputLimit: number,
|
|
191
175
|
): VariantMap {
|
|
192
176
|
const variants: VariantMap = {};
|
|
193
|
-
|
|
177
|
+
// The provider CLI offers these levels to every reasoning model because its
|
|
178
|
+
// `thinkingLevelMap` is unset; `xhigh` and `max` stay opt-in.
|
|
179
|
+
if (!options || options.length === 0) {
|
|
180
|
+
for (const level of DEFAULT_THINKING_LEVELS) {
|
|
181
|
+
variants[level] = { reasoningEffort: level };
|
|
182
|
+
}
|
|
183
|
+
return variants;
|
|
184
|
+
}
|
|
194
185
|
const effort = options.find(
|
|
195
186
|
(option): option is Extract<ReasoningOption, { type: "effort" }> =>
|
|
196
187
|
option.type === "effort",
|
|
@@ -205,17 +196,21 @@ export function modelVariants(
|
|
|
205
196
|
variants.none = { reasoningEffort: "none" };
|
|
206
197
|
variants.high = { reasoningEffort: "high" };
|
|
207
198
|
}
|
|
208
|
-
|
|
209
|
-
(
|
|
210
|
-
|
|
211
|
-
);
|
|
212
|
-
if (budget) budgetVariants(budget, outputLimit, variants);
|
|
199
|
+
if (options.some((option) => option.type === "budget_tokens")) {
|
|
200
|
+
budgetVariants(variants);
|
|
201
|
+
}
|
|
213
202
|
return variants;
|
|
214
203
|
}
|
|
215
204
|
|
|
205
|
+
export type BuildModelsOptions = {
|
|
206
|
+
/** pi's `compact100` arm compacts at 100k instead of the default ceiling. */
|
|
207
|
+
compact100?: boolean;
|
|
208
|
+
};
|
|
209
|
+
|
|
216
210
|
export function buildModels(
|
|
217
211
|
models: CatalogModel[],
|
|
218
212
|
candidates: RegistryCandidate[] = [],
|
|
213
|
+
options: BuildModelsOptions = {},
|
|
219
214
|
): ModelMap {
|
|
220
215
|
const result: ModelMap = {};
|
|
221
216
|
for (const model of models) {
|
|
@@ -230,14 +225,17 @@ export function buildModels(
|
|
|
230
225
|
// an advertised 1M window would let OpenCode grow a session past the
|
|
231
226
|
// server's real ceiling and fail with `context_too_long` instead of
|
|
232
227
|
// compacting.
|
|
228
|
+
const contextCeiling = options.compact100
|
|
229
|
+
? COMPACT100_CONTEXT_WINDOW
|
|
230
|
+
: CONTEXT_WINDOW;
|
|
233
231
|
const limitContext = Math.min(
|
|
234
232
|
positiveNumber(
|
|
235
233
|
model.context_window,
|
|
236
234
|
model.contextWindow,
|
|
237
235
|
model.limit?.context,
|
|
238
236
|
capability?.limit?.context,
|
|
239
|
-
) ??
|
|
240
|
-
|
|
237
|
+
) ?? contextCeiling,
|
|
238
|
+
contextCeiling,
|
|
241
239
|
);
|
|
242
240
|
const limitOutput = Math.min(
|
|
243
241
|
positiveNumber(
|
|
@@ -260,6 +258,10 @@ export function buildModels(
|
|
|
260
258
|
reasoning,
|
|
261
259
|
reasoning_options: reasoningOptions,
|
|
262
260
|
variants: reasoning ? modelVariants(reasoningOptions, limitOutput) : {},
|
|
261
|
+
...(reasoning
|
|
262
|
+
? { settings: { reasoningEffort: DEFAULT_REASONING_EFFORT } }
|
|
263
|
+
: {}),
|
|
264
|
+
enabled: model.unavailable !== true,
|
|
263
265
|
temperature: model.temperature ?? capability?.temperature ?? true,
|
|
264
266
|
tool_call: model.tool_call ?? capability?.tool_call ?? true,
|
|
265
267
|
attachment: model.attachment ?? capability?.attachment ?? false,
|
package/src/catalog/v2.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/** Converts internal model definitions into OpenCode V2 provider records. */
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
|
+
CHUNK_TIMEOUT_MS,
|
|
4
5
|
CONTEXT_WINDOW,
|
|
6
|
+
HEADER_TIMEOUT_MS,
|
|
5
7
|
MAX_OUTPUT_TOKENS,
|
|
6
8
|
OPENAI_COMPATIBLE_PACKAGE,
|
|
7
9
|
PROVIDER_ID,
|
|
@@ -30,12 +32,16 @@ export function toV2Models(providerID: string, models: ModelMap): any[] {
|
|
|
30
32
|
...(model.family ? { family: model.family } : {}),
|
|
31
33
|
capabilities: {
|
|
32
34
|
tools: model.tool_call !== false,
|
|
33
|
-
|
|
34
|
-
|
|
35
|
+
// The provider CLI registers every free-pi model as text-only. An
|
|
36
|
+
// advertised image input would let OpenCode send media the server
|
|
37
|
+
// does not accept.
|
|
38
|
+
input: ["text"],
|
|
39
|
+
output: ["text"],
|
|
35
40
|
...(model.temperature === undefined
|
|
36
41
|
? {}
|
|
37
42
|
: { temperature: model.temperature }),
|
|
38
43
|
},
|
|
44
|
+
...(model.settings ? { settings: model.settings } : {}),
|
|
39
45
|
variants: Object.entries(model.variants ?? {}).map(([id, settings]) => ({
|
|
40
46
|
id,
|
|
41
47
|
settings,
|
|
@@ -52,7 +58,7 @@ export function toV2Models(providerID: string, models: ModelMap): any[] {
|
|
|
52
58
|
},
|
|
53
59
|
],
|
|
54
60
|
status: model.status === "deprecated" ? "deprecated" : "active",
|
|
55
|
-
enabled:
|
|
61
|
+
enabled: model.enabled !== false,
|
|
56
62
|
limit: {
|
|
57
63
|
context: model.limit?.context ?? CONTEXT_WINDOW,
|
|
58
64
|
output: model.limit?.output ?? MAX_OUTPUT_TOKENS,
|
|
@@ -75,6 +81,13 @@ export function baseProviderInfo(
|
|
|
75
81
|
settings: {
|
|
76
82
|
baseURL: completionsBaseUrl(),
|
|
77
83
|
apiKey: token ?? "free-pi",
|
|
84
|
+
// free-pi is ad-supported and bills credits, so OpenCode's keep-alive
|
|
85
|
+
// warmer would spend requests the provider CLI never makes. pi keeps
|
|
86
|
+
// warming off for free-pi and the economics are always zero.
|
|
87
|
+
cache: { warming: false },
|
|
88
|
+
// Match pi's HTTP idle timeout for both response headers and chunks.
|
|
89
|
+
headerTimeout: HEADER_TIMEOUT_MS,
|
|
90
|
+
chunkTimeout: CHUNK_TIMEOUT_MS,
|
|
78
91
|
},
|
|
79
92
|
};
|
|
80
93
|
}
|
package/src/constants.ts
CHANGED
|
@@ -19,6 +19,49 @@ export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
|
19
19
|
export const EFFICIENCY_RULE =
|
|
20
20
|
"- When several independent reads or searches are needed, issue them in the same turn.";
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* The provider CLI registers every free-pi model with reasoning enabled and
|
|
24
|
+
* defaults to thinking off. OpenCode only sends `reasoning_effort` when a
|
|
25
|
+
* variant or model setting provides one, so the model carries the off default
|
|
26
|
+
* and the picker offers the levels the CLI would.
|
|
27
|
+
*/
|
|
28
|
+
export const DEFAULT_REASONING_EFFORT = "none";
|
|
29
|
+
export const DEFAULT_THINKING_LEVELS = [
|
|
30
|
+
"minimal",
|
|
31
|
+
"low",
|
|
32
|
+
"medium",
|
|
33
|
+
"high",
|
|
34
|
+
] as const;
|
|
35
|
+
|
|
36
|
+
/** pi-ai's HTTP idle timeout for headers and body chunks. */
|
|
37
|
+
export const HEADER_TIMEOUT_MS = 300_000;
|
|
38
|
+
export const CHUNK_TIMEOUT_MS = 300_000;
|
|
39
|
+
|
|
40
|
+
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
41
|
+
export const RETRY_MAX_RETRIES = 3;
|
|
42
|
+
export const RETRY_BASE_DELAY_MS = 2_000;
|
|
43
|
+
export const RETRY_MAX_DELAY_MS = 60_000;
|
|
44
|
+
|
|
45
|
+
/** pi assumes a 5 minute prompt-cache TTL when explaining a miss. */
|
|
46
|
+
export const CACHE_TTL_MS = 5 * 60_000;
|
|
47
|
+
export const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
|
|
48
|
+
export const CACHE_MISS_NOTICE_TOKENS = 20_000;
|
|
49
|
+
|
|
50
|
+
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
51
|
+
export const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
52
|
+
export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
53
|
+
export const COMPACTED_HEADER = "x-freepi-compacted";
|
|
54
|
+
export const TOOL_META_BUDGET = 1_500;
|
|
55
|
+
export const TOOL_ID_LIMIT = 50;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The `compact100` cost experiment reserves 100k tokens, so pi compacts when
|
|
59
|
+
* the prompt reaches 100k. OpenCode compacts at `window - max(15%, 16k)`;
|
|
60
|
+
* 117_647 is the smallest window that keeps that trigger at 100k.
|
|
61
|
+
*/
|
|
62
|
+
export const COMPACT100_TRIGGER_TOKENS = 100_000;
|
|
63
|
+
export const COMPACT100_CONTEXT_WINDOW = 117_647;
|
|
64
|
+
|
|
22
65
|
export const SESSION_TRACK_LIMIT = 200;
|
|
23
66
|
export const AUTH_SKEW_MS = 60_000;
|
|
24
67
|
export const AUTH_TIMEOUT_MS = 15 * 60_000;
|
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": {
|