hyperclaw 5.2.9 → 5.3.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.
Files changed (48) hide show
  1. package/dist/banner-7G-bEcQg.js +143 -0
  2. package/dist/banner-BbUkjcoX.js +7 -0
  3. package/dist/banner-DXWl0t8M.js +7 -0
  4. package/dist/banner-DupxNjxh.js +143 -0
  5. package/dist/chat-2cf--psT.js +545 -0
  6. package/dist/chat-TGA-UO46.js +536 -0
  7. package/dist/daemon-BgT541y-.js +421 -0
  8. package/dist/daemon-CckV-o_V.js +421 -0
  9. package/dist/daemon-OqS7Ohda.js +7 -0
  10. package/dist/daemon-iM7U3tDr.js +7 -0
  11. package/dist/engine-BUqmNzOL.js +7 -0
  12. package/dist/engine-BrDEACit.js +327 -0
  13. package/dist/engine-Co38wljj.js +327 -0
  14. package/dist/engine-DrsMsoLZ.js +7 -0
  15. package/dist/hyperclawbot-CZ4DjvO-.js +516 -0
  16. package/dist/hyperclawbot-ukhzbWGk.js +516 -0
  17. package/dist/mcp-loader-CVhiejBN.js +93 -0
  18. package/dist/mcp-loader-u-tt6BEx.js +93 -0
  19. package/dist/onboard-CSJuvkMN.js +14 -0
  20. package/dist/onboard-D6afaGWd.js +3812 -0
  21. package/dist/onboard-eIxjVYKi.js +3812 -0
  22. package/dist/onboard-gr80CpYU.js +14 -0
  23. package/dist/orchestrator-BwBZ5iON.js +189 -0
  24. package/dist/orchestrator-Cgj-8BbJ.js +189 -0
  25. package/dist/orchestrator-CjZos0wH.js +6 -0
  26. package/dist/orchestrator-PLHfNTD6.js +6 -0
  27. package/dist/osint-B6mHZP10.js +283 -0
  28. package/dist/osint-CMyamX3_.js +283 -0
  29. package/dist/osint-chat-DPHec6BB.js +789 -0
  30. package/dist/osint-chat-D_6Fb27C.js +789 -0
  31. package/dist/run-main.js +37 -32
  32. package/dist/server-B9rMYJwV.js +4 -0
  33. package/dist/server-CrZ_WVSf.js +1365 -0
  34. package/dist/server-DMC1wOsc.js +1365 -0
  35. package/dist/server-zXVY2lfd.js +4 -0
  36. package/dist/skill-runtime-CxDPbEuj.js +104 -0
  37. package/dist/skill-runtime-CzsUymMA.js +104 -0
  38. package/dist/skill-runtime-DAP0Gs_7.js +5 -0
  39. package/dist/skill-runtime-DXEKaHRd.js +5 -0
  40. package/dist/src-CSriPfaE.js +63 -0
  41. package/dist/src-CYUaLsXl.js +458 -0
  42. package/dist/src-CvJOtJlj.js +458 -0
  43. package/dist/src-cowbRb9x.js +63 -0
  44. package/dist/sub-agent-tools-CFlCWrhp.js +39 -0
  45. package/dist/sub-agent-tools-CIA8mqjv.js +39 -0
  46. package/dist/update-check-CApy4DTc.js +117 -0
  47. package/dist/update-check-CCMXnjxr.js +7 -0
  48. package/package.json +1 -1
