@igorjpimenta/winch-openclaw 0.0.0-stage → 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.
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
1
+ # @igorjpimenta/winch-openclaw
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OpenClaw companion for [winch](https://github.com/igorjpimenta/winch). Four jobs:
4
+
5
+ 1. **Identity** — `before_tool_call` stamps `_meta.winch {harness, agent, session}`
6
+ onto every winch MCP tool call, overwriting unconditionally so model-supplied
7
+ meta cannot impersonate an agent.
8
+ 2. **Wake receiver** — serves `POST /api/winch/dispatch`, verifies the
9
+ executor bearer, acknowledges standby deliveries, deduplicates on
10
+ `admissionId + attemptNo`, and starts a one-shot session. Tasks use
11
+ `backlog_claim`; planner wakes must call `backlog_accept_wake` with the
12
+ payload lease before working.
13
+ 3. **Self-registration and recovery** — registers one wake URL per
14
+ `WINCH_CONSUMER_ID` with `WINCH_WEBHOOK_BEARER`, then reconciles assigned
15
+ `in_progress` work through `POST /dispatch/recover`. The first run is
16
+ `fresh: true`; later heartbeats preserve failure state. `WINCH_EXECUTOR_ID`
17
+ identifies the live connection; the event's `kind` selects the listener
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`.
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ openclaw plugins install @igorjpimenta/winch-openclaw --accept-capabilities
30
+ ```
31
+
32
+ The manifest declares `activation.onStartup`, so the plugin loads at gateway
33
+ boot (without it the host never calls `register()` and the route never
34
+ binds). The `--accept-capabilities` flag is required: the plugin registers
35
+ an HTTP route and a service.
36
+
37
+ The plugin depends on `@igorjpimenta/winch`, so npm resolves and pins the
38
+ server version alongside it.
39
+
40
+ Set `dispatchPublicBaseUrl` if the gateway port isn't detectable. Generate the
41
+ bearer with `winch webhook bearer`, then set `WINCH_WEBHOOK_BEARER` and a unique
42
+ `WINCH_EXECUTOR_ID` in the gateway/plugin environment. `WINCH_CONSUMER_ID`
43
+ defaults to `harness:hostname`, so the gateway keeps one route across restarts.
44
+ The receiver stays disarmed and logs a warning if the executor or bearer is
45
+ missing.
46
+
47
+ ## Releases
48
+
49
+ Ships on its own line, independent of the core server:
50
+ `winch-openclaw-<semver>` tags publish `@igorjpimenta/winch-openclaw`
51
+ (stable → `latest`, prerelease → `beta`). Bump this package's `version` and
52
+ its `@igorjpimenta/winch` dependency floor together.
53
+
54
+ ## Config
55
+
56
+ | key | default | meaning |
57
+ |---|---|---|
58
+ | `dispatchEnabled` | `true` | receive wakes and reconcile assigned `in_progress` work |
59
+ | `dispatchPublicBaseUrl` | `http://127.0.0.1:<gateway.port>` | gateway address winch can reach |
60
+ | `winchHarness` | `WINCH_HARNESS` or `openclaw` | harness name for identity and dispatch |
61
+ | `winchExecutorId` | `WINCH_EXECUTOR_ID` | unique instance id for this connection; also the registration lease owner |
62
+ | `winchConsumerId` | `WINCH_CONSUMER_ID` or `harness:hostname` | stable webhook identity |
63
+ | `dispatchReconcileMs` | `30000` | recovery interval |
64
+ | `dispatchOpenclawBin` | shim beside the gateway entry | CLI used to start a wake session |
65
+
66
+ Environment:
67
+
68
+ | variable | meaning |
69
+ |---|---|
70
+ | `WINCH_EXECUTOR_ID` | unique instance id; required unless `winchExecutorId` is set |
71
+ | `WINCH_CONSUMER_ID` | stable webhook identity; default `harness:hostname` |
72
+ | `WINCH_WEBHOOK_BEARER` | receiver token; generate with `winch webhook bearer` |
73
+ | `WINCH_DISPATCH_URL` | winch base URL, default `http://127.0.0.1:38293` |
74
+ | `WINCH_DISPATCH_PUBLIC_BASE_URL` | fallback for `dispatchPublicBaseUrl` |
75
+ | `WINCH_DISPATCH_TOKEN` | management bearer for register/recover/notify; required for a non-loopback winch bind |
76
+
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.
package/dispatch.js ADDED
@@ -0,0 +1,236 @@
1
+ // dispatch.js — receive wake webhooks and reconcile in-progress work.
2
+ //
3
+ // The gateway owns the HTTP route; winch POSTs { type: "wake", ... } and gets
4
+ // 202 immediately. A wake only starts a turn: the agent's MCP claim is the
5
+ // work guard, so duplicate delivery is harmless.
6
+
7
+ export const ROUTE_PATH = "/api/winch/dispatch";
8
+ export const DEFAULT_DISPATCH_URL = "http://127.0.0.1:38293";
9
+ const MAX_BODY_BYTES = 1024 * 1024;
10
+ const INFLIGHT_TTL_MS = 35 * 60 * 1000;
11
+
12
+ function readJson(req, res) {
13
+ return (async () => {
14
+ let size = 0;
15
+ let raw = "";
16
+ for await (const chunk of req) {
17
+ size += chunk.length;
18
+ if (size > MAX_BODY_BYTES) {
19
+ res.statusCode = 413;
20
+ res.end(JSON.stringify({ error: "body too large" }));
21
+ return undefined;
22
+ }
23
+ raw += chunk;
24
+ }
25
+ if (!raw) return {};
26
+ try {
27
+ return JSON.parse(raw);
28
+ } catch {
29
+ res.statusCode = 400;
30
+ res.end(JSON.stringify({ error: "invalid json body" }));
31
+ return undefined;
32
+ }
33
+ })();
34
+ }
35
+
36
+ function json(res, status, body) {
37
+ res.statusCode = status;
38
+ res.setHeader("content-type", "application/json");
39
+ res.end(JSON.stringify(body));
40
+ }
41
+
42
+ function routeUrl(baseUrl) {
43
+ return `${String(baseUrl).replace(/\/+$/, "")}${ROUTE_PATH}`;
44
+ }
45
+
46
+ export function registerReceiver({ api, bearer, wake, started, logger = console }) {
47
+ api.registerHttpRoute({
48
+ path: ROUTE_PATH,
49
+ auth: "plugin",
50
+ match: "exact",
51
+ handler: async (req, res) => {
52
+ if (req.method !== "POST") {
53
+ res.statusCode = 405;
54
+ res.setHeader("allow", "POST");
55
+ res.end(JSON.stringify({ error: "method not allowed" }));
56
+ return;
57
+ }
58
+ const auth = req.headers?.authorization ?? "";
59
+ if (!auth.startsWith("Bearer ") || auth.slice(7) !== bearer) {
60
+ json(res, 401, { error: "unauthorized" });
61
+ return;
62
+ }
63
+ const body = await readJson(req, res);
64
+ if (body === undefined) return;
65
+ if (body?.type === "ping") {
66
+ json(res, 200, { ok: true, test: true });
67
+ return;
68
+ }
69
+ if (body?.type !== "wake" || !body.admissionId || !body.itemId || !body.agent) {
70
+ json(res, 400, { error: "wake payload requires admissionId, itemId, agent" });
71
+ return;
72
+ }
73
+ if (body.execution === "standby") {
74
+ json(res, 202, { ok: true, admissionId: body.admissionId, standby: true });
75
+ return;
76
+ }
77
+ const key = `start:${body.admissionId}:${body.attemptNo ?? "none"}`;
78
+ const now = Date.now();
79
+ for (const [k, at] of started ?? []) if (now - at > INFLIGHT_TTL_MS) started.delete(k);
80
+ if (started?.has(key)) {
81
+ json(res, 202, { ok: true, admissionId: body.admissionId, duplicate: true });
82
+ return;
83
+ }
84
+ started?.set(key, now);
85
+ Promise.resolve(wake({
86
+ agent: body.agent,
87
+ message: wakeMessage(body),
88
+ kind: body.kind,
89
+ admissionId: body.admissionId,
90
+ attemptNo: body.attemptNo,
91
+ leaseEpoch: body.leaseEpoch ?? 0,
92
+ })).catch((err) => {
93
+ started?.delete(key);
94
+ logger?.warn?.(`winch: wake ${body.itemId} failed: ${err?.message ?? err}`);
95
+ });
96
+ json(res, 202, { ok: true, admissionId: body.admissionId });
97
+ },
98
+ });
99
+ }
100
+
101
+ function dispatchAuthHeaders() {
102
+ const headers = { "content-type": "application/json" };
103
+ const token = String(process.env.WINCH_DISPATCH_TOKEN ?? "").trim();
104
+ if (token) headers.authorization = `Bearer ${token}`;
105
+ return headers;
106
+ }
107
+
108
+ function wakeMessage({ itemId, kind, admissionId, attemptNo, leaseEpoch }) {
109
+ if (kind === "story" || kind === "append" || kind === "review") {
110
+ return `Call backlog_accept_wake with admissionId "${admissionId}", attemptNo ${attemptNo}, and leaseEpoch ${leaseEpoch ?? 0} before working on ${itemId}.`;
111
+ }
112
+ return itemId;
113
+ }
114
+
115
+ export async function registerExecutor({ baseUrl, harness, consumerId, executorId, url, bearer, fresh = false, timeoutMs = 5000 }) {
116
+ const res = await fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/register`, {
117
+ method: "POST",
118
+ headers: dispatchAuthHeaders(),
119
+ body: JSON.stringify({ harness, consumerId, executorId, instanceId: executorId, url, bearer, fresh }),
120
+ signal: AbortSignal.timeout(timeoutMs),
121
+ });
122
+ if (!res.ok) throw new Error(`dispatch register ${res.status}`);
123
+ return res.json();
124
+ }
125
+
126
+ export async function recoverOnce({ baseUrl, harness, consumerId, executorId, wake, started, logger = console, timeoutMs = 5000 }) {
127
+ const res = await fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/recover`, {
128
+ method: "POST",
129
+ headers: dispatchAuthHeaders(),
130
+ body: JSON.stringify({ harness, consumerId, executorId }),
131
+ signal: AbortSignal.timeout(timeoutMs),
132
+ });
133
+ if (!res.ok) throw new Error(`dispatch recover ${res.status}`);
134
+ const body = await res.json();
135
+ const now = Date.now();
136
+ for (const [key, at] of started) if (now - at > INFLIGHT_TTL_MS) started.delete(key);
137
+
138
+ for (const row of body?.resume ?? []) {
139
+ if (!row?.task?.id) continue;
140
+ const key = `resume:${row.task.id}:${row.attemptId ?? "none"}`;
141
+ if (started.has(key)) continue;
142
+ started.set(key, now);
143
+ Promise.resolve(wake({
144
+ agent: row.task.assignee_agent,
145
+ message: resumePrompt(row),
146
+ sessionKey: row.task.id,
147
+ kind: "resume",
148
+ attemptId: row.attemptId,
149
+ })).catch((err) => {
150
+ started.delete(key);
151
+ logger?.warn?.(`winch: resume ${row.task.id} failed: ${err?.message ?? err}`);
152
+ });
153
+ }
154
+
155
+ for (const row of body?.start ?? []) {
156
+ if (!row?.admissionId || !row?.itemId) continue;
157
+ const key = `start:${row.admissionId}:${row.attemptNo ?? "none"}`;
158
+ if (started.has(key)) continue;
159
+ started.set(key, now);
160
+ Promise.resolve(wake({
161
+ agent: row.agent,
162
+ message: wakeMessage(row),
163
+ kind: row.kind,
164
+ admissionId: row.admissionId,
165
+ attemptNo: row.attemptNo,
166
+ leaseEpoch: row.leaseEpoch ?? 0,
167
+ })).catch((err) => {
168
+ started.delete(key);
169
+ logger?.warn?.(`winch: wake ${row.itemId} failed: ${err?.message ?? err}`);
170
+ });
171
+ }
172
+ return body;
173
+ }
174
+
175
+ export function resumePrompt(row) {
176
+ const taskId = row?.task?.id ?? "(unknown)";
177
+ const attemptId = row?.attemptId ?? null;
178
+ const leaseEpoch = row?.leaseEpoch ?? 0;
179
+ if (!attemptId) {
180
+ return `Repair ${taskId}. The task is in_progress but has no live attempt. Do not call backlog_claim. Call backlog_update with taskId "${taskId}", heartbeat true, and no attemptId so the store repairs the missing attempt. If it returns stale_claim, stop. Then continue from the existing brief.`;
181
+ }
182
+ return `Resume ${taskId} attempt ${attemptId} leaseEpoch ${leaseEpoch}. You already own this task. Do not call backlog_claim. Call backlog_update with taskId "${taskId}", attemptId "${attemptId}", leaseEpoch ${leaseEpoch}, heartbeat true. If it returns stale_claim, stop. Then continue from the existing brief.`;
183
+ }
184
+
185
+ export function startDispatch({ api, cfg = {}, harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "openclaw", wake, logger = console }) {
186
+ if (cfg.dispatchEnabled === false) return null;
187
+ const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
188
+ const consumerId = cfg.winchConsumerId ?? process.env.WINCH_CONSUMER_ID ?? `${harness}:${hostname()}`;
189
+ const bearer = process.env.WINCH_WEBHOOK_BEARER;
190
+ if (!executorId || !bearer) {
191
+ logger?.warn?.("winch: dispatch needs WINCH_EXECUTOR_ID and WINCH_WEBHOOK_BEARER; receiver disabled");
192
+ return null;
193
+ }
194
+ const baseUrl = process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL;
195
+ const publicBaseUrl = cfg.dispatchPublicBaseUrl ?? process.env.WINCH_DISPATCH_PUBLIC_BASE_URL ?? "http://127.0.0.1:18789";
196
+ const started = new Map();
197
+
198
+ registerReceiver({ api, bearer, wake, started, logger });
199
+
200
+ let fresh = true;
201
+ const run = async () => {
202
+ try {
203
+ await registerExecutor({
204
+ baseUrl,
205
+ harness,
206
+ consumerId,
207
+ executorId,
208
+ url: routeUrl(publicBaseUrl),
209
+ bearer,
210
+ fresh,
211
+ });
212
+ fresh = false;
213
+ } catch (err) {
214
+ logger?.warn?.(`winch: dispatch register failed: ${err?.message ?? err}`);
215
+ return;
216
+ }
217
+ try {
218
+ await recoverOnce({ baseUrl, harness, consumerId, executorId, wake, started, logger });
219
+ } catch (err) {
220
+ logger?.warn?.(`winch: dispatch recover failed: ${err?.message ?? err}`);
221
+ }
222
+ };
223
+
224
+ void run();
225
+ const intervalMs = Number(cfg.dispatchReconcileMs ?? 30000);
226
+ const timer = intervalMs > 0 ? setInterval(() => { void run(); }, intervalMs) : null;
227
+ timer?.unref?.();
228
+
229
+ return {
230
+ close() {
231
+ if (timer) clearInterval(timer);
232
+ },
233
+ get executorId() { return executorId; },
234
+ get consumerId() { return consumerId; },
235
+ };
236
+ }
package/index.js ADDED
@@ -0,0 +1,160 @@
1
+ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
2
+ import { buildWinchMeta } from "./meta.js";
3
+ import { startDispatch, DEFAULT_DISPATCH_URL } from "./dispatch.js";
4
+ import { carriesItemId, remember, reportReplyUsage } from "./usage.js";
5
+ import { spawn } from "node:child_process";
6
+ import { existsSync } from "node:fs";
7
+ import { hostname } from "node:os";
8
+ import path from "node:path";
9
+
10
+ // Mechanics: before_tool_call runs before MCP dispatch, and this hook returns
11
+ // a full replacement of event.params with _meta.winch set unconditionally on
12
+ // every winch tool call. A call without a resolvable session/agent returns
13
+ // undefined and is refused by the server; the model cannot supply identity.
14
+ export default definePluginEntry({
15
+ id: "winch",
16
+ name: "Winch",
17
+ description: "Stamps _meta.winch onto winch MCP tool calls, accepts HTTP wake webhooks, and reconciles assigned in-progress work after a gateway restart.",
18
+ configSchema: () => ({
19
+ type: "object",
20
+ additionalProperties: true,
21
+ properties: {
22
+ dispatchEnabled: {
23
+ type: "boolean",
24
+ description: "Accept wake webhooks and reconcile assigned in-progress work. Default true.",
25
+ },
26
+ dispatchPublicBaseUrl: {
27
+ type: "string",
28
+ description: "Gateway address winch can reach, e.g. http://127.0.0.1:18789. Used to register the wake route.",
29
+ },
30
+ winchHarness: {
31
+ type: "string",
32
+ description: "Harness name for identity and dispatch (must match WINCH_HARNESS). Default: openclaw.",
33
+ },
34
+ winchExecutorId: {
35
+ type: "string",
36
+ description: "Unique executor id for this connection. Default: WINCH_EXECUTOR_ID.",
37
+ },
38
+ winchConsumerId: {
39
+ type: "string",
40
+ description: "Stable consumer id shared by this gateway's executors. Default: harness:hostname.",
41
+ },
42
+ dispatchReconcileMs: {
43
+ type: "integer",
44
+ description: "Reconcile interval in milliseconds. Default: 30000.",
45
+ },
46
+ dispatchOpenclawBin: {
47
+ type: "string",
48
+ description: "OpenClaw CLI entry used to start a wake session (default: the shim beside the gateway entry).",
49
+ },
50
+ },
51
+ }),
52
+ register: (api) => {
53
+ const cfg = api.pluginConfig ?? {};
54
+ const harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "openclaw";
55
+ const consumerId = cfg.winchConsumerId ?? process.env.WINCH_CONSUMER_ID ?? `${harness}:${hostname()}`;
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();
60
+ if (typeof api.on === "function") {
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
+ });
79
+ } else {
80
+ api.logger.warn("winch: api.on unavailable; identity and usage hooks not registered");
81
+ }
82
+
83
+ let dispatch = null;
84
+ if (typeof api.registerService === "function") {
85
+ api.registerService({
86
+ id: "winch-dispatch",
87
+ start: async () => {
88
+ if (cfg.dispatchEnabled === false) {
89
+ api.logger.info("winch: dispatch disabled by config");
90
+ return;
91
+ }
92
+ // scheduleSessionTurn only commits for bundled plugins; an npm
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 });
151
+ },
152
+ stop: async () => {
153
+ dispatch?.close();
154
+ dispatch = null;
155
+ },
156
+ });
157
+ }
158
+ api.logger.info("winch: registered (identity stamp + HTTP dispatch receiver)");
159
+ },
160
+ });
package/meta.js ADDED
@@ -0,0 +1,35 @@
1
+ // meta.js — pure before_tool_call identity stamping. No plugin-SDK import,
2
+ // so it loads under `node --test` outside the openclaw gateway.
3
+
4
+ // openclaw exposes MCP tools as mcp__<server>__<tool> (e.g.
5
+ // mcp__winch__backlog_claim); the substring match survives a prefix change.
6
+ export function isWinchTool(name) {
7
+ return typeof name === "string" && name.includes("winch");
8
+ }
9
+
10
+ // Session resolution mirrors the HookContext the host guarantees for bundled
11
+ // MCP tool calls since v2026.5.16-beta.7 (oldest compatible stable:
12
+ // v2026.5.18, declared in package.json as openclaw.install.minHostVersion).
13
+ // Order below is most stable first: the live session key, then the session
14
+ // id, then the single-run id, then the same fields off the event. A null dimension stays
15
+ // null in the stamp: src/identity.js treats it as a miss and refuses the
16
+ // call, so a half-stamped call fails loudly instead of minting a default
17
+ // key. With no resolvable dimension at all the hook returns undefined and
18
+ // the call proceeds unstamped, for the server to refuse.
19
+ export function buildWinchMeta(event, ctx, harness = "openclaw", consumerId = null, instanceId = null) {
20
+ const toolName = event?.toolName ?? ctx?.toolName;
21
+ if (!isWinchTool(toolName)) return undefined;
22
+ const agent = ctx?.agentId ?? event?.agentId ?? null;
23
+ const session = ctx?.sessionKey ?? ctx?.sessionId ?? ctx?.runId ?? event?.sessionId ?? event?.runId ?? null;
24
+ if (agent === null && session === null) return undefined;
25
+ const params = event?.params ?? {};
26
+ return {
27
+ params: {
28
+ ...params,
29
+ _meta: {
30
+ ...(params._meta ?? {}),
31
+ winch: { harness, agent, session, ...(consumerId ? { consumer: consumerId } : {}), ...(instanceId ? { instance: instanceId } : {}) },
32
+ },
33
+ },
34
+ };
35
+ }
@@ -0,0 +1,43 @@
1
+ {
2
+ "id": "winch",
3
+ "name": "Winch",
4
+ "description": "Stamps _meta.winch onto tool calls, accepts HTTP wake webhooks, and reconciles assigned in-progress work.",
5
+ "enabledByDefault": true,
6
+ "activation": {
7
+ "onStartup": true
8
+ },
9
+ "configSchema": {
10
+ "type": "object",
11
+ "additionalProperties": true,
12
+ "properties": {
13
+ "dispatchEnabled": {
14
+ "type": "boolean",
15
+ "description": "Accept wake webhooks and reconcile assigned in-progress work. Default true."
16
+ },
17
+ "dispatchPublicBaseUrl": {
18
+ "type": "string",
19
+ "description": "Gateway address winch can reach, e.g. http://127.0.0.1:18789. Used to register the wake route."
20
+ },
21
+ "dispatchReconcileMs": {
22
+ "type": "integer",
23
+ "description": "Reconcile interval in milliseconds. Default: 30000."
24
+ },
25
+ "dispatchOpenclawBin": {
26
+ "type": "string",
27
+ "description": "OpenClaw CLI entry used to start a wake session (default: the shim beside the gateway entry)."
28
+ },
29
+ "winchHarness": {
30
+ "type": "string",
31
+ "description": "Harness name for identity and dispatch (must match WINCH_HARNESS). Default: openclaw."
32
+ },
33
+ "winchExecutorId": {
34
+ "type": "string",
35
+ "description": "Unique executor id for this connection. Default: WINCH_EXECUTOR_ID."
36
+ },
37
+ "winchConsumerId": {
38
+ "type": "string",
39
+ "description": "Stable consumer id shared by this gateway's executors. Default: harness:hostname."
40
+ }
41
+ }
42
+ }
43
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch-openclaw",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2026.11.23-beta.3",
4
+ "description": "OpenClaw companion for winch: stamps caller identity on winch MCP tool calls, receives HTTP dispatch wakes, and reconciles in-progress work.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/igorjpimenta/winch.git",
10
+ "directory": "plugins/openclaw/winch"
11
+ },
12
+ "publishConfig": {
13
+ "registry": "https://registry.npmjs.org",
14
+ "access": "public"
15
+ },
16
+ "files": [
17
+ "index.js",
18
+ "meta.js",
19
+ "dispatch.js",
20
+ "openclaw.plugin.json",
21
+ "README.md",
22
+ "usage.js"
23
+ ],
24
+ "openclaw": {
25
+ "extensions": [
26
+ "./index.js"
27
+ ],
28
+ "install": {
29
+ "minHostVersion": ">=2026.5.18"
30
+ }
31
+ },
32
+ "dependencies": {
33
+ "@igorjpimenta/winch": "^2026.11.19-beta.1"
34
+ },
35
+ "peerDependencies": {
36
+ "openclaw": ">=2026.5.18"
37
+ }
38
+ }
package/usage.js ADDED
@@ -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
+ }