@eduardo191labs/opencode-free-pi 0.6.5 → 0.6.7

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,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[]>;