@johpaz/hive-sdk 0.0.14 → 0.0.16

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 (257) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +280 -0
  3. package/docs/API-AGENTS.md +316 -0
  4. package/docs/API-CONTEXT-COMPILER.md +252 -0
  5. package/docs/API-DAG-SCHEDULER.md +273 -0
  6. package/docs/API-TOOLS-SKILLS-CHANNELS.md +350 -0
  7. package/docs/API-WORKERS-EVENTS.md +299 -0
  8. package/docs/INDEX.md +190 -0
  9. package/docs/README.md +161 -0
  10. package/docs/TEMPLATE-HIVE-APP.md +360 -0
  11. package/package.json +60 -104
  12. package/packages/cli/bin/hive +2 -0
  13. package/packages/cli/package.json +17 -0
  14. package/packages/cli/src/commands/add-skill.ts +42 -0
  15. package/packages/cli/src/commands/add-tool.ts +45 -0
  16. package/packages/cli/src/commands/add-worker.ts +49 -0
  17. package/packages/cli/src/commands/create-app-utils.ts +32 -0
  18. package/packages/cli/src/commands/create-app.test.ts +151 -0
  19. package/packages/cli/src/commands/create-app.ts +35 -0
  20. package/packages/cli/src/commands/init.ts +56 -0
  21. package/packages/cli/src/commands/run.ts +45 -0
  22. package/packages/cli/src/commands/test.ts +42 -0
  23. package/packages/cli/src/commands/trace.ts +55 -0
  24. package/packages/cli/src/index.ts +59 -0
  25. package/packages/cli/templates/hive-app/.env.example +17 -0
  26. package/packages/cli/templates/hive-app/docker-compose.yml +20 -0
  27. package/packages/cli/templates/hive-app/hive.config.ts +19 -0
  28. package/packages/cli/templates/hive-app/package.json +16 -0
  29. package/packages/cli/templates/hive-app/src/agents/coordinator.ts +9 -0
  30. package/packages/cli/templates/hive-app/src/main.ts +56 -0
  31. package/packages/core/package.json +58 -0
  32. package/packages/core/src/ace/Curator.ts +158 -0
  33. package/packages/core/src/ace/Reflector.ts +200 -0
  34. package/packages/core/src/ace/Tracer.ts +100 -0
  35. package/packages/core/src/ace/index.ts +4 -0
  36. package/packages/core/src/agent/AgentRunner.ts +699 -0
  37. package/packages/core/src/agent/Compaction.ts +221 -0
  38. package/packages/core/src/agent/ContextCompiler.ts +567 -0
  39. package/packages/core/src/agent/ContextGuard.ts +91 -0
  40. package/packages/core/src/agent/ConversationStore.ts +244 -0
  41. package/packages/core/src/agent/Hooks.ts +166 -0
  42. package/packages/core/src/agent/NativeTools.ts +31 -0
  43. package/packages/core/src/agent/PromptBuilder.ts +169 -0
  44. package/packages/core/src/agent/Service.ts +267 -0
  45. package/packages/core/src/agent/StuckLoop.ts +133 -0
  46. package/packages/core/src/agent/index.ts +12 -0
  47. package/packages/core/src/agent/providers/LLMClient.ts +149 -0
  48. package/packages/core/src/agent/providers/anthropic.ts +212 -0
  49. package/packages/core/src/agent/providers/gemini.ts +215 -0
  50. package/packages/core/src/agent/providers/index.ts +199 -0
  51. package/packages/core/src/agent/providers/interface.ts +195 -0
  52. package/packages/core/src/agent/providers/ollama.ts +175 -0
  53. package/packages/core/src/agent/providers/openai-compat.ts +231 -0
  54. package/packages/core/src/agent/selectors/PlaybookSelector.ts +147 -0
  55. package/packages/core/src/agent/selectors/SkillSelector.ts +478 -0
  56. package/packages/core/src/agent/selectors/ToolSelector.ts +577 -0
  57. package/packages/core/src/agent/selectors/index.ts +6 -0
  58. package/packages/core/src/api/createAgent.test.ts +48 -0
  59. package/packages/core/src/api/createAgent.ts +122 -0
  60. package/packages/core/src/api/index.ts +2 -0
  61. package/packages/core/src/auth/auth.ts +108 -0
  62. package/packages/core/src/auth/index.ts +1 -0
  63. package/packages/core/src/canvas/CanvasManager.ts +390 -0
  64. package/packages/core/src/canvas/a2ui-tools.ts +255 -0
  65. package/packages/core/src/canvas/canvas-tools.ts +448 -0
  66. package/packages/core/src/canvas/canvas.test.ts +32 -0
  67. package/packages/core/src/canvas/emitter.ts +149 -0
  68. package/packages/core/src/canvas/index.ts +3 -0
  69. package/packages/core/src/channels/base.ts +154 -0
  70. package/packages/core/src/channels/channels.test.ts +18 -0
  71. package/packages/core/src/channels/discord.ts +273 -0
  72. package/packages/core/src/channels/index.ts +7 -0
  73. package/packages/core/src/channels/manager.ts +450 -0
  74. package/packages/core/src/channels/slack.ts +323 -0
  75. package/packages/core/src/channels/telegram.ts +612 -0
  76. package/packages/core/src/channels/webchat.ts +139 -0
  77. package/packages/core/src/channels/whatsapp.ts +548 -0
  78. package/packages/core/src/config/index.ts +2 -0
  79. package/packages/core/src/config/loader.ts +554 -0
  80. package/packages/core/src/ethics/EthicsGuard.test.ts +54 -0
  81. package/packages/core/src/ethics/EthicsGuard.ts +66 -0
  82. package/packages/core/src/ethics/index.ts +2 -0
  83. package/packages/core/src/events/agent-bus.ts +460 -0
  84. package/packages/core/src/events/event-bus.ts +169 -0
  85. package/packages/core/src/gateway/channel-notify.ts +37 -0
  86. package/packages/core/src/gateway/gateway.test.ts +38 -0
  87. package/packages/core/src/gateway/index.ts +2 -0
  88. package/packages/core/src/gateway/server.ts +139 -0
  89. package/packages/core/src/heartbeat/index.ts +157 -0
  90. package/packages/core/src/index.ts +81 -0
  91. package/packages/core/src/mcp/MCPClient.ts +439 -0
  92. package/packages/core/src/mcp/MCPToolAdapter.ts +176 -0
  93. package/packages/core/src/mcp/config.ts +13 -0
  94. package/packages/core/src/mcp/hot-reload.ts +147 -0
  95. package/packages/core/src/mcp/index.ts +11 -0
  96. package/packages/core/src/mcp/logger.ts +42 -0
  97. package/packages/core/src/mcp/singleton.ts +21 -0
  98. package/packages/core/src/mcp/transports/index.ts +67 -0
  99. package/packages/core/src/mcp/transports/sse.ts +241 -0
  100. package/packages/core/src/mcp/transports/websocket.ts +159 -0
  101. package/packages/core/src/memory/Scratchpad.test.ts +47 -0
  102. package/packages/core/src/memory/Scratchpad.ts +37 -0
  103. package/packages/core/src/memory/Storage.ts +6 -0
  104. package/packages/core/src/memory/index.ts +2 -0
  105. package/packages/core/src/multimodal/VisionService.ts +293 -0
  106. package/packages/core/src/multimodal/index.ts +2 -0
  107. package/packages/core/src/multimodal/types.ts +28 -0
  108. package/packages/core/src/multimodal/vision-service.ts +283 -0
  109. package/packages/core/src/plugins/api.ts +128 -0
  110. package/packages/core/src/plugins/index.ts +2 -0
  111. package/packages/core/src/plugins/loader.ts +365 -0
  112. package/packages/core/src/resilience/circuit-breaker.ts +225 -0
  113. package/packages/core/src/scheduler/CronScheduler.ts +699 -0
  114. package/packages/core/src/scheduler/dag/AgentExecutor.ts +53 -0
  115. package/packages/core/src/scheduler/dag/DAGScheduler.ts +250 -0
  116. package/packages/core/src/scheduler/dag/EventBridge.ts +122 -0
  117. package/packages/core/src/scheduler/dag/TaskGraph.ts +192 -0
  118. package/packages/core/src/scheduler/dag/TaskNode.ts +97 -0
  119. package/packages/core/src/scheduler/dag/TaskResult.ts +22 -0
  120. package/packages/core/src/scheduler/dag/errors.ts +37 -0
  121. package/packages/core/src/scheduler/dag/index.ts +26 -0
  122. package/packages/core/src/scheduler/dag/presets/ResearchPreset.ts +97 -0
  123. package/packages/core/src/scheduler/dag/strategies/ParallelStrategy.ts +21 -0
  124. package/packages/core/src/scheduler/dag/strategies/PriorityStrategy.ts +46 -0
  125. package/packages/core/src/scheduler/index.ts +22 -0
  126. package/packages/core/src/scheduler/integration.ts +237 -0
  127. package/packages/core/src/scheduler/scheduler.test.ts +19 -0
  128. package/packages/core/src/scheduler/types.ts +164 -0
  129. package/packages/core/src/security/Pairing.ts +250 -0
  130. package/packages/core/src/security/RateLimit.ts +270 -0
  131. package/packages/core/src/security/google-chat.ts +269 -0
  132. package/packages/core/src/security/index.ts +192 -0
  133. package/packages/core/src/security/rate-limit.ts +270 -0
  134. package/packages/core/src/security/signal.ts +321 -0
  135. package/packages/core/src/skills/SkillLoader.ts +388 -0
  136. package/packages/core/src/skills/bundled-data.generated.ts +3332 -0
  137. package/packages/core/src/skills/defineSkill.ts +18 -0
  138. package/packages/core/src/skills/index.ts +4 -0
  139. package/packages/core/src/state/index.ts +2 -0
  140. package/packages/core/src/state/store.ts +312 -0
  141. package/packages/core/src/storage/SQLiteStorage.ts +407 -0
  142. package/packages/core/src/storage/crypto.ts +233 -0
  143. package/packages/core/src/storage/index.ts +10 -0
  144. package/packages/core/src/storage/onboarding.ts +1603 -0
  145. package/packages/core/src/storage/schema.ts +689 -0
  146. package/packages/core/src/storage/seed.ts +740 -0
  147. package/packages/core/src/storage/storage.test.ts +37 -0
  148. package/packages/core/src/storage/usage.ts +374 -0
  149. package/packages/core/src/swarm/AgentBus.ts +460 -0
  150. package/packages/core/src/swarm/AgentExecutor.ts +53 -0
  151. package/packages/core/src/swarm/Coordinator.ts +251 -0
  152. package/packages/core/src/swarm/EventBridge.ts +122 -0
  153. package/packages/core/src/swarm/EventBus.ts +169 -0
  154. package/packages/core/src/swarm/TaskGraph.ts +192 -0
  155. package/packages/core/src/swarm/TaskNode.ts +97 -0
  156. package/packages/core/src/swarm/TaskResult.ts +22 -0
  157. package/packages/core/src/swarm/WorkerPool.ts +236 -0
  158. package/packages/core/src/swarm/errors.ts +37 -0
  159. package/packages/core/src/swarm/index.ts +30 -0
  160. package/packages/core/src/swarm/presets/HiveLearnPreset.ts +99 -0
  161. package/packages/core/src/swarm/presets/ResearchPreset.ts +97 -0
  162. package/packages/core/src/swarm/presets/index.ts +4 -0
  163. package/packages/core/src/swarm/strategies/ParallelStrategy.ts +21 -0
  164. package/packages/core/src/swarm/strategies/PriorityStrategy.ts +46 -0
  165. package/packages/core/src/swarm/strategies/index.ts +3 -0
  166. package/packages/core/src/swarm/swarm.test.ts +24 -0
  167. package/packages/core/src/swarm/types.ts +164 -0
  168. package/packages/core/src/tool-runtime/index.ts +522 -0
  169. package/packages/core/src/tool-runtime/tool-runtime.test.ts +91 -0
  170. package/packages/core/src/tool-runtime/tool-worker.ts +125 -0
  171. package/packages/core/src/tools/ToolExecutor.ts +58 -0
  172. package/packages/core/src/tools/ToolRegistry.test.ts +98 -0
  173. package/packages/core/src/tools/ToolRegistry.ts +61 -0
  174. package/packages/core/src/tools/agents/get-available-models.ts +118 -0
  175. package/packages/core/src/tools/agents/index.ts +715 -0
  176. package/packages/core/src/tools/bridge-events.ts +26 -0
  177. package/packages/core/src/tools/canvas/index.ts +375 -0
  178. package/packages/core/src/tools/cli/index.ts +142 -0
  179. package/packages/core/src/tools/codebridge/index.ts +342 -0
  180. package/packages/core/src/tools/core/index.ts +476 -0
  181. package/packages/core/src/tools/cron/index.ts +626 -0
  182. package/packages/core/src/tools/filesystem/fs-delete.ts +78 -0
  183. package/packages/core/src/tools/filesystem/fs-edit.ts +106 -0
  184. package/packages/core/src/tools/filesystem/fs-exists.ts +63 -0
  185. package/packages/core/src/tools/filesystem/fs-glob.ts +108 -0
  186. package/packages/core/src/tools/filesystem/fs-list.ts +129 -0
  187. package/packages/core/src/tools/filesystem/fs-read.ts +72 -0
  188. package/packages/core/src/tools/filesystem/fs-write.ts +67 -0
  189. package/packages/core/src/tools/filesystem/index.ts +34 -0
  190. package/packages/core/src/tools/filesystem/workspace-guard.ts +62 -0
  191. package/packages/core/src/tools/index.ts +231 -0
  192. package/packages/core/src/tools/meeting/index.ts +363 -0
  193. package/packages/core/src/tools/office/index.ts +47 -0
  194. package/packages/core/src/tools/office/office-escribir-docx.ts +192 -0
  195. package/packages/core/src/tools/office/office-escribir-pdf.ts +172 -0
  196. package/packages/core/src/tools/office/office-escribir-pptx.ts +174 -0
  197. package/packages/core/src/tools/office/office-escribir-xlsx.ts +116 -0
  198. package/packages/core/src/tools/office/office-leer-docx.ts +93 -0
  199. package/packages/core/src/tools/office/office-leer-pdf.ts +114 -0
  200. package/packages/core/src/tools/office/office-leer-pptx.ts +136 -0
  201. package/packages/core/src/tools/office/office-leer-xlsx.ts +124 -0
  202. package/packages/core/src/tools/projects/index.ts +37 -0
  203. package/packages/core/src/tools/projects/project-create.ts +94 -0
  204. package/packages/core/src/tools/projects/project-done.ts +66 -0
  205. package/packages/core/src/tools/projects/project-fail.ts +66 -0
  206. package/packages/core/src/tools/projects/project-list.ts +96 -0
  207. package/packages/core/src/tools/projects/project-update.ts +72 -0
  208. package/packages/core/src/tools/projects/task-create.ts +68 -0
  209. package/packages/core/src/tools/projects/task-evaluate.ts +93 -0
  210. package/packages/core/src/tools/projects/task-update.ts +93 -0
  211. package/packages/core/src/tools/types.ts +39 -0
  212. package/packages/core/src/tools/voice/index.ts +104 -0
  213. package/packages/core/src/tools/web/browser-click.ts +78 -0
  214. package/packages/core/src/tools/web/browser-extract.ts +139 -0
  215. package/packages/core/src/tools/web/browser-navigate.ts +106 -0
  216. package/packages/core/src/tools/web/browser-screenshot.ts +87 -0
  217. package/packages/core/src/tools/web/browser-script.ts +88 -0
  218. package/packages/core/src/tools/web/browser-service.ts +554 -0
  219. package/packages/core/src/tools/web/browser-type.ts +101 -0
  220. package/packages/core/src/tools/web/browser-wait.ts +136 -0
  221. package/packages/core/src/tools/web/index.ts +41 -0
  222. package/packages/core/src/tools/web/web-fetch.ts +78 -0
  223. package/packages/core/src/tools/web/web-search.ts +123 -0
  224. package/packages/core/src/utils/benchmark.ts +80 -0
  225. package/packages/core/src/utils/crypto.ts +73 -0
  226. package/packages/core/src/utils/date.ts +42 -0
  227. package/packages/core/src/utils/index.ts +10 -0
  228. package/packages/core/src/utils/logger.ts +389 -0
  229. package/packages/core/src/utils/retry.ts +70 -0
  230. package/packages/core/src/utils/toon.ts +253 -0
  231. package/packages/core/src/voice/index.ts +643 -0
  232. package/packages/core/src/workers/WorkerPool.ts +167 -0
  233. package/packages/core/src/workers/agent.worker.ts +68 -0
  234. package/packages/core/src/workers/createWorker.ts +144 -0
  235. package/packages/core/src/workers/index.ts +5 -0
  236. package/packages/core/src/workers/workers.test.ts +48 -0
  237. package/test/setup-db.ts +216 -0
  238. package/tsconfig.json +40 -0
  239. package/src/agents.ts +0 -1
  240. package/src/canvas.ts +0 -1
  241. package/src/channels.ts +0 -1
  242. package/src/config.ts +0 -1
  243. package/src/events.ts +0 -1
  244. package/src/gateway.ts +0 -1
  245. package/src/index.ts +0 -304
  246. package/src/mcp.ts +0 -1
  247. package/src/multimodal.ts +0 -1
  248. package/src/scheduler.ts +0 -1
  249. package/src/security.ts +0 -1
  250. package/src/skills.ts +0 -1
  251. package/src/state.ts +0 -1
  252. package/src/storage.ts +0 -1
  253. package/src/tools.ts +0 -1
  254. package/src/tts.ts +0 -1
  255. package/src/types.ts +0 -82
  256. package/src/utils.ts +0 -1
  257. package/src/voice.ts +0 -1
