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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dispatch.js CHANGED
@@ -40,22 +40,36 @@ function json(res, status, body) {
40
40
  res.end(JSON.stringify(body));
41
41
  }
42
42
 
43
- export async function registerExecutor({ baseUrl, harness, executorId, url, bearer, timeoutMs = 5000 }) {
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 }) {
44
58
  const res = await fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/register`, {
45
59
  method: "POST",
46
- headers: { "content-type": "application/json" },
47
- body: JSON.stringify({ harness, executorId, url, bearer }),
60
+ headers: dispatchAuthHeaders(),
61
+ body: JSON.stringify({ harness, consumerId, executorId, instanceId: executorId, url, bearer, fresh }),
48
62
  signal: AbortSignal.timeout(timeoutMs),
49
63
  });
50
64
  if (!res.ok) throw new Error(`dispatch register ${res.status}`);
51
65
  return res.json();
52
66
  }
53
67
 
54
- export async function recoverOnce({ baseUrl, harness, executorId, wake, started, logger = console, timeoutMs = 5000 }) {
68
+ export async function recoverOnce({ baseUrl, harness, consumerId, executorId, wake, started, logger = console, timeoutMs = 5000 }) {
55
69
  const res = await fetch(`${String(baseUrl).replace(/\/+$/, "")}/dispatch/recover`, {
56
70
  method: "POST",
57
- headers: { "content-type": "application/json" },
58
- body: JSON.stringify({ harness, executorId }),
71
+ headers: dispatchAuthHeaders(),
72
+ body: JSON.stringify({ harness, consumerId, executorId }),
59
73
  signal: AbortSignal.timeout(timeoutMs),
60
74
  });
61
75
  if (!res.ok) throw new Error(`dispatch recover ${res.status}`);
@@ -82,14 +96,16 @@ export async function recoverOnce({ baseUrl, harness, executorId, wake, started,
82
96
 
83
97
  for (const row of body?.start ?? []) {
84
98
  if (!row?.admissionId || !row?.itemId) continue;
85
- const key = `start:${row.admissionId}`;
99
+ const key = `start:${row.admissionId}:${row.attemptNo ?? "none"}`;
86
100
  if (started.has(key)) continue;
87
101
  started.set(key, now);
88
102
  Promise.resolve(wake({
89
103
  agent: row.agent,
90
- message: row.itemId,
104
+ message: wakeMessage(row),
91
105
  kind: row.kind,
92
106
  admissionId: row.admissionId,
107
+ attemptNo: row.attemptNo,
108
+ leaseEpoch: row.leaseEpoch ?? 0,
93
109
  })).catch((err) => {
94
110
  started.delete(key);
95
111
  logger?.warn?.(`winch: wake ${row.itemId} failed: ${err?.message ?? err}`);
@@ -100,12 +116,17 @@ export async function recoverOnce({ baseUrl, harness, executorId, wake, started,
100
116
 
101
117
  export function resumePrompt(row) {
102
118
  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.`;
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.`;
105
125
  }
106
126
 
107
- export function startDispatch({ baseUrl = DEFAULT_DISPATCH_URL, harness, executorId, bearer, wake, logger = console, host = "127.0.0.1", port = 0, reconcileMs = 30000 } = {}) {
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 } = {}) {
108
128
  if (!executorId || !bearer) throw new Error("dispatch needs an executor id and bearer");
129
+ const subscriptionId = consumerId || executorId;
109
130
  const started = new Map();
110
131
  let closed = false;
111
132
  let timer = null;
@@ -131,30 +152,50 @@ export function startDispatch({ baseUrl = DEFAULT_DISPATCH_URL, harness, executo
131
152
  json(res, 400, { error: "wake payload requires admissionId, itemId, agent" });
132
153
  return;
133
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());
134
165
  Promise.resolve(wake({
135
166
  agent: body.agent,
136
- message: body.itemId,
167
+ message: wakeMessage(body),
137
168
  kind: body.kind,
138
169
  admissionId: body.admissionId,
139
- })).catch((err) => logger?.warn?.(`winch: wake ${body.itemId} failed: ${err?.message ?? err}`));
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
+ });
140
176
  json(res, 202, { ok: true, admissionId: body.admissionId });
141
177
  });
142
178
 
179
+ let fresh = true;
143
180
  const run = async () => {
144
181
  if (closed) return;
145
182
  try {
146
183
  await registerExecutor({
147
184
  baseUrl,
148
185
  harness,
186
+ consumerId: subscriptionId,
149
187
  executorId,
150
188
  url: `http://${host}:${listener.address().port}/wake`,
151
189
  bearer,
190
+ fresh,
152
191
  });
