@igorjpimenta/winch-opencode 2026.11.18-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.
package/dispatch.js CHANGED
@@ -40,22 +40,36 @@ function json(res, status, body) {
40
40
  res.end(JSON.stringify(body));
41
41
  }
42
42
 
43
- export async function registerExecutor({ baseUrl, harness, executorId, url, bearer, timeoutMs = 5000 }) {
43
+ function dispatchAuthHeaders() {
44
+ const headers = { "content-type": "application/json" };
45
+ const token = String(process.env.WINCH_DISPATCH_TOKEN ?? "").trim();
46
+ if (token) headers.authorization = `Bearer ${token}`;
47
+ return headers;
48
+ }
49
+
50
+ function wakeMessage({ itemId, kind, admissionId, attemptNo, leaseEpoch }) {
51
+ if (kind === "story" || kind === "append" || kind === "review") {
52
+ return `Call backlog_accept_wake with admissionId "${admissionId}", attemptNo ${attemptNo}, and leaseEpoch ${leaseEpoch ?? 0} before working on ${itemId}.`;
53
+ }
54
+ return itemId;
55
+ }
56
+
57
+ export async function registerExecutor({ baseUrl, harness, consumerId, executorId, url, bearer, fresh = false, timeoutMs = 5000 }) {
44
58
  const res = await fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/register`, {
45
59
  method: "POST",
46
- headers: { "content-type": "application/json" },
47
- body: JSON.stringify({ harness, executorId, url, bearer }),
60
+ headers: dispatchAuthHeaders(),
61
+ body: JSON.stringify({ harness, consumerId, executorId, instanceId: executorId, url, bearer, fresh }),
48
62
  signal: AbortSignal.timeout(timeoutMs),
49
63
  });
50
64
  if (!res.ok) throw new Error(`dispatch register ${res.status}`);
51
65
  return res.json();
52
66
  }
53
67
 
54
- export async function recoverOnce({ baseUrl, harness, executorId, wake, started, logger = console, timeoutMs = 5000 }) {
68
+ export async function recoverOnce({ baseUrl, harness, consumerId, executorId, wake, started, logger = console, timeoutMs = 5000 }) {
55
69
  const res = await fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/recover`, {
56
70
  method: "POST",
57
- headers: { "content-type": "application/json" },
58
- body: JSON.stringify({ harness, executorId }),
71
+ headers: dispatchAuthHeaders(),
72
+ body: JSON.stringify({ harness, consumerId, executorId }),
59
73
  signal: AbortSignal.timeout(timeoutMs),
60
74
  });
61
75
  if (!res.ok) throw new Error(`dispatch recover ${res.status}`);
@@ -82,14 +96,16 @@ export async function recoverOnce({ baseUrl, harness, executorId, wake, started,
82
96
 
83
97
  for (const row of body?.start ?? []) {
84
98
  if (!row?.admissionId || !row?.itemId) continue;
85
- const key = `start:${row.admissionId}`;
99
+ const key = `start:${row.admissionId}:${row.attemptNo ?? "none"}`;
86
100
  if (started.has(key)) continue;
87
101
  started.set(key, now);
88
102
  Promise.resolve(wake({
89
103
  agent: row.agent,
90
- message: row.itemId,
104
+ message: wakeMessage(row),
91
105
  kind: row.kind,
92
106
  admissionId: row.admissionId,
107
+ attemptNo: row.attemptNo,
108
+ leaseEpoch: row.leaseEpoch ?? 0,
93
109
  })).catch((err) => {
94
110
  started.delete(key);
95
111
  logger?.warn?.(`winch: wake ${row.itemId} failed: ${err?.message ?? err}`);
@@ -100,12 +116,17 @@ export async function recoverOnce({ baseUrl, harness, executorId, wake, started,
100
116
 
101
117
  export function resumePrompt(row) {
102
118
  const taskId = row?.task?.id ?? "(unknown)";
103
- const attemptId = row?.attemptId ?? "(unknown)";
104
- return `Resume ${taskId} attempt ${attemptId}. You already own this task. Do not call backlog_claim. Call backlog_update with taskId "${taskId}" and attemptId "${attemptId}", heartbeat true. If it returns stale_claim, stop. Then continue from the existing brief.`;
119
+ const attemptId = row?.attemptId ?? null;
120
+ const leaseEpoch = row?.leaseEpoch ?? 0;
121
+ if (!attemptId) {
122
+ return `Repair ${taskId}. The task is in_progress but has no live attempt. Do not call backlog_claim. Call backlog_update with taskId "${taskId}", heartbeat true, and no attemptId so the store repairs the missing attempt. If it returns stale_claim, stop. Then continue from the existing brief.`;
123
+ }
124
+ return `Resume ${taskId} attempt ${attemptId} leaseEpoch ${leaseEpoch}. You already own this task. Do not call backlog_claim. Call backlog_update with taskId "${taskId}", attemptId "${attemptId}", leaseEpoch ${leaseEpoch}, heartbeat true. If it returns stale_claim, stop. Then continue from the existing brief.`;
105
125
  }
106
126
 
107
- export function startDispatch({ baseUrl = DEFAULT_DISPATCH_URL, harness, executorId, bearer, wake, logger = console, host = "127.0.0.1", port = 0, reconcileMs = 30000 } = {}) {
127
+ export function startDispatch({ baseUrl = DEFAULT_DISPATCH_URL, harness, consumerId = null, executorId, bearer, wake, logger = console, host = "127.0.0.1", port = 0, reconcileMs = 30000 } = {}) {
108
128
  if (!executorId || !bearer) throw new Error("dispatch needs an executor id and bearer");
129
+ const subscriptionId = consumerId || executorId;
109
130
  const started = new Map();
110
131
  let closed = false;
111
132
  let timer = null;
@@ -131,30 +152,50 @@ export function startDispatch({ baseUrl = DEFAULT_DISPATCH_URL, harness, executo
131
152
  json(res, 400, { error: "wake payload requires admissionId, itemId, agent" });
132
153
  return;
133
154
  }
155
+ if (body.execution === "standby") {
156
+ json(res, 202, { ok: true, admissionId: body.admissionId, standby: true });
157
+ return;
158
+ }
159
+ const key = `start:${body.admissionId}:${body.attemptNo ?? "none"}`;
160
+ if (started.has(key)) {
161
+ json(res, 202, { ok: true, admissionId: body.admissionId, duplicate: true });
162
+ return;
163
+ }
164
+ started.set(key, Date.now());
134
165
  Promise.resolve(wake({
135
166
  agent: body.agent,
136
- message: body.itemId,
167
+ message: wakeMessage(body),
137
168
  kind: body.kind,
138
169
  admissionId: body.admissionId,
139
- })).catch((err) => logger?.warn?.(`winch: wake ${body.itemId} failed: ${err?.message ?? err}`));
170
+ attemptNo: body.attemptNo,
171
+ leaseEpoch: body.leaseEpoch ?? 0,
172
+ })).catch((err) => {
173
+ started.delete(key);
174
+ logger?.warn?.(`winch: wake ${body.itemId} failed: ${err?.message ?? err}`);
175
+ });
140
176
  json(res, 202, { ok: true, admissionId: body.admissionId });
141
177
  });
142
178
 
179
+ let fresh = true;
143
180
  const run = async () => {
144
181
  if (closed) return;
145
182
  try {
146
183
  await registerExecutor({
147
184
  baseUrl,
148
185
  harness,
186
+ consumerId: subscriptionId,
149
187
  executorId,
150
188
  url: `http://${host}:${listener.address().port}/wake`,
151
189
  bearer,
190
+ fresh,
152
191
  });
192
+ fresh = false;
153
193
  } catch (err) {
154
194
  logger?.warn?.(`winch: dispatch register failed: ${err?.message ?? err}`);
195
+ return;
155
196
  }
156
197
  try {
157
- await recoverOnce({ baseUrl, harness, executorId, wake, started, logger });
198
+ await recoverOnce({ baseUrl, harness, consumerId: subscriptionId, executorId, wake, started, logger });
158
199
  } catch (err) {
159
200
  logger?.warn?.(`winch: dispatch recover failed: ${err?.message ?? err}`);
160
201
  }
@@ -169,13 +210,14 @@ export function startDispatch({ baseUrl = DEFAULT_DISPATCH_URL, harness, executo
169
210
  timer = setInterval(() => { void run(); }, Number(reconcileMs));
170
211
  timer.unref?.();
171
212
  }
172
- resolve({ port: listener.address().port, executorId });
213
+ resolve({ port: listener.address().port, executorId, consumerId: subscriptionId });
173
214
  });
174
215
  });
175
216
 
176
217
  return {
177
218
  ready,
178
219
  get executorId() { return executorId; },
220
+ get consumerId() { return subscriptionId; },
179
221
  get port() { return listener?.address()?.port ?? null; },
180
222
  close() {
181
223
  closed = true;
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() {
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() {
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 });
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/identity.js CHANGED
@@ -7,7 +7,7 @@ export function isWinchTool(name) {
7
7
  return typeof name === "string" && name.includes("winch");
8
8
  }
9
9
 
10
- export function stampWinchIdentity(input, output, { agent = null } = {}) {
10
+ export function stampWinchIdentity(input, output, { agent = null, consumerId = null, instanceId = null } = {}) {
11
11
  if (!isWinchTool(input?.tool)) return false;
12
12
  output.args = output.args ?? {};
13
13
  // Overwrite, never merge: an unknown agent blanks the slot (unstamped),
@@ -15,16 +15,20 @@ export function stampWinchIdentity(input, output, { agent = null } = {}) {
15
15
  // model-supplied identity never survives.
16
16
  output.args.winch_agent = agent ?? "";
17
17
  output.args.winch_session = input?.sessionID ?? "";
18
+ output.args.winch_consumer = consumerId ?? "";
19
+ output.args.winch_instance = instanceId ?? "";
18
20
  return true;
19
21
  }
20
22
 
21
23
  // V2: the tool hook hands one mutable event instead of (input, output). Same
22
24
  // rule — the pair is stamped unconditionally.
23
- export function stampWinchEvent(event, agent) {
25
+ export function stampWinchEvent(event, agent, consumerId = null, instanceId = null) {
24
26
  if (!isWinchTool(event?.tool)) return false;
25
27
  const input = event.input && typeof event.input === "object" ? event.input : {};
26
28
  event.input = input;
27
29
  input.winch_agent = agent ?? "";
28
30
  input.winch_session = event.sessionID ?? "";
31
+ input.winch_consumer = consumerId ?? "";
32
+ input.winch_instance = instanceId ?? "";
29
33
  return true;
30
34
  }
package/index.js CHANGED
@@ -1,27 +1,122 @@
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";
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";
5
9
 
6
- function opencodeWake({ agent, message }) {
7
- return new Promise((resolve, reject) => {
8
- const bin = process.env.OPENCODE_BIN || "opencode";
9
- const child = spawn(bin, ["run", "--agent", agent, message], {
10
- detached: true,
11
- 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();
12
75
  });
13
- let stderr = "";
14
- child.stderr?.on("data", (d) => { stderr = (stderr + d.toString()).slice(-2000); });
15
- child.on("error", reject);
16
- child.on("exit", (code) =>
17
- code === 0 ? resolve() : reject(new Error(`exit ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`))
18
- );
19
- child.unref();
20
- });
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 };
108
+ }
109
+
110
+ function consumerIdFor(harness, cfg = {}) {
111
+ return cfg.winchConsumerId ?? process.env.WINCH_CONSUMER_ID ?? `${harness}:${hostname()}`;
21
112
  }
22
113
 
23
114
  function start({ cfg = {}, harness, logger }) {
115
+ const runner = createWakeRunner({ logger, stateDir: cfg.wakeStateDir });
116
+ runner.reapOrphans();
117
+
24
118
  const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
119
+ const consumerId = consumerIdFor(harness, cfg);
25
120
  const bearer = process.env.WINCH_WEBHOOK_BEARER;
26
121
  if (!executorId || !bearer) {
27
122
  logger?.warn?.("winch: dispatch needs WINCH_EXECUTOR_ID and WINCH_WEBHOOK_BEARER; receiver disabled");
@@ -30,14 +125,21 @@ function start({ cfg = {}, harness, logger }) {
30
125
  const dispatch = startDispatch({
31
126
  baseUrl: process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL,
32
127
  harness,
128
+ consumerId,
33
129
  executorId,
34
130
  bearer,
35
- wake: opencodeWake,
131
+ wake: runner.wake,
36
132
  port: Number(cfg.dispatchPort ?? process.env.WINCH_DISPATCH_PORT ?? 0),
37
133
  reconcileMs: Number(cfg.dispatchReconcileMs ?? process.env.WINCH_DISPATCH_RECONCILE_MS ?? 30000),
38
134
  logger,
39
135
  });
40
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;
41
143
  return dispatch;
42
144
  }
43
145
 
@@ -49,13 +151,17 @@ export default {
49
151
  // SessionContext (the "context" hook event) carries both sessionID and
50
152
  // the session's agent; session.get() in this beta returns a projection
51
153
  // without agent, so the request hook is the reliable source.
154
+ const cfg = ctx.options ?? {};
155
+ const harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "opencode";
156
+ const consumerId = consumerIdFor(harness, cfg);
157
+ const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID ?? null;
52
158
  const agents = new Map();
159
+ const reported = new Set();
160
+ const engaged = new Set();
53
161
  let dispatch = null;
54
162
  const ensureDispatch = () => {
55
163
  if (dispatch) return;
56
- const cfg = ctx.options ?? {};
57
164
  if (cfg.dispatchEnabled === false || process.env.WINCH_DISPATCH_ENABLED === "0") return;
58
- const harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "opencode";
59
165
  dispatch = start({ cfg, harness, logger: console });
60
166
  };
61
167
  await ctx.session.hook("context", (event) => {
@@ -66,16 +172,33 @@ export default {
66
172
  const agent = agents.get(event.sessionID) ?? process.env.WINCH_AGENT ?? null;
67
173
  // Unconditional: unknown agent blanks the slot, the server refuses
68
174
  // rather than trusting whatever the model wrote there.
69
- stampWinchEvent(event, agent);
175
+ if (stampWinchEvent(event, agent, consumerId, executorId) && carriesItemId(event.input)) remember(engaged, event.sessionID);
70
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
+ }
71
192
  },
72
193
  async server() {
73
- const hooks = createWinchHooks();
194
+ const harness = process.env.WINCH_HARNESS ?? "opencode";
195
+ const consumerId = consumerIdFor(harness);
196
+ const executorId = process.env.WINCH_EXECUTOR_ID ?? null;
197
+ const hooks = createWinchHooks({ consumerId, instanceId: executorId, harness, logger: console });
74
198
  let dispatch = null;
75
199
  const ensureDispatch = () => {
76
200
  if (dispatch) return;
77
201
  if (process.env.WINCH_DISPATCH_ENABLED === "0") return;
78
- const harness = process.env.WINCH_HARNESS ?? "opencode";
79
202
  dispatch = start({ cfg: {}, harness, logger: console });
80
203
  };
81
204
  const origMessage = hooks["chat.message"];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch-opencode",
3
- "version": "2026.11.18-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 \u2014 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
+ }