import {
  loadCredentials,
  saveCredentials
} from "./chunks/chunk-SRCBBT4H.js";

// src/utils/client-header.ts
var DEEPLAKE_CLIENT_HEADER = "X-Deeplake-Client";
function deeplakeClientValue() {
  return "hivemind";
}
function deeplakeClientHeader() {
  return { [DEEPLAKE_CLIENT_HEADER]: deeplakeClientValue() };
}

// src/commands/auth.ts
var DEFAULT_API_URL = "https://api.deeplake.ai";
async function apiGet(path, token, apiUrl, orgId) {
  const headers = {
    Authorization: `Bearer ${token}`,
    "Content-Type": "application/json",
    ...deeplakeClientHeader()
  };
  if (orgId) headers["X-Activeloop-Org-Id"] = orgId;
  const resp = await fetch(`${apiUrl}${path}`, { headers });
  if (!resp.ok) throw new Error(`API ${resp.status}: ${await resp.text().catch(() => "")}`);
  return resp.json();
}
async function requestDeviceCode(apiUrl = DEFAULT_API_URL) {
  const resp = await fetch(`${apiUrl}/auth/device/code`, {
    method: "POST",
    headers: { "Content-Type": "application/json", ...deeplakeClientHeader() }
  });
  if (!resp.ok) throw new Error(`Device flow unavailable: HTTP ${resp.status}`);
  return resp.json();
}
async function pollForToken(deviceCode, apiUrl = DEFAULT_API_URL) {
  const resp = await fetch(`${apiUrl}/auth/device/token`, {
    method: "POST",
    headers: { "Content-Type": "application/json", ...deeplakeClientHeader() },
    body: JSON.stringify({ device_code: deviceCode })
  });
  if (resp.ok) return resp.json();
  if (resp.status === 400) {
    const err = await resp.json().catch(() => null);
    if (err?.error === "authorization_pending" || err?.error === "slow_down") return null;
    if (err?.error === "expired_token") throw new Error("Device code expired. Try again.");
    if (err?.error === "access_denied") throw new Error("Authorization denied.");
  }
  throw new Error(`Token polling failed: HTTP ${resp.status}`);
}
async function listOrgs(token, apiUrl = DEFAULT_API_URL) {
  const data = await apiGet("/organizations", token, apiUrl);
  return Array.isArray(data) ? data : [];
}
async function switchOrg(orgId, orgName) {
  const creds = loadCredentials();
  if (!creds) throw new Error("Not logged in. Run deeplake login first.");
  saveCredentials({ ...creds, orgId, orgName });
}
async function listWorkspaces(token, apiUrl = DEFAULT_API_URL, orgId) {
  const raw = await apiGet("/workspaces", token, apiUrl, orgId);
  const data = raw.data ?? raw;
  return Array.isArray(data) ? data : [];
}
async function switchWorkspace(workspaceId) {
  const creds = loadCredentials();
  if (!creds) throw new Error("Not logged in. Run deeplake login first.");
  saveCredentials({ ...creds, workspaceId });
}

// src/deeplake-api.ts
import { randomUUID } from "node:crypto";

