@igorjpimenta/winch-opencode 2026.11.9-beta.1 → 2026.11.18-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dispatch.js +186 -0
  2. package/index.js +73 -8
  3. package/package.json +4 -3
package/dispatch.js ADDED
@@ -0,0 +1,186 @@
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
+ export async function registerExecutor({ baseUrl, harness, executorId, url, bearer, timeoutMs = 5000 }) {
44
+ const res = await fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/register`, {
45
+ method: "POST",
46
+ headers: { "content-type": "application/json" },
47
+ body: JSON.stringify({ harness, executorId, url, bearer }),
48
+ signal: AbortSignal.timeout(timeoutMs),
49
+ });
50
+ if (!res.ok) throw new Error(`dispatch register ${res.status}`);
51
+ return res.json();
52
+ }
53
+
54
+ export async function recoverOnce({ baseUrl, harness, executorId, wake, started, logger = console, timeoutMs = 5000 }) {
55
+ const res = await fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/recover`, {
56
+ method: "POST",
57
+ headers: { "content-type": "application/json" },
58
+ body: JSON.stringify({ harness, executorId }),
59
+ signal: AbortSignal.timeout(timeoutMs),
60
+ });
61
+ if (!res.ok) throw new Error(`dispatch recover ${res.status}`);
62
+ const body = await res.json();
63
+ const now = Date.now();
64
+ for (const [key, at] of started) if (now - at > INFLIGHT_TTL_MS) started.delete(key);
65
+
66
+ for (const row of body?.resume ?? []) {
67
+ if (!row?.task?.id) continue;
68
+ const key = `resume:${row.task.id}:${row.attemptId ?? "none"}`;
69
+ if (started.has(key)) continue;
70
+ started.set(key, now);
71
+ Promise.resolve(wake({
72
+ agent: row.task.assignee_agent,
73
+ message: resumePrompt(row),
74
+ sessionKey: row.task.id,
75
+ kind: "resume",
76
+ attemptId: row.attemptId,
77
+ })).catch((err) => {
78
+ started.delete(key);
79
+ logger?.warn?.(`winch: resume ${row.task.id} failed: ${err?.message ?? err}`);
80
+ });
81
+ }
82
+
83
+ for (const row of body?.start ?? []) {
84
+ if (!row?.admissionId || !row?.itemId) continue;
85
+ const key = `start:${row.admissionId}`;
86
+ if (started.has(key)) continue;
87
+ started.set(key, now);
88
+ Promise.resolve(wake({
89
+ agent: row.agent,
90
+ message: row.itemId,
91
+ kind: row.kind,
92
+ admissionId: row.admissionId,
93
+ })).catch((err) => {
94
+ started.delete(key);
95
+ logger?.warn?.(`winch: wake ${row.itemId} failed: ${err?.message ?? err}`);
96
+ });
97
+ }
98
+ return body;
99
+ }
100
+
101
+ export function resumePrompt(row) {
102
+ const taskId = row?.task?.id ?? "(unknown)";
103
+ const attemptId = row?.attemptId ?? "(unknown)";
104
+ return `Resume ${taskId} attempt ${attemptId}. You already own this task. Do not call backlog_claim. Call backlog_update with taskId "${taskId}" and attemptId "${attemptId}", heartbeat true. If it returns stale_claim, stop. Then continue from the existing brief.`;
105
+ }
106
+
107
+ export function startDispatch({ baseUrl = DEFAULT_DISPATCH_URL, harness, executorId, bearer, wake, logger = console, host = "127.0.0.1", port = 0, reconcileMs = 30000 } = {}) {
108
+ if (!executorId || !bearer) throw new Error("dispatch needs an executor id and bearer");
109
+ const started = new Map();
110
+ let closed = false;
111
+ let timer = null;
112
+ let listener = null;
113
+
114
+ const server = http.createServer(async (req, res) => {
115
+ if (req.method !== "POST" || req.url !== "/wake") {
116
+ json(res, 404, { error: "not found" });
117
+ return;
118
+ }
119
+ const auth = req.headers?.authorization ?? "";
120
+ if (!auth.startsWith("Bearer ") || auth.slice(7) !== bearer) {
121
+ json(res, 401, { error: "unauthorized" });
122
+ return;
123
+ }
124
+ const body = await readJson(req, res);
125
+ if (body === undefined) return;
126
+ if (body?.type === "ping") {
127
+ json(res, 200, { ok: true, test: true });
128
+ return;
129
+ }
130
+ if (body?.type !== "wake" || !body.admissionId || !body.itemId || !body.agent) {
131
+ json(res, 400, { error: "wake payload requires admissionId, itemId, agent" });
132
+ return;
133
+ }
134
+ Promise.resolve(wake({
135
+ agent: body.agent,
136
+ message: body.itemId,
137
+ kind: body.kind,
138
+ admissionId: body.admissionId,
139
+ })).catch((err) => logger?.warn?.(`winch: wake ${body.itemId} failed: ${err?.message ?? err}`));
140
+ json(res, 202, { ok: true, admissionId: body.admissionId });
141
+ });
142
+
143
+ const run = async () => {
144
+ if (closed) return;
145
+ try {
146
+ await registerExecutor({
147
+ baseUrl,
148
+ harness,
149
+ executorId,
150
+ url: `http://${host}:${listener.address().port}/wake`,
151
+ bearer,
152
+ });
153
+ } catch (err) {
154
+ logger?.warn?.(`winch: dispatch register failed: ${err?.message ?? err}`);
155
+ }
156
+ try {
157
+ await recoverOnce({ baseUrl, harness, executorId, wake, started, logger });
158
+ } catch (err) {
159
+ logger?.warn?.(`winch: dispatch recover failed: ${err?.message ?? err}`);
160
+ }
161
+ };
162
+
163
+ const ready = new Promise((resolve, reject) => {
164
+ server.once("error", reject);
165
+ server.listen(port, host, () => {
166
+ listener = server;
167
+ void run();
168
+ if (Number(reconcileMs) > 0) {
169
+ timer = setInterval(() => { void run(); }, Number(reconcileMs));
170
+ timer.unref?.();
171
+ }
172
+ resolve({ port: listener.address().port, executorId });
173
+ });
174
+ });
175
+
176
+ return {
177
+ ready,
178
+ get executorId() { return executorId; },
179
+ get port() { return listener?.address()?.port ?? null; },
180
+ close() {
181
+ closed = true;
182
+ if (timer) clearInterval(timer);
183
+ return new Promise((resolve) => server.close(() => resolve()));
184
+ },
185
+ };
186
+ }
package/index.js CHANGED
@@ -1,19 +1,66 @@
1
1
  import { createWinchHooks } from "./hooks.js";
