@eduardo191labs/opencode-free-pi 0.7.26 → 0.7.29

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.
Files changed (48) hide show
  1. package/README.md +60 -105
  2. package/dist/catalog/live.js +4 -1
  3. package/dist/catalog/models.d.ts +1 -1
  4. package/dist/catalog/models.js +14 -3
  5. package/dist/constants.d.ts +15 -35
  6. package/dist/constants.js +15 -35
  7. package/dist/index.d.ts +1 -1
  8. package/dist/plugin.js +14 -46
  9. package/dist/session/events.js +5 -12
  10. package/dist/session/hooks.js +83 -348
  11. package/dist/session/overflow.d.ts +7 -28
  12. package/dist/session/overflow.js +7 -73
  13. package/dist/session/replay.d.ts +8 -41
  14. package/dist/session/replay.js +9 -148
  15. package/dist/session/tools.d.ts +2 -7
  16. package/dist/session/tools.js +3 -18
  17. package/dist/session/trace.js +0 -1
  18. package/dist/session/track.d.ts +2 -0
  19. package/dist/session/track.js +5 -0
  20. package/dist/state.d.ts +1 -6
  21. package/dist/state.js +0 -2
  22. package/dist/tools/vision.js +1 -0
  23. package/dist/types.d.ts +0 -1
  24. package/package.json +2 -2
  25. package/src/catalog/live.ts +4 -1
  26. package/src/catalog/models.ts +20 -3
  27. package/src/constants.ts +16 -38
  28. package/src/index.ts +0 -1
  29. package/src/plugin.ts +12 -52
  30. package/src/session/events.ts +5 -12
  31. package/src/session/hooks.ts +109 -431
  32. package/src/session/overflow.ts +7 -77
  33. package/src/session/replay.ts +12 -188
  34. package/src/session/tools.ts +1 -22
  35. package/src/session/trace.ts +0 -1
  36. package/src/session/track.ts +11 -0
  37. package/src/state.ts +0 -8
  38. package/src/tools/vision.ts +2 -0
  39. package/src/types.ts +0 -1
  40. package/dist/session/diet.d.ts +0 -23
  41. package/dist/session/diet.js +0 -176
  42. package/dist/session/title.d.ts +0 -18
  43. package/dist/session/title.js +0 -81
  44. package/dist/session/usage.d.ts +0 -5
  45. package/dist/session/usage.js +0 -32
  46. package/src/session/diet.ts +0 -201
  47. package/src/session/title.ts +0 -90
  48. package/src/session/usage.ts +0 -46
