@igorjpimenta/winch 2026.11.22-beta.3 → 2026.11.23-beta.2

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.
@@ -92,6 +92,20 @@
92
92
  "when": 1795056387292,
93
93
  "tag": "0012_dispatch_fencing_audit",
94
94
  "breakpoints": true
95
+ },
96
+ {
97
+ "idx": 13,
98
+ "version": "6",
99
+ "when": 1795440999481,
100
+ "tag": "0013_webhook_delivery_tables",
101
+ "breakpoints": true
102
+ },
103
+ {
104
+ "idx": 14,
105
+ "version": "6",
106
+ "when": 1795442379791,
107
+ "tag": "0014_usage_events",
108
+ "breakpoints": true
95
109
  }
96
110
  ]
97
- }
111
+ }
package/README.md CHANGED
@@ -4,9 +4,9 @@
4
4
 
5
5
  Winch is a pull-based delivery backlog - epic to story to task with a dependency
6
6
  DAG - served as an MCP server. The spec lives in the records: a planner writes
7
- it once, a worker reads it, claims atomically, and reports back. `serve --ws`
8
- streams every store event, so a harness wakes agents from the queue instead of
9
- polling it.
7
+ it once, a worker reads it, claims atomically, and reports back. Webhook wakes
8
+ fan every work-making transition out to consumers, so a harness wakes agents
9
+ from the queue instead of polling it.
10
10
 
11
11
  Winch is harness-agnostic: the server contains no harness-specific code. The
12
12
  adapters under `plugins/` are optional and installed per harness; the MCP
@@ -15,7 +15,7 @@ contract itself is the only integration surface.
15
15
  - **Spec in the records** - goal, acceptance criteria, dependencies, capabilities all written once by the planner.
16
16
  - **Atomic claim** - CAS under a lease; highest-priority ready task selected when no id is given.
17
17
  - **Dependency DAG** - forward-only deps, cycle-checked, cancelled deps count as resolved.
18
- - **Event stream** - every store insert broadcast over WebSocket; subscribers wake agents, no polling.
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
20
  - **Content-addressed evidence** - artifacts recorded on close, carried into downstream handoffs.
21
21
 
@@ -57,7 +57,7 @@ Inside your harness agent:
57
57
  Verify from the operator side - no transcript reading:
58
58
 
59
59
  $ winch next # task gone from the ready queue
60
- $ winch serve --ws # watch the event stream light up
60
+ $ winch webhook serve # watch the wake pump light up
61
61
 
62
62
  All MCP tools and their contracts are defined in `src/tools/` - or just list
63
63
  them from the running server.
@@ -69,9 +69,6 @@ them from the running server.
69
69
  - The **MCP server** exposes the whole backlog as tools over stdio (one pipe per
70
70
  harness) or streamable HTTP (one shared daemon). Identity is stamped at the
71
71
  transport edge.
72
- - The **Event stream** (`winch serve --ws`) is a read-only feed of backlog
73
- events; its frame protocol is in [WebSocket event
74
- stream](docs/websocket.md).
75
72
  - The **Dispatch server** (`winch webhook serve`) accepts executor
76
73
  registration and recovery, pumps `admission_queue`, and fans wakes out to
77
74
  consumer webhooks. Tasks accept with MCP `backlog_claim`; planner wakes accept
@@ -106,8 +103,7 @@ stamping automatically. Full contract, per-dimension table and adapter setup:
106
103
 
107
104
  ## Dispatch
108
105
 
109
- `winch webhook serve` hosts the HTTP dispatch endpoints and the wake pump;
110
- `winch serve --ws` hosts only the read-only event stream. The dispatch server
106
+ `winch webhook serve` hosts the HTTP dispatch endpoints and the wake pump. It
111
107
  is the single scheduler:
112
108
 
113
109
  - It routes work-making transitions: `task.created`, `task.assigned`,
@@ -145,8 +141,8 @@ notify; a non-loopback bind refuses without it. See
145
141
  `POST /dispatch/recover` returns assigned `in_progress` work with its
146
142
  `attemptId`, `leaseEpoch`, and `ownerInstance`, so a restarted harness resumes
147
143
  that attempt instead of re-claiming it. The winner is recorded on the work
148
- attempt; if a legacy claim has no owner, the active dispatch lease holder gets
149
- it. If no active holder exists, the row is not fanned out. Standby consumers do
144
+ attempt; only that consumer gets the resume, and a claim that never named a
145
+ consumer is not fanned out. Standby consumers do
150
146
  not resume the same attempt. Its first call is `backlog_update` with the
