@eduardo191labs/opencode-free-pi 0.6.6 → 0.6.8

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.
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `free_pi_subagent_read`, a transcript reader for child sessions.
3
+ *
4
+ * OpenCode's `subagent` tool reports the child's final output and pings the
5
+ * parent when the child goes idle, but the parent cannot open the child's
6
+ * conversation afterwards. This tool fills that gap: it reads the transcript
7
+ * of a session that is really a child of the calling session, so the parent can
8
+ * see every task the subagent ran (tool calls with input and result) and quote
9
+ * its answer.
10
+ *
11
+ * Read-only. The session is checked against its `parentID`, so a model cannot
12
+ * use it to read unrelated sessions.
13
+ */
14
+ import type { Plugin } from "@opencode/plugin";
15
+ import type { Deps } from "../deps.js";
16
+ export type Transcript = {
17
+ readonly text: string;
18
+ readonly messages: number;
19
+ readonly truncated: boolean;
20
+ };
21
+ /**
22
+ * Renders a session transcript, keeping the newest turns when it does not fit.
23
+ * The final assistant text is repeated at the end so the parent can quote it
24
+ * even when the middle of the transcript was dropped.
25
+ */
26
+ export declare function formatTranscript(messages: readonly unknown[], maxChars?: number): Transcript;
27
+ export declare function registerSubagentTool(ctx: Plugin.Context, deps: Deps): Promise<{
28
+ dispose: () => Promise<void>;
29
+ }>;
@@ -0,0 +1,197 @@
1
+ /**
2
+ * `free_pi_subagent_read`, a transcript reader for child sessions.
3
+ *
4
+ * OpenCode's `subagent` tool reports the child's final output and pings the
5
+ * parent when the child goes idle, but the parent cannot open the child's
6
+ * conversation afterwards. This tool fills that gap: it reads the transcript
7
+ * of a session that is really a child of the calling session, so the parent can
8
+ * see every task the subagent ran (tool calls with input and result) and quote
9
+ * its answer.
10
+ *
11
+ * Read-only. The session is checked against its `parentID`, so a model cannot
12
+ * use it to read unrelated sessions.
13
+ */
14
+ import { done, fail, GATED_TEXT, isGatedSession } from "./api.js";
15
+ const DEFAULT_MAX_CHARS = 60_000;
16
+ const MIN_MAX_CHARS = 2_000;
17
+ const MAX_MAX_CHARS = 200_000;
18
+ const TOOL_RESULT_CHARS = 2_000;
19
+ const TOOL_INPUT_CHARS = 1_500;
20
+ const USER_TEXT_CHARS = 8_000;
21
+ const ASSISTANT_TEXT_CHARS = 16_000;
22
+ const INPUT_SCHEMA = {
23
+ type: "object",
24
+ additionalProperties: false,
25
+ properties: {
26
+ sessionID: {
27
+ type: "string",
28
+ description: "Child session to read, as returned by the `subagent` tool. Omit it to list this session's children.",
29
+ },
30
+ maxChars: {
31
+ type: "integer",
32
+ minimum: MIN_MAX_CHARS,
33
+ maximum: MAX_MAX_CHARS,
34
+ description: `Transcript budget in characters (default ${DEFAULT_MAX_CHARS}). The newest turns are kept.`,
35
+ },
36
+ },
37
+ };
38
+ function cut(value, limit) {
39
+ const text = value.trim();
40
+ if (text.length <= limit)
41
+ return text;
42
+ return `${text.slice(0, limit)}\n[... ${text.length - limit} characters cut]`;
43
+ }
44
+ function stringify(value) {
45
+ if (typeof value === "string")
46
+ return value;
47
+ try {
48
+ return JSON.stringify(value, null, 2) ?? "";
49
+ }
50
+ catch {
51
+ return String(value ?? "");
52
+ }
53
+ }
54
+ function textOfContent(content) {
55
+ if (typeof content === "string")
56
+ return content;
57
+ if (!Array.isArray(content))
58
+ return "";
59
+ return content
60
+ .filter((part) => part?.type === "text" && part.synthetic !== true)
61
+ .map((part) => part.text ?? "")
62
+ .join("\n");
63
+ }
64
+ function formatTool(part) {
65
+ const status = part.state?.status ?? "unknown";
66
+ const header = `[tool ${part.name ?? "?"}] ${status}`;
67
+ const input = stringify(part.state?.input ?? {});
68
+ const output = textOfContent(part.state?.content);
69
+ return [
70
+ header,
71
+ `input: ${cut(input, TOOL_INPUT_CHARS)}`,
72
+ ...(output.trim() ? [`result: ${cut(output, TOOL_RESULT_CHARS)}`] : []),
73
+ ].join("\n");
74
+ }
75
+ function formatMessage(message) {
76
+ const role = message.role ?? message.type;
77
+ if (role === "user") {
78
+ const text = message.text ?? textOfContent(message.content);
79
+ return text.trim() ? `[user]\n${cut(text, USER_TEXT_CHARS)}` : "";
80
+ }
81
+ if (role !== "assistant")
82
+ return "";
83
+ const blocks = [];
84
+ const content = Array.isArray(message.content) ? message.content : [];
85
+ for (const part of content) {
86
+ if (part?.type === "text" && part.synthetic !== true) {
87
+ const text = part.text ?? "";
88
+ if (text.trim())
89
+ blocks.push(cut(text, ASSISTANT_TEXT_CHARS));
90
+ }
91
+ else if (part?.type === "tool") {
92
+ blocks.push(formatTool(part));
93
+ }
94
+ }
95
+ if (blocks.length === 0)
96
+ return "";
97
+ const finish = message.finish && message.finish !== "stop" ? ` (${message.finish})` : "";
98
+ return `[assistant${message.agent ? ` ${message.agent}` : ""}]${finish}\n${blocks.join("\n\n")}`;
99
+ }
100
+ /**
101
+ * Renders a session transcript, keeping the newest turns when it does not fit.
102
+ * The final assistant text is repeated at the end so the parent can quote it
103
+ * even when the middle of the transcript was dropped.
104
+ */
105
+ export function formatTranscript(messages, maxChars = DEFAULT_MAX_CHARS) {
106
+ const budget = Math.max(MIN_MAX_CHARS, Math.min(maxChars, MAX_MAX_CHARS));
107
+ const entries = messages
108
+ .map(formatMessage)
109
+ .filter((entry) => entry.length > 0);
110
+ let text = entries.join("\n\n");
111
+ if (text.length <= budget) {
112
+ return { text, messages: entries.length, truncated: false };
113
+ }
114
+ const kept = [];
115
+ let size = 0;
116
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
117
+ const entry = entries[index];
118
+ if (size + entry.length + 2 > budget)
119
+ break;
120
+ kept.unshift(entry);
121
+ size += entry.length + 2;
122
+ }
123
+ const dropped = entries.length - kept.length;
124
+ const notice = `[... ${dropped} older transcript block${dropped === 1 ? "" : "s"} omitted to stay inside ${budget} characters; pass a larger maxChars to see them]`;
125
+ text = [notice, ...kept].join("\n\n");
126
+ return { text, messages: entries.length, truncated: true };
127
+ }
128
+ function listLine(session) {
129
+ const when = session.updated
130
+ ? new Date(session.updated).toISOString()
131
+ : "unknown time";
132
+ return `- ${session.id} - ${session.title ?? "(untitled)"} - agent ${session.agent ?? "?"} - ${session.outcome ?? "unknown"} - updated ${when}`;
133
+ }
134
+ async function execute(deps, raw, context) {
135
+ if (!isGatedSession(deps, context.sessionID))
136
+ return fail(GATED_TEXT);
137
+ const input = (raw ?? {});
138
+ const requested = typeof input.sessionID === "string" && input.sessionID.trim()
139
+ ? input.sessionID.trim()
140
+ : undefined;
141
+ if (!requested) {
142
+ const children = deps.listSubagentSessions
143
+ ? await deps.listSubagentSessions(context.sessionID).catch(() => [])
144
+ : [];
145
+ if (children.length === 0) {
146
+ return done("This session has no child sessions yet. The `subagent` tool returns a sessionID when a child starts.", { ok: true, children: 0 });
147
+ }
148
+ return done(["Child sessions of this session:", ...children.map(listLine)].join("\n"), { ok: true, children: children.length });
149
+ }
150
+ if (!deps.readSession) {
151
+ return fail("Reading subagent sessions is not available in this OpenCode build.");
152
+ }
153
+ const info = await deps.readSession(requested).catch(() => undefined);
154
+ if (!info)
155
+ return fail(`No OpenCode session with id ${requested}.`);
156
+ if (info.parentID !== context.sessionID) {
157
+ return fail(`${requested} is not a subagent of this session, so its transcript cannot be read here.`);
158
+ }
159
+ const messages = await deps.readContext(requested).catch(() => []);
160
+ if (messages.length === 0) {
161
+ return done(`The subagent session ${requested} has no messages yet. It may still be starting.`, { ok: false, sessionID: requested, messages: 0 });
162
+ }
163
+ const budget = typeof input.maxChars === "number" && Number.isFinite(input.maxChars)
164
+ ? input.maxChars
165
+ : DEFAULT_MAX_CHARS;
166
+ const transcript = formatTranscript(messages, budget);
167
+ const header = [
168
+ `Subagent session ${requested}${info.title ? ` - ${info.title}` : ""}`,
169
+ `agent: ${info.agent ?? "?"} - outcome: ${info.outcome ?? "running"} - stored messages: ${messages.length}`,
170
+ ].join("\n");
171
+ deps.log.info("free_pi_subagent_read answered", {
172
+ sessionID: context.sessionID,
173
+ child: requested,
174
+ messages: transcript.messages,
175
+ truncated: transcript.truncated,
176
+ });
177
+ return done(`${header}\n\n${transcript.text}`, {
178
+ ok: true,
179
+ sessionID: requested,
180
+ parentID: info.parentID,
181
+ agent: info.agent,
182
+ outcome: info.outcome,
183
+ messages: transcript.messages,
184
+ truncated: transcript.truncated,
185
+ });
186
+ }
187
+ export async function registerSubagentTool(ctx, deps) {
188
+ return ctx.tool.transform((editor) => {
189
+ editor.add({
190
+ name: "free_pi_subagent_read",
191
+ description: "Read the transcript of a subagent session started from this session: its prompts, tool calls with inputs and results, and final answer. Pass the child sessionID returned by `subagent`, or omit it to list this session's children. Read-only; only child sessions of the calling session are readable.",
192
+ input: INPUT_SCHEMA,
193
+ options: { codemode: false },
194
+ execute: (input, context) => execute(deps, input, context),
195
+ });
196
+ });
197
+ }
package/dist/types.d.ts CHANGED
@@ -290,3 +290,14 @@ export type SessionMessageInfo = {
290
290
  [key: string]: unknown;
291
291
  };
