@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
package/src/session/hooks.ts
CHANGED
|
@@ -11,6 +11,9 @@ 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
19
|
import {
|
|
@@ -18,7 +21,14 @@ import {
|
|
|
18
21
|
rewriteLimitResponse,
|
|
19
22
|
} from "../errors/limit.js";
|
|
20
23
|
import { trimMap } from "../utils/async.js";
|
|
24
|
+
import { watchFreePiNotice } from "./notices.js";
|
|
21
25
|
import { rememberFreePiSession } from "./track.js";
|
|
26
|
+
import {
|
|
27
|
+
recordCompaction,
|
|
28
|
+
recordToolEnd,
|
|
29
|
+
recordToolStart,
|
|
30
|
+
toolHeaders,
|
|
31
|
+
} from "./tools.js";
|
|
22
32
|
import { rememberTrackedModel } from "./usage.js";
|
|
23
33
|
|
|
24
34
|
type Registration = { dispose: () => Promise<void> };
|
|
@@ -28,7 +38,8 @@ type SessionHookName =
|
|
|
28
38
|
| "generate"
|
|
29
39
|
| "title"
|
|
30
40
|
| "model.request"
|
|
31
|
-
| "http.response"
|
|
41
|
+
| "http.response"
|
|
42
|
+
| "retry";
|
|
32
43
|
type RequestKind = "primary" | "compaction" | "generate" | "title";
|
|
33
44
|
|
|
34
45
|
const PENDING_LIMIT = 400;
|
|
@@ -77,6 +88,16 @@ async function applyGeneration(
|
|
|
77
88
|
if (current === undefined || current > cap) event.options.maxTokens = cap;
|
|
78
89
|
}
|
|
79
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
|
+
|
|
80
101
|
if (deps.state.costExperimentArm === "efficiency") {
|
|
81
102
|
const system = Array.isArray(event.system) ? event.system : [];
|
|
82
103
|
if (
|
|
@@ -122,6 +143,11 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
122
143
|
// an impression the user never sees.
|
|
123
144
|
if (event.kind === "title") return;
|
|
124
145
|
|
|
146
|
+
Object.assign(
|
|
147
|
+
event.headers,
|
|
148
|
+
toolHeaders(deps, event.sessionID, event.kind !== "compaction"),
|
|
149
|
+
);
|
|
150
|
+
|
|
125
151
|
const pending = deps.state.pendingAdTurns.get(
|
|
126
152
|
pendingKeyOf(event.sessionID, agent, event.kind),
|
|
127
153
|
);
|
|
@@ -145,6 +171,47 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
145
171
|
}
|
|
146
172
|
}
|
|
147
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
|
+
|
|
148
215
|
async function hookForProviders(
|
|
149
216
|
ctx: Plugin.Context,
|
|
150
217
|
name: SessionHookName,
|
|
@@ -193,16 +260,26 @@ export async function registerSessionHooks(
|
|
|
193
260
|
event.response,
|
|
194
261
|
).catch(() => undefined);
|
|
195
262
|
if (overflow) {
|
|
196
|
-
event.response = overflow;
|
|
263
|
+
event.response = watchFreePiNotice(deps, overflow);
|
|
197
264
|
return;
|
|
198
265
|
}
|
|
199
266
|
const rewritten = await rewriteLimitResponse(event.response).catch(
|
|
200
267
|
() => undefined,
|
|
201
268
|
);
|
|
202
|
-
|
|
269
|
+
event.response = watchFreePiNotice(
|
|
270
|
+
deps,
|
|
271
|
+
rewritten ?? event.response,
|
|
272
|
+
);
|
|
203
273
|
},
|
|
204
274
|
registrations,
|
|
205
275
|
);
|
|
276
|
+
await hookForProviders(
|
|
277
|
+
ctx,
|
|
278
|
+
"retry",
|
|
279
|
+
(event: any) => applyRetryPolicy(event),
|
|
280
|
+
registrations,
|
|
281
|
+
);
|
|
282
|
+
await registerToolHooks(ctx, deps, registrations);
|
|
206
283
|
|
|
207
284
|
return registrations;
|
|
208
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;
|