@igorjpimenta/winch 0.0.0-stage → 2026.11.22-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.
Files changed (88) hide show
  1. package/.migrations/0000_next_katie_power.sql +99 -0
  2. package/.migrations/0001_add-events-kind.sql +8 -0
  3. package/.migrations/0002_drop-session-budgets.sql +1 -0
  4. package/.migrations/0003_pink_siren.sql +8 -0
  5. package/.migrations/0004_salty_trauma.sql +1 -0
  6. package/.migrations/0005_classy_havok.sql +1 -0
  7. package/.migrations/0006_recursive_items.sql +265 -0
  8. package/.migrations/0007_unify_statuses.sql +35 -0
  9. package/.migrations/0008_core_dispatch.sql +61 -0
  10. package/.migrations/0009_webhooks.sql +17 -0
  11. package/.migrations/0010_dispatch_consumer_id.sql +1 -0
  12. package/.migrations/0011_dispatch_delivery_leases.sql +53 -0
  13. package/.migrations/0012_dispatch_fencing_audit.sql +32 -0
  14. package/.migrations/meta/0000_snapshot.json +658 -0
  15. package/.migrations/meta/0001_snapshot.json +665 -0
  16. package/.migrations/meta/0002_snapshot.json +604 -0
  17. package/.migrations/meta/0003_snapshot.json +656 -0
  18. package/.migrations/meta/0004_snapshot.json +664 -0
  19. package/.migrations/meta/0005_snapshot.json +671 -0
  20. package/.migrations/meta/0006_snapshot.json +1089 -0
  21. package/.migrations/meta/0007_unify_statuses_snapshot.json +1097 -0
  22. package/.migrations/meta/0008_snapshot.json +1382 -0
  23. package/.migrations/meta/0009_snapshot.json +1428 -0
  24. package/.migrations/meta/0010_snapshot.json +1435 -0
  25. package/.migrations/meta/0011_snapshot.json +1670 -0
  26. package/.migrations/meta/0012_snapshot.json +1900 -0
  27. package/.migrations/meta/_journal.json +97 -0
  28. package/README.md +480 -2
  29. package/bin/winch.js +4 -0
  30. package/package.json +36 -4
  31. package/plugins/README.md +304 -0
  32. package/plugins/openclaw/winch/README.md +71 -0
  33. package/plugins/openclaw/winch/dispatch.js +236 -0
  34. package/plugins/openclaw/winch/index.js +139 -0
  35. package/plugins/openclaw/winch/meta.js +35 -0
  36. package/plugins/openclaw/winch/openclaw.plugin.json +43 -0
  37. package/plugins/openclaw/winch/package.json +37 -0
  38. package/plugins/opencode/winch/dispatch.js +228 -0
  39. package/plugins/opencode/winch/hooks.js +22 -0
  40. package/plugins/opencode/winch/identity.js +34 -0
  41. package/plugins/opencode/winch/index.js +198 -0
  42. package/plugins/opencode/winch/package.json +26 -0
  43. package/src/cli.js +434 -0
  44. package/src/config.js +181 -0
  45. package/src/db.js +39 -0
  46. package/src/deps.js +70 -0
  47. package/src/dispatch-server.js +204 -0
  48. package/src/dispatch-webhook.js +221 -0
  49. package/src/dispatch.js +258 -0
  50. package/src/events-ws.js +269 -0
  51. package/src/identity.js +140 -0
  52. package/src/ids.js +18 -0
  53. package/src/mcp-http.js +208 -0
  54. package/src/mcp.js +107 -0
  55. package/src/merges.js +150 -0
  56. package/src/paths.js +15 -0
  57. package/src/ready-queue.js +77 -0
  58. package/src/release.js +96 -0
  59. package/src/reserved.js +23 -0
  60. package/src/schema.js +302 -0
  61. package/src/store/admission.js +314 -0
  62. package/src/store/artifacts.js +24 -0
  63. package/src/store/attempts.js +22 -0
  64. package/src/store/claims.js +182 -0
  65. package/src/store/core.js +225 -0
  66. package/src/store/delivery.js +137 -0
  67. package/src/store/deps.js +62 -0
  68. package/src/store/dispatch-events.js +38 -0
  69. package/src/store/epics.js +31 -0
  70. package/src/store/events.js +21 -0
  71. package/src/store/gates.js +85 -0
  72. package/src/store/index.js +135 -0
  73. package/src/store/items.js +303 -0
  74. package/src/store/stories.js +37 -0
  75. package/src/store/sweep.js +77 -0
  76. package/src/store/tasks.js +190 -0
  77. package/src/store/webhook.js +197 -0
  78. package/src/tools/accept-wake.js +30 -0
  79. package/src/tools/assign.js +75 -0
  80. package/src/tools/claim.js +88 -0
  81. package/src/tools/definitions.js +371 -0
  82. package/src/tools/delegate.js +147 -0
  83. package/src/tools/index.js +44 -0
  84. package/src/tools/plan.js +262 -0
  85. package/src/tools/read.js +103 -0
  86. package/src/tools/report.js +190 -0
  87. package/src/tools/shared.js +62 -0
  88. package/src/watcher.js +105 -0