292
292
  export type ReadContext = (sessionID: string) => Promise<readonly SessionMessageInfo[]>;
293
+ /** Minimal view of an OpenCode V2 session header. */
294
+ export type SubagentSessionInfo = {
295
+ id: string;
296
+ parentID?: string;
297
+ title?: string;
298
+ agent?: string;
299
+ outcome?: string;
300
+ updated?: number;
301
+ };
302
+ export type ReadSessionInfo = (sessionID: string) => Promise<SubagentSessionInfo | undefined>;
303
+ export type ListSubagentSessions = (parentID: string) => Promise<readonly SubagentSessionInfo[]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.6.6",
3
+ "version": "0.6.8",
4
4
  "description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,7 +24,7 @@
24
24
  "scripts": {
25
25
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
26
26
  "typecheck": "tsc -p tsconfig.json --noEmit",
27
- "test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/tools.mjs",
27
+ "test": "npm run build && node test/catalog.mjs && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/agents.mjs && node test/wire.mjs && node test/tools.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },
@@ -48,6 +48,9 @@ it.
48
48
  ## Tools
49
49
  - \`free_pi_usage\` shows today's remaining allowance, credits, token counts and
50
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.
51
54
  - \`look_at_image\` asks a vision model about a PNG, JPEG or WebP inside the
52
55
  project. Use it when the current model takes text only, or when the image is a
53
56
  file on disk and you want a targeted answer instead of attaching it.
@@ -73,7 +76,10 @@ Use OpenCode's native subagent tool with the agents this plugin installs:
73
76
  Subagents inherit the free-pi model, share the same daily allowance, and run as
74
77
  child sessions in the background. Keep large exploration in a subagent so it
75
78
  does not fill your own context. Use OpenCode's agent picker or the \`subagent\`
76
- tool; do not try to launch them through shell commands.
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.
77
83
 
78
84
  ## Memory and sessions
79
85
 
@@ -2,11 +2,14 @@
2
2
 
3
3
  import { resolveToken } from "../auth/token.js";
4
4
  import {
5
+ CATALOG_ATTEMPTS,
6
+ CATALOG_RETRY_MS,
5
7
  CATALOG_TIMEOUT_MS,
6
8
  CATALOG_TTL_MS,
7
9
  } from "../constants.js";
8
10
  import type { Deps } from "../deps.js";
9
11
  import type { Catalog } from "../types.js";
12
+ import { sleep } from "../utils/async.js";
10
13
  import { resolveBaseUrl } from "../utils/urls.js";
11
14
 
12
15
  function isCatalog(value: unknown): value is Catalog {
@@ -43,33 +46,48 @@ export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
43
46
  const state = deps.state;
44
47
  if (state.catalogPromise) return state.catalogPromise;
45
48
  const pending = (async () => {
46
- try {
47
- const token = await resolveToken(deps).catch(() => undefined);
48
- const headers: Record<string, string> = {
49
- accept: "application/json",
50
- };
51
- if (token) headers.authorization = `Bearer ${token}`;
52
- const response = await fetch(`${resolveBaseUrl()}/client-version`, {
53
- headers,
54
- signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
55
- });
56
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
57
- const catalog = (await response.json()) as Catalog;
58
- if (!isCatalog(catalog)) {
59
- throw new Error("free-pi returned an unexpected catalog payload");
49
+ let lastError: unknown;
50
+ for (let attempt = 1; attempt <= CATALOG_ATTEMPTS; attempt += 1) {
51
+ try {
52
+ const token = await resolveToken(deps).catch(() => undefined);
53
+ const headers: Record<string, string> = {
54
+ accept: "application/json",
55
+ };
56
+ if (token) headers.authorization = `Bearer ${token}`;
57
+ const response = await fetch(`${resolveBaseUrl()}/client-version`, {
58
+ headers,
59
+ signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
60
+ });
61
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
62
+ const catalog = (await response.json()) as Catalog;
63
+ if (!isCatalog(catalog)) {
64
+ throw new Error("free-pi returned an unexpected catalog payload");
65
+ }
66
+ applyCatalog(deps, catalog);
67
+ return catalog;
68
+ } catch (error) {
69
+ lastError = error;
70
+ // A timeout or a dropped connection is often transient. Retrying here
71
+ // avoids registering a provider with zero models for this location,
72
+ // which would hide every free-pi model from the picker until OpenCode
73
+ // restarts.
74
+ if (attempt < CATALOG_ATTEMPTS) {
75
+ deps.log.info("free-pi catalog request failed; retrying", {
76
+ attempt,
77
+ reason: reasonText(error),
78
+ });
79
+ await sleep(CATALOG_RETRY_MS * attempt);
80
+ }
60
81
  }
61
- applyCatalog(deps, catalog);
62
- return catalog;
63
- } catch (error) {
64
- const cached = state.cachedCatalog;
65
- deps.log.warn(
66
- cached
67
- ? "free-pi catalog is unreachable; using the cached model list"
68
- : "free-pi catalog is unreachable; no free-pi models were registered",
69
- { reason: reasonText(error) },
70
- );
71
- return cached;
72
82
  }
83
+ const cached = state.cachedCatalog;
84
+ deps.log.warn(
85
+ cached
86
+ ? "free-pi catalog is unreachable; using the cached model list"
87
+ : "free-pi catalog is unreachable; no free-pi models were registered",
88
+ { reason: reasonText(lastError) },
89
+ );
90
+ return cached;
73
91
  })();
74
92
  state.catalogPromise = pending;
75
93
  void pending.finally(() => {
package/src/constants.ts CHANGED
@@ -77,7 +77,7 @@ export const FREE_PI_GUIDANCE = `# free-pi working rules
77
77
  - Read the files involved before editing and run the project's checks afterwards. Never say a test, build or command passed unless you ran it and saw it pass.
78
78
  - Treat the conversation above as memory: reuse earlier decisions, file paths, identifiers and results. If something is genuinely missing, say what is missing instead of guessing.
79
79
  - Use the available tools (read, grep, glob, bash, edit) for real work; do not describe hypothetical commands as if they ran.
80
- - Delegate large or self-contained work with OpenCode's native \`subagent\` tool: \`free-pi/scout\` and \`free-pi/planner\` for read-only recon and planning, \`free-pi/worker\` for a full task, \`free-pi/reviewer\` for review. A subagent runs in its own context and reports back; never launch a subagent from inside one.
80
+ - Delegate large or self-contained work with OpenCode's native \`subagent\` tool: \`free-pi/scout\` and \`free-pi/planner\` for read-only recon and planning, \`free-pi/worker\` for a full task, \`free-pi/reviewer\` for review. A subagent runs in its own context and reports back; never launch a subagent from inside one. The \`subagent\` tool returns a child \`sessionID\` and OpenCode injects the child's report when it goes idle; to inspect what that child actually did, call \`free_pi_subagent_read\` with its \`sessionID\` (omit it to list this session's children).
81
81
  - Load a skill with the native \`skill\` tool when its description matches the task.
82
82
  - \`AGENTS.md\` and the files listed under \`instructions\` are the project's memory. Follow them; do not restate or replace them.
83
83
  - Never claim to have compacted, summarized or cleared context unless that actually happened.
@@ -105,6 +105,16 @@ export const RETRY_MAX_RETRIES = 3;
105
105
  export const RETRY_BASE_DELAY_MS = 2_000;
106
106
  export const RETRY_MAX_DELAY_MS = 60_000;
107
107
 
108
+ /**
109
+ * Transport failures (a refused or dropped connection, DNS blips) usually
110
+ * clear on their own. OpenCode stops after its own retries, which can end a
111
+ * turn during a brief local network or service restart, so the plugin gives
112
+ * them a longer budget before giving up.
113
+ */
114
+ export const TRANSPORT_RETRY_MAX = 5;
115
+ export const TRANSPORT_RETRY_BASE_MS = 2_000;
116
+ export const TRANSPORT_RETRY_MAX_DELAY_MS = 30_000;
117
+
108
118
  /**
109
119
  * free-pi allows one in-flight request per `x-session-id` and answers a second
110
120
  * one with `429 concurrent`. OpenCode does not retry that itself, and a slot
@@ -138,6 +148,17 @@ export const CREDITS_PER_USD = 40_000 / 3;
138
148
 
139
149
  export const CATALOG_TTL_MS = 10 * 60_000;
140
150
  export const CATALOG_TIMEOUT_MS = 8_000;
151
+ export const CATALOG_ATTEMPTS = 2;
152
+ export const CATALOG_RETRY_MS = 1_000;
153
+ /**
154
+ * When the catalog cannot be fetched, the provider is registered with no models
155
+ * and the model picker loses every free-pi entry for that location. These are
156
+ * the delays before each background attempt to fetch it again and re-register
157
+ * the models, so a transient timeout heals without restarting OpenCode.
158
+ */
159
+ export const CATALOG_RECOVERY_DELAYS_MS = [
160
+ 2_000, 5_000, 10_000, 20_000, 30_000, 60_000,
161
+ ] as const;
141
162
  export const REGISTRY_TTL_MS = 5 * 60_000;
142
163
  export const REGISTRY_RETRY_MS = 60_000;
143
164
  export const REGISTRY_TIMEOUT_MS = 3_500;
package/src/deps.ts CHANGED
@@ -4,13 +4,20 @@ import type { Credential } from "@opencode/schema/credential";
4
4
  import type { Plugin } from "@opencode/plugin";
5
5
  import type { Logger } from "./logging.js";
6
6
  import type { RuntimeState } from "./state.js";
7
- import type { ReadContext } from "./types.js";
7
+ import type {
8
+ ListSubagentSessions,
9
+ ReadContext,
10
+ ReadSessionInfo,
11
+ } from "./types.js";
8
12
 
9
13
  export type Deps = {
10
14
  readonly state: RuntimeState;
11
15
  readonly log: Logger;
12
16
  readonly activeCredential: () => Promise<Credential.Value | undefined>;
13
17
  readonly readContext: ReadContext;
18
+ /** Session headers, used to prove a session is really this session's child. */
19
+ readonly readSession?: ReadSessionInfo;
20
+ readonly listSubagentSessions?: ListSubagentSessions;
14
21
  /** Plugin-scoped durable storage, used to reconnect provider sessions. */
15
22
  readonly storage?: Plugin.Context["storage"];
16
23
  };