No agent selected
+Add your Midnight City API token in Settings to list your agents, or add an agent by its ID.
+diff --git a/addons/midnight-addon/LICENSE b/addons/midnight-addon/LICENSE new file mode 100644 index 0000000..4bcf45e --- /dev/null +++ b/addons/midnight-addon/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Mauricio Prieto Davila (notsoblack) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/addons/midnight-addon/README.md b/addons/midnight-addon/README.md new file mode 100644 index 0000000..d3505f1 --- /dev/null +++ b/addons/midnight-addon/README.md @@ -0,0 +1,61 @@ +# π Midnight City β a Mosaic Companion add-on + +A renderer-only add-on for [Mosaic Companion](https://github.com/hypercycle-development/mosaic-companion) that puts your **Midnight City agents** and the **midnight-wallet** toolbox in one panel: live agent status, vitals, skills, inventory, wallet snapshot, and a grouped MCP tool explorer. + +Bring your own Midnight City API token (Settings) and the add-on lists the agents on your account. Nothing is hard-coded to one user β each person's token and agent selection live in their own add-on settings. + +## What it does + +| Feature | How | +|---|---| +| Agent list | Add agents by ID, or paste an API token and **Sync from account**. The first agent is auto-selected on boot. | +| Agent detail | Status, location, control channel, health / hunger bars, skills with progress, inventory chips, load stats. | +| Wallet strip | Address, balance, network, and the connected midnight-wallet MCP server. | +| Toolbox | Every tool on every connected MCP server, grouped by functional prefix (Wallet, Localnet, Contracts, Grants, Swaps, Dust, Config, Transactions, Utilities). One-click run for zero-arg tools; JSON args for the rest. | +| Live status | A status pill (ok / warn) on every action, refresh pill with last-updated time, observer polling. | + +## Layout + +``` +midnight-addon/ +βββ manifest.json # id "midnight-addon", tab mount "Midnight", permissions +βββ renderer/ # no build step β served directly by the add-on loader +β βββ index.html +β βββ app.js # vanilla JS, drives addonAPI.mcp + observer REST +β βββ style.css # muted palette, Inter/system-ui, 6β10px radii +βββ src/index.ts # inert scaffolding (not loaded) +βββ package.json # inert β the loader reads manifest.json, not package.json +βββ tsconfig.json +``` + +## Permissions + +`wallet:read`, `mcp:read`, `mcp:call` β the add-on only reads wallet state and calls tools on servers the user has already connected in Mosaic. No `wallet:sign`. + +## Install as a dev add-on + +Register it in `~/.config/mosaic-companion/addon-state.json`: + +```json +"midnight-addon": { + "version": "0.2.0", + "activated": true, + "grantedPermissions": ["wallet:read", "mcp:read", "mcp:call"], + "linkVisibilityToActivation": true, + "source": { "type": "dev", "path": "/path/to/midnight-addon" } +} +``` + +Then open the **Midnight** tab in Mosaic Companion. + +## Submitting to the catalogue + +The catalogue submission lives in `hypercycle-development/mosaic-open-platform` under `addons/midnight-addon/` (manifest, `renderer/`, `LICENSE`). Both adjudication gates (`scripts/adjudicate/adjudicate.mjs` and `checks.mjs`) must pass before the PR. + +## Licence + +MIT β see `LICENSE`. + +--- + +Built for the Midnight City ops team: @hermes, @nighter, @debugger diff --git a/addons/midnight-addon/manifest.json b/addons/midnight-addon/manifest.json new file mode 100644 index 0000000..6a658a5 --- /dev/null +++ b/addons/midnight-addon/manifest.json @@ -0,0 +1,27 @@ +{ + "manifestVersion": 1, + "id": "midnight-addon", + "version": "0.2.0", + "minAppVersion": "0.1.13", + "name": "Midnight City", + "description": "Your Midnight City agents at a glance: live status, vitals, skills and inventory, plus the Mosaic wallet and the midnight-wallet toolbox. Bring your own API token to manage your agents.", + "author": "notsoblack", + "ipcNamespace": "midnight", + "mountPoint": "tab", + "tab": { + "label": "Midnight", + "icon": "Star", + "order": 200 + }, + "renderer": { + "entry": "renderer/index.html" + }, + "permissions": [ + "wallet:read", + "mcp:read", + "mcp:call" + ], + "updates": { + "checkMode": "manual" + } +} diff --git a/addons/midnight-addon/renderer/app.js b/addons/midnight-addon/renderer/app.js new file mode 100644 index 0000000..6ee0ccd --- /dev/null +++ b/addons/midnight-addon/renderer/app.js @@ -0,0 +1,543 @@ +// Midnight City β addon for Mosaic Companion. +// A read-only console over the public Midnight City observer, plus the Mosaic +// wallet strip and the midnight-wallet MCP toolbox. State lives in memory; +// credentials and the agent list persist in this addon's local settings. + +const api = window.addonAPI; + +const DEFAULTS = { + observerUrl: "https://www.midnight.city/observer", + apiToken: "", + agents: [], // [{ id }] + selectedAgentId: "", +}; +const POLL_MS = 5000; +const WALLET_SERVER = "midnight-wallet"; + +const state = { + settings: { ...DEFAULTS }, + cache: new Map(), // agentId -> { context, needs, progression, inventory, fetchedAt, error } + polling: false, + tools: [], +}; + +/* ββ DOM helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */ +const $ = (sel) => document.querySelector(sel); + +function el(tag, attrs = {}, ...children) { + const node = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (v === null || v === undefined || v === false) continue; + if (k === "class") node.className = v; + else if (k === "text") node.textContent = v; + else if (k === "style") node.style.cssText = v; + else if (k.startsWith("on")) node.addEventListener(k.slice(2), v); + else node.setAttribute(k, v); + } + for (const child of children.flat()) { + if (child === null || child === undefined || child === false) continue; + node.append(child instanceof Node ? child : document.createTextNode(String(child))); + } + return node; +} + +const num = (n) => Number(n || 0).toLocaleString("en-US"); +const compact = (n) => { + const v = Number(n || 0); + if (Math.abs(v) >= 1e6) return `${(v / 1e6).toFixed(2).replace(/\.?0+$/, "")}M`; + if (Math.abs(v) >= 1e4) return `${(v / 1e3).toFixed(1).replace(/\.0$/, "")}k`; + return num(v); +}; +const titleCase = (s) => String(s ?? "").replace(/[_-]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()); +const shortHex = (s, keep = 6) => (s && s.length > keep * 2 + 2 ? `${s.slice(0, keep)}β¦${s.slice(-keep)}` : s || "β"); + +function timeAgo(ms) { + if (!ms) return "β"; + const s = Math.round((ms - Date.now()) / 1000); + const past = s < 0; + const a = Math.abs(s); + if (a < 5) return past ? "just now" : "now"; + const fmt = past ? (t) => `${t} ago` : (t) => `in ${t}`; + if (a < 60) return fmt(`${a}s`); + if (a < 3600) return fmt(`${Math.round(a / 60)}m`); + if (a < 86400) return fmt(`${Math.round(a / 3600)}h`); + return fmt(`${Math.round(a / 86400)}d`); +} + +/* ββ settings ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */ +async function loadSettings() { + try { + const stored = await api.settings.get(); + state.settings = { ...DEFAULTS, ...(stored || {}) }; + } catch { + state.settings = { ...DEFAULTS }; + } + state.settings.agents = Array.isArray(state.settings.agents) + ? state.settings.agents.filter((a) => a && typeof a.id === "string") + : []; +} + +async function saveSettings(patch = {}) { + Object.assign(state.settings, patch); + await api.settings.set({ ...state.settings }); +} + +/* ββ observer client βββββββββββββββββββββββββββββββββββββββββββββββββββββ */ +function observerBase() { + return String(state.settings.observerUrl || DEFAULTS.observerUrl).trim().replace(/\/+$/, ""); +} + +async function observer(path, { auth = false, timeoutMs = 10000 } = {}) { + const headers = {}; + if (auth && state.settings.apiToken) headers.Authorization = `Bearer ${state.settings.apiToken}`; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + try { + const res = await fetch(observerBase() + path, { headers, signal: controller.signal, cache: "no-store" }); + if (!res.ok) throw new Error(`${res.status} ${res.statusText}`.trim()); + return await res.json(); + } finally { + clearTimeout(timer); + } +} + +const agentPath = (id, view) => `/api/skill/agents/${encodeURIComponent(id)}/${view}`; + +async function fetchBundle(id) { + const [context, needs, progression, inventory] = await Promise.all([ + observer(agentPath(id, "context")), + observer(agentPath(id, "needs")), + observer(agentPath(id, "progression")), + observer(agentPath(id, "inventory")), + ]); + return { context, needs, progression, inventory, fetchedAt: Date.now(), error: null }; +} + +async function fetchContextOnly(id) { + const context = await observer(agentPath(id, "context")); + return { context, fetchedAt: Date.now(), error: null }; +} + +/* ββ polling βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */ +let pollTimer = null; + +async function refreshAll({ deep = false } = {}) { + if (state.polling) return; + state.polling = true; + try { + const { agents, selectedAgentId } = state.settings; + await Promise.all(agents.map(async ({ id }) => { + const prev = state.cache.get(id) || {}; + try { + const full = deep || id === selectedAgentId; + state.cache.set(id, full ? await fetchBundle(id) : { ...prev, ...(await fetchContextOnly(id)) }); + } catch (err) { + state.cache.set(id, { ...prev, error: err.message, notFound: /^404\b/.test(err.message) }); + } + })); + const errors = agents.filter(({ id }) => state.cache.get(id)?.error).length; + setPill("net-pill", errors === agents.length && agents.length ? "bad" : errors ? "warn" : "ok", + `observer Β· ${agents.length} agent${agents.length === 1 ? "" : "s"}${errors ? ` Β· ${errors} unreachable` : ""}`); + } catch (err) { + setPill("net-pill", "bad", `observer Β· ${err.message}`); + } finally { + state.polling = false; + setPill("refresh-pill", "muted", `updated ${new Date().toLocaleTimeString()}`); + } + render(); +} + +function startPolling() { + clearInterval(pollTimer); + pollTimer = setInterval(() => { refreshAll({ deep: true }); }, POLL_MS); +} + +/* ββ top-bar pills βββββββββββββββββββββββββββββββββββββββββββββββββββββββ */ +function setPill(id, kind, text) { + const node = document.getElementById(id); + if (!node) return; + node.className = `pill pill-${kind}`; + node.textContent = text; + node.title = text; +} + +/* ββ rail ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */ +const STATUS_DOT = { busy: "busy", awake: "ok", idle: "ok", sleeping: "warn", dead: "bad", starving: "bad" }; + +function renderRail() { + const list = $("#agent-list"); + const { agents, selectedAgentId } = state.settings; + list.replaceChildren(...agents.map(({ id }) => { + const data = state.cache.get(id) || {}; + const agent = data.context?.agent || {}; + const status = data.error ? (data.notFound ? "not found" : "unreachable") : (agent.status || "unknown"); + return el("li", { + class: `agent${id === selectedAgentId ? " active" : ""}`, + role: "button", tabindex: "0", + onclick: () => selectAgent(id), + onkeydown: (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); selectAgent(id); } }, + }, + el("div", { class: "agent-top" }, + el("span", { class: `dot dot-${data.error ? "bad" : (STATUS_DOT[agent.status] || "")}`, title: status }), + el("span", { class: "agent-name", text: agent.name || `agent β¦${id.slice(-6)}` }), + ), + el("div", { class: "agent-meta" }, + el("span", { text: agent.profession ? titleCase(agent.profession) : status }), + el("span", { class: "agent-id", text: id }), + ), + ); + })); + + const hint = $("#rail-hint"); + hint.textContent = agents.length === 0 + ? "Open Settings to add your API token and sync your agents." + : state.settings.apiToken ? "" : "Agents added by hand. Add an API token to sync from your account."; +} + +/* ββ detail ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */ +function bar(kind, pct) { + return el("div", { class: "bar" }, el("i", { class: kind, style: `width:${Math.max(0, Math.min(100, pct))}%` })); +} + +function vital(label, value, max, kind) { + return el("div", { class: "vital" }, + el("div", { class: "vital-top" }, + el("span", { class: "label", text: label }), + el("span", { class: "mono", text: `${Math.round(value)} / ${Math.round(max)}` }), + ), + bar(kind, (value / max) * 100), + ); +} + +function cardHead(title, meta) { + return el("div", { class: "card-head" }, + el("h2", { text: title }), + el("span", { class: "label", text: meta }), + ); +} + +function kv(k, v) { + return [el("dt", { text: k }), el("dd", { text: v })]; +} + +function renderDetail() { + const detail = $("#detail"); + const id = state.settings.selectedAgentId; + const data = id ? state.cache.get(id) : undefined; + const ctx = data?.context; + + if (!id || !ctx) { + detail.replaceChildren(el("div", { class: "detail-empty" }, + el("p", { class: "detail-empty-title", text: data?.error ? "Agent unreachable" : "No agent selected" }), + el("p", { class: "muted", text: data?.error ? `${id} Β· ${data.error}` : "Add your Midnight City API token in Settings to sync your agents, or add an agent by its ID." }), + )); + return; + } + + const agent = ctx.agent || {}; + const action = ctx.activeAction || null; + const hunger = data.needs?.hunger; + const vitals = data.progression?.vitals; + const skills = data.progression?.skills || {}; + const inventory = data.inventory?.inventory || {}; + const load = data.inventory?.load; + const control = ctx.controlStatus || {}; + const status = agent.status || "unknown"; + const healthPct = vitals?.maxHealth ? vitals.health / vitals.maxHealth : 1; + + const hero = el("section", { class: "hero" }, + el("div", { class: "hero-main" }, + el("div", { class: "hero-name" }, + el("span", { class: `dot dot-${STATUS_DOT[status] || ""}` }), + el("h3", { text: agent.name || id }), + agent.profession && el("span", { class: "hero-tag", text: titleCase(agent.profession) }), + ), + el("div", { class: "hero-sub" }, + agent.position && el("span", {}, "at ", el("b", { text: `${titleCase(ctx.currentSpace?.name || agent.position.spaceId)} Β· ${agent.position.x}, ${agent.position.y}` })), + el("span", {}, "status ", el("b", { text: status })), + control.mode && el("span", {}, "control ", el("b", { text: `${control.mode} Β· ${control.state || "β"}` })), + ), + ), + el("div", { class: "hero-when" }, + el("div", { text: `observed ${timeAgo(data.fetchedAt)}` }), + el("div", { text: `tick ${num(ctx.tick)}` }), + ), + (vitals?.maxHealth || hunger) && el("div", { class: "vitals" }, + vitals?.maxHealth && vital("health", vitals.health, vitals.maxHealth, healthPct >= 0.4 ? "ok" : "bad"), + hunger && vital(`hunger Β· ${hunger.state}`, hunger.value, 100, hunger.state === "starving" ? "bad" : hunger.state === "hungry" ? "warn" : "ok"), + ), + action && el("div", { class: "activity" }, + el("span", { class: "dot dot-busy" }), + el("span", { class: "mono", text: action.activity }), + action.engageTargetId && el("span", { class: "muted", text: `β ${action.engageTargetId}` }), + el("span", { class: "muted", text: `${action.phase || "active"} Β· ends ${timeAgo(action.endsAtMs)}` }), + ), + ); + + const topSkills = Object.entries(skills) + .map(([name, s]) => ({ name, ...s })) + .sort((a, b) => (b.level - a.level) || (b.xp - a.xp)) + .slice(0, 6); + + const skillsCard = el("section", { class: "card" }, + cardHead("Skills", `${Object.keys(skills).length} tracked`), + topSkills.length + ? topSkills.map(({ name, level, xp, nextLevelXp }) => el("div", { class: "skill" }, + el("span", { class: "skill-name", text: titleCase(name) }), + el("span", { + class: "skill-lv", + text: nextLevelXp ? `Lv ${level} Β· ${compact(xp)} / ${compact(nextLevelXp)} xp` : `Lv ${level}`, + title: nextLevelXp ? `${num(xp)} / ${num(nextLevelXp)} xp` : "", + }), + bar("ok", nextLevelXp ? (xp / nextLevelXp) * 100 : 100), + )) + : el("p", { class: "muted", text: "No skill data yet." }), + ); + + const items = Object.entries(inventory).sort((a, b) => b[1] - a[1]).slice(0, 18); + const inventoryCard = el("section", { class: "card" }, + cardHead("Inventory", `${Object.keys(inventory).length} items`), + items.length + ? el("div", { class: "chips" }, items.map(([name, qty]) => el("span", { class: "chip" }, + el("span", { class: "chip-name", text: titleCase(name) }), + el("b", { text: num(qty) }), + ))) + : el("p", { class: "muted", text: "Empty." }), + load && el("p", { class: "hint", text: `Load ${load.state} Β· heaviest ${titleCase(load.heaviestItem || "β")} Β· work speed ${load.workSpeedPercent ?? "β"}%` }), + ); + + const profileCard = el("section", { class: "card" }, + cardHead("Profile", agent.id ? `β¦${agent.id.slice(-8)}` : ""), + el("dl", { class: "kv" }, + kv("Agent", agent.id || id), + kv("Control", `${control.mode || "β"} Β· ${control.state || "β"}`), + kv("Job", agent.isPerformingJob ? "in progress" : "none"), + kv("Conversation", agent.canStartConversation ? "open" : "closed"), + kv("Module", ctx.activeModule?.id || "β"), + ctx.latestSkillVersion && kv("Skill bundle", ctx.latestSkillVersion.version), + ), + ); + + detail.replaceChildren(hero, el("div", { class: "grid" }, skillsCard, inventoryCard, profileCard)); +} + +function render() { + renderRail(); + renderDetail(); +} + +async function selectAgent(id) { + await saveSettings({ selectedAgentId: id }); + render(); + refreshAll({ deep: true }); +} + +/* ββ wallet strip (Mosaic wallet, read-only) βββββββββββββββββββββββββββββ */ +async function loadWallet() { + try { + const [address, balance, network] = await Promise.all([ + api.wallet.getAddress(), + api.wallet.getBalance(), + api.wallet.getNetworkInfo(), + ]); + $("#wallet-address").textContent = shortHex(address); + $("#wallet-address").title = address || ""; + $("#wallet-balance").textContent = balance ? `${num(Number(balance.balance) / 1e18)} ${balance.symbol}` : "β"; + $("#wallet-balance").title = balance ? `${balance.balance} wei` : ""; + $("#wallet-network").textContent = network?.name || network?.networkId || "β"; + setPill("wallet-pill", address ? "ok" : "warn", address ? "wallet Β· ready" : "wallet Β· not set up"); + } catch (err) { + setPill("wallet-pill", "bad", "wallet Β· unavailable"); + $("#wallet-network").textContent = err.message; + } +} + +/* ββ toolbox: midnight-wallet MCP ββββββββββββββββββββββββββββββββββββββββ */ +async function loadTools() { + const select = $("#tool-select"); + select.replaceChildren(el("option", { value: "", text: "Loading toolsβ¦" })); + try { + const tools = await api.mcp.listTools(WALLET_SERVER); + state.tools = Array.isArray(tools) ? tools : []; + const categories = [ + ["wallet", "Wallet"], ["localnet", "Localnet"], ["contract", "Contracts"], ["grant", "Grants"], + ["swap", "Swaps"], ["dust", "Dust"], ["config", "Config"], ["tx", "Transactions"], + ]; + const groups = new Map(categories.map(([k, label]) => [k, { label, items: [] }])); + groups.set("other", { label: "Utilities", items: [] }); + for (const t of state.tools) { + const name = t.name.replace(/^midnight_/, ""); + const key = name.split("_")[0]; + (groups.get(key) ?? groups.get("other")).items.push({ name, full: t.name }); + } + select.replaceChildren(...[...groups.values()].filter((g) => g.items.length).map((g) => + el("optgroup", { label: g.label }, ...g.items.map((t) => el("option", { value: t.full, text: t.name }))) + )); + if (state.tools.length === 0) select.replaceChildren(el("option", { value: "", text: `No tools from β${WALLET_SERVER}β β is it enabled in MCP settings?` })); + else onToolChange(); + } catch (err) { + select.replaceChildren(el("option", { value: "", text: `Toolbox unavailable: ${err.message}` })); + } +} + +function onToolChange() { + const name = $("#tool-select").value; + const tool = state.tools.find((t) => t.name === name); + const required = tool?.inputSchema?.required || []; + const props = tool?.inputSchema?.properties || {}; + const template = Object.fromEntries(Object.keys(props).map((k) => [k, required.includes(k) ? `<${props[k].type || "value"}>` : ""])); + $("#tool-args").value = template && Object.keys(template).length ? JSON.stringify(template) : "{}"; + $("#tool-output").textContent = tool?.description || ""; +} + +async function runTool() { + const name = $("#tool-select").value; + const out = $("#tool-output"); + if (!name) return; + let args; + try { + args = JSON.parse($("#tool-args").value || "{}"); + } catch (err) { + out.textContent = `Arguments must be JSON: ${err.message}`; + return; + } + const button = $("#tool-run"); + button.disabled = true; + out.textContent = `Running ${name}β¦`; + try { + const result = await api.mcp.callTool(WALLET_SERVER, name, args); + const text = (result?.content || []).map((c) => c.text ?? JSON.stringify(c)).join("\n"); + out.textContent = text || JSON.stringify(result, null, 2); + } catch (err) { + const { code } = api.parseError(err); + out.textContent = `Error ${code || ""}: ${err.message}`; + } finally { + button.disabled = false; + } +} + +/* ββ settings drawer βββββββββββββββββββββββββββββββββββββββββββββββββββββ */ +function openDrawer() { + $("#drawer").classList.add("open"); + $("#drawer").setAttribute("aria-hidden", "false"); + $("#drawer-backdrop").hidden = false; + $("#set-url").value = state.settings.observerUrl; + $("#set-token").value = state.settings.apiToken; + $("#set-token").type = "password"; + $("#btn-token-show").textContent = "Show"; + renderSettingsAgents(); + $("#settings-status").textContent = ""; +} + +function closeDrawer() { + $("#drawer").classList.remove("open"); + $("#drawer").setAttribute("aria-hidden", "true"); + $("#drawer-backdrop").hidden = true; +} + +function renderSettingsAgents() { + $("#set-agent-list").replaceChildren(...state.settings.agents.map(({ id }) => el("li", {}, + el("span", { text: id }), + el("button", { class: "btn btn-sm", type: "button", text: "Remove", onclick: () => removeAgent(id) }), + ))); +} + +async function addAgent(id) { + id = id.trim(); + if (!/^user-agent-[a-z0-9]+$/.test(id)) { + showStatus(`β${id || "β "}β is not an agent ID (user-agent-β¦).`, false); + return; + } + if (state.settings.agents.some((a) => a.id === id)) return showStatus("Already in the list.", true); + const patch = { agents: [...state.settings.agents, { id }] }; + if (!state.settings.selectedAgentId) patch.selectedAgentId = id; + await saveSettings(patch); + renderSettingsAgents(); + showStatus(`Added ${id}.`, true); + render(); + refreshAll({ deep: true }); +} + +async function removeAgent(id) { + const agents = state.settings.agents.filter((a) => a.id !== id); + const patch = { agents }; + if (state.settings.selectedAgentId === id) patch.selectedAgentId = agents[0]?.id || ""; + await saveSettings(patch); + state.cache.delete(id); + renderSettingsAgents(); + render(); +} + +async function syncAgentsFromAccount() { + if (!state.settings.apiToken) return showStatus("Add your API token first.", false); + await saveSettings({ apiToken: $("#set-token").value.trim(), observerUrl: $("#set-url").value.trim() }); + try { + const { agentIds } = await observer("/api/local-control/claimable", { auth: true }); + const known = new Set(state.settings.agents.map((a) => a.id)); + const merged = [...state.settings.agents, ...(agentIds || []).filter((id) => !known.has(id)).map((id) => ({ id }))]; + await saveSettings({ agents: merged }); + renderSettingsAgents(); + showStatus(`${agentIds.length} agent(s) on your account; ${merged.length} listed.`, true); + refreshAll({ deep: true }); + } catch (err) { + showStatus(`Sync failed: ${err.message}`, false); + } +} + +async function saveAndTest(e) { + e.preventDefault(); + const url = $("#set-url").value.trim(); + const token = $("#set-token").value.trim(); + await saveSettings({ observerUrl: url, apiToken: token }); + try { + await observer("/api/stats"); + if (token) await observer("/api/local-control/claimable", { auth: true }); + showStatus("Connection OK.", true); + refreshAll({ deep: true }); + } catch (err) { + showStatus(`Connection failed: ${err.message}`, false); + } +} + +function showStatus(text, ok) { + const node = $("#settings-status"); + node.textContent = text; + node.className = `status ${ok ? "status-ok" : "status-bad"}`; +} + +/* ββ boot ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */ +async function boot() { + $("#btn-refresh").addEventListener("click", () => refreshAll({ deep: true })); + $("#btn-settings").addEventListener("click", openDrawer); + $("#btn-drawer-close").addEventListener("click", closeDrawer); + $("#drawer-backdrop").addEventListener("click", closeDrawer); + $("#btn-add-agent").addEventListener("click", () => { openDrawer(); $("#set-agent-id").focus(); }); + document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeDrawer(); }); + + $("#settings-form").addEventListener("submit", saveAndTest); + $("#btn-sync").addEventListener("click", syncAgentsFromAccount); + $("#btn-agent-add").addEventListener("click", () => addAgent($("#set-agent-id").value)); + $("#set-agent-id").addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); addAgent(e.target.value); } }); + $("#btn-token-show").addEventListener("click", () => { + const input = $("#set-token"); + const show = input.type === "password"; + input.type = show ? "text" : "password"; + $("#btn-token-show").textContent = show ? "Hide" : "Show"; + }); + + $("#tool-select").addEventListener("change", onToolChange); + $("#tool-run").addEventListener("click", runTool); + + await loadSettings(); + if (!state.settings.selectedAgentId && state.settings.agents.length) { + state.settings.selectedAgentId = state.settings.agents[0].id; + saveSettings({ selectedAgentId: state.settings.selectedAgentId }); + } + render(); + loadWallet(); + loadTools(); + await refreshAll({ deep: true }); + startPolling(); +} + +boot(); diff --git a/addons/midnight-addon/renderer/index.html b/addons/midnight-addon/renderer/index.html new file mode 100644 index 0000000..af2fa99 --- /dev/null +++ b/addons/midnight-addon/renderer/index.html @@ -0,0 +1,125 @@ + + +
+ + +No agent selected
+Add your Midnight City API token in Settings to list your agents, or add an agent by its ID.
+