@eduardo191labs/opencode-free-pi 0.7.27 → 0.7.30

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.
@@ -1,354 +0,0 @@
1
- /**
2
- * Native OpenCode agents for free-pi.
3
- *
4
- * The provider CLI ships four agent personalities (scout, planner, worker,
5
- * reviewer) with their own prompts and tool access. OpenCode's V2 plugin API
6
- * cannot add agents through `AgentEditor`, but it loads Markdown agents from the
7
- * global config directory. Installing those files is the supported way to map
8
- * the CLI agents onto OpenCode's native `subagent` tool, so child sessions,
9
- * background reports, permissions and the agent picker keep working normally.
10
- *
11
- * They use `mode: all`: OpenCode only lists non-subagent agents in the `/agents`
12
- * picker, and only agents whose mode is not `primary` can run through the
13
- * `subagent` tool. `all` satisfies both, so the same personalities are
14
- * selectable as the main agent and spawnable as children.
15
- *
16
- * Files live under `agents/free-pi/`, which makes their IDs `free-pi/scout`,
17
- * `free-pi/planner`, `free-pi/worker` and `free-pi/reviewer`.
18
- */
19
-
20
- import { mkdir, readFile, writeFile } from "node:fs/promises";
21
- import { homedir } from "node:os";
22
- import { dirname, join } from "node:path";
23
-
24
- const MARKER =
25
- "<!-- managed by @eduardo191labs/opencode-free-pi; delete this line to keep your own copy -->";
26
-
27
- export const FREE_PI_AGENT_IDS = [
28
- "free-pi/scout",
29
- "free-pi/planner",
30
- "free-pi/worker",
31
- "free-pi/reviewer",
32
- ] as const;
33
-
34
- export type FreePiAgentID = (typeof FREE_PI_AGENT_IDS)[number];
35
-
36
- export const FREE_PI_SKILL_ID = "free-pi";
37
- export const FREE_PI_SKILL_NAME = "free-pi";
38
- export const FREE_PI_SKILL_DESCRIPTION =
39
- "How free-pi works in OpenCode: its tools, the installed native subagents, allowance and limits, and where sessions and memory live.";
40
-
41
- export const FREE_PI_SKILL = `# free-pi in OpenCode
42
-
43
- free-pi is a free, ad-supported provider for OpenCode. You sign in with GitHub
44
- and ads in the session pay for the inference; there is no model API key. The
45
- free daily allowance is shared by every free-pi model and every tool that spends
46
- it.
47
-
48
- ## Tools
49
- - \`free_pi_usage\` shows today's remaining allowance, credits, token counts and
50
- the account tier. Read-only.
51
- - \`free_pi_subagent_read\` reads the transcript of a child session started with
52
- the \`subagent\` tool: its prompts, every tool call with input and result, and
53
- its final answer. Read-only; omit \`sessionID\` to list this session's children.
54
- - \`look_at_image\` asks a vision model about a PNG, JPEG or WebP inside the
55
- project. Use it when the current model takes text only, or when the image is a
56
- file on disk and you want a targeted answer instead of attaching it.
57
- - \`generate_image\` draws one image from a prompt and saves it under \`images/\`.
58
- - \`web_search\` searches the web for current information.
59
- - \`docs_lookup\` looks up current library and framework documentation.
60
-
61
- Every tool except \`free_pi_usage\` spends allowance. Usage limits
62
- (\`daily_cap\`, \`rolling_cap\`, concurrency) are terminal: stop and continue
63
- without the tool instead of retrying.
64
-
65
- ## Subagents
66
-
67
- Use OpenCode's native subagent tool with the agents this plugin installs:
68
-
69
- | Agent | Use it for |
70
- | --- | --- |
71
- | \`free-pi/scout\` | Read-only recon: locate code and return structured findings. |
72
- | \`free-pi/planner\` | Read-only plan for a change, ready for a worker. |
73
- | \`free-pi/worker\` | Carry out one full task in its own context window. |
74
- | \`free-pi/reviewer\` | Read-only review with file and line references. |
75
-
76
- Subagents inherit the free-pi model, share the same daily allowance, and run as
77
- child sessions in the background. Keep large exploration in a subagent so it
78
- does not fill your own context. Use OpenCode's agent picker or the \`subagent\`
79
- tool; do not try to launch them through shell commands. The \`subagent\` tool
80
- returns the child \`sessionID\` and OpenCode injects the child's report when it
81
- goes idle; call \`free_pi_subagent_read\` with that id to see what the child ran
82
- and why its answer says what it says.
83
-
84
- ## Memory and sessions
85
-
86
- OpenCode owns memory and context: \`AGENTS.md\` and configured instruction files
87
- are loaded natively, sessions persist and resume, and compaction folds long
88
- conversations into a summary. Put durable project facts in \`AGENTS.md\` (or a
89
- file listed under \`instructions\`) instead of repeating them in every prompt.
90
-
91
- ## Native integrations
92
-
93
- MCP servers, skills, commands, references and permissions are configured in
94
- OpenCode as usual; free-pi does not replace them. Prefer those native features
95
- over running an external CLI.
96
- `;
97
-
98
- /**
99
- * The same skill as a native `SKILL.md`. OpenCode discovers it from the global
100
- * skills directory, so the file, its ID, its permissions and the `skill` tool
101
- * all belong to OpenCode instead of a runtime registration.
102
- */
103
- export const FREE_PI_SKILL_FILE = `---
104
- name: ${FREE_PI_SKILL_NAME}
105
- description: ${FREE_PI_SKILL_DESCRIPTION}
106
- ---
107
-
108
- ${MARKER}
109
-
110
- ${FREE_PI_SKILL}`;
111
-
112
- const SCOUT = `---
113
- description: Read-only recon. Locates code, traces how pieces connect, and returns structured findings the lead can use without re-reading the files.
114
- mode: all
115
- color: "#4cc9f0"
116
- permissions:
117
- - action: edit
118
- resource: "*"
119
- effect: deny
120
- - action: shell
121
- resource: "*"
122
- effect: deny
123
- - action: subagent
124
- resource: "*"
125
- effect: deny
126
- ---
127
-
128
- ${MARKER}
129
-
130
- You are a scout. Quickly investigate a codebase and return structured findings
131
- that another agent can use without re-reading everything. Your output goes to an
132
- agent who has NOT seen the files you explored.
133
-
134
- Use read, grep and glob to locate relevant code; read key sections (not whole
135
- files); note types, key functions, and how pieces connect. Do not modify files.
136
-
137
- Output format:
138
- ## Files Retrieved
139
- 1. \`path/to/file.ts\` (lines 10-50) - what is here
140
- ## Key Code
141
- The critical types, interfaces, or functions, quoted from the files.
142
- ## Architecture
143
- How the pieces connect, briefly.
144
- ## Start Here
145
- Which file to look at first and why.
146
- `;
147
-
148
- const PLANNER = `---
149
- description: Turns context and requirements into a concrete implementation plan. Read-only: never edits files or runs commands.
150
- mode: all
151
- color: "#b5179e"
152
- permissions:
153
- - action: edit
154
- resource: "*"
155
- effect: deny
156
- - action: shell
157
- resource: "*"
158
- effect: deny
159
- - action: subagent
160
- resource: "*"
161
- effect: deny
162
- ---
163
-
164
- ${MARKER}
165
-
166
- You are a planning specialist. You receive context and requirements, then
167
- produce a clear implementation plan. You must NOT make any changes. Only read,
168
- analyze, and plan.
169
-
170
- Output format:
171
- ## Goal
172
- One sentence.
173
- ## Plan
174
- Numbered steps, each small and actionable, naming the file or function to change.
175
- ## Files to Modify
176
- ## New Files (if any)
177
- ## Risks
178
- Keep the plan concrete: a worker agent will execute it verbatim.
179
- `;
180
-
181
- const WORKER = `---
182
- description: Full-capability worker that carries out one delegated task in its own context window and reports what changed.
183
- mode: all
184
- color: "#2a9d8f"
185
- permissions:
186
- - action: subagent
187
- resource: "*"
188
- effect: deny
189
- ---
190
-
191
- ${MARKER}
192
-
193
- You are a worker agent with full capabilities, working in an isolated context
194
- window on a task delegated by the lead. Work autonomously to complete it.
195
-
196
- Do not start other subagents.
197
-
198
- Output format when finished:
199
- ## Completed
200
- What was done.
201
- ## Files Changed
202
- - \`path/to/file.ts\` - what changed
203
- ## Notes (if any)
204
- Anything the lead should know.
205
- `;
206
-
207
- const REVIEWER = `---
208
- description: Senior code reviewer for quality, security and maintainability. Read-only; reports findings with file and line references.
209
- mode: all
210
- color: "#e76f51"
211
- permissions:
212
- - action: edit
213
- resource: "*"
214
- effect: deny
215
- - action: shell
216
- resource: "*"
217
- effect: deny
218
- - action: shell
219
- resource: "git diff*"
220
- effect: allow
221
- - action: shell
222
- resource: "git log*"
223
- effect: allow
224
- - action: shell
225
- resource: "git show*"
226
- effect: allow
227
- - action: shell
228
- resource: "git status*"
229
- effect: allow
230
- - action: subagent
231
- resource: "*"
232
- effect: deny
233
- ---
234
-
235
- ${MARKER}
236
-
237
- You are a senior code reviewer. Analyze code for quality, security, and
238
- maintainability.
239
-
240
- Bash is for read-only commands only: \`git diff\`, \`git log\`, \`git show\`.
241
- Do NOT modify files or run builds. Assume tool permissions are not perfectly
242
- enforceable; keep all bash usage strictly read-only.
243
-
244
- Strategy: run \`git diff\` to see recent changes (if applicable), read the
245
- modified files, check for bugs, security issues, and code smells.
246
-
247
- Output format:
248
- ## Files Reviewed
249
- ## Critical (must fix)
250
- - \`file.ts:42\` - issue
251
- ## Warnings (should fix)
252
- ## Suggestions (consider)
253
- ## Summary
254
- Overall assessment in 2-3 sentences. Be specific with file paths and line
255
- numbers.
256
- `;
257
-
258
- const AGENT_FILES: ReadonlyArray<{ id: FreePiAgentID; content: string }> = [
259
- { id: "free-pi/scout", content: SCOUT },
260
- { id: "free-pi/planner", content: PLANNER },
261
- { id: "free-pi/worker", content: WORKER },
262
- { id: "free-pi/reviewer", content: REVIEWER },
263
- ];
264
-
265
- /** OpenCode's user-wide config directory, where it loads custom agents. */
266
- export function openCodeConfigDir(): string {
267
- const explicit = process.env.OPENCODE_CONFIG_DIR?.trim();
268
- if (explicit) return explicit;
269
- const xdg = process.env.XDG_CONFIG_HOME?.trim();
270
- if (xdg) return join(xdg, "opencode");
271
- return join(homedir(), ".config", "opencode");
272
- }
273
-
274
- export function freePiAgentPath(configDir: string, id: FreePiAgentID): string {
275
- return join(configDir, "agents", ...id.split("/")) + ".md";
276
- }
277
-
278
- export function freePiSkillPath(configDir: string): string {
279
- return join(configDir, "skills", FREE_PI_SKILL_ID, "SKILL.md");
280
- }
281
-
282
- async function fileState(
283
- path: string,
284
- content: string,
285
- ): Promise<"write" | "same" | "protected"> {
286
- try {
287
- const current = await readFile(path, "utf8");
288
- if (current === content) return "same";
289
- // The user replaced or edited this file; never overwrite their work.
290
- return current.slice(0, 1024).includes(MARKER) ? "write" : "protected";
291
- } catch {
292
- return "write";
293
- }
294
- }
295
-
296
- export type AgentInstallResult = {
297
- readonly installed: FreePiAgentID[];
298
- readonly skipped: FreePiAgentID[];
299
- readonly changed: boolean;
300
- };
301
-
302
- /**
303
- * Writes the bundled agents into the OpenCode config directory so OpenCode's
304
- * own loader and agent picker own them. Existing files without our marker are
305
- * treated as user-owned and left untouched.
306
- */
307
- export async function installFreePiAgents(
308
- configDir = openCodeConfigDir(),
309
- ): Promise<AgentInstallResult> {
310
- const installed: FreePiAgentID[] = [];
311
- const skipped: FreePiAgentID[] = [];
312
-
313
- for (const agent of AGENT_FILES) {
314
- const path = freePiAgentPath(configDir, agent.id);
315
- const state = await fileState(path, agent.content);
316
- if (state === "same") continue;
317
- if (state === "protected") {
318
- skipped.push(agent.id);
319
- continue;
320
- }
321
- await mkdir(dirname(path), { recursive: true });
322
- await writeFile(path, agent.content, "utf8");
323
- installed.push(agent.id);
324
- }
325
-
326
- return { installed, skipped, changed: installed.length > 0 };
327
- }
328
-
329
- export type SkillInstallResult = {
330
- readonly installed: boolean;
331
- readonly skipped: boolean;
332
- readonly changed: boolean;
333
- };
334
-
335
- /**
336
- * Writes the free-pi skill as `skills/free-pi/SKILL.md`, the layout OpenCode's
337
- * own skill loader reads. A file without our marker is user-owned and stays
338
- * untouched, exactly like the agent files.
339
- */
340
- export async function installFreePiSkill(
341
- configDir = openCodeConfigDir(),
342
- ): Promise<SkillInstallResult> {
343
- const path = freePiSkillPath(configDir);
344
- const state = await fileState(path, FREE_PI_SKILL_FILE);
345
- if (state === "same") {
346
- return { installed: false, skipped: false, changed: false };
347
- }
348
- if (state === "protected") {
349
- return { installed: false, skipped: true, changed: false };
350
- }
351
- await mkdir(dirname(path), { recursive: true });
352
- await writeFile(path, FREE_PI_SKILL_FILE, "utf8");
353
- return { installed: true, skipped: false, changed: true };
354
- }
@@ -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
- }