AUDIO

Listen to this page

0:00
Chapters

    Developing holai plugins (API contract)

    A holai plugin is one folder with manifest.json + index.js where index.js exports an object with execute(...) (the Tool the AI agent calls), optionally routes(...) (admin HTTP API) plus ui/index.html (its own admin screen). One plugin = ONE tool: the plugin name IS the tool name and the argument surface is switched with an action enum inside execute.

    You develop in your instance's server/plugins/<name>/ folder, test it live, and — when ready — publish the exact folder as an npm package; from then on users install it from the dashboard marketplace by keyword search (marketplace).

    1. Folder layout

    my-plugin/
    ├── manifest.json      # the tool schema the AI sees + permissions + UI entry
    ├── index.js           # module.exports = { execute(args, ctx), routes?(ctx), health?() }
    ├── ui/index.html      # optional: own admin screen (iframe page)
    ├── ui/i18n/*.json     # optional: translations for the admin page (see §6)
    ├── migrations/        # optional: data-dir migrations for updates
    └── package.json       # for npm publishing (version must equal manifest version)
    

    2. manifest.json

    {
      "name": "my_plugin",
      "version": "1.0.0",
      "description": "What the tool does — the agent chooses it by this text, so
                      write it for the AI, not for humans.",
      "parameters": {
        "type": "object",
        "properties": {
          "action": {
            "type": "string",
            "enum": ["list", "run"],
            "description": "'list' shows ..., 'run' starts ..."
          }
        },
        "required": ["action"]
      },
      "ui": { "title": "My plugin", "entry": "ui/index.html" },
      "permissions": {
        "scopes": ["devices:lights:write"],
        "minRole": "user"
      }
    }
    

    Rules enforced by the core: folder name == name; npm package version == manifest version; first install + every new scope asks the admin for approval (marketplace). minRole applies to tool calls for every user.

    The AI permission gate (architecture "AI permissions & consent") reads one more optional field: "control": { "actions": ["run"], "plugin": true, "description": "…" } — the action values that CHANGE the real world. Each such call passes the user's consent (allow / ask each time / deny). With "plugin": true the core skips its generic gate and your plugin confirms per RESOLVED subject via ctx.confirm (a device id, a scenario) — the bundled tuya, manage_light and scenarios plugins do this; without it the core gates on the tool level. Read-only actions belong in no control list — queries never ask.

    One more manifest field the backup plugin understands: "backup": { "include": ["vault"] } — directory names (relative to your data dir) that travel in the disaster-recovery zip as files/<name>/… (plugins/backup); use it only for files that MUST live on disk for external tools (e.g. the obsidian vault) — everything else stays in ctx.sqlStore.

    3. index.js — the shape

    class MyPlugin {
      // ---- the TOOL (called by the AI agent / voice pipeline) ----
      async execute(args, ctx) {
        try {
          switch (args?.action) {
            case 'list': return { success: true, message: '…', data: {…} };
            case 'run':  return { success: true, message: 'done', data: {…} };
            default: return { success: false, error: `unknown action "${args?.action}"` };
          }
        } catch (err) {
          return { success: false, error: err.message }; // human error, never a crash
        }
      }
    
      // ---- own HTTP routes under /api/v1/plugins/<name>/… (optional) ----
      routes(ctx) {
        return [
          { method: 'GET', path: '/status', role: 'user', handler: (req, res) => res.json({ ok: true }) },
          { method: 'PUT', path: '/settings', role: 'admin', handler: (req, res) => { /* … */ } },
        ];
      }
    }
    
    module.exports = new MyPlugin();
    
    • Returned values are { success, message?, data?, error? } — the agent quotes message to the user by voice; a tool's own SUCCESS message is authored by the plugin (server-side service phrases/failures are already localized by the core, see agent-and-language). Set data.noData = true when the tool found NOTHING for a knowledge-style lookup (e.g. the household birthday list has no such person) — the pipeline then asks the configured AI provider for a direct general-knowledge answer ("birthday Pushkin") and uses it as the spoken reply; without a provider answer your "not found" phrase stays. Never set it for live-data misses (devices, weather) — the provider must not invent readings.
    • Route role is enforced by the core (kid < guest < user < admin); authentication and scope checks happen BEFORE your handler runs. A route can never shadow core plugin-management endpoints (matched after core routes had their chance). Throw errors with a status code — raw errors become HTTP 500.
    • An optional health() method runs after plugin updates; throw to roll back.
    • THE LOCALIZATION RULE — tools speak in the user's language: the core injects the pipeline language into EVERY tool call (chat, voice, direct /tools calls pass it themselves). A tool SHOULD accept the optional language argument and compose its message in it; en is the fallback for codes it has no phrases for. language is a core-reserved transport key — an undeclared one still passes argument validation.

    HTTP routes detail

    Static UI files — everything below <plugin>/ui/ is served by the core at GET /plugins-ui/<plugin>/<path> (same origin as /admin). Pages are plain HTML/JS (no build step). They authenticate like the SPA does: read holai_token from (same-origin) localStorage and send it as Authorization: Bearer. In the dashboard the page opens at #/pui/<plugin-name>; the nav item appears automatically for users whose role satisfies the plugin's minRole.

    Chat fallback

    Besides execute, a plugin may export chat(text, ctx) — the FIRST enabled plugin doing so becomes the conversational fallback: it answers every request that fits no tool (and every case where the configured LLM provider failed). Return { reply, model? } or null to decline. Reference implementation: plugins/ollama.

    4. The host plugin API — ctx

    Everything you need comes through the ctx argument. Do not require() any core internals — those paths only exist inside the bundled repo and would break once the plugin is installed from npm.

    member what
    ctx.plugin your mount name (== manifest name == tool name)
    ctx.dataDir persistent data dir that survives plugin updates/restarts (<data>/plugin-data/<plugin>/) — for runtime artifacts only (zips, caches, staging files); config state belongs in ctx.sqlStore
    ctx.plugins read-only overview of every LOADED plugin: ctx.plugins() → { name: { dir, dataDir, manifest } } (flat admin-level info; e.g. the backup plugin ships per-plugin declared dirs this way — never write into another plugin's data dir through it)
    ctx.env read-only copy of the env store (dashboard → Settings → Env variables); combine with process.env
    ctx.logger namespaced logger
    ctx.publish(type, payload) publish to the home event bus — pushes to phones over the hub (see hub). Types: notify, or your own <plugin>.<event>; the host stamps plugin: for you
    ctx.token(ttl='10m') short-lived machine JWT (admin, sub: plugin-<name>) for calling the core's own HTTP API or authenticating to YOUR sidecar container (same secret pattern as the cameras plugin worker)
    ctx.sqlStore(sub) a row-level JSON store inside the central holai.db (store table, key plugin-<name>-<sub>), same data/get/set/persist shape as a JsonStore. All persistent plugin state belongs here — the backup zip ships only the db (format 2), so state outside it (Media, artifacts) does not survive a restore. Pre-registry builds kept JSON files in the data dir: imports them on first read and deletes the file, so restored legacy zips re-import automatically
    ctx.user who invoked the tool call: { id, username, role, scopes } (the core stamps the authenticated caller, plugins build per-user credential routing on it; a plugin-internal pseudouser call carries id: null and the plugin's own name)
    ctx.confirm(spec) AI permission gate (architecture "AI permissions & consent"): call it with the RESOLVED subject before actuating — await ctx.confirm({ kind: 'device'|'scenario'|'tool', key, name }). Applies the user's mode (allow → proceeds; ask → a dialog / spoken yes-no until answered; deny → throws 403). Absent on cores without the gate — guard with if (ctx.confirm) so the plugin works on older cores too. Use it when the actuation target is known only inside the plugin (a device id, a scenario); for whole-action gating declare control in the manifest instead
    ctx.dbPath + ctx.snapshot(to) path of the central holai.db and an awaitable consistent copy of it (await ctx.snapshot('<path>')) — disaster-recovery style (the backup plugin ships the whole state with it)

    Need more? Propose an addition to this table instead of bypassing the context — the table is the distribution-stable contract (bundled folder and npm packages get exactly the same API).

    Sidecar services without the docker socket

    A plugin may ship docker-compose.yml next to index.js — the installer merges it into the main stack (COMPOSE_FILE in .env; in a GPU setup the sibling docker-compose.gpu.yml too), so your service joins the holai network and is reachable by name (http://<service>:<port>; pick a name that cannot clash with the core's own services). Doctor warns when it is not merged. Never require() the docker SDK or mount the socket for this. Details: deployment.

    5. ui/index.html (optional admin screen)

    Own HTML page served at /plugins-ui/<name>/, embedded by the dashboard iframe:

    <script>
      const headers = () => ({
        authorization: `Bearer ${localStorage.getItem('holai_token')}`,
        'content-type': 'application/json',
      });
      fetch('/api/v1/plugins/my_plugin/status', { headers: headers() }).then(r => r.json())
    </script>
    

    Dashboard widgets (optional)

    A plugin can offer compact live tiles for the dashboard home screen. Declare them in the manifest:

    "widgets": [
      {
        "id": "last-motion",
        "title": "Last motion",
        "entry": "widgets/last-motion.html",
        "size": [2, 2],
        "min": [2, 1],
        "max": [2, 2]
      }
    ]
    

    size is the default span on the dashboard grid (width × height in grid cells), min/max bound what the user can cycle it to. The HTML lives at ui/widgets/<id>.html — served at /plugins-ui/<name>/widgets/<id>.html and embedded by the dashboard as a small same-origin iframe, so it follows the exact same contract as the admin page: the i18n loader (/plugins-i18n.js, data-i18n, holaiT.ready.then(boot)), the theme contract (holai_theme localStorage + holai-theme postMessage) and the shared token (localStorage.getItem('holai_token')) for calling the plugin's own routes. Keep a widget self-contained, transparent-backgrounded and non-scrolling — it renders inside an 88 px-per-row grid cell, and it refreshes its own data on a timer (the core does not push to widgets). The dashboard home also ships two built-in core widgets (system health, live events) that no plugin provides; the per-user arrangement (order + spans) is persisted by the core's /dashboard/layout route.

    Runtime widget cards: besides the static manifest list, a plugin may implement a widgets(ctx) method in index.js returning extra widget declarations — the core merges the two lists by id (a runtime entry wins on conflict). Tuya uses this to offer one chart card per device that actually reports sensor readings (plugs and hubs without readings get none — their toggles live in the overview widget) (entry: "widgets/device.html?dev=<id>" — the widget takes the device id from its own URL query). Keep the hook cheap: it runs on every /dashboard/widgets call, so serve only cached data and return [] when nothing is available; a slow or throwing hook degrades to the static list only.

    Widget settings: a widget that wants a settings UI declares "settings": true in its manifest entry (or in its runtime widgets(ctx) card) — the dashboard then shows the ⚙ button only on that widget. Widget iframes are same-origin, so the handshake is a plain function call, race-free: the dashboard calls iframe.contentWindow.holaiWidgetSettings() (retrying while the widget is still mounting or its data is still loading) and the widget returns its schema and current values — fields are {id, type:'select'|'multi', label, options:[{v,l}]} (labels pre-translated with the widget's own i18n; options may be dynamic, e.g. the device list), values the current settings; null means "not ready yet". The call may receive the current draft values — a widget can rebuild its options live from them (Tuya: the device checkbox list follows the online/all toggle before Apply). The dashboard renders a generic modal (select = choice buttons, multi = checkboxes), and on apply stores the chosen values as the layout item's s object (per user, in /dashboard/layout) and reloads the iframe with ?s=<urlencoded json> — the widget reads its settings from its own URL:

    let S = {};
    try { S = JSON.parse(new URLSearchParams(location.search).get('s') || '{}'); } catch { }
    

    Native clients (the mobile dashboard tab) embed the same widget pages in WebViews and pass ?token= (accepted by the core's authenticate on every route) and ?lang= — the URL language outranks localStorage, which a foreign WebView has none of.

    Tuya's widgets use this: the overview card filters online-only vs all devices plus a per-device checkbox list; the device card chooses the chart period (24 h / 7 d / 30 d) and which parameters to chart. One widget kind may be placed several times with different settings (the layout item has an iid instance id) — e.g. two cards of the same device, one charting temperature, the other humidity.

    6. Admin page i18n

    Pages include the shared loader once (<script src="/plugins-i18n.js"></script>) and:

    • mark texts with data-i18n="KEY" (textContent), data-i18n-ph="KEY" (placeholder), data-i18n-title="KEY" (title);
    • put translations as flat { KEY: "text with {vars}" } objects into ui/i18n/{en,ru,es,de,pl,fr,nl}.json (en is the fallback table);
    • use const t = window.holaiT.t; for dynamic strings (t('KEY', {count})).

    The chosen language follows the dashboard's holai_lang (live, storage event). A working t() is exposed synchronously, but it returns the raw key until the language table has arrived — a page that draws translated content right away (lists, buttons) waits for holaiT.ready before the first render and may re-render its dynamic parts on the holaiT:lang event when the user switches language.

    Theme contract: plugin pages ship black by default and follow the dashboard's common theme — they read the localStorage key holai_theme ("light" / "dark", default "dark") on load, listen for storage events on that key and for {type:'holai-theme', theme} postMessages from the parent frame, and the page mirrors the palette with an html.light class.

    Modal veil contract: a fixed modal's backdrop only covers the plugin iframe — clicks on the app chrome around it would fall dead. A page with fixed modals reports {type:'holai-modal', open} to the parent whenever one opens/closes; the dashboard host then dims+blurs the whole app AROUND the iframe (the frame stays stacked above the veil) and answers a veil tap with {type:'holai-modal-close'}, which the page handles by closing its open modals. Skip the whole exchange when window.parent === window.

    7. Data dir state

    Store state in ctx.sqlStore — the central SQLite db is the only persistent state layer, and the backup zip ships exactly that db. The ONE exception: folders a user may open/touch with an external app (a text editor, Obsidian …) must live as plain files — declare them (manifest.backup.include) and the backup zip carries them too. The data dir (ctx.dataDir) is for runtime artifacts (caches, staging files); files placed there deliberately fall back as legacy imports: when the store is empty, a <file>.json with the same state shape is imported on first read and removed. When the STATE FORMAT changes across versions, write a numbered migrations/0020-add-field.js descriptor with up(state)/down(state) (lifecycle: marketplace).

    8. Local development workflow

    1. Create server/plugins/my_plugin/ in your running instance with the files above; the loader picks it up at restart — edit + restart (npm run dev reloads on save; in the Docker deployment restart the core container after plugin edits).
    2. Test the tool by voice or via the API: POST /api/v1/tools/my_plugin {"action":"list"} (Bearer token from POST /api/v1/auth/login).
    3. Test routes/UI in the dashboard plugins screen.
    4. Debug the "agent chose it badly" case by sharpening the manifest description and per-action descriptions.

    9. Publishing to npm

    1. Add package.json to the plugin folder:
    {
      "name": "@holai/plugin-my_plugin",     // community: "holai-plugin-my_plugin"
      "version": "1.0.0",                    // == manifest.json version
      "description": "…",
      "keywords": ["holai-plugin"],          // REQUIRED for marketplace discovery
      "main": "index.js",
      "dependencies": {}                     // real deps if any; installed on install
    }
    
    1. npm publish (scoped packages need --access public).
    2. Installs/updates then come from the dashboard: keyword search → Install → approve scope diff → the core stages, validates, migrates, swaps, health-checks and records plugins.lock.json. Rollback restores the previous version directory.
    3. The priority rule protects you: a local folder with the same name in plugins/ IS the source of truth; marketplace operations refuse to overwrite local edits (HTTP 409 + {force: true} to discard on purpose). Details: marketplace.

    10. Reference implementations

    plugin demonstrates
    manage_light minimal tool, no routes/UI (plugins/manage_light)
    esphome presets, data-dir customs, child_process CLI + optional sidecar service (ctx.env-driven), rich UI page (plugins/esphome)
    google_docs OAuth2 flow in routes, multi-account store in ctx.dataDir, token refresh, Google REST calls (plugins/google_docs)
    cameras ctx.publish (phone push on events) + ctx.token (machine JWT to a worker container), media proxying, own dockerized detector (plugins/cameras)
    orbit free external APIs without keys (Open-Meteo, Nager.Date), timezone-aware scheduler in the core process, ctx.publish reminders, big admin UI (plugins/orbit)
    backup ctx.snapshot (consistent db copy), pure-node zip R/W (lib/zip.js), OAuth Drive + minimal FTP (net) + S3 SigV4 without deps, staged pending-restore consumed by the core on restart, format-3 declared-extras packing (plugins/backup)
    obsidian everything-fallback tooling: MCP bridge (streamable-HTTP + stdio child) to the real obsidian-mcp-server, direct-file degraded mode, isomorphic-git auto-commit watcher, backup.include vault (plugins/obsidian)
    composio cloud SaaS bridge: lazy ESM SDK load (import('@composio/core') from a CJS plugin), key-only OAuth handshakes on the Composio side, three-step agent gateway (kits/find/run) (plugins/composio)
    tuya zero-dependency cloud client: HMAC-signed REST (crypto primitives only), token cache + refresh, device cache + DP-code mapper in warmup tick, env/store merged credentials (plugins/tuya)

    Gotchas (project conventions)

    • Route files export factories taking injected deps, e.g. module.exports = function routes({ pluginManager, agent, settingsStore }) — wire new deps in src/index.js (only relevant for core-side routes).
    • Svelte JSX-style \" escapes are invalid inside markup — pass strings as JS expressions or requote (dashboard HTML embedding).
    • Escape HTML from user data (&<>") before injecting.

    Last updated: November 2026