@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.
- package/README.md +43 -1
- package/dist/agents/definitions.d.ts +2 -2
- package/dist/agents/definitions.js +7 -1
- package/dist/catalog/live.d.ts +18 -2
- package/dist/catalog/live.js +43 -2
- package/dist/catalog/models.js +6 -1
- package/dist/constants.d.ts +10 -1
- package/dist/constants.js +10 -1
- package/dist/deps.d.ts +4 -1
- package/dist/plugin.js +46 -3
- package/dist/session/hooks.js +84 -4
- package/dist/session/overflow.d.ts +31 -0
- package/dist/session/overflow.js +82 -4
- package/dist/session/replay.d.ts +4 -0
- package/dist/session/replay.js +10 -7
- package/dist/session/tools.d.ts +1 -1
- package/dist/session/tools.js +1 -0
- package/dist/tools/subagent.d.ts +29 -0
- package/dist/tools/subagent.js +197 -0
- package/dist/types.d.ts +11 -0
- package/package.json +1 -1
- package/src/agents/definitions.ts +7 -1
- package/src/catalog/live.ts +65 -2
- package/src/catalog/models.ts +6 -0
- package/src/constants.ts +11 -1
- package/src/deps.ts +8 -1
- package/src/plugin.ts +44 -2
- package/src/session/hooks.ts +102 -3
- package/src/session/overflow.ts +98 -4
- package/src/session/replay.ts +14 -6
- package/src/session/tools.ts +1 -0
- package/src/tools/subagent.ts +271 -0
- package/src/types.ts +18 -0
package/dist/session/overflow.js
CHANGED
|
@@ -22,18 +22,35 @@ const STORM_LIMIT = 2;
|
|
|
22
22
|
const STORM_LIMIT_PER_SESSION = 512;
|
|
23
23
|
export const SPURIOUS_OVERFLOW_MESSAGE = "free-pi rejected this request as too long even though it fits the model's window; " +
|
|
24
24
|
"this is a provider failure, not a context overflow. Retry the message, or start a new session if it persists.";
|
|
25
|
+
/** Part types that carry an inline image or file, which the provider bills in full. */
|
|
26
|
+
const MEDIA_PART_TYPES = new Set([
|
|
27
|
+
"image",
|
|
28
|
+
"image_url",
|
|
29
|
+
"input_image",
|
|
30
|
+
"file",
|
|
31
|
+
"input_file",
|
|
32
|
+
]);
|
|
25
33
|
/**
|
|
26
34
|
* Approximate token count of a chat-completions body: every string in it,
|
|
27
35
|
* message text and tool output alike, at the usual four characters per token.
|
|
28
36
|
* Inline media counts at its base64 length, which is what the provider bills.
|
|
37
|
+
*
|
|
38
|
+
* The same walk reports the requested model and whether the body carries
|
|
39
|
+
* inline media. A rejection caused by a large attachment says nothing about
|
|
40
|
+
* the model's text window, so callers must not learn a ceiling from it.
|
|
29
41
|
*/
|
|
30
|
-
export function
|
|
42
|
+
export function profileRequest(body) {
|
|
31
43
|
try {
|
|
32
44
|
const data = JSON.parse(body);
|
|
33
45
|
let chars = 0;
|
|
46
|
+
let model;
|
|
47
|
+
let hasMedia = false;
|
|
34
48
|
const walk = (value) => {
|
|
35
49
|
if (typeof value === "string") {
|
|
36
50
|
chars += value.length;
|
|
51
|
+
if (value.startsWith("data:image/") || value.startsWith("data:application/")) {
|
|
52
|
+
hasMedia = true;
|
|
53
|
+
}
|
|
37
54
|
return;
|
|
38
55
|
}
|
|
39
56
|
if (Array.isArray(value)) {
|
|
@@ -42,18 +59,79 @@ export function measureRequestTokens(body) {
|
|
|
42
59
|
return;
|
|
43
60
|
}
|
|
44
61
|
if (value && typeof value === "object") {
|
|
45
|
-
|
|
62
|
+
const record = value;
|
|
63
|
+
if (typeof record.type === "string" && MEDIA_PART_TYPES.has(record.type)) {
|
|
64
|
+
hasMedia = true;
|
|
65
|
+
}
|
|
66
|
+
if (model === undefined &&
|
|
67
|
+
typeof record.model === "string" &&
|
|
68
|
+
record.model.length > 0) {
|
|
69
|
+
model = record.model;
|
|
70
|
+
}
|
|
71
|
+
for (const [key, item] of Object.entries(record)) {
|
|
46
72
|
chars += key.length;
|
|
47
73
|
walk(item);
|
|
48
74
|
}
|
|
49
75
|
}
|
|
50
76
|
};
|
|
51
77
|
walk(data);
|
|
52
|
-
return Math.ceil(chars / 4);
|
|
78
|
+
return { tokens: Math.ceil(chars / 4), model, hasMedia };
|
|
53
79
|
}
|
|
54
80
|
catch {
|
|
55
|
-
return Math.ceil(body.length / 4);
|
|
81
|
+
return { tokens: Math.ceil(body.length / 4), hasMedia: false };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Token count of a request body, without the extra facts. */
|
|
85
|
+
export function measureRequestTokens(body) {
|
|
86
|
+
return profileRequest(body).tokens;
|
|
87
|
+
}
|
|
88
|
+
/** Cheap per-message estimate; the body is serialized once per message. */
|
|
89
|
+
export function estimateMessageTokens(message) {
|
|
90
|
+
try {
|
|
91
|
+
return Math.ceil(JSON.stringify(message).length / 4);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return 0;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Keeps the newest part of a message list inside `budget` tokens, cutting only
|
|
99
|
+
* at user turns so an assistant tool call never loses its results.
|
|
100
|
+
*
|
|
101
|
+
* OpenCode refuses to compact when the summarization request itself is still
|
|
102
|
+
* too large, and then the turn dies with nothing but the checkpoint shown. The
|
|
103
|
+
* gateway's real ceiling is lower than the advertised window, so the plugin
|
|
104
|
+
* trims the oldest turns it can spare before the summarizer is asked to read
|
|
105
|
+
* them.
|
|
106
|
+
*/
|
|
107
|
+
export function trimMessagesForBudget(messages, budget) {
|
|
108
|
+
if (messages.length === 0)
|
|
109
|
+
return { messages, dropped: 0, tokens: 0 };
|
|
110
|
+
const sizes = messages.map(estimateMessageTokens);
|
|
111
|
+
let total = 0;
|
|
112
|
+
for (const size of sizes)
|
|
113
|
+
total += size;
|
|
114
|
+
if (total <= budget)
|
|
115
|
+
return { messages, dropped: 0, tokens: total };
|
|
116
|
+
const cuts = [];
|
|
117
|
+
for (let index = 1; index < messages.length; index += 1) {
|
|
118
|
+
const role = messages[index]?.role;
|
|
119
|
+
if (role === "user")
|
|
120
|
+
cuts.push(index);
|
|
121
|
+
}
|
|
122
|
+
for (const cut of cuts) {
|
|
123
|
+
let tail = 0;
|
|
124
|
+
for (let index = cut; index < sizes.length; index += 1)
|
|
125
|
+
tail += sizes[index];
|
|
126
|
+
if (tail <= budget) {
|
|
127
|
+
return { messages: messages.slice(cut), dropped: cut, tokens: tail };
|
|
128
|
+
}
|
|
56
129
|
}
|
|
130
|
+
const last = cuts.length > 0 ? cuts[cuts.length - 1] : messages.length - 1;
|
|
131
|
+
let tail = 0;
|
|
132
|
+
for (let index = last; index < sizes.length; index += 1)
|
|
133
|
+
tail += sizes[index];
|
|
134
|
+
return { messages: messages.slice(last), dropped: last, tokens: tail };
|
|
57
135
|
}
|
|
58
136
|
/**
|
|
59
137
|
* Records a rejection of a request that fits, and returns the number of them
|
package/dist/session/replay.d.ts
CHANGED
|
@@ -24,6 +24,10 @@ export declare function replayConcurrentResponse(deps: Deps, event: any): Promis
|
|
|
24
24
|
export type OverflowReplay = {
|
|
25
25
|
/** Tokens of the rejected request, when its body was available. */
|
|
26
26
|
readonly tokens?: number;
|
|
27
|
+
/** Upstream model the rejected request asked for. */
|
|
28
|
+
readonly model?: string;
|
|
29
|
+
/** Whether the rejected request carried an inline image or file. */
|
|
30
|
+
readonly hasMedia?: boolean;
|
|
27
31
|
/** Whether the rejected request plainly fits the model window. */
|
|
28
32
|
readonly spurious?: boolean;
|
|
29
33
|
/** A good response from a fresh wire session, when the retry succeeded. */
|
package/dist/session/replay.js
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
import { closeFreePiSession } from "../api/session.js";
|
|
17
17
|
import { overflowCodeOf } from "../errors/limit.js";
|
|
18
18
|
import { sleep, trimMap } from "../utils/async.js";
|
|
19
|
-
import {
|
|
19
|
+
import { profileRequest, SPURIOUS_OVERFLOW_TOKENS, } from "./overflow.js";
|
|
20
20
|
import { rotateWireSessionID, wireSessionID } from "./wire.js";
|
|
21
21
|
const REPLAY_BODY_LIMIT = 24;
|
|
22
22
|
const REPLAY_MAX_ATTEMPTS = 4;
|
|
@@ -152,13 +152,16 @@ export async function replaySpuriousOverflow(deps, event) {
|
|
|
152
152
|
const body = await storedBody(deps, event);
|
|
153
153
|
if (!body)
|
|
154
154
|
return {};
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
155
|
+
const profile = profileRequest(body);
|
|
156
|
+
const tokens = profile.tokens;
|
|
157
|
+
const facts = { model: profile.model, hasMedia: profile.hasMedia };
|
|
158
|
+
if (tokens >= SPURIOUS_OVERFLOW_TOKENS) {
|
|
159
|
+
return { tokens, ...facts, spurious: false };
|
|
160
|
+
}
|
|
158
161
|
let previous = request.headers.get("x-session-id") ?? wireSessionID(deps, event.sessionID);
|
|
159
162
|
for (let attempt = 1; attempt <= OVERFLOW_REPLAY_ATTEMPTS; attempt++) {
|
|
160
163
|
if (request.signal.aborted)
|
|
161
|
-
return { tokens, spurious: true };
|
|
164
|
+
return { tokens, ...facts, spurious: true };
|
|
162
165
|
const next = rotateWireSessionID(deps, event.sessionID);
|
|
163
166
|
if (previous && previous !== next) {
|
|
164
167
|
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
@@ -178,9 +181,9 @@ export async function replaySpuriousOverflow(deps, event) {
|
|
|
178
181
|
continue;
|
|
179
182
|
if (!(await overflowCodeOf(response))) {
|
|
180
183
|
deps.log.info("free-pi rejected a request that fits as too long; replayed it on a fresh session id", { sessionID: event.sessionID, tokens, to: next, attempt });
|
|
181
|
-
return { tokens, spurious: true, response };
|
|
184
|
+
return { tokens, ...facts, spurious: true, response };
|
|
182
185
|
}
|
|
183
186
|
}
|
|
184
187
|
deps.log.info("free-pi keeps rejecting a request that fits as too long; the provider is failing", { sessionID: event.sessionID, tokens });
|
|
185
|
-
return { tokens, spurious: true };
|
|
188
|
+
return { tokens, ...facts, spurious: true };
|
|
186
189
|
}
|
package/dist/session/tools.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ import type { Deps } from "../deps.js";
|
|
|
13
13
|
* served by another provider (see `hideFreePiTools`) and refuses to run them
|
|
14
14
|
* outside a free-pi session.
|
|
15
15
|
*/
|
|
16
|
-
export declare const FREE_PI_TOOL_NAMES: readonly ["look_at_image", "free_pi_usage", "web_search", "docs_lookup", "generate_image"];
|
|
16
|
+
export declare const FREE_PI_TOOL_NAMES: readonly ["look_at_image", "free_pi_usage", "free_pi_subagent_read", "web_search", "docs_lookup", "generate_image"];
|
|
17
17
|
type ToolResultLike = {
|
|
18
18
|
metadata?: Record<string, unknown>;
|
|
19
19
|
};
|
package/dist/session/tools.js
CHANGED
|
@@ -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
|
@@ -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
|
|
package/src/catalog/live.ts
CHANGED
|
@@ -37,6 +37,8 @@ const INITIAL_CHARS_PER_TOKEN = 4;
|
|
|
37
37
|
export type ModelObservation = {
|
|
38
38
|
/** Largest prompt the gateway accepted for this model. */
|
|
39
39
|
maxPromptTokens?: number;
|
|
40
|
+
/** Smallest prompt the gateway rejected as too long for this model. */
|
|
41
|
+
rejectedPromptTokens?: number;
|
|
40
42
|
/** Whether a real response carried reasoning tokens. */
|
|
41
43
|
reasoning?: boolean;
|
|
42
44
|
updatedAt: number;
|
|
@@ -71,6 +73,14 @@ function sanitize(value: unknown): LiveLimits {
|
|
|
71
73
|
if (Number.isFinite(entry.maxPromptTokens) && entry.maxPromptTokens! > 0) {
|
|
72
74
|
observation.maxPromptTokens = Math.floor(entry.maxPromptTokens!);
|
|
73
75
|
}
|
|
76
|
+
if (
|
|
77
|
+
Number.isFinite(entry.rejectedPromptTokens) &&
|
|
78
|
+
entry.rejectedPromptTokens! > 0
|
|
79
|
+
) {
|
|
80
|
+
observation.rejectedPromptTokens = Math.floor(
|
|
81
|
+
entry.rejectedPromptTokens!,
|
|
82
|
+
);
|
|
83
|
+
}
|
|
74
84
|
if (typeof entry.reasoning === "boolean") {
|
|
75
85
|
observation.reasoning = entry.reasoning;
|
|
76
86
|
}
|
|
@@ -166,8 +176,61 @@ export function noteStepTokens(
|
|
|
166
176
|
scheduleWrite();
|
|
167
177
|
}
|
|
168
178
|
|
|
169
|
-
/**
|
|
170
|
-
|
|
179
|
+
/** Keeps the advertised window this far below the smallest rejected prompt. */
|
|
180
|
+
const REJECTION_HEADROOM = 0.85;
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Safe context window for a model whose real ceiling is only known from a
|
|
184
|
+
* rejection. The gateway never publishes it, so the smallest prompt it refused
|
|
185
|
+
* is the only evidence available; the advertised window stays a margin below
|
|
186
|
+
* that, which lets OpenCode compact before the summarizer request is refused
|
|
187
|
+
* too.
|
|
188
|
+
*/
|
|
189
|
+
export function learnedContextWindow(
|
|
190
|
+
limits: LiveLimits | undefined,
|
|
191
|
+
modelID: string,
|
|
192
|
+
): number | undefined {
|
|
193
|
+
const rejected = limits?.models[modelID]?.rejectedPromptTokens;
|
|
194
|
+
if (!rejected || rejected <= 0) return undefined;
|
|
195
|
+
return Math.max(2_048, Math.min(
|
|
196
|
+
Math.floor(rejected * REJECTION_HEADROOM),
|
|
197
|
+
MAX_WINDOW,
|
|
198
|
+
));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Records a request the gateway refused as too long. Real traffic is the only
|
|
203
|
+
* probe that costs nothing, and a rejection is a hard upper bound on the
|
|
204
|
+
* model's window, so it lowers what the catalog advertises for that model from
|
|
205
|
+
* the next build on. Returns the window that now applies, if it changed.
|
|
206
|
+
*/
|
|
207
|
+
export function noteRejectedPrompt(
|
|
208
|
+
deps: Deps,
|
|
209
|
+
modelID: string,
|
|
210
|
+
tokens: number,
|
|
211
|
+
): number | undefined {
|
|
212
|
+
if (!modelID || !Number.isFinite(tokens) || tokens <= 0) return undefined;
|
|
213
|
+
const rejected = Math.floor(tokens);
|
|
214
|
+
const entry = observation(modelID);
|
|
215
|
+
if (
|
|
216
|
+
entry.rejectedPromptTokens !== undefined &&
|
|
217
|
+
entry.rejectedPromptTokens <= rejected
|
|
218
|
+
) {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
const previous = learnedContextWindow(cached, modelID);
|
|
222
|
+
entry.rejectedPromptTokens = rejected;
|
|
223
|
+
entry.updatedAt = Date.now();
|
|
224
|
+
scheduleWrite();
|
|
225
|
+
const window = learnedContextWindow(cached, modelID);
|
|
226
|
+
deps.log.warn(
|
|
227
|
+
"free-pi rejected a prompt as too long; lowering the advertised window",
|
|
228
|
+
{ model: modelID, rejectedTokens: rejected, previous, window },
|
|
229
|
+
);
|
|
230
|
+
return window;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Whether the persisted window is old enough to verify again. */export function shouldVerifyWindow(limits: LiveLimits | undefined): boolean {
|
|
171
234
|
const verifiedAt = limits?.window?.verifiedAt;
|
|
172
235
|
if (!verifiedAt) return true;
|
|
173
236
|
return Date.now() - verifiedAt > VERIFY_LIMITS_TTL_MS;
|
package/src/catalog/models.ts
CHANGED
|
@@ -20,6 +20,7 @@ import type {
|
|
|
20
20
|
RegistryCandidate,
|
|
21
21
|
} from "../types.js";
|
|
22
22
|
import type { LiveLimits } from "./live.js";
|
|
23
|
+
import { learnedContextWindow } from "./live.js";
|
|
23
24
|
import { positiveNumber } from "../utils/numbers.js";
|
|
24
25
|
import { cleanText } from "../utils/text.js";
|
|
25
26
|
|
|
@@ -376,6 +377,10 @@ export function buildModels(
|
|
|
376
377
|
MAX_CONTEXT_WINDOW,
|
|
377
378
|
Math.max(options.live?.window?.tokens ?? CONTEXT_WINDOW, observed),
|
|
378
379
|
);
|
|
380
|
+
// A prompt the gateway already refused is a hard ceiling: advertise below
|
|
381
|
+
// it so OpenCode compacts before the summarization request itself is
|
|
382
|
+
// rejected, which ends the turn with the checkpoint and no answer.
|
|
383
|
+
const learned = learnedContextWindow(options.live, model.id);
|
|
379
384
|
const limitContext = Math.min(
|
|
380
385
|
positiveNumber(
|
|
381
386
|
model.context_window,
|
|
@@ -384,6 +389,7 @@ export function buildModels(
|
|
|
384
389
|
capability?.limit?.context,
|
|
385
390
|
) ?? contextCeiling,
|
|
386
391
|
contextCeiling,
|
|
392
|
+
learned ?? contextCeiling,
|
|
387
393
|
);
|
|
388
394
|
// Reasoning shares the output budget. When models.dev knows the upstream
|
|
389
395
|
// model emits more than the CLI's 32k, advertise that larger budget (up to a
|
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
|
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 {
|
|
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
|
};
|