@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.
package/src/plugin.ts CHANGED
@@ -33,6 +33,7 @@ import {
33
33
  import { fetchModelsRegistry } from "./catalog/registry.js";
34
34
  import { applyProvider } from "./catalog/v2.js";
35
35
  import {
36
+ CATALOG_RECOVERY_DELAYS_MS,
36
37
  DEFENSE_PROVIDER_ID,
37
38
  PROVIDER_ID,
38
39
  } from "./constants.js";
@@ -45,6 +46,7 @@ import { cancelAllFinalizeTimers } from "./session/track.js";
45
46
  import { createRuntimeState } from "./state.js";
46
47
  import { registerGenerateImageTool } from "./tools/image-generate.js";
47
48
  import { registerUsageTool } from "./tools/usage.js";
49
+ import { registerSubagentTool } from "./tools/subagent.js";
48
50
  import { registerVisionTool } from "./tools/vision.js";
49
51
  import { registerWebTools } from "./tools/web.js";
50
52
  import { settle } from "./utils/async.js";
@@ -77,6 +79,36 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
77
79
  return [];
78
80
  }
79
81
  },
82
+ readSession: async (sessionID) => {
83
+ try {
84
+ const info = await ctx.session.get({ sessionID });
85
+ return {
86
+ id: info.id,
87
+ parentID: info.parentID,
88
+ title: info.title,
89
+ agent: info.agent,
90
+ outcome: info.outcome,
91
+ updated: info.time?.updated,
92
+ };
93
+ } catch {
94
+ return undefined;
95
+ }
96
+ },
97
+ listSubagentSessions: async (parentID) => {
98
+ try {
99
+ const result = await ctx.session.list({ parentID, limit: 50 });
100
+ return (result.data ?? []).map((info) => ({
101
+ id: info.id,
102
+ parentID: info.parentID,
103
+ title: info.title,
104
+ agent: info.agent,
105
+ outcome: info.outcome,
106
+ updated: info.time?.updated,
107
+ }));
108
+ } catch {
109
+ return [];
110
+ }
111
+ },
80
112
  storage: ctx.storage,
81
113
  };
82
114
 
@@ -153,8 +185,9 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
153
185
  const access = accountAccess(quota?.me);
154
186
  const { main: catalogMain, defense: catalogDefense } =
155
187
  partitionModels(catalog);
156
- const main = filterAccessibleModels(catalogMain, access);
157
- const defense = filterAccessibleModels(catalogDefense, access);
188
+ let currentCatalog = catalog;
189
+ let currentMain = filterAccessibleModels(catalogMain, access);
190
+ let currentDefense = filterAccessibleModels(catalogDefense, access);
158
191
  const candidates = modelRegistryCandidates(registry);
159
192
  const live = await loadLiveLimits();
160
193
  const configuredEffort = ctx.options?.reasoningEffort;
@@ -166,21 +199,37 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
166
199
  ? { reasoningEffort: configuredEffort }
167
200
  : {}),
168
201
  };
169
- const mainModels = buildModels(main, candidates, buildOptions);
170
- const defenseModels = buildModels(defense, candidates, buildOptions);
171
202
 
