@igorjpimenta/winch 0.0.0-stage → 2026.11.22-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.
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 +104 -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,139 @@
1
+ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
2
+ import { buildWinchMeta } from "./meta.js";
3
+ import { startDispatch } from "./dispatch.js";
4
+ import { spawn } from "node:child_process";
5
+ import { existsSync } from "node:fs";
6
+ import { hostname } from "node:os";
7
+ import path from "node:path";
8
+
9
+ // Mechanics: before_tool_call runs before MCP dispatch, and this hook returns
10
+ // a full replacement of event.params with _meta.winch set unconditionally on
11
+ // every winch tool call. A call without a resolvable session/agent returns
12
+ // undefined and is refused by the server; the model cannot supply identity.
13
+ export default definePluginEntry({
14
+ id: "winch",
15
+ name: "Winch",
16
+ description: "Stamps _meta.winch onto winch MCP tool calls, accepts HTTP wake webhooks, and reconciles assigned in-progress work after a gateway restart.",
17
+ configSchema: () => ({
18
+ type: "object",
19
+ additionalProperties: true,
20
+ properties: {
21
+ dispatchEnabled: {
22
+ type: "boolean",
23
+ description: "Accept wake webhooks and reconcile assigned in-progress work. Default true.",
24
+ },
25
+ dispatchPublicBaseUrl: {
26
+ type: "string",
27
+ description: "Gateway address winch can reach, e.g. http://127.0.0.1:18789. Used to register the wake route.",
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
+ dispatchReconcileMs: {
42
+ type: "integer",
43
+ description: "Reconcile interval in milliseconds. Default: 30000.",
44
+ },
45
+ dispatchOpenclawBin: {
46
+ type: "string",
47
+ description: "OpenClaw CLI entry used to start a wake session (default: the shim beside the gateway entry).",
48
+ },
49
+ },
50
+ }),
51
+ register: (api) => {
52
+ const cfg = api.pluginConfig ?? {};
53
+ const harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "openclaw";
54
+ const consumerId = cfg.winchConsumerId ?? process.env.WINCH_CONSUMER_ID ?? `${harness}:${hostname()}`;
55
+ const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID ?? null;
56
+ if (typeof api.on === "function") {
57
+ api.on("before_tool_call", (event, ctx) => buildWinchMeta(event, ctx, harness, consumerId, executorId));
58
+ } else {
59
+ api.logger.warn("winch: api.on unavailable; identity hook not registered");
60
+ }
61
+
62
+ let dispatch = null;
63
+ if (typeof api.registerService === "function") {
64
+ api.registerService({
65
+ id: "winch-dispatch",
66
+ start: async () => {
67
+ if (cfg.dispatchEnabled === false) {
68
+ api.logger.info("winch: dispatch disabled by config");
69
+ return;
70
+ }
71
+ // scheduleSessionTurn only commits for bundled plugins; an npm
72
+ // adapter wakes by starting a one-shot agent session through the CLI.
73
+ // The gateway's own argv[1] is the internal dist entry, which has no
74
+ // `agent` subcommand, so resolve the package's CLI shim beside it.
75
+ const candidates = [
76
+ cfg.dispatchOpenclawBin,
77
+ path.resolve(path.dirname(process.argv[1] ?? ""), "..", "openclaw.mjs"),
78
+ "/opt/homebrew/bin/openclaw",
79
+ ].filter(Boolean);
80
+ const entry = candidates.find((c) => { try { return existsSync(c); } catch { return false; } }) ?? candidates[0];
81
+ const wake = ({ agent, message, sessionKey }) => {
82
+ const tryOnce = () =>
83
+ new Promise((resolve, reject) => {
84
+ const args = [
85
+ entry,
86
+ "agent",
87
+ "--agent", agent,
88
+ "--session-key", `agent:${agent}:winch:${sessionKey ?? message}`,
89
+ "--message", message,
90
+ ];
91
+ // The gateway marks its own env; a child that inherits the
92
+ // service markers exits before doing any work.
93
+ const env = { ...process.env };
94
+ for (const key of [
95
+ "OPENCLAW_LAUNCHD_LABEL",
96
+ "OPENCLAW_SERVICE_KIND",
97
+ "OPENCLAW_SERVICE_MARKER",
98
+ "OPENCLAW_SERVICE_MANAGED_ENV_KEYS",
99
+ "OPENCLAW_SYSTEMD_UNIT",
100
+ "OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER",
101
+ "OPENCLAW_WINDOWS_TASK_NAME",
102
+ ]) delete env[key];
103
+ const child = spawn(process.execPath, args, {
104
+ detached: true,
105
+ stdio: ["ignore", "ignore", "pipe"],
106
+ env,
107
+ });
108
+ let stderr = "";
109
+ child.stderr?.on("data", (d) => { stderr = (stderr + d.toString()).slice(-2000); });
110
+ child.on("error", reject);
111
+ child.on("exit", (code) =>
112
+ code === 0 ? resolve() : reject(new Error(`exit ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`))
113
+ );
114
+ child.unref();
115
+ });
116
+ return (async () => {
117
+ let last;
118
+ for (let attempt = 0; attempt < 3; attempt++) {
119
+ try {
120
+ return await tryOnce();
121
+ } catch (e) {
122
+ last = e;
123
+ await new Promise((r) => setTimeout(r, 5000));
124
+ }
125
+ }
126
+ throw last;
127
+ })();
128
+ };
129
+ dispatch = startDispatch({ api, cfg, harness, wake, logger: api.logger });
130
+ },
131
+ stop: async () => {
132
+ dispatch?.close();
133
+ dispatch = null;
134
+ },
135
+ });
136
+ }
137
+ api.logger.info("winch: registered (identity stamp + HTTP dispatch receiver)");
138
+ },
139
+ });
@@ -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
+ }
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@igorjpimenta/winch-openclaw",
3
+ "version": "2026.11.19-beta.1",
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
+ ],
23
+ "openclaw": {
24
+ "extensions": [
25
+ "./index.js"
26
+ ],
27
+ "install": {
28
+ "minHostVersion": ">=2026.5.18"
29
+ }
30
+ },
31
+ "dependencies": {
32
+ "@igorjpimenta/winch": "^2026.11.19-beta.1"
33
+ },
34
+ "peerDependencies": {
35
+ "openclaw": ">=2026.5.18"
36
+ }
37
+ }
@@ -0,0 +1,228 @@
1
+ // dispatch.js — local HTTP receiver plus recovery reconciliation for OpenCode.
2
+ //
3
+ // Winch POSTs a wake to this plugin's loopback listener and gets 202. The
4
+ // listener only starts a turn; the MCP claim is the work guard, so duplicate
5
+ // delivery is harmless. The reconciler handles restarts.
6
+
7
+ import http from "node:http";
8
+
9
+ export const DEFAULT_DISPATCH_URL = "http://127.0.0.1:38293";
10
+ const MAX_BODY_BYTES = 1024 * 1024;
11
+ const INFLIGHT_TTL_MS = 35 * 60 * 1000;
12
+
13
+ function readJson(req, res) {
14
+ return (async () => {
15
+ let size = 0;
16
+ let raw = "";
17
+ for await (const chunk of req) {
18
+ size += chunk.length;
19
+ if (size > MAX_BODY_BYTES) {
20
+ res.statusCode = 413;
21
+ res.end(JSON.stringify({ error: "body too large" }));
22
+ return undefined;
23
+ }
24
+ raw += chunk;
25
+ }
26
+ if (!raw) return {};
27
+ try {
28
+ return JSON.parse(raw);
29
+ } catch {
30
+ res.statusCode = 400;
31
+ res.end(JSON.stringify({ error: "invalid json body" }));
32
+ return undefined;
33
+ }
34
+ })();
35
+ }
36
+
37
+ function json(res, status, body) {
38
+ res.statusCode = status;
39
+ res.setHeader("content-type", "application/json");
40
+ res.end(JSON.stringify(body));
41
+ }
42
+
43
+ function dispatchAuthHeaders() {
44
+ const headers = { "content-type": "application/json" };
45
+ const token = String(process.env.WINCH_DISPATCH_TOKEN ?? "").trim();
46
+ if (token) headers.authorization = `Bearer ${token}`;
47
+ return headers;
48
+ }
49
+
50
+ function wakeMessage({ itemId, kind, admissionId, attemptNo, leaseEpoch }) {
51
+ if (kind === "story" || kind === "append" || kind === "review") {
52
+ return `Call backlog_accept_wake with admissionId "${admissionId}", attemptNo ${attemptNo}, and leaseEpoch ${leaseEpoch ?? 0} before working on ${itemId}.`;
53
+ }
54
+ return itemId;
55
+ }
56
+
57
+ export async function registerExecutor({ baseUrl, harness, consumerId, executorId, url, bearer, fresh = false, timeoutMs = 5000 }) {
58
+ const res = await fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/register`, {
59
+ method: "POST",
60
+ headers: dispatchAuthHeaders(),
61
+ body: JSON.stringify({ harness, consumerId, executorId, instanceId: executorId, url, bearer, fresh }),
62
+ signal: AbortSignal.timeout(timeoutMs),
63
+ });
64
+ if (!res.ok) throw new Error(`dispatch register ${res.status}`);
65
+ return res.json();
66
+ }
67
+
68
+ export async function recoverOnce({ baseUrl, harness, consumerId, executorId, wake, started, logger = console, timeoutMs = 5000 }) {
69
+ const res = await fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/recover`, {
70
+ method: "POST",
71
+ headers: dispatchAuthHeaders(),
72
+ body: JSON.stringify({ harness, consumerId, executorId }),
73
+ signal: AbortSignal.timeout(timeoutMs),
74
+ });
75
+ if (!res.ok) throw new Error(`dispatch recover ${res.status}`);
76
+ const body = await res.json();
77
+ const now = Date.now();
78
+ for (const [key, at] of started) if (now - at > INFLIGHT_TTL_MS) started.delete(key);
79
+
80
+ for (const row of body?.resume ?? []) {
81
+ if (!row?.task?.id) continue;
82
+ const key = `resume:${row.task.id}:${row.attemptId ?? "none"}`;
83
+ if (started.has(key)) continue;
84
+ started.set(key, now);
85
+ Promise.resolve(wake({
86
+ agent: row.task.assignee_agent,
87
+ message: resumePrompt(row),
88
+ sessionKey: row.task.id,
89
+ kind: "resume",
90
+ attemptId: row.attemptId,
91
+ })).catch((err) => {
92
+ started.delete(key);
93
+ logger?.warn?.(`winch: resume ${row.task.id} failed: ${err?.message ?? err}`);
94
+ });
95
+ }
96
+
97
+ for (const row of body?.start ?? []) {
98
+ if (!row?.admissionId || !row?.itemId) continue;
99
+ const key = `start:${row.admissionId}:${row.attemptNo ?? "none"}`;
100
+ if (started.has(key)) continue;
101
+ started.set(key, now);
102
+ Promise.resolve(wake({
103
+ agent: row.agent,
104
+ message: wakeMessage(row),
105
+ kind: row.kind,
106
+ admissionId: row.admissionId,
107
+ attemptNo: row.attemptNo,
108
+ leaseEpoch: row.leaseEpoch ?? 0,
109
+ })).catch((err) => {
110
+ started.delete(key);
111
+ logger?.warn?.(`winch: wake ${row.itemId} failed: ${err?.message ?? err}`);
112
+ });
113
+ }
114
+ return body;
115
+ }
116
+
117
+ export function resumePrompt(row) {
118
+ const taskId = row?.task?.id ?? "(unknown)";
119
+ const attemptId = row?.attemptId ?? null;
120
+ const leaseEpoch = row?.leaseEpoch ?? 0;
121
+ if (!attemptId) {
122
+ 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.`;
123
+ }
124
+ 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.`;
125
+ }
126
+
127
+ export function startDispatch({ baseUrl = DEFAULT_DISPATCH_URL, harness, consumerId = null, executorId, bearer, wake, logger = console, host = "127.0.0.1", port = 0, reconcileMs = 30000 } = {}) {
128
+ if (!executorId || !bearer) throw new Error("dispatch needs an executor id and bearer");
129
+ const subscriptionId = consumerId || executorId;
130
+ const started = new Map();
131
+ let closed = false;
132
+ let timer = null;
133
+ let listener = null;
134
+
135
+ const server = http.createServer(async (req, res) => {
136
+ if (req.method !== "POST" || req.url !== "/wake") {
137
+ json(res, 404, { error: "not found" });
138
+ return;
139
+ }
140
+ const auth = req.headers?.authorization ?? "";
141
+ if (!auth.startsWith("Bearer ") || auth.slice(7) !== bearer) {
142
+ json(res, 401, { error: "unauthorized" });
143
+ return;
144
+ }
145
+ const body = await readJson(req, res);
146
+ if (body === undefined) return;
147
+ if (body?.type === "ping") {
148
+ json(res, 200, { ok: true, test: true });
149
+ return;
150
+ }
151
+ if (body?.type !== "wake" || !body.admissionId || !body.itemId || !body.agent) {
152
+ json(res, 400, { error: "wake payload requires admissionId, itemId, agent" });
153
+ return;
154
+ }
155
+ if (body.execution === "standby") {
156
+ json(res, 202, { ok: true, admissionId: body.admissionId, standby: true });
157
+ return;
158
+ }
159
+ const key = `start:${body.admissionId}:${body.attemptNo ?? "none"}`;
160
+ if (started.has(key)) {
161
+ json(res, 202, { ok: true, admissionId: body.admissionId, duplicate: true });
162
+ return;
163
+ }
164
+ started.set(key, Date.now());
165
+ Promise.resolve(wake({
166
+ agent: body.agent,
167
+ message: wakeMessage(body),
168
+ kind: body.kind,
169
+ admissionId: body.admissionId,
170
+ attemptNo: body.attemptNo,
171
+ leaseEpoch: body.leaseEpoch ?? 0,
172
+ })).catch((err) => {
173
+ started.delete(key);
174
+ logger?.warn?.(`winch: wake ${body.itemId} failed: ${err?.message ?? err}`);
175
+ });
176
+ json(res, 202, { ok: true, admissionId: body.admissionId });
177
+ });
178
+
179
+ let fresh = true;
180
+ const run = async () => {
181
+ if (closed) return;
182
+ try {
183
+ await registerExecutor({
184
+ baseUrl,
185
+ harness,
186
+ consumerId: subscriptionId,
187
+ executorId,
188
+ url: `http://${host}:${listener.address().port}/wake`,
189
+ bearer,
190
+ fresh,
191
+ });
192
+ fresh = false;
193
+ } catch (err) {
194
+ logger?.warn?.(`winch: dispatch register failed: ${err?.message ?? err}`);
195
+ return;
196
+ }
197
+ try {
198
+ await recoverOnce({ baseUrl, harness, consumerId: subscriptionId, executorId, wake, started, logger });
199
+ } catch (err) {
200
+ logger?.warn?.(`winch: dispatch recover failed: ${err?.message ?? err}`);
201
+ }
202
+ };
203
+
204
+ const ready = new Promise((resolve, reject) => {
205
+ server.once("error", reject);
206
+ server.listen(port, host, () => {
207
+ listener = server;
208
+ void run();
209
+ if (Number(reconcileMs) > 0) {
210
+ timer = setInterval(() => { void run(); }, Number(reconcileMs));
211
+ timer.unref?.();
212
+ }
213
+ resolve({ port: listener.address().port, executorId, consumerId: subscriptionId });
214
+ });
215
+ });
216
+
217
+ return {
218
+ ready,
219
+ get executorId() { return executorId; },
220
+ get consumerId() { return subscriptionId; },
221
+ get port() { return listener?.address()?.port ?? null; },
222
+ close() {
223
+ closed = true;
224
+ if (timer) clearInterval(timer);
225
+ return new Promise((resolve) => server.close(() => resolve()));
226
+ },
227
+ };
228
+ }
@@ -0,0 +1,22 @@
1
+ import { stampWinchIdentity } from "./identity.js";
2
+
3
+ // The agent is not on the tool call, only the session: remember it from the
4
+ // chat events that carry both, then stamp the pair on every winch call.
5
+ export function createWinchHooks({ consumerId = null, instanceId = null } = {}) {
6
+ const agents = new Map();
7
+
8
+ return {
9
+ "chat.message": async (input) => {
10
+ if (input?.sessionID && input?.agent) agents.set(input.sessionID, input.agent);
11
+ },
12
+ "chat.params": async (input) => {
13
+ if (input?.sessionID && input?.agent) agents.set(input.sessionID, input.agent);
14
+ },
15
+ "tool.execute.before": async (input, output) => {
16
+ // Unconditional: when the agent is unknown the slot is blanked, so a
17
+ // model-supplied pair can never ride through as identity. Blank means
18
+ // 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 });
20
+ },
21
+ };
22
+ }
@@ -0,0 +1,34 @@
1
+ // identity.js — opencode can mutate tool args but not request _meta, so the
2
+ // winch server accepts a whole agent+session pair as winch_agent/winch_session
3
+ // args (src/identity.js, args channel). The hook overwrites them
4
+ // unconditionally: a model-supplied pair must never survive.
5
+
6
+ export function isWinchTool(name) {
7
+ return typeof name === "string" && name.includes("winch");
8
+ }
9
+
10
+ export function stampWinchIdentity(input, output, { agent = null, consumerId = null, instanceId = null } = {}) {
11
+ if (!isWinchTool(input?.tool)) return false;
12
+ output.args = output.args ?? {};
13
+ // Overwrite, never merge: an unknown agent blanks the slot (unstamped),
14
+ // which the server refuses — that is the fail-closed side of the rule that
15
+ // model-supplied identity never survives.
16
+ output.args.winch_agent = agent ?? "";
17
+ output.args.winch_session = input?.sessionID ?? "";
18
+ output.args.winch_consumer = consumerId ?? "";
19
+ output.args.winch_instance = instanceId ?? "";
20
+ return true;
21
+ }
22
+
23
+ // V2: the tool hook hands one mutable event instead of (input, output). Same
24
+ // rule — the pair is stamped unconditionally.
25
+ export function stampWinchEvent(event, agent, consumerId = null, instanceId = null) {
26
+ if (!isWinchTool(event?.tool)) return false;
27
+ const input = event.input && typeof event.input === "object" ? event.input : {};
28
+ event.input = input;
29
+ input.winch_agent = agent ?? "";
30
+ input.winch_session = event.sessionID ?? "";
31
+ input.winch_consumer = consumerId ?? "";
32
+ input.winch_instance = instanceId ?? "";
33
+ return true;
34
+ }
@@ -0,0 +1,104 @@
1
+ import { createWinchHooks } from "./hooks.js";
2
+ import { stampWinchEvent } from "./identity.js";
3
+ import { startDispatch, DEFAULT_DISPATCH_URL } from "./dispatch.js";
4
+ import { spawn } from "node:child_process";
5
+ import { hostname } from "node:os";
6
+
7
+ function opencodeWake({ agent, message }) {
8
+ return new Promise((resolve, reject) => {
9
+ const bin = process.env.OPENCODE_BIN || "opencode";
10
+ const child = spawn(bin, ["run", "--agent", agent, message], {
11
+ detached: true,
12
+ stdio: ["ignore", "ignore", "pipe"],
13
+ });
14
+ let stderr = "";
15
+ child.stderr?.on("data", (d) => { stderr = (stderr + d.toString()).slice(-2000); });
16
+ child.on("error", reject);
17
+ child.on("exit", (code) =>
18
+ code === 0 ? resolve() : reject(new Error(`exit ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`))
19
+ );
20
+ child.unref();
21
+ });
22
+ }
23
+
24
+ function consumerIdFor(harness, cfg = {}) {
25
+ return cfg.winchConsumerId ?? process.env.WINCH_CONSUMER_ID ?? `${harness}:${hostname()}`;
26
+ }
27
+
28
+ function start({ cfg = {}, harness, logger }) {
29
+ const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
30
+ const consumerId = consumerIdFor(harness, cfg);
31
+ const bearer = process.env.WINCH_WEBHOOK_BEARER;
32
+ if (!executorId || !bearer) {
33
+ logger?.warn?.("winch: dispatch needs WINCH_EXECUTOR_ID and WINCH_WEBHOOK_BEARER; receiver disabled");
34
+ return null;
35
+ }
36
+ const dispatch = startDispatch({
37
+ baseUrl: process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL,
38
+ harness,
39
+ consumerId,
40
+ executorId,
41
+ bearer,
42
+ wake: opencodeWake,
43
+ port: Number(cfg.dispatchPort ?? process.env.WINCH_DISPATCH_PORT ?? 0),
44
+ reconcileMs: Number(cfg.dispatchReconcileMs ?? process.env.WINCH_DISPATCH_RECONCILE_MS ?? 30000),
45
+ logger,
46
+ });
47
+ dispatch.ready.catch((err) => logger?.warn?.(`winch: dispatch listener failed: ${err?.message ?? err}`));
48
+ return dispatch;
49
+ }
50
+
51
+ // One package, two hosts: V1 calls server() and gets the object hooks; V2
52
+ // reads id/setup() and gets the domain hooks. Both stamp the same identity pair.
53
+ export default {
54
+ id: "winch-opencode",
55
+ async setup(ctx) {
56
+ // SessionContext (the "context" hook event) carries both sessionID and
57
+ // the session's agent; session.get() in this beta returns a projection
58
+ // without agent, so the request hook is the reliable source.
59
+ const cfg = ctx.options ?? {};
60
+ const harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "opencode";
61
+ const consumerId = consumerIdFor(harness, cfg);
62
+ const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID ?? null;
63
+ const agents = new Map();
64
+ let dispatch = null;
65
+ const ensureDispatch = () => {
66
+ if (dispatch) return;
67
+ if (cfg.dispatchEnabled === false || process.env.WINCH_DISPATCH_ENABLED === "0") return;
68
+ dispatch = start({ cfg, harness, logger: console });
69
+ };
70
+ await ctx.session.hook("context", (event) => {
71
+ if (event?.sessionID && event.agent) agents.set(event.sessionID, event.agent);
72
+ ensureDispatch();
73
+ });
74
+ await ctx.tool.hook("execute.before", (event) => {
75
+ const agent = agents.get(event.sessionID) ?? process.env.WINCH_AGENT ?? null;
76
+ // Unconditional: unknown agent blanks the slot, the server refuses
77
+ // rather than trusting whatever the model wrote there.
78
+ stampWinchEvent(event, agent, consumerId, executorId);
79
+ });
80
+ },
81
+ async server() {
82
+ const harness = process.env.WINCH_HARNESS ?? "opencode";
83
+ const consumerId = consumerIdFor(harness);
84
+ const executorId = process.env.WINCH_EXECUTOR_ID ?? null;
85
+ const hooks = createWinchHooks({ consumerId, instanceId: executorId });
86
+ let dispatch = null;
87
+ const ensureDispatch = () => {
88
+ if (dispatch) return;
89
+ if (process.env.WINCH_DISPATCH_ENABLED === "0") return;
90
+ dispatch = start({ cfg: {}, harness, logger: console });
91
+ };
92
+ const origMessage = hooks["chat.message"];
93
+ hooks["chat.message"] = async (input) => {
94
+ if (typeof origMessage === "function") await origMessage(input);
95
+ ensureDispatch();
96
+ };
97
+ const origParams = hooks["chat.params"];
98
+ hooks["chat.params"] = async (input) => {
99
+ if (typeof origParams === "function") await origParams(input);
100
+ ensureDispatch();
101
+ };
102
+ return hooks;
103
+ },
104
+ };
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@igorjpimenta/winch-opencode",
3
+ "version": "2026.11.19-beta.1",
4
+ "description": "OpenCode companion for winch: stamps agent and session identity on winch tool calls, receives HTTP dispatch wakes, and reconciles assigned in-progress work. No SDK dependency — a plain id/setup/server export.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/igorjpimenta/winch.git",
10
+ "directory": "plugins/opencode/winch"
11
+ },
12
+ "publishConfig": {
13
+ "registry": "https://registry.npmjs.org",
14
+ "access": "public"
15
+ },
16
+ "exports": {
17
+ ".": "./index.js"
18
+ },
19
+ "files": [
20
+ "index.js",
21
+ "hooks.js",
22
+ "identity.js",
23
+ "dispatch.js"
24
+ ],
25
+ "main": "index.js"
26
+ }