hyperclaw 5.2.3 → 5.2.4

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