Skip to content
Back to search

openloomi

OpenLoomi is an open-source AI coworker. It connects your work tools, understands what you’re working on, and tells you what needs your attention, why it matters, and what to do next. It’s your open-source Attention Agent.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/melandlabs--openloomi/badge.svg)](/listings/melandlabs--openloomi)

HTML

<a href="/listings/melandlabs--openloomi"><img src="/api/listings/melandlabs--openloomi/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

**Download directly** (for end users):

<p align="center"> </p>

<p align="center"> </p>

Full documentation: [openloomi.ai/docs](https://openloomi.ai/docs)

**Use as an Agent plugin** (for Claude Code / Codex users):

OpenLoomi ships official marketplace plugins that turn your existing agent into a front-end for the local OpenLoomi runtime.

| Agent | Install | First-run setup | | ----------- | ----------------------------------------------------------------------------------------- | --------------------------------- | | Claude Code | `/plugin marketplace add melandlabs/plugins`<br>`/plugin install openloomi` | `/openloomi:setup` | | Codex CLI | `codex plugin marketplace add melandlabs/plugins && codex plugin add openloomi@openloomi` | `@OpenLoomi Run first-use setup.` |

The slim public marketplace lives at [`melandlabs/plugins`](https://github.com/melandlabs/plugins) so adding it only fetches the plugin payloads. See the plugin docs for full reference: [`plugins/claude`](https://openloomi.ai/docs/plugins/claude) · [`plugins/codex`](https://openloomi.ai/docs/plugins/codex).

**Use in skill-only agent runtimes**:

Install the OpenLoomi skill set directly from this repository:

npx skills add https://github.com/melandlabs/openloomi/tree/main/skills \
  --skill openloomi openloomi-setup openloomi-memory openloomi-connectors openloomi-loop openloomi-goals openloomi-api openloomi-feature-guide composio \
  -y

Start with the `openloomi` or `openloomi-setup` skill. The first setup pass checks whether OpenLoomi Desktop is installed, whether the local API is reachable, and whether a local session token is available. If OpenLoomi Desktop is missing, the skill points the user to the official Getting Started guide and release downloads before continuing.

**Develop locally** (for developers):

git clone https://github.com/melandlabs/openloomi.git
cd openloomi

pnpm install
pnpm tauri:dev

Requires Node.js 22+, pnpm 9+, Rust 1.75+, and on Windows: Visual Studio Build Tools with C++ workload. For more platform-specific setup requirements, see [CONTRIBUTING.md](./CONTRIBUTING.md).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 37 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "openloomi",
  3. "owner": {
  4. "name": "OpenLoomi",
  5. "email": "developers@melandlabs.ai"
  6. },
  7. "metadata": {
  8. "description": "OpenLoomi local-first runtime plugins for Claude",
  9. "version": "4",
  10. "homepage": "https://openloomi.ai",
  11. "repository": "https://github.com/melandlabs/openloomi",
  12. "license": "Apache-2.0"
  13. },
  14. "plugins": [
  15. {
  16. "name": "openloomi",
  17. "source": "./plugins/claude",
  18. "description": "Connect Claude Code to your local OpenLoomi runtime. Sync ANTHROPIC_API_KEY, mirror lifecycle onto the Loomi Pet, auto-archive Stop events into OpenLoomi memory.",
  19. "version": "0.9.0",
  20. "author": {
  21. "name": "OpenLoomi"
  22. },
  23. "homepage": "https://openloomi.ai",
  24. "repository": "https://github.com/melandlabs/openloomi/tree/main/plugins/claude",
  25. "license": "Apache-2.0",
  26. "keywords": [
  27. "openloomi",
  28. "memory",
  29. "pet",
  30. "anthropic",
  31. "claude-code",
  32. "local-first",
  33. "loops"
  34. ]
  35. }
  36. ]
  37. }
README.md · README · 204 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <div align="center">
  2. <picture>
  3. <source media="(prefers-color-scheme: dark)" srcset="apps/web/public/images/logo-text-dark.png">
  4. <img src="apps/web/public/images/logo-text.png" alt="OpenLoomi Logo" width="400">
  5. </picture>
  6. **Open-source AI coworker, built to protect your attention**
  7. <p align="center">
  8. <a href="./README.md">English</a> | <a href="./README-zh.md">简体中文</a> | <a href="./README-ja.md">日本語</a>
  9. </p>
  10. [![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20macOS%20%7C%20Linux-4B4B4B?logo=linux&logoColor=white)](https://openloomi.ai)
  11. [![License](https://img.shields.io/badge/License-Apache%202.0-F8D52A?logo=apache)](https://www.apache.org/licenses/LICENSE-2.0)
  12. [![Discord](https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white)](https://discord.com/invite/xkJaJyWcsv)
  13. [![X](https://img.shields.io/badge/X-Follow-000000?logo=x&logoColor=white)](https://x.com/AlloomiAI)
  14. [![Downloads](https://img.shields.io/github/downloads/melandlabs/openloomi/total?logo=github)](https://github.com/melandlabs/openloomi/releases)
  15. </div>
  16. <div align="center">
  17. ⭐ **If you find OpenLoomi useful, please consider giving us a star on GitHub!** It helps more people discover the project and motivates us to keep building. 🙏
  18. [![GitHub Repo stars](https://img.shields.io/github/stars/melandlabs/openloomi?style=social&label=Star)](https://github.com/melandlabs/openloomi)
  19. </div>
  20. ---
  21. ## What is OpenLoomi?
  22. Your work is scattered across apps. OpenLoomi connects the tools you use and, with your permission, understands what’s on your screen. It brings together the context behind your people, projects, and decisions, then surfaces only what needs your decision or action.
  23. **Focus on what matters. This is your Attention Agent.**
  24. <p align="center">
  25. <img src="screenshots/app/main-with-loomi.gif" alt="OpenLoomi main window with Loomi" width="100%">
  26. </p>
  27. ## What is it for?
  28. An always-on desktop **attention agent** — the friendly desk companion Loomi — watches the door so you don't have to, and turns the day's scattered signals into decision cards you can approve in one tap. Use it standalone, or plug any Agent framework into the same resident desktop: Claude Code, Codex, OpenCode, Hermes, and OpenClaw all work.
  29. - **Stop dropping commitments.** Overdue replies, creeping deadlines, "I'll send that follow-up Friday" — Loomi nudges you with a small bubble at the right moment, and you can teach it the signals and decisions to watch for.
  30. - **Find anything from your work life in seconds.** "What did I decide about pricing last quarter?", "Who owns design on Acorn?", "What was I working on before vacation?" — memory spans every tool and channel, no more digging through Slack, Gmail, or Notion.
  31. - **Morning brief at 9 AM, end-of-day recap at 6 PM.** Today's to-do slides into view every morning, today's done ships every evening — the key info lives in one place instead of nine apps.
  32. - **Ask AI for work help right inside your chat.** Draft a reply, summarize a long thread, schedule a follow-up — directly in Telegram, WhatsApp, iMessage, QQ, or Lark/Feishu.
  33. → Learn more about the always-on companion in the [Attention Agent docs](https://openloomi.ai/docs/attention-agent) and [Use cases](https://openloomi.ai/docs/use-cases).
  34. ## Features
  35. | | Capability | What it does |
  36. | --- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  37. | 🐾 | **[Attention Agent](https://openloomi.ai/docs/attention-agent)** | An always-on desktop companion (Loomi) that surfaces pre-decided reminders — 9 AM to-do, 6 PM recap, overdue replies — as small bubbles, without fighting for your focus. |
  38. | 🧠 | **[Holistic Context](https://openloomi.ai/docs/memory)** | Short → mid → long-term memory that grows on its own — visible, auditable, and always remembering your people, projects, and decisions across months |
  39. | 🔌 | **[Platform Connectors](https://openloomi.ai/docs/connectors)** | **[Auto-fetch](https://openloomi.ai/docs/what-is-openloomi#a-complete-intelligence-loop-from-perception-to-action)** background sync loop pulls commits, issues, emails, and docs proactively into your context graph. **[Messaging apps](https://openloomi.ai/docs/messaging-apps)** — Telegram, WhatsApp, iMessage, QQ, Lark/Feishu — let you chat with AI directly inside your existing conversations. |
  40. | ⏰ | **[Proactive Tasks](https://openloomi.ai/docs/automation)** | Schedule recurring work — daily digests, weekly reports, reminders — that run automatically on your desktop. |
  41. | 🖥️ | **[Security & Ease of Use](https://openloomi.ai/docs/privacy-security)** | Native app for Windows, macOS, Linux Desktop Apps — **works out of the box**, minutes to set up, no configuration wrestling; local-first storage, AES-256 encryption, no data leaves your machine, auditable access logs |
  42. | 🧩 | **[Any Agent Integration](https://openloomi.ai/docs/reference/agent-runtimes)** | OpenLoomi's context, memory, connectors, attention agent, and Loop engine are all delivered as open-source [Skills](https://openloomi.ai/docs/skills) and [Plugins](https://openloomi.ai/docs/plugins). Use OpenLoomi Desktop directly, or plug into your existing Agent — Claude, Codex, OpenCode, Hermes, or OpenClaw. |
  43. ## Quick Start
  44. **Download directly** (for end users):
  45. <p align="center">
  46. <a href="https://github.com/melandlabs/openloomi/releases/download/v0.9.0/openloomi_0.9.0_macOS_aarch64.dmg"><img src="https://img.shields.io/badge/macOS_Apple_Silicon-000000?style=for-the-badge&logo=apple&logoColor=white" alt="macOS Apple Silicon"></a>
  47. <a href="https://github.com/melandlabs/openloomi/releases/download/v0.9.0/openloomi_0.9.0_macOS_amd64.dmg"><img src="https://img.shields.io/badge/macOS_Intel-000000?style=for-the-badge&logo=apple&logoColor=white" alt="macOS Intel"></a>
  48. <a href="https://github.com/melandlabs/openloomi/releases/download/v0.9.0/openloomi_0.9.0_windows_amd64.exe"><img src="https://img.shields.io/badge/Windows_x64-0078D6?style=for-the-badge&logo=windows&logoColor=white" alt="Windows x64"></a>
  49. </p>
  50. <p align="center">
  51. <a href="https://github.com/melandlabs/openloomi/releases/download/v0.9.0/openloomi_0.9.0_linux_amd64.deb"><img src="https://img.shields.io/badge/Linux_AMD64_(.deb)-FCC624?style=for-the-badge&logo=linux&logoColor=black" alt="Linux AMD64 .deb"></a>
  52. <a href="https://github.com/melandlabs/openloomi/releases/download/v0.9.0/openloomi_0.9.0_linux_amd64.rpm"><img src="https://img.shields.io/badge/Linux_AMD64_(.rpm)-FCC624?style=for-the-badge&logo=linux&logoColor=black" alt="Linux AMD64 .rpm"></a>
  53. <a href="https://github.com/melandlabs/openloomi/releases/download/v0.9.0/openloomi_0.9.0_linux_aarch64.deb"><img src="https://img.shields.io/badge/Linux_ARM64_(.deb)-FCC624?style=for-the-badge&logo=linux&logoColor=black" alt="Linux ARM64 .deb"></a>
  54. <a href="https://github.com/melandlabs/openloomi/releases/download/v0.9.0/openloomi_0.9.0_linux_aarch64.rpm"><img src="https://img.shields.io/badge/Linux_ARM64_(.rpm)-FCC624?style=for-the-badge&logo=linux&logoColor=black" alt="Linux ARM64 .rpm"></a>
  55. </p>
  56. Full documentation: [openloomi.ai/docs](https://openloomi.ai/docs)
  57. **Use as an Agent plugin** (for Claude Code / Codex users):
  58. OpenLoomi ships official marketplace plugins that turn your existing agent into a front-end for the local OpenLoomi runtime.
  59. | Agent | Install | First-run setup |
  60. | ----------- | ----------------------------------------------------------------------------------------- | --------------------------------- |
  61. | Claude Code | `/plugin marketplace add melandlabs/plugins`<br>`/plugin install openloomi` | `/openloomi:setup` |
  62. | Codex CLI | `codex plugin marketplace add melandlabs/plugins && codex plugin add openloomi@openloomi` | `@OpenLoomi Run first-use setup.` |
  63. The slim public marketplace lives at [`melandlabs/plugins`](https://github.com/melandlabs/plugins) so adding it only fetches the plugin payloads. See the plugin docs for full reference: [`plugins/claude`](https://openloomi.ai/docs/plugins/claude) · [`plugins/codex`](https://openloomi.ai/docs/plugins/codex).
  64. **Use in skill-only agent runtimes**:
  65. Install the OpenLoomi skill set directly from this repository:
  66. ```bash
  67. npx skills add https://github.com/melandlabs/openloomi/tree/main/skills \
  68. --skill openloomi openloomi-setup openloomi-memory openloomi-connectors openloomi-loop openloomi-goals openloomi-api openloomi-feature-guide composio \
  69. -y
  70. ```
  71. Start with the `openloomi` or `openloomi-setup` skill. The first setup pass
  72. checks whether OpenLoomi Desktop is installed, whether the local API is
  73. reachable, and whether a local session token is available. If OpenLoomi
  74. Desktop is missing, the skill points the user to the official Getting Started
  75. guide and release downloads before continuing.
  76. **Develop locally** (for developers):
  77. ```bash
  78. git clone https://github.com/melandlabs/openloomi.git
  79. cd openloomi
  80. pnpm install
  81. pnpm tauri:dev
  82. ```
  83. Requires Node.js 22+, pnpm 9+, Rust 1.75+, and on Windows: Visual Studio Build Tools with C++ workload. For more platform-specific setup requirements, see [CONTRIBUTING.md](./CONTRIBUTING.md).
  84. ## Why It Is Different
  85. **OpenLoomi is open-source and neutral.** Instead of locking you into a single vendor's agent, it integrates with any Agent Runtime — Claude Code, Codex, OpenCode, Hermes, OpenClaw — and brings a shared, cross-agent layer to all of them: a resident desktop **attention agent**, **holistic context memory**, **platform connectors**, and **proactive tasks**. Whichever agent you run, OpenLoomi watches the door, remembers what matters, and surfaces only the decisions worth your time — so you spend your attention on the work, not on chasing it.
  86. | Compared with... | OpenLoomi adds |
  87. | -------------------------- | ----------------------------------------------------------------------------------------------------------------- |
  88. | Claude Cowork-style agents | an open-source, local-first AI coworker and workspace with source evidence and approval |
  89. | Codex / Claude Code | workspace context beyond the repo: people, product decisions, launch context, issues, and follow-ups |
  90. | OpenClaw / Hermes | context before and after the action: why it matters, what source was used, what changed, what remains open |
  91. | RAG / knowledge bases | work state, not just document retrieval: what changed, what is still true, and what should affect the next action |
  92. ## App Screenshots
  93. <table>
  94. <tr>
  95. <td><img src="screenshots/app/loomi-pet.gif" alt="Loomi Pet" width="100%"></td>
  96. <td><img src="screenshots/app/loomi-proactive-task.gif" alt="Proactive Tasks" width="100%"></td>
  97. </tr>
  98. <tr>
  99. <td><img src="screenshots/app/docx.gif" alt="Document preview" width="100%"></td>
  100. <td><img src="screenshots/app/excel.gif" alt="Spreadsheet preview" width="100%"></td>
  101. </tr>
  102. <tr>
  103. <td><img src="screenshots/app/automation.gif" alt="Automation" width="100%"></td>
  104. <td><img src="screenshots/app/connectors.gif" alt="Connectors" width="100%"></td>
  105. </tr>
  106. </table>
  107. ## Feedback
  108. This is early-stage software. We're looking for people who'll actually install it, connect their tools, and tell us what's broken.
  109. - [GitHub Issues](https://github.com/melandlabs/openloomi/issues) — bugs, install problems, feature requests
  110. - [Discord](https://discord.com/invite/xkJaJyWcsv) — discussion, questions, help
  111. - [Email](mailto:developer@alloomi.ai) — anything else
  112. ## Contributing
  113. See [CONTRIBUTING.md](./CONTRIBUTING.md). Look for [`good first issue`](https://github.com/melandlabs/openloomi/labels/good%20first%20issue) labels.
  114. ## Related Projects
  115. OpenLoomi is the desktop experience. Many of the lower-level building blocks
  116. it depends on — AI runtime, integrations, loop engine, audit, memory — are
  117. developed in the open at:
  118. ### [OpenContext](https://github.com/melandlabs/opencontext) — the context layer
  119. **Your agent forgets why it made decisions. OpenContext fixes that.**
  120. OpenContext is the agentic context runtime that sits underneath an agentic
  121. application — a temporal context graph, a memory API, retrieval primitives, a
  122. multi-platform integration mesh, a deterministic loop engine, and an agent
  123. runtime, all behind a single library-first dependency.
  124. - **Temporal Context Graph.** A directed acyclic graph where every fact carries
  125. `valid_from` / `valid_until`. Supersession, contradiction, and merge are
  126. first-class edges — corrections are append-only, not destructive, so *"what
  127. did we believe last quarter?"* is a real, citable query.
  128. - **Library-First API.** Drop it into any host process with
  129. `pnpm add @melandlabs/opencontext`. It's not a UI, a chat surface, or a model
  130. provider — it's the glue between durable memory, retrieval, context
  131. correction, and multi-platform connectivity.
  132. - **Platform Integration Mesh.** One uniform `IntegrationRecord` shape across
  133. Gmail, Slack, Telegram, Linear, Jira, iMessage, Feishu, Weixin, and friends —
  134. credential rotation, rate-limit handling, and reconnect logic live behind the
  135. adapter.
  136. - **Deterministic Loop Engine.** A scheduler that wakes up, decides whether
  137. there is real work, and only then calls into the agent runtime. LLM calls are
  138. not the foundation — they are the last step.
  139. - **Built for embedded agents.** Designed to be embedded into any host process
  140. — CLI, MCP server, daemon, desktop app, or product backend. OpenLoomi Desktop
  141. is one such host.
  142. → Read [`docs/architecture.md`](https://github.com/melandlabs/opencontext/blob/main/docs/architecture.md)
  143. for the full data model, lifecycle of a fact, and transport surface map.
  144. ```bash
  145. pnpm add @melandlabs/opencontext
  146. ```
  147. ## License
  148. [Apache 2.0](./LICENSE)
plugins/claude/scripts/loomi-bridge.mjs · Bundled script · 3,681 lines · 2 findings marked
  1. #!/usr/bin/env node
  2. // SPDX-License-Identifier: Apache-2.0
  3. //
  4. // loomi-bridge.mjs — single Node 18+ ESM entrypoint for the OpenLoomi
  5. // Claude Code plugin.
  6. //
  7. // This file is intentionally dependency-free (only Node built-ins). It
  8. // implements every subcommand advertised by `plugin.json` and called by
  9. // the slash commands in `commands/`. Every side-effect path is opt-in.
  10. //
  11. // Subcommands:
  12. // version print plugin version
  13. // setup discover → install? → login → sync → status
  14. // setup-status [--json] stable JSON
  15. // install [--yes] user-approved install
  16. // login open OpenLoomi login surface
  17. // pet <state> set OpenLoomi Pet state
  18. // state <name> [--event <e>] fire-and-forget state (hook internal)
  19. // archive archive last Stop transcript (hook internal)
  20. // usage GET /api/llm/usage/summary
  21. // install-hooks merge into ~/.claude/settings.json
  22. // uninstall-hooks strip only the plugin's block
  23. // hooks-status report merge state
  24. //
  25. // IMPORTANT (secrets contract):
  26. // - This bridge never reads AI-provider env vars. AI provider
  27. // configuration lives entirely inside the OpenLoomi runtime,
  28. // which detects the user's `claude` CLI auth on its own. The
  29. // plugin's job is "Claude Code ↔ OpenLoomi Pet/state/usage";
  30. // AI config is the runtime's.
  31. // - ~/.openloomi/token is read at most for base64-decode to obtain
  32. // the bearer; its contents are never printed.
  33. // - All status checks report presence/absence only.
  34. import { spawn } from "node:child_process";
  35. import { randomUUID } from "node:crypto";
  36. import {
  37. existsSync,
  38. readFileSync,
  39. writeFileSync,
  40. renameSync,
  41. mkdirSync,
  42. statSync,
  43. chmodSync,
  44. } from "node:fs";
  45. import { readFile } from "node:fs/promises";
  46. import { EOL } from "node:os";
  47. import { homedir, platform, tmpdir } from "node:os";
  48. import { join, delimiter, sep, dirname, basename } from "node:path";
  49. import { fileURLToPath } from "node:url";
  50. // ---------------------------------------------------------------------------
  51. // Constants & state
  52. // ---------------------------------------------------------------------------
  53. const PLUGIN_VERSION = "0.1.0";
  54. const CLAUDE_NATIVE_PROVIDER = "claude";
  55. const DEFAULT_PROVIDER_BASE = "https://api.anthropic.com";
  56. const DEFAULT_PROVIDER_MODEL = "claude-opus-4-6";
  57. function parsePortEnv(name, fallback) {
  58. const raw = process.env[name];
  59. if (!raw) return fallback;
  60. const parsed = Number(raw);
  61. if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
  62. return fallback;
  63. }
  64. return parsed;
  65. }
  66. // Matches the documented ports in skills/openloomi-api/SKILL.md; the
  67. // desktop app falls back to 3515 when 3414 is busy.
  68. const OPENLOOMI_PORT_DEFAULT = parsePortEnv("OPENLOOMI_PORT_DEFAULT", 3414);
  69. const OPENLOOMI_PORT_FALLBACK = parsePortEnv("OPENLOOMI_PORT_FALLBACK", 3515);
  70. let _resolvedPort = OPENLOOMI_PORT_DEFAULT;
  71. const STATE_HTTP_TIMEOUT_MS = 2000;
  72. const ARCHIVE_HTTP_TIMEOUT_MS = 15_000;
  73. const CLAUDE_CLI_PROBE_TIMEOUT_MS = 5000;
  74. const ARCHIVE_MAX_BYTES = 5 * 1024 * 1024; // 5 MB cap on transcripts
  75. const ARCHIVE_MAX_TURNS = 6; // 6 user+assistant turns
  76. const ARCHIVE_MAX_CONTENT_CHARS = 6000; // 6k char summary cap
  77. // ---------------------------------------------------------------------------
  78. // Per-stage setup timeouts (issue #397)
  79. //
  80. // First-run /openloomi:setup chains four different waits behind one command:
  81. // 1. install (download + lay down the .app bundle via the platform script)
  82. // 2. launch (open -a / gtk-launch / start "" — short)
  83. // 3. api_ready (poll the local HTTP API until it responds)
  84. // 4. permission_grace (extra budget on top of api_ready for the first call
  85. // in case macOS is showing a TCC/Accessibility prompt
  86. // that the user has to dismiss by hand)
  87. //
  88. // The legacy `--max-wait` flag is kept as a global cap. The per-stage flags
  89. // below are the new defaults: each is independently tunable so a slow
  90. // download does not steal budget from the API wait, and vice versa.
  91. // ---------------------------------------------------------------------------
  92. const DEFAULT_INSTALL_TIMEOUT_MS = 300_000; // 5 min — covers slow 50 Mbps
  93. const DEFAULT_LAUNCH_TIMEOUT_MS = 10_000; // 10 s
  94. const DEFAULT_API_TIMEOUT_MS = 120_000; // 2 min — first-run default
  95. const DEFAULT_PERMISSION_GRACE_MS = 60_000; // 1 min extra for TCC prompts
  96. const SETUP_MAX_WAIT_DEFAULT_MS = 120_000; // --max-wait legacy default
  97. // Throttle live progress lines to ~1 Hz so we don't spam the terminal.
  98. // The value is the most-recent full-second tick we already printed for a
  99. // given stage; same-tick calls are silent.
  100. const _lastProgressSecond = Object.create(null);
  101. // 9-state capybara sprite set (apps/web/public/loomi-pet/assets/capybara/).
  102. // The plugin ships fox-sprite branding in `assets/`, but the bridge itself
  103. // is theme-agnostic — it validates state names against the superset of
  104. // names used by both the capybara and fox (loomi-*) sprite sets; the
  105. // OpenLoomi runtime's `map_state_to_pet` watcher decides which sprite
  106. // to render per the user's chosen theme.
  107. const CAPYBARA_STATES = new Set([
  108. "happy",
  109. "idle",
  110. "juggling",
  111. "needsinput",
  112. "presenting",
  113. "sleeping",
  114. "sweeping",
  115. "thinking",
  116. "working",
  117. ]);
  118. const MARKER = "_openloomi_plugin";
  119. const PLUGIN_BLOCK_KEY = "__openloomi_claude_plugin_hooks__";
  120. const PLUGIN_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
  121. const HOOKS_FILE = join(PLUGIN_DIR, "hooks", "hooks.json");
  122. const PLUGIN_DATA_DIR = (() => {
  123. const explicit = process.env.CLAUDE_PLUGIN_DATA;
  124. if (explicit) return explicit;
  125. return join(homedir(), ".claude", "plugins", "openloomi");
  126. })();
  127. const NEXT_ACTIONS = new Set([
  128. "install_openloomi",
  129. "provide_install_or_repo_path",
  130. "build_or_stage_openloomi",
  131. "login_openloomi",
  132. "configure_ai_provider",
  133. "install_claude_cli",
  134. "login_claude_cli",
  135. "inspect_claude_cli",
  136. "configure_connectors",
  137. "show_openloomi_skills",
  138. "run",
  139. ]);
  140. function pluginDataDir() {
  141. if (!existsSync(PLUGIN_DATA_DIR)) {
  142. try {
  143. mkdirSync(PLUGIN_DATA_DIR, { recursive: true });
  144. } catch {
  145. /* non-fatal */
  146. }
  147. }
  148. return PLUGIN_DATA_DIR;
  149. }
  150. function readSavedBinPath() {
  151. try {
  152. const cfg = join(pluginDataDir(), "config.json");
  153. if (!existsSync(cfg)) return null;
  154. const txt = readFileSync(cfg, "utf8");
  155. const j = JSON.parse(txt);
  156. if (typeof j?.binPath === "string" && existsSync(j.binPath)) {
  157. return j.binPath;
  158. }
  159. } catch {
  160. /* ignore */
  161. }
  162. return null;
  163. }
  164. function saveBinPath(p) {
  165. try {
  166. const cfg = join(pluginDataDir(), "config.json");
  167. writeFileSync(
  168. cfg,
  169. JSON.stringify({ binPath: p, savedAt: Date.now() }, null, 2),
  170. );
  171. } catch {
  172. /* non-fatal */
  173. }
  174. }
  175. // ---------------------------------------------------------------------------
  176. // Tiny utilities
  177. // ---------------------------------------------------------------------------
  178. const isTTY = !!process.stdout.isTTY;
  179. function out(obj, exitCode = 0) {
  180. process.stdout.write(JSON.stringify(obj, null, 2) + EOL);
  181. if (exitCode !== 0) process.exit(exitCode);
  182. }
  183. function err(code, msg, extra = {}) {
  184. out({ ok: false, code, error: msg, ...extra }, 1);
  185. }
  186. function sleep(ms) {
  187. return new Promise((r) => setTimeout(r, ms));
  188. }
  189. // Format a millisecond duration as a compact "Ns" string for status lines.
  190. // `ms <= 0` returns "0s"; values up to ~540s render as integer seconds; beyond
  191. // that we fall back to "XmYYs" so the line still fits on a terminal.
  192. function formatMs(ms) {
  193. const total = Math.max(0, Math.floor(ms / 1000));
  194. if (total < 60) return `${total}s`;
  195. if (total < 600) {
  196. const m = Math.floor(total / 60);
  197. const s = total % 60;
  198. return s ? `${m}m${s}s` : `${m}m`;
  199. }
  200. const m = Math.floor(total / 60);
  201. const s = total % 60;
  202. return `${m}m${s.toString().padStart(2, "0")}s`;
  203. }
  204. // Throttled live-progress writer for the setup wizard. Returns a function
  205. // the caller invokes periodically (e.g. once per poll iteration). At most
  206. // one line per stage per second is emitted, on stderr so the JSON payload
  207. // on stdout stays parseable.
  208. //
  209. // `stage` — short human-readable label, e.g. "wait_api".
  210. // `startedAt` — Date.now() when the stage began. The returned ticker also
  211. // handles a synthetic "0 s / max Z s …" first beat so the
  212. // user sees feedback within ~1 s of starting a long stage.
  213. //
  214. // The returned function is safe to call from a tight loop; it does its own
  215. // throttling and never throws.
  216. function makeStageTicker(stage, budgetMs) {
  217. if (!Number.isFinite(budgetMs) || budgetMs <= 0) {
  218. return () => {}; // negative budget = no-op ticker
  219. }
  220. const startedAt = Date.now();
  221. // Prime the throttle slot so the first non-zero tick is emitted.
  222. _lastProgressSecond[stage] = -1;
  223. return function tick({ force = false } = {}) {
  224. const elapsedMs = Date.now() - startedAt;
  225. const sec = Math.floor(elapsedMs / 1000);
  226. if (!force && _lastProgressSecond[stage] === sec) return;
  227. _lastProgressSecond[stage] = sec;
  228. const label = STAGE_LABELS[stage] || stage;
  229. try {
  230. process.stderr.write(
  231. ` \u00b7 ${label} (${formatMs(elapsedMs)} / max ${formatMs(budgetMs)}) \u2026\n`,
  232. );
  233. } catch {
  234. /* non-fatal: stderr may be piped */
  235. }
  236. };
  237. }
  238. // Stable, safe-to-print human labels for the stages used by the wizard.
  239. const STAGE_LABELS = Object.freeze({
  240. install: "installing OpenLoomi",
  241. launch: "launching desktop app",
  242. wait_api: "waiting for local API",
  243. permission_grace: "waiting on macOS permission prompt",
  244. });
  245. // ---------------------------------------------------------------------------
  246. // Network retry helper
  247. //
  248. // `fetchWithRetry(url, init, opts)` is a thin wrapper around `fetch` that
  249. // retries on transient failures:
  250. //
  251. // * network errors (fetch threw, e.g. ECONNRESET / "fetch failed")
  252. // * per-attempt timeouts (our AbortController fired)
  253. // * HTTP 5xx
  254. // * HTTP 429 (honoring Retry-After when present)
  255. //
  256. // Non-retryable:
  257. // * HTTP 4xx other than 429 — the server actively rejected the request
  258. // * AbortError caused by an *external* caller signal (init.signal) — we
  259. // don't override the caller's intent to cancel.
  260. //
  261. // Backoff is exponential with full jitter, capped at `maxDelayMs`. Defaults
  262. // give 3 total attempts (initial + 2 retries) with 250 ms / 750 ms sleeps,
  263. // adding at most ~1 s of latency in the worst case. Each attempt has its
  264. // own `timeoutMs` budget, so a 5 s timeout means a hard ceiling of ~15 s
  265. // per call across all attempts.
  266. //
  267. // Designed for the local OpenLoomi API (127.0.0.1), where brief hiccups
  268. // are common during desktop-app launches. The helper is dependency-free
  269. // and safe to use from any of the existing call sites.
  270. // ---------------------------------------------------------------------------
  271. const DEFAULT_RETRY_BASE_DELAY_MS = 250;
  272. const DEFAULT_RETRY_MAX_DELAY_MS = 2000;
  273. const DEFAULT_RETRY_ATTEMPTS = 2; // initial + 2 retries = 3 total
  274. function defaultIsRetryable({ status, error }) {
  275. if (error) {
  276. // External caller-initiated aborts are not transient.
  277. if (error.name === "AbortError" && error.__external) return false;
  278. return true; // network error / our-internal timeout
  279. }
  280. if (status === 429) return true;
  281. if (status >= 500 && status < 600) return true;
  282. return false;
  283. }
  284. // Pick a Retry-After value from a Response (seconds or HTTP-date), or null.
  285. // Spec: https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.3
  286. function readRetryAfterMs(res) {
  287. const v = res?.headers?.get?.("retry-after");
  288. if (!v) return null;
  289. const asNum = Number(v);
  290. if (Number.isFinite(asNum)) return Math.max(0, asNum * 1000);
  291. const asDate = Date.parse(v);
  292. if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now());
  293. return null;
  294. }
  295. function computeBackoffMs(attempt, baseDelayMs, maxDelayMs) {
  296. // attempt is 1-based: 1 -> base, 2 -> 2*base, ...
  297. const exp = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
  298. // Full jitter: pick a random value in [baseDelayMs, exp] so a thundering
  299. // herd of plugins retrying in lockstep doesn't synchronize. Lower bound
  300. // stays at baseDelayMs so we still back off meaningfully on attempt 1.
  301. const lo = Math.min(baseDelayMs, exp);
  302. return lo + Math.floor(Math.random() * Math.max(1, exp - lo));
  303. }
  304. async function fetchWithRetry(url, init = {}, opts = {}) {
  305. const {
  306. timeoutMs,
  307. retries = DEFAULT_RETRY_ATTEMPTS,
  308. baseDelayMs = DEFAULT_RETRY_BASE_DELAY_MS,
  309. maxDelayMs = DEFAULT_RETRY_MAX_DELAY_MS,
  310. isRetryable = defaultIsRetryable,
  311. onRetry,
  312. sleepFn = sleep,
  313. } = opts;
  314. const externalSignal = init.signal || null;
  315. const maxAttempts = Math.max(1, retries + 1);
  316. let lastError = null;
  317. let lastStatus = 0;
  318. for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
  319. // Per-attempt controller. If we time out, the AbortError carries our
  320. // internal reason so defaultIsRetryable knows to retry it.
  321. const ctrl = new AbortController();
  322. const onExternalAbort = () => ctrl.abort();
  323. if (externalSignal) {
  324. if (externalSignal.aborted) {
  325. const e = new Error("aborted");
  326. e.name = "AbortError";
  327. e.__external = true;
  328. throw e;
  329. }
  330. externalSignal.addEventListener("abort", onExternalAbort, {
  331. once: true,
  332. });
  333. }
  334. let timer = null;
  335. if (Number.isFinite(timeoutMs) && timeoutMs > 0) {
  336. timer = setTimeout(() => {
  337. const e = new Error(`request timed out after ${timeoutMs}ms`);
  338. e.name = "AbortError";
  339. e.__external = false;
  340. ctrl.abort();
  341. }, timeoutMs);
  342. }
  343. try {
  344. const res = await fetch(url, { ...init, signal: ctrl.signal });
  345. lastStatus = res.status;
  346. if (
  347. !isRetryable({ status: res.status, error: null }) ||
  348. attempt === maxAttempts
  349. ) {
  350. return res;
  351. }
  352. // Retryable HTTP status — back off and try again.
  353. const retryAfter = readRetryAfterMs(res);
  354. const delayMs =
  355. retryAfter ?? computeBackoffMs(attempt, baseDelayMs, maxDelayMs);
  356. if (typeof onRetry === "function") {
  357. try {
  358. onRetry({ attempt, delayMs, reason: `http_${res.status}` });
  359. } catch {
  360. /* non-fatal */
  361. }
  362. }
  363. // Drain the body so the underlying socket can be reused / closed cleanly.
  364. try {
  365. await res.arrayBuffer();
  366. } catch {
  367. /* ignore */
  368. }
  369. await sleepFn(delayMs);
  370. continue;
  371. } catch (error) {
  372. lastError = error;
  373. const retryable = isRetryable({ status: 0, error });
  374. if (!retryable || attempt === maxAttempts) {
  375. throw error;
  376. }
  377. const delayMs = computeBackoffMs(attempt, baseDelayMs, maxDelayMs);
  378. if (typeof onRetry === "function") {
  379. try {
  380. onRetry({
  381. attempt,
  382. delayMs,
  383. reason: error?.name === "AbortError" ? "timeout" : "network",
  384. });
  385. } catch {
  386. /* non-fatal */
  387. }
  388. }
  389. await sleepFn(delayMs);
  390. continue;
  391. } finally {
  392. if (timer) clearTimeout(timer);
  393. if (externalSignal) {
  394. externalSignal.removeEventListener("abort", onExternalAbort);
  395. }
  396. }
  397. }
  398. // Unreachable: the loop above always either returns or throws. Defensive
  399. // throw so callers can rely on this function never resolving to undefined.
  400. if (lastError) throw lastError;
  401. const e = new Error(
  402. `fetch failed after ${maxAttempts} attempts (status ${lastStatus})`,
  403. );
  404. e.__lastStatus = lastStatus;
  405. throw e;
  406. }
  407. // Compose the per-stage + global budgets from CLI args. Each per-stage flag
  408. // wins; otherwise we fall back to the legacy `--max-wait` (so existing
  409. // callers keep working unchanged), and finally to the documented default.
  410. //
  411. // Returns: { installMs, launchMs, apiMs, permissionMs, totalMs }
  412. // - totalMs is the global cap; the wizard short-circuits when (sum of
  413. // elapsed across all stages) > totalMs.
  414. function readStageTimeouts(args) {
  415. const totalMs = Number(args["max-wait"] || SETUP_MAX_WAIT_DEFAULT_MS);
  416. const num = (v, fallback) => {
  417. const n = Number(v);
  418. return Number.isFinite(n) && n > 0 ? n : fallback;
  419. };
  420. const apiMs = num(
  421. args["api-timeout"] ?? args["api-timeout-ms"],
  422. num(args["max-wait"], DEFAULT_API_TIMEOUT_MS),
  423. );
  424. const installMs = num(
  425. args["install-timeout"] ?? args["install-timeout-ms"],
  426. num(args["max-wait"], DEFAULT_INSTALL_TIMEOUT_MS),
  427. );
  428. const launchMs = num(
  429. args["launch-timeout"] ?? args["launch-timeout-ms"],
  430. DEFAULT_LAUNCH_TIMEOUT_MS,
  431. );
  432. const permissionMs = num(
  433. args["permission-timeout"] ?? args["permission-timeout-ms"],
  434. DEFAULT_PERMISSION_GRACE_MS,
  435. );
  436. return { installMs, launchMs, apiMs, permissionMs, totalMs };
  437. }
  438. // Compose a concrete `/openloomi:setup --yes ...` resume command for an
  439. // install failure. The install timeout flag is raised to a level that
  440. // comfortably covers a slow 50 Mbps download so the user's retry doesn't
  441. // hit the same wall.
  442. function installResumeCommand() {
  443. const tuned = Math.max(DEFAULT_INSTALL_TIMEOUT_MS, 600_000);
  444. return `/openloomi:setup --yes --install-timeout ${tuned}`;
  445. }
  446. // Map a non-OK install result to a stable, human `message` and at least
  447. // one concrete next action in `hints[]`. Resumable cases additionally
  448. // receive `canResume: true` and a pre-built `resumeCommand` so the chat
  449. // layer doesn't have to invent the flags.
  450. //
  451. // Covers at minimum the codes the platform helpers can emit today:
  452. // EXIT_22, EXIT_28, EXIT_35, INSTALL_TIMEOUT / TIMEOUT,
  453. // SPAWN_FAILED, INSTALL_SCRIPT_MISSING, NON_INTERACTIVE_REQUIRES_YES,
  454. // CANCELLED, and a generic `EXIT_*` fallback.
  455. //
  456. // `result.elapsedMs` (when present) is preserved; `result.stdout` /
  457. // `result.stderr` are preserved as-is so the chat layer can echo the
  458. // raw helper output if it wants to. Already-populated `message` /
  459. // `hints` on `result` win so callers can override.
  460. function installErrorGuidance(result) {
  461. const code = result?.code || "EXIT_NONZERO";
  462. const baseHints = [
  463. "Re-run /openloomi:setup to retry — already-completed steps will be skipped.",
  464. ];
  465. // Allow callers to seed either field; we only fill in what's missing.
  466. const out = {
  467. code,
  468. message: typeof result?.message === "string" ? result.message : null,
  469. hints:
  470. Array.isArray(result?.hints) && result.hints.length > 0
  471. ? result.hints.slice()
  472. : null,
  473. canResume: typeof result?.canResume === "boolean" ? result.canResume : true,
  474. resumeCommand: result?.resumeCommand || installResumeCommand(),
  475. };
  476. switch (code) {
  477. case "EXIT_22": {
  478. if (!out.message) {
  479. out.message =
  480. "The GitHub asset server returned an HTTP error (curl exit 22). The release may not exist, your network blocked the CDN, or a rate limit was hit.";
  481. }
  482. out.hints = out.hints || [
  483. "If you are on a corporate network, see https://openloomi.ai/docs/install/restricted-network.",
  484. "Pin a known-good release with OPENLOOMI_VERSION=vX.Y.Z and re-run /openloomi:setup.",
  485. "Pre-stage a local bundle: export OPENLOOMI_DMG_PATH=/path/to/file.dmg (mac) and re-run setup.",
  486. ...baseHints,
  487. ];
  488. break;
  489. }
  490. case "EXIT_28": {
  491. if (!out.message) {
  492. out.message =
  493. "The download timed out (curl exit 28). The connection is too slow or unstable to complete the asset transfer within the current budget.";
  494. }
  495. out.hints = out.hints || [
  496. `Re-run /openloomi:setup --yes --install-timeout ${Math.max(DEFAULT_INSTALL_TIMEOUT_MS, 600_000)} to give the download more time.`,
  497. "If you are on a slow or metered connection, see https://openloomi.ai/docs/install/restricted-network.",
  498. "Pre-stage a local bundle with OPENLOOMI_DMG_PATH (mac) or --offline <path> and re-run setup.",
  499. ];
  500. break;
  501. }
  502. case "EXIT_35": {
  503. if (!out.message) {
  504. out.message =
  505. "TLS handshake to the asset CDN failed (curl exit 35). Your network may require a corporate CA bundle or a TLS-inspection proxy.";
  506. }
  507. out.hints = out.hints || [
  508. "If you are behind a corporate proxy or TLS inspection, see https://openloomi.ai/docs/install/restricted-network.",
  509. "Set NODE_EXTRA_CA_CERTS=/path/to/corp-ca.pem (or add the CA via macOS Profiles) and re-run setup.",
  510. "Pre-stage a local bundle with OPENLOOMI_DMG_PATH (mac) or --offline <path> and re-run setup.",
  511. ...baseHints,
  512. ];
  513. break;
  514. }
  515. case "INSTALL_TIMEOUT":
  516. case "TIMEOUT": {
  517. const ms =
  518. Number.isFinite(result?.budgetMs) && result.budgetMs > 0
  519. ? `${result.budgetMs}ms`
  520. : `${DEFAULT_INSTALL_TIMEOUT_MS}ms`;
  521. if (!out.message) {
  522. out.message = `Install exceeded the time budget (${ms}).`;
  523. }
  524. out.hints = out.hints || [
  525. `Re-run /openloomi:setup --yes --install-timeout ${Math.max(DEFAULT_INSTALL_TIMEOUT_MS, 600_000)} to give the download more time.`,
  526. "If you are on a slow or metered connection, see https://openloomi.ai/docs/install/restricted-network.",
  527. ];
  528. break;
  529. }
  530. case "SPAWN_FAILED": {
  531. if (!out.message) {
  532. out.message =
  533. "Could not start the platform install helper. Make sure bash (macOS/Linux) or PowerShell (Windows) is on PATH.";
  534. }
  535. out.hints = out.hints || [
  536. "Verify that bash (macOS/Linux) or PowerShell (Windows) is on PATH.",
  537. "Re-run /openloomi:setup --yes from a regular terminal session.",
  538. ];
  539. break;
  540. }
  541. case "INSTALL_SCRIPT_MISSING": {
  542. if (!out.message) {
  543. out.message = "No install script shipped for this platform.";
  544. }
  545. out.hints = out.hints || [
  546. "Visit https://openloomi.ai/docs/install and follow the manual steps.",
  547. "Re-run /openloomi:setup from inside the plugin directory so the helper scripts are reachable.",
  548. ];
  549. break;
  550. }
  551. case "CANCELLED":
  552. case "NON_INTERACTIVE_REQUIRES_YES": {
  553. out.hints = out.hints || [
  554. "Re-run /openloomi:setup --yes to pre-approve the install in non-interactive shells.",
  555. ];
  556. break;
  557. }
  558. default: {
  559. // Generic EXIT_<n> / unknown code
  560. const numeric = String(code).replace(/^EXIT_/, "");
  561. if (!out.message) {
  562. out.message = `Install exited with code ${numeric}.`;
  563. }
  564. out.hints = out.hints || [
  565. "See the install helper's stderr output (printed above) for details.",
  566. "If you are behind a corporate proxy, see https://openloomi.ai/docs/install/restricted-network.",
  567. ...baseHints,
  568. ];
  569. }
  570. }
  571. return out;
  572. }
  573. // Build the actionable hints list for an API timeout. Order is deliberate:
  574. // the most likely cause goes first so it survives any UI truncation.
  575. // All entries are safe to print verbatim — no secrets, no installation
  576. // paths the user shouldn't see.
    • Note: Quoted as data in code: Tells the agent to keep something from the user
    • Line 612 on GitHub
  577. function apiNotReadyHints({ stage, platformName, canResume }) {
  578. const hints = [];
  579. if (platformName === "macos" || /darwin/i.test(String(process.platform))) {
  580. hints.push(
  581. "If macOS is showing a permission prompt for OpenLoomi, approve it and run /openloomi:setup again.",
  582. );
  583. }
  584. hints.push("Run /openloomi:setup --max-wait 180000 to give it more time.");
  585. hints.push(
  586. "If you are offline or behind a corporate proxy, see https://openloomi.ai/docs/install/restricted-network.",
  587. );
  588. if (canResume) {
  589. hints.push(
  590. "Re-run /openloomi:setup to keep waiting — already-completed steps will be skipped.",
  591. );
  592. }
  593. return hints;
  594. }
  595. function detectPlatform() {
  596. const p = platform();
  597. if (p === "darwin") return "macos";
  598. if (p === "win32") return "windows";
  599. return "linux";
  600. }
  601. function envBool(v) {
  602. if (v == null) return false;
  603. const s = String(v).toLowerCase().trim();
  604. return s === "1" || s === "true" || s === "yes";
  605. }
  606. function normPath(p) {
  607. if (!p) return null;
  608. return p.endsWith("/") || p.endsWith("\\") ? p.replace(/[\\/]+$/, "") : p;
  609. }
  610. // ---------------------------------------------------------------------------
  611. // Argv parsing (tiny, no deps)
  612. // ---------------------------------------------------------------------------
  613. function parseArgs(argv) {
  614. const out = { _: [] };
  615. for (let i = 0; i < argv.length; i++) {
  616. const a = argv[i];
  617. if (a.startsWith("--")) {
  618. const key = a.slice(2);
  619. const next = argv[i + 1];
  620. if (next === undefined || next.startsWith("--")) {
  621. out[key] = true;
  622. } else {
  623. out[key] = next;
  624. i++;
  625. }
  626. } else {
  627. out._.push(a);
  628. }
  629. }
  630. return out;
  631. }
  632. // ---------------------------------------------------------------------------
  633. // Path resolution & discovery
  634. // ---------------------------------------------------------------------------
  635. function isExecutable(p) {
  636. try {
  637. const st = statSync(p);
  638. return st.isFile();
  639. } catch {
  640. return false;
  641. }
  642. }
  643. // Platform default locations for the OpenLoomi **main binary** (`openloomi`).
  644. // This is the Tauri desktop app — what users actually launch. The bridge
  645. // always discovers and invokes `openloomi`; an internal helper CLI bundled
  646. // alongside it is reached transparently via the runtime's own entry point.
  647. function packageDefaults() {
  648. const home = homedir();
  649. switch (detectPlatform()) {
  650. case "macos":
  651. return [
  652. // Standard macOS install (where Drag-to-Applications puts it).
  653. // We deliberately do NOT also look at ~/Applications — the user
  654. // installed OpenLoomi system-wide and we want a single source of
  655. // truth (/Applications) so the bridge never disagrees with the
  656. // desktop app about where the bundle lives.
  657. "/Applications/OpenLoomi.app/Contents/MacOS/openloomi",
  658. ];
  659. case "windows":
  660. return [
  661. join(
  662. process.env.LOCALAPPDATA || join(home, "AppData", "Local"),
  663. "OpenLoomi",
  664. "openloomi.exe",
  665. ),
  666. ];
  667. default:
  668. return [
  669. join(home, ".local", "bin", "openloomi"),
  670. "/opt/openloomi/openloomi",
  671. "/usr/local/bin/openloomi",
  672. ];
  673. }
  674. }
  675. // Detect whether the user-visible OpenLoomi desktop app is installed.
  676. // We treat the *desktop app* (OpenLoomi.app on macOS, etc.) as the install
  677. // signal, not the helper CLI's filename — users know "OpenLoomi", not the
  678. // internal binary name. This way, a brand-new install where the app is
  679. // This way, a brand-new install where the app is present but the ctl hasn't
  680. // been laid down yet is reported as `installed: true / reason:
  681. // OPENLOOMI_NOT_FINALIZED` instead of `installed: false / OPENLOOMI_NOT_INSTALLED`.
  682. function detectDesktopInstalled() {
  683. const home = homedir();
  684. switch (detectPlatform()) {
  685. case "macos":
  686. // System-wide /Applications only. We do NOT fall back to
  687. // ~/Applications — the bridge and the desktop app must agree on
  688. // a single install location.
  689. {
  690. const marker = "/Applications/OpenLoomi.app";
  691. if (existsSync(marker)) return { installed: true, marker };
  692. }
  693. return { installed: false, marker: null };
  694. case "windows": {
  695. const roots = [
  696. process.env.LOCALAPPDATA || join(home, "AppData", "Local"),
  697. process.env.PROGRAMFILES || "C:\\Program Files",
  698. ];
  699. for (const root of roots) {
  700. for (const marker of [
  701. join(root, "OpenLoomi"),
  702. join(root, "OpenLoomi", "OpenLoomi.exe"),
  703. ]) {
  704. if (existsSync(marker)) return { installed: true, marker };
  705. }
  706. }
  707. return { installed: false, marker: null };
  708. }
  709. default:
  710. for (const marker of [
  711. "/opt/openloomi",
  712. join(home, ".local", "share", "openloomi"),
  713. join(home, ".local", "share", "applications", "openloomi.desktop"),
  714. ]) {
  715. if (existsSync(marker)) return { installed: true, marker };
  716. }
  717. return { installed: false, marker: null };
  718. }
  719. }
  720. function expandHome(p) {
  721. if (!p) return p;
  722. if (p === "~") return homedir();
  723. if (p.startsWith("~/")) return homedir() + p.slice(1);
  724. if (p.startsWith("~\\")) return homedir() + p.slice(2);
  725. return p;
  726. }
  727. function lookupOnPath(name, pathEnv = process.env.PATH || "") {
  728. const exts =
  729. detectPlatform() === "windows" ? [".exe", ".cmd", ".bat", ""] : [""];
  730. for (const dir of pathEnv.split(delimiter).filter(Boolean)) {
  731. for (const ext of exts) {
  732. const candidate = join(dir, name + ext);
  733. if (isExecutable(candidate)) return candidate;
  734. }
  735. }
  736. return null;
  737. }
  738. // Look for the OpenLoomi main binary inside a known install layout. We
  739. // search for the Tauri main binary only; the bridge does not depend on
  740. // the layout of any internal helper CLI the runtime may bundle.
  741. function searchInstallRoot(root) {
  742. if (!root) return null;
  743. const exe = detectPlatform() === "windows" ? "openloomi.exe" : "openloomi";
  744. const candidates = [
  745. join(root, exe),
  746. join(root, "Contents", "MacOS", exe), // macOS bundle
  747. join(root, "bin", exe), // Linux packaging
  748. ];
  749. for (const c of candidates) {
  750. if (isExecutable(c)) return c;
  751. }
  752. return null;
  753. }
  754. // Look for the OpenLoomi main binary inside a source checkout. The Tauri
  755. // main binary lives in `target/release/`.
  756. function searchRepoLayout(root) {
  757. if (!root) return null;
  758. const exe = detectPlatform() === "windows" ? "openloomi.exe" : "openloomi";
  759. const candidates = [
  760. join(root, "apps", "web", "src-tauri", "target", "release", exe),
  761. ];
  762. for (const c of candidates) {
  763. if (isExecutable(c)) return c;
  764. }
  765. return null;
  766. }
  767. // Given a binary path, returns the parent .app bundle if the binary lives
  768. // inside one (e.g. /Applications/OpenLoomi.app/Contents/MacOS/openloomi
  769. // → /Applications/OpenLoomi.app). Returns null otherwise. Used so callers
  770. // have a stable bundle path for `open -a` regardless of how discovery
  771. // resolved the inner binary.
  772. function desktopBundleForBin(binPath) {
  773. if (!binPath) return null;
  774. // Walk up from Contents/MacOS/<exe> to Contents to <App>.app.
  775. const macos = dirname(binPath); // Contents/MacOS
  776. const contents = dirname(macos); // Contents
  777. const bundle = dirname(contents); // <App>.app
  778. if (!bundle || bundle === "." || bundle === contents) return null;
  779. if (!bundle.endsWith(".app")) return null;
  780. // Sanity check: Info.plist must exist for this to be a real bundle.
  781. if (!existsSync(join(bundle, "Contents", "Info.plist"))) return null;
  782. return bundle;
  783. }
  784. function discovery({ explicit = null } = {}) {
  785. // Step 1: OPENLOOMI_BIN
  786. if (process.env.OPENLOOMI_BIN && isExecutable(process.env.OPENLOOMI_BIN)) {
  787. return {
  788. binPath: normPath(process.env.OPENLOOMI_BIN),
  789. mode: "env",
  790. source: "OPENLOOMI_BIN",
  791. };
  792. }
  793. // Step 2: OPENLOOMI_HOME / OPENLOOMI_INSTALL_DIR
  794. for (const k of ["OPENLOOMI_HOME", "OPENLOOMI_INSTALL_DIR"]) {
  795. const v = expandHome(process.env[k]);
  796. const hit = searchInstallRoot(v);
  797. if (hit) return { binPath: normPath(hit), mode: "packaged", source: k };
  798. }
  799. // Step 3: OPENLOOMI_REPO_DIR
  800. if (process.env.OPENLOOMI_REPO_DIR) {
  801. const repoHit = searchRepoLayout(
  802. expandHome(process.env.OPENLOOMI_REPO_DIR),
  803. );
  804. if (repoHit) {
  805. return {
  806. binPath: normPath(repoHit),
  807. mode: "source",
  808. source: "OPENLOOMI_REPO_DIR",
  809. };
  810. }
  811. // Source dir is set but the main binary isn't built yet — return a hint.
  812. const exe = detectPlatform() === "windows" ? "openloomi.exe" : "openloomi";
  813. return {
  814. binPath: null,
  815. mode: "source",
  816. source: "OPENLOOMI_REPO_DIR",
  817. hint: {
  818. repoDir: expandHome(process.env.OPENLOOMI_REPO_DIR),
  819. needed: join("apps", "web", "src-tauri", "target", "release", exe),
  820. },
  821. };
  822. }
  823. // Step 4: PATH lookup for the main `openloomi` binary
  824. const onPath = lookupOnPath(
  825. detectPlatform() === "windows" ? "openloomi.exe" : "openloomi",
  826. );
  827. if (onPath) {
  828. return { binPath: normPath(onPath), mode: "packaged", source: "PATH" };
  829. }
  830. // Step 5: Platform default packaged install paths
  831. for (const def of packageDefaults()) {
  832. if (isExecutable(def)) {
  833. // When the resolved binary lives inside a macOS .app bundle, surface
  834. // the bundle path as desktopMarker so callers can `open -a` it
  835. // without re-deriving the path.
  836. const desktopMarker = desktopBundleForBin(def);
  837. return {
  838. binPath: normPath(def),
  839. mode: "packaged",
  840. source: "platform-default",
  841. desktopInstalled: !!desktopMarker,
  842. desktopMarker,
  843. };
  844. }
  845. }
  846. // Step 6: Saved plugin config
  847. const saved = readSavedBinPath();
  848. if (saved) {
  849. return {
  850. binPath: normPath(saved),
  851. mode: "packaged",
  852. source: "saved-config",
  853. };
  854. }
  855. // Step 7: User-provided --bin-path
  856. if (explicit && isExecutable(explicit)) {
  857. return { binPath: normPath(explicit), mode: "packaged", source: "flag" };
  858. }
  859. // Step 8: No main `openloomi` binary found via the explicit paths above.
  860. // Still detect whether the OpenLoomi desktop app itself is present. If it
  861. // is, try to derive the binary path from the install marker — many users
  862. // have `OpenLoomi.app` in /Applications but the inner main binary lives
  863. // under Contents/MacOS and isn't always on PATH.
  864. const desktop = detectDesktopInstalled();
  865. if (desktop.installed) {
  866. const exe = detectPlatform() === "windows" ? "openloomi.exe" : "openloomi";
  867. const candidate = join(desktop.marker, "Contents", "MacOS", exe);
  868. const winCandidate = join(desktop.marker, exe);
  869. const bin = isExecutable(candidate)
  870. ? candidate
  871. : isExecutable(winCandidate)
  872. ? winCandidate
  873. : null;
  874. if (bin) {
  875. return {
  876. binPath: normPath(bin),
  877. mode: "packaged",
  878. source: "desktop-marker",
  879. desktopInstalled: true,
  880. desktopMarker: desktop.marker,
  881. };
  882. }
  883. return {
  884. binPath: null,
  885. mode: "packaged",
  886. source: "desktop-only",
  887. desktopInstalled: true,
  888. desktopMarker: desktop.marker,
  889. };
  890. }
  891. return {
  892. binPath: null,
  893. mode: "unconfigured",
  894. source: null,
  895. desktopInstalled: false,
  896. desktopMarker: null,
  897. };
  898. }
  899. async function runBin(
  900. binPath,
  901. args,
  902. { stdin = null, timeoutMs = 120_000, env = process.env, shell = false } = {},
  903. ) {
  904. return await new Promise((resolve) => {
  905. let stdout = "";
  906. let stderr = "";
  907. let resolved = false;
  908. const child = spawn(binPath, args, {
  909. stdio: ["pipe", "pipe", "pipe"],
  910. env,
  911. shell,
  912. windowsHide: true,
  913. });
  914. const timer = setTimeout(() => {
  915. if (!resolved) {
  916. resolved = true;
  917. try {
  918. child.kill("SIGKILL");
  919. } catch {
  920. /* noop */
  921. }
  922. resolve({
  923. ok: false,
  924. error: {
  925. code: "timeout",
  926. message: `helper timed out after ${timeoutMs}ms`,
  927. },
  928. });
  929. }
  930. }, timeoutMs);
  931. child.stdout.on("data", (b) => (stdout += b.toString("utf8")));
  932. child.stderr.on("data", (b) => (stderr += b.toString("utf8")));
  933. child.on("error", (e) => {
  934. if (resolved) return;
  935. resolved = true;
  936. clearTimeout(timer);
  937. resolve({
  938. ok: false,
  939. error: { code: "spawn_failed", message: String(e?.message || e) },
  940. stderr,
  941. });
  942. });
  943. child.on("exit", (code, signal) => {
  944. if (resolved) return;
  945. resolved = true;
  946. clearTimeout(timer);
  947. if (code === 0) {
  948. resolve({ ok: true, stdout, stderr });
  949. } else {
  950. resolve({
  951. ok: false,
  952. error: { code: `exit_${code ?? signal ?? "unknown"}` },
  953. stdout,
  954. stderr,
  955. });
  956. }
  957. });
  958. if (stdin != null) {
  959. try {
  960. child.stdin.end(stdin);
  961. } catch {
  962. /* noop */
  963. }
  964. } else {
  965. try {
  966. child.stdin.end();
  967. } catch {
  968. /* noop */
  969. }
  970. }
  971. });
  972. }
  973. function getClaudeCliProbePath() {
  974. const home = homedir();
  975. const dirs = [process.env.PATH || ""];
  976. if (detectPlatform() === "windows") {
  977. dirs.push(
  978. join(home, "AppData", "Roaming", "npm"),
  979. join(home, "AppData", "Local", "Programs", "nodejs"),
  980. join(home, ".volta", "bin"),
  981. "C:\\Program Files\\nodejs",
  982. "C:\\Program Files (x86)\\nodejs",
  983. );
  984. } else {
  985. dirs.push(
  986. "/usr/local/bin",
  987. "/opt/homebrew/bin",
  988. join(home, ".local", "bin"),
  989. join(home, ".npm-global", "bin"),
  990. join(home, ".volta", "bin"),
  991. join(home, "code", "node", "npm_global", "bin"),
  992. );
  993. }
  994. return Array.from(new Set(dirs.filter(Boolean))).join(delimiter);
  995. }
  996. function resolveClaudeCliPath() {
  997. const explicit = expandHome(process.env.CLAUDE_CODE_PATH);
  998. if (explicit) {
  999. if (isExecutable(explicit)) {
  1000. return {
  1001. path: normPath(explicit),
  1002. source: "CLAUDE_CODE_PATH",
  1003. reason: "CLAUDE_CLI_FOUND",
  1004. };
  1005. }
  1006. return {
  1007. path: null,
  1008. source: "CLAUDE_CODE_PATH",
  1009. reason: "CLAUDE_CODE_PATH_INVALID",
  1010. };
  1011. }
  1012. const pathEnv = getClaudeCliProbePath();
  1013. const found = lookupOnPath("claude", pathEnv);
  1014. if (found) {
  1015. return {
  1016. path: normPath(found),
  1017. source: "PATH",
  1018. reason: "CLAUDE_CLI_FOUND",
  1019. };
  1020. }
  1021. return {
  1022. path: null,
  1023. source: null,
  1024. reason: "CLAUDE_CLI_UNAVAILABLE",
  1025. };
  1026. }
  1027. async function runClaudeCli(
  1028. claudePath,
  1029. args,
  1030. { timeoutMs = CLAUDE_CLI_PROBE_TIMEOUT_MS } = {},
  1031. ) {
  1032. if (detectPlatform() === "windows" && /\.ps1$/i.test(claudePath)) {
  1033. return await runBin(
  1034. "powershell.exe",
  1035. [
  1036. "-NoProfile",
  1037. "-ExecutionPolicy",
  1038. "Bypass",
  1039. "-File",
  1040. claudePath,
  1041. ...args,
  1042. ],
  1043. {
  1044. timeoutMs,
  1045. env: { ...process.env, PATH: getClaudeCliProbePath() },
  1046. },
  1047. );
  1048. }
  1049. const shell =
  1050. detectPlatform() === "windows" && /\.(cmd|bat)$/i.test(claudePath);
  1051. return await runBin(claudePath, args, {
  1052. timeoutMs,
  1053. shell,
  1054. env: { ...process.env, PATH: getClaudeCliProbePath() },
  1055. });
  1056. }
  1057. function summarizeCliProbeResult(result) {
  1058. return {
  1059. ok: !!result?.ok,
  1060. code: result?.error?.code || null,
  1061. stdoutPresent: !!result?.stdout,
  1062. stderrPresent: !!result?.stderr,
  1063. };
  1064. }
  1065. function classifyClaudeAuthFailure(result) {
  1066. if (result?.error?.code === "timeout")
  1067. return "CLAUDE_CLI_AUTH_STATUS_TIMEOUT";
  1068. const output =
  1069. `${result?.stdout || ""}\n${result?.stderr || ""}`.toLowerCase();
  1070. if (
  1071. output.includes("not authenticated") ||
  1072. output.includes("not logged") ||
  1073. output.includes("not signed") ||
  1074. output.includes("please login") ||
  1075. output.includes("please log in") ||
  1076. output.includes("sign in") ||
  1077. output.includes("/login")
  1078. ) {
  1079. return "CLAUDE_CLI_AUTH_REQUIRED";
  1080. }
  1081. if (
  1082. output.includes("unknown command") ||
  1083. output.includes("invalid command")
  1084. ) {
  1085. return "CLAUDE_CLI_AUTH_STATUS_UNAVAILABLE";
  1086. }
  1087. // `claude auth status` is a status command; a non-zero exit usually means
  1088. // there is no usable local Claude Code authentication.
  1089. return "CLAUDE_CLI_AUTH_REQUIRED";
  1090. }
  1091. async function probeClaudeNativeRuntime(aiProvider) {
  1092. const defaultAgent =
  1093. typeof aiProvider?.defaultAgent === "string"
  1094. ? aiProvider.defaultAgent
  1095. : null;
  1096. const active = defaultAgent === CLAUDE_NATIVE_PROVIDER;
  1097. if (!active) {
  1098. // The native Claude runtime was intentionally skipped: the configured
  1099. // `defaultAgent` is something other than `claude` (e.g. `codex`) or no
  1100. // agent is configured at all. The host's `claude` CLI may be perfectly
  1101. // healthy — we just don't probe it because it isn't the configured
  1102. // execution provider. Fields are `null` (not `false`) so consumers can
  1103. // distinguish "not probed / not applicable" from "probed and failed",
  1104. // and the reason strings are neutral so they don't read as errors at
  1105. // the top-level setup-status surface.
  1106. return {
  1107. checked: false,
  1108. available: null,
  1109. authenticated: null,
  1110. active: false,
  1111. ready: null,
  1112. reason: defaultAgent
  1113. ? "NATIVE_RUNTIME_NOT_SELECTED"
  1114. : "NATIVE_RUNTIME_NOT_CONFIGURED",
  1115. defaultAgent,
  1116. cliPathPresent: null,
  1117. cliPathSource: null,
  1118. versionPresent: null,
  1119. probes: {},
  1120. };
  1121. }
  1122. const resolved = resolveClaudeCliPath();
  1123. if (!resolved.path) {
  1124. return {
  1125. checked: true,
  1126. available: false,
  1127. authenticated: false,
  1128. active: true,
  1129. ready: false,
  1130. reason: resolved.reason,
  1131. defaultAgent,
  1132. cliPathPresent: false,
  1133. cliPathSource: resolved.source,
  1134. versionPresent: false,
  1135. probes: {},
  1136. nextAction:
  1137. resolved.reason === "CLAUDE_CODE_PATH_INVALID"
  1138. ? "inspect_claude_cli"
  1139. : "install_claude_cli",
  1140. };
  1141. }
  1142. const versionProbe = await runClaudeCli(resolved.path, ["--version"]);
  1143. if (!versionProbe.ok) {
  1144. return {
  1145. checked: true,
  1146. available: false,
  1147. authenticated: false,
  1148. active: true,
  1149. ready: false,
  1150. reason:
  1151. versionProbe?.error?.code === "timeout"
  1152. ? "CLAUDE_CLI_VERSION_TIMEOUT"
  1153. : "CLAUDE_CLI_VERSION_FAILED",
  1154. defaultAgent,
  1155. cliPathPresent: true,
  1156. cliPathSource: resolved.source,
  1157. versionPresent: false,
  1158. probes: {
  1159. version: summarizeCliProbeResult(versionProbe),
  1160. },
  1161. nextAction: "inspect_claude_cli",
  1162. };
  1163. }
  1164. const authProbe = await runClaudeCli(resolved.path, [
  1165. "auth",
  1166. "status",
  1167. "--json",
  1168. ]);
  1169. if (authProbe.ok) {
  1170. return {
  1171. checked: true,
  1172. available: true,
  1173. authenticated: true,
  1174. active: true,
  1175. ready: true,
  1176. reason: "CLAUDE_CLI_AUTHENTICATED",
  1177. defaultAgent,
  1178. cliPathPresent: true,
  1179. cliPathSource: resolved.source,
  1180. versionPresent: !!(versionProbe.stdout || "").trim(),
  1181. probes: {
  1182. version: summarizeCliProbeResult(versionProbe),
  1183. auth: summarizeCliProbeResult(authProbe),
  1184. },
  1185. nextAction: "run",
  1186. };
  1187. }
  1188. const reason = classifyClaudeAuthFailure(authProbe);
  1189. return {
  1190. checked: true,
  1191. available: true,
  1192. authenticated: false,
  1193. active: true,
  1194. ready: false,
  1195. reason,
  1196. defaultAgent,
  1197. cliPathPresent: true,
  1198. cliPathSource: resolved.source,
  1199. versionPresent: !!(versionProbe.stdout || "").trim(),
  1200. probes: {
  1201. version: summarizeCliProbeResult(versionProbe),
  1202. auth: summarizeCliProbeResult(authProbe),
  1203. },
  1204. nextAction:
  1205. reason === "CLAUDE_CLI_AUTH_REQUIRED"
  1206. ? "login_claude_cli"
  1207. : "inspect_claude_cli",
  1208. };
  1209. }
  1210. function getExecutionProviderStatus(aiProvider, nativeRuntime) {
  1211. // `source` is the user-facing label for *how* the runtime is reaching
  1212. // an LLM. A non-Claude `defaultAgent` is already a selected execution
  1213. // runtime and brings its own CLI auth, so it must not be gated on Claude
  1214. // authentication or an Anthropic-compatible API key.
  1215. const defaultAgent =
  1216. typeof aiProvider?.defaultAgent === "string"
  1217. ? aiProvider.defaultAgent
  1218. : null;
  1219. if (defaultAgent && defaultAgent !== CLAUDE_NATIVE_PROVIDER) {
  1220. return {
  1221. ready: true,
  1222. source: `native_${defaultAgent}_runtime`,
  1223. };
  1224. }
  1225. // The HTTP probe (`aiProvider`) reports `configured: true` when EITHER a
  1226. // user-saved `anthropic_compatible` row OR the runtime's own native Claude
  1227. // probe says "ready". Disambiguate those paths for the user-facing label.
  1228. if (aiProvider?.configured) {
  1229. return {
  1230. ready: true,
  1231. source: aiProvider.directApi?.userConfigured
  1232. ? "ai_provider"
  1233. : "native_claude_runtime",
  1234. };
  1235. }
  1236. if (nativeRuntime?.ready) {
  1237. return {
  1238. ready: true,
  1239. source: "native_claude_runtime",
  1240. };
  1241. }
  1242. return {
  1243. ready: false,
  1244. source: null,
  1245. };
  1246. }
  1247. function providerStatusFields(aiProvider, nativeRuntime) {
  1248. const executionProvider = getExecutionProviderStatus(
  1249. aiProvider,
  1250. nativeRuntime,
  1251. );
  1252. // `aiProviderConfigured` is the public "can the runtime talk to an LLM
  1253. // right now" signal. `executionProvider` combines all supported paths:
  1254. // a user-saved API provider, authenticated native Claude, or a selected
  1255. // non-Claude runtime such as Codex/OpenCode/Hermes/OpenClaw.
  1256. return {
  1257. aiProviderConfigured: executionProvider.ready,
  1258. aiProviderStatus:
  1259. aiProvider?.status ||
  1260. (aiProvider?.ok ? "unknown" : aiProvider?.reason || "unknown"),
  1261. executionProviderReady: executionProvider.ready,
  1262. executionProviderSource: executionProvider.source,
  1263. nativeRuntimeActive: !!nativeRuntime?.active,
  1264. nativeRuntimeProvider: nativeRuntime?.defaultAgent || null,
  1265. // Only surface the runtime's reason at the top level when the probe
  1266. // actually ran (`checked: true`). When the runtime was skipped because
  1267. // the user picked a different default agent, the reason is
  1268. // informational and would mislead users (e.g. surface
  1269. // "CLAUDE_RUNTIME_INACTIVE" / "DEFAULT_AGENT_UNAVAILABLE" when nothing
  1270. // is wrong with their setup — they just chose Codex as the execution
  1271. // provider and Claude CLI status isn't on the critical path).
  1272. nativeRuntimeStatus: nativeRuntime?.checked
  1273. ? nativeRuntime?.reason || null
  1274. : null,
  1275. nativeRuntime: {
  1276. // Pass `null` through as `null` instead of `!!`-coercing to `false`
  1277. // so consumers can distinguish "not probed / not applicable" from
  1278. // "probed and failed". `probeClaudeNativeRuntime` already returns
  1279. // `null` for fields it didn't probe.
  1280. checked: nativeRuntime?.checked ?? null,
  1281. available: nativeRuntime?.available ?? null,
  1282. authenticated: nativeRuntime?.authenticated ?? null,
  1283. active: !!nativeRuntime?.active,
  1284. ready: nativeRuntime?.ready ?? null,
  1285. reason: nativeRuntime?.reason || null,
  1286. defaultAgent: nativeRuntime?.defaultAgent || null,
  1287. cliPathPresent: nativeRuntime?.cliPathPresent ?? null,
  1288. cliPathSource: nativeRuntime?.cliPathSource || null,
  1289. versionPresent: nativeRuntime?.versionPresent ?? null,
  1290. probes: nativeRuntime?.probes || {},
  1291. },
  1292. };
  1293. }
  1294. // ---------------------------------------------------------------------------
  1295. // Auth (presence-only)
  1296. // ---------------------------------------------------------------------------
  1297. function readOpenloomiTokenPath() {
  1298. const p = join(homedir(), ".openloomi", "token");
  1299. return existsSync(p) ? p : null;
  1300. }
  1301. function tokenPresent() {
  1302. if (process.env.OPENLOOMI_AUTH_TOKEN) return true;
  1303. return readOpenloomiTokenPath() != null;
  1304. }
  1305. // Mirrors the Tauri runtime's `save_token` (see
  1306. // apps/web/src-tauri/src/storage.rs): base64-encode the bearer and write
  1307. // to `~/.openloomi/token` with 0o600 perms. The directory is created if
  1308. // missing. Returns the on-disk path.
  1309. function saveOpenloomiToken(token) {
  1310. if (typeof token !== "string" || !token.trim()) {
  1311. return { ok: false, code: "EMPTY_TOKEN" };
  1312. }
  1313. const p = join(homedir(), ".openloomi", "token");
  1314. try {
  1315. const dir = dirname(p);
  1316. if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
  1317. const encoded = Buffer.from(token, "utf8").toString("base64");
  1318. writeFileSync(p, encoded, { mode: 0o600 });
  1319. // Belt-and-braces: chmod after the fact too, since some platforms
  1320. // ignore the mode arg on writeFileSync (e.g. when the file already
  1321. // exists with looser perms).
  1322. try {
  1323. chmodSync(p, 0o600);
  1324. } catch {
  1325. /* noop on platforms without chmod */
  1326. }
  1327. return { ok: true, path: p };
  1328. } catch (e) {
  1329. return { ok: false, code: "WRITE_FAILED", error: String(e?.message || e) };
  1330. }
  1331. }
  1332. function loadBearerToken() {
  1333. // Returns the bearer token locally; NEVER prints it.
  1334. // Env-var path returns the raw value (no decode).
  1335. // File path is base64-encoded by the Tauri runtime
  1336. // (see apps/web/src-tauri/src/storage.rs -> save_token / load_token),
  1337. // so we mirror that here: decode once, trim, return.
  1338. const envTok = process.env.OPENLOOMI_AUTH_TOKEN;
  1339. if (envTok && envTok.trim()) return envTok.trim();
  1340. const p = readOpenloomiTokenPath();
  1341. if (!p) return null;
  1342. try {
  1343. const raw = readFileSync(p, "utf8").trim();
  1344. if (!raw) return null;
  1345. // Strict path: token files are always base64(STANDARD). If decode
  1346. // fails, fall back to the raw text — covers any hand-rolled token
  1347. // file a power user might have dropped in before this fix.
  1348. try {
  1349. const decoded = Buffer.from(raw, "base64").toString("utf8").trim();
  1350. // A successful decode of a JWT payload.sig yields the two segments
  1351. // joined with a `.`; if we don't see that, the file was probably
  1352. // not base64-encoded and the raw text is the actual token.
  1353. if (decoded && decoded.includes(".")) return decoded;
  1354. return raw;
  1355. } catch {
  1356. return raw;
  1357. }
  1358. } catch {
  1359. return null;
  1360. }
  1361. }
  1362. // ---------------------------------------------------------------------------
  1363. // Local API
  1364. // ---------------------------------------------------------------------------
  1365. function openloomiBaseUrl() {
  1366. if (process.env.OPENLOOMI_BASE_URL)
  1367. return process.env.OPENLOOMI_BASE_URL.replace(/\/+$/, "");
  1368. return `http://127.0.0.1:${_resolvedPort}`;
  1369. }
  1370. function openloomiProbePorts() {
  1371. return Array.from(
  1372. new Set([_resolvedPort, OPENLOOMI_PORT_DEFAULT, OPENLOOMI_PORT_FALLBACK]),
  1373. );
  1374. }
  1375. // Probes the cached, default, then fallback ports for any HTTP response from
  1376. // /api/remote-auth/user, caches whichever port answered for the
  1377. // lifetime of the process, and returns the resolved base URL. Returns
  1378. // null if neither port responds.
  1379. async function probeOpenLoomiBaseUrl() {
  1380. for (const port of openloomiProbePorts()) {
  1381. const url = `http://127.0.0.1:${port}`;
  1382. const ctrl = new AbortController();
  1383. const t = setTimeout(() => ctrl.abort(), 1500);
  1384. try {
  1385. // 1.5 s per-attempt budget; probe runs once per port (no retry) so a
  1386. // desktop app still booting doesn't burn the whole 5 s budget on the
  1387. // first port before falling through to the fallback.
  1388. const res = await fetchWithRetry(
  1389. `${url}/api/remote-auth/user`,
  1390. { method: "GET", signal: ctrl.signal },
  1391. { timeoutMs: 1500, retries: 0 },
  1392. );
  1393. if (res.status > 0) {
  1394. _resolvedPort = port;
  1395. return url;
  1396. }
  1397. } catch {
  1398. // connection refused / timeout — try the next port
  1399. } finally {
  1400. clearTimeout(t);
  1401. }
  1402. }
  1403. return null;
  1404. }
  1405. async function resolveOpenLoomiBaseUrl() {
  1406. if (process.env.OPENLOOMI_BASE_URL) return openloomiBaseUrl();
  1407. const probed = await probeOpenLoomiBaseUrl();
  1408. return probed || openloomiBaseUrl();
  1409. }
  1410. async function apiGET(path, { timeoutMs = 5000 } = {}) {
  1411. const bearer = loadBearerToken();
  1412. const headers = { Accept: "application/json" };
  1413. if (bearer) headers.Authorization = `Bearer ${bearer}`;
  1414. try {
  1415. const baseUrl = await resolveOpenLoomiBaseUrl();
  1416. const res = await fetchWithRetry(
  1417. baseUrl + path,
  1418. { method: "GET", headers },
  1419. { timeoutMs },
  1420. );
  1421. const text = await res.text().catch(() => "");
  1422. let json = null;
  1423. try {
  1424. json = text ? JSON.parse(text) : null;
  1425. } catch {
  1426. json = { raw: text };
  1427. }
  1428. return { ok: res.ok, status: res.status, json };
  1429. } catch (e) {
  1430. return {
  1431. ok: false,
  1432. status: 0,
  1433. error: { code: "network", message: String(e?.message || e) },
  1434. };
  1435. }
  1436. }
  1437. async function apiPOST(path, body, { timeoutMs = 10_000 } = {}) {
  1438. const bearer = loadBearerToken();
  1439. const headers = {
  1440. "Content-Type": "application/json",
  1441. Accept: "application/json",
  1442. };
  1443. if (bearer) headers.Authorization = `Bearer ${bearer}`;
  1444. try {
  1445. const baseUrl = await resolveOpenLoomiBaseUrl();
  1446. const res = await fetchWithRetry(
  1447. baseUrl + path,
  1448. {
  1449. method: "POST",
  1450. headers,
  1451. body: JSON.stringify(body),
  1452. },
  1453. { timeoutMs },
  1454. );
  1455. const text = await res.text().catch(() => "");
  1456. let json = null;
  1457. try {
  1458. json = text ? JSON.parse(text) : null;
  1459. } catch {
  1460. json = { raw: text };
  1461. }
  1462. return { ok: res.ok, status: res.status, json };
  1463. } catch (e) {
  1464. return {
  1465. ok: false,
  1466. status: 0,
  1467. error: { code: "network", message: String(e?.message || e) },
  1468. };
  1469. }
  1470. }
  1471. async function apiPUT(path, body, { timeoutMs = 10_000 } = {}) {
  1472. // Same contract as apiPOST — Bearer + JSON. Used for the per-user
  1473. // /api/preferences/ai upsert, which is the runtime's source of truth
  1474. // for AI provider config (see apps/web/app/(chat)/api/preferences/ai/route.ts).
  1475. const bearer = loadBearerToken();
  1476. const headers = {
  1477. "Content-Type": "application/json",
  1478. Accept: "application/json",
  1479. };
  1480. if (bearer) headers.Authorization = `Bearer ${bearer}`;
  1481. try {
  1482. const baseUrl = await resolveOpenLoomiBaseUrl();
  1483. const res = await fetchWithRetry(
  1484. baseUrl + path,
  1485. {
  1486. method: "PUT",
  1487. headers,
  1488. body: JSON.stringify(body),
  1489. },
  1490. { timeoutMs },
  1491. );
  1492. const text = await res.text().catch(() => "");
  1493. let json = null;
  1494. try {
  1495. json = text ? JSON.parse(text) : null;
  1496. } catch {
  1497. json = { raw: text };
  1498. }
  1499. return { ok: res.ok, status: res.status, json };
  1500. } catch (e) {
  1501. return {
  1502. ok: false,
  1503. status: 0,
  1504. error: { code: "network", message: String(e?.message || e) },
  1505. };
  1506. }
  1507. }
  1508. // ---------------------------------------------------------------------------
  1509. // Status
  1510. // ---------------------------------------------------------------------------
  1511. // Module-level cache of the last install script's structured stdout line.
  1512. // The install scripts print a single JSON object describing what they
  1513. // installed (version / tag / assetUrl / binPath). We keep it here so
  1514. // `buildStatus` can surface the resolved version without re-curl'ing the
  1515. // GitHub API and without calling --version on the inner Tauri binary
  1516. // (which flashes a GUI window).
  1517. let _installInfo = null;
  1518. function getInstallInfo() {
  1519. return _installInfo;
  1520. }
  1521. function setInstallInfo(info) {
  1522. _installInfo = info;
  1523. }
  1524. // Reads CFBundleShortVersionString from an .app bundle's Info.plist.
  1525. // We deliberately avoid calling --version on the main Tauri binary
  1526. // because it launches the GUI. Info.plist is the canonical, side-
  1527. // effect-free source for the version of a packaged macOS app.
  1528. // Uses `plutil -p` on macOS (always present) and falls back to a
  1529. // minimal binary plist scan if plutil isn't available.
  1530. async function readBundleVersion(appPath) {
  1531. if (!appPath) return null;
  1532. const platformName = detectPlatform();
  1533. if (platformName !== "macos") return null;
  1534. const infoPlist = join(appPath, "Contents", "Info.plist");
  1535. if (!existsSync(infoPlist)) return null;
  1536. // Try plutil first — it prints a stable `key: "value"` text format.
  1537. const r = await runBin("plutil", ["-p", infoPlist], { timeoutMs: 3000 });
  1538. if (r.ok && r.stdout) {
  1539. // plutil output is like: "CFBundleShortVersionString" => "0.9.0"
  1540. // or (older): CFBundleShortVersionString = "0.9.0"
  1541. const m = r.stdout.match(
  1542. /["']?CFBundleShortVersionString["']?\s*(?:=>|=)\s*["']([^"']+)["']/,
  1543. );
  1544. if (m) return m[1].trim();
  1545. }
  1546. // Binary plist fallback: scan for the ASCII run "CFBundleShortVersionString"
  1547. // followed shortly by a UTF-16 string token. This is best-effort; on real
  1548. // installs plutil will always succeed.
  1549. try {
  1550. const raw = readFileSync(infoPlist);
  1551. const ascii = raw.toString("binary");
  1552. const idx = ascii.indexOf("CFBundleShortVersionString");
  1553. if (idx >= 0) {
  1554. // After the key, look for a UTF-16BE string value. Format in binary
  1555. // plist: ...<len-byte><UTF-16BE bytes>. We just grab the next chunk
  1556. // of printable UTF-16.
  1557. const slice = ascii.slice(idx, idx + 256);
  1558. const m2 = slice.match(/[A-Za-z0-9.\-+]+\x00/);
  1559. if (m2) return m2[0].replace(/\x00+$/g, "").trim();
  1560. }
  1561. } catch {
  1562. /* fallthrough */
  1563. }
  1564. return null;
  1565. }
  1566. async function readBinVersion(binPath) {
  1567. if (!binPath) return null;
  1568. // The OpenLoomi main `openloomi` binary launches the GUI app on any CLI
  1569. // invocation, so calling --version would flash a window. For that case,
  1570. // we resolve the version from the .app bundle's Info.plist instead.
  1571. const base = basename(binPath).toLowerCase();
  1572. const isMainTauriBinary = base === "openloomi" || base === "openloomi.exe";
  1573. if (isMainTauriBinary) {
  1574. // Walk up from .../<App>.app/Contents/MacOS/openloomi to .../<App>.app
  1575. const parent = dirname(binPath); // Contents/MacOS
  1576. const grand = dirname(parent); // Contents
  1577. const great = dirname(grand); // <App>.app
  1578. return await readBundleVersion(great);
  1579. }
  1580. // For non-main binaries (e.g. an OPENLOOMI_BIN pointing at a CLI helper),
  1581. // --version is safe and doesn't flash a GUI.
  1582. const r = await runBin(binPath, ["--version"], { timeoutMs: 5000 });
  1583. if (!r.ok) return null;
  1584. // Match a semver-ish version (e.g. "0.9.0", "1.2.3-rc.1") anywhere in
  1585. // the --version output. Real binaries print "<name> 0.9.0"; tests
  1586. // just print "9.9.9" — both should parse.
  1587. const m = (r.stdout || "").match(/(\d+\.\d+\.\d+(?:[-+][\w.\-]+)?)/);
  1588. return m ? m[1].trim() : (r.stdout || "").trim();
  1589. }
  1590. async function probeAiProvider() {
  1591. // The runtime exposes per-user AI settings and the native Claude CLI
  1592. // probe at /api/preferences/ai (apps/web/app/(chat)/api/preferences/ai/
  1593. // route.ts). A provider is "configured" when EITHER:
  1594. // - the runtime reports the user's local `claude` CLI as authenticated
  1595. // (`nativeRuntime.authenticated`), so the runtime can talk to Claude
  1596. // without any per-user key, OR
  1597. // - the user has saved an explicit `anthropic_compatible` row with a key.
  1598. // We never read the AI provider env vars the runtime may have inherited;
  1599. // the runtime's own `nativeRuntime` probe is the source of truth.
  1600. const r = await apiGET("/api/preferences/ai", { timeoutMs: 3000 });
  1601. if (r.ok && r.json) {
  1602. const native = r.json?.nativeRuntime;
  1603. const fromNative = !!(native && native.authenticated);
  1604. const defaultAgent =
  1605. typeof r.json?.defaultAgent === "string" ? r.json.defaultAgent : null;
  1606. const fromUser =
  1607. Array.isArray(r.json?.settings) &&
  1608. r.json.settings.some(
  1609. (s) =>
  1610. s?.providerType === "anthropic_compatible" &&
  1611. s?.enabled !== false &&
  1612. s?.hasApiKey,
  1613. );
  1614. const configured = fromNative || fromUser;
  1615. return {
  1616. ok: true,
  1617. configured,
  1618. status: configured ? "direct_api_configured" : "direct_api_missing",
  1619. defaultAgent,
  1620. directApi: {
  1621. nativeRuntimeAuthenticated: fromNative,
  1622. userConfigured: fromUser,
  1623. },
  1624. };
  1625. }
  1626. if (r.status === 401 || r.status === 403) {
  1627. return {
  1628. ok: true,
  1629. configured: false,
  1630. status: "auth_required",
  1631. reason: "auth_required",
  1632. defaultAgent: null,
  1633. };
  1634. }
  1635. return {
  1636. ok: false,
  1637. configured: false,
  1638. status: "runtime_status_unavailable",
  1639. reason: r.error?.code || "unknown",
  1640. defaultAgent: null,
  1641. };
  1642. }
  1643. async function probeApiReachable() {
  1644. // Tries the default port (3414) first, then the documented fallback
  1645. // (3515). Any HTTP response — including 401 — counts as "reachable";
  1646. // only network errors / timeouts mean the runtime is not running.
  1647. return (await probeOpenLoomiBaseUrl()) !== null;
  1648. }
  1649. async function buildStatus({ json = true, explicit = null } = {}) {
  1650. // AI provider readiness is the runtime's job — the bridge never reads
  1651. // AI provider env vars. The runtime's `/api/preferences/ai` endpoint
  1652. // surfaces `nativeRuntime` (Claude CLI auth probe) and
  1653. // `aiProviderConfigured`, and those are the only signals we trust.
  1654. const disc = discovery({ explicit });
  1655. // Source checkout detected but CLI not yet built: report that BEFORE
  1656. // the generic "!binPath → OPENLOOMI_NOT_INSTALLED" branch.
  1657. if (disc.mode === "source" && disc.hint) {
  1658. return {
  1659. mode: "source",
  1660. installed: false,
  1661. binPath: null,
  1662. version: null,
  1663. tokenPresent: tokenPresent(),
  1664. aiProviderConfigured: false,
  1665. apiReachable: false,
  1666. hooksInstalled: detectHooksInstalled(),
  1667. ready: false,
  1668. nextAction: "build_or_stage_openloomi",
  1669. reason: "SOURCE_FOUND_CLI_NOT_BUILT",
  1670. source: disc.source,
  1671. hint: disc.hint,
  1672. };
  1673. }
  1674. if (!disc.binPath) {
  1675. // ctl is missing. Distinguish "never installed" from "OpenLoomi is
  1676. // there, just hasn't placed the ctl yet" — user-only install detection
  1677. // (OpenLoomi.app present) means we should NOT try to install again.
  1678. const desktop = disc.desktopInstalled || false;
  1679. const apiReachable = await probeApiReachable();
  1680. if (desktop) {
  1681. return {
  1682. mode: disc.mode,
  1683. installed: true,
  1684. binPath: null,
  1685. version: null,
  1686. tokenPresent: tokenPresent(),
  1687. aiProviderConfigured: (await probeAiProvider()).configured,
  1688. apiReachable,
  1689. canGuestLogin: apiReachable,
  1690. hooksInstalled: detectHooksInstalled(),
  1691. ready: false,
  1692. nextAction: "launch_openloomi_to_finalize",
  1693. reason: "OPENLOOMI_NOT_FINALIZED",
  1694. source: disc.source,
  1695. desktopMarker: disc.desktopMarker,
  1696. hint: {
  1697. message:
  1698. "OpenLoomi is installed but the local helper is not yet laid down. Launch the OpenLoomi desktop app once so it can finalize the install, then re-run /openloomi:setup.",
  1699. actions: {
  1700. macos:
  1701. 'open -a "' +
  1702. (disc.desktopMarker || "/Applications/OpenLoomi.app") +
  1703. '"',
  1704. },
  1705. },
  1706. };
  1707. }
  1708. return {
  1709. mode: disc.mode,
  1710. installed: false,
  1711. binPath: null,
  1712. version: null,
  1713. tokenPresent: tokenPresent(),
  1714. aiProviderConfigured: false,
  1715. apiReachable: false,
  1716. canGuestLogin: false,
  1717. hooksInstalled: detectHooksInstalled(),
  1718. ready: false,
  1719. nextAction: "install_openloomi",
  1720. reason: "OPENLOOMI_NOT_INSTALLED",
  1721. source: disc.source,
  1722. hint: disc.hint || null,
  1723. };
  1724. }
  1725. const version = await readBinVersion(disc.binPath);
  1726. // Fall back to the version reported by the install script. We don't
  1727. // want to call --version on the main Tauri binary (it flashes a GUI
  1728. // window) and Info.plist is sometimes stripped from dev builds, so the
  1729. // install-time tag is the most reliable source when both are missing.
  1730. const resolvedVersion = version || getInstallInfo()?.version || null;
  1731. const aiProvider = await probeAiProvider();
  1732. const nativeRuntime = await probeClaudeNativeRuntime(aiProvider);
  1733. const providerFields = providerStatusFields(aiProvider, nativeRuntime);
  1734. const apiReachable = await probeApiReachable();
  1735. if (!tokenPresent()) {
  1736. return {
  1737. mode: disc.mode,
  1738. installed: true,
  1739. binPath: disc.binPath,
  1740. version: resolvedVersion,
  1741. tokenPresent: false,
  1742. ...providerFields,
  1743. apiReachable,
  1744. canGuestLogin: apiReachable,
  1745. hooksInstalled: detectHooksInstalled(),
  1746. ready: false,
  1747. nextAction: "login_openloomi",
  1748. reason: "LOGIN_REQUIRED",
  1749. source: disc.source,
  1750. desktopMarker: disc.desktopMarker,
  1751. };
  1752. }
  1753. if (!aiProvider.configured && nativeRuntime.ready) {
  1754. return {
  1755. mode: disc.mode,
  1756. installed: true,
  1757. binPath: disc.binPath,
  1758. version: resolvedVersion,
  1759. tokenPresent: true,
  1760. ...providerFields,
  1761. apiReachable,
  1762. canGuestLogin: apiReachable,
  1763. hooksInstalled: detectHooksInstalled(),
  1764. ready: true,
  1765. nextAction: "run",
  1766. reason: "READY",
  1767. readinessSource: "native_claude_runtime",
  1768. message:
  1769. "OpenLoomi is ready through the authenticated native Claude Code runtime. A separate Anthropic-compatible API key is not required for native Claude execution.",
  1770. source: disc.source,
  1771. desktopMarker: disc.desktopMarker,
  1772. };
  1773. }
  1774. if (
  1775. !aiProvider.configured &&
  1776. nativeRuntime.active &&
  1777. nativeRuntime.checked &&
  1778. !nativeRuntime.ready
  1779. ) {
  1780. return {
  1781. mode: disc.mode,
  1782. installed: true,
  1783. binPath: disc.binPath,
  1784. version: resolvedVersion,
  1785. tokenPresent: true,
  1786. ...providerFields,
  1787. apiReachable,
  1788. canGuestLogin: apiReachable,
  1789. hooksInstalled: detectHooksInstalled(),
  1790. ready: false,
  1791. nextAction: nativeRuntime.nextAction || "inspect_claude_cli",
  1792. reason: nativeRuntime.reason,
  1793. message:
  1794. nativeRuntime.reason === "CLAUDE_CLI_AUTH_REQUIRED"
  1795. ? "The native Claude runtime is selected, but Claude Code CLI is not authenticated. Run `claude auth login` or configure a direct Anthropic-compatible provider."
  1796. : "The native Claude runtime is selected, but Claude Code CLI readiness could not be confirmed. Install or repair Claude Code CLI, or configure a direct Anthropic-compatible provider.",
  1797. source: disc.source,
  1798. desktopMarker: disc.desktopMarker,
  1799. };
  1800. }
  1801. if (!providerFields.executionProviderReady) {
  1802. return {
  1803. mode: disc.mode,
  1804. installed: true,
  1805. binPath: disc.binPath,
  1806. version: resolvedVersion,
  1807. tokenPresent: true,
  1808. ...providerFields,
  1809. apiReachable,
  1810. canGuestLogin: apiReachable,
  1811. hooksInstalled: detectHooksInstalled(),
  1812. ready: false,
  1813. nextAction: "configure_ai_provider",
  1814. reason: "AI_PROVIDER_REQUIRED",
  1815. source: disc.source,
  1816. desktopMarker: disc.desktopMarker,
  1817. };
  1818. }
  1819. return {
  1820. mode: disc.mode,
  1821. installed: true,
  1822. binPath: disc.binPath,
  1823. version: resolvedVersion,
  1824. tokenPresent: true,
  1825. ...providerFields,
  1826. apiReachable,
  1827. canGuestLogin: apiReachable,
  1828. hooksInstalled: detectHooksInstalled(),
  1829. ready: true,
  1830. nextAction: "run",
  1831. reason: "READY",
  1832. source: disc.source,
  1833. desktopMarker: disc.desktopMarker,
  1834. };
  1835. }
  1836. // ---------------------------------------------------------------------------
  1837. // Hooks install/uninstall (settings merge)
  1838. // ---------------------------------------------------------------------------
  1839. function settingsPath() {
  1840. return join(homedir(), ".claude", "settings.json");
  1841. }
  1842. function readSettings() {
  1843. const p = settingsPath();
  1844. if (!existsSync(p)) return { raw: "{}", json: {}, path: p };
  1845. try {
  1846. const raw = readFileSync(p, "utf8");
  1847. const json = JSON.parse(raw);
  1848. return { raw, json, path: p };
  1849. } catch {
  1850. return { raw: "{}", json: {}, path: p };
  1851. }
  1852. }
  1853. function atomicWriteJson(filePath, jsonObj) {
  1854. const dir = dirname(filePath);
  1855. if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
  1856. const tmp = join(dir, `.${randomUUID()}.tmp`);
  1857. writeFileSync(tmp, JSON.stringify(jsonObj, null, 2));
  1858. renameSync(tmp, filePath);
  1859. }
  1860. function loadHooksTemplate() {
  1861. try {
  1862. const raw = readFileSync(HOOKS_FILE, "utf8");
  1863. return JSON.parse(raw);
  1864. } catch {
  1865. return { hooks: {} };
  1866. }
  1867. }
  1868. // Resolve `${CLAUDE_PLUGIN_ROOT}` placeholders in a hook command to the
  1869. // plugin's absolute path. Claude Code only injects this env var when hooks
  1870. // are loaded directly from a plugin manifest; when we install them into
  1871. // user-level `~/.claude/settings.json` we have to substitute ourselves or
  1872. // the placeholder expands to empty and Node tries to resolve
  1873. // `/scripts/loomi-bridge.mjs` from the filesystem root.
  1874. function substitutePluginRoot(command) {
  1875. if (
  1876. typeof command !== "string" ||
  1877. !command.includes("${CLAUDE_PLUGIN_ROOT}")
  1878. ) {
  1879. return command;
  1880. }
  1881. // Wrap the substituted path in double quotes so paths with spaces parse
  1882. // correctly under the shell. The original template has the placeholder
  1883. // unquoted (e.g. `node ${CLAUDE_PLUGIN_ROOT}/scripts/...`), so quote just
  1884. // the path component by replacing the placeholder with `"<pluginDir>"`.
  1885. const quoted = `"${PLUGIN_DIR}"`;
  1886. return command.split("${CLAUDE_PLUGIN_ROOT}").join(quoted);
  1887. }
  1888. function materializeHookEntry(entry) {
  1889. // Deep-clone so we don't mutate the shared template, then rewrite each
  1890. // inner command's placeholder to an absolute path.
  1891. const cloned = JSON.parse(JSON.stringify(entry));
  1892. if (cloned && Array.isArray(cloned.hooks)) {
  1893. cloned.hooks = cloned.hooks.map((h) => {
  1894. if (h && typeof h.command === "string") {
  1895. return { ...h, command: substitutePluginRoot(h.command) };
  1896. }
  1897. return h;
  1898. });
  1899. }
  1900. return cloned;
  1901. }
  1902. function detectHooksInstalled() {
  1903. const s = readSettings();
  1904. if (!s.json || typeof s.json !== "object") return false;
  1905. const hooks = s.json.hooks || {};
  1906. // Legacy nested block from older broken versions.
  1907. if (hooks[PLUGIN_BLOCK_KEY]) return true;
  1908. // Current schema: per-event arrays with _openloomi_plugin marker.
  1909. for (const event of Object.keys(hooks)) {
  1910. if (event === PLUGIN_BLOCK_KEY) continue;
  1911. const arr = hooks[event];
  1912. if (!Array.isArray(arr)) continue;
  1913. for (const entry of arr) {
  1914. if (entry?.[MARKER]) return true;
  1915. if (entry?.hooks) {
  1916. for (const h of entry.hooks) {
  1917. if (
  1918. h &&
  1919. typeof h.command === "string" &&
  1920. h.command.includes("loomi-bridge.mjs")
  1921. )
  1922. return true;
  1923. }
  1924. }
  1925. }
  1926. }
  1927. return false;
  1928. }
  1929. function installHooks({ yes = false } = {}) {
  1930. const settings = readSettings();
  1931. const j = settings.json || {};
  1932. if (!j.hooks || typeof j.hooks !== "object") j.hooks = {};
  1933. // Legacy cleanup: drop the old nested block from previous broken versions.
  1934. // Safe to run unconditionally — if absent, this is a no-op.
  1935. if (j.hooks[PLUGIN_BLOCK_KEY]) {
  1936. delete j.hooks[PLUGIN_BLOCK_KEY];
  1937. }
  1938. const template = loadHooksTemplate();
  1939. const templateHooks = template?.hooks || {};
  1940. if (Object.keys(templateHooks).length === 0) {
  1941. return {
  1942. ok: false,
  1943. error: "No hooks loaded from template",
  1944. path: settings.path,
  1945. };
  1946. }
  1947. // Merge per-event into settings.hooks (Claude Code's actual schema is
  1948. // `{ EventName: [matcher-group, ...] }`). Each entry we add carries the
  1949. // `_openloomi_plugin: true` marker so uninstallHooks can strip just our
  1950. // entries without touching other plugins.
  1951. let added = 0;
  1952. let already = 0;
  1953. for (const [event, rawEntries] of Object.entries(templateHooks)) {
  1954. const entries = Array.isArray(rawEntries) ? rawEntries : [rawEntries];
  1955. if (!Array.isArray(j.hooks[event])) j.hooks[event] = [];
  1956. for (const entry of entries) {
  1957. // Compare against the post-substitution command so dedup still
  1958. // works after the placeholder has been rewritten to the absolute
  1959. // plugin path (otherwise the second run would see a fresh-looking
  1960. // template string and append a duplicate entry).
  1961. const cmd0 = substitutePluginRoot(entry?.hooks?.[0]?.command || "");
  1962. const isDup = j.hooks[event].some(
  1963. (e) =>
  1964. e && e[MARKER] === true && e.hooks?.some((h) => h?.command === cmd0),
  1965. );
  1966. if (isDup) {
  1967. already++;
  1968. continue;
  1969. }
  1970. j.hooks[event].push({ ...materializeHookEntry(entry), [MARKER]: true });
  1971. added++;
  1972. }
  1973. }
  1974. const summary = {
  1975. events: Object.keys(templateHooks),
  1976. added,
  1977. alreadyInstalled: already,
  1978. note: "Per-event merge into settings.hooks (Claude Code schema-compliant). Other plugins untouched.",
  1979. };
  1980. atomicWriteJson(settings.path, j);
  1981. return {
  1982. ok: true,
  1983. alreadyInstalled: added === 0,
  1984. path: settings.path,
  1985. summary,
  1986. };
  1987. }
  1988. function uninstallHooks() {
  1989. const settings = readSettings();
  1990. const j = settings.json || {};
  1991. let removed = false;
  1992. if (!j.hooks || typeof j.hooks !== "object") {
  1993. atomicWriteJson(settings.path, j);
  1994. return { ok: true, removed, path: settings.path };
  1995. }
  1996. // Always strip the legacy nested block from older broken versions, even
  1997. // if per-event marker entries also exist.
  1998. if (j.hooks[PLUGIN_BLOCK_KEY]) {
  1999. delete j.hooks[PLUGIN_BLOCK_KEY];
  2000. removed = true;
  2001. }
  2002. // Strip per-event marker entries (current schema) and any inner
  2003. // loomi-bridge.mjs commands from mixed entries — defensive against any
  2004. // future tool that merges our marker-bearing entry into someone else's.
  2005. for (const event of Object.keys(j.hooks)) {
  2006. if (event === PLUGIN_BLOCK_KEY) continue;
  2007. const arr = j.hooks[event];
  2008. if (!Array.isArray(arr)) continue;
  2009. const before = arr.length;
  2010. const filtered = arr.filter((entry) => {
  2011. if (!entry) return false;
  2012. if (entry[MARKER]) return false;
  2013. if (entry.hooks && Array.isArray(entry.hooks)) {
  2014. const inner = entry.hooks.filter(
  2015. (h) =>
  2016. !(
  2017. h &&
  2018. typeof h.command === "string" &&
  2019. h.command.includes("loomi-bridge.mjs")
  2020. ),
  2021. );
  2022. if (inner.length === 0) return false;
  2023. entry.hooks = inner;
  2024. return true;
  2025. }
  2026. return true;
  2027. });
  2028. j.hooks[event] = filtered;
  2029. if (filtered.length !== before) removed = true;
  2030. }
  2031. atomicWriteJson(settings.path, j);
  2032. return { ok: true, removed, path: settings.path };
  2033. }
  2034. // ---------------------------------------------------------------------------
  2035. // pet / state (Pet mirror)
  2036. // ---------------------------------------------------------------------------
  2037. async function cmdPet(state) {
  2038. if (!state || !CAPYBARA_STATES.has(state)) {
  2039. return {
  2040. ok: false,
  2041. code: "INVALID_STATE",
  2042. validStates: [...CAPYBARA_STATES],
  2043. };
  2044. }
  2045. const res = await apiPOST(
  2046. "/api/pet/state",
  2047. { state, source: "claude-code-plugin" },
  2048. { timeoutMs: STATE_HTTP_TIMEOUT_MS },
  2049. );
  2050. if (res.status === 404) {
  2051. return {
  2052. ok: false,
  2053. code: "ENDPOINT_MISSING",
  2054. message:
  2055. 'OpenLoomi runtime does not yet expose POST /api/pet/state. Pending endpoint — would have set state to "' +
  2056. state +
  2057. '".',
  2058. state,
  2059. };
  2060. }
  2061. if (!res.ok) {
  2062. return {
  2063. ok: false,
  2064. code: "PET_FAILED",
  2065. status: res.status,
  2066. error: res.json || res.error,
  2067. };
  2068. }
  2069. return { ok: true, state, response: res.json };
  2070. }
  2071. // One-tap guest login: POST /api/remote-auth/guest → mint a bearer →
  2072. // persist to ~/.openloomi/token (base64-encoded to match the Tauri
  2073. // runtime's `save_token`). Used by the setup wizard as a fallback when
  2074. // `LOGIN_REQUIRED` fires and the user doesn't want to open the desktop
  2075. // app to sign in with their existing account.
  2076. async function cmdGuestLogin({ baseUrl = null } = {}) {
  2077. // The /api/remote-auth/guest endpoint does NOT require an existing
  2078. // token, so we deliberately bypass the `Authorization: Bearer` header
  2079. // path here by calling the server directly without a bearer.
  2080. const target = (baseUrl || openloomiBaseUrl()) + "/api/remote-auth/guest";
  2081. try {
  2082. // 10 s per-attempt timeout, 2 retries — total budget ~30 s worst case.
  2083. // POST without a body is safely idempotent in the runtime's eyes: a 5xx
  2084. // means the token wasn't minted, so a follow-up call mints a fresh one.
  2085. const res = await fetchWithRetry(
  2086. target,
  2087. {
  2088. method: "POST",
  2089. headers: {
  2090. "Content-Type": "application/json",
  2091. Accept: "application/json",
  2092. },
  2093. body: JSON.stringify({}),
  2094. },
  2095. { timeoutMs: 10_000 },
  2096. );
  2097. const text = await res.text().catch(() => "");
  2098. let json = null;
  2099. try {
  2100. json = text ? JSON.parse(text) : null;
  2101. } catch {
  2102. json = { raw: text };
  2103. }
  2104. if (!res.ok) {
  2105. return {
  2106. ok: false,
  2107. code: res.status === 404 ? "ENDPOINT_MISSING" : `http_${res.status}`,
  2108. status: res.status,
  2109. error: json,
  2110. };
  2111. }
  2112. const token = json?.token;
  2113. if (typeof token !== "string" || !token.trim()) {
  2114. return { ok: false, code: "NO_TOKEN_IN_RESPONSE", response: json };
  2115. }
  2116. const saved = saveOpenloomiToken(token);
  2117. if (!saved.ok) {
  2118. return {
  2119. ok: false,
  2120. code: saved.code || "TOKEN_WRITE_FAILED",
  2121. error: saved.error || null,
  2122. };
  2123. }
  2124. return {
  2125. ok: true,
  2126. user: json.user || null,
  2127. tokenPath: saved.path,
  2128. };
  2129. } catch (e) {
  2130. return { ok: false, code: "NETWORK", error: String(e?.message || e) };
  2131. }
  2132. }
  2133. async function cmdState(name, { event } = {}) {
  2134. if (!CAPYBARA_STATES.has(name)) {
  2135. // Hooks should never reach this with an invalid name, but be safe.
  2136. return {
  2137. ok: false,
  2138. archive: "skipped",
  2139. reason: "invalid_state",
  2140. state: name,
  2141. };
  2142. }
  2143. try {
  2144. const res = await apiPOST(
  2145. "/api/pet/state",
  2146. { state: name, source: "claude-code-plugin", event: event || null },
  2147. { timeoutMs: STATE_HTTP_TIMEOUT_MS },
  2148. );
  2149. if (res.status === 404) {
  2150. return {
  2151. ok: false,
  2152. archive: "skipped",
  2153. reason: "endpoint_missing",
  2154. state: name,
  2155. };
  2156. }
  2157. if (!res.ok) {
  2158. return {
  2159. ok: false,
  2160. archive: "skipped",
  2161. reason: `http_${res.status}`,
  2162. state: name,
  2163. };
  2164. }
  2165. return { ok: true, state: name };
  2166. } catch {
  2167. return { ok: false, archive: "skipped", reason: "exception", state: name };
  2168. }
  2169. }
  2170. // ---------------------------------------------------------------------------
  2171. // archive (Stop hook)
  2172. // ---------------------------------------------------------------------------
  2173. async function readStdinJson({ maxBytes = 64 * 1024 } = {}) {
  2174. return await new Promise((resolve) => {
  2175. let total = 0;
  2176. let buf = "";
  2177. process.stdin.setEncoding("utf8");
  2178. process.stdin.on("data", (chunk) => {
  2179. total += Buffer.byteLength(chunk, "utf8");
  2180. if (total <= maxBytes) buf += chunk;
  2181. });
  2182. process.stdin.on("end", () => resolve(buf));
  2183. process.stdin.on("error", () => resolve(""));
  2184. // If nothing arrives, resolve after 200ms with empty.
  2185. setTimeout(() => resolve(buf), 200);
  2186. });
  2187. }
  2188. async function cmdArchive() {
  2189. // Always exit 0. Never block Claude.
  2190. let payload = {};
  2191. try {
  2192. const stdinRaw = await readStdinJson({ maxBytes: 32 * 1024 });
  2193. if (stdinRaw) {
  2194. try {
  2195. payload = JSON.parse(stdinRaw);
  2196. } catch {
  2197. payload = {};
  2198. }
  2199. }
  2200. } catch {
  2201. payload = {};
  2202. }
  2203. const eventName = payload.hook_event_name || payload.event || "";
  2204. if (eventName !== "Stop") {
  2205. return {
  2206. continue: true,
  2207. _openloomi: {
  2208. archive: "skipped",
  2209. reason: "not_stop_event",
  2210. event: eventName,
  2211. },
  2212. };
  2213. }
  2214. const transcriptPath =
  2215. payload.transcript_path || payload.transcriptPath || null;
  2216. if (!transcriptPath || !existsSync(transcriptPath)) {
  2217. return {
  2218. continue: true,
  2219. _openloomi: { archive: "skipped", reason: "transcript_missing" },
  2220. };
  2221. }
  2222. let raw;
  2223. try {
  2224. const st = statSync(transcriptPath);
  2225. if (st.size > ARCHIVE_MAX_BYTES) {
  2226. // Truncate by reading last ~ARCHIVE_MAX_BYTES bytes.
  2227. const fd = await import("node:fs/promises");
  2228. const fh = await fd.open(transcriptPath, "r");
  2229. try {
  2230. const start = Math.max(0, st.size - ARCHIVE_MAX_BYTES);
  2231. const buf = Buffer.alloc(st.size - start);
  2232. await fh.read(buf, 0, buf.length, start);
  2233. raw = buf.toString("utf8");
  2234. } finally {
  2235. await fh.close();
  2236. }
  2237. } else {
  2238. raw = await readFile(transcriptPath, "utf8");
  2239. }
  2240. } catch {
  2241. return {
  2242. continue: true,
  2243. _openloomi: { archive: "skipped", reason: "transcript_unreadable" },
  2244. };
  2245. }
  2246. const lines = raw.split(/\r?\n/).filter(Boolean);
  2247. const parsed = [];
  2248. for (const line of lines) {
  2249. try {
  2250. const o = JSON.parse(line);
  2251. if (
  2252. o &&
  2253. (o.type === "user" || o.type === "human" || o.type === "assistant")
  2254. ) {
  2255. parsed.push(o);
  2256. }
  2257. } catch {
  2258. /* skip */
  2259. }
  2260. }
  2261. if (parsed.length === 0) {
  2262. return {
  2263. continue: true,
  2264. _openloomi: { archive: "skipped", reason: "no_messages" },
  2265. };
  2266. }
  2267. const tail = parsed.slice(-ARCHIVE_MAX_TURNS);
  2268. const summaryText = buildArchiveSummary(tail, payload.session_id || null);
  2269. if (!summaryText) {
  2270. return {
  2271. continue: true,
  2272. _openloomi: { archive: "skipped", reason: "empty_summary" },
  2273. };
  2274. }
  2275. const bearer = loadBearerToken();
  2276. if (!bearer) {
  2277. return {
  2278. continue: true,
  2279. _openloomi: { archive: "skipped", reason: "auth_missing" },
  2280. };
  2281. }
  2282. const res = await apiPOST(
  2283. "/api/insights",
  2284. {
  2285. type: "note",
  2286. title: `Claude Code session${payload.session_id ? " " + String(payload.session_id).slice(0, 8) : ""} (${new Date().toISOString().slice(0, 10)})`,
  2287. description: summaryText,
  2288. platform: "claude-code",
  2289. groups: ["claude-code"],
  2290. sessionId: payload.session_id || null,
  2291. source: "claude-code-plugin-stop-hook",
  2292. capturedAt: new Date().toISOString(),
  2293. },
  2294. { timeoutMs: ARCHIVE_HTTP_TIMEOUT_MS },
  2295. );
  2296. if (!res.ok) {
  2297. return {
  2298. continue: true,
  2299. _openloomi: {
  2300. archive: "skipped",
  2301. reason: res.status === 404 ? "endpoint_missing" : `http_${res.status}`,
  2302. details: res.json || res.error || null,
  2303. },
  2304. };
  2305. }
  2306. return {
  2307. continue: true,
  2308. _openloomi: {
  2309. archive: "ok",
  2310. session: payload.session_id || null,
  2311. insightId: res.json?.id || null,
  2312. },
  2313. };
  2314. }
  2315. function buildArchiveSummary(turns, sessionId) {
  2316. const parts = [];
  2317. let total = 0;
  2318. for (const t of turns) {
  2319. const content = extractMessageText(t);
  2320. if (!content) continue;
  2321. const role = t.role || t.type || "message";
  2322. const tag =
  2323. role === "user" || role === "human"
  2324. ? "user"
  2325. : role === "assistant"
  2326. ? "assistant"
  2327. : role;
  2328. const slice = `${tag}: ${content}`.slice(0, 1500);
  2329. parts.push(slice);
  2330. total += slice.length;
  2331. if (total > ARCHIVE_MAX_CONTENT_CHARS) break;
  2332. }
  2333. if (parts.length === 0) return null;
  2334. const header = `[claude-code session${sessionId ? " " + sessionId : ""}]`;
  2335. const joined = parts.join("\n");
  2336. const capped =
  2337. joined.length > ARCHIVE_MAX_CONTENT_CHARS
  2338. ? joined.slice(0, ARCHIVE_MAX_CONTENT_CHARS) + "…"
  2339. : joined;
  2340. return `${header}\n${capped}`;
  2341. }
  2342. function extractMessageText(obj) {
  2343. const msg = obj?.message || obj;
  2344. const c = msg?.content;
  2345. if (typeof c === "string") return c;
  2346. if (Array.isArray(c)) {
  2347. return c
  2348. .map((p) => {
  2349. if (!p) return "";
  2350. if (typeof p === "string") return p;
  2351. if (p.type === "text" && typeof p.text === "string") return p.text;
  2352. return "";
  2353. })
  2354. .filter(Boolean)
  2355. .join("\n");
  2356. }
  2357. return "";
  2358. }
  2359. // ---------------------------------------------------------------------------
  2360. // usage
  2361. // ---------------------------------------------------------------------------
  2362. async function cmdUsage() {
  2363. const r = await apiGET("/api/llm/usage/summary", { timeoutMs: 5000 });
  2364. if (!r.ok && r.status === 0) {
  2365. return { ok: false, code: "API_UNREACHABLE", error: r.error };
  2366. }
  2367. return { ok: r.ok, status: r.status, usage: r.json };
  2368. }
  2369. // ---------------------------------------------------------------------------
  2370. // install (user-approved)
  2371. // ---------------------------------------------------------------------------
  2372. async function promptYesNo(question) {
  2373. if (!isTTY) return false;
  2374. process.stdout.write(`${question} [y/N] `);
  2375. return await new Promise((resolve) => {
  2376. let buf = "";
  2377. const onData = (b) => {
  2378. buf += b.toString("utf8");
  2379. if (buf.includes("\n")) {
  2380. process.stdin.removeListener("data", onData);
  2381. const answer = buf.trim().toLowerCase();
  2382. resolve(answer === "y" || answer === "yes");
  2383. }
  2384. };
  2385. process.stdin.on("data", onData);
  2386. process.stdin.resume();
  2387. });
  2388. }
  2389. async function runInstallScript({
  2390. platformName,
  2391. yes,
  2392. onTick = null,
  2393. budgetMs = null,
  2394. }) {
  2395. const filename =
  2396. platformName === "macos"
  2397. ? "setup.macos.sh"
  2398. : platformName === "windows"
  2399. ? "setup.windows.ps1"
  2400. : "setup.linux.sh";
  2401. const candidates = [
  2402. join(PLUGIN_DIR, "scripts", "install-assets", filename),
  2403. join(PLUGIN_DIR, "install-assets", filename),
  2404. ];
  2405. let scriptPath = null;
  2406. for (const c of candidates) {
  2407. if (existsSync(c)) {
  2408. scriptPath = c;
  2409. break;
  2410. }
  2411. }
  2412. if (!scriptPath) {
  2413. return {
  2414. ok: false,
  2415. code: "INSTALL_SCRIPT_MISSING",
  2416. message: `No install script shipped for ${platformName}. Open https://openloomi.ai/docs/install and follow the manual steps.`,
  2417. };
  2418. }
  2419. if (!yes) {
  2420. if (!isTTY) {
  2421. return {
  2422. ok: false,
  2423. code: "NON_INTERACTIVE_REQUIRES_YES",
  2424. message:
  2425. "Install invoked without --yes from a non-interactive shell (no TTY). Re-run with --yes to confirm consent, or run directly in a terminal so the y/N prompt can be answered.",
  2426. };
  2427. }
  2428. const proceed = await promptYesNo(
  2429. `This will execute ${filename} from the OpenLoomi plugin to install OpenLoomi locally. Proceed?`,
  2430. );
  2431. if (!proceed)
  2432. return {
  2433. ok: false,
  2434. code: "CANCELLED",
  2435. message: "User cancelled installation.",
  2436. };
  2437. }
  2438. let cmd, args;
  2439. if (platformName === "windows") {
  2440. cmd = "powershell";
  2441. args = ["-ExecutionPolicy", "Bypass", "-NoProfile", "-File", scriptPath];
  2442. } else {
  2443. cmd = "bash";
  2444. args = [scriptPath];
  2445. }
  2446. // The install helper reads `OPENLOOMI_VERSION`, `OPENLOOMI_DMG_PATH`,
  2447. // `OPENLOOMI_REPO`, `OPENLOOMI_DOCS_BASE`, `OPENLOOMI_INSTALL_ROOT`,
  2448. // `GITHUB_TOKEN` / `GH_TOKEN`, etc. from the parent process env. Those
  2449. // propagate by default — no explicit `env` override. See issue #401
  2450. // (restricted-network / corporate proxy install) for the full contract,
  2451. // and openloomi.ai/docs/install/restricted-network for the user-facing
  2452. // narrative. The bridge intentionally does NOT strip these here: doing
  2453. // so would silently break `--offline <path>` and the env-var form of
  2454. // the same path.
  2455. const startedAt = Date.now();
  2456. return await new Promise((resolve) => {
  2457. let stdout = "";
  2458. let stderr = "";
  2459. let tickHandle = null;
  2460. let budgetHandle = null;
  2461. let resolved = false;
  2462. // Latest `[openloomi-installer] stage=...` line seen on stderr. Kept
  2463. // only for diagnostics; the helper's raw stderr is forwarded to
  2464. // process.stderr as it arrives so the user sees progress in real time.
  2465. let lastStage = null;
  2466. // Detect stage lines emitted by the install helpers — they're
  2467. // verbose by design so the chat layer can surface them as a
  2468. // structured `stage=` field without re-parsing free-form prose.
  2469. const stageLineRe = /^\[openloomi-installer\]\s+(?:stage=([a-z_]+))/;
  2470. const finalize = (result) => {
  2471. // Guard against double-resolve: timeout + exit / spawn + exit
  2472. // can race. The first writer wins; later calls become no-ops.
  2473. if (resolved) return;
  2474. resolved = true;
  2475. if (tickHandle) {
  2476. clearInterval(tickHandle);
  2477. tickHandle = null;
  2478. }
  2479. if (budgetHandle) {
  2480. clearTimeout(budgetHandle);
  2481. budgetHandle = null;
  2482. }
  2483. const elapsedMs = Date.now() - startedAt;
  2484. const base = {
  2485. elapsedMs,
  2486. lastStage,
  2487. stdout,
  2488. stderr,
  2489. budgetMs: Number.isFinite(budgetMs) ? budgetMs : null,
  2490. };
  2491. // OK passes through untouched — only failure paths need the
  2492. // mapper to guarantee non-empty `hints` and a concrete next step.
  2493. const merged = result.ok
  2494. ? { ...base, ...result }
  2495. : { ...base, ...result };
  2496. if (!result.ok) {
  2497. Object.assign(merged, installErrorGuidance(merged));
  2498. }
  2499. resolve(merged);
  2500. };
  2501. const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
  2502. child.stdout.on("data", (b) => (stdout += b.toString("utf8")));
  2503. // Tee child stderr to process.stderr as it arrives (so the user
  2504. // sees progress live, instead of waiting for the child to exit)
  2505. // while still buffering the full text for the final result. This
  2506. // is the fix for issue #398: a 200 MB DMG download previously
  2507. // buffered silently until the helper returned.
  2508. child.stderr.on("data", (b) => {
  2509. const text = b.toString("utf8");
  2510. stderr += text;
  2511. try {
  2512. process.stderr.write(text);
  2513. } catch {
  2514. /* stderr may be piped / closed; not fatal */
  2515. }
  2516. // Update diagnostics only — never filter or rewrite the bytes the
  2517. // user sees. We scan the last tail so chunked writes still match.
  2518. const tail = text.split(/\r?\n/);
  2519. for (const line of tail) {
  2520. const m = stageLineRe.exec(line);
  2521. if (m) lastStage = m[1];
  2522. }
  2523. });
  2524. child.on("error", (e) =>
  2525. finalize({
  2526. ok: false,
  2527. code: "SPAWN_FAILED",
  2528. message: String(e?.message || e),
  2529. }),
  2530. );
  2531. child.on("exit", (code, signal) => {
  2532. // Parse the install script's structured stdout line (if any). The
  2533. // script emits a single JSON object describing what it installed.
  2534. // We extract it from the captured stdout so we don't have to re-curl
  2535. // the GitHub API and we never call --version on the inner Tauri
  2536. // binary.
  2537. const infoLineMatch = stdout.match(/\{[^{}]*"version"[^{}]*\}/);
  2538. if (infoLineMatch) {
  2539. try {
  2540. const parsed = JSON.parse(infoLineMatch[0]);
  2541. setInstallInfo(parsed);
  2542. } catch {
  2543. /* ignore malformed */
  2544. }
  2545. }
  2546. // If the per-stage budget killed the child with SIGKILL we still
  2547. // want a stable INSTALL_TIMEOUT code (the timeout handler will
  2548. // have already called finalize, but if the child happened to exit
  2549. // first we want the timeout-friendly code path here too).
  2550. if (signal === "SIGKILL" && Number.isFinite(budgetMs) && budgetMs > 0) {
  2551. finalize({
  2552. ok: false,
  2553. code: "INSTALL_TIMEOUT",
  2554. message: `Install exceeded ${budgetMs}ms budget. Re-run with a higher --install-timeout (default ${DEFAULT_INSTALL_TIMEOUT_MS}ms).`,
  2555. });
  2556. return;
  2557. }
  2558. finalize({
  2559. ok: code === 0,
  2560. code: code === 0 ? "OK" : `EXIT_${code}`,
  2561. signal: signal || null,
  2562. });
  2563. });
  2564. // Drive a 1 Hz heartbeat on stderr so the user sees the install is
  2565. // still progressing (per issue #397). The interval is best-effort:
  2566. // we unref() it so it never blocks process exit, and we clear it as
  2567. // soon as the child exits.
  2568. if (onTick) {
  2569. try {
  2570. onTick();
  2571. } catch {
  2572. /* ticker is best-effort */
  2573. }
  2574. tickHandle = setInterval(() => {
  2575. try {
  2576. onTick();
  2577. } catch {
  2578. /* ignore */
  2579. }
  2580. }, 1000);
  2581. if (tickHandle.unref) tickHandle.unref();
  2582. }
  2583. // Per-stage budget. SIGKILL on overshoot so a stuck installer never
  2584. // strands the wizard — the bridge returns INSTALL_TIMEOUT and the
  2585. // user can retry with --install-timeout <N> or --yes to bypass.
  2586. if (Number.isFinite(budgetMs) && budgetMs > 0) {
  2587. budgetHandle = setTimeout(() => {
  2588. try {
  2589. child.kill("SIGKILL");
  2590. } catch {
  2591. /* already exited */
  2592. }
  2593. finalize({
  2594. ok: false,
  2595. code: "INSTALL_TIMEOUT",
  2596. message: `Install exceeded ${budgetMs}ms budget. Re-run with a higher --install-timeout (default ${DEFAULT_INSTALL_TIMEOUT_MS}ms).`,
  2597. });
  2598. }, budgetMs);
  2599. if (budgetHandle.unref) budgetHandle.unref();
  2600. }
  2601. });
  2602. }
  2603. async function cmdInstall({
  2604. yes = false,
  2605. onTick = null,
  2606. budgetMs = null,
  2607. } = {}) {
  2608. const platformName = detectPlatform();
  2609. const r = await runInstallScript({ platformName, yes, onTick, budgetMs });
  2610. // After install, refresh discovery state.
  2611. const status = await buildStatus({ json: true });
  2612. return { install: r, status, installInfo: getInstallInfo() };
  2613. }
  2614. // Checks whether the desktop GUI binary is actually running. Used by the
  2615. // setup state machine to decide whether the user is already looking at
  2616. // an OpenLoomi window (in which case setup can declare success) or
  2617. // whether we need to call `open -a <bundle>` to surface the window.
  2618. //
  2619. // We deliberately don't reuse `buildStatus`'s `apiReachable` flag here —
  2620. // the HTTP API can be up (Next.js server child process) while the Tauri
  2621. // GUI window is closed or never started (e.g. after a headless dev run,
  2622. // or if the user dismissed the window). The bridge relies on `binPath`
  2623. // (the Tauri binary path under the .app bundle) as the discriminator.
  2624. //
  2625. // Per-platform: macOS/Linux use `pgrep -if <pattern>` — the Tauri main
  2626. // process argv[0] carries the bundle path, so matching the distinctive
  2627. // `Contents/MacOS/<binName>` suffix won't false-positive on the inner
  2628. // `node server.js` (whose argv[0] is the node binary, not the Tauri one).
  2629. // Windows uses `tasklist /FI "IMAGENAME eq <binName>"`.
  2630. async function probeDesktopProcessRunning(binPath) {
  2631. if (!binPath) return false;
  2632. const platformName = detectPlatform();
  2633. if (platformName === "windows") {
  2634. const binName = binPath.split(/[\\/]/).pop() || "";
  2635. return await new Promise((resolve) => {
  2636. const proc = spawn("tasklist", ["/FI", `IMAGENAME eq ${binName}`], {
  2637. stdio: ["ignore", "pipe", "ignore"],
  2638. });
  2639. let out = "";
  2640. proc.stdout?.on("data", (b) => (out += b.toString("utf8")));
  2641. proc.on("exit", () => resolve(out.includes(binName)));
  2642. proc.on("error", () => resolve(false));
  2643. });
  2644. }
  2645. // Match the distinctive `Contents/MacOS/<binName>` suffix (Linux has no
  2646. // such prefix, so we fall back to the binary basename there) rather than
  2647. // the full absolute path: the installed bundle can differ in case from
  2648. // our discovered `binPath` (e.g. `/Applications/openloomi.app/...` on
  2649. // disk vs. `/Applications/OpenLoomi.app/...` as resolved), and macOS
  2650. // `pgrep -f` is case-sensitive. `-i` makes the match case-insensitive so
  2651. // the discriminator still avoids false-positiving on the inner
  2652. // `node server.js` while surviving the case mismatch.
  2653. const binName = binPath.split(/[\\/]/).pop() || "";
  2654. const pattern =
  2655. platformName === "macos" ? `Contents/MacOS/${binName}` : binName;
  2656. return await new Promise((resolve) => {
  2657. const proc = spawn("pgrep", ["-if", pattern], {
  2658. stdio: ["ignore", "pipe", "ignore"],
  2659. });
  2660. let out = "";
  2661. proc.stdout?.on("data", (b) => (out += b.toString("utf8")));
  2662. proc.on("exit", (code) => {
  2663. // pgrep exits 1 when no match, 2+ on error. Treat both as "not running".
  2664. if (code !== 0) {
  2665. resolve(false);
  2666. return;
  2667. }
  2668. const pids = out.split("\n").filter(Boolean);
  2669. resolve(pids.length > 0);
  2670. });
  2671. proc.on("error", () => resolve(false));
  2672. });
  2673. }
  2674. // Marks the next desktop launch as plugin-initiated by setting
  2675. // OPENLOOMI_LAUNCH_MODE=plugin in the environment the desktop
  2676. // process will see. The Codex plugin's `applyRuntimeEnvChange` is
  2677. // not reused here because it brings in a LaunchAgent plist /
  2678. // environment.d / dry-run pipeline that's overkill for this
  2679. // single-use side-band. We just want to leave a flag in the right
  2680. // spot, no rollback semantics, no persistence guarantees.
  2681. //
  2682. // Per-platform notes:
  2683. //
  2684. // * macOS — `open -a` hands off to LaunchServices; the new app
  2685. // process inherits from launchd, not from this Node process.
  2686. // Set via `launchctl setenv` so the freshly-spawned Tauri process
  2687. // sees it.
  2688. //
  2689. // * Windows — `cmd /c start "" <exe>` forks without inheriting the
  2690. // parent env in the same reliable way as Mac/Linux. The
  2691. // `launchDesktopApp` spawn site below passes the env explicitly
  2692. // via the `env` option, so this helper is a no-op on Windows.
  2693. //
  2694. // * Linux — gtk-launch / direct fork inherit `process.env`
  2695. // automatically. We still inject the env into the spawn call
  2696. // below as belt-and-braces in case a hook scrubbed it.
  2697. async function ensureLaunchModeEnvForLaunch() {
  2698. if (process.env.OPENLOOMI_LAUNCH_MODE === "plugin") {
  2699. return { ok: true, platform: process.platform, method: "already-set" };
  2700. }
  2701. const platform = process.platform;
  2702. if (platform === "darwin") {
  2703. const r = await runBin(
  2704. "launchctl",
  2705. ["setenv", "OPENLOOMI_LAUNCH_MODE", "plugin"],
  2706. { timeoutMs: 5000 },
  2707. );
  2708. if (r.ok) {
  2709. return { ok: true, platform, method: "launchctl setenv" };
  2710. }
  2711. return {
  2712. ok: false,
  2713. platform,
  2714. method: "launchctl setenv",
  2715. error: r.error?.message || r.stderr || "unknown",
  2716. };
  2717. }
  2718. // Non-darwin: the spawn site in launchDesktopApp passes the env
  2719. // explicitly. Mark success so the caller doesn't log a warning.
  2720. return { ok: true, platform, method: "spawn-env" };
  2721. }
  2722. // Programmatically launches the OpenLoomi desktop app so the helper binary
  2723. // gets laid down and the local HTTP API comes up. This is what unblocks
  2724. // `canGuestLogin: true` and the auto-login step in the setup state
  2725. // machine. We do NOT touch the GUI (no AppleScript, no keystrokes); the
  2726. // app starts in its normal state and we just poll for the API.
  2727. //
  2728. // Per-platform: macOS uses `open -a <bundle>`, Linux uses
  2729. // `gtk-launch <desktopId>` (best-effort) and Windows uses `cmd /c start "" <exe>`.
  2730. // If the platform doesn't support auto-launch, we return ok=false with
  2731. // a clear reason and let the user launch it once manually.
  2732. async function launchDesktopApp({ desktopMarker, binPath } = {}) {
  2733. const platformName = detectPlatform();
  2734. // We need either the .app bundle (macOS) or a runnable exe (Win/Linux).
  2735. const target = desktopMarker || binPath || null;
  2736. if (!target) {
  2737. return {
  2738. ok: false,
  2739. code: "NO_LAUNCH_TARGET",
  2740. message: "No OpenLoomi app path or binary to launch.",
  2741. };
  2742. }
  2743. // Mark this launch as plugin-initiated. The freshly-spawned desktop
  2744. // reads OPENLOOMI_LAUNCH_MODE from its environment and uses the
  2745. // value to route pet left-clicks to the compact status card
  2746. // instead of the main dashboard — surfacing two dialogs for the
  2747. // same chat (plugin + main) would be confusing. The user can
  2748. // still reach the main window via the pet right-click "Open
  2749. // Loomi" or the card's "Open in dashboard" CTA.
  2750. //
  2751. // Non-fatal on purpose: a failure here means the desktop falls
  2752. // back to standalone behaviour (pet click → main window), which is
  2753. // the same UX the user had before this code existed. We don't
  2754. // promote the failure to a launch-blocker.
  2755. const launchModeEnvResult = await ensureLaunchModeEnvForLaunch();
  2756. if (!launchModeEnvResult.ok) {
  2757. console.warn(
  2758. "[loomi-bridge] failed to set OPENLOOMI_LAUNCH_MODE=plugin; " +
  2759. "pet click will fall back to standalone behaviour",
  2760. launchModeEnvResult,
  2761. );
  2762. }
  2763. let cmd;
  2764. let args;
  2765. let spawnEnv = process.env;
    • Dismissed after review: Copies every environment variable, where API keys and tokens live, in a file that sends data
    • Line 2,913 on GitHub
  2766. if (platformName === "macos") {
  2767. cmd = "open";
  2768. args = ["-a", desktopMarker || target];
  2769. } else if (platformName === "windows") {
  2770. cmd = "cmd";
  2771. args = ["/c", "start", '""', target];
  2772. } else {
  2773. // Linux: try gtk-launch with a guessed desktopId; fall back to executing the
  2774. // binary directly if that fails. We don't ship a .desktop file from the
  2775. // plugin, so gtk-launch is best-effort.
  2776. cmd = "gtk-launch";
  2777. args = ["openloomi"];
  2778. // On Linux, gtk-launch / direct fork inherit `process.env` from the
  2779. // plugin's Node process. Inject OPENLOOMI_LAUNCH_MODE explicitly so
  2780. // the desktop sees it even if the parent process was started
  2781. // without it (e.g. by a hook that scrubbed the env).
  2782. spawnEnv = { ...process.env, OPENLOOMI_LAUNCH_MODE: "plugin" };
  2783. }
  2784. const spawnResult = await new Promise((resolve) => {
  2785. let stderr = "";
  2786. let stdout = "";
  2787. let child;
  2788. try {
  2789. child = spawn(cmd, args, {
  2790. stdio: ["ignore", "pipe", "pipe"],
  2791. detached: true,
  2792. env: spawnEnv,
  2793. });
  2794. } catch (e) {
  2795. resolve({
  2796. ok: false,
  2797. code: "SPAWN_FAILED",
  2798. message: String(e?.message || e),
  2799. });
  2800. return;
  2801. }
  2802. child.stdout?.on("data", (b) => (stdout += b.toString("utf8")));
  2803. child.stderr?.on("data", (b) => (stderr += b.toString("utf8")));
  2804. child.on("error", (e) =>
  2805. resolve({
  2806. ok: false,
  2807. code: "SPAWN_FAILED",
  2808. message: String(e?.message || e),
  2809. }),
  2810. );
  2811. // `open -a` and `start ""` return immediately; gtk-launch returns after
  2812. // the app is forked. Treat any non-error exit (or no exit within the
  2813. // short window) as success — what we really care about is whether the
  2814. // API comes up, which we verify in waitForApi().
  2815. child.on("exit", (code) => {
  2816. if (code === 0 || code === null) {
  2817. resolve({ ok: true, code: "OK", stdout, stderr, via: cmd });
  2818. } else {
  2819. // Try the binary directly as a Linux fallback before giving up.
  2820. if (platformName === "linux" && binPath) {
  2821. spawn(binPath, [], {
  2822. stdio: "ignore",
  2823. detached: true,
  2824. // Mirror the gtk-launch branch above: inject the launch
  2825. // mode so the desktop sees OPENLOOMI_LAUNCH_MODE=plugin
  2826. // even on the direct-spawn fallback path.
  2827. env: { ...process.env, OPENLOOMI_LAUNCH_MODE: "plugin" },
  2828. }).unref();
  2829. resolve({ ok: true, code: "OK_FALLBACK_DIRECT", via: binPath });
  2830. return;
  2831. }
  2832. resolve({ ok: false, code: `EXIT_${code}`, stdout, stderr, via: cmd });
  2833. }
  2834. });
  2835. // Hard cap so we don't block forever on platforms where the launcher
  2836. // doesn't exit (some `open -a` invocations under launchd behave that way).
  2837. setTimeout(
  2838. () => resolve({ ok: true, code: "OK_TIMEOUT", via: cmd, stdout, stderr }),
  2839. 2000,
  2840. ).unref();
  2841. });
  2842. // Surface `launchMode` so callers (notably the setup state machine)
  2843. // can record it as a distinct audit step. The env write is logically
  2844. // a separate action from the spawn — they have different failure
  2845. // modes (e.g. macOS TCC blocking `launchctl setenv` succeeds the
  2846. // spawn but loses the signal) and different operators (env state
  2847. // vs process state). Merging them into one step would obscure both.
  2848. return { ...spawnResult, launchMode: launchModeEnvResult };
  2849. }
  2850. // Polls the local OpenLoomi HTTP API until it responds, or the timeout
  2851. // elapses. Used after launching the desktop app to confirm the runtime
  2852. // is up before minting a guest bearer / syncing the AI provider.
  2853. //
  2854. // Per-issue #397:
  2855. // - Accepts an optional `onProgress` ticker (typically built with
  2856. // makeStageTicker("wait_api", timeoutMs)) so the caller can drive a
  2857. // 1 Hz "waiting for local API (12s / max 90s) …" line on stderr.
  2858. // - Returns the stable `code: "API_NOT_READY"` on timeout (the older
  2859. // `code: "TIMEOUT"` is preserved as `legacyCode` so existing callers
  2860. // that grep for it keep working).
  2861. // - When the desktop process is confirmed running but the API still
  2862. // has not woken up, `code` is upgraded to `"PERMISSION_PROMPT_LIKELY"`
  2863. // so the wizard can surface a TCC-prompt hint instead of a generic
  2864. // "did not respond" message. `binPath` is forwarded by the caller.
  2865. async function waitForApi({
  2866. timeoutMs = 30_000,
  2867. intervalMs = 500,
  2868. onProgress = null,
  2869. binPath = null,
  2870. isPermissionLikely = null, // async () => bool — defaults to probing the bin
  2871. } = {}) {
  2872. const start = Date.now();
  2873. let lastError = null;
  2874. while (Date.now() - start < timeoutMs) {
  2875. try {
  2876. const url = await probeOpenLoomiBaseUrl();
  2877. if (url) return { ok: true, elapsedMs: Date.now() - start, url };
  2878. } catch (e) {
  2879. lastError = e;
  2880. }
  2881. if (onProgress) {
  2882. try {
  2883. onProgress({ stage: "wait_api", elapsedMs: Date.now() - start });
  2884. } catch {
  2885. /* ticker is best-effort */
  2886. }
  2887. }
  2888. await new Promise((r) => setTimeout(r, intervalMs));
  2889. }
  2890. const elapsedMs = Date.now() - start;
  2891. let permissionLikely = false;
  2892. try {
  2893. permissionLikely = isPermissionLikely
  2894. ? await isPermissionLikely()
  2895. : binPath
  2896. ? await probeDesktopProcessRunning(binPath)
  2897. : false;
  2898. } catch {
  2899. permissionLikely = false;
  2900. }
  2901. return {
  2902. ok: false,
  2903. legacyCode: "TIMEOUT",
  2904. code: permissionLikely ? "PERMISSION_PROMPT_LIKELY" : "API_NOT_READY",
  2905. stage: "wait_api",
  2906. elapsedMs,
  2907. permissionLikely,
  2908. lastError: lastError ? String(lastError?.message || lastError) : null,
  2909. message: permissionLikely
  2910. ? `OpenLoomi desktop process is running but the local API did not respond within ${timeoutMs}ms — macOS is likely showing a permission prompt that needs to be approved.`
  2911. : `OpenLoomi local API did not respond within ${timeoutMs}ms.${lastError ? " last error: " + String(lastError?.message || lastError) : ""}`,
  2912. };
  2913. }
  2914. // ---------------------------------------------------------------------------
  2915. // Command routing
  2916. // ---------------------------------------------------------------------------
  2917. async function main() {
  2918. const argv = process.argv.slice(2);
  2919. const args = parseArgs(argv);
  2920. const sub = args._[0];
  2921. switch (sub) {
  2922. case "version": {
  2923. out({ ok: true, plugin: "openloomi", version: PLUGIN_VERSION });
  2924. return;
  2925. }
  2926. case "launch-mode-info": {
  2927. // Diagnostic surface for OPENLOOMI_LAUNCH_MODE. The desktop
  2928. // app reads this env var to route pet left-clicks: plugin
  2929. // sessions default to the compact status card instead of the
  2930. // main dashboard, so the user doesn't see "two dialogs" for
  2931. // the same chat. Mirrors `codex-runtime-info` on the Codex
  2932. // plugin side — same shape so tests can grep for the key.
  2933. const platformName = detectPlatform();
  2934. out({
  2935. ok: true,
  2936. purpose:
  2937. "Mark the next OpenLoomi desktop launch as plugin-initiated " +
  2938. "so the pet left-click defaults to the compact status card.",
  2939. envKey: "OPENLOOMI_LAUNCH_MODE",
  2940. envValue: "plugin",
  2941. platform: platformName,
  2942. perPlatform: {
  2943. darwin:
  2944. "Sets the env var via `launchctl setenv` before `open -a`. " +
  2945. "The freshly-spawned Tauri process inherits from launchd.",
  2946. linux:
  2947. "Spawns gtk-launch / fallback binary with `env` containing " +
  2948. "OPENLOOMI_LAUNCH_MODE=plugin (parent process.env is also " +
  2949. "inherited by default).",
  2950. win32:
  2951. "Passes `env` containing OPENLOOMI_LAUNCH_MODE=plugin to the " +
  2952. "`cmd /c start \"\" <exe>` spawn site.",
  2953. },
  2954. // The same helper that `launchDesktopApp` invokes. Surfaced
  2955. // here so tests can grep for it and operators can confirm the
  2956. // key matches what the desktop reads in `launch_mode.rs`.
  2957. helper: "ensureLaunchModeEnvForLaunch",
  2958. consumerFile: "apps/web/src-tauri/src/launch_mode.rs",
  2959. // Name of the audit step the setup state machine records
  2960. // when `launchDesktopApp` runs the helper. Lets operators
  2961. // and tests confirm the wizard surfaces this side-band —
  2962. // it isn't merged into `launch` / `launch_gui` because it
  2963. // has a distinct failure mode (env write vs process spawn).
  2964. auditStep: "launch_mode_env",
  2965. });
  2966. return;
  2967. }
  2968. case "launch-mode-apply": {
  2969. // Test-only entry point. Invokes the same helper that
  2970. // `launchDesktopApp` calls before spawning the desktop
  2971. // process, so tests can mock `launchctl` on PATH and assert
  2972. // the right env var key + value land in the mock's argv.
  2973. const result = await ensureLaunchModeEnvForLaunch();
  2974. out(result);
  2975. return;
  2976. }
  2977. case "setup-status": {
  2978. const status = await buildStatus({
  2979. json: true,
  2980. explicit: args["bin-path"] || null,
  2981. });
  2982. out(status);
  2983. return;
  2984. }
  2985. case "setup": {
  2986. // End-to-end wizard. Walks the full state machine in one invocation:
  2987. // install → launch app → wait API → guest login → sync env → READY.
  2988. // Every transition is automatic — we never ask the user to click
  2989. // anything. If a step can't be auto-resolved (e.g. AI provider needed
  2990. // but no env key, or login failed), we return `awaiting_user_action`
  2991. // with a clear `nextAction` and stop.
  2992. //
  2993. // Per-issue #397: timeouts are now per-stage (install / launch /
  2994. // wait_api + permission_grace), each independently configurable
  2995. // through CLI flags. `--max-wait` is kept as a global cap. Long
  2996. // stages emit a throttled "stage X (Ys / max Zs) …" heartbeat on
  2997. // stderr so the user sees progress in their terminal.
  2998. const explicit = args["bin-path"] || null;
  2999. const yesFlag = !!args.yes;
  3000. const stages = readStageTimeouts(args);
  3001. const maxSteps = 8; // hard ceiling on chained transitions
  3002. const steps = [];
  3003. const stageStartedAt = Date.now();
  3004. const record = (name, ok, detail) => {
  3005. steps.push({ step: name, ok, at: Date.now(), ...detail });
  3006. };
  3007. for (let i = 0; i < maxSteps; i++) {
  3008. const status = await buildStatus({ json: true, explicit });
  3009. // Augment with a per-call desktop-process probe. `buildStatus`
  3010. // only knows about the .app bundle and the local API — not
  3011. // whether the Tauri GUI window is actually up. Without this,
  3012. // a setup call after a server-only prior run would land on
  3013. // READY immediately while the user is staring at nothing.
  3014. status.desktopProcessRunning = status.binPath
  3015. ? await probeDesktopProcessRunning(status.binPath)
  3016. : false;
  3017. // Surface the desktop window if it's not already up. We do
  3018. // this BEFORE the READY check so a "ready in everything but
  3019. // the GUI" state falls into this branch instead of returning
  3020. // success. `open -a <bundle>` is idempotent — a running app
  3021. // just gets its window forwarded, so a redundant launch
  3022. // alongside the existing 2a/2b branches is harmless.
  3023. if (
  3024. status.installed &&
  3025. status.desktopMarker &&
  3026. !status.desktopProcessRunning
  3027. ) {
  3028. const launch = await launchDesktopApp({
  3029. desktopMarker: status.desktopMarker,
  3030. binPath: status.binPath,
  3031. });
  3032. // The env write happens before the spawn in `launchDesktopApp`,
  3033. // so record it first — the audit trail is chronological.
  3034. if (launch.launchMode) {
  3035. record("launch_mode_env", launch.launchMode.ok, {
  3036. platform: launch.launchMode.platform,
  3037. method: launch.launchMode.method,
  3038. error: launch.launchMode.error,
  3039. });
  3040. }
  3041. record("launch_gui", launch.ok, {
  3042. code: launch.code,
  3043. via: launch.via,
  3044. });
  3045. if (!launch.ok) {
  3046. out({
  3047. ok: false,
  3048. setup: "gui_launch_failed",
  3049. steps,
  3050. launch,
  3051. status,
  3052. });
  3053. return;
  3054. }
  3055. continue;
  3056. }
  3057. // Truly ready requires both the local API and the desktop GUI
  3058. // process to be running. If the GUI isn't up, the branch above
  3059. // has already launched it — the next iteration will land here
  3060. // with both signals green.
  3061. if (status.reason === "READY" && status.desktopProcessRunning) {
  3062. out({ ok: true, setup: "ready", steps, status });
  3063. return;
  3064. }
  3065. // 1. Install.
  3066. if (!status.installed && status.nextAction === "install_openloomi") {
  3067. const installTicker = makeStageTicker("install", stages.installMs);
  3068. installTicker();
  3069. const r = await cmdInstall({
  3070. yes: yesFlag,
  3071. onTick: () => installTicker(),
  3072. budgetMs: stages.installMs,
  3073. });
  3074. record("install", !!r.install?.ok, {
  3075. code: r.install?.code,
  3076. elapsedMs:
  3077. r.install && Number.isFinite(r.install.elapsedMs)
  3078. ? r.install.elapsedMs
  3079. : null,
  3080. });
  3081. if (!r.install?.ok) {
  3082. const elapsedMs = Date.now() - stageStartedAt;
  3083. // `runInstallScript` already maps every non-OK result to a
  3084. // human message + non-empty hints + concrete resume command
  3085. // via `installErrorGuidance`. Surface those fields directly
  3086. // so the chat layer has a stable shape regardless of which
  3087. // exit code or failure mode the helper produced (issue #398).
  3088. const ins = r.install || {};
  3089. out({
  3090. ok: false,
  3091. setup: "install_failed",
  3092. code: ins.code || "EXIT_NONZERO",
  3093. stage: "install",
  3094. elapsedMs,
  3095. message: ins.message,
  3096. hints:
  3097. Array.isArray(ins.hints) && ins.hints.length > 0
  3098. ? ins.hints
  3099. : undefined,
  3100. canResume:
  3101. typeof ins.canResume === "boolean" ? ins.canResume : true,
  3102. resumeCommand: ins.resumeCommand,
  3103. lastStage: ins.lastStage || null,
  3104. steps,
  3105. install: ins,
  3106. status: r.status,
  3107. });
  3108. return;
  3109. }
  3110. continue;
  3111. }
  3112. // 2. .app installed but helper binary / local API not yet on disk.
  3113. // Auto-launch the desktop app (signed bundle, safe to do) and
  3114. // poll for the API to come up.
  3115. if (status.installed && status.reason === "OPENLOOMI_NOT_FINALIZED") {
  3116. const launch = await launchDesktopApp({
  3117. desktopMarker: status.desktopMarker,
  3118. binPath: status.binPath,
  3119. });
  3120. if (launch.launchMode) {
  3121. record("launch_mode_env", launch.launchMode.ok, {
  3122. platform: launch.launchMode.platform,
  3123. method: launch.launchMode.method,
  3124. error: launch.launchMode.error,
  3125. });
  3126. }
  3127. record("launch", launch.ok, { code: launch.code, via: launch.via });
  3128. if (!launch.ok) {
  3129. out({ ok: false, setup: "launch_failed", steps, launch, status });
  3130. return;
  3131. }
  3132. const apiTicker = makeStageTicker("wait_api", stages.apiMs);
  3133. // Prime the ticker so the user sees feedback within ~1 s.
  3134. apiTicker();
  3135. const wait = await waitForApi({
  3136. timeoutMs: stages.apiMs,
  3137. onProgress: () => apiTicker(),
  3138. binPath: status.binPath,
  3139. });
  3140. record("wait_api", wait.ok, {
  3141. elapsedMs: wait.elapsedMs,
  3142. url: wait.url,
  3143. code: wait.code,
  3144. permissionLikely: wait.permissionLikely,
  3145. });
  3146. if (!wait.ok) {
  3147. const elapsedMs = Date.now() - stageStartedAt;
  3148. // Apply the permission_grace budget on top of apiMs only when
  3149. // the desktop process is actually running. That way a slow
  3150. // download does NOT silently extend the wait — permission
  3151. // grace is exclusively for "process up but TCC blocking".
  3152. let effectiveBudget = stages.apiMs;
  3153. if (wait.permissionLikely) {
  3154. effectiveBudget += stages.permissionMs;
  3155. // One more bounded wait_for_api cycle for the permission
  3156. // prompt to be approved by the user.
  3157. const graceTicker = makeStageTicker(
  3158. "permission_grace",
  3159. stages.permissionMs,
  3160. );
  3161. graceTicker();
  3162. const graceWait = await waitForApi({
  3163. timeoutMs: stages.permissionMs,
  3164. onProgress: () => graceTicker(),
  3165. binPath: status.binPath,
  3166. });
  3167. if (graceWait.ok) {
  3168. record("wait_api.grace", true, {
  3169. elapsedMs: graceWait.elapsedMs,
  3170. url: graceWait.url,
  3171. });
  3172. continue;
  3173. }
  3174. record("wait_api.grace", false, {
  3175. elapsedMs: graceWait.elapsedMs,
  3176. code: graceWait.code,
  3177. });
  3178. }
  3179. // Honor the global cap (--max-wait) once we know the user
  3180. // asked for a ceiling smaller than what we've already spent.
  3181. const overCap = elapsedMs > stages.totalMs + stages.permissionMs;
  3182. const hints = apiNotReadyHints({
  3183. stage: wait.stage || "wait_api",
  3184. platformName: detectPlatform(),
  3185. canResume: true,
  3186. });
  3187. out({
  3188. ok: false,
  3189. setup: "api_not_ready",
  3190. code: wait.code,
  3191. stage: wait.stage || "wait_api",
  3192. elapsedMs,
  3193. effectiveBudgetMs: effectiveBudget,
  3194. overCap,
  3195. canResume: true,
  3196. resumeCommand:
  3197. "/openloomi:setup --yes --max-wait " +
  3198. Math.max(stages.totalMs, 180_000),
  3199. hints,
  3200. steps,
  3201. wait,
  3202. status,
  3203. });
  3204. return;
  3205. }
  3206. continue;
  3207. }
  3208. // 2b. .app is installed AND inner binary exists, but the desktop
  3209. // process isn't running yet so the API is unreachable. We
  3210. // launch it the same way as the NOT_FINALIZED branch — this is
  3211. // the normal "first time you call setup on a fresh install"
  3212. // path (the user has not yet opened OpenLoomi.app).
  3213. if (status.installed && !status.apiReachable && status.desktopMarker) {
  3214. const launch = await launchDesktopApp({
  3215. desktopMarker: status.desktopMarker,
  3216. binPath: status.binPath,
  3217. });
  3218. if (launch.launchMode) {
  3219. record("launch_mode_env", launch.launchMode.ok, {
  3220. platform: launch.launchMode.platform,
  3221. method: launch.launchMode.method,
  3222. error: launch.launchMode.error,
  3223. });
  3224. }
  3225. record("launch", launch.ok, { code: launch.code, via: launch.via });
  3226. if (!launch.ok) {
  3227. out({ ok: false, setup: "launch_failed", steps, launch, status });
  3228. return;
  3229. }
  3230. const apiTicker = makeStageTicker("wait_api", stages.apiMs);
  3231. // Prime the ticker so the user sees feedback within ~1 s.
  3232. apiTicker();
  3233. const wait = await waitForApi({
  3234. timeoutMs: stages.apiMs,
  3235. onProgress: () => apiTicker(),
  3236. binPath: status.binPath,
  3237. });
  3238. record("wait_api", wait.ok, {
  3239. elapsedMs: wait.elapsedMs,
  3240. url: wait.url,
  3241. code: wait.code,
  3242. permissionLikely: wait.permissionLikely,
  3243. });
  3244. if (!wait.ok) {
  3245. const elapsedMs = Date.now() - stageStartedAt;
  3246. // Apply the permission_grace budget on top of apiMs only when
  3247. // the desktop process is actually running. That way a slow
  3248. // download does NOT silently extend the wait — permission
  3249. // grace is exclusively for "process up but TCC blocking".
  3250. let effectiveBudget = stages.apiMs;
  3251. if (wait.permissionLikely) {
  3252. effectiveBudget += stages.permissionMs;
  3253. // One more bounded wait_for_api cycle for the permission
  3254. // prompt to be approved by the user.
  3255. const graceTicker = makeStageTicker(
  3256. "permission_grace",
  3257. stages.permissionMs,
  3258. );
  3259. graceTicker();
  3260. const graceWait = await waitForApi({
  3261. timeoutMs: stages.permissionMs,
  3262. onProgress: () => graceTicker(),
  3263. binPath: status.binPath,
  3264. });
  3265. if (graceWait.ok) {
  3266. record("wait_api.grace", true, {
  3267. elapsedMs: graceWait.elapsedMs,
  3268. url: graceWait.url,
  3269. });
  3270. continue;
  3271. }
  3272. record("wait_api.grace", false, {
  3273. elapsedMs: graceWait.elapsedMs,
  3274. code: graceWait.code,
  3275. });
  3276. }
  3277. // Honor the global cap (--max-wait) once we know the user
  3278. // asked for a ceiling smaller than what we've already spent.
  3279. const overCap = elapsedMs > stages.totalMs + stages.permissionMs;
  3280. const hints = apiNotReadyHints({
  3281. stage: wait.stage || "wait_api",
  3282. platformName: detectPlatform(),
  3283. canResume: true,
  3284. });
  3285. out({
  3286. ok: false,
  3287. setup: "api_not_ready",
  3288. code: wait.code,
  3289. stage: wait.stage || "wait_api",
  3290. elapsedMs,
  3291. effectiveBudgetMs: effectiveBudget,
  3292. overCap,
  3293. canResume: true,
  3294. resumeCommand:
  3295. "/openloomi:setup --yes --max-wait " +
  3296. Math.max(stages.totalMs, 180_000),
  3297. hints,
  3298. steps,
  3299. wait,
  3300. status,
  3301. });
  3302. return;
  3303. }
  3304. continue;
  3305. }
  3306. // 3. Login needed and API reachable → mint a one-tap guest bearer.
  3307. if (status.reason === "LOGIN_REQUIRED" && status.canGuestLogin) {
  3308. const g = await cmdGuestLogin();
  3309. record("guest_login", !!g.ok, { code: g.code, user: g.user });
  3310. if (!g.ok) {
  3311. out({
  3312. ok: false,
  3313. setup: "guest_login_failed",
  3314. code: g.code,
  3315. message:
  3316. "Guest login failed. Open OpenLoomi Desktop and sign in with an existing account, then re-run /openloomi:setup.",
  3317. guest: g,
  3318. steps,
  3319. status,
  3320. });
  3321. return;
  3322. }
  3323. continue;
  3324. }
  3325. // 5. No automatic transition matches. Surface a clear next step.
  3326. // The two realistic stops here are:
  3327. // - LOGIN_REQUIRED but canGuestLogin=false → API is down
  3328. // (we couldn't reach it after launch). Tell the user to
  3329. // sign in via the GUI and re-run setup.
  3330. // - AI_PROVIDER_REQUIRED with no env key → walk them through
  3331. // OpenLoomi Desktop → API Settings.
  3332. out({
  3333. ok: true,
  3334. setup: "awaiting_user_action",
  3335. steps,
  3336. status,
  3337. });
  3338. return;
  3339. }
  3340. // Hit the step ceiling without reaching READY — return current state.
  3341. const final = await buildStatus({ json: true, explicit });
  3342. out({ ok: false, setup: "step_limit_reached", steps, status: final });
  3343. return;
  3344. }
  3345. case "install": {
  3346. // Honor --install-timeout for the direct install path so users
  3347. // running `node loomi-bridge.mjs install --yes` get the same 1 Hz
  3348. // heartbeat as the `/openloomi:setup` wizard (issue #398). The
  3349. // setup wizard passes its own ticker; this branch owns it itself.
  3350. const stages = readStageTimeouts(args);
  3351. const installTicker = makeStageTicker("install", stages.installMs);
  3352. installTicker();
  3353. const tickHandle = setInterval(() => installTicker(), 1000);
  3354. if (tickHandle.unref) tickHandle.unref();
  3355. try {
  3356. const r = await cmdInstall({
  3357. yes: !!args.yes,
  3358. onTick: () => installTicker(),
  3359. budgetMs: stages.installMs,
  3360. });
  3361. out(r);
  3362. } finally {
  3363. clearInterval(tickHandle);
  3364. }
  3365. return;
  3366. }
  3367. case "login": {
  3368. // We deliberately do not spawn a browser here — the user can open
  3369. // OpenLoomi Desktop themselves. We just report token presence.
  3370. const status = await buildStatus({ json: true });
  3371. out({
  3372. ok: true,
  3373. loginRequired: !status.tokenPresent,
  3374. instructions: status.tokenPresent
  3375. ? "Already authenticated. No action required."
  3376. : "Open OpenLoomi Desktop and complete sign-in. The plugin will detect the token automatically. Alternatively, run `guest-login` for a one-tap guest account.",
  3377. status,
  3378. });
  3379. return;
  3380. }
  3381. case "guest-login": {
  3382. const r = await cmdGuestLogin({
  3383. baseUrl: process.env.OPENLOOMI_BASE_URL || null,
  3384. });
  3385. // Sanitize: never echo the raw token; report the path on success so
  3386. // the caller can confirm the file landed.
  3387. if (r.ok) {
  3388. out({ ok: true, guest: "ok", user: r.user, tokenPath: r.tokenPath });
  3389. } else {
  3390. out(
  3391. {
  3392. ok: false,
  3393. guest: r.code || "failed",
  3394. error: r.error || null,
  3395. status: r.status || null,
  3396. },
  3397. 1,
  3398. );
  3399. }
  3400. return;
  3401. }
  3402. case "pet": {
  3403. const state = args._[1];
  3404. const r = await cmdPet(state);
  3405. out(r, r.ok ? 0 : 1);
  3406. return;
  3407. }
  3408. case "state": {
  3409. const name = args._[1];
  3410. const event = args.event || null;
  3411. const r = await cmdState(name, { event });
  3412. out(r);
  3413. return;
  3414. }
  3415. case "archive": {
  3416. // Hooks must always exit 0. We capture the result and print, but
  3417. // never set a non-zero exit code from this path.
  3418. try {
  3419. const r = await cmdArchive();
  3420. process.stdout.write(JSON.stringify(r) + EOL);
  3421. } catch {
  3422. process.stdout.write(
  3423. JSON.stringify({
  3424. continue: true,
  3425. _openloomi: { archive: "skipped", reason: "exception" },
  3426. }) + EOL,
  3427. );
  3428. }
  3429. process.exit(0);
  3430. return;
  3431. }
  3432. case "usage": {
  3433. const r = await cmdUsage();
  3434. out(r, r.ok ? 0 : 0);
  3435. return;
  3436. }
  3437. case "install-hooks": {
  3438. const r = installHooks({ yes: !!args.yes });
  3439. out(r, r.ok ? 0 : 1);
  3440. return;
  3441. }
  3442. case "uninstall-hooks": {
  3443. const r = uninstallHooks();
  3444. out(r, r.ok ? 0 : 1);
  3445. return;
  3446. }
  3447. case "hooks-status": {
  3448. const installed = detectHooksInstalled();
  3449. const settings = readSettings();
  3450. out({
  3451. ok: true,
  3452. installed,
  3453. settingsPath: settings.path,
  3454. marker: MARKER,
  3455. legacyBlockKey: PLUGIN_BLOCK_KEY,
  3456. schema: "per-event",
  3457. });
  3458. return;
  3459. }
  3460. case "help": {
  3461. process.stdout.write(
  3462. [
  3463. "loomi-bridge.mjs <subcommand> [...flags]",
  3464. "",
  3465. "Subcommands:",
  3466. " version print plugin version",
  3467. " setup full setup wizard",
  3468. " setup-status [--json] stable JSON status",
  3469. " install [--yes] user-approved install",
  3470. " login check token presence",
  3471. " guest-login one-tap guest bearer (writes ~/.openloomi/token)",
  3472. " pet <state> set OpenLoomi Pet state",
  3473. " state <name> [--event E] fire-and-forget state (hook)",
  3474. " archive archive last Stop transcript (hook)",
  3475. " usage GET /api/llm/usage/summary",
  3476. " install-hooks merge into ~/.claude/settings.json",
  3477. " uninstall-hooks strip plugin hook block",
  3478. " hooks-status report merge state",
  3479. " help this help",
  3480. "",
  3481. ].join("\n"),
  3482. );
  3483. return;
  3484. }
  3485. default: {
  3486. err("UNKNOWN_SUBCOMMAND", `Unknown subcommand: ${sub || "(none)"}`, {
  3487. valid: [
  3488. "version",
  3489. "setup",
  3490. "setup-status",
  3491. "install",
  3492. "login",
  3493. "guest-login",
  3494. "pet",
  3495. "state",
  3496. "archive",
  3497. "usage",
  3498. "install-hooks",
  3499. "uninstall-hooks",
  3500. "hooks-status",
  3501. "help",
  3502. ],
  3503. });
  3504. return;
  3505. }
  3506. }
  3507. }
  3508. main().catch((e) => {
  3509. // Top-level catch: print JSON, exit 1.
  3510. process.stdout.write(
  3511. JSON.stringify({
  3512. ok: false,
  3513. code: "UNEXPECTED",
  3514. error: String(e?.stack || e?.message || e),
  3515. }) + EOL,
  3516. );
  3517. process.exit(1);
  3518. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.