// src/utils/debug.ts
import { appendFileSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
var DEBUG = false;
var LOG = join(homedir(), ".deeplake", "hook-debug.log");
function log(tag, msg) {
  if (!DEBUG) return;
  appendFileSync(LOG, `${(/* @__PURE__ */ new Date()).toISOString()} [${tag}] ${msg}
`);
}

// src/utils/sql.ts
function sqlStr(value) {
  return value.replace(/\\/g, "\\\\").replace(/'/g, "''").replace(/\0/g, "").replace(/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
}
function sqlLike(value) {
  return sqlStr(value).replace(/%/g, "\\%").replace(/_/g, "\\_");
}
function sqlIdent(name) {
  if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
    throw new Error(`Invalid SQL identifier: ${JSON.stringify(name)}`);
  }
  return name;
}

// src/embeddings/columns.ts
var SUMMARY_EMBEDDING_COL = "summary_embedding";
var MESSAGE_EMBEDDING_COL = "message_embedding";

// src/deeplake-api.ts
var indexMarkerStorePromise = null;
function getIndexMarkerStore() {
  if (!indexMarkerStorePromise) indexMarkerStorePromise = import("./chunks/index-marker-store-PGT5CW6T.js");
  return indexMarkerStorePromise;
}
var log2 = (msg) => log("sdk", msg);
function summarizeSql(sql, maxLen = 220) {
  const compact = sql.replace(/\s+/g, " ").trim();
  return compact.length > maxLen ? `${compact.slice(0, maxLen)}...` : compact;
}
function traceSql(msg) {
  const traceEnabled = false;
  if (!traceEnabled) return;
  process.stderr.write(`[deeplake-sql] ${msg}
`);
  if (false) log2(msg);
}
var RETRYABLE_CODES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
var MAX_RETRIES = 3;
var BASE_DELAY_MS = 500;
var MAX_CONCURRENCY = 5;
var QUERY_TIMEOUT_MS = Number(1e4);
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
function isTimeoutError(error) {
  const name = error instanceof Error ? error.name.toLowerCase() : "";
  const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
  return name.includes("timeout") || name === "aborterror" || message.includes("timeout") || message.includes("timed out");
}
function isDuplicateIndexError(error) {
  const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
  return message.includes("duplicate key value violates unique constraint") || message.includes("pg_class_relname_nsp_index") || message.includes("already exists");
}
function isSessionInsertQuery(sql) {
  return /^\s*insert\s+into\s+"[^"]+"\s*\(\s*id\s*,\s*path\s*,\s*filename\s*,\s*message\s*,/i.test(sql);
}
function isTransientHtml403(text) {
  const body = text.toLowerCase();
  return body.includes("<html") || body.includes("403 forbidden") || body.includes("cloudflare") || body.includes("nginx");
}
var Semaphore = class {
  constructor(max) {
    this.max = max;
  }
  max;
  waiting = [];
  active = 0;
  async acquire() {
    if (this.active < this.max) {
      this.active++;
      return;
    }
    await new Promise((resolve) => this.waiting.push(resolve));
  }
  release() {
    this.active--;
    const next = this.waiting.shift();
    if (next) {
      this.active++;
      next();
    }
  }
};
var DeeplakeApi = class {
  constructor(token, apiUrl, orgId, workspaceId, tableName) {
    this.token = token;
    this.apiUrl = apiUrl;
    this.orgId = orgId;
    this.workspaceId = workspaceId;
    this.tableName = tableName;
  }
  token;
  apiUrl;
  orgId;
  workspaceId;
  tableName;
  _pendingRows = [];
  _sem = new Semaphore(MAX_CONCURRENCY);
  _tablesCache = null;
  /** Execute SQL with retry on transient errors and bounded concurrency. */
  async query(sql) {
    const startedAt = Date.now();
    const summary = summarizeSql(sql);
    traceSql(`query start: ${summary}`);
    await this._sem.acquire();
    try {
      const rows = await this._queryWithRetry(sql);
      traceSql(`query ok (${Date.now() - startedAt}ms, rows=${rows.length}): ${summary}`);
      return rows;
    } catch (e) {
      const message = e instanceof Error ? e.message : String(e);
      traceSql(`query fail (${Date.now() - startedAt}ms): ${summary} :: ${message}`);
      throw e;
    } finally {
      this._sem.release();
    }
  }
  async _queryWithRetry(sql) {
    let lastError;
    for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
      let resp;
      try {
        const signal = AbortSignal.timeout(QUERY_TIMEOUT_MS);
        resp = await fetch(`${this.apiUrl}/workspaces/${this.workspaceId}/tables/query`, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${this.token}`,
            "Content-Type": "application/json",
            "X-Activeloop-Org-Id": this.orgId,
            ...deeplakeClientHeader()
          },
          signal,
          body: JSON.stringify({ query: sql })
        });
      } catch (e) {
        if (isTimeoutError(e)) {
          lastError = new Error(`Query timeout after ${QUERY_TIMEOUT_MS}ms`);
          throw lastError;
        }
        lastError = e instanceof Error ? e : new Error(String(e));
        if (attempt < MAX_RETRIES) {
          const delay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200;
          log2(`query retry ${attempt + 1}/${MAX_RETRIES} (fetch error: ${lastError.message}) in ${delay.toFixed(0)}ms`);
          await sleep(delay);
          continue;
        }
        throw lastError;
      }
      if (resp.ok) {
        const raw = await resp.json();
        if (!raw?.rows || !raw?.columns) return [];
        return raw.rows.map(
          (row) => Object.fromEntries(raw.columns.map((col, i) => [col, row[i]]))
        );
      }
      const text = await resp.text().catch(() => "");
      const retryable403 = isSessionInsertQuery(sql) && (resp.status === 401 || resp.status === 403 && (text.length === 0 || isTransientHtml403(text)));
      const alreadyExists = resp.status === 500 && isDuplicateIndexError(text);
      if (!alreadyExists && attempt < MAX_RETRIES && (RETRYABLE_CODES.has(resp.status) || retryable403)) {
        const delay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200;
        log2(`query retry ${attempt + 1}/${MAX_RETRIES} (${resp.status}) in ${delay.toFixed(0)}ms`);
        await sleep(delay);
        continue;
      }
      throw new Error(`Query failed: ${resp.status}: ${text.slice(0, 200)}`);
    }
    throw lastError ?? new Error("Query failed: max retries exceeded");
  }
  // ── Writes ──────────────────────────────────────────────────────────────────
  /** Queue rows for writing. Call commit() to flush. */
  appendRows(rows) {
    this._pendingRows.push(...rows);
  }
  /** Flush pending rows via SQL. */
  async commit() {
    if (this._pendingRows.length === 0) return;
    const rows = this._pendingRows;
    this._pendingRows = [];
    const CONCURRENCY = 10;
    for (let i = 0; i < rows.length; i += CONCURRENCY) {
      const chunk = rows.slice(i, i + CONCURRENCY);
      await Promise.allSettled(chunk.map((r) => this.upsertRowSql(r)));
    }
    log2(`commit: ${rows.length} rows`);
  }
  async upsertRowSql(row) {
    const ts = (/* @__PURE__ */ new Date()).toISOString();
    const cd = row.creationDate ?? ts;
    const lud = row.lastUpdateDate ?? ts;
    const exists = await this.query(
      `SELECT path FROM "${this.tableName}" WHERE path = '${sqlStr(row.path)}' LIMIT 1`
    );
    if (exists.length > 0) {
      let setClauses = `summary = E'${sqlStr(row.contentText)}', ${SUMMARY_EMBEDDING_COL} = NULL, mime_type = '${sqlStr(row.mimeType)}', size_bytes = ${row.sizeBytes}, last_update_date = '${lud}'`;
      if (row.project !== void 0) setClauses += `, project = '${sqlStr(row.project)}'`;
      if (row.description !== void 0) setClauses += `, description = '${sqlStr(row.description)}'`;
      await this.query(
        `UPDATE "${this.tableName}" SET ${setClauses} WHERE path = '${sqlStr(row.path)}'`
      );
    } else {
      const id = randomUUID();
      let cols = `id, path, filename, summary, ${SUMMARY_EMBEDDING_COL}, mime_type, size_bytes, creation_date, last_update_date`;
      let vals = `'${id}', '${sqlStr(row.path)}', '${sqlStr(row.filename)}', E'${sqlStr(row.contentText)}', NULL, '${sqlStr(row.mimeType)}', ${row.sizeBytes}, '${cd}', '${lud}'`;
      if (row.project !== void 0) {
        cols += ", project";
        vals += `, '${sqlStr(row.project)}'`;
      }
      if (row.description !== void 0) {
        cols += ", description";
        vals += `, '${sqlStr(row.description)}'`;
      }
      await this.query(
        `INSERT INTO "${this.tableName}" (${cols}) VALUES (${vals})`
      );
    }
  }
  /** Update specific columns on a row by path. */
  async updateColumns(path, columns) {
    const setClauses = Object.entries(columns).map(([col, val]) => typeof val === "number" ? `${col} = ${val}` : `${col} = '${sqlStr(String(val))}'`).join(", ");
    await this.query(
      `UPDATE "${this.tableName}" SET ${setClauses} WHERE path = '${sqlStr(path)}'`
    );
  }
  // ── Convenience ─────────────────────────────────────────────────────────────
  /** Create a BM25 search index on a column. */
  async createIndex(column) {
    await this.query(`CREATE INDEX IF NOT EXISTS idx_${sqlStr(column)}_bm25 ON "${this.tableName}" USING deeplake_index ("${column}")`);
  }
  buildLookupIndexName(table, suffix) {
    return `idx_${table}_${suffix}`.replace(/[^a-zA-Z0-9_]/g, "_");
  }
  async ensureLookupIndex(table, suffix, columnsSql) {
    const markers = await getIndexMarkerStore();
    const markerPath = markers.buildIndexMarkerPath(this.workspaceId, this.orgId, table, suffix);
    if (markers.hasFreshIndexMarker(markerPath)) return;
    const indexName = this.buildLookupIndexName(table, suffix);
    try {
      await this.query(`CREATE INDEX IF NOT EXISTS "${indexName}" ON "${table}" ${columnsSql}`);
      markers.writeIndexMarker(markerPath);
    } catch (e) {
      if (isDuplicateIndexError(e)) {
        markers.writeIndexMarker(markerPath);
        return;
      }
      log2(`index "${indexName}" skipped: ${e.message}`);
    }
  }
  /**
   * Ensure a vector column exists on the given table.
   *
   * The previous implementation always issued `ALTER TABLE ADD COLUMN IF NOT
   * EXISTS …` on every SessionStart. On a long-running workspace that's
   * already migrated, every call returns 500 "Column already exists" — noisy
   * in the log and a wasted round-trip. Worse, the very first call after the
   * column is genuinely added triggers Deeplake's post-ALTER `vector::at`
   * window (~30s) during which subsequent INSERTs fail; minimising the
   * number of ALTER calls minimises exposure to that window.
   *
   * New flow:
   *   1. Check the local marker file (mirrors ensureLookupIndex). If fresh,
   *      return — zero network calls.
   *   2. SELECT 1 FROM information_schema.columns WHERE table_name = T AND
   *      column_name = C. Read-only, idempotent, can't tickle the post-ALTER
   *      bug. If the column is present → mark + return.
   *   3. Only if step 2 says the column is missing, fall back to ALTER ADD
   *      COLUMN IF NOT EXISTS. Mark on success, also mark if Deeplake reports
   *      "already exists" (race: another client added it between our SELECT
   *      and ALTER).
   *
   * Marker uses the same dir / TTL as ensureLookupIndex so both schema
   * caches share an opt-out (HIVEMIND_INDEX_MARKER_DIR) and a TTL knob.
   */
  async ensureEmbeddingColumn(table, column) {
    await this.ensureColumn(table, column, "FLOAT4[]");
  }
  /**
   * Generic marker-gated column migration. Same SELECT-then-ALTER flow as
   * ensureEmbeddingColumn, parameterized by SQL type so it can patch up any
   * column that was added to the schema after the table was originally
   * created. Used today for `summary_embedding`, `message_embedding`, and
   * the `agent` column (added 2026-04-11) — the latter has no fallback if
   * a user upgraded over a pre-2026-04-11 table, so every INSERT fails
   * with `column "agent" does not exist`.
   */
  async ensureColumn(table, column, sqlType) {
    const markers = await getIndexMarkerStore();
    const markerPath = markers.buildIndexMarkerPath(this.workspaceId, this.orgId, table, `col_${column}`);
    if (markers.hasFreshIndexMarker(markerPath)) return;
    const colCheck = `SELECT 1 FROM information_schema.columns WHERE table_name = '${sqlStr(table)}' AND column_name = '${sqlStr(column)}' AND table_schema = '${sqlStr(this.workspaceId)}' LIMIT 1`;
    const rows = await this.query(colCheck);
    if (rows.length > 0) {
      markers.writeIndexMarker(markerPath);
      return;
    }
    try {
      await this.query(`ALTER TABLE "${table}" ADD COLUMN ${column} ${sqlType}`);
    } catch (e) {
      const msg = e instanceof Error ? e.message : String(e);
      if (!/already exists/i.test(msg)) throw e;
      const recheck = await this.query(colCheck);
      if (recheck.length === 0) throw e;
    }
    markers.writeIndexMarker(markerPath);
  }
  /** List all tables in the workspace (with retry). */
  async listTables(forceRefresh = false) {
    if (!forceRefresh && this._tablesCache) return [...this._tablesCache];
    const { tables, cacheable } = await this._fetchTables();
    if (cacheable) this._tablesCache = [...tables];
    return tables;
  }
  async _fetchTables() {
    for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
      try {
        const resp = await fetch(`${this.apiUrl}/workspaces/${this.workspaceId}/tables`, {
          headers: {
            Authorization: `Bearer ${this.token}`,
            "X-Activeloop-Org-Id": this.orgId,
            ...deeplakeClientHeader()
          }
        });
        if (resp.ok) {
          const data = await resp.json();
          return {
            tables: (data.tables ?? []).map((t) => t.table_name),
            cacheable: true
          };
        }
        if (attempt < MAX_RETRIES && RETRYABLE_CODES.has(resp.status)) {
          await sleep(BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200);
          continue;
        }
        return { tables: [], cacheable: false };
      } catch {
        if (attempt < MAX_RETRIES) {
          await sleep(BASE_DELAY_MS * Math.pow(2, attempt));
          continue;
        }
        return { tables: [], cacheable: false };
      }
    }
    return { tables: [], cacheable: false };
  }
  /**
   * Run a `CREATE TABLE` with an extra outer retry budget. The base
   * `query()` already retries 3 times on fetch errors (~3.5s total), but a
   * failed CREATE is permanent corruption — every subsequent SELECT against
   * the missing table fails. Wrapping in an outer loop with longer backoff
   * (2s, 5s, then 10s) gives us ~17s of reach across transient network
   * blips before giving up. Failures still propagate; getApi() resets its
   * cache on init failure (openclaw plugin) so the next call retries the
   * whole init flow.
   */
  async createTableWithRetry(sql, label) {
    const OUTER_BACKOFFS_MS = [2e3, 5e3, 1e4];
    let lastErr = null;
    for (let attempt = 0; attempt <= OUTER_BACKOFFS_MS.length; attempt++) {
      try {
        await this.query(sql);
        return;
      } catch (err) {
        lastErr = err;
        const msg = err instanceof Error ? err.message : String(err);
        log2(`CREATE TABLE "${label}" attempt ${attempt + 1}/${OUTER_BACKOFFS_MS.length + 1} failed: ${msg}`);
        if (attempt < OUTER_BACKOFFS_MS.length) {
          await sleep(OUTER_BACKOFFS_MS[attempt]);
        }
      }
    }
    throw lastErr;
  }
  /** Create the memory table if it doesn't already exist. Migrate columns on existing tables. */
  async ensureTable(name) {
    const tbl = sqlIdent(name ?? this.tableName);
    const tables = await this.listTables();
    if (!tables.includes(tbl)) {
      log2(`table "${tbl}" not found, creating`);
      await this.createTableWithRetry(
        `CREATE TABLE IF NOT EXISTS "${tbl}" (id TEXT NOT NULL DEFAULT '', path TEXT NOT NULL DEFAULT '', filename TEXT NOT NULL DEFAULT '', summary TEXT NOT NULL DEFAULT '', summary_embedding FLOAT4[], author TEXT NOT NULL DEFAULT '', mime_type TEXT NOT NULL DEFAULT 'text/plain', size_bytes BIGINT NOT NULL DEFAULT 0, project TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL DEFAULT '', creation_date TEXT NOT NULL DEFAULT '', last_update_date TEXT NOT NULL DEFAULT '') USING deeplake`,
        tbl
      );
      log2(`table "${tbl}" created`);
      if (!tables.includes(tbl)) this._tablesCache = [...tables, tbl];
    }
    await this.ensureEmbeddingColumn(tbl, SUMMARY_EMBEDDING_COL);
    await this.ensureColumn(tbl, "agent", "TEXT NOT NULL DEFAULT ''");
  }
  /** Create the sessions table (uses JSONB for message since every row is a JSON event). */
  async ensureSessionsTable(name) {
    const safe = sqlIdent(name);
    const tables = await this.listTables();
    if (!tables.includes(safe)) {
      log2(`table "${safe}" not found, creating`);
      await this.createTableWithRetry(
        `CREATE TABLE IF NOT EXISTS "${safe}" (id TEXT NOT NULL DEFAULT '', path TEXT NOT NULL DEFAULT '', filename TEXT NOT NULL DEFAULT '', message JSONB, message_embedding FLOAT4[], author TEXT NOT NULL DEFAULT '', mime_type TEXT NOT NULL DEFAULT 'application/json', size_bytes BIGINT NOT NULL DEFAULT 0, project TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL DEFAULT '', creation_date TEXT NOT NULL DEFAULT '', last_update_date TEXT NOT NULL DEFAULT '') USING deeplake`,
        safe
      );
      log2(`table "${safe}" created`);
      if (!tables.includes(safe)) this._tablesCache = [...tables, safe];
    }
    await this.ensureEmbeddingColumn(safe, MESSAGE_EMBEDDING_COL);
    await this.ensureColumn(safe, "agent", "TEXT NOT NULL DEFAULT ''");
    await this.ensureLookupIndex(safe, "path_creation_date", `("path", "creation_date")`);
  }
  /**
   * Create the skills table.
   *
   * One row per skill version. Workers INSERT a fresh row on every KEEP /
   * MERGE rather than UPDATE-ing in place, so the full version history is
   * recoverable. Uniqueness in the *current* state is by (project_key, name)
   * — newer rows shadow older ones at read time (ORDER BY version DESC).
   * This sidesteps the Deeplake UPDATE-coalescing quirk that bit the wiki
   * worker.
   */
  async ensureSkillsTable(name) {
    const safe = sqlIdent(name);
    const tables = await this.listTables();
    if (!tables.includes(safe)) {
      log2(`table "${safe}" not found, creating`);
      await this.createTableWithRetry(
        `CREATE TABLE IF NOT EXISTS "${safe}" (id TEXT NOT NULL DEFAULT '', name TEXT NOT NULL DEFAULT '', project TEXT NOT NULL DEFAULT '', project_key TEXT NOT NULL DEFAULT '', local_path TEXT NOT NULL DEFAULT '', install TEXT NOT NULL DEFAULT 'project', source_sessions TEXT NOT NULL DEFAULT '[]', source_agent TEXT NOT NULL DEFAULT '', scope TEXT NOT NULL DEFAULT 'me', author TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '', trigger_text TEXT NOT NULL DEFAULT '', body TEXT NOT NULL DEFAULT '', version BIGINT NOT NULL DEFAULT 1, created_at TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL DEFAULT '') USING deeplake`,
        safe
      );
      log2(`table "${safe}" created`);
      if (!tables.includes(safe)) this._tablesCache = [...tables, safe];
    }
    await this.ensureLookupIndex(safe, "project_key_name", `("project_key", "name")`);
  }
};

// src/shell/grep-core.ts
var TOOL_INPUT_FIELDS = [
  "command",
  "file_path",
  "path",
  "pattern",
  "prompt",
  "subagent_type",
  "query",
  "url",
  "notebook_path",
  "old_string",
  "new_string",
  "content",
  "skill",
  "args",
  "taskId",
  "status",
  "subject",
  "description",
  "to",
  "message",
  "summary",
  "max_results"
];
var TOOL_RESPONSE_DROP = /* @__PURE__ */ new Set([
  // Note: `stderr` is intentionally NOT in this set. The `stdout` high-signal
  // branch below already de-dupes it for the common case (appends as suffix
  // when non-empty). If a tool response has ONLY `stderr` and no `stdout`
  // (hard-failure on some tools), the generic cleanup preserves it so the
  // error message reaches Claude instead of collapsing to `[ok]`.
  "interrupted",
  "isImage",
  "noOutputExpected",
  "type",
  "structuredPatch",
  "userModified",
  "originalFile",
  "replaceAll",
  "totalDurationMs",
  "totalTokens",
  "totalToolUseCount",
  "usage",
  "toolStats",
  "durationMs",
  "durationSeconds",
  "bytes",
  "code",
  "codeText",
  "agentId",
  "agentType",
  "verificationNudgeNeeded",
  "numLines",
  "numFiles",
  "truncated",
  "statusChange",
  "updatedFields",
  "isAgent",
  "success"
]);
function maybeParseJson(v) {
  if (typeof v !== "string") return v;
  const s = v.trim();
  if (s[0] !== "{" && s[0] !== "[") return v;
  try {
    return JSON.parse(s);
  } catch {
    return v;
  }
}
function snakeCase(k) {
  return k.replace(/([A-Z])/g, "_$1").toLowerCase();
}
function camelCase(k) {
  return k.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
}
function formatToolInput(raw) {
  const p = maybeParseJson(raw);
  if (typeof p !== "object" || p === null) return String(p ?? "");
  const parts = [];
  for (const k of TOOL_INPUT_FIELDS) {
    if (p[k] === void 0) continue;
    const v = p[k];
    parts.push(`${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`);
  }
  for (const k of ["glob", "output_mode", "limit", "offset"]) {
    if (p[k] !== void 0) parts.push(`${k}: ${p[k]}`);
  }
  return parts.length ? parts.join("\n") : JSON.stringify(p);
}
function formatToolResponse(raw, inp, toolName) {
  const r = maybeParseJson(raw);
  if (typeof r !== "object" || r === null) return String(r ?? "");
  if (toolName === "Edit" || toolName === "Write" || toolName === "MultiEdit") {
    return r.filePath ? `[wrote ${r.filePath}]` : "[ok]";
  }
  if (typeof r.stdout === "string") {
    const stderr = r.stderr;
    return r.stdout + (stderr ? `
stderr: ${stderr}` : "");
  }
  if (typeof r.content === "string") return r.content;
  if (r.file && typeof r.file === "object") {
    const f = r.file;
    if (typeof f.content === "string") return `[${f.filePath ?? ""}]
${f.content}`;
    if (typeof f.base64 === "string") return `[binary ${f.filePath ?? ""}: ${f.base64.length} base64 chars]`;
  }
  if (Array.isArray(r.filenames)) return r.filenames.join("\n");
  if (Array.isArray(r.matches)) {
    return r.matches.map((m) => typeof m === "string" ? m : JSON.stringify(m)).join("\n");
  }
  if (Array.isArray(r.results)) {
    return r.results.map((x) => typeof x === "string" ? x : x?.title ?? x?.url ?? JSON.stringify(x)).join("\n");
  }
  const inpObj = maybeParseJson(inp);
  const kept = {};
  for (const [k, v] of Object.entries(r)) {
    if (TOOL_RESPONSE_DROP.has(k)) continue;
    if (v === "" || v === false || v == null) continue;
    if (typeof inpObj === "object" && inpObj) {
      const inObj = inpObj;
      if (k in inObj && JSON.stringify(inObj[k]) === JSON.stringify(v)) continue;
      const snake = snakeCase(k);
      if (snake in inObj && JSON.stringify(inObj[snake]) === JSON.stringify(v)) continue;
      const camel = camelCase(k);
      if (camel in inObj && JSON.stringify(inObj[camel]) === JSON.stringify(v)) continue;
    }
    kept[k] = v;
  }
  return Object.keys(kept).length ? JSON.stringify(kept) : "[ok]";
}
function formatToolCall(obj) {
  return `[tool:${obj?.tool_name ?? "?"}]
input: ${formatToolInput(obj?.tool_input)}
response: ${formatToolResponse(obj?.tool_response, obj?.tool_input, obj?.tool_name)}`;
}
function normalizeContent(path, raw) {
  if (!path.includes("/sessions/")) return raw;
  if (!raw || raw[0] !== "{") return raw;
  let obj;
  try {
    obj = JSON.parse(raw);
  } catch {
    return raw;
  }
  if (Array.isArray(obj.turns)) {
    const dateHeader = obj.date_time ? `(${String(obj.date_time)}) ` : "";
    const lines = obj.turns.map((t) => {
      const sp = String(t?.speaker ?? t?.name ?? "?").trim();
      const tx = String(t?.text ?? t?.content ?? "").replace(/\s+/g, " ").trim();
      const tag = t?.dia_id ? `[${t.dia_id}] ` : "";
      return `${dateHeader}${tag}${sp}: ${tx}`;
    });
    const out2 = lines.join("\n");
    return out2.trim() ? out2 : raw;
  }
  if (obj.turn && typeof obj.turn === "object" && !Array.isArray(obj.turn)) {
    const t = obj.turn;
    const sp = String(t.speaker ?? t.name ?? "?").trim();
    const tx = String(t.text ?? t.content ?? "").replace(/\s+/g, " ").trim();
    const tag = t.dia_id ? `[${String(t.dia_id)}] ` : "";
    const dateHeader = obj.date_time ? `(${String(obj.date_time)}) ` : "";
    const line = `${dateHeader}${tag}${sp}: ${tx}`;
    return line.trim() ? line : raw;
  }
  const stripRecalled = (t) => {
    const i = t.indexOf("<recalled-memories>");
    if (i === -1) return t;
    const j = t.lastIndexOf("</recalled-memories>");
    if (j === -1 || j < i) return t;
    const head = t.slice(0, i);
    const tail = t.slice(j + "</recalled-memories>".length);
    return (head + tail).replace(/^\s+/, "").replace(/\n{3,}/g, "\n\n");
  };
  let out = null;
  if (obj.type === "user_message") {
    out = `[user] ${stripRecalled(String(obj.content ?? ""))}`;
  } else if (obj.type === "assistant_message") {
    const agent = obj.agent_type ? ` (agent=${obj.agent_type})` : "";
    out = `[assistant${agent}] ${stripRecalled(String(obj.content ?? ""))}`;
  } else if (obj.type === "tool_call") {
    out = formatToolCall(obj);
  }
  if (out === null) return raw;
  const trimmed = out.trim();
  if (!trimmed || trimmed === "[user]" || trimmed === "[assistant]" || /^\[tool:[^\]]*\]\s+input:\s+\{\}\s+response:\s+\{\}$/.test(trimmed)) return raw;
  return out;
}
function buildPathCondition(targetPath) {
  if (!targetPath || targetPath === "/") return "";
  const clean = targetPath.replace(/\/+$/, "");
  if (/[*?]/.test(clean)) {
    const likePattern = sqlLike(clean).replace(/\*/g, "%").replace(/\?/g, "_");
    return `path LIKE '${likePattern}' ESCAPE '\\'`;
  }
  const base = clean.split("/").pop() ?? "";
  if (base.includes(".")) {
    return `path = '${sqlStr(clean)}'`;
  }
  return `(path = '${sqlStr(clean)}' OR path LIKE '${sqlLike(clean)}/%' ESCAPE '\\')`;
}
async function searchDeeplakeTables(api2, memoryTable2, sessionsTable2, opts) {
  const { pathFilter, contentScanOnly, likeOp, escapedPattern, prefilterPattern, prefilterPatterns, queryEmbedding, multiWordPatterns } = opts;
  const limit = opts.limit ?? 100;
  if (queryEmbedding && queryEmbedding.length > 0) {
    const vecLit = serializeFloat4Array(queryEmbedding);
    const semanticLimit = Math.min(
      limit,
      Number(process.env.HIVEMIND_SEMANTIC_LIMIT ?? "20")
    );
    const lexicalLimit = Math.min(
      limit,
      Number(process.env.HIVEMIND_HYBRID_LEXICAL_LIMIT ?? "20")
    );
    const filterPatternsForLex = contentScanOnly ? prefilterPatterns && prefilterPatterns.length > 0 ? prefilterPatterns : prefilterPattern ? [prefilterPattern] : [] : [escapedPattern];
    const memLexFilter = buildContentFilter("summary::text", likeOp, filterPatternsForLex);
    const sessLexFilter = buildContentFilter("message::text", likeOp, filterPatternsForLex);
    const memLexQuery = memLexFilter ? `SELECT path, summary::text AS content, 0 AS source_order, '' AS creation_date, 1.0 AS score FROM "${memoryTable2}" WHERE 1=1${pathFilter}${memLexFilter} LIMIT ${lexicalLimit}` : null;
    const sessLexQuery = sessLexFilter ? `SELECT path, message::text AS content, 1 AS source_order, COALESCE(creation_date::text, '') AS creation_date, 1.0 AS score FROM "${sessionsTable2}" WHERE 1=1${pathFilter}${sessLexFilter} LIMIT ${lexicalLimit}` : null;
    const memSemQuery = `SELECT path, summary::text AS content, 0 AS source_order, '' AS creation_date, (summary_embedding <#> ${vecLit}) AS score FROM "${memoryTable2}" WHERE ARRAY_LENGTH(summary_embedding, 1) > 0${pathFilter} ORDER BY score DESC LIMIT ${semanticLimit}`;
    const sessSemQuery = `SELECT path, message::text AS content, 1 AS source_order, COALESCE(creation_date::text, '') AS creation_date, (message_embedding <#> ${vecLit}) AS score FROM "${sessionsTable2}" WHERE ARRAY_LENGTH(message_embedding, 1) > 0${pathFilter} ORDER BY score DESC LIMIT ${semanticLimit}`;
    const parts = [memSemQuery, sessSemQuery];
    if (memLexQuery) parts.push(memLexQuery);
    if (sessLexQuery) parts.push(sessLexQuery);
    const unionSql = parts.map((q) => `(${q})`).join(" UNION ALL ");
    const outerLimit = semanticLimit + lexicalLimit;
    const rows2 = await api2.query(
      `SELECT path, content, source_order, creation_date, score FROM (` + unionSql + `) AS combined ORDER BY score DESC LIMIT ${outerLimit}`
    );
    const seen = /* @__PURE__ */ new Set();
    const unique = [];
    for (const row of rows2) {
      const p = String(row["path"]);
      if (seen.has(p)) continue;
      seen.add(p);
      unique.push({ path: p, content: String(row["content"] ?? "") });
    }
    return unique;
  }
  const filterPatterns = contentScanOnly ? prefilterPatterns && prefilterPatterns.length > 0 ? prefilterPatterns : prefilterPattern ? [prefilterPattern] : [] : multiWordPatterns && multiWordPatterns.length > 1 ? multiWordPatterns : [escapedPattern];
  const memFilter = buildContentFilter("summary::text", likeOp, filterPatterns);
  const sessFilter = buildContentFilter("message::text", likeOp, filterPatterns);
  const memQuery = `SELECT path, summary::text AS content, 0 AS source_order, '' AS creation_date FROM "${memoryTable2}" WHERE 1=1${pathFilter}${memFilter} LIMIT ${limit}`;
  const sessQuery = `SELECT path, message::text AS content, 1 AS source_order, COALESCE(creation_date::text, '') AS creation_date FROM "${sessionsTable2}" WHERE 1=1${pathFilter}${sessFilter} LIMIT ${limit}`;
  const rows = await api2.query(
    `SELECT path, content, source_order, creation_date FROM ((${memQuery}) UNION ALL (${sessQuery})) AS combined ORDER BY path, source_order, creation_date`
  );
  return rows.map((row) => ({
    path: String(row["path"]),
    content: String(row["content"] ?? "")
  }));
}
function serializeFloat4Array(vec) {
  const parts = [];
  for (const v of vec) {
    if (!Number.isFinite(v)) return "NULL";
    parts.push(String(v));
  }
  return `ARRAY[${parts.join(",")}]::float4[]`;
}
function buildPathFilter(targetPath) {
  const condition = buildPathCondition(targetPath);
  return condition ? ` AND ${condition}` : "";
}
function extractRegexLiteralPrefilter(pattern) {
  if (!pattern) return null;
  const parts = [];
  let current = "";
  for (let i = 0; i < pattern.length; i++) {
    const ch = pattern[i];
    if (ch === "\\") {
      const next = pattern[i + 1];
      if (!next) return null;
      if (/[dDsSwWbBAZzGkKpP]/.test(next)) return null;
      current += next;
      i++;
      continue;
    }
    if (ch === ".") {
      if (pattern[i + 1] === "*") {
        if (current) parts.push(current);
        current = "";
        i++;
        continue;
      }
      return null;
    }
    if ("|()[]{}+?^$".includes(ch) || ch === "*") return null;
    current += ch;
  }
  if (current) parts.push(current);
  const literal = parts.reduce((best, part) => part.length > best.length ? part : best, "");
  return literal.length >= 2 ? literal : null;
}
function extractRegexAlternationPrefilters(pattern) {
  if (!pattern.includes("|")) return null;
  const parts = [];
  let current = "";
  let escaped = false;
  for (let i = 0; i < pattern.length; i++) {
    const ch = pattern[i];
    if (escaped) {
      current += `\\${ch}`;
      escaped = false;
      continue;
    }
    if (ch === "\\") {
      escaped = true;
      continue;
    }
    if (ch === "|") {
      if (!current) return null;
      parts.push(current);
      current = "";
      continue;
    }
    if ("()[]{}^$".includes(ch)) return null;
    current += ch;
  }
  if (escaped || !current) return null;
  parts.push(current);
  const literals = [...new Set(
    parts.map((part) => extractRegexLiteralPrefilter(part)).filter((part) => typeof part === "string" && part.length >= 2)
  )];
  return literals.length > 0 ? literals : null;
}
function buildGrepSearchOptions(params, targetPath) {
  const hasRegexMeta = !params.fixedString && /[.*+?^${}()|[\]\\]/.test(params.pattern);
  const literalPrefilter = hasRegexMeta ? extractRegexLiteralPrefilter(params.pattern) : null;
  const alternationPrefilters = hasRegexMeta ? extractRegexAlternationPrefilters(params.pattern) : null;
  const multiWordPatterns = !hasRegexMeta ? params.pattern.split(/\s+/).filter((w) => w.length > 2).slice(0, 4) : [];
  return {
    pathFilter: buildPathFilter(targetPath),
    contentScanOnly: hasRegexMeta,
    likeOp: process.env.HIVEMIND_GREP_LIKE === "case-sensitive" ? "LIKE" : "ILIKE",
    escapedPattern: sqlLike(params.pattern),
    prefilterPattern: literalPrefilter ? sqlLike(literalPrefilter) : void 0,
    prefilterPatterns: alternationPrefilters?.map((literal) => sqlLike(literal)),
    multiWordPatterns: multiWordPatterns.length > 1 ? multiWordPatterns.map((w) => sqlLike(w)) : void 0
  };
}
function buildContentFilter(column, likeOp, patterns) {
  if (patterns.length === 0) return "";
  if (patterns.length === 1) return ` AND ${column} ${likeOp} '%${patterns[0]}%'`;
  return ` AND (${patterns.map((pattern) => `${column} ${likeOp} '%${pattern}%'`).join(" OR ")})`;
}
function compileGrepRegex(params) {
  let reStr = params.fixedString ? params.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : params.pattern;
  if (params.wordMatch) reStr = `\\b${reStr}\\b`;
  try {
    return new RegExp(reStr, params.ignoreCase ? "i" : "");
  } catch {
    return new RegExp(
      params.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
      params.ignoreCase ? "i" : ""
    );
  }
}

// src/hooks/virtual-table-query.ts
function normalizeSessionPart(path, content) {
  return normalizeContent(path, content);
}
var INDEX_LIMIT_PER_SECTION = 50;
function buildVirtualIndexContent(summaryRows, sessionRows = [], opts = {}) {
  const lines = [
    "# Session Index",
    "",
    "Two sources are available. Consult the section relevant to the question.",
    ""
  ];
  lines.push("## memory", "");
  if (summaryRows.length === 0) {
    lines.push("_(empty \u2014 no summaries ingested yet)_");
  } else {
    lines.push("AI-generated summaries per session. Read these first for topic-level overviews.");
    lines.push("");
    if (opts.summaryTruncated) {
      lines.push(`_Showing ${INDEX_LIMIT_PER_SECTION} most-recent of many \u2014 older summaries reachable via \`Grep pattern="..." path="~/.deeplake/memory"\`._`);
      lines.push("");
    }
    lines.push("| Session | Created | Last Updated | Project | Description |");
    lines.push("|---------|---------|--------------|---------|-------------|");
    for (const row of summaryRows) {
      const p = row["path"] || "";
      const match = p.match(/\/summaries\/([^/]+)\/([^/]+)\.md$/);
      if (!match) continue;
      const summaryUser = match[1];
      const sessionId = match[2];
      const relPath = `summaries/${summaryUser}/${sessionId}.md`;
      const project = row["project"] || "";
      const description = row["description"] || "";
      const creationDate = row["creation_date"] || "";
      const lastUpdateDate = row["last_update_date"] || "";
      lines.push(`| [${sessionId}](${relPath}) | ${creationDate} | ${lastUpdateDate} | ${project} | ${description} |`);
    }
  }
  lines.push("");
  lines.push("## sessions", "");
  if (sessionRows.length === 0) {
    lines.push("_(empty \u2014 no session records ingested yet)_");
  } else {
    lines.push("Raw session records (dialogue, tool calls). Read for exact detail / quotes.");
    lines.push("");
    if (opts.sessionTruncated) {
      lines.push(`_Showing ${INDEX_LIMIT_PER_SECTION} most-recent of many \u2014 older sessions reachable via \`Grep pattern="..." path="~/.deeplake/memory"\`._`);
      lines.push("");
    }
    lines.push("| Session | Created | Last Updated | Description |");
    lines.push("|---------|---------|--------------|-------------|");
    for (const row of sessionRows) {
      const p = row["path"] || "";
      const rel = p.startsWith("/") ? p.slice(1) : p;
      const filename = p.split("/").pop() ?? p;
      const description = row["description"] || "";
      const creationDate = row["creation_date"] || "";
      const lastUpdateDate = row["last_update_date"] || "";
      lines.push(`| [${filename}](${rel}) | ${creationDate} | ${lastUpdateDate} | ${description} |`);
    }
  }
  lines.push("");
  return lines.join("\n");
}
function buildUnionQuery(memoryQuery, sessionsQuery) {
  return `SELECT path, content, size_bytes, creation_date, source_order FROM ((${memoryQuery}) UNION ALL (${sessionsQuery})) AS combined ORDER BY path, source_order, creation_date`;
}
function buildInList(paths) {
  return paths.map((path) => `'${sqlStr(path)}'`).join(", ");
}
async function queryUnionRows(api2, memoryQuery, sessionsQuery) {
  const unionQuery = buildUnionQuery(memoryQuery, sessionsQuery);
  try {
    return await api2.query(unionQuery);
  } catch {
    const [memoryRows, sessionRows] = await Promise.all([
      api2.query(memoryQuery).catch(() => []),
      api2.query(sessionsQuery).catch(() => [])
    ]);
    return [...memoryRows, ...sessionRows];
  }
}
async function readVirtualPathContents(api2, memoryTable2, sessionsTable2, virtualPaths) {
  const uniquePaths = [...new Set(virtualPaths)];
  const result = new Map(uniquePaths.map((path) => [path, null]));
  if (uniquePaths.length === 0) return result;
  const inList = buildInList(uniquePaths);
  const rows = await queryUnionRows(
    api2,
    `SELECT path, summary::text AS content, NULL::bigint AS size_bytes, '' AS creation_date, 0 AS source_order FROM "${memoryTable2}" WHERE path IN (${inList})`,
    `SELECT path, message::text AS content, NULL::bigint AS size_bytes, COALESCE(creation_date::text, '') AS creation_date, 1 AS source_order FROM "${sessionsTable2}" WHERE path IN (${inList})`
  );
  const memoryHits = /* @__PURE__ */ new Map();
  const sessionHits = /* @__PURE__ */ new Map();
  for (const row of rows) {
    const path = row["path"];
    const content = row["content"];
    const sourceOrder = Number(row["source_order"] ?? 0);
    if (typeof path !== "string" || typeof content !== "string") continue;
    if (sourceOrder === 0) {
      memoryHits.set(path, content);
    } else {
      const current = sessionHits.get(path) ?? [];
      current.push(normalizeSessionPart(path, content));
      sessionHits.set(path, current);
    }
  }
  for (const path of uniquePaths) {
    if (memoryHits.has(path)) {
      result.set(path, memoryHits.get(path) ?? null);
      continue;
    }
    const sessionParts = sessionHits.get(path) ?? [];
    if (sessionParts.length > 0) {
      result.set(path, sessionParts.join("\n"));
    }
  }
  if (result.get("/index.md") === null && uniquePaths.includes("/index.md")) {
    const fetchLimit = INDEX_LIMIT_PER_SECTION + 1;
    const [summaryRows, sessionRows] = await Promise.all([
      api2.query(
        `SELECT path, project, description, creation_date, last_update_date FROM "${memoryTable2}" WHERE path LIKE '/summaries/%' ORDER BY last_update_date DESC LIMIT ${fetchLimit}`
      ).catch(() => []),
      api2.query(
        `SELECT path, MAX(description) AS description, MIN(creation_date) AS creation_date, MAX(last_update_date) AS last_update_date FROM "${sessionsTable2}" WHERE path LIKE '/sessions/%' GROUP BY path ORDER BY MAX(last_update_date) DESC LIMIT ${fetchLimit}`
      ).catch(() => [])
    ]);
    const summaryTruncated = summaryRows.length > INDEX_LIMIT_PER_SECTION;
    const sessionTruncated = sessionRows.length > INDEX_LIMIT_PER_SECTION;
    result.set(
      "/index.md",
      buildVirtualIndexContent(
        summaryRows.slice(0, INDEX_LIMIT_PER_SECTION),
        sessionRows.slice(0, INDEX_LIMIT_PER_SECTION),
        { summaryTruncated, sessionTruncated }
      )
    );
  }
  return result;
}
async function readVirtualPathContent(api2, memoryTable2, sessionsTable2, virtualPath) {
  return (await readVirtualPathContents(api2, memoryTable2, sessionsTable2, [virtualPath])).get(virtualPath) ?? null;
}

// openclaw/src/index.ts
import { fileURLToPath } from "node:url";
import { join as joinPath, dirname as dirnamePath } from "node:path";
import { homedir as homedir2, tmpdir } from "node:os";
import {
  existsSync as fsExists,
  mkdirSync as fsMkdir,
  openSync as fsOpen,
  closeSync as fsClose,
  writeFileSync as fsWriteFile,
  constants as fsConstants
} from "node:fs";
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
function definePluginEntry(entry) {
  return entry;
}
function loadSetupConfig() {
  return import("./chunks/setup-config-C35UK4LP.js");
}
var credsModulePromise = null;
var configModulePromise = null;
function loadCredsModule() {
  if (!credsModulePromise) credsModulePromise = import("./chunks/auth-creds-AEKS6D3P.js");
  return credsModulePromise;
}
function loadConfigModule() {
  if (!configModulePromise) configModulePromise = import("./chunks/config-ZLH6JFJS.js");
  return configModulePromise;
}
async function loadCredentials2() {
  const m = await loadCredsModule();
  return m.loadCredentials();
}
async function saveCredentials2(creds) {
  if (!creds) return;
  const m = await loadCredsModule();
  m.saveCredentials(creds);
}
async function loadConfig() {
  const m = await loadConfigModule();
  return m.loadConfig();
}
var requireFromOpenclaw = createRequire(import.meta.url);
var { spawn: realSpawn, execFileSync: realExecFileSync } = requireFromOpenclaw("node:child_process");
var DEFAULT_API_URL2 = "https://api.deeplake.ai";
var VERSION_URL = "https://registry.npmjs.org/@deeplake/hivemind/latest";
function extractLatestVersion(body) {
  if (typeof body !== "object" || body === null) return null;
  const v = body.version;
  return typeof v === "string" && v.length > 0 ? v : null;
}
function getInstalledVersion() {
  return "0.7.13".length > 0 ? "0.7.13" : null;
}
function isNewer(latest, current) {
  const parse = (v) => v.replace(/-.*$/, "").split(".").map(Number);
  const [la, lb, lc] = parse(latest);
  const [ca, cb, cc] = parse(current);
  return la > ca || la === ca && lb > cb || la === ca && lb === cb && lc > cc;
}
async function checkForUpdate(logger) {
  try {
    const current = getInstalledVersion();
    if (!current) return;
    const res = await fetch(VERSION_URL, { signal: AbortSignal.timeout(5e3) });
    if (!res.ok) return;
    const latest = extractLatestVersion(await res.json());
    if (latest && isNewer(latest, current)) {
      pendingUpdate = { current, latest };
      logger.info?.(`\u2B06\uFE0F Hivemind update available: ${current} \u2192 ${latest}. Run: hivemind update`);
    }
  } catch (err) {
    logger.error(`Auto-update check failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}
var authPending = false;
var authUrl = null;
var pendingUpdate = null;
var justAuthenticated = false;
async function requestAuth() {
  if (authPending) return authUrl ?? "";
  authPending = true;
  try {
    const code = await requestDeviceCode();
    authUrl = code.verification_uri_complete;
    const pollMs = Math.max(code.interval || 5, 5) * 1e3;
    const deadline = Date.now() + code.expires_in * 1e3;
    (async () => {
      while (Date.now() < deadline && authPending) {
        await new Promise((r) => setTimeout(r, pollMs));
        try {
          const result = await pollForToken(code.device_code);
          if (result) {
            const token = result.access_token;
            let userName;
            try {
              const meResp = await fetch(`${DEFAULT_API_URL2}/me`, {
                headers: { Authorization: `Bearer ${token}` }
              });
              if (meResp.ok) {
                const me = await meResp.json();
                userName = me.name || (me.email ? me.email.split("@")[0] : void 0);
              }
            } catch {
            }
            const orgs = await listOrgs(token);
            const personal = orgs.find((o) => o.name.endsWith("'s Organization"));
            const org = personal ?? orgs[0];
            const orgId = org?.id ?? "";
            const orgName = org?.name ?? orgId;
            let savedToken = token;
            if (orgId) {
              try {
                const resp = await fetch(`${DEFAULT_API_URL2}/users/me/tokens`, {
                  method: "POST",
                  headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json",
                    "X-Activeloop-Org-Id": orgId,
                    ...deeplakeClientHeader()
                  },
                  body: JSON.stringify({ name: `hivemind-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`, duration: 365 * 24 * 60 * 60, organization_id: orgId })
                });
                if (resp.ok) {
                  const data = await resp.json();
                  savedToken = typeof data.token === "string" ? data.token : data.token.token;
                }
              } catch {
              }
            }
            await saveCredentials2({ token: savedToken, orgId, orgName, userName, apiUrl: DEFAULT_API_URL2, savedAt: (/* @__PURE__ */ new Date()).toISOString() });
            authPending = false;
            authUrl = null;
            justAuthenticated = true;
            return;
          }
        } catch {
        }
      }
      authPending = false;
      authUrl = null;
    })();
    return code.verification_uri_complete;
  } catch (err) {
    authPending = false;
    throw err;
  }
}
var api = null;
var sessionsTable = "sessions";
var memoryTable = "memory";
var skillsTable = "skills";
var captureEnabled = true;
var capturedCounts = /* @__PURE__ */ new Map();
var fallbackSessionId = crypto.randomUUID();
var __openclaw_filename = fileURLToPath(import.meta.url);
var __openclaw_dirname = dirnamePath(__openclaw_filename);
var OPENCLAW_SKILIFY_WORKER_PATH = joinPath(__openclaw_dirname, "skilify-worker.js");
var OPENCLAW_SKILIFY_STATE_DIR = joinPath(homedir2(), ".deeplake", "state", "skilify");
function deriveOpenclawProjectKey(channel) {
  const project = channel || "openclaw";
  const key = createHash("sha1").update(project).digest("hex").slice(0, 16);
  return { key, project };
}
function tryAcquireOpenclawSkilifyLock(projectKey) {
  try {
    fsMkdir(OPENCLAW_SKILIFY_STATE_DIR, { recursive: true });
    const lockPath = joinPath(OPENCLAW_SKILIFY_STATE_DIR, `${projectKey}.worker.lock`);
    const fd = fsOpen(lockPath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY);
    fsClose(fd);
    return true;
  } catch {
    return false;
  }
}
function detectOpenclawGateAgent() {
  const candidates = [
    ["claude_code", "claude"],
    ["codex", "codex"],
    ["cursor", "cursor-agent"],
    ["hermes", "hermes"],
    ["pi", "pi"]
  ];
  for (const [agent, bin] of candidates) {
    try {
      realExecFileSync("which", [bin], { stdio: ["ignore", "pipe", "ignore"] });
      return agent;
    } catch {
    }
  }
  return null;
}
function spawnOpenclawSkilifyWorker(a) {
  if (!fsExists(OPENCLAW_SKILIFY_WORKER_PATH)) {
    a.loggerWarn?.(`skilify worker missing at ${OPENCLAW_SKILIFY_WORKER_PATH} \u2014 reinstall openclaw plugin`);
    return;
  }
  const gateAgent = detectOpenclawGateAgent();
  if (!gateAgent) {
    a.loggerWarn?.(`skilify spawn: no delegate gate CLI found on PATH (need one of: claude, codex, cursor-agent, hermes, pi). Mining skipped.`);
    return;
  }
  const { key: projectKey, project } = deriveOpenclawProjectKey(a.channel);
  if (!tryAcquireOpenclawSkilifyLock(projectKey)) {
    return;
  }
  const tmpDir = joinPath(tmpdir(), `deeplake-skilify-openclaw-${projectKey}-${Date.now()}`);
  try {
    fsMkdir(tmpDir, { recursive: true, mode: 448 });
  } catch (e) {
    a.loggerWarn?.(`skilify spawn: mkdir failed: ${e?.message ?? e}`);
    return;
  }
  const configPath = joinPath(tmpDir, "config.json");
  const config = {
    apiUrl: a.apiUrl,
    token: a.token,
    orgId: a.orgId,
    workspaceId: a.workspaceId,
    sessionsTable,
    skillsTable,
    userName: a.userName,
    cwd: homedir2(),
    // sentinel — only used by worker if install=project
    projectKey,
    project,
    agent: "openclaw",
    gateAgent,
    // delegate CLI for the worker's gate call (openclaw has no CLI of its own)
    scope: "me",
    team: [],
    install: "global",
    tmpDir,
    gateBin: null,
    // worker uses gateAgent to look up the binary itself
    cursorModel: void 0,
    hermesProvider: void 0,
    hermesModel: void 0,
    skilifyLog: joinPath(homedir2(), ".deeplake", "hivemind-openclaw-skilify.log"),
    currentSessionId: a.sessionId
  };
  try {
    fsWriteFile(configPath, JSON.stringify(config), { mode: 384 });
  } catch (e) {
    a.loggerWarn?.(`skilify spawn: config write failed: ${e?.message ?? e}`);
    return;
  }
  try {
    realSpawn(process.execPath, [OPENCLAW_SKILIFY_WORKER_PATH, configPath], {
      detached: true,
      stdio: "ignore",
      env: { ...process.env, HIVEMIND_SKILIFY_WORKER: "1", HIVEMIND_CAPTURE: "false" }
    }).unref();
  } catch (e) {
    a.loggerWarn?.(`skilify spawn: spawn failed: ${e?.message ?? e}`);
  }
}
function buildSessionPath(config, sessionId) {
  return `/sessions/${config.userName}/${config.userName}_${config.orgName}_${config.workspaceId}_${sessionId}.jsonl`;
}
var RECALL_STOPWORDS = /* @__PURE__ */ new Set([
  "the",
  "and",
  "for",
  "are",
  "but",
  "not",
  "you",
  "all",
  "can",
  "had",
  "her",
  "was",
  "one",
  "our",
  "out",
  "has",
  "have",
  "what",
  "does",
  "like",
  "with",
  "this",
  "that",
  "from",
  "they",
  "been",
  "will",
  "more",
  "when",
  "who",
  "how",
  "its",
  "into",
  "some",
  "than",
  "them",
  "these",
  "then",
  "your",
  "just",
  "about",
  "would",
  "could",
  "should",
  "where",
  "which",
  "there",
  "their",
  "being",
  "each",
  "other"
]);
function extractKeywords(prompt) {
  return prompt.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((w) => w.length >= 3 && !RECALL_STOPWORDS.has(w)).slice(0, 4);
}
function normalizeVirtualPath(p) {
  if (!p || typeof p !== "string") return "/";
  const trimmed = p.trim();
  if (!trimmed || trimmed === "/") return "/";
  return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
}
async function getApi() {
  if (api) return api;
  const config = await loadConfig();
  if (!config) {
    if (!authPending) await requestAuth();
    return null;
  }
  sessionsTable = config.sessionsTableName;
  memoryTable = config.tableName;
  skillsTable = config.skillsTableName;
  const candidate = new DeeplakeApi(config.token, config.apiUrl, config.orgId, config.workspaceId, config.tableName);
  await candidate.ensureTable();
  await candidate.ensureSessionsTable(sessionsTable);
  api = candidate;
  return api;
}
var src_default = definePluginEntry({
  id: "hivemind",
  name: "Hivemind",
  description: "Cloud-backed shared memory powered by Deeplake",
  register(pluginApi) {
    void (async () => {
      try {
        pluginApi.registerCommand({
          name: "hivemind_login",
          description: "Log in to Hivemind (or switch accounts)",
          handler: async () => {
            const existing = await loadCredentials2();
            const url = await requestAuth();
            if (existing?.token) {
              return {
                text: `\u2139\uFE0F Currently logged in as ${existing.orgName ?? existing.orgId}.

To re-authenticate or switch accounts:

${url}

After signing in, send another message.`
              };
            }
            return { text: `\u{1F510} Sign in to activate Hivemind memory:

${url}

After signing in, send another message.` };
          }
        });
        pluginApi.registerCommand({
          name: "hivemind_capture",
          description: "Toggle conversation capture on/off",
          handler: async () => {
            captureEnabled = !captureEnabled;
            return { text: captureEnabled ? "\u2705 Capture enabled \u2014 conversations will be stored to Hivemind." : "\u23F8\uFE0F Capture paused \u2014 conversations will NOT be stored until you run /hivemind_capture again." };
          }
        });
        pluginApi.registerCommand({
          name: "hivemind_whoami",
          description: "Show current Hivemind org and workspace",
          handler: async () => {
            const creds2 = await loadCredentials2();
            if (!creds2?.token) return { text: "Not logged in. Run /hivemind_login" };
            return { text: `Org: ${creds2.orgName ?? creds2.orgId}
Workspace: ${creds2.workspaceId ?? "default"}` };
          }
        });
        pluginApi.registerCommand({
          name: "hivemind_orgs",
          description: "List available organizations",
          handler: async () => {
            const creds2 = await loadCredentials2();
            if (!creds2?.token) return { text: "Not logged in. Run /hivemind_login" };
            const orgs = await listOrgs(creds2.token, creds2.apiUrl);
            if (!orgs.length) return { text: "No organizations found." };
            const lines = orgs.map((o) => `${o.id === creds2.orgId ? "\u2192 " : "  "}${o.name}`);
            return { text: lines.join("\n") };
          }
        });
        pluginApi.registerCommand({
          name: "hivemind_switch_org",
          description: "Switch to a different organization",
          acceptsArgs: true,
          handler: async (ctx) => {
            const creds2 = await loadCredentials2();
            if (!creds2?.token) return { text: "Not logged in. Run /hivemind_login" };
            const target = ctx.args?.trim();
            if (!target) return { text: "Usage: /hivemind_switch_org <name-or-id>" };
            const orgs = await listOrgs(creds2.token, creds2.apiUrl);
            const lc = target.toLowerCase();
            const match = orgs.find((o) => o.id === target || o.name.toLowerCase() === lc) ?? orgs.find((o) => o.name.toLowerCase().includes(lc) || o.id.toLowerCase().includes(lc));
            if (!match) {
              const available = orgs.length ? orgs.map((o) => `  - ${o.name} (id: ${o.id})`).join("\n") : "  (none \u2014 your current token has no organization access)";
              return { text: `Org not found: ${target}

Available:
${available}` };
            }
            await switchOrg(match.id, match.name);
            api = null;
            return { text: `Switched to org: ${match.name}` };
          }
        });
        pluginApi.registerCommand({
          name: "hivemind_workspaces",
          description: "List available workspaces",
          handler: async () => {
            const creds2 = await loadCredentials2();
            if (!creds2?.token) return { text: "Not logged in. Run /hivemind_login" };
            const ws = await listWorkspaces(creds2.token, creds2.apiUrl, creds2.orgId);
            if (!ws.length) return { text: "No workspaces found." };
            const lines = ws.map((w) => `${w.id === (creds2.workspaceId ?? "default") ? "\u2192 " : "  "}${w.name}`);
            return { text: lines.join("\n") };
          }
        });
        pluginApi.registerCommand({
          name: "hivemind_switch_workspace",
          description: "Switch to a different workspace",
          acceptsArgs: true,
          handler: async (ctx) => {
            const creds2 = await loadCredentials2();
            if (!creds2?.token) return { text: "Not logged in. Run /hivemind_login" };
            const target = ctx.args?.trim();
            if (!target) return { text: "Usage: /hivemind_switch_workspace <name-or-id>" };
            const ws = await listWorkspaces(creds2.token, creds2.apiUrl, creds2.orgId);
            const lc = target.toLowerCase();
            const match = ws.find((w) => w.id === target || w.name.toLowerCase() === lc) ?? ws.find((w) => w.name.toLowerCase().includes(lc) || w.id.toLowerCase().includes(lc));
            if (!match) {
              const available = ws.length ? ws.map((w) => `  - ${w.name} (id: ${w.id})`).join("\n") : "  (none in current org \u2014 try /hivemind_switch_org first)";
              return { text: `Workspace not found: ${target}

Available:
${available}` };
            }
            await switchWorkspace(match.id);
            api = null;
            return { text: `Switched to workspace: ${match.name}` };
          }
        });
        pluginApi.registerCommand({
          name: "hivemind_setup",
          description: "Add Hivemind tools to your openclaw allowlist (needed once per install)",
          handler: async () => {
            const { ensureHivemindAllowlisted } = await loadSetupConfig();
            const result = ensureHivemindAllowlisted();
            const skilifyHint = `

Skill mining (skilify) runs in the background after each turn \u2014 your conversations get crystallised into reusable skills automatically. From your terminal:
  hivemind skilify status   \u2014 see what's been mined
  hivemind skilify pull     \u2014 fetch teammates' skills`;
            if (result.status === "already-set") {
              return { text: `\u2705 Hivemind tools are already enabled in your allowlist.

No changes needed \u2014 memory tools are available to the agent.${skilifyHint}` };
            }
            if (result.status === "added") {
              return { text: `\u2705 Added "hivemind" to your tool allowlist.

Openclaw will detect the config change and restart. On the next turn, the agent will have access to hivemind_search, hivemind_read, and hivemind_index.

Backup of previous config: ${result.backupPath}${skilifyHint}` };
            }
            return { text: `\u26A0\uFE0F Could not update allowlist: ${result.error}

Manual fix: open ${result.configPath} and add "hivemind" to the "alsoAllow" array under "tools".` };
          }
        });
        pluginApi.registerCommand({
          name: "hivemind_version",
          description: "Show the installed Hivemind version and check for updates",
          handler: async () => {
            const current = getInstalledVersion();
            if (!current) return { text: "Could not determine installed version." };
            try {
              const res = await fetch(VERSION_URL, { signal: AbortSignal.timeout(3e3) });
              if (!res.ok) return { text: `Current version: ${current}. Could not check for updates.` };
              const latest = extractLatestVersion(await res.json());
              if (!latest) return { text: `Current version: ${current}. Could not parse latest version.` };
              if (isNewer(latest, current)) {
                return { text: `\u2B06\uFE0F Update available: ${current} \u2192 ${latest}

Run /hivemind_update to install it now.` };
              }
              return { text: `\u2705 Hivemind v${current} is up to date.` };
            } catch {
              return { text: `Current version: ${current}. Could not check for updates.` };
            }
          }
        });
        pluginApi.registerCommand({
          name: "hivemind_update",
          description: "Install the latest Hivemind version from npm",
          handler: async () => {
            const current = getInstalledVersion() ?? "unknown";
            return {
              text: `Hivemind v${current} installed. To install the latest:

\u2022 Ask me in chat: "update hivemind" \u2014 I'll run \`hivemind update\` via my exec tool.
\u2022 Or run in your terminal: \`hivemind update\`

The gateway restarts automatically once the install completes.`
            };
          }
        });
        pluginApi.registerCommand({
          name: "hivemind_autoupdate",
          description: "Toggle Hivemind auto-update on/off",
          acceptsArgs: true,
          handler: async (ctx) => {
            const arg = ctx.args?.trim().toLowerCase();
            let setTo;
            if (arg === "on" || arg === "true" || arg === "enable") setTo = true;
            else if (arg === "off" || arg === "false" || arg === "disable") setTo = false;
            const { toggleAutoUpdateConfig } = await loadSetupConfig();
            const result = toggleAutoUpdateConfig(setTo);
            if (result.status === "error") {
              return { text: `\u26A0\uFE0F Could not update auto-update setting: ${result.error}` };
            }
            return {
              text: result.newValue ? "\u2705 Auto-update is ON. Hivemind will install new versions automatically when the gateway starts." : "\u23F8\uFE0F Auto-update is OFF. Run /hivemind_update manually to install new versions."
            };
          }
        });
        pluginApi.registerTool({
          name: "hivemind_search",
          label: "Hivemind Search",
          description: "Search Hivemind shared memory (summaries + past session turns) for keywords, phrases, or regex. Returns matching path + snippet pairs from BOTH the memory and sessions tables. Use this FIRST when the user asks about past work, decisions, people, or anything that might live in memory.",
          parameters: {
            type: "object",
            additionalProperties: false,
            properties: {
              query: {
                type: "string",
                minLength: 1,
                description: "Search text. Treated as a literal substring by default; set `regex: true` to use regex metacharacters."
              },
              path: {
                type: "string",
                description: "Optional virtual path prefix to scope the search, e.g. '/summaries/' or '/sessions/alice/'. Defaults to '/' (all of memory)."
              },
              regex: {
                type: "boolean",
                description: "If true, `query` is interpreted as a regex. Default false (literal substring)."
              },
              ignoreCase: {
                type: "boolean",
                description: "Case-insensitive match. Default true."
              },
              limit: {
                type: "integer",
                minimum: 1,
                maximum: 100,
                description: "Max rows returned per table. Default 20."
              }
            },
            required: ["query"]
          },
          execute: async (_toolCallId, rawParams) => {
            const params = rawParams;
            const dl = await getApi();
            if (!dl) {
              return {
                content: [{ type: "text", text: "Not logged in. Run /hivemind_login first." }]
              };
            }
            const targetPath = normalizeVirtualPath(params.path);
            const grepParams = {
              pattern: params.query,
              ignoreCase: params.ignoreCase !== false,
              wordMatch: false,
              filesOnly: false,
              countOnly: false,
              lineNumber: false,
              invertMatch: false,
              fixedString: params.regex !== true
            };
            const searchOpts = buildGrepSearchOptions(grepParams, targetPath);
            searchOpts.limit = Math.min(Math.max(params.limit ?? 20, 1), 100);
            const t0 = Date.now();
            try {
              const rawRows = await searchDeeplakeTables(dl, memoryTable, sessionsTable, searchOpts);
              const matchedRows = searchOpts.contentScanOnly ? (() => {
                const re = compileGrepRegex(grepParams);
                return rawRows.filter((r) => re.test(normalizeContent(r.path, r.content)));
              })() : rawRows;
              pluginApi.logger.info?.(`hivemind_search "${params.query.slice(0, 60)}" \u2192 ${matchedRows.length}/${rawRows.length} hits in ${Date.now() - t0}ms`);
              if (matchedRows.length === 0) {
                return { content: [{ type: "text", text: `No memory matches for "${params.query}" under ${targetPath}.` }] };
              }
              const text = matchedRows.map((r, i) => {
                const body = normalizeContent(r.path, r.content);
                return `${i + 1}. ${r.path}
${body.slice(0, 500)}`;
              }).join("\n\n");
              return { content: [{ type: "text", text }], details: { hits: matchedRows.length, path: targetPath } };
            } catch (err) {
              const msg = err instanceof Error ? err.message : String(err);
              pluginApi.logger.error(`hivemind_search failed: ${msg}`);
              return { content: [{ type: "text", text: `Search failed: ${msg}` }] };
            }
          }
        });
        pluginApi.registerTool({
          name: "hivemind_read",
          label: "Hivemind Read",
          description: "Read the full content of a specific Hivemind memory path (e.g. '/summaries/alice/abc.md' or '/sessions/alice/alice_org_ws_xyz.jsonl' or '/index.md'). Use this after hivemind_search to drill into a hit, or after hivemind_index to fetch a specific session.",
          parameters: {
            type: "object",
            additionalProperties: false,
            properties: {
              path: {
                type: "string",
                minLength: 1,
                description: "Virtual path under /summaries/, /sessions/, or '/index.md' for the memory index."
              }
            },
            required: ["path"]
          },
          execute: async (_toolCallId, rawParams) => {
            const params = rawParams;
            const dl = await getApi();
            if (!dl) {
              return { content: [{ type: "text", text: "Not logged in. Run /hivemind_login first." }] };
            }
            const virtualPath = normalizeVirtualPath(params.path);
            try {
              const content = await readVirtualPathContent(dl, memoryTable, sessionsTable, virtualPath);
              if (content === null) {
                return { content: [{ type: "text", text: `No content at ${virtualPath}.` }] };
              }
              return { content: [{ type: "text", text: content }], details: { path: virtualPath } };
            } catch (err) {
              const msg = err instanceof Error ? err.message : String(err);
              pluginApi.logger.error(`hivemind_read failed: ${msg}`);
              return { content: [{ type: "text", text: `Read failed: ${msg}` }] };
            }
          }
        });
        pluginApi.registerTool({
          name: "hivemind_index",
          label: "Hivemind Index",
          description: "List every summary and session available in Hivemind (with paths, dates, descriptions). Use this when the user asks 'what's in memory?' or you don't know where to start looking.",
          parameters: {
            type: "object",
            additionalProperties: false,
            properties: {}
          },
          execute: async () => {
            const dl = await getApi();
            if (!dl) {
              return { content: [{ type: "text", text: "Not logged in. Run /hivemind_login first." }] };
            }
            try {
              const text = await readVirtualPathContent(dl, memoryTable, sessionsTable, "/index.md");
              return { content: [{ type: "text", text: text ?? "(memory is empty)" }] };
            } catch (err) {
              const msg = err instanceof Error ? err.message : String(err);
              pluginApi.logger.error(`hivemind_index failed: ${msg}`);
              return { content: [{ type: "text", text: `Index build failed: ${msg}` }] };
            }
          }
        });
        pluginApi.registerMemoryCorpusSupplement({
          search: async ({ query, maxResults }) => {
            const dl = await getApi();
            if (!dl) return [];
            const grepParams = {
              pattern: query,
              ignoreCase: true,
              wordMatch: false,
              filesOnly: false,
              countOnly: false,
              lineNumber: false,
              invertMatch: false,
              fixedString: true
            };
            const searchOpts = buildGrepSearchOptions(grepParams, "/");
            searchOpts.limit = Math.min(Math.max(maxResults ?? 10, 1), 50);
            try {
              const rows = await searchDeeplakeTables(dl, memoryTable, sessionsTable, searchOpts);
              return rows.map((r, i) => ({
                path: r.path,
                snippet: normalizeContent(r.path, r.content).slice(0, 400),
                corpus: "hivemind",
                kind: r.path.startsWith("/summaries/") ? "summary" : "session",
                score: r.path.startsWith("/summaries/") ? 0.8 - i * 5e-3 : 0.6 - i * 5e-3
              }));
            } catch {
              return [];
            }
          },
          get: async ({ lookup }) => {
            const dl = await getApi();
            if (!dl) return null;
            try {
              const content = await readVirtualPathContent(dl, memoryTable, sessionsTable, normalizeVirtualPath(lookup));
              return content === null ? null : { path: lookup, content };
            } catch {
              return null;
            }
          }
        });
        const config = pluginApi.pluginConfig ?? {};
        const logger = pluginApi.logger;
        const hook = (event, handler) => {
          pluginApi.on(event, handler);
        };
        if ('---\nname: hivemind\ndescription: Global team and org memory powered by Activeloop. ALWAYS check BOTH built-in memory AND Hivemind memory when recalling information.\nallowed-tools: hivemind_search, hivemind_read, hivemind_index\n---\n\n# Hivemind Memory\n\nYou have TWO memory sources. ALWAYS check BOTH when the user asks you to recall, remember, or look up ANY information:\n\n1. **Your built-in memory** \u2014 personal per-project notes from the host agent\n2. **Hivemind global memory** \u2014 global memory shared across all sessions, users, and agents in the org, accessed via the tools below\n\n## Memory Structure\n\n```\n/index.md                           \u2190 START HERE \u2014 table of all sessions\n/summaries/\n  <username>/\n    <session-id>.md                 \u2190 AI-generated wiki summary per session\n/sessions/\n  <username>/\n    <user_org_ws_slug>.jsonl        \u2190 raw session data\n```\n\n## How to Search\n\n1. **First**: call `hivemind_index()` \u2014 table of all sessions with dates, projects, descriptions\n2. **If you need details**: call `hivemind_read("/summaries/<username>/<session>.md")`\n3. **If you need raw data**: call `hivemind_read("/sessions/<username>/<file>.jsonl")`\n4. **Keyword search**: call `hivemind_search("keyword")` \u2014 substring search across both summaries and sessions, returns `path:line` hits\n\nDo NOT jump straight to reading raw JSONL files. Always start with `hivemind_index` and summaries.\n\n## Organization Management\n\n- `/hivemind_login` \u2014 sign in via device flow\n- `/hivemind_capture` \u2014 toggle capture on/off (off = no data sent)\n- `/hivemind_whoami` \u2014 show current org and workspace\n- `/hivemind_orgs` \u2014 list organizations\n- `/hivemind_switch_org <name-or-id>` \u2014 switch organization\n- `/hivemind_workspaces` \u2014 list workspaces\n- `/hivemind_switch_workspace <id>` \u2014 switch workspace\n- `/hivemind_version` \u2014 show installed version and check npm for updates\n- `/hivemind_update` \u2014 shows how to install (ask the agent, or run `hivemind update` in your terminal)\n- `/hivemind_autoupdate [on|off]` \u2014 toggle the agent-facing update nudge (on by default: when a newer version is available, the agent is prompted to install it via `exec` if you ask to update)\n\n## Skill Management (skilify)\n\nHivemind also mines reusable Claude skills from agent sessions and stores them in a per-org Deeplake table. Openclaw itself doesn\'t run sessions to mine, but you can pull skills others have already mined for the user. These run in the user\'s terminal (the openclaw plugin does not register them as `/hivemind_*` commands):\n\n- `hivemind skilify` \u2014 show scope/team/install + per-project state\n- `hivemind skilify pull` \u2014 sync skills for the current project from the org table\n- `hivemind skilify pull --user <email>` \u2014 only that author\'s skills\n- `hivemind skilify pull --users a,b,c` \u2014 multiple authors (CSV)\n- `hivemind skilify pull --all-users` \u2014 explicit "no author filter"\n- `hivemind skilify pull --to project|global` \u2014 install location (`<cwd>/.claude/skills/` vs `~/.claude/skills/`)\n- `hivemind skilify pull --dry-run` \u2014 preview without touching disk\n- `hivemind skilify pull --force` \u2014 overwrite local (creates `.bak`)\n- `hivemind skilify pull <skill-name>` \u2014 pull only that one skill (combines with `--user`)\n- `hivemind skilify scope <me|team|org>` \u2014 set sharing scope for new skills\n- `hivemind skilify install <project|global>` \u2014 default install location\n- `hivemind skilify team add|remove|list <name>` \u2014 manage team list\n\nIf the user asks to "pull skills from X", "share skills with the team", or similar, suggest the matching `hivemind skilify` command. Run `hivemind skilify --help` for the full reference.\n\n## Limits\n\nDo NOT delegate to subagents when reading Hivemind memory. If a tool call returns empty after 2 attempts, skip it and move on. Report what you found rather than exhaustively retrying.\n\n## Getting Started\n\nAfter installing the plugin:\n1. Run `/hivemind_login` to authenticate\n2. Run `/hivemind_setup` to enable the memory tools in your openclaw allowlist (one-time, per install)\n3. Start using memory \u2014 ask questions, the agent automatically captures and searches\n\n## Sharing memory\n\nMultiple agents share memory when users are in the same Activeloop organization.\n'.length > 0) {
          const setupConfigPromise = loadSetupConfig();
          hook("before_prompt_build", async () => {
            const { detectAllowlistMissing } = await setupConfigPromise;
            const allowlistNudge = detectAllowlistMissing() ? "\n\n<hivemind-setup-needed>\nThe user hasn't run /hivemind_setup yet, so hivemind_search, hivemind_read, and hivemind_index are NOT available to you. If they ask about memory and you can't help, tell them to run /hivemind_setup to enable Hivemind memory tools.\n</hivemind-setup-needed>\n" : "";
            const updateNudge = pendingUpdate ? `

<hivemind-update-available>
A newer Hivemind version is available: ${pendingUpdate.current} \u2192 ${pendingUpdate.latest}. Install command: \`hivemind update\`. The gateway reloads the plugin after install.
</hivemind-update-available>
` : "";
            return {
              prependSystemContext: allowlistNudge + updateNudge + '\n\n<hivemind-skill>\n---\nname: hivemind\ndescription: Global team and org memory powered by Activeloop. ALWAYS check BOTH built-in memory AND Hivemind memory when recalling information.\nallowed-tools: hivemind_search, hivemind_read, hivemind_index\n---\n\n# Hivemind Memory\n\nYou have TWO memory sources. ALWAYS check BOTH when the user asks you to recall, remember, or look up ANY information:\n\n1. **Your built-in memory** \u2014 personal per-project notes from the host agent\n2. **Hivemind global memory** \u2014 global memory shared across all sessions, users, and agents in the org, accessed via the tools below\n\n## Memory Structure\n\n```\n/index.md                           \u2190 START HERE \u2014 table of all sessions\n/summaries/\n  <username>/\n    <session-id>.md                 \u2190 AI-generated wiki summary per session\n/sessions/\n  <username>/\n    <user_org_ws_slug>.jsonl        \u2190 raw session data\n```\n\n## How to Search\n\n1. **First**: call `hivemind_index()` \u2014 table of all sessions with dates, projects, descriptions\n2. **If you need details**: call `hivemind_read("/summaries/<username>/<session>.md")`\n3. **If you need raw data**: call `hivemind_read("/sessions/<username>/<file>.jsonl")`\n4. **Keyword search**: call `hivemind_search("keyword")` \u2014 substring search across both summaries and sessions, returns `path:line` hits\n\nDo NOT jump straight to reading raw JSONL files. Always start with `hivemind_index` and summaries.\n\n## Organization Management\n\n- `/hivemind_login` \u2014 sign in via device flow\n- `/hivemind_capture` \u2014 toggle capture on/off (off = no data sent)\n- `/hivemind_whoami` \u2014 show current org and workspace\n- `/hivemind_orgs` \u2014 list organizations\n- `/hivemind_switch_org <name-or-id>` \u2014 switch organization\n- `/hivemind_workspaces` \u2014 list workspaces\n- `/hivemind_switch_workspace <id>` \u2014 switch workspace\n- `/hivemind_version` \u2014 show installed version and check npm for updates\n- `/hivemind_update` \u2014 shows how to install (ask the agent, or run `hivemind update` in your terminal)\n- `/hivemind_autoupdate [on|off]` \u2014 toggle the agent-facing update nudge (on by default: when a newer version is available, the agent is prompted to install it via `exec` if you ask to update)\n\n## Skill Management (skilify)\n\nHivemind also mines reusable Claude skills from agent sessions and stores them in a per-org Deeplake table. Openclaw itself doesn\'t run sessions to mine, but you can pull skills others have already mined for the user. These run in the user\'s terminal (the openclaw plugin does not register them as `/hivemind_*` commands):\n\n- `hivemind skilify` \u2014 show scope/team/install + per-project state\n- `hivemind skilify pull` \u2014 sync skills for the current project from the org table\n- `hivemind skilify pull --user <email>` \u2014 only that author\'s skills\n- `hivemind skilify pull --users a,b,c` \u2014 multiple authors (CSV)\n- `hivemind skilify pull --all-users` \u2014 explicit "no author filter"\n- `hivemind skilify pull --to project|global` \u2014 install location (`<cwd>/.claude/skills/` vs `~/.claude/skills/`)\n- `hivemind skilify pull --dry-run` \u2014 preview without touching disk\n- `hivemind skilify pull --force` \u2014 overwrite local (creates `.bak`)\n- `hivemind skilify pull <skill-name>` \u2014 pull only that one skill (combines with `--user`)\n- `hivemind skilify scope <me|team|org>` \u2014 set sharing scope for new skills\n- `hivemind skilify install <project|global>` \u2014 default install location\n- `hivemind skilify team add|remove|list <name>` \u2014 manage team list\n\nIf the user asks to "pull skills from X", "share skills with the team", or similar, suggest the matching `hivemind skilify` command. Run `hivemind skilify --help` for the full reference.\n\n## Limits\n\nDo NOT delegate to subagents when reading Hivemind memory. If a tool call returns empty after 2 attempts, skip it and move on. Report what you found rather than exhaustively retrying.\n\n## Getting Started\n\nAfter installing the plugin:\n1. Run `/hivemind_login` to authenticate\n2. Run `/hivemind_setup` to enable the memory tools in your openclaw allowlist (one-time, per install)\n3. Start using memory \u2014 ask questions, the agent automatically captures and searches\n\n## Sharing memory\n\nMultiple agents share memory when users are in the same Activeloop organization.\n\n</hivemind-skill>\n'
            };
          });
        }
        if (config.autoRecall !== false) {
          hook("before_agent_start", async (event) => {
            if (!event.prompt || event.prompt.length < 5) return;
            try {
              const dl = await getApi();
              if (!dl && authUrl) {
                return {
                  prependContext: `

IMPORTANT: The user needs to authenticate with Hivemind. Include this link in your reply: ${authUrl}
Tell them to click it and sign in, then send another message.
`
                };
              }
              if (!dl) return;
              if (justAuthenticated) {
                justAuthenticated = false;
                const creds2 = await loadCredentials2();
                const orgName = creds2?.orgName ?? creds2?.orgId ?? "unknown";
                return { prependContext: `

\u{1F41D} Welcome to Hivemind!

Current org: ${orgName}

Your agents now share memory across sessions, teammates, and machines.

Get started:
1. Verify sync: spin up multiple sessions and confirm agents share context
2. Invite a teammate: ask the agent to add them over email
3. Switch orgs: ask the agent to list or switch your organizations

One brain for every agent on your team.
` };
              }
              const keywords = extractKeywords(event.prompt);
              if (!keywords.length) return;
              const grepParams = {
                pattern: keywords.join(" "),
                ignoreCase: true,
                wordMatch: false,
                filesOnly: false,
                countOnly: false,
                lineNumber: false,
                invertMatch: false,
                fixedString: true
              };
              const searchOpts = buildGrepSearchOptions(grepParams, "/");
              searchOpts.limit = 10;
              const rows = await searchDeeplakeTables(dl, memoryTable, sessionsTable, searchOpts);
              if (!rows.length) return;
              const recalled = rows.map((r) => {
                const body = normalizeContent(r.path, r.content);
                return `[${r.path}] ${body.slice(0, 400)}`;
              }).join("\n\n");
              logger.info?.(`Auto-recalled ${rows.length} memories`);
              const instruction = "These are raw Hivemind search hits from prior sessions. Each hit is prefixed with its path (e.g. `/summaries/<username>/...`). Different usernames are different people \u2014 do NOT merge, alias, or conflate them. If you need more detail, call `hivemind_search` with a more specific query or `hivemind_read` on a specific path. If these hits don't answer the question, say so rather than guessing.";
              return {
                prependContext: "\n\n<recalled-memories>\n" + instruction + "\n\n" + recalled + "\n</recalled-memories>\n"
              };
            } catch (err) {
              logger.error(`Auto-recall failed: ${err instanceof Error ? err.message : String(err)}`);
            }
          });
        }
        if (config.autoCapture !== false) {
          hook("agent_end", async (event) => {
            const ev = event;
            if (!captureEnabled || !ev.success || !ev.messages?.length) return;
            try {
              const dl = await getApi();
              if (!dl) return;
              const cfg = await loadConfig();
              if (!cfg) return;
              const sid = ev.session_id || fallbackSessionId;
              const lastCount = capturedCounts.get(sid) ?? 0;
              const newMessages = ev.messages.slice(lastCount);
              capturedCounts.set(sid, ev.messages.length);
              if (!newMessages.length) return;
              const sessionPath = buildSessionPath(cfg, sid);
              const filename = sessionPath.split("/").pop() ?? "";
              const projectName = ev.channel || "openclaw";
              for (const msg of newMessages) {
                if (msg.role !== "user" && msg.role !== "assistant") continue;
                let text = "";
                if (typeof msg.content === "string") {
                  text = msg.content;
                } else if (Array.isArray(msg.content)) {
                  text = msg.content.filter((b) => b.type === "text" && b.text).map((b) => b.text).join("\n");
                }
                if (!text.trim()) continue;
                const ts = (/* @__PURE__ */ new Date()).toISOString();
                const entry = {
                  id: crypto.randomUUID(),
                  type: msg.role === "user" ? "user_message" : "assistant_message",
                  session_id: sid,
                  content: text,
                  timestamp: ts
                };
                const line = JSON.stringify(entry);
                const jsonForSql = line.replace(/'/g, "''");
                const insertSql = `INSERT INTO "${sessionsTable}" (id, path, filename, message, author, size_bytes, project, description, agent, creation_date, last_update_date) VALUES ('${crypto.randomUUID()}', '${sqlStr(sessionPath)}', '${sqlStr(filename)}', '${jsonForSql}'::jsonb, '${sqlStr(cfg.userName)}', ${Buffer.byteLength(line, "utf-8")}, '${sqlStr(projectName)}', '${sqlStr(msg.role)}', 'openclaw', '${ts}', '${ts}')`;
                try {
                  await dl.query(insertSql);
                } catch (e) {
                  if (e.message?.includes("permission denied") || e.message?.includes("does not exist")) {
                    await dl.ensureSessionsTable(sessionsTable);
                    await dl.query(insertSql);
                  } else {
                    throw e;
                  }
                }
              }
              logger.info?.(`Auto-captured ${newMessages.length} messages`);
              try {
                spawnOpenclawSkilifyWorker({
                  apiUrl: cfg.apiUrl,
                  token: cfg.token,
                  orgId: cfg.orgId,
                  workspaceId: cfg.workspaceId,
                  userName: cfg.userName,
                  channel: ev.channel || "openclaw",
                  sessionId: sid,
                  loggerWarn: (msg) => logger.error(`Skilify spawn: ${msg}`)
                });
              } catch (e) {
                logger.error(`Skilify spawn threw: ${e?.message ?? e}`);
              }
            } catch (err) {
              logger.error(`Auto-capture failed: ${err instanceof Error ? err.message : String(err)}`);
            }
          });
        }
        const creds = await loadCredentials2();
        if (!creds?.token) {
          logger.info?.("Hivemind installed. Run /hivemind_login to authenticate and activate shared memory.");
          if (!authPending) {
            requestAuth().catch((err) => {
              logger.error(`Pre-auth failed: ${err instanceof Error ? err.message : String(err)}`);
            });
          }
        }
        if (config.autoUpdate !== false) {
          checkForUpdate(logger).catch(() => {
          });
        }
        logger.info?.("Hivemind plugin registered");
      } catch (err) {
        pluginApi.logger?.error?.(`Hivemind register failed: ${err instanceof Error ? err.message : String(err)}`);
      }
    })();
  }
});
export {
  src_default as default
};
