@igorjpimenta/winch 2026.11.22-beta.2 → 2026.11.23-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/src/watcher.js CHANGED
@@ -21,14 +21,13 @@ import { readyTasks } from "./ready-queue.js";
21
21
  export const MAX_ACTIVE_PER_AGENT = 2;
22
22
 
23
23
  /**
24
- * @returns {{ts:number, swept:string[], resolved:string[], waits:object[], routed:object[], human:object[], deferred:object[], unrouted:object[], blocked:object[], gates:object[]}}
24
+ * @returns {{ts:number, swept:string[], resolved:string[], waits:object[], routed:object[], human:object[], deferred:object[], blocked:object[], gates:object[]}}
25
25
  * swept — lease-expired tasks the sweep requeued or escalated this tick
26
26
  * resolved — dependency-wait tasks returned to ready this tick
27
27
  * waits — gate-waiting rows written this tick (24h/72h age thresholds, one per gate per level)
28
28
  * routed — claimable AND assigned AND assignee under the active cap: the cron wakes `assigned`
29
29
  * human — claimable human work: ready for a person, never woken through an agent harness
30
30
  * deferred — claimable AND assigned BUT assignee at MAX_ACTIVE: never woken (starvation metric)
31
- * unrouted — always empty while ready requires an assignment; kept for manifest compatibility
32
31
  */
