@igorjpimenta/winch 2026.11.23-beta.1 → 2026.11.23-beta.3

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.
@@ -99,6 +99,13 @@
99
99
  "when": 1795440999481,
100
100
  "tag": "0013_webhook_delivery_tables",
101
101
  "breakpoints": true
102
+ },
103
+ {
104
+ "idx": 14,
105
+ "version": "6",
106
+ "when": 1795442379791,
107
+ "tag": "0014_usage_events",
108
+ "breakpoints": true
102
109
  }
103
110
  ]
104
111
  }
package/README.md CHANGED
@@ -17,6 +17,7 @@ contract itself is the only integration surface.
17
17
  - **Dependency DAG** - forward-only deps, cycle-checked, cancelled deps count as resolved.
18
18
  - **Webhook wakes** - every work-making transition fans out to consumer webhooks; subscribers wake agents, no polling.
19
19
  - **Human gates** - block/resume with gate types; one resume per gate, actor-checked.
20
+ - **Human-gated artifacts** - attaching a `pr`/`release`/`design` artifact spawns a review child for the reserved `human` pair and parks the parent until it resolves.
20
21
  - **Content-addressed evidence** - artifacts recorded on close, carried into downstream handoffs.
21
22
 
22
23
  It is local-first and harness-neutral: OpenCode, OpenClaw and future harnesses
@@ -161,7 +162,7 @@ checkpoints on turn end, resumes from the latest checkpoint, receives dispatch
161
162
  wakes at `POST /api/winch/dispatch`, and reconciles `in_progress` attempts
162
163
  after a restart.
163
164
 
164
- openclaw plugins install npm:@igorjpimenta/winch-openclaw@latest
165
+ openclaw plugins install npm:@igorjpimenta/winch-openclaw@beta
165
166
 
166
167
  One daemon for all harnesses (recommended):
167
168
 
@@ -215,7 +216,7 @@ canonical form for new setup:
215
216
  }
216
217
  }
217
218
  },
218
- "plugins": ["@igorjpimenta/winch-opencode"]
219
+ "plugins": ["@igorjpimenta/winch-opencode@beta"]
219
220
  }
220
221
 
221
222
  Or via the CLI:
@@ -240,9 +241,9 @@ loopback endpoint and starts a claimable session with `opencode run`.
240
241
  | `backlog_delegate` | split work from a task to another worker (agent or human); each child becomes its own card, the parent parks in `blocked` until all children close, then returns to `ready` for the accountable. `childKey`/`visitSeq` make retries idempotent and start new rounds |
241
242
  | `backlog_get` | read an epic, story or task by id - acceptance, results, artifacts, dependencies, readiness |
242
243
  | `backlog_claim` | claim one task by id, or the highest-priority ready task when the id is omitted; atomic CAS under a lease |
243
- | `backlog_update` | heartbeat and append progress, comment or artifact to a claimed task; pass the `leaseEpoch` for wake-owned attempts |
244
+ | `backlog_update` | heartbeat and append progress, comment or artifact to a claimed task; pass the `leaseEpoch` for wake-owned attempts. `addArtifact` accepts a URI or `{uri, kind?, label?}`; kinds in `hitlArtifactKinds` (default `pr`/`release`/`design`) spawn the human review child |
244
245
  | `backlog_accept_wake` | take the single-flight execution lease for a story/append/review wake before planning |
245
- | `backlog_done` | close a claimed task with a result; closing the last task closes its story, and the last story closes the epic and wakes the agent that planned it |
246
+ | `backlog_done` | close a claimed task with a result; refuses while deps are unmet (`deps_unmet`) or when a HITL artifact is only now being attached (`hitl_at_done`); closing the last task closes its story, and the last story closes the epic and wakes the agent that planned it |
246
247
  | `backlog_block` / `backlog_resume` | open a human gate (with optional `gateType` and `blockedBy` dep edge) and resolve it (`actor` optional) |
247
248
 
248
249
  ## Task lifecycle
@@ -261,6 +262,23 @@ work, but neither value is a caller identity, and agent dispatchers never wake
261
262
  it. A block parks it until an operator resumes it; the last task closes its
262
263
  story, and the last story closes the epic.
263
264
 
