@jakedowns/progress-tool-opencode-plugin 0.0.0-stage → 2.14.0
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 +74 -2
- package/dist/gui-experimental.cjs +10 -0
- package/package.json +63 -4
- package/skills/delegation/SKILL.md +67 -0
- package/skills/osc-demo/SKILL.md +25 -0
- package/skills/progress-tool/SKILL.md +91 -0
- package/skills/tree-demo/SKILL.md +25 -0
- package/src/gui.tsx +613 -0
- package/src/index.ts +473 -0
- package/src/instructions.ts +27 -0
- package/src/monitor.ts +366 -0
- package/src/rpc.ts +60 -0
- package/src/state.ts +94 -0
- package/src/telemetry.ts +76 -0
- package/src/tree.ts +433 -0
- package/src/tui.tsx +151 -0
- package/src/types.ts +48 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode Progress Plugin — server part.
|
|
3
|
+
*
|
|
4
|
+
* Watches the shared progress state file written by the progress MCP server /
|
|
5
|
+
* relay and exposes it to the TUI and GUI parts through RPC.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import { createRequire } from "node:module";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { Plugin, Skill } from "@opencode/plugin";
|
|
13
|
+
import { ProgressRpc } from "./rpc.js";
|
|
14
|
+
import { readProgressState, writeDismissal } from "./state.js";
|
|
15
|
+
import { normalizeRefreshMs } from "./tree.js";
|
|
16
|
+
import { PROGRESS_RULES, instructionsEnabled } from "./instructions.js";
|
|
17
|
+
import {
|
|
18
|
+
observeToolCall,
|
|
19
|
+
normalizeStrictMode,
|
|
20
|
+
normalizeStaleAfterMs,
|
|
21
|
+
normalizeWallClockMs,
|
|
22
|
+
silentRunNudge,
|
|
23
|
+
staleProgressNudge,
|
|
24
|
+
idleReminder,
|
|
25
|
+
wallClockNudge,
|
|
26
|
+
relayHintFor,
|
|
27
|
+
relayHintMessage,
|
|
28
|
+
type MonitorState,
|
|
29
|
+
type IdleTracker,
|
|
30
|
+
type WallClockState,
|
|
31
|
+
} from "./monitor.js";
|
|
32
|
+
import { logNudge, nudgeLoggingEnabled, diffStatuses, type StatusSnapshot } from "./telemetry.js";
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The plugin's own version, read at runtime so a running server part can be
|
|
36
|
+
* identified in logs independently of the (separately loaded) GUI bundle.
|
|
37
|
+
* The desktop app reloads GUI bundles on window reopen but only reloads this
|
|
38
|
+
* server part on a service restart — logging the version makes that
|
|
39
|
+
* split-brain visible ("GUI updated, server stale").
|
|
40
|
+
*/
|
|
41
|
+
const pluginVersion = (() => {
|
|
42
|
+
try {
|
|
43
|
+
return (
|
|
44
|
+
JSON.parse(
|
|
45
|
+
readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8")
|
|
46
|
+
).version ?? "unknown"
|
|
47
|
+
);
|
|
48
|
+
} catch {
|
|
49
|
+
return "unknown";
|
|
50
|
+
}
|
|
51
|
+
})();
|
|
52
|
+
|
|
53
|
+
/** Skills shipped in the package and registered at setup (see plugin/skills/). */
|
|
54
|
+
const PLUGIN_DIR = path.dirname(fileURLToPath(new URL("../package.json", import.meta.url)));
|
|
55
|
+
const PACKAGED_SKILLS = [
|
|
56
|
+
{
|
|
57
|
+
id: "progress-tool",
|
|
58
|
+
name: "Progress Tool Usage",
|
|
59
|
+
description:
|
|
60
|
+
"Use the progress-tool MCP correctly — report long-horizon work (research, planning, exploration, refactors, docs) with the fire-and-forget progress tool, structure multi-step plans as a parentId tree, keep entries current between tool calls, and wrap long-running commands with the out-of-band progress-relay at zero token cost",
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
id: "osc-demo",
|
|
64
|
+
name: "OSC 9;4 Demo",
|
|
65
|
+
description:
|
|
66
|
+
"Demo OSC 9;4 terminal progress support in progress-tool — run a fake build that streams native OSC 9;4 progress sequences through the out-of-band relay (progress-relay), zero agent tokens",
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
id: "tree-demo",
|
|
70
|
+
name: "Task Tree Demo",
|
|
71
|
+
description:
|
|
72
|
+
"Demo nested task trees (parentId roll-up) in progress-tool — run a fake release pipeline with parent, child, and grandchild tasks streaming through the out-of-band relay at zero agent tokens, with an optional failure mode that rolls an error up the tree",
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
id: "delegation",
|
|
76
|
+
name: "Delegation (Subagents)",
|
|
77
|
+
description:
|
|
78
|
+
"Use subagents well — fan out independent research and verification in parallel, pick explore vs general, inherit the session's model, and avoid parallel-edit conflicts",
|
|
79
|
+
},
|
|
80
|
+
];
|
|
81
|
+
|
|
82
|
+
function loadPackagedSkillBody(id: string): string {
|
|
83
|
+
// Strip frontmatter: the skill tool adds the Markdown body, and the
|
|
84
|
+
// directory copies keep frontmatter for repo-local discovery.
|
|
85
|
+
const raw = readFileSync(path.join(PLUGIN_DIR, "skills", id, "SKILL.md"), "utf8");
|
|
86
|
+
return raw.replace(/^---\n[\s\S]*?\n---\n/, "").trimStart();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export default Plugin.define({
|
|
90
|
+
id: "opencode-progress",
|
|
91
|
+
async setup(ctx) {
|
|
92
|
+
// Auto-register the MCP server from the published companion package so a
|
|
93
|
+
// single `opencode plugin add` installs everything. A dev checkout that
|
|
94
|
+
// loads this plugin by path won't resolve the package — skip silently.
|
|
95
|
+
// Opt out with { options: { autoRegisterMcp: false } }.
|
|
96
|
+
if (ctx.options?.autoRegisterMcp !== false) {
|
|
97
|
+
try {
|
|
98
|
+
const requireFromHere = createRequire(import.meta.url);
|
|
99
|
+
const mcpEntry = requireFromHere.resolve("@jakedowns/progress-tool-mcp");
|
|
100
|
+
await ctx.mcp.transform((editor) => {
|
|
101
|
+
if (!editor.get("progress-server")) {
|
|
102
|
+
editor.set("progress-server", {
|
|
103
|
+
type: "local",
|
|
104
|
+
command: [process.execPath, mcpEntry],
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
console.log(`[opencode-progress] registered MCP server from ${mcpEntry}`);
|
|
109
|
+
} catch {
|
|
110
|
+
// Companion package not installed (local dev) — keep the existing config.
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
let signature = JSON.stringify(readProgressState().entries ?? {});
|
|
115
|
+
|
|
116
|
+
const registration = await ctx.rpc.register(ProgressRpc, {
|
|
117
|
+
list: async () => {
|
|
118
|
+
const state = readProgressState();
|
|
119
|
+
return { entries: state.entries ?? {}, updatedAt: Date.now() };
|
|
120
|
+
},
|
|
121
|
+
dismiss: async ({ key, status }) => {
|
|
122
|
+
const ok = writeDismissal(key, status);
|
|
123
|
+
console.log(`[opencode-progress] v${pluginVersion} dismiss rpc key=${key} status=${status} ok=${ok}`);
|
|
124
|
+
return { ok };
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const refreshMs = normalizeRefreshMs(ctx.options);
|
|
129
|
+
|
|
130
|
+
const timer = setInterval(() => {
|
|
131
|
+
const next = JSON.stringify(readProgressState().entries ?? {});
|
|
132
|
+
if (next === signature) return;
|
|
133
|
+
signature = next;
|
|
134
|
+
void registration.events.emit("updated", { updatedAt: Date.now() }).catch(() => {});
|
|
135
|
+
}, refreshMs);
|
|
136
|
+
|
|
137
|
+
// Inject the progress & relay rules into the agent loop's system
|
|
138
|
+
// instructions so agents know about the out-of-band relay BEFORE their
|
|
139
|
+
// first long-running command, not only from the `progress` tool response.
|
|
140
|
+
// Opt out per project with `{ "options": { "injectInstructions": false } }`.
|
|
141
|
+
let rulesRegistration: Awaited<ReturnType<typeof ctx.session.hook>> | undefined;
|
|
142
|
+
if (instructionsEnabled(ctx.options)) {
|
|
143
|
+
rulesRegistration = await ctx.session.hook("context", (event) => {
|
|
144
|
+
event.system.push({ type: "text", text: PROGRESS_RULES });
|
|
145
|
+
});
|
|
146
|
+
console.log("[opencode-progress] progress rules injected into system instructions");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Ship the usage + demo skills with the package so installing the plugin
|
|
150
|
+
// installs the skills. Opt out per project with
|
|
151
|
+
// `{ "options": { "registerSkills": false } }`.
|
|
152
|
+
if (ctx.options?.registerSkills !== false) {
|
|
153
|
+
await ctx.skill.transform((editor) => {
|
|
154
|
+
for (const skill of PACKAGED_SKILLS) {
|
|
155
|
+
editor.add({
|
|
156
|
+
id: Skill.ID.make(skill.id),
|
|
157
|
+
name: Skill.Name.make(skill.name),
|
|
158
|
+
description: skill.description,
|
|
159
|
+
path: Skill.Info.fields.path.make(path.join(PLUGIN_DIR, "skills", skill.id, "SKILL.md")),
|
|
160
|
+
content: loadPackagedSkillBody(skill.id),
|
|
161
|
+
autoinvoke: true,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
console.log(`[opencode-progress] v${pluginVersion} registered ${PACKAGED_SKILLS.length} packaged skills`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Strict mode: watch tool calls and nudge when the agent works silently
|
|
169
|
+
// (no task entry) or leaves pending tasks' progress unchanged.
|
|
170
|
+
const strictMode = normalizeStrictMode(ctx.options);
|
|
171
|
+
const staleAfterMs = normalizeStaleAfterMs(ctx.options);
|
|
172
|
+
const strictThreshold =
|
|
173
|
+
typeof ctx.options?.strictThreshold === 'number' && ctx.options.strictThreshold >= 2
|
|
174
|
+
? ctx.options.strictThreshold
|
|
175
|
+
: 3;
|
|
176
|
+
const monitors = new Map<string, MonitorState>();
|
|
177
|
+
const verbose = nudgeLoggingEnabled(ctx.options);
|
|
178
|
+
|
|
179
|
+
// Behaviour telemetry: compare every observed store snapshot against the
|
|
180
|
+
// previous one so we can measure how agents drive the lifecycle
|
|
181
|
+
// (null→running start, running→running repeat, running→done finish,
|
|
182
|
+
// done→running reopen, running→waiting pause).
|
|
183
|
+
const statusSnapshots = new Map<string, StatusSnapshot>();
|
|
184
|
+
const observeTransitions = (
|
|
185
|
+
sessionID: string,
|
|
186
|
+
entries: ReadonlyArray<{ id: string; status: string }>
|
|
187
|
+
) => {
|
|
188
|
+
if (!verbose) return;
|
|
189
|
+
const prev = statusSnapshots.get(sessionID) ?? {};
|
|
190
|
+
const { transitions, next } = diffStatuses(prev, entries);
|
|
191
|
+
statusSnapshots.set(sessionID, next);
|
|
192
|
+
for (const transition of transitions) {
|
|
193
|
+
logNudge({
|
|
194
|
+
event: 'transition',
|
|
195
|
+
sessionID,
|
|
196
|
+
id: transition.id,
|
|
197
|
+
from: transition.from,
|
|
198
|
+
to: transition.to,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
const lastSeenProgress = new Map<string, number>();
|
|
203
|
+
const NUDGE_KEY = 'progress-nudge';
|
|
204
|
+
let promptReminderHook: Awaited<ReturnType<typeof ctx.session.hook>> | undefined;
|
|
205
|
+
|
|
206
|
+
let toolHook: Awaited<ReturnType<typeof ctx.tool.hook>> | undefined;
|
|
207
|
+
if (strictMode !== 'off') {
|
|
208
|
+
toolHook = await ctx.tool.hook('execute.after', (event) => {
|
|
209
|
+
try {
|
|
210
|
+
const isProgressCall = /(^|_)progress$/.test(event.tool);
|
|
211
|
+
const entries = Object.values(readProgressState().entries ?? {}).filter(
|
|
212
|
+
(entry) => entry && entry.sessionId === event.sessionID
|
|
213
|
+
);
|
|
214
|
+
const hasActive = entries.some(
|
|
215
|
+
(entry) => entry.status === 'running' || entry.status === 'waiting'
|
|
216
|
+
);
|
|
217
|
+
const lastProgressAt = entries.reduce(
|
|
218
|
+
(max, entry) => Math.max(max, entry.updatedAt ?? 0),
|
|
219
|
+
0
|
|
220
|
+
);
|
|
221
|
+
|
|
222
|
+
const previousSeen = lastSeenProgress.get(event.sessionID) ?? 0;
|
|
223
|
+
const progressAdvanced = lastProgressAt > previousSeen;
|
|
224
|
+
if (lastProgressAt > previousSeen) lastSeenProgress.set(event.sessionID, lastProgressAt);
|
|
225
|
+
observeTransitions(event.sessionID, entries);
|
|
226
|
+
|
|
227
|
+
const monitor = monitors.get(event.sessionID) ?? {
|
|
228
|
+
count: 0,
|
|
229
|
+
callsSinceProgress: 0,
|
|
230
|
+
nudged: false,
|
|
231
|
+
forced: false,
|
|
232
|
+
lastStaleNudgeAt: 0,
|
|
233
|
+
};
|
|
234
|
+
const step = observeToolCall(
|
|
235
|
+
monitor,
|
|
236
|
+
{
|
|
237
|
+
isProgressCall,
|
|
238
|
+
hasActive,
|
|
239
|
+
lastProgressAt: lastProgressAt || undefined,
|
|
240
|
+
progressAdvanced,
|
|
241
|
+
now: Date.now(),
|
|
242
|
+
},
|
|
243
|
+
{ strictMode, staleAfterMs, threshold: strictThreshold }
|
|
244
|
+
);
|
|
245
|
+
|
|
246
|
+
monitor.count = step.count;
|
|
247
|
+
monitor.callsSinceProgress = step.callsSinceProgress;
|
|
248
|
+
monitor.lastStaleNudgeAt = step.lastStaleNudgeAt;
|
|
249
|
+
if (step.action === 'nudge' || step.action === 'force' || step.action === 'stale-nudge') {
|
|
250
|
+
monitor.nudged = true;
|
|
251
|
+
}
|
|
252
|
+
if (step.action === 'force') monitor.forced = true;
|
|
253
|
+
if (step.action === 'clear') monitor.nudged = false;
|
|
254
|
+
monitors.set(event.sessionID, monitor);
|
|
255
|
+
|
|
256
|
+
if (verbose && step.action !== 'none' && step.action !== 'clear') {
|
|
257
|
+
logNudge({
|
|
258
|
+
event: 'strict',
|
|
259
|
+
action: step.action,
|
|
260
|
+
sessionID: event.sessionID,
|
|
261
|
+
count: step.count,
|
|
262
|
+
callsSinceProgress: step.callsSinceProgress,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
if (verbose && event.status === 'completed') {
|
|
266
|
+
const resultText = JSON.stringify(event.result ?? '');
|
|
267
|
+
if (resultText.includes('INVALID USAGE')) {
|
|
268
|
+
logNudge({ event: 'child-list-error', sessionID: event.sessionID, tool: event.tool });
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const text =
|
|
273
|
+
step.action === 'stale-nudge'
|
|
274
|
+
? staleProgressNudge(step.callsSinceProgress)
|
|
275
|
+
: silentRunNudge(step.count);
|
|
276
|
+
|
|
277
|
+
if (step.action === 'nudge' || step.action === 'force' || step.action === 'stale-nudge') {
|
|
278
|
+
void ctx.session.instructions.entry
|
|
279
|
+
.put({ sessionID: event.sessionID, key: NUDGE_KEY, value: text })
|
|
280
|
+
.catch(() => {});
|
|
281
|
+
}
|
|
282
|
+
if (step.action === 'force') {
|
|
283
|
+
void ctx.session
|
|
284
|
+
.synthetic({ sessionID: event.sessionID, text })
|
|
285
|
+
.catch(() => {});
|
|
286
|
+
}
|
|
287
|
+
if (step.action === 'clear') {
|
|
288
|
+
void ctx.session.instructions.entry
|
|
289
|
+
.remove({ sessionID: event.sessionID, key: NUDGE_KEY })
|
|
290
|
+
.catch(() => {});
|
|
291
|
+
}
|
|
292
|
+
} catch (error) {
|
|
293
|
+
console.error('[opencode-progress] strict-mode monitor failed', String(error));
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
console.log(`[opencode-progress] v${pluginVersion} strict mode: ${strictMode} (threshold ${strictThreshold})`);
|
|
297
|
+
if (verbose) {
|
|
298
|
+
logNudge({ event: "config", strictMode, strictThreshold, wallClockMs: normalizeWallClockMs(ctx.options), idleReminder: ctx.options?.idleReminder !== false, unhinged: ctx.options?.unhinged === true });
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// Idle reminder: at turn end (session about to go idle) with open,
|
|
303
|
+
// non-dismissed entries, admit ONE synthetic message — it runs in the
|
|
304
|
+
// same execution instead of the session going idle, so the model gets a
|
|
305
|
+
// turn-end reminder ("you have a tree of todos pending"). Debounced by
|
|
306
|
+
// entry signature + cooldown + per-run cap (monitor.ts).
|
|
307
|
+
const idleTrackers = new Map<string, IdleTracker>();
|
|
308
|
+
let idleHook: Awaited<ReturnType<typeof ctx.session.hook>> | undefined;
|
|
309
|
+
if (ctx.options?.idleReminder !== false) {
|
|
310
|
+
idleHook = await ctx.session.hook('experimental.idle', async (event) => {
|
|
311
|
+
try {
|
|
312
|
+
const entries = Object.values(readProgressState().entries ?? {}).filter(
|
|
313
|
+
(entry) => entry && entry.sessionId === event.sessionID
|
|
314
|
+
);
|
|
315
|
+
const tracker = idleTrackers.get(event.sessionID) ?? { signature: '', lastAt: 0, count: 0 };
|
|
316
|
+
const decision = idleReminder(tracker, entries, { now: Date.now() });
|
|
317
|
+
idleTrackers.set(event.sessionID, {
|
|
318
|
+
signature: decision.signature,
|
|
319
|
+
lastAt: decision.lastAt,
|
|
320
|
+
count: decision.count,
|
|
321
|
+
});
|
|
322
|
+
if (decision.action !== 'remind' || !decision.message) return;
|
|
323
|
+
console.log(`[opencode-progress] v${pluginVersion} idle reminder (${decision.count}) for ${event.sessionID}`);
|
|
324
|
+
if (verbose) {
|
|
325
|
+
logNudge({ event: 'idle-reminder', sessionID: event.sessionID, count: decision.count, openEntries: decision.signature.split(' | ').filter(Boolean).length });
|
|
326
|
+
}
|
|
327
|
+
await ctx.session.synthetic({ sessionID: event.sessionID, text: decision.message });
|
|
328
|
+
} catch (error) {
|
|
329
|
+
console.error('[opencode-progress] idle reminder failed', String(error));
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// "Unhinged" mode (opt-in): append a progress reminder to every user
|
|
335
|
+
// message so the agent re-checks its task list whenever the workload
|
|
336
|
+
// changes. Off by default — it edits user input text.
|
|
337
|
+
if (ctx.options?.unhinged === true) {
|
|
338
|
+
const promptHook = await ctx.session.hook('prompt', (event) => {
|
|
339
|
+
event.prompt.text = `${event.prompt.text}\n\n[did the user's message just change your workload? update your task list!]`;
|
|
340
|
+
if (verbose) logNudge({ event: 'unhinged', sessionID: (event as { sessionID?: string }).sessionID });
|
|
341
|
+
});
|
|
342
|
+
promptReminderHook = promptHook;
|
|
343
|
+
console.log(`[opencode-progress] v${pluginVersion} unhinged mode: prompt suffix enabled`);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Wall-clock nudge: the call-count monitor cannot fire while an agent is
|
|
347
|
+
// blocked (no tool calls ⇒ no events). A 30s timer evaluates every
|
|
348
|
+
// session with pending entries and, after wallClockMs (default 10m) with
|
|
349
|
+
// no progress write, writes a standing instruction — removed again as
|
|
350
|
+
// soon as progress resumes.
|
|
351
|
+
const wallClockMs = normalizeWallClockMs(ctx.options);
|
|
352
|
+
const wallTrackers = new Map<string, WallClockState>();
|
|
353
|
+
const lastToolCallAt = new Map<string, number>();
|
|
354
|
+
const WALL_KEY = 'progress-wall-clock';
|
|
355
|
+
|
|
356
|
+
// Track per-session tool activity so the wall-clock nudge can tell a
|
|
357
|
+
// working-but-silent agent apart from a session stalled in a provider
|
|
358
|
+
// queue (or abandoned). Always registered, even with strict mode off.
|
|
359
|
+
const activityHook = await ctx.tool.hook('execute.after', (event) => {
|
|
360
|
+
lastToolCallAt.set(event.sessionID, Date.now());
|
|
361
|
+
// Delegation telemetry: record subagent launches (Dax's general vs
|
|
362
|
+
// explore question, locally and continuously).
|
|
363
|
+
if (verbose && /subagent|(^|_)task$/.test(event.tool)) {
|
|
364
|
+
const input = (event.input ?? {}) as { agent?: string; subagent_type?: string; description?: string };
|
|
365
|
+
logNudge({
|
|
366
|
+
event: 'subagent',
|
|
367
|
+
sessionID: event.sessionID,
|
|
368
|
+
tool: event.tool,
|
|
369
|
+
agent: input.agent ?? input.subagent_type ?? null,
|
|
370
|
+
description: input.description ?? null,
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
// Pre-flight relay hint: see a long-running command BEFORE it runs and
|
|
376
|
+
// suggest wrapping it in the relay. Detection only — commands are never
|
|
377
|
+
// rewritten. Opt out with { options: { relayHints: false } }.
|
|
378
|
+
const relayHintCooldown = new Map<string, number>();
|
|
379
|
+
let relayHintHook: Awaited<ReturnType<typeof ctx.tool.hook>> | undefined;
|
|
380
|
+
if (ctx.options?.relayHints !== false) {
|
|
381
|
+
relayHintHook = await ctx.tool.hook('execute.before', (event) => {
|
|
382
|
+
try {
|
|
383
|
+
if (!/^(bash|shell)$/.test(event.tool)) return;
|
|
384
|
+
const input = event.input as { command?: string } | undefined;
|
|
385
|
+
const command = typeof input?.command === 'string' ? input.command : '';
|
|
386
|
+
const match = relayHintFor(command);
|
|
387
|
+
if (!match) return;
|
|
388
|
+
const now = Date.now();
|
|
389
|
+
if (now - (relayHintCooldown.get(event.sessionID) ?? 0) < 90_000) return;
|
|
390
|
+
relayHintCooldown.set(event.sessionID, now);
|
|
391
|
+
void ctx.session.instructions.entry
|
|
392
|
+
.put({ sessionID: event.sessionID, key: 'progress-relay-hint', value: relayHintMessage(match) })
|
|
393
|
+
.catch(() => {});
|
|
394
|
+
if (verbose) {
|
|
395
|
+
logNudge({ event: 'relay-hint', sessionID: event.sessionID, command: match.slice(0, 120) });
|
|
396
|
+
}
|
|
397
|
+
} catch (error) {
|
|
398
|
+
console.error('[opencode-progress] relay hint failed', String(error));
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
let wallTimer: ReturnType<typeof setInterval> | undefined;
|
|
404
|
+
if (wallClockMs > 0) {
|
|
405
|
+
wallTimer = setInterval(() => {
|
|
406
|
+
try {
|
|
407
|
+
const entries = Object.values(readProgressState().entries ?? {});
|
|
408
|
+
const sessions = new Set(
|
|
409
|
+
entries.map((entry) => entry?.sessionId).filter((id): id is string => Boolean(id))
|
|
410
|
+
);
|
|
411
|
+
const now = Date.now();
|
|
412
|
+
for (const sessionID of sessions) {
|
|
413
|
+
const sessionEntries = entries.filter((entry) => entry?.sessionId === sessionID);
|
|
414
|
+
observeTransitions(sessionID, sessionEntries);
|
|
415
|
+
const hasActive = sessionEntries.some(
|
|
416
|
+
(entry) => entry.status === 'running' || entry.status === 'waiting'
|
|
417
|
+
);
|
|
418
|
+
const lastProgressAt = sessionEntries.reduce(
|
|
419
|
+
(max, entry) => Math.max(max, entry.updatedAt ?? 0),
|
|
420
|
+
0
|
|
421
|
+
);
|
|
422
|
+
// Progress changed since the last tick ⇒ reset the reminder streak.
|
|
423
|
+
const previousSeen = lastSeenProgress.get(sessionID) ?? 0;
|
|
424
|
+
if (lastProgressAt > previousSeen) lastSeenProgress.set(sessionID, lastProgressAt);
|
|
425
|
+
const tracker = wallTrackers.get(sessionID) ?? { lastAt: 0, streak: 0 };
|
|
426
|
+
if (lastProgressAt > previousSeen) tracker.streak = 0;
|
|
427
|
+
const decision = wallClockNudge(
|
|
428
|
+
tracker,
|
|
429
|
+
{
|
|
430
|
+
hasActive,
|
|
431
|
+
lastProgressAt,
|
|
432
|
+
lastToolCallAt: lastToolCallAt.get(sessionID),
|
|
433
|
+
now,
|
|
434
|
+
},
|
|
435
|
+
{ thresholdMs: wallClockMs }
|
|
436
|
+
);
|
|
437
|
+
wallTrackers.set(sessionID, { lastAt: decision.lastAt, streak: decision.streak });
|
|
438
|
+
|
|
439
|
+
if (decision.action === 'remind' && decision.message) {
|
|
440
|
+
console.log(`[opencode-progress] v${pluginVersion} wall-clock nudge for ${sessionID}`);
|
|
441
|
+
if (verbose) {
|
|
442
|
+
logNudge({ event: 'wall-clock', sessionID, ageMinutes: Math.round((now - lastProgressAt) / 60000), activeEntries: sessionEntries.filter((e) => e.status === 'running' || e.status === 'waiting').length });
|
|
443
|
+
}
|
|
444
|
+
void ctx.session.instructions.entry
|
|
445
|
+
.put({ sessionID, key: WALL_KEY, value: decision.message })
|
|
446
|
+
.catch(() => {});
|
|
447
|
+
} else if (hasActive && now - lastProgressAt < wallClockMs) {
|
|
448
|
+
void ctx.session.instructions.entry
|
|
449
|
+
.remove({ sessionID, key: WALL_KEY })
|
|
450
|
+
.catch(() => {});
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
} catch (error) {
|
|
454
|
+
console.error('[opencode-progress] wall-clock nudge failed', String(error));
|
|
455
|
+
}
|
|
456
|
+
}, 30_000);
|
|
457
|
+
console.log(`[opencode-progress] v${pluginVersion} wall-clock nudge: ${Math.round(wallClockMs / 60000)}m`);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
console.log(`[opencode-progress] server part v${pluginVersion} loaded`);
|
|
461
|
+
|
|
462
|
+
return () => {
|
|
463
|
+
clearInterval(timer);
|
|
464
|
+
if (wallTimer) clearInterval(wallTimer);
|
|
465
|
+
void rulesRegistration?.dispose();
|
|
466
|
+
void toolHook?.dispose();
|
|
467
|
+
void idleHook?.dispose();
|
|
468
|
+
void promptReminderHook?.dispose();
|
|
469
|
+
void activityHook?.dispose();
|
|
470
|
+
void relayHintHook?.dispose();
|
|
471
|
+
};
|
|
472
|
+
},
|
|
473
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Progress & relay rules injected into every session's system instructions.
|
|
3
|
+
*
|
|
4
|
+
* These are the pre-emptive counterpart to the relay hint the `progress` tool
|
|
5
|
+
* returns with every `running` response (see `docs/out-of-band-relay-spec.md`
|
|
6
|
+
* §5.3 and §7.4): the hint teaches the relay AFTER the agent calls the tool;
|
|
7
|
+
* this text makes sure the agent already knows about it BEFORE its first
|
|
8
|
+
* long-running command.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export const PROGRESS_RULES = `Progress reporting rules (progress-server MCP tool + progress-relay). This tool is DUAL PURPOSE:
|
|
12
|
+
(1) A drop-in replacement for the todo/task-tracking tools you might instinctively reach for (todowrite / TaskCreate): task state belongs here, where it also drives the live indicator.
|
|
13
|
+
(2) A wrapper for long-running programmatic tool calls (build scripts, compilers, test suites, installs — anything that reports progress on stdout) via the out-of-band relay.
|
|
14
|
+
- Report ANY multi-step or long-horizon work with the fire-and-forget progress tool — not just shell commands: research, planning, codebase exploration, multi-file refactors, documentation writing — anything expected to run longer than a couple of minutes or a single reply. Call it once at the start (status "running", a clean stable id, parentId for phases like plan → implement → verify), then KEEP IT CURRENT WHILE YOU WORK: non-shell work has no relay, so spend one of your turns between tool calls — roughly every few calls, or whenever you start or finish a step — on a progress update (fresh detail, a progress 0.0–1.0 fraction, or a status change). That between-turn cadence is the todowrite-style data plane that keeps the summary rollup live. Close with "done" or "error" when the work finishes or fails. Keep titles short; put multi-line context in detail. For multi-step plans, make one child entry per step (parentId = the parent task) — never a numbered list inside one title/detail — so each step gets its own status/progress in the rollup.
|
|
15
|
+
- RE-ARM AND REtro-count: when your current progress tree is "done" and you begin new multi-edit work, open a FRESH tree — do not keep working entry-less. And if you find you have ALREADY made 2+ consecutive edits or shell calls on one task with no active progress entry, that is multi-step work by definition: start a tree now (it is never too late — record what is done, what remains).
|
|
16
|
+
- Steering is work: when the user redirects you mid-flight while a tree is in progress, record the steer as a child entry — one line summarizing the ask plus what you plan to do in reaction — and update it as you respond. The user should see their steer land in the rollup.
|
|
17
|
+
- Delegate independent work: subagents run in parallel with fresh context — use explore for read-only searches and general for multi-step work, and omit model so they inherit this session's model. Mirror each workstream as a child progress entry and wait for the completion report instead of polling.
|
|
18
|
+
- Why this tool exists: the transcript — thought traces, tool calls, command output — is a wall of text. The tree is the glance-able layer above it: a live, high-level view of what you are doing, what you are waiting on, and what is next. Keep it accurate at that level. A short headline title, the current step in detail, an honest progress fraction — so the user can read the pill instead of scrolling the log.
|
|
19
|
+
- For long-running shell commands (compilers, test suites, installs, downloads, docker builds, full lint runs), call progress with status "running" first, then run the command THROUGH the out-of-band relay instead of waiting on it: progress-relay --id <id> -- <cmd> (or pipe: <cmd> | progress-relay --id <id>). Use the exact relay command printed in the progress tool response. When the harness supports background commands, run the wrapped command in the background and keep working; the completion notification is your cue for the final milestone.
|
|
20
|
+
- NEVER poll for shell telemetry: no sleep loops, no re-calling progress on a timer for elapsed time or percentages, no reading terminal output in a loop. The relay streams throttled telemetry (latest output line, "45%") into the indicator at zero token cost, and its exit code maps automatically to done/error — do not re-call progress with "done" unless adding semantic detail. (Between-turn updates during non-shell work are the intended cadence, not polling.)
|
|
21
|
+
- If progress-relay is unavailable, report start/done/error boundaries only; the UI derives elapsed time from startedAt.`;
|
|
22
|
+
|
|
23
|
+
/** Resolve whether rule injection is enabled (default: true). */
|
|
24
|
+
export function instructionsEnabled(raw: unknown): boolean {
|
|
25
|
+
const options = (raw ?? {}) as Record<string, unknown>;
|
|
26
|
+
return options.injectInstructions !== false;
|
|
27
|
+
}
|