@johpaz/hive-agents 0.0.5 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hive.js CHANGED
@@ -15328,21 +15328,7 @@ function buildDefaultConfig() {
15328
15328
  function loadConfig() {
15329
15329
  return buildDefaultConfig();
15330
15330
  }
15331
- function expandConfigPath(p) {
15332
- if (!p)
15333
- return;
15334
- return expandPath(p);
15335
- }
15336
- var LogLevelSchema, DMPolicySchema, TransportSchema, expandPath = (p) => {
15337
- if (p.startsWith("~/.hive")) {
15338
- const hiveDir = getHiveDir();
15339
- return p.replace("~/.hive", hiveDir);
15340
- }
15341
- if (p.startsWith("~")) {
15342
- return path.join(process.env.HOME || "", p.slice(1));
15343
- }
15344
- return p;
15345
- }, ProviderConfigSchema, ToolRestrictionsSchema, ExecConfigSchema, WebConfigSchema, BrowserConfigSchema, CanvasConfigSchema, SandboxConfigSchema, ToolsConfigSchema, ContextConfigSchema, AgentEntrySchema, AccountConfigSchema, ChannelConfigSchema, PeerMatchSchema, BindingMatchSchema, BindingSchema, MCPServerConfigSchema, MCPConfigSchema, EpisodicMemoryConfigSchema, MemoryConfigSchema, CronConfigSchema, RetryConfigSchema, HooksConfigSchema, LoggingConfigSchema, GatewayConfigSchema, ModelsConfigSchema, SessionsConfigSchema, SkillsConfigSchema, SecurityConfigSchema, CaptchaConfigSchema, UserConfigSchema, ConfigSchema;
15331
+ var LogLevelSchema, DMPolicySchema, TransportSchema, ProviderConfigSchema, ToolRestrictionsSchema, ExecConfigSchema, WebConfigSchema, BrowserConfigSchema, CanvasConfigSchema, SandboxConfigSchema, ToolsConfigSchema, ContextConfigSchema, AgentEntrySchema, AccountConfigSchema, ChannelConfigSchema, PeerMatchSchema, BindingMatchSchema, BindingSchema, MCPServerConfigSchema, MCPConfigSchema, EpisodicMemoryConfigSchema, MemoryConfigSchema, CronConfigSchema, RetryConfigSchema, HooksConfigSchema, LoggingConfigSchema, GatewayConfigSchema, ModelsConfigSchema, SessionsConfigSchema, SkillsConfigSchema, SecurityConfigSchema, CaptchaConfigSchema, UserConfigSchema, ConfigSchema;
15346
15332
  var init_loader = __esm(() => {
15347
15333
  init_zod();
15348
15334
  LogLevelSchema = _enum2(["debug", "info", "warn", "error"]);
@@ -15596,7 +15582,7 @@ function emitLogEntry(entry) {
15596
15582
  } catch {}
15597
15583
  }
15598
15584
  }
15599
- function expandPath2(p) {
15585
+ function expandPath(p) {
15600
15586
  if (p.startsWith("~")) {
15601
15587
  return path2.join(process.env.HOME || "", p.slice(1));
15602
15588
  }
@@ -15665,7 +15651,7 @@ class Logger {
15665
15651
  return this;
15666
15652
  }
15667
15653
  initLogFile() {
15668
- const logDir = expandPath2(this.config.dir);
15654
+ const logDir = expandPath(this.config.dir);
15669
15655
  try {
15670
15656
  if (!existsSync2(logDir)) {
15671
15657
  mkdirSync2(logDir, { recursive: true });
@@ -15900,6 +15886,8 @@ var SCHEMA = `
15900
15886
  occupation TEXT,
15901
15887
  notes TEXT,
15902
15888
  master_key_hash TEXT,
15889
+ email TEXT UNIQUE,
15890
+ password_hash TEXT,
15903
15891
  preferred_cron_channel TEXT NOT NULL DEFAULT 'auto',
15904
15892
  created_at INTEGER NOT NULL DEFAULT (unixepoch())
15905
15893
  );
@@ -16541,6 +16529,8 @@ function ensureColumnExists(tableName, columnName, columnDefinition) {
16541
16529
  function ensureSchemaSync() {
16542
16530
  if (!_db)
16543
16531
  return;
16532
+ ensureColumnExists("users", "email", "TEXT");
16533
+ ensureColumnExists("users", "password_hash", "TEXT");
16544
16534
  ensureColumnExists("mcp_servers", "tools_count", "INTEGER DEFAULT 0");
16545
16535
  ensureColumnExists("mcp_servers", "status", "TEXT NOT NULL DEFAULT 'disconnected'");
16546
16536
  ensureColumnExists("mcp_servers", "env_encrypted", "TEXT");
@@ -19983,11 +19973,6 @@ var init_seed = __esm(() => {
19983
19973
  { id: "whisper-large-v3", providerId: "groq", name: "Whisper Large V3", modelType: "stt", contextWindow: 0, capabilities: JSON.stringify(["transcription"]) },
19984
19974
  { id: "whisper-large-v3-turbo", providerId: "groq", name: "Whisper Large V3 Turbo", modelType: "stt", contextWindow: 0, capabilities: JSON.stringify(["transcription"]) },
19985
19975
  { id: "distil-whisper-large-v3-en", providerId: "groq", name: "Distil Whisper V3 EN", modelType: "stt", contextWindow: 0, capabilities: JSON.stringify(["transcription", "english"]) },
19986
- { id: "qwen3:4b", providerId: "ollama", name: "Qwen3 4B", modelType: "llm", contextWindow: 32000, capabilities: JSON.stringify(["chat", "json_mode", "streaming"]) },
19987
- { id: "qwen3:8b", providerId: "ollama", name: "Qwen3 8B", modelType: "llm", contextWindow: 32000, capabilities: JSON.stringify(["chat", "json_mode", "function_calling", "streaming"]) },
19988
- { id: "qwen3:14b", providerId: "ollama", name: "Qwen3 14B", modelType: "llm", contextWindow: 32000, capabilities: JSON.stringify(["chat", "json_mode", "function_calling", "streaming"]) },
19989
- { id: "llama3.2:3b", providerId: "ollama", name: "Llama 3.2 3B", modelType: "llm", contextWindow: 128000, capabilities: JSON.stringify(["chat", "json_mode", "streaming"]) },
19990
- { id: "gemma3:9b", providerId: "ollama", name: "Gemma 3 9B", modelType: "llm", contextWindow: 128000, capabilities: JSON.stringify(["chat", "json_mode", "streaming"]) },
19991
19976
  { id: "eleven_flash_v2_5", providerId: "elevenlabs", name: "Eleven Flash V2.5", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "speech", "fast"]) },
19992
19977
  { id: "eleven_turbo_v2_5", providerId: "elevenlabs", name: "Eleven Turbo V2.5", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "speech", "balanced"]) },
19993
19978
  { id: "eleven_multilingual_v2", providerId: "elevenlabs", name: "Eleven Multilingual V2", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "multilingual"]) },
@@ -20204,6 +20189,12 @@ async function saveProviderConfig(data) {
20204
20189
  WHERE id = ?
20205
20190
  `).run(apiKeyEncrypted, apiKeyIv, data.baseUrl || null, data.provider);
20206
20191
  log2.info("\u2705 Provider actualizado:", { provider: data.provider });
20192
+ if (data.provider === "ollama" && data.model) {
20193
+ db.query(`
20194
+ INSERT OR IGNORE INTO models (id, name, provider_id, model_type, enabled, active)
20195
+ VALUES (?, ?, 'ollama', 'llm', 1, 1)
20196
+ `).run(data.model, data.model);
20197
+ }
20207
20198
  db.query(`
20208
20199
  UPDATE models SET enabled = 1, active = 1
20209
20200
  WHERE id = ?
@@ -20232,13 +20223,17 @@ function saveAgentConfig(data) {
20232
20223
  try {
20233
20224
  const db = getDb();
20234
20225
  let finalAgentId = data.agentId;
20226
+ const rawProviderId = data.providerId || null;
20227
+ const rawModelId = data.modelId || null;
20228
+ const safeProviderId = rawProviderId && db.query("SELECT id FROM providers WHERE id = ?").get(rawProviderId) ? rawProviderId : null;
20229
+ const safeModelId = rawModelId && db.query("SELECT id FROM models WHERE id = ?").get(rawModelId) ? rawModelId : null;
20235
20230
  if (!finalAgentId) {
20236
20231
  const result2 = db.query(`
20237
20232
  INSERT INTO agents
20238
20233
  (user_id, name, description, tone, system_prompt, provider_id, model_id, status, role, enabled)
20239
20234
  VALUES (?, ?, ?, ?, ?, ?, ?, 'idle', 'coordinator', 1)
20240
20235
  RETURNING id
20241
- `).get(data.userId, data.agentName, data.description || null, data.tone, HIVE_SYSTEM_PROMPT, data.providerId || null, data.modelId || null);
20236
+ `).get(data.userId, data.agentName, data.description || null, data.tone, HIVE_SYSTEM_PROMPT, safeProviderId, safeModelId);
20242
20237
  finalAgentId = result2.id;
20243
20238
  log2.info("\u2705 Agent created with auto-generated ID", { agentId: finalAgentId });
20244
20239
  } else {
@@ -20257,7 +20252,7 @@ function saveAgentConfig(data) {
20257
20252
  status = 'idle',
20258
20253
  enabled = 1,
20259
20254
  role = 'coordinator'
20260
- `).run(data.agentId, data.userId, data.agentName, data.description || null, data.tone, HIVE_SYSTEM_PROMPT, data.providerId || null, data.modelId || null);
20255
+ `).run(data.agentId, data.userId, data.agentName, data.description || null, data.tone, HIVE_SYSTEM_PROMPT, safeProviderId, safeModelId);
20261
20256
  }
20262
20257
  return finalAgentId;
20263
20258
  } catch (e) {
@@ -55931,56 +55926,54 @@ class OllamaProvider {
55931
55926
  const { Ollama: Ollama3 } = await Promise.resolve().then(() => (init_dist3(), exports_dist2));
55932
55927
  const modelName = options2.model.replace(/^ollama\//, "");
55933
55928
  const host = options2.baseUrl?.trim() || process.env.OLLAMA_HOST || "http://localhost:11434";
55934
- try {
55935
- const isCloud = host.includes("ollama.com");
55936
- const headers = {};
55937
- if (isCloud && options2.apiKey) {
55938
- headers["Authorization"] = `Bearer ${options2.apiKey}`;
55929
+ const isCloud = host.includes("ollama.com");
55930
+ const headers = {};
55931
+ if (isCloud && options2.apiKey)
55932
+ headers["Authorization"] = `Bearer ${options2.apiKey}`;
55933
+ const client = new Ollama3({
55934
+ host,
55935
+ ...Object.keys(headers).length ? { headers } : {}
55936
+ });
55937
+ const messages = sanitizeMessages(options2.messages).map((m) => {
55938
+ if (m.role === "assistant" && m.tool_calls?.length) {
55939
+ return {
55940
+ role: "assistant",
55941
+ content: m.content || "",
55942
+ tool_calls: m.tool_calls.map((tc) => ({
55943
+ function: {
55944
+ name: tc.function.name,
55945
+ arguments: (() => {
55946
+ try {
55947
+ return JSON.parse(tc.function.arguments);
55948
+ } catch {
55949
+ return {};
55950
+ }
55951
+ })()
55952
+ }
55953
+ }))
55954
+ };
55939
55955
  }
55940
- const client = new Ollama3({
55941
- host,
55942
- ...Object.keys(headers).length ? { headers } : {}
55943
- });
55944
- const messages = sanitizeMessages(options2.messages).map((m) => {
55945
- if (m.role === "assistant" && m.tool_calls?.length) {
55946
- return {
55947
- role: "assistant",
55948
- content: m.content || "",
55949
- tool_calls: m.tool_calls.map((tc) => ({
55950
- function: {
55951
- name: tc.function.name,
55952
- arguments: (() => {
55953
- try {
55954
- return JSON.parse(tc.function.arguments);
55955
- } catch {
55956
- return {};
55957
- }
55958
- })()
55959
- }
55960
- }))
55961
- };
55962
- }
55963
- if (m.role === "tool") {
55964
- return { role: "tool", content: m.content };
55965
- }
55966
- return { role: m.role, content: m.content };
55967
- });
55968
- const tools = options2.tools?.map((t2) => ({
55969
- type: "function",
55970
- function: {
55971
- name: t2.function.name,
55972
- description: t2.function.description,
55973
- parameters: t2.function.parameters
55974
- }
55975
- }));
55976
- const runtimeOptions = {};
55977
- if (options2.numCtx)
55978
- runtimeOptions.num_ctx = options2.numCtx;
55979
- if (options2.numGpu !== undefined)
55980
- runtimeOptions.num_gpu = options2.numGpu;
55981
- if (options2.temperature !== undefined)
55982
- runtimeOptions.temperature = options2.temperature;
55983
- log9.info(`[llm-client] ollama/${modelName} @ ${isCloud ? "ollama.com" : host} stream=true` + ` \u2014 ${messages.length} msgs, ${tools?.length ?? 0} tools` + (options2.numCtx ? ` num_ctx=${options2.numCtx}` : ""));
55956
+ if (m.role === "tool")
55957
+ return { role: "tool", content: m.content };
55958
+ return { role: m.role, content: m.content };
55959
+ });
55960
+ const tools = options2.tools?.map((t2) => ({
55961
+ type: "function",
55962
+ function: {
55963
+ name: t2.function.name,
55964
+ description: t2.function.description,
55965
+ parameters: t2.function.parameters
55966
+ }
55967
+ }));
55968
+ const runtimeOptions = {
55969
+ num_ctx: options2.numCtx ?? 4096
55970
+ };
55971
+ if (options2.numGpu !== undefined)
55972
+ runtimeOptions.num_gpu = options2.numGpu;
55973
+ if (options2.temperature !== undefined)
55974
+ runtimeOptions.temperature = options2.temperature;
55975
+ try {
55976
+ log9.info(`[llm-client] ollama/${modelName} @ ${isCloud ? "ollama.com" : host} stream=true` + ` \u2014 ${messages.length} msgs, ${tools?.length ?? 0} tools num_ctx=${runtimeOptions.num_ctx}`);
55984
55977
  const stream = await client.chat({
55985
55978
  model: modelName,
55986
55979
  messages,
@@ -56029,8 +56022,25 @@ class OllamaProvider {
56029
56022
  log9.error(`[llm-client] Context requested: num_ctx=${options2.numCtx}`);
56030
56023
  if (options2.tools?.length)
56031
56024
  log9.error(`[llm-client] Tools defined: ${options2.tools.length}`);
56032
- if (error49.message?.includes("model runner has unexpectedly stopped")) {
56033
- log9.warn(`[llm-client] TIP: This usually means Ollama ran out of VRAM/RAM. Try reducing 'num_ctx' or the number of tools.`);
56025
+ if (error49.message?.includes("model runner has unexpectedly stopped") && tools?.length) {
56026
+ log9.warn(`[llm-client] OOM with tools \u2014 retrying without tools (num_ctx=${runtimeOptions.num_ctx})`);
56027
+ const stream2 = await client.chat({
56028
+ model: modelName,
56029
+ messages,
56030
+ tools: undefined,
56031
+ options: runtimeOptions,
56032
+ stream: true
56033
+ });
56034
+ let content = "";
56035
+ for await (const part of stream2) {
56036
+ const delta = part.message?.content ?? "";
56037
+ if (delta) {
56038
+ content += delta;
56039
+ if (options2.onToken)
56040
+ options2.onToken(delta);
56041
+ }
56042
+ }
56043
+ return { content, tool_calls: undefined, stop_reason: "stop" };
56034
56044
  }
56035
56045
  throw error49;
56036
56046
  }
@@ -64290,7 +64300,7 @@ var init_prompt_builder = __esm(() => {
64290
64300
  // packages/core/src/tools/filesystem/workspace-guard.ts
64291
64301
  import * as path10 from "path";
64292
64302
  import * as os from "os";
64293
- function expandPath3(p) {
64303
+ function expandPath2(p) {
64294
64304
  if (p.startsWith("~")) {
64295
64305
  return path10.join(os.homedir(), p.slice(1));
64296
64306
  }
@@ -64300,7 +64310,7 @@ function resolveInWorkspace(filePath, workspace) {
64300
64310
  if (!workspace) {
64301
64311
  return filePath;
64302
64312
  }
64303
- const wsRoot = path10.resolve(expandPath3(workspace));
64313
+ const wsRoot = path10.resolve(expandPath2(workspace));
64304
64314
  let resolved;
64305
64315
  if (path10.isAbsolute(filePath)) {
64306
64316
  resolved = path10.normalize(filePath);
@@ -64628,7 +64638,7 @@ var init_fs_list = __esm(() => {
64628
64638
  },
64629
64639
  execute: async (params2, config2) => {
64630
64640
  const workspace = getWorkspace(config2);
64631
- const rawPath = params2.path ?? (workspace ? expandPath3(workspace) : ".");
64641
+ const rawPath = params2.path ?? (workspace ? expandPath2(workspace) : ".");
64632
64642
  let dirPath;
64633
64643
  try {
64634
64644
  dirPath = resolveInWorkspace(rawPath, workspace);
@@ -64725,7 +64735,7 @@ var init_fs_glob = __esm(() => {
64725
64735
  },
64726
64736
  execute: async (params2, config2) => {
64727
64737
  const workspace = getWorkspace(config2);
64728
- const rawBase = params2.basePath ?? (workspace ? expandPath3(workspace) : ".");
64738
+ const rawBase = params2.basePath ?? (workspace ? expandPath2(workspace) : ".");
64729
64739
  let base;
64730
64740
  try {
64731
64741
  base = resolveInWorkspace(rawBase, workspace);
@@ -317839,7 +317849,7 @@ var init_cli = __esm(() => {
317839
317849
  const timeoutSecs = Math.min(params2.timeout ?? 30, 300);
317840
317850
  const timeoutMs = timeoutSecs * 1000;
317841
317851
  const workspace = getWorkspace(config3);
317842
- const defaultCwd = workspace ? expandPath3(workspace) : process.cwd();
317852
+ const defaultCwd = workspace ? expandPath2(workspace) : process.cwd();
317843
317853
  let cwd;
317844
317854
  try {
317845
317855
  const rawCwd = params2.cwd ?? defaultCwd;
@@ -499906,6 +499916,7 @@ var import_qrcode_terminal, WhatsAppChannel;
499906
499916
  var init_whatsapp = __esm(() => {
499907
499917
  init_lib8();
499908
499918
  init_logger();
499919
+ init_sqlite();
499909
499920
  import_qrcode_terminal = __toESM(require_main2(), 1);
499910
499921
  WhatsAppChannel = class WhatsAppChannel extends BaseChannel {
499911
499922
  name = "whatsapp";
@@ -499967,6 +499978,7 @@ var init_whatsapp = __esm(() => {
499967
499978
  version: version4,
499968
499979
  auth: state2,
499969
499980
  printQRInTerminal: false,
499981
+ syncFullHistory: false,
499970
499982
  getMessage: async () => ({ conversation: "" })
499971
499983
  });
499972
499984
  this.socket.ev.on("connection.update", async (update) => {
@@ -499997,7 +500009,10 @@ var init_whatsapp = __esm(() => {
499997
500009
  const shouldReconnect = statusCode !== DisconnectReason.loggedOut;
499998
500010
  this.connectionState.status = "disconnected";
499999
500011
  this.log.warn(`WhatsApp disconnected: ${statusCode}`);
500000
- const needsSessionClear = statusCode === DisconnectReason.loggedOut || statusCode === DisconnectReason.badSession || statusCode === 515;
500012
+ try {
500013
+ getDb().query(`UPDATE channels SET status = ? WHERE id = ?`).run(shouldReconnect ? "connecting" : "disconnected", this.accountId);
500014
+ } catch {}
500015
+ const needsSessionClear = statusCode === DisconnectReason.loggedOut || statusCode === DisconnectReason.badSession;
500001
500016
  if (needsSessionClear) {
500002
500017
  this.log.info("Clearing WhatsApp session files for fresh QR scan.");
500003
500018
  rmSync2(this.authPath, { recursive: true, force: true });
@@ -500014,6 +500029,9 @@ var init_whatsapp = __esm(() => {
500014
500029
  this.connectionState.qrCode = undefined;
500015
500030
  saveCreds();
500016
500031
  this.log.info("WhatsApp connected successfully");
500032
+ try {
500033
+ getDb().query(`UPDATE channels SET status = 'connected', last_active = ? WHERE id = ?`).run(Date.now(), this.accountId);
500034
+ } catch {}
500017
500035
  }
500018
500036
  }
500019
500037
  hasCredentials() {
@@ -500043,11 +500061,17 @@ var init_whatsapp = __esm(() => {
500043
500061
  return;
500044
500062
  for (const msg of update.messages) {
500045
500063
  const typedMsg = msg;
500046
- if (typedMsg.key.fromMe)
500047
- continue;
500048
500064
  const from2 = typedMsg.key.remoteJid;
500049
500065
  if (!from2)
500050
500066
  continue;
500067
+ if (from2.includes("@g.us"))
500068
+ continue;
500069
+ const rawOwnJid = this.socket?.user?.id ?? "";
500070
+ const ownNumber = rawOwnJid.split(":")[0];
500071
+ const fromNumber2 = from2.split("@")[0];
500072
+ const isSelfMessage = typedMsg.key.fromMe && fromNumber2 === ownNumber;
500073
+ if (!isSelfMessage)
500074
+ continue;
500051
500075
  const { content, audioMediaId } = this.extractMessageContent(typedMsg.message);
500052
500076
  if (!content && !audioMediaId)
500053
500077
  continue;
@@ -545277,11 +545301,12 @@ var init_slack = __esm(() => {
545277
545301
  constructor(config3) {
545278
545302
  super();
545279
545303
  this.config = config3;
545280
- const extractedAccountId = config3.botToken.split(":")[0]?.replace("xoxb-", "");
545281
- if (!extractedAccountId) {
545282
- throw new Error("Could not determine account ID from Slack token");
545304
+ if (config3.accountId) {
545305
+ this.accountId = config3.accountId;
545306
+ } else {
545307
+ const extracted = config3.botToken?.split(":")[0]?.replace("xoxb-", "") ?? "";
545308
+ this.accountId = extracted || "slack";
545283
545309
  }
545284
- this.accountId = extractedAccountId;
545285
545310
  }
545286
545311
  async start() {
545287
545312
  this.running = true;
@@ -545309,7 +545334,6 @@ var init_slack = __esm(() => {
545309
545334
  });
545310
545335
  this.app = new import_bolt.App({
545311
545336
  token: this.config.botToken,
545312
- appToken: this.config.appToken,
545313
545337
  receiver
545314
545338
  });
545315
545339
  this.app.event("app_mention", async ({ event }) => {
@@ -545571,22 +545595,29 @@ class ChannelManager {
545571
545595
  allowFrom: []
545572
545596
  });
545573
545597
  break;
545574
- case "whatsapp":
545598
+ case "whatsapp": {
545599
+ let coordinatorId = "main";
545600
+ try {
545601
+ const coordinator = getDb().query(`SELECT id FROM agents WHERE role = 'coordinator' LIMIT 1`).get();
545602
+ if (coordinator?.id)
545603
+ coordinatorId = coordinator.id;
545604
+ } catch {}
545575
545605
  channel = createWhatsAppChannel({
545576
545606
  enabled: true,
545577
545607
  accountId,
545578
- agentId: config3.agentId ?? "main",
545608
+ agentId: config3.agentId ?? coordinatorId,
545579
545609
  dmPolicy: config3.dmPolicy ?? "allowlist",
545580
545610
  allowFrom: config3.allowFrom ?? [],
545581
545611
  reconnectMaxAttempts: config3.reconnectMaxAttempts ?? 10,
545582
545612
  reconnectBaseDelayMs: config3.reconnectBaseDelayMs ?? 5000
545583
545613
  });
545584
545614
  break;
545615
+ }
545585
545616
  case "slack":
545586
545617
  channel = createSlackChannel({
545587
545618
  enabled: true,
545619
+ accountId,
545588
545620
  botToken: config3.botToken,
545589
- appToken: config3.appToken,
545590
545621
  signingSecret: config3.signingSecret,
545591
545622
  port: config3.port ?? 3000,
545592
545623
  dmPolicy: config3.dmPolicy ?? "allowlist",
@@ -545711,6 +545742,10 @@ class ChannelManager {
545711
545742
  const state2 = channel.getConnectionState();
545712
545743
  return { status: state2.status, qrCode: state2.qrCode };
545713
545744
  }
545745
+ if ("getState" in channel) {
545746
+ const state2 = channel.getState();
545747
+ return { status: state2.status };
545748
+ }
545714
545749
  return { status: channel.isRunning() ? "connected" : "disconnected" };
545715
545750
  }
545716
545751
  async stopChannel(channelName, accountId) {
@@ -556640,8 +556675,12 @@ import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync9 } from "fs";
556640
556675
  import * as path28 from "path";
556641
556676
  function isSetupMode() {
556642
556677
  try {
556643
- const count = getDb().query("SELECT COUNT(*) as count FROM users").get().count;
556644
- return count === 0;
556678
+ const db = getDb();
556679
+ const userCount = db.query("SELECT COUNT(*) as count FROM users").get().count;
556680
+ if (userCount === 0)
556681
+ return true;
556682
+ const agentCount = db.query("SELECT COUNT(*) as count FROM agents WHERE role = 'coordinator'").get().count;
556683
+ return agentCount === 0;
556645
556684
  } catch {
556646
556685
  return true;
556647
556686
  }
@@ -556681,6 +556720,30 @@ function handleSetupEthics(addCorsHeaders, req) {
556681
556720
  return addCorsHeaders(Response.json({ error: error50.message }, { status: 500 }), req);
556682
556721
  }
556683
556722
  }
556723
+ async function handleSetupOllamaModels(addCorsHeaders, req) {
556724
+ const base = (process.env.OLLAMA_HOST || "http://localhost:11434").replace(/\/(v1|api)\/?$/, "");
556725
+ try {
556726
+ const res = await fetch(`${base}/api/tags`, { signal: AbortSignal.timeout(5000) });
556727
+ if (!res.ok) {
556728
+ return addCorsHeaders(Response.json({ models: [], error: `Ollama respondi\xF3 ${res.status}` }), req);
556729
+ }
556730
+ const data = await res.json();
556731
+ const detected = data.models ?? [];
556732
+ try {
556733
+ const db = getDb();
556734
+ for (const m2 of detected) {
556735
+ db.query(`
556736
+ INSERT OR IGNORE INTO models (id, name, provider_id, model_type, enabled, active)
556737
+ VALUES (?, ?, 'ollama', 'llm', 1, 0)
556738
+ `).run(m2.name, m2.name);
556739
+ }
556740
+ } catch {}
556741
+ const models = detected.map((m2) => ({ id: m2.name, name: m2.name }));
556742
+ return addCorsHeaders(Response.json({ models }), req);
556743
+ } catch {
556744
+ return addCorsHeaders(Response.json({ models: [], error: "Ollama no disponible en localhost:11434" }), req);
556745
+ }
556746
+ }
556684
556747
  async function handleSetupStatus() {
556685
556748
  const setupMode = isSetupMode();
556686
556749
  return Response.json({
@@ -556837,7 +556900,23 @@ async function handleCompleteSetup(req, config3, addCorsHeaders) {
556837
556900
  }
556838
556901
  const body = await req.json().catch(() => ({}));
556839
556902
  try {
556903
+ try {
556904
+ const db = getDb();
556905
+ const userCount = db.query("SELECT COUNT(*) as count FROM users").get().count;
556906
+ const agentCount = db.query("SELECT COUNT(*) as count FROM agents WHERE role = 'coordinator'").get().count;
556907
+ if (userCount > 0 && agentCount === 0) {
556908
+ db.exec("DELETE FROM users");
556909
+ }
556910
+ } catch {}
556840
556911
  initOnboardingDb();
556912
+ if (body.provider === "ollama" && body.model) {
556913
+ try {
556914
+ getDb().query(`
556915
+ INSERT OR IGNORE INTO models (id, name, provider_id, model_type, enabled, active)
556916
+ VALUES (?, ?, 'ollama', 'llm', 1, 1)
556917
+ `).run(body.model, body.model);
556918
+ } catch {}
556919
+ }
556841
556920
  const userId = saveUserProfile({
556842
556921
  userName: body.userName || "User",
556843
556922
  userLanguage: body.userLanguage || "es",
@@ -556853,12 +556932,12 @@ async function handleCompleteSetup(req, config3, addCorsHeaders) {
556853
556932
  providerId: body.provider || "",
556854
556933
  modelId: body.model || ""
556855
556934
  });
556856
- if (body.provider && body.apiKey) {
556935
+ if (body.provider && (body.apiKey || body.provider === "ollama")) {
556857
556936
  await saveProviderConfig({
556858
556937
  userId,
556859
556938
  provider: body.provider,
556860
556939
  model: body.model,
556861
- apiKey: body.apiKey
556940
+ apiKey: body.apiKey || undefined
556862
556941
  });
556863
556942
  }
556864
556943
  await activateChannel(userId, {
@@ -556929,6 +557008,100 @@ var init_setup = __esm(() => {
556929
557008
  init_loader();
556930
557009
  });
556931
557010
 
557011
+ // packages/core/src/gateway/routes/auth.ts
557012
+ import { readFileSync as readFileSync9 } from "fs";
557013
+ import * as path29 from "path";
557014
+ function getAuthTokenFromFile() {
557015
+ try {
557016
+ return readFileSync9(path29.join(getHiveDir(), ".auth_token"), "utf-8").trim();
557017
+ } catch {
557018
+ return process.env.HIVE_AUTH_TOKEN ?? "";
557019
+ }
557020
+ }
557021
+ async function handleAuthStatus(req, cors) {
557022
+ const user = getDb().query(`SELECT email, password_hash FROM users LIMIT 1`).get();
557023
+ const hasCredentials = !!(user?.email && user?.password_hash);
557024
+ return cors(Response.json({ hasCredentials, email: user?.email ?? null }), req);
557025
+ }
557026
+ async function handleRecoveryKey(req, cors) {
557027
+ const recoveryKey = getAuthTokenFromFile();
557028
+ return cors(Response.json({ recoveryKey }), req);
557029
+ }
557030
+ async function handleLogin(req, cors) {
557031
+ const body = await req.json().catch(() => ({}));
557032
+ if (!body.email || !body.password) {
557033
+ return cors(Response.json({ error: "Email y contrase\xF1a requeridos" }, { status: 400 }), req);
557034
+ }
557035
+ const user = getDb().query(`SELECT password_hash FROM users WHERE email = ? LIMIT 1`).get(body.email.toLowerCase().trim());
557036
+ if (!user?.password_hash) {
557037
+ return cors(Response.json({ error: "Credenciales inv\xE1lidas" }, { status: 401 }), req);
557038
+ }
557039
+ const valid = await Bun.password.verify(body.password, user.password_hash);
557040
+ if (!valid) {
557041
+ return cors(Response.json({ error: "Credenciales inv\xE1lidas" }, { status: 401 }), req);
557042
+ }
557043
+ const authToken = process.env.HIVE_AUTH_TOKEN ?? getAuthTokenFromFile();
557044
+ return cors(Response.json({ authToken }), req);
557045
+ }
557046
+ async function handleSetupCredentials(req, cors) {
557047
+ const body = await req.json().catch(() => ({}));
557048
+ if (!body.email || !body.password) {
557049
+ return cors(Response.json({ error: "Email y contrase\xF1a requeridos" }, { status: 400 }), req);
557050
+ }
557051
+ if (body.password.length < 8) {
557052
+ return cors(Response.json({ error: "La contrase\xF1a debe tener al menos 8 caracteres" }, { status: 400 }), req);
557053
+ }
557054
+ const passwordHash = await Bun.password.hash(body.password, { algorithm: "bcrypt", cost: 10 });
557055
+ const email3 = body.email.toLowerCase().trim();
557056
+ getDb().query(`UPDATE users SET email = ?, password_hash = ?`).run(email3, passwordHash);
557057
+ return cors(Response.json({ success: true }), req);
557058
+ }
557059
+ async function handleChangePassword(req, cors) {
557060
+ const body = await req.json().catch(() => ({}));
557061
+ if (!body.currentPassword || !body.newPassword) {
557062
+ return cors(Response.json({ error: "Campos requeridos" }, { status: 400 }), req);
557063
+ }
557064
+ if (body.newPassword.length < 8) {
557065
+ return cors(Response.json({ error: "La contrase\xF1a debe tener al menos 8 caracteres" }, { status: 400 }), req);
557066
+ }
557067
+ const user = getDb().query(`SELECT password_hash FROM users LIMIT 1`).get();
557068
+ if (!user?.password_hash) {
557069
+ return cors(Response.json({ error: "No hay contrase\xF1a configurada" }, { status: 400 }), req);
557070
+ }
557071
+ const valid = await Bun.password.verify(body.currentPassword, user.password_hash);
557072
+ if (!valid) {
557073
+ return cors(Response.json({ error: "Contrase\xF1a actual incorrecta" }, { status: 401 }), req);
557074
+ }
557075
+ const newHash = await Bun.password.hash(body.newPassword, { algorithm: "bcrypt", cost: 10 });
557076
+ getDb().query(`UPDATE users SET password_hash = ?`).run(newHash);
557077
+ return cors(Response.json({ success: true }), req);
557078
+ }
557079
+ async function handleRecover(req, cors) {
557080
+ const body = await req.json().catch(() => ({}));
557081
+ if (!body.recoveryKey || !body.newPassword) {
557082
+ return cors(Response.json({ error: "Recovery key y nueva contrase\xF1a requeridos" }, { status: 400 }), req);
557083
+ }
557084
+ if (body.newPassword.length < 8) {
557085
+ return cors(Response.json({ error: "La contrase\xF1a debe tener al menos 8 caracteres" }, { status: 400 }), req);
557086
+ }
557087
+ const storedToken = getAuthTokenFromFile();
557088
+ if (!storedToken || body.recoveryKey.trim() !== storedToken) {
557089
+ return cors(Response.json({ error: "Recovery key inv\xE1lido" }, { status: 401 }), req);
557090
+ }
557091
+ const newHash = await Bun.password.hash(body.newPassword, { algorithm: "bcrypt", cost: 10 });
557092
+ getDb().query(`UPDATE users SET password_hash = ?`).run(newHash);
557093
+ const authToken = process.env.HIVE_AUTH_TOKEN ?? storedToken;
557094
+ return cors(Response.json({ success: true, authToken }), req);
557095
+ }
557096
+ async function handleDisableAuth(req, cors) {
557097
+ getDb().query(`UPDATE users SET email = NULL, password_hash = NULL`).run();
557098
+ return cors(Response.json({ success: true }), req);
557099
+ }
557100
+ var init_auth = __esm(() => {
557101
+ init_sqlite();
557102
+ init_loader();
557103
+ });
557104
+
556932
557105
  // packages/core/src/gateway/routes/agents.ts
556933
557106
  async function handleGetAgents(req, addCorsHeaders) {
556934
557107
  const rows = getDb().query(`
@@ -558363,7 +558536,7 @@ var package_default;
558363
558536
  var init_package = __esm(() => {
558364
558537
  package_default = {
558365
558538
  name: "@johpaz/hive-agents-core",
558366
- version: "0.0.5",
558539
+ version: "0.0.8",
558367
558540
  private: true,
558368
558541
  description: "Hive Gateway \u2014 Personal AI agent runtime",
558369
558542
  main: "./src/index.ts",
@@ -558379,9 +558552,9 @@ var init_package = __esm(() => {
558379
558552
  },
558380
558553
  dependencies: {
558381
558554
  "@ag-ui/core": "^0.0.46",
558382
- "@johpaz/hive-agents-code-bridge": "^0.0.5",
558383
- "@johpaz/hive-agents-mcp": "^0.0.5",
558384
- "@johpaz/hive-agents-skills": "^0.0.5",
558555
+ "@johpaz/hive-agents-code-bridge": "^0.0.8",
558556
+ "@johpaz/hive-agents-mcp": "^0.0.8",
558557
+ "@johpaz/hive-agents-skills": "^0.0.8",
558385
558558
  "@modelcontextprotocol/sdk": "latest",
558386
558559
  "@sapphire/snowflake": "latest",
558387
558560
  "@slack/bolt": "latest",
@@ -558997,7 +559170,7 @@ var init_config = () => {};
558997
559170
 
558998
559171
  // packages/core/src/gateway/routes/workspace.ts
558999
559172
  import { mkdirSync as mkdirSync10, existsSync as existsSync17, accessSync as accessSync2, constants as constants2 } from "fs";
559000
- import * as path29 from "path";
559173
+ import * as path30 from "path";
559001
559174
  import { exec as exec2 } from "child_process";
559002
559175
  import { promisify as promisify4 } from "util";
559003
559176
  async function handleValidateWorkspace(req, addCorsHeaders) {
@@ -559012,7 +559185,7 @@ async function handleValidateWorkspace(req, addCorsHeaders) {
559012
559185
  accessible: false
559013
559186
  }), req);
559014
559187
  }
559015
- const isAbsolute4 = path29.isAbsolute(workspacePath);
559188
+ const isAbsolute4 = path30.isAbsolute(workspacePath);
559016
559189
  if (!isAbsolute4) {
559017
559190
  return addCorsHeaders(Response.json({
559018
559191
  ok: false,
@@ -559069,7 +559242,7 @@ async function handleCreateWorkspace(req, addCorsHeaders) {
559069
559242
  error: "Path es requerido"
559070
559243
  }), req);
559071
559244
  }
559072
- if (!path29.isAbsolute(workspacePath)) {
559245
+ if (!path30.isAbsolute(workspacePath)) {
559073
559246
  return addCorsHeaders(Response.json({
559074
559247
  ok: false,
559075
559248
  error: "El path debe ser absoluto"
@@ -559098,7 +559271,7 @@ async function handleOpenWorkspace(req, addCorsHeaders) {
559098
559271
  error: "Path es requerido"
559099
559272
  }), req);
559100
559273
  }
559101
- if (!path29.isAbsolute(workspacePath)) {
559274
+ if (!path30.isAbsolute(workspacePath)) {
559102
559275
  return addCorsHeaders(Response.json({
559103
559276
  ok: false,
559104
559277
  error: "El path debe ser absoluto"
@@ -559132,7 +559305,7 @@ async function handleOpenWorkspace(req, addCorsHeaders) {
559132
559305
  }
559133
559306
  }
559134
559307
  async function handleGetWorkspace(req, addCorsHeaders, workspacePath, wsType) {
559135
- const filePath = path29.join(workspacePath, `${wsType.toUpperCase()}.md`);
559308
+ const filePath = path30.join(workspacePath, `${wsType.toUpperCase()}.md`);
559136
559309
  const wsFile = Bun.file(filePath);
559137
559310
  const defaults2 = {
559138
559311
  soul: `# Agent Soul
@@ -559150,7 +559323,7 @@ Define ethical guidelines here.`
559150
559323
  }
559151
559324
  async function handleUpdateWorkspace(req, addCorsHeaders, workspacePath, wsType, reloadFn) {
559152
559325
  const content = await req.text();
559153
- const filePath = path29.join(workspacePath, `${wsType.toUpperCase()}.md`);
559326
+ const filePath = path30.join(workspacePath, `${wsType.toUpperCase()}.md`);
559154
559327
  mkdirSync10(workspacePath, { recursive: true });
559155
559328
  await Bun.write(filePath, content);
559156
559329
  if (reloadFn) {
@@ -559218,10 +559391,10 @@ var init_narration = __esm(() => {
559218
559391
  });
559219
559392
 
559220
559393
  // packages/core/src/gateway/helpers/path.ts
559221
- import * as path30 from "path";
559222
- function expandPath4(p2) {
559394
+ import * as path31 from "path";
559395
+ function expandPath3(p2) {
559223
559396
  if (p2.startsWith("~")) {
559224
- return path30.join(process.env.HOME ?? "", p2.slice(1));
559397
+ return path31.join(process.env.HOME ?? "", p2.slice(1));
559225
559398
  }
559226
559399
  return p2;
559227
559400
  }
@@ -560180,14 +560353,14 @@ var init_scheduled_tasks = __esm(() => {
560180
560353
  });
560181
560354
 
560182
560355
  // packages/core/src/gateway/server.ts
560183
- import { mkdirSync as mkdirSync11, unlinkSync as unlinkSync4, existsSync as existsSync18, writeFileSync as writeFileSync5, readFileSync as readFileSync9 } from "fs";
560184
- import * as path31 from "path";
560356
+ import { mkdirSync as mkdirSync11, unlinkSync as unlinkSync4, existsSync as existsSync18, writeFileSync as writeFileSync5, readFileSync as readFileSync10 } from "fs";
560357
+ import * as path32 from "path";
560185
560358
  import { cpus as osCpus } from "os";
560186
560359
  import { randomUUID as randomUUID2 } from "crypto";
560187
560360
  async function startGateway(config3) {
560188
560361
  const host = config3.gateway?.host ?? "127.0.0.1";
560189
560362
  const port = config3.gateway?.port ?? 18790;
560190
- const pidFile = expandPath4(config3.gateway?.pidFile ?? "~/.hive/gateway.pid");
560363
+ const pidFile = expandPath3(config3.gateway?.pidFile ?? "~/.hive/gateway.pid");
560191
560364
  const startTime2 = Date.now();
560192
560365
  const numCores = osCpus().length || 1;
560193
560366
  let lastCpuSample = process.cpuUsage();
@@ -560195,15 +560368,15 @@ async function startGateway(config3) {
560195
560368
  const log70 = logger.child("gateway");
560196
560369
  const mcpLog2 = logger.child("mcp:api");
560197
560370
  log70.info(`Starting gateway on ${host}:${port}`);
560198
- const tokenFile = path31.join(getHiveDir(), ".auth_token");
560371
+ const tokenFile = path32.join(getHiveDir(), ".auth_token");
560199
560372
  if (!process.env.HIVE_AUTH_TOKEN) {
560200
560373
  if (existsSync18(tokenFile)) {
560201
- process.env.HIVE_AUTH_TOKEN = readFileSync9(tokenFile, "utf-8").trim();
560374
+ process.env.HIVE_AUTH_TOKEN = readFileSync10(tokenFile, "utf-8").trim();
560202
560375
  log70.info("\uD83D\uDD11 Auth token loaded from persistent storage");
560203
560376
  } else {
560204
560377
  const generated = randomUUID2().replace(/-/g, "");
560205
560378
  process.env.HIVE_AUTH_TOKEN = generated;
560206
- mkdirSync11(path31.dirname(tokenFile), { recursive: true });
560379
+ mkdirSync11(path32.dirname(tokenFile), { recursive: true });
560207
560380
  writeFileSync5(tokenFile, generated, { mode: 384 });
560208
560381
  log70.info("\uD83D\uDD11 Auth token auto-generated and persisted");
560209
560382
  }
@@ -560474,7 +560647,7 @@ ${messageContent}`;
560474
560647
  });
560475
560648
  }
560476
560649
  });
560477
- const isDev = process.env.HIVE_DEV === "true";
560650
+ const isDev = process.env.HIVE_DEV === "true" && existsSync18(path32.join(process.cwd(), "packages/hive-ui/package.json"));
560478
560651
  function checkAuth(req, url3) {
560479
560652
  if (isDev)
560480
560653
  return true;
@@ -560482,6 +560655,12 @@ ${messageContent}`;
560482
560655
  return true;
560483
560656
  if (url3.pathname.startsWith("/api/setup/"))
560484
560657
  return true;
560658
+ if (url3.pathname === "/api/auth/status")
560659
+ return true;
560660
+ if (url3.pathname === "/api/auth/login")
560661
+ return true;
560662
+ if (url3.pathname === "/api/auth/recover")
560663
+ return true;
560485
560664
  const activeToken = process.env.HIVE_AUTH_TOKEN;
560486
560665
  if (!activeToken)
560487
560666
  return true;
@@ -560570,10 +560749,10 @@ ${messageContent}`;
560570
560749
  `, { status: 404, headers: { "Content-Type": "text/plain" } });
560571
560750
  }
560572
560751
  const uiDirFromEnv = process.env.HIVE_UI_DIR;
560573
- const uiDirFromHive = path31.join(getHiveDir(), "ui");
560574
- const uiDirFromDist = process.env.HIVE_DIST_DIR ? path31.join(process.env.HIVE_DIST_DIR, "ui") : null;
560575
- const uiDirFromCwd = path31.join(process.cwd(), "packages/hive-ui/dist");
560576
- const uiDir = uiDirFromEnv || (existsSync18(path31.join(uiDirFromHive, "index.html")) ? uiDirFromHive : uiDirFromDist && existsSync18(path31.join(uiDirFromDist, "index.html")) ? uiDirFromDist : uiDirFromCwd);
560752
+ const uiDirFromHive = path32.join(getHiveDir(), "ui");
560753
+ const uiDirFromDist = process.env.HIVE_DIST_DIR ? path32.join(process.env.HIVE_DIST_DIR, "ui") : null;
560754
+ const uiDirFromCwd = path32.join(process.cwd(), "packages/hive-ui/dist");
560755
+ const uiDir = uiDirFromEnv || (existsSync18(path32.join(uiDirFromHive, "index.html")) ? uiDirFromHive : uiDirFromDist && existsSync18(path32.join(uiDirFromDist, "index.html")) ? uiDirFromDist : uiDirFromCwd);
560577
560756
  let subPath = url3.pathname;
560578
560757
  if (gatewaySetupMode && (subPath === "/" || subPath === "/ui" || subPath === "/ui/")) {
560579
560758
  const _publicBase = process.env.HIVE_PUBLIC_URL?.replace(/\/$/, "") ?? `http://${host === "0.0.0.0" ? "localhost" : host}:${port}`;
@@ -560595,13 +560774,13 @@ ${messageContent}`;
560595
560774
  if (!subPath)
560596
560775
  subPath = "/index.html";
560597
560776
  }
560598
- const filePath = path31.join(uiDir, subPath);
560777
+ const filePath = path32.join(uiDir, subPath);
560599
560778
  const uiFile = Bun.file(filePath);
560600
560779
  if (await uiFile.exists()) {
560601
560780
  return new Response(uiFile);
560602
560781
  }
560603
- if (!path31.extname(subPath)) {
560604
- const indexFile = Bun.file(path31.join(uiDir, "index.html"));
560782
+ if (!path32.extname(subPath)) {
560783
+ const indexFile = Bun.file(path32.join(uiDir, "index.html"));
560605
560784
  if (await indexFile.exists()) {
560606
560785
  return new Response(indexFile);
560607
560786
  }
@@ -560628,6 +560807,9 @@ ${messageContent}`;
560628
560807
  if (url3.pathname === "/api/setup/providers" && req.method === "GET") {
560629
560808
  return handleSetupProviders(addCorsHeaders, req);
560630
560809
  }
560810
+ if (url3.pathname === "/api/setup/ollama-models" && req.method === "GET") {
560811
+ return handleSetupOllamaModels(addCorsHeaders, req);
560812
+ }
560631
560813
  if (url3.pathname === "/api/setup/ethics" && req.method === "GET") {
560632
560814
  return handleSetupEthics(addCorsHeaders, req);
560633
560815
  }
@@ -560637,6 +560819,27 @@ ${messageContent}`;
560637
560819
  if (url3.pathname === "/api/setup/complete" && req.method === "POST") {
560638
560820
  return await handleCompleteSetup(req, config3, addCorsHeaders);
560639
560821
  }
560822
+ if (url3.pathname === "/api/auth/status" && req.method === "GET") {
560823
+ return handleAuthStatus(req, addCorsHeaders);
560824
+ }
560825
+ if (url3.pathname === "/api/auth/login" && req.method === "POST") {
560826
+ return handleLogin(req, addCorsHeaders);
560827
+ }
560828
+ if (url3.pathname === "/api/auth/setup-credentials" && req.method === "POST") {
560829
+ return handleSetupCredentials(req, addCorsHeaders);
560830
+ }
560831
+ if (url3.pathname === "/api/auth/change-password" && req.method === "POST") {
560832
+ return handleChangePassword(req, addCorsHeaders);
560833
+ }
560834
+ if (url3.pathname === "/api/auth/recover" && req.method === "POST") {
560835
+ return handleRecover(req, addCorsHeaders);
560836
+ }
560837
+ if (url3.pathname === "/api/auth/disable" && req.method === "POST") {
560838
+ return handleDisableAuth(req, addCorsHeaders);
560839
+ }
560840
+ if (url3.pathname === "/api/auth/recovery-key" && req.method === "GET") {
560841
+ return handleRecoveryKey(req, addCorsHeaders);
560842
+ }
560640
560843
  if (url3.pathname === "/status" || url3.pathname === "/status/") {
560641
560844
  return addCorsHeaders(new Response(JSON.stringify({
560642
560845
  status: "ok",
@@ -560797,7 +561000,7 @@ ${messageContent}`;
560797
561000
  for (const wsType of ["soul", "user", "ethics"]) {
560798
561001
  if (url3.pathname === `/api/workspace/${wsType}`) {
560799
561002
  const coordinatorRow = getDb().query("SELECT workspace FROM agents WHERE role = 'coordinator' LIMIT 1").get();
560800
- const liveWorkspacePath = coordinatorRow?.workspace ? expandPath4(coordinatorRow.workspace) : expandPath4("~/.hive/workspace");
561003
+ const liveWorkspacePath = coordinatorRow?.workspace ? expandPath3(coordinatorRow.workspace) : expandPath3("~/.hive/workspace");
560801
561004
  if (req.method === "GET") {
560802
561005
  return await handleGetWorkspace(req, addCorsHeaders, liveWorkspacePath, wsType);
560803
561006
  }
@@ -561772,6 +561975,7 @@ var init_server = __esm(() => {
561772
561975
  init_voice();
561773
561976
  init_initializer();
561774
561977
  init_setup();
561978
+ init_auth();
561775
561979
  init_onboarding();
561776
561980
  init_agents2();
561777
561981
  init_providers2();
@@ -561800,8 +562004,8 @@ var init_server = __esm(() => {
561800
562004
  init_scheduled_tasks();
561801
562005
  _pkgVersion = (() => {
561802
562006
  try {
561803
- const pkgPath = path31.join(import.meta.dir, "../../../package.json");
561804
- return JSON.parse(readFileSync9(pkgPath, "utf-8")).version;
562007
+ const pkgPath = path32.join(import.meta.dir, "../../../package.json");
562008
+ return JSON.parse(readFileSync10(pkgPath, "utf-8")).version;
561805
562009
  } catch {
561806
562010
  return "2.0.3";
561807
562011
  }
@@ -563243,7 +563447,7 @@ var init_circuit_breaker = __esm(() => {
563243
563447
  });
563244
563448
  // packages/core/src/plugins/loader.ts
563245
563449
  import { mkdirSync as mkdirSync12, readdirSync as readdirSync5, existsSync as existsSync19 } from "fs";
563246
- import * as path32 from "path";
563450
+ import * as path33 from "path";
563247
563451
 
563248
563452
  class PluginLoader {
563249
563453
  options;
@@ -563267,7 +563471,7 @@ class PluginLoader {
563267
563471
  const entries = readdirSync5(pluginDir, { withFileTypes: true });
563268
563472
  for (const entry of entries) {
563269
563473
  if (entry.isDirectory()) {
563270
- const manifestPath = path32.join(pluginDir, entry.name, "manifest.json");
563474
+ const manifestPath = path33.join(pluginDir, entry.name, "manifest.json");
563271
563475
  if (existsSync19(manifestPath)) {
563272
563476
  discovered.push(entry.name);
563273
563477
  }
@@ -563283,8 +563487,8 @@ class PluginLoader {
563283
563487
  this.log.warn(`Plugin ${pluginName} already loaded`);
563284
563488
  return;
563285
563489
  }
563286
- const pluginPath = path32.join(this.options.pluginDir, pluginName);
563287
- const manifestPath = path32.join(pluginPath, "manifest.json");
563490
+ const pluginPath = path33.join(this.options.pluginDir, pluginName);
563491
+ const manifestPath = path33.join(pluginPath, "manifest.json");
563288
563492
  this.updateState(pluginName, "activating");
563289
563493
  try {
563290
563494
  this.log.debug(`Reading plugin manifest: ${manifestPath}`);
@@ -563296,7 +563500,7 @@ class PluginLoader {
563296
563500
  return;
563297
563501
  }
563298
563502
  const mainFile = manifest.main ?? "index.js";
563299
- const mainPath2 = path32.join(pluginPath, mainFile);
563503
+ const mainPath2 = path33.join(pluginPath, mainFile);
563300
563504
  if (!await Bun.file(mainPath2).exists()) {
563301
563505
  throw new Error(`Main file not found: ${mainPath2}`);
563302
563506
  }
@@ -563348,7 +563552,7 @@ class PluginLoader {
563348
563552
  const exports = {};
563349
563553
  try {
563350
563554
  const fn = eval(wrappedCode);
563351
- fn(module, exports, path32.dirname(mainPath), mainPath);
563555
+ fn(module, exports, path33.dirname(mainPath), mainPath);
563352
563556
  const PluginClass = module.exports.default ?? exports.default;
563353
563557
  if (typeof PluginClass !== "function") {
563354
563558
  throw new Error("Plugin must export a class as default");
@@ -563595,6 +563799,1023 @@ var init_src3 = __esm(() => {
563595
563799
  init_canvas2();
563596
563800
  });
563597
563801
 
563802
+ // packages/cli/src/ui-bundle.generated.ts
563803
+ var exports_ui_bundle_generated = {};
563804
+ __export(exports_ui_bundle_generated, {
563805
+ embeddedUI: () => embeddedUI
563806
+ });
563807
+ var embeddedUI;
563808
+ var init_ui_bundle_generated = __esm(() => {
563809
+ embeddedUI = new Map;
563810
+ });
563811
+
563812
+ // packages/cli/src/adapters/types.ts
563813
+ var gatewayConfigSchema, installationPathsSchema, installationConfigSchema, PORTS;
563814
+ var init_types8 = __esm(() => {
563815
+ init_zod();
563816
+ gatewayConfigSchema = exports_external.object({
563817
+ host: exports_external.string().optional().default("127.0.0.1"),
563818
+ port: exports_external.number().int().min(1).max(65535).default(18790),
563819
+ uiPort: exports_external.number().int().min(1).max(65535).optional(),
563820
+ wsPort: exports_external.number().int().min(1).max(65535).default(18790),
563821
+ codeBridgePort: exports_external.number().int().min(1).max(65535).default(18791),
563822
+ publicUrl: exports_external.string().url().optional(),
563823
+ openBrowser: exports_external.boolean().default(true),
563824
+ daemon: exports_external.boolean().default(false)
563825
+ });
563826
+ installationPathsSchema = exports_external.object({
563827
+ hiveDir: exports_external.string(),
563828
+ dbPath: exports_external.string(),
563829
+ logPath: exports_external.string(),
563830
+ pidPath: exports_external.string(),
563831
+ uiDir: exports_external.string().nullable().optional(),
563832
+ workspaceDir: exports_external.string().nullable().optional()
563833
+ });
563834
+ installationConfigSchema = exports_external.object({
563835
+ type: exports_external.enum(["docker", "bun-global", "binary"]),
563836
+ gateway: gatewayConfigSchema,
563837
+ paths: installationPathsSchema,
563838
+ env: exports_external.record(exports_external.string(), exports_external.string()),
563839
+ isDev: exports_external.boolean(),
563840
+ hasEmbeddedUI: exports_external.boolean()
563841
+ });
563842
+ PORTS = {
563843
+ GATEWAY: 18790,
563844
+ CODE_BRIDGE: 18791,
563845
+ VITE_DEV: 5173
563846
+ };
563847
+ });
563848
+
563849
+ // packages/cli/src/adapters/config.ts
563850
+ import * as path34 from "path";
563851
+ import { existsSync as existsSync20, readFileSync as readFileSync11 } from "fs";
563852
+ function getHiveDir2(customDir) {
563853
+ if (customDir) {
563854
+ return path34.resolve(customDir);
563855
+ }
563856
+ if (process.env.HIVE_HOME) {
563857
+ return path34.resolve(process.env.HIVE_HOME);
563858
+ }
563859
+ if (process.env.HIVE_DEV === "true") {
563860
+ return path34.join(process.env.HOME || "", ".hive-dev");
563861
+ }
563862
+ return path34.join(process.env.HOME || "", ".hive");
563863
+ }
563864
+ function getDefaultPaths(hiveDir) {
563865
+ const dir = getHiveDir2(hiveDir);
563866
+ const dataDir = path34.join(dir, "data");
563867
+ const logsDir = path34.join(dir, "logs");
563868
+ return {
563869
+ hiveDir: dir,
563870
+ dbPath: path34.join(dataDir, "hive.db"),
563871
+ logPath: path34.join(logsDir, "gateway.log"),
563872
+ pidPath: path34.join(dir, "gateway.pid"),
563873
+ uiDir: null,
563874
+ workspaceDir: null
563875
+ };
563876
+ }
563877
+ function loadEnvFile(envPath) {
563878
+ const filePath = envPath || path34.join(process.cwd(), ".env");
563879
+ if (!existsSync20(filePath)) {
563880
+ return {};
563881
+ }
563882
+ try {
563883
+ const content = readFileSync11(filePath, "utf-8");
563884
+ const env3 = {};
563885
+ for (const line of content.split(`
563886
+ `)) {
563887
+ const trimmed = line.trim();
563888
+ if (!trimmed || trimmed.startsWith("#")) {
563889
+ continue;
563890
+ }
563891
+ const [key, ...valueParts] = trimmed.split("=");
563892
+ if (key && valueParts.length > 0) {
563893
+ const value = valueParts.join("=").trim();
563894
+ const cleanValue = value.replace(/^["']|["']$/g, "");
563895
+ env3[key.trim()] = cleanValue;
563896
+ }
563897
+ }
563898
+ return env3;
563899
+ } catch {
563900
+ return {};
563901
+ }
563902
+ }
563903
+ function mergeEnv(...envs) {
563904
+ const result2 = {};
563905
+ for (const env3 of envs) {
563906
+ Object.assign(result2, env3);
563907
+ }
563908
+ return result2;
563909
+ }
563910
+ async function isPortAvailable(port) {
563911
+ try {
563912
+ const server3 = Bun.serve({
563913
+ port,
563914
+ hostname: "0.0.0.0",
563915
+ fetch: () => new Response("")
563916
+ });
563917
+ server3.stop();
563918
+ return true;
563919
+ } catch {
563920
+ return false;
563921
+ }
563922
+ }
563923
+ async function waitForHttpPort(port, path35 = "/health", timeout3 = 30000) {
563924
+ const start = Date.now();
563925
+ while (Date.now() - start < timeout3) {
563926
+ try {
563927
+ const response = await fetch(`http://127.0.0.1:${port}${path35}`, {
563928
+ signal: AbortSignal.timeout(1000)
563929
+ });
563930
+ if (response.ok) {
563931
+ return true;
563932
+ }
563933
+ } catch {}
563934
+ await new Promise((resolve9) => setTimeout(resolve9, 500));
563935
+ }
563936
+ return false;
563937
+ }
563938
+ function getDistDir() {
563939
+ if (process.env.HIVE_DIST_DIR) {
563940
+ return process.env.HIVE_DIST_DIR;
563941
+ }
563942
+ const scriptPath = process.argv[1];
563943
+ if (!scriptPath) {
563944
+ return null;
563945
+ }
563946
+ const dir = path34.dirname(scriptPath);
563947
+ if (path34.basename(dir) === "dist") {
563948
+ return dir;
563949
+ }
563950
+ const distPath = path34.join(dir, "dist");
563951
+ if (existsSync20(distPath)) {
563952
+ return distPath;
563953
+ }
563954
+ return null;
563955
+ }
563956
+ function isDevMode() {
563957
+ return process.env.HIVE_DEV === "true" && existsSync20(path34.join(process.cwd(), "packages/hive-ui/package.json"));
563958
+ }
563959
+ function isChildProcess() {
563960
+ return process.env.HIVE_GATEWAY_CHILD === "1";
563961
+ }
563962
+ var init_config3 = __esm(() => {
563963
+ init_types8();
563964
+ });
563965
+
563966
+ // packages/cli/src/adapters/docker.ts
563967
+ var exports_docker = {};
563968
+ __export(exports_docker, {
563969
+ DockerAdapter: () => DockerAdapter
563970
+ });
563971
+ import { spawn as spawn5, execSync as execSync2 } from "child_process";
563972
+ import * as path35 from "path";
563973
+ import { existsSync as existsSync21 } from "fs";
563974
+
563975
+ class DockerAdapter {
563976
+ type = "docker";
563977
+ name = "Docker Compose";
563978
+ hiveDir;
563979
+ composeFile;
563980
+ envFile;
563981
+ constructor(options2) {
563982
+ this.hiveDir = options2?.hiveDir || getHiveDir2();
563983
+ this.composeFile = options2?.composeFile || this.findComposeFile();
563984
+ this.envFile = path35.join(path35.dirname(this.composeFile), ".env");
563985
+ }
563986
+ findComposeFile() {
563987
+ const standardPaths = [
563988
+ "/opt/hive/docker-compose.yml",
563989
+ "/usr/local/share/hive/docker-compose.yml",
563990
+ path35.join(process.env.HOME || "", ".hive", "docker-compose.yml")
563991
+ ];
563992
+ for (const composePath of standardPaths) {
563993
+ if (existsSync21(composePath)) {
563994
+ return composePath;
563995
+ }
563996
+ }
563997
+ return "/opt/hive/docker-compose.yml";
563998
+ }
563999
+ async detect() {
564000
+ try {
564001
+ execSync2("docker --version", { stdio: "ignore" });
564002
+ execSync2("docker compose version", { stdio: "ignore" });
564003
+ if (!existsSync21(this.composeFile)) {
564004
+ return false;
564005
+ }
564006
+ try {
564007
+ const out = execSync2(`docker compose -f "${this.composeFile}" config --services`, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
564008
+ return out.trim().split(`
564009
+ `).map((s2) => s2.trim()).includes("hive");
564010
+ } catch {
564011
+ return false;
564012
+ }
564013
+ } catch {
564014
+ return false;
564015
+ }
564016
+ }
564017
+ async getConfig() {
564018
+ const env3 = await this.getEnvironment();
564019
+ const paths = getDefaultPaths(this.hiveDir);
564020
+ paths.uiDir = null;
564021
+ const port = parseInt(env3.HIVE_PORT || "18790", 10) || PORTS.GATEWAY;
564022
+ const publicUrl = env3.HIVE_PUBLIC_URL || undefined;
564023
+ return {
564024
+ type: this.type,
564025
+ gateway: {
564026
+ host: env3.HIVE_HOST || "0.0.0.0",
564027
+ port,
564028
+ wsPort: port,
564029
+ codeBridgePort: PORTS.CODE_BRIDGE,
564030
+ publicUrl,
564031
+ openBrowser: !env3.NO_BROWSER,
564032
+ daemon: false
564033
+ },
564034
+ paths,
564035
+ env: env3,
564036
+ isDev: false,
564037
+ hasEmbeddedUI: false
564038
+ };
564039
+ }
564040
+ async start(config4) {
564041
+ return new Promise((resolve9, reject) => {
564042
+ const child = spawn5("docker", ["compose", "-f", this.composeFile, "up", "-d"], {
564043
+ stdio: "inherit",
564044
+ detached: false
564045
+ });
564046
+ child.on("close", (code2) => {
564047
+ if (code2 === 0) {
564048
+ resolve9();
564049
+ } else {
564050
+ reject(new Error(`Docker compose exited with code ${code2}`));
564051
+ }
564052
+ });
564053
+ child.on("error", (error50) => {
564054
+ reject(error50);
564055
+ });
564056
+ });
564057
+ }
564058
+ async stop() {
564059
+ return new Promise((resolve9, reject) => {
564060
+ const child = spawn5("docker", ["compose", "-f", this.composeFile, "down"], {
564061
+ stdio: "inherit",
564062
+ detached: false
564063
+ });
564064
+ child.on("close", (code2) => {
564065
+ if (code2 === 0) {
564066
+ resolve9();
564067
+ } else {
564068
+ reject(new Error(`Docker compose down exited with code ${code2}`));
564069
+ }
564070
+ });
564071
+ child.on("error", (error50) => {
564072
+ reject(error50);
564073
+ });
564074
+ });
564075
+ }
564076
+ async isRunning() {
564077
+ try {
564078
+ const output2 = execSync2("docker compose ps --format json", {
564079
+ encoding: "utf-8",
564080
+ stdio: ["ignore", "pipe", "ignore"]
564081
+ });
564082
+ const services = JSON.parse(output2.trim());
564083
+ if (Array.isArray(services)) {
564084
+ const hive = services.find((s2) => s2.service === "hive");
564085
+ return hive && hive.state === "running";
564086
+ }
564087
+ return false;
564088
+ } catch {
564089
+ return false;
564090
+ }
564091
+ }
564092
+ async getPid() {
564093
+ try {
564094
+ const output2 = execSync2("docker inspect --format '{{.State.Pid}}' $(docker compose ps -q hive)", {
564095
+ encoding: "utf-8",
564096
+ stdio: ["ignore", "pipe", "ignore"]
564097
+ });
564098
+ const pid = parseInt(output2.trim(), 10);
564099
+ if (!isNaN(pid) && pid > 0) {
564100
+ return pid;
564101
+ }
564102
+ return null;
564103
+ } catch {
564104
+ return null;
564105
+ }
564106
+ }
564107
+ async getEnvironment() {
564108
+ const fileEnv = loadEnvFile(this.envFile);
564109
+ const defaults2 = {
564110
+ HIVE_HOST: "0.0.0.0",
564111
+ HIVE_PORT: String(PORTS.GATEWAY),
564112
+ OLLAMA_HOST: "http://host.docker.internal:11434",
564113
+ NO_BROWSER: "1",
564114
+ HIVE_PUBLIC_URL: ""
564115
+ };
564116
+ return mergeEnv(defaults2, fileEnv, process.env);
564117
+ }
564118
+ async validate() {
564119
+ const errors3 = [];
564120
+ const warnings = [];
564121
+ const info = [];
564122
+ try {
564123
+ const version4 = execSync2("docker --version", { encoding: "utf-8" }).trim();
564124
+ info.push(`Docker: ${version4}`);
564125
+ } catch {
564126
+ errors3.push("Docker is not installed or not in PATH");
564127
+ }
564128
+ try {
564129
+ const version4 = execSync2("docker compose version", { encoding: "utf-8" }).trim();
564130
+ info.push(`Docker Compose: ${version4}`);
564131
+ } catch {
564132
+ errors3.push("Docker Compose is not installed");
564133
+ }
564134
+ if (!existsSync21(this.composeFile)) {
564135
+ errors3.push(`docker-compose.yml not found at ${this.composeFile}`);
564136
+ } else {
564137
+ info.push(`Compose file: ${this.composeFile}`);
564138
+ }
564139
+ try {
564140
+ execSync2("docker info", { stdio: "ignore" });
564141
+ info.push("Docker daemon is running");
564142
+ } catch {
564143
+ errors3.push("Docker daemon is not running");
564144
+ }
564145
+ const running = await this.isRunning();
564146
+ if (running) {
564147
+ info.push("Hive container is running");
564148
+ const config4 = await this.getConfig();
564149
+ const healthy = await waitForHttpPort(config4.gateway.port, "/health", 5000);
564150
+ if (healthy) {
564151
+ info.push("Hive health check passed");
564152
+ } else {
564153
+ warnings.push("Hive container is running but health check failed");
564154
+ }
564155
+ } else {
564156
+ warnings.push("Hive container is not running");
564157
+ }
564158
+ return {
564159
+ valid: errors3.length === 0,
564160
+ errors: errors3,
564161
+ warnings,
564162
+ info
564163
+ };
564164
+ }
564165
+ }
564166
+ var init_docker = __esm(() => {
564167
+ init_config3();
564168
+ init_types8();
564169
+ });
564170
+
564171
+ // packages/cli/src/adapters/bun-global.ts
564172
+ import { spawn as spawn6, execSync as execSync3 } from "child_process";
564173
+ import * as path36 from "path";
564174
+ import { existsSync as existsSync22, readFileSync as readFileSync12, unlinkSync as unlinkSync5 } from "fs";
564175
+
564176
+ class BunGlobalAdapter {
564177
+ type = "bun-global";
564178
+ name = "Bun Global (npm-style)";
564179
+ hiveDir;
564180
+ pidFile;
564181
+ constructor(options2) {
564182
+ this.hiveDir = options2?.hiveDir || getHiveDir2();
564183
+ this.pidFile = path36.join(this.hiveDir, "gateway.pid");
564184
+ }
564185
+ async detect() {
564186
+ try {
564187
+ execSync3("bun --version", { stdio: "ignore" });
564188
+ try {
564189
+ const output2 = execSync3("bun which hive", {
564190
+ encoding: "utf-8",
564191
+ stdio: ["ignore", "pipe", "ignore"]
564192
+ });
564193
+ const hivePath = output2.trim();
564194
+ if (hivePath && existsSync22(hivePath)) {
564195
+ return true;
564196
+ }
564197
+ } catch {
564198
+ const output2 = execSync3("bun pm ls -g", {
564199
+ encoding: "utf-8",
564200
+ stdio: ["ignore", "pipe", "ignore"]
564201
+ });
564202
+ if (output2.includes("@johpaz/hive-agents") || output2.includes("hive")) {
564203
+ return true;
564204
+ }
564205
+ }
564206
+ return false;
564207
+ } catch {
564208
+ return false;
564209
+ }
564210
+ }
564211
+ async getConfig() {
564212
+ const env3 = await this.getEnvironment();
564213
+ const paths = getDefaultPaths(this.hiveDir);
564214
+ let uiDir = null;
564215
+ try {
564216
+ const hivePath = execSync3("bun which hive", {
564217
+ encoding: "utf-8",
564218
+ stdio: ["ignore", "pipe", "ignore"]
564219
+ }).trim();
564220
+ const distDir = path36.dirname(hivePath);
564221
+ const potentialUiDir = path36.join(distDir, "ui");
564222
+ if (existsSync22(potentialUiDir)) {
564223
+ uiDir = potentialUiDir;
564224
+ }
564225
+ } catch {}
564226
+ if (!uiDir) {
564227
+ const cwdUiDir = path36.join(process.cwd(), "packages/hive-ui/dist");
564228
+ if (existsSync22(cwdUiDir)) {
564229
+ uiDir = cwdUiDir;
564230
+ }
564231
+ }
564232
+ paths.uiDir = uiDir;
564233
+ const port = parseInt(env3.HIVE_PORT || "18790", 10) || PORTS.GATEWAY;
564234
+ const publicUrl = env3.HIVE_PUBLIC_URL || undefined;
564235
+ return {
564236
+ type: this.type,
564237
+ gateway: {
564238
+ host: env3.HIVE_HOST || "127.0.0.1",
564239
+ port,
564240
+ wsPort: port,
564241
+ codeBridgePort: PORTS.CODE_BRIDGE,
564242
+ publicUrl,
564243
+ openBrowser: !env3.NO_BROWSER,
564244
+ daemon: !!env3.HIVE_DAEMON
564245
+ },
564246
+ paths,
564247
+ env: env3,
564248
+ isDev: process.env.HIVE_DEV === "true",
564249
+ hasEmbeddedUI: false
564250
+ };
564251
+ }
564252
+ async start(config4) {
564253
+ return new Promise((resolve9, reject) => {
564254
+ const args = ["hive", "start", "--skip-check"];
564255
+ if (config4.daemon) {
564256
+ args.push("--daemon");
564257
+ }
564258
+ const child = spawn6("bun", args, {
564259
+ stdio: "inherit",
564260
+ detached: false,
564261
+ env: mergeEnv(process.env, {
564262
+ HIVE_HOME: this.hiveDir
564263
+ })
564264
+ });
564265
+ child.on("close", (code2) => {
564266
+ if (code2 === 0) {
564267
+ resolve9();
564268
+ } else {
564269
+ reject(new Error(`Bun hive exited with code ${code2}`));
564270
+ }
564271
+ });
564272
+ child.on("error", (error50) => {
564273
+ reject(error50);
564274
+ });
564275
+ });
564276
+ }
564277
+ async stop() {
564278
+ try {
564279
+ if (existsSync22(this.pidFile)) {
564280
+ const pid = parseInt(readFileSync12(this.pidFile, "utf-8").trim(), 10);
564281
+ if (!isNaN(pid)) {
564282
+ try {
564283
+ process.kill(pid, "SIGTERM");
564284
+ console.log(`\u2705 Hive Gateway detenido (PID: ${pid})`);
564285
+ } catch (error50) {
564286
+ if (error50.code === "ESRCH") {
564287
+ console.log("\u26A0\uFE0F Hive Gateway no est\xE1 corriendo");
564288
+ } else {
564289
+ throw error50;
564290
+ }
564291
+ } finally {
564292
+ try {
564293
+ unlinkSync5(this.pidFile);
564294
+ } catch {}
564295
+ }
564296
+ }
564297
+ } else {
564298
+ try {
564299
+ execSync3("pkill -f 'bun.*hive.*start'", { stdio: "ignore" });
564300
+ console.log("\u2705 Hive Gateway detenido");
564301
+ } catch {
564302
+ console.log("\u26A0\uFE0F Hive Gateway no est\xE1 corriendo");
564303
+ }
564304
+ }
564305
+ } catch (error50) {
564306
+ console.error("\u274C Error deteniendo Hive Gateway:", error50.message);
564307
+ throw error50;
564308
+ }
564309
+ }
564310
+ async isRunning() {
564311
+ try {
564312
+ if (existsSync22(this.pidFile)) {
564313
+ const pid = parseInt(readFileSync12(this.pidFile, "utf-8").trim(), 10);
564314
+ if (!isNaN(pid)) {
564315
+ try {
564316
+ process.kill(pid, 0);
564317
+ return true;
564318
+ } catch {
564319
+ try {
564320
+ unlinkSync5(this.pidFile);
564321
+ } catch {}
564322
+ }
564323
+ }
564324
+ }
564325
+ const config4 = await this.getConfig();
564326
+ const portAvailable = await isPortAvailable(config4.gateway.port);
564327
+ return !portAvailable;
564328
+ } catch {
564329
+ return false;
564330
+ }
564331
+ }
564332
+ async getPid() {
564333
+ try {
564334
+ if (existsSync22(this.pidFile)) {
564335
+ const pid = parseInt(readFileSync12(this.pidFile, "utf-8").trim(), 10);
564336
+ if (!isNaN(pid) && pid > 0) {
564337
+ try {
564338
+ process.kill(pid, 0);
564339
+ return pid;
564340
+ } catch {}
564341
+ }
564342
+ }
564343
+ return null;
564344
+ } catch {
564345
+ return null;
564346
+ }
564347
+ }
564348
+ async getEnvironment() {
564349
+ const fileEnv = loadEnvFile();
564350
+ const homeEnv = loadEnvFile(path36.join(this.hiveDir, ".env"));
564351
+ const defaults2 = {
564352
+ HIVE_HOST: "127.0.0.1",
564353
+ HIVE_PORT: String(PORTS.GATEWAY),
564354
+ HIVE_HOME: this.hiveDir,
564355
+ NO_BROWSER: "0",
564356
+ HIVE_PUBLIC_URL: "",
564357
+ HIVE_DAEMON: "0"
564358
+ };
564359
+ return mergeEnv(defaults2, fileEnv, homeEnv, process.env);
564360
+ }
564361
+ async validate() {
564362
+ const errors3 = [];
564363
+ const warnings = [];
564364
+ const info = [];
564365
+ try {
564366
+ const version4 = execSync3("bun --version", { encoding: "utf-8" }).trim();
564367
+ info.push(`Bun: v${version4}`);
564368
+ } catch {
564369
+ errors3.push("Bun is not installed or not in PATH");
564370
+ }
564371
+ try {
564372
+ const hivePath = execSync3("bun which hive", {
564373
+ encoding: "utf-8",
564374
+ stdio: ["ignore", "pipe", "ignore"]
564375
+ }).trim();
564376
+ if (hivePath && existsSync22(hivePath)) {
564377
+ info.push(`Hive binary: ${hivePath}`);
564378
+ const distDir = path36.dirname(hivePath);
564379
+ const uiDir = path36.join(distDir, "ui");
564380
+ if (existsSync22(uiDir)) {
564381
+ info.push(`UI directory: ${uiDir}`);
564382
+ } else {
564383
+ warnings.push("UI directory not found - may use embedded UI");
564384
+ }
564385
+ } else {
564386
+ errors3.push("Hive is not installed globally");
564387
+ }
564388
+ } catch {
564389
+ errors3.push("Hive is not installed globally (try: bun install -g @johpaz/hive-agents)");
564390
+ }
564391
+ if (existsSync22(this.hiveDir)) {
564392
+ info.push(`Hive home: ${this.hiveDir}`);
564393
+ } else {
564394
+ warnings.push(`Hive home directory does not exist: ${this.hiveDir}`);
564395
+ }
564396
+ const running = await this.isRunning();
564397
+ if (running) {
564398
+ info.push("Hive Gateway is running");
564399
+ const config4 = await this.getConfig();
564400
+ const healthy = await waitForHttpPort(config4.gateway.port, "/health", 5000);
564401
+ if (healthy) {
564402
+ info.push("Hive health check passed");
564403
+ } else {
564404
+ warnings.push("Hive Gateway is running but health check failed");
564405
+ }
564406
+ } else {
564407
+ warnings.push("Hive Gateway is not running");
564408
+ }
564409
+ try {
564410
+ execSync3("docker --version", { stdio: "ignore" });
564411
+ const dockerAdapter = new (await Promise.resolve().then(() => (init_docker(), exports_docker))).DockerAdapter;
564412
+ const dockerInstalled = await dockerAdapter.detect();
564413
+ if (dockerInstalled) {
564414
+ info.push("Note: Docker installation also detected");
564415
+ }
564416
+ } catch {}
564417
+ return {
564418
+ valid: errors3.length === 0,
564419
+ errors: errors3,
564420
+ warnings,
564421
+ info
564422
+ };
564423
+ }
564424
+ }
564425
+ var init_bun_global = __esm(() => {
564426
+ init_config3();
564427
+ init_types8();
564428
+ });
564429
+
564430
+ // packages/cli/src/adapters/binary.ts
564431
+ import { spawn as spawn7, execSync as execSync4 } from "child_process";
564432
+ import * as path37 from "path";
564433
+ import { existsSync as existsSync23, readFileSync as readFileSync13, unlinkSync as unlinkSync6 } from "fs";
564434
+
564435
+ class BinaryAdapter {
564436
+ type = "binary";
564437
+ hiveDir;
564438
+ pidFile;
564439
+ binaryPath;
564440
+ isDockerContainer;
564441
+ constructor(options2) {
564442
+ this.hiveDir = options2?.hiveDir || getHiveDir2();
564443
+ this.pidFile = path37.join(this.hiveDir, "gateway.pid");
564444
+ this.binaryPath = options2?.binaryPath || this.findBinary();
564445
+ this.isDockerContainer = process.env.HIVE_UI_DIR === "/app/ui" || process.env.HIVE_HOST === "0.0.0.0" || existsSync23("/.dockerenv");
564446
+ }
564447
+ get name() {
564448
+ return this.isDockerContainer ? "Docker Container" : "Standalone Binary";
564449
+ }
564450
+ findBinary() {
564451
+ const scriptPath = process.argv[1];
564452
+ if (scriptPath) {
564453
+ const dir = path37.dirname(scriptPath);
564454
+ if (path37.basename(dir) === "dist") {
564455
+ const binaryInDist = path37.join(dir, "hive");
564456
+ if (existsSync23(binaryInDist)) {
564457
+ return binaryInDist;
564458
+ }
564459
+ const binaryWindows = path37.join(dir, "hive.exe");
564460
+ if (existsSync23(binaryWindows)) {
564461
+ return binaryWindows;
564462
+ }
564463
+ }
564464
+ if (existsSync23(scriptPath) && !scriptPath.endsWith(".ts")) {
564465
+ return scriptPath;
564466
+ }
564467
+ }
564468
+ const commonPaths = [
564469
+ path37.join(process.cwd(), "dist", "hive"),
564470
+ path37.join(process.cwd(), "dist", "hive.exe"),
564471
+ "/usr/local/bin/hive",
564472
+ "/usr/bin/hive",
564473
+ path37.join(process.env.HOME || "", ".local", "bin", "hive"),
564474
+ path37.join(process.env.HOME || "", ".bun", "bin", "hive")
564475
+ ];
564476
+ for (const binaryPath of commonPaths) {
564477
+ if (existsSync23(binaryPath)) {
564478
+ return binaryPath;
564479
+ }
564480
+ }
564481
+ return process.execPath;
564482
+ }
564483
+ async detect() {
564484
+ const scriptPath = process.argv[1];
564485
+ if (!scriptPath) {
564486
+ return false;
564487
+ }
564488
+ if (scriptPath.endsWith(".ts")) {
564489
+ return false;
564490
+ }
564491
+ if (existsSync23(this.binaryPath)) {
564492
+ return true;
564493
+ }
564494
+ try {
564495
+ const { embeddedUI: embeddedUI2 } = await Promise.resolve().then(() => (init_ui_bundle_generated(), exports_ui_bundle_generated));
564496
+ if (embeddedUI2 && embeddedUI2.size > 0) {
564497
+ return true;
564498
+ }
564499
+ } catch {}
564500
+ const distDir = getDistDir();
564501
+ if (distDir) {
564502
+ const uiDir = path37.join(distDir, "ui");
564503
+ if (existsSync23(uiDir)) {
564504
+ return true;
564505
+ }
564506
+ }
564507
+ return false;
564508
+ }
564509
+ async getConfig() {
564510
+ const env3 = await this.getEnvironment();
564511
+ const paths = getDefaultPaths(this.hiveDir);
564512
+ if (this.isDockerContainer) {
564513
+ paths.uiDir = process.env.HIVE_UI_DIR || "/app/ui";
564514
+ }
564515
+ if (!this.isDockerContainer) {
564516
+ const distDir = getDistDir();
564517
+ if (distDir) {
564518
+ const uiDir = path37.join(distDir, "ui");
564519
+ if (existsSync23(uiDir)) {
564520
+ paths.uiDir = uiDir;
564521
+ }
564522
+ }
564523
+ }
564524
+ let hasEmbeddedUI = false;
564525
+ if (!this.isDockerContainer) {
564526
+ try {
564527
+ const { embeddedUI: embeddedUI2 } = await Promise.resolve().then(() => (init_ui_bundle_generated(), exports_ui_bundle_generated));
564528
+ hasEmbeddedUI = embeddedUI2 && embeddedUI2.size > 0;
564529
+ } catch {
564530
+ hasEmbeddedUI = false;
564531
+ }
564532
+ if (hasEmbeddedUI) {
564533
+ paths.uiDir = null;
564534
+ }
564535
+ }
564536
+ const port = parseInt(env3.HIVE_PORT || "18790", 10) || PORTS.GATEWAY;
564537
+ const publicUrl = env3.HIVE_PUBLIC_URL || undefined;
564538
+ return {
564539
+ type: this.type,
564540
+ gateway: {
564541
+ host: env3.HIVE_HOST || (this.isDockerContainer ? "0.0.0.0" : "127.0.0.1"),
564542
+ port,
564543
+ wsPort: port,
564544
+ codeBridgePort: PORTS.CODE_BRIDGE,
564545
+ publicUrl,
564546
+ openBrowser: !env3.NO_BROWSER && !this.isDockerContainer,
564547
+ daemon: !!env3.HIVE_DAEMON
564548
+ },
564549
+ paths,
564550
+ env: env3,
564551
+ isDev: false,
564552
+ hasEmbeddedUI: this.isDockerContainer ? false : hasEmbeddedUI
564553
+ };
564554
+ }
564555
+ async start(config4) {
564556
+ return new Promise((resolve9, reject) => {
564557
+ const args = ["start", "--skip-check"];
564558
+ if (config4.daemon) {
564559
+ args.push("--daemon");
564560
+ }
564561
+ const isBunScript = this.binaryPath.endsWith(".js") || this.binaryPath.endsWith(".ts");
564562
+ const executable = isBunScript ? process.execPath : this.binaryPath;
564563
+ const spawnArgs = isBunScript ? [this.binaryPath, ...args] : args;
564564
+ const child = spawn7(executable, spawnArgs, {
564565
+ stdio: "inherit",
564566
+ detached: false,
564567
+ env: mergeEnv(process.env, {
564568
+ HIVE_HOME: this.hiveDir,
564569
+ HIVE_GATEWAY_CHILD: "0"
564570
+ })
564571
+ });
564572
+ child.on("close", (code2) => {
564573
+ if (code2 === 0) {
564574
+ resolve9();
564575
+ } else {
564576
+ reject(new Error(`Hive binary exited with code ${code2}`));
564577
+ }
564578
+ });
564579
+ child.on("error", (error50) => {
564580
+ reject(error50);
564581
+ });
564582
+ });
564583
+ }
564584
+ async stop() {
564585
+ try {
564586
+ if (existsSync23(this.pidFile)) {
564587
+ const pid = parseInt(readFileSync13(this.pidFile, "utf-8").trim(), 10);
564588
+ if (!isNaN(pid)) {
564589
+ try {
564590
+ process.kill(pid, "SIGTERM");
564591
+ console.log(`\u2705 Hive Gateway detenido (PID: ${pid})`);
564592
+ } catch (error50) {
564593
+ if (error50.code === "ESRCH") {
564594
+ console.log("\u26A0\uFE0F Hive Gateway no est\xE1 corriendo");
564595
+ } else {
564596
+ throw error50;
564597
+ }
564598
+ } finally {
564599
+ try {
564600
+ unlinkSync6(this.pidFile);
564601
+ } catch {}
564602
+ }
564603
+ }
564604
+ } else {
564605
+ try {
564606
+ const pattern = process.platform === "win32" ? "hive.exe" : "hive";
564607
+ execSync4(`pkill -f "${pattern}"`, { stdio: "ignore" });
564608
+ console.log("\u2705 Hive Gateway detenido");
564609
+ } catch {
564610
+ console.log("\u26A0\uFE0F Hive Gateway no est\xE1 corriendo");
564611
+ }
564612
+ }
564613
+ } catch (error50) {
564614
+ console.error("\u274C Error deteniendo Hive Gateway:", error50.message);
564615
+ throw error50;
564616
+ }
564617
+ }
564618
+ async isRunning() {
564619
+ try {
564620
+ if (existsSync23(this.pidFile)) {
564621
+ const pid = parseInt(readFileSync13(this.pidFile, "utf-8").trim(), 10);
564622
+ if (!isNaN(pid)) {
564623
+ try {
564624
+ process.kill(pid, 0);
564625
+ return true;
564626
+ } catch {
564627
+ try {
564628
+ unlinkSync6(this.pidFile);
564629
+ } catch {}
564630
+ }
564631
+ }
564632
+ }
564633
+ const config4 = await this.getConfig();
564634
+ const portAvailable = await isPortAvailable(config4.gateway.port);
564635
+ return !portAvailable;
564636
+ } catch {
564637
+ return false;
564638
+ }
564639
+ }
564640
+ async getPid() {
564641
+ try {
564642
+ if (existsSync23(this.pidFile)) {
564643
+ const pid = parseInt(readFileSync13(this.pidFile, "utf-8").trim(), 10);
564644
+ if (!isNaN(pid) && pid > 0) {
564645
+ try {
564646
+ process.kill(pid, 0);
564647
+ return pid;
564648
+ } catch {}
564649
+ }
564650
+ }
564651
+ return null;
564652
+ } catch {
564653
+ return null;
564654
+ }
564655
+ }
564656
+ async getEnvironment() {
564657
+ const fileEnv = loadEnvFile();
564658
+ const homeEnv = loadEnvFile(path37.join(this.hiveDir, ".env"));
564659
+ const defaults2 = {
564660
+ HIVE_HOST: "127.0.0.1",
564661
+ HIVE_PORT: String(PORTS.GATEWAY),
564662
+ HIVE_HOME: this.hiveDir,
564663
+ HIVE_UI_DIR: process.env.HIVE_UI_DIR || "",
564664
+ NO_BROWSER: "0",
564665
+ HIVE_PUBLIC_URL: "",
564666
+ HIVE_DAEMON: "0",
564667
+ NODE_ENV: "production"
564668
+ };
564669
+ return mergeEnv(defaults2, fileEnv, homeEnv, process.env);
564670
+ }
564671
+ async validate() {
564672
+ const errors3 = [];
564673
+ const warnings = [];
564674
+ const info = [];
564675
+ if (existsSync23(this.binaryPath)) {
564676
+ info.push(`Binary: ${this.binaryPath}`);
564677
+ try {
564678
+ const stat3 = await import("fs/promises").then((m2) => m2.stat(this.binaryPath));
564679
+ if (stat3 && !stat3.isDirectory()) {
564680
+ const sizeKB = (stat3.size / 1024).toFixed(1);
564681
+ info.push(`Binary size: ${sizeKB} KB`);
564682
+ }
564683
+ } catch {}
564684
+ } else {
564685
+ errors3.push("Hive binary not found");
564686
+ }
564687
+ let hasEmbeddedUI = false;
564688
+ try {
564689
+ const { embeddedUI: embeddedUI2 } = await Promise.resolve().then(() => (init_ui_bundle_generated(), exports_ui_bundle_generated));
564690
+ if (embeddedUI2 && embeddedUI2.size > 0) {
564691
+ hasEmbeddedUI = true;
564692
+ info.push(`Embedded UI: ${embeddedUI2.size} files`);
564693
+ }
564694
+ } catch {}
564695
+ const distDir = getDistDir();
564696
+ if (distDir) {
564697
+ const uiDir = path37.join(distDir, "ui");
564698
+ if (existsSync23(uiDir)) {
564699
+ info.push(`UI directory: ${uiDir}`);
564700
+ } else if (!hasEmbeddedUI) {
564701
+ warnings.push("UI directory not found and no embedded UI");
564702
+ }
564703
+ }
564704
+ if (existsSync23(this.hiveDir)) {
564705
+ info.push(`Hive home: ${this.hiveDir}`);
564706
+ } else {
564707
+ warnings.push(`Hive home directory does not exist: ${this.hiveDir}`);
564708
+ }
564709
+ const running = await this.isRunning();
564710
+ if (running) {
564711
+ info.push("Hive Gateway is running");
564712
+ const config4 = await this.getConfig();
564713
+ const healthy = await waitForHttpPort(config4.gateway.port, "/health", 5000);
564714
+ if (healthy) {
564715
+ info.push("Hive health check passed");
564716
+ } else {
564717
+ warnings.push("Hive Gateway is running but health check failed");
564718
+ }
564719
+ } else {
564720
+ warnings.push("Hive Gateway is not running");
564721
+ }
564722
+ if (process.platform !== "win32" && existsSync23(this.binaryPath)) {
564723
+ try {
564724
+ execSync4(`test -x "${this.binaryPath}"`, { stdio: "ignore" });
564725
+ info.push("Binary is executable");
564726
+ } catch {
564727
+ warnings.push("Binary may not be executable (try: chmod +x <binary>)");
564728
+ }
564729
+ }
564730
+ return {
564731
+ valid: errors3.length === 0,
564732
+ errors: errors3,
564733
+ warnings,
564734
+ info
564735
+ };
564736
+ }
564737
+ }
564738
+ var init_binary = __esm(() => {
564739
+ init_config3();
564740
+ init_types8();
564741
+ });
564742
+
564743
+ // packages/cli/src/adapters/factory.ts
564744
+ function createAllAdapters(options2) {
564745
+ return {
564746
+ docker: new DockerAdapter({ hiveDir: options2?.hiveDir }),
564747
+ "bun-global": new BunGlobalAdapter({ hiveDir: options2?.hiveDir }),
564748
+ binary: new BinaryAdapter({ hiveDir: options2?.hiveDir })
564749
+ };
564750
+ }
564751
+ async function detectAdapter(options2) {
564752
+ const hiveDir = options2?.hiveDir;
564753
+ const verbose = options2?.verbose ?? false;
564754
+ if (options2?.forceType) {
564755
+ const adapters2 = createAllAdapters({ hiveDir });
564756
+ const adapter = adapters2[options2.forceType];
564757
+ if (verbose) {
564758
+ console.log(`Using forced adapter: ${adapter.name} (${options2.forceType})`);
564759
+ }
564760
+ return adapter;
564761
+ }
564762
+ const adapters = createAllAdapters({ hiveDir });
564763
+ for (const type2 of DETECTION_PRIORITY) {
564764
+ const adapter = adapters[type2];
564765
+ try {
564766
+ const isDetected = await adapter.detect();
564767
+ if (isDetected) {
564768
+ if (verbose) {
564769
+ console.log(`Detected installation: ${adapter.name} (${type2})`);
564770
+ }
564771
+ return adapter;
564772
+ }
564773
+ } catch (error50) {
564774
+ if (verbose) {
564775
+ console.warn(`Error detecting ${type2}:`, error50.message);
564776
+ }
564777
+ }
564778
+ }
564779
+ if (verbose) {
564780
+ console.log("No specific installation detected, using BinaryAdapter (fallback)");
564781
+ }
564782
+ return adapters.binary;
564783
+ }
564784
+ async function detectAllAdapters(options2) {
564785
+ const adapters = createAllAdapters({ hiveDir: options2?.hiveDir });
564786
+ const available = [];
564787
+ for (const type2 of DETECTION_PRIORITY) {
564788
+ const adapter = adapters[type2];
564789
+ try {
564790
+ if (await adapter.detect()) {
564791
+ available.push(adapter);
564792
+ }
564793
+ } catch {}
564794
+ }
564795
+ return available;
564796
+ }
564797
+ var DETECTION_PRIORITY;
564798
+ var init_factory = __esm(() => {
564799
+ init_docker();
564800
+ init_bun_global();
564801
+ init_binary();
564802
+ DETECTION_PRIORITY = [
564803
+ "docker",
564804
+ "binary",
564805
+ "bun-global"
564806
+ ];
564807
+ });
564808
+
564809
+ // packages/cli/src/adapters/index.ts
564810
+ var init_adapters = __esm(() => {
564811
+ init_types8();
564812
+ init_config3();
564813
+ init_docker();
564814
+ init_bun_global();
564815
+ init_binary();
564816
+ init_factory();
564817
+ });
564818
+
563598
564819
  // packages/code-bridge/src/process-manager.ts
563599
564820
  class ProcessManager {
563600
564821
  agents = new Map;
@@ -563950,50 +565171,20 @@ __export(exports_gateway, {
563950
565171
  stop: () => stop,
563951
565172
  status: () => status,
563952
565173
  start: () => start,
565174
+ resetAdapter: () => resetAdapter,
563953
565175
  reload: () => reload
563954
565176
  });
563955
- import { existsSync as existsSync20, mkdirSync as mkdirSync13, writeFileSync as writeFileSync6, readFileSync as readFileSync10, unlinkSync as unlinkSync5, openSync } from "fs";
563956
- import * as path33 from "path";
563957
- import { spawn as spawn5 } from "child_process";
563958
- async function findFreePort(startPort) {
563959
- for (let port = startPort;port < startPort + 100; port++) {
563960
- try {
563961
- const s2 = Bun.serve({ port, hostname: "0.0.0.0", fetch: () => new Response("") });
563962
- s2.stop();
563963
- return port;
563964
- } catch {
563965
- continue;
563966
- }
565177
+ import { existsSync as existsSync24, mkdirSync as mkdirSync13, writeFileSync as writeFileSync6, readFileSync as readFileSync14, unlinkSync as unlinkSync7, openSync } from "fs";
565178
+ import * as path38 from "path";
565179
+ import { spawn as spawn8 } from "child_process";
565180
+ async function getAdapter() {
565181
+ if (!_adapter) {
565182
+ _adapter = await detectAdapter({ verbose: false });
563967
565183
  }
563968
- throw new Error(`No free port found starting from ${startPort}`);
565184
+ return _adapter;
563969
565185
  }
563970
- function startUIServer(uiDir, gatewayPort, uiPort) {
563971
- const configScript = `<script>window.__HIVE_CONFIG__={"apiUrl":"http://localhost:${gatewayPort}","wsUrl":"ws://localhost:${gatewayPort}"}</script>`;
563972
- Bun.serve({
563973
- hostname: "0.0.0.0",
563974
- port: uiPort,
563975
- async fetch(req) {
563976
- const url3 = new URL(req.url);
563977
- let subPath = url3.pathname === "/" ? "/index.html" : url3.pathname;
563978
- if (!path33.extname(subPath))
563979
- subPath = "/index.html";
563980
- const filePath = path33.join(uiDir, subPath);
563981
- const file2 = Bun.file(filePath);
563982
- if (!await file2.exists()) {
563983
- const index2 = Bun.file(path33.join(uiDir, "index.html"));
563984
- if (await index2.exists()) {
563985
- const html = (await index2.text()).replace("</head>", `${configScript}</head>`);
563986
- return new Response(html, { headers: { "Content-Type": "text/html" } });
563987
- }
563988
- return new Response("Not found", { status: 404 });
563989
- }
563990
- if (subPath === "/index.html") {
563991
- const html = (await file2.text()).replace("</head>", `${configScript}</head>`);
563992
- return new Response(html, { headers: { "Content-Type": "text/html" } });
563993
- }
563994
- return new Response(file2);
563995
- }
563996
- });
565186
+ function resetAdapter() {
565187
+ _adapter = null;
563997
565188
  }
563998
565189
  function cleanup() {
563999
565190
  if (children.length === 0)
@@ -564011,22 +565202,22 @@ function cleanup() {
564011
565202
  }
564012
565203
  }
564013
565204
  function getDefaultPidFile() {
564014
- return path33.join(getHiveDir(), "gateway.pid");
565205
+ return path38.join(getHiveDir(), "gateway.pid");
564015
565206
  }
564016
565207
  function getLogFile() {
564017
- return path33.join(getHiveDir(), "logs", "gateway.log");
565208
+ return path38.join(getHiveDir(), "logs", "gateway.log");
564018
565209
  }
564019
565210
  async function getPidFile() {
564020
565211
  try {
564021
565212
  const config4 = await loadConfig();
564022
- return expandConfigPath(config4.gateway?.pidFile) ?? getDefaultPidFile();
565213
+ return config4.gateway?.pidFile || getDefaultPidFile();
564023
565214
  } catch {
564024
565215
  return getDefaultPidFile();
564025
565216
  }
564026
565217
  }
564027
565218
  function ensureLogDir() {
564028
- const logDir = path33.dirname(getLogFile());
564029
- if (!existsSync20(logDir)) {
565219
+ const logDir = path38.dirname(getLogFile());
565220
+ if (!existsSync24(logDir)) {
564030
565221
  mkdirSync13(logDir, { recursive: true });
564031
565222
  }
564032
565223
  }
@@ -564058,14 +565249,21 @@ function openBrowser(url3) {
564058
565249
  }
564059
565250
  async function isSetupMode2() {
564060
565251
  const hiveDir = getHiveDir();
564061
- const dbPath = path33.join(hiveDir, "data", "hive.db");
564062
- return !existsSync20(dbPath);
565252
+ const dbPath = path38.join(hiveDir, "data", "hive.db");
565253
+ return !existsSync24(dbPath);
564063
565254
  }
564064
565255
  async function isRunning() {
565256
+ try {
565257
+ const adapter = await getAdapter();
565258
+ const adapterRunning = await adapter.isRunning();
565259
+ if (adapterRunning) {
565260
+ return true;
565261
+ }
565262
+ } catch {}
564065
565263
  const pidFile = await getPidFile();
564066
- if (!existsSync20(pidFile))
565264
+ if (!existsSync24(pidFile))
564067
565265
  return false;
564068
- const pid = parseInt(readFileSync10(pidFile, "utf-8").trim(), 10);
565266
+ const pid = parseInt(readFileSync14(pidFile, "utf-8").trim(), 10);
564069
565267
  if (isNaN(pid))
564070
565268
  return false;
564071
565269
  try {
@@ -564073,27 +565271,13 @@ async function isRunning() {
564073
565271
  return true;
564074
565272
  } catch {
564075
565273
  try {
564076
- unlinkSync5(pidFile);
565274
+ unlinkSync7(pidFile);
564077
565275
  } catch {}
564078
565276
  return false;
564079
565277
  }
564080
565278
  }
564081
- async function waitForPort(port, timeout3 = 30000) {
564082
- const start = Date.now();
564083
- while (Date.now() - start < timeout3) {
564084
- try {
564085
- const response = await fetch(`http://127.0.0.1:${port}/health`, {
564086
- signal: AbortSignal.timeout(1000)
564087
- });
564088
- if (response.ok) {
564089
- const body = await response.json().catch(() => ({}));
564090
- if (body?.status === "ok")
564091
- return true;
564092
- }
564093
- } catch {}
564094
- await Bun.sleep(500);
564095
- }
564096
- return false;
565279
+ async function waitForPort2(port, timeout3 = 30000) {
565280
+ return waitForHttpPort(port, "/health", timeout3);
564097
565281
  }
564098
565282
  async function waitForVite(port, timeout3 = 30000) {
564099
565283
  const start = Date.now();
@@ -564115,22 +565299,21 @@ async function start(flags) {
564115
565299
  const daemon = flags.includes("--daemon");
564116
565300
  const skipCheck = flags.includes("--skip-check");
564117
565301
  const devInternal = flags.includes("--dev-internal");
564118
- const isDev = process.env.HIVE_DEV === "true";
564119
- const distDir = path33.dirname(process.argv[1] || "");
564120
- if (distDir && !process.env.HIVE_DIST_DIR) {
564121
- process.env.HIVE_DIST_DIR = distDir;
564122
- }
564123
- const hiveDir = getHiveDir();
564124
- const dbPath = path33.join(hiveDir, "data", "hive.db");
565302
+ const isDev = isDevMode();
565303
+ const isChild = isChildProcess();
565304
+ const adapter = await getAdapter();
565305
+ const config4 = await adapter.getConfig();
564125
565306
  const isGatewayChild = process.env.HIVE_GATEWAY_CHILD === "1";
564126
565307
  if (!skipCheck && await isRunning()) {
564127
565308
  console.log("\u26A0\uFE0F Hive Gateway ya est\xE1 corriendo");
564128
565309
  return;
564129
565310
  }
564130
- const config4 = await loadConfig();
564131
- if (config4.logging?.level) {
564132
- logger.setLevel(config4.logging.level);
564133
- }
565311
+ try {
565312
+ const coreConfig = await loadConfig();
565313
+ if (coreConfig.logging?.level) {
565314
+ logger.setLevel(coreConfig.logging.level);
565315
+ }
565316
+ } catch {}
564134
565317
  if (!isGatewayChild) {
564135
565318
  console.log(`
564136
565319
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
@@ -564142,14 +565325,16 @@ async function start(flags) {
564142
565325
  \u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2551
564143
565326
  \u2551 \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u2551
564144
565327
  \u2551 \u2551
564145
- \u2551 Personal Swarm AI Gateway \u2014 v0.0.5 \u2551
565328
+ \u2551 Personal Swarm AI Gateway \u2014 v0.0.8 \u2551
564146
565329
  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
565330
+
565331
+ \uD83D\uDCE6 Installation: ${adapter.name}
564147
565332
  `);
564148
565333
  }
564149
565334
  if (daemon) {
564150
565335
  ensureLogDir();
564151
565336
  const logFile = getLogFile();
564152
- const child = spawn5(process.execPath, [process.argv[1] || "", "start", "--skip-check"], {
565337
+ const child = spawn8(process.execPath, [process.argv[1] || "", "start", "--skip-check"], {
564153
565338
  detached: true,
564154
565339
  stdio: ["ignore", openSync(logFile, "a"), openSync(logFile, "a")],
564155
565340
  env: { ...process.env, HIVE_GATEWAY_CHILD: "1" }
@@ -564161,113 +565346,118 @@ async function start(flags) {
564161
565346
  return;
564162
565347
  }
564163
565348
  if (isDev) {
564164
- if (isGatewayChild) {
564165
- logger.info("Starting Gateway server (child process)...");
564166
- await startGateway(config4);
564167
- return;
564168
- }
564169
- const hiveUiPath = path33.join(process.cwd(), "packages/hive-ui");
564170
- const hasVite = existsSync20(path33.join(hiveUiPath, "package.json"));
564171
- if (hasVite) {
564172
- console.log(`\uD83C\uDFA8 Iniciando Vite (UI)...
565349
+ await handleDevMode(adapter, config4.gateway, daemon);
565350
+ return;
565351
+ }
565352
+ await handleProductionMode(adapter, config4.gateway, daemon);
565353
+ }
565354
+ async function handleDevMode(adapter, gatewayConfig, daemon) {
565355
+ if (isChildProcess()) {
565356
+ logger.info("Starting Gateway server (child process)...");
565357
+ const coreConfig = await loadConfig();
565358
+ await startGateway(coreConfig);
565359
+ return;
565360
+ }
565361
+ const hiveUiPath = path38.join(process.cwd(), "packages/hive-ui");
565362
+ const hasVite = existsSync24(path38.join(hiveUiPath, "package.json"));
565363
+ if (hasVite) {
565364
+ console.log(`\uD83C\uDFA8 Iniciando Vite (UI)...
564173
565365
  `);
564174
- const viteProcess = spawn5("bun", ["run", "dev"], {
564175
- cwd: hiveUiPath,
564176
- stdio: ["ignore", "pipe", "pipe"],
564177
- detached: true
564178
- });
564179
- viteProcess.stdout?.on("data", (data) => {
564180
- const lines = data.toString().split(`
565366
+ const viteProcess = spawn8("bun", ["run", "dev"], {
565367
+ cwd: hiveUiPath,
565368
+ stdio: ["ignore", "pipe", "pipe"],
565369
+ detached: true
565370
+ });
565371
+ viteProcess.stdout?.on("data", (data) => {
565372
+ const lines = data.toString().split(`
564181
565373
  `);
564182
- for (const line of lines) {
564183
- if (line.trim())
564184
- console.log(`[Vite] ${line}`);
564185
- }
564186
- });
564187
- viteProcess.stderr?.on("data", (data) => {
564188
- const lines = data.toString().split(`
565374
+ for (const line of lines) {
565375
+ if (line.trim())
565376
+ console.log(`[Vite] ${line}`);
565377
+ }
565378
+ });
565379
+ viteProcess.stderr?.on("data", (data) => {
565380
+ const lines = data.toString().split(`
564189
565381
  `);
564190
- for (const line of lines) {
564191
- if (line.trim())
564192
- console.error(`[Vite] ${line}`);
564193
- }
564194
- });
564195
- viteProcess.on("error", (error50) => {
564196
- console.error(`\u274C Error iniciando Vite: ${error50.message}`);
564197
- });
564198
- if (!daemon) {
564199
- children.push(viteProcess);
564200
- } else {
564201
- viteProcess.unref();
565382
+ for (const line of lines) {
565383
+ if (line.trim())
565384
+ console.error(`[Vite] ${line}`);
564202
565385
  }
565386
+ });
565387
+ viteProcess.on("error", (error50) => {
565388
+ console.error(`\u274C Error iniciando Vite: ${error50.message}`);
565389
+ });
565390
+ if (!daemon) {
565391
+ children.push(viteProcess);
565392
+ } else {
565393
+ viteProcess.unref();
564203
565394
  }
564204
- try {
564205
- await Promise.resolve().then(() => (init_src4(), exports_src));
564206
- } catch (error50) {
564207
- console.warn(`\u26A0\uFE0F No se pudo iniciar el Code Bridge: ${error50.message}`);
564208
- }
564209
- const spawnGateway = () => {
564210
- const gw = spawn5(process.execPath, [process.argv[1] || "", "start", "--skip-check", "--dev-internal"], {
564211
- detached: true,
564212
- stdio: ["ignore", "pipe", "pipe"],
564213
- env: { ...process.env, HIVE_DEV: "true", HIVE_GATEWAY_CHILD: "1" }
564214
- });
564215
- gw.stdout?.on("data", (data) => {
564216
- const lines = data.toString().split(`
565395
+ }
565396
+ try {
565397
+ await Promise.resolve().then(() => (init_src4(), exports_src));
565398
+ } catch (error50) {
565399
+ console.warn(`\u26A0\uFE0F No se pudo iniciar el Code Bridge: ${error50.message}`);
565400
+ }
565401
+ const spawnGateway = () => {
565402
+ const gw = spawn8(process.execPath, [process.argv[1] || "", "start", "--skip-check", "--dev-internal"], {
565403
+ detached: true,
565404
+ stdio: ["ignore", "pipe", "pipe"],
565405
+ env: { ...process.env, HIVE_DEV: "true", HIVE_GATEWAY_CHILD: "1" }
565406
+ });
565407
+ gw.stdout?.on("data", (data) => {
565408
+ const lines = data.toString().split(`
564217
565409
  `);
564218
- for (const line of lines) {
564219
- if (line.trim())
564220
- console.log(`[Gateway] ${line}`);
564221
- }
564222
- });
564223
- gw.stderr?.on("data", (data) => {
564224
- const lines = data.toString().split(`
565410
+ for (const line of lines) {
565411
+ if (line.trim())
565412
+ console.log(`[Gateway] ${line}`);
565413
+ }
565414
+ });
565415
+ gw.stderr?.on("data", (data) => {
565416
+ const lines = data.toString().split(`
564225
565417
  `);
564226
- for (const line of lines) {
564227
- if (line.trim())
564228
- console.error(`[Gateway] ${line}`);
564229
- }
564230
- });
564231
- gw.on("error", (error50) => {
564232
- console.error(`\u274C Error iniciando Gateway: ${error50.message}`);
564233
- });
564234
- gw.on("exit", (code2) => {
564235
- if (code2 === 0) {
564236
- console.log("[Gateway] Reiniciando tras setup...");
564237
- const newGw = spawnGateway();
564238
- if (!daemon) {
564239
- const idx = children.indexOf(gw);
564240
- if (idx !== -1)
564241
- children.splice(idx, 1, newGw);
564242
- }
564243
- }
564244
- });
564245
- if (!daemon) {
564246
- children.push(gw);
564247
- } else {
564248
- gw.unref();
565418
+ for (const line of lines) {
565419
+ if (line.trim())
565420
+ console.error(`[Gateway] ${line}`);
564249
565421
  }
564250
- return gw;
564251
- };
564252
- const gatewayProcess = spawnGateway();
564253
- console.log("\u23F3 Esperando servicios...");
564254
- const [viteReady, gatewayReady] = await Promise.all([
564255
- hasVite ? waitForVite(5173, 30000) : Promise.resolve(true),
564256
- waitForPort(18790, 30000)
564257
- ]);
564258
- if (!viteReady && hasVite) {
564259
- console.error("\u26A0\uFE0F Vite no respondi\xF3 a tiempo");
564260
- }
564261
- if (!gatewayReady) {
564262
- console.error("\u26A0\uFE0F Gateway no respondi\xF3 a tiempo");
564263
- return;
565422
+ });
565423
+ gw.on("error", (error50) => {
565424
+ console.error(`\u274C Error iniciando Gateway: ${error50.message}`);
565425
+ });
565426
+ gw.on("exit", (code2) => {
565427
+ if (code2 === 0) {
565428
+ console.log("[Gateway] Reiniciando tras setup...");
565429
+ const newGw = spawnGateway();
565430
+ const idx = children.indexOf(gw);
565431
+ if (idx !== -1)
565432
+ children.splice(idx, 1, newGw);
565433
+ }
565434
+ });
565435
+ if (!daemon) {
565436
+ children.push(gw);
565437
+ } else {
565438
+ gw.unref();
564264
565439
  }
564265
- console.log(`\u2705 Servicios listos
565440
+ return gw;
565441
+ };
565442
+ const gatewayProcess = spawnGateway();
565443
+ console.log("\u23F3 Esperando servicios...");
565444
+ const [viteReady, gatewayReady] = await Promise.all([
565445
+ hasVite ? waitForVite(5173, 30000) : Promise.resolve(true),
565446
+ waitForPort2(18790, 30000)
565447
+ ]);
565448
+ if (!viteReady && hasVite) {
565449
+ console.error("\u26A0\uFE0F Vite no respondi\xF3 a tiempo");
565450
+ }
565451
+ if (!gatewayReady) {
565452
+ console.error("\u26A0\uFE0F Gateway no respondi\xF3 a tiempo");
565453
+ return;
565454
+ }
565455
+ console.log(`\u2705 Servicios listos
564266
565456
  `);
564267
- const setupMode = await isSetupMode2();
564268
- const browserPort = hasVite ? 5173 : 18790;
564269
- const url3 = setupMode ? `http://localhost:${browserPort}/setup` : `http://localhost:${browserPort}`;
564270
- console.log(`
565457
+ const setupMode = await isSetupMode2();
565458
+ const browserPort = hasVite ? 5173 : 18790;
565459
+ const url3 = setupMode ? `http://localhost:${browserPort}/setup` : `http://localhost:${browserPort}`;
565460
+ console.log(`
564271
565461
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
564272
565462
  \u2551 \uD83D\uDC1D Hive \u2014 Modo Desarrollo \u2551
564273
565463
  \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
@@ -564279,10 +565469,15 @@ async function start(flags) {
564279
565469
  \u2551 ${setupMode ? "\uD83C\uDF89 Primer arranque \u2014 abriendo setup..." : "Administra tu Hive aqu\xED "}\u2551
564280
565470
  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
564281
565471
  `);
564282
- openBrowser(url3);
564283
- if (!daemon) {
564284
- await new Promise(() => {});
564285
- }
565472
+ openBrowser(url3);
565473
+ if (!daemon) {
565474
+ await new Promise(() => {});
565475
+ }
565476
+ }
565477
+ async function handleProductionMode(adapter, gatewayConfig, daemon) {
565478
+ if (isChildProcess()) {
565479
+ const coreConfig = await loadConfig();
565480
+ await startGateway(coreConfig);
564286
565481
  return;
564287
565482
  }
564288
565483
  try {
@@ -564291,52 +565486,29 @@ async function start(flags) {
564291
565486
  } catch (error50) {
564292
565487
  console.warn(`\u26A0\uFE0F No se pudo iniciar el Code Bridge: ${error50.message}`);
564293
565488
  }
564294
- if (isGatewayChild) {
564295
- await startGateway(config4);
564296
- return;
564297
- }
564298
- const port = config4.gateway?.port || 18790;
564299
- const uiDirFromEnv = process.env.HIVE_UI_DIR;
564300
- const uiDirFromDist = process.env.HIVE_DIST_DIR ? path33.join(process.env.HIVE_DIST_DIR, "ui") : null;
564301
- const uiDirFromCwd = path33.join(process.cwd(), "packages/hive-ui/dist");
564302
- const uiDir = uiDirFromEnv || (uiDirFromDist && existsSync20(path33.join(uiDirFromDist, "index.html")) ? uiDirFromDist : null) || (existsSync20(path33.join(uiDirFromCwd, "index.html")) ? uiDirFromCwd : null);
564303
- let uiPort = port;
564304
- if (uiDir) {
564305
- uiPort = await findFreePort(5173);
564306
- startUIServer(uiDir, port, uiPort);
564307
- console.log(`\uD83C\uDFA8 UI server en http://localhost:${uiPort}`);
564308
- }
564309
- waitForPort(port, 30000).then(async () => {
564310
- let needsSetup = false;
564311
- try {
564312
- const res = await fetch(`http://127.0.0.1:${port}/api/setup/status`, { signal: AbortSignal.timeout(3000) });
564313
- const body = await res.json();
564314
- needsSetup = body.setupMode === true;
564315
- } catch {
564316
- needsSetup = !existsSync20(dbPath);
564317
- }
564318
- const url3 = needsSetup ? `http://localhost:${uiPort}/setup` : `http://localhost:${uiPort}`;
564319
- if (needsSetup) {
564320
- console.log(`
564321
- \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
564322
- \u2551 \uD83C\uDF89 \xA1Bienvenido a Hive! \u2551
564323
- \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
564324
- \u2551 Abriendo configuraci\xF3n en tu browser \u2551
564325
- \u2551 ${url3.padEnd(38)}\u2551
564326
- \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
564327
- `);
565489
+ const adapterConfig = await adapter.getConfig();
565490
+ const isDocker = adapterConfig.type === "docker" || adapterConfig.type === "binary" && process.env.HIVE_UI_DIR === "/app/ui";
565491
+ const uiPort = gatewayConfig.port;
565492
+ const spawnGatewayProd = () => {
565493
+ const scriptPath = process.argv[1] || "";
565494
+ const isDockerContainer = process.env.HIVE_UI_DIR === "/app/ui";
565495
+ const isBunScript = scriptPath.endsWith(".js") || scriptPath.endsWith(".ts");
565496
+ let command2;
565497
+ let args;
565498
+ if (isDockerContainer) {
565499
+ command2 = "/app/hive-server";
565500
+ args = ["start", "--skip-check"];
565501
+ } else if (isBunScript) {
565502
+ command2 = process.execPath;
565503
+ args = [scriptPath, "start", "--skip-check"];
564328
565504
  } else {
564329
- console.log(`
564330
- \uD83C\uDF10 Hive listo en: ${url3}
564331
- `);
565505
+ command2 = process.execPath;
565506
+ args = ["start", "--skip-check"];
564332
565507
  }
564333
- openBrowser(url3);
564334
- });
564335
- const spawnGatewayProd = () => {
564336
- const gw = spawn5(process.execPath, [process.argv[1] || "", "start", "--skip-check"], {
565508
+ const gw = spawn8(command2, args, {
564337
565509
  detached: true,
564338
565510
  stdio: ["ignore", "pipe", "pipe"],
564339
- env: { ...process.env, HIVE_GATEWAY_CHILD: "1", NO_BROWSER: "1" }
565511
+ env: { ...process.env, HIVE_GATEWAY_CHILD: "1", NO_BROWSER: "1", ...getDistDir() ? { HIVE_DIST_DIR: getDistDir() } : {} }
564340
565512
  });
564341
565513
  gw.stdout?.on("data", (data) => {
564342
565514
  const lines = data.toString().split(`
@@ -564370,45 +565542,90 @@ async function start(flags) {
564370
565542
  return gw;
564371
565543
  };
564372
565544
  spawnGatewayProd();
565545
+ waitForPort2(gatewayConfig.port, 30000).then(async () => {
565546
+ let needsSetup = false;
565547
+ try {
565548
+ const res = await fetch(`http://127.0.0.1:${gatewayConfig.port}/api/setup/status`, {
565549
+ signal: AbortSignal.timeout(3000)
565550
+ });
565551
+ const body = await res.json();
565552
+ needsSetup = body.setupMode === true;
565553
+ } catch {
565554
+ const hiveDir = getHiveDir();
565555
+ const dbPath = path38.join(hiveDir, "data", "hive.db");
565556
+ needsSetup = !existsSync24(dbPath);
565557
+ }
565558
+ const url3 = needsSetup ? `http://localhost:${uiPort}/setup` : `http://localhost:${uiPort}`;
565559
+ if (needsSetup) {
565560
+ console.log(`
565561
+ \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
565562
+ \u2551 \uD83C\uDF89 \xA1Bienvenido a Hive! \u2551
565563
+ \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
565564
+ \u2551 Abriendo configuraci\xF3n en tu browser \u2551
565565
+ \u2551 ${url3.padEnd(38)}\u2551
565566
+ \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
565567
+ `);
565568
+ } else {
565569
+ console.log(`
565570
+ \uD83C\uDF10 Hive listo en: ${url3}
565571
+ `);
565572
+ }
565573
+ openBrowser(url3);
565574
+ });
564373
565575
  await new Promise(() => {});
564374
565576
  }
564375
565577
  async function stop() {
565578
+ const adapter = await getAdapter();
565579
+ try {
565580
+ if (await adapter.isRunning()) {
565581
+ await adapter.stop();
565582
+ console.log("\u2705 Hive Gateway detenido");
565583
+ return;
565584
+ }
565585
+ } catch {}
564376
565586
  if (!await isRunning()) {
564377
565587
  console.log("\u26A0\uFE0F Hive Gateway no est\xE1 corriendo");
564378
565588
  return;
564379
565589
  }
564380
565590
  const pidFile = await getPidFile();
564381
- const pid = parseInt(readFileSync10(pidFile, "utf-8").trim(), 10);
565591
+ const pid = parseInt(readFileSync14(pidFile, "utf-8").trim(), 10);
564382
565592
  try {
564383
565593
  process.kill(pid, "SIGTERM");
564384
- unlinkSync5(pidFile);
565594
+ unlinkSync7(pidFile);
564385
565595
  console.log("\u2705 Hive Gateway detenido");
564386
565596
  } catch (e) {
564387
565597
  console.error("\u274C Error deteniendo el Gateway:", e);
564388
565598
  }
564389
565599
  }
564390
565600
  async function status(flags) {
564391
- const running = await isRunning();
565601
+ const adapter = await getAdapter();
565602
+ const adapterConfig = await adapter.getConfig();
565603
+ const running = await adapter.isRunning();
564392
565604
  const hiveDir = getHiveDir();
564393
565605
  console.log(`\uD83D\uDC1D Hive Gateway Status
564394
565606
  `);
564395
- const config4 = await loadConfig();
564396
- const pidFile = await getPidFile();
564397
- console.log(`Estado: ${running ? "\u2705 Corriendo" : "\u23F9\uFE0F Detenido"}`);
564398
- if (running) {
564399
- const pid = readFileSync10(pidFile, "utf-8").trim();
564400
- console.log(`PID: ${pid}`);
564401
- }
564402
- console.log(`Puerto: ${config4.gateway?.port || 18790}`);
564403
- console.log(`Host: ${config4.gateway?.host || "127.0.0.1"}`);
564404
- const provider = config4.models?.defaultProvider || "no configurado";
564405
- const model = config4.models?.defaults?.[provider] || config4.models?.defaults?.default || "no configurado";
564406
- console.log(`Modelo: ${provider} / ${model}`);
564407
- console.log(`Home: ${hiveDir}`);
564408
- console.log(`Logs: ${getLogFile()}`);
565607
+ const coreConfig = await loadConfig();
565608
+ const pid = await adapter.getPid();
565609
+ console.log(`Estado: ${running ? "\u2705 Corriendo" : "\u23F9\uFE0F Detenido"}`);
565610
+ if (running && pid) {
565611
+ console.log(`PID: ${pid}`);
565612
+ }
565613
+ console.log(`Installation: ${adapter.name} (${adapterConfig.type})`);
565614
+ console.log(`Puerto: ${adapterConfig.gateway.port}`);
565615
+ console.log(`Host: ${adapterConfig.gateway.host}`);
565616
+ const provider = coreConfig.models?.defaultProvider || "no configurado";
565617
+ const model = coreConfig.models?.defaults?.[provider] || coreConfig.models?.defaults?.default || "no configurado";
565618
+ console.log(`Modelo: ${provider} / ${model}`);
565619
+ console.log(`Home: ${hiveDir}`);
565620
+ console.log(`Logs: ${getLogFile()}`);
564409
565621
  if (flags.includes("--json")) {
564410
565622
  console.log(`
564411
- ` + JSON.stringify({ running, pid: running ? readFileSync10(pidFile, "utf-8").trim() : null, config: config4 }, null, 2));
565623
+ ` + JSON.stringify({
565624
+ running,
565625
+ pid,
565626
+ type: adapterConfig.type,
565627
+ config: adapterConfig
565628
+ }, null, 2));
564412
565629
  }
564413
565630
  }
564414
565631
  async function reload() {
@@ -564416,7 +565633,8 @@ async function reload() {
564416
565633
  console.log("\u26A0\uFE0F Hive Gateway no est\xE1 corriendo");
564417
565634
  return;
564418
565635
  }
564419
- const pid = parseInt(readFileSync10(await getPidFile(), "utf-8").trim(), 10);
565636
+ const pidFile = await getPidFile();
565637
+ const pid = parseInt(readFileSync14(pidFile, "utf-8").trim(), 10);
564420
565638
  try {
564421
565639
  process.kill(pid, "SIGHUP");
564422
565640
  console.log("\u2705 Configuraci\xF3n recargada");
@@ -564424,9 +565642,11 @@ async function reload() {
564424
565642
  console.error("\u274C Error recargando configuraci\xF3n:", e);
564425
565643
  }
564426
565644
  }
564427
- var children;
565645
+ var children, _adapter = null;
564428
565646
  var init_gateway2 = __esm(() => {
564429
565647
  init_src3();
565648
+ init_ui_bundle_generated();
565649
+ init_adapters();
564430
565650
  children = [];
564431
565651
  process.on("SIGINT", () => {
564432
565652
  cleanup();
@@ -564449,7 +565669,7 @@ init_gateway2();
564449
565669
  init_dist2();
564450
565670
  init_loader();
564451
565671
  import * as fs21 from "fs";
564452
- import * as path34 from "path";
565672
+ import * as path39 from "path";
564453
565673
  function showDevBanner() {
564454
565674
  const hiveDir = getHiveDir();
564455
565675
  console.log(`
@@ -564462,7 +565682,7 @@ function showDevBanner() {
564462
565682
  }
564463
565683
  async function dev() {
564464
565684
  const hiveDir = getHiveDir();
564465
- const dbPath = path34.join(hiveDir, "data", "hive.db");
565685
+ const dbPath = path39.join(hiveDir, "data", "hive.db");
564466
565686
  if (!fs21.existsSync(hiveDir)) {
564467
565687
  fs21.mkdirSync(hiveDir, { recursive: true });
564468
565688
  }
@@ -564499,8 +565719,8 @@ async function dev() {
564499
565719
  init_dist2();
564500
565720
  init_loader();
564501
565721
  import * as fs22 from "fs";
564502
- import * as path35 from "path";
564503
- var getAgentsPath = () => path35.join(getHiveDir(), "agents");
565722
+ import * as path40 from "path";
565723
+ var getAgentsPath = () => path40.join(getHiveDir(), "agents");
564504
565724
  async function loadLifecycleAgents() {
564505
565725
  const agents = [];
564506
565726
  try {
@@ -564510,7 +565730,7 @@ async function loadLifecycleAgents() {
564510
565730
  for (const entry of entries) {
564511
565731
  if (!entry.isDirectory())
564512
565732
  continue;
564513
- const statePath = path35.join(getAgentsPath(), entry.name, "state.json");
565733
+ const statePath = path40.join(getAgentsPath(), entry.name, "state.json");
564514
565734
  try {
564515
565735
  const content = fs22.readFileSync(statePath, "utf-8");
564516
565736
  agents.push(JSON.parse(content));
@@ -564579,10 +565799,10 @@ async function createAgent(args) {
564579
565799
  const name = args[0] || await promptInput("Agent name:", `agent-${Date.now()}`);
564580
565800
  const purpose = args[1] || await promptInput("Purpose:", "General AI assistant");
564581
565801
  const agentId = `agent-${crypto.randomUUID().slice(0, 8)}`;
564582
- const workspacePath = path35.join(getAgentsPath(), agentId);
564583
- fs22.mkdirSync(path35.join(workspacePath, "memory"), { recursive: true });
564584
- fs22.mkdirSync(path35.join(workspacePath, "skills"), { recursive: true });
564585
- fs22.mkdirSync(path35.join(workspacePath, "logs"), { recursive: true });
565802
+ const workspacePath = path40.join(getAgentsPath(), agentId);
565803
+ fs22.mkdirSync(path40.join(workspacePath, "memory"), { recursive: true });
565804
+ fs22.mkdirSync(path40.join(workspacePath, "skills"), { recursive: true });
565805
+ fs22.mkdirSync(path40.join(workspacePath, "logs"), { recursive: true });
564586
565806
  const soulMd = `# SOUL.md - ${name}
564587
565807
 
564588
565808
  ## Identity
@@ -564604,9 +565824,9 @@ I am ${name}, created to ${purpose.toLowerCase()}.
564604
565824
  3. Safety - Prevent harm
564605
565825
  4. Consent - Ask before significant actions
564606
565826
  `;
564607
- fs22.writeFileSync(path35.join(workspacePath, "SOUL.md"), soulMd);
564608
- fs22.writeFileSync(path35.join(workspacePath, "ETHICS.md"), ethicsMd);
564609
- fs22.writeFileSync(path35.join(workspacePath, "USER.md"), `# USER.md
565827
+ fs22.writeFileSync(path40.join(workspacePath, "SOUL.md"), soulMd);
565828
+ fs22.writeFileSync(path40.join(workspacePath, "ETHICS.md"), ethicsMd);
565829
+ fs22.writeFileSync(path40.join(workspacePath, "USER.md"), `# USER.md
564610
565830
 
564611
565831
  ## Preferences
564612
565832
 
@@ -564623,7 +565843,7 @@ I am ${name}, created to ${purpose.toLowerCase()}.
564623
565843
  lastActivity: new Date().toISOString(),
564624
565844
  capabilities: ["general"]
564625
565845
  };
564626
- fs22.writeFileSync(path35.join(workspacePath, "state.json"), JSON.stringify(state2, null, 2));
565846
+ fs22.writeFileSync(path40.join(workspacePath, "state.json"), JSON.stringify(state2, null, 2));
564627
565847
  console.log(`
564628
565848
  \u2705 Agent created: ${name} (${agentId})`);
564629
565849
  console.log(` Workspace: ${workspacePath}
@@ -564646,7 +565866,7 @@ async function showLogs(agentId) {
564646
565866
  console.log("Usage: hive agents logs <agent-id>");
564647
565867
  return;
564648
565868
  }
564649
- const logPath = path35.join(getAgentsPath(), agentId, "logs");
565869
+ const logPath = path40.join(getAgentsPath(), agentId, "logs");
564650
565870
  try {
564651
565871
  const files = fs22.readdirSync(logPath).filter((f2) => f2.endsWith(".log")).sort().reverse();
564652
565872
  if (files.length === 0) {
@@ -564655,7 +565875,7 @@ async function showLogs(agentId) {
564655
565875
  `);
564656
565876
  return;
564657
565877
  }
564658
- const content = fs22.readFileSync(path35.join(logPath, files[0]), "utf-8");
565878
+ const content = fs22.readFileSync(path40.join(logPath, files[0]), "utf-8");
564659
565879
  console.log(`
564660
565880
  \uD83D\uDCCB Logs for ${agentId}:
564661
565881
  `);
@@ -564671,7 +565891,7 @@ async function hibernateAgent(agentId) {
564671
565891
  console.log("Usage: hive agents hibernate <agent-id>");
564672
565892
  return;
564673
565893
  }
564674
- const statePath = path35.join(getAgentsPath(), agentId, "state.json");
565894
+ const statePath = path40.join(getAgentsPath(), agentId, "state.json");
564675
565895
  try {
564676
565896
  const state2 = JSON.parse(fs22.readFileSync(statePath, "utf-8"));
564677
565897
  state2.state = "hibernated";
@@ -564691,7 +565911,7 @@ async function wakeAgent(agentId) {
564691
565911
  console.log("Usage: hive agents wake <agent-id>");
564692
565912
  return;
564693
565913
  }
564694
- const statePath = path35.join(getAgentsPath(), agentId, "state.json");
565914
+ const statePath = path40.join(getAgentsPath(), agentId, "state.json");
564695
565915
  try {
564696
565916
  const state2 = JSON.parse(fs22.readFileSync(statePath, "utf-8"));
564697
565917
  state2.state = "active";
@@ -564711,7 +565931,7 @@ async function terminateAgent(agentId, cascade) {
564711
565931
  console.log("Usage: hive agents terminate <agent-id> [--cascade]");
564712
565932
  return;
564713
565933
  }
564714
- const statePath = path35.join(getAgentsPath(), agentId, "state.json");
565934
+ const statePath = path40.join(getAgentsPath(), agentId, "state.json");
564715
565935
  try {
564716
565936
  const state2 = JSON.parse(fs22.readFileSync(statePath, "utf-8"));
564717
565937
  state2.state = "terminated";
@@ -564785,8 +566005,8 @@ async function addAgent(id) {
564785
566005
  Nt("Cancelado");
564786
566006
  return;
564787
566007
  }
564788
- const workspace = path35.join(getHiveDir(), "agents", id, "workspace");
564789
- const agentDir = path35.join(getHiveDir(), "agents", id, "agent");
566008
+ const workspace = path40.join(getHiveDir(), "agents", id, "workspace");
566009
+ const agentDir = path40.join(getHiveDir(), "agents", id, "agent");
564790
566010
  const newAgent = {
564791
566011
  id,
564792
566012
  name,
@@ -564795,14 +566015,14 @@ async function addAgent(id) {
564795
566015
  };
564796
566016
  fs22.mkdirSync(workspace, { recursive: true });
564797
566017
  fs22.mkdirSync(agentDir, { recursive: true });
564798
- const soulPath = path35.join(agentDir, "SOUL.md");
566018
+ const soulPath = path40.join(agentDir, "SOUL.md");
564799
566019
  if (!fs22.existsSync(soulPath)) {
564800
566020
  fs22.writeFileSync(soulPath, `# ${name} \u2014 Soul
564801
566021
 
564802
566022
  Eres ${name}, un agente especializado.
564803
566023
  `, "utf-8");
564804
566024
  }
564805
- const userPath = path35.join(agentDir, "USER.md");
566025
+ const userPath = path40.join(agentDir, "USER.md");
564806
566026
  if (!fs22.existsSync(userPath)) {
564807
566027
  fs22.writeFileSync(userPath, `# User Profile
564808
566028
 
@@ -564866,7 +566086,7 @@ async function removeAgent(id) {
564866
566086
  // packages/cli/src/commands/mcp.ts
564867
566087
  init_dist2();
564868
566088
  init_loader();
564869
- import { spawn as spawn6 } from "child_process";
566089
+ import { spawn as spawn9 } from "child_process";
564870
566090
  async function mcp(subcommand, args) {
564871
566091
  switch (subcommand) {
564872
566092
  case "list":
@@ -564963,7 +566183,7 @@ async function testMCP(name) {
564963
566183
  return;
564964
566184
  }
564965
566185
  console.log(`\uD83D\uDD0C Probando conexi\xF3n con ${name}...`);
564966
- const proc = spawn6(server4.command, server4.args || [], {
566186
+ const proc = spawn9(server4.command, server4.args || [], {
564967
566187
  env: { ...process.env, ...server4.env },
564968
566188
  stdio: ["pipe", "pipe", "pipe"]
564969
566189
  });
@@ -565009,8 +566229,8 @@ async function removeMCP(name) {
565009
566229
  // packages/cli/src/commands/skills.ts
565010
566230
  init_dist2();
565011
566231
  import * as fs23 from "fs";
565012
- import * as path36 from "path";
565013
- var SKILLS_DIR = path36.join(process.env.HOME || "", ".hive", "skills");
566232
+ import * as path41 from "path";
566233
+ var SKILLS_DIR = path41.join(process.env.HOME || "", ".hive", "skills");
565014
566234
  var BUNDLED_SKILLS = [
565015
566235
  { slug: "web-search", name: "Web Search", description: "Search the web using multiple search engines" },
565016
566236
  { slug: "code-exec", name: "Code Execution", description: "Execute code snippets safely" },
@@ -565059,14 +566279,14 @@ async function listSkills() {
565059
566279
  }
565060
566280
  if (fs23.existsSync(SKILLS_DIR)) {
565061
566281
  const managedSkills = fs23.readdirSync(SKILLS_DIR).filter((f2) => {
565062
- const skillPath = path36.join(SKILLS_DIR, f2);
566282
+ const skillPath = path41.join(SKILLS_DIR, f2);
565063
566283
  return fs23.statSync(skillPath).isDirectory();
565064
566284
  });
565065
566285
  if (managedSkills.length > 0) {
565066
566286
  console.log(`
565067
566287
  Managed (instaladas):`);
565068
566288
  for (const slug of managedSkills) {
565069
- const skillPath = path36.join(SKILLS_DIR, slug, "skill.json");
566289
+ const skillPath = path41.join(SKILLS_DIR, slug, "skill.json");
565070
566290
  if (fs23.existsSync(skillPath)) {
565071
566291
  const meta3 = JSON.parse(fs23.readFileSync(skillPath, "utf-8"));
565072
566292
  console.log(` \u2022 ${meta3.name || slug}`);
@@ -565118,7 +566338,7 @@ async function installSkill(slug) {
565118
566338
  if (!fs23.existsSync(SKILLS_DIR)) {
565119
566339
  fs23.mkdirSync(SKILLS_DIR, { recursive: true });
565120
566340
  }
565121
- const skillPath = path36.join(SKILLS_DIR, slug);
566341
+ const skillPath = path41.join(SKILLS_DIR, slug);
565122
566342
  if (fs23.existsSync(skillPath)) {
565123
566343
  console.log("\u26A0\uFE0F La skill ya est\xE1 instalada");
565124
566344
  return;
@@ -565130,7 +566350,7 @@ async function installSkill(slug) {
565130
566350
  description: "Skill instalada manualmente",
565131
566351
  installed: new Date().toISOString()
565132
566352
  };
565133
- fs23.writeFileSync(path36.join(skillPath, "skill.json"), JSON.stringify(meta3, null, 2));
566353
+ fs23.writeFileSync(path41.join(skillPath, "skill.json"), JSON.stringify(meta3, null, 2));
565134
566354
  console.log(`\u2705 Skill "${slug}" instalada`);
565135
566355
  }
565136
566356
  async function removeSkill(slug) {
@@ -565138,7 +566358,7 @@ async function removeSkill(slug) {
565138
566358
  console.log("\u274C Especifica la skill: hive skills remove <slug>");
565139
566359
  return;
565140
566360
  }
565141
- const skillPath = path36.join(SKILLS_DIR, slug);
566361
+ const skillPath = path41.join(SKILLS_DIR, slug);
565142
566362
  if (!fs23.existsSync(skillPath)) {
565143
566363
  console.log(`\u274C La skill "${slug}" no est\xE1 instalada`);
565144
566364
  return;
@@ -565161,7 +566381,7 @@ async function updateSkills() {
565161
566381
  }
565162
566382
  const spinner = be();
565163
566383
  spinner.start("Actualizando skills...");
565164
- await new Promise((resolve8) => setTimeout(resolve8, 1000));
566384
+ await new Promise((resolve9) => setTimeout(resolve9, 1000));
565165
566385
  spinner.stop("Skills actualizadas \u2705");
565166
566386
  }
565167
566387
 
@@ -565215,10 +566435,10 @@ async function showConfig() {
565215
566435
 
565216
566436
  // packages/cli/src/commands/logs.ts
565217
566437
  import * as fs24 from "fs";
565218
- import * as path37 from "path";
565219
- import { spawn as spawn7 } from "child_process";
565220
- var LOG_DIR = path37.join(process.env.HOME || "", ".hive", "logs");
565221
- var LOG_FILE = path37.join(LOG_DIR, "gateway.log");
566438
+ import * as path42 from "path";
566439
+ import { spawn as spawn10 } from "child_process";
566440
+ var LOG_DIR = path42.join(process.env.HOME || "", ".hive", "logs");
566441
+ var LOG_FILE = path42.join(LOG_DIR, "gateway.log");
565222
566442
  async function logs(flags) {
565223
566443
  if (flags.includes("--clear")) {
565224
566444
  await clearLogs();
@@ -565235,7 +566455,7 @@ async function logs(flags) {
565235
566455
  const agent = agentFlag ? agentFlag.split("=")[1] || flags[flags.indexOf(agentFlag) + 1] : null;
565236
566456
  const lines = 100;
565237
566457
  if (follow) {
565238
- const tail = spawn7("tail", ["-f", LOG_FILE], { stdio: "inherit" });
566458
+ const tail = spawn10("tail", ["-f", LOG_FILE], { stdio: "inherit" });
565239
566459
  process.on("SIGINT", () => {
565240
566460
  tail.kill();
565241
566461
  process.exit(0);
@@ -565288,8 +566508,8 @@ async function chat2(flags) {
565288
566508
  output: process.stdout
565289
566509
  });
565290
566510
  const question = (prompt) => {
565291
- return new Promise((resolve8) => {
565292
- rl.question(prompt, resolve8);
566511
+ return new Promise((resolve9) => {
566512
+ rl.question(prompt, resolve9);
565293
566513
  });
565294
566514
  };
565295
566515
  const messages2 = [];
@@ -565388,9 +566608,9 @@ async function callLLM2(config5, messages2) {
565388
566608
 
565389
566609
  // packages/cli/src/commands/sessions.ts
565390
566610
  import * as fs26 from "fs";
565391
- import * as path38 from "path";
565392
- var HIVE_DIR = path38.join(process.env.HOME || "", ".hive");
565393
- var SESSIONS_DIR = path38.join(HIVE_DIR, "sessions");
566611
+ import * as path43 from "path";
566612
+ var HIVE_DIR = path43.join(process.env.HOME || "", ".hive");
566613
+ var SESSIONS_DIR = path43.join(HIVE_DIR, "sessions");
565394
566614
  async function sessions(subcommand, args) {
565395
566615
  switch (subcommand) {
565396
566616
  case "list":
@@ -565427,7 +566647,7 @@ async function listSessions() {
565427
566647
  \uD83D\uDCCB Sesiones:
565428
566648
  `);
565429
566649
  for (const session of sessions2) {
565430
- const sessionPath = path38.join(SESSIONS_DIR, session);
566650
+ const sessionPath = path43.join(SESSIONS_DIR, session);
565431
566651
  const stat3 = fs26.statSync(sessionPath);
565432
566652
  const id = session.replace(".json", "");
565433
566653
  const date6 = stat3.mtime.toLocaleDateString();
@@ -565448,7 +566668,7 @@ async function viewSession(id) {
565448
566668
  console.log("\u274C Especifica el ID de la sesi\xF3n: hive sessions view <id>");
565449
566669
  return;
565450
566670
  }
565451
- const sessionPath = path38.join(SESSIONS_DIR, `${id}.json`);
566671
+ const sessionPath = path43.join(SESSIONS_DIR, `${id}.json`);
565452
566672
  if (!fs26.existsSync(sessionPath)) {
565453
566673
  console.log(`\u274C Sesi\xF3n no encontrada: ${id}`);
565454
566674
  return;
@@ -565475,7 +566695,7 @@ async function pruneSessions() {
565475
566695
  const maxAge = 7 * 24 * 60 * 60 * 1000;
565476
566696
  let pruned = 0;
565477
566697
  for (const session of sessions2) {
565478
- const sessionPath = path38.join(SESSIONS_DIR, session);
566698
+ const sessionPath = path43.join(SESSIONS_DIR, session);
565479
566699
  const stat3 = fs26.statSync(sessionPath);
565480
566700
  if (now - stat3.mtimeMs > maxAge) {
565481
566701
  fs26.unlinkSync(sessionPath);
@@ -565499,8 +566719,8 @@ function getUserTimezone2() {
565499
566719
  return "UTC";
565500
566720
  }
565501
566721
  }
565502
- async function apiRequest(path39, options2) {
565503
- const url3 = `${API_BASE}${path39}`;
566722
+ async function apiRequest(path44, options2) {
566723
+ const url3 = `${API_BASE}${path44}`;
565504
566724
  const response = await fetch(url3, {
565505
566725
  headers: {
565506
566726
  "Content-Type": "application/json",
@@ -565568,15 +566788,15 @@ async function listCron(args) {
565568
566788
  const statusFilter = args.find((a) => a.startsWith("--status="))?.split("=")[1];
565569
566789
  const typeFilter = args.find((a) => a.startsWith("--type="))?.split("=")[1];
565570
566790
  try {
565571
- let path39 = "/scheduled-tasks";
566791
+ let path44 = "/scheduled-tasks";
565572
566792
  const params2 = new URLSearchParams;
565573
566793
  if (statusFilter)
565574
566794
  params2.append("status", statusFilter);
565575
566795
  if (typeFilter)
565576
566796
  params2.append("task_type", typeFilter);
565577
566797
  if (params2.toString())
565578
- path39 += `?${params2.toString()}`;
565579
- const result2 = await apiRequest(path39);
566798
+ path44 += `?${params2.toString()}`;
566799
+ const result2 = await apiRequest(path44);
565580
566800
  if (!result2.tasks || result2.tasks.length === 0) {
565581
566801
  console.log("No scheduled tasks found");
565582
566802
  return;
@@ -565766,16 +566986,16 @@ async function cronAction(action, id) {
565766
566986
  }
565767
566987
  taskId = task.id;
565768
566988
  }
565769
- let path39 = `/scheduled-tasks/${taskId}`;
566989
+ let path44 = `/scheduled-tasks/${taskId}`;
565770
566990
  let method = "POST";
565771
566991
  if (action === "trigger") {
565772
- path39 += "/trigger";
566992
+ path44 += "/trigger";
565773
566993
  } else if (action === "delete") {
565774
566994
  method = "DELETE";
565775
566995
  } else {
565776
- path39 += `/${action}`;
566996
+ path44 += `/${action}`;
565777
566997
  }
565778
- await apiRequest(path39, { method });
566998
+ await apiRequest(path44, { method });
565779
566999
  console.log(`\u2705 Task "${id}" ${action}d`);
565780
567000
  } catch (err) {
565781
567001
  console.error(`\u274C Error: ${err.message}`);
@@ -565894,18 +567114,19 @@ function formatDate(isoString) {
565894
567114
  // packages/cli/src/commands/doctor.ts
565895
567115
  init_dist2();
565896
567116
  init_loader();
567117
+ init_adapters();
565897
567118
  import * as fs27 from "fs";
565898
- import * as path39 from "path";
565899
- import { execSync as execSync2 } from "child_process";
567119
+ import * as path44 from "path";
567120
+ import { execSync as execSync5 } from "child_process";
565900
567121
  var getHiveDirConst2 = () => getHiveDir();
565901
567122
  var getPidFile2 = () => {
565902
567123
  const config5 = loadConfig();
565903
- return config5.gateway?.pidFile ?? path39.join(getHiveDirConst2(), "gateway.pid");
567124
+ return config5.gateway?.pidFile ?? path44.join(getHiveDirConst2(), "gateway.pid");
565904
567125
  };
565905
- var getDbFile = () => path39.join(getHiveDirConst2(), "data", "hive.db");
567126
+ var getDbFile = () => path44.join(getHiveDirConst2(), "data", "hive.db");
565906
567127
  function checkBun() {
565907
567128
  try {
565908
- const version4 = execSync2("bun --version", { encoding: "utf-8" }).trim();
567129
+ const version4 = execSync5("bun --version", { encoding: "utf-8" }).trim();
565909
567130
  return { ok: true, version: version4 };
565910
567131
  } catch {
565911
567132
  return { ok: false, version: "no instalado" };
@@ -565913,7 +567134,7 @@ function checkBun() {
565913
567134
  }
565914
567135
  function checkNode() {
565915
567136
  try {
565916
- const version4 = execSync2("node --version", { encoding: "utf-8" }).trim();
567137
+ const version4 = execSync5("node --version", { encoding: "utf-8" }).trim();
565917
567138
  return { ok: true, version: version4 };
565918
567139
  } catch {
565919
567140
  return { ok: false, version: "no instalado" };
@@ -565937,6 +567158,64 @@ async function doctor() {
565937
567158
  \uD83D\uDC1D Hive Doctor \u2014 Diagn\xF3stico del sistema
565938
567159
  `);
565939
567160
  const checks4 = [];
567161
+ let detectedAdapter = null;
567162
+ let adapterValidation = null;
567163
+ try {
567164
+ detectedAdapter = await detectAdapter({ verbose: false });
567165
+ const validation2 = await detectedAdapter.validate();
567166
+ adapterValidation = validation2;
567167
+ checks4.push({
567168
+ category: "Installation",
567169
+ name: "Tipo detectado",
567170
+ status: "ok",
567171
+ message: `${detectedAdapter.name} (${detectedAdapter.type})`
567172
+ });
567173
+ for (const infoMsg of validation2.info) {
567174
+ checks4.push({
567175
+ category: "Installation",
567176
+ name: "Info",
567177
+ status: "ok",
567178
+ message: infoMsg
567179
+ });
567180
+ }
567181
+ for (const warnMsg of validation2.warnings) {
567182
+ checks4.push({
567183
+ category: "Installation",
567184
+ name: "Warning",
567185
+ status: "warn",
567186
+ message: warnMsg
567187
+ });
567188
+ }
567189
+ for (const errMsg of validation2.errors) {
567190
+ checks4.push({
567191
+ category: "Installation",
567192
+ name: "Error",
567193
+ status: "error",
567194
+ message: errMsg,
567195
+ hint: "Verifica la instalaci\xF3n o ejecuta hive update"
567196
+ });
567197
+ }
567198
+ } catch (error50) {
567199
+ checks4.push({
567200
+ category: "Installation",
567201
+ name: "Detecci\xF3n",
567202
+ status: "warn",
567203
+ message: `No se pudo detectar el adapter: ${error50.message}`
567204
+ });
567205
+ }
567206
+ try {
567207
+ const allAdapters = await detectAllAdapters();
567208
+ if (allAdapters.length > 1) {
567209
+ const installationNames = allAdapters.map((a) => a.name).join(", ");
567210
+ checks4.push({
567211
+ category: "Installation",
567212
+ name: "M\xFAltiples instalaciones",
567213
+ status: "warn",
567214
+ message: `${allAdapters.length} m\xE9todos detectados: ${installationNames}`,
567215
+ hint: "Esto puede causar conflictos. Considera usar solo uno."
567216
+ });
567217
+ }
567218
+ } catch {}
565940
567219
  const bun = checkBun();
565941
567220
  checks4.push({ category: "Runtime", name: "Bun", status: bun.ok ? "ok" : "error", message: `v${bun.version}` });
565942
567221
  const node2 = checkNode();
@@ -566019,9 +567298,9 @@ async function doctor() {
566019
567298
  // packages/cli/src/commands/security.ts
566020
567299
  init_loader();
566021
567300
  import * as fs28 from "fs";
566022
- import * as path40 from "path";
567301
+ import * as path45 from "path";
566023
567302
  var getHiveDirConst3 = () => getHiveDir();
566024
- var getWorkspace2 = () => path40.join(getHiveDirConst3(), "workspace");
567303
+ var getWorkspace2 = () => path45.join(getHiveDirConst3(), "workspace");
566025
567304
  async function securityAudit() {
566026
567305
  console.log(`
566027
567306
  \uD83D\uDD12 Hive Security Audit
@@ -566038,7 +567317,7 @@ async function securityAudit() {
566038
567317
  status: token && token.length > 0 ? "ok" : "warn",
566039
567318
  message: token && token.length > 0 ? "configurado" : "no configurado"
566040
567319
  });
566041
- const authProfiles = path40.join(getHiveDirConst3(), "auth-profiles.json");
567320
+ const authProfiles = path45.join(getHiveDirConst3(), "auth-profiles.json");
566042
567321
  if (fs28.existsSync(authProfiles)) {
566043
567322
  const stat3 = fs28.statSync(authProfiles);
566044
567323
  const mode = stat3.mode & 511;
@@ -566049,7 +567328,7 @@ async function securityAudit() {
566049
567328
  message: mode === 384 ? "600 (seguro)" : `${mode.toString(8)} \u2014 ejecuta: chmod 600 ${authProfiles}`
566050
567329
  });
566051
567330
  }
566052
- const envFile = path40.join(getHiveDirConst3(), ".env");
567331
+ const envFile = path45.join(getHiveDirConst3(), ".env");
566053
567332
  if (fs28.existsSync(envFile)) {
566054
567333
  const stat3 = fs28.statSync(envFile);
566055
567334
  const mode = stat3.mode & 511;
@@ -566100,10 +567379,10 @@ async function securityAudit() {
566100
567379
  } else {
566101
567380
  results.push({ category: "MCP", name: "Servidores", status: "ok", message: "ninguno configurado" });
566102
567381
  }
566103
- const skillsDir = path40.join(getHiveDirConst3(), "skills");
567382
+ const skillsDir = path45.join(getHiveDirConst3(), "skills");
566104
567383
  if (fs28.existsSync(skillsDir)) {
566105
567384
  const managedSkills = fs28.readdirSync(skillsDir).filter((f2) => {
566106
- return fs28.statSync(path40.join(skillsDir, f2)).isDirectory();
567385
+ return fs28.statSync(path45.join(skillsDir, f2)).isDirectory();
566107
567386
  });
566108
567387
  results.push({
566109
567388
  category: "Skills",
@@ -566131,10 +567410,10 @@ async function securityAudit() {
566131
567410
 
566132
567411
  // packages/cli/src/commands/service.ts
566133
567412
  import * as fs29 from "fs";
566134
- import * as path41 from "path";
566135
- import { execSync as execSync3 } from "child_process";
567413
+ import * as path46 from "path";
567414
+ import { execSync as execSync6 } from "child_process";
566136
567415
  var HOME = process.env.HOME || "";
566137
- var SYSTEMD_DIR = path41.join(HOME, ".config", "systemd", "user");
567416
+ var SYSTEMD_DIR = path46.join(HOME, ".config", "systemd", "user");
566138
567417
  async function installService() {
566139
567418
  console.log(`\uD83D\uDD27 Instalando servicio systemd para Hive...
566140
567419
  `);
@@ -566158,14 +567437,14 @@ WorkingDirectory=${HOME}
566158
567437
  [Install]
566159
567438
  WantedBy=default.target
566160
567439
  `;
566161
- const servicePath = path41.join(SYSTEMD_DIR, "hive.service");
567440
+ const servicePath = path46.join(SYSTEMD_DIR, "hive.service");
566162
567441
  fs29.writeFileSync(servicePath, serviceContent, "utf-8");
566163
567442
  console.log(`\u2705 Archivo de servicio creado: ${servicePath}
566164
567443
  `);
566165
567444
  console.log("Recargando systemd...");
566166
- execSync3("systemctl --user daemon-reload", { stdio: "inherit" });
567445
+ execSync6("systemctl --user daemon-reload", { stdio: "inherit" });
566167
567446
  console.log("Habilitando servicio...");
566168
- execSync3("systemctl --user enable hive", { stdio: "inherit" });
567447
+ execSync6("systemctl --user enable hive", { stdio: "inherit" });
566169
567448
  console.log(`
566170
567449
  \u2705 Servicio instalado correctamente.
566171
567450
  `);
@@ -566409,7 +567688,7 @@ async function executeAsync(gatewayUrl, payload, spinner) {
566409
567688
  }
566410
567689
 
566411
567690
  // packages/cli/src/index.ts
566412
- var VERSION4 = "0.0.5";
567691
+ var VERSION4 = "0.0.8";
566413
567692
  var HELP = `
566414
567693
  \uD83D\uDC1D Hive \u2014 Personal Swarm AI Gateway v${VERSION4}
566415
567694