@igorjpimenta/winch 2026.11.25-beta.1 → 2026.11.26-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/package.json +1 -1
- package/plugins/README.md +5 -2
- package/plugins/openclaw/winch/README.md +19 -10
- package/plugins/openclaw/winch/dispatch.js +14 -10
- package/plugins/openclaw/winch/index.js +105 -66
- package/plugins/openclaw/winch/package.json +1 -4
- package/plugins/openclaw/winch/usage.js +64 -5
- package/plugins/opencode/winch/package.json +1 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Igor Pimenta
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
package/plugins/README.md
CHANGED
|
@@ -27,8 +27,11 @@ construction.
|
|
|
27
27
|
|
|
28
28
|
Both companions also report LLM usage per turn to winch's `POST /usage` under
|
|
29
29
|
the same `harness:agent:session` key, so cost lands on the item the session is
|
|
30
|
-
bound to. openclaw
|
|
31
|
-
|
|
30
|
+
bound to. openclaw sums `llm_output` attempt snapshots per run and flushes at
|
|
31
|
+
`agent_end` (the host leaves `usageState` off reply hooks on agent-command
|
|
32
|
+
runs — the wake path — so `reply_payload_sending` is only the inbound
|
|
33
|
+
fallback); this needs `plugins.entries.winch.hooks.allowConversationAccess=true`.
|
|
34
|
+
opencode
|
|
32
35
|
reads final `message.updated` assistant messages (accumulated `cost` plus the
|
|
33
36
|
last step's token snapshot). Both post fire-and-forget with `WINCH_DISPATCH_URL`
|
|
34
37
|
and `WINCH_DISPATCH_TOKEN`; a failed post never affects the host turn, and the
|
|
@@ -16,12 +16,20 @@ OpenClaw companion for [winch](https://github.com/igorjpimenta/winch). Four jobs
|
|
|
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** — `
|
|
20
|
-
`
|
|
21
|
-
to winch's `POST /usage` under the session's
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
`
|
|
19
|
+
4. **Usage reporting** — `llm_output` sums each attempt's token counts into a
|
|
20
|
+
per-run accumulator; `agent_end` (once per run) and `reply_payload_sending`
|
|
21
|
+
(fallback) flush it to winch's `POST /usage` under the session's
|
|
22
|
+
`harness:agent:session` key with `turnRef = runId`, so the server's unique
|
|
23
|
+
index dedupes a double flush. Only sessions bound to an item (a winch call
|
|
24
|
+
carrying an item id) flush. The host does not attach `usageState` to reply
|
|
25
|
+
hooks on agent-command runs — it consumes the recorded snapshot only for
|
|
26
|
+
inbound replies — so the accumulator is the primary source and `usageState`
|
|
27
|
+
the inbound fallback. Posts are fire-and-forget and never delay or fail the
|
|
28
|
+
turn; they use `WINCH_DISPATCH_URL` and `WINCH_DISPATCH_TOKEN`.
|
|
29
|
+
`llm_output`/`agent_end` require `plugins.entries.winch.hooks.
|
|
30
|
+
allowConversationAccess=true` in openclaw.json: the host blocks those hook
|
|
31
|
+
names for non-bundled plugins without it, and a blocked registration is
|
|
32
|
+
logged as a warning but the gateway keeps running without usage reporting.
|
|
25
33
|
|
|
26
34
|
## Install
|
|
27
35
|
|
|
@@ -34,8 +42,9 @@ boot (without it the host never calls `register()` and the route never
|
|
|
34
42
|
binds). The `--accept-capabilities` flag is required: the plugin registers
|
|
35
43
|
an HTTP route and a service.
|
|
36
44
|
|
|
37
|
-
The plugin
|
|
38
|
-
|
|
45
|
+
The plugin talks to the winch server over HTTP (`WINCH_DISPATCH_URL`,
|
|
46
|
+
default `http://127.0.0.1:38293`) and does not bundle the server. The core
|
|
47
|
+
server is installed separately (`npm i -g @igorjpimenta/winch`).
|
|
39
48
|
|
|
40
49
|
Set `dispatchPublicBaseUrl` if the gateway port isn't detectable. Generate the
|
|
41
50
|
bearer with `winch webhook bearer`, then set `WINCH_WEBHOOK_BEARER` and a unique
|
|
@@ -48,8 +57,8 @@ missing.
|
|
|
48
57
|
|
|
49
58
|
Ships on its own line, independent of the core server:
|
|
50
59
|
`winch-openclaw-<semver>` tags publish `@igorjpimenta/winch-openclaw`
|
|
51
|
-
(stable → `latest`, prerelease → `beta`). Bump this package's `version`
|
|
52
|
-
|
|
60
|
+
(stable → `latest`, prerelease → `beta`). Bump this package's `version`
|
|
61
|
+
on each release; there is no npm dependency on the core server.
|
|
53
62
|
|
|
54
63
|
## Config
|
|
55
64
|
|
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
// 202 immediately. A wake only starts a turn: the agent's MCP claim is the
|
|
5
5
|
// work guard, so duplicate delivery is harmless.
|
|
6
6
|
|
|
7
|
+
import { hostname } from "node:os";
|
|
8
|
+
|
|
7
9
|
export const ROUTE_PATH = "/api/winch/dispatch";
|
|
8
10
|
export const DEFAULT_DISPATCH_URL = "http://127.0.0.1:38293";
|
|
9
11
|
const MAX_BODY_BYTES = 1024 * 1024;
|
|
@@ -85,6 +87,7 @@ export function registerReceiver({ api, bearer, wake, started, logger = console
|
|
|
85
87
|
Promise.resolve(wake({
|
|
86
88
|
agent: body.agent,
|
|
87
89
|
message: wakeMessage(body),
|
|
90
|
+
sessionKey: body.itemId,
|
|
88
91
|
kind: body.kind,
|
|
89
92
|
admissionId: body.admissionId,
|
|
90
93
|
attemptNo: body.attemptNo,
|
|
@@ -109,7 +112,9 @@ function wakeMessage({ itemId, kind, admissionId, attemptNo, leaseEpoch }) {
|
|
|
109
112
|
if (kind === "story" || kind === "append" || kind === "review") {
|
|
110
113
|
return `Call backlog_accept_wake with admissionId "${admissionId}", attemptNo ${attemptNo}, and leaseEpoch ${leaseEpoch ?? 0} before working on ${itemId}.`;
|
|
111
114
|
}
|
|
112
|
-
|
|
115
|
+
// A bare item id is not a prompt: the agent must be told to claim, or it
|
|
116
|
+
// answers conversationally and the admission never leaves offered.
|
|
117
|
+
return `Claim task ${itemId} with backlog_claim (taskId "${itemId}"), then work it to completion.`;
|
|
113
118
|
}
|
|
114
119
|
|
|
115
120
|
export async function registerExecutor({ baseUrl, harness, consumerId, executorId, url, bearer, fresh = false, timeoutMs = 5000 }) {
|
|
@@ -160,6 +165,7 @@ export async function recoverOnce({ baseUrl, harness, consumerId, executorId, wa
|
|
|
160
165
|
Promise.resolve(wake({
|
|
161
166
|
agent: row.agent,
|
|
162
167
|
message: wakeMessage(row),
|
|
168
|
+
sessionKey: row.itemId,
|
|
163
169
|
kind: row.kind,
|
|
164
170
|
admissionId: row.admissionId,
|
|
165
171
|
attemptNo: row.attemptNo,
|
|
@@ -216,23 +222,21 @@ export function postSettle({ baseUrl, admissionId, consumerId = null, bearer = n
|
|
|
216
222
|
}).catch((err) => logger?.warn?.(`winch: settle ${admissionId} failed: ${err?.message ?? err}`));
|
|
217
223
|
}
|
|
218
224
|
|
|
219
|
-
|
|
225
|
+
// The receiver is registered from plugin register() — before the gateway HTTP
|
|
226
|
+
// server binds; a route attached from this service start never reaches the
|
|
227
|
+
// live listener (observed 404 on /api/winch/dispatch). startDispatch owns only
|
|
228
|
+
// the register/reconcile loop.
|
|
229
|
+
export function startDispatch({ cfg = {}, harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "openclaw", wake, started = new Map(), logger = console }) {
|
|
220
230
|
if (cfg.dispatchEnabled === false) return null;
|
|
221
231
|
const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
|
|
222
232
|
const consumerId = cfg.winchConsumerId ?? process.env.WINCH_CONSUMER_ID ?? `${harness}:${hostname()}`;
|
|
223
233
|
const bearer = process.env.WINCH_WEBHOOK_BEARER;
|
|
224
234
|
if (!executorId || !bearer) {
|
|
225
|
-
logger?.warn?.("winch: dispatch needs WINCH_EXECUTOR_ID and WINCH_WEBHOOK_BEARER;
|
|
235
|
+
logger?.warn?.("winch: dispatch needs WINCH_EXECUTOR_ID and WINCH_WEBHOOK_BEARER; reconcile loop disabled");
|
|
226
236
|
return null;
|
|
227
237
|
}
|
|
228
238
|
const baseUrl = process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL;
|
|
229
239
|
const publicBaseUrl = cfg.dispatchPublicBaseUrl ?? process.env.WINCH_DISPATCH_PUBLIC_BASE_URL ?? "http://127.0.0.1:18789";
|
|
230
|
-
const started = new Map();
|
|
231
|
-
const gatedWake = createWakeGuard(wake, {
|
|
232
|
-
settle: (admissionId) => void postSettle({ baseUrl, admissionId, consumerId, bearer, logger }),
|
|
233
|
-
});
|
|
234
|
-
|
|
235
|
-
registerReceiver({ api, bearer, wake: gatedWake, started, logger });
|
|
236
240
|
|
|
237
241
|
let fresh = true;
|
|
238
242
|
const run = async () => {
|
|
@@ -252,7 +256,7 @@ export function startDispatch({ api, cfg = {}, harness = cfg.winchHarness ?? pro
|
|
|
252
256
|
return;
|
|
253
257
|
}
|
|
254
258
|
try {
|
|
255
|
-
await recoverOnce({ baseUrl, harness, consumerId, executorId, wake
|
|
259
|
+
await recoverOnce({ baseUrl, harness, consumerId, executorId, wake, started, logger });
|
|
256
260
|
} catch (err) {
|
|
257
261
|
logger?.warn?.(`winch: dispatch recover failed: ${err?.message ?? err}`);
|
|
258
262
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
2
2
|
import { buildWinchMeta } from "./meta.js";
|
|
3
|
-
import { startDispatch, DEFAULT_DISPATCH_URL } from "./dispatch.js";
|
|
4
|
-
import { carriesItemId, remember, reportReplyUsage } from "./usage.js";
|
|
3
|
+
import { createWakeGuard, postSettle, registerReceiver, startDispatch, DEFAULT_DISPATCH_URL } from "./dispatch.js";
|
|
4
|
+
import { accumulateUsage, carriesItemId, llmOutputUsage, remember, reportReplyUsage } from "./usage.js";
|
|
5
5
|
import { spawn } from "node:child_process";
|
|
6
6
|
import { existsSync } from "node:fs";
|
|
7
7
|
import { hostname } from "node:os";
|
|
@@ -11,6 +11,67 @@ import path from "node:path";
|
|
|
11
11
|
// a full replacement of event.params with _meta.winch set unconditionally on
|
|
12
12
|
// every winch tool call. A call without a resolvable session/agent returns
|
|
13
13
|
// undefined and is refused by the server; the model cannot supply identity.
|
|
14
|
+
// scheduleSessionTurn only commits for bundled plugins; an npm adapter wakes
|
|
15
|
+
// by starting a one-shot agent session through the CLI. The gateway's own
|
|
16
|
+
// argv[1] is the internal dist entry, which has no `agent` subcommand, so
|
|
17
|
+
// resolve the package's CLI shim beside it.
|
|
18
|
+
function buildWake({ cfg, logger }) {
|
|
19
|
+
const candidates = [
|
|
20
|
+
cfg.dispatchOpenclawBin,
|
|
21
|
+
path.resolve(path.dirname(process.argv[1] ?? ""), "..", "openclaw.mjs"),
|
|
22
|
+
"/opt/homebrew/bin/openclaw",
|
|
23
|
+
].filter(Boolean);
|
|
24
|
+
const entry = candidates.find((c) => { try { return existsSync(c); } catch { return false; } }) ?? candidates[0];
|
|
25
|
+
return ({ agent, message, sessionKey }) => {
|
|
26
|
+
const tryOnce = () =>
|
|
27
|
+
new Promise((resolve, reject) => {
|
|
28
|
+
const args = [
|
|
29
|
+
entry,
|
|
30
|
+
"agent",
|
|
31
|
+
"--agent", agent,
|
|
32
|
+
"--session-key", `agent:${agent}:winch:${sessionKey ?? message}`,
|
|
33
|
+
"--message", message,
|
|
34
|
+
];
|
|
35
|
+
// The gateway marks its own env; a child that inherits the
|
|
36
|
+
// service markers exits before doing any work.
|
|
37
|
+
const env = { ...process.env };
|
|
38
|
+
for (const key of [
|
|
39
|
+
"OPENCLAW_LAUNCHD_LABEL",
|
|
40
|
+
"OPENCLAW_SERVICE_KIND",
|
|
41
|
+
"OPENCLAW_SERVICE_MARKER",
|
|
42
|
+
"OPENCLAW_SERVICE_MANAGED_ENV_KEYS",
|
|
43
|
+
"OPENCLAW_SYSTEMD_UNIT",
|
|
44
|
+
"OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER",
|
|
45
|
+
"OPENCLAW_WINDOWS_TASK_NAME",
|
|
46
|
+
]) delete env[key];
|
|
47
|
+
const child = spawn(process.execPath, args, {
|
|
48
|
+
detached: true,
|
|
49
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
50
|
+
env,
|
|
51
|
+
});
|
|
52
|
+
let stderr = "";
|
|
53
|
+
child.stderr?.on("data", (d) => { stderr = (stderr + d.toString()).slice(-2000); });
|
|
54
|
+
child.on("error", reject);
|
|
55
|
+
child.on("exit", (code) =>
|
|
56
|
+
code === 0 ? resolve() : reject(new Error(`exit ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`))
|
|
57
|
+
);
|
|
58
|
+
child.unref();
|
|
59
|
+
});
|
|
60
|
+
return (async () => {
|
|
61
|
+
let last;
|
|
62
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
63
|
+
try {
|
|
64
|
+
return await tryOnce();
|
|
65
|
+
} catch (e) {
|
|
66
|
+
last = e;
|
|
67
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
throw last;
|
|
71
|
+
})();
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
14
75
|
export default definePluginEntry({
|
|
15
76
|
id: "winch",
|
|
16
77
|
name: "Winch",
|
|
@@ -57,29 +118,65 @@ export default definePluginEntry({
|
|
|
57
118
|
// Only sessions that have made a winch call are bound to an item, so only
|
|
58
119
|
// those carry usage the server can attribute.
|
|
59
120
|
const engaged = new Set();
|
|
121
|
+
// Per-run token sums from llm_output; flushed at agent_end (once per run)
|
|
122
|
+
// and on reply_payload_sending as a fallback, gated on engagement.
|
|
123
|
+
const runs = new Map();
|
|
60
124
|
if (typeof api.on === "function") {
|
|
61
125
|
api.on("before_tool_call", (event, ctx) => {
|
|
62
126
|
const stamp = buildWinchMeta(event, ctx, harness, consumerId, executorId);
|
|
63
127
|
if (stamp && carriesItemId(stamp.params)) remember(engaged, stamp.params._meta.winch.session);
|
|
64
128
|
return stamp;
|
|
65
129
|
});
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
130
|
+
api.on("llm_output", (event, ctx) => {
|
|
131
|
+
const snap = llmOutputUsage(event, ctx);
|
|
132
|
+
if (snap) accumulateUsage(runs, snap);
|
|
133
|
+
});
|
|
134
|
+
const flush = (session, event) => {
|
|
135
|
+
if (!session || !engaged.has(session)) return;
|
|
71
136
|
reportReplyUsage({
|
|
72
137
|
event,
|
|
138
|
+
runs,
|
|
73
139
|
harness,
|
|
74
140
|
baseUrl: process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL,
|
|
75
141
|
token: process.env.WINCH_DISPATCH_TOKEN,
|
|
76
142
|
logger: api.logger,
|
|
77
143
|
});
|
|
144
|
+
};
|
|
145
|
+
api.on("agent_end", (event, ctx) => {
|
|
146
|
+
flush(ctx?.sessionKey ?? event?.sessionKey ?? null, { runId: event?.runId ?? ctx?.runId ?? null });
|
|
147
|
+
});
|
|
148
|
+
// Fires on agent-command replies too, but without usageState there; kept
|
|
149
|
+
// as the inbound-path fallback where the host does attach a snapshot.
|
|
150
|
+
// The hook returns nothing so the payload is delivered unchanged.
|
|
151
|
+
api.on("reply_payload_sending", (event) => {
|
|
152
|
+
flush(event?.sessionKey ?? event?.usageState?.sessionId ?? event?.runId ?? null, event);
|
|
78
153
|
});
|
|
79
154
|
} else {
|
|
80
155
|
api.logger.warn("winch: api.on unavailable; identity and usage hooks not registered");
|
|
81
156
|
}
|
|
82
157
|
|
|
158
|
+
// Wake + route must exist at register() time: the HTTP listener binds
|
|
159
|
+
// after plugin registration, and service start runs too late to attach
|
|
160
|
+
// a new route. The service below only owns the reconcile loop. The guard
|
|
161
|
+
// dedupes receiver-vs-recover wakes and settles each admission on exit;
|
|
162
|
+
// both paths share it (plus `started`) so the pump/recover race sees one
|
|
163
|
+
// live child per admission.
|
|
164
|
+
const started = new Map();
|
|
165
|
+
const wake = buildWake({ cfg, logger: api.logger });
|
|
166
|
+
let gatedWake = wake;
|
|
167
|
+
if (cfg.dispatchEnabled !== false && typeof api.registerHttpRoute === "function") {
|
|
168
|
+
const bearer = process.env.WINCH_WEBHOOK_BEARER;
|
|
169
|
+
if (bearer) {
|
|
170
|
+
const baseUrl = process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL;
|
|
171
|
+
gatedWake = createWakeGuard(wake, {
|
|
172
|
+
settle: (admissionId) => void postSettle({ baseUrl, admissionId, consumerId, bearer, logger: api.logger }),
|
|
173
|
+
});
|
|
174
|
+
registerReceiver({ api, bearer, wake: gatedWake, started, logger: api.logger });
|
|
175
|
+
} else {
|
|
176
|
+
api.logger.warn("winch: dispatch needs WINCH_WEBHOOK_BEARER; receiver not registered");
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
83
180
|
let dispatch = null;
|
|
84
181
|
if (typeof api.registerService === "function") {
|
|
85
182
|
api.registerService({
|
|
@@ -89,65 +186,7 @@ export default definePluginEntry({
|
|
|
89
186
|
api.logger.info("winch: dispatch disabled by config");
|
|
90
187
|
return;
|
|
91
188
|
}
|
|
92
|
-
|
|
93
|
-
// adapter wakes by starting a one-shot agent session through the CLI.
|
|
94
|
-
// The gateway's own argv[1] is the internal dist entry, which has no
|
|
95
|
-
// `agent` subcommand, so resolve the package's CLI shim beside it.
|
|
96
|
-
const candidates = [
|
|
97
|
-
cfg.dispatchOpenclawBin,
|
|
98
|
-
path.resolve(path.dirname(process.argv[1] ?? ""), "..", "openclaw.mjs"),
|
|
99
|
-
"/opt/homebrew/bin/openclaw",
|
|
100
|
-
].filter(Boolean);
|
|
101
|
-
const entry = candidates.find((c) => { try { return existsSync(c); } catch { return false; } }) ?? candidates[0];
|
|
102
|
-
const wake = ({ agent, message, sessionKey }) => {
|
|
103
|
-
const tryOnce = () =>
|
|
104
|
-
new Promise((resolve, reject) => {
|
|
105
|
-
const args = [
|
|
106
|
-
entry,
|
|
107
|
-
"agent",
|
|
108
|
-
"--agent", agent,
|
|
109
|
-
"--session-key", `agent:${agent}:winch:${sessionKey ?? message}`,
|
|
110
|
-
"--message", message,
|
|
111
|
-
];
|
|
112
|
-
// The gateway marks its own env; a child that inherits the
|
|
113
|
-
// service markers exits before doing any work.
|
|
114
|
-
const env = { ...process.env };
|
|
115
|
-
for (const key of [
|
|
116
|
-
"OPENCLAW_LAUNCHD_LABEL",
|
|
117
|
-
"OPENCLAW_SERVICE_KIND",
|
|
118
|
-
"OPENCLAW_SERVICE_MARKER",
|
|
119
|
-
"OPENCLAW_SERVICE_MANAGED_ENV_KEYS",
|
|
120
|
-
"OPENCLAW_SYSTEMD_UNIT",
|
|
121
|
-
"OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER",
|
|
122
|
-
"OPENCLAW_WINDOWS_TASK_NAME",
|
|
123
|
-
]) delete env[key];
|
|
124
|
-
const child = spawn(process.execPath, args, {
|
|
125
|
-
detached: true,
|
|
126
|
-
stdio: ["ignore", "ignore", "pipe"],
|
|
127
|
-
env,
|
|
128
|
-
});
|
|
129
|
-
let stderr = "";
|
|
130
|
-
child.stderr?.on("data", (d) => { stderr = (stderr + d.toString()).slice(-2000); });
|
|
131
|
-
child.on("error", reject);
|
|
132
|
-
child.on("exit", (code) =>
|
|
133
|
-
code === 0 ? resolve() : reject(new Error(`exit ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`))
|
|
134
|
-
);
|
|
135
|
-
child.unref();
|
|
136
|
-
});
|
|
137
|
-
return (async () => {
|
|
138
|
-
let last;
|
|
139
|
-
for (let attempt = 0; attempt < 3; attempt++) {
|
|
140
|
-
try {
|
|
141
|
-
return await tryOnce();
|
|
142
|
-
} catch (e) {
|
|
143
|
-
last = e;
|
|
144
|
-
await new Promise((r) => setTimeout(r, 5000));
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
throw last;
|
|
148
|
-
})();
|
|
149
|
-
};
|
|
150
|
-
dispatch = startDispatch({ api, cfg, harness, wake, logger: api.logger });
|
|
189
|
+
dispatch = startDispatch({ cfg, harness, wake: gatedWake, started, logger: api.logger });
|
|
151
190
|
},
|
|
152
191
|
stop: async () => {
|
|
153
192
|
dispatch?.close();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@igorjpimenta/winch-openclaw",
|
|
3
|
-
"version": "2026.11.
|
|
3
|
+
"version": "2026.11.26-beta.1",
|
|
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",
|
|
@@ -29,9 +29,6 @@
|
|
|
29
29
|
"minHostVersion": ">=2026.5.18"
|
|
30
30
|
}
|
|
31
31
|
},
|
|
32
|
-
"dependencies": {
|
|
33
|
-
"@igorjpimenta/winch": "^2026.11.19-beta.1"
|
|
34
|
-
},
|
|
35
32
|
"peerDependencies": {
|
|
36
33
|
"openclaw": ">=2026.5.18"
|
|
37
34
|
}
|
|
@@ -62,6 +62,64 @@ export function usageBody({ harness, agent, session, usage, turnRef }) {
|
|
|
62
62
|
return { sessionKey: `${harness}:${agent}:${session}`, turnRef: turnRef ?? null, usage };
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
+
// llm_output is the only hook carrying token counts on agent-command runs
|
|
66
|
+
// (the wake path): reply_payload_sending arrives with usageState undefined
|
|
67
|
+
// there because the host consumes the recorded snapshot only for inbound
|
|
68
|
+
// replies. Attempts accumulate per runId; agent_end and reply flush pass
|
|
69
|
+
// turnRef=runId so the server's unique index dedupes a double report.
|
|
70
|
+
export function llmOutputUsage(event, ctx) {
|
|
71
|
+
const raw = event?.usage;
|
|
72
|
+
if (!raw || typeof raw !== "object") return null;
|
|
73
|
+
const usage = {
|
|
74
|
+
model: typeof event.resolvedRef === "string" && event.resolvedRef
|
|
75
|
+
? event.resolvedRef
|
|
76
|
+
: (event.provider && event.model ? `${event.provider}/${event.model}` : null),
|
|
77
|
+
tokensIn: num(raw.input),
|
|
78
|
+
tokensOut: num(raw.output),
|
|
79
|
+
cacheRead: num(raw.cacheRead),
|
|
80
|
+
};
|
|
81
|
+
if (usage.tokensIn === null && usage.tokensOut === null && usage.cacheRead === null) return null;
|
|
82
|
+
const runId = typeof event.runId === "string" && event.runId ? event.runId : null;
|
|
83
|
+
const session = typeof ctx?.sessionKey === "string" && ctx.sessionKey ? ctx.sessionKey : null;
|
|
84
|
+
const agent = typeof ctx?.agentId === "string" && ctx.agentId ? ctx.agentId : null;
|
|
85
|
+
if (!runId || !session || !agent) return null;
|
|
86
|
+
return { runId, agent, session, usage };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function sumNullable(a, b) {
|
|
90
|
+
if (a === null && b === null) return null;
|
|
91
|
+
return (a ?? 0) + (b ?? 0);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// FIFO-bounded: llm_output fires for every run in the gateway, engaged or
|
|
95
|
+
// not; engagement is checked at flush, not at accumulation, because a session
|
|
96
|
+
// binds to its item mid-run (first tool call) after earlier attempts.
|
|
97
|
+
export function accumulateUsage(runs, snap, max = 500) {
|
|
98
|
+
const prev = runs.get(snap.runId);
|
|
99
|
+
if (prev) {
|
|
100
|
+
prev.usage.tokensIn = sumNullable(prev.usage.tokensIn, snap.usage.tokensIn);
|
|
101
|
+
prev.usage.tokensOut = sumNullable(prev.usage.tokensOut, snap.usage.tokensOut);
|
|
102
|
+
prev.usage.cacheRead = sumNullable(prev.usage.cacheRead, snap.usage.cacheRead);
|
|
103
|
+
if (snap.usage.model) prev.usage.model = snap.usage.model;
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (runs.size >= max) runs.delete(runs.keys().next().value);
|
|
107
|
+
runs.set(snap.runId, { agent: snap.agent, session: snap.session, usage: { ...snap.usage } });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function runUsageBody({ event, runs, harness }) {
|
|
111
|
+
const runId = typeof event?.runId === "string" && event.runId ? event.runId : null;
|
|
112
|
+
const snap = runId && runs ? runs.get(runId) : null;
|
|
113
|
+
if (!snap) return null;
|
|
114
|
+
return usageBody({ harness, agent: snap.agent, session: snap.session, turnRef: runId, usage: snap.usage });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function usageStateBody({ event, harness }) {
|
|
118
|
+
const reported = usageFromReplyEvent(event);
|
|
119
|
+
if (!reported) return null;
|
|
120
|
+
return usageBody({ harness, ...reported });
|
|
121
|
+
}
|
|
122
|
+
|
|
65
123
|
export async function postUsage({
|
|
66
124
|
baseUrl,
|
|
67
125
|
token,
|
|
@@ -91,11 +149,12 @@ export async function postUsage({
|
|
|
91
149
|
}
|
|
92
150
|
}
|
|
93
151
|
|
|
94
|
-
// Fire-and-forget entry used by the
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
152
|
+
// Fire-and-forget entry used by the hooks; returns the body when it posted.
|
|
153
|
+
// The per-run accumulator wins over usageState: on agent-command runs the
|
|
154
|
+
// host never attaches usageState, and the accumulator holds the summed
|
|
155
|
+
// attempts either way.
|
|
156
|
+
export function reportReplyUsage({ event, runs, harness, baseUrl, token, logger = console, fetchImpl = fetch }) {
|
|
157
|
+
const body = runUsageBody({ event, runs, harness }) ?? usageStateBody({ event, harness });
|
|
99
158
|
if (!body) return null;
|
|
100
159
|
void postUsage({ baseUrl, token, body, logger, fetchImpl });
|
|
101
160
|
return body;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@igorjpimenta/winch-opencode",
|
|
3
|
-
"version": "2026.11.
|
|
3
|
+
"version": "2026.11.26-beta.1",
|
|
4
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",
|