@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
package/src/config.js ADDED
@@ -0,0 +1,181 @@
1
+ // config.js — layered tuning config, declared the way the harness is.
2
+ //
3
+ // Precedence: per-call `_meta.winch.config` > constructor `{ config }` >
4
+ // `WINCH_*` env > code defaults. Nothing here is required: every knob has a
5
+ // safe default, so a server started with no config behaves exactly like the
6
+ // old hardcoded one. (Identity is the opposite — the triple refuses when
7
+ // absent. Config never refuses for being absent; it refuses only for being
8
+ // malformed, naming the key, the way a bad harness declaration does.)
9
+
10
+ const DURATION_RE = /^(\d+)(ms|s|m|h|d)$/;
11
+ const UNIT_MS = { ms: 1, s: 1000, m: 60 * 1000, h: 3600 * 1000, d: 24 * 3600 * 1000 };
12
+
13
+ function parseLevelToken(tok) {
14
+ const m = String(tok ?? "").trim().match(DURATION_RE);
15
+ if (!m) return null;
16
+ return { ms: Number(m[1]) * UNIT_MS[m[2]], label: String(tok).trim() };
17
+ }
18
+
19
+ function parseGateWaitLevels(raw) {
20
+ const toks = Array.isArray(raw) ? raw : String(raw ?? "").split(",");
21
+ const levels = [];
22
+ for (const t of toks) {
23
+ if (t != null && typeof t === "object" && Number.isFinite(t.ms)) {
24
+ levels.push({ ms: Math.floor(t.ms), label: String(t.label ?? `${t.ms}ms`) });
25
+ continue;
26
+ }
27
+ const p = parseLevelToken(t);
28
+ if (!p || p.ms <= 0) return null;
29
+ levels.push(p);
30
+ }
31
+ if (!levels.length) return null;
32
+ return [...levels].sort((a, b) => a.ms - b.ms);
33
+ }
34
+
35
+ function parseInt(raw) {
36
+ if (typeof raw === "number") return Number.isInteger(raw) ? raw : null;
37
+ const s = String(raw ?? "").trim();
38
+ if (!/^\d+$/.test(s)) return null;
39
+ return Number(s);
40
+ }
41
+
42
+ // key -> { env, parse, check }. parse normalizes (string|number|array) to the
43
+ // stored shape; check rejects out-of-range values. Stored shapes are plain
44
+ // JSON: a resolved config survives a round-trip through JSON by construction.
45
+ const SPEC = {
46
+ leaseSeconds: { env: "WINCH_LEASE_SECONDS", parse: parseInt, check: (v) => v > 0 },
47
+ maxAttempts: { env: "WINCH_MAX_ATTEMPTS", parse: parseInt, check: (v) => v > 0 },
48
+ gateWaitLevels: { env: "WINCH_GATE_WAIT_LEVELS", parse: parseGateWaitLevels, check: (v) => v !== null },
49
+ wsPort: { env: "WINCH_WS_PORT", parse: parseInt, check: (v) => v >= 1 && v <= 65535 },
50
+ mcpHttpPort: { env: "WINCH_MCP_HTTP_PORT", parse: parseInt, check: (v) => v >= 1 && v <= 65535 },
51
+ wsHistoryLimit: { env: "WINCH_WS_HISTORY_LIMIT", parse: parseInt, check: (v) => v > 0 },
52
+ wsIntervalMs: { env: "WINCH_WS_INTERVAL_MS", parse: parseInt, check: (v) => v > 0 },
53
+ dispatchPort: { env: "WINCH_DISPATCH_PORT", parse: parseInt, check: (v) => v >= 1 && v <= 65535 },
54
+ dispatchIntervalMs: { env: "WINCH_DISPATCH_INTERVAL_MS", parse: parseInt, check: (v) => v > 0 },
55
+ dispatchSweepMs: { env: "WINCH_DISPATCH_SWEEP_MS", parse: parseInt, check: (v) => v > 0 },
56
+ maxActivePerAgent: { env: "WINCH_MAX_ACTIVE_PER_AGENT", parse: parseInt, check: (v) => v > 0 },
57
+ dispatchHarnessMax: { env: "WINCH_DISPATCH_HARNESS_MAX", parse: parseInt, check: (v) => v > 0 },
58
+ dispatchGlobalMax: { env: "WINCH_DISPATCH_GLOBAL_MAX", parse: parseInt, check: (v) => v > 0 },
59
+ dispatchOfferMs: { env: "WINCH_DISPATCH_OFFER_MS", parse: parseInt, check: (v) => v > 0 },
60
+ dispatchOfferBackoffMs: { env: "WINCH_DISPATCH_OFFER_BACKOFF_MS", parse: parseInt, check: (v) => v > 0 },
61
+ dispatchOfferMaxBackoffMs: { env: "WINCH_DISPATCH_OFFER_MAX_BACKOFF_MS", parse: parseInt, check: (v) => v > 0 },
62
+ dispatchOfferMaxAttempts: { env: "WINCH_DISPATCH_OFFER_MAX_ATTEMPTS", parse: parseInt, check: (v) => v > 0 },
63
+ dispatchDeliveryBackoffMs: { env: "WINCH_DISPATCH_DELIVERY_BACKOFF_MS", parse: parseInt, check: (v) => v > 0 },
64
+ dispatchDeliveryMaxBackoffMs: { env: "WINCH_DISPATCH_DELIVERY_MAX_BACKOFF_MS", parse: parseInt, check: (v) => v > 0 },
65
+ dispatchDeliveryMaxAttempts: { env: "WINCH_DISPATCH_DELIVERY_MAX_ATTEMPTS", parse: parseInt, check: (v) => v > 0 },
66
+ dispatchDeliveryFailureThreshold: { env: "WINCH_DISPATCH_DELIVERY_FAILURE_THRESHOLD", parse: parseInt, check: (v) => v > 0 },
67
+ dispatchDeliveryLeaseMs: { env: "WINCH_DISPATCH_DELIVERY_LEASE_MS", parse: parseInt, check: (v) => v > 0 },
68
+ dispatchConsumerTtlMs: { env: "WINCH_DISPATCH_CONSUMER_TTL_MS", parse: parseInt, check: (v) => v > 0 },
69
+ webhookTimeoutMs: { env: "WINCH_WEBHOOK_TIMEOUT_MS", parse: parseInt, check: (v) => v > 0 },
70
+ scanLimit: { env: "WINCH_SCAN_LIMIT", parse: parseInt, check: (v) => v > 0 },
71
+ candidates: { env: "WINCH_CANDIDATES", parse: parseInt, check: (v) => v > 0 },
72
+ blockedLimit: { env: "WINCH_BLOCKED_LIMIT", parse: parseInt, check: (v) => v > 0 },
73
+ dfsNodes: { env: "WINCH_DFS_NODES", parse: parseInt, check: (v) => v > 0 },
74
+ noteProgressLimit: { env: "WINCH_NOTE_PROGRESS_LIMIT", parse: parseInt, check: (v) => v > 0 },
75
+ noteResultLimit: { env: "WINCH_NOTE_RESULT_LIMIT", parse: parseInt, check: (v) => v > 0 },
76
+ noteReasonLimit: { env: "WINCH_NOTE_REASON_LIMIT", parse: parseInt, check: (v) => v > 0 },
77
+ noteArtifactLimit: { env: "WINCH_NOTE_ARTIFACT_LIMIT", parse: parseInt, check: (v) => v > 0 },
78
+ maxArtifacts: { env: "WINCH_MAX_ARTIFACTS", parse: parseInt, check: (v) => v > 0 },
79
+ };
80
+
81
+ export const CONFIG_DEFAULTS = {
82
+ leaseSeconds: 1800,
83
+ maxAttempts: 3,
84
+ gateWaitLevels: "24h,72h",
85
+ wsPort: 38291,
86
+ mcpHttpPort: 38292,
87
+ wsHistoryLimit: 200,
88
+ wsIntervalMs: 1000,
89
+ dispatchPort: 38293,
90
+ dispatchIntervalMs: 1000,
91
+ dispatchSweepMs: 30000,
92
+ maxActivePerAgent: 2,
93
+ dispatchHarnessMax: 8,
94
+ dispatchGlobalMax: 16,
95
+ dispatchOfferMs: 120000,
96
+ dispatchOfferBackoffMs: 30000,
97
+ dispatchOfferMaxBackoffMs: 300000,
98
+ dispatchOfferMaxAttempts: 5,
99
+ dispatchDeliveryBackoffMs: 30000,
100
+ dispatchDeliveryMaxBackoffMs: 300000,
101
+ dispatchDeliveryMaxAttempts: 5,
102
+ dispatchDeliveryFailureThreshold: 4,
103
+ dispatchDeliveryLeaseMs: 300000,
104
+ dispatchConsumerTtlMs: 90000,
105
+ webhookTimeoutMs: 3000,
106
+ scanLimit: 50,
107
+ candidates: 5,
108
+ blockedLimit: 20,
109
+ dfsNodes: 500,
110
+ noteProgressLimit: 2000,
111
+ noteResultLimit: 4000,
112
+ noteReasonLimit: 1000,
113
+ noteArtifactLimit: 500,
114
+ maxArtifacts: 50,
115
+ };
116
+
117
+ export const CONFIG_ENV = Object.fromEntries(
118
+ Object.entries(SPEC).map(([key, s]) => [key, s.env])
119
+ );
120
+
121
+ function refused(what, key, hint) {
122
+ throw new Error(`winch: refused ${what} (bad ${key}). ${hint}`);
123
+ }
124
+
125
+ function parseKey(key, raw, what) {
126
+ const spec = SPEC[key];
127
+ const parsed = spec.parse(raw);
128
+ if (parsed === null || !spec.check(parsed)) {
129
+ refused(what, key, `Expected ${key === "gateWaitLevels" ? "a duration list like \"24h,72h\"" : key === "wsPort" ? "a port 1-65535" : "a positive integer"} — got ${JSON.stringify(raw) ?? "nothing"}.`);
130
+ }
131
+ return parsed;
132
+ }
133
+
134
+ /**
135
+ * Construction-time config: explicit object wins, then WINCH_* env, then
136
+ * code defaults. Unknown explicit keys refuse — a typo'd knob must fail at
137
+ * startup, not run for a month at the default while the operator believes
138
+ * otherwise. Env carries only known vars, so there is nothing to reject there.
139
+ */
140
+ export function resolveConfig({ explicit = {}, env = process.env } = {}) {
141
+ if (explicit == null || typeof explicit !== "object" || Array.isArray(explicit)) {
142
+ refused("config", "config", "Pass an object keyed by knob name.");
143
+ }
144
+ for (const key of Object.keys(explicit)) {
145
+ if (!SPEC[key]) refused("config", key, `Unknown knob — known: ${Object.keys(SPEC).join(", ")}.`);
146
+ }
147
+ const out = {};
148
+ for (const [key, spec] of Object.entries(SPEC)) {
149
+ if (explicit[key] !== undefined) {
150
+ out[key] = parseKey(key, explicit[key], "config");
151
+ continue;
152
+ }
153
+ const envRaw = env?.[spec.env];
154
+ if (envRaw !== undefined && envRaw !== "") {
155
+ out[key] = parseKey(key, envRaw, `config (env ${spec.env})`);
156
+ continue;
157
+ }
158
+ out[key] = parseKey(key, CONFIG_DEFAULTS[key], "config");
159
+ }
160
+ return out;
161
+ }
162
+
163
+ /**
164
+ * Per-call overlay: `_meta.winch.config` merges over the construction
165
+ * config. Unknown keys are ignored (a newer harness stamping knobs an older
166
+ * server never heard of must not break the call); malformed known keys
167
+ * refuse the call, the way an unstamped identity does.
168
+ */
169
+ export function resolveRequestConfig(base, meta) {
170
+ const patch = meta?.winch?.config ?? null;
171
+ if (patch == null) return base;
172
+ if (typeof patch !== "object" || Array.isArray(patch)) {
173
+ refused("caller config", "config", "Pass an object keyed by knob name.");
174
+ }
175
+ const out = { ...base };
176
+ for (const [key, raw] of Object.entries(patch)) {
177
+ if (!SPEC[key] || raw === undefined) continue;
178
+ out[key] = parseKey(key, raw, "caller config");
179
+ }
180
+ return out;
181
+ }
package/src/db.js ADDED
@@ -0,0 +1,39 @@
1
+ // db.js — the better-sqlite3 connection and Drizzle client. Schema changes
2
+ // are generated into .migrations/ from src/schema.js and applied here on open.
3
+
4
+ import { existsSync, mkdirSync } from "node:fs";
5
+ import path from "node:path";
6
+ import Database from "better-sqlite3";
7
+ import { drizzle } from "drizzle-orm/better-sqlite3";
8
+ import { migrate } from "drizzle-orm/better-sqlite3/migrator";
9
+ import * as schema from "./schema.js";
10
+
11
+ const MIGRATIONS_FOLDER = path.join(import.meta.dirname, "..", ".migrations");
12
+
13
+ export function openDatabase({ dbPath, logger } = {}) {
14
+ const dir = path.dirname(dbPath);
15
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
16
+
17
+ const sqlite = new Database(dbPath);
18
+ sqlite.exec("PRAGMA journal_mode = WAL;");
19
+ sqlite.exec("PRAGMA foreign_keys = ON;");
20
+ sqlite.exec("PRAGMA busy_timeout = 5000;");
21
+
22
+ const orm = drizzle(sqlite, { schema });
23
+ // Migrations that rebuild a referenced table cannot run with enforcement on:
24
+ // SQLite ignores `PRAGMA foreign_keys=OFF` inside the migration transaction.
25
+ // Turn it off for the whole run, then prove the result is clean.
26
+ sqlite.exec("PRAGMA foreign_keys = OFF;");
27
+ try {
28
+ migrate(orm, { migrationsFolder: MIGRATIONS_FOLDER });
29
+ } finally {
30
+ sqlite.exec("PRAGMA foreign_keys = ON;");
31
+ }
32
+ const violations = sqlite.pragma("foreign_key_check");
33
+ if (violations.length > 0) {
34
+ throw new Error(`winch: migration left ${violations.length} foreign-key violation(s)`);
35
+ }
36
+
37
+ logger?.info?.(`backlog: store ready at ${dbPath}`);
38
+ return { sqlite, orm };
39
+ }
package/src/deps.js ADDED
@@ -0,0 +1,70 @@
1
+ // deps.js — dependency mutations with DAG cycle prevention.
2
+ //
3
+ // `addDep(store, from, to)` rejects with `{ok:false, code:"cycle", path:[...]}`
4
+ // if accepting the edge would create a cycle. We DFS forward from `to` over
5
+ // the existing item_edges graph; if we reach `from`, the new edge would close
6
+ // a loop. Depth-limited to avoid pathological graphs (500 nodes is plenty for
7
+ // any human-scale backlog).
8
+
9
+ const MAX_DFS_NODES = 500;
10
+
11
+ function reachable(store, startId, targetId) {
12
+ const cap = store.config?.dfsNodes ?? MAX_DFS_NODES;
13
+ if (startId === targetId) return [startId];
14
+ const seen = new Set([startId]);
15
+ const stack = [[startId, [startId]]];
16
+ let visited = 0;
17
+ while (stack.length) {
18
+ const [cur, trail] = stack.pop();
19
+ if (++visited > cap) return null;
20
+ const out = store.dep.listOutgoing(cur);
21
+ for (const edge of out) {
22
+ if (seen.has(edge.to_id)) continue;
23
+ if (edge.to_id === targetId) return [...trail, edge.to_id];
24
+ seen.add(edge.to_id);
25
+ stack.push([edge.to_id, [...trail, edge.to_id]]);
26
+ }
27
+ }
28
+ return null;
29
+ }
30
+
31
+ /**
32
+ * Add `from depends on to`. Rejects:
33
+ * - missing items
34
+ * - self-edge
35
+ * - duplicate edge (treated as ok / no-op)
36
+ * - would-be cycle
37
+ */
38
+ export function addDep(store, fromId, toId) {
39
+ if (fromId === toId) return { ok: false, code: "self_edge" };
40
+ const fromKind = store.itemKindOf(fromId);
41
+ const toKind = store.itemKindOf(toId);
42
+ if (!fromKind) return { ok: false, code: "from_not_found", id: fromId };
43
+ if (!toKind) return { ok: false, code: "to_not_found", id: toId };
44
+
45
+ // Would the new edge `from → to` create a cycle? It does iff there's an
46
+ // existing path `to → ... → from`. DFS from `to` looking for `from`.
47
+ const cyclePath = reachable(store, toId, fromId);
48
+ if (cyclePath) return { ok: false, code: "cycle", path: [fromId, ...cyclePath] };
49
+
50
+ store.dep.addRaw({ fromId, toId });
51
+ return { ok: true };
52
+ }
53
+
54
+ export function removeDep(store, fromId, toId) {
55
+ return store.dep.remove({ fromId, toId }) ? { ok: true } : { ok: false, code: "not_found" };
56
+ }
57
+
58
+ /**
59
+ * Are all dependencies of `id` resolved? Returns true iff every outgoing
60
+ * `id → other` has `other.status` in {done, cancelled}.
61
+ */
62
+ export function depsResolved(store, id) {
63
+ const out = store.dep.listOutgoing(id);
64
+ for (const edge of out) {
65
+ const item = store.item.get(edge.to_id, { includeDeleted: true });
66
+ if (!item) return false; // hard-deleted dep target = block (safer than ignoring)
67
+ if (item.status !== "done" && item.status !== "cancelled") return false;
68
+ }
69
+ return true;
70
+ }
@@ -0,0 +1,204 @@
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.
4
+
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";
10
+
11
+ export const DEFAULT_DISPATCH_PORT = 38293;
12
+
13
+ export function startDispatchServer({ store, port = null, host = "127.0.0.1", intervalMs = null, logger } = {}) {
14
+ const cfg = store.config ?? {};
15
+ const listenPort = port ?? cfg.dispatchPort ?? DEFAULT_DISPATCH_PORT;
16
+ const pollMs = intervalMs ?? cfg.dispatchIntervalMs ?? 1000;
17
+ const sweepMs = cfg.dispatchSweepMs ?? 30000;
18
+ const consumerTtlMs = cfg.dispatchConsumerTtlMs ?? 90000;
19
+ const histLimit = cfg.wsHistoryLimit ?? HISTORY_LIMIT;
20
+ const authToken = String(process.env.WINCH_DISPATCH_TOKEN ?? "").trim() || null;
21
+ const loopback = host === "127.0.0.1" || host === "::1" || host === "localhost";
22
+ if (!loopback && !authToken) {
23
+ throw new Error("winch: dispatch server refuses a non-loopback host without WINCH_DISPATCH_TOKEN");
24
+ }
25
+ let closing = false;
26
+ let pumping = false;
27
+
28
+ const pruneConsumers = () => {
29
+ try { store.webhook.prune({ topic: "dispatch", before: Date.now() - consumerTtlMs }); } catch {}
30
+ };
31
+ const sweeper = sweepMs > 0
32
+ ? setInterval(() => {
33
+ try { store.task.sweepExpired({}); } catch {}
34
+ pruneConsumers();
35
+ }, sweepMs)
36
+ : null;
37
+ sweeper?.unref?.();
38
+
39
+ store.admission.resetOffers();
40
+ pruneConsumers();
41
+ // Repair a queue written before write-time routing existed. `enqueue` is
42
+ // idempotent per event, so replaying tells the same story without minting a
43
+ // second wake for rows the write hook already admitted.
44
+ let since = 0;
45
+ const cursor = lastEventId(store);
46
+ for (;;) {
47
+ const rows = eventsSince(store, since, histLimit);
48
+ if (!rows.length) break;
49
+ for (const row of rows) observe(store, toEventMessage(store, row), Date.now());
50
+ since = rows[rows.length - 1].id;
51
+ if (since >= cursor) break;
52
+ }
53
+
54
+ function json(res, status, body) {
55
+ res.writeHead(status, { "content-type": "application/json" });
56
+ res.end(JSON.stringify(body));
57
+ }
58
+
59
+ function unauthorized(req) {
60
+ if (!authToken) return false;
61
+ const auth = req.headers?.authorization ?? "";
62
+ return auth !== `Bearer ${authToken}`;
63
+ }
64
+
65
+ async function readJson(req, res) {
66
+ let size = 0;
67
+ let raw = "";
68
+ for await (const chunk of req) {
69
+ size += chunk.length;
70
+ if (size > 1024 * 1024) {
71
+ json(res, 413, { error: "body too large" });
72
+ return undefined;
73
+ }
74
+ raw += chunk;
75
+ }
76
+ if (!raw) return {};
77
+ try {
78
+ return JSON.parse(raw);
79
+ } catch {
80
+ json(res, 400, { error: "invalid json body" });
81
+ return undefined;
82
+ }
83
+ }
84
+
85
+ async function pump() {
86
+ if (pumping) return;
87
+ pumping = true;
88
+ try {
89
+ pruneConsumers();
90
+ const offered = dispatchTick(store, {
91
+ at: Date.now(),
92
+ reachable: store.webhook.harnesses({ topic: "dispatch" }),
93
+ config: cfg,
94
+ });
95
+ for (const row of offered) await deliverWake(store, row, { config: cfg, logger });
96
+ await deliverDue(store, { config: cfg, logger });
97
+ } catch (err) {
98
+ logger?.warn?.(`winch: dispatch pump failed: ${err?.message ?? err}`);
99
+ } finally {
100
+ pumping = false;
101
+ }
102
+ }
103
+
104
+ const server = http.createServer(async (req, res) => {
105
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
106
+ if (req.method === "POST" && url.pathname === "/dispatch/register") {
107
+ if (unauthorized(req)) { json(res, 401, { error: "unauthorized" }); return; }
108
+ const body = await readJson(req, res);
109
+ if (body === undefined) return;
110
+ try {
111
+ const harness = typeof body.harness === "string" ? body.harness.trim() : "";
112
+ const executorId = typeof body.executorId === "string" ? body.executorId.trim() : "";
113
+ const consumerId = typeof body.consumerId === "string" ? body.consumerId.trim() : "";
114
+ const instanceId = typeof body.instanceId === "string" ? body.instanceId.trim() : "";
115
+ const fresh = body.fresh === true;
116
+ if (!harness || (!consumerId && !executorId)) throw new Error("dispatch registration requires harness and consumerId or executorId");
117
+ const id = consumerId || executorId;
118
+ const row = store.webhook.upsert({
119
+ topic: "dispatch",
120
+ id,
121
+ harness,
122
+ executorId: executorId || null,
123
+ instanceId: instanceId || executorId || id,
124
+ url: body.url,
125
+ bearer: body.bearer,
126
+ timeoutMs: body.timeoutMs ?? null,
127
+ leaseMs: consumerTtlMs,
128
+ managed: true,
129
+ fresh,
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
+ json(res, 201, {
136
+ ok: true, topic: row.topic, id: row.id, harness: row.harness,
137
+ executorId: row.executorId, instanceId: row.instanceId,
138
+ generation: row.generation, leaseUntil: row.leaseUntil,
139
+ });
140
+ void pump();
141
+ } catch (err) {
142
+ if (err instanceof StaleRegistrationError || err?.code === "stale_instance") {
143
+ const current = err.current
144
+ ? { instanceId: err.current.instanceId ?? null, generation: err.current.generation ?? null,
145
+ state: err.current.state ?? null, leaseUntil: err.current.leaseUntil ?? null }
146
+ : null;
147
+ json(res, 409, { error: String(err.message ?? err), code: "stale_instance", current });
148
+ } else {
149
+ json(res, 400, { error: String(err?.message ?? err) });
150
+ }
151
+ }
152
+ return;
153
+ }
154
+ if (req.method === "POST" && url.pathname === "/dispatch/notify") {
155
+ if (unauthorized(req)) { json(res, 401, { error: "unauthorized" }); return; }
156
+ req.resume();
157
+ json(res, 202, { ok: true });
158
+ void pump();
159
+ return;
160
+ }
161
+ if (req.method === "POST" && url.pathname === "/dispatch/recover") {
162
+ if (unauthorized(req)) { json(res, 401, { error: "unauthorized" }); return; }
163
+ const body = await readJson(req, res);
164
+ if (body === undefined) return;
165
+ try {
166
+ const result = recover(store, {
167
+ harness: String(body.harness ?? "").trim(),
168
+ consumerId: String(body.consumerId ?? "").trim() || null,
169
+ at: Date.now(),
170
+ config: cfg,
171
+ mutate: true,
172
+ });
173
+ json(res, 200, result);
174
+ } catch (err) {
175
+ json(res, 400, { error: String(err?.message ?? err) });
176
+ }
177
+ return;
178
+ }
179
+ json(res, 404, { error: "not found" });
180
+ });
181
+
182
+ const timer = setInterval(() => {
183
+ if (closing) return;
184
+ void pump();
185
+ }, pollMs);
186
+ if (typeof timer.unref === "function") timer.unref();
187
+
188
+ return new Promise((resolve, reject) => {
189
+ server.once("error", reject);
190
+ server.listen(listenPort, host, () => {
191
+ resolve({
192
+ port: server.address().port,
193
+ host,
194
+ close: () =>
195
+ new Promise((res) => {
196
+ closing = true;
197
+ clearInterval(timer);
198
+ if (sweeper) clearInterval(sweeper);
199
+ server.close(() => res());
200
+ }),
201
+ });
202
+ });
203
+ });
204
+ }