151
147
  returned `attemptId` and `leaseEpoch`; a stale attempt or epoch gets
152
148
  `stale_claim`. Expired leases return work to `ready` through the normal sweep.
@@ -292,7 +288,6 @@ Claim leases, attempt caps, and gate rules: [lifecycle](docs/lifecycle.md).
292
288
  | Configure ports, bearer, store, webhooks | [Configuration](docs/configuration.md) |
293
289
  | Understand claim/lease/gate rules | [Lifecycle](docs/lifecycle.md) |
294
290
  | Webhook subscriptions, dispatch routing, recovery and CLI | [Webhooks](docs/webhooks.md) |
295
- | Event stream frame protocol and retention | [WebSocket event stream](docs/websocket.md) |
296
291
  | Run it on a host persistently | [Docker](docs/docker.md) |
297
292
  | Publish a release | [Releases](docs/releases.md) |
298
293
 
@@ -313,7 +308,6 @@ Claim leases, attempt caps, and gate rules: [lifecycle](docs/lifecycle.md).
313
308
  | `webhook deliveries [--status S] [--admission ID] [--consumer ID] [--limit N]` | inspect the per-consumer delivery ledger; `--status dead` lists dead letters |
314
309
  | `webhook revoke [--topic T] --id I` | remove a webhook subscription |
315
310
  | `webhook test [--topic T] [--harness H] [--id I]` | POST a ping to webhook subscriptions |
316
- | `serve --ws --port N [--host H]` | stream store events over WebSocket |
317
311
  | `webhook serve [--port N] [--host H]` | serve dispatch registration, recovery and the wake pump |
318
312
 
319
313
  ## Deploy (any server)
@@ -341,20 +335,13 @@ any VPS, compose host or cluster with one replica (SQLite has one writer).
341
335
  remains the one-shot tick for hosts that do not run the dispatch service.
342
336
  Claims still self-heal on the next tick when the DB lives elsewhere.
343
337
 
344
- ## Events stream
338
+ ## Event envelopes
345
339
 
346
- `winch serve --ws [--port N] [--host H]` (default port 38291, localhost-only
347
- unless `--host` says otherwise) tails the `item_events` ledger and broadcasts every
348
- new row to all connected clients as JSON text frames:
349
-
350
- - `{"type":"welcome","payload":"v3","lastEventId":N}` on connect, then
351
- `{"type":"history","events":[...]}` (newest 200), then
352
- - `{"type":"event","kind":"task.completed","id":N,"at":T,"item":{id,kind,
353
- title,status,assigned},"task":{id,title,story,epic,acceptance,artifacts,
354
- assignee},"actor":"...","note":"..."}` per insert, in id order.
355
- - Dispatch wakes are not frames on this stream and run in a separate
356
- `winch webhook serve` process; see [Webhooks](docs/webhooks.md) and
357
- [WebSocket event stream](docs/websocket.md).
340
+ Every stored transition becomes one envelope (`src/webhook/envelope.js`): the stored
341
+ transition plus the task, story and epic context a subscriber would otherwise
342
+ fetch once per row. Webhook wakes are the main event driver — the dispatch
343
+ server projects these envelopes into wake payloads; see
344
+ [Webhooks](docs/webhooks.md).
358
345
 
359
346
  Kinds are declared by their producer at write time and stored on the row's
360
347
  `kind` column. Structural inference covers `task.*` and `gate.*`; producers
@@ -363,25 +350,22 @@ asserts a tag exists: merge-detect tags first and writes nothing on tag
363
350
  failure. The emitter feeds the stored kind straight through; otherwise a row
364
351
  maps by transition structure alone. Notes never classify anything: they are
365
352
  free text and can change, so pre-kind rows keep exactly the meanings they
366
- streamed with - an append-only log keeps its history.
367
- The structural mapping lives in `src/events-ws.js`; stored producer kinds pass
353
+ were recorded with - an append-only log keeps its history.
354
+ The structural mapping lives in `src/webhook/envelope.js`; stored producer kinds pass
368
355
  through unchanged. History and live rows share one envelope shape.
369
356
 
370
- Delivery-dynamics notes the wire will not tell you: heartbeats renew the claim
371
- lease (only silence gets swept); an unmerged close dissolves its gate (late
372
- approvals answer `gate_dissolved`); starvation lives in the watcher manifest
373
- (`deferred` list, per-task `idleMs`), not the stream; a disputed completion is
374
- a new ticket linked by dep edge with a `supersedes: ITM-x` note, never a
375
- rewrite of history.
357
+ Delivery-dynamics notes the envelopes will not tell you: heartbeats renew the
358
+ claim lease (only silence gets swept); an unmerged close dissolves its gate
359
+ (late approvals answer `gate_dissolved`); starvation lives in the watcher
360
+ manifest (`deferred` list), not the envelopes; a disputed
361
+ completion is a new ticket linked by dep edge with a `supersedes: ITM-x` note,
362
+ never a rewrite of history.
376
363
 
