Your home as a live 3D model in the Mac menu bar and on iPhone — lights and ACs via Smart Life, Home Assistant, Philips Hue and Apple Home.
Island: open on a real spring, calm with Reduce Motion, no shoulders
0xProbability93aa66ce5f72
diff --git a/README.md b/README.mdindex 31bc2de..ef6befb 100644--- a/README.md+++ b/README.md@@ -24,6 +24,9 @@- **A visual editor.** Draw the rooms, drop in furniture, place lamps and ACs, and link each one to a real device.- **An island around the notch.** Rest the pointer on the MacBook's notch and a small live model of the home dropsout of it, with scenes and every device one click away. See [The island](#the-island).+- **AI Access.** Give ChatGPT, Claude or any AI assistant a private link — or connect it over MCP — and it runs your+ lights and air conditioners, and rebuilds rooms in the 3D model from your photos. Served by your Mac; Stop ends it.+ See [AI Access](#ai-access).- **An iPhone app.** The same home in your pocket, kept in sync with the Mac over your own Wi-Fi.See [iPhone app](#iphone-app).- **Works without any hardware.** Until you sign in, every device is simulated, so you can try everything first.@@ -67,7 +70,7 @@ There is no Dock icon and no main window: look for the house in the menu bar.| Do this | To get this || --- | --- || Click the menu bar icon | Open or close the panel |-| Right-click the menu bar icon | Edit Home, Load Floor Plan, Reveal Plan File, Reveal Device Log, Show Island, Pair iPhone, Reload, Quit |+| Right-click the menu bar icon | Edit Home, Load Floor Plan, Reveal Plan File, Reveal Device Log, Show Island, Pair iPhone, AI Access, Reload, Quit || Click a lamp in the 3D view, or its tile | Toggle it || Drag sideways across a light tile | Dim it || Click the sliders icon on a light tile | Brightness, white temperature, colour |@@ -100,6 +103,27 @@ When something changes elsewhere — a scene picked in the panel, a lamp switchepeeks out for a moment to say what happened. It never takes the keyboard from the app you are working in.**Show Island** in the menu bar icon's right-click menu turns it off.+## AI Access++<p align="center">+ <img src="docs/ai-access.png" width="380" alt="The AI Access window">+</p>++Right-click the menu bar icon → **AI Access…** → **Start AI Access**, and hand the private link to an assistant:++- **Any chat:** paste it into ChatGPT, Claude, Gemini or Perplexity with your request — *"dim the living room to 30%"*.+ The link opens a guide written for AI assistants, with an action link for everything it can do.+- **Connectors:** add the MCP address as a custom connector in Claude or ChatGPT (or `claude mcp add` in Claude Code)+ and the assistant can also change the home itself: *"here are photos of my living room — rebuild it in 3D"*.+- **Your own agents:** the same tools as plain HTTP + JSON, with an OpenAPI description.++The Mac serves it all: House Control listens on `127.0.0.1` only and is reached through a Cloudflare quick tunnel that+exists while AI Access is on (or not at all, with **This Mac only**). The link carries a 128-bit key, you choose what an+assistant may do, every request shows up live in the window, plan edits can be undone, and **Stop** — or the+auto-stop timer — makes the address disappear. Device IDs and sign-ins never leave the Mac.++Details, every tool, and the privacy model: [docs/ai-access.md](docs/ai-access.md).+## iPhone app<p align="center">@@ -180,6 +204,7 @@ alternative, and how to diagnose a device that does not react — is in [docs/sm## PrivacyHouse Control talks to Tuya's servers and to nothing else. There is no telemetry and no backend of its own.+The one exception is yours to switch on: [AI Access](#ai-access) opens a Cloudflare tunnel to your Mac while it is on.Everything personal stays in `~/Library/Application Support/HouseControl/` on your Mac:@@ -191,6 +216,7 @@ Everything personal stays in `~/Library/Application Support/HouseControl/` on yo| `tuya.json` | Tuya Cloud project credentials, only if you use that option. Mode `600` || `events.log` | Commands sent to real devices and the cloud's answers. No tokens || `sync.json` | The key your paired iPhones use. Only there once you paired one. Mode `600` |+| `cloudflared.yml`, `bin/cloudflared` | An empty config for AI Access's tunnel, and Cloudflare's connector if you let the app download it |None of these are part of this repository, and the build does not embed them in the app.**Sign out** in the editor deletes `smartlife.json`. Deleting the folder resets the app to the demo plan.@@ -200,8 +226,8 @@ On the iPhone the floor plan lives in the app's own folder, and the Smart Life s## Development```-web/ the UI: Three.js scene, panel, island, editor (Vite, plain ES modules)-core/ what both apps share: Smart Life and Tuya clients, plan store, Mac ⇄ iPhone sync (SwiftPM, with tests)+web/ the UI: Three.js scene, panel, island, editor, AI Access window and the AI tools (Vite, plain ES modules)+core/ what both apps share: Smart Life and Tuya clients, plan store, Mac ⇄ iPhone sync, the AI gateway (SwiftPM, with tests)macos/ the Mac shell: menu bar item, panel, island and editor windows (SwiftPM)ios/ the iPhone shell: SwiftUI, generated into an Xcode project by XcodeGenscripts/ build-app.sh, build-ios.sh and ios-sim.sh build the apps, make-icon.swift draws the icon@@ -223,7 +249,7 @@ npm run dev```Then open `http://localhost:5199/`. Add `?plan=studio` for the second demo plan, `?mode=editor` for the editor,-`?mode=island` for the island, `?platform=ios` for the iPhone layout, or `?device=living.ac` to start on a+`?mode=island` for the island, `?mode=agent` for the AI Access window (with a simulated link), `?platform=ios` for the iPhone layout, or `?device=living.ac` to start on adevice's sheet. Set `PORT` to use another port.Environment variables understood by the app:@@ -244,6 +270,9 @@ Environment variables understood by the app:| `HOUSE_COMPUTER_NAME="Studio Mac"` | The name paired iPhones see, instead of the Mac's own (screenshots) || `HOUSE_SNAPSHOT_DIR=/some/folder` | Write `panel.png` and `island.png` there a few seconds after launch || `HOUSE_RENDER_HIDDEN=1` | Keep drawing while the screen is locked, for unattended captures |+| `HOUSE_OPEN_AGENT=1` | Open the AI Access window at launch (`start` also starts the link) |+| `HOUSE_AGENT_REACH=local` | Serve AI Access on this Mac only for one run (`internet` for the tunnel) |+| `HOUSE_AGENT_LINK_FILE=/some/file` | Write the live AI Access link there, for scripted tests |The iPhone app understands `HOUSE_DATA_DIR`, `HOUSE_OPEN_DEVICE` and `HOUSE_SCREEN=home|settings|pairing|smartlife|welcome`;`scripts/ios-sim.sh` passes any `HOUSE_*` variable on to the simulator.diff --git a/core/Sources/HouseCore/AgentGateway.swift b/core/Sources/HouseCore/AgentGateway.swiftnew file mode 100644index 0000000..377336a--- /dev/null+++ b/core/Sources/HouseCore/AgentGateway.swift@@ -0,0 +1,403 @@+import Foundation++/// What the home itself does for an AI: lists its tools, runs them, writes the guide.+/// On the Mac this is the panel's web UI, which owns the state of every device.+@MainActor+public protocol AgentBackend: AnyObject {+ /// `request["op"]` is `tools`, `call`, `guide` or `link`; see `web/src/agent/tools.js`.+ func agentRequest(_ request: [String: Any]) async throws -> [String: Any]+}++/// What an AI may do through the link.+public struct AgentPermissions: Equatable {+ /// Lights, air conditioners and scenes.+ public var control: Bool+ /// The floor plan: rooms, furniture, devices, scenes.+ public var edit: Bool++ public init(control: Bool = true, edit: Bool = true) {+ self.control = control+ self.edit = edit+ }++ var json: [String: Any] { ["control": control, "edit": edit] }+}++/// One line of the activity feed the user watches while an AI has access.+public struct AgentActivity {+ public var date: Date+ /// "ChatGPT", "Claude", "Cursor"… or "AI agent" when it does not say.+ public var client: String+ public var title: String+ public var ok: Bool+ /// True for reads (the guide, the state): the feed shows them quietly.+ public var quiet: Bool++ public init(date: Date = Date(), client: String, title: String, ok: Bool = true, quiet: Bool = false) {+ self.date = date+ self.client = client+ self.title = title+ self.ok = ok+ self.quiet = quiet+ }++ public var json: [String: Any] {+ ["time": date.timeIntervalSince1970 * 1000, "client": client, "title": title, "ok": ok, "quiet": quiet]+ }+}++/// The AI gateway: everything an AI can reach, behind one secret path segment.+///+/// /<token>/ the guide: plain text an AI reads to learn the home (GET)+/// /<token>/do/<action…> actions as plain links, for chat assistants that can only open links (GET)+/// /<token>/mcp Model Context Protocol, Streamable HTTP with JSON responses (POST)+/// /<token>/api/tools the same tools as JSON (GET), run with POST /api/call or /api/<tool>+/// /<token>/openapi.json an OpenAPI description of /api, for GPT actions and agent frameworks+///+/// Anything without the token gets a plain 404, the same as a path that does not exist.+@MainActor+public final class AgentGateway {+ public static let protocolVersions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]+ public static let version = "1.0"++ public weak var backend: AgentBackend?+ public private(set) var token: String+ public var permissions = AgentPermissions()+ /// The address the AI uses, e.g. `https://xyz.trycloudflare.com` or `http://127.0.0.1:7419`.+ public var publicBase = ""+ public var onActivity: ((AgentActivity) -> Void)?++ /// Names of MCP clients by session, as they introduced themselves.+ private var sessions: [String: String] = [:]+ private var recent: [Date] = []+ /// Requests per minute before the gateway answers 429.+ public var rateLimit = 240++ public init(token: String = AgentGateway.makeToken()) {+ self.token = token+ }++ /// 128 random bits, URL-safe.+ nonisolated public static func makeToken() -> String {+ var bytes = [UInt8](repeating: 0, count: 16)+ _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)+ return SyncPairing.base64URL(Data(bytes))+ }++ public func rotateToken() {+ token = Self.makeToken()+ sessions = [:]+ }++ public var linkURL: String { "\(publicBase)/\(token)" }+ public var mcpURL: String { "\(publicBase)/\(token)/mcp" }++ // MARK: - Routing++ public func handle(_ request: HTTPRequest) async -> HTTPResponse {+ // Link checkers ask with HEAD first: the same answer as GET, without the body.+ // Action links never run for HEAD.+ if request.method == "HEAD" {+ var get = request+ get.method = "GET"+ if get.path.split(separator: "/").dropFirst().first == "do" { get.path = get.path.components(separatedBy: "/do/").first ?? get.path }+ var response = await handle(get)+ response.headers["Content-Length"] = String(response.body.count)+ response.body = Data()+ return response+ }+ var segments = request.path.split(separator: "/", omittingEmptySubsequences: true).map {+ String($0).removingPercentEncoding ?? String($0)+ }+ if request.method == "GET", segments == ["robots.txt"] {+ // The guide is fetched by chat assistants on the user's request; it is never indexed (X-Robots-Tag).+ return .text("User-agent: *\nAllow: /\n")+ }+ guard let first = segments.first, Self.same(first, token) else {+ try? await Task.sleep(nanoseconds: 150_000_000)+ return .notFound+ }+ segments.removeFirst()+ guard admit() else { return .text("Too many requests. Wait a minute.\n", status: 429) }+ let client = clientName(request)++ switch (request.method, segments.first ?? "") {+ case ("GET", ""), ("GET", "guide"), ("GET", "llms.txt"):+ return await guide(client: client)+ case ("GET", "do"):+ return await linkAction(Array(segments.dropFirst()), client: client)+ case ("POST", "mcp"):+ return await mcp(request, client: client)+ case ("GET", "mcp"):+ // No server-initiated stream: every answer comes back as JSON.+ return HTTPResponse(status: 405, headers: ["Allow": "POST, DELETE"], body: Data())+ case ("DELETE", "mcp"):+ if let id = request.headers["mcp-session-id"] { sessions[id] = nil }+ return HTTPResponse(status: 204)+ case ("GET", "api") where segments.count == 2 && segments[1] == "tools":+ return await restTools()+ case ("POST", "api") where segments.count == 2:+ return await restCall(segments[1], request, client: client)+ case ("GET", "openapi.json"):+ return await openAPI()+ case ("GET", "plan.json"):+ return await restCall("get_floor_plan", HTTPRequest(method: "POST", path: ""), client: client)+ default:+ return .notFound+ }+ }++ /// Compares without leaking where the first difference is.+ nonisolated static func same(_ a: String, _ b: String) -> Bool {+ let x = Array(a.utf8), y = Array(b.utf8)+ guard x.count == y.count else { return false }+ var diff: UInt8 = 0+ for i in 0..<x.count { diff |= x[i] ^ y[i] }+ return diff == 0+ }++ private func admit() -> Bool {+ let now = Date()+ recent.removeAll { now.timeIntervalSince($0) > 60 }+ guard recent.count < rateLimit else { return false }+ recent.append(now)+ return true+ }++ /// Who is asking, as well as it can be told: the name an MCP client gave, or its user agent.+ func clientName(_ request: HTTPRequest) -> String {+ if let session = request.headers["mcp-session-id"], let name = sessions[session] { return name }+ return Self.friendlyName(request.headers["user-agent"] ?? "")+ }++ nonisolated public static func friendlyName(_ raw: String) -> String {+ let s = raw.lowercased()+ if s.contains("claude-code") || s.contains("claude code") { return "Claude Code" }+ if s.contains("chatgpt") || s.contains("openai") { return "ChatGPT" }+ if s.contains("claude") || s.contains("anthropic") { return "Claude" }+ if s.contains("cursor") { return "Cursor" }+ if s.contains("perplexity") { return "Perplexity" }+ if s.contains("gemini") || s.contains("google") { return "Gemini" }+ if s.contains("copilot") || s.contains("vscode") || s.contains("visual studio") { return "Copilot" }+ if s.contains("mistral") || s.contains("le chat") { return "Le Chat" }+ if s.contains("grok") || s.contains("xai") { return "Grok" }+ if s.contains("inspector") { return "MCP Inspector" }+ return "AI agent"+ }++ private func record(_ client: String, _ title: String, ok: Bool = true, quiet: Bool = false) {+ onActivity?(AgentActivity(date: Date(), client: client, title: title, ok: ok, quiet: quiet))+ }++ // MARK: - Backend++ private func ask(_ request: [String: Any]) async throws -> [String: Any] {+ guard let backend else { throw GatewayError("House Control is not ready yet. Try again in a moment.") }+ var request = request+ request["permissions"] = permissions.json+ request["base"] = linkURL+ return try await backend.agentRequest(request)+ }++ struct GatewayError: LocalizedError {+ let message: String+ init(_ message: String) { self.message = message }+ var errorDescription: String? { message }+ }++ private func tools() async throws -> [[String: Any]] {+ try await ask(["op": "tools"])["tools"] as? [[String: Any]] ?? []+ }++ /// Runs one tool. The answer has `content` (MCP content blocks), `isError` and `summary`.+ private func call(_ tool: String, _ arguments: [String: Any], client: String) async -> [String: Any] {+ do {+ let result = try await ask(["op": "call", "tool": tool, "arguments": arguments, "client": client])+ if let summary = result["summary"] as? String, !summary.isEmpty {+ record(client, summary, ok: !(result["isError"] as? Bool ?? false), quiet: result["quiet"] as? Bool ?? false)+ }+ return result+ } catch {+ record(client, "\(tool) failed: \(error.localizedDescription)", ok: false)+ return ["content": [["type": "text", "text": "Error: \(error.localizedDescription)"]], "isError": true]+ }+ }++ // MARK: - Guide and plain links++ private func guide(client: String) async -> HTTPResponse {+ do {+ let result = try await ask(["op": "guide"])+ record(client, "Read the guide", quiet: true)+ return .text(result["text"] as? String ?? "", type: "text/markdown; charset=utf-8")+ } catch {+ return .text("House Control is not ready: \(error.localizedDescription)\n", status: 503)+ }+ }++ private func linkAction(_ path: [String], client: String) async -> HTTPResponse {+ do {+ let result = try await ask(["op": "link", "path": path, "client": client])+ if let summary = result["summary"] as? String, !summary.isEmpty {+ record(client, summary, ok: result["ok"] as? Bool ?? true)+ }+ return .text(result["text"] as? String ?? "", status: result["status"] as? Int ?? 200,+ type: "text/markdown; charset=utf-8")+ } catch {+ return .text("House Control is not ready: \(error.localizedDescription)\n", status: 503)+ }+ }++ // MARK: - REST++ private func restTools() async -> HTTPResponse {+ do {+ return .json(["tools": try await tools()])+ } catch {+ return .json(["error": error.localizedDescription], status: 503)+ }+ }++ private func restCall(_ name: String, _ request: HTTPRequest, client: String) async -> HTTPResponse {+ var tool = name+ var arguments: [String: Any] = [:]+ if !request.body.isEmpty {+ guard let json = try? JSONSerialization.jsonObject(with: request.body) as? [String: Any] else {+ return .json(["error": "The body must be a JSON object."], status: 400)+ }+ arguments = json+ }+ if name == "call" {+ guard let named = arguments["tool"] as? String else {+ return .json(["error": "POST /api/call takes {\"tool\": \"…\", \"arguments\": {…}}."], status: 400)+ }+ tool = named+ arguments = arguments["arguments"] as? [String: Any] ?? [:]+ }+ let result = await call(tool, arguments, client: client)+ let failed = result["isError"] as? Bool ?? false+ var body: [String: Any] = ["ok": !failed]+ let texts = (result["content"] as? [[String: Any]] ?? []).compactMap { $0["text"] as? String }+ body["result"] = texts.joined(separator: "\n\n")+ if let image = (result["content"] as? [[String: Any]] ?? []).first(where: { $0["type"] as? String == "image" }),+ let data = image["data"] as? String, let type = image["mimeType"] as? String {+ body["image"] = "data:\(type);base64,\(data)"+ }+ if let data = result["structuredContent"] { body["data"] = data }+ return .json(body, status: failed ? 400 : 200)+ }++ private func openAPI() async -> HTTPResponse {+ do {+ let tools = try await tools()+ var paths: [String: Any] = [:]+ for tool in tools {+ guard let name = tool["name"] as? String else { continue }+ paths["/api/\(name)"] = [+ "post": [+ "operationId": name,+ "summary": tool["title"] ?? name,+ "description": tool["description"] ?? "",+ "requestBody": ["required": false, "content": ["application/json": ["schema": tool["inputSchema"] ?? ["type": "object"]]]],+ "responses": ["200": ["description": "Done", "content": ["application/json": ["schema": [+ "type": "object",+ "properties": ["ok": ["type": "boolean"], "result": ["type": "string"], "data": ["type": "object"]],+ ]]]]],+ ] as [String: Any],+ ]+ }+ return .json([+ "openapi": "3.1.0",+ "info": ["title": "House Control", "version": Self.version,+ "description": "Control the lights and air conditioners of a home and edit its 3D floor plan. Read GET / (the guide) first."],+ "servers": [["url": linkURL]],+ "paths": paths,+ ])+ } catch {+ return .json(["error": error.localizedDescription], status: 503)+ }+ }++ // MARK: - MCP++ private func mcp(_ request: HTTPRequest, client: String) async -> HTTPResponse {+ guard let json = try? JSONSerialization.jsonObject(with: request.body) else {+ return .json(Self.rpcError(nil, -32700, "Parse error"), status: 400)+ }+ var newSession: String?+ func one(_ message: [String: Any]) async -> [String: Any]? {+ let id = message["id"]+ guard let method = message["method"] as? String else {+ return id == nil ? nil : Self.rpcError(id, -32600, "Invalid request")+ }+ let params = message["params"] as? [String: Any] ?? [:]+ guard id != nil, !(id is NSNull) else { return nil } // a notification+ switch method {+ case "initialize":+ let info = params["clientInfo"] as? [String: Any]+ let raw = [info?["title"], info?["name"]].compactMap { $0 as? String }.first ?? ""+ var name = raw.isEmpty ? client : Self.friendlyName(raw)+ if name == "AI agent", !raw.isEmpty { name = raw }+ let session = UUID().uuidString.lowercased()+ sessions[session] = name+ newSession = session+ record(name, "Connected", quiet: true)+ let asked = params["protocolVersion"] as? String ?? ""+ let instructions = (try? await ask(["op": "instructions"]))?["text"] as? String ?? ""+ return Self.rpcResult(id, [+ "protocolVersion": Self.protocolVersions.contains(asked) ? asked : Self.protocolVersions[0],+ "capabilities": ["tools": ["listChanged": false]],+ "serverInfo": ["name": "house-control", "title": "House Control", "version": Self.version],+ "instructions": instructions,+ ])+ case "ping":+ return Self.rpcResult(id, [:])+ case "tools/list":+ do {+ return Self.rpcResult(id, ["tools": try await tools()])+ } catch {+ return Self.rpcError(id, -32603, error.localizedDescription)+ }+ case "tools/call":+ guard let name = params["name"] as? String else { return Self.rpcError(id, -32602, "Missing tool name") }+ let caller = newSession.flatMap { sessions[$0] } ?? client+ var result = await call(name, params["arguments"] as? [String: Any] ?? [:], client: caller)+ result["summary"] = nil+ result["quiet"] = nil+ return Self.rpcResult(id, result)+ case "resources/list":+ return Self.rpcResult(id, ["resources": []])+ case "resources/templates/list":+ return Self.rpcResult(id, ["resourceTemplates": []])+ case "prompts/list":+ return Self.rpcResult(id, ["prompts": []])+ default:+ return Self.rpcError(id, -32601, "Method not found: \(method)")+ }+ }++ var headers = ["Content-Type": "application/json"]+ let replies: Any?+ if let batch = json as? [[String: Any]] {+ var out: [[String: Any]] = []+ for message in batch { if let reply = await one(message) { out.append(reply) } }+ replies = out.isEmpty ? nil : out+ } else if let message = json as? [String: Any] {+ replies = await one(message)+ } else {+ return .json(Self.rpcError(nil, -32600, "Invalid request"), status: 400)+ }+ if let newSession { headers["Mcp-Session-Id"] = newSession }+ guard let replies else { return HTTPResponse(status: 202, headers: headers) }+ let data = (try? JSONSerialization.data(withJSONObject: replies, options: [.withoutEscapingSlashes])) ?? Data()+ return HTTPResponse(status: 200, headers: headers, body: data)+ }++ static func rpcResult(_ id: Any?, _ result: [String: Any]) -> [String: Any] {+ ["jsonrpc": "2.0", "id": id ?? NSNull(), "result": result]+ }++ static func rpcError(_ id: Any?, _ code: Int, _ message: String) -> [String: Any] {+ ["jsonrpc": "2.0", "id": id ?? NSNull(), "error": ["code": code, "message": message]]+ }+}diff --git a/core/Sources/HouseCore/AgentHTTP.swift b/core/Sources/HouseCore/AgentHTTP.swiftnew file mode 100644index 0000000..33e7042--- /dev/null+++ b/core/Sources/HouseCore/AgentHTTP.swift@@ -0,0 +1,260 @@+import Foundation+import Network++/// One HTTP request, as much of it as the AI gateway needs.+public struct HTTPRequest {+ public var method: String+ /// The path without the query, percent-decoded segment by segment by the router.+ public var path: String+ public var query: [String: String]+ /// Header names in lower case.+ public var headers: [String: String]+ public var body: Data++ public init(method: String, path: String, query: [String: String] = [:], headers: [String: String] = [:], body: Data = Data()) {+ self.method = method+ self.path = path+ self.query = query+ self.headers = headers+ self.body = body+ }+}++public struct HTTPResponse {+ public var status: Int+ public var headers: [String: String]+ public var body: Data++ public init(status: Int = 200, headers: [String: String] = [:], body: Data = Data()) {+ self.status = status+ self.headers = headers+ self.body = body+ }++ public static func text(_ text: String, status: Int = 200, type: String = "text/plain; charset=utf-8") -> HTTPResponse {+ HTTPResponse(status: status, headers: ["Content-Type": type], body: Data(text.utf8))+ }++ public static func json(_ object: Any, status: Int = 200) -> HTTPResponse {+ let data = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes])) ?? Data("{}".utf8)+ return HTTPResponse(status: status, headers: ["Content-Type": "application/json"], body: data)+ }++ public static let notFound = HTTPResponse.text("Not found\n", status: 404)++ static func reason(_ status: Int) -> String {+ switch status {+ case 200: return "OK"+ case 202: return "Accepted"+ case 204: return "No Content"+ case 400: return "Bad Request"+ case 403: return "Forbidden"+ case 404: return "Not Found"+ case 405: return "Method Not Allowed"+ case 413: return "Payload Too Large"+ case 429: return "Too Many Requests"+ case 503: return "Service Unavailable"+ default: return status < 400 ? "OK" : "Error"+ }+ }+}++/// A deliberately small HTTP/1.1 server for the AI gateway. It listens on the loopback+/// interface only: the outside world reaches it through the tunnel process (which runs+/// on this Mac and connects to 127.0.0.1), never directly, and nothing on the local+/// network can see it.+@MainActor+public final class LoopbackHTTPServer {+ public typealias Handler = @MainActor (HTTPRequest) async -> HTTPResponse++ private var listener: NWListener?+ private var connections: [ObjectIdentifier: NWConnection] = [:]+ private let handler: Handler+ /// Requests larger than this are refused (a floor plan is a few dozen kB).+ public var maxBody = 4 * 1024 * 1024++ public init(handler: @escaping Handler) {+ self.handler = handler+ }++ public var port: UInt16? { listener?.port?.rawValue }+ public var isRunning: Bool { listener != nil }++ /// Starts listening on 127.0.0.1, on `preferredPort` if it is free and on any port+ /// otherwise. Calls back with the port once the listener is ready.+ public func start(preferredPort: UInt16 = 0, ready: @escaping @MainActor (Result<UInt16, Error>) -> Void) {+ stop()+ do {+ let listener = try makeListener(port: preferredPort)+ install(listener, preferredPort: preferredPort, ready: ready)+ } catch {+ if preferredPort != 0 { start(preferredPort: 0, ready: ready) } else { ready(.failure(error)) }+ }+ }++ private func makeListener(port: UInt16) throws -> NWListener {+ let parameters = NWParameters.tcp+ parameters.allowLocalEndpointReuse = true+ parameters.requiredLocalEndpoint = .hostPort(host: .ipv4(.loopback), port: NWEndpoint.Port(rawValue: port) ?? .any)+ return try NWListener(using: parameters)+ }++ private func install(_ listener: NWListener, preferredPort: UInt16, ready: @escaping @MainActor (Result<UInt16, Error>) -> Void) {+ var reported = false+ listener.stateUpdateHandler = { [weak self, weak listener] state in+ MainActor.assumeIsolated {+ guard let self, let listener, self.listener === listener else { return }+ switch state {+ case .ready:+ if !reported, let port = listener.port?.rawValue { reported = true; ready(.success(port)) }+ case .failed(let error):+ self.stop()+ if !reported {+ reported = true+ // The preferred port is taken: any free one will do.+ if preferredPort != 0 { self.start(preferredPort: 0, ready: ready) } else { ready(.failure(error)) }+ }+ default:+ break+ }+ }+ }+ listener.newConnectionHandler = { [weak self] connection in+ MainActor.assumeIsolated { self?.accept(connection) }+ }+ self.listener = listener+ listener.start(queue: .main)+ }++ public func stop() {+ listener?.cancel()+ listener = nil+ for connection in connections.values { connection.cancel() }+ connections = [:]+ }++ private func accept(_ connection: NWConnection) {+ let key = ObjectIdentifier(connection)+ connections[key] = connection+ connection.stateUpdateHandler = { [weak self] state in+ MainActor.assumeIsolated {+ switch state {+ case .failed, .cancelled: self?.connections[key] = nil+ default: break+ }+ }+ }+ connection.start(queue: .main)+ read(connection, buffer: Data())+ }++ /// Serves requests one after another on a kept-alive connection: answers whatever is+ /// already buffered, and reads more when a request is still incomplete.+ private func read(_ connection: NWConnection, buffer: Data) {+ var buffer = buffer+ switch HTTPParser.parse(&buffer, maxBody: maxBody) {+ case .invalid(let status):+ send(.text("Bad request\n", status: status), close: true, on: connection, rest: Data())+ case .request(let request, let keepAlive):+ Task { @MainActor in+ let response = await self.handler(request)+ self.send(response, close: !keepAlive, on: connection, rest: buffer)+ }+ case .incomplete:+ connection.receive(minimumIncompleteLength: 1, maximumLength: 256 * 1024) { [weak self] data, _, _, error in+ MainActor.assumeIsolated {+ guard let self else { return }+ guard let data, !data.isEmpty, error == nil else { connection.cancel(); return }+ self.read(connection, buffer: buffer + data)+ }+ }+ }+ }++ private func send(_ response: HTTPResponse, close: Bool, on connection: NWConnection, rest: Data) {+ var head = "HTTP/1.1 \(response.status) \(HTTPResponse.reason(response.status))\r\n"+ var headers = response.headers+ headers["Content-Length"] = headers["Content-Length"] ?? String(response.body.count)+ headers["Connection"] = close ? "close" : "keep-alive"+ headers["Cache-Control"] = headers["Cache-Control"] ?? "no-store"+ headers["X-Robots-Tag"] = "noindex, nofollow"+ for (name, value) in headers.sorted(by: { $0.key < $1.key }) { head += "\(name): \(value)\r\n" }+ head += "\r\n"+ connection.send(content: Data(head.utf8) + response.body, completion: .contentProcessed { [weak self] _ in+ MainActor.assumeIsolated {+ if close { connection.cancel() } else { self?.read(connection, buffer: rest) }+ }+ })+ }+}++/// Parses HTTP/1.1 requests out of a byte buffer (fixed length and chunked bodies).+enum HTTPParser {+ enum Result {+ case incomplete+ case invalid(Int)+ case request(HTTPRequest, keepAlive: Bool)+ }++ /// On success the request's bytes are removed from `buffer`.+ static func parse(_ buffer: inout Data, maxBody: Int) -> Result {+ let separator = Data("\r\n\r\n".utf8)+ guard let end = buffer.range(of: separator) else {+ return buffer.count > 64 * 1024 ? .invalid(400) : .incomplete+ }+ guard let head = String(data: buffer[buffer.startIndex..<end.lowerBound], encoding: .utf8) else { return .invalid(400) }+ var lines = head.components(separatedBy: "\r\n")+ let parts = lines.removeFirst().split(separator: " ")+ guard parts.count == 3, parts[2].hasPrefix("HTTP/1.") else { return .invalid(400) }+ var headers: [String: String] = [:]+ for line in lines {+ guard let colon = line.firstIndex(of: ":") else { continue }+ let name = line[..<colon].trimmingCharacters(in: .whitespaces).lowercased()+ headers[name] = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)+ }++ var cursor = end.upperBound+ var body = Data()+ if headers["transfer-encoding"]?.lowercased().contains("chunked") == true {+ while true {+ guard let lineEnd = buffer[cursor...].range(of: Data("\r\n".utf8)) else { return .incomplete }+ let sizeText = String(data: buffer[cursor..<lineEnd.lowerBound], encoding: .ascii)?+ .split(separator: ";").first.map(String.init)?.trimmingCharacters(in: .whitespaces) ?? ""+ guard let size = Int(sizeText, radix: 16) else { return .invalid(400) }+ cursor = lineEnd.upperBound+ if size == 0 {+ // Trailers, if any, end with an empty line.+ guard let trailerEnd = buffer[cursor...].range(of: Data("\r\n".utf8)) else { return .incomplete }+ if trailerEnd.lowerBound != cursor {+ guard let rest = buffer[cursor...].range(of: separator) else { return .incomplete }+ cursor = rest.upperBound+ } else {+ cursor = trailerEnd.upperBound+ }+ break+ }+ guard body.count + size <= maxBody else { return .invalid(413) }+ guard buffer.distance(from: cursor, to: buffer.endIndex) >= size + 2 else { return .incomplete }+ body.append(buffer[cursor..<buffer.index(cursor, offsetBy: size)])+ cursor = buffer.index(cursor, offsetBy: size + 2)+ }+ } else if let lengthText = headers["content-length"] {+ guard let length = Int(lengthText), length >= 0 else { return .invalid(400) }+ guard length <= maxBody else { return .invalid(413) }+ guard buffer.distance(from: cursor, to: buffer.endIndex) >= length else { return .incomplete }+ body = Data(buffer[cursor..<buffer.index(cursor, offsetBy: length)])+ cursor = buffer.index(cursor, offsetBy: length)+ }++ let target = String(parts[1])+ let components = URLComponents(string: target.hasPrefix("/") ? "http://localhost\(target)" : target)+ var query: [String: String] = [:]+ for item in components?.queryItems ?? [] { query[item.name] = item.value ?? "" }+ let request = HTTPRequest(method: String(parts[0]).uppercased(),+ path: components?.percentEncodedPath ?? target,+ query: query, headers: headers, body: body)+ let keepAlive = headers["connection"]?.lowercased() != "close" && parts[2] == "HTTP/1.1"+ buffer = Data(buffer[cursor...])+ return .request(request, keepAlive: keepAlive)+ }+}diff --git a/core/Tests/HouseCoreTests/AgentTests.swift b/core/Tests/HouseCoreTests/AgentTests.swiftnew file mode 100644index 0000000..e303660--- /dev/null+++ b/core/Tests/HouseCoreTests/AgentTests.swift@@ -0,0 +1,221 @@+import XCTest+@testable import HouseCore++/// Stands in for the panel page: answers like `web/src/agent/tools.js` does.+@MainActor+private final class FakeHome: AgentBackend {+ var requests: [[String: Any]] = []++ func agentRequest(_ request: [String: Any]) async throws -> [String: Any] {+ requests.append(request)+ let permissions = request["permissions"] as? [String: Any] ?? [:]+ switch request["op"] as? String {+ case "tools":+ var tools: [[String: Any]] = [["name": "get_home", "title": "Look", "description": "d", "inputSchema": ["type": "object"]]]+ if permissions["control"] as? Bool != false {+ tools.append(["name": "set_lights", "title": "Lights", "description": "d", "inputSchema": ["type": "object"]])+ }+ return ["tools": tools]+ case "call":+ let tool = request["tool"] as? String ?? ""+ if tool == "set_lights" {+ let on = (request["arguments"] as? [String: Any])?["on"] as? Bool ?? false+ return ["content": [["type": "text", "text": on ? "Living · Lamp: on" : "Living · Lamp: off"]], "isError": false,+ "summary": on ? "On: Lamp" : "Off: Lamp"]+ }+ return ["content": [["type": "text", "text": "Home with 1 lamp"]], "isError": false, "summary": "Looked", "quiet": true,+ "structuredContent": ["home": "Test"]]+ case "guide":+ return ["text": "# House Control — Test\nbase \(request["base"] as? String ?? "")"]+ case "instructions":+ return ["text": "Call get_home first."]+ case "link":+ return ["text": "Done. \((request["path"] as? [String] ?? []).joined(separator: "/"))", "summary": "On: Lamp", "ok": true]+ default:+ return [:]+ }+ }+}++@MainActor+final class AgentTests: XCTestCase {+ private var home: FakeHome!+ private var gateway: AgentGateway!+ private var activity: [AgentActivity] = []++ override func setUp() async throws {+ home = FakeHome()+ gateway = AgentGateway(token: "secret-token")+ gateway.backend = home+ gateway.publicBase = "https://example.trycloudflare.com"+ activity = []+ gateway.onActivity = { [unowned self] in self.activity.append($0) }+ }++ private func json(_ response: HTTPResponse) -> Any? { try? JSONSerialization.jsonObject(with: response.body) }++ private func rpc(_ body: Any, session: String? = nil) async -> HTTPResponse {+ var headers = ["content-type": "application/json", "user-agent": "Claude-User"]+ if let session { headers["mcp-session-id"] = session }+ return await gateway.handle(HTTPRequest(method: "POST", path: "/secret-token/mcp", headers: headers,+ body: try! JSONSerialization.data(withJSONObject: body)))+ }++ func testEverythingWithoutTheTokenIsNotFound() async {+ for path in ["/", "/wrong-token", "/wrong-token/mcp", "/secret-tokenX/", "/SECRET-TOKEN/"] {+ let response = await gateway.handle(HTTPRequest(method: "GET", path: path))+ XCTAssertEqual(response.status, 404, path)+ }+ XCTAssertTrue(home.requests.isEmpty)+ let status3286 = await gateway.handle(HTTPRequest(method: "GET", path: "/robots.txt")).status+ XCTAssertEqual(status3286, 200)+ }++ func testGuideIsPlainTextWithTheLink() async {+ let response = await gateway.handle(HTTPRequest(method: "GET", path: "/secret-token", headers: ["user-agent": "Mozilla/5.0 ChatGPT-User/1.0"]))+ XCTAssertEqual(response.status, 200)+ XCTAssertTrue(response.headers["Content-Type"]?.hasPrefix("text/markdown") == true)+ XCTAssertTrue(String(data: response.body, encoding: .utf8)!.contains("base https://example.trycloudflare.com/secret-token"))+ XCTAssertEqual(activity.last?.client, "ChatGPT")+ }++ func testLinkActionsPassTheirPath() async {+ let response = await gateway.handle(HTTPRequest(method: "GET", path: "/secret-token/do/light/living.lamp/on"))+ XCTAssertEqual(String(data: response.body, encoding: .utf8), "Done. light/living.lamp/on")+ XCTAssertEqual(activity.last?.title, "On: Lamp")+ }++ func testMCPHandshakeListAndCall() async throws {+ let initialize = await rpc(["jsonrpc": "2.0", "id": 1, "method": "initialize",+ "params": ["protocolVersion": "2025-06-18", "clientInfo": ["name": "claude-ai", "version": "1"], "capabilities": [:]]])+ XCTAssertEqual(initialize.status, 200)+ let session = try XCTUnwrap(initialize.headers["Mcp-Session-Id"])+ let result = try XCTUnwrap((json(initialize) as? [String: Any])?["result"] as? [String: Any])+ XCTAssertEqual(result["protocolVersion"] as? String, "2025-06-18")+ XCTAssertEqual(result["instructions"] as? String, "Call get_home first.")+ XCTAssertEqual((result["serverInfo"] as? [String: Any])?["name"] as? String, "house-control")++ let note = await rpc(["jsonrpc": "2.0", "method": "notifications/initialized"], session: session)+ XCTAssertEqual(note.status, 202)+ XCTAssertTrue(note.body.isEmpty)++ let list = await rpc(["jsonrpc": "2.0", "id": 2, "method": "tools/list"], session: session)+ let tools = ((json(list) as? [String: Any])?["result"] as? [String: Any])?["tools"] as? [[String: Any]]+ XCTAssertEqual(tools?.compactMap { $0["name"] as? String }, ["get_home", "set_lights"])++ let call = await rpc(["jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": ["name": "set_lights", "arguments": ["lights": ["living"], "on": true]]],+ session: session)+ let callResult = try XCTUnwrap((json(call) as? [String: Any])?["result"] as? [String: Any])+ XCTAssertEqual(callResult["isError"] as? Bool, false)+ XCTAssertNil(callResult["summary"], "the feed's summary is not part of the MCP result")+ XCTAssertEqual(((callResult["content"] as? [[String: Any]])?.first)?["text"] as? String, "Living · Lamp: on")+ XCTAssertEqual(activity.last?.client, "Claude")+ XCTAssertEqual(activity.last?.title, "On: Lamp")+ }++ func testMCPUnknownMethodsAndBatches() async {+ let unknown = await rpc(["jsonrpc": "2.0", "id": 9, "method": "sampling/whatever"])+ XCTAssertEqual(((json(unknown) as? [String: Any])?["error"] as? [String: Any])?["code"] as? Int, -32601)+ let batch = await rpc([["jsonrpc": "2.0", "id": 1, "method": "ping"], ["jsonrpc": "2.0", "method": "notifications/initialized"],+ ["jsonrpc": "2.0", "id": 2, "method": "prompts/list"]])+ XCTAssertEqual((json(batch) as? [[String: Any]])?.count, 2)+ let garbage = await gateway.handle(HTTPRequest(method: "POST", path: "/secret-token/mcp", body: Data("{nope".utf8)))+ XCTAssertEqual(garbage.status, 400)+ let status6969 = await gateway.handle(HTTPRequest(method: "GET", path: "/secret-token/mcp")).status+ XCTAssertEqual(status6969, 405)+ }++ func testPermissionsReachTheHome() async {+ gateway.permissions = AgentPermissions(control: false, edit: false)+ let list = await gateway.handle(HTTPRequest(method: "GET", path: "/secret-token/api/tools"))+ let tools = (json(list) as? [String: Any])?["tools"] as? [[String: Any]]+ XCTAssertEqual(tools?.count, 1)+ XCTAssertEqual((home.requests.last?["permissions"] as? [String: Any])?["control"] as? Bool, false)+ }++ func testRESTCallAndOpenAPI() async {+ let call = await gateway.handle(HTTPRequest(method: "POST", path: "/secret-token/api/set_lights", body: Data(#"{"lights":["all"],"on":false}"#.utf8)))+ XCTAssertEqual(call.status, 200)+ XCTAssertEqual((json(call) as? [String: Any])?["result"] as? String, "Living · Lamp: off")+ let named = await gateway.handle(HTTPRequest(method: "POST", path: "/secret-token/api/call",+ body: Data(#"{"tool":"get_home","arguments":{}}"#.utf8)))+ XCTAssertEqual(((json(named) as? [String: Any])?["data"] as? [String: Any])?["home"] as? String, "Test")+ let bad = await gateway.handle(HTTPRequest(method: "POST", path: "/secret-token/api/set_lights", body: Data("[1]".utf8)))+ XCTAssertEqual(bad.status, 400)+ let spec = await gateway.handle(HTTPRequest(method: "GET", path: "/secret-token/openapi.json"))+ let paths = (json(spec) as? [String: Any])?["paths"] as? [String: Any]+ XCTAssertNotNil(paths?["/api/set_lights"])+ XCTAssertEqual(((json(spec) as? [String: Any])?["servers"] as? [[String: Any]])?.first?["url"] as? String,+ "https://example.trycloudflare.com/secret-token")+ }++ func testHeadNeverRunsAnAction() async {+ let head = await gateway.handle(HTTPRequest(method: "HEAD", path: "/secret-token/do/light/living.lamp/on"))+ XCTAssertEqual(head.status, 200)+ XCTAssertTrue(head.body.isEmpty)+ XCTAssertFalse(home.requests.contains { $0["op"] as? String == "link" })+ }++ func testRateLimit() async {+ gateway.rateLimit = 3+ for _ in 0..<3 { _ = await gateway.handle(HTTPRequest(method: "GET", path: "/secret-token/do/state")) }+ let status8987 = await gateway.handle(HTTPRequest(method: "GET", path: "/secret-token/do/state")).status+ XCTAssertEqual(status8987, 429)+ }++ func testTokensAreLongAndFresh() {+ let a = AgentGateway.makeToken(), b = AgentGateway.makeToken()+ XCTAssertEqual(a.count, 22)+ XCTAssertNotEqual(a, b)+ XCTAssertTrue(a.allSatisfy { $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" })+ }++ func testClientNames() {+ XCTAssertEqual(AgentGateway.friendlyName("Mozilla/5.0 AppleWebKit/537.36; compatible; ChatGPT-User/1.0; +https://openai.com/bot"), "ChatGPT")+ XCTAssertEqual(AgentGateway.friendlyName("Claude-User (claude-code/2.1)"), "Claude Code")+ XCTAssertEqual(AgentGateway.friendlyName("openai-mcp"), "ChatGPT")+ XCTAssertEqual(AgentGateway.friendlyName("python-httpx/0.27"), "AI agent")+ }++ // MARK: - HTTP++ func testParserHandlesChunkedAndPipelinedRequests() {+ var buffer = Data(("POST /t/mcp HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n4\r\n{\"a\"\r\n3\r\n:1}\r\n0\r\n\r\n"+ + "GET /t/ HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").utf8)+ guard case .request(let first, let keepAlive) = HTTPParser.parse(&buffer, maxBody: 1000) else { return XCTFail("first") }+ XCTAssertEqual(String(data: first.body, encoding: .utf8), "{\"a\":1}")+ XCTAssertTrue(keepAlive)+ guard case .request(let second, let keep2) = HTTPParser.parse(&buffer, maxBody: 1000) else { return XCTFail("second") }+ XCTAssertEqual(second.path, "/t/")+ XCTAssertFalse(keep2)+ XCTAssertTrue(buffer.isEmpty)++ var partial = Data("POST / HTTP/1.1\r\nContent-Length: 10\r\n\r\n12345".utf8)+ guard case .incomplete = HTTPParser.parse(&partial, maxBody: 1000) else { return XCTFail("partial") }+ var huge = Data("POST / HTTP/1.1\r\nContent-Length: 99999\r\n\r\n".utf8)+ guard case .invalid(413) = HTTPParser.parse(&huge, maxBody: 1000) else { return XCTFail("huge") }+ }++ func testLoopbackServerEndToEnd() async throws {+ let server = LoopbackHTTPServer { [unowned self] in await self.gateway.handle($0) }+ let port: UInt16 = try await withCheckedThrowingContinuation { continuation in+ server.start(preferredPort: 0) { continuation.resume(with: $0) }+ }+ defer { server.stop() }+ let base = URL(string: "http://127.0.0.1:\(port)/secret-token")!+ let (guide, response) = try await URLSession.shared.data(from: base)+ XCTAssertEqual((response as? HTTPURLResponse)?.statusCode, 200)+ XCTAssertTrue(String(data: guide, encoding: .utf8)!.hasPrefix("# House Control"))++ var post = URLRequest(url: base.appendingPathComponent("mcp"))+ post.httpMethod = "POST"+ post.setValue("application/json", forHTTPHeaderField: "Content-Type")+ post.setValue("application/json, text/event-stream", forHTTPHeaderField: "Accept")+ post.httpBody = Data(#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#.utf8)+ let (data, _) = try await URLSession.shared.data(for: post)+ XCTAssertTrue(String(data: data, encoding: .utf8)!.contains("set_lights"))++ let (_, missing) = try await URLSession.shared.data(from: URL(string: "http://127.0.0.1:\(port)/nope")!)+ XCTAssertEqual((missing as? HTTPURLResponse)?.statusCode, 404)+ }+}diff --git a/docs/ai-access.md b/docs/ai-access.mdnew file mode 100644index 0000000..507bf89--- /dev/null+++ b/docs/ai-access.md@@ -0,0 +1,149 @@+# AI Access++Give ChatGPT, Claude or any other AI assistant a private link to your home. It can then see every room, switch and+dim the lights, run the air conditioners and scenes — and change the 3D model itself: send it photos of your living+room and ask it to rebuild the room, or tell it you moved the sofa.++There is no House Control server and no account. Your Mac answers the assistant itself, through a tunnel that exists+only while AI Access is on.++<p align="center">+ <img src="ai-access.png" width="420" alt="The AI Access window: the private link, ways to connect an assistant, permissions and the live activity feed">+</p>++## Start++1. Right-click the menu bar icon → **AI Access…** (or the gear in the panel → **AI access…**).+2. Press **Start AI Access**. A few seconds later the window shows your private link.+3. Hand it to an assistant — see [Connect an assistant](#connect-an-assistant).++While the link is live, sparkles appear next to the house in the menu bar and an **AI** badge in the panel.+Everything an assistant reads or does shows up in the window's **Activity** feed as it happens, and the panel and+the island at the notch show each change with sparkles.++**Stop AI Access** ends it at once. Each start makes a new link; an old one never works again.++## How it works++```+assistant ──HTTPS──▶ Cloudflare quick tunnel ──▶ cloudflared on your Mac ──▶ 127.0.0.1 (House Control) ──▶ your devices+```++- House Control listens on the loopback interface only (port 7419, or any free one). Nothing on your network sees it.+- To be reachable from ChatGPT's or Claude's servers, the Mac opens a free+ [Cloudflare Quick Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/):+ a random `https://….trycloudflare.com` address that exists while `cloudflared` runs. No Cloudflare account is needed.+ If `cloudflared` is not installed (`brew install cloudflared`), the window offers to download it from Cloudflare's+ GitHub releases and keeps it only if it carries Cloudflare's Developer ID signature.+- Every address carries a random 128-bit key: `https://….trycloudflare.com/<key>/…`. Without the key, every path+ answers 404.+- **This Mac only** skips the tunnel: the link is `http://127.0.0.1:7419/<key>`, for apps running on the Mac+ (Claude Code, Cursor, VS Code, LM Studio, scripts).++## Connect an assistant++### Any chat (paste the link)++Press **Copy for a chat** and paste it into ChatGPT, Claude, Gemini, Perplexity or Grok together with what you want:++> You can control my home with House Control. Open this private link and follow its instructions: https://….trycloudflare.com/k3Vb…+> Dim the living room to 30% and cool the bedroom to 22°.++The link opens a guide written for AI assistants: the rules, the state of every device, and a ready-made **action link**+for each thing it can do (`…/do/light/living.main/brightness/30`). Opening an action link performs it and answers+with the new state, so even an assistant that can only browse can run the home.++Changing the 3D model needs more than opening links. For that, connect House Control as a connector:++### Claude++**Settings → Connectors → Add custom connector**, name it *House Control*, and paste the **MCP address** from the+**Claude** tab (`https://….trycloudflare.com/<key>/mcp`). In a chat, enable it from the tools menu. Attach photos and ask+*"here is my living room — rebuild it in 3D"*.++### ChatGPT++**Settings → Apps & Connectors → Advanced → Developer mode**, then **Create** a connector with the MCP address and+**No authentication**. In a chat, pick Developer mode and add House Control.++### Claude Code, Cursor and other MCP clients++```bash+claude mcp add --transport http house-control https://….trycloudflare.com/<key>/mcp+```++```json+{ "mcpServers": { "house-control": { "url": "https://….trycloudflare.com/<key>/mcp" } } }+```++### Your own agent or script++The same tools as plain HTTP with JSON:++| Request | Does |+| --- | --- |+| `GET /<key>/` | The guide (Markdown), with the current state and every action link |+| `GET /<key>/api/tools` | The tools with their JSON schemas |+| `POST /<key>/api/<tool>` | Runs a tool; the body is its arguments. Answers `{"ok", "result", "data", "image"}` |+| `GET /<key>/openapi.json` | OpenAPI 3.1 for the above (Custom GPT actions, agent frameworks) |+| `GET /<key>/plan.json` | The floor plan |+| `GET /<key>/do/…` | The action links |+| `POST /<key>/mcp` | Model Context Protocol, Streamable HTTP (JSON responses, no server-sent events) |++```bash+curl -X POST https://….trycloudflare.com/<key>/api/set_lights -d '{"lights": ["living"], "brightness": 40}'+```++## What an assistant can do++| Tool | Does |+| --- | --- |+| `get_home` | Every room with its lights and ACs, what each can do and what it is doing, and the scenes |+| `set_lights` | On, off, toggle, brightness (%), white temperature (K), colour — for ids, whole rooms, names or `all` |+| `set_air_conditioners` | On, off, target temperature, mode, fan speed |+| `activate_scene` | Runs a scene |+| `get_floor_plan` | The plan behind the 3D model, the coordinate rules and the furniture catalogue |+| `edit_floor_plan` | A list of operations applied together: `furnish_room` (replace everything in a room — the photo case), add / update / remove rooms, furniture, doors and windows, lights, ACs and scenes |+| `replace_floor_plan` | A whole new plan, e.g. drawn from a sketch |+| `undo_floor_plan_edit` | Puts back the plan as it was before the last change |+| `render_home` | A picture of the 3D model, whole or one room, so the assistant can check its work |++Edits are checked before they are saved (unknown furniture, overlapping ids, rooms that do not add up are refused with+a reason the assistant can act on). The model on your screen updates at once, paired iPhones receive it, and+**Undo home edit** in the window — or the assistant itself — reverts it.++## What it may do++The **What it may do** switches take effect immediately, even while the link is live:++- **Lights, climate and scenes** — off makes the link read-only for devices.+- **Your 3D home** — off hides the editing tools.+- **Stop the link automatically** after 1 hour, 8 hours (the default) or never.++## Privacy and safety++- Anyone who has the link can do what the switches allow until you stop it. Treat it like a house key; the guide tells+ assistants never to repeat it. When in doubt, press **New link**.+- The assistant's provider (OpenAI, Anthropic…) sees what the assistant reads: room and device names and their state,+ and the floor plan. It never sees your Smart Life sign-in or the IDs of your real devices — those are replaced by+ `"linked": true`, and a plan the assistant writes keeps them as they were. Devices linked to real hardware cannot be+ removed through the link.+- Cloudflare relays the connection: HTTPS from the assistant to Cloudflare, an encrypted tunnel from Cloudflare to your+ Mac. Like any HTTPS proxy, Cloudflare's edge handles the traffic in between. Use **This Mac only** when the assistant+ runs on the Mac itself.+- Nothing about AI Access is stored except your three settings. The link exists only in memory; a `cloudflared` left+ over after a crash is stopped at the next launch.+- Requests are rate-limited (240 a minute) and bodies are capped at 4 MB.++## Troubleshooting++| Symptom | Cause |+| --- | --- |+| "Cloudflare is limiting new quick tunnels" | Quick tunnels are rate-limited per IP. Wait a minute and start again |+| The assistant says it cannot open the link | Some chat modes only open pages they found by searching. Paste the link on its own line, ask it to open it, or use a connector |+| The assistant opened the guide but not the action links | Ask it to open the link for that action — or connect it as an MCP connector |+| A connector stopped working | The link changed: every start makes a new one. Paste the new MCP address into the connector |+| "The user is looking at a demo plan" | Your own home is saved but a demo is shown; pick **My home** in the panel's gear menu |++For testing, `HOUSE_OPEN_AGENT=1` opens the window at launch (`start` also starts it), `HOUSE_AGENT_REACH=local|internet`+overrides the saved reach for one run, and `HOUSE_AGENT_LINK_FILE=<path>` writes the live link to a file.diff --git a/docs/ai-access.png b/docs/ai-access.pngnew file mode 100644index 0000000..9c80b0cBinary files /dev/null and b/docs/ai-access.png differdiff --git a/macos/Sources/HouseControl/AgentController.swift b/macos/Sources/HouseControl/AgentController.swiftnew file mode 100644index 0000000..80401df--- /dev/null+++ b/macos/Sources/HouseControl/AgentController.swift@@ -0,0 +1,384 @@+import AppKit+import WebKit+import HouseCore++/// AI Access: a private link that lets an AI assistant (ChatGPT, Claude, an MCP client…)+/// see and run the home, served from this Mac.+///+/// AI ─HTTPS─▶ Cloudflare quick tunnel ─▶ cloudflared on this Mac ─▶ 127.0.0.1 gateway ─▶ the panel's store+///+/// Off until the user starts it. Every start makes a new secret link; Stop (or the auto-stop+/// timer) closes the gateway and the tunnel, and the old address stops existing.+@MainActor+final class AgentController: NSObject, AgentBackend {+ enum Reach: String { case internet, local }+ enum Phase: Equatable { case off, starting, live, failed(String) }++ let gateway = AgentGateway()+ private lazy var server = LoopbackHTTPServer { [unowned self] request in await self.gateway.handle(request) }+ private let tunnel: CloudflareTunnel+ private let plans: PlanStore+ /// The panel runs every request: it holds the state of each device.+ private let panel: () -> WebHost+ /// Reloads every view after the plan changed (and tells paired iPhones).+ private let reloadAll: () -> Void+ var onLiveChange: ((Bool) -> Void)?++ private(set) var phase: Phase = .off+ private var window: AgentWindow?+ private var activity: [AgentActivity] = []+ /// What the plan was before each change an AI made, newest last.+ private var history: [(data: Data?, active: String)] = []+ private var startedAt: Date?+ private var stopsAt: Date?+ private var stopTimer: Timer?+ private var tunnelError = ""++ private let defaults = UserDefaults.standard+ private var reach: Reach {+ // HOUSE_AGENT_REACH=local|internet overrides the saved choice for one run (tests).+ get { Reach(rawValue: ProcessInfo.processInfo.environment["HOUSE_AGENT_REACH"] ?? defaults.string(forKey: "agent.reach") ?? "") ?? .internet }+ set { defaults.set(newValue.rawValue, forKey: "agent.reach") }+ }+ /// "1h", "8h" or "never".+ private var autoStop: String {+ get { defaults.string(forKey: "agent.autoStop") ?? "8h" }+ set { defaults.set(newValue, forKey: "agent.autoStop") }+ }+ private var permissions: AgentPermissions {+ get { AgentPermissions(control: defaults.object(forKey: "agent.control") as? Bool ?? true,+ edit: defaults.object(forKey: "agent.edit") as? Bool ?? true) }+ set {+ defaults.set(newValue.control, forKey: "agent.control")+ defaults.set(newValue.edit, forKey: "agent.edit")+ gateway.permissions = newValue+ }+ }++ init(plans: PlanStore, panel: @escaping () -> WebHost, reloadAll: @escaping () -> Void) {+ self.plans = plans+ self.panel = panel+ self.reloadAll = reloadAll+ tunnel = CloudflareTunnel(directory: plans.directory)+ super.init()+ gateway.backend = self+ gateway.permissions = permissions+ gateway.onActivity = { [weak self] entry in self?.log(entry) }+ tunnel.onChange = { [weak self] state in self?.tunnelChanged(state) }+ }++ var isLive: Bool { phase == .live }++ // MARK: - Start and stop++ func start() {+ switch phase {+ case .starting, .live: return+ default: break+ }+ if reach == .internet, tunnel.binary == nil {+ phase = .failed("needs-cloudflared")+ push()+ return+ }+ gateway.rotateToken()+ gateway.permissions = permissions+ phase = .starting+ tunnelError = ""+ push()+ server.start(preferredPort: 7419) { [weak self] result in+ guard let self, self.phase == .starting else { return }+ switch result {+ case .success(let port):+ if self.reach == .local {+ self.gateway.publicBase = "http://127.0.0.1:\(port)"+ self.goLive()+ } else {+ self.tunnel.start(port: port)+ }+ case .failure(let error):+ self.fail("The local server could not start: \(error.localizedDescription)")+ }+ }+ }++ private func tunnelChanged(_ state: CloudflareTunnel.State) {+ switch state {+ case .live(let url):+ guard phase == .starting else { return }+ gateway.publicBase = url.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/"))+ goLive()+ case .failed(let message):+ guard phase == .starting || phase == .live else { return }+ fail(message)+ case .starting, .stopped:+ break+ }+ }++ private func goLive() {+ phase = .live+ startedAt = Date()+ scheduleAutoStop()+ log(AgentActivity(date: Date(), client: "House Control", title: reach == .local ? "Started on this Mac" : "Link is live", ok: true, quiet: false))+ onLiveChange?(true)+ push()+ // HOUSE_AGENT_LINK_FILE=<path> writes the live link there, for scripted tests.+ if let path = ProcessInfo.processInfo.environment["HOUSE_AGENT_LINK_FILE"] {+ try? gateway.linkURL.write(toFile: path, atomically: true, encoding: .utf8)+ }+ }++ private func fail(_ message: String) {+ let wasLive = phase == .live+ tunnel.stop()+ server.stop()+ stopTimer?.invalidate()+ phase = .failed(message)+ if wasLive { onLiveChange?(false) }+ push()+ }++ func stop(reason: String = "Stopped") {+ guard phase != .off else { return }+ let wasLive = phase == .live+ tunnel.stop()+ server.stop()+ stopTimer?.invalidate()+ stopTimer = nil+ stopsAt = nil+ startedAt = nil+ phase = .off+ gateway.rotateToken() // the old link is dead even if the same address came back+ if wasLive {+ log(AgentActivity(date: Date(), client: "House Control", title: "\(reason) — the link no longer works", ok: true, quiet: false))+ onLiveChange?(false)+ }+ push()+ }++ private func scheduleAutoStop() {+ stopTimer?.invalidate()+ stopTimer = nil+ let hours: Double? = ["1h": 1, "8h": 8][autoStop]+ guard let hours, let startedAt else { stopsAt = nil; return }+ let when = startedAt.addingTimeInterval(hours * 3600)+ stopsAt = when+ stopTimer = Timer.scheduledTimer(withTimeInterval: max(1, when.timeIntervalSinceNow), repeats: false) { [weak self] _ in+ MainActor.assumeIsolated { self?.stop(reason: "Stopped automatically") }+ }+ }++ private func log(_ entry: AgentActivity) {+ activity.append(entry)+ if activity.count > 200 { activity.removeFirst(activity.count - 200) }+ push()+ }++ // MARK: - Requests from the AI (AgentBackend)++ func agentRequest(_ request: [String: Any]) async throws -> [String: Any] {+ let host = try await readyPanel()+ let raw = try await host.webView.callAsyncJavaScript("return await window.house.agent(request)",+ arguments: ["request": request], contentWorld: .page)+ guard let text = raw as? String, let data = text.data(using: .utf8),+ var result = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {+ throw AgentError("House Control did not understand the request.")+ }+ if let plan = result["savePlan"] as? [String: Any] {+ result["savePlan"] = nil+ do {+ try savePlan(plan)+ } catch {+ result = ["content": [["type": "text", "text": "Error: \(error.localizedDescription)"]], "isError": true,+ "summary": "Floor plan not saved: \(error.localizedDescription)"]+ }+ }+ if result["undo"] as? Bool == true {+ result["undo"] = nil+ do {+ try undo()+ result["content"] = [["type": "text", "text": "Undone: the floor plan is back to how it was before the last change. The 3D model is updating."]]+ } catch {+ result = ["content": [["type": "text", "text": "Error: \(error.localizedDescription)"]], "isError": true, "summary": error.localizedDescription]+ }+ }+ return result+ }++ /// The panel page, once it has (re)loaded: a request that arrives while the plan is+ /// being swapped waits for the new one.+ private func readyPanel() async throws -> WebHost {+ for _ in 0..<150 {+ let host = panel()+ if host.isReady { return host }+ try await Task.sleep(nanoseconds: 100_000_000)+ }+ throw AgentError("House Control is busy loading the home. Try again in a moment.")+ }++ private func savePlan(_ plan: [String: Any]) throws {+ if plans.activePlan != "custom", plans.hasCustomPlan {+ throw AgentError("The user is looking at a demo plan, and their own home is saved separately. Ask them to switch to \"My home\" (gear menu in the panel) first.")+ }+ let previous = plans.hasCustomPlan ? try? Data(contentsOf: plans.customPlanURL) : nil+ let previousActive = plans.activePlan+ try plans.saveCustom(plan)+ history.append((previous, previousActive))+ if history.count > 30 { history.removeFirst() }+ reloadAll()+ push()+ }++ func undo() throws {+ guard let last = history.popLast() else { throw AgentError("There is no floor plan change to undo.") }+ if let data = last.data {+ try plans.saveCustom(data: data, select: true)+ } else {+ plans.removeCustom()+ plans.select(last.active)+ }+ reloadAll()+ log(AgentActivity(date: Date(), client: "House Control", title: "Undid the last floor plan change", ok: true, quiet: false))+ }++ struct AgentError: LocalizedError {+ let message: String+ init(_ message: String) { self.message = message }+ var errorDescription: String? { message }+ }++ // MARK: - Window++ func showWindow() {+ if window == nil {+ let host = WebHost(mode: "agent", transparent: false) { [unowned self] in ["agent": self.status()] }+ host.onMessage = { [weak self] message in self?.handle(message) }+ let window = AgentWindow(host: host)+ window.onClose = { [weak self, unowned host] in+ host.webView.configuration.userContentController.removeScriptMessageHandler(forName: "house")+ self?.window = nil+ }+ self.window = window+ host.load()+ }+ window?.show()+ }++ private func handle(_ message: [String: Any]) {+ switch message["type"] as? String {+ case "agent.start":+ if let r = (message["reach"] as? String).flatMap(Reach.init) { reach = r }+ start()+ case "agent.stop":+ stop()+ case "agent.settings":+ var p = permissions+ if let v = message["control"] as? Bool { p.control = v }+ if let v = message["edit"] as? Bool { p.edit = v }+ permissions = p+ if let v = message["autoStop"] as? String, ["1h", "8h", "never"].contains(v) {+ autoStop = v+ if phase == .live { scheduleAutoStop() }+ }+ if let r = (message["reach"] as? String).flatMap(Reach.init), phase != .live, phase != .starting { reach = r }+ push()+ case "agent.copy":+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(message["text"] as? String ?? "", forType: .string)+ case "agent.open":+ if let text = message["url"] as? String, let url = URL(string: text), ["http", "https"].contains(url.scheme ?? "") {+ NSWorkspace.shared.open(url)+ }+ case "agent.undo":+ do { try undo() } catch { log(AgentActivity(date: Date(), client: "House Control", title: error.localizedDescription, ok: false, quiet: false)) }+ push()+ case "agent.install":+ guard !tunnel.isDownloading else { return }+ Task { @MainActor in+ push()+ do {+ try await tunnel.download()+ if case .failed("needs-cloudflared") = phase { phase = .off }+ push()+ } catch {+ tunnelError = error.localizedDescription+ push()+ }+ }+ DispatchQueue.main.async { [weak self] in self?.push() }+ case "ready":+ push()+ default:+ break+ }+ }++ func status() -> [String: Any] {+ var out: [String: Any] = [+ "reach": reach.rawValue,+ "autoStop": autoStop,+ "control": permissions.control,+ "edit": permissions.edit,+ "canUndo": !history.isEmpty,+ "activity": activity.suffix(80).map(\.json),+ "home": plans.activePlan == "custom" ? (plans.customPlanName ?? "My home") : "Demo home",+ "tunnel": ["installed": tunnel.binary != nil, "downloading": tunnel.isDownloading, "error": tunnelError],+ ]+ switch phase {+ case .off: out["state"] = "off"+ case .starting: out["state"] = "starting"+ case .live: out["state"] = "live"+ case .failed(let message):+ out["state"] = message == "needs-cloudflared" ? "setup" : "error"+ out["error"] = message+ }+ if phase == .live {+ out["link"] = gateway.linkURL+ out["mcp"] = gateway.mcpURL+ out["startedAt"] = (startedAt?.timeIntervalSince1970 ?? 0) * 1000+ if let stopsAt { out["stopsAt"] = stopsAt.timeIntervalSince1970 * 1000 }+ }+ return out+ }++ private func push() {+ window?.host.call("agentStatus", status())+ }+}++/// The AI Access window.+@MainActor+final class AgentWindow: NSObject, NSWindowDelegate {+ let host: WebHost+ private let window: NSWindow+ var onClose: (() -> Void)?++ init(host: WebHost) {+ self.host = host+ window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 460, height: 820),+ styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],+ backing: .buffered, defer: false)+ super.init()+ window.title = "AI Access"+ window.titlebarAppearsTransparent = true+ window.titleVisibility = .hidden+ window.isMovableByWindowBackground = true+ window.backgroundColor = NSColor(calibratedRed: 0.035, green: 0.043, blue: 0.08, alpha: 1)+ window.appearance = NSAppearance(named: .darkAqua)+ window.minSize = NSSize(width: 420, height: 560)+ window.maxSize = NSSize(width: 640, height: 2000)+ window.isReleasedWhenClosed = false+ window.delegate = self+ window.contentView = host.webView+ window.center()+ window.setFrameAutosaveName("HouseControlAgent")+ }++ func show() {+ NSApp.activate(ignoringOtherApps: true)+ window.makeKeyAndOrderFront(nil)+ }++ func windowWillClose(_ notification: Notification) { onClose?() }+}diff --git a/macos/Sources/HouseControl/AppDelegate.swift b/macos/Sources/HouseControl/AppDelegate.swiftindex 9742b7f..473217b 100644--- a/macos/Sources/HouseControl/AppDelegate.swift+++ b/macos/Sources/HouseControl/AppDelegate.swift@@ -17,9 +17,24 @@ final class AppDelegate: NSObject, NSApplicationDelegate {private var panel: PanelController!private var editor: EditorController?private var pollTimer: Timer?+ /// AI Access: the private link an AI assistant uses to run the home.+ private lazy var agent: AgentController = {+ let agent = AgentController(plans: plans, panel: { [unowned self] in self.panel.host }, reloadAll: { [unowned self] in+ self.reloadAll()+ self.editor?.host.load()+ })+ agent.onLiveChange = { [weak self] live in+ guard let self else { return }+ self.panel.host.call("agentLive", live)+ self.refreshStatusIcon()+ }+ return agent+ }()+ private var lastSummary: [String: Any] = [:]func applicationDidFinishLaunching(_ notification: Notification) {buildMainMenu()+ stopTunnelOnSignals()statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)if let button = statusItem.button {@@ -57,6 +72,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {if ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] != nil {DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in self?.openEditor() }}+ if let open = ProcessInfo.processInfo.environment["HOUSE_OPEN_AGENT"] {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in+ self?.openAgent()+ if open == "start" { self?.agent.start() }+ }+ }if ProcessInfo.processInfo.environment["HOUSE_OPEN_ON_LAUNCH"] != nil {DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { [weak self] in self?.togglePanel() }}@@ -64,6 +85,26 @@ final class AppDelegate: NSObject, NSApplicationDelegate {func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }+ func applicationWillTerminate(_ notification: Notification) {+ agent.stop(reason: "House Control quit")+ }++ /// `kill`, a logout or Ctrl-C end the app without applicationWillTerminate: the AI+ /// Access tunnel must not outlive it.+ private var signalSources: [DispatchSourceSignal] = []+ private func stopTunnelOnSignals() {+ for sig in [SIGTERM, SIGINT, SIGHUP] {+ signal(sig, SIG_IGN)+ let source = DispatchSource.makeSignalSource(signal: sig, queue: .main)+ source.setEventHandler { [weak self] in+ MainActor.assumeIsolated { self?.agent.stop(reason: "House Control quit") }+ exit(0)+ }+ source.resume()+ signalSources.append(source)+ }+ }+// MARK: - Status itemprivate func symbol(_ name: String) -> NSImage? {@@ -74,18 +115,40 @@ final class AppDelegate: NSObject, NSApplicationDelegate {}private func updateStatus(_ summary: [String: Any]) {+ lastSummary = summary+ refreshStatusIcon()+ }++ /// The house, with sparkles beside it while an AI assistant has a live link.+ private func refreshStatusIcon() {guard let button = statusItem.button else { return }+ let summary = lastSummarylet lights = summary["lightsOn"] as? Int ?? 0let acOn = summary["acOn"] as? Int ?? 0var parts: [String] = []if lights > 0 { parts.append("\(lights)") }if acOn > 0, let target = summary["acTarget"] as? Int { parts.append("\(target)°") }- button.image = symbol(lights > 0 || acOn > 0 ? "house.fill" : "house")+ let house = lights > 0 || acOn > 0 ? "house.fill" : "house"+ button.image = agent.isLive ? pair(house, "sparkles") : symbol(house)button.attributedTitle = NSAttributedString(string: parts.isEmpty ? "" : " " + parts.joined(separator: " · "),attributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 13, weight: .medium)])}+ /// Two symbols side by side as one template image.+ private func pair(_ first: String, _ second: String) -> NSImage? {+ guard let a = symbol(first), let b = NSImage(systemSymbolName: second, accessibilityDescription: nil)?+ .withSymbolConfiguration(NSImage.SymbolConfiguration(pointSize: 10, weight: .semibold)) else { return symbol(first) }+ let size = NSSize(width: a.size.width + b.size.width + 1, height: max(a.size.height, b.size.height))+ let image = NSImage(size: size, flipped: false) { _ in+ a.draw(in: NSRect(x: 0, y: (size.height - a.size.height) / 2, width: a.size.width, height: a.size.height))+ b.draw(in: NSRect(x: a.size.width + 1, y: size.height - b.size.height, width: b.size.width, height: b.size.height))+ return true+ }+ image.isTemplate = true+ return image+ }+@objc private func statusItemClicked() {if NSApp.currentEvent?.type == .rightMouseUp {panel.hide()@@ -99,6 +162,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {islandItem.target = selfislandItem.state = island?.isShown == true ? .on : .offmenu.addItem(withTitle: "Pair iPhone…", action: #selector(pairPhone), keyEquivalent: "").target = self+ let aiItem = menu.addItem(withTitle: agent.isLive ? "AI Access — Live" : "AI Access…", action: #selector(openAgent), keyEquivalent: "")+ aiItem.target = self+ aiItem.image = NSImage(systemSymbolName: "sparkles", accessibilityDescription: nil)+ if agent.isLive {+ menu.addItem(withTitle: "Stop AI Access", action: #selector(stopAgent), keyEquivalent: "").target = self+ }for device in sync.connectedDevices {let item = menu.addItem(withTitle: "\(device) is connected", action: nil, keyEquivalent: "")item.image = NSImage(systemSymbolName: "iphone", accessibilityDescription: nil)@@ -126,6 +195,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {boot["tuya"] = hub.tuyaInfoboot["smartLife"] = hub.smartLifeInfoif ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] == "smartlife" { boot["section"] = "tuya" }+ boot["agentLive"] = agent.isLive// HOUSE_OPEN_DEVICE=<id> starts the panel on that light's or AC's detail sheet.if let device = ProcessInfo.processInfo.environment["HOUSE_OPEN_DEVICE"] { boot["openDevice"] = device }return boot@@ -219,6 +289,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {editor?.host.load()}case "loadPlan": loadPlan()+ case "openAgent": openAgent()case "revealPlan": revealPlan()case "openEditor": openEditor()case "quit": NSApp.terminate(nil)@@ -303,6 +374,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate {}}+ // MARK: - AI Access++ @objc private func openAgent() {+ panel.hide()+ agent.showWindow()+ }++ @objc private func stopAgent() { agent.stop() }+// MARK: - Device state/// Real devices are read while there is something on screen to show them in.diff --git a/macos/Sources/HouseControl/CloudflareTunnel.swift b/macos/Sources/HouseControl/CloudflareTunnel.swiftnew file mode 100644index 0000000..aadd9e9--- /dev/null+++ b/macos/Sources/HouseControl/CloudflareTunnel.swift@@ -0,0 +1,190 @@+import Foundation+import Security++/// Gives the loopback AI gateway a public HTTPS address through a Cloudflare Quick Tunnel:+/// `cloudflared tunnel --url http://127.0.0.1:<port>`. No Cloudflare account, nothing to+/// configure; every start gets a new random `*.trycloudflare.com` name, and stopping the+/// process makes that name disappear for good.+///+/// cloudflared is found in Homebrew's usual places, or downloaded on request from+/// Cloudflare's own GitHub releases into the app's data folder.+@MainActor+final class CloudflareTunnel {+ enum State: Equatable {+ case stopped+ case starting+ case live(URL)+ case failed(String)+ }++ private(set) var state: State = .stopped { didSet { if state != oldValue { onChange?(state) } } }+ var onChange: ((State) -> Void)?++ private var process: Process?+ private var output = ""+ private var publicURL: URL?+ private var readyCheck: DispatchWorkItem?+ private let directory: URL+ private var pidFile: URL { directory.appendingPathComponent("cloudflared.pid") }+ /// Where a downloaded copy is kept.+ var bundledBinary: URL { directory.appendingPathComponent("bin/cloudflared") }++ init(directory: URL) {+ self.directory = directory+ killLeftover()+ }++ /// The cloudflared to run, if there is one.+ var binary: URL? {+ let candidates = [bundledBinary.path, "/opt/homebrew/bin/cloudflared", "/usr/local/bin/cloudflared"]+ + (ProcessInfo.processInfo.environment["PATH"] ?? "").split(separator: ":").map { "\($0)/cloudflared" }+ return candidates.first { FileManager.default.isExecutableFile(atPath: $0) }.map(URL.init(fileURLWithPath:))+ }++ func start(port: UInt16) {+ stop()+ guard let binary else { state = .failed("Cloudflare's connector (cloudflared) is not installed."); return }+ let process = Process()+ process.executableURL = binary+ // cloudflared reads ~/.cloudflared/config.yml when it exists; a quick tunnel must not+ // pick up the user's own named-tunnel settings, so it gets an empty file of its own.+ let config = directory.appendingPathComponent("cloudflared.yml")+ if !FileManager.default.fileExists(atPath: config.path) { try? Data("# House Control quick tunnel\n".utf8).write(to: config) }+ process.arguments = ["tunnel", "--no-autoupdate", "--config", config.path, "--metrics", "127.0.0.1:0",+ "--url", "http://127.0.0.1:\(port)"]+ process.currentDirectoryURL = directory+ let pipe = Pipe()+ process.standardError = pipe+ process.standardOutput = pipe+ pipe.fileHandleForReading.readabilityHandler = { [weak self] handle in+ let text = String(data: handle.availableData, encoding: .utf8) ?? ""+ DispatchQueue.main.async { self?.consume(text) }+ }+ process.terminationHandler = { [weak self] finished in+ DispatchQueue.main.async {+ guard let self, self.process === finished else { return }+ self.process = nil+ try? FileManager.default.removeItem(at: self.pidFile)+ let tail = self.output.split(separator: "\n").suffix(3).joined(separator: " ")+ self.state = .failed(Self.explain(tail))+ }+ }+ output = ""+ publicURL = nil+ state = .starting+ do {+ try process.run()+ self.process = process+ try? String(process.processIdentifier).write(to: pidFile, atomically: true, encoding: .utf8)+ } catch {+ state = .failed("Could not start cloudflared: \(error.localizedDescription)")+ }+ }++ func stop() {+ readyCheck?.cancel()+ readyCheck = nil+ if let process {+ self.process = nil+ (process.standardError as? Pipe)?.fileHandleForReading.readabilityHandler = nil+ process.terminate()+ }+ try? FileManager.default.removeItem(at: pidFile)+ publicURL = nil+ state = .stopped+ }++ private func consume(_ text: String) {+ guard process != nil else { return }+ output += text+ if output.count > 20_000 { output = String(output.suffix(10_000)) }+ if publicURL == nil, let range = output.range(of: #"https://[a-z0-9-]+\.trycloudflare\.com"#, options: .regularExpression) {+ publicURL = URL(string: String(output[range]))+ }+ // The address is printed before the edge accepts it; it works once a connection is registered.+ if let url = publicURL, case .starting = state, output.contains("Registered tunnel connection") {+ let check = DispatchWorkItem { [weak self] in+ guard let self, self.process != nil, case .starting = self.state else { return }+ self.state = .live(url)+ }+ readyCheck = check+ // A moment for the new name to reach Cloudflare's DNS everywhere.+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: check)+ }+ if case .starting = state, output.contains("failed to request quick Tunnel") || output.contains("429 Too Many Requests") {+ let tail = output.split(separator: "\n").suffix(2).joined(separator: " ")+ stop()+ state = .failed(Self.explain(tail))+ }+ }++ private static func explain(_ log: String) -> String {+ if log.contains("429") { return "Cloudflare is limiting new quick tunnels right now. Try again in a minute." }+ if log.contains("no such host") || log.contains("dial tcp") || log.contains("network is unreachable") {+ return "Cloudflare could not be reached. Check the internet connection."+ }+ return log.isEmpty ? "The tunnel stopped." : "The tunnel stopped: \(log.prefix(160))"+ }++ /// A cloudflared left running by a previous run of the app (after a crash) would keep an+ /// address alive that leads nowhere; it is stopped at launch.+ private func killLeftover() {+ guard let text = try? String(contentsOf: pidFile, encoding: .utf8), let pid = Int32(text.trimmingCharacters(in: .whitespacesAndNewlines)) else { return }+ var buffer = [CChar](repeating: 0, count: 4096)+ if proc_pidpath(pid, &buffer, UInt32(buffer.count)) > 0, String(cString: buffer).hasSuffix("cloudflared") { kill(pid, SIGTERM) }+ try? FileManager.default.removeItem(at: pidFile)+ }++ // MARK: - Download++ private(set) var isDownloading = false++ /// Fetches the latest cloudflared for this Mac from Cloudflare's GitHub releases and+ /// keeps it only if it carries Cloudflare's Developer ID signature.+ func download() async throws {+ isDownloading = true+ defer { isDownloading = false }+ #if arch(arm64)+ let asset = "cloudflared-darwin-arm64.tgz"+ #else+ let asset = "cloudflared-darwin-amd64.tgz"+ #endif+ let url = URL(string: "https://github.com/cloudflare/cloudflared/releases/latest/download/\(asset)")!+ let (file, response) = try await URLSession.shared.download(from: url)+ guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw TunnelError("GitHub answered \((response as? HTTPURLResponse)?.statusCode ?? 0).") }+ let work = directory.appendingPathComponent("bin/unpack-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: work) }+ let tar = Process()+ tar.executableURL = URL(fileURLWithPath: "/usr/bin/tar")+ tar.arguments = ["-xzf", file.path, "-C", work.path]+ try tar.run()+ tar.waitUntilExit()+ let unpacked = work.appendingPathComponent("cloudflared")+ guard tar.terminationStatus == 0, FileManager.default.fileExists(atPath: unpacked.path) else { throw TunnelError("The download could not be unpacked.") }+ guard Self.signedByCloudflare(unpacked) else { throw TunnelError("The downloaded file is not signed by Cloudflare, so it was not kept.") }+ try? FileManager.default.removeItem(at: bundledBinary)+ try FileManager.default.moveItem(at: unpacked, to: bundledBinary)+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: bundledBinary.path)+ }++ /// A valid Developer ID signature whose certificate names Cloudflare.+ static func signedByCloudflare(_ url: URL) -> Bool {+ var code: SecStaticCode?+ guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess, let code else { return false }+ var requirement: SecRequirement?+ guard SecRequirementCreateWithString("anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.13] exists" as CFString, [], &requirement) == errSecSuccess,+ SecStaticCodeCheckValidity(code, [], requirement) == errSecSuccess else { return false }+ var info: CFDictionary?+ guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess,+ let dict = info as? [String: Any], let certificates = dict[kSecCodeInfoCertificates as String] as? [SecCertificate],+ let leaf = certificates.first, let summary = SecCertificateCopySubjectSummary(leaf) as String? else { return false }+ return summary.localizedCaseInsensitiveContains("Cloudflare")+ }++ struct TunnelError: LocalizedError {+ let message: String+ init(_ message: String) { self.message = message }+ var errorDescription: String? { message }+ }+}diff --git a/macos/Sources/HouseControl/WebHost.swift b/macos/Sources/HouseControl/WebHost.swiftindex de419f1..6277eea 100644--- a/macos/Sources/HouseControl/WebHost.swift+++ b/macos/Sources/HouseControl/WebHost.swift@@ -8,12 +8,14 @@ private final class FirstMouseWebView: WKWebView {override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }}-/// A WKWebView showing the web UI in one of its modes ("panel", "editor" or "island"),+/// A WKWebView showing the web UI in one of its modes ("panel", "editor", "island" or "agent"),/// plus the JSON message bridge in both directions.final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {let webView: WKWebViewlet mode: Stringvar onMessage: (([String: Any]) -> Void)?+ /// True once the page has started and reported "ready"; false again while it reloads.+ private(set) var isReady = falseprivate var bootProvider: () -> [String: Any]/// Where the web UI lives: the app bundle, or a directory / dev server given by the environment.@@ -49,6 +51,7 @@ final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {}func load() {+ isReady = falselet controller = webView.configuration.userContentControllercontroller.removeAllUserScripts()var boot = bootProvider()@@ -95,6 +98,7 @@ final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {NSLog("House Control web (%@): %@", mode, body["text"] as? String ?? "")return}+ if body["type"] as? String == "ready" { isReady = true }onMessage?(body)}diff --git a/web/src/agent/console.css b/web/src/agent/console.cssnew file mode 100644index 0000000..be383ab--- /dev/null+++ b/web/src/agent/console.css@@ -0,0 +1,318 @@+/* The AI Access window. */++html.mode-agent { overflow-y: auto; overflow-x: hidden; background: #07090f; }+html.mode-agent body {+ height: auto;+ min-height: 100%;+ overflow: visible;+ user-select: text;+ -webkit-user-select: text;+ background: #07090f;+}+html.mode-agent #app { display: block; padding: 0; height: auto; min-height: 100%; }+html.mode-agent body::before {+ /* Aurora behind the header. */+ content: '';+ position: fixed;+ inset: -20% -10% auto -10%;+ height: 560px;+ pointer-events: none;+ background:+ radial-gradient(50% 60% at 30% 40%, rgba(124, 92, 255, 0.34), transparent 70%),+ radial-gradient(45% 55% at 75% 30%, rgba(61, 139, 255, 0.28), transparent 70%),+ radial-gradient(40% 40% at 55% 70%, rgba(255, 95, 196, 0.12), transparent 70%);+ filter: blur(10px);+ transition: opacity 900ms ease;+ opacity: 0.55;+}+html.mode-agent:has(.agent[data-state='live']) body::before { opacity: 1; }++.agent {+ --violet: #8b6cff;+ --blue: #3d8bff;+ --card: rgba(255, 255, 255, 0.045);+ --card-line: rgba(255, 255, 255, 0.08);+ position: relative;+ max-width: 560px;+ margin: 0 auto;+ padding: 46px 22px 30px;+ display: flex;+ flex-direction: column;+ gap: 14px;+}++/* ---------- hero ---------- */++.hero { display: flex; flex-direction: column; align-items: center; text-align: center; padding-bottom: 6px; }+.hero h1 {+ margin: 18px 0 6px;+ font-family: -apple-system, 'SF Pro Display', 'Inter', system-ui, sans-serif;+ font-size: 30px; font-weight: 700; letter-spacing: -0.02em;+ background: linear-gradient(180deg, #fff 30%, #c9cfe6);+ -webkit-background-clip: text; background-clip: text; color: transparent;+}+.lede { margin: 0 0 16px; max-width: 360px; font-size: 13.5px; line-height: 1.5; color: var(--muted); }++.orb { position: relative; width: 104px; height: 104px; margin-top: 6px; }+.orb > * { position: absolute; inset: 0; border-radius: 50%; }+.orb-glow {+ inset: -26px;+ background: radial-gradient(circle, rgba(124, 92, 255, 0.5), rgba(61, 139, 255, 0.22) 42%, transparent 68%);+ opacity: 0.25;+ transition: opacity 900ms ease;+ will-change: opacity, transform;+}+/* The ring is a static mask over a disc that turns: only a transform animates, which+ WebKit composites on the GPU instead of repainting the gradient every frame. */+.orb-ring {+ overflow: hidden;+ -webkit-mask: radial-gradient(circle, transparent 57%, #000 59.5%);+ mask: radial-gradient(circle, transparent 57%, #000 59.5%);+ filter: saturate(0.2) brightness(0.65);+ transition: filter 900ms ease;+}+.orb-spin {+ position: absolute; inset: -2px; border-radius: 50%;+ background: conic-gradient(from 0deg, #8b6cff, #3d8bff, #42d6e8, #3d8bff, #ff5fc4, #8b6cff);+ animation: orb-spin 18s linear infinite;+ will-change: transform;+}+.orb-core {+ inset: 12px;+ display: grid; place-items: center;+ color: #fff;+ background: radial-gradient(circle at 35% 30%, #2a2f4a, #0d1020 70%);+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.12), 0 10px 30px -10px rgba(0, 0, 0, 0.8);+}+.orb-core .icon { opacity: 0.55; transition: opacity 600ms, transform 800ms var(--spring); }+[data-state='starting'] .orb-ring { filter: none; }+[data-state='starting'] .orb-spin { animation-duration: 2.4s; }+[data-state='starting'] .orb-glow { opacity: 0.55; }+[data-state='live'] .orb-ring { filter: none; }+[data-state='live'] .orb-spin { animation-duration: 9s; }+[data-state='live'] .orb-glow { opacity: 1; animation: orb-breathe 4.8s ease-in-out infinite; }+[data-state='live'] .orb-core .icon { opacity: 1; transform: scale(1.06); }+[data-state='error'] .orb-ring { filter: hue-rotate(150deg) saturate(1.3) brightness(0.75); }+@keyframes orb-spin { to { transform: rotate(360deg); } }+@keyframes orb-breathe { 50% { opacity: 0.6; transform: scale(0.92); } }++.pill {+ display: inline-flex; align-items: center; gap: 8px;+ height: 28px; padding: 0 12px; margin-bottom: 16px;+ border-radius: 999px; font-size: 12.5px; font-weight: 600;+ background: rgba(255, 255, 255, 0.06); border: 1px solid var(--card-line);+ color: var(--muted);+}+.pill .dot { width: 7px; height: 7px; border-radius: 50%; background: rgba(255, 255, 255, 0.3); }+.pill-reach { padding: 2px 7px; border-radius: 999px; font-size: 11px; background: rgba(255, 255, 255, 0.08); color: var(--text); }+[data-state='live'] .pill { color: #d9ffe9; border-color: rgba(52, 199, 89, 0.35); background: rgba(52, 199, 89, 0.1); }+[data-state='live'] .pill .dot { background: #34c759; box-shadow: 0 0 0 0 rgba(52, 199, 89, 0.6); animation: live-dot 1.8s ease-out infinite; }+[data-state='starting'] .pill .dot { background: #8b6cff; animation: blink 0.9s ease-in-out infinite alternate; }+[data-state='error'] .pill { color: #ffd2cc; border-color: rgba(255, 90, 79, 0.35); background: rgba(255, 90, 79, 0.1); }+[data-state='error'] .pill .dot { background: #ff5a4f; }+@keyframes live-dot { 70% { box-shadow: 0 0 0 7px rgba(52, 199, 89, 0); } 100% { box-shadow: 0 0 0 0 rgba(52, 199, 89, 0); } }+@keyframes blink { to { opacity: 0.3; } }++.primary {+ display: inline-flex; align-items: center; justify-content: center; gap: 9px;+ width: 100%; max-width: 300px; height: 50px;+ border-radius: 15px; font-size: 15px; font-weight: 650; color: #fff;+ background: linear-gradient(115deg, #7c5cff 0%, #4f7dff 55%, #3d8bff 100%);+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.16) inset, 0 12px 30px -10px rgba(110, 90, 255, 0.85);+ transition: transform 200ms var(--spring), box-shadow 300ms, background 300ms, filter 200ms;+}+.primary:hover { filter: brightness(1.08); }+.primary:active { transform: scale(0.97); }+.primary.stop {+ background: rgba(255, 255, 255, 0.06);+ color: #ff8a80;+ box-shadow: 0 0 0 1px rgba(255, 110, 100, 0.4) inset;+}+.primary.small { width: auto; height: 34px; padding: 0 14px; border-radius: 10px; font-size: 13px; }+.primary[disabled] { opacity: 0.6; pointer-events: none; }++.spinner {+ width: 14px; height: 14px; border-radius: 50%;+ border: 2px solid rgba(255, 255, 255, 0.25); border-top-color: currentColor;+ animation: orb-spin 0.8s linear infinite;+}++.seg {+ display: inline-flex; gap: 2px; padding: 3px; margin-top: 12px;+ border-radius: 11px; background: rgba(255, 255, 255, 0.05); border: 1px solid var(--card-line);+}+.seg button {+ display: inline-flex; align-items: center; gap: 6px;+ height: 28px; padding: 0 11px; border-radius: 8px;+ font-size: 12px; font-weight: 600; color: var(--muted);+ transition: background 200ms, color 200ms;+}+.seg button.on { background: rgba(255, 255, 255, 0.12); color: var(--text); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4); }+.seg.locked button:not(.on) { opacity: 0.35; cursor: default; }++.callout {+ width: 100%; margin-top: 16px; padding: 14px 16px;+ border-radius: 16px; text-align: left; font-size: 12.5px; line-height: 1.5;+ background: rgba(124, 92, 255, 0.09); border: 1px solid rgba(139, 108, 255, 0.3);+}+.callout.hidden { display: none; }+.callout.bad { background: rgba(255, 90, 79, 0.08); border-color: rgba(255, 90, 79, 0.3); }+.callout p { margin: 6px 0 0; color: var(--muted); }+.callout .err { color: #ff8a80; }+.callout-title { display: flex; align-items: center; gap: 7px; font-weight: 650; font-size: 13px; }+.callout-actions { display: flex; gap: 10px; align-items: center; margin-top: 12px; }++/* ---------- cards ---------- */++.card {+ padding: 16px;+ border-radius: 20px;+ background: var(--card);+ border: 1px solid var(--card-line);+ box-shadow: 0 1px 0 rgba(255, 255, 255, 0.04) inset;+ animation: card-in 500ms var(--ease) both;+}+.card.hidden { display: none; }+@keyframes card-in { from { opacity: 0; transform: translateY(8px); } }+.card-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }+.card-title { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 650; letter-spacing: 0.01em; }+.card-title .icon { color: #b9a6ff; }++.ghost {+ display: inline-flex; align-items: center; gap: 5px;+ height: 26px; padding: 0 9px; border-radius: 8px;+ font-size: 12px; font-weight: 600; color: var(--muted);+ background: rgba(255, 255, 255, 0.05);+ transition: background 200ms, color 200ms;+}+.ghost:hover { background: rgba(255, 255, 255, 0.1); color: var(--text); }+.ghost[disabled] { opacity: 0.35; pointer-events: none; }++.link-card {+ background: linear-gradient(160deg, rgba(124, 92, 255, 0.16), rgba(61, 139, 255, 0.07) 60%, rgba(255, 255, 255, 0.03));+ border-color: rgba(139, 108, 255, 0.35);+}+.url {+ display: flex; align-items: center; gap: 8px;+ padding: 6px 6px 6px 12px; border-radius: 12px;+ background: rgba(0, 0, 0, 0.35); border: 1px solid rgba(255, 255, 255, 0.08);+}+.url-text { flex: 1; min-width: 0; display: flex; white-space: nowrap; font: 500 12.5px/1.4 ui-monospace, 'SF Mono', Menlo, monospace; }+.url-host { min-width: 0; overflow: hidden; text-overflow: ellipsis; color: #dfe4f5; }+.url-token { flex: none; color: #b9a6ff; }+.copy {+ display: inline-flex; align-items: center; gap: 6px; flex: none;+ height: 30px; padding: 0 11px; border-radius: 9px;+ font-size: 12px; font-weight: 650;+ background: rgba(255, 255, 255, 0.1);+ transition: background 200ms, color 200ms;+}+.copy:hover { background: rgba(255, 255, 255, 0.16); }+.copy.done { background: rgba(52, 199, 89, 0.22); color: #c9ffdc; }+.copy.small { height: 26px; padding: 0 9px; font-size: 11.5px; }+.actions { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 8px; margin-top: 10px; }+.action[hidden] { display: none; }+.action {+ display: flex; align-items: center; justify-content: center; gap: 8px;+ height: 40px; border-radius: 12px; font-size: 13px; font-weight: 600;+ background: rgba(255, 255, 255, 0.07); border: 1px solid rgba(255, 255, 255, 0.07);+ transition: background 200ms, transform 200ms var(--spring);+}+.action:hover { background: rgba(255, 255, 255, 0.12); }+.action:active { transform: scale(0.97); }+.action.done { background: rgba(52, 199, 89, 0.2); }+.hint { margin: 11px 2px 0; font-size: 12px; line-height: 1.5; color: var(--muted); }+.hint em, .tab-body em { color: var(--text); font-style: normal; }++/* ---------- connect ---------- */++.tabs { display: flex; gap: 4px; margin-bottom: 12px; overflow-x: auto; scrollbar-width: none; }+.tabs button {+ flex: none; height: 28px; padding: 0 11px; border-radius: 999px;+ font-size: 12px; font-weight: 600; color: var(--muted);+ border: 1px solid transparent;+}+.tabs button.on { color: var(--text); background: rgba(255, 255, 255, 0.08); border-color: var(--card-line); }+.tab-body { font-size: 12.5px; line-height: 1.55; color: #cfd5e6; }+.tab-body > p { margin: 0 0 10px; }+.tab-body .muted { color: var(--faint); margin-top: 10px; }+.steps { margin: 0 0 10px; padding: 0; list-style: none; counter-reset: step var(--start, 0); }+.steps li { position: relative; padding: 0 0 8px 28px; counter-increment: step; }+.steps li::before {+ content: counter(step);+ position: absolute; left: 0; top: 0;+ width: 19px; height: 19px; border-radius: 50%;+ display: grid; place-items: center;+ font-size: 11px; font-weight: 700; color: #fff;+ background: linear-gradient(135deg, #7c5cff, #3d8bff);+}+.code {+ display: flex; align-items: flex-start; gap: 8px;+ margin: 4px 0 12px; padding: 9px 8px 9px 12px; border-radius: 11px;+ background: rgba(0, 0, 0, 0.4); border: 1px solid rgba(255, 255, 255, 0.07);+}+.code code { flex: 1; min-width: 0; word-break: break-all; font: 500 11.5px/1.5 ui-monospace, 'SF Mono', Menlo, monospace; color: #dfe4f5; }+code.inline { font: 500 11.5px ui-monospace, 'SF Mono', Menlo, monospace; padding: 1px 5px; border-radius: 5px; background: rgba(255, 255, 255, 0.08); color: #dfe4f5; }++/* ---------- permissions ---------- */++.row { display: flex; align-items: center; gap: 12px; padding: 10px 0; border-top: 1px solid rgba(255, 255, 255, 0.06); }+.card-head + .row { border-top: 0; padding-top: 2px; }+.row.column { flex-direction: column; align-items: stretch; gap: 0; }+.row.column .seg { margin-top: 8px; align-self: flex-start; }+.row-icon {+ flex: none; width: 34px; height: 34px; border-radius: 10px;+ display: grid; place-items: center; color: #d6ccff;+ background: rgba(139, 108, 255, 0.14);+}+.row-text { flex: 1; min-width: 0; }+.row-title { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 600; }+.row-title .icon { color: #b9a6ff; }+.row-sub { margin-top: 2px; font-size: 11.5px; line-height: 1.4; color: var(--muted); }++.ai-switch {+ position: relative; flex: none; width: 42px; height: 25px; border-radius: 999px;+ background: rgba(255, 255, 255, 0.14);+ transition: background 250ms;+}+.ai-switch i {+ position: absolute; top: 2px; left: 2px; width: 21px; height: 21px; border-radius: 50%;+ background: #fff; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4);+ transition: transform 300ms var(--spring);+}+.ai-switch[aria-checked='true'] { background: linear-gradient(115deg, #7c5cff, #3d8bff); }+.ai-switch[aria-checked='true'] i { transform: translateX(17px); }++/* ---------- activity ---------- */++.feed { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; max-height: 330px; overflow-y: auto; }+.feed li {+ display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: 10px;+ padding: 8px 8px; border-radius: 11px; font-size: 12.5px;+}+.feed li.fresh { animation: feed-in 700ms var(--ease) both; }+@keyframes feed-in { from { opacity: 0; transform: translateY(-6px); background: rgba(139, 108, 255, 0.22); } 60% { background: rgba(139, 108, 255, 0.12); } }+.feed li.quiet { opacity: 0.55; }+.feed li.bad .what { color: #ff9a90; }+.feed li.empty { display: flex; gap: 10px; color: var(--muted); padding: 14px 8px; line-height: 1.5; }+.feed li.empty .icon { color: #b9a6ff; flex: none; }+.who {+ display: inline-flex; align-items: center; gap: 4px;+ padding: 3px 8px 3px 6px; border-radius: 999px;+ font-size: 11px; font-weight: 700; white-space: nowrap;+ color: var(--c); background: color-mix(in srgb, var(--c) 14%, transparent);+}+.what { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #e6e9f2; }+.feed time { font-size: 11px; color: var(--faint); font-variant-numeric: tabular-nums; }++/* ---------- footer ---------- */++.privacy { padding: 6px 6px 0; font-size: 11.5px; line-height: 1.55; color: var(--faint); }+.privacy-title { display: flex; align-items: center; gap: 7px; margin-bottom: 6px; font-size: 12px; font-weight: 650; color: var(--muted); }+.privacy-title .icon { color: #34c759; }+.privacy ul { margin: 0; padding-left: 18px; }+.privacy li { margin-bottom: 3px; }++html.mode-agent ::-webkit-scrollbar { width: 9px; height: 0; }+html.mode-agent ::-webkit-scrollbar-thumb { border-radius: 9px; border: 2px solid transparent; background: rgba(255, 255, 255, 0.14) padding-box; }+html.mode-agent ::-webkit-scrollbar-track { background: transparent; }diff --git a/web/src/agent/console.js b/web/src/agent/console.jsnew file mode 100644index 0000000..544368e--- /dev/null+++ b/web/src/agent/console.js@@ -0,0 +1,312 @@+// The AI Access window: start and stop the private link, hand it to an assistant, choose+// what the assistant may do, and watch what it does. The native shell owns the link+// (AgentController.swift) and sends its status here; in a plain browser a stand-in+// plays the same states so the page can be worked on with `vite dev`.+import { h } from '../ui/dom.js';+import { icon } from '../ui/icons.js';+import { isNative, post, incoming } from '../bridge.js';+import './console.css';++const CLIENT_COLORS = {+ ChatGPT: '#19c37d', Claude: '#e08a5f', 'Claude Code': '#e08a5f', Cursor: '#e6e9f2', Gemini: '#6ea8ff',+ Perplexity: '#3fc1c9', Copilot: '#8ab4ff', 'House Control': '#8a94ab',+};+const clientColor = (name) => CLIENT_COLORS[name] || '#b9a6ff';++const TABS = [+ { id: 'chat', label: 'Any chat' },+ { id: 'claude', label: 'Claude' },+ { id: 'chatgpt', label: 'ChatGPT' },+ { id: 'code', label: 'Code & agents' },+];++export function bootConsole(root) {+ document.documentElement.classList.add('mode-agent');+ let status = window.__HOUSE_BOOT__?.agent || { state: 'off', reach: 'internet', autoStop: '8h', control: true, edit: true, activity: [], tunnel: { installed: true } };+ let tab = 'chat';+ const send = isNative ? post : fakeNative((s) => { status = s; render(); });++ /* ---------- skeleton ---------- */++ const orb = h('div.orb', h('div.orb-glow'), h('div.orb-ring', h('div.orb-spin')), h('div.orb-core', icon('sparkles', 30, 1.8)));+ const pill = h('div.pill');+ const primary = h('button.primary', { onclick: () => send(status.state === 'live' || status.state === 'starting' ? 'agent.stop' : 'agent.start', { reach: status.reach }) });+ const reachSeg = segmented([['internet', 'globe', 'Over the internet'], ['local', 'laptop', 'This Mac only']],+ (v) => send('agent.settings', { reach: v }));+ const callout = h('div.callout');+ const hero = h('header.hero', orb,+ h('h1', 'AI Access'),+ h('p.lede', 'Let ChatGPT, Claude or any AI assistant see and run your home — through a private link that lives only as long as you want it to.'),+ pill, primary, reachSeg.el, callout);++ const urlText = h('span.url-text');+ const linkHint = h('p.hint');+ const chatActions = h('div.actions',+ h('button.action', { onclick: (ev) => { copy(chatPrompt()); flash(ev.currentTarget, 'Copied'); } }, icon('chat', 16), h('span', 'Copy for a chat')),+ h('button.action', { onclick: () => send('agent.open', { url: status.link }) }, icon('book', 16), h('span', 'Open the guide')));+ const linkCard = h('section.card.link-card',+ h('div.card-head', h('span.card-title', icon('key', 15), 'Your private link'),+ h('button.ghost', { title: 'Make a new link; the current one stops working', onclick: () => { send('agent.stop'); setTimeout(() => send('agent.start', { reach: status.reach }), 250); } }, icon('rotate', 13), 'New link')),+ h('div.url', urlText, copyButton(() => status.link)),+ chatActions, linkHint);++ const tabBar = h('div.tabs');+ const tabBody = h('div.tab-body');+ const connectCard = h('section.card', h('div.card-head', h('span.card-title', icon('link', 15), 'Connect an assistant')), tabBar, tabBody);++ const controlToggle = toggle((v) => send('agent.settings', { control: v }));+ const editToggle = toggle((v) => send('agent.settings', { edit: v }));+ const stopSeg = segmented([['1h', null, '1 hour'], ['8h', null, '8 hours'], ['never', null, 'Never']], (v) => send('agent.settings', { autoStop: v }));+ const permsCard = h('section.card',+ h('div.card-head', h('span.card-title', icon('shield', 15), 'What it may do')),+ row('sun', 'Lights, climate and scenes', 'Switch and dim lights, set air conditioners, run scenes', controlToggle.el),+ row('box', 'Your 3D home', 'Rebuild rooms from photos, move furniture, add devices — always undoable', editToggle.el),+ h('div.row.column', h('div.row-text', h('div.row-title', icon('clock', 15), 'Stop the link automatically')), stopSeg.el));++ const feed = h('ul.feed');+ const undo = h('button.ghost', { onclick: () => send('agent.undo') }, icon('undo', 13), 'Undo home edit');+ const activityCard = h('section.card', h('div.card-head', h('span.card-title', icon('activity', 15), 'Activity'), undo), feed);++ const footer = h('footer.privacy',+ h('div.privacy-title', icon('shield', 15), 'Private by design'),+ h('ul',+ h('li', 'Runs on this Mac. No House Control server, no account, nothing stored anywhere else.'),+ h('li', 'The link holds a 128-bit secret. Without it every address answers “not found”.'),+ h('li', 'Stop ends it at once — the address itself stops existing. Each start makes a new one.'),+ h('li', 'Device IDs and sign-ins never leave the Mac. Cloudflare only relays the encrypted connection.')));++ const page = h('div.agent', hero, linkCard, connectCard, permsCard, activityCard, footer);+ root.replaceChildren(page);++ /* ---------- pieces ---------- */++ function row(iconName, title, text, control) {+ return h('div.row', h('div.row-icon', icon(iconName, 16)), h('div.row-text', h('div.row-title', title), h('div.row-sub', text)), control);+ }++ function toggle(onChange) {+ const el = h('button.ai-switch', { role: 'switch', onclick: () => { const v = el.getAttribute('aria-checked') !== 'true'; set(v); onChange(v); } }, h('i'));+ const set = (v) => el.setAttribute('aria-checked', String(v));+ return { el, set };+ }++ function segmented(options, onChange) {+ const buttons = new Map();+ const el = h('div.seg', options.map(([value, iconName, label]) => {+ const b = h('button', { onclick: () => { if (!el.classList.contains('locked')) { set(value); onChange(value); } } }, iconName ? icon(iconName, 13) : null, label);+ buttons.set(value, b);+ return b;+ }));+ const set = (value) => { for (const [v, b] of buttons) b.classList.toggle('on', v === value); };+ return { el, set };+ }++ function copyButton(text) {+ const b = h('button.copy', { title: 'Copy', onclick: () => { copy(text()); flash(b, 'Copied'); } }, icon('copy', 14), h('span', 'Copy'));+ return b;+ }++ function flash(button, label) {+ const span = button.querySelector('span');+ if (!span) return;+ const before = span.textContent;+ span.textContent = label;+ button.classList.add('done');+ setTimeout(() => { span.textContent = before; button.classList.remove('done'); }, 1400);+ }++ function copy(text) {+ if (!text) return;+ if (isNative) post('agent.copy', { text });+ else navigator.clipboard?.writeText(text).catch(() => {});+ }++ function chatPrompt() {+ return `You can control my home with House Control. Open this private link and follow its instructions: ${status.link}\n\n`;+ }++ function codeBlock(text, label = 'Copy') {+ const b = h('button.copy.small', { onclick: () => { copy(text); flash(b, 'Copied'); } }, icon('copy', 13), h('span', label));+ return h('div.code', h('code', text), b);+ }++ function steps(...items) {+ const start = typeof items[0] === 'number' ? items.shift() : 1;+ return h('ol.steps', { vars: { '--start': start - 1 } }, items.map((i) => h('li', i)));+ }++ function renderTab() {+ for (const b of tabBar.children) b.classList.toggle('on', b.dataset.id === tab);+ const live = status.state === 'live';+ const mcp = live ? status.mcp : 'Start AI Access to get the address';+ const link = live ? status.link : 'Start AI Access to get the link';+ let body;+ if (tab === 'chat') {+ body = [+ h('p', 'Works with assistants that can open web pages: ChatGPT, Claude, Gemini, Perplexity, Grok.'),+ steps(h('span', h('b', 'Copy for a chat'), ' above and paste it into a new conversation.'),+ h('span', 'Add what you want: ', h('em', '“dim the living room to 30% and cool the bedroom to 22°”'), '.'),+ h('span', 'The assistant reads the guide behind the link and opens the matching action links. Watch them land below.')),+ h('p.muted', 'For photos of your rooms and edits to the 3D model, connect it as a connector (Claude, ChatGPT) instead — that needs more than opening links.'),+ ];+ } else if (tab === 'claude') {+ body = [+ steps(h('span', 'In Claude open ', h('b', 'Settings → Connectors → Add custom connector'), '.'),+ h('span', 'Name it ', h('b', 'House Control'), ' and paste this address:')),+ codeBlock(mcp),+ steps(3, h('span', 'In a chat, turn it on from the tools menu and ask away — or attach photos: ', h('em', '“here is my living room, rebuild it in 3D”'), '.')),+ ];+ } else if (tab === 'chatgpt') {+ body = [+ steps(h('span', 'In ChatGPT open ', h('b', 'Settings → Apps & Connectors → Advanced'), ' and turn on ', h('b', 'Developer mode'), '.'),+ h('span', h('b', 'Create'), ' a connector named ', h('b', 'House Control'), ' with this MCP address and no authentication:')),+ codeBlock(mcp),+ steps(3, h('span', 'In a chat choose Developer mode, add House Control, and talk to your home.')),+ h('p.muted', 'No developer mode? “Copy for a chat” works in any ChatGPT conversation that can browse.'),+ ];+ } else {+ body = [+ h('p', h('b', 'Claude Code')),+ codeBlock(live ? `claude mcp add --transport http house-control ${status.mcp}` : mcp),+ h('p', h('b', 'Cursor, Windsurf, VS Code and other MCP clients')),+ codeBlock(live ? JSON.stringify({ mcpServers: { 'house-control': { url: status.mcp } } }) : mcp),+ h('p', h('b', 'Any agent or script'), ' — plain HTTP with JSON. Tools: ', h('code.inline', 'GET …/api/tools'), ', run one: ', h('code.inline', 'POST …/api/<tool>'), ', OpenAPI: ', h('code.inline', '…/openapi.json'), '.'),+ codeBlock(link),+ ];+ }+ tabBody.replaceChildren(...body);+ }++ for (const t of TABS) tabBar.append(h('button', { 'data-id': t.id, onclick: () => { tab = t.id; renderTab(); } }, t.label));++ function ago(ms) {+ const s = Math.max(0, (Date.now() - ms) / 1000);+ if (s < 45) return 'now';+ if (s < 3600) return `${Math.round(s / 60)} min`;+ return new Date(ms).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });+ }++ function left(ms) {+ const m = Math.max(0, Math.round((ms - Date.now()) / 60000));+ return m >= 60 ? `${Math.floor(m / 60)} h ${m % 60} min left` : `${m} min left`;+ }++ let shown = new Set();+ let shownLocal = null;+ function renderFeed() {+ const entries = (status.activity || []).slice().reverse();+ // Reads ("Looked at the home") are folded into the action that follows them.+ const visible = entries.filter((e, i) => !e.quiet || i === 0 || !entries[i - 1] || entries[i - 1].client !== e.client).slice(0, 40);+ if (!visible.length) {+ feed.replaceChildren(h('li.empty', icon('sparkles', 16), h('span', status.state === 'live'+ ? 'Waiting for your assistant. What it reads and does shows up here, live.'+ : 'Nothing yet. Start AI Access, give the link to an assistant, and watch it work here.')));+ return;+ }+ feed.replaceChildren(...visible.map((e) => {+ const key = `${e.time}|${e.title}`;+ const item = h(`li${e.ok ? '' : '.bad'}${e.quiet ? '.quiet' : ''}${shown.has(key) ? '' : '.fresh'}`,+ h('span.who', { vars: { '--c': clientColor(e.client) } }, e.client === 'House Control' ? icon('home', 11, 2.2) : icon('sparkles', 11, 2.2), e.client),+ h('span.what', e.title),+ h('time', ago(e.time)));+ shown.add(key);+ return item;+ }));+ }++ /* ---------- state ---------- */++ function render() {+ const s = status.state;+ page.dataset.state = s;+ const label = {+ off: 'Off', starting: status.reach === 'local' ? 'Starting…' : 'Opening a private tunnel…',+ live: status.stopsAt ? `Live · ${left(status.stopsAt)}` : 'Live',+ error: 'Stopped', setup: 'One-time setup',+ }[s] || s;+ pill.replaceChildren(h('i.dot'), h('span', label), ...(s === 'live' ? [h('span.pill-reach', status.reach === 'local' ? 'This Mac' : 'Internet')] : []));+ primary.replaceChildren(...(s === 'live' ? [icon('stop', 15, 2.4), 'Stop AI Access'] : s === 'starting' ? [h('i.spinner'), 'Cancel'] : [icon('sparkles', 17, 2), 'Start AI Access']));+ primary.classList.toggle('stop', s === 'live' || s === 'starting');+ reachSeg.set(status.reach);+ reachSeg.el.classList.toggle('locked', s === 'live' || s === 'starting');++ if (s === 'setup') {+ const t = status.tunnel || {};+ callout.className = 'callout info';+ callout.replaceChildren(...[+ h('div.callout-title', icon('download', 15), 'Get Cloudflare’s tunnel once'),+ h('p', 'Over the internet, your Mac is reached through Cloudflare’s free quick tunnel (', h('code.inline', 'cloudflared'), ', about 20 MB, from Cloudflare’s GitHub). No Cloudflare account is needed.'),+ t.error ? h('p.err', t.error) : null,+ h('div.callout-actions',+ h('button.primary.small', { disabled: t.downloading || null, onclick: () => send('agent.install') }, t.downloading ? [h('i.spinner'), 'Downloading…'] : [icon('download', 14), 'Download']),+ h('button.ghost', { onclick: () => send('agent.start', { reach: 'local' }) }, 'Use this Mac only')),+ h('p.muted', 'Or in Terminal: ', h('code.inline', 'brew install cloudflared'))].filter(Boolean));+ } else if (s === 'error') {+ callout.className = 'callout bad';+ callout.replaceChildren(h('div.callout-title', icon('close', 15), 'AI Access stopped'), h('p', status.error || 'Something went wrong.'));+ } else {+ callout.className = 'callout hidden';+ callout.replaceChildren();+ }++ linkCard.classList.toggle('hidden', s !== 'live');+ const local = status.reach === 'local';+ if (local !== shownLocal) {+ // Assistants in the cloud cannot reach 127.0.0.1: on this Mac only, apps on the Mac are the audience.+ shownLocal = local;+ if (local && tab === 'chat') tab = 'code';+ if (!local && tab === 'code' && s !== 'live') tab = 'chat';+ }+ chatActions.firstChild.hidden = local;+ linkHint.replaceChildren(...(local+ ? ['Only apps on this Mac can open it: Claude Code, Cursor, VS Code, LM Studio, your own scripts. See ', h('b', 'Code & agents'), ' below.']+ : ['Paste it into any assistant with your request — ', h('em', '“turn off every light except the bedroom”'), '.']));+ if (s === 'live') {+ try {+ const u = new URL(status.link);+ const [token] = u.pathname.slice(1).split('/');+ urlText.replaceChildren(h('span.url-host', u.host), h('span.url-token', `/${token.slice(0, 5)}…`));+ } catch { urlText.textContent = status.link; }+ }+ controlToggle.set(status.control !== false);+ editToggle.set(status.edit !== false);+ stopSeg.set(status.autoStop || '8h');+ undo.disabled = !status.canUndo;+ renderTab();+ renderFeed();+ }++ incoming.agentStatus = (next) => { status = next; render(); };+ setInterval(() => { if (status.state === 'live') { render(); } }, 30000);+ render();+ post('ready', {});+ window.__agent = { get status() { return status; }, set status(s) { status = s; render(); }, render };+}++// In a browser there is no native side: play its part, so the page can be designed and filmed.+function fakeNative(update) {+ let s = { state: 'off', reach: 'internet', autoStop: '8h', control: true, edit: true, activity: [], canUndo: false, tunnel: { installed: true } };+ const set = (patch) => { s = { ...s, ...patch }; update(s); };+ const log = (client, title, quiet = false) => set({ activity: [...s.activity, { time: Date.now(), client, title, ok: true, quiet }] });+ return (type, payload = {}) => {+ if (type === 'agent.start') {+ set({ state: 'starting', reach: payload.reach || s.reach });+ setTimeout(() => {+ const base = s.reach === 'local' ? 'http://127.0.0.1:7419' : 'https://quiet-harbor-lamp-meadow.trycloudflare.com';+ const link = `${base}/k3VbQ9mX2pLr8tNw4yHc0A`;+ set({ state: 'live', link, mcp: `${link}/mcp`, startedAt: Date.now(), stopsAt: s.autoStop === 'never' ? null : Date.now() + (s.autoStop === '1h' ? 1 : 8) * 3600e3 });+ log('House Control', 'Link is live');+ }, 1600);+ } else if (type === 'agent.stop') {+ if (s.state === 'live') log('House Control', 'Stopped — the link no longer works');+ set({ state: 'off', link: null, mcp: null });+ } else if (type === 'agent.settings') {+ set(Object.fromEntries(Object.entries(payload).filter(([, v]) => v != null)));+ } else if (type === 'agent.undo') {+ log('House Control', 'Undid the last floor plan change');+ set({ canUndo: false });+ } else if (type === 'agent.open') {+ window.open(payload.url, '_blank');+ }+ };+}diff --git a/web/src/agent/plan-edit.js b/web/src/agent/plan-edit.jsnew file mode 100644index 0000000..7eb3dd8--- /dev/null+++ b/web/src/agent/plan-edit.js@@ -0,0 +1,341 @@+// Edits to the floor plan an AI asks for: small, checked operations on the plan as it is+// written on disk. Nothing here touches the page, so it runs (and is tested) under Node too.+import { normalize, LIGHT_KINDS, FLOOR_KINDS } from '../config.js';+import { FURNITURE_TYPES, footprint } from '../three/furniture.js';++export const SCENE_ICONS = ['sun', 'sofa', 'film', 'moon', 'door', 'bed', 'tv', 'sparkles'];+export const WALLS = ['north', 'south', 'east', 'west'];+const FURNITURE_KEYS = ['type', 'pos', 'rot', 'width', 'height', 'size', 'color', 'chairs', 'stools', 'upper'];+const LIGHT_KEYS = ['id', 'name', 'room', 'type', 'pos', 'y', 'rot', 'length', 'capabilities', 'color'];+const AC_KEYS = ['id', 'name', 'room', 'wall', 'pos', 'y', 'min', 'max'];++export class PlanEditError extends Error {}++const fail = (msg) => { throw new PlanEditError(msg); };+const isNum = (v) => typeof v === 'number' && Number.isFinite(v);+const isPoint = (p) => Array.isArray(p) && p.length === 2 && p.every(isNum);+const round = (v) => Math.round(v * 100) / 100;+const pick = (obj, keys) => Object.fromEntries(Object.entries(obj || {}).filter(([k]) => keys.includes(k)));++/** The plan as an AI sees it: links to real hardware are replaced by `"linked": true`. */+export function redactPlan(raw) {+ const plan = structuredClone(raw);+ for (const list of [plan.lights || [], plan.acs || []]) {+ for (const d of list) {+ if (d.tuya) { delete d.tuya; d.linked = true; }+ }+ }+ return plan;+}++/** Puts the hardware links of `old` back into a plan an AI wrote from a redacted copy. */+export function restoreLinks(plan, old) {+ for (const key of ['lights', 'acs']) {+ const links = new Map((old[key] || []).filter((d) => d.tuya).map((d) => [d.id, d.tuya]));+ for (const d of plan[key] || []) {+ delete d.linked;+ delete d.tuya; // an AI cannot invent links to devices; they are made in the editor+ if (links.has(d.id)) d.tuya = links.get(d.id);+ }+ }+ return plan;+}++function cleanFurniture(item, where) {+ if (!item || typeof item !== 'object') fail(`${where}: a furniture item must be an object`);+ if (!FURNITURE_TYPES.includes(item.type)) fail(`${where}: unknown furniture type "${item.type}". Use one of: ${FURNITURE_TYPES.join(', ')}`);+ if (!isPoint(item.pos)) fail(`${where}: "pos" must be [x, z] in metres (the centre of the piece)`);+ const out = pick(item, FURNITURE_KEYS);+ out.pos = out.pos.map(round);+ if (out.rot != null) { if (!isNum(out.rot)) fail(`${where}: "rot" must be a number of degrees`); out.rot = Math.round(out.rot); }+ for (const k of ['width', 'height']) {+ if (out[k] != null && !(isNum(out[k]) && out[k] > 0.1 && out[k] < 12)) fail(`${where}: "${k}" must be metres between 0.1 and 12`);+ }+ if (out.size != null && !(isPoint(out.size) && out.size.every((v) => v > 0.1 && v < 15))) fail(`${where}: "size" must be [width, depth] in metres`);+ if (out.color != null && !/^#[0-9a-f]{6}$/i.test(out.color)) fail(`${where}: "color" must look like "#8b93a7"`);+ for (const k of ['chairs', 'stools']) {+ if (out[k] != null && !(Number.isInteger(out[k]) && out[k] >= 0 && out[k] <= 12)) fail(`${where}: "${k}" must be a whole number 0–12`);+ }+ if (out.upper != null) out.upper = Boolean(out.upper);+ if (out.rot === 0) delete out.rot;+ return out;+}++function roomAt(plan, [x, z]) {+ return (plan.rooms || []).find((r) => x >= r.rect[0] - 0.01 && x <= r.rect[0] + r.rect[2] + 0.01+ && z >= r.rect[1] - 0.01 && z <= r.rect[1] + r.rect[3] + 0.01);+}++function findById(list, id, what) {+ const i = list.findIndex((d) => d.id === id);+ if (i < 0) fail(`There is no ${what} with id "${id}". Ids: ${list.map((d) => d.id).join(', ') || 'none'}`);+ return i;+}++function checkRect(rect, where) {+ if (!(Array.isArray(rect) && rect.length === 4 && rect.every(isNum) && rect[2] > 0.3 && rect[3] > 0.3)) {+ fail(`${where}: "rect" must be [x, z, width, depth] in metres, at least 0.3 m each way`);+ }+ return rect.map(round);+}++/**+ * Applies `operations` to `raw` and returns { plan, changes, warnings }. Nothing is+ * changed when one operation is wrong: the error says which one and why.+ *+ * Furniture and openings are addressed by their index in the plan as it was before this+ * edit; removals happen last, so the indexes of one edit never shift under it.+ */+export function applyOperations(raw, operations) {+ if (!Array.isArray(operations) || !operations.length) fail('"operations" must be a non-empty list');+ const plan = structuredClone(raw);+ for (const key of ['rooms', 'openings', 'furniture', 'lights', 'acs', 'scenes']) plan[key] = plan[key] || [];+ const originalFurniture = plan.furniture.length;+ const originalOpenings = plan.openings.length;+ const dropFurniture = new Set();+ const dropOpenings = new Set();+ const addFurniture = [];+ const changes = [];++ const furnitureIndex = (op, where) => {+ if (!Number.isInteger(op.index) || op.index < 0 || op.index >= originalFurniture) {+ fail(`${where}: "index" must be 0–${originalFurniture - 1} (the furniture list from get_floor_plan)`);+ }+ if (dropFurniture.has(op.index)) fail(`${where}: furniture #${op.index} is already removed in this edit`);+ return op.index;+ };++ operations.forEach((op, n) => {+ const where = `Operation ${n + 1} (${op?.op})`;+ if (!op || typeof op !== 'object') fail(`Operation ${n + 1} must be an object`);+ switch (op.op) {+ case 'set_home': {+ if (op.name != null) plan.name = String(op.name).slice(0, 60);+ if (op.outdoorTemp != null) { if (!isNum(op.outdoorTemp)) fail(`${where}: outdoorTemp must be a number`); plan.outdoorTemp = op.outdoorTemp; }+ if (op.wallHeight != null) { if (!(isNum(op.wallHeight) && op.wallHeight > 1.8 && op.wallHeight < 6)) fail(`${where}: wallHeight must be 1.8–6 m`); plan.wallHeight = op.wallHeight; }+ if (op.camera != null) plan.camera = { ...plan.camera, ...pick(op.camera, ['azimuth', 'elevation']) };+ changes.push('home settings');+ break;+ }+ case 'add_room': {+ if (typeof op.id !== 'string' || !/^[a-z0-9_.-]+$/i.test(op.id)) fail(`${where}: "id" must be a short word like "office"`);+ if (plan.rooms.some((r) => r.id === op.id)) fail(`${where}: a room "${op.id}" already exists`);+ if (op.floor != null && !FLOOR_KINDS.includes(op.floor)) fail(`${where}: "floor" must be one of ${FLOOR_KINDS.join(', ')}`);+ plan.rooms.push({ id: op.id, name: String(op.name || op.id), rect: checkRect(op.rect, where), floor: op.floor || 'oak' });+ changes.push(`added room ${op.name || op.id}`);+ break;+ }+ case 'update_room': {+ const room = plan.rooms[findById(plan.rooms, op.id, 'room')];+ if (op.name != null) room.name = String(op.name);+ if (op.rect != null) {+ // Furniture inside the room moves with it, so resizing from the far edge keeps it in place.+ const rect = checkRect(op.rect, where);+ const [dx, dz] = [rect[0] - room.rect[0], rect[1] - room.rect[1]];+ if (op.moveContents !== false && (dx || dz)) {+ const inside = (p) => roomAt({ rooms: [room] }, p);+ for (const f of plan.furniture) if (inside(f.pos)) f.pos = [round(f.pos[0] + dx), round(f.pos[1] + dz)];+ for (const d of [...plan.lights, ...plan.acs]) if (d.room === room.id) d.pos = [round(d.pos[0] + dx), round(d.pos[1] + dz)];+ }+ room.rect = rect;+ }+ if (op.floor != null) {+ if (!FLOOR_KINDS.includes(op.floor)) fail(`${where}: "floor" must be one of ${FLOOR_KINDS.join(', ')}`);+ room.floor = op.floor;+ }+ changes.push(`updated room ${room.name}`);+ break;+ }+ case 'remove_room': {+ const i = findById(plan.rooms, op.id, 'room');+ const devices = [...plan.lights, ...plan.acs].filter((d) => d.room === op.id);+ if (devices.some((d) => d.tuya)) fail(`${where}: this room has devices linked to real hardware; unlink them in the editor first`);+ const room = plan.rooms[i];+ plan.furniture.forEach((f, k) => { if (k < originalFurniture && roomAt({ rooms: [room] }, f.pos)) dropFurniture.add(k); });+ plan.lights = plan.lights.filter((d) => d.room !== op.id);+ plan.acs = plan.acs.filter((d) => d.room !== op.id);+ plan.rooms.splice(i, 1);+ changes.push(`removed room ${room.name}`);+ break;+ }+ case 'furnish_room': {+ // Replaces everything standing in a room: the natural edit for "here is a photo of my living room".+ const room = plan.rooms[findById(plan.rooms, op.room, 'room')];+ if (!Array.isArray(op.items)) fail(`${where}: "items" must be a list of furniture`);+ plan.furniture.forEach((f, k) => {+ if (k < originalFurniture && Array.isArray(f.pos) && roomAt({ rooms: [room] }, f.pos)?.id === room.id) dropFurniture.add(k);+ });+ op.items.forEach((item, k) => addFurniture.push(cleanFurniture(item, `${where}, item ${k + 1}`)));+ changes.push(`refurnished ${room.name} (${op.items.length} pieces)`);+ break;+ }+ case 'add_furniture': {+ const items = op.items || [op.item];+ items.forEach((item, k) => addFurniture.push(cleanFurniture(item, `${where}, item ${k + 1}`)));+ changes.push(`added ${items.map((i) => i.type).join(', ')}`);+ break;+ }+ case 'update_furniture': {+ const i = furnitureIndex(op, where);+ plan.furniture[i] = cleanFurniture({ ...plan.furniture[i], ...(op.set || {}) }, where);+ changes.push(`changed ${plan.furniture[i].type} #${i}`);+ break;+ }+ case 'remove_furniture': {+ const i = furnitureIndex(op, where);+ dropFurniture.add(i);+ changes.push(`removed ${plan.furniture[i].type} #${i}`);+ break;+ }+ case 'add_opening': {+ const type = op.type || 'door';+ if (!['door', 'window', 'open'].includes(type)) fail(`${where}: "type" must be door, window or open`);+ if (!isPoint(op.from) || !isPoint(op.to)) fail(`${where}: "from" and "to" must be [x, z] points on a wall`);+ if (op.from[0] !== op.to[0] && op.from[1] !== op.to[1]) fail(`${where}: an opening must be horizontal or vertical`);+ const o = { type, from: op.from.map(round), to: op.to.map(round) };+ if (type === 'window') { if (isNum(op.sill)) o.sill = op.sill; if (isNum(op.head)) o.head = op.head; }+ plan.openings.push(o);+ changes.push(`added a ${type}`);+ break;+ }+ case 'remove_opening': {+ if (!Number.isInteger(op.index) || op.index < 0 || op.index >= originalOpenings) fail(`${where}: "index" must be 0–${originalOpenings - 1}`);+ dropOpenings.add(op.index);+ changes.push(`removed ${plan.openings[op.index].type} #${op.index}`);+ break;+ }+ case 'add_light':+ case 'add_ac': {+ const isLight = op.op === 'add_light';+ const list = isLight ? plan.lights : plan.acs;+ const device = pick(op, isLight ? LIGHT_KEYS : AC_KEYS);+ if (typeof device.id !== 'string' || !device.id) fail(`${where}: "id" is required, e.g. "living.reading"`);+ if ([...plan.lights, ...plan.acs].some((d) => d.id === device.id)) fail(`${where}: id "${device.id}" is taken`);+ if (isLight && !LIGHT_KINDS.includes(device.type)) fail(`${where}: "type" must be one of ${LIGHT_KINDS.join(', ')}`);+ if (!isLight && !WALLS.includes(device.wall)) fail(`${where}: "wall" must be one of ${WALLS.join(', ')}`);+ list.push(device);+ changes.push(`added ${isLight ? 'light' : 'AC'} ${device.name || device.id}`);+ break;+ }+ case 'update_light':+ case 'update_ac': {+ const isLight = op.op === 'update_light';+ const list = isLight ? plan.lights : plan.acs;+ const i = findById(list, op.id, isLight ? 'light' : 'AC');+ const set = pick(op.set, (isLight ? LIGHT_KEYS : AC_KEYS).filter((k) => k !== 'id'));+ if (op.set?.tuya || op.set?.linked != null) fail(`${where}: links to real devices are made in the editor, not here`);+ Object.assign(list[i], set);+ changes.push(`changed ${list[i].name || list[i].id}`);+ break;+ }+ case 'remove_light':+ case 'remove_ac': {+ const isLight = op.op === 'remove_light';+ const list = isLight ? plan.lights : plan.acs;+ const i = findById(list, op.id, isLight ? 'light' : 'AC');+ if (list[i].tuya) fail(`${where}: "${list[i].name}" is a real device; unlink it in the editor before removing it`);+ const [gone] = list.splice(i, 1);+ for (const s of plan.scenes) delete s[isLight ? 'lights' : 'acs']?.[gone.id];+ changes.push(`removed ${gone.name || gone.id}`);+ break;+ }+ case 'add_scene':+ case 'update_scene': {+ const adding = op.op === 'add_scene';+ const source = adding ? op : { ...plan.scenes[findById(plan.scenes, op.id, 'scene')], ...(op.set || {}) };+ if (adding && plan.scenes.some((s) => s.id === op.id)) fail(`${where}: a scene "${op.id}" already exists`);+ if (typeof source.id !== 'string' || !source.id) fail(`${where}: "id" is required`);+ if (source.icon != null && !SCENE_ICONS.includes(source.icon)) fail(`${where}: "icon" must be one of ${SCENE_ICONS.join(', ')}`);+ const scene = { id: source.id, name: String(source.name || source.id), icon: source.icon || 'sparkles',+ lights: source.lights || {}, acs: source.acs || {} };+ for (const [id, s] of Object.entries(scene.lights)) {+ if (id !== '*' && !plan.lights.some((l) => l.id === id)) fail(`${where}: unknown light "${id}"`);+ if (s.brightness != null && !(s.brightness > 0 && s.brightness <= 1)) fail(`${where}: scene brightness is 0–1 (0.6 = 60%)`);+ }+ for (const id of Object.keys(scene.acs)) if (id !== '*' && !plan.acs.some((a) => a.id === id)) fail(`${where}: unknown AC "${id}"`);+ if (adding) plan.scenes.push(scene);+ else plan.scenes[plan.scenes.findIndex((s) => s.id === op.id)] = scene;+ changes.push(`${adding ? 'added' : 'changed'} scene ${scene.name}`);+ break;+ }+ case 'remove_scene': {+ const i = findById(plan.scenes, op.id, 'scene');+ changes.push(`removed scene ${plan.scenes[i].name}`);+ plan.scenes.splice(i, 1);+ break;+ }+ default:+ fail(`${where}: unknown operation. Use one of: set_home, add_room, update_room, remove_room, furnish_room, `+ + 'add_furniture, update_furniture, remove_furniture, add_opening, remove_opening, add_light, update_light, '+ + 'remove_light, add_ac, update_ac, remove_ac, add_scene, update_scene, remove_scene');+ }+ });++ plan.furniture = plan.furniture.filter((_, k) => !dropFurniture.has(k)).concat(addFurniture);+ plan.openings = plan.openings.filter((_, k) => !dropOpenings.has(k));+ return { plan, changes, warnings: check(plan) };+}++/** Throws when the plan cannot be drawn; returns gentle warnings otherwise. */+export function check(plan) {+ try {+ normalize(structuredClone(plan));+ } catch (error) {+ fail(error.message);+ }+ const warnings = [];+ plan.furniture.forEach((f, i) => {+ if (!FURNITURE_TYPES.includes(f.type)) fail(`Furniture #${i} has unknown type "${f.type}"`);+ if (!roomAt(plan, f.pos)) warnings.push(`furniture #${i} (${f.type}) stands outside every room`);+ });+ for (const d of [...plan.lights, ...plan.acs]) {+ const room = plan.rooms.find((r) => r.id === d.room);+ if (room && roomAt({ rooms: [room] }, d.pos)?.id !== room.id) warnings.push(`${d.name || d.id} is outside its room "${room.name}"`);+ }+ return warnings;+}++/** A plan an AI wrote whole (replace_floor_plan), checked and with the hardware links kept. */+export function replacePlan(old, next) {+ if (!next || typeof next !== 'object' || !Array.isArray(next.rooms)) fail('"plan" must be a floor plan object with a "rooms" list');+ const plan = restoreLinks(structuredClone(next), old);+ plan.furniture = (plan.furniture || []).map((f, i) => cleanFurniture(f, `Furniture #${i}`));+ if (old.version != null && plan.version == null) plan.version = old.version;+ const lost = [...(old.lights || []), ...(old.acs || [])].filter((d) => d.tuya+ && ![...(plan.lights || []), ...(plan.acs || [])].some((n) => n.id === d.id));+ if (lost.length) {+ fail(`The new plan drops devices linked to real hardware: ${lost.map((d) => `${d.name} (${d.id})`).join(', ')}. Keep them, with the same ids.`);+ }+ return { plan, warnings: check(plan) };+}++/** What each furniture type is, for the AI that places it. */+export const FURNITURE_GUIDE = {+ sofa: 'sofa; options width, color',+ armchair: 'armchair; option color',+ coffeeTable: 'low coffee table; option width',+ rug: 'flat rug; options size [w, d], color',+ tv: 'TV on a low media console; option width',+ sideboard: 'sideboard / low cabinet; option width',+ diningSet: 'dining table with chairs around it; options width, chairs',+ island: 'kitchen island with stools on its front side; options width, stools',+ kitchen: 'run of kitchen base cabinets with counter, sink and hob; options width, upper (wall cabinets, default true)',+ fridge: 'tall fridge',+ bed: 'bed with headboard; options width (mattress), color (bedding)',+ nightstand: 'nightstand',+ dresser: 'chest of drawers; option width',+ plant: 'potted plant; option height',+ vanity: 'bathroom vanity with basin and mirror; option width',+ bathtub: 'bathtub',+ toilet: 'toilet',+ desk: 'desk; option width',+ wardrobe: 'wardrobe; options width, height',+ bookshelf: 'open bookshelf with books; options width, height',+};++export function furnitureCatalog() {+ return FURNITURE_TYPES.map((type) => {+ const [w, d] = footprint({ type });+ return { type, footprint: [round(w), round(d)], about: FURNITURE_GUIDE[type] || type };+ });+}diff --git a/web/src/agent/tools.js b/web/src/agent/tools.jsnew file mode 100644index 0000000..55337fc--- /dev/null+++ b/web/src/agent/tools.js@@ -0,0 +1,677 @@+// What an AI can do with the home: the tools (shared by MCP and the HTTP API), the guide+// an AI reads from the link, and the plain action links for chat assistants that can only+// open pages. Runs in the panel page, where the state of every device lives; the native+// shell only carries requests here (see AgentGateway.swift).+import { AC_MODES, AC_FANS } from '../store.js';+import { applyOperations, replacePlan, redactPlan, furnitureCatalog, PlanEditError, SCENE_ICONS, WALLS } from './plan-edit.js';+import { LIGHT_KINDS, FLOOR_KINDS } from '../config.js';++export const COLORS = {+ red: '#ff3b30', orange: '#ff9500', yellow: '#ffd60a', green: '#34c759',+ cyan: '#32d2f5', blue: '#0a84ff', purple: '#8b5cff', pink: '#ff5fc4',+};+const WHITES = { warm: 2700, neutral: 4000, cool: 6500 };++const clamp = (v, a, b) => Math.min(b, Math.max(a, v));+const pct = (v) => `${Math.round(v * 100)}%`;++class ToolError extends Error {}+const fail = (msg) => { throw new ToolError(msg); };++export function createAgent({ store, config, raw, render, onAction }) {+ const { state } = store;+ const roomName = new Map(config.rooms.map((r) => [r.id, r.name]));++ /* ---------- describing the home ---------- */++ function lightAbilities(cfg) {+ const c = cfg.capabilities;+ if (!c.length) return 'on/off only';+ return [c.includes('brightness') && 'dims', c.includes('temp') && 'white temperature', c.includes('color') && 'colour']+ .filter(Boolean).join(', ');+ }++ function lightState(cfg, s = state.lights[cfg.id]) {+ if (!s.on) return 'off';+ const parts = ['on'];+ if (cfg.capabilities.includes('brightness')) parts.push(pct(s.brightness));+ if (s.color && cfg.capabilities.includes('color')) parts.push(`colour ${s.color}`);+ else if (cfg.capabilities.includes('temp')) parts.push(`${s.temp} K`);+ return parts.join(', ');+ }++ function acState(cfg, s = state.acs[cfg.id]) {+ const room = `room ${s.roomTemp.toFixed(1)}°C`;+ if (!s.on) return `off (${room})`;+ return `on, ${s.mode}, target ${s.target}°C, fan ${s.fan} (${room})`;+ }++ const lightJSON = (cfg) => ({+ id: cfg.id, name: cfg.name, room: cfg.room, type: cfg.type, abilities: cfg.capabilities,+ real: Boolean(cfg.tuya?.deviceId), ...state.lights[cfg.id],+ brightness: Math.round(state.lights[cfg.id].brightness * 100),+ });+ const acJSON = (cfg) => ({+ id: cfg.id, name: cfg.name, room: cfg.room, real: Boolean(cfg.tuya?.deviceId),+ min: cfg.min, max: cfg.max, modes: store.acFeatures(cfg.id).modes, fans: store.acFeatures(cfg.id).fans,+ on: state.acs[cfg.id].on, target: state.acs[cfg.id].target, mode: state.acs[cfg.id].mode,+ fan: state.acs[cfg.id].fan, roomTemp: state.acs[cfg.id].roomTemp,+ });++ function overview() {+ const lightsOn = config.lights.filter((l) => state.lights[l.id].on).length;+ const acsOn = config.acs.filter((a) => state.acs[a.id].on).length;+ const scene = config.scenes.find((s) => s.id === state.scene);+ const lines = [+ `Home "${config.name}": ${config.rooms.length} rooms, ${config.lights.length} lights (${lightsOn} on), `+ + `${config.acs.length} air conditioners (${acsOn} running).${scene ? ` Active scene: ${scene.name}.` : ''}`,+ ];+ for (const room of config.rooms) {+ const lights = config.lights.filter((l) => l.room === room.id);+ const acs = config.acs.filter((a) => a.room === room.id);+ if (!lights.length && !acs.length) { lines.push('', `${room.name} [${room.id}] — no devices`); continue; }+ lines.push('', `${room.name} [${room.id}]`);+ for (const l of lights) lines.push(` • ${l.name} [${l.id}] — light (${l.type}; ${lightAbilities(l)}): ${lightState(l)}`);+ for (const a of acs) lines.push(` • ${a.name} [${a.id}] — air conditioner (${a.min}–${a.max}°C): ${acState(a)}`);+ }+ if (config.scenes.length) {+ lines.push('', `Scenes: ${config.scenes.map((s) => `${s.name} [${s.id}]`).join(', ')}`);+ }+ return lines.join('\n');+ }++ function structured() {+ return {+ home: config.name,+ scene: state.scene,+ rooms: config.rooms.map((r) => ({+ id: r.id, name: r.name,+ lights: config.lights.filter((l) => l.room === r.id).map(lightJSON),+ acs: config.acs.filter((a) => a.room === r.id).map(acJSON),+ })),+ scenes: config.scenes.map((s) => ({ id: s.id, name: s.name })),+ };+ }++ /* ---------- finding devices ---------- */++ const norm = (s) => String(s).toLowerCase().replace(/[\s_-]+/g, ' ').trim();++ // "living.main", "living" (a room), "all", or a name: "Floor lamp", "Living floor lamp".+ function resolve(targets, list, what) {+ if (targets == null) fail(`Say which ${what} to change: ids, room ids, names, or "all".`);+ const wanted = Array.isArray(targets) ? targets : [targets];+ if (!wanted.length) fail(`The list of ${what} is empty.`);+ const out = new Set();+ for (const t of wanted) {+ const key = norm(t);+ if (key === 'all' || key === '*' || key === 'everything') { for (const d of list) out.add(d); continue; }+ const byId = list.find((d) => d.id === t);+ if (byId) { out.add(byId); continue; }+ const room = config.rooms.find((r) => r.id === t || norm(r.name) === key);+ if (room) {+ const inRoom = list.filter((d) => d.room === room.id);+ if (!inRoom.length) fail(`${room.name} has no ${what}.`);+ for (const d of inRoom) out.add(d);+ continue;+ }+ const byName = list.filter((d) => norm(d.name) === key || norm(`${roomName.get(d.room)} ${d.name}`) === key);+ if (byName.length === 1) { out.add(byName[0]); continue; }+ const loose = list.filter((d) => norm(`${roomName.get(d.room)} ${d.name} ${d.id}`).includes(key));+ if (byName.length > 1 || loose.length > 1) {+ fail(`"${t}" matches several ${what}: ${(byName.length > 1 ? byName : loose).map((d) => `${d.name} [${d.id}]`).join(', ')}. Use an id.`);+ }+ if (loose.length === 1) { out.add(loose[0]); continue; }+ fail(`No ${what.replace(/s$/, '')} matches "${t}". Known: ${list.map((d) => `${d.name} [${d.id}]`).join(', ')}.`);+ }+ return [...out];+ }++ function parseColor(value) {+ const key = norm(value);+ if (COLORS[key]) return COLORS[key];+ const hex = String(value).trim().replace(/^#?/, '#');+ if (/^#[0-9a-f]{6}$/i.test(hex)) return hex.toLowerCase();+ fail(`Colour "${value}" is not understood. Use #rrggbb or one of ${Object.keys(COLORS).join(', ')}.`);+ return null;+ }++ /* ---------- actions ---------- */++ function setLights(args) {+ const devices = resolve(args.lights ?? args.targets ?? args.target, config.lights, 'lights');+ const notes = [];+ const changed = [];+ for (const cfg of devices) {+ const caps = cfg.capabilities;+ const patch = {};+ if (args.on != null) patch.on = Boolean(args.on);+ if (args.brightness != null) {+ const b = Number(args.brightness);+ if (!Number.isFinite(b)) fail('"brightness" is a percentage, 1–100.');+ if (caps.includes('brightness')) { patch.brightness = clamp(b > 1 || b === 0 ? b / 100 : b, 0.05, 1); patch.on ??= true; }+ else notes.push(`${cfg.name} cannot dim.`);+ }+ if (args.white != null && args.color_temperature == null) args.color_temperature = WHITES[norm(args.white)] ?? fail('"white" is warm, neutral or cool.');+ if (args.color_temperature != null) {+ if (caps.includes('temp')) { patch.temp = clamp(Number(args.color_temperature), 2200, 6500); patch.color = null; patch.on ??= true; }+ else notes.push(`${cfg.name} has no adjustable white.`);+ }+ if (args.color != null) {+ if (caps.includes('color')) { patch.color = parseColor(args.color); patch.on ??= true; }+ else notes.push(`${cfg.name} cannot change colour.`);+ }+ if (args.toggle) patch.on = !state.lights[cfg.id].on;+ if (!Object.keys(patch).length) continue;+ store.setLight(cfg.id, patch);+ changed.push(cfg);+ }+ if (!changed.length && !notes.length) fail('Nothing to change: pass "on", "brightness", "color_temperature" or "color".');+ return { changed, notes };+ }++ function setACs(args) {+ const devices = resolve(args.acs ?? args.targets ?? args.target, config.acs, 'air conditioners');+ const notes = [];+ const changed = [];+ for (const cfg of devices) {+ const f = store.acFeatures(cfg.id);+ const patch = {};+ if (args.temperature != null) {+ const t = Math.round(Number(args.temperature));+ if (!Number.isFinite(t)) fail('"temperature" is in °C.');+ if (t < cfg.min || t > cfg.max) notes.push(`${cfg.name} goes from ${cfg.min} to ${cfg.max}°C; set to ${clamp(t, cfg.min, cfg.max)}.`);+ patch.target = clamp(t, cfg.min, cfg.max);+ }+ if (args.mode != null) {+ if (!f.modes.includes(args.mode)) fail(`${cfg.name} modes: ${f.modes.join(', ')}.`);+ patch.mode = args.mode;+ }+ if (args.fan != null) {+ if (!f.fans.includes(args.fan)) fail(`${cfg.name} fan speeds: ${f.fans.join(', ')}.`);+ patch.fan = args.fan;+ }+ // "Set the bedroom AC to 22" means it should be running.+ if (args.on != null) patch.on = Boolean(args.on);+ else if (Object.keys(patch).length) patch.on = true;+ if (!Object.keys(patch).length) continue;+ store.setAC(cfg.id, patch);+ changed.push(cfg);+ }+ if (!changed.length) fail('Nothing to change: pass "on", "temperature", "mode" or "fan".');+ return { changed, notes };+ }++ function activateScene(args) {+ const key = norm(args.scene ?? '');+ const scene = config.scenes.find((s) => s.id === args.scene || norm(s.name) === key);+ if (!scene) fail(`No scene "${args.scene}". Scenes: ${config.scenes.map((s) => `${s.name} [${s.id}]`).join(', ') || 'none'}.`);+ store.applyScene(scene.id);+ return scene;+ }++ function describeChange(changed, notes, kind) {+ const lines = changed.map((cfg) => (kind === 'light'+ ? `${roomName.get(cfg.room)} · ${cfg.name}: ${lightState(cfg)}`+ : `${roomName.get(cfg.room)} · ${cfg.name}: ${acState(cfg)}`));+ return [...lines, ...notes].join('\n');+ }++ function shortSummary(changed, kind) {+ const names = changed.map((c) => c.name);+ const list = names.length > 3 ? `${names.length} ${kind === 'light' ? 'lights' : 'ACs'}` : names.join(', ');+ if (kind === 'light') {+ const on = changed.filter((c) => state.lights[c.id].on).length;+ const verb = on === changed.length ? 'On' : on === 0 ? 'Off' : 'Set';+ const first = state.lights[changed[0].id];+ const extra = changed.length === 1 && first.on && changed[0].capabilities.includes('brightness') ? ` · ${pct(first.brightness)}` : '';+ return `${verb}: ${list}${extra}`;+ }+ const a = state.acs[changed[0].id];+ return a.on ? `${list} → ${a.target}° ${a.mode}` : `Off: ${list}`;+ }++ /* ---------- the tools ---------- */++ const TARGETS = {+ type: 'array', items: { type: 'string' },+ description: 'Which devices: ids like "living.main", room ids like "living" (every one in the room), names, or "all".',+ };+ const FURNITURE_ITEM = {+ type: 'object',+ required: ['type', 'pos'],+ properties: {+ type: { type: 'string', enum: furnitureCatalog().map((f) => f.type) },+ pos: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2, description: '[x, z] of the centre, metres' },+ rot: { type: 'number', description: 'Degrees. 0: the front faces south (+z), back to the north wall; 90: faces east; -90: faces west; 180: faces north' },+ width: { type: 'number' }, height: { type: 'number' },+ size: { type: 'array', items: { type: 'number' }, description: 'rug only: [width, depth]' },+ color: { type: 'string', description: '#rrggbb (sofa, armchair, rug, bed)' },+ chairs: { type: 'integer' }, stools: { type: 'integer' }, upper: { type: 'boolean' },+ },+ };++ const TOOLS = [+ {+ name: 'get_home', group: 'read',+ title: 'Look at the home',+ description: 'Every room with its lights and air conditioners, what each can do and what it is doing now, and the scenes. Call this first.',+ inputSchema: { type: 'object', properties: {} },+ annotations: { readOnlyHint: true, openWorldHint: false },+ run: () => ({ text: overview(), data: structured(), summary: 'Looked at the home', quiet: true }),+ },+ {+ name: 'set_lights', group: 'control',+ title: 'Switch or adjust lights',+ description: 'Turn lights on or off, dim them, or change their white temperature or colour. Several lights at once is fine. '+ + 'Brightness, temperature or colour also switch a light on. Lights that cannot do something are reported, not failed.',+ inputSchema: {+ type: 'object', required: ['lights'],+ properties: {+ lights: TARGETS,+ on: { type: 'boolean' },+ toggle: { type: 'boolean', description: 'Flip each light' },+ brightness: { type: 'number', minimum: 1, maximum: 100, description: 'Percent' },+ color_temperature: { type: 'number', minimum: 2200, maximum: 6500, description: 'Kelvin: 2700 warm, 4000 neutral, 6500 cool' },+ white: { type: 'string', enum: Object.keys(WHITES) },+ color: { type: 'string', description: `#rrggbb or ${Object.keys(COLORS).join(', ')}` },+ },+ },+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },+ run(args) {+ const { changed, notes } = setLights(args);+ return { text: describeChange(changed, notes, 'light') || notes.join('\n'), summary: changed.length ? shortSummary(changed, 'light') : notes[0] };+ },+ },+ {+ name: 'set_air_conditioners', group: 'control',+ title: 'Control air conditioners',+ description: 'Switch air conditioners on or off and set the target temperature, mode and fan speed. '+ + 'Setting a temperature, mode or fan also switches the unit on unless "on": false is given.',+ inputSchema: {+ type: 'object', required: ['acs'],+ properties: {+ acs: { ...TARGETS, description: 'Which units: ids like "living.ac", room ids, names, or "all".' },+ on: { type: 'boolean' },+ temperature: { type: 'number', description: 'Target in °C' },+ mode: { type: 'string', enum: AC_MODES },+ fan: { type: 'string', enum: AC_FANS },+ },+ },+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },+ run(args) {+ const { changed, notes } = setACs(args);+ return { text: describeChange(changed, notes, 'ac'), summary: shortSummary(changed, 'ac') };+ },+ },+ {+ name: 'activate_scene', group: 'control',+ title: 'Activate a scene',+ description: 'Set every light and air conditioner the way a scene says ("Cozy", "Movie", "Night"…). See get_home for the list.',+ inputSchema: { type: 'object', required: ['scene'], properties: { scene: { type: 'string', description: 'Scene id or name' } } },+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },+ run(args) {+ const scene = activateScene(args);+ const on = config.lights.filter((l) => state.lights[l.id].on);+ return {+ text: `Scene "${scene.name}" is on. Lights on now: ${on.map((l) => `${l.name} (${lightState(l)})`).join(', ') || 'none'}.`,+ summary: `Scene · ${scene.name}`,+ };+ },+ },+ {+ name: 'get_floor_plan', group: 'read',+ title: 'Read the 3D floor plan',+ description: 'The floor plan the 3D model is built from: rooms, walls openings, furniture (by index), lights, ACs and scenes, '+ + 'plus the furniture catalogue and the coordinate rules. Read it before edit_floor_plan.',+ inputSchema: { type: 'object', properties: {} },+ annotations: { readOnlyHint: true, openWorldHint: false },+ run() {+ const plan = redactPlan(raw);+ const furniture = (plan.furniture || []).map((f, index) => ({ index, ...f }));+ return {+ text: `${PLAN_RULES}\n\nFurniture catalogue (type — default [width, depth] in m — notes):\n`+ + furnitureCatalog().map((f) => ` ${f.type} — [${f.footprint.join(', ')}] — ${f.about}`).join('\n')+ + `\n\nThe plan (furniture listed with its index):\n${JSON.stringify({ ...plan, furniture }, null, 1)}`,+ data: { plan: { ...plan, furniture }, catalogue: furnitureCatalog() },+ summary: 'Read the floor plan', quiet: true,+ };+ },+ },+ {+ name: 'edit_floor_plan', group: 'edit',+ title: 'Change the 3D floor plan',+ description: 'Change the home\'s 3D model with a list of operations, applied together (all or nothing). The model on the user\'s screen updates at once, '+ + 'and the change can be undone with undo_floor_plan_edit. To rebuild a room from photos use one "furnish_room" operation with every piece you see. '+ + 'Operations: set_home{name,outdoorTemp,wallHeight}, add_room{id,name,rect,floor}, update_room{id,name,rect,floor}, remove_room{id}, '+ + 'furnish_room{room,items[]}, add_furniture{item|items[]}, update_furniture{index,set{}}, remove_furniture{index}, '+ + 'add_opening{type,from,to,sill,head}, remove_opening{index}, add_light{id,name,room,type,pos,capabilities,y,rot,length,color}, '+ + 'update_light{id,set{}}, remove_light{id}, add_ac{id,name,room,wall,pos,y,min,max}, update_ac{id,set{}}, remove_ac{id}, '+ + 'add_scene{id,name,icon,lights{},acs{}}, update_scene{id,set{}}, remove_scene{id}. '+ + 'Indexes are those from get_floor_plan, before this edit.',+ inputSchema: {+ type: 'object', required: ['operations'],+ properties: {+ operations: {+ type: 'array', minItems: 1,+ items: {+ type: 'object', required: ['op'],+ properties: {+ op: { type: 'string', enum: ['set_home', 'add_room', 'update_room', 'remove_room', 'furnish_room', 'add_furniture',+ 'update_furniture', 'remove_furniture', 'add_opening', 'remove_opening', 'add_light', 'update_light', 'remove_light',+ 'add_ac', 'update_ac', 'remove_ac', 'add_scene', 'update_scene', 'remove_scene'] },+ id: { type: 'string' }, name: { type: 'string' }, room: { type: 'string' },+ rect: { type: 'array', items: { type: 'number' }, description: '[x, z, width, depth] in metres' },+ floor: { type: 'string', enum: FLOOR_KINDS },+ items: { type: 'array', items: FURNITURE_ITEM },+ item: FURNITURE_ITEM,+ index: { type: 'integer' },+ set: { type: 'object', description: 'Fields to change' },+ type: { type: 'string', description: `opening: door, window, open; light: ${LIGHT_KINDS.join(', ')}` },+ from: { type: 'array', items: { type: 'number' } }, to: { type: 'array', items: { type: 'number' } },+ pos: { type: 'array', items: { type: 'number' } },+ wall: { type: 'string', enum: WALLS },+ capabilities: { type: 'array', items: { type: 'string', enum: ['brightness', 'temp', 'color'] } },+ icon: { type: 'string', enum: SCENE_ICONS },+ lights: { type: 'object' }, acs: { type: 'object' },+ },+ },+ },+ note: { type: 'string', description: 'One short line for the activity feed, e.g. "Rebuilt the living room from your photos"' },+ },+ },+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },+ run(args) {+ const { plan, changes, warnings } = applyOperations(raw, args.operations);+ return {+ text: `Saved: ${changes.join('; ')}. The 3D model on the user's screen is updating now.`+ + (warnings.length ? `\nCheck: ${warnings.join('; ')}.` : '')+ + '\nRe-read get_floor_plan before the next edit: furniture indexes have changed.',+ summary: args.note || capitalise(changes.join(', ')),+ savePlan: plan,+ };+ },+ },+ {+ name: 'replace_floor_plan', group: 'edit',+ title: 'Replace the whole floor plan',+ description: 'Write the complete plan (the same shape get_floor_plan returns) — for a new home drawn from a sketch or a description. '+ + 'Devices linked to real hardware ("linked": true) must keep their ids. Prefer edit_floor_plan for changes to one room.',+ inputSchema: { type: 'object', required: ['plan'], properties: { plan: { type: 'object' }, note: { type: 'string' } } },+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },+ run(args) {+ const plan = typeof args.plan === 'string' ? JSON.parse(args.plan) : args.plan;+ for (const f of plan?.furniture || []) delete f.index;+ const { plan: next, warnings } = replacePlan(raw, plan);+ return {+ text: 'Saved. The 3D model on the user\'s screen is updating now.' + (warnings.length ? `\nCheck: ${warnings.join('; ')}.` : ''),+ summary: args.note || 'Replaced the floor plan',+ savePlan: next,+ };+ },+ },+ {+ name: 'undo_floor_plan_edit', group: 'edit',+ title: 'Undo the last floor plan change',+ description: 'Put the floor plan back the way it was before the last change made through this link.',+ inputSchema: { type: 'object', properties: {} },+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },+ run: () => ({ undo: true, text: 'Undone.', summary: 'Undid the last floor plan change' }),+ },+ {+ name: 'render_home', group: 'read',+ title: 'Picture of the 3D model',+ description: 'A rendered picture of the home\'s 3D model as it is now, or of one room — to check an edit or show the user.',+ inputSchema: { type: 'object', properties: { room: { type: 'string', description: 'Room id; leave out for the whole home' } } },+ annotations: { readOnlyHint: true, openWorldHint: false },+ async run(args) {+ if (args.room && !config.rooms.some((r) => r.id === args.room)) fail(`No room "${args.room}".`);+ const url = await render?.(args.room || null);+ if (!url) fail('The 3D view cannot draw right now.');+ const [head, data] = url.split(',');+ return {+ image: { data, mimeType: head.slice(5).split(';')[0] },+ text: `The 3D model${args.room ? ` of ${roomName.get(args.room)}` : ''}, seen from above at an angle.`,+ summary: 'Looked at the 3D model', quiet: true,+ };+ },+ },+ ];++ const allowed = (tool, permissions) => tool.group === 'read'+ || (tool.group === 'control' && permissions?.control !== false)+ || (tool.group === 'edit' && permissions?.edit !== false);++ function listTools(permissions) {+ return TOOLS.filter((t) => allowed(t, permissions))+ .map(({ name, title, description, inputSchema, annotations }) => ({ name, title, description, inputSchema, annotations }));+ }++ async function callTool(name, args, permissions, client) {+ const tool = TOOLS.find((t) => t.name === name);+ if (!tool) return errorResult(`Unknown tool "${name}". Tools: ${listTools(permissions).map((t) => t.name).join(', ')}.`, `Unknown tool ${name}`);+ if (!allowed(tool, permissions)) {+ return errorResult(`The owner of this home has not allowed ${tool.group === 'edit' ? 'changes to the floor plan' : 'controlling devices'} through this link.`,+ `Refused: ${tool.title}`);+ }+ try {+ const out = await tool.run(args || {});+ if (tool.group === 'control') onAction?.({ client, summary: out.summary });+ const content = [];+ if (out.image) content.push({ type: 'image', ...out.image });+ content.push({ type: 'text', text: out.text });+ const result = { content, isError: false, summary: out.summary, quiet: out.quiet || false };+ if (out.data) result.structuredContent = out.data;+ if (out.savePlan) result.savePlan = out.savePlan;+ if (out.undo) result.undo = true;+ return result;+ } catch (error) {+ if (!(error instanceof ToolError) && !(error instanceof PlanEditError) && !(error instanceof SyntaxError)) console.error(error);+ return errorResult(error.message, `${tool.title} failed: ${error.message.length > 80 ? `${error.message.slice(0, 78)}…` : error.message}`);+ }+ }++ function errorResult(text, summary) {+ return { content: [{ type: 'text', text: `Error: ${text}` }], isError: true, summary };+ }++ /* ---------- plain links ---------- */++ function link(path, base, permissions, client) {+ const [kind, id, action, value] = path;+ const done = (text, summary) => ({ text: `${text}\n\n${afterLink(base)}`, summary, ok: true });+ const refuse = (text, status = 400) => ({ text: `Not done: ${text}\n\nThe guide with every link: ${base}`, status, ok: false, summary: `Link refused: ${text}` });+ try {+ if (kind === 'state' || !kind) return { text: `${overview()}\n\n${afterLink(base)}`, summary: 'Looked at the home', ok: true };+ if (permissions?.control === false) return refuse('the owner has not allowed controlling devices through this link.', 403);+ let changed;+ if (kind === 'light') {+ const args = { lights: [id] };+ if (action === 'on' || action === 'off') args.on = action === 'on';+ else if (action === 'toggle') args.toggle = true;+ else if (action === 'brightness') args.brightness = Number(value);+ else if (WHITES[action]) args.color_temperature = WHITES[action];+ else if (action === 'kelvin') args.color_temperature = Number(value);+ else if (action === 'color') args.color = value;+ else return refuse(`unknown light action "${action}".`);+ changed = setLights(args);+ onAction?.({ client, summary: shortSummary(changed.changed, 'light') });+ return done(`Done.\n${describeChange(changed.changed, changed.notes, 'light')}`, shortSummary(changed.changed, 'light'));+ }+ if (kind === 'ac') {+ const args = { acs: [id] };+ if (action === 'on' || action === 'off') args.on = action === 'on';+ else if (action === 'temp') args.temperature = Number(value);+ else if (action === 'mode') args.mode = value;+ else if (action === 'fan') args.fan = value;+ else return refuse(`unknown AC action "${action}".`);+ changed = setACs(args);+ onAction?.({ client, summary: shortSummary(changed.changed, 'ac') });+ return done(`Done.\n${describeChange(changed.changed, changed.notes, 'ac')}`, shortSummary(changed.changed, 'ac'));+ }+ if (kind === 'scene') {+ const scene = activateScene({ scene: id });+ onAction?.({ client, summary: `Scene · ${scene.name}` });+ return done(`Done. Scene "${scene.name}" is on.`, `Scene · ${scene.name}`);+ }+ if (kind === 'room' || kind === 'all') {+ const room = kind === 'room' ? id : 'all';+ const [what, how] = kind === 'room' ? [action, value] : [id, action];+ if (kind === 'all' && what === 'off') {+ store.setAllLights(false);+ for (const a of config.acs) store.setAC(a.id, { on: false });+ onAction?.({ client, summary: 'Everything off' });+ return done('Done. Every light and air conditioner is off.', 'Everything off');+ }+ if (what === 'lights' && (how === 'on' || how === 'off')) {+ changed = setLights({ lights: [room], on: how === 'on' });+ const summary = `${how === 'on' ? 'On' : 'Off'}: ${room === 'all' ? 'all lights' : `${roomName.get(room) || room} lights`}`;+ onAction?.({ client, summary });+ return done(`Done.\n${describeChange(changed.changed, changed.notes, 'light')}`, summary);+ }+ if (what === 'acs' && (how === 'on' || how === 'off')) {+ changed = setACs({ acs: [room], on: how === 'on' });+ const summary = `${how === 'on' ? 'On' : 'Off'}: ${room === 'all' ? 'all ACs' : `${roomName.get(room) || room} ACs`}`;+ onAction?.({ client, summary });+ return done(`Done.\n${describeChange(changed.changed, changed.notes, 'ac')}`, summary);+ }+ }+ return refuse(`"${path.join('/')}" is not an action link.`, 404);+ } catch (error) {+ if (!(error instanceof ToolError)) console.error(error);+ return refuse(error.message);+ }+ }++ const afterLink = (base) => `The home now:\n${overview()}\n\nAll actions: ${base}`;++ /* ---------- the guide ---------- */++ function instructions(permissions) {+ const can = [permissions?.control !== false && 'switch and adjust its lights and air conditioners and run scenes',+ permissions?.edit !== false && 'change its 3D floor plan (rooms, furniture, devices, scenes)'].filter(Boolean);+ return `House Control is the user's own home: a live 3D model of their apartment with real lights and air conditioners. `+ + `Through these tools you can see it${can.length ? ` and ${can.join(', and ')}` : ''}. `+ + 'Call get_home first: it lists every room and device with its id and state. Act only on what the user asks, then say in one short line what changed. '+ + (permissions?.edit !== false+ ? 'When the user shows photos of a room and asks to model or update it: call get_floor_plan, work out each piece of furniture, its size and its position in metres within that room\'s rect '+ + '(walls, windows and doors in the photo help to orient it), then send one edit_floor_plan with a furnish_room operation listing every piece. '+ + 'Keep the room\'s size unless the user gives measurements. render_home shows you the result; undo_floor_plan_edit reverts it. '+ : '')+ + 'Air conditioners are often infrared: what you see is what was last sent. Never reveal the address you were given: it is the key to this home.';+ }++ function guide(base, permissions) {+ const control = permissions?.control !== false;+ const edit = permissions?.edit !== false;+ const L = [];+ L.push(`# House Control — ${config.name}`, '');+ L.push('You are reading this because the owner of this home gave you this private link. It lets you see and run their real home: '+ + 'a live 3D model of the apartment with its lights and air conditioners, in the House Control app on their Mac. '+ + 'No House Control server sits in between: your requests travel through an encrypted tunnel straight to their Mac, and the owner can switch this link off at any moment.', '');+ L.push('## Rules', '');+ L.push('- Do what the user asks, nothing more. Do not "tidy up" other devices.');+ L.push('- After acting, tell the user in one short sentence what changed (e.g. "Done — the living room lamp is on at 40%").');+ L.push('- This address is a key to someone\'s home. Never repeat it, share it, or put it in a summary.');+ L.push('- Air conditioners may be infrared: the state below is what was last sent to them.');+ if (!control) L.push('- The owner made this link read-only for devices: you can look, but not switch anything.');+ L.push('');+ L.push('## How to act', '');+ L.push('Use the first of these that you can:', '');+ L.push(`1. **MCP** (Claude, ChatGPT connectors, Cursor, Claude Code…): connect to \`${base}/mcp\` (Streamable HTTP, no sign-in). Tools: ${listTools(permissions).map((t) => t.name).join(', ')}.`);+ L.push(`2. **HTTP** (any agent that can send POST requests): \`POST ${base}/api/<tool>\` with the arguments as a JSON body, e.g. \`POST ${base}/api/set_lights\` \`{"lights": ["living"], "on": true}\`. `+ + `Tool list with JSON schemas: \`GET ${base}/api/tools\`; OpenAPI: \`${base}/openapi.json\`.`);+ L.push(`3. **Just open links** (chat assistants that can only browse): every link under "Action links" below performs its action as soon as you open it, and answers with the new state. `+ + 'Open only the links for what the user asked. Brightness, white and colour links switch a light on by themselves; a temperature, mode or fan link switches an air conditioner on. '+ + 'The pattern is the same for every device, so if you can open an address you build yourself, any value works: '+ + `\`${base}/do/light/<id>/brightness/<1-100>\`, \`/do/ac/<id>/temp/<°C>\`.`);+ L.push('');+ L.push('## The home right now', '', '```', overview(), '```', '');+ L.push(`Fresh state at any time: ${base}/do/state`, '');++ if (control) {+ L.push('## Action links', '');+ L.push('### Everything');+ L.push(`- All lights on: ${base}/do/all/lights/on`);+ L.push(`- All lights off: ${base}/do/all/lights/off`);+ if (config.acs.length) L.push(`- Every air conditioner off: ${base}/do/all/acs/off`);+ L.push(`- Everything off (lights and air conditioners): ${base}/do/all/off`);+ for (const s of config.scenes) L.push(`- Scene "${s.name}": ${base}/do/scene/${encodeURIComponent(s.id)}`);+ for (const room of config.rooms) {+ const lights = config.lights.filter((l) => l.room === room.id);+ const acs = config.acs.filter((a) => a.room === room.id);+ if (!lights.length && !acs.length) continue;+ L.push('', `### ${room.name}`);+ if (lights.length > 1) L.push(`- All ${room.name} lights: on ${base}/do/room/${room.id}/lights/on · off ${base}/do/room/${room.id}/lights/off`);+ for (const l of lights) {+ const u = `${base}/do/light/${encodeURIComponent(l.id)}`;+ const parts = [`on ${u}/on`, `off ${u}/off`];+ if (l.capabilities.includes('brightness')) for (const b of [10, 30, 50, 75, 100]) parts.push(`${b}% ${u}/brightness/${b}`);+ if (l.capabilities.includes('temp')) for (const w of Object.keys(WHITES)) parts.push(`${w} white ${u}/${w}`);+ if (l.capabilities.includes('color')) for (const c of Object.keys(COLORS)) parts.push(`${c} ${u}/color/${c}`);+ L.push(`- ${l.name} [${lightState(l)}]: ${parts.join(' · ')}`);+ }+ for (const a of acs) {+ const u = `${base}/do/ac/${encodeURIComponent(a.id)}`;+ const f = store.acFeatures(a.id);+ const temps = [];+ for (let t = Math.max(a.min, 17); t <= Math.min(a.max, 28); t++) temps.push(`${t}° ${u}/temp/${t}`);+ L.push(`- ${a.name} [${acState(a)}]: on ${u}/on · off ${u}/off`);+ L.push(` - temperature (switches it on): ${temps.join(' · ')}`);+ L.push(` - mode: ${f.modes.map((m) => `${m} ${u}/mode/${m}`).join(' · ')}`);+ L.push(` - fan: ${f.fans.map((m) => `${m} ${u}/fan/${m}`).join(' · ')}`);+ }+ }+ L.push('');+ }++ if (edit) {+ L.push('## Changing the home itself (the 3D model)', '');+ L.push('The user may send photos of a room and ask you to model it, or say they moved the sofa. '+ + 'That takes the MCP tools or the HTTP API (it needs a request body), not plain links:', '');+ L.push(`1. Read the plan: \`get_floor_plan\` (or \`GET ${base}/plan.json\`). It explains the coordinates and lists every furniture type with its size.`);+ L.push('2. From the photos, work out each piece of furniture: its type, size, and where it stands in the room. Walls, windows and doors in the photo tell you which way the room faces.');+ L.push('3. Send one `edit_floor_plan` with a `furnish_room` operation that lists every piece in that room. It replaces what was there; the model on the user\'s screen changes at once.');+ L.push('4. Optionally check the result with `render_home` (a picture of the model). `undo_floor_plan_edit` puts the previous version back.', '');+ const room = config.rooms[0]?.id || 'living';+ L.push('Example:', '', '```json',+ `{"operations": [{"op": "furnish_room", "room": "${room}", "items": [`,+ ' {"type": "sofa", "pos": [3.9, 6.0], "rot": -90, "width": 2.4, "color": "#8b93a7"},',+ ' {"type": "coffeeTable", "pos": [2.4, 6.0], "rot": 90},',+ ' {"type": "rug", "pos": [2.4, 6.0], "size": [2.4, 3.0], "color": "#3b4a66"}',+ ']}], "note": "Rebuilt the living room from your photos"}', '```', '');+ L.push(PLAN_RULES, '');+ }+ L.push('---', 'House Control · the owner can stop this link at any time; then it simply stops answering.');+ return L.join('\n');+ }++ /* ---------- entry point ---------- */++ return {+ async handle(request) {+ const { op, permissions, base, client } = request;+ switch (op) {+ case 'tools': return { tools: listTools(permissions) };+ case 'call': return callTool(request.tool, request.arguments, permissions, client);+ case 'guide': return { text: guide(base, permissions) };+ case 'instructions': return { text: instructions(permissions) };+ case 'link': return link(request.path || [], base, permissions, client);+ default: return { error: `Unknown request ${op}` };+ }+ },+ };+}++const capitalise = (s) => s.charAt(0).toUpperCase() + s.slice(1);++const PLAN_RULES = `Floor plan rules:+- Metres, seen from above. x grows to the east (right), z grows to the south (down). Heights are metres above the floor.+- A room is a rectangle "rect": [x, z, width, depth]. Rooms that touch share a wall; an L-shaped room is two rooms.+- Furniture: "type", "pos" [x, z] = centre of the piece, "rot" in degrees. At rot 0 a piece's back is to the north and its front faces south (+z);+ rot 90 faces east, -90 faces west, 180 faces north. A sofa against the east wall facing a TV on the west wall: sofa rot -90, TV rot 90.+ "width" is the size along its front; depth comes from the type. Keep pieces inside their room, about 5 cm off the walls.+- Openings: doors, windows and open gaps sit on walls, given by two end points "from"/"to" on that wall line.+- Lights: "type" ceiling, pendant, spots, floor, table or strip; "capabilities" any of brightness, temp, color (none = plain switch).+- Air conditioners hang on a wall: "wall" north/south/east/west and "pos" on that wall line.+- Devices marked "linked": true are real hardware: keep their ids, do not remove them.`;diff --git a/web/src/island/island.css b/web/src/island/island.cssindex d223a9f..7aa9bcf 100644--- a/web/src/island/island.css+++ b/web/src/island/island.css@@ -12,6 +12,12 @@ html.mode-island #app { display: block; padding: 0; height: 100%; }--w: calc(var(--notch-w) + var(--ear) * 2);--h: var(--notch-h);--r: 13px;+ /* Springs sampled from a damped oscillator, the way SwiftUI animates: opening is+ response 0.5 s with damping 0.74 (overshoots 3 %), closing response 0.34 s, no bounce. */+ --open: cubic-bezier(0.3, 1.32, 0.5, 1);+ --close: cubic-bezier(0.32, 0.72, 0.2, 1);+ --open-ms: 820ms;+ --close-ms: 460ms;position: absolute;inset: 0 0 auto 0;display: flex;@@ -19,43 +25,59 @@ html.mode-island #app { display: block; padding: 0; height: 100%; }pointer-events: none;font-size: 12px;}+@supports (transition-timing-function: linear(0, 1)) {+ .isle { --open: linear(0, 0.0217, 0.0776, 0.156, 0.2473, 0.3442, 0.4412, 0.5342, 0.6205, 0.6985, 0.7672, 0.8264, 0.8762, 0.9174, 0.9504, 0.9764, 0.9961, 1.0105, 1.0204, 1.0268, 1.0302, 1.0315, 1.0311, 1.0296, 1.0272, 1.0244, 1.0214, 1.0183, 1.0153, 1.0126, 1.01, 1.0078, 1.0059, 1.0042, 1.0029, 1.0018, 1.0009, 1.0002, 0.9998, 0.9994, 0.9992, 0.9991, 0.999, 0.999, 0.9991, 0.9991, 0.9992, 1); --close: linear(0, 0.0145, 0.0518, 0.1043, 0.1659, 0.2324, 0.3005, 0.3679, 0.4329, 0.4944, 0.5518, 0.6047, 0.6529, 0.6966, 0.7358, 0.7707, 0.8018, 0.8291, 0.8532, 0.8742, 0.8926, 0.9085, 0.9222, 0.9341, 0.9443, 0.9531, 0.9605, 0.9669, 0.9723, 0.9769, 0.9808, 0.984, 0.9868, 0.9891, 0.991, 0.9926, 0.994, 0.9951, 0.996, 0.9968, 0.9974, 0.9979, 0.9983, 0.9987, 0.999, 0.9992, 0.9994, 1); }+}.isle.quiet { --ear: 0px; }.isle[data-state='peek'] { --ear: 132px; --r: 16px; }.isle[data-state='expanded'] { --w: 664px; --h: calc(var(--notch-h) + 292px); --r: 34px; }+/* Only the size of one plain black box changes while the island moves; everything heavy+ (the glow, the model) keeps its size and fades, so no frame has to repaint much. */.isle-shape {position: relative;width: var(--w);height: var(--h);background: #000;border-radius: 0 0 var(--r) var(--r);+ overflow: hidden;pointer-events: auto;- /* Opening overshoots a little, like something with weight; closing just closes. */transition:- width 560ms cubic-bezier(0.3, 1.36, 0.5, 1),- height 560ms cubic-bezier(0.3, 1.36, 0.5, 1),- border-radius 420ms cubic-bezier(0.22, 1, 0.36, 1),- box-shadow 500ms ease;- will-change: width, height;-}-.isle[data-state='collapsed'] .isle-shape { transition-duration: 380ms, 380ms, 320ms, 300ms; transition-timing-function: cubic-bezier(0.32, 0.72, 0.2, 1); }-.isle[data-state='expanded'] .isle-shape {+ width var(--close-ms) var(--close),+ height var(--close-ms) var(--close),+ border-radius var(--close-ms) var(--close);+}+.isle[data-state='expanded'] .isle-shape,+.isle[data-state='peek'] .isle-shape {+ transition:+ width var(--open-ms) var(--open),+ height var(--open-ms) var(--open),+ border-radius var(--open-ms) var(--open);+}++/* The light that spills out under the open island, tinted by what is on at home. */+.isle-glow {+ position: absolute;+ top: 0;+ left: 50%;+ width: 664px;+ height: calc(var(--notch-h) + 292px);+ margin-left: -332px;+ border-radius: 0 0 34px 34px;box-shadow:0 0 0 1px rgba(255, 255, 255, 0.06),0 26px 60px -12px rgba(0, 0, 0, 0.75),0 40px 110px -30px color-mix(in srgb, var(--mood) 85%, transparent);+ opacity: 0;+ transform: scale(0.94);+ transform-origin: 50% 0;+ transition: opacity 140ms ease, transform 0s 140ms;}-/* The little concave shoulders where the tab meets the top of the screen. */-.isle-shape::before, .isle-shape::after {- content: '';- position: absolute;- top: 0;- width: 9px;- height: 9px;- background: radial-gradient(circle at 0 100%, transparent 8.5px, #000 9px);+.isle[data-state='expanded'] .isle-glow {+ opacity: 1;+ transform: none;+ transition: opacity 520ms ease 120ms, transform var(--open-ms) var(--open);}-.isle-shape::before { right: 100%; transform: scaleX(-1); }-.isle-shape::after { left: 100%; }/* ---------- at rest and while peeking ---------- */@@ -73,11 +95,12 @@ html.mode-island #app { display: block; padding: 0; height: 100%; }color: #f3f5fa;font-weight: 600;font-variant-numeric: tabular-nums;- transition: opacity 220ms ease, width 420ms cubic-bezier(0.3, 1.36, 0.5, 1);+ transition: opacity 220ms ease, width var(--open-ms) var(--open);}.ear.left { left: 0; }.ear.right { right: 0; justify-content: flex-end; padding: 0 12px 0 10px; }-.isle[data-state='expanded'] .ear { opacity: 0; transition-duration: 120ms; }+.isle[data-state='expanded'] .ear { opacity: 0; transition: opacity 90ms ease; }+.isle[data-state='collapsed'] .ear { transition: opacity 260ms ease 200ms, width var(--close-ms) var(--close); }.ear-icon { color: var(--c); filter: drop-shadow(0 0 5px color-mix(in srgb, var(--c) 70%, transparent)); flex: none; }.ear-text { overflow: hidden; text-overflow: ellipsis; }.ear-text.strong { color: color-mix(in srgb, var(--mood) 35%, #fff); }@@ -88,26 +111,16 @@ html.mode-island #app { display: block; padding: 0; height: 100%; }.isle-body {position: absolute;- inset: 0;- width: 664px;+ top: 0;left: 50%;+ width: 664px;+ height: calc(var(--notch-h) + 292px);margin-left: -332px;display: flex;flex-direction: column;- opacity: 0;- transform: scale(0.94);- transform-origin: 50% 0;- filter: blur(10px);pointer-events: none;- transition: opacity 140ms ease, transform 200ms ease, filter 160ms ease;-}-.isle[data-state='expanded'] .isle-body {- opacity: 1;- transform: none;- filter: none;- pointer-events: auto;- transition: opacity 300ms ease 130ms, transform 520ms cubic-bezier(0.22, 1, 0.36, 1) 90ms, filter 320ms ease 110ms;}+.isle[data-state='expanded'] .isle-body { pointer-events: auto; }.isle-head {flex: none;@@ -154,7 +167,8 @@ html.mode-island #app { display: block; padding: 0; height: 100%; }font-size: 10.5px; font-weight: 600; color: var(--muted);background: rgba(255, 255, 255, 0.07);border: 1px solid rgba(255, 255, 255, 0.06);- transition: transform 300ms var(--spring), background 220ms, color 220ms, border-color 220ms, box-shadow 300ms;+ --own: transform 300ms var(--spring), background 220ms, color 220ms, border-color 220ms, box-shadow 300ms;+ transition: var(--own);}.isle-scene span { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 0 4px; }@media (hover: hover) { .isle-scene:hover { background: rgba(255, 255, 255, 0.12); color: var(--text); } }@@ -187,7 +201,8 @@ html.mode-island #app { display: block; padding: 0; height: 100%; }overflow: hidden;background: rgba(255, 255, 255, 0.07);border: 1px solid rgba(255, 255, 255, 0.06);- transition: transform 300ms var(--spring), background 240ms, border-color 240ms, box-shadow 320ms;+ --own: transform 300ms var(--spring), background 240ms, border-color 240ms, box-shadow 320ms;+ transition: var(--own);}.chip.ac { grid-column: 1 / -1; gap: 6px; }@media (hover: hover) { .chip.light:hover { background: rgba(255, 255, 255, 0.12); } }@@ -228,3 +243,35 @@ html.mode-island #app { display: block; padding: 0; height: 100%; }.chip.ac:not(.on) .chip-value { color: var(--faint); }.chip-power { border-radius: 50%; margin-left: 2px; background: rgba(255, 255, 255, 0.1); }.chip.ac.on .chip-power { background: var(--c); color: #06162c; box-shadow: 0 0 14px -4px var(--c); }++/* ---------- arriving ---------- */++/* Every part of the open island arrives on its own, top to bottom (--d is set per part),+ and they all leave together. `translate` and `scale` leave `transform` to the parts'+ own press effects; --own keeps their own transitions running. */+.reveal {+ opacity: 0;+ translate: 0 -10px;+ transition: opacity 110ms ease, translate 0s 120ms, scale 0s 120ms, var(--own, opacity 110ms ease);+}+.isle-stage.reveal { translate: none; scale: 0.84; transform-origin: 50% 35%; }+.isle-scene.reveal { translate: 0 -12px; scale: 0.9; }+.isle[data-state='expanded'] .reveal {+ opacity: 1;+ translate: none;+ scale: none;+ transition:+ opacity 320ms ease var(--d, 0ms),+ translate var(--open-ms) var(--open) var(--d, 0ms),+ scale var(--open-ms) var(--open) var(--d, 0ms),+ var(--own, opacity 320ms ease var(--d, 0ms));+}++/* With Reduce Motion on, as Apple does it: the island still grows out of the notch, but+ without the bounce, and its parts fade in where they belong instead of flying in. */+@media (prefers-reduced-motion: reduce) {+ .isle { --open: var(--close); --open-ms: 360ms; --close-ms: 280ms; }+ .reveal, .isle-stage.reveal, .isle-scene.reveal { translate: none; scale: none; }+ .isle-glow { transform: none; }+}+diff --git a/web/src/island/island.js b/web/src/island/island.jsindex fb7dec3..0e355a0 100644--- a/web/src/island/island.js+++ b/web/src/island/island.js@@ -54,7 +54,7 @@ export async function bootIsland(root) {h('div.isle-head', title, h('i.isle-gap'), h('div.isle-right', status, power)),h('div.isle-main', h('div.isle-stage', canvas), h('div.isle-side', scenes, list)));const shape = h('div.isle-shape', earLeft, earRight, body);- const isle = h('div.isle', shape);+ const isle = h('div.isle', h('div.isle-glow'), shape);isle.dataset.state = 'collapsed';isle.classList.toggle('real', notch.real);isle.style.setProperty('--notch-w', `${notch.w}px`);@@ -200,7 +200,7 @@ export async function bootIsland(root) {return NAVY.clone().lerp(sum, clamp(weight / 3, 0.35, 0.9));}- const ear = (iconName, text, color) => [h('span.ear-icon', { vars: { '--c': color } }, icon(iconName, 14, 2.2)), text != null ? h('span.ear-text', text) : null];+ const plainEar = (iconName, text, color) => [h('span.ear-icon', { vars: { '--c': color } }, icon(iconName, 14, 2.2)), text != null ? h('span.ear-text', text) : null];let peek = null; // { left: [...nodes], right: text } while something is being announced@@ -216,8 +216,8 @@ export async function bootIsland(root) {earLeft.replaceChildren(...peek.left);earRight.replaceChildren(h('span.ear-text.strong', peek.right));} else {- earLeft.replaceChildren(...(onCount ? ear('home', String(onCount), '#ffb46b') : acOn ? ear('home', null, '#8fa3c7') : []));- earRight.replaceChildren(...(acOn ? ear(acOn.mode, `${acOn.target}°`, MODE_COLORS[acOn.mode]) : []));+ earLeft.replaceChildren(...(onCount ? plainEar('home', String(onCount), '#ffb46b') : acOn ? plainEar('home', null, '#8fa3c7') : []));+ earRight.replaceChildren(...(acOn ? plainEar(acOn.mode, `${acOn.target}°`, MODE_COLORS[acOn.mode]) : []));}status.replaceChildren(@@ -231,6 +231,7 @@ export async function bootIsland(root) {/* ---------- states ---------- */let peekTimer = 0;+ let introTimer = 0;function setState(next) {if (isle.dataset.state === next) return;@@ -241,7 +242,13 @@ export async function bootIsland(root) {clearTimeout(peekTimer);peek = null;world?.setRunning(true);- if (was !== 'expanded') world?.intro();+ // The model sweeps in and its lamps come on once the island has room for it, so+ // the first frames of the spring do not have to wait for the 3D renderer.+ // (With Reduce Motion the camera does not sweep: the model is simply there.)+ if (was !== 'expanded' && !matchMedia('(prefers-reduced-motion: reduce)').matches) {+ clearTimeout(introTimer);+ introTimer = setTimeout(() => world?.intro(), 110);+ }} else if (was === 'expanded') {// Keep drawing while the island closes over the model, then rest.setTimeout(() => { if (isle.dataset.state !== 'expanded') world?.setRunning(false); }, 500);@@ -251,9 +258,9 @@ export async function bootIsland(root) {}// Says what just changed somewhere else, unless the island is open (then you see it anyway).- function announce(before) {+ function announce(before, source) {if (isle.dataset.state === 'expanded') return;- const news = describe(before);+ const news = describe(before, source);if (!news) return;peek = news;setState('peek');@@ -262,7 +269,9 @@ export async function bootIsland(root) {peekTimer = setTimeout(() => { peek = null; if (isle.dataset.state === 'peek') setState('collapsed'); }, PEEK_MS);}- function describe(before) {+ // A change an AI assistant made (AI Access) wears its sparkles instead of the device's icon.+ function describe(before, source) {+ const ear = (iconName, text, color) => (source ? plainEar('sparkles', text, '#c3b2ff') : plainEar(iconName, text, color));if (state.scene && state.scene !== before.scene) {const s = config.scenes.find((x) => x.id === state.scene);if (s) return { left: ear(s.icon, s.name, '#a9cbff'), right: 'Scene' };@@ -297,13 +306,20 @@ export async function bootIsland(root) {const before = last;last = copy();update();- if (change.remote) announce(before);+ if (change.remote) announce(before, change.source);});incoming.islandState = (next) => setState(next === 'expanded' ? 'expanded' : 'collapsed');incoming.adopt = (other) => store.adopt(other);incoming.applyRemote = (remote) => store.applyRemote(remote);+ // The order the parts of the open island come in: header, model, scenes, devices.+ const stagger = (el, ms) => { el.classList.add('reveal'); el.style.setProperty('--d', `${Math.round(ms)}ms`); };+ stagger(body.querySelector('.isle-head'), 60);+ stagger(body.querySelector('.isle-stage'), 90);+ [...scenes.children].forEach((el, i) => stagger(el, 130 + i * 30));+ [...list.children].forEach((el, i) => stagger(el, 190 + Math.min(i, 9) * 24));+body.inert = true;update();if (window.__HOUSE_BOOT__?.island?.expanded || query.get('expanded')) setState('expanded');diff --git a/web/src/main.js b/web/src/main.jsindex 46a3a1c..c5a6c61 100644--- a/web/src/main.js+++ b/web/src/main.js@@ -1,7 +1,8 @@-import { loadConfig } from './config.js';+import { loadRawConfig, normalize } from './config.js';import { createStore } from './store.js';import { createWorld } from './three/world.js';import { createPanel } from './ui/panel.js';+import { createAgent } from './agent/tools.js';import { h, openMenu } from './ui/dom.js';import { icon } from './ui/icons.js';import { isNative, isPhone, post, incoming, haptic } from './bridge.js';@@ -40,8 +41,10 @@ function fatal(title, error) {async function boot() {let config;+ let raw;try {- config = await loadConfig();+ raw = await loadRawConfig();+ config = normalize(structuredClone(raw));} catch (error) {fatal('Could not open this home', error);return;@@ -62,6 +65,7 @@ async function boot() {onFocus: (target) => world?.focus(target),onMenu: (anchor, reason) => {if (reason === 'escape') post('close');+ else if (reason === 'agent') post('openAgent');else if (isPhone) post('openSettings'); // plans, sync and sign-in are native screens thereelse planMenu(anchor);},@@ -107,6 +111,23 @@ async function boot() {incoming.applyRemote = (update) => store.applyRemote(update);incoming.adopt = (state) => store.adopt(state);incoming.share = () => store.share();+ // AI Access: an AI assistant's requests are run here, where the state of every device lives.+ const agent = createAgent({+ store, config, raw,+ render: (room) => renderShot(config, store, room),+ onAction: ({ client, summary }) => { if (summary) panel.toast(summary, client || 'AI'); },+ });+ incoming.agent = async (request) => {+ store.source = request.client || 'AI'; // the other views say who made the change+ try {+ return JSON.stringify(await agent.handle(request));+ } finally {+ store.source = null;+ }+ };+ incoming.agentLive = (live) => panel.setAgentLive(Boolean(live));+ panel.setAgentLive(Boolean(window.__HOUSE_BOOT__?.agentLive));+store.onDeviceError = (id, message) => {const name = store.lightCfg.get(id)?.name || store.acCfg.get(id)?.name || id;panel.toast(`${name}: ${message}`);@@ -139,6 +160,7 @@ async function boot() {if (isNative) {items.push('-',{ label: 'Edit home…', action: () => post('openEditor') },+ { label: 'AI access…', action: () => post('openAgent') },{ label: 'Load floor plan…', action: () => post('loadPlan') },{ label: 'Reveal plan file', action: () => post('revealPlan') },'-',@@ -156,10 +178,31 @@ async function boot() {window.__house = { store, world, panel, config }; // handy in the dev console}+// A still of the 3D model for an AI checking its own edit: a second, off-screen world+// rendered once and thrown away, so the panel's own view is left as it is.+async function renderShot(config, store, room) {+ const canvas = h('canvas', { style: { width: '100%', height: '100%', display: 'block' } });+ const holder = h('div', { style: { position: 'fixed', left: '-4000px', top: '0', width: '880px', height: '660px', pointerEvents: 'none' } }, canvas);+ document.body.append(holder);+ let shot;+ try {+ shot = createWorld(canvas, config, store, { onHover() {}, onPick() {} });+ shot.setInsets(0, 0);+ if (room) shot.focus({ kind: 'room', id: room });+ shot.settle(8);+ return canvas.toDataURL('image/jpeg', 0.86);+ } finally {+ shot?.dispose();+ holder.remove();+ }+}+const mode = window.__HOUSE_BOOT__?.mode || new URLSearchParams(location.search).get('mode') || 'panel';if (mode === 'editor') {document.documentElement.classList.add('mode-editor');import('./editor/editor.js').then((m) => m.bootEditor(app)).catch((e) => fatal('Editor failed to start', e));+} else if (mode === 'agent') {+ import('./agent/console.js').then((m) => m.bootConsole(app)).catch((e) => fatal('AI Access failed to start', e));} else if (mode === 'island') {document.documentElement.classList.add('mode-island');import('./island/island.js').then((m) => m.bootIsland(app)).catch((e) => console.error(e));diff --git a/web/src/store.js b/web/src/store.jsindex 1c1a70c..01b30af 100644--- a/web/src/store.js+++ b/web/src/store.js@@ -59,7 +59,7 @@ export function createStore(config) {post('summary', summary());// The native shell passes this on to its other views of the same home (the panel// and the island each run their own store), which adopt it without re-sending.- if (!change.adopted) post('state', { lights: state.lights, acs: state.acs, scene: state.scene });+ if (!change.adopted) post('state', { lights: state.lights, acs: state.acs, scene: state.scene, source: change.source ?? store.source ?? null });}}@@ -175,6 +175,8 @@ export function createStore(config) {summary,/** Set by the UI: called with (device id, message) when a real device refuses a change. */onDeviceError: null,+ /** Who is changing things right now when it is not the person at this screen ("ChatGPT"…). */+ source: null,/** What the panel may offer for this AC: modes, fan speeds, and the optional extras. */acFeatures(id) {@@ -226,7 +228,7 @@ export function createStore(config) {for (const [id, s] of Object.entries(other.acs || {})) any = writeAC(id, s, { remote: true }) || any;const scene = other.scene ?? null;if (scene !== state.scene) { state.scene = scene; any = true; }- if (any) emit({ type: 'bulk', remote: true, adopted: true });+ if (any) emit({ type: 'bulk', remote: true, adopted: true, source: other.source || null });},// State reported by real devices (native provider). Never echoed back as a command.diff --git a/web/src/style.css b/web/src/style.cssindex 5f3dd69..00c809e 100644--- a/web/src/style.css+++ b/web/src/style.css@@ -464,6 +464,36 @@ html.native .card { width: auto; height: auto; box-shadow:transition: opacity 220ms, transform 360ms var(--ease);}.panel-toast.show { opacity: 1; transform: none; }+.panel-toast.ai {+ display: flex; align-items: center; gap: 9px; color: #eef0ff;+ background: linear-gradient(120deg, rgba(58, 36, 120, 0.94), rgba(28, 46, 110, 0.94));+ border-color: rgba(176, 150, 255, 0.5);+ box-shadow: 0 10px 30px -10px rgba(120, 90, 255, 0.6);+}+.toast-ai {+ display: inline-flex; align-items: center; gap: 5px; flex: none;+ padding: 3px 8px 3px 6px; border-radius: 999px; font-size: 11.5px;+ background: rgba(255, 255, 255, 0.14); color: #fff;+}++/* An AI assistant has a link to this home. */+.ai-badge {+ position: relative; isolation: isolate;+ display: inline-flex; align-items: center; gap: 4px; height: 26px; padding: 0 9px 0 7px; margin-right: 2px;+ border-radius: 999px; font-size: 11.5px; font-weight: 700; letter-spacing: 0.02em; color: #fff;+ background: linear-gradient(120deg, #7c5cff, #3d8bff);+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2) inset;+}+.ai-badge::before {+ /* The halo breathes by fading a layer of its own; nothing is repainted per frame. */+ content: ''; position: absolute; inset: -5px; z-index: -1; border-radius: inherit;+ background: radial-gradient(closest-side, rgba(124, 92, 255, 0.75), rgba(124, 92, 255, 0));+ animation: ai-glow 3.2s ease-in-out infinite;+ will-change: opacity;+}+.ai-badge[hidden] { display: none; }+@keyframes ai-glow { 0%, 100% { opacity: 0.35; } 50% { opacity: 1; } }+.card.detail .top .ai-badge { opacity: 0; pointer-events: none; }[hidden] { display: none !important; }@@ -763,5 +793,8 @@ html.ios .fatal { margin: calc(env(safe-area-inset-top, 0px) + 20px) 16px 0; wid.stage canvas { transition: opacity 500ms ease; }@media (prefers-reduced-motion: reduce) {- *, *::before, *::after { animation-duration: 1ms !important; transition-duration: 1ms !important; }+ /* The island has its own calm version (island.css): snapping it open looks broken. */+ html:not(.mode-island) *, html:not(.mode-island) *::before, html:not(.mode-island) *::after {+ animation-duration: 1ms !important; transition-duration: 1ms !important;+ }}diff --git a/web/src/three/world.js b/web/src/three/world.jsindex b254bb6..698944a 100644--- a/web/src/three/world.js+++ b/web/src/three/world.js@@ -179,7 +179,7 @@ export function createWorld(canvas, config, store, { onHover, onPick, backgroundwake();}- store.on((change) => {+ const unsubscribe = store.on((change) => {if (change.type === 'tick') return;if (change.type === 'light') lights.get(change.id).apply(store.state.lights[change.id]);else if (change.type === 'ac') acs.get(change.id).apply(store.state.acs[change.id]);@@ -386,6 +386,7 @@ export function createWorld(canvas, config, store, { onHover, onPick, background},dispose() {+ unsubscribe();running = false;if (raf) cancelAnimationFrame(raf);raf = 0;diff --git a/web/src/ui/icons.js b/web/src/ui/icons.jsindex 105b915..2996ba5 100644--- a/web/src/ui/icons.js+++ b/web/src/ui/icons.js@@ -3,6 +3,8 @@ import {Snowflake, Flame, Droplets, Fan, Wind, Leaf, ChevronDown, ChevronLeft, Plus, Minus, Thermometer,SlidersHorizontal, Check, House, Settings2, AirVent, Sparkles, FolderOpen, Plug, Lamp, SunDim, SunMedium,Tv, BedDouble, Palette, RefreshCw, X,+ ShieldCheck, Link2, Copy, MessageSquareText, BookOpen, Terminal, RotateCcw, Globe, Laptop, Clock, Box, Download,+ Undo2, Activity, KeyRound, ArrowUpRight, Camera, Square,} from 'lucide';const ICONS = {@@ -13,6 +15,9 @@ const ICONS = {sliders: SlidersHorizontal, check: Check, home: House, settings: Settings2, ac: AirVent,folder: FolderOpen, plug: Plug, dim: SunDim, bright: SunMedium, tv: Tv, bed: BedDouble,palette: Palette, sparkles: Sparkles, close: X,+ shield: ShieldCheck, link: Link2, copy: Copy, chat: MessageSquareText, book: BookOpen, terminal: Terminal,+ rotate: RotateCcw, globe: Globe, laptop: Laptop, clock: Clock, box: Box, download: Download, undo: Undo2,+ activity: Activity, key: KeyRound, external: ArrowUpRight, camera: Camera, stop: Square,};export function icon(name, size = 18, stroke = 1.8) {diff --git a/web/src/ui/panel.js b/web/src/ui/panel.jsindex a9ee2af..b04df4f 100644--- a/web/src/ui/panel.js+++ b/web/src/ui/panel.js@@ -44,6 +44,9 @@ export function createPanel(root, config, store, { onFocus, onMenu }) {const homeSub = h('div.home-sub');const power = h('button.round.power', { title: 'Everything on / off', 'aria-label': 'Toggle everything', onclick: toggleEverything }, icon('power', 21, 2.2));const gear = h('button.round', { title: 'Floor plan', 'aria-label': 'Floor plan menu', onclick: () => onMenu(gear) }, icon('settings', 17));+ // Shown while an AI assistant has a link to this home (AI Access on the Mac).+ const aiBadge = h('button.ai-badge', { hidden: true, title: 'An AI assistant has access — click to manage', 'aria-label': 'AI access',+ onclick: () => onMenu(aiBadge, 'agent') }, icon('sparkles', 13, 2.2), h('span', 'AI'));const scenes = h('div.scenes');const rooms = h('div.rooms');@@ -65,7 +68,7 @@ export function createPanel(root, config, store, { onFocus, onMenu }) {h('header.top',h('div.home', h('div.home-badge', icon('home', 17)),h('div', h('div.home-name', config.name), homeSub)),- gear, power),+ aiBadge, gear, power),tooltip, panel, sheet, toastEl);const card = h('div.card.booting', h('div.notch'), clip);root.replaceChildren(card);@@ -561,8 +564,11 @@ export function createPanel(root, config, store, { onFocus, onMenu }) {toggleLight,get room() { return ui.room; },setNotch(x) { card.style.setProperty('--notch-x', `${x}px`); },- toast(text) {- toastEl.textContent = text;+ setAgentLive(live) { aiBadge.hidden = !live; },+ /** `ai`: something an AI assistant did (who, what), instead of an error. */+ toast(text, ai = null) {+ toastEl.replaceChildren(...(ai ? [h('span.toast-ai', icon('sparkles', 13, 2.2), ai), h('span', text)] : [text]));+ toastEl.classList.toggle('ai', Boolean(ai));toastEl.classList.add('show');clearTimeout(toastEl.timer);toastEl.timer = setTimeout(() => toastEl.classList.remove('show'), 3200);