@firefunc-agent/runner 0.9.14 → 0.9.35
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/README.md +184 -10
- package/dist/alive.d.ts +40 -0
- package/dist/alive.js +138 -0
- package/dist/api-fallback.d.ts +4 -2
- package/dist/api-fallback.js +26 -1
- package/dist/api.d.ts +66 -3
- package/dist/api.js +164 -3
- package/dist/brief-file.d.ts +15 -0
- package/dist/brief-file.js +36 -0
- package/dist/brief.d.ts +3 -0
- package/dist/brief.js +14 -4
- package/dist/build-caches.d.ts +7 -0
- package/dist/build-caches.js +63 -0
- package/dist/build-info.json +2 -2
- package/dist/checkpoint.d.ts +40 -0
- package/dist/checkpoint.js +98 -0
- package/dist/cli.js +184 -18
- package/dist/cloud-boot.d.ts +41 -0
- package/dist/cloud-boot.js +239 -0
- package/dist/command-activity.d.ts +23 -0
- package/dist/command-activity.js +89 -0
- package/dist/command-step.d.ts +58 -0
- package/dist/command-step.js +248 -0
- package/dist/config.d.ts +39 -0
- package/dist/config.js +23 -0
- package/dist/cut.d.ts +1 -1
- package/dist/cut.js +13 -3
- package/dist/daemon.js +364 -15
- package/dist/device-lease.d.ts +15 -0
- package/dist/device-lease.js +608 -0
- package/dist/editor/fs-server.d.ts +31 -0
- package/dist/editor/fs-server.js +159 -0
- package/dist/editor/relay-crypto.d.ts +68 -0
- package/dist/editor/relay-crypto.js +191 -0
- package/dist/editor/sessions.d.ts +50 -0
- package/dist/editor/sessions.js +279 -0
- package/dist/editor/worktree-of.d.ts +1 -0
- package/dist/editor/worktree-of.js +23 -0
- package/dist/editor/ws-client.d.ts +26 -0
- package/dist/editor/ws-client.js +227 -0
- package/dist/engine-account.d.ts +24 -0
- package/dist/engine-account.js +118 -0
- package/dist/engine-login.d.ts +12 -0
- package/dist/engine-login.js +88 -0
- package/dist/engine-models.d.ts +13 -0
- package/dist/engine-models.js +71 -0
- package/dist/engine-watch.d.ts +1 -0
- package/dist/engine-watch.js +22 -6
- package/dist/engines/antigravity.d.ts +2 -0
- package/dist/engines/antigravity.js +74 -4
- package/dist/engines/claude.js +22 -9
- package/dist/engines/codex.js +16 -2
- package/dist/engines/copilot.js +12 -0
- package/dist/engines/crush.d.ts +2 -0
- package/dist/engines/crush.js +58 -0
- package/dist/engines/cursor.js +12 -0
- package/dist/engines/gemini.js +14 -9
- package/dist/engines/index.d.ts +8 -0
- package/dist/engines/index.js +73 -1
- package/dist/engines/kilo.d.ts +2 -0
- package/dist/engines/kilo.js +63 -0
- package/dist/engines/opencode.d.ts +9 -0
- package/dist/engines/opencode.js +234 -0
- package/dist/engines/openhands.d.ts +10 -0
- package/dist/engines/openhands.js +271 -0
- package/dist/engines/pi.d.ts +10 -0
- package/dist/engines/pi.js +248 -0
- package/dist/engines/qwen.d.ts +8 -0
- package/dist/engines/qwen.js +153 -0
- package/dist/engines/sessions.d.ts +6 -0
- package/dist/engines/sessions.js +68 -0
- package/dist/engines/types.d.ts +3 -3
- package/dist/exec.d.ts +1 -0
- package/dist/exec.js +10 -4
- package/dist/firefunc/agents.d.ts +8 -1
- package/dist/firefunc/agents.js +53 -3
- package/dist/firefunc/auth.js +72 -19
- package/dist/firefunc/automations.d.ts +2 -0
- package/dist/firefunc/automations.js +290 -0
- package/dist/firefunc/cli.js +25 -0
- package/dist/firefunc/client.d.ts +5 -1
- package/dist/firefunc/client.js +12 -2
- package/dist/firefunc/config.d.ts +11 -1
- package/dist/firefunc/config.js +6 -4
- package/dist/firefunc/io.d.ts +1 -0
- package/dist/firefunc/main.js +34 -2
- package/dist/firefunc/oauth-login.d.ts +23 -0
- package/dist/firefunc/oauth-login.js +304 -0
- package/dist/firefunc/tasks.d.ts +4 -0
- package/dist/firefunc/tasks.js +89 -2
- package/dist/fleet-words.d.ts +2 -0
- package/dist/fleet-words.js +7 -0
- package/dist/git-auth.d.ts +15 -0
- package/dist/git-auth.js +39 -1
- package/dist/held.d.ts +3 -0
- package/dist/job.d.ts +26 -3
- package/dist/job.js +763 -152
- package/dist/keep-awake.d.ts +17 -0
- package/dist/keep-awake.js +90 -0
- package/dist/keep-local.d.ts +1 -1
- package/dist/keep-local.js +5 -3
- package/dist/limit.d.ts +9 -1
- package/dist/limit.js +260 -3
- package/dist/local-checks.d.ts +19 -0
- package/dist/local-checks.js +79 -0
- package/dist/locks.d.ts +18 -1
- package/dist/locks.js +249 -69
- package/dist/machine-commands.d.ts +21 -0
- package/dist/machine-commands.js +107 -0
- package/dist/machine-profile.d.ts +18 -0
- package/dist/machine-profile.js +69 -0
- package/dist/mcp-init.d.ts +2 -0
- package/dist/mcp-init.js +28 -0
- package/dist/mcp.d.ts +13 -1
- package/dist/mcp.js +48 -4
- package/dist/network.js +3 -2
- package/dist/openrouter.d.ts +15 -0
- package/dist/openrouter.js +39 -0
- package/dist/orphans.d.ts +4 -0
- package/dist/orphans.js +96 -4
- package/dist/pool.d.ts +1 -0
- package/dist/pool.js +25 -2
- package/dist/pr-title.d.ts +10 -0
- package/dist/pr-title.js +15 -0
- package/dist/recover.d.ts +3 -1
- package/dist/recover.js +27 -7
- package/dist/release-draft.d.ts +79 -0
- package/dist/release-draft.js +301 -0
- package/dist/resources.d.ts +86 -0
- package/dist/resources.js +217 -0
- package/dist/restart-idle.d.ts +23 -0
- package/dist/restart-idle.js +67 -0
- package/dist/run-attachments.d.ts +5 -0
- package/dist/run-attachments.js +14 -9
- package/dist/run-stops.d.ts +15 -0
- package/dist/run-stops.js +90 -0
- package/dist/run-temp.d.ts +12 -0
- package/dist/run-temp.js +57 -0
- package/dist/secret-scan.d.ts +5 -0
- package/dist/secret-scan.js +30 -0
- package/dist/self-upgrade.d.ts +36 -0
- package/dist/self-upgrade.js +78 -0
- package/dist/service.d.ts +7 -1
- package/dist/service.js +50 -7
- package/dist/sign-in.d.ts +42 -0
- package/dist/sign-in.js +243 -0
- package/dist/tool-call.d.ts +59 -0
- package/dist/tool-call.js +375 -0
- package/dist/transport.d.ts +26 -0
- package/dist/transport.js +118 -0
- package/dist/work-dir.d.ts +11 -0
- package/dist/work-dir.js +69 -0
- package/dist/worktree-report.d.ts +10 -0
- package/dist/worktree-report.js +17 -0
- package/dist/worktrees.d.ts +16 -1
- package/dist/worktrees.js +62 -17
- package/package.json +4 -4
- package/skill/firefunc/SKILL.md +22 -3
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { FolderServer } from './fs-server.js';
|
|
3
|
+
import { SecureChannel, acceptText, deriveSession, joinText, newSessionKey, relayControl, signWith, verifyWith, } from './relay-crypto.js';
|
|
4
|
+
import { connectWebSocket } from './ws-client.js';
|
|
5
|
+
export const MAX_EDITOR_SESSIONS = 4;
|
|
6
|
+
const CEILING_MS = 8 * 60 * 60_000;
|
|
7
|
+
const PING_MS = 60_000;
|
|
8
|
+
export function readOffer(raw) {
|
|
9
|
+
const o = raw;
|
|
10
|
+
if (!o || typeof o !== 'object')
|
|
11
|
+
return null;
|
|
12
|
+
const str = (k) => (typeof o[k] === 'string' ? o[k] : null);
|
|
13
|
+
const state = str('state');
|
|
14
|
+
if (state !== 'joined' && state !== 'open' && state !== 'ended')
|
|
15
|
+
return null;
|
|
16
|
+
const grantId = str('grantId');
|
|
17
|
+
const runId = str('runId');
|
|
18
|
+
if (!grantId || !runId)
|
|
19
|
+
return null;
|
|
20
|
+
return {
|
|
21
|
+
grantId,
|
|
22
|
+
runId,
|
|
23
|
+
taskId: str('taskId') ?? '',
|
|
24
|
+
state,
|
|
25
|
+
editor: str('editor') ?? 'an editor',
|
|
26
|
+
by: str('by'),
|
|
27
|
+
editorPublicKey: str('editorPublicKey') ?? '',
|
|
28
|
+
editorSignature: str('editorSignature') ?? '',
|
|
29
|
+
editorIdentityKey: str('editorIdentityKey') ?? '',
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const EDITOR_WORD = {
|
|
33
|
+
vscode: 'VS Code',
|
|
34
|
+
cursor: 'Cursor',
|
|
35
|
+
windsurf: 'Windsurf',
|
|
36
|
+
jetbrains: 'JetBrains',
|
|
37
|
+
};
|
|
38
|
+
export function createEditorSessions(deps) {
|
|
39
|
+
const dial = deps.dial ?? ((url, h) => connectWebSocket(url, h));
|
|
40
|
+
const now = deps.now ?? Date.now;
|
|
41
|
+
const live = new Map();
|
|
42
|
+
const handled = new Set();
|
|
43
|
+
const who = (o) => `${o.by ?? 'Someone'} in ${EDITOR_WORD[o.editor] ?? o.editor}`;
|
|
44
|
+
const close = (grantId, why, tell) => {
|
|
45
|
+
const s = live.get(grantId);
|
|
46
|
+
if (!s)
|
|
47
|
+
return;
|
|
48
|
+
s.closing = true;
|
|
49
|
+
live.delete(grantId);
|
|
50
|
+
clearInterval(s.ping);
|
|
51
|
+
s.stopWatch();
|
|
52
|
+
try {
|
|
53
|
+
if (s.conn?.open)
|
|
54
|
+
s.conn.send(s.channel.send({ t: 'bye', reason: why }));
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
}
|
|
58
|
+
s.conn?.close(1000, 'ended');
|
|
59
|
+
deps.log(`editor session closed: ${who(s.offer)} · ${why}`);
|
|
60
|
+
if (tell)
|
|
61
|
+
void deps.api.endEditorGrant(grantId, tell).catch(() => false);
|
|
62
|
+
};
|
|
63
|
+
const onText = (s, text) => {
|
|
64
|
+
const control = relayControl(text);
|
|
65
|
+
if (control) {
|
|
66
|
+
if (control === 'ended')
|
|
67
|
+
close(s.offer.grantId, 'its time ran out', 'runner_ended');
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const got = s.channel.receive(text);
|
|
71
|
+
if (got.kind === 'skip')
|
|
72
|
+
return;
|
|
73
|
+
if (got.kind === 'fail') {
|
|
74
|
+
close(s.offer.grantId, 'a message failed its check, so the session was ended', 'runner_ended');
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const m = got.message;
|
|
78
|
+
const reply = (msg) => {
|
|
79
|
+
try {
|
|
80
|
+
s.conn?.send(s.channel.send(msg));
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
if (m.t === 'hello') {
|
|
86
|
+
const folder = s.server.root.split(/[\\/]/).filter(Boolean).pop() ?? '';
|
|
87
|
+
reply({ t: 'welcome', v: 1, machine: deps.machineName, folder, readOnly: true });
|
|
88
|
+
}
|
|
89
|
+
else if (m.t === 'req' && typeof m.id === 'number') {
|
|
90
|
+
const id = m.id;
|
|
91
|
+
let frame;
|
|
92
|
+
try {
|
|
93
|
+
frame = s.channel.send({ t: 'res', id, ...s.server.handle(m) });
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
frame = s.channel.send({
|
|
97
|
+
t: 'res',
|
|
98
|
+
id,
|
|
99
|
+
ok: false,
|
|
100
|
+
error: {
|
|
101
|
+
code: 'Unavailable',
|
|
102
|
+
message: 'That folder has too many entries to list through the relay.',
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
s.conn?.send(frame);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
else if (m.t === 'ping') {
|
|
113
|
+
reply({ t: 'pong' });
|
|
114
|
+
}
|
|
115
|
+
else if (m.t === 'bye') {
|
|
116
|
+
close(s.offer.grantId, 'the editor closed');
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const connect = async (s, relay, attempt = 0) => {
|
|
120
|
+
const url = `${relay.url}${relay.url.includes('?') ? '&' : '?'}t=${encodeURIComponent(relay.ticket)}`;
|
|
121
|
+
try {
|
|
122
|
+
s.conn = await dial(url, {
|
|
123
|
+
onMessage: (text) => onText(s, text),
|
|
124
|
+
onClose: () => {
|
|
125
|
+
s.conn = null;
|
|
126
|
+
if (s.closing || !live.has(s.offer.grantId))
|
|
127
|
+
return;
|
|
128
|
+
if (now() - s.openedAt > CEILING_MS) {
|
|
129
|
+
close(s.offer.grantId, 'eight hours passed', 'runner_ended');
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
void reconnect(s, 0);
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
if (attempt >= 4) {
|
|
138
|
+
close(s.offer.grantId, `could not reach the relay (${err.message})`, 'runner_ended');
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
await reconnect(s, attempt + 1);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
const reconnect = async (s, attempt) => {
|
|
145
|
+
await new Promise((r) => setTimeout(r, Math.min(2_000 * 2 ** attempt, 30_000)));
|
|
146
|
+
if (s.closing || !live.has(s.offer.grantId))
|
|
147
|
+
return;
|
|
148
|
+
const relay = await deps.api.editorTicket(s.offer.grantId).catch(() => null);
|
|
149
|
+
if (!relay) {
|
|
150
|
+
if (attempt >= 4)
|
|
151
|
+
close(s.offer.grantId, 'FireFunc gave no new relay ticket', 'runner_ended');
|
|
152
|
+
else
|
|
153
|
+
await reconnect(s, attempt + 1);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
await connect(s, relay, attempt);
|
|
157
|
+
};
|
|
158
|
+
const refuse = (o, reason, words) => {
|
|
159
|
+
deps.log(`editor session refused: ${who(o)} · ${words}`);
|
|
160
|
+
void deps.api.refuseEditorGrant(o.grantId, reason).catch(() => false);
|
|
161
|
+
};
|
|
162
|
+
const start = async (o) => {
|
|
163
|
+
if (!deps.allowed()) {
|
|
164
|
+
refuse(o, 'editor_off', 'editors are off here (firefunc-runner config set devMode.editor on)');
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (live.size >= MAX_EDITOR_SESSIONS) {
|
|
168
|
+
refuse(o, 'busy', `${MAX_EDITOR_SESSIONS} editor sessions are open already`);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (!verifyWith(o.editorIdentityKey, joinText(o.grantId, o.editorPublicKey), o.editorSignature)) {
|
|
172
|
+
refuse(o, 'bad_signature', 'the editor’s key is not signed by its pairing key');
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const root = deps.worktreeOf(o.runId);
|
|
176
|
+
let server;
|
|
177
|
+
try {
|
|
178
|
+
if (!root || !existsSync(root))
|
|
179
|
+
throw new Error('gone');
|
|
180
|
+
server = new FolderServer(root);
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
refuse(o, 'no_folder', 'the run’s folder is not on this machine any more');
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const own = newSessionKey();
|
|
187
|
+
const keys = deriveSession({
|
|
188
|
+
grantId: o.grantId,
|
|
189
|
+
side: 'runner',
|
|
190
|
+
own,
|
|
191
|
+
editorPublicKey: o.editorPublicKey,
|
|
192
|
+
runnerPublicKey: own.publicKey,
|
|
193
|
+
});
|
|
194
|
+
if (!keys) {
|
|
195
|
+
refuse(o, 'bad_signature', 'the editor’s session key is not one this runner can use');
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const machine = deps.machineKey();
|
|
199
|
+
const relay = await deps.api
|
|
200
|
+
.acceptEditorGrant(o.grantId, {
|
|
201
|
+
publicKey: own.publicKey,
|
|
202
|
+
signature: signWith(machine.privateKey, acceptText(o.grantId, o.editorPublicKey, own.publicKey)),
|
|
203
|
+
machineKey: machine.publicKey,
|
|
204
|
+
})
|
|
205
|
+
.catch(() => null);
|
|
206
|
+
if (!relay) {
|
|
207
|
+
deps.log(`editor session not opened: ${who(o)} · FireFunc did not take this machine’s answer`);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
const s = {
|
|
211
|
+
offer: o,
|
|
212
|
+
channel: new SecureChannel(keys),
|
|
213
|
+
server,
|
|
214
|
+
conn: null,
|
|
215
|
+
stopWatch: () => { },
|
|
216
|
+
ping: setInterval(() => {
|
|
217
|
+
if (!deps.allowed()) {
|
|
218
|
+
close(o.grantId, 'editors were turned off on this machine', 'runner_ended');
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
try {
|
|
222
|
+
if (s.conn?.open)
|
|
223
|
+
s.conn.send(s.channel.send({ t: 'ping' }));
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
}
|
|
227
|
+
}, PING_MS),
|
|
228
|
+
openedAt: now(),
|
|
229
|
+
closing: false,
|
|
230
|
+
check: keys.check,
|
|
231
|
+
};
|
|
232
|
+
s.ping.unref?.();
|
|
233
|
+
live.set(o.grantId, s);
|
|
234
|
+
s.stopWatch = server.watch((paths) => {
|
|
235
|
+
try {
|
|
236
|
+
if (s.conn?.open)
|
|
237
|
+
s.conn.send(s.channel.send({ t: 'changed', paths }));
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
deps.log(`editor session open: ${who(o)} · read-only · ${server.root} · session check ${keys.check}`);
|
|
243
|
+
await connect(s, relay);
|
|
244
|
+
};
|
|
245
|
+
return {
|
|
246
|
+
take(list) {
|
|
247
|
+
for (const raw of list) {
|
|
248
|
+
const o = readOffer(raw);
|
|
249
|
+
if (!o)
|
|
250
|
+
continue;
|
|
251
|
+
if (o.state === 'ended') {
|
|
252
|
+
handled.add(o.grantId);
|
|
253
|
+
close(o.grantId, 'FireFunc ended it');
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
if (handled.has(o.grantId))
|
|
257
|
+
continue;
|
|
258
|
+
handled.add(o.grantId);
|
|
259
|
+
if (o.state === 'joined') {
|
|
260
|
+
void start(o).catch((err) => deps.log(`editor session failed: ${err.message}`));
|
|
261
|
+
}
|
|
262
|
+
else if (!live.has(o.grantId)) {
|
|
263
|
+
void deps.api.endEditorGrant(o.grantId, 'runner_ended').catch(() => false);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
active() {
|
|
268
|
+
return live.size;
|
|
269
|
+
},
|
|
270
|
+
checkOf(grantId) {
|
|
271
|
+
return live.get(grantId)?.check ?? null;
|
|
272
|
+
},
|
|
273
|
+
closeAll(why = 'the runner stopped') {
|
|
274
|
+
for (const id of [...live.keys()])
|
|
275
|
+
close(id, why, 'runner_ended');
|
|
276
|
+
},
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
//# sourceMappingURL=sessions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function worktreeOfRun(runnerDir: string, runId: string): string | null;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { listKept } from '../ask-first.js';
|
|
3
|
+
import { listCuts } from '../cut.js';
|
|
4
|
+
import { listHeld } from '../held.js';
|
|
5
|
+
import { isAlive } from '../orphans.js';
|
|
6
|
+
export function worktreeOfRun(runnerDir, runId) {
|
|
7
|
+
const candidates = [
|
|
8
|
+
...listHeld(runnerDir)
|
|
9
|
+
.filter((h) => h.runId === runId && isAlive(h.pid))
|
|
10
|
+
.map((h) => h.worktree),
|
|
11
|
+
...listKept(runnerDir)
|
|
12
|
+
.filter((k) => k.runId === runId)
|
|
13
|
+
.map((k) => k.worktree),
|
|
14
|
+
...listCuts(runnerDir)
|
|
15
|
+
.filter((c) => c.runId === runId)
|
|
16
|
+
.map((c) => c.worktree),
|
|
17
|
+
];
|
|
18
|
+
for (const p of candidates)
|
|
19
|
+
if (p && existsSync(p))
|
|
20
|
+
return p;
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=worktree-of.js.map
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export declare const MAX_MESSAGE: number;
|
|
2
|
+
export type Frame = {
|
|
3
|
+
fin: boolean;
|
|
4
|
+
opcode: number;
|
|
5
|
+
payload: Buffer;
|
|
6
|
+
};
|
|
7
|
+
export declare function encodeFrame(opcode: number, payload: Buffer, mask?: boolean, fin?: boolean): Buffer;
|
|
8
|
+
export declare function decodeFrames(buf: Buffer): {
|
|
9
|
+
frames: Frame[];
|
|
10
|
+
rest: Buffer;
|
|
11
|
+
error?: string;
|
|
12
|
+
};
|
|
13
|
+
export type WsHandlers = {
|
|
14
|
+
onMessage: (text: string) => void;
|
|
15
|
+
onClose: (code: number, reason: string) => void;
|
|
16
|
+
};
|
|
17
|
+
export type WsConnection = {
|
|
18
|
+
send: (text: string) => void;
|
|
19
|
+
close: (code?: number, reason?: string) => void;
|
|
20
|
+
readonly open: boolean;
|
|
21
|
+
};
|
|
22
|
+
export declare function dialable(url: string): boolean;
|
|
23
|
+
export declare function connectWebSocket(url: string, handlers: WsHandlers, opts?: {
|
|
24
|
+
timeoutMs?: number;
|
|
25
|
+
userAgent?: string;
|
|
26
|
+
}): Promise<WsConnection>;
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
2
|
+
import { request as httpRequest } from 'node:http';
|
|
3
|
+
import { request as httpsRequest } from 'node:https';
|
|
4
|
+
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
5
|
+
export const MAX_MESSAGE = 128 * 1024;
|
|
6
|
+
export function encodeFrame(opcode, payload, mask = true, fin = true) {
|
|
7
|
+
const len = payload.length;
|
|
8
|
+
const head = [(fin ? 0x80 : 0) | (opcode & 0x0f)];
|
|
9
|
+
const maskBit = mask ? 0x80 : 0;
|
|
10
|
+
let ext;
|
|
11
|
+
if (len < 126) {
|
|
12
|
+
head.push(maskBit | len);
|
|
13
|
+
ext = Buffer.alloc(0);
|
|
14
|
+
}
|
|
15
|
+
else if (len < 65536) {
|
|
16
|
+
head.push(maskBit | 126);
|
|
17
|
+
ext = Buffer.alloc(2);
|
|
18
|
+
ext.writeUInt16BE(len);
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
head.push(maskBit | 127);
|
|
22
|
+
ext = Buffer.alloc(8);
|
|
23
|
+
ext.writeBigUInt64BE(BigInt(len));
|
|
24
|
+
}
|
|
25
|
+
if (!mask)
|
|
26
|
+
return Buffer.concat([Buffer.from(head), ext, payload]);
|
|
27
|
+
const key = randomBytes(4);
|
|
28
|
+
const body = Buffer.alloc(len);
|
|
29
|
+
for (let i = 0; i < len; i++)
|
|
30
|
+
body[i] = payload[i] ^ key[i % 4];
|
|
31
|
+
return Buffer.concat([Buffer.from(head), ext, key, body]);
|
|
32
|
+
}
|
|
33
|
+
export function decodeFrames(buf) {
|
|
34
|
+
const frames = [];
|
|
35
|
+
let off = 0;
|
|
36
|
+
while (buf.length - off >= 2) {
|
|
37
|
+
const b0 = buf[off];
|
|
38
|
+
const b1 = buf[off + 1];
|
|
39
|
+
if (b0 & 0x70)
|
|
40
|
+
return { frames, rest: Buffer.alloc(0), error: 'reserved bits set' };
|
|
41
|
+
const masked = (b1 & 0x80) !== 0;
|
|
42
|
+
let len = b1 & 0x7f;
|
|
43
|
+
let p = off + 2;
|
|
44
|
+
if (len === 126) {
|
|
45
|
+
if (buf.length - p < 2)
|
|
46
|
+
break;
|
|
47
|
+
len = buf.readUInt16BE(p);
|
|
48
|
+
p += 2;
|
|
49
|
+
}
|
|
50
|
+
else if (len === 127) {
|
|
51
|
+
if (buf.length - p < 8)
|
|
52
|
+
break;
|
|
53
|
+
const big = buf.readBigUInt64BE(p);
|
|
54
|
+
if (big > BigInt(MAX_MESSAGE))
|
|
55
|
+
return { frames, rest: Buffer.alloc(0), error: 'frame too large' };
|
|
56
|
+
len = Number(big);
|
|
57
|
+
p += 8;
|
|
58
|
+
}
|
|
59
|
+
if (len > MAX_MESSAGE)
|
|
60
|
+
return { frames, rest: Buffer.alloc(0), error: 'frame too large' };
|
|
61
|
+
let key = null;
|
|
62
|
+
if (masked) {
|
|
63
|
+
if (buf.length - p < 4)
|
|
64
|
+
break;
|
|
65
|
+
key = buf.subarray(p, p + 4);
|
|
66
|
+
p += 4;
|
|
67
|
+
}
|
|
68
|
+
if (buf.length - p < len)
|
|
69
|
+
break;
|
|
70
|
+
const payload = Buffer.from(buf.subarray(p, p + len));
|
|
71
|
+
if (key)
|
|
72
|
+
for (let i = 0; i < payload.length; i++)
|
|
73
|
+
payload[i] = payload[i] ^ key[i % 4];
|
|
74
|
+
frames.push({ fin: (b0 & 0x80) !== 0, opcode: b0 & 0x0f, payload });
|
|
75
|
+
off = p + len;
|
|
76
|
+
}
|
|
77
|
+
return { frames, rest: Buffer.from(buf.subarray(off)) };
|
|
78
|
+
}
|
|
79
|
+
export function dialable(url) {
|
|
80
|
+
try {
|
|
81
|
+
const u = new URL(url);
|
|
82
|
+
if (u.protocol === 'wss:')
|
|
83
|
+
return true;
|
|
84
|
+
return u.protocol === 'ws:' && (u.hostname === '127.0.0.1' || u.hostname === 'localhost');
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
export function connectWebSocket(url, handlers, opts = {}) {
|
|
91
|
+
if (!dialable(url))
|
|
92
|
+
return Promise.reject(new Error('refused: only wss:// is dialled'));
|
|
93
|
+
const u = new URL(url);
|
|
94
|
+
const key = randomBytes(16).toString('base64');
|
|
95
|
+
const expected = createHash('sha1')
|
|
96
|
+
.update(key + GUID)
|
|
97
|
+
.digest('base64');
|
|
98
|
+
const req = (u.protocol === 'wss:' ? httpsRequest : httpRequest)({
|
|
99
|
+
host: u.hostname,
|
|
100
|
+
port: u.port || (u.protocol === 'wss:' ? 443 : 80),
|
|
101
|
+
path: `${u.pathname || '/'}${u.search}`,
|
|
102
|
+
method: 'GET',
|
|
103
|
+
headers: {
|
|
104
|
+
Connection: 'Upgrade',
|
|
105
|
+
Upgrade: 'websocket',
|
|
106
|
+
'Sec-WebSocket-Version': '13',
|
|
107
|
+
'Sec-WebSocket-Key': key,
|
|
108
|
+
...(opts.userAgent ? { 'User-Agent': opts.userAgent } : {}),
|
|
109
|
+
},
|
|
110
|
+
...(u.protocol === 'wss:' ? { servername: u.hostname } : {}),
|
|
111
|
+
});
|
|
112
|
+
return new Promise((resolve, reject) => {
|
|
113
|
+
const timer = setTimeout(() => {
|
|
114
|
+
req.destroy(new Error('timed out connecting to the relay'));
|
|
115
|
+
}, opts.timeoutMs ?? 15_000);
|
|
116
|
+
req.on('error', (err) => {
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
reject(err);
|
|
119
|
+
});
|
|
120
|
+
req.on('response', (res) => {
|
|
121
|
+
clearTimeout(timer);
|
|
122
|
+
res.resume();
|
|
123
|
+
reject(new Error(`the relay refused the connection (${res.statusCode})`));
|
|
124
|
+
});
|
|
125
|
+
req.on('upgrade', (res, socket, head) => {
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
if (res.headers['sec-websocket-accept'] !== expected) {
|
|
128
|
+
socket.destroy();
|
|
129
|
+
reject(new Error('the relay answered the upgrade wrongly'));
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
resolve(attach(socket, head, handlers));
|
|
133
|
+
});
|
|
134
|
+
req.end();
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
function attach(socket, head, handlers) {
|
|
138
|
+
let buf = Buffer.from(head);
|
|
139
|
+
let parts = [];
|
|
140
|
+
let partsLen = 0;
|
|
141
|
+
let open = true;
|
|
142
|
+
let closed = false;
|
|
143
|
+
socket.setNoDelay(true);
|
|
144
|
+
const finish = (code, reason) => {
|
|
145
|
+
if (closed)
|
|
146
|
+
return;
|
|
147
|
+
closed = true;
|
|
148
|
+
open = false;
|
|
149
|
+
socket.destroy();
|
|
150
|
+
handlers.onClose(code, reason);
|
|
151
|
+
};
|
|
152
|
+
const write = (opcode, payload) => {
|
|
153
|
+
if (!socket.destroyed)
|
|
154
|
+
socket.write(encodeFrame(opcode, payload));
|
|
155
|
+
};
|
|
156
|
+
const onData = (chunk) => {
|
|
157
|
+
buf = buf.length ? Buffer.concat([buf, chunk]) : chunk;
|
|
158
|
+
const { frames, rest, error } = decodeFrames(buf);
|
|
159
|
+
buf = rest;
|
|
160
|
+
for (const f of frames) {
|
|
161
|
+
if (f.opcode === 0x8) {
|
|
162
|
+
const code = f.payload.length >= 2 ? f.payload.readUInt16BE(0) : 1005;
|
|
163
|
+
const reason = f.payload.length > 2 ? f.payload.subarray(2).toString('utf8') : '';
|
|
164
|
+
if (open)
|
|
165
|
+
write(0x8, f.payload.subarray(0, 2));
|
|
166
|
+
finish(code, reason);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (f.opcode === 0x9) {
|
|
170
|
+
write(0xa, f.payload);
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (f.opcode === 0xa)
|
|
174
|
+
continue;
|
|
175
|
+
if (f.opcode === 0x2) {
|
|
176
|
+
write(0x8, Buffer.from([0x03, 0xeb]));
|
|
177
|
+
finish(1003, 'binary frames are not accepted');
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (f.opcode === 0x1 || f.opcode === 0x0) {
|
|
181
|
+
parts.push(f.payload);
|
|
182
|
+
partsLen += f.payload.length;
|
|
183
|
+
if (partsLen > MAX_MESSAGE) {
|
|
184
|
+
finish(1009, 'message too large');
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (f.fin) {
|
|
188
|
+
const text = Buffer.concat(parts).toString('utf8');
|
|
189
|
+
parts = [];
|
|
190
|
+
partsLen = 0;
|
|
191
|
+
handlers.onMessage(text);
|
|
192
|
+
}
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
finish(1002, `unknown opcode ${f.opcode}`);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (error)
|
|
199
|
+
finish(1002, error);
|
|
200
|
+
};
|
|
201
|
+
socket.on('data', onData);
|
|
202
|
+
socket.on('close', () => finish(1006, 'connection lost'));
|
|
203
|
+
socket.on('error', () => finish(1006, 'connection lost'));
|
|
204
|
+
if (buf.length)
|
|
205
|
+
setImmediate(() => onData(Buffer.alloc(0)));
|
|
206
|
+
return {
|
|
207
|
+
send(text) {
|
|
208
|
+
if (!open)
|
|
209
|
+
throw new Error('the relay connection is closed');
|
|
210
|
+
write(0x1, Buffer.from(text, 'utf8'));
|
|
211
|
+
},
|
|
212
|
+
close(code = 1000, reason = '') {
|
|
213
|
+
if (!open)
|
|
214
|
+
return;
|
|
215
|
+
open = false;
|
|
216
|
+
const p = Buffer.alloc(2 + Buffer.byteLength(reason));
|
|
217
|
+
p.writeUInt16BE(code);
|
|
218
|
+
p.write(reason, 2);
|
|
219
|
+
write(0x8, p);
|
|
220
|
+
setTimeout(() => finish(code, reason), 500).unref?.();
|
|
221
|
+
},
|
|
222
|
+
get open() {
|
|
223
|
+
return open;
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
//# sourceMappingURL=ws-client.js.map
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { EngineEnding } from './declined.js';
|
|
2
|
+
import type { EngineId, UnattendedBlock } from './engines/types.js';
|
|
3
|
+
export type AccountProblem = 'not_signed_in' | 'api_key_no_credit';
|
|
4
|
+
export declare const ACCOUNT_RETRY_FIRST_MS: number;
|
|
5
|
+
export declare const ACCOUNT_RETRY_MAX_MS: number;
|
|
6
|
+
export declare function accountProblemOf(ending: EngineEnding | undefined, opts: {
|
|
7
|
+
billedKey: boolean;
|
|
8
|
+
stderr?: string;
|
|
9
|
+
}): AccountProblem | null;
|
|
10
|
+
export declare function accountBlock(code: AccountProblem, engineName: string, retryInMinutes: number): UnattendedBlock;
|
|
11
|
+
export declare function cannotWorkSentence(engineName: string, block: UnattendedBlock): string;
|
|
12
|
+
export declare function keyFingerprint(key: string | null): string | null;
|
|
13
|
+
export type AccountHolds = {
|
|
14
|
+
hold(engine: EngineId, code: AccountProblem, engineName: string): boolean;
|
|
15
|
+
heldBlock(engine: EngineId): UnattendedBlock | null;
|
|
16
|
+
standing(installed: readonly EngineId[], probed: readonly EngineId[]): Array<UnattendedBlock & {
|
|
17
|
+
engine: EngineId;
|
|
18
|
+
}>;
|
|
19
|
+
};
|
|
20
|
+
export declare function accountHolds(deps: {
|
|
21
|
+
now?: () => number;
|
|
22
|
+
billedKey?: (engine: EngineId) => string | null;
|
|
23
|
+
log?: (msg: string) => void;
|
|
24
|
+
}): AccountHolds;
|