265
+ Human-gated artifacts use that same pair. Attaching an artifact whose kind is
266
+ in `hitlArtifactKinds` (`WINCH_HITL_ARTIFACT_KINDS`, default
267
+ `pr,release,design`) while a task is claimed:
268
+
269
+ 1. stores the artifact (URI unique across the store);
270
+ 2. spawns a ready child assigned to `human`/`human_in_the_loop`
271
+ (`execution_kind: gate`, keyed `hitl:<kind>:<uri>` for idempotency);
272
+ 3. adds `parent → child` on the dependency DAG and parks the parent in a
273
+ deps wait — claim and `backlog_done` refuse until the child resolves.
274
+
275
+ The PR body carries `Backlog:` / `Backlog-Task:` markers; the claim handoff's
276
+ `receiverPrompt` states the protocol (attach while `in_progress`, never
277
+ self-complete while a child is open). Resolution is human-only: merge the PR
278
+ and `merge-detect` closes the child and frees the parent, or run
279
+ `winch resolve <childId>` for non-PR kinds. `winch hitl` lists the human
280
+ queue; `winch next` excludes it.
281
+
264
282
  ```mermaid
265
283
  flowchart LR
266
284
  Z[backlog] -->|assign| A[ready]
@@ -299,9 +317,11 @@ Claim leases, attempt caps, and gate rules: [lifecycle](docs/lifecycle.md).
299
317
  | `serve --mcp http --port N [--host H]` | serve the same tools over Streamable HTTP (shared daemon) |
300
318
  | `watch` | one watcher tick (JSON manifest on stdout) |
301
319
  | `resume <taskId> [--actor <name>]` | resolve a human gate: blocked to ready |
302
- | `next` | list the current ready queue |
320
+ | `next` | list the current ready queue (agent work only — human HITL children are excluded) |
321
+ | `hitl [--status S]` | list the human-in-the-loop queue (PR/release/design review children, with artifacts and parents) |
322
+ | `resolve <taskId> [--note N]` | operator closes a HITL child; frees parents parked on it |
303
323
  | `release-epic --epic <id> [--task ID] [--version V] [--base B]` | release notes + branch/PR with backlog markers |
304
- | `merge-detect [--dry-run]` | apply merged/closed PR outcomes |
324
+ | `merge-detect [--dry-run]` | apply merged/closed PR outcomes (closes HITL children and cascades parents) |
305
325
  | `webhook bearer` | generate a dispatch bearer |
306
326
  | `webhook register --topic T [--harness H] [--executor E] --url U [--id I] [--bearer B]` | register or replace a webhook subscription; a bearer is generated and printed when omitted |
307
327
  | `webhook list [--topic T] [--harness H]` | list webhook subscriptions with bearer redacted |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch",
3
- "version": "2026.11.23-beta.1",
3
+ "version": "2026.11.23-beta.3",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
package/plugins/README.md CHANGED
@@ -23,6 +23,17 @@ identity is the operator-set env on the MCP server entry — process-scoped
23
23
  configuration the model cannot alter per call, so the same property holds by
24
24
  construction.
25
25
 
26
+ ## Usage reporting
27
+
28
+ Both companions also report LLM usage per turn to winch's `POST /usage` under
29
+ the same `harness:agent:session` key, so cost lands on the item the session is
30
+ bound to. openclaw reads the gateway's `reply_payload_sending.usageState` (one
31
+ consumed snapshot per run: tokens, resolved model, estimated cost). opencode
32
+ reads final `message.updated` assistant messages (accumulated `cost` plus the
33
+ last step's token snapshot). Both post fire-and-forget with `WINCH_DISPATCH_URL`
34
+ and `WINCH_DISPATCH_TOKEN`; a failed post never affects the host turn, and the
35
+ server dedups on the turn id.
36
+
26
37
  ## openclaw
27
38
 
28
39
  Setup verified against the existing extension wiring: every loaded extension
@@ -1,6 +1,6 @@
1
1
  # @igorjpimenta/winch-openclaw
2
2
 
3
- OpenClaw companion for [winch](https://github.com/igorjpimenta/winch). Three jobs:
3
+ OpenClaw companion for [winch](https://github.com/igorjpimenta/winch). Four jobs:
4
4
 
5
5
  1. **Identity** — `before_tool_call` stamps `_meta.winch {harness, agent, session}`
6
6
  onto every winch MCP tool call, overwriting unconditionally so model-supplied
@@ -16,6 +16,12 @@ OpenClaw companion for [winch](https://github.com/igorjpimenta/winch). Three job
16
16
  `fresh: true`; later heartbeats preserve failure state. `WINCH_EXECUTOR_ID`
17
17
  identifies the live connection; the event's `kind` selects the listener
18
18
  action. Set `WINCH_DISPATCH_TOKEN` for authenticated management calls.
19
+ 4. **Usage reporting** — `reply_payload_sending` reads the gateway's per-turn
20
+ `usageState` (token counts, resolved model, estimated turn cost) and posts it
21
+ to winch's `POST /usage` under the session's `harness:agent:session` key.
22
+ One snapshot is consumed per run, so a turn reports once; the post is
23
+ fire-and-forget and never delays or fails reply delivery. It uses
24
+ `WINCH_DISPATCH_URL` and `WINCH_DISPATCH_TOKEN`.
19
25
 
20
26
  ## Install
21
27
 
@@ -69,3 +75,20 @@ Environment:
69
75
  | `WINCH_DISPATCH_TOKEN` | management bearer for register/recover/notify; required for a non-loopback winch bind |
70
76
 
71
77
  Requires OpenClaw ≥ 2026.5.18 (declared as `openclaw.install.minHostVersion`).
78
+
79
+ ## Human artifacts (HITL)
80
+
81
+ This plugin adds no HITL logic — the server owns it. What an OpenClaw session
82
+ needs to know:
83
+
84
+ - **Agents** get the PR protocol from the claim handoff's `receiverPrompt`:
85
+ put `Backlog:` / `Backlog-Task:` in the PR body, attach with
86
+ `backlog_update({ addArtifact: "<pr-url>", addArtifactKind: "pr" })` while
87
+ `in_progress`, and never `backlog_done` while a review child is open.
88
+ - **Operators** list the human queue with `winch hitl` (not `winch next`,
89
+ which excludes `human`). Resolve a non-PR child with
90
+ `winch resolve <taskId> --note "…"`. For PR children, merge on GitHub —
91
+ `merge-detect` closes the child and frees the parent within its schedule.
92
+ - **Wakes never target humans**: the reserved `human`/`human_in_the_loop`
93
+ pair is excluded from agent wake lists; the gateway will not start a
94
+ session for a review child.
@@ -1,6 +1,7 @@
1
1
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
2
2
  import { buildWinchMeta } from "./meta.js";
3
- import { startDispatch } from "./dispatch.js";
3
+ import { startDispatch, DEFAULT_DISPATCH_URL } from "./dispatch.js";
4
+ import { carriesItemId, remember, reportReplyUsage } from "./usage.js";
4
5
  import { spawn } from "node:child_process";
5
6
  import { existsSync } from "node:fs";
6
7
  import { hostname } from "node:os";
@@ -53,10 +54,30 @@ export default definePluginEntry({
53
54
  const harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "openclaw";
54
55
  const consumerId = cfg.winchConsumerId ?? process.env.WINCH_CONSUMER_ID ?? `${harness}:${hostname()}`;
55
56
  const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID ?? null;
57
+ // Only sessions that have made a winch call are bound to an item, so only
58
+ // those carry usage the server can attribute.
59
+ const engaged = new Set();
56
60
  if (typeof api.on === "function") {
57
- api.on("before_tool_call", (event, ctx) => buildWinchMeta(event, ctx, harness, consumerId, executorId));
61
+ api.on("before_tool_call", (event, ctx) => {
62
+ const stamp = buildWinchMeta(event, ctx, harness, consumerId, executorId);
63
+ if (stamp && carriesItemId(stamp.params)) remember(engaged, stamp.params._meta.winch.session);
64
+ return stamp;
65
+ });
66
+ // One usage snapshot per run arrives on reply_payload_sending. The hook
67
+ // returns nothing so the payload is delivered unchanged.
68
+ api.on("reply_payload_sending", (event) => {
69
+ const session = event?.sessionKey ?? event?.usageState?.sessionId ?? event?.runId;
70
+ if (!engaged.has(session)) return;
71
+ reportReplyUsage({
72
+ event,
73
+ harness,
74
+ baseUrl: process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL,
75
+ token: process.env.WINCH_DISPATCH_TOKEN,
76
+ logger: api.logger,
77
+ });
78
+ });
58
79
  } else {
59
- api.logger.warn("winch: api.on unavailable; identity hook not registered");
80
+ api.logger.warn("winch: api.on unavailable; identity and usage hooks not registered");
60
81
  }
61
82
 
62
83
  let dispatch = null;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch-openclaw",
3
- "version": "2026.11.19-beta.1",
3
+ "version": "2026.11.23-beta.3",
4
4
  "description": "OpenClaw companion for winch: stamps caller identity on winch MCP tool calls, receives HTTP dispatch wakes, and reconciles in-progress work.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -18,7 +18,8 @@
18
18
  "meta.js",
19
19
  "dispatch.js",
20
20
  "openclaw.plugin.json",
21
- "README.md"
21
+ "README.md",
22
+ "usage.js"
22
23
  ],
23
24
  "openclaw": {
24
25
  "extensions": [
@@ -0,0 +1,111 @@
1
+ // usage.js — report per-turn LLM usage to winch's dispatch server.
2
+ //
3
+ // The gateway attaches one usage snapshot per run to the first outbound payload
4
+ // (reply_payload_sending.usageState); later payloads of the same run do not
5
+ // carry it, so a report per snapshot is already one per turn. Posting is
6
+ // fire-and-forget: reporting must never delay or fail reply delivery.
7
+
8
+ const USAGE_PATH = "/usage";
9
+ const DEFAULT_TIMEOUT_MS = 2000;
10
+
11
+ function num(value) {
12
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
13
+ }
14
+
15
+ function hasNumbers(usage) {
16
+ return usage.tokensIn !== null || usage.tokensOut !== null || usage.cacheRead !== null || usage.costUsd !== null;
17
+ }
18
+
19
+ // reply_payload_sending -> { agent, session, usage, turnRef } | null
20
+ export function usageFromReplyEvent(event) {
21
+ const state = event?.usageState;
22
+ if (!state) return null;
23
+ const model = state.resolvedRef ?? state.model ?? null;
24
+ const costUsd = num(state.turnUsd);
25
+ const identity = {
26
+ agent: state.agentId ?? null,
27
+ session: event?.sessionKey ?? state.sessionId ?? event?.runId ?? null,
28
+ turnRef: event?.runId ?? null,
29
+ };
30
+ // The aggregate covers the whole tool loop; lastUsage is the final call only.
31
+ for (const observed of [state.usage, state.lastUsage]) {
32
+ if (!observed) continue;
33
+ const usage = {
34
+ model,
35
+ tokensIn: num(observed.input),
36
+ tokensOut: num(observed.output),
37
+ cacheRead: num(observed.cacheRead),
38
+ costUsd,
39
+ };
40
+ if (hasNumbers(usage)) return { ...identity, usage };
41
+ }
42
+ if (costUsd !== null) {
43
+ return { ...identity, usage: { model, tokensIn: null, tokensOut: null, cacheRead: null, costUsd } };
44
+ }
45
+ return null;
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,
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 hook; returns the body when it posted.
95
+ export function reportReplyUsage({ event, harness, baseUrl, token, logger = console, fetchImpl = fetch }) {
96
+ const reported = usageFromReplyEvent(event);
97
+ if (!reported) return null;
98
+ const body = usageBody({ harness, ...reported });
99
+ if (!body) return null;
100
+ void postUsage({ baseUrl, token, body, logger, fetchImpl });
101
+ return body;
102
+ }
103
+
104
+ // Bounded membership set: keeps engagement and turn keys from growing forever.
105
+ export function remember(seen, key, max = 1000) {
106
+ if (!key) return true;
107
+ if (seen.has(key)) return false;
108
+ seen.add(key);
109
+ if (seen.size > max) seen.delete(seen.values().next().value);
110
+ return true;
111
+ }
@@ -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
  }
@@ -1,6 +1,7 @@
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 { carriesItemId, isFinalAssistant, remember, reportAssistantUsage } from "./usage.js";
4
5
  import { spawn, execFileSync } from "node:child_process";
5
6
  import { mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
6
7
  import os, { hostname } from "node:os";
@@ -155,6 +156,8 @@ export default {
155
156
  const consumerId = consumerIdFor(harness, cfg);
156
157
  const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID ?? null;
157
158
  const agents = new Map();
159
+ const reported = new Set();
160
+ const engaged = new Set();
158
161
  let dispatch = null;
159
162
  const ensureDispatch = () => {
160
163
  if (dispatch) return;
@@ -169,14 +172,29 @@ export default {
169
172
  const agent = agents.get(event.sessionID) ?? process.env.WINCH_AGENT ?? null;
170
173
  // Unconditional: unknown agent blanks the slot, the server refuses
171
174
  // rather than trusting whatever the model wrote there.
172
- stampWinchEvent(event, agent, consumerId, executorId);
175
+ if (stampWinchEvent(event, agent, consumerId, executorId) && carriesItemId(event.input)) remember(engaged, event.sessionID);
173
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
+ }
174
192
  },
175
193
  async server() {
176
194
  const harness = process.env.WINCH_HARNESS ?? "opencode";
177
195
  const consumerId = consumerIdFor(harness);
178
196
  const executorId = process.env.WINCH_EXECUTOR_ID ?? null;
179
- const hooks = createWinchHooks({ consumerId, instanceId: executorId });
197
+ const hooks = createWinchHooks({ consumerId, instanceId: executorId, harness, logger: console });
180
198
  let dispatch = null;
181
199
  const ensureDispatch = () => {
182
200
  if (dispatch) return;
@@ -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.3",
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
  }
@@ -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
+ }