172
- for (const [id, model] of Object.entries(mainModels)) {
173
- state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
174
- if (model.modalities.input.includes("image")) {
175
- state.imageModels.add(`${PROVIDER_ID}/${id}`);
203
+ // Rebuilt on every call so a learned context ceiling or a recovered catalog
204
+ // applies without restarting OpenCode.
205
+ const buildMain = () =>
206
+ buildModels(currentMain, candidates, {
207
+ ...buildOptions,
208
+ live: currentLiveLimits() ?? live,
209
+ });
210
+ const buildDefense = () =>
211
+ buildModels(currentDefense, candidates, {
212
+ ...buildOptions,
213
+ live: currentLiveLimits() ?? live,
214
+ });
215
+
216
+ function indexModelState(): void {
217
+ const mainNow = buildMain();
218
+ const defenseNow = buildDefense();
219
+ for (const [id, model] of Object.entries(mainNow)) {
220
+ state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
221
+ if (model.modalities.input.includes("image")) {
222
+ state.imageModels.add(`${PROVIDER_ID}/${id}`);
223
+ }
176
224
  }
177
- }
178
- for (const [id, model] of Object.entries(defenseModels)) {
179
- state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
180
- if (model.modalities.input.includes("image")) {
181
- state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
225
+ for (const [id, model] of Object.entries(defenseNow)) {
226
+ state.outputLimits.set(`${DEFENSE_PROVIDER_ID}/${id}`, model.limit.output);
227
+ if (model.modalities.input.includes("image")) {
228
+ state.imageModels.add(`${DEFENSE_PROVIDER_ID}/${id}`);
229
+ }
182
230
  }
183
231
  }
232
+ indexModelState();
184
233
 
185
234
  const credential = await deps.activeCredential().catch(() => undefined);
186
235
  state.providerToken =
@@ -189,25 +238,19 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
189
238
  await registerIntegration(ctx, deps);
190
239
 
191
240
  await ctx.provider.transform((editor) => {
192
- // Rebuilt on every transform so a learned context ceiling applies as soon
193
- // as the response hook records it, without restarting OpenCode.
194
- const active = currentLiveLimits() ?? live;
195
- const buildOptionsNow = { ...buildOptions, live: active };
196
- const mainNow = buildModels(main, candidates, buildOptionsNow);
197
- const defenseNow = buildModels(defense, candidates, buildOptionsNow);
198
241
  applyProvider(
199
242
  editor,
200
243
  PROVIDER_ID,
201
244
  "Free Pi",
202
- mainNow,
245
+ buildMain(),
203
246
  state.providerToken,
204
247
  );
205
- if (includeDefense && defense.length > 0) {
248
+ if (includeDefense && currentDefense.length > 0) {
206
249
  applyProvider(
207
250
  editor,
208
251
  DEFENSE_PROVIDER_ID,
209
252
  "Free Pi Defense",
210
- defenseNow,
253
+ buildDefense(),
211
254
  state.providerToken,
212
255
  );
213
256
  }
@@ -219,7 +262,7 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
219
262
  // the largest prompt already accepted in real traffic: it has the most
220
263
  // evidence behind it, so the growth probes describe the window sessions use.
221
264
  if (ctx.options?.liveLimits !== false && shouldVerifyWindow(live)) {
222
- const free = main.filter(
265
+ const free = currentMain.filter(
223
266
  (model) => model.free === true && typeof model.id === "string",
224
267
  );
225
268
  const probe =
@@ -229,12 +272,12 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
229
272
  seen: live?.models[model.id ?? ""]?.maxPromptTokens ?? 0,
230
273
  }))
231
274
  .sort((a, b) => b.seen - a.seen)[0]?.id ??
232
- (catalog?.default_model &&
233
- free.some((model) => model.id === catalog.default_model)
234
- ? catalog.default_model
275
+ (currentCatalog?.default_model &&
276
+ free.some((model) => model.id === currentCatalog?.default_model)
277
+ ? currentCatalog.default_model
235
278
  : undefined) ??
236
279
  free[0]?.id ??
237
- Object.keys(mainModels)[0];
280
+ Object.keys(buildMain())[0];
238
281
  if (probe) {
239
282
  void verifyGatewayWindow(deps, { model: probe }).catch(() => undefined);
240
283
  }
@@ -243,10 +286,11 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
243
286
  // V1 selected the catalog default when the user had no model configured.
244
287
  await ctx.model.transform((editor) => {
245
288
  if (editor.default.get()) return;
289
+ const models = buildMain();
246
290
  const preferred =
247
- (catalog?.default_model && mainModels[catalog.default_model]
248
- ? catalog.default_model
249
- : undefined) ?? Object.keys(mainModels)[0];
291
+ (currentCatalog?.default_model && models[currentCatalog.default_model]
292
+ ? currentCatalog.default_model
293
+ : undefined) ?? Object.keys(models)[0];
250
294
  if (preferred) editor.default.set(PROVIDER_ID, preferred);
251
295
  });
252
296
 
@@ -258,6 +302,10 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
258
302
  }> = [
259
303
  { name: "look_at_image", register: () => registerVisionTool(ctx, deps) },
260
304
  { name: "free_pi_usage", register: () => registerUsageTool(ctx, deps) },
305
+ {
306
+ name: "free_pi_subagent_read",
307
+ register: () => registerSubagentTool(ctx, deps),
308
+ },
261
309
  { name: "web", register: () => registerWebTools(ctx, deps) },
262
310
  { name: "generate_image", register: () => registerGenerateImageTool(ctx, deps) },
263
311
  ];
@@ -271,13 +319,65 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
271
319
  const abort = new AbortController();
272
320
  const eventTask = subscribeEvents(ctx, deps, abort.signal);
273
321
 
322
+ // A failed catalog fetch registers the provider with zero models, which
323
+ // hides every free-pi entry from the model picker for this location until
324
+ // OpenCode restarts. Retry in the background and re-register the models as
325
+ // soon as the gateway answers, so a transient timeout heals on its own.
326
+ const waitForAbort = (ms: number) =>
327
+ new Promise<void>((resolve) => {
328
+ if (abort.signal.aborted) return resolve();
329
+ const finish = () => {
330
+ clearTimeout(timer);
331
+ abort.signal.removeEventListener("abort", finish);
332
+ resolve();
333
+ };
334
+ const timer = setTimeout(finish, ms);
335
+ abort.signal.addEventListener("abort", finish, { once: true });
336
+ });
337
+ const catalogRecovery = (async () => {
338
+ // Only a missing catalog needs recovery; an empty model list after access
339
+ // filtering means the account cannot use these models, not a timeout.
340
+ if (currentCatalog) return;
341
+ for (const delay of CATALOG_RECOVERY_DELAYS_MS) {
342
+ if (abort.signal.aborted || currentMain.length > 0) return;
343
+ await waitForAbort(delay);
344
+ if (abort.signal.aborted || currentMain.length > 0) return;
345
+ const next = await fetchCatalog(deps).catch(() => undefined);
346
+ if (!next) continue;
347
+ const parts = partitionModels(next);
348
+ const accessNow = accountAccess(state.quotaCache?.me);
349
+ const nextMain = filterAccessibleModels(parts.main, accessNow);
350
+ if (nextMain.length === 0) continue;
351
+ currentCatalog = next;
352
+ currentMain = nextMain;
353
+ currentDefense = filterAccessibleModels(parts.defense, accessNow);
354
+ indexModelState();
355
+ await ctx.provider.reload().catch(() => undefined);
356
+ await ctx.model.reload().catch(() => undefined);
357
+ log.info(
358
+ `free-pi catalog recovered; registered ${currentMain.length} model(s)`,
359
+ {
360
+ defaultModel: currentCatalog?.default_model,
361
+ clientVersion: state.latestClientVersion,
362
+ models: currentMain.map((model) => model.id),
363
+ },
364
+ );
365
+ return;
366
+ }
367
+ log.warn(
368
+ "free-pi catalog stayed unreachable; free-pi models remain unavailable",
369
+ { attempts: CATALOG_RECOVERY_DELAYS_MS.length },
370
+ );
371
+ })();
372
+ void catalogRecovery.catch(() => undefined);
373
+
274
374
  log.info(
275
- `Loaded ${main.length} free-pi model(s) and ${includeDefense ? defense.length : 0} defense model(s)`,
375
+ `Loaded ${currentMain.length} free-pi model(s) and ${includeDefense ? currentDefense.length : 0} defense model(s)`,
276
376
  {
277
- defaultModel: catalog?.default_model,
377
+ defaultModel: currentCatalog?.default_model,
278
378
  clientVersion: state.latestClientVersion,
279
379
  capabilities: candidates.length,
280
- models: main.map((model) => model.id),
380
+ models: currentMain.map((model) => model.id),
281
381
  },
282
382
  );
283
383
 
@@ -23,6 +23,9 @@ import {
23
23
  RETRY_MAX_DELAY_MS,
24
24
  RETRY_MAX_RETRIES,
25
25
  SUBAGENT_HEADER,
26
+ TRANSPORT_RETRY_BASE_MS,
27
+ TRANSPORT_RETRY_MAX,
28
+ TRANSPORT_RETRY_MAX_DELAY_MS,
26
29
  } from "../constants.js";
27
30
  import {
28
31
  currentLiveLimits,
@@ -333,6 +336,22 @@ const TERMINAL_RETRY_CODES = new Set([
333
336
  const TERMINAL_RETRY_PATTERN =
334
337
  /free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
335
338
 
339
+ /**
340
+ * A request that never reached the gateway. `provider.transport` covers the
341
+ * typed path, while the pattern catches bare fetch errors. These are worth
342
+ * retrying beyond the usual budget: a brief offline moment or a background
343
+ * service restart is not a provider limit.
344
+ */
345
+ const TRANSPORT_RETRY_PATTERN =
346
+ /ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|EPIPE|socket hang up|fetch failed|Unable to connect|connection (?:refused|reset)/i;
347
+
348
+ function isTransportFailure(error: any): boolean {
349
+ const type = typeof error?.type === "string" ? error.type : "";
350
+ if (/transport|network|connection/i.test(type)) return true;
351
+ const message = `${error?.message ?? ""}\n${error?.cause?.message ?? ""}`;
352
+ return TRANSPORT_RETRY_PATTERN.test(message);
353
+ }
354
+
336
355
  function isTerminalFailure(error: any): boolean {
337
356
  if (
338
357
  error?.type === "aborted" ||
@@ -392,6 +411,30 @@ function applyRetryPolicy(deps: Deps, event: any): void {
392
411
  event.decision = { retry: false };
393
412
  return;
394
413
  }
414
+ if (isTransportFailure(event.error)) {
415
+ if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
416
+ event.decision = { retry: false };
417
+ return;
418
+ }
419
+ // A connection that dropped mid-turn can leave the gateway's per-session
420
+ // slot marked busy, so the next attempt should not reuse the wire id.
421
+ markWireSessionDirty(deps, event.sessionID);
422
+ const attempt = Math.max(1, event.attempt - 1);
423
+ event.decision = {
424
+ retry: true,
425
+ delay: Math.min(
426
+ TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1),
427
+ TRANSPORT_RETRY_MAX_DELAY_MS,
428
+ ),
429
+ };
430
+ deps.log.warn("free-pi could not be reached; retrying", {
431
+ sessionID: event.sessionID,
432
+ attempt: event.attempt,
433
+ delay: event.decision.delay,
434
+ error: typeof event.error?.message === "string" ? event.error.message : undefined,
435
+ });
436
+ return;
437
+ }
395
438
  if (event.attempt > RETRY_MAX_RETRIES + 1) {
396
439
  event.decision = { retry: false };
397
440
  return;
@@ -33,6 +33,7 @@ const MAX_STARTED = 200;
33
33
  export const FREE_PI_TOOL_NAMES = [
34
34
  "look_at_image",
35
35
  "free_pi_usage",
36
+ "free_pi_subagent_read",
36
37
  "web_search",
37
38
  "docs_lookup",
38
39
  "generate_image",
@@ -0,0 +1,271 @@
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
+
15
+ import type { Plugin } from "@opencode/plugin";
16
+ import type { Deps } from "../deps.js";
17
+ import { done, fail, GATED_TEXT, isGatedSession } from "./api.js";
18
+
19
+ const DEFAULT_MAX_CHARS = 60_000;
20
+ const MIN_MAX_CHARS = 2_000;
21
+ const MAX_MAX_CHARS = 200_000;
22
+ const TOOL_RESULT_CHARS = 2_000;
23
+ const TOOL_INPUT_CHARS = 1_500;
24
+ const USER_TEXT_CHARS = 8_000;
25
+ const ASSISTANT_TEXT_CHARS = 16_000;
26
+
27
+ const INPUT_SCHEMA = {
28
+ type: "object",
29
+ additionalProperties: false,
30
+ properties: {
31
+ sessionID: {
32
+ type: "string",
33
+ description:
34
+ "Child session to read, as returned by the `subagent` tool. Omit it to list this session's children.",
35
+ },
36
+ maxChars: {
37
+ type: "integer",
38
+ minimum: MIN_MAX_CHARS,
39
+ maximum: MAX_MAX_CHARS,
40
+ description: `Transcript budget in characters (default ${DEFAULT_MAX_CHARS}). The newest turns are kept.`,
41
+ },
42
+ },
43
+ } as const;
44
+
45
+ type Part = {
46
+ type?: string;
47
+ text?: string;
48
+ synthetic?: boolean;
49
+ name?: string;
50
+ state?: {
51
+ status?: string;
52
+ input?: unknown;
53
+ content?: unknown;
54
+ };
55
+ };
56
+
57
+ type Message = {
58
+ id?: string;
59
+ type?: string;
60
+ role?: string;
61
+ text?: string;
62
+ agent?: string;
63
+ finish?: string;
64
+ error?: unknown;
65
+ content?: unknown;
66
+ };
67
+
68
+ function cut(value: string, limit: number): string {
69
+ const text = value.trim();
70
+ if (text.length <= limit) return text;
71
+ return `${text.slice(0, limit)}\n[... ${text.length - limit} characters cut]`;
72
+ }
73
+
74
+ function stringify(value: unknown): string {
75
+ if (typeof value === "string") return value;
76
+ try {
77
+ return JSON.stringify(value, null, 2) ?? "";
78
+ } catch {
79
+ return String(value ?? "");
80
+ }
81
+ }
82
+
83
+ function textOfContent(content: unknown): string {
84
+ if (typeof content === "string") return content;
85
+ if (!Array.isArray(content)) return "";
86
+ return content
87
+ .filter(
88
+ (part: Part) => part?.type === "text" && part.synthetic !== true,
89
+ )
90
+ .map((part: Part) => part.text ?? "")
91
+ .join("\n");
92
+ }
93
+
94
+ function formatTool(part: Part): string {
95
+ const status = part.state?.status ?? "unknown";
96
+ const header = `[tool ${part.name ?? "?"}] ${status}`;
97
+ const input = stringify(part.state?.input ?? {});
98
+ const output = textOfContent(part.state?.content);
99
+ return [
100
+ header,
101
+ `input: ${cut(input, TOOL_INPUT_CHARS)}`,
102
+ ...(output.trim() ? [`result: ${cut(output, TOOL_RESULT_CHARS)}`] : []),
103
+ ].join("\n");
104
+ }
105
+
106
+ function formatMessage(message: Message): string {
107
+ const role = message.role ?? message.type;
108
+ if (role === "user") {
109
+ const text = message.text ?? textOfContent(message.content);
110
+ return text.trim() ? `[user]\n${cut(text, USER_TEXT_CHARS)}` : "";
111
+ }
112
+ if (role !== "assistant") return "";
113
+
114
+ const blocks: string[] = [];
115
+ const content = Array.isArray(message.content) ? message.content : [];
116
+ for (const part of content as Part[]) {
117
+ if (part?.type === "text" && part.synthetic !== true) {
118
+ const text = part.text ?? "";
119
+ if (text.trim()) blocks.push(cut(text, ASSISTANT_TEXT_CHARS));
120
+ } else if (part?.type === "tool") {
121
+ blocks.push(formatTool(part));
122
+ }
123
+ }
124
+ if (blocks.length === 0) return "";
125
+ const finish =
126
+ message.finish && message.finish !== "stop" ? ` (${message.finish})` : "";
127
+ return `[assistant${message.agent ? ` ${message.agent}` : ""}]${finish}\n${blocks.join("\n\n")}`;
128
+ }
129
+
130
+ export type Transcript = {
131
+ readonly text: string;
132
+ readonly messages: number;
133
+ readonly truncated: boolean;
134
+ };
135
+
136
+ /**
137
+ * Renders a session transcript, keeping the newest turns when it does not fit.
138
+ * The final assistant text is repeated at the end so the parent can quote it
139
+ * even when the middle of the transcript was dropped.
140
+ */
141
+ export function formatTranscript(
142
+ messages: readonly unknown[],
143
+ maxChars = DEFAULT_MAX_CHARS,
144
+ ): Transcript {
145
+ const budget = Math.max(MIN_MAX_CHARS, Math.min(maxChars, MAX_MAX_CHARS));
146
+ const entries = (messages as Message[])
147
+ .map(formatMessage)
148
+ .filter((entry) => entry.length > 0);
149
+
150
+ let text = entries.join("\n\n");
151
+ if (text.length <= budget) {
152
+ return { text, messages: entries.length, truncated: false };
153
+ }
154
+
155
+ const kept: string[] = [];
156
+ let size = 0;
157
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
158
+ const entry = entries[index]!;
159
+ if (size + entry.length + 2 > budget) break;
160
+ kept.unshift(entry);
161
+ size += entry.length + 2;
162
+ }
163
+ const dropped = entries.length - kept.length;
164
+ const notice = `[... ${dropped} older transcript block${dropped === 1 ? "" : "s"} omitted to stay inside ${budget} characters; pass a larger maxChars to see them]`;
165
+ text = [notice, ...kept].join("\n\n");
166
+ return { text, messages: entries.length, truncated: true };
167
+ }
168
+
169
+ function listLine(session: {
170
+ id: string;
171
+ title?: string;
172
+ agent?: string;
173
+ outcome?: string;
174
+ updated?: number;
175
+ }): string {
176
+ const when = session.updated
177
+ ? new Date(session.updated).toISOString()
178
+ : "unknown time";
179
+ return `- ${session.id} - ${session.title ?? "(untitled)"} - agent ${session.agent ?? "?"} - ${session.outcome ?? "unknown"} - updated ${when}`;
180
+ }
181
+
182
+ async function execute(
183
+ deps: Deps,
184
+ raw: unknown,
185
+ context: { readonly sessionID: string; readonly signal: AbortSignal },
186
+ ) {
187
+ if (!isGatedSession(deps, context.sessionID)) return fail(GATED_TEXT);
188
+ const input = (raw ?? {}) as { sessionID?: unknown; maxChars?: unknown };
189
+ const requested =
190
+ typeof input.sessionID === "string" && input.sessionID.trim()
191
+ ? input.sessionID.trim()
192
+ : undefined;
193
+
194
+ if (!requested) {
195
+ const children = deps.listSubagentSessions
196
+ ? await deps.listSubagentSessions(context.sessionID).catch(() => [])
197
+ : [];
198
+ if (children.length === 0) {
199
+ return done(
200
+ "This session has no child sessions yet. The `subagent` tool returns a sessionID when a child starts.",
201
+ { ok: true, children: 0 },
202
+ );
203
+ }
204
+ return done(
205
+ ["Child sessions of this session:", ...children.map(listLine)].join("\n"),
206
+ { ok: true, children: children.length },
207
+ );
208
+ }
209
+
210
+ if (!deps.readSession) {
211
+ return fail("Reading subagent sessions is not available in this OpenCode build.");
212
+ }
213
+ const info = await deps.readSession(requested).catch(() => undefined);
214
+ if (!info) return fail(`No OpenCode session with id ${requested}.`);
215
+ if (info.parentID !== context.sessionID) {
216
+ return fail(
217
+ `${requested} is not a subagent of this session, so its transcript cannot be read here.`,
218
+ );
219
+ }
220
+
221
+ const messages = await deps.readContext(requested).catch(() => []);
222
+ if (messages.length === 0) {
223
+ return done(
224
+ `The subagent session ${requested} has no messages yet. It may still be starting.`,
225
+ { ok: false, sessionID: requested, messages: 0 },
226
+ );
227
+ }
228
+
229
+ const budget =
230
+ typeof input.maxChars === "number" && Number.isFinite(input.maxChars)
231
+ ? input.maxChars
232
+ : DEFAULT_MAX_CHARS;
233
+ const transcript = formatTranscript(messages, budget);
234
+ const header = [
235
+ `Subagent session ${requested}${info.title ? ` - ${info.title}` : ""}`,
236
+ `agent: ${info.agent ?? "?"} - outcome: ${info.outcome ?? "running"} - stored messages: ${messages.length}`,
237
+ ].join("\n");
238
+
239
+ deps.log.info("free_pi_subagent_read answered", {
240
+ sessionID: context.sessionID,
241
+ child: requested,
242
+ messages: transcript.messages,
243
+ truncated: transcript.truncated,
244
+ });
245
+
246
+ return done(`${header}\n\n${transcript.text}`, {
247
+ ok: true,
248
+ sessionID: requested,
249
+ parentID: info.parentID,
250
+ agent: info.agent,
251
+ outcome: info.outcome,
252
+ messages: transcript.messages,
253
+ truncated: transcript.truncated,
254
+ });
255
+ }
256
+
257
+ export async function registerSubagentTool(
258
+ ctx: Plugin.Context,
259
+ deps: Deps,
260
+ ): Promise<{ dispose: () => Promise<void> }> {
261
+ return ctx.tool.transform((editor) => {
262
+ editor.add({
263
+ name: "free_pi_subagent_read",
264
+ description:
265
+ "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.",
266
+ input: INPUT_SCHEMA,
267
+ options: { codemode: false },
268
+ execute: (input: unknown, context: any) => execute(deps, input, context),
269
+ } as any);
270
+ });
271
+ }
package/src/types.ts CHANGED
@@ -280,3 +280,21 @@ export type SessionMessageInfo =
280
280
  export type ReadContext = (
281
281
  sessionID: string,
282
282
  ) => Promise<readonly SessionMessageInfo[]>;
283
+
284
+ /** Minimal view of an OpenCode V2 session header. */
285
+ export type SubagentSessionInfo = {
286
+ id: string;
287
+ parentID?: string;
288
+ title?: string;
289
+ agent?: string;
290
+ outcome?: string;
291
+ updated?: number;
292
+ };
293
+
294
+ export type ReadSessionInfo = (
295
+ sessionID: string,
296
+ ) => Promise<SubagentSessionInfo | undefined>;
297
+
298
+ export type ListSubagentSessions = (
299
+ parentID: string,
300
+ ) => Promise<readonly SubagentSessionInfo[]>;