@cloop/runner 0.3.29 → 0.3.30

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.
@@ -1,220 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/wake.ts
4
- var WAKE_TICK_MS = 5e3;
5
- var SLEEP_GAP_MS = 3e4;
6
- var systemClocks = { wall: () => Date.now(), mono: () => performance.now() };
7
- function wakeWatch(clocks = systemClocks) {
8
- let wall = clocks.wall();
9
- let mono = clocks.mono();
10
- return () => {
11
- const nowWall = clocks.wall();
12
- const nowMono = clocks.mono();
13
- const gap = nowWall - wall - (nowMono - mono);
14
- wall = nowWall;
15
- mono = nowMono;
16
- return gap > SLEEP_GAP_MS ? { slept_ms: Math.round(gap), woke_at: new Date(nowWall).toISOString() } : null;
17
- };
18
- }
19
-
20
- // src/mesh-socket.ts
21
- var WS_OPEN = 1;
22
- function backoffDelay(attempt, { base = 1e3, max = 6e4, jitter = 0.2 } = {}, rand = Math.random) {
23
- const raw = Math.min(base * 2 ** attempt, max);
24
- const spread = raw * jitter;
25
- return Math.round(raw - spread + rand() * spread * 2);
26
- }
27
- var CALL_GRACE_MS = 15e3;
28
- var PING_RTT_MAX_MS = 1e4;
29
- var PING_CLOCKS_AGREE_MS = 1e3;
30
- function freshness(deadline, now, offset) {
31
- if (deadline === void 0 || offset === null) return "fresh";
32
- const meshNow = now + offset;
33
- if (meshNow <= deadline) return "fresh";
34
- return meshNow > deadline + CALL_GRACE_MS ? "expired" : "late";
35
- }
36
- function wsUrl(meshUrl, sessionKey, kind) {
37
- const base = meshUrl.replace(/^http/, "ws").replace(/\/+$/, "");
38
- const kindParam = kind && kind !== "agent" ? `&kind=${encodeURIComponent(kind)}` : "";
39
- return `${base}/mesh/agent?session_key=${encodeURIComponent(sessionKey)}${kindParam}`;
40
- }
41
- var MeshSocket = class {
42
- constructor(opts) {
43
- this.opts = opts;
44
- this.token = opts.token;
45
- }
46
- opts;
47
- ws = null;
48
- attempt = 0;
49
- timer = null;
50
- stopped = false;
51
- open = false;
52
- token;
53
- /** The newest beat the caller gave, sent again each time the socket opens. */
54
- presence = null;
55
- ping_ = null;
56
- offset = null;
57
- /** Connect again with a new device token, after a refusal of the old one. */
58
- restart(token) {
59
- this.token = token;
60
- this.attempt = 0;
61
- this.start();
62
- }
63
- /** Begin connecting (and keep reconnecting until close()). */
64
- start() {
65
- this.stopped = false;
66
- this.connect();
67
- }
68
- connect() {
69
- if (this.stopped) return;
70
- let ws;
71
- try {
72
- ws = this.opts.factory(wsUrl(this.opts.meshUrl, this.opts.sessionKey, this.opts.kind), [
73
- "cloop.v1",
74
- this.token
75
- ]);
76
- } catch {
77
- this.scheduleReconnect();
78
- return;
79
- }
80
- this.ws = ws;
81
- ws.on("open", () => {
82
- this.open = true;
83
- this.attempt = 0;
84
- if (this.presence) this.send({ type: "presence", ...this.presence });
85
- if (this.opts.kind === "workstation") this.ping();
86
- this.opts.onOpen?.();
87
- });
88
- ws.on("message", (data) => this.handleMessage(data));
89
- ws.on("close", (code) => {
90
- const wasOpen = this.open;
91
- this.open = false;
92
- if (wasOpen) this.opts.onClose?.(typeof code === "number" ? code : void 0);
93
- this.scheduleReconnect();
94
- });
95
- ws.on("error", (err) => {
96
- if (this.opts.onRefused && /Unexpected server response: 401\b/.test(String(err?.message))) {
97
- this.stopped = true;
98
- this.opts.onRefused();
99
- }
100
- });
101
- }
102
- handleMessage(data) {
103
- let frame;
104
- try {
105
- const text = typeof data === "string" ? data : String(data);
106
- frame = JSON.parse(text);
107
- } catch {
108
- return;
109
- }
110
- if (frame.type === "call") {
111
- if (frame.id && frame.tool) {
112
- this.opts.onCall?.({
113
- type: "call",
114
- id: frame.id,
115
- tool: frame.tool,
116
- args: frame.args ?? {},
117
- ...typeof frame.deadline === "number" && Number.isFinite(frame.deadline) ? { deadline: frame.deadline } : {}
118
- });
119
- }
120
- return;
121
- }
122
- if (frame.type === "ack") {
123
- if (frame.of === "ping") this.measureOffset(frame.now);
124
- else if (typeof frame.of === "string") this.opts.onAck?.(frame.of, frame.ok !== false);
125
- return;
126
- }
127
- if (frame.type === "result_ack") {
128
- if (typeof frame.id === "string") this.opts.onResultAck?.(frame.id);
129
- return;
130
- }
131
- if (frame.type !== "delegate" && frame.type !== "dm") return;
132
- this.opts.onMessage({
133
- type: frame.type,
134
- id: frame.id ?? "",
135
- at: frame.at ?? (/* @__PURE__ */ new Date()).toISOString(),
136
- ...frame.from ? { from: frame.from } : {},
137
- ...frame.type === "delegate" ? { task: frame.task } : { body: frame.body ?? "" }
138
- });
139
- }
140
- scheduleReconnect() {
141
- if (this.stopped || this.timer) return;
142
- const delay = backoffDelay(this.attempt, this.opts.backoff, this.opts.rand);
143
- this.attempt++;
144
- this.timer = setTimeout(() => {
145
- this.timer = null;
146
- this.connect();
147
- }, delay);
148
- this.timer.unref?.();
149
- }
150
- /**
151
- * Send a ping and time its round trip. Only a ping this socket sent and
152
- * timed measures the offset, never a queued call frame, whose delay is
153
- * exactly what the offset must not absorb.
154
- */
155
- ping() {
156
- const clocks = this.opts.clocks ?? systemClocks;
157
- const sent = { wall: clocks.wall(), mono: clocks.mono() };
158
- if (this.send({ type: "ping" })) this.ping_ = sent;
159
- }
160
- /** The mesh's clock minus this machine's, from the latest timed ping. Null until one answers with its clock. */
161
- clockOffset() {
162
- return this.offset;
163
- }
164
- measureOffset(meshNow) {
165
- const sent = this.ping_;
166
- this.ping_ = null;
167
- if (!sent || typeof meshNow !== "number" || !Number.isFinite(meshNow)) return;
168
- const clocks = this.opts.clocks ?? systemClocks;
169
- const rtt = clocks.mono() - sent.mono;
170
- const wallRtt = clocks.wall() - sent.wall;
171
- if (rtt < 0 || wallRtt > PING_RTT_MAX_MS || Math.abs(wallRtt - rtt) > PING_CLOCKS_AGREE_MS)
172
- return;
173
- this.offset = Math.round(meshNow - (sent.wall + rtt / 2));
174
- }
175
- isConnected() {
176
- return this.open && this.ws?.readyState === WS_OPEN;
177
- }
178
- /**
179
- * Send a presence beat over the socket. Returns false if not connected;
180
- * the socket still keeps the beat and sends it when it opens.
181
- */
182
- sendPresence(body) {
183
- this.presence = body;
184
- return this.send({ type: "presence", ...body });
185
- }
186
- /** Send any client frame. Returns false if not connected. */
187
- send(frame) {
188
- if (!this.isConnected() || !this.ws) return false;
189
- try {
190
- this.ws.send(JSON.stringify(frame));
191
- return true;
192
- } catch {
193
- return false;
194
- }
195
- }
196
- close() {
197
- this.stopped = true;
198
- this.open = false;
199
- if (this.timer) {
200
- clearTimeout(this.timer);
201
- this.timer = null;
202
- }
203
- try {
204
- this.ws?.close();
205
- } catch {
206
- }
207
- }
208
- };
209
- async function defaultSocketFactory() {
210
- const { WebSocket } = await import("ws");
211
- return (url, protocols) => new WebSocket(url, protocols);
212
- }
213
-
214
- export {
215
- WAKE_TICK_MS,
216
- wakeWatch,
217
- freshness,
218
- MeshSocket,
219
- defaultSocketFactory
220
- };