@@ -1,81 +0,0 @@
1
- /**
2
- * Builds session titles locally.
3
- *
4
- * free-pi charges credits and shows ads per model request, and the CLI never
5
- * spends a turn on a title. OpenCode asks the selected model for a title, so
6
- * the title hook answers from the first user message instead: the session gets
7
- * a real name immediately, no ad is fetched, and a failed title request can
8
- * never leave the session stuck on "New session".
9
- */
10
- const MAX_TITLE_LENGTH = 60;
11
- const MAX_SOURCE_LENGTH = 4_000;
12
- const MESSAGE_BLOCK = /<message>([\s\S]*?)<\/message>/i;
13
- const CONVERSATION_BLOCK = /<conversation>([\s\S]*?)<\/conversation>/i;
14
- const PREFIX = /^(?:original request|recent conversation|user|assistant)\s*:\s*/i;
15
- const NOISE = /^(?:```[\w-]*|---+|===+|\*\*\*+)$/;
16
- const XML_LINE = /^<\/?[a-z][^>]*>$/i;
17
- const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
18
- function textOf(content) {
19
- if (typeof content === "string")
20
- return content;
21
- if (!Array.isArray(content))
22
- return "";
23
- return content
24
- .filter((part) => part?.type === "text" && typeof part.text === "string")
25
- .map((part) => part.text)
26
- .join("\n");
27
- }
28
- function latestUserText(messages) {
29
- for (let index = messages.length - 1; index >= 0; index -= 1) {
30
- const message = messages[index];
31
- const role = message?.role ?? message?.type;
32
- if (role !== "user")
33
- continue;
34
- const text = typeof message?.text === "string"
35
- ? message.text
36
- : textOf(message?.content);
37
- if (text.trim())
38
- return text;
39
- }
40
- return "";
41
- }
42
- /** OpenCode wraps the source in `<message>` or `<conversation>` tags. */
43
- function sourceText(messages) {
44
- const raw = latestUserText(messages);
45
- const block = MESSAGE_BLOCK.exec(raw)?.[1] ?? CONVERSATION_BLOCK.exec(raw)?.[1] ?? raw;
46
- return block.slice(0, MAX_SOURCE_LENGTH);
47
- }
48
- function cleanLine(line) {
49
- let value = line.replace(CONTROL, " ").trim();
50
- if (!value)
51
- return undefined;
52
- value = value
53
- .replace(/^#{1,6}\s+/, "")
54
- .replace(/^[-*+>]\s+/, "")
55
- .trim();
56
- value = value.replace(PREFIX, "").trim();
57
- if (!value || NOISE.test(value) || XML_LINE.test(value))
58
- return undefined;
59
- value = value.replace(/^["'`]+|["'`]+$/g, "").trim();
60
- return value || undefined;
61
- }
62
- function truncate(value) {
63
- if (value.length <= MAX_TITLE_LENGTH)
64
- return value;
65
- const cut = value.slice(0, MAX_TITLE_LENGTH - 3);
66
- const space = cut.lastIndexOf(" ");
67
- return `${(space >= 20 ? cut.slice(0, space) : cut).trimEnd()}...`;
68
- }
69
- /** Derives a title from the first meaningful line of the title request. */
70
- export function localTitle(messages) {
71
- if (!Array.isArray(messages) || messages.length === 0)
72
- return "Session";
73
- const lines = sourceText(messages)
74
- .split(/\r?\n/)
75
- .map(cleanLine)
76
- .filter((line) => Boolean(line));
77
- const first = lines[0];
78
- if (!first)
79
- return "Session";
80
- return truncate(first.replace(/[\s:;,\-]+$/g, "").trim()) || "Session";
81
- }
@@ -1,5 +0,0 @@
1
- /** Tracks the last request's model and token usage and refreshes quota. */
2
- import type { Deps } from "../deps.js";
3
- import type { TokenUsageLike } from "../types.js";
4
- export declare function rememberTrackedModel(deps: Deps, sessionID: string, providerID: string, modelID: string): void;
5
- export declare function recordUsage(deps: Deps, sessionID: string, cost: number, tokens: TokenUsageLike | undefined): void;
@@ -1,32 +0,0 @@
1
- /** Tracks the last request's model and token usage and refreshes quota. */
2
- import { fetchQuota } from "../api/quota.js";
3
- import { QUOTA_REFRESH_DEBOUNCE_MS } from "../constants.js";
4
- import { trimMap } from "../utils/async.js";
5
- import { touchSessionActivity } from "./track.js";
6
- export function rememberTrackedModel(deps, sessionID, providerID, modelID) {
7
- trimMap(deps.state.trackedModels, 200);
8
- deps.state.trackedModels.set(sessionID, { providerID, modelID });
9
- }
10
- export function recordUsage(deps, sessionID, cost, tokens) {
11
- if (typeof sessionID !== "string" || !sessionID)
12
- return;
13
- touchSessionActivity(deps, sessionID);
14
- const tracked = deps.state.trackedModels.get(sessionID);
15
- deps.state.lastUsage = {
16
- at: Date.now(),
17
- messageID: "",
18
- providerID: tracked?.providerID ?? "",
19
- modelID: tracked?.modelID ?? "",
20
- cost: typeof cost === "number" ? cost : 0,
21
- input: tokens?.input ?? 0,
22
- output: tokens?.output ?? 0,
23
- reasoning: tokens?.reasoning ?? 0,
24
- cacheRead: tokens?.cache?.read ?? 0,
25
- cacheWrite: tokens?.cache?.write ?? 0,
26
- };
27
- const now = Date.now();
28
- if (now - deps.state.lastQuotaRefreshAt < QUOTA_REFRESH_DEBOUNCE_MS)
29
- return;
30
- deps.state.lastQuotaRefreshAt = now;
31
- void fetchQuota(deps, { force: true }).catch(() => undefined);
32
- }
@@ -1,201 +0,0 @@
1
- /**
2
- * Keeps a primary request inside the range where free models still attend to
3
- * the system prompt and the recent turns.
4
- *
5
- * Long free-pi sessions reach 100k-170k token prompts because every `read`,
6
- * `grep` and `shell` result stays verbatim forever. At that size the free
7
- * models lose the middle of the conversation and stop following the working
8
- * rules even though the gateway accepts the request. Whole turns cannot be
9
- * dropped: the user's wording and the assistant's decisions must survive. Only
10
- * stale tool payloads are collapsed, and the newest messages are never touched.
11
- */
12
-
13
- /** Characters of a pruned tool result that stay readable at the head. */
14
- const STUB_HEAD_CHARS = 600;
15
- /** Characters kept from the end of a pruned result (summaries, errors, totals). */
16
- const STUB_TAIL_CHARS = 240;
17
- /** A result smaller than this is left alone: stubbing it saves nothing. */
18
- const MIN_PRUNE_CHARS = STUB_HEAD_CHARS + STUB_TAIL_CHARS + 400;
19
-
20
- export type DietResult = {
21
- readonly messages: readonly unknown[];
22
- readonly pruned: number;
23
- readonly tokensBefore: number;
24
- readonly tokensAfter: number;
25
- };
26
-
27
- type Part = {
28
- type?: string;
29
- text?: string;
30
- name?: string;
31
- state?: { content?: unknown };
32
- result?: { type?: string; value?: unknown };
33
- };
34
-
35
- type ResultPart = Part & { result?: { type?: string; value?: unknown } };
36
-
37
- /** OpenCode v2 `tool-result` value: text, json, error or content parts. */
38
- type ToolResultValue = { type?: string; value?: unknown } | undefined;
39
-
40
- function messageRole(message: unknown): string | undefined {
41
- const role = (message as { role?: unknown } | undefined)?.role;
42
- return typeof role === "string" ? role : undefined;
43
- }
44
-
45
- /** Text of a tool result in either the request shape or the native one. */
46
- function textOfContent(content: unknown): string {
47
- if (typeof content === "string") return content;
48
- if (!Array.isArray(content)) return "";
49
- let text = "";
50
- for (const part of content as Part[]) {
51
- if (typeof part?.text === "string") text += part.text;
52
- }
53
- return text;
54
- }
55
-
56
- /**
57
- * Renders an OpenCode v2 `tool-result` value as text. Media parts (files,
58
- * images) are never rendered: pruning them would destroy the payload instead of
59
- * shortening prose.
60
- */
61
- function textOfResult(result: ToolResultValue): string | undefined {
62
- if (!result || typeof result !== "object") return undefined;
63
- if (result.type === "content") {
64
- if (!Array.isArray(result.value)) return undefined;
65
- let text = "";
66
- for (const part of result.value as Part[]) {
67
- if (part?.type === "file") return undefined;
68
- if (typeof part?.text === "string") text += part.text;
69
- }
70
- return text;
71
- }
72
- if (typeof result.value === "string") return result.value;
73
- if (result.value === undefined || result.value === null) return undefined;
74
- try {
75
- return JSON.stringify(result.value);
76
- } catch {
77
- return undefined;
78
- }
79
- }
80
-
81
- function onlyTextParts(content: unknown): boolean {
82
- if (!Array.isArray(content)) return false;
83
- return (content as Part[]).every(
84
- (part) => part?.type === "text" || typeof part?.text === "string",
85
- );
86
- }
87
-
88
- function stub(text: string): string {
89
- const head = text.slice(0, STUB_HEAD_CHARS);
90
- const tail =
91
- text.length > STUB_HEAD_CHARS + STUB_TAIL_CHARS
92
- ? text.slice(-STUB_TAIL_CHARS)
93
- : "";
94
- const cut = text.length - head.length - tail.length;
95
- const note = `[... ${cut} characters of this tool result were pruned so the prompt stays readable; call the tool again if you need them]`;
96
- return tail ? `${head}\n${note}\n${tail}` : `${head}\n${note}`;
97
- }
98
-
99
- /**
100
- * The same message with its tool result collapsed, or `undefined` when the
101
- * message has nothing worth pruning. The native v2 shape (`tool-result` parts
102
- * with `result.value`) is the one OpenCode sends; the OpenAI-style shapes are
103
- * accepted too so a provider-lowered list is handled the same way.
104
- */
105
- function shrunk(message: unknown): unknown | undefined {
106
- const role = messageRole(message);
107
- const record = message as Record<string, unknown> & {
108
- content?: unknown;
109
- };
110
-
111
- if (role === "tool") {
112
- if (typeof record.content === "string") {
113
- return record.content.length < MIN_PRUNE_CHARS
114
- ? undefined
115
- : { ...record, content: stub(record.content) };
116
- }
117
- if (!Array.isArray(record.content)) return undefined;
118
- const parts = record.content as ResultPart[];
119
- if (parts.length === 0) return undefined;
120
-
121
- // Legacy/OpenAI-style text parts.
122
- if (onlyTextParts(parts)) {
123
- const text = textOfContent(parts);
124
- if (text.length < MIN_PRUNE_CHARS) return undefined;
125
- return { ...record, content: stub(text) };
126
- }
127
-
128
- let changed = false;
129
- const next = parts.map((part) => {
130
- if (part?.type !== "tool-result") return part;
131
- const text = textOfResult(part.result);
132
- if (!text || text.length < MIN_PRUNE_CHARS) return part;
133
- changed = true;
134
- return { ...part, result: { type: "text", value: stub(text) } };
135
- });
136
- return changed ? { ...record, content: next } : undefined;
137
- }
138
-
139
- if (role !== "assistant" || !Array.isArray(record.content)) return undefined;
140
- const parts = record.content as Part[];
141
- let changed = false;
142
- const next = parts.map((part) => {
143
- if (part?.type !== "tool" || !part.state) return part;
144
- const text = textOfContent(part.state.content);
145
- if (text.length < MIN_PRUNE_CHARS) return part;
146
- changed = true;
147
- return {
148
- ...part,
149
- state: { ...part.state, content: [{ type: "text", text: stub(text) }] },
150
- };
151
- });
152
- return changed ? { ...record, content: next } : undefined;
153
- }
154
-
155
- /**
156
- * Collapses stale tool results until the request fits `budget` tokens. The
157
- * newest messages (up to half the budget) are protected so the model always
158
- * sees what it was doing. Returns the same list untouched when it already fits.
159
- */
160
- export function pruneStaleToolResults(
161
- messages: readonly unknown[],
162
- budget: number,
163
- estimate: (message: unknown) => number,
164
- ): DietResult {
165
- const tokensBefore = messages.reduce<number>(
166
- (sum, message) => sum + estimate(message),
167
- 0,
168
- );
169
- if (messages.length === 0 || !(budget > 0) || tokensBefore <= budget) {
170
- return { messages, pruned: 0, tokensBefore, tokensAfter: tokensBefore };
171
- }
172
-
173
- const sizes = messages.map(estimate);
174
- let protectedStart = messages.length;
175
- let tail = 0;
176
- for (let index = messages.length - 1; index >= 0; index -= 1) {
177
- const size = sizes[index]!;
178
- if (tail > 0 && tail + size > budget * 0.5) break;
179
- tail += size;
180
- protectedStart = index;
181
- }
182
-
183
- const out = [...messages];
184
- let total = tokensBefore;
185
- let pruned = 0;
186
- for (let index = 0; index < protectedStart && total > budget; index += 1) {
187
- const smaller = shrunk(out[index]);
188
- if (!smaller) continue;
189
- const size = estimate(smaller);
190
- if (size >= sizes[index]!) continue;
191
- total -= sizes[index]! - size;
192
- sizes[index] = size;
193
- out[index] = smaller;
194
- pruned += 1;
195
- }
196
-
197
- if (pruned === 0) {
198
- return { messages, pruned: 0, tokensBefore, tokensAfter: tokensBefore };
199
- }
200
- return { messages: out, pruned, tokensBefore, tokensAfter: total };
201
- }
@@ -1,90 +0,0 @@
1
- /**
2
- * Builds session titles locally.
3
- *
4
- * free-pi charges credits and shows ads per model request, and the CLI never
5
- * spends a turn on a title. OpenCode asks the selected model for a title, so
6
- * the title hook answers from the first user message instead: the session gets
7
- * a real name immediately, no ad is fetched, and a failed title request can
8
- * never leave the session stuck on "New session".
9
- */
10
-
11
- const MAX_TITLE_LENGTH = 60;
12
- const MAX_SOURCE_LENGTH = 4_000;
13
- const MESSAGE_BLOCK = /<message>([\s\S]*?)<\/message>/i;
14
- const CONVERSATION_BLOCK = /<conversation>([\s\S]*?)<\/conversation>/i;
15
- const PREFIX = /^(?:original request|recent conversation|user|assistant)\s*:\s*/i;
16
- const NOISE = /^(?:```[\w-]*|---+|===+|\*\*\*+)$/;
17
- const XML_LINE = /^<\/?[a-z][^>]*>$/i;
18
- const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
19
-
20
- type TitleMessage = {
21
- role?: unknown;
22
- type?: unknown;
23
- text?: unknown;
24
- content?: unknown;
25
- };
26
-
27
- function textOf(content: unknown): string {
28
- if (typeof content === "string") return content;
29
- if (!Array.isArray(content)) return "";
30
- return content
31
- .filter(
32
- (part: any) => part?.type === "text" && typeof part.text === "string",
33
- )
34
- .map((part: any) => part.text)
35
- .join("\n");
36
- }
37
-
38
- function latestUserText(messages: readonly TitleMessage[]): string {
39
- for (let index = messages.length - 1; index >= 0; index -= 1) {
40
- const message = messages[index];
41
- const role = message?.role ?? message?.type;
42
- if (role !== "user") continue;
43
- const text =
44
- typeof message?.text === "string"
45
- ? message.text
46
- : textOf(message?.content);
47
- if (text.trim()) return text;
48
- }
49
- return "";
50
- }
51
-
52
- /** OpenCode wraps the source in `<message>` or `<conversation>` tags. */
53
- function sourceText(messages: readonly TitleMessage[]): string {
54
- const raw = latestUserText(messages);
55
- const block =
56
- MESSAGE_BLOCK.exec(raw)?.[1] ?? CONVERSATION_BLOCK.exec(raw)?.[1] ?? raw;
57
- return block.slice(0, MAX_SOURCE_LENGTH);
58
- }
59
-
60
- function cleanLine(line: string): string | undefined {
61
- let value = line.replace(CONTROL, " ").trim();
62
- if (!value) return undefined;
63
- value = value
64
- .replace(/^#{1,6}\s+/, "")
65
- .replace(/^[-*+>]\s+/, "")
66
- .trim();
67
- value = value.replace(PREFIX, "").trim();
68
- if (!value || NOISE.test(value) || XML_LINE.test(value)) return undefined;
69
- value = value.replace(/^["'`]+|["'`]+$/g, "").trim();
70
- return value || undefined;
71
- }
72
-
73
- function truncate(value: string): string {
74
- if (value.length <= MAX_TITLE_LENGTH) return value;
75
- const cut = value.slice(0, MAX_TITLE_LENGTH - 3);
76
- const space = cut.lastIndexOf(" ");
77
- return `${(space >= 20 ? cut.slice(0, space) : cut).trimEnd()}...`;
78
- }
79
-
80
- /** Derives a title from the first meaningful line of the title request. */
81
- export function localTitle(messages: readonly TitleMessage[] | undefined): string {
82
- if (!Array.isArray(messages) || messages.length === 0) return "Session";
83
- const lines = sourceText(messages)
84
- .split(/\r?\n/)
85
- .map(cleanLine)
86
- .filter((line): line is string => Boolean(line));
87
- const first = lines[0];
88
- if (!first) return "Session";
89
- return truncate(first.replace(/[\s:;,\-]+$/g, "").trim()) || "Session";
90
- }
@@ -1,46 +0,0 @@
1
- /** Tracks the last request's model and token usage and refreshes quota. */
2
-
3
- import { fetchQuota } from "../api/quota.js";
4
- import { QUOTA_REFRESH_DEBOUNCE_MS } from "../constants.js";
5
- import type { Deps } from "../deps.js";
6
- import type { TokenUsageLike } from "../types.js";
7
- import { trimMap } from "../utils/async.js";
8
- import { touchSessionActivity } from "./track.js";
9
-
10
- export function rememberTrackedModel(
11
- deps: Deps,
12
- sessionID: string,
13
- providerID: string,
14
- modelID: string,
15
- ): void {
16
- trimMap(deps.state.trackedModels, 200);
17
- deps.state.trackedModels.set(sessionID, { providerID, modelID });
18
- }
19
-
20
- export function recordUsage(
21
- deps: Deps,
22
- sessionID: string,
23
- cost: number,
24
- tokens: TokenUsageLike | undefined,
25
- ): void {
26
- if (typeof sessionID !== "string" || !sessionID) return;
27
- touchSessionActivity(deps, sessionID);
28
- const tracked = deps.state.trackedModels.get(sessionID);
29
- deps.state.lastUsage = {
30
- at: Date.now(),
31
- messageID: "",
32
- providerID: tracked?.providerID ?? "",
33
- modelID: tracked?.modelID ?? "",
34
- cost: typeof cost === "number" ? cost : 0,
35
- input: tokens?.input ?? 0,
36
- output: tokens?.output ?? 0,
37
- reasoning: tokens?.reasoning ?? 0,
38
- cacheRead: tokens?.cache?.read ?? 0,
39
- cacheWrite: tokens?.cache?.write ?? 0,
40
- };
41
-
42
- const now = Date.now();
43
- if (now - deps.state.lastQuotaRefreshAt < QUOTA_REFRESH_DEBOUNCE_MS) return;
44
- deps.state.lastQuotaRefreshAt = now;
45
- void fetchQuota(deps, { force: true }).catch(() => undefined);
46
- }