@jakedowns/progress-tool-opencode-plugin 0.0.0-stage → 2.14.1

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/mcp.ts ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Companion MCP launch resolution.
3
+ *
4
+ * The plugin auto-registers `@jakedowns/progress-tool-mcp`, but it cannot use
5
+ * `process.execPath` as the interpreter. In OpenCode Desktop (and in
6
+ * bun-compiled CLI builds) `process.execPath` is the `opencode` executable,
7
+ * not a JavaScript runtime. OpenCode then receives the MCP entrypoint as a
8
+ * positional project path, tries to `chdir` into the `.js` file, and the
9
+ * server dies with `ENOTDIR` — so `progress`/`list` never register.
10
+ * See https://github.com/jakedowns/progress-tool/issues/1.
11
+ *
12
+ * Resolution order:
13
+ * 1. an explicit `mcpRuntime` plugin option
14
+ * 2. `process.execPath`, only when it really is node/bun/deno
15
+ * 3. node, then bun — on PATH, then in well-known install locations
16
+ * 4. `npx -y @jakedowns/progress-tool-mcp` as a last resort
17
+ */
18
+
19
+ import { existsSync, readdirSync } from "node:fs";
20
+ import os from "node:os";
21
+ import path from "node:path";
22
+
23
+ /** Published companion package, used by the `npx` fallback. */
24
+ export const MCP_PACKAGE = "@jakedowns/progress-tool-mcp";
25
+
26
+ /** Basenames that really are JavaScript runtimes. */
27
+ const RUNTIME_NAMES = new Set(["node", "nodejs", "bun", "deno"]);
28
+
29
+ /**
30
+ * Everything the resolver touches from the outside world is injectable so the
31
+ * launch order can be tested without the host's real PATH or install layout.
32
+ */
33
+ export interface RuntimeProbe {
34
+ /** Explicit runtime from `options.mcpRuntime`. */
35
+ runtime?: string;
36
+ /** Override for `process.execPath` (the OpenCode binary, usually). */
37
+ execPath?: string;
38
+ env?: Record<string, string | undefined>;
39
+ platform?: string;
40
+ home?: string;
41
+ exists?: (candidate: string) => boolean;
42
+ readdir?: (directory: string) => string[];
43
+ }
44
+
45
+ export interface McpLaunch {
46
+ command: string[];
47
+ /** Human-readable explanation for the startup log. */
48
+ source: string;
49
+ }
50
+
51
+ /** True when `execPath` names a JS runtime rather than an application binary. */
52
+ export function isJsRuntime(execPath: string | undefined | null): boolean {
53
+ if (typeof execPath !== "string" || execPath.length === 0) return false;
54
+ // Split on both separators so the check also recognizes Windows paths when
55
+ // inspected from another platform in tests.
56
+ const base = execPath.split(/[\\/]/).pop()?.toLowerCase().replace(/\.(exe|cmd|bat)$/, "") ?? "";
57
+ return RUNTIME_NAMES.has(base);
58
+ }
59
+
60
+ function executableNames(name: string, platform: string): string[] {
61
+ if (platform !== "win32") return [name];
62
+ return [`${name}.exe`, `${name}.cmd`, `${name}.bat`, name];
63
+ }
64
+
65
+ function lookup(
66
+ name: string,
67
+ directories: readonly string[],
68
+ platform: string,
69
+ exists: (candidate: string) => boolean
70
+ ): string | undefined {
71
+ for (const directory of directories) {
72
+ if (!directory) continue;
73
+ for (const file of executableNames(name, platform)) {
74
+ const candidate = path.join(directory, file);
75
+ if (exists(candidate)) return candidate;
76
+ }
77
+ }
78
+ return undefined;
79
+ }
80
+
81
+ /** Search the process PATH for an executable. */
82
+ export function findExecutable(name: string, probe: RuntimeProbe = {}): string | undefined {
83
+ const env = probe.env ?? process.env;
84
+ const platform = probe.platform ?? process.platform;
85
+ const exists = probe.exists ?? existsSync;
86
+ const separator = platform === "win32" ? ";" : ":";
87
+ const rawPath = env.PATH ?? env.Path ?? env.path ?? "";
88
+ const directories = String(rawPath)
89
+ .split(separator)
90
+ .map((entry) => entry.trim())
91
+ .filter(Boolean);
92
+ return lookup(name, directories, platform, exists);
93
+ }
94
+
95
+ /**
96
+ * Install locations worth checking when PATH is minimal — as it is for GUI
97
+ * apps on macOS, where Desktop's server may inherit only
98
+ * `/usr/bin:/bin:/usr/sbin:/sbin`.
99
+ */
100
+ export function knownInstallDirs(probe: RuntimeProbe = {}): string[] {
101
+ const home = probe.home ?? os.homedir();
102
+ const platform = probe.platform ?? process.platform;
103
+ const readdir =
104
+ probe.readdir ??
105
+ ((directory: string): string[] => {
106
+ try {
107
+ return readdirSync(directory);
108
+ } catch {
109
+ return [];
110
+ }
111
+ });
112
+
113
+ const dirs = [
114
+ path.join(home, ".bun", "bin"),
115
+ path.join(home, ".volta", "bin"),
116
+ path.join(home, ".local", "bin"),
117
+ ];
118
+
119
+ if (platform === "win32") {
120
+ dirs.push(path.join(home, "AppData", "Roaming", "npm"));
121
+ } else {
122
+ dirs.push("/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin");
123
+ }
124
+
125
+ // nvm keeps one directory per installed Node version.
126
+ const nvmRoot = path.join(home, ".nvm", "versions", "node");
127
+ for (const version of readdir(nvmRoot)) {
128
+ dirs.push(path.join(nvmRoot, version, "bin"));
129
+ }
130
+
131
+ return dirs;
132
+ }
133
+
134
+ /** Find an executable on PATH, then in the well-known install locations. */
135
+ export function findRuntime(name: string, probe: RuntimeProbe = {}): string | undefined {
136
+ const onPath = findExecutable(name, probe);
137
+ if (onPath) return onPath;
138
+ const platform = probe.platform ?? process.platform;
139
+ const exists = probe.exists ?? existsSync;
140
+ return lookup(name, knownInstallDirs(probe), platform, exists);
141
+ }
142
+
143
+ /**
144
+ * Build the command OpenCode should spawn for the companion MCP server.
145
+ * Returns `null` when no runtime and no `npx` can be found — the caller should
146
+ * then skip auto-registration and tell the user how to configure it manually.
147
+ */
148
+ export function resolveMcpLaunch(entry: string, probe: RuntimeProbe = {}): McpLaunch | null {
149
+ const configured = typeof probe.runtime === "string" ? probe.runtime.trim() : "";
150
+ if (configured) return { command: [configured, entry], source: "options.mcpRuntime" };
151
+
152
+ // Prefer the host runtime when the plugin really runs on a JS runtime
153
+ // (plain `node`/`bun` dev runs). Under Desktop this is the `opencode`
154
+ // binary and is deliberately rejected.
155
+ const execPath = probe.execPath ?? process.execPath;
156
+ if (isJsRuntime(execPath)) {
157
+ return { command: [execPath as string, entry], source: "process.execPath" };
158
+ }
159
+
160
+ for (const name of ["node", "bun"]) {
161
+ const found = findRuntime(name, probe);
162
+ if (found) return { command: [found, entry], source: `${name} (PATH or known install dir)` };
163
+ }
164
+
165
+ const npx = findRuntime("npx", probe);
166
+ if (npx) return { command: [npx, "-y", MCP_PACKAGE], source: "npx fallback" };
167
+
168
+ return null;
169
+ }
package/src/monitor.ts ADDED
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Strict-mode monitor: detect agents calling tools back-to-back without
3
+ * updating progress, and decide whether/how to nudge.
4
+ *
5
+ * Two detection paths:
6
+ *
7
+ * 1. SILENT RUN — the session has no running/waiting entry at all and the
8
+ * agent keeps calling tools. At `threshold` consecutive silent calls:
9
+ * "you're working without a task entry — start one".
10
+ *
11
+ * 2. STALE PROGRESS — the session HAS pending tasks, the agent keeps calling
12
+ * tools, but no progress value has changed (across all roots and
13
+ * descendants) for `staleAfterMs`, AND at least `staleMinCalls` tool calls
14
+ * have happened since that last change. At most once per `cooldownMs`:
15
+ * "you have pending tasks and haven't changed their % recently — any
16
+ * updates?".
17
+ *
18
+ * Progress activity is measured from the store, not from the model's
19
+ * self-reports: any progress write (tool call or relay tick) bumps an
20
+ * entry's updatedAt, which resets the staleness clock and the
21
+ * calls-since-progress counter.
22
+ *
23
+ * Pure decision logic — no I/O — so it is unit-testable. The plugin server
24
+ * part applies the decision: an instructions entry (visible to the model at
25
+ * the next step boundary, without queuing a message turn) for "nudge" /
26
+ * "stale-nudge", plus a synthetic message for "force".
27
+ */
28
+
29
+ export type StrictMode = "nudge" | "force" | "off";
30
+
31
+ export interface MonitorState {
32
+ /** Consecutive tool calls with no active entry. */
33
+ count: number;
34
+ /** Tool calls since any progress value changed (tool write or relay tick). */
35
+ callsSinceProgress: number;
36
+ /** A silent-run nudge is currently standing (instructions entry present). */
37
+ nudged: boolean;
38
+ /** A forced synthetic reminder was already sent this non-compliance run. */
39
+ forced: boolean;
40
+ /** Epoch ms of the last stale-progress nudge (cooldown). */
41
+ lastStaleNudgeAt: number;
42
+ }
43
+
44
+ export type MonitorAction = "none" | "nudge" | "force" | "clear" | "stale-nudge";
45
+
46
+ export interface ObserveInput {
47
+ /** The call was to the progress tool itself. */
48
+ isProgressCall: boolean;
49
+ /** The session currently has a running/waiting progress entry. */
50
+ hasActive: boolean;
51
+ /** Epoch ms of the last progress write across all roots + descendants. */
52
+ lastProgressAt?: number;
53
+ /** True when the store's newest update is newer than the last observed one. */
54
+ progressAdvanced?: boolean;
55
+ /** Epoch ms now. */
56
+ now?: number;
57
+ }
58
+
59
+ export interface ObserveOptions {
60
+ threshold?: number;
61
+ strictMode?: StrictMode;
62
+ /** No progress write for this long with pending tasks ⇒ stale nudge. Default 5 min. */
63
+ staleAfterMs?: number;
64
+ /** Tool calls since the last progress write before a stale nudge. Default 3. */
65
+ staleMinCalls?: number;
66
+ /** Minimum gap between stale nudges. Default 2 min. */
67
+ cooldownMs?: number;
68
+ }
69
+
70
+ export function normalizeStrictMode(raw: unknown): StrictMode {
71
+ const value = (raw ?? {}) as Record<string, unknown>;
72
+ if (value.strictMode === "force") return "force";
73
+ if (value.strictMode === "off") return "off";
74
+ return "nudge";
75
+ }
76
+
77
+ export function normalizeStaleAfterMs(raw: unknown, fallback = 5 * 60 * 1000): number {
78
+ const value = (raw ?? {}) as Record<string, unknown>;
79
+ const ms = value.staleAfterMs;
80
+ return typeof ms === "number" && Number.isFinite(ms) && ms >= 30_000 ? ms : fallback;
81
+ }
82
+
83
+ /**
84
+ * Decide the response to one observed tool call.
85
+ *
86
+ * Precedence: a progress call always clears a standing nudge and resets all
87
+ * counters. With pending tasks, stale-progress detection applies; without
88
+ * them, silent-run detection applies.
89
+ */
90
+ export function observeToolCall(
91
+ monitor: MonitorState,
92
+ input: ObserveInput,
93
+ options: ObserveOptions = {}
94
+ ): { action: MonitorAction; count: number; callsSinceProgress: number; lastStaleNudgeAt: number } {
95
+ const threshold = options.threshold ?? 3;
96
+ const strictMode = options.strictMode ?? 'nudge';
97
+ const staleAfterMs = options.staleAfterMs ?? 5 * 60 * 1000;
98
+ const staleMinCalls = options.staleMinCalls ?? 3;
99
+ const cooldownMs = options.cooldownMs ?? 2 * 60 * 1000;
100
+
101
+ const untouched = {
102
+ count: monitor.count,
103
+ callsSinceProgress: monitor.callsSinceProgress,
104
+ lastStaleNudgeAt: monitor.lastStaleNudgeAt,
105
+ };
106
+
107
+ if (strictMode === 'off') return { action: 'none', count: 0, callsSinceProgress: 0, lastStaleNudgeAt: monitor.lastStaleNudgeAt };
108
+
109
+ if (input.isProgressCall) {
110
+ return {
111
+ action: monitor.nudged ? 'clear' : 'none',
112
+ count: 0,
113
+ callsSinceProgress: 0,
114
+ lastStaleNudgeAt: monitor.lastStaleNudgeAt,
115
+ };
116
+ }
117
+
118
+ // A relay tick (or any write since the last observation) is progress
119
+ // activity: reset the staleness clock and the counter.
120
+ const callsSinceProgress = input.progressAdvanced ? 0 : monitor.callsSinceProgress + 1;
121
+ const now = input.now ?? Date.now();
122
+ const lastProgressAt = input.lastProgressAt ?? now;
123
+
124
+ if (input.hasActive) {
125
+ // Compliant on the "has a task" axis. A standing nudge entry clears only
126
+ // when actual progress happened (a progress call or a store write) —
127
+ // otherwise a stale-progress reminder would be wiped by the very next
128
+ // tool call before the agent acted on it.
129
+ const progressed = input.progressAdvanced === true;
130
+ const clearAction: MonitorAction = monitor.nudged && progressed ? 'clear' : 'none';
131
+ const age = now - lastProgressAt;
132
+ if (
133
+ age >= staleAfterMs &&
134
+ callsSinceProgress >= staleMinCalls &&
135
+ now - monitor.lastStaleNudgeAt >= cooldownMs
136
+ ) {
137
+ return { action: 'stale-nudge', count: 0, callsSinceProgress, lastStaleNudgeAt: now };
138
+ }
139
+ return { action: clearAction, count: 0, callsSinceProgress, lastStaleNudgeAt: monitor.lastStaleNudgeAt };
140
+ }
141
+
142
+ const count = monitor.count + 1;
143
+ if (count >= threshold && !monitor.nudged) {
144
+ if (strictMode === 'force' && !monitor.forced) {
145
+ return { action: 'force', count, callsSinceProgress, lastStaleNudgeAt: monitor.lastStaleNudgeAt };
146
+ }
147
+ return { action: 'nudge', count, callsSinceProgress, lastStaleNudgeAt: monitor.lastStaleNudgeAt };
148
+ }
149
+ return { ...untouched, action: 'none', count, callsSinceProgress };
150
+ }
151
+
152
+ /** The standing instructions-entry nudge text (silent run). */
153
+ export function silentRunNudge(count: number): string {
154
+ return `⚠ STRICT MODE: ${count} consecutive tool calls with no progress entry. Call the progress tool NOW (status "running", a stable id, a short title), then keep it current between steps — see the progress-tool skill.`;
155
+ }
156
+
157
+ /** The stale-progress nudge text (pending tasks, unchanged %). */
158
+ export function staleProgressNudge(callsSinceProgress: number): string {
159
+ return `⚠ STRICT MODE: ${callsSinceProgress} tool calls since any progress value changed, and you have pending tasks — any updates? Update the running entries now (fresh detail and a 0.0–1.0 progress fraction, or close what is finished), or mark them waiting.`;
160
+ }
161
+
162
+ // --- Relay hint (pre-flight, before the command runs) ---------------------
163
+
164
+ const LONG_COMMAND_RE =
165
+ /\b(?:npm|pnpm|yarn|bun)\s+(?:test|run\s+(?:build|test|lint|check|typecheck))\b|\b(?:vite\s+build|webpack|rollup|jest|vitest|pytest|cargo\s+(?:build|test)|go\s+(?:build|test)|make\b|gradle|mvn|docker\s+build)\b/i;
166
+
167
+ /**
168
+ * Detect a long-running command that is NOT already piped through the relay.
169
+ * Returns the command when a hint should be shown, otherwise null. Detection
170
+ * only — the plugin never rewrites the command.
171
+ */
172
+ export function relayHintFor(command: string | null | undefined): string | null {
173
+ if (!command || typeof command !== "string") return null;
174
+ // Already relayed: the bin/alias, or the bundled invocation path.
175
+ if (/progress-relay|progress-emit|index\.js\s+relay\b/.test(command)) return null;
176
+ // Git operations are fast; their commit messages often mention test/build
177
+ // commands in prose, which must not trigger a relay hint.
178
+ if (/^\s*git\b/.test(command)) return null;
179
+ if (!LONG_COMMAND_RE.test(command)) return null;
180
+ return command.trim();
181
+ }
182
+
183
+ export function relayHintMessage(command: string): string {
184
+ const shown = command.length > 90 ? `${command.slice(0, 87)}…` : command;
185
+ return [
186
+ `⚠ This looks long-running — wrap it in the out-of-band relay so the UI stays live at zero token cost:`,
187
+ ` progress-relay --id <id> -- ${shown}`,
188
+ ` # or: ${shown} | progress-relay --id <id>`,
189
+ `Wrap mode maps the exit code to done/error. Run it in the background and keep working.`,
190
+ ].join("\n");
191
+ }
192
+
193
+ // --- Idle reminder (turn-end nudge) --------------------------------------
194
+
195
+ export interface IdleEntry {
196
+ id: string;
197
+ title?: string;
198
+ status: string;
199
+ dismissed?: { at: number } | null;
200
+ /** Epoch ms of the entry's last write; relay ticks keep this fresh. */
201
+ updatedAt?: number;
202
+ }
203
+
204
+ export interface IdleTracker {
205
+ /** Sorted signature of the open entries at the last reminder. */
206
+ signature: string;
207
+ /** Epoch ms of the last reminder. */
208
+ lastAt: number;
209
+ /** Reminders sent for the current (unchanged) signature. */
210
+ count: number;
211
+ }
212
+
213
+ export interface IdleDecision {
214
+ action: "remind" | "none";
215
+ signature: string;
216
+ lastAt: number;
217
+ count: number;
218
+ message?: string;
219
+ }
220
+
221
+ /**
222
+ * Decide whether to remind the model on session idle (turn end).
223
+ *
224
+ * Fires when the session is about to go idle with open (running/waiting,
225
+ * non-dismissed) entries. Guardrails against loops — the synthetic message
226
+ * runs in the same execution, so an agent that ignores it would otherwise
227
+ * idle again immediately:
228
+ * - Same signature re-idles are suppressed until `cooldownMs` and capped at
229
+ * `maxPerRun` reminders; a changed signature resets the count.
230
+ */
231
+ export function idleReminder(
232
+ tracker: IdleTracker,
233
+ entries: readonly IdleEntry[],
234
+ options: { cooldownMs?: number; maxPerRun?: number; now?: number; staleAfterMs?: number } = {}
235
+ ): IdleDecision {
236
+ const cooldownMs = options.cooldownMs ?? 120_000;
237
+ const maxPerRun = options.maxPerRun ?? 3;
238
+ const now = options.now ?? Date.now();
239
+ // Relay-driven tasks tick several times per second; only entries nobody is
240
+ // writing to deserve an idle nag. Unknown timestamps count as stale.
241
+ const staleAfterMs = options.staleAfterMs ?? 5 * 60_000;
242
+
243
+ const open = entries
244
+ .filter(
245
+ (entry) =>
246
+ (entry.status === "running" || entry.status === "waiting") &&
247
+ !entry.dismissed &&
248
+ (entry.updatedAt == null || now - entry.updatedAt >= staleAfterMs)
249
+ )
250
+ .map((entry) => `${entry.id} (${entry.status})`)
251
+ .sort();
252
+ const signature = open.join(" | ");
253
+
254
+ if (open.length === 0) {
255
+ return { action: "none", signature, lastAt: tracker.lastAt, count: 0 };
256
+ }
257
+
258
+ const changed = signature !== tracker.signature;
259
+ const count = changed ? 0 : tracker.count;
260
+ if (!changed && (count >= maxPerRun || now - tracker.lastAt < cooldownMs)) {
261
+ return { action: "none", signature, lastAt: tracker.lastAt, count };
262
+ }
263
+
264
+ const message = [
265
+ `⚠ IDLE WITH OPEN TASKS (${open.length}): ${open.join(", ")}.`,
266
+ `You are about to go idle, but these progress entries are still running/waiting.`,
267
+ `Close what is finished (status "done" or "error"), mark genuinely blocked work "waiting" with a detail, or continue the work now. Do not leave stale trees behind.`,
268
+ ].join(" ");
269
+
270
+ return { action: "remind", signature, lastAt: now, count: count + 1, message };
271
+ }
272
+
273
+ // --- Wall-clock nudge -----------------------------------------------------
274
+
275
+ export interface WallClockState {
276
+ /** Epoch ms of the last wall-clock reminder for this session. */
277
+ lastAt: number;
278
+ /** Consecutive reminders since progress last changed (throttle). */
279
+ streak?: number;
280
+ }
281
+
282
+ export interface WallClockInput {
283
+ /** Pending (running/waiting) entries exist for the session. */
284
+ hasActive: boolean;
285
+ /** Epoch ms of the newest progress write across the session's entries. */
286
+ lastProgressAt?: number;
287
+ /**
288
+ * Epoch ms of the session's last tool call. Unset ⇒ dormant session: it may
289
+ * simply be queued at the inference provider, so do not nag.
290
+ */
291
+ lastToolCallAt?: number;
292
+ /** Epoch ms now. */
293
+ now?: number;
294
+ }
295
+
296
+ export interface WallClockOptions {
297
+ /** No progress write for this long ⇒ remind. Default 2 minutes; 0 disables. */
298
+ thresholdMs?: number;
299
+ /** Minimum gap between wall-clock reminders. Default: same as threshold. */
300
+ cooldownMs?: number;
301
+ /**
302
+ * Only remind sessions that called a tool within this window. Default
303
+ * 10 minutes — a session idle longer than this is likely stalled upstream
304
+ * (model queueing/throttling) or abandoned; nagging it is noise.
305
+ */
306
+ activeWindowMs?: number;
307
+ /** Cap reminders per non-progress stretch. Default 3; 0 = uncapped. */
308
+ maxStreak?: number;
309
+ }
310
+
311
+ export function normalizeWallClockMs(raw: unknown, fallback = 2 * 60 * 1000): number {
312
+ const value = (raw ?? {}) as Record<string, unknown>;
313
+ const ms = value.wallClockMs;
314
+ if (ms === 0) return 0; // explicitly disabled
315
+ return typeof ms === "number" && Number.isFinite(ms) && ms >= 60_000 ? ms : fallback;
316
+ }
317
+
318
+ /**
319
+ * Wall-clock reminder: the dimension the call-count monitor cannot cover.
320
+ *
321
+ * The tool-call monitor only fires when the agent calls tools. An agent that
322
+ * is blocked — waiting on a background task it never wrapped in the relay, or
323
+ * simply thinking for a long time — produces no events at all, so without a
324
+ * timer nothing would nudge it. The plugin evaluates this on a 30s interval
325
+ * for every session with pending entries.
326
+ */
327
+ export function wallClockNudge(
328
+ state: WallClockState,
329
+ input: WallClockInput,
330
+ options: WallClockOptions = {}
331
+ ): { action: "remind" | "none"; lastAt: number; streak: number; message?: string } {
332
+ const thresholdMs = options.thresholdMs ?? 2 * 60 * 1000;
333
+ const cooldownMs = options.cooldownMs ?? thresholdMs;
334
+ const activeWindowMs = options.activeWindowMs ?? 10 * 60 * 1000;
335
+ const maxStreak = options.maxStreak ?? 3;
336
+ const now = input.now ?? Date.now();
337
+ const streak = state.streak ?? 0;
338
+
339
+ if (thresholdMs <= 0 || !input.hasActive) {
340
+ return { action: "none", lastAt: state.lastAt, streak };
341
+ }
342
+ // Dormant session: no tool calls recently. This is the provider-queueing /
343
+ // abandoned case — the agent may be stalled upstream, not neglectful.
344
+ if (input.lastToolCallAt == null || now - input.lastToolCallAt > activeWindowMs) {
345
+ return { action: "none", lastAt: state.lastAt, streak };
346
+ }
347
+ // Throttle: a few reminders per non-progress stretch is plenty; more only
348
+ // trains the model to ignore them.
349
+ if (maxStreak > 0 && streak >= maxStreak) {
350
+ return { action: "none", lastAt: state.lastAt, streak };
351
+ }
352
+
353
+ const lastProgressAt = input.lastProgressAt ?? now;
354
+ const age = now - lastProgressAt;
355
+ if (age < thresholdMs) return { action: "none", lastAt: state.lastAt, streak };
356
+ if (now - state.lastAt < cooldownMs) return { action: "none", lastAt: state.lastAt, streak };
357
+
358
+ const minutes = Math.max(1, Math.round(age / 60_000));
359
+ const message = [
360
+ `⚠ WALL CLOCK: it has been ~${minutes} minute${minutes === 1 ? "" : "s"} since any progress value changed, and you still have open tasks.`,
361
+ `Update the tracker now (fresh detail, a 0.0–1.0 progress fraction, or close what is finished).`,
362
+ `If you are waiting on a long-running command, route it through the out-of-band relay so telemetry stays live without polling: progress-relay --id <id> -- <cmd>.`,
363
+ ].join(" ");
364
+
365
+ return { action: "remind", lastAt: now, streak: streak + 1, message };
366
+ }
package/src/rpc.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * RPC contract shared by the server part, the TUI part, and the GUI bundle.
3
+ *
4
+ * `list` returns the current entries from the shared state file. `updated`
5
+ * fires when the server observes a change, so GUI windows do not have to poll.
6
+ */
7
+
8
+ import { Rpc } from "@opencode/plugin/rpc";
9
+
10
+ export const ProgressRpc = Rpc.define({
11
+ id: "opencode-progress",
12
+ methods: {
13
+ list: {
14
+ input: {
15
+ // Empty schema: accept `list()` from older bundles and `list({})`.
16
+ },
17
+ output: {
18
+ type: "object",
19
+ properties: {
20
+ entries: { type: "object", additionalProperties: true },
21
+ updatedAt: { type: "number" },
22
+ },
23
+ required: ["entries", "updatedAt"],
24
+ additionalProperties: false,
25
+ },
26
+ },
27
+ dismiss: {
28
+ input: {
29
+ type: "object",
30
+ properties: {
31
+ // Storage key (may be session-scoped), not the bare task id.
32
+ key: { type: "string" },
33
+ // Rolled-up status at dismiss time; drives revival semantics
34
+ // (terminal vs non-terminal, child-failure carve-out).
35
+ status: { type: "string" },
36
+ },
37
+ required: ["key", "status"],
38
+ additionalProperties: false,
39
+ },
40
+ output: {
41
+ type: "object",
42
+ properties: { ok: { type: "boolean" } },
43
+ required: ["ok"],
44
+ additionalProperties: false,
45
+ },
46
+ },
47
+ },
48
+ events: {
49
+ updated: {
50
+ schema: {
51
+ type: "object",
52
+ properties: {
53
+ updatedAt: { type: "number" },
54
+ },
55
+ required: ["updatedAt"],
56
+ additionalProperties: false,
57
+ },
58
+ },
59
+ },
60
+ });
package/src/state.ts ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Reads the progress state file written by the progress MCP server and relay.
3
+ *
4
+ * The path must match `mcp-server/state-store.js` so the TUI and server parts
5
+ * see the same entries as the `progress` tool.
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import type { ProgressState } from "./types.js";
12
+
13
+ export function stateFilePath(): string {
14
+ return (
15
+ process.env.PROGRESS_STATE_PATH ||
16
+ path.join(process.env.HOME || process.env.USERPROFILE || os.tmpdir(), ".opencode-progress-state.json")
17
+ );
18
+ }
19
+
20
+ export function readProgressState(): ProgressState {
21
+ try {
22
+ const parsed = JSON.parse(fs.readFileSync(stateFilePath(), "utf8"));
23
+ if (parsed && typeof parsed === "object" && parsed.entries && typeof parsed.entries === "object") {
24
+ return parsed as ProgressState;
25
+ }
26
+ } catch {
27
+ // Missing or mid-write state file: treat as empty until the next tick.
28
+ }
29
+ return { entries: {}, version: 2 };
30
+ }
31
+
32
+ /**
33
+ * Persist a user dismissal into the shared state doc as view-plane metadata:
34
+ *
35
+ * entry.dismissed = { status, at }
36
+ *
37
+ * The status snapshot drives the shared revival semantics (see tree.ts
38
+ * `isDismissed`): terminal dismissals (done/error) only revive on a direct
39
+ * re-report or a child failure; non-terminal ones also revive on any
40
+ * rolled-up status change. Agent/relay upserts preserve the field (mcp-server
41
+ * state-store §4.5 merge semantics) and lifecycle restarts clear it.
42
+ *
43
+ * Writes follow the same contract as the relay: atomic temp-file + rename
44
+ * under a sibling lock file (spec §4.3/§4.4). A failed write is logged and
45
+ * left to the next attempt — dismissal is never worth breaking the view over.
46
+ */
47
+ export function writeDismissal(key: string, status: string): boolean {
48
+ const file = stateFilePath();
49
+ const lock = `${file}.lock`;
50
+
51
+ // Acquire the sibling lock (open "wx", break a lock older than 15s).
52
+ let locked = false;
53
+ for (let attempt = 0; attempt < 10 && !locked; attempt++) {
54
+ try {
55
+ fs.writeFileSync(lock, String(process.pid), { flag: "wx" });
56
+ locked = true;
57
+ } catch {
58
+ try {
59
+ if (Date.now() - fs.statSync(lock).mtimeMs > 15_000) fs.unlinkSync(lock);
60
+ } catch {
61
+ // Lock vanished or stat failed; retry briefly.
62
+ }
63
+ try {
64
+ // Brief synchronous pause; Node allows blocking Atomics.wait.
65
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
66
+ } catch {
67
+ // Restricted context: fall through to the next attempt immediately.
68
+ }
69
+ }
70
+ }
71
+ if (!locked) return false;
72
+
73
+ try {
74
+ const state = readProgressState();
75
+ const entry = state.entries[key];
76
+ if (!entry) return false;
77
+ entry.dismissed = { status, at: Date.now() };
78
+ state.version = state.version ?? 2;
79
+ const tmp = `${file}.${process.pid}.tmp`;
80
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2));
81
+ fs.renameSync(tmp, file);
82
+ console.log(`[opencode-progress] dismissal persisted key=${key} status=${status} at=${entry.dismissed.at}`);
83
+ return true;
84
+ } catch (error) {
85
+ console.error("[opencode-progress] dismissal write failed", String(error));
86
+ return false;
87
+ } finally {
88
+ try {
89
+ fs.unlinkSync(lock);
90
+ } catch {
91
+ // Already released.
92
+ }
93
+ }
94
+ }