192
+ fresh = false;
153
193
  } catch (err) {
154
194
  logger?.warn?.(`winch: dispatch register failed: ${err?.message ?? err}`);
195
+ return;
155
196
  }
156
197
  try {
157
- await recoverOnce({ baseUrl, harness, executorId, wake, started, logger });
198
+ await recoverOnce({ baseUrl, harness, consumerId: subscriptionId, executorId, wake, started, logger });
158
199
  } catch (err) {
159
200
  logger?.warn?.(`winch: dispatch recover failed: ${err?.message ?? err}`);
160
201
  }
@@ -169,13 +210,14 @@ export function startDispatch({ baseUrl = DEFAULT_DISPATCH_URL, harness, executo
169
210
  timer = setInterval(() => { void run(); }, Number(reconcileMs));
170
211
  timer.unref?.();
171
212
  }
172
- resolve({ port: listener.address().port, executorId });
213
+ resolve({ port: listener.address().port, executorId, consumerId: subscriptionId });
173
214
  });
174
215
  });
175
216
 
176
217
  return {
177
218
  ready,
178
219
  get executorId() { return executorId; },
220
+ get consumerId() { return subscriptionId; },
179
221
  get port() { return listener?.address()?.port ?? null; },
180
222
  close() {
181
223
  closed = true;
package/hooks.js CHANGED
@@ -2,7 +2,7 @@ import { stampWinchIdentity } from "./identity.js";
2
2
 
3
3
  // The agent is not on the tool call, only the session: remember it from the
4
4
  // chat events that carry both, then stamp the pair on every winch call.
5
- export function createWinchHooks() {
5
+ export function createWinchHooks({ consumerId = null, instanceId = null } = {}) {
6
6
  const agents = new Map();
7
7
 
8
8
  return {
@@ -16,7 +16,7 @@ export function createWinchHooks() {
16
16
  // Unconditional: when the agent is unknown the slot is blanked, so a
17
17
  // model-supplied pair can never ride through as identity. Blank means
18
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 });
19
+ stampWinchIdentity(input, output, { agent: agents.get(input?.sessionID) ?? process.env.WINCH_AGENT ?? null, consumerId, instanceId });
20
20
  },
21
21
  };
22
22
  }
package/identity.js CHANGED
@@ -7,7 +7,7 @@ export function isWinchTool(name) {
7
7
  return typeof name === "string" && name.includes("winch");
8
8
  }
9
9
 
10
- export function stampWinchIdentity(input, output, { agent = null } = {}) {
10
+ export function stampWinchIdentity(input, output, { agent = null, consumerId = null, instanceId = null } = {}) {
11
11
  if (!isWinchTool(input?.tool)) return false;
12
12
  output.args = output.args ?? {};
13
13
  // Overwrite, never merge: an unknown agent blanks the slot (unstamped),
@@ -15,16 +15,20 @@ export function stampWinchIdentity(input, output, { agent = null } = {}) {
15
15
  // model-supplied identity never survives.
16
16
  output.args.winch_agent = agent ?? "";
17
17
  output.args.winch_session = input?.sessionID ?? "";
18
+ output.args.winch_consumer = consumerId ?? "";
19
+ output.args.winch_instance = instanceId ?? "";
18
20
  return true;
19
21
  }
20
22
 
21
23
  // V2: the tool hook hands one mutable event instead of (input, output). Same
22
24
  // rule — the pair is stamped unconditionally.
23
- export function stampWinchEvent(event, agent) {
25
+ export function stampWinchEvent(event, agent, consumerId = null, instanceId = null) {
24
26
  if (!isWinchTool(event?.tool)) return false;
25
27
  const input = event.input && typeof event.input === "object" ? event.input : {};
26
28
  event.input = input;
27
29
  input.winch_agent = agent ?? "";
28
30
  input.winch_session = event.sessionID ?? "";
31
+ input.winch_consumer = consumerId ?? "";
32
+ input.winch_instance = instanceId ?? "";
29
33
  return true;
30
34
  }
package/index.js CHANGED
@@ -2,6 +2,7 @@ import { createWinchHooks } from "./hooks.js";
2
2
  import { stampWinchEvent } from "./identity.js";
3
3
  import { startDispatch, DEFAULT_DISPATCH_URL } from "./dispatch.js";
4
4
  import { spawn } from "node:child_process";
5
+ import { hostname } from "node:os";
5
6
 
6
7
  function opencodeWake({ agent, message }) {
7
8
  return new Promise((resolve, reject) => {
@@ -20,8 +21,13 @@ function opencodeWake({ agent, message }) {
20
21
  });
21
22
  }
22
23
 
24
+ function consumerIdFor(harness, cfg = {}) {
25
+ return cfg.winchConsumerId ?? process.env.WINCH_CONSUMER_ID ?? `${harness}:${hostname()}`;
26
+ }
27
+
23
28
  function start({ cfg = {}, harness, logger }) {
24
29
  const executorId = cfg.winchExecutorId ?? process.env.WINCH_EXECUTOR_ID;
30
+ const consumerId = consumerIdFor(harness, cfg);
25
31
  const bearer = process.env.WINCH_WEBHOOK_BEARER;
26
32
  if (!executorId || !bearer) {
27
33
  logger?.warn?.("winch: dispatch needs WINCH_EXECUTOR_ID and WINCH_WEBHOOK_BEARER; receiver disabled");
@@ -30,6 +36,7 @@ function start({ cfg = {}, harness, logger }) {
30
36
  const dispatch = startDispatch({
31
37
  baseUrl: process.env.WINCH_DISPATCH_URL ?? DEFAULT_DISPATCH_URL,
32
38
  harness,
39
+ consumerId,
33
40
  executorId,
34
41
  bearer,
35
42
  wake: opencodeWake,
@@ -49,13 +56,15 @@ export default {
49
56
  // SessionContext (the "context" hook event) carries both sessionID and
50
57
  // the session's agent; session.get() in this beta returns a projection
51
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;
52
63
  const agents = new Map();
53
64
  let dispatch = null;
54
65
  const ensureDispatch = () => {
55
66
  if (dispatch) return;
56
- const cfg = ctx.options ?? {};
57
67
  if (cfg.dispatchEnabled === false || process.env.WINCH_DISPATCH_ENABLED === "0") return;
58
- const harness = cfg.winchHarness ?? process.env.WINCH_HARNESS ?? "opencode";
59
68
  dispatch = start({ cfg, harness, logger: console });
60
69
  };
61
70
  await ctx.session.hook("context", (event) => {
@@ -66,16 +75,18 @@ export default {
66
75
  const agent = agents.get(event.sessionID) ?? process.env.WINCH_AGENT ?? null;
67
76
  // Unconditional: unknown agent blanks the slot, the server refuses
68
77
  // rather than trusting whatever the model wrote there.
69
- stampWinchEvent(event, agent);
78
+ stampWinchEvent(event, agent, consumerId, executorId);
70
79
  });
71
80
  },
72
81
  async server() {
73
- const hooks = createWinchHooks();
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 });
74
86
  let dispatch = null;
75
87
  const ensureDispatch = () => {
76
88
  if (dispatch) return;
77
89
  if (process.env.WINCH_DISPATCH_ENABLED === "0") return;
78
- const harness = process.env.WINCH_HARNESS ?? "opencode";
79
90
  dispatch = start({ cfg: {}, harness, logger: console });
80
91
  };
81
92
  const origMessage = hooks["chat.message"];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@igorjpimenta/winch-opencode",
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.",
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
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "repository": {