@@ -0,0 +1,1365 @@
1
+ const require_chunk = require('./chunk-jS-bbMI5.js');
2
+ const chalk = require_chunk.__toESM(require("chalk"));
3
+ const fs_extra = require_chunk.__toESM(require("fs-extra"));
4
+ const path = require_chunk.__toESM(require("path"));
5
+ const os = require_chunk.__toESM(require("os"));
6
+ const crypto = require_chunk.__toESM(require("crypto"));
7
+ const ws = require_chunk.__toESM(require("ws"));
8
+ const child_process = require_chunk.__toESM(require("child_process"));
9
+ const http = require_chunk.__toESM(require("http"));
10
+
11
+ //#region packages/gateway/src/server.ts
12
+ let activeServer = null;
13
+ const PUBLIC_API_PATHS = new Set(["/api/v1/check", "/api/status"]);
14
+ /**
15
+
16
+ * Thrown when the gateway cannot bind its WebSocket port.
17
+
18
+ *
19
+
20
+ * Most common cause: another gateway instance is already running on the same
21
+
22
+ * port (EADDRINUSE). The OS releases the port automatically on any exit,
23
+
24
+ * including crashes and SIGKILL — no separate lock file or cleanup is needed.
25
+
26
+ *
27
+
28
+ * To run a second gateway on the same host, use an isolated profile and a
29
+
30
+ * unique port (leave at least 20 ports between base ports):
31
+
32
+ * hyperclaw --profile rescue gateway --port 19001
33
+
34
+ */
35
+ var GatewayLockError = class extends Error {
36
+ code;
37
+ constructor(message, code = "GATEWAY_LOCK") {
38
+ super(message);
39
+ this.name = "GatewayLockError";
40
+ this.code = code;
41
+ }
42
+ };
43
+ var GatewayServer = class {
44
+ wss = null;
45
+ httpServer = null;
46
+ sessions = /* @__PURE__ */ new Map();
47
+ transcripts = /* @__PURE__ */ new Map();
48
+ sessionStore = null;
49
+ config;
50
+ startedAt = "";
51
+ stopCron = null;
52
+ channelRunner = null;
53
+ configWatcher = null;
54
+ configReloadDebounce = null;
55
+ constructor(config) {
56
+ this.config = config;
57
+ }
58
+ /** Start watching the config file for changes and hot-apply safe settings. */
59
+ startConfigWatcher() {
60
+ const mode = this.config.reloadMode ?? "hybrid";
61
+ if (mode === "off") return;
62
+ const configPath = this.config.deps.getConfigPath?.() ?? "";
63
+ if (!configPath) return;
64
+ const fsNode = require("fs");
65
+ const debounceMs = this.config.reloadDebounceMs ?? 300;
66
+ const tryWatch = () => {
67
+ try {
68
+ const watcher = fsNode.watch(configPath, { persistent: false }, (_event) => {
69
+ if (this.configReloadDebounce) clearTimeout(this.configReloadDebounce);
70
+ this.configReloadDebounce = setTimeout(() => void this.hotReloadConfig(), debounceMs);
71
+ });
72
+ this.configWatcher = watcher;
73
+ console.log(chalk.default.gray(` ⚙ Config watcher active (mode: ${mode}) — ${configPath}`));
74
+ } catch {
75
+ const dir = require("path").dirname(configPath);
76
+ try {
77
+ const dirWatcher = fsNode.watch(dir, { persistent: false }, (_event, filename) => {
78
+ if (filename && configPath.endsWith(filename) && fsNode.existsSync(configPath)) {
79
+ dirWatcher.close();
80
+ tryWatch();
81
+ }
82
+ });
83
+ } catch {}
84
+ }
85
+ };
86
+ tryWatch();
87
+ }
88
+ /** Hot-apply safe config changes without restarting. */
89
+ async hotReloadConfig() {
90
+ try {
91
+ const fs$1 = require("fs-extra");
92
+ const configPath = this.config.deps.getConfigPath?.() ?? "";
93
+ if (!configPath) return;
94
+ const raw = await fs$1.readJson(configPath).catch(() => null);
95
+ if (!raw) return;
96
+ const restartRequired = raw.gateway?.port !== this.config.port || raw.gateway?.bind !== this.config.bind;
97
+ if (restartRequired) {
98
+ console.log(chalk.default.yellow("\n ⚙ Config change requires gateway restart — restarting...\n"));
99
+ for (const s of this.sessions.values()) if (s.socket.readyState === 1) s.socket.send(JSON.stringify({
100
+ type: "gateway:reloading",
101
+ reason: "config-change"
102
+ }));
103
+ if (typeof this.config.deps.restartDaemon === "function") try {
104
+ await this.config.deps.restartDaemon();
105
+ } catch {}
106
+ else console.log(chalk.default.yellow(" ⚠ restartDaemon not available — restart manually: hyperclaw daemon restart\n"));
107
+ return;
108
+ }
109
+ if (raw.gateway?.hooks !== void 0) this.config.hooks = raw.gateway.hooks;
110
+ if (raw.gateway?.enabledChannels !== void 0) this.config.enabledChannels = raw.gateway.enabledChannels;
111
+ const newDm = raw.gateway?.dmScope ?? raw.session?.dmScope;
112
+ if (newDm !== void 0) this.config.dmScope = newDm === "main" ? "global" : newDm === "per-peer" ? "per-channel" : newDm;
113
+ if (typeof this.config.deps.onConfigReloaded === "function") this.config.deps.onConfigReloaded(raw);
114
+ const reloadMsg = JSON.stringify({
115
+ type: "gateway:config-reloaded",
116
+ ts: (/* @__PURE__ */ new Date()).toISOString()
117
+ });
118
+ for (const s of this.sessions.values()) if (s.socket.readyState === 1) s.socket.send(reloadMsg);
119
+ console.log(chalk.default.green(" ⚙ Config hot-reloaded (no restart needed)"));
120
+ } catch (e) {
121
+ console.log(chalk.default.yellow(` ⚙ Config reload failed: ${e.message}`));
122
+ }
123
+ }
124
+ async start() {
125
+ this.httpServer = http.default.createServer((req, res) => {
126
+ this.handleHttp(req, res);
127
+ });
128
+ this.wss = new ws.WebSocketServer({ server: this.httpServer });
129
+ this.wss.on("connection", this.handleConnection.bind(this));
130
+ await new Promise((resolve, reject) => {
131
+ this.httpServer.on("error", (err) => {
132
+ if (err.code === "EADDRINUSE") reject(new GatewayLockError(`another gateway instance is already listening on ws://${this.config.bind}:${this.config.port}`, "EADDRINUSE"));
133
+ else reject(new GatewayLockError(`failed to bind gateway socket on ws://${this.config.bind}:${this.config.port}: ${err.message}`, err.code || "BIND_ERROR"));
134
+ });
135
+ this.httpServer.listen(this.config.port, this.config.bind, () => resolve());
136
+ });
137
+ this.startedAt = (/* @__PURE__ */ new Date()).toISOString();
138
+ activeServer = this;
139
+ try {
140
+ this.sessionStore = await this.config.deps.createSessionStore(this.config.deps.getHyperClawDir());
141
+ } catch (_) {
142
+ this.sessionStore = null;
143
+ }
144
+ const icon = this.config.daemonMode ? "🩸" : "🦅";
145
+ const color = this.config.daemonMode ? chalk.default.red.bind(chalk.default) : chalk.default.hex("#06b6d4");
146
+ console.log(color(`\n ${icon} Gateway started: ws://${this.config.bind}:${this.config.port}\n`));
147
+ this.channelRunner = await this.config.deps.startChannelRunners({
148
+ port: this.config.port,
149
+ bind: this.config.bind,
150
+ authToken: this.config.deps.resolveGatewayToken(this.config.authToken)
151
+ });
152
+ if (this.config.hooks && this.config.deps.createHookLoader) {
153
+ const loader = this.config.deps.createHookLoader();
154
+ loader.execute("gateway:start", {}).catch(() => {});
155
+ this.stopCron = loader.startCronScheduler();
156
+ }
157
+ this.startConfigWatcher();
158
+ }
159
+ async stop() {
160
+ if (this.configWatcher) {
161
+ this.configWatcher.close();
162
+ this.configWatcher = null;
163
+ }
164
+ if (this.configReloadDebounce) clearTimeout(this.configReloadDebounce);
165
+ if (this.channelRunner) {
166
+ await this.channelRunner.stop();
167
+ this.channelRunner = null;
168
+ }
169
+ if (this.stopCron) {
170
+ this.stopCron();
171
+ this.stopCron = null;
172
+ }
173
+ for (const s of this.sessions.values()) s.socket.close(1001, "Gateway shutting down");
174
+ this.sessions.clear();
175
+ this.wss?.close();
176
+ await new Promise((resolve) => this.httpServer?.close(() => resolve()));
177
+ activeServer = null;
178
+ }
179
+ /** Returns false and sends 401 if auth required but missing/invalid. */
180
+ async requireAuth(req, res) {
181
+ const token = this.config.deps.resolveGatewayToken(this.config.authToken);
182
+ const auth = req.headers.authorization;
183
+ if (!token && !auth) return true;
184
+ if (!auth || !auth.startsWith("Bearer ")) {
185
+ res.writeHead(401, { "Content-Type": "application/json" });
186
+ res.end(JSON.stringify({
187
+ error: "Unauthorized",
188
+ hint: "Authorization: Bearer <gateway_token_or_developer_key>"
189
+ }));
190
+ return false;
191
+ }
192
+ const bearer = auth.slice(7);
193
+ if (token && bearer === token) return true;
194
+ if (this.config.deps.validateApiAuth) {
195
+ const ok = await this.config.deps.validateApiAuth(bearer);
196
+ if (ok) return true;
197
+ }
198
+ res.writeHead(401, { "Content-Type": "application/json" });
199
+ res.end(JSON.stringify({
200
+ error: "Unauthorized",
201
+ hint: "Authorization: Bearer <gateway_token_or_developer_key>"
202
+ }));
203
+ return false;
204
+ }
205
+ /** Resolve real client IP, honouring X-Forwarded-For only when the socket peer is a trusted proxy. */
206
+ resolveClientIp(req) {
207
+ const socketIp = req.socket.remoteAddress ?? "127.0.0.1";
208
+ const trusted = this.config.trustedProxies ?? [];
209
+ if (trusted.length === 0) return socketIp;
210
+ const isTrusted = trusted.some((proxy) => {
211
+ if (proxy === socketIp) return true;
212
+ if (proxy.includes("/")) try {
213
+ const [base, bits] = proxy.split("/");
214
+ const mask = ~((1 << 32 - parseInt(bits, 10)) - 1);
215
+ const ipToNum = (ip) => ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0);
216
+ return (ipToNum(socketIp) & mask) === (ipToNum(base) & mask);
217
+ } catch {
218
+ return false;
219
+ }
220
+ return false;
221
+ });
222
+ if (!isTrusted) return socketIp;
223
+ const xff = req.headers["x-forwarded-for"];
224
+ return xff ? xff.split(",")[0].trim() : socketIp;
225
+ }
226
+ configRpcRateLimit = /* @__PURE__ */ new Map();
227
+ CONFIG_RPC_MAX = 3;
228
+ CONFIG_RPC_WINDOW_MS = 6e4;
229
+ checkConfigRpcRateLimit(key) {
230
+ const now = Date.now();
231
+ let entry = this.configRpcRateLimit.get(key);
232
+ if (!entry || now - entry.windowStart > this.CONFIG_RPC_WINDOW_MS) entry = {
233
+ count: 0,
234
+ windowStart: now
235
+ };
236
+ entry.count++;
237
+ this.configRpcRateLimit.set(key, entry);
238
+ if (entry.count > this.CONFIG_RPC_MAX) {
239
+ const retryAfterMs = this.CONFIG_RPC_WINDOW_MS - (now - entry.windowStart);
240
+ return {
241
+ ok: false,
242
+ retryAfterMs
243
+ };
244
+ }
245
+ return { ok: true };
246
+ }
247
+ isProtectedApiPath(pathname) {
248
+ return pathname.startsWith("/api/") && !PUBLIC_API_PATHS.has(pathname);
249
+ }
250
+ resolveWebhookChannelId(pathname) {
251
+ if (!pathname.startsWith("/webhook/")) return null;
252
+ const parts = pathname.split("/").filter(Boolean);
253
+ if (parts.length !== 2) return null;
254
+ const channelId = parts[1] ?? "";
255
+ return /^[a-z0-9-]+$/i.test(channelId) ? channelId : null;
256
+ }
257
+ async handleHttp(req, res) {
258
+ const requestUrl = new URL(req.url || "/", "http://localhost");
259
+ const pathname = requestUrl.pathname;
260
+ res.setHeader("Access-Control-Allow-Origin", "*");
261
+ res.setHeader("Content-Type", "application/json");
262
+ if (req.method === "OPTIONS") {
263
+ res.writeHead(204);
264
+ res.end();
265
+ return;
266
+ }
267
+ if (this.isProtectedApiPath(pathname) && !await this.requireAuth(req, res)) return;
268
+ if (pathname === "/api/v1/check") {
269
+ res.writeHead(200);
270
+ res.end(JSON.stringify({
271
+ ok: true,
272
+ service: "hyperclaw",
273
+ version: "5.3.1"
274
+ }));
275
+ return;
276
+ }
277
+ if ((pathname === "/api/v1/config/apply" || pathname === "/api/v1/config/patch") && req.method === "POST") {
278
+ const clientIp = this.resolveClientIp(req);
279
+ const deviceId = req.headers["x-hyperclaw-device"] || "anon";
280
+ const rlKey = `${deviceId}:${clientIp}`;
281
+ const rl = this.checkConfigRpcRateLimit(rlKey);
282
+ if (!rl.ok) {
283
+ res.writeHead(429, { "Retry-After": String(Math.ceil((rl.retryAfterMs ?? 6e4) / 1e3)) });
284
+ res.end(JSON.stringify({
285
+ error: "UNAVAILABLE",
286
+ retryAfterMs: rl.retryAfterMs,
287
+ hint: "Config RPC is rate-limited to 3 requests per 60 seconds."
288
+ }));
289
+ return;
290
+ }
291
+ let body = "";
292
+ req.on("data", (c) => body += c);
293
+ req.on("end", async () => {
294
+ try {
295
+ const payload = JSON.parse(body || "{}");
296
+ const configPath = this.config.deps.getConfigPath();
297
+ const current = await fs_extra.default.readJson(configPath).catch(() => ({}));
298
+ let next;
299
+ if (pathname.endsWith("/apply")) next = payload;
300
+ else next = {
301
+ ...current,
302
+ ...payload
303
+ };
304
+ await fs_extra.default.writeJson(configPath, next, { spaces: 2 });
305
+ res.writeHead(200);
306
+ res.end(JSON.stringify({
307
+ ok: true,
308
+ action: pathname.endsWith("/apply") ? "apply" : "patch"
309
+ }));
310
+ } catch (e) {
311
+ res.writeHead(400);
312
+ res.end(JSON.stringify({ error: e.message }));
313
+ }
314
+ });
315
+ return;
316
+ }
317
+ if (pathname === "/api/v1/pi" && req.method === "POST") {
318
+ let body = "";
319
+ req.on("data", (c) => body += c);
320
+ req.on("end", async () => {
321
+ try {
322
+ const handler = this.config.deps.createPiRPCHandler((msg, opts) => this.callAgent(msg, {
323
+ currentSessionId: opts?.currentSessionId,
324
+ source: opts?.source
325
+ }), () => this.getSessionsList());
326
+ const rpcReq = JSON.parse(body || "{}");
327
+ const rpcRes = await handler(rpcReq);
328
+ res.writeHead(200);
329
+ res.end(JSON.stringify(rpcRes));
330
+ } catch (e) {
331
+ res.writeHead(500);
332
+ res.end(JSON.stringify({
333
+ jsonrpc: "2.0",
334
+ error: {
335
+ code: -32700,
336
+ message: e.message || "Parse error"
337
+ }
338
+ }));
339
+ }
340
+ });
341
+ return;
342
+ }
343
+ if (pathname === "/api/status") {
344
+ const cfg = this.loadConfig();
345
+ res.writeHead(200);
346
+ res.end(JSON.stringify({
347
+ running: true,
348
+ port: this.config.port,
349
+ channels: this.config.enabledChannels,
350
+ model: cfg?.provider?.modelId || "unknown",
351
+ agentName: cfg?.identity?.agentName || "Hyper",
352
+ sessions: this.sessions.size,
353
+ uptime: this.startedAt ? `${Math.round((Date.now() - new Date(this.startedAt).getTime()) / 1e3)}s` : "0s"
354
+ }));
355
+ return;
356
+ }
357
+ if (pathname === "/api/traces" && req.method === "GET") {
358
+ (async () => {
359
+ const params = requestUrl.searchParams;
360
+ const limit = Math.min(100, parseInt(params.get("limit") || "50", 10) || 50);
361
+ try {
362
+ const traces = this.config.deps.listTraces ? await this.config.deps.listTraces(this.config.deps.getHyperClawDir(), limit) : [];
363
+ res.writeHead(200);
364
+ res.end(JSON.stringify({ traces }));
365
+ } catch {
366
+ res.writeHead(500);
367
+ res.end(JSON.stringify({ error: "Failed to list traces" }));
368
+ }
369
+ })();
370
+ return;
371
+ }
372
+ if (pathname === "/api/costs" && req.method === "GET") {
373
+ (async () => {
374
+ const params = requestUrl.searchParams;
375
+ const sessionId = params.get("sessionId");
376
+ const hcDir = this.config.deps.getHyperClawDir();
377
+ try {
378
+ if (sessionId && this.config.deps.getSessionSummary) {
379
+ const summary = await this.config.deps.getSessionSummary(hcDir, sessionId);
380
+ res.writeHead(200);
381
+ res.end(JSON.stringify({
382
+ sessionId,
383
+ summary
384
+ }));
385
+ } else if (this.config.deps.getGlobalSummary) {
386
+ const summary = await this.config.deps.getGlobalSummary(this.config.deps.getHyperClawDir());
387
+ res.writeHead(200);
388
+ res.end(JSON.stringify({ summary }));
389
+ }
390
+ } catch (e) {
391
+ res.writeHead(500);
392
+ res.end(JSON.stringify({ error: e.message }));
393
+ }
394
+ })();
395
+ return;
396
+ }
397
+ if (pathname === "/api/remote/restart" && req.method === "POST") {
398
+ (async () => {
399
+ const hcDir = this.config.deps.getHyperClawDir();
400
+ const pidFile = path.default.join(hcDir, "gateway.pid");
401
+ let didSpawn = false;
402
+ try {
403
+ if (await fs_extra.default.pathExists(pidFile)) {
404
+ const storedPid = parseInt(await fs_extra.default.readFile(pidFile, "utf8"), 10);
405
+ if (storedPid === process.pid && this.config.daemonMode) {
406
+ const runMainPath = this.config.deps.getRunMainPath?.() || process.argv[1] || require.main?.filename || path.default.resolve(process.cwd(), "dist/run-main.js");
407
+ const child = (0, child_process.spawn)(process.execPath, [
408
+ runMainPath,
409
+ "daemon",
410
+ "restart"
411
+ ], {
412
+ detached: true,
413
+ stdio: "ignore",
414
+ env: process.env,
415
+ cwd: process.cwd()
416
+ });
417
+ child.unref();
418
+ didSpawn = true;
419
+ }
420
+ }
421
+ } catch (e) {
422
+ if (process.env.DEBUG) console.error("[gateway] daemon restart spawn:", e?.message);
423
+ }
424
+ res.writeHead(200);
425
+ res.end(JSON.stringify({
426
+ accepted: true,
427
+ message: didSpawn ? "Restarting daemon..." : "Gateway does not run as daemon. Run: hyperclaw daemon start, or from remote: ssh user@host \"hyperclaw daemon restart\"",
428
+ restarted: didSpawn
429
+ }));
430
+ })();
431
+ return;
432
+ }
433
+ if (pathname === "/api/v1/tts" && req.method === "POST") {
434
+ let body = "";
435
+ req.on("data", (c) => body += c);
436
+ req.on("end", async () => {
437
+ try {
438
+ const { text } = JSON.parse(body || "{}");
439
+ const cfg = this.loadConfig();
440
+ const apiKey = cfg?.talkMode?.apiKey || process.env.ELEVENLABS_API_KEY;
441
+ if (!apiKey || !text) {
442
+ res.writeHead(400);
443
+ res.end(JSON.stringify({ error: "Missing text or ELEVENLABS_API_KEY" }));
444
+ return;
445
+ }
446
+ const audio = this.config.deps.textToSpeech ? await this.config.deps.textToSpeech(text.slice(0, 4e3), {
447
+ apiKey,
448
+ voiceId: cfg?.talkMode?.voiceId,
449
+ modelId: cfg?.talkMode?.modelId
450
+ }) : null;
451
+ if (!audio) {
452
+ res.writeHead(502);
453
+ res.end(JSON.stringify({ error: "TTS failed" }));
454
+ return;
455
+ }
456
+ res.writeHead(200, { "Content-Type": "application/json" });
457
+ res.end(JSON.stringify({
458
+ format: "mp3",
459
+ data: audio
460
+ }));
461
+ } catch (e) {
462
+ res.writeHead(500);
463
+ res.end(JSON.stringify({ error: e.message }));
464
+ }
465
+ });
466
+ return;
467
+ }
468
+ if (pathname === "/api/nodes" && req.method === "GET") {
469
+ try {
470
+ const NR = this.config.deps.NodeRegistry;
471
+ const nodes = NR ? NR.getNodes().map((n) => ({
472
+ nodeId: n.nodeId,
473
+ platform: n.platform,
474
+ capabilities: n.capabilities,
475
+ deviceName: n.deviceName,
476
+ connectedAt: n.connectedAt,
477
+ lastSeenAt: n.lastSeenAt
478
+ })) : [];
479
+ res.writeHead(200);
480
+ res.end(JSON.stringify({ nodes }));
481
+ } catch (e) {
482
+ res.writeHead(500);
483
+ res.end(JSON.stringify({ error: e.message }));
484
+ }
485
+ return;
486
+ }
487
+ if (pathname === "/api/terminal" && req.method === "POST") {
488
+ let body = "";
489
+ req.on("data", (c) => body += c);
490
+ req.on("end", () => {
491
+ try {
492
+ const parsed = JSON.parse(body || "{}");
493
+ const command = typeof parsed.command === "string" ? parsed.command.trim() : "";
494
+ if (!command || command.length > 500) {
495
+ res.writeHead(400);
496
+ res.end(JSON.stringify({ error: "Invalid command" }));
497
+ return;
498
+ }
499
+ const shell = process.platform === "win32" ? process.env.COMSPEC || "cmd.exe" : process.env.SHELL || "/bin/bash";
500
+ const args = process.platform === "win32" ? [
501
+ "/d",
502
+ "/s",
503
+ "/c",
504
+ command
505
+ ] : ["-lc", command];
506
+ const cwd = process.cwd();
507
+ const child = (0, child_process.spawn)(shell, args, {
508
+ cwd,
509
+ env: process.env
510
+ });
511
+ let stdout = "";
512
+ let stderr = "";
513
+ child.stdout.on("data", (chunk) => {
514
+ stdout += chunk.toString();
515
+ if (stdout.length > 16e3) stdout = stdout.slice(-16e3);
516
+ });
517
+ child.stderr.on("data", (chunk) => {
518
+ stderr += chunk.toString();
519
+ if (stderr.length > 8e3) stderr = stderr.slice(-8e3);
520
+ });
521
+ child.on("error", (e) => {
522
+ res.writeHead(500);
523
+ res.end(JSON.stringify({ error: e.message || "Failed to start shell" }));
524
+ });
525
+ child.on("close", (code) => {
526
+ try {
527
+ res.writeHead(200);
528
+ res.end(JSON.stringify({
529
+ ok: code === 0,
530
+ code,
531
+ stdout,
532
+ stderr,
533
+ user: os.default.userInfo().username,
534
+ hostname: os.default.hostname(),
535
+ cwd
536
+ }));
537
+ } catch {}
538
+ });
539
+ } catch (e) {
540
+ res.writeHead(500);
541
+ res.end(JSON.stringify({ error: e.message || "Failed to run command" }));
542
+ }
543
+ });
544
+ return;
545
+ }
546
+ if (pathname === "/api/chat" && req.method === "POST") {
547
+ let body = "";
548
+ req.on("data", (c) => body += c);
549
+ req.on("end", async () => {
550
+ try {
551
+ const parsed = JSON.parse(body);
552
+ const { message } = parsed;
553
+ const agentId = parsed.agentId;
554
+ const sessionKey = parsed.sessionKey;
555
+ const source = req.headers["x-hyperclaw-source"] || "unknown";
556
+ const response = await this.callAgent(message, {
557
+ source,
558
+ agentId,
559
+ sessionKey
560
+ });
561
+ res.writeHead(200);
562
+ res.end(JSON.stringify({ response }));
563
+ } catch (e) {
564
+ res.writeHead(500);
565
+ res.end(JSON.stringify({ error: e.message }));
566
+ }
567
+ });
568
+ return;
569
+ }
570
+ if (pathname === "/api/webhook/inbound" && req.method === "POST") {
571
+ let body = "";
572
+ req.on("data", (c) => body += c);
573
+ req.on("end", async () => {
574
+ try {
575
+ const parsed = typeof body === "string" ? JSON.parse(body || "{}") : {};
576
+ const message = parsed.message || parsed.text || parsed.prompt || String(parsed);
577
+ if (!message || typeof message !== "string") {
578
+ res.writeHead(400);
579
+ res.end(JSON.stringify({ error: "Body must include \"message\" or \"text\" or \"prompt\"" }));
580
+ return;
581
+ }
582
+ const response = await this.callAgent(message, { source: "webhook:inbound" });
583
+ res.writeHead(200);
584
+ res.end(JSON.stringify({
585
+ ok: true,
586
+ response
587
+ }));
588
+ } catch (e) {
589
+ res.writeHead(500);
590
+ res.end(JSON.stringify({ error: e.message }));
591
+ }
592
+ });
593
+ return;
594
+ }
595
+ if (pathname === "/api/canvas/state" && req.method === "GET") {
596
+ const getState = this.config.deps.getCanvasState;
597
+ if (getState) getState().then((canvas) => {
598
+ res.writeHead(200, { "Content-Type": "application/json" });
599
+ res.end(JSON.stringify(canvas));
600
+ }).catch((e) => {
601
+ res.writeHead(500);
602
+ res.end(JSON.stringify({ error: e.message }));
603
+ });
604
+ else Promise.resolve().then(() => require("./renderer-B1ToXngl.js")).then(({ CanvasRenderer }) => {
605
+ const renderer = new CanvasRenderer();
606
+ renderer.getOrCreate().then((canvas) => {
607
+ res.writeHead(200, { "Content-Type": "application/json" });
608
+ res.end(JSON.stringify(canvas));
609
+ }).catch((e) => {
610
+ res.writeHead(500);
611
+ res.end(JSON.stringify({ error: e.message }));
612
+ });
613
+ }).catch((e) => {
614
+ res.writeHead(500);
615
+ res.end(JSON.stringify({ error: e.message }));
616
+ });
617
+ return;
618
+ }
619
+ if (pathname === "/api/canvas/a2ui" && req.method === "GET") {
620
+ const getA2UI = this.config.deps.getCanvasA2UI;
621
+ if (getA2UI) getA2UI().then((jsonl) => {
622
+ res.setHeader("Content-Type", "application/x-ndjson");
623
+ res.setHeader("Cache-Control", "no-cache");
624
+ res.writeHead(200);
625
+ res.end(jsonl + "\n");
626
+ }).catch((e) => {
627
+ res.writeHead(500);
628
+ res.end(JSON.stringify({ error: e.message }));
629
+ });
630
+ else Promise.resolve().then(() => require("./renderer-B1ToXngl.js")).then(({ CanvasRenderer }) => {
631
+ Promise.resolve().then(() => require("./a2ui-protocol-DEsfqO7h.js")).then(({ toBeginRendering, toJSONL }) => {
632
+ const renderer = new CanvasRenderer();
633
+ renderer.getOrCreate().then((canvas) => {
634
+ const msg = toBeginRendering(canvas);
635
+ res.setHeader("Content-Type", "application/x-ndjson");
636
+ res.setHeader("Cache-Control", "no-cache");
637
+ res.writeHead(200);
638
+ res.end(toJSONL([msg]) + "\n");
639
+ }).catch((e) => {
640
+ res.writeHead(500);
641
+ res.end(JSON.stringify({ error: e.message }));
642
+ });
643
+ });
644
+ }).catch((e) => {
645
+ res.writeHead(500);
646
+ res.end(JSON.stringify({ error: e.message }));
647
+ });
648
+ return;
649
+ }
650
+ if (pathname === "/chat" || pathname === "/chat/") {
651
+ res.setHeader("Content-Type", "text/html");
652
+ const staticDir = path.default.resolve(__dirname, "..", "static");
653
+ const fp = path.default.join(staticDir, "chat.html");
654
+ if (fs_extra.default.pathExistsSync(fp)) res.end(fs_extra.default.readFileSync(fp, "utf8"));
655
+ else res.end("<!DOCTYPE html><html><body><p>Chat UI not found. Run from package root or reinstall hyperclaw.</p></body></html>");
656
+ return;
657
+ }
658
+ if (pathname === "/dashboard" || pathname === "/dashboard/") {
659
+ res.setHeader("Content-Type", "text/html");
660
+ const staticDir = path.default.resolve(__dirname, "..", "static");
661
+ const fp = path.default.join(staticDir, "dashboard.html");
662
+ if (fs_extra.default.pathExistsSync(fp)) res.end(fs_extra.default.readFileSync(fp, "utf8"));
663
+ else res.end("<!DOCTYPE html><html><body><p>Dashboard: <a href=\"/api/status\">status</a></p></body></html>");
664
+ return;
665
+ }
666
+ if (pathname === "/" || pathname === "") {
667
+ res.writeHead(302, { Location: "/dashboard" });
668
+ res.end();
669
+ return;
670
+ }
671
+ if (pathname.startsWith("/webhook/")) {
672
+ const channelId = this.resolveWebhookChannelId(pathname);
673
+ if (!channelId || !this.channelRunner?.hasWebhookChannel?.(channelId)) {
674
+ res.writeHead(404);
675
+ res.end(JSON.stringify({ error: "Webhook channel not found" }));
676
+ return;
677
+ }
678
+ if (req.method === "GET") {
679
+ const params = requestUrl.searchParams;
680
+ if (channelId === "twitter") {
681
+ const crcToken = params.get("crc_token");
682
+ if (crcToken) {
683
+ const verified$1 = this.channelRunner?.verifyWebhook?.(channelId, "crc", crcToken, "");
684
+ if (verified$1) {
685
+ res.writeHead(200, { "Content-Type": "application/json" });
686
+ res.end(verified$1);
687
+ return;
688
+ }
689
+ res.writeHead(403);
690
+ res.end(JSON.stringify({ error: "Webhook verification failed" }));
691
+ return;
692
+ }
693
+ }
694
+ const mode = (params.get("hub.mode") || "").slice(0, 64);
695
+ const token = (params.get("hub.verify_token") || "").slice(0, 512);
696
+ const rawChallenge = params.get("hub.challenge") || "";
697
+ const challenge = rawChallenge.length > 0 && rawChallenge.length <= 512 && /^[\x20-\x7e]*$/.test(rawChallenge) ? rawChallenge : "";
698
+ const verified = this.channelRunner?.verifyWebhook?.(channelId, mode, token, challenge);
699
+ if (verified !== null && verified !== void 0 && typeof verified === "string") {
700
+ res.writeHead(200, { "Content-Type": "text/plain" });
701
+ res.end(verified);
702
+ } else {
703
+ res.writeHead(403);
704
+ res.end(JSON.stringify({ error: "Webhook verification failed" }));
705
+ }
706
+ return;
707
+ }
708
+ if (req.method === "POST") {
709
+ let body = "";
710
+ req.on("data", (c) => body += c);
711
+ req.on("end", async () => {
712
+ const host = req.headers["host"] || "localhost";
713
+ const baseUrl = `${req.headers["x-forwarded-proto"] === "https" ? "https" : "http"}://${host}`;
714
+ let opts;
715
+ if (channelId === "slack") opts = {
716
+ signature: req.headers["x-slack-signature"] || "",
717
+ timestamp: req.headers["x-slack-request-timestamp"] || ""
718
+ };
719
+ else if (channelId === "line") opts = { signature: req.headers["x-line-signature"] || "" };
720
+ else if (channelId === "sms") opts = {
721
+ twilioSignature: req.headers["x-twilio-signature"] || "",
722
+ webhookUrl: `${baseUrl}${req.url}`
723
+ };
724
+ else if (channelId === "instagram" || channelId === "messenger") opts = { signature: req.headers["x-hub-signature-256"] || "" };
725
+ else if (channelId === "viber") opts = { signature: req.headers["x-viber-signature"] || "" };
726
+ let challenge = void 0;
727
+ try {
728
+ if (this.channelRunner?.handleWebhook) challenge = await this.channelRunner.handleWebhook(channelId, body, opts);
729
+ } catch {
730
+ res.writeHead(403);
731
+ res.end(JSON.stringify({ error: "Webhook rejected" }));
732
+ return;
733
+ }
734
+ this.broadcast({
735
+ type: "webhook:received",
736
+ channelId,
737
+ payload: body
738
+ });
739
+ if (typeof challenge === "string") {
740
+ const contentType = challenge.trim().startsWith("{") ? "application/json" : "text/plain";
741
+ res.writeHead(200, { "Content-Type": contentType });
742
+ res.end(challenge);
743
+ } else {
744
+ res.writeHead(200);
745
+ res.end(JSON.stringify({ ok: true }));
746
+ }
747
+ });
748
+ return;
749
+ }
750
+ }
751
+ res.writeHead(404);
752
+ res.end(JSON.stringify({ error: "Not found" }));
753
+ }
754
+ handleConnection(ws$1, req) {
755
+ const id = crypto.default.randomBytes(8).toString("hex");
756
+ const source = req.headers["x-hyperclaw-source"] || "unknown";
757
+ const authToken = this.config.deps.resolveGatewayToken(this.config.authToken);
758
+ const session = {
759
+ id,
760
+ socket: ws$1,
761
+ authenticated: !authToken,
762
+ source,
763
+ connectedAt: (/* @__PURE__ */ new Date()).toISOString(),
764
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
765
+ };
766
+ this.sessions.set(id, session);
767
+ this.broadcast({
768
+ type: "presence:join",
769
+ sessionId: id,
770
+ source
771
+ }, id);
772
+ console.log(chalk.default.gray(` [gateway] +connect ${source} ${id}`));
773
+ if (authToken && !session.authenticated) this.send(session, {
774
+ type: "connect.challenge",
775
+ sessionId: id
776
+ });
777
+ else {
778
+ this.send(session, {
779
+ type: "connect.ok",
780
+ sessionId: id,
781
+ version: "5.3.1",
782
+ heartbeatInterval: 3e4
783
+ });
784
+ if (this.config.hooks && this.config.deps.createHookLoader) this.config.deps.createHookLoader().execute("session:start", { sessionId: id }).catch(() => {});
785
+ }
786
+ ws$1.on("message", (data) => {
787
+ session.lastActiveAt = (/* @__PURE__ */ new Date()).toISOString();
788
+ try {
789
+ this.handleMessage(session, JSON.parse(data.toString()));
790
+ } catch {
791
+ this.send(session, {
792
+ type: "error",
793
+ message: "Invalid JSON"
794
+ });
795
+ }
796
+ });
797
+ ws$1.on("close", () => {
798
+ const s = this.sessions.get(id);
799
+ if (s?.nodeId && this.config.deps.NodeRegistry) {
800
+ this.config.deps.NodeRegistry.unregister(s.nodeId);
801
+ console.log(chalk.default.gray(` [gateway] -node ${s.nodeId}`));
802
+ }
803
+ if (this.config.hooks && !s?.nodeId && this.config.deps.createHookLoader) {
804
+ const turnCount = this.transcripts.get(id)?.length ?? 0;
805
+ this.config.deps.createHookLoader().execute("session:end", {
806
+ sessionId: id,
807
+ turnCount
808
+ }).catch(() => {});
809
+ }
810
+ this.transcripts.delete(id);
811
+ this.sessions.delete(id);
812
+ this.broadcast({
813
+ type: "presence:leave",
814
+ sessionId: id
815
+ });
816
+ console.log(chalk.default.gray(` [gateway] -disconnect ${id}`));
817
+ });
818
+ ws$1.on("error", (e) => console.log(chalk.default.yellow(` [gateway] error ${id}: ${e.message}`)));
819
+ }
820
+ handleMessage(session, msg) {
821
+ if (msg.type === "node_register") {
822
+ const nodeId = msg.nodeId || `node-${session.id}`;
823
+ const platform = msg.platform === "ios" || msg.platform === "android" ? msg.platform : "ios";
824
+ const capabilities = msg.capabilities || {};
825
+ const authToken = this.config.deps.resolveGatewayToken(this.config.authToken);
826
+ if (authToken && msg.token !== authToken) {
827
+ this.send(session, {
828
+ type: "node:error",
829
+ message: "Invalid token"
830
+ });
831
+ session.socket.close(4001, "Unauthorized");
832
+ return;
833
+ }
834
+ const NR = this.config.deps.NodeRegistry;
835
+ if (!NR) {
836
+ this.send(session, {
837
+ type: "node:error",
838
+ message: "Node registry not available"
839
+ });
840
+ return;
841
+ }
842
+ const cmdIdToResolve = /* @__PURE__ */ new Map();
843
+ session._nodePending = cmdIdToResolve;
844
+ const node = {
845
+ nodeId,
846
+ platform,
847
+ capabilities,
848
+ deviceName: msg.deviceName,
849
+ connectedAt: (/* @__PURE__ */ new Date()).toISOString(),
850
+ lastSeenAt: (/* @__PURE__ */ new Date()).toISOString(),
851
+ send: async (cmd) => {
852
+ return new Promise((resolve) => {
853
+ const timeout = setTimeout(() => {
854
+ cmdIdToResolve.delete(cmd.id);
855
+ resolve({
856
+ ok: false,
857
+ error: "Timeout"
858
+ });
859
+ }, 3e4);
860
+ cmdIdToResolve.set(cmd.id, { resolve: (r) => {
861
+ clearTimeout(timeout);
862
+ resolve(r);
863
+ } });
864
+ this.send(session, {
865
+ type: "node:command",
866
+ id: cmd.id,
867
+ command: cmd.type,
868
+ params: cmd.params
869
+ });
870
+ });
871
+ }
872
+ };
873
+ const protocolVersion = msg.protocolVersion ?? 1;
874
+ NR.register(node);
875
+ session.nodeId = nodeId;
876
+ session.authenticated = true;
877
+ session.source = `node:${platform}`;
878
+ this.send(session, {
879
+ type: "node:registered",
880
+ nodeId,
881
+ sessionId: session.id,
882
+ protocolVersion: Math.min(protocolVersion, 2),
883
+ heartbeatInterval: 3e4,
884
+ capabilities: Object.keys(capabilities)
885
+ });
886
+ console.log(chalk.default.gray(` [gateway] +node ${nodeId} (${platform})`));
887
+ return;
888
+ }
889
+ if (msg.type === "node:unregister" && session.nodeId && this.config.deps.NodeRegistry) {
890
+ this.config.deps.NodeRegistry.unregister(session.nodeId);
891
+ session.nodeId = void 0;
892
+ this.send(session, { type: "node:unregistered" });
893
+ return;
894
+ }
895
+ if (msg.type === "node:command_response" && session._nodePending) {
896
+ const r = session._nodePending.get(msg.id);
897
+ if (r) {
898
+ session._nodePending.delete(msg.id);
899
+ r.resolve({
900
+ ok: msg.ok,
901
+ data: msg.data,
902
+ error: msg.error
903
+ });
904
+ }
905
+ return;
906
+ }
907
+ if (msg.type === "session:restore" && (msg.restoreKey ?? msg.previousSessionId)) {
908
+ const key = String(msg.restoreKey ?? msg.previousSessionId);
909
+ session.restoreKey = key;
910
+ if (this.sessionStore) this.sessionStore.get(key).then((state) => {
911
+ if (state?.transcript?.length) {
912
+ const arr = this.transcripts.get(session.id) || [];
913
+ for (const t of state.transcript) if (!arr.some((x) => x.role === t.role && x.content === t.content)) arr.push(t);
914
+ if (arr.length > 100) arr.splice(0, arr.length - 80);
915
+ this.transcripts.set(session.id, arr);
916
+ this.send(session, {
917
+ type: "session:restored",
918
+ transcript: state.transcript
919
+ });
920
+ }
921
+ }).catch(() => {});
922
+ return;
923
+ }
924
+ if (msg.type === "auth") {
925
+ const resolved = this.config.deps.resolveGatewayToken(this.config.authToken);
926
+ if (resolved && msg.token === resolved) {
927
+ session.authenticated = true;
928
+ this.send(session, {
929
+ type: "auth.ok",
930
+ sessionId: session.id
931
+ });
932
+ } else session.socket.close(4001, "Unauthorized");
933
+ return;
934
+ }
935
+ if (!session.authenticated) {
936
+ this.send(session, {
937
+ type: "error",
938
+ message: "Not authenticated"
939
+ });
940
+ return;
941
+ }
942
+ switch (msg.type) {
943
+ case "ping": {
944
+ if (session.nodeId && this.config.deps.NodeRegistry) this.config.deps.NodeRegistry.updateLastSeen?.(session.nodeId);
945
+ this.send(session, {
946
+ type: "pong",
947
+ ts: Date.now()
948
+ });
949
+ break;
950
+ }
951
+ case "talk:enable":
952
+ session.talkMode = true;
953
+ this.send(session, {
954
+ type: "talk:ok",
955
+ enabled: true
956
+ });
957
+ break;
958
+ case "talk:disable":
959
+ session.talkMode = false;
960
+ this.send(session, {
961
+ type: "talk:ok",
962
+ enabled: false
963
+ });
964
+ break;
965
+ case "elevated:enable": {
966
+ const cfg = this.loadConfig();
967
+ const allowFrom = (cfg?.tools?.elevated)?.allowFrom ?? [];
968
+ const enabled = (cfg?.tools?.elevated)?.enabled === true;
969
+ if (!enabled) {
970
+ this.send(session, {
971
+ type: "error",
972
+ message: "Elevated mode disabled in config"
973
+ });
974
+ break;
975
+ }
976
+ if (allowFrom.length && !allowFrom.includes(session.source) && !allowFrom.includes("*")) {
977
+ this.send(session, {
978
+ type: "error",
979
+ message: "Source not in elevated allowFrom"
980
+ });
981
+ break;
982
+ }
983
+ session.elevated = true;
984
+ this.send(session, {
985
+ type: "elevated:ok",
986
+ enabled: true
987
+ });
988
+ break;
989
+ }
990
+ case "elevated:disable":
991
+ session.elevated = false;
992
+ this.send(session, {
993
+ type: "elevated:ok",
994
+ enabled: false
995
+ });
996
+ break;
997
+ case "chat:message": {
998
+ const content = typeof msg.content === "string" ? msg.content : String(msg.content ?? "");
999
+ if (this.config.hooks && this.config.deps.createHookLoader) this.config.deps.createHookLoader().execute("message:received", { sessionId: session.id }).catch(() => {});
1000
+ const onDone = (response) => {
1001
+ this.send(session, {
1002
+ type: "chat:response",
1003
+ content: response
1004
+ });
1005
+ if (session.talkMode && response) this.synthesizeAndSendAudio(session, response).catch(() => {});
1006
+ if (this.config.hooks && this.config.deps.createHookLoader) this.config.deps.createHookLoader().execute("message:sent", {
1007
+ sessionId: session.id,
1008
+ message: content,
1009
+ response
1010
+ }).catch(() => {});
1011
+ };
1012
+ this.callAgent(content, {
1013
+ currentSessionId: session.id,
1014
+ onToken: (token) => this.send(session, {
1015
+ type: "chat:chunk",
1016
+ content: token
1017
+ }),
1018
+ onDone
1019
+ }).catch((e) => this.send(session, {
1020
+ type: "chat:response",
1021
+ content: `Error: ${e.message}`
1022
+ }));
1023
+ break;
1024
+ }
1025
+ case "gateway:status":
1026
+ this.send(session, {
1027
+ type: "gateway:status",
1028
+ sessions: this.sessions.size,
1029
+ uptime: this.startedAt
1030
+ });
1031
+ break;
1032
+ case "presence:list":
1033
+ this.send(session, {
1034
+ type: "presence:list",
1035
+ sessions: Array.from(this.sessions.entries()).map(([sid, s]) => ({
1036
+ id: sid,
1037
+ source: s.source
1038
+ }))
1039
+ });
1040
+ break;
1041
+ case "config:get":
1042
+ this.send(session, {
1043
+ type: "config:data",
1044
+ config: this.scrubConfig(this.loadConfig())
1045
+ });
1046
+ break;
1047
+ }
1048
+ }
1049
+ async callAgent(message, opts) {
1050
+ const sid = opts?.currentSessionId;
1051
+ const sess = sid ? this.sessions.get(sid) : void 0;
1052
+ const confirmTriggers = [
1053
+ "confirm",
1054
+ "yes",
1055
+ "ok",
1056
+ "elevate"
1057
+ ];
1058
+ if (sid && confirmTriggers.includes(message.trim().toLowerCase())) {
1059
+ const getPending = this.config.deps.getPending;
1060
+ const clearPending = this.config.deps.clearPending;
1061
+ if (getPending && clearPending) {
1062
+ const pending = getPending(sid);
1063
+ if (pending) {
1064
+ clearPending(sid);
1065
+ try {
1066
+ const result$1 = await pending.execute();
1067
+ opts?.onDone?.(result$1);
1068
+ return result$1;
1069
+ } catch (e) {
1070
+ const err = `Error: ${e.message}`;
1071
+ opts?.onDone?.(err);
1072
+ return err;
1073
+ }
1074
+ }
1075
+ }
1076
+ }
1077
+ const cfg = this.loadConfig();
1078
+ const elevated = sess?.elevated && (cfg?.tools?.elevated)?.enabled === true;
1079
+ const source = opts?.source || sess?.source;
1080
+ const hcDir = this.config.deps.getHyperClawDir();
1081
+ const effectiveKey = opts?.sessionKey || sid;
1082
+ const runOpts = {
1083
+ sessionId: sid,
1084
+ source,
1085
+ elevated,
1086
+ onToken: opts?.onToken,
1087
+ onDone: opts?.onDone,
1088
+ daemonMode: this.config.daemonMode,
1089
+ appendTranscript: (key, role, content, src) => this.appendTranscript(key, role, content, src),
1090
+ activeServer: activeServer ?? this,
1091
+ agentId: opts?.agentId,
1092
+ sessionKey: opts?.sessionKey,
1093
+ ...effectiveKey && this.sessionStore ? { getTranscript: async (k) => {
1094
+ const s = await this.sessionStore.get(k);
1095
+ return s?.transcript ?? null;
1096
+ } } : {}
1097
+ };
1098
+ if ((cfg?.observability)?.traces && this.config.deps.createRunTracer && this.config.deps.writeTraceToFile) {
1099
+ const tracer = this.config.deps.createRunTracer(sid, source);
1100
+ runOpts.onToolCall = tracer.onToolCall;
1101
+ runOpts.onToolResult = tracer.onToolResult;
1102
+ runOpts.onRunEnd = (usage, err) => {
1103
+ tracer.onRunEnd(usage, err);
1104
+ this.config.deps.writeTraceToFile(hcDir, tracer.trace).catch(() => {});
1105
+ };
1106
+ }
1107
+ const baseOnRunEnd = runOpts.onRunEnd;
1108
+ const recordUsage = this.config.deps.recordUsage;
1109
+ runOpts.onRunEnd = (usage, err) => {
1110
+ baseOnRunEnd?.(usage, err);
1111
+ const recordId = effectiveKey || sid;
1112
+ if (recordId && usage && recordUsage) recordUsage(hcDir, recordId, usage, {
1113
+ source,
1114
+ model: cfg?.provider?.modelId ?? void 0
1115
+ }).catch(() => {});
1116
+ };
1117
+ const result = await this.config.deps.runAgentEngine(message, runOpts);
1118
+ return result.text;
1119
+ }
1120
+ appendTranscript(sessionId, role, content, sourceOverride) {
1121
+ let arr = this.transcripts.get(sessionId);
1122
+ if (!arr) {
1123
+ arr = [];
1124
+ this.transcripts.set(sessionId, arr);
1125
+ }
1126
+ arr.push({
1127
+ role,
1128
+ content
1129
+ });
1130
+ if (arr.length > 100) arr.splice(0, arr.length - 80);
1131
+ const sess = this.sessions.get(sessionId);
1132
+ const storeKey = sess?.restoreKey || sessionId;
1133
+ const source = sourceOverride ?? sess?.source;
1134
+ if (this.sessionStore) this.sessionStore.append(storeKey, role, content, source).catch(() => {});
1135
+ }
1136
+ getSessionsList() {
1137
+ return Array.from(this.sessions.entries()).map(([id, s]) => ({
1138
+ id,
1139
+ source: s.source,
1140
+ connectedAt: s.connectedAt
1141
+ }));
1142
+ }
1143
+ sendToSession(sessionId, msg) {
1144
+ const s = this.sessions.get(sessionId);
1145
+ if (!s || s.socket.readyState !== ws.WebSocket.OPEN) return false;
1146
+ this.send(s, msg);
1147
+ return true;
1148
+ }
1149
+ getSessionHistory(sessionId, limit = 20) {
1150
+ const arr = this.transcripts.get(sessionId) ?? [];
1151
+ return arr.slice(-limit);
1152
+ }
1153
+ send(session, msg) {
1154
+ if (session.socket.readyState === ws.WebSocket.OPEN) session.socket.send(JSON.stringify(msg));
1155
+ }
1156
+ broadcast(msg, excludeId) {
1157
+ for (const [id, s] of this.sessions) if (id !== excludeId && s.authenticated) this.send(s, msg);
1158
+ }
1159
+ async synthesizeAndSendAudio(session, text) {
1160
+ const cfg = this.loadConfig();
1161
+ const talk = cfg?.talkMode;
1162
+ const apiKey = talk?.apiKey || process.env.ELEVENLABS_API_KEY;
1163
+ if (!apiKey) return;
1164
+ const textToSpeech = this.config.deps.textToSpeech;
1165
+ if (!textToSpeech) return;
1166
+ const audio = await textToSpeech(text.slice(0, 4e3), {
1167
+ apiKey,
1168
+ voiceId: talk?.voiceId,
1169
+ modelId: talk?.modelId || "eleven_multilingual_v2"
1170
+ });
1171
+ if (audio) this.send(session, {
1172
+ type: "chat:audio",
1173
+ format: "mp3",
1174
+ data: audio
1175
+ });
1176
+ }
1177
+ loadConfig() {
1178
+ if (this.config.deps.loadConfig) return this.config.deps.loadConfig();
1179
+ try {
1180
+ return fs_extra.default.readJsonSync(this.config.deps.getConfigPath());
1181
+ } catch {
1182
+ return null;
1183
+ }
1184
+ }
1185
+ scrubConfig(cfg) {
1186
+ if (!cfg) return null;
1187
+ const s = JSON.parse(JSON.stringify(cfg));
1188
+ if (s.provider?.apiKey) s.provider.apiKey = "***";
1189
+ if (s.gateway?.authToken) s.gateway.authToken = "***";
1190
+ return s;
1191
+ }
1192
+ getStatus() {
1193
+ return {
1194
+ running: true,
1195
+ port: this.config.port,
1196
+ sessions: this.sessions.size,
1197
+ startedAt: this.startedAt
1198
+ };
1199
+ }
1200
+ };
1201
+ const DEFAULT_PORT = 18789;
1202
+ async function startGateway(opts) {
1203
+ const deps = opts.deps;
1204
+ let base;
1205
+ let fullCfg = {};
1206
+ try {
1207
+ fullCfg = fs_extra.default.readJsonSync(deps.getConfigPath());
1208
+ base = fullCfg.gateway ?? {};
1209
+ } catch {
1210
+ base = {
1211
+ port: DEFAULT_PORT,
1212
+ bind: "127.0.0.1",
1213
+ authToken: "",
1214
+ runtime: "node",
1215
+ enabledChannels: [],
1216
+ hooks: true
1217
+ };
1218
+ }
1219
+ const portEnv = process.env.PORT || process.env.HYPERCLAW_PORT;
1220
+ const port = portEnv ? parseInt(portEnv, 10) || base.port : base.port;
1221
+ const sessionDm = fullCfg?.session?.dmScope;
1222
+ const gwDm = base.dmScope ?? sessionDm;
1223
+ const dmScope = gwDm === "main" ? "global" : gwDm === "per-peer" ? "per-channel" : gwDm;
1224
+ const cfg = {
1225
+ ...base,
1226
+ port: port ?? DEFAULT_PORT,
1227
+ bind: base.bind ?? "127.0.0.1",
1228
+ authToken: deps.resolveGatewayToken(base.authToken ?? "") ?? base.authToken ?? "",
1229
+ runtime: base.runtime ?? "node",
1230
+ enabledChannels: base.enabledChannels ?? [],
1231
+ hooks: base.hooks ?? true,
1232
+ dmScope: dmScope ?? base.dmScope,
1233
+ daemonMode: opts.daemonMode,
1234
+ deps
1235
+ };
1236
+ const server = new GatewayServer(cfg);
1237
+ await server.start();
1238
+ return server;
1239
+ }
1240
+ function getActiveServer() {
1241
+ return activeServer;
1242
+ }
1243
+ GatewayServer.prototype.getSessionsList = function() {
1244
+ const out = [];
1245
+ for (const [id, s] of this.sessions) out.push({
1246
+ id,
1247
+ source: s.source,
1248
+ connectedAt: s.connectedAt,
1249
+ lastActiveAt: s.lastActiveAt,
1250
+ talkMode: s.talkMode ?? false,
1251
+ nodeId: s.nodeId ?? null
1252
+ });
1253
+ return out;
1254
+ };
1255
+ GatewayServer.prototype.sendToSession = function(id, msg) {
1256
+ const session = this.sessions.get(id);
1257
+ if (!session || session.socket.readyState !== 1) return false;
1258
+ try {
1259
+ session.socket.send(JSON.stringify(msg));
1260
+ return true;
1261
+ } catch {
1262
+ return false;
1263
+ }
1264
+ };
1265
+ GatewayServer.prototype.getSessionHistory = function(id, limit) {
1266
+ const history = this.transcripts.get(id);
1267
+ if (!history) return [];
1268
+ return history.slice(-limit);
1269
+ };
1270
+
1271
+ //#endregion
1272
+ //#region src/gateway/deps-provider.ts
1273
+ async function createDefaultGatewayDeps() {
1274
+ const [paths, envResolve, sessionStore, channelRunner, hookLoader, core, devKeys, pendingApproval, observability, costTracker, tts, nodesRegistry, canvasRenderer, a2ui, daemon] = await Promise.all([
1275
+ Promise.resolve().then(() => require("./paths-D-QecARF.js")),
1276
+ Promise.resolve().then(() => require("./env-resolve-pIETNTpQ.js")),
1277
+ Promise.resolve().then(() => require("./session-store-7sEPyV16.js")),
1278
+ Promise.resolve().then(() => require("./runner-Cr1_mwnU.js")),
1279
+ Promise.resolve().then(() => require("./loader-Dq_cDlOW.js")),
1280
+ Promise.resolve().then(() => require("./src-CSriPfaE.js")),
1281
+ Promise.resolve().then(() => require("./developer-keys-CzDxVczE.js")),
1282
+ Promise.resolve().then(() => require("./pending-approval-C4ZaHHWl.js")),
1283
+ Promise.resolve().then(() => require("./observability-BtLyuxcz.js")),
1284
+ Promise.resolve().then(() => require("./cost-tracker-DCXDUzBI.js")),
1285
+ Promise.resolve().then(() => require("./tts-elevenlabs-y6HGWWDS.js")),
1286
+ Promise.resolve().then(() => require("./nodes-registry-DLUZhEMS.js")),
1287
+ Promise.resolve().then(() => require("./renderer-B1ToXngl.js")),
1288
+ Promise.resolve().then(() => require("./a2ui-protocol-DEsfqO7h.js")),
1289
+ Promise.resolve().then(() => require("./daemon-OqS7Ohda.js"))
1290
+ ]);
1291
+ const createSessionStore = async (baseDir) => {
1292
+ const store = await sessionStore.createFileSessionStore(baseDir);
1293
+ return store;
1294
+ };
1295
+ const createHookLoader = () => new hookLoader.HookLoader();
1296
+ const getCanvasState = async () => {
1297
+ const renderer = new canvasRenderer.CanvasRenderer();
1298
+ const canvas = await renderer.getOrCreate();
1299
+ return canvas;
1300
+ };
1301
+ const getCanvasA2UI = async () => {
1302
+ const renderer = new canvasRenderer.CanvasRenderer();
1303
+ const canvas = await renderer.getOrCreate();
1304
+ const msg = a2ui.toBeginRendering(canvas);
1305
+ return a2ui.toJSONL([msg]);
1306
+ };
1307
+ return {
1308
+ getHyperClawDir: paths.getHyperClawDir,
1309
+ getConfigPath: paths.getConfigPath,
1310
+ resolveGatewayToken: envResolve.resolveGatewayToken,
1311
+ validateApiAuth: async (bearer) => (await devKeys.validateDeveloperKey(bearer)).valid,
1312
+ createSessionStore,
1313
+ startChannelRunners: channelRunner.startChannelRunners,
1314
+ createHookLoader,
1315
+ runAgentEngine: core.runAgentEngine,
1316
+ createPiRPCHandler: core.createPiRPCHandler,
1317
+ listTraces: observability.listTraces,
1318
+ getSessionSummary: costTracker.getSessionSummary,
1319
+ getGlobalSummary: costTracker.getGlobalSummary,
1320
+ recordUsage: costTracker.recordUsage,
1321
+ textToSpeech: tts.textToSpeech,
1322
+ getPending: pendingApproval.getPending,
1323
+ clearPending: pendingApproval.clearPending,
1324
+ createRunTracer: observability.createRunTracer,
1325
+ writeTraceToFile: observability.writeTraceToFile,
1326
+ NodeRegistry: nodesRegistry.NodeRegistry,
1327
+ getCanvasState,
1328
+ getCanvasA2UI,
1329
+ restartDaemon: async () => {
1330
+ const dm = new daemon.DaemonManager();
1331
+ await dm.restart?.();
1332
+ }
1333
+ };
1334
+ }
1335
+
1336
+ //#endregion
1337
+ //#region src/gateway/server.ts
1338
+ /** Start gateway with default deps (paths, channels, hooks, etc.). */
1339
+ async function startGateway$1(opts) {
1340
+ const deps = await createDefaultGatewayDeps();
1341
+ return startGateway({
1342
+ ...opts,
1343
+ deps
1344
+ });
1345
+ }
1346
+
1347
+ //#endregion
1348
+ Object.defineProperty(exports, 'GatewayServer', {
1349
+ enumerable: true,
1350
+ get: function () {
1351
+ return GatewayServer;
1352
+ }
1353
+ });
1354
+ Object.defineProperty(exports, 'getActiveServer', {
1355
+ enumerable: true,
1356
+ get: function () {
1357
+ return getActiveServer;
1358
+ }
1359
+ });
1360
+ Object.defineProperty(exports, 'startGateway', {
1361
+ enumerable: true,
1362
+ get: function () {
1363
+ return startGateway$1;
1364
+ }
1365
+ });