// ─────────────────────────────────────────────────────────────────────────────
// AGENTS.md allow-list entry: the subcommand handlers below are lazy-loaded
// via `await import("./commands/...")` rather than static imports. See the
// AGENTS.md allow-list (Agent Rules → "No new dynamic imports outside the
// documented allow-list") for the documented exceptions and rationale —
// sibling entries cover the connector / apply / browser-auth codepaths and
// test files. This comment only documents the specific reason this file
// qualifies.
//
// Why: the CLI's command graph pulls in `postgres`, `playwright`, every
// `@chat-adapter/*`, the bundled server, etc. Measured boot times on a 2026
// macOS host:
//
//   lazy (current)   `lobu --help` / `--version` : ~60ms
//   static import    same invocations           : ~470-540ms (8x slower)
//
// `lobu --help` runs every time a user TAB-completes or pokes the CLI; the
// 400ms penalty is paid on every shell hit even when the user never runs the
// subcommand whose module would have been loaded. Dynamic import keeps the
// hot path (commander parses argv, prints help) free of any module the user
// didn't actually invoke. The measurement was redone after the round-2 audit
// (REPORT.md → "CLI dynamic-imports rule conflict") so future contributors
// have a fresh data point before re-litigating the rule.
//
// Rules for adding a new subcommand:
//   1. Put the handler in `./commands/<name>.ts`.
//   2. Register it with `.command(...).action(async (...) => { … })`.
//   3. Inside the action, do `const { fooCommand } = await import("./commands/foo.js");`
//      then call `fooCommand(...)`.
//   4. Do NOT hoist the import to the top of this file.
// ─────────────────────────────────────────────────────────────────────────────
import { readFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import chalk from "chalk";
import { Command } from "commander";
import { GATEWAY_DEFAULT_URL } from "./internal/index.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
async function getPackageVersion() {
    const pkgPath = join(__dirname, "..", "package.json");
    const pkgContent = await readFile(pkgPath, "utf-8");
    const pkg = JSON.parse(pkgContent);
    return pkg.version ?? "0.0.0";
}
/**
 * Options shared by most cloud subcommands. `--context` is always present;
 * `--org` / `--json` are opt-in. Descriptions here are the canonical ones —
 * commands needing a different wording (e.g. "Org slug override (defaults to
 * [memory].org)") keep their own explicit `.option(...)` call.
 */
function withCommonOpts(cmd, opts = {}) {
    cmd.option("-c, --context <name>", "Use a named context");
    if (opts.org)
        cmd.option("--org <slug>", "Org slug override");
    if (opts.json)
        cmd.option("--json", "Print JSON");
    return cmd;
}
function handleCliError(error) {
    const exitCode = typeof error === "object" &&
        error !== null &&
        "exitCode" in error &&
        typeof error.exitCode === "number"
        ? error.exitCode
        : 1;
    const message = error instanceof Error ? error.message : String(error);
    console.error(chalk.red("\n  Error:"), message);
    process.exitCode = exitCode;
}
export async function runCli(argv = process.argv) {
    const program = new Command();
    const version = await getPackageVersion();
    program
        .name("lobu")
        .description("CLI for deploying and managing AI agents on Lobu")
        .version(version);
    // Group commands in --help output. Commander v14 has no native grouping,
    // so we override the help formatter via addHelpText to print our own
    // categorized list. The flat command list is still available.
    program.addHelpText("after", `
Local dev:
  init [name]              Scaffold a new agent project
  run | dev | start        Boot the embedded Lobu stack
  chat <prompt>            Send a prompt to an agent and stream the response
  validate                 Validate lobu.config.ts
  doctor                   Health checks (deps, DB, pgvector, ports, keys)
  telemetry                Show / toggle anonymous error reporting

Cloud:
  login | logout           OAuth device-code login (or --token for CI)
  whoami | status          Show user / agent state
  context <subcmd>         Manage API contexts
  org <subcmd>             Manage active org slug
  link | unlink            Bind this directory to a (context, org)
  apply | deploy           Sync lobu.config.ts to cloud (idempotent)
  agent <subcmd>           CRUD agents via REST
  call [tool]              Invoke an admin REST tool by name (--list to discover)
  token [create]           Print or mint personal access tokens

Memory:
  memory run [tool]        Invoke a memory MCP tool
  memory exec <script>     Run a ClientSDK script
  memory health            Validate login + MCP connectivity
  memory configure         Wire OpenClaw config
  memory seed [path]       Provision a memory workspace
  memory init              Wire agents to a memory MCP endpoint
`);
    // ─── init ───────────────────────────────────────────────────────────
    program
        .command("init [name]")
        .description("Scaffold a new agent project (lobu.config.ts + agent files + .env), or bootstrap one from an existing org with --from-org")
        .option("-y, --yes", "Skip prompts; use defaults / flag values")
        .option("--here", "Scaffold into the current directory (alias for `init .`)")
        .option("--port <port>", "Gateway port (default 8787)")
        .option("--public-url <url>", "Public gateway URL (OAuth/webhooks)")
        .option("--network <policy>", "Worker network policy: restricted | open | isolated")
        .option("--provider <id>", "Provider id from `config/providers.json`")
        .option("--provider-key <key>", "Provider API key (else read from env)")
        .option("--platform <type>", "Chat platform: telegram | slack | discord | whatsapp | teams | gchat")
        .option("--memory <choice>", "Memory backend: none | lobu-cloud | lobu-custom")
        .option("--memory-url <url>", "Custom memory MCP URL (with --memory lobu-custom)")
        .option("--otel-endpoint <url>", "OpenTelemetry collector endpoint")
        .option("--sentry", "Enable Sentry error reporting")
        .option("--no-sentry", "Disable Sentry without prompting")
        .option("--hosted-slack", "Use the hosted Lobu Slack bot (no bot token) in lobu.config.ts")
        .option("--no-hosted-slack", "Skip the hosted Slack bot without prompting")
        .option("--list-providers", "Print available provider ids from config/providers.json and exit")
        .option("--from-org [slug]", "Bootstrap a re-appliable project from an existing org (defaults to active session)")
        .option("--url <url>", "Server URL override (with --from-org)")
        .action(async (name, 
    // Commander's raw shape: `sentry` is a tristate (true=--sentry,
    // false=--no-sentry, undefined=neither) and `fromOrg` is string|true.
    // Every other field maps 1:1 onto InitOptions, so we spread and only
    // normalize those two below.
    options) => {
        const { initCommand } = await import("./commands/init.js");
        // `--from-org` with no value is `true`; normalize to "" (active org).
        const fromOrg = options.fromOrg === undefined
            ? undefined
            : options.fromOrg === true
                ? ""
                : options.fromOrg;
        await initCommand(process.cwd(), name, {
            ...options,
            sentry: options.sentry === true,
            noSentry: options.sentry === false,
            fromOrg,
        });
    });
    // ─── chat ──────────────────────────────────────────────────────────
    program
        .command("chat <prompt>")
        .description("Send a prompt to an agent and stream the response. With --user, routes through Telegram/Slack.")
        .option("-a, --agent <id>", "Agent ID (defaults to first in lobu.config.ts)")
        .option("-u, --user <id>", "User ID to impersonate (e.g. telegram:12345)")
        .option("-t, --thread <id>", "Thread/conversation ID for multi-turn")
        .option("-g, --gateway <url>", `Gateway URL (default: ${GATEWAY_DEFAULT_URL})`)
        .option("--dry-run", "Skip side-effecting tool calls (sandbox writes, sdk_run mutations). The turn still runs and history is still persisted.")
        .option("--new", "Force new session (ignore existing)")
        .option("-C, --continue", "Resume the last thread for this (context, agent)")
        .option("--auto-approve", "Auto-approve every tool call (use only in trusted environments)")
        .option("--json", "Emit raw SSE events as JSON lines instead of text")
        .option("-c, --context <name>", "Use a named context")
        .option("--org <slug>", "Org slug override for this run (defaults to active context org; no config write)")
        .action(async (prompt, options) => {
        const { chatCommand } = await import("./commands/chat.js");
        await chatCommand(process.cwd(), prompt, options);
    });
    // ─── validate ───────────────────────────────────────────────────────
    program
        .command("validate")
        .description("Validate lobu.config.ts schema, skill IDs, and provider config")
        .action(async () => {
        const { validateCommand } = await import("./commands/validate.js");
        const valid = await validateCommand(process.cwd());
        if (!valid)
            process.exit(1);
    });
    // ─── apply / deploy ─────────────────────────────────────────────────
    program
        .command("apply")
        .alias("deploy")
        .description("Sync lobu.config.ts + agent dirs to your Lobu Cloud org (idempotent)")
        .option("--dry-run", "Show the plan and exit without mutating")
        .option("--yes", "Skip the confirmation prompt (CI mode)")
        .option("--only <kind>", "Restrict to one resource family: 'agents' | 'memory'")
        .option("--org <slug>", "Org slug override (defaults to active session)")
        .option("--url <url>", "Server URL override")
        .option("--force", "Bypass the project-link guard if context/org don't match")
        .action(async (options) => {
        if (options.only !== undefined &&
            options.only !== "agents" &&
            options.only !== "memory") {
            console.error(chalk.red("\n  Error:"), `--only must be 'agents' or 'memory' (got: ${options.only})`);
            process.exit(2);
        }
        const { applyCommand } = await import("./commands/_lib/apply/apply-cmd.js");
        await applyCommand({
            dryRun: options.dryRun,
            yes: options.yes,
            only: options.only,
            org: options.org,
            url: options.url,
            force: options.force,
        });
    });
    // ─── run / dev / start ──────────────────────────────────────────────
    program
        .command("run")
        .aliases(["dev", "start"])
        .description("Run the embedded Lobu stack (gateway + workers in one Node process)")
        .option("--port <port>", "Gateway port (overrides GATEWAY_PORT in .env)")
        .option("--quiet", "Suppress startup banner; raise log level to warn")
        .option("--verbose", "Lower log level to debug")
        .option("--log-level <level>", "Forwarded as LOG_LEVEL to the bundle")
        .option("--unsafe-shared-db", "Allow running against a non-loopback DATABASE_URL inherited from the shell")
        .action(async (options) => {
        const { devCommand } = await import("./commands/dev.js");
        await devCommand(process.cwd(), options);
    });
    // ─── login ──────────────────────────────────────────────────────────
    withCommonOpts(program
        .command("login")
        .description("Authenticate with Lobu Cloud")
        .option("--token <token>", "Use API token directly (CI/CD)"))
        .option("-f, --force", "Re-authenticate (revokes existing session)")
        .option("-q, --quiet", "Suppress spinner; bail immediately if non-interactive (CI / backgrounded shells)")
        .option("--email <address>", "Headless login on a user's behalf: the server emails them an approval link (auth.md user_claimed flow)")
        .action(async (options) => {
        const { loginCommand } = await import("./commands/login.js");
        await loginCommand({ ...options, cliVersion: version });
    });
    // ─── logout ─────────────────────────────────────────────────────────
    withCommonOpts(program.command("logout").description("Clear stored credentials")).action(async (options) => {
        const { logoutCommand } = await import("./commands/logout.js");
        await logoutCommand(options);
    });
    // ─── whoami ─────────────────────────────────────────────────────────
    withCommonOpts(program
        .command("whoami")
        .description("Show current user and linked agent")
        .option("--json", "Emit machine-readable session JSON (for Owletto Mac)")).action(async (options) => {
        const { whoamiCommand } = await import("./commands/whoami.js");
        await whoamiCommand(options);
    });
    // ─── token ──────────────────────────────────────────────────────────
    const token = withCommonOpts(program.command("token").description("Print or create Lobu access tokens"))
        .option("--raw", "Print token only (no labels)")
        .action(async (options) => {
        const { tokenCommand } = await import("./commands/token.js");
        await tokenCommand(options);
    });
    const tokenCreate = withCommonOpts(token
        .command("create")
        .description("Create an org-scoped personal access token for servers/CI"), { org: true })
        .option("--name <name>", "Token name (default: lobu-cli-YYYY-MM-DD)")
        .option("--description <text>", "Token description")
        .option("--scope <scope>", "Space-separated scopes (default: mcp:read mcp:write)")
        .option("--expires-in-days <days>", "Expire token after N days", (value) => {
        const days = Number(value);
        if (!Number.isInteger(days) || days < 1) {
            throw new Error("--expires-in-days must be a positive integer");
        }
        return days;
    })
        .option("--raw", "Print token only")
        .option("--json", "Print JSON response");
    // `-c/--context` is declared on both `token` and `token create`. Commander
    // binds a flag shared by parent and child to the *parent*, so the child's
    // local `.opts()` never sees `context` — read `optsWithGlobals()` to merge
    // the ancestor's value back in (otherwise `-c` is silently ignored, #1023).
    tokenCreate.action(async () => {
        const { tokenCreateCommand } = await import("./commands/token.js");
        await tokenCreateCommand(tokenCreate.optsWithGlobals());
    });
    token
        .command("revoke <jti>")
        .description("Revoke a worker/settings token by its jti (kill switch)")
        .option("--expires-at <iso>", "Original token expiry (ISO 8601); the revocation row is GC'd past it. Defaults to 24h from now.")
        .action(async (jti, options) => {
        const { tokenRevokeCommand } = await import("./commands/token.js");
        await tokenRevokeCommand(jti, options);
    });
    // ─── context ────────────────────────────────────────────────────────
    const context = program
        .command("context")
        .description("Manage Lobu API contexts");
    context
        .command("list")
        .description("List configured contexts")
        .action(async () => {
        const { contextListCommand } = await import("./commands/context.js");
        await contextListCommand();
    });
    context
        .command("current")
        .description("Show the active context")
        .action(async () => {
        const { contextCurrentCommand } = await import("./commands/context.js");
        await contextCurrentCommand();
    });
    context
        .command("add <name>")
        .description("Add a named context")
        .requiredOption("--url <url>", "Base URL for this context")
        .option("--cwd <path>", "Working directory the lifecycle owner cd's into before spawning `lobu run` (used by per-worktree contexts)")
        .option("--lifecycle <mode>", "managed | external — managed means the menubar spawns `lobu run`", (value) => {
        if (value !== "managed" && value !== "external") {
            throw new Error(`--lifecycle must be 'managed' or 'external'`);
        }
        return value;
    })
        .action(async (name, options) => {
        const { contextAddCommand } = await import("./commands/context.js");
        await contextAddCommand({
            name,
            url: options.url,
            cwd: options.cwd,
            lifecycle: options.lifecycle,
        });
    });
    context
        .command("use <name>")
        .description("Set the active context")
        .action(async (name) => {
        const { contextUseCommand } = await import("./commands/context.js");
        await contextUseCommand(name);
    });
    context
        .command("rm <name>")
        .description("Remove a named context (idempotent)")
        .action(async (name) => {
        const { contextRmCommand } = await import("./commands/context.js");
        await contextRmCommand(name);
    });
    // ─── status ─────────────────────────────────────────────────────────
    withCommonOpts(program
        .command("status")
        .description("Show agent status from the active org"), { org: true }).action(async (options) => {
        const { statusCommand } = await import("./commands/status.js");
        await statusCommand(options);
    });
    // ─── org ────────────────────────────────────────────────────────────
    const org = program.command("org").description("Manage active Lobu org");
    withCommonOpts(org
        .command("list")
        .description("List organizations available to the current login")).action(async (options) => {
        const { orgListCommand } = await import("./commands/org.js");
        await orgListCommand(options);
    });
    withCommonOpts(org.command("current").description("Show the active org")).action(async (options) => {
        const { orgCurrentCommand } = await import("./commands/org.js");
        await orgCurrentCommand(options);
    });
    withCommonOpts(org.command("set <slug>").description("Set the active org slug")).action(async (slug, options) => {
        const { orgSetCommand } = await import("./commands/org.js");
        await orgSetCommand(slug, options);
    });
    withCommonOpts(org
        .command("create <slug>")
        .description("Open the browser to create an organization (slug pre-filled)")
        .option("-n, --name <name>", "Organization display name")).action(async (slug, options) => {
        const { orgCreateCommand } = await import("./commands/org.js");
        await orgCreateCommand(slug, options);
    });
    // ─── link / unlink ──────────────────────────────────────────────────
    withCommonOpts(program
        .command("link")
        .description("Bind the current directory to a (context, org). Stored at .lobu/project.json.")
        .option("--org <slug>", "Org slug to link (defaults to active)")).action(async (options) => {
        const { linkCommand } = await import("./commands/link.js");
        await linkCommand(options);
    });
    program
        .command("unlink")
        .description("Remove the project link file")
        .action(async () => {
        const { unlinkCommand } = await import("./commands/link.js");
        await unlinkCommand();
    });
    // ─── agent ──────────────────────────────────────────────────────────
    const agent = program
        .command("agent")
        .description("Manage agents via the same REST API as the web app");
    withCommonOpts(agent.command("list").description("List agents"), {
        org: true,
        json: true,
    }).action(async (options) => {
        const { agentListCommand } = await import("./commands/agent.js");
        await agentListCommand(options);
    });
    withCommonOpts(agent.command("get <agentId>").description("Get an agent"), {
        org: true,
    }).action(async (agentId, options) => {
        const { agentGetCommand } = await import("./commands/agent.js");
        await agentGetCommand(agentId, options);
    });
    withCommonOpts(agent
        .command("create <agentId>")
        .description("Create an agent")
        .option("--name <name>", "Display name")
        .option("--description <text>", "Description"), { org: true, json: true }).action(async (agentId, options) => {
        const { agentCreateCommand } = await import("./commands/agent.js");
        await agentCreateCommand(agentId, options);
    });
    agent
        .command("scaffold <agentId>")
        .description("Add a new local agent (agents/<id>/* + lobu.config.ts entry) without overwriting existing ones")
        .option("--name <name>", "Display name")
        .option("--description <text>", "Description")
        .action(async (agentId, options) => {
        const { agentScaffoldCommand } = await import("./commands/agent.js");
        await agentScaffoldCommand(agentId, options);
    });
    withCommonOpts(agent
        .command("update <agentId>")
        .description("Update agent metadata")
        .option("--name <name>", "Display name")
        .option("--description <text>", "Description"), { org: true, json: true }).action(async (agentId, options) => {
        const { agentUpdateCommand } = await import("./commands/agent.js");
        await agentUpdateCommand(agentId, options);
    });
    withCommonOpts(agent
        .command("delete <agentId>")
        .description("Delete an agent")
        .option("--yes", "Confirm deletion"), { org: true }).action(async (agentId, options) => {
        const { agentDeleteCommand } = await import("./commands/agent.js");
        await agentDeleteCommand(agentId, options);
    });
    const agentConfig = agent
        .command("config")
        .description("Read or patch agent config");
    withCommonOpts(agentConfig
        .command("get <agentId>")
        .description("Print agent config JSON")
        .option("--output <file>", "Write JSON to a file"), { org: true }).action(async (agentId, options) => {
        const { agentConfigGetCommand } = await import("./commands/agent.js");
        await agentConfigGetCommand(agentId, options);
    });
    withCommonOpts(agentConfig
        .command("patch <agentId>")
        .description("Patch agent config from a JSON file")
        .requiredOption("--file <file>", "JSON file with config fields to update"), { org: true, json: true }).action(async (agentId, options) => {
        const { agentConfigPatchCommand } = await import("./commands/agent.js");
        await agentConfigPatchCommand(agentId, options);
    });
    // ─── call ───────────────────────────────────────────────────────────
    // Generic dispatcher over the admin REST tool surface
    // (`POST /api/<org>/<tool>`). Replaces the urge to add bespoke
    // per-action commands (`lobu sync`, `lobu retry-feed`, ...) by exposing
    // every UI-callable tool through one entry point. `lobu memory run` is
    // kept alongside intentionally — it routes via MCP JSON-RPC, this one via
    // the REST proxy. See packages/cli/src/commands/call.ts for the arg shape.
    withCommonOpts(program
        .command("call [tool]")
        .description("Invoke an admin REST tool by name (POST /api/<org>/<tool>). Run with --list or no args to discover.")
        .option("--list", "List tools available to the current token (default when called bare)")
        .option("--all", "Include internal/admin-only tools in --list output")
        .option("--input-file <path>", "Read the JSON args body from a file (top-level object)")
        .option("--arg <entry>", "Add a top-level arg as key=string or key:=<json> (repeatable)", (value, previous) => previous ? [...previous, value] : [value])
        .option("--raw", "Emit compact JSON (default is pretty-printed)")
        .option("--url <url>", "Server URL override"), { org: true, json: true }).action(async (tool, options) => {
        const { callCommand } = await import("./commands/call.js");
        await callCommand(tool, options);
    });
    // ─── connector ──────────────────────────────────────────────────────
    const connector = program
        .command("connector")
        .description("Run connectors locally against an auth profile (no feed required)");
    connector
        .command("run [connector_key]")
        .description("Execute a connector locally; events stream to stdout, nothing is persisted")
        .option("--auth-profile <slug>", "Auth profile slug (browser_session only in v1)")
        .option("--config <json>", 'Feed config as JSON object (e.g. \'{"start_url":"https://..."}\')')
        .option("--checkpoint-from-feed <id>", "Borrow checkpoint state from this feed id")
        .option("--from-feed <id>", "Resolve connector + auth + config + checkpoint from this feed id")
        .option("--max-items <n>", "Cap pagination to this many items")
        .option("--check", "Resolve + validate without executing the connector")
        .option("--json", "Emit machine-readable JSON to stdout (artifact-shaped)")
        .option("-c, --context <name>", "Use a named context")
        .option("--url <url>", "Server URL override")
        .option("--org <slug>", "Org slug override")
        .action(async (connectorKey, options) => {
        const { connectorRunCommand } = await import("./commands/connector.js");
        await connectorRunCommand(connectorKey, options);
    });
    // Hidden internal command: the CLI side of the connector-runtime parity
    // smoke gate. Runs the SAME runConnectorRuntimeSelfCheck() the worker image
    // runs (compile + default SubprocessExecutor), so a packaging/parity drift
    // (e.g. a missing `COPY packages/core`) is caught by RUNNING the artifact,
    // not just building it. CI-only — hidden from help.
    connector
        .command("runtime-self-check", { hidden: true })
        .description("Internal: assert the connector runtime can resolve + compile + execute (CI smoke gate)")
        .option("--json", "Emit machine-readable JSON to stdout")
        .action(async (options) => {
        const { connectorRuntimeSelfCheckCommand } = await import("./commands/connector.js");
        await connectorRuntimeSelfCheckCommand(options);
    });
    // ─── doctor ─────────────────────────────────────────────────────────
    program
        .command("doctor")
        .description("Health checks (deps, DB, pgvector, ports, provider keys)")
        .option("--memory-only", "Only check memory MCP connectivity + auth")
        .action(async (options) => {
        const { doctorCommand } = await import("./commands/doctor.js");
        await doctorCommand(options);
    });
    // ─── telemetry ──────────────────────────────────────────────────────
    const telemetry = program
        .command("telemetry")
        .description("Show or toggle anonymous error reporting (Sentry)");
    telemetry
        .command("status", { isDefault: true })
        .description("Show whether telemetry is on or off")
        .action(async () => {
        const { telemetryStatusCommand } = await import("./commands/telemetry.js");
        await telemetryStatusCommand();
    });
    telemetry
        .command("on")
        .description("Enable telemetry (writes SENTRY_DSN to .env)")
        .option("--dsn <dsn>", "Custom Sentry DSN (defaults to Lobu's)")
        .action(async (options) => {
        const { telemetryOnCommand } = await import("./commands/telemetry.js");
        await telemetryOnCommand(options);
    });
    telemetry
        .command("off")
        .description("Disable telemetry (removes SENTRY_DSN from .env)")
        .action(async () => {
        const { telemetryOffCommand } = await import("./commands/telemetry.js");
        await telemetryOffCommand();
    });
    // ─── memory ─────────────────────────────────────────────────────────
    const memory = program
        .command("memory")
        .description("Lobu memory MCP — tools, seeding, and client configuration");
    const memoryOrg = memory
        .command("org")
        .description("Manage active organization for memory MCP");
    withCommonOpts(memoryOrg.command("current").description("Show the active org")).action(async (options) => {
        const { memoryOrgCurrentCommand } = await import("./commands/memory/org.js");
        await memoryOrgCurrentCommand(options);
    });
    withCommonOpts(memoryOrg.command("set <slug>").description("Set the active org slug")).action(async (slug, options) => {
        const { memoryOrgSetCommand } = await import("./commands/memory/org.js");
        await memoryOrgSetCommand(slug, options);
    });
    withCommonOpts(memory
        .command("run [tool] [params]")
        .description("Invoke an MCP tool (or list tools when called bare)")
        .option("--url <url>", "Server URL override"), { org: true }).action(async (tool, params, options) => {
        const { memoryRunCommand } = await import("./commands/memory/run.js");
        await memoryRunCommand(tool, params, options);
    });
    withCommonOpts(memory
        .command("exec <script>")
        .description("Run a TypeScript ClientSDK script via the memory MCP")
        .option("--url <url>", "Server URL override"), { org: true }).action(async (script, options) => {
        const { memoryRunCommand } = await import("./commands/memory/run.js");
        await memoryRunCommand("run_sdk", JSON.stringify({ script }), options);
    });
    withCommonOpts(memory
        .command("health")
        .description("Validate Lobu login + MCP connectivity")
        .option("--url <url>", "Server URL override"), { org: true }).action(async (options) => {
        const { memoryHealthCommand } = await import("./commands/memory/health.js");
        await memoryHealthCommand(options);
    });
    withCommonOpts(memory
        .command("configure")
        .description("Write OpenClaw plugin config pointing at the active memory MCP")
        .option("--url <url>", "Server URL override"), { org: true })
        .option("--config-path <path>", "OpenClaw config path (defaults to ~/.openclaw/openclaw.json)")
        .option("--token-command <cmd>", "Override the plugin's token retrieval command")
        .action(async (options) => {
        const { memoryConfigureCommand } = await import("./commands/memory/configure.js");
        await memoryConfigureCommand(options);
    });
    memory
        .command("seed [path]")
        .description("Provision a Lobu memory workspace from lobu.config.ts + optional ./data records")
        .option("--dry-run", "Log what would be created without mutating")
        .option("--org <slug>", "Org slug override (defaults to [memory].org)")
        .option("--url <url>", "Server URL override")
        .option("-c, --context <name>", "Use a named context")
        .action(async (pathArg, options) => {
        const { memorySeedCommand } = await import("./commands/memory/seed.js");
        await memorySeedCommand(pathArg, options);
    });
    memory
        .command("init")
        .description("Wire an existing project's agents to a memory MCP endpoint")
        .option("--url <url>", "MCP server URL (skips the picker)")
        .option("--agent <id>", "Configure a specific agent only")
        .option("--skip-auth", "Skip the authentication step")
        .action(async (options) => {
        const { memoryInitCommand } = await import("./commands/memory/init.js");
        await memoryInitCommand(options);
    });
    memory
        .command("browser-auth")
        .description("Set up browser auth for a connector: launch a dedicated Chrome with remote debugging and store its CDP endpoint on the auth profile")
        .requiredOption("--connector <key>", 'Connector key (e.g. "x")')
        .option("--domains <list>", "Comma-separated cookie domains override")
        .option("--auth-profile-slug <slug>", "Browser auth profile slug to store the CDP endpoint on")
        .option("--remote-debug-port <port>", "Remote debugging port for the dedicated Chrome", "9222")
        .option("--dedicated-profile <name>", "Dedicated Chrome profile dir name")
        .option("--check", "Check if the CDP endpoint stored on a browser auth profile is reachable")
        .action(async (options) => {
        const { memoryBrowserAuthCommand } = await import("./commands/memory/browser-auth.js");
        await memoryBrowserAuthCommand(options);
    });
    try {
        await program.parseAsync(argv);
    }
    catch (error) {
        handleCliError(error);
    }
}
//# sourceMappingURL=index.js.map