2
2
  import { stampWinchEvent } from "./identity.js";
3
+ import { startDispatch, DEFAULT_DISPATCH_URL } from "./dispatch.js";
4
+ import { spawn } from "node:child_process";
5
+
6
+ function opencodeWake({ agent, message }) {
7
+ return new Promise((resolve, reject) => {
8
+ const bin = process.env.OPENCODE_BIN || "opencode";
9
+ const child = spawn(bin, ["run", "--agent", agent, message], {
10
+ detached: true,
11
+ stdio: ["ignore", "ignore", "pipe"],
12
+ });
13
+ let stderr = "";
14
+ child.stderr?.on("data", (d) => { stderr = (stderr + d.toString()).slice(-2000); });
15
+ child.on("error", reject);
16
+ child.on("exit", (code) =>
17
+ code === 0 ? resolve() : reject(new Error(`exit ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join(" | ")}` : ""}`))
18
+ );
19
+ child.unref();
20
+ });
21
+ }
22
+
23
+ function start({ cfg = {}, harness, logger }) {
24
+ const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
25
+ const bearer = process.env.WINCH_WEBHOOK_BEARER;
26
+ if (!executorId || !bearer) {
27
+ logger?.warn?.("winch: dispatch needs WINCH_EXECUTOR_ID and WINCH_WEBHOOK_BEARER; receiver disabled");
28
+ return null;
29
+ }
30
+ const dispatch = startDispatch({
31
+ baseUrl: process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL,
32
+ harness,
33
+ executorId,
34
+ bearer,
35
+ wake: opencodeWake,
36
+ port: Number(cfg.dispatchPort ?? process.env.WINCH_DISPATCH_PORT ?? 0),
37
+ reconcileMs: Number(cfg.dispatchReconcileMs ?? process.env.WINCH_DISPATCH_RECONCILE_MS ?? 30000),
38
+ logger,
39
+ });
40
+ dispatch.ready.catch((err) => logger?.warn?.(`winch: dispatch listener failed: ${err?.message ?? err}`));
41
+ return dispatch;
42
+ }
3
43
 
4
44
  // One package, two hosts: V1 calls server() and gets the object hooks; V2
5
- // reads id/setup() and gets the domain hooks. The implementations stay
6
- // separate — V1 mutates (input, output), V2 mutates one event — but both
7
- // stamp the same unconditional identity pair.
45
+ // reads id/setup() and gets the domain hooks. Both stamp the same identity pair.
8
46
  export default {
9
47
  id: "winch-opencode",
10
48
  async setup(ctx) {
11
49
  // SessionContext (the "context" hook event) carries both sessionID and
12
- // the session's agent; session.get() in this beta returns a projection
13
- // without agent, so the request hook is the reliable source.
14
- const agents = new Map();
15
- await ctx.session.hook("context", (event) => {
50
+ // the session's agent; session.get() in this beta returns a projection
51
+ // without agent, so the request hook is the reliable source.
52
+ const agents = new Map();
53
+ let dispatch = null;
54
+ const ensureDispatch = () => {
55
+ if (dispatch) return;
56
+ const cfg = ctx.options ?? {};
57
+ if (cfg.dispatchEnabled === false || process.env.WINCH_DISPATCH_ENABLED === "0") return;
58
+ const harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "opencode";
59
+ dispatch = start({ cfg, harness, logger: console });
60
+ };
61
+ await ctx.session.hook("context", (event) => {
16
62
  if (event?.sessionID && event.agent) agents.set(event.sessionID, event.agent);
63
+ ensureDispatch();
17
64
  });
18
65
  await ctx.tool.hook("execute.before", (event) => {
19
66
  const agent = agents.get(event.sessionID) ?? process.env.WINCH_AGENT ?? null;
@@ -23,6 +70,24 @@ export default {
23
70
  });
24
71
  },
25
72
  async server() {
26
- return createWinchHooks();
73
+ const hooks = createWinchHooks();
74
+ let dispatch = null;
75
+ const ensureDispatch = () => {
76
+ if (dispatch) return;
77
+ if (process.env.WINCH_DISPATCH_ENABLED === "0") return;
78
+ const harness = process.env.WINCH_HARNESS ?? "opencode";
79
+ dispatch = start({ cfg: {}, harness, logger: console });
80
+ };
81
+ const origMessage = hooks["chat.message"];
82
+ hooks["chat.message"] = async (input) => {
83
+ if (typeof origMessage === "function") await origMessage(input);
84
+ ensureDispatch();
85
+ };
86
+ const origParams = hooks["chat.params"];
87
+ hooks["chat.params"] = async (input) => {
88
+ if (typeof origParams === "function") await origParams(input);
89
+ ensureDispatch();
90
+ };
91
+ return hooks;
27
92
  },
28
93
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch-opencode",
3
- "version": "2026.11.9-beta.1",
4
- "description": "OpenCode companion for winch: stamps agent and session identity on winch tool calls (V1 hooks + V2 setup). No SDK dependency — a plain id/setup/server export.",
3
+ "version": "2026.11.18-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 \u2014 a plain id/setup/server export.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "repository": {
@@ -19,7 +19,8 @@
19
19
  "files": [
20
20
  "index.js",
21
21
  "hooks.js",
22
- "identity.js"
22
+ "identity.js",
23
+ "dispatch.js"
23
24
  ],
24
25
  "main": "index.js"
25
26
  }