hyperclaw 5.0.1 → 5.0.2

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