33
32
  export function tick(store, { config: override = null } = {}) {
34
33
  const cfg = override ?? store.config;
@@ -52,8 +51,8 @@ export function tick(store, { config: override = null } = {}) {
52
51
  .slice(0, cfg.blockedLimit)
53
52
  .map((t) => ({ id: t.id, title: t.title, assigned: t.assignee_agent, gate_type: t.gate_type, blocked_at: t.blocked_at }));
54
53
  // Gated tasks are separated from plain blocks for visibility. Who should
55
- // be told about them is a subscriber decision — the events WebSocket
56
- // streams every row, and clients track their own seen state.
54
+ // be told about them is a subscriber decision — event envelopes carry every
55
+ // row, and webhook subscribers track their own seen state.
57
56
  const gates = store.item
58
57
  .list({ kind: "task", status: "blocked" })
59
58
  .filter((t) => t.gate_type)
@@ -71,14 +70,6 @@ export function tick(store, { config: override = null } = {}) {
71
70
  const deferred = claimable
72
71
  .filter((c) => c.assigned && c.assigned !== HUMAN_AGENT && (active.get(c.assigned) ?? 0) >= cfg.maxActivePerAgent)
73
72
  .map((c) => ({ ...c, activeCount: active.get(c.assigned) }));
74
- const unrouted = claimable
75
- .filter((c) => !c.assigned)
76
- // Waiting-age gauge: the wire streams transitions, never waiting, so the
77
- // manifest carries how long each unrouted task has sat idle instead.
78
- .map((c) => {
79
- const row = store.task.get(c.taskId);
80
- return { ...c, idleMs: row ? nowTs - (row.updated_at ?? nowTs) : 0 };
81
- });
82
73
 
83
74
  return {
84
75
  ts: nowTs,
@@ -88,7 +79,6 @@ export function tick(store, { config: override = null } = {}) {
88
79
  routed,
89
80
  human,
90
81
  deferred,
91
- unrouted,
92
82
  blocked,
93
83
  gates,
94
84
  };
@@ -2,8 +2,8 @@
2
2
  // under per-harness and global caps. The harness accepts an offer; only the
3
3
  // winner starts a session. Item status remains the work acknowledgement.
4
4
 
5
- import { HUMAN_AGENT, HUMAN_HARNESS } from "./reserved.js";
6
- import { pickConsumer } from "./dispatch-webhook.js";
5
+ import { HUMAN_AGENT, HUMAN_HARNESS } from "../reserved.js";
6
+ import { pickConsumer } from "./delivery.js";
7
7
 
8
8
  const RELEASING_STATUSES = new Set(["done", "cancelled", "blocked", "backlog", "review"]);
9
9
 
@@ -129,25 +129,17 @@ export function recover(store, { harness, consumerId = null, at = Date.now(), co
129
129
  maxAttempts: config.dispatchOfferMaxAttempts,
130
130
  });
131
131
 
132
- const ownerForItem = `COALESCE(
133
- a.consumer_id,
134
- (SELECT aa.active_consumer_id
135
- FROM admission_queue q
136
- JOIN admission_attempts aa ON aa.admission_id=q.id
137
- WHERE q.item_id=s.item_id AND q.status='active' AND q.ended_at IS NULL
138
- ORDER BY aa.attempt_no DESC LIMIT 1)
139
- )`;
140
132
  const resume = store.db.prepare(`
141
133
  SELECT s.item_id, s.assignee_agent, s.assignee_harness,
142
134
  a.id AS attempt_id, a.attempt_no, a.claimed_at, a.heartbeat_at, a.expires_at,
143
135
  a.lease_epoch, a.owner_instance,
144
136
  ws.id AS session_id, ws.external_session_id, ws.session_key,
145
- ${ownerForItem} AS consumer_id
137
+ a.consumer_id AS consumer_id
146
138
  FROM item_state s
147
139
  LEFT JOIN attempts a ON a.item_id=s.item_id AND a.ended_at IS NULL
148
140
  LEFT JOIN work_sessions ws ON ws.id=a.session_id
149
141
  WHERE s.status='in_progress' AND s.deleted_at IS NULL AND s.assignee_harness=?
150
- AND (? IS NULL OR ${ownerForItem} = ?)
142
+ AND (? IS NULL OR a.consumer_id = ?)
151
143
  ORDER BY a.claimed_at ASC, s.updated_at ASC
152
144
  `).all(harness, consumerId, consumerId).map((r) => ({
153
145
  task: store.task.get(r.item_id),
@@ -197,9 +197,9 @@ export async function deliverDue(store, { config = store.config, logger = null,
197
197
  FROM admission_queue q
198
198
  JOIN admission_attempts aa ON aa.admission_id=q.id AND aa.ended_at IS NULL
199
199
  WHERE q.status IN ('offered','accepted') AND q.ended_at IS NULL
200
- AND EXISTS (SELECT 1 FROM dispatch_deliveries d
200
+ AND EXISTS (SELECT 1 FROM webhook_deliveries d
201
201
  WHERE d.admission_id=q.id AND d.attempt_no=aa.attempt_no)
202
- AND NOT EXISTS (SELECT 1 FROM dispatch_deliveries d
202
+ AND NOT EXISTS (SELECT 1 FROM webhook_deliveries d
203
203
  WHERE d.admission_id=q.id AND d.attempt_no=aa.attempt_no
204
204
  AND d.status != 'dead')
205
205
  `).all();
@@ -0,0 +1,131 @@
1
+ // envelope.js — the event envelope: stored transition rows in, subscriber
2
+ // envelopes out. No socket here. Webhook wakes are the main event driver
3
+ // (delivery.js via server.js); the store write hook and the
4
+ // dispatch boot catch-up share this one shape.
5
+ //
6
+ // kindForEvent: stable kind for a stored transition. Structural inference
7
+ // covers task.* (created, claimed, progressed, completed, released, blocked,
8
+ // cancelled, updated) and gate.* (opened, resolved, dissolved); producers may
9
+ // store story.*, deps.* and release.*. A stored `kind` wins; otherwise the row
10
+ // maps by transition structure alone. Notes are free text and can change, so
11
+ // no branch here may read note content — a renamed note must never
12
+ // reclassify history.
13
+ //
14
+ // Pre-standardization rows still carry `todo` as a task status; map it with
15
+ // `ready` so the append-only history keeps the meaning it was recorded with.
16
+
17
+ import { collectStoryArtifacts } from "../tools/index.js";
18
+ import { depsResolved } from "../deps.js";
19
+ import { HUMAN_AGENT } from "../reserved.js";
20
+
21
+ export const HISTORY_LIMIT = 200;
22
+
23
+ export function lastEventId(store) {
24
+ return store.event.lastEventId();
25
+ }
26
+
27
+ export function eventsSince(store, id, limit = HISTORY_LIMIT) {
28
+ return store.event.since(id, limit);
29
+ }
30
+
31
+ export function eventsLatest(store, limit = HISTORY_LIMIT) {
32
+ return store.event.latest(limit);
33
+ }
34
+
35
+ export function kindForEvent(row) {
36
+ if (row.kind) return row.kind;
37
+ const from = row.from_status;
38
+ const to = row.to_status;
39
+ if (from == null) return "task.created";
40
+ if ((from === "ready" || from === "todo") && to === "in_progress") return "task.claimed";
41
+ if (from === "in_progress" && to === "in_progress") return "task.progressed";
42
+ if (to === "done") return "task.completed";
43
+ if (to === "cancelled") return "task.cancelled";
44
+ if (to === "blocked") return "task.blocked";
45
+ if (to === "ready" || to === "todo") return "task.released";
46
+ return "task.updated";
47
+ }
48
+
49
+ // One envelope shape for history and live rows alike: the stored transition
50
+ // plus the task, story and epic context a subscriber would otherwise fetch
51
+ // once per row. Artifacts come from the same collector the claim handoff
52
+ // uses, so both paths agree on what "the artifacts" means.
53
+ function unblockedFor(store, row, kind) {
54
+ const terminal = row.to_status === "done" || row.to_status === "cancelled";
55
+ const claims = terminal
56
+ || kind === "task.released" || kind === "task.appended"
57
+ || kind === "deps.resolved" || kind === "gate.resolved";
58
+ if (!claims) return [];
59
+
60
+ const ids = new Set();
61
+ if (terminal) {
62
+ for (const edge of store.dep.listIncoming(row.item_id)) ids.add(edge.from_id);
63
+ } else if (row.item_id) {
64
+ ids.add(row.item_id);
65
+ }
66
+
67
+ const out = [];
68
+ for (const id of ids) {
69
+ const task = store.task.get(id);
70
+ if (!task || task.status !== "ready" || !task.assignee_agent || task.assignee_agent === HUMAN_AGENT) continue;
71
+ if (!depsResolved(store, id)) continue;
72
+ out.push({ id: task.id, assigned: task.assignee_agent, assigneeHarness: task.assignee_harness });
73
+ if (out.length === 20) break;
74
+ }
75
+ return out;
76
+ }
77
+
78
+ export function toEventMessage(store, row, { includeArtifacts = true, includeUnblocked = true } = {}) {
79
+ const kind = kindForEvent(row);
80
+ const item = !row.item_id ? null : store.item.get(row.item_id);
81
+ const itemKind = item?.kind ?? null;
82
+ const task = itemKind === "task" ? item : null;
83
+ const story = itemKind === "story" ? item : task?.story_id ? store.story.get(task.story_id) : null;
84
+ const epic = itemKind === "epic" ? item : story?.epic_id ? store.epic.get(story.epic_id) : item?.epic_id ? store.epic.get(item.epic_id) : null;
85
+ const actorSession = row.session_id ? store.session.get(row.session_id) : null;
86
+ return {
87
+ type: "event",
88
+ kind,
89
+ id: row.id,
90
+ at: row.created_at,
91
+ fromStatus: row.from_status ?? null,
92
+ toStatus: row.to_status,
93
+ // Normalised item: a dispatcher routes assignment and review wakes without
94
+ // knowing which level the row is about.
95
+ item: item
96
+ ? {
97
+ id: item.id,
98
+ kind: itemKind,
99
+ title: item.title,
100
+ status: item.status,
101
+ assigned: item.assignee_agent ?? null,
102
+ assigneeHarness: item.assignee_harness ?? null,
103
+ createdBy: item.created_by ?? null,
104
+ }
105
+ : null,
106
+ epicId: epic?.id ?? null,
107
+ epicCreatedBy: epic?.created_by ?? null,
108
+ epicAssigneeHarness: epic?.assignee_harness ?? null,
109
+ storyId: story?.id ?? null,
110
+ storyAssigned: story?.assignee_agent ?? null,
111
+ storyAssigneeHarness: story?.assignee_harness ?? null,
112
+ // Work a transition just made claimable: a dispatcher wakes these without
113
+ // recomputing the dependency graph. Creation and direct assignment already
114
+ // route their own item, so only a close looks at incoming edges.
115
+ unblocked: includeUnblocked ? unblockedFor(store, row, kind) : [],
116
+ task: task
117
+ ? {
118
+ id: task.id,
119
+ title: task.title,
120
+ story: story ? story.title : null,
121
+ epic: epic ? epic.title : null,
122
+ acceptance: story ? story.acceptance : null,
123
+ artifacts: includeArtifacts && story ? collectStoryArtifacts(store, story.id) : [],
124
+ assignee: task.assignee_agent,
125
+ }
126
+ : null,
127
+ actor: row.actor,
128
+ actorHarness: actorSession?.harness ?? null,
129
+ note: row.note,
130
+ };
131
+ }
@@ -1,12 +1,12 @@
1
- // dispatch-server.js — HTTP dispatch endpoints and the admission queue pump.
2
- // Executors register here and winch POSTs wakes from here; the read-only event
3
- // stream lives in events-ws.js and shares no socket with dispatch.
1
+ // server.js — HTTP dispatch endpoints and the admission queue pump.
2
+ // Executors register here and winch POSTs webhook wakes from here; webhook
3
+ // delivery is the main event driver.
4
4
 
5
5
  import http from "node:http";
6
- import { observe, recover, tick as dispatchTick } from "./dispatch.js";
7
- import { deliverDue, deliverWake } from "./dispatch-webhook.js";
8
- import { StaleRegistrationError } from "./store/webhook.js";
9
- import { eventsSince, lastEventId, toEventMessage, HISTORY_LIMIT } from "./events-ws.js";
6
+ import { observe, recover, tick as dispatchTick } from "./core.js";
7
+ import { deliverDue, deliverWake } from "./delivery.js";
8
+ import { StaleRegistrationError } from "../store/webhook.js";
9
+ import { eventsSince, lastEventId, toEventMessage, HISTORY_LIMIT } from "./envelope.js";
10
10
 
11
11
  export const DEFAULT_DISPATCH_PORT = 38293;
12
12
 
@@ -16,7 +16,7 @@ export function startDispatchServer({ store, port = null, host = "127.0.0.1", in
16
16
  const pollMs = intervalMs ?? cfg.dispatchIntervalMs ?? 1000;
17
17
  const sweepMs = cfg.dispatchSweepMs ?? 30000;
18
18
  const consumerTtlMs = cfg.dispatchConsumerTtlMs ?? 90000;
19
- const histLimit = cfg.wsHistoryLimit ?? HISTORY_LIMIT;
19
+ const histLimit = cfg.eventHistoryLimit ?? HISTORY_LIMIT;
20
20
  const authToken = String(process.env.WINCH_DISPATCH_TOKEN ?? "").trim() || null;
21
21
  const loopback = host === "127.0.0.1" || host === "::1" || host === "localhost";
22
22
  if (!loopback && !authToken) {
@@ -128,10 +128,6 @@ export function startDispatchServer({ store, port = null, host = "127.0.0.1", in
128
128
  managed: true,
129
129
  fresh,
130
130
  });
131
- if (executorId && id !== executorId) {
132
- const legacy = store.webhook.get({ topic: "dispatch", id: executorId });
133
- if (legacy?.executorId === executorId) store.webhook.remove({ topic: "dispatch", id: executorId });
134
- }
135
131
  json(res, 201, {
136
132
  ok: true, topic: row.topic, id: row.id, harness: row.harness,
137
133
  executorId: row.executorId, instanceId: row.instanceId,
package/src/events-ws.js DELETED
@@ -1,269 +0,0 @@
1
- // events-ws.js — the read-only event pipe.
2
- // Tails the item_events ledger and broadcasts every new row; dispatch wakes
3
- // leave over executor webhooks served by dispatch-server.js, not this socket.
4
- //
5
- // Wire protocol (JSON text frames):
6
- // server → client:
7
- // {"type":"welcome","payload":"v3","lastEventId":N}
8
- // {"type":"history","events":[...]} backlog of envelopes, oldest-first
9
- // {"type":"event","kind":...,"item":{...},...} one flat envelope per new row, in id order
10
- //
11
- // Clients track their own seen state: reconnecting replays history, so a
12
- // missed frame costs a re-read, never a lost event. The admission queue owns
13
- // wake delivery and retry; MCP claim remains the work-level guard. No auth
14
- // in-process — bind localhost, or put a bearer-checked reverse proxy in front.
15
-
16
- import http from "node:http";
17
- import crypto from "node:crypto";
18
- import { collectStoryArtifacts } from "./tools/index.js";
19
- import { depsResolved } from "./deps.js";
20
- import { HUMAN_AGENT } from "./reserved.js";
21
-
22
- const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
23
- export const DEFAULT_WS_PORT = 38291;
24
- export const HISTORY_LIMIT = 200;
25
-
26
- function acceptKey(key) {
27
- return crypto.createHash("sha1").update(key + WS_GUID).digest("base64");
28
- }
29
-
30
- // Server → client frames are never masked (RFC 6455 §5.3).
31
- function encodeFrame(text) {
32
- const payload = Buffer.from(text, "utf8");
33
- const len = payload.length;
34
- let header;
35
- if (len < 126) {
36
- header = Buffer.from([0x81, len]);
37
- } else if (len < 65536) {
38
- header = Buffer.alloc(4);
39
- header[0] = 0x81;
40
- header[1] = 126;
41
- header.writeUInt16BE(len, 2);
42
- } else {
43
- header = Buffer.alloc(10);
44
- header[0] = 0x81;
45
- header[1] = 127;
46
- header.writeBigUInt64BE(BigInt(len), 2);
47
- }
48
- return Buffer.concat([header, payload]);
49
- }
50
-
51
- export function lastEventId(store) {
52
- return store.event.lastEventId();
53
- }
54
-
55
- export function eventsSince(store, id, limit = HISTORY_LIMIT) {
56
- return store.event.since(id, limit);
57
- }
58
-
59
- export function eventsLatest(store, limit = HISTORY_LIMIT) {
60
- return store.event.latest(limit);
61
- }
62
-
63
- // Stable kind for a stored transition. Structural inference covers task.*
64
- // (created, claimed, progressed, completed, released, blocked, cancelled,
65
- // updated) and gate.* (opened, resolved, dissolved); producers may store
66
- // story.*, deps.* and release.*. A stored `kind` wins; otherwise the row maps
67
- // by transition structure alone. Notes are free text and can change, so no
68
- // branch here may read note content —
69
- // a renamed note must never reclassify history.
70
- //
71
- // Pre-standardization rows still carry `todo` as a task status; map it with
72
- // `ready` so the append-only history keeps the meaning it streamed with.
73
- export function kindForEvent(row) {
74
- if (row.kind) return row.kind;
75
- const from = row.from_status;
76
- const to = row.to_status;
77
- if (from == null) return "task.created";
78
- if ((from === "ready" || from === "todo") && to === "in_progress") return "task.claimed";
79
- if (from === "in_progress" && to === "in_progress") return "task.progressed";
80
- if (to === "done") return "task.completed";
81
- if (to === "cancelled") return "task.cancelled";
82
- if (to === "blocked") return "task.blocked";
83
- if (to === "ready" || to === "todo") return "task.released";
84
- return "task.updated";
85
- }
86
-
87
- // One envelope shape for history and live rows alike: the stored transition
88
- // plus the task, story and epic context a subscriber would otherwise fetch
89
- // once per row. Artifacts come from the same collector the claim handoff
90
- // uses, so both paths agree on what "the artifacts" means.
91
- function unblockedFor(store, row, kind) {
92
- const terminal = row.to_status === "done" || row.to_status === "cancelled";
93
- const claims = terminal
94
- || kind === "task.released" || kind === "task.appended"
95
- || kind === "deps.resolved" || kind === "gate.resolved";
96
- if (!claims) return [];
97
-
98
- const ids = new Set();
99
- if (terminal) {
100
- for (const edge of store.dep.listIncoming(row.item_id)) ids.add(edge.from_id);
101
- } else if (row.item_id) {
102
- ids.add(row.item_id);
103
- }
104
-
105
- const out = [];
106
- for (const id of ids) {
107
- const task = store.task.get(id);
108
- if (!task || task.status !== "ready" || !task.assignee_agent || task.assignee_agent === HUMAN_AGENT) continue;
109
- if (!depsResolved(store, id)) continue;
110
- out.push({ id: task.id, assigned: task.assignee_agent, assigneeHarness: task.assignee_harness });
111
- if (out.length === 20) break;
112
- }
113
- return out;
114
- }
115
-
116
- export function toEventMessage(store, row, { includeArtifacts = true, includeUnblocked = true } = {}) {
117
- const kind = kindForEvent(row);
118
- const item = !row.item_id ? null : store.item.get(row.item_id);
119
- const itemKind = item?.kind ?? null;
120
- const task = itemKind === "task" ? item : null;
121
- const story = itemKind === "story" ? item : task?.story_id ? store.story.get(task.story_id) : null;
122
- const epic = itemKind === "epic" ? item : story?.epic_id ? store.epic.get(story.epic_id) : item?.epic_id ? store.epic.get(item.epic_id) : null;
123
- const actorSession = row.session_id ? store.session.get(row.session_id) : null;
124
- return {
125
- type: "event",
126
- kind,
127
- id: row.id,
128
- at: row.created_at,
129
- fromStatus: row.from_status ?? null,
130
- toStatus: row.to_status,
131
- // Normalised item: a dispatcher routes assignment and review wakes without
132
- // knowing which level the row is about.
133
- item: item
134
- ? {
135
- id: item.id,
136
- kind: itemKind,
137
- title: item.title,
138
- status: item.status,
139
- assigned: item.assignee_agent ?? null,
140
- assigneeHarness: item.assignee_harness ?? null,
141
- createdBy: item.created_by ?? null,
142
- }
143
- : null,
144
- epicId: epic?.id ?? null,
145
- epicCreatedBy: epic?.created_by ?? null,
146
- epicAssigneeHarness: epic?.assignee_harness ?? null,
147
- storyId: story?.id ?? null,
148
- storyAssigned: story?.assignee_agent ?? null,
149
- storyAssigneeHarness: story?.assignee_harness ?? null,
150
- // Work a transition just made claimable: a dispatcher wakes these without
151
- // recomputing the dependency graph. Creation and direct assignment already
152
- // route their own item, so only a close looks at incoming edges.
153
- unblocked: includeUnblocked ? unblockedFor(store, row, kind) : [],
154
- task: task
155
- ? {
156
- id: task.id,
157
- title: task.title,
158
- story: story ? story.title : null,
159
- epic: epic ? epic.title : null,
160
- acceptance: story ? story.acceptance : null,
161
- artifacts: includeArtifacts && story ? collectStoryArtifacts(store, story.id) : [],
162
- assignee: task.assignee_agent,
163
- }
164
- : null,
165
- actor: row.actor,
166
- actorHarness: actorSession?.harness ?? null,
167
- note: row.note,
168
- };
169
- }
170
-
171
- export function startEventServer({ store, port = null, host = "127.0.0.1", intervalMs = null, historyLimit = null, logger } = {}) {
172
- const cfg = store.config ?? {};
173
- const listenPort = port ?? cfg.wsPort ?? DEFAULT_WS_PORT;
174
- const pollMs = intervalMs ?? cfg.wsIntervalMs ?? 1000;
175
- const histLimit = historyLimit ?? cfg.wsHistoryLimit ?? HISTORY_LIMIT;
176
- const clients = new Map();
177
- let closing = false;
178
- let cursor = lastEventId(store);
179
-
180
- function send(socket, obj) {
181
- if (socket.destroyed || !socket.writable) return false;
182
- try {
183
- socket.write(encodeFrame(JSON.stringify(obj)));
184
- return true;
185
- } catch {
186
- return false;
187
- }
188
- }
189
-
190
- function broadcast(obj) {
191
- const frame = encodeFrame(JSON.stringify(obj));
192
- for (const client of [...clients.values()]) {
193
- const sock = client.socket;
194
- if (sock.destroyed || !sock.writable) {
195
- clients.delete(sock);
196
- continue;
197
- }
198
- sock.write(frame);
199
- }
200
- }
201
-
202
- const server = http.createServer((req, res) => {
203
- res.writeHead(404, { "content-type": "application/json" });
204
- res.end(JSON.stringify({ error: "not found" }));
205
- });
206
-
207
- server.on("upgrade", (req, socket) => {
208
- const key = req.headers["sec-websocket-key"];
209
- if ((req.headers.upgrade || "").toLowerCase() !== "websocket" || !key) {
210
- socket.destroy();
211
- return;
212
- }
213
- socket.write(
214
- "HTTP/1.1 101 Switching Protocols\r\n" +
215
- "Upgrade: websocket\r\n" +
216
- "Connection: Upgrade\r\n" +
217
- `Sec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`
218
- );
219
- const client = { socket, connectedAt: Date.now() };
220
- clients.set(socket, client);
221
- logger?.info?.(`winch: ws subscriber connected (${clients.size} total)`);
222
- try {
223
- send(socket, { type: "welcome", payload: "v3", lastEventId: cursor });
224
- send(socket, { type: "history", events: eventsLatest(store, histLimit).map((row) => toEventMessage(store, row)) });
225
- } catch {
226
- clients.delete(socket);
227
- }
228
-
229
- const drop = () => {
230
- clients.delete(socket);
231
- if (closing) return;
232
- };
233
- socket.on("close", drop);
234
- socket.on("error", drop);
235
- });
236
-
237
- const timer = setInterval(() => {
238
- try {
239
- const rows = eventsSince(store, cursor, histLimit);
240
- if (rows.length) {
241
- cursor = rows[rows.length - 1].id;
242
- for (const row of rows) {
243
- broadcast(toEventMessage(store, row));
244
- }
245
- }
246
- } catch (err) {
247
- logger?.warn?.(`winch: event poll failed: ${err?.message ?? err}`);
248
- }
249
- }, pollMs);
250
- if (typeof timer.unref === "function") timer.unref();
251
-
252
- return new Promise((resolve, reject) => {
253
- server.once("error", reject);
254
- server.listen(listenPort, host, () => {
255
- resolve({
256
- port: server.address().port,
257
- host,
258
- clients: () => clients.size,
259
- close: () =>
260
- new Promise((res) => {
261
- closing = true;
262
- clearInterval(timer);
263
- for (const client of clients.values()) client.socket.destroy();
264
- server.close(() => res());
265
- }),
266
- });
267
- });
268
- });
269
- }