@@ -0,0 +1,304 @@
1
+ # winch companion plugins — the identity contract
2
+
3
+ The winch server keys every claim to three dimensions
4
+ (`src/identity.js`), and only one of them is declared: the **harness**,
5
+ named at construction (`--harness` / `WINCH_HARNESS`). The **agent** and
6
+ **session** of each call arrive with the call itself — the calling harness's
7
+ companion plugin stamps them in its `before_tool_call` hook, the way lineage
8
+ attributes per-call cost to an agent and a session instead of a configured
9
+ default. Unstamped agent/session fail the call; nothing defaults, ever.
10
+
11
+ | dimension | construction | per-call source | who reads |
12
+ | --------- | -------------------------------- | ---------------------------------------- | ------------------------------------------- |
13
+ | harness | `WINCH_HARNESS` env (**required**, stdio) / `X-Winch-Harness` header (HTTP) | `_meta.winch.harness` if stamped (never overrides a matching declaration) | winch server: logs, `harness:agent:session` claim key |
14
+ | agent | — (never declared) | plugin: ctx `agentId` | winch server: claim attribution, per-agent caps |
15
+ | session | — (never declared) | plugin: ctx `sessionKey`/`runId` | winch server: claim key |
16
+
17
+ **Anti-impersonation:** the openclaw plugin's `before_tool_call` hook runs
18
+ before MCP dispatch and returns a full replacement of `event.params` with
19
+ `_meta.winch` set **unconditionally** on every winch tool call — a model that
20
+ supplies its own `_meta.winch` has it overwritten before the request reaches
21
+ the server. On opencode the meta channel is unreachable (mechanics below), so
22
+ identity is the operator-set env on the MCP server entry — process-scoped
23
+ configuration the model cannot alter per call, so the same property holds by
24
+ construction.
25
+
26
+ ## openclaw
27
+
28
+ Setup verified against the existing extension wiring: every loaded extension
29
+ id is listed in `openclaw.json` → `plugins.allow` (e.g. `browser-lease`), and
30
+ extensions are discovered from `~/.openclaw/extensions/<id>/` — openclaw.json
31
+ carries no explicit extensions path; the browser-lease extension lives at
32
+ `~/.openclaw/extensions/browser-lease/` with its own `openclaw.plugin.json`.
33
+
34
+ 1. Install the plugin package (its own release line, and it pulls
35
+ `@igorjpimenta/winch` as a dependency): `openclaw plugins install
36
+ @igorjpimenta/winch-openclaw`. From a checkout instead: copy or symlink
37
+ `plugins/openclaw/winch/` into `~/.openclaw/extensions/winch/`.
38
+ Set `dispatchPublicBaseUrl` (e.g. `http://127.0.0.1:18789`) if the gateway
39
+ port isn't detectable, and `winchHarness` if the winch MCP entry uses a
40
+ harness other than `openclaw`. Generate a bearer with
41
+ `winch webhook bearer`; set `WINCH_WEBHOOK_BEARER` and a unique
42
+ `WINCH_EXECUTOR_ID` in the gateway/plugin environment; `WINCH_CONSUMER_ID`
43
+ defaults to `harness:hostname` and names the single wake route. The adapter
44
+ fails closed if the executor or bearer is missing, then registers on boot.
45
+ 2. In `~/.openclaw/openclaw.json`, add the MCP server (mirrors the `gbrain`
46
+ entry) and the plugin id (mirrors the `browser-lease` line in
47
+ `plugins.allow`):
48
+
49
+ ```json
50
+ "mcp": {
51
+ "servers": {
52
+ "winch": {
53
+ "command": "winch",
54
+ "args": ["serve", "--mcp", "stdio"],
55
+ "env": { "WINCH_HARNESS": "openclaw" }
56
+ }
57
+ }
58
+ },
59
+ "plugins": {
60
+ "allow": [ "...existing entries...", "winch" ]
61
+ }
62
+ ```
63
+
64
+ Calls arrive as `mcp__winch__backlog_claim` etc.; the hook filters on the
65
+ `winch` substring and stamps meta from `ctx.sessionKey` → `ctx.sessionId` →
66
+ `ctx.runId` (mirroring the HookContext the host guarantees for bundled MCP
67
+ calls since v2026.5.16-beta.7; oldest compatible stable is v2026.5.18,
68
+ declared in `package.json` as `openclaw.install.minHostVersion`, enforced by
69
+ install and registry loading). No resolvable session or agent → the hook
70
+ returns `undefined`; the call reaches the server unstamped and is refused
71
+ (there is no env fallback).
72
+
73
+ ## Assignment dispatch (wake on routing)
74
+
75
+ An assigned task is inert until someone starts the assignee's session, and a
76
+ worker must never receive a hand-written brief: the record is the spec.
77
+
78
+ The winch server routes and the plugin receives. On boot the plugin registers
79
+ `POST /api/winch/dispatch` and reconciles once; every
80
+ `dispatchReconcileMs` (default 30s) it calls `POST /dispatch/recover` and
81
+ resumes assigned `in_progress` work. A wake carries the opaque item id, or a
82
+ `resume` wake carries the task id, `attemptId`, `leaseEpoch`, and owner; the
83
+ row's `kind` says whether to claim, break down, or review. The session is
84
+ started through the gateway's own CLI entry (`agent --session-key agent:<agent>:winch:<id>`),
85
+ because the host only lets bundled plugins schedule turns in-process.
86
+
87
+ Routing, one row per decision:
88
+
89
+ - `task.created` / `task.assigned` / `task.released` / `task.restored` / `gate.resolved` → the assignee (never the planner itself)
90
+ - `story.created` / `story.assigned` → the story owner, to append its tasks
91
+ - `task.appended` → the epic's creator, to route the new work
92
+ - a close (`done`/`cancelled`) → every assigned task the envelope reports as
93
+ `unblocked`, so dependents start without a scheduler
94
+ - `epic.completed` → the epic's creator, to review the delivery
95
+
96
+ Two more rows matter to the dispatcher:
97
+
98
+ - `story.assigned` — a story handed to one agent to break down. Wake that
99
+ agent with the story id; it reads the story and appends tasks, which then
100
+ arrive as `task.appended` rows for the planner to route.
101
+ - `task.appended` — work recorded after the plan (`backlog_append`) lands
102
+ unassigned. Wake the planner so it routes the task; a dispatcher can wait a
103
+ few seconds first and skip it if the appending turn already assigned.
104
+ - `story.completed` — written when a story's last task closes; usually just
105
+ bookkeeping for dashboards.
106
+ - `epic.completed` — one row per close cycle, written when the epic's last
107
+ story closes (each story closes when its last task does). Wake
108
+ `epics.created_by` with the epic id; the planner calls `backlog_get`,
109
+ reviews the delivered results and artifacts, and either appends follow-up
110
+ tasks (which reopens the epic) or reports it done. Act on each marker once,
111
+ not on every replay.
112
+
113
+ Dispatch is delivered by HTTP, not polled. `202` means the receiver accepted
114
+ the request. Each consumer gets its own delivery row and per-attempt audit row;
115
+ one consumer's failure does not suppress another's retry. The payload marks one
116
+ consumer `execution: "active"` and the rest `"standby"`; only the active
117
+ consumer starts a session. Standby receivers acknowledge and stop. If the
118
+ active route dies or its lease expires, the dispatcher promotes a standby and
119
+ bumps `leaseEpoch`.
120
+
121
+ Planner wakes (`story`, `append`, `review`) require `backlog_accept_wake` with
122
+ the payload's `admissionId`, `attemptNo`, and `leaseEpoch` before doing work.
123
+ Tasks use `backlog_claim`; the claim records `consumerId`, `ownerInstance`, and
124
+ `leaseEpoch`, and `backlog_update`/`backlog_done`/`backlog_block` reject a
125
+ missing or stale epoch. An unaccepted planner wake requeues at the offer TTL.
126
+
127
+ The admission queue holds an offer until it is claimed, closes, or expires;
128
+ failed deliveries and expired offers requeue with backoff. Story/append/review
129
+ wakes are one-shot only after `backlog_accept_wake`; an unaccepted offer
130
+ requeues. Tasks still use `backlog_claim` as the work-level guard; the accepted
131
+ execution lease is the guard for wakes with no claim.
132
+
133
+ ## Restart recovery
134
+
135
+ The core query is `POST /dispatch/recover`; it returns assigned `in_progress`
136
+ work with `attemptId`, `leaseEpoch`, `ownerInstance`, `sessionId`, `sessionKey`
137
+ 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.
140
+ The plugin dedupes by task id and resumes the same attempt. Its first action is
141
+ `backlog_update` with the returned `attemptId` and `leaseEpoch`; a stale attempt
142
+ or epoch gets `stale_claim`, and only an expired lease returns the item to
143
+ `ready` for a normal wake and claim.
144
+
145
+ ## opencode
146
+
147
+ opencode's `tool.execute.before` hook can mutate the outgoing call's `args`
148
+ but cannot reach request `_meta` (its MCP path sends only name + arguments).
149
+ winch therefore declares `winch_agent` / `winch_session` as optional schema
150
+ slots (`src/mcp.js`) and reads them as a whole pair (`src/identity.js`); the
151
+ companion stamps them unconditionally, so a model-supplied pair never
152
+ survives.
153
+
154
+ `@igorjpimenta/winch-opencode` is that companion, and it is dual-entry: V1
155
+ opencode calls `server()` (object hooks), V2 calls `setup()` — which learns
156
+ the session's agent from `ctx.session.hook("context")` and stamps in
157
+ `ctx.tool.hook("execute.before")`. No SDK dependency: a plain
158
+ `{ id, setup, server }` export satisfies both loaders.
159
+
160
+ ### Auto-wake dispatch (opencode)
161
+
162
+ The opencode companion ships its own dispatch receiver
163
+ (`plugins/opencode/winch/dispatch.js`). It opens a loopback listener, registers
164
+ with `WINCH_CONSUMER_ID` (default `harness:hostname`),
165
+ `WINCH_EXECUTOR_ID` as the instance id, and `WINCH_WEBHOOK_BEARER`, and calls
166
+ `POST /dispatch/recover` on startup and on its reconcile interval. The wake
167
+ payload's `kind` selects the listener action; many consumers may share one
168
+ harness, each with its own route. The first registration sends `fresh: true`;
169
+ later heartbeats send `fresh: false` and preserve failure/disabled state. A
170
+ second live instance for the same consumer gets `409` until the current lease
171
+ expires. Set `WINCH_DISPATCH_TOKEN` to authenticate management calls. Missing
172
+ identity or bearer disables the receiver.
173
+
174
+ A wake carries the opaque item id; the plugin starts a claimable `opencode run`
175
+ session after local dedupe by `admissionId + attemptNo`, and only when
176
+ `execution` is `"active"`. Resume wakes carry the task id, `attemptId`,
177
+ `leaseEpoch`, and owner, so the prompt fences the session with
178
+ `backlog_update` and `backlog_done` and never re-claims an `in_progress` item.
179
+ `202` is delivery; the task claim or planner acceptance picks the winner.
180
+
181
+ The plugin config mirrors OpenClaw: `dispatchEnabled`, `winchHarness`,
182
+ `winchConsumerId`, `winchExecutorId`, `dispatchReconcileMs`, and a port for the
183
+ loopback listener.
184
+ `dispatchUrl` and the state path are gone; use `WINCH_DISPATCH_URL` and
185
+ `WINCH_WEBHOOK_BEARER` instead. OpenCode V1 reads only the environment; V2
186
+ reads `ctx.options` first.
187
+
188
+ ### Local (stdio) — the strong shape
189
+
190
+ ```jsonc
191
+ {
192
+ "mcp": {
193
+ "winch": {
194
+ "type": "local",
195
+ "command": ["winch", "serve", "--mcp", "stdio"],
196
+ "environment": { "WINCH_HARNESS": "opencode" }
197
+ }
198
+ },
199
+ "plugin": ["@igorjpimenta/winch-opencode"]
200
+ }
201
+ ```
202
+
203
+ Stdio keeps the channel sound by construction: the spawner is the sole peer,
204
+ so nobody but the adapter can write the identity args.
205
+
206
+ ### Remote (HTTP) — loopback with a bearer
207
+
208
+ A persistent server (`winch serve --mcp http --port 38292`) avoids per-call
209
+ spawns. Read the bearer from a `0600` file, not from the environment:
210
+
211
+ ```jsonc
212
+ {
213
+ "mcp": {
214
+ "winch": {
215
+ "type": "remote",
216
+ "url": "http://127.0.0.1:38292/mcp",
217
+ "headers": {
218
+ "Authorization": "Bearer {file:~/.secrets/winch-bearer}",
219
+ "X-Winch-Harness": "opencode"
220
+ },
221
+ "enabled": true
222
+ }
223
+ }
224
+ }
225
+ ```
226
+
227
+ - `{env:NAME}` resolves from the process environment only, an unset variable
228
+ becomes an **empty string**, and opencode does not load `.env` — so an
229
+ `{env:…}` header that nobody exported makes every run hang on MCP connect
230
+ with no error. `{file:…}` has no such failure mode; write the value with
231
+ no trailing newline and `chmod 600`.
232
+ - Trust note: over HTTP, anyone holding the bearer can call the server and
233
+ stamp any identity the schema accepts. Keep the listener on loopback and
234
+ treat the bearer as the trust boundary; use stdio where that matters.
235
+
236
+ ### v2
237
+
238
+ Pin `"codemode": false` on the server entry when you want winch tools on the
239
+ model's native tool list (the shape the adapter's hooks are verified against).
240
+ On v2, hot config reload reconciles MCP at the next step boundary, so adding
241
+ this entry does not require restarting a running session.
242
+
243
+ The hook learns the agent from `chat.message` / `chat.params` (V1) or the
244
+ `context` hook (V2) per session, and falls back to `WINCH_AGENT`. Agent and
245
+ session are stamped on every winch call, so claims are attributed to the real
246
+ caller instead of being refused.
247
+
248
+ ## Remote servers: URL + credentials
249
+
250
+ Winch itself authenticates nothing on stdio — it trusts the OS user, and that
251
+ is the whole auth model in-process. A hosted winch (`winch serve --mcp http`,
252
+ or any stdio→network bridge you run in front of a stdio server) authenticates
253
+ at the transport: reverse proxy, tailnet identity, or the bearer check in
254
+ front of (or built into) the HTTP daemon. Keep credentials and
255
+ identity apart in your head: a token proves *which deployment* may call; the
256
+ declared harness/agent/session says *whose work* this is. Keep credentials and
257
+ identity apart in your head: a token proves *which deployment* may call; the
258
+ declared harness/agent/session says *whose work* this is.
259
+
260
+ | client | local (stdio) | remote (URL) | credentials live in |
261
+ | --- | --- | --- | --- |
262
+ | openclaw | `mcp.servers.winch = {command, args, env}` | same object plus `url`, `transport: "sse" \| "streamable-http"`, `headers` | the `headers` map, e.g. `Authorization` |
263
+ | opencode | `"type": "local", command, environment` | `"type": "remote", url, headers` | the `headers` map |
264
+ | langgraph | stdio entry in `mcpServers` | SSE/HTTP transport entry per its adapter | the adapter's header/auth config |
265
+ | claude | `claude mcp add winch --env WINCH_HARNESS=generic -- winch serve --mcp stdio` | `claude mcp add --transport http <name> <url> -H "Authorization: Bearer …"` | the `-H` flags, stored in its config |
266
+
267
+ ## generic MCP clients
268
+
269
+
270
+ ```
271
+ claude mcp add winch --env WINCH_HARNESS=generic -- winch serve --mcp stdio
272
+ ```
273
+
274
+ No plugin: declare the harness in the environment and stamp agent/session
275
+ per call yourself, or the server refuses:
276
+
277
+ ```
278
+ WINCH_HARNESS=generic winch serve --mcp stdio
279
+ ```
280
+
281
+ ### langgraph
282
+
283
+ A LangGraph deployment is one more declared consumer; declare the graph's
284
+ identity as the floor the server keys everything to:
285
+
286
+ A LangGraph deployment declares the one thing it can — its own harness —
287
+ and stamps agent/session per call from its own wiring (thread id and node
288
+ name make natural values):
289
+
290
+ ```json
291
+ {
292
+ "mcpServers": {
293
+ "winch": {
294
+ "command": "winch",
295
+ "args": ["serve", "--mcp", "stdio"],
296
+ "env": { "WINCH_HARNESS": "langgraph" }
297
+ }
298
+ }
299
+ }
300
+ ```
301
+
302
+ Env works identically (`WINCH_HARNESS=langgraph`). Without per-call stamps
303
+ the calls fail loudly — which is the correct signal that the graph side of
304
+ the identity contract is not wired yet.
@@ -0,0 +1,71 @@
1
+ # @igorjpimenta/winch-openclaw
2
+
3
+ OpenClaw companion for [winch](https://github.com/igorjpimenta/winch). Three 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
+
20
+ ## Install
21
+
22
+ ```sh
23
+ openclaw plugins install @igorjpimenta/winch-openclaw --accept-capabilities
24
+ ```
25
+
26
+ The manifest declares `activation.onStartup`, so the plugin loads at gateway
27
+ boot (without it the host never calls `register()` and the route never
28
+ binds). The `--accept-capabilities` flag is required: the plugin registers
29
+ an HTTP route and a service.
30
+
31
+ The plugin depends on `@igorjpimenta/winch`, so npm resolves and pins the
32
+ server version alongside it.
33
+
34
+ Set `dispatchPublicBaseUrl` if the gateway port isn't detectable. Generate the
35
+ bearer with `winch webhook bearer`, then set `WINCH_WEBHOOK_BEARER` and a unique
36
+ `WINCH_EXECUTOR_ID` in the gateway/plugin environment. `WINCH_CONSUMER_ID`
37
+ defaults to `harness:hostname`, so the gateway keeps one route across restarts.
38
+ The receiver stays disarmed and logs a warning if the executor or bearer is
39
+ missing.
40
+
41
+ ## Releases
42
+
43
+ Ships on its own line, independent of the core server:
44
+ `winch-openclaw-<semver>` tags publish `@igorjpimenta/winch-openclaw`
45
+ (stable → `latest`, prerelease → `beta`). Bump this package's `version` and
46
+ its `@igorjpimenta/winch` dependency floor together.
47
+
48
+ ## Config
49
+
50
+ | key | default | meaning |
51
+ |---|---|---|
52
+ | `dispatchEnabled` | `true` | receive wakes and reconcile assigned `in_progress` work |
53
+ | `dispatchPublicBaseUrl` | `http://127.0.0.1:<gateway.port>` | gateway address winch can reach |
54
+ | `winchHarness` | `WINCH_HARNESS` or `openclaw` | harness name for identity and dispatch |
55
+ | `winchExecutorId` | `WINCH_EXECUTOR_ID` | unique instance id for this connection; also the registration lease owner |
56
+ | `winchConsumerId` | `WINCH_CONSUMER_ID` or `harness:hostname` | stable webhook identity |
57
+ | `dispatchReconcileMs` | `30000` | recovery interval |
58
+ | `dispatchOpenclawBin` | shim beside the gateway entry | CLI used to start a wake session |
59
+
60
+ Environment:
61
+
62
+ | variable | meaning |
63
+ |---|---|
64
+ | `WINCH_EXECUTOR_ID` | unique instance id; required unless `winchExecutorId` is set |
65
+ | `WINCH_CONSUMER_ID` | stable webhook identity; default `harness:hostname` |
66
+ | `WINCH_WEBHOOK_BEARER` | receiver token; generate with `winch webhook bearer` |
67
+ | `WINCH_DISPATCH_URL` | winch base URL, default `http://127.0.0.1:38293` |
68
+ | `WINCH_DISPATCH_PUBLIC_BASE_URL` | fallback for `dispatchPublicBaseUrl` |
69
+ | `WINCH_DISPATCH_TOKEN` | management bearer for register/recover/notify; required for a non-loopback winch bind |
70
+
71
+ Requires OpenClaw ≥ 2026.5.18 (declared as `openclaw.install.minHostVersion`).
@@ -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
+ }