@@ -0,0 +1,269 @@
1
+ import http, { type IncomingMessage, type ServerResponse, type Server } from "http";
2
+ import { BaseChannel, type ChannelConfig, type IncomingMessage as HiveIncomingMessage, type OutboundMessage } from "../channels/base.ts";
3
+ import { logger } from "../utils/logger.ts";
4
+ import { pairingService } from "./Pairing.ts";
5
+
6
+ export interface GoogleChatConfig extends ChannelConfig {
7
+ projectId?: string;
8
+ serviceAccountKey?: string;
9
+ webhookPort?: number;
10
+ webhookPath?: string;
11
+ }
12
+
13
+ interface GoogleChatEvent {
14
+ type: string;
15
+ eventTime: string;
16
+ space: {
17
+ name: string;
18
+ displayName: string;
19
+ type: "ROOM" | "DM";
20
+ };
21
+ message?: {
22
+ name: string;
23
+ sender: {
24
+ name: string;
25
+ displayName: string;
26
+ };
27
+ createTime: string;
28
+ text: string;
29
+ thread?: {
30
+ name: string;
31
+ };
32
+ };
33
+ user?: {
34
+ name: string;
35
+ displayName: string;
36
+ };
37
+ }
38
+
39
+ export class GoogleChatChannel extends BaseChannel {
40
+ name = "google-chat";
41
+ accountId: string;
42
+ config: GoogleChatConfig;
43
+
44
+ private server?: Server;
45
+ private log = logger.child("google-chat");
46
+ private spaceCache: Map<string, { space: string; thread?: string }> = new Map();
47
+
48
+ constructor(accountId: string, config: GoogleChatConfig) {
49
+ super();
50
+ this.accountId = accountId;
51
+ this.config = {
52
+ ...config,
53
+ dmPolicy: config.dmPolicy ?? "pairing",
54
+ allowFrom: config.allowFrom ?? [],
55
+ enabled: config.enabled ?? true,
56
+ webhookPort: config.webhookPort ?? 8080,
57
+ webhookPath: config.webhookPath ?? "/webhook/google-chat",
58
+ };
59
+ }
60
+
61
+ async start(): Promise<void> {
62
+ this.server = http.createServer((req, res) => {
63
+ if (req.url === this.config.webhookPath && req.method === "POST") {
64
+ this.handleWebhook(req, res);
65
+ } else {
66
+ res.writeHead(404).end();
67
+ }
68
+ });
69
+
70
+ return new Promise((resolve, reject) => {
71
+ this.server!.listen(this.config.webhookPort, () => {
72
+ this.running = true;
73
+ this.log.info(
74
+ `Google Chat webhook listening on port ${this.config.webhookPort}${this.config.webhookPath}`
75
+ );
76
+ resolve();
77
+ });
78
+
79
+ this.server!.on("error", (error: Error) => {
80
+ this.log.error(`Server error: ${error.message}`);
81
+ reject(error);
82
+ });
83
+ });
84
+ }
85
+
86
+ private async handleWebhook(req: IncomingMessage, res: ServerResponse): Promise<void> {
87
+ let body = "";
88
+ req.on("data", (chunk) => (body += chunk));
89
+ req.on("end", async () => {
90
+ try {
91
+ const event: GoogleChatEvent = JSON.parse(body);
92
+
93
+ if (event.type === "ADDED_TO_SPACE") {
94
+ await this.handleAddedToSpace(event, res);
95
+ return;
96
+ }
97
+
98
+ if (event.type === "REMOVED_FROM_SPACE") {
99
+ this.log.info(`Removed from space: ${event.space.name}`);
100
+ res.writeHead(200).end();
101
+ return;
102
+ }
103
+
104
+ if (event.type === "MESSAGE" && event.message) {
105
+ await this.handleChatMessage(event, res);
106
+ return;
107
+ }
108
+
109
+ res.writeHead(200).end();
110
+ } catch (error) {
111
+ this.log.error(`Webhook error: ${(error as Error).message}`);
112
+ res.writeHead(500).end();
113
+ }
114
+ });
115
+ }
116
+
117
+ private async handleAddedToSpace(
118
+ event: GoogleChatEvent,
119
+ res: ServerResponse
120
+ ): Promise<void> {
121
+ const message =
122
+ event.space.type === "DM"
123
+ ? {
124
+ text: "¡Hola! Soy tu asistente AI. Envía un mensaje para comenzar.",
125
+ }
126
+ : {
127
+ text: "¡Gracias por añadirme al espacio! Mencióname con @bot para interactuar.",
128
+ };
129
+
130
+ res.writeHead(200, { "Content-Type": "application/json" });
131
+ res.end(JSON.stringify(message));
132
+ }
133
+
134
+ private async handleChatMessage(event: GoogleChatEvent, res: ServerResponse): Promise<void> {
135
+ if (!event.message) {
136
+ res.writeHead(200).end();
137
+ return;
138
+ }
139
+
140
+ const userId = event.message.sender.name.split("/").pop() ?? "unknown";
141
+ const spaceName = event.space.name;
142
+ const isDM = event.space.type === "DM";
143
+ const kind = isDM ? "direct" : "group";
144
+ const peerId = isDM ? userId : `${spaceName}:${userId}`;
145
+
146
+ if (event.message.text === "/myid") {
147
+ res.writeHead(200, { "Content-Type": "application/json" });
148
+ res.end(
149
+ JSON.stringify({
150
+ text: `🆔 Tu Google Chat ID es: ${userId}\n\nPara emparejar, solicita un código al administrador.`,
151
+ })
152
+ );
153
+ return;
154
+ }
155
+
156
+ if (event.message.text.startsWith("/pair ")) {
157
+ const code = event.message.text.split(" ")[1]?.trim();
158
+ const result = pairingService.approve(code ?? "");
159
+
160
+ res.writeHead(200, { "Content-Type": "application/json" });
161
+ res.end(
162
+ JSON.stringify({
163
+ text: result.success
164
+ ? "✅ ¡Emparejamiento exitoso!"
165
+ : `❌ ${result.error}`,
166
+ })
167
+ );
168
+ return;
169
+ }
170
+
171
+ if (this.config.dmPolicy === "pairing" && !pairingService.isAllowed("google-chat", userId)) {
172
+ this.log.debug(`Message from unpaired user: ${userId}`);
173
+ res.writeHead(200, { "Content-Type": "application/json" });
174
+ res.end(
175
+ JSON.stringify({
176
+ text:
177
+ "⛔ No estás emparejado.\n\n" +
178
+ "Tu ID: " +
179
+ userId +
180
+ "\n\n" +
181
+ "Solicita un código de emparejamiento al administrador.",
182
+ })
183
+ );
184
+ return;
185
+ }
186
+
187
+ if (!isDM && !this.isUserAllowed(peerId)) {
188
+ this.log.debug(`Message from unauthorized user: ${peerId}`);
189
+ res.writeHead(200).end();
190
+ return;
191
+ }
192
+
193
+ const sessionId = this.formatSessionId(peerId, kind);
194
+ this.spaceCache.set(sessionId, {
195
+ space: spaceName,
196
+ thread: event.message.thread?.name,
197
+ });
198
+
199
+ const incomingMessage: HiveIncomingMessage = {
200
+ sessionId,
201
+ channel: "google-chat",
202
+ accountId: this.accountId,
203
+ peerId,
204
+ peerKind: kind,
205
+ content: event.message.text,
206
+ metadata: {
207
+ googleChat: {
208
+ spaceName,
209
+ userId,
210
+ displayName: event.message.sender.displayName,
211
+ threadName: event.message.thread?.name,
212
+ },
213
+ },
214
+ };
215
+
216
+ res.writeHead(200).end();
217
+
218
+ await this.handleMessage(incomingMessage);
219
+ }
220
+
221
+ async stop(): Promise<void> {
222
+ if (this.server) {
223
+ return new Promise((resolve) => {
224
+ this.server!.close(() => {
225
+ this.running = false;
226
+ this.log.info("Google Chat channel stopped");
227
+ resolve();
228
+ });
229
+ });
230
+ }
231
+ }
232
+
233
+ async send(sessionId: string, message: OutboundMessage): Promise<void> {
234
+ const content = message.content ?? "";
235
+
236
+ if (!content || content.trim().length === 0) {
237
+ this.log.warn("Empty response, skipping send");
238
+ return;
239
+ }
240
+
241
+ const cached = this.spaceCache.get(sessionId);
242
+
243
+ if (!cached) {
244
+ this.log.warn(`No cached space for session: ${sessionId}`);
245
+ return;
246
+ }
247
+
248
+ if (message.type === "stream" && message.chunk) {
249
+ this.log.info(`[Google Chat] Stream chunk to ${cached.space}: ${message.chunk.slice(0, 50)}...`);
250
+ return;
251
+ }
252
+
253
+ this.log.info(`[Google Chat] Would send to ${cached.space}: ${content.slice(0, 100)}...`);
254
+ }
255
+
256
+ async sendMessage(space: string, content: string, thread?: string): Promise<void> {
257
+ this.log.info(`[Google Chat] Sending to ${space}: ${content.slice(0, 100)}...`);
258
+ if (thread) {
259
+ this.log.info(` Thread: ${thread}`);
260
+ }
261
+ }
262
+ }
263
+
264
+ export function createGoogleChatChannel(
265
+ accountId: string,
266
+ config: GoogleChatConfig
267
+ ): GoogleChatChannel {
268
+ return new GoogleChatChannel(accountId, config);
269
+ }
@@ -0,0 +1,192 @@
1
+ import type { Config } from "../config/loader.ts";
2
+ import { logger } from "../utils/logger.ts";
3
+
4
+ export * from "./Pairing.ts";
5
+ export * from "./rate-limit.ts";
6
+ export * from "./signal.ts";
7
+ export * from "./google-chat.ts";
8
+
9
+ export interface RateLimitConfig {
10
+ windowMs: number;
11
+ maxRequests: number;
12
+ }
13
+
14
+ export interface RateLimitEntry {
15
+ count: number;
16
+ resetAt: number;
17
+ }
18
+
19
+ export class RateLimiter {
20
+ private limits: Map<string, RateLimitEntry> = new Map();
21
+ private config: RateLimitConfig;
22
+ private log = logger.child("rate-limiter");
23
+
24
+ constructor(config: RateLimitConfig) {
25
+ this.config = config;
26
+ this.startCleanup();
27
+ }
28
+
29
+ check(key: string): { allowed: boolean; remaining: number; resetAt: number } {
30
+ const now = Date.now();
31
+ const entry = this.limits.get(key);
32
+
33
+ if (!entry || now > entry.resetAt) {
34
+ const resetAt = now + this.config.windowMs;
35
+ this.limits.set(key, { count: 1, resetAt });
36
+ return { allowed: true, remaining: this.config.maxRequests - 1, resetAt };
37
+ }
38
+
39
+ if (entry.count >= this.config.maxRequests) {
40
+ this.log.warn(`Rate limit exceeded for ${key}`);
41
+ return { allowed: false, remaining: 0, resetAt: entry.resetAt };
42
+ }
43
+
44
+ entry.count++;
45
+ return {
46
+ allowed: true,
47
+ remaining: this.config.maxRequests - entry.count,
48
+ resetAt: entry.resetAt
49
+ };
50
+ }
51
+
52
+ reset(key: string): void {
53
+ this.limits.delete(key);
54
+ }
55
+
56
+ private startCleanup(): void {
57
+ setInterval(() => {
58
+ const now = Date.now();
59
+ for (const [key, entry] of this.limits) {
60
+ if (now > entry.resetAt) {
61
+ this.limits.delete(key);
62
+ }
63
+ }
64
+ }, this.config.windowMs);
65
+ }
66
+ }
67
+
68
+ export class InputValidator {
69
+ private maxMessageLength: number;
70
+ private maxCommandArgs: number;
71
+ private log = logger.child("validator");
72
+
73
+ constructor(options: { maxMessageLength?: number; maxCommandArgs?: number } = {}) {
74
+ this.maxMessageLength = options.maxMessageLength ?? 100000;
75
+ this.maxCommandArgs = options.maxCommandArgs ?? 50;
76
+ }
77
+
78
+ validateMessage(content: string): { valid: boolean; error?: string } {
79
+ if (typeof content !== "string") {
80
+ return { valid: false, error: "Message must be a string" };
81
+ }
82
+
83
+ if (content.length === 0) {
84
+ return { valid: false, error: "Message cannot be empty" };
85
+ }
86
+
87
+ if (content.length > this.maxMessageLength) {
88
+ this.log.warn(`Message too long: ${content.length} > ${this.maxMessageLength}`);
89
+ return {
90
+ valid: false,
91
+ error: `Message too long (max ${this.maxMessageLength} characters)`
92
+ };
93
+ }
94
+
95
+ return { valid: true };
96
+ }
97
+
98
+ validateCommand(name: string, args: string[]): { valid: boolean; error?: string } {
99
+ if (!name || typeof name !== "string") {
100
+ return { valid: false, error: "Command name is required" };
101
+ }
102
+
103
+ if (!/^[a-z0-9_-]+$/.test(name)) {
104
+ return { valid: false, error: "Invalid command name format" };
105
+ }
106
+
107
+ if (args.length > this.maxCommandArgs) {
108
+ return { valid: false, error: `Too many arguments (max ${this.maxCommandArgs})` };
109
+ }
110
+
111
+ return { valid: true };
112
+ }
113
+
114
+ validateSessionId(sessionId: string): { valid: boolean; error?: string } {
115
+ if (!sessionId || typeof sessionId !== "string") {
116
+ return { valid: false, error: "Session ID is required" };
117
+ }
118
+
119
+ const pattern = /^agent:[a-z0-9_-]+:[a-z0-9_-]+:(main|dm|group)(?::[a-z0-9_-]+)?$/;
120
+ if (!pattern.test(sessionId)) {
121
+ return { valid: false, error: "Invalid session ID format" };
122
+ }
123
+
124
+ return { valid: true };
125
+ }
126
+
127
+ sanitizeInput(input: string): string {
128
+ return input
129
+ .replace(/\x00/g, "")
130
+ .replace(/[\x1F\x7F]/g, "")
131
+ .trim();
132
+ }
133
+ }
134
+
135
+ export class AuthManager {
136
+ private config: Config;
137
+ private allowedUsers: Set<string>;
138
+ private log = logger.child("auth");
139
+
140
+ constructor(config: Config) {
141
+ this.config = config;
142
+ this.allowedUsers = new Set(config.security?.allowedUsers ?? []);
143
+ }
144
+
145
+ isAllowed(peerId: string, channel: string): boolean {
146
+ if (this.allowedUsers.size === 0) {
147
+ return true;
148
+ }
149
+
150
+ const channelConfig = this.config.channels?.[channel as keyof typeof this.config.channels];
151
+ if (channelConfig && typeof channelConfig === "object" && "allowFrom" in channelConfig) {
152
+ const allowFrom = (channelConfig as { allowFrom?: string[] }).allowFrom;
153
+ if (allowFrom && allowFrom.length > 0) {
154
+ return allowFrom.includes(peerId);
155
+ }
156
+ }
157
+
158
+ return this.allowedUsers.has(peerId);
159
+ }
160
+
161
+ addAllowedUser(peerId: string): void {
162
+ this.allowedUsers.add(peerId);
163
+ this.log.info(`Added allowed user: ${peerId}`);
164
+ }
165
+
166
+ removeAllowedUser(peerId: string): boolean {
167
+ const removed = this.allowedUsers.delete(peerId);
168
+ if (removed) {
169
+ this.log.info(`Removed allowed user: ${peerId}`);
170
+ }
171
+ return removed;
172
+ }
173
+
174
+ listAllowedUsers(): string[] {
175
+ return Array.from(this.allowedUsers);
176
+ }
177
+ }
178
+
179
+ export function createRateLimiter(config: RateLimitConfig): RateLimiter {
180
+ return new RateLimiter(config);
181
+ }
182
+
183
+ export function createInputValidator(options?: {
184
+ maxMessageLength?: number;
185
+ maxCommandArgs?: number;
186
+ }): InputValidator {
187
+ return new InputValidator(options);
188
+ }
189
+
190
+ export function createAuthManager(config: Config): AuthManager {
191
+ return new AuthManager(config);
192
+ }