@igorjpimenta/winch-opencode 2026.11.19-beta.1 → 2026.11.23-beta.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.
Files changed (4) hide show
  1. package/hooks.js +16 -2
  2. package/index.js +131 -19
  3. package/package.json +4 -3
  4. package/usage.js +120 -0
package/hooks.js CHANGED
@@ -1,9 +1,14 @@
1
1
  import { stampWinchIdentity } from "./identity.js";
2
+ import { carriesItemId, isFinalAssistant, remember, reportAssistantUsage } from "./usage.js";
2
3
 
3
4
  // The agent is not on the tool call, only the session: remember it from the
4
5
  // chat events that carry both, then stamp the pair on every winch call.
5
- export function createWinchHooks({ consumerId = null, instanceId = null } = {}) {
6
+ export function createWinchHooks({ consumerId = null, instanceId = null, harness = "opencode", logger = console } = {}) {
6
7
  const agents = new Map();
8
+ const reported = new Set();
9
+ // Usage is reported only for sessions that have made a winch call, which is
10
+ // when the session is bound to an item the server can attribute it to.
11
+ const engaged = new Set();
7
12
 
8
13
  return {
9
14
  "chat.message": async (input) => {
@@ -16,7 +21,16 @@ export function createWinchHooks({ consumerId = null, instanceId = null } = {})
16
21
  // Unconditional: when the agent is unknown the slot is blanked, so a
17
22
  // model-supplied pair can never ride through as identity. Blank means
18
23
  // unstamped, and the server refuses that rather than trusting it.
19
- stampWinchIdentity(input, output, { agent: agents.get(input?.sessionID) ?? process.env.WINCH_AGENT ?? null, consumerId, instanceId });
24
+ const stamped = stampWinchIdentity(input, output, { agent: agents.get(input?.sessionID) ?? process.env.WINCH_AGENT ?? null, consumerId, instanceId });
25
+ if (stamped && carriesItemId(output.args)) remember(engaged, input?.sessionID);
26
+ },
27
+ // A final assistant message carries the turn's cost and token snapshot.
28
+ event: async ({ event } = {}) => {
29
+ if (event?.type !== "message.updated") return;
30
+ const info = event.properties?.info;
31
+ if (!engaged.has(info?.sessionID) || !isFinalAssistant(info) || !remember(reported, info.id)) return;
32
+ const agent = agents.get(info?.sessionID) ?? info?.agent ?? process.env.WINCH_AGENT ?? null;
33
+ reportAssistantUsage({ info, harness, agent, logger });
20
34
  },
21
35
  };
22
36
  }
package/index.js CHANGED
@@ -1,24 +1,110 @@
1
1
  import { createWinchHooks } from "./hooks.js";
2
2
  import { stampWinchEvent } from "./identity.js";
3
3
  import { startDispatch, DEFAULT_DISPATCH_URL } from "./dispatch.js";
4
- import { spawn } from "node:child_process";
5
- import { hostname } from "node:os";
4
+ import { carriesItemId, isFinalAssistant, remember, reportAssistantUsage } from "./usage.js";
5
+ import { spawn, execFileSync } from "node:child_process";
6
+ import { mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import os, { hostname } from "node:os";
8
+ import path from "node:path";
6
9
 
7
- function opencodeWake({ agent, message }) {
8
- return new Promise((resolve, reject) => {
9
- const bin = process.env.OPENCODE_BIN || "opencode";
10
- const child = spawn(bin, ["run", "--agent", agent, message], {
11
- detached: true,
12
- stdio: ["ignore", "ignore", "pipe"],
10
+ // A wake child is orphaned only when the process that spawned it is gone. A
11
+ // child whose owner is still running is doing real work, so it must not be
12
+ // reaped. The sweep therefore kills nothing except leftovers from a dead owner.
13
+ const SWEEP_MS = 60 * 1000;
14
+
15
+ function wakeStateDir() {
16
+ return path.join(os.homedir(), ".opencode", "state", "winch-wakes");
17
+ }
18
+
19
+ function pidAlive(pid) {
20
+ try { process.kill(pid, 0); return true; }
21
+ catch (err) { return err?.code === "EPERM"; }
22
+ }
23
+
24
+ function processCommand(pid) {
25
+ try {
26
+ return execFileSync("ps", ["-o", "command=", "-p", String(pid)], { encoding: "utf8" }).trim();
27
+ } catch {
28
+ return "";
29
+ }
30
+ }
31
+
32
+ export function createWakeRunner({ logger = console, stateDir = wakeStateDir() } = {}) {
33
+ // Detached children lead their own process group; kill the group so a
34
+ // reaped turn's tool and MCP subprocesses go with it.
35
+ const reap = (pid) => {
36
+ try { process.kill(-pid, "SIGKILL"); }
37
+ catch { try { process.kill(pid, "SIGKILL"); } catch {} }
38
+ };
39
+
40
+ const recordPath = (ownerPid, childPid) => path.join(stateDir, `wake-${ownerPid}-${childPid}.json`);
41
+
42
+ const wake = ({ agent, message }) =>
43
+ new Promise((resolve, reject) => {
44
+ const bin = process.env.OPENCODE_BIN || "opencode";
45
+ const child = spawn(bin, ["run", "--agent", agent, message], {
46
+ detached: true,
47
+ stdio: ["ignore", "ignore", "pipe"],
48
+ // A wake child loads the same config and would start its own dispatch
49
+ // listener, registering as another executor; then every wake fans out
50
+ // into more waking agents. Keep dispatch to the root instance only.
51
+ env: { ...process.env, WINCH_DISPATCH_ENABLED: "0" },
52
+ });
53
+ const file = child.pid ? recordPath(process.pid, child.pid) : null;
54
+ if (file) {
55
+ try {
56
+ mkdirSync(stateDir, { recursive: true });
57
+ writeFileSync(file, JSON.stringify({ pid: child.pid, ownerPid: process.pid, agent, message }));
58
+ } catch (err) {
59
+ logger?.warn?.(`winch: wake record not written: ${err?.message ?? err}`);
60
+ }
61
+ }
62
+ const forget = () => { try { if (file) unlinkSync(file); } catch {} };
63
+ let stderr = "";
64
+ child.stderr?.on("data", (d) => { stderr = (stderr + d.toString()).slice(-2000); });
65
+ child.on("error", (err) => { forget(); reject(err); });
66
+ child.on("exit", (code) => {
67
+ forget();
68
+ code === 0 ? resolve() : reject(new Error(`exit ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`));
69
+ });
70
+ // Unref: an agent run must not hold its caller's event loop open, or a
71
+ // daemon could not shut down while a wake is in flight. A caller that
72
+ // awaits wake() must therefore keep its own handle alive — the exit
73
+ // event will not dispatch on an otherwise empty loop.
74
+ child.unref();
13
75
  });
14
- let stderr = "";
15
- child.stderr?.on("data", (d) => { stderr = (stderr + d.toString()).slice(-2000); });
16
- child.on("error", reject);
17
- child.on("exit", (code) =>
18
- code === 0 ? resolve() : reject(new Error(`exit ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`))
19
- );
20
- child.unref();
21
- });
76
+
77
+ // Kill wake children whose spawning owner is no longer alive. Called at
78
+ // dispatch startup and on a sweep timer; never on close, because a child
79
+ // still owned by a live instance is not an orphan.
80
+ function reapOrphans() {
81
+ let names = [];
82
+ try { names = readdirSync(stateDir); } catch { return 0; }
83
+ let killed = 0;
84
+ for (const name of names) {
85
+ if (!name.startsWith("wake-") || !name.endsWith(".json")) continue;
86
+ const file = path.join(stateDir, name);
87
+ let entry;
88
+ try { entry = JSON.parse(readFileSync(file, "utf8")); }
89
+ catch { try { unlinkSync(file); } catch {} continue; }
90
+ if (!entry?.pid || !entry?.ownerPid) { try { unlinkSync(file); } catch {} continue; }
91
+ if (pidAlive(entry.ownerPid)) continue; // owner alive: not an orphan
92
+ if (pidAlive(entry.pid)) {
93
+ // Guard PID reuse: only kill a process still running this wake's
94
+ // command, never whatever now occupies the recycled pid.
95
+ const cmd = processCommand(entry.pid);
96
+ if (cmd.includes("--agent") && entry.message && cmd.includes(entry.message)) {
97
+ reap(entry.pid);
98
+ killed += 1;
99
+ }
100
+ }
101
+ try { unlinkSync(file); } catch {}
102
+ }
103
+ if (killed) logger?.warn?.(`winch: reaped ${killed} orphaned wake(s)`);
104
+ return killed;
105
+ }
106
+
107
+ return { wake, reapOrphans };
22
108
  }
23
109
 
24
110
  function consumerIdFor(harness, cfg = {}) {
@@ -26,6 +112,9 @@ function consumerIdFor(harness, cfg = {}) {
26
112
  }
27
113
 
28
114
  function start({ cfg = {}, harness, logger }) {
115
+ const runner = createWakeRunner({ logger, stateDir: cfg.wakeStateDir });
116
+ runner.reapOrphans();
117
+
29
118
  const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
30
119
  const consumerId = consumerIdFor(harness, cfg);
31
120
  const bearer = process.env.WINCH_WEBHOOK_BEARER;
@@ -39,12 +128,18 @@ function start({ cfg = {}, harness, logger }) {
39
128
  consumerId,
40
129
  executorId,
41
130
  bearer,
42
- wake: opencodeWake,
131
+ wake: runner.wake,
43
132
  port: Number(cfg.dispatchPort ?? process.env.WINCH_DISPATCH_PORT ?? 0),
44
133
  reconcileMs: Number(cfg.dispatchReconcileMs ?? process.env.WINCH_DISPATCH_RECONCILE_MS ?? 30000),
45
134
  logger,
46
135
  });
47
136
  dispatch.ready.catch((err) => logger?.warn?.(`winch: dispatch listener failed: ${err?.message ?? err}`));
137
+
138
+ const sweep = setInterval(() => runner.reapOrphans(), Number(cfg.wakeSweepMs ?? SWEEP_MS));
139
+ sweep.unref?.();
140
+ const close = dispatch.close.bind(dispatch);
141
+ dispatch.close = async () => { clearInterval(sweep); await close(); };
142
+ dispatch.reapOrphans = runner.reapOrphans;
48
143
  return dispatch;
49
144
  }
50
145
 
@@ -61,6 +156,8 @@ export default {
61
156
  const consumerId = consumerIdFor(harness, cfg);
62
157
  const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID ?? null;
63
158
  const agents = new Map();
159
+ const reported = new Set();
160
+ const engaged = new Set();
64
161
  let dispatch = null;
65
162
  const ensureDispatch = () => {
66
163
  if (dispatch) return;
@@ -75,14 +172,29 @@ export default {
75
172
  const agent = agents.get(event.sessionID) ?? process.env.WINCH_AGENT ?? null;
76
173
  // Unconditional: unknown agent blanks the slot, the server refuses
77
174
  // rather than trusting whatever the model wrote there.
78
- stampWinchEvent(event, agent, consumerId, executorId);
175
+ if (stampWinchEvent(event, agent, consumerId, executorId) && carriesItemId(event.input)) remember(engaged, event.sessionID);
79
176
  });
177
+ if (typeof ctx.event?.subscribe === "function") {
178
+ const controller = new AbortController();
179
+ void (async () => {
180
+ try {
181
+ for await (const event of ctx.event.subscribe({ types: ["message.updated"], signal: controller.signal })) {
182
+ if (event?.type !== "message.updated") continue;
183
+ const info = event.properties?.info;
184
+ if (!engaged.has(info?.sessionID) || !isFinalAssistant(info) || !remember(reported, info.id)) continue;
185
+ const agent = agents.get(info?.sessionID) ?? info?.agent ?? process.env.WINCH_AGENT ?? null;
186
+ reportAssistantUsage({ info, harness, agent, logger: console });
187
+ }
188
+ } catch { /* subscription closed */ }
189
+ })();
190
+ return () => controller.abort();
191
+ }
80
192
  },
81
193
  async server() {
82
194
  const harness = process.env.WINCH_HARNESS ?? "opencode";
83
195
  const consumerId = consumerIdFor(harness);
84
196
  const executorId = process.env.WINCH_EXECUTOR_ID ?? null;
85
- const hooks = createWinchHooks({ consumerId, instanceId: executorId });
197
+ const hooks = createWinchHooks({ consumerId, instanceId: executorId, harness, logger: console });
86
198
  let dispatch = null;
87
199
  const ensureDispatch = () => {
88
200
  if (dispatch) return;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch-opencode",
3
- "version": "2026.11.19-beta.1",
4
- "description": "OpenCode companion for winch: stamps agent and session identity on winch tool calls, receives HTTP dispatch wakes, and reconciles assigned in-progress work. No SDK dependency — a plain id/setup/server export.",
3
+ "version": "2026.11.23-beta.1",
4
+ "description": "OpenCode companion for winch: stamps agent and session identity on winch tool calls, receives HTTP dispatch wakes, reports LLM usage, and reconciles assigned in-progress work. No SDK dependency \u2014 a plain id/setup/server export.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "repository": {
@@ -20,7 +20,8 @@
20
20
  "index.js",
21
21
  "hooks.js",
22
22
  "identity.js",
23
- "dispatch.js"
23
+ "dispatch.js",
24
+ "usage.js"
24
25
  ],
25
26
  "main": "index.js"
26
27
  }
package/usage.js ADDED
@@ -0,0 +1,120 @@
1
+ // usage.js — report per-turn LLM usage to winch's dispatch server.
2
+ //
3
+ // OpenCode emits `message.updated` on its event bus; an assistant message with
4
+ // `finish` (or a completed timestamp) is final and carries the accumulated
5
+ // `cost` and the last step's token snapshot. Posting is fire-and-forget and
6
+ // idempotent per message id (the server dedups on turnRef).
7
+
8
+ import { DEFAULT_DISPATCH_URL } from "./dispatch.js";
9
+
10
+ const USAGE_PATH = "/usage";
11
+ const DEFAULT_TIMEOUT_MS = 2000;
12
+
13
+ function num(value) {
14
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
15
+ }
16
+
17
+ function hasNumbers(usage) {
18
+ return usage.tokensIn !== null || usage.tokensOut !== null || usage.cacheRead !== null || usage.costUsd !== null;
19
+ }
20
+
21
+ // A turn's usage is final only once the assistant message has finished; the
22
+ // same message id appears earlier in `message.updated` without usage totals.
23
+ export function isFinalAssistant(info) {
24
+ return !!info && info.role === "assistant" && (info.finish != null || info.time?.completed != null);
25
+ }
26
+
27
+ // AssistantMessage -> { agent, session, usage, turnRef } | null
28
+ export function usageFromAssistantMessage(info) {
29
+ if (!isFinalAssistant(info)) return null;
30
+ const tokens = info.tokens ?? {};
31
+ const cache = tokens.cache ?? {};
32
+ const usage = {
33
+ model: info.providerID && info.modelID ? `${info.providerID}/${info.modelID}` : info.modelID ?? null,
34
+ tokensIn: num(tokens.input),
35
+ tokensOut: num(tokens.output),
36
+ cacheRead: num(cache.read),
37
+ costUsd: num(info.cost),
38
+ };
39
+ if (!hasNumbers(usage)) return null;
40
+ return {
41
+ agent: info.agent ?? null,
42
+ session: info.sessionID ?? null,
43
+ usage,
44
+ turnRef: info.id ?? null,
45
+ };
46
+ }
47
+
48
+ const ITEM_ID_KEYS = ["taskId", "task_id", "id", "epicId", "epic_id", "storyId", "story_id"];
49
+
50
+ // The server binds a session to an item only for a call carrying an item id
51
+ // (backlog_claim, get, update, append, ...). accept_wake carries an
52
+ // admissionId, so it alone does not bind; reporting is armed on the first call
53
+ // that can actually attribute the row.
54
+ export function carriesItemId(args) {
55
+ if (!args || typeof args !== "object") return false;
56
+ return ITEM_ID_KEYS.some((key) => typeof args[key] === "string" && args[key].trim() !== "");
57
+ }
58
+
59
+ // The winch server keys sessions by `<harness>:<agent>:<external session>`.
60
+ export function usageBody({ harness, agent, session, usage, turnRef }) {
61
+ if (!agent || !session || !usage) return null;
62
+ return { sessionKey: `${harness}:${agent}:${session}`, turnRef: turnRef ?? null, usage };
63
+ }
64
+
65
+ export async function postUsage({
66
+ baseUrl = DEFAULT_DISPATCH_URL,
67
+ token,
68
+ body,
69
+ logger = console,
70
+ fetchImpl = fetch,
71
+ timeoutMs = DEFAULT_TIMEOUT_MS,
72
+ }) {
73
+ if (!body) return false;
74
+ const headers = { "content-type": "application/json" };
75
+ if (token) headers.authorization = `Bearer ${token}`;
76
+ try {
77
+ const res = await fetchImpl(`${String(baseUrl).replace(/\/+$/, "")}${USAGE_PATH}`, {
78
+ method: "POST",
79
+ headers,
80
+ body: JSON.stringify(body),
81
+ signal: AbortSignal.timeout(timeoutMs),
82
+ });
83
+ if (!res.ok) {
84
+ logger?.warn?.(`winch: usage report ${res.status}`);
85
+ return false;
86
+ }
87
+ return true;
88
+ } catch (err) {
89
+ logger?.warn?.(`winch: usage report failed: ${err?.message ?? err}`);
90
+ return false;
91
+ }
92
+ }
93
+
94
+ // Fire-and-forget entry used by the event hook; returns the body when posted.
95
+ export function reportAssistantUsage({
96
+ info,
97
+ harness,
98
+ agent = null,
99
+ baseUrl = process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL,
100
+ token = process.env.WINCH_DISPATCH_TOKEN,
101
+ logger = console,
102
+ fetchImpl = fetch,
103
+ }) {
104
+ const reported = usageFromAssistantMessage(info);
105
+ if (!reported) return null;
106
+ const body = usageBody({ harness, agent: agent ?? reported.agent, session: reported.session, usage: reported.usage, turnRef: reported.turnRef });
107
+ if (!body) return null;
108
+ void postUsage({ baseUrl, token, body, logger, fetchImpl });
109
+ return body;
110
+ }
111
+
112
+ // Keeps a bounded set: message ids so repeated message.updated frames do not
113
+ // re-post, and session ids so only winch-bound sessions report usage.
114
+ export function remember(seen, key, max = 1000) {
115
+ if (!key) return true;
116
+ if (seen.has(key)) return false;
117
+ seen.add(key);
118
+ if (seen.size > max) seen.delete(seen.values().next().value);
119
+ return true;
120
+ }