377
- Rows carry their stored `kind` and the recursive `item` envelope; the legacy
378
- `task`/`story`/`epic` blocks stay for subscribers that predate the recursive-item schema.
364
+ Rows carry their stored `kind`, the normalized `item` block, and the task-context
365
+ block (`task` with story/epic/acceptance/artifacts) the claim handoff also uses.
379
366
 
380
367
  The server never interprets a row - a gate opening is just another event, and
381
- reminders, digests and dashboards are subscriber code. Reconnect replays
382
- history, so a missed frame costs a re-read, never a lost event. No auth in
383
- process: keep the loopback bind, or put a bearer-checked reverse proxy in
384
- front. Plain HTTP hits get 404.
368
+ reminders, digests and dashboards are subscriber code.
385
369
 
386
370
  ## Store
387
371
 
@@ -392,7 +376,7 @@ Schema lives in `src/schema.js` as Drizzle tables. The schema is one recursive
392
376
  `items` tree (`kind` = epic/story/task, `parent_id` for nesting), with
393
377
  `item_state`, `item_tags`, `item_edges`, `attempts`, `work_sessions`,
394
378
  `artifacts`, `item_events`, `admission_queue`, `admission_attempts`,
395
- `dispatch_events`, `dispatch_deliveries`, `dispatch_delivery_attempts` and
379
+ `dispatch_events`, `webhook_deliveries`, `webhook_delivery_attempts` and
396
380
  `webhooks`. Item ids are opaque; `kind`
397
381
  is the discriminator, never an id prefix. `npm run db:generate`
398
382
  turns schema changes into SQL in `.migrations/`; `src/db.js` applies pending
@@ -434,7 +418,7 @@ refuse as likely typos, unknown meta keys are ignored for forward compat.
434
418
  | Claim lease | `WINCH_LEASE_SECONDS` | 1800 (30 min) |
435
419
  | Sweeper max attempts | `WINCH_MAX_ATTEMPTS` | 3 |
436
420
  | Gate-wait thresholds | `WINCH_GATE_WAIT_LEVELS` (`"24h,72h"`, `ms|s|m|h|d` suffixes) | 24h / 72h |
437
- | WS port / history / poll | `WINCH_WS_PORT` / `WINCH_WS_HISTORY_LIMIT` / `WINCH_WS_INTERVAL_MS` | 38291 / 200 / 1000 ms |
421
+ | Event history limit (dispatch boot catch-up batch) | `WINCH_EVENT_HISTORY_LIMIT` | 200 |
438
422
  | Dispatch port / poll / lease sweep | `WINCH_DISPATCH_PORT` / `WINCH_DISPATCH_INTERVAL_MS` / `WINCH_DISPATCH_SWEEP_MS` | 38293 / 1000 / 30000 ms |
439
423
  | Dispatch caps per harness / global | `WINCH_DISPATCH_HARNESS_MAX` / `WINCH_DISPATCH_GLOBAL_MAX` | 8 / 16 |
440
424
  | Dispatch consumer heartbeat TTL | `WINCH_DISPATCH_CONSUMER_TTL_MS` | 90000 ms |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch",
3
- "version": "2026.11.22-beta.3",
3
+ "version": "2026.11.23-beta.2",
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
@@ -135,8 +146,8 @@ execution lease is the guard for wakes with no claim.
135
146
  The core query is `POST /dispatch/recover`; it returns assigned `in_progress`
136
147
  work with `attemptId`, `leaseEpoch`, `ownerInstance`, `sessionId`, `sessionKey`
137
148
  and lease expiry. The winning claim records its consumer on the work attempt,
138
- so only that consumer gets the resume. A legacy claim with no owner falls back
139
- to the active dispatch lease holder, and fails closed if there is no holder.
149
+ so only that consumer gets the resume; a claim that never named a consumer is
150
+ not fanned out to any of them.
140
151
  The plugin dedupes by task id and resumes the same attempt. Its first action is
141
152
  `backlog_update` with the returned `attemptId` and `leaseEpoch`; a stale attempt
142
153
  or epoch gets `stale_claim`, and only an expired lease returns the item to
@@ -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
 
@@ -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;
@@ -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.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
  }
@@ -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
+ }