@igorjpimenta/winch 2026.11.23-beta.1 → 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.
- package/.migrations/0014_usage_events.sql +30 -0
- package/.migrations/meta/0012_snapshot.json +2 -2
- package/.migrations/meta/0013_snapshot.json +9 -9
- package/.migrations/meta/0014_snapshot.json +2121 -0
- package/.migrations/meta/_journal.json +7 -0
- package/package.json +1 -1
- package/plugins/README.md +11 -0
- package/plugins/openclaw/winch/README.md +7 -1
- package/plugins/openclaw/winch/index.js +24 -3
- package/plugins/openclaw/winch/package.json +2 -1
- package/plugins/openclaw/winch/usage.js +111 -0
- package/plugins/opencode/winch/hooks.js +16 -2
- package/plugins/opencode/winch/index.js +20 -2
- package/plugins/opencode/winch/package.json +4 -3
- package/plugins/opencode/winch/usage.js +120 -0
- package/src/schema.js +30 -0
- package/src/store/index.js +3 -0
- package/src/store/usage.js +85 -0
- package/src/tools/index.js +16 -0
- package/src/webhook/server.js +57 -0
package/package.json
CHANGED
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).
|
|
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) =>
|
|
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
|
|
80
|
+
api.logger.warn("winch: api.on unavailable; identity and usage hooks not registered");
|
|
60
81
|
}
|
|
61
82
|
|
|
62
83
|
let dispatch = null;
|
|
@@ -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.
|
|
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
|
|
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
|
+
}
|
package/src/schema.js
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
sqliteTable,
|
|
14
14
|
text,
|
|
15
15
|
integer,
|
|
16
|
+
real,
|
|
16
17
|
index,
|
|
17
18
|
uniqueIndex,
|
|
18
19
|
check,
|
|
@@ -33,6 +34,7 @@ export const ADMISSION_STATUSES = ["queued", "offered", "accepted", "active", "d
|
|
|
33
34
|
export const EDGE_KINDS = ["depends_on"];
|
|
34
35
|
export const DELIVERY_STATUSES = ["pending", "delivering", "delivered", "dead", "cancelled"];
|
|
35
36
|
export const WEBHOOK_STATES = ["active", "suspect", "disabled"];
|
|
37
|
+
export const USAGE_SOURCES = ["api"];
|
|
36
38
|
|
|
37
39
|
const inList = (values) => sql.raw(values.map((v) => `'${v}'`).join(", "));
|
|
38
40
|
|
|
@@ -179,6 +181,34 @@ export const itemEvents = sqliteTable("item_events", {
|
|
|
179
181
|
index("idx_item_events_created").on(table.createdAt),
|
|
180
182
|
]);
|
|
181
183
|
|
|
184
|
+
export const usageEvents = sqliteTable("usage_events", {
|
|
185
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
186
|
+
itemId: text("item_id").notNull().references(() => items.id, { onDelete: "restrict" }),
|
|
187
|
+
sessionId: text("session_id").references(() => workSessions.id, { onDelete: "set null" }),
|
|
188
|
+
attemptId: text("attempt_id").references(() => attempts.id, { onDelete: "set null" }),
|
|
189
|
+
harness: text("harness").notNull(),
|
|
190
|
+
agentId: text("agent_id").notNull(),
|
|
191
|
+
externalSessionId: text("external_session_id").notNull(),
|
|
192
|
+
model: text("model"),
|
|
193
|
+
tokensIn: integer("tokens_in"),
|
|
194
|
+
tokensOut: integer("tokens_out"),
|
|
195
|
+
cacheRead: integer("cache_read"),
|
|
196
|
+
costUsd: real("cost_usd"),
|
|
197
|
+
toolCalls: integer("tool_calls"),
|
|
198
|
+
source: text("source").notNull().default("api"),
|
|
199
|
+
turnRef: text("turn_ref"),
|
|
200
|
+
createdAt: integer("created_at").notNull(),
|
|
201
|
+
}, (table) => [
|
|
202
|
+
check("usage_source", sql`${table.source} IN (${inList(USAGE_SOURCES)})`),
|
|
203
|
+
check("usage_nonneg", sql`(${table.tokensIn} IS NULL OR ${table.tokensIn} >= 0) AND (${table.tokensOut} IS NULL OR ${table.tokensOut} >= 0) AND (${table.cacheRead} IS NULL OR ${table.cacheRead} >= 0) AND (${table.costUsd} IS NULL OR ${table.costUsd} >= 0) AND (${table.toolCalls} IS NULL OR ${table.toolCalls} >= 0)`),
|
|
204
|
+
index("idx_usage_item").on(table.itemId),
|
|
205
|
+
index("idx_usage_session").on(table.sessionId),
|
|
206
|
+
index("idx_usage_attempt").on(table.attemptId),
|
|
207
|
+
index("idx_usage_created").on(table.createdAt),
|
|
208
|
+
index("idx_usage_identity").on(table.harness, table.agentId, table.externalSessionId),
|
|
209
|
+
uniqueIndex("uq_usage_turn").on(table.harness, table.agentId, table.externalSessionId, table.turnRef).where(sql`${table.turnRef} IS NOT NULL`),
|
|
210
|
+
]);
|
|
211
|
+
|
|
182
212
|
export const itemEdges = sqliteTable("item_edges", {
|
|
183
213
|
fromItemId: text("from_item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
|
|
184
214
|
toItemId: text("to_item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
|
package/src/store/index.js
CHANGED
|
@@ -38,6 +38,7 @@ import { createDeliveryApi } from "./delivery.js";
|
|
|
38
38
|
import { createDispatchEventApi } from "./dispatch-events.js";
|
|
39
39
|
import { observe } from "../webhook/core.js";
|
|
40
40
|
import { toEventMessage } from "../webhook/envelope.js";
|
|
41
|
+
import { createUsageApi } from "./usage.js";
|
|
41
42
|
|
|
42
43
|
export { MAX_ATTEMPTS };
|
|
43
44
|
export { EPIC_STATUSES, STORY_STATUSES, TASK_STATUSES, EXECUTION_KINDS, ITEM_KINDS };
|
|
@@ -70,6 +71,7 @@ export function createStore({ dbPath, logger, config: explicitConfig, notifyDisp
|
|
|
70
71
|
apis.admission = createAdmissionApi({ core });
|
|
71
72
|
apis.delivery = createDeliveryApi({ core });
|
|
72
73
|
apis.dispatchEvent = createDispatchEventApi({ core });
|
|
74
|
+
apis.usage = createUsageApi({ core });
|
|
73
75
|
|
|
74
76
|
const notifyBase = process.env.WINCH_DISPATCH_URL ?? `http://127.0.0.1:${cfg.dispatchPort}`;
|
|
75
77
|
const targetUrl = notifyUrl ?? `${notifyBase.replace(/\/+$/, "")}/dispatch/notify`;
|
|
@@ -115,6 +117,7 @@ export function createStore({ dbPath, logger, config: explicitConfig, notifyDisp
|
|
|
115
117
|
admission: apis.admission,
|
|
116
118
|
delivery: apis.delivery,
|
|
117
119
|
dispatchEvent: apis.dispatchEvent,
|
|
120
|
+
usage: apis.usage,
|
|
118
121
|
epic: apis.epic,
|
|
119
122
|
story: apis.story,
|
|
120
123
|
task: apis.task,
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// usage.js — LLM cost/usage tracking on top of the v8 ledger.
|
|
2
|
+
//
|
|
3
|
+
// One append-only `usage_events` row per reported turn. The row carries the
|
|
4
|
+
// identity triple denormalized (so it survives session deletion), an item_id
|
|
5
|
+
// attribution and optional session/attempt links. Aggregations read this table
|
|
6
|
+
// directly; there is no rollup.
|
|
7
|
+
|
|
8
|
+
export function createUsageApi({ core }) {
|
|
9
|
+
const { db, now } = core;
|
|
10
|
+
|
|
11
|
+
function record({
|
|
12
|
+
harness, agent, session, itemId,
|
|
13
|
+
sessionId = null, attemptId = null,
|
|
14
|
+
usage, source = "api", turnRef = null, at = null,
|
|
15
|
+
}) {
|
|
16
|
+
if (!usage || !itemId) return null;
|
|
17
|
+
const u = usage;
|
|
18
|
+
const r = db.prepare(`
|
|
19
|
+
INSERT OR IGNORE INTO usage_events(
|
|
20
|
+
item_id, session_id, attempt_id, harness, agent_id, external_session_id,
|
|
21
|
+
model, tokens_in, tokens_out, cache_read, cost_usd, tool_calls,
|
|
22
|
+
source, turn_ref, created_at
|
|
23
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
24
|
+
`).run(
|
|
25
|
+
itemId, sessionId, attemptId, harness, agent, session,
|
|
26
|
+
u.model ?? null, u.tokensIn ?? null, u.tokensOut ?? null, u.cacheRead ?? null,
|
|
27
|
+
u.costUsd ?? null, u.toolCalls ?? null, source ?? "api", turnRef, at ?? now(),
|
|
28
|
+
);
|
|
29
|
+
return r.changes ? Number(r.lastInsertRowid) : null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function whereClause({ itemId, harness, agent, session, model, since } = {}) {
|
|
33
|
+
const where = [];
|
|
34
|
+
const args = [];
|
|
35
|
+
if (itemId) { where.push("item_id=?"); args.push(itemId); }
|
|
36
|
+
if (harness) { where.push("harness=?"); args.push(harness); }
|
|
37
|
+
if (agent) { where.push("agent_id=?"); args.push(agent); }
|
|
38
|
+
if (session) { where.push("external_session_id=?"); args.push(session); }
|
|
39
|
+
if (model) { where.push("model=?"); args.push(model); }
|
|
40
|
+
if (since) { where.push("created_at>=?"); args.push(since); }
|
|
41
|
+
return { where, args };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function list(opts = {}) {
|
|
45
|
+
const { where, args } = whereClause(opts);
|
|
46
|
+
const sql = `SELECT u.*, i.kind AS item_kind
|
|
47
|
+
FROM usage_events u JOIN items i ON i.id=u.item_id
|
|
48
|
+
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
|
|
49
|
+
ORDER BY u.created_at DESC`;
|
|
50
|
+
return db.prepare(sql).all(...args).map((r) => ({
|
|
51
|
+
id: r.id,
|
|
52
|
+
itemId: r.item_id,
|
|
53
|
+
itemKind: r.item_kind,
|
|
54
|
+
sessionId: r.session_id,
|
|
55
|
+
attemptId: r.attempt_id,
|
|
56
|
+
harness: r.harness,
|
|
57
|
+
agentId: r.agent_id,
|
|
58
|
+
externalSessionId: r.external_session_id,
|
|
59
|
+
model: r.model,
|
|
60
|
+
tokensIn: r.tokens_in,
|
|
61
|
+
tokensOut: r.tokens_out,
|
|
62
|
+
cacheRead: r.cache_read,
|
|
63
|
+
costUsd: r.cost_usd,
|
|
64
|
+
toolCalls: r.tool_calls,
|
|
65
|
+
source: r.source,
|
|
66
|
+
turnRef: r.turn_ref,
|
|
67
|
+
at: r.created_at,
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function summary(opts = {}) {
|
|
72
|
+
const { where, args } = whereClause(opts);
|
|
73
|
+
const sql = `SELECT COUNT(*) AS calls,
|
|
74
|
+
COALESCE(SUM(tokens_in),0) AS tokens_in,
|
|
75
|
+
COALESCE(SUM(tokens_out),0) AS tokens_out,
|
|
76
|
+
COALESCE(SUM(cache_read),0) AS cache_read,
|
|
77
|
+
COALESCE(SUM(cost_usd),0) AS cost_usd,
|
|
78
|
+
COALESCE(SUM(tool_calls),0) AS tool_calls
|
|
79
|
+
FROM usage_events
|
|
80
|
+
${where.length ? `WHERE ${where.join(" AND ")}` : ""}`;
|
|
81
|
+
return db.prepare(sql).get(...args);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return { record, list, summary };
|
|
85
|
+
}
|
package/src/tools/index.js
CHANGED
|
@@ -35,6 +35,22 @@ export function createToolHandlers(store, logger) {
|
|
|
35
35
|
async function handle(name, args, identity, meta = null) {
|
|
36
36
|
assertCleanTriple(identity, `caller identity for ${name}`);
|
|
37
37
|
const cfg = resolveRequestConfig(baseConfig, meta);
|
|
38
|
+
// Implicit session bind: an item-touching call binds the session to that
|
|
39
|
+
// item, so a later POST /usage attributes to the last-touched item.
|
|
40
|
+
try {
|
|
41
|
+
const fromArgs = (typeof args?.taskId === "string" || typeof args?.task_id === "string" ||
|
|
42
|
+
typeof args?.id === "string" || typeof args?.epicId === "string" ||
|
|
43
|
+
typeof args?.epic_id === "string" || typeof args?.storyId === "string" ||
|
|
44
|
+
typeof args?.story_id === "string");
|
|
45
|
+
const itemId = fromArgs
|
|
46
|
+
? (args?.taskId ?? args?.task_id ?? args?.id ?? args?.epicId ?? args?.epic_id ?? args?.storyId ?? args?.story_id)
|
|
47
|
+
: null;
|
|
48
|
+
if (fromArgs && itemId) {
|
|
49
|
+
store.session.ensure({ harness: identity.harness, agentId: identity.agent, externalSessionId: identity.session, itemId, kind: "claim" });
|
|
50
|
+
}
|
|
51
|
+
} catch (e) {
|
|
52
|
+
logger?.warn?.(`winch: session bind failed: ${e?.message}`);
|
|
53
|
+
}
|
|
38
54
|
const fn = handlers[name];
|
|
39
55
|
if (!fn) return err(`unknown tool: ${name}`, "unknown_tool");
|
|
40
56
|
return fn(args, identity, cfg);
|