diff --git a/catalog.json b/catalog.json index 7ac6b98..a38ed91 100644 --- a/catalog.json +++ b/catalog.json @@ -22,7 +22,7 @@ { "id": "blender", "package": "@neuralnomads/opencode-blender", - "range": "^0.4", + "range": "^0.5", "displayName": "OpenCode for Blender", "family": "native", "plugin": "neuralnomads.blender", @@ -32,7 +32,7 @@ "fr": "Lire et modifier la scène ouverte dans Blender grâce à l'extension OpenCode Link : changements typés en un pas d'annulation, inspection du Blender lancé, rendus de vérification et en arrière-plan." }, "app": { "name": "Blender", "versions": ">=5.3" }, - "host": { "protocol": 1, "range": "^0.4.8" }, + "host": { "protocol": 1, "range": "^0.5.0" }, "docs": "https://github.com/NeuralNomadsAI/opencode-integrations/blob/main/integrations/blender/plugin/README.md", "status": "preview", "sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/blender/plugin"] } @@ -40,7 +40,7 @@ { "id": "gaffer", "package": "@neuralnomads/opencode-gaffer", - "range": "^0.3", + "range": "^0.4", "displayName": "OpenCode for Gaffer", "family": "native", "plugin": "neuralnomads.gaffer", @@ -50,7 +50,7 @@ "fr": "Lire, modifier et vérifier les scripts ouverts dans Gaffer depuis toute conversation OpenCode, avec un panneau facultatif dans Gaffer." }, "app": { "name": "Gaffer", "versions": ">=1.6" }, - "host": { "protocol": 1, "range": "^0.3.0" }, + "host": { "protocol": 1, "range": "^0.4.0" }, "docs": "https://github.com/NeuralNomadsAI/opencode-integrations/blob/main/integrations/gaffer/plugin/README.md", "status": "preview", "sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/gaffer/plugin"] } @@ -58,7 +58,7 @@ { "id": "godot", "package": "@neuralnomads/opencode-godot", - "range": "^0.1", + "range": "^0.2", "displayName": "OpenCode for Godot", "family": "native", "plugin": "neuralnomads.godot", @@ -68,7 +68,7 @@ "fr": "Lire, modifier et vérifier le projet ouvert dans l'éditeur Godot depuis toute conversation OpenCode : GDScript en une action d'annulation, vérifications et exécutions dans un Godot en arrière-plan, et un dock de conversation facultatif dans l'éditeur." }, "app": { "name": "Godot", "versions": ">=4.7 <5" }, - "host": { "protocol": 1, "range": "^0.1.0" }, + "host": { "protocol": 1, "range": "^0.2.0" }, "docs": "https://github.com/NeuralNomadsAI/opencode-integrations/blob/main/integrations/godot/plugin/README.md", "status": "preview", "sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/godot/plugin"] } @@ -76,7 +76,7 @@ { "id": "houdini", "package": "@neuralnomads/opencode-houdini", - "range": "^0.3", + "range": "^0.4", "displayName": "OpenCode for Houdini", "family": "native", "plugin": "neuralnomads.houdini", @@ -86,7 +86,7 @@ "fr": "Lire, modifier et vérifier la scène Houdini ouverte depuis toute conversation OpenCode, avec un panneau facultatif dans Houdini." }, "app": { "name": "Houdini", "versions": ">=21.0" }, - "host": { "protocol": 1, "range": "^0.3.1" }, + "host": { "protocol": 1, "range": "^0.4.0" }, "docs": "https://github.com/NeuralNomadsAI/opencode-integrations/blob/main/integrations/houdini/plugin/README.md", "status": "preview", "sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/houdini/plugin"] } diff --git a/integrations/blender/host/opencode_link/_console_opencode.py b/integrations/blender/host/opencode_link/_console_opencode.py new file mode 100644 index 0000000..94ee6b4 --- /dev/null +++ b/integrations/blender/host/opencode_link/_console_opencode.py @@ -0,0 +1,484 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Blender's OpenCode console language. Workers own the pipes; only the timer touches the UI.""" + +import json +import os +from pathlib import Path +import queue +import re +import subprocess +import sys +import tempfile +import threading +import time +import uuid + +import bpy + +from .opencode_service import panel_launcher, registration_name +from .process import state as process_state + +HELP = "/list /open /new /stop /status /help /allow /reject" +INTERVAL = 0.05 + + +class Lines: + def __init__(self): + self.pending = "" + self.code = False + + def _line(self, text): + if text.lstrip().startswith(("```", "~~~")): + self.code = not self.code + return None + if self.code: + return " " + text + return re.sub(r"^\s{0,3}#{1,6}\s+", "", text).replace("**", "").replace("__", "") + + def feed(self, text, end=False): + parts = (self.pending + text).split("\n") + self.pending = parts.pop() + if end and self.pending: + parts.append(self.pending) + lines = [self._line(line.removesuffix("\r")) for line in parts] + if end: + self.pending, self.code = "", False + return [line for line in lines if line is not None] + + +class Pipes: + def __init__(self, launcher): + self.out = queue.Queue() + self.inbox = queue.Queue() + threading.Thread(target=self._read, args=launcher, daemon=True).start() + + def _read(self, runtime, bun): + def failed(message): + self.out.put({"event": "exit", "data": {"message": message}}) + + script = Path(__file__).with_name("sidecar.cjs") + if not script.is_file(): + return failed("Console sidecar missing. Install the built OpenCode Link add-on.") + env = os.environ.copy() + env.pop("BUN_BE_BUN", None) + if bun: + env["BUN_BE_BUN"] = "1" + try: + proc = subprocess.Popen( + [runtime, str(script)], env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, encoding="utf-8", errors="replace", creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), + ) + except OSError: + return failed("Could not start the OpenCode sidecar runtime.") + + def write(): + with proc.stdin: + try: + while (message := self.inbox.get()) is not None: + proc.stdin.write(json.dumps(message) + "\n") + proc.stdin.flush() + except (OSError, ValueError): + pass + + threading.Thread(target=write, daemon=True).start() + with proc.stdout: + for line in proc.stdout: + try: + self.out.put(json.loads(line)) + except ValueError: + pass + self.inbox.put(None) + proc.wait() + failed("") + + +class Chat: + def __init__(self): + self.pipes = None + self.lines = Lines() + self.permission = {} + self.target = None + self.unsent = [] + self.entries = [] + self.numbered = [] + self.menu_time = 0 + self.redraw = False + self.show_list = False + self.selected = None + self.draft = False + self.active = False + self.problem = "" + self.retry_at = 0 + self.launch_at = time.monotonic() + 5 + self.state, self.agent, self.model = "Connecting", "", "" + + def send(self, method, **params): + request = uuid.uuid4().hex + if self.pipes: + self.pipes.inbox.put({"id": request, "channel": "blender", "method": method, "params": params}) + elif method == "prompt": + self.unsent.append(params) + elif method == "interrupt": + self.unsent.clear() + return request + + def close(self): + if self.pipes is not None: + self.pipes.inbox.put(None) # EOF detaches the conversation, never withdraws the offer. + self.pipes = None + self.__init__() + + def status(self): + name = os.path.basename(bpy.data.filepath) or "Untitled" + if self.problem: + return f"OpenCode | {name} | {self.problem}" + return f"OpenCode | {name} | {self.state} | agent: {self.agent or 'default'} | model: {self.model or 'default'}" + + def blocked(self, message, append): + if message != self.problem: + self.problem = message + if message: + append("INFO", self.status()) + + def sync(self, target): + if target != self.target: + if target and self.target and target["directory"] != self.target["directory"]: + self.unsent.clear() + self.entries = [] + self.numbered = [] + self.selected = None + self.draft = False + self.target = target + self.state, self.agent, self.model = "Connecting", "", "" + self.lines = Lines() + self.permission.clear() + if target is not None: + self.send("connect", **target) + elif self.pipes: + self.send("close") + + def drain(self, append, limit=120): + if not self.pipes: + return + for _ in range(limit): + try: + item = self.pipes.out.get_nowait() + except queue.Empty: + break + self._event(item, append) + if not self.pipes: + break + + def _event(self, item, append): + name, data = item.get("event"), item.get("data", {}) + + def output(text="", end=False): + for line in self.lines.feed(text, end): + append("OUTPUT", line) + + def user(text): + for line in text.splitlines(): + append("INPUT", "> " + line) + + def tool(data): + elapsed = data.get("duration_ms") + duration = "" if elapsed is None else f" ({elapsed / 1000:.2f} s)" + append("INFO", f"Tool: {data.get('name') or 'tool'} — {data['state']}{duration}") + + if name == "exit": + output(end=True) + self.pipes = None + self.state = "Connecting" + self.retry_at = time.monotonic() + 2 + self.blocked(data["message"], append) + elif name == "error": + if self.state == "Connecting": + self.blocked(data["message"], append) + else: + append("ERROR", data["message"]) + elif name == "notice": + append("INFO", data["message"]) + elif name == "session": + self.selected = data["id"] + self.draft = data.get("draft", False) + self.state, self.agent, self.model = "Ready", data.get("agent"), data.get("model") + self.problem = "" + if self.selected: + append("INFO", "Resumed conversation." if data.get("resumed") else "New conversation attached.") + append("INFO", self.status()) + elif name == "history": + self.lines = Lines() + append("CLEAR", "") + for message in data["messages"]: + role, text = message["role"], message["text"] + if role == "user": + user(text) + elif role == "assistant": + output(text, end=True) + elif role == "tool": + tool(message) + else: + append("INFO", text) + elif name == "user_message": + user(data["text"]) + elif name == "conversations": + self.entries = data["entries"] + self.redraw = True + if self.show_list: + self.show_list = False + self.numbered = self.entries + for i, entry in enumerate(self.numbered, 1): + mark = "*" if entry["id"] == data.get("selected") else " " + append("INFO", f"{mark}{i}. {entry['title']}") + if not self.numbered: + append("INFO", "No conversations in this folder yet.") + elif name == "assistant_delta": + output(data["text"]) + elif name == "assistant_end": + output(end=True) + elif name == "tool": + tool(data) + elif name == "status": + self.state = {"busy": "Working", "connecting": "Connecting"}.get(data["state"], "Ready") + if self.state == "Connecting": + output(end=True) + self.permission.clear() + if self.state == "Ready": + output(end=True) + self.permission.clear() + if data.get("interrupted"): + append("INFO", "Interrupted.") + elif name == "agent": + self.agent = data.get("agent") + elif name == "model": + self.model = data.get("selected") + elif name == "profile": + self.agent, self.model = data.get("agent"), data.get("model") + elif name == "permission": + self.permission[data["request_id"]] = data + resources = ", ".join(data["resources"]) + append("INFO", f"Permission requested: {data['action']} {resources} — /allow once or /reject") + elif name == "permission_done": + self.permission.pop(data["request_id"], None) + + +chat = Chat() + + +def _append(kind, text): + if kind == "CLEAR": + bpy.ops.console.clear(scrollback=True, history=False) + else: + bpy.ops.console.scrollback_append(text=text, type=kind) + + +def _areas(): + manager = getattr(bpy.context, "window_manager", None) + for window in manager.windows if manager else (): + for area in window.screen.areas: + if area.type != "CONSOLE" or area.spaces.active.language != "opencode": + continue + region = next((r for r in area.regions if r.type == "WINDOW"), None) + if region is not None: + yield window, area, region + + +def _drain(): + areas = list(_areas()) + chat.active = chat.active or bool(areas) + if not chat.active: + return 0.5 + rows = [] + def append(kind, text): + rows.append((kind, text)) + _sync(append) + chat.drain(append) + if rows or chat.redraw: + for window, area, region in areas: + with bpy.context.temp_override(window=window, area=area, region=region): + for kind, text in rows: + _append(kind, text) + area.tag_redraw() + chat.redraw = False + return INTERVAL + + +def _sync(append): + from .addon import preferences, session + + if time.monotonic() < chat.retry_at: + return + path = bpy.data.filepath + if path: + directory = os.path.dirname(path) + else: + process = process_state() + if not getattr(process, "console_unsaved_folder", None): + process.console_unsaved_folder = tempfile.TemporaryDirectory(prefix="opencode-blender-") + directory = process.console_unsaved_folder.name + host = session() + port, token, handle, label = host.snapshot() if host else (0, None, "", "") + try: + prefs = preferences() + registration = registration_name(prefs.service_name.strip()) if prefs else None + except (ValueError, AttributeError): + chat.sync(None) + return chat.blocked("Invalid OpenCode service name in OpenCode Link preferences.", append) + chat.sync(dict( + host="127.0.0.1", port=port, token=token, script_handle=handle, offer_label=label, + directory=directory, + registration=registration, + )) + if not chat.pipes: + services = host.advertiser.results if host and host.advertiser else [] + waiting = time.monotonic() < chat.launch_at + launcher = panel_launcher(services, "NEURALNOMADS_BLENDER_NODE", wait=waiting) + if launcher[0]: + chat.pipes = Pipes(launcher) + chat.send("connect", **chat.target, session_id=chat.selected, draft=chat.draft) + for params in chat.unsent: + chat.send("prompt", **params) + chat.unsent.clear() + elif not waiting: + chat.blocked("No OpenCode runtime, NEURALNOMADS_BLENDER_NODE executable, or Node on PATH.", append) + + +def execute(context, is_interactive): + del is_interactive + history = context.space_data.history + if not history or not (text := history[-1].body.strip()): + return {"CANCELLED"} + if text.startswith("/"): + _append("INPUT", "> " + text) + bpy.ops.console.history_append(text="", current_character=0, remove_duplicates=True) + chat.active = True + _sync(_append) + if text in ("/help", "/status"): + _append("INFO", HELP if text == "/help" else chat.status()) + elif text == "/list": + if chat.pipes: + chat.show_list = True + chat.send("list") + else: + _append("INFO", chat.status()) + elif text.startswith("/open "): + index = text[6:].strip() + if chat.pipes and index.isascii() and index.isdecimal() and len(index) < 8 and 1 <= int(index) <= len(chat.numbered): + chat.send("open", session_id=chat.numbered[int(index) - 1]["id"]) + else: + _append("INFO", "Use /list, then /open .") + elif text == "/new": + if chat.state == "Ready" and chat.target: + chat.send("new_session", **chat.target) + else: + _append("INFO", "Wait for OpenCode to be ready.") + elif text.startswith("/") and text not in ("/stop", "/allow", "/reject"): + _append("ERROR", "Unknown command. Use /help.") + elif text == "/stop": + chat.send("interrupt") + elif text in ("/allow", "/reject"): + if len(chat.permission) == 1: + request_id = next(iter(chat.permission)) + chat.send("permission_reply", request_id=request_id, reply="once" if text == "/allow" else "reject") + elif chat.permission: + _append("INFO", "Several permissions are pending; review them in OpenCode.") + else: + _append("INFO", "No permission is pending.") + elif chat.state == "Working": + _append("INFO", "OpenCode is working. Wait or use /stop.") + elif chat.target: + chat.send("prompt", text=text) + else: + _append("INFO", chat.status()) + return {"FINISHED"} + + +def autocomplete(context): + return {"CANCELLED"} + + +def copy_as_script(context): + # The Console's fixed menu label says "as Script"; copy this area's visible scrollback as text. + context.window_manager.clipboard = "\n".join(line.body for line in context.space_data.scrollback) + return {"FINISHED"} + + +def banner(context): + chat.active = True + _sync(_append) + context.space_data.prompt = "> " + _append("INFO", HELP) + return {"FINISHED"} + + +def _header(self, context): + if context.space_data.language == "opencode": + selected = next((entry["title"] for entry in chat.entries if entry["id"] == chat.selected), "New conversation") + self.layout.menu("OPENCODE_MT_conversations", text=selected) + + +def _menu_classes(): + # Blender is optional for the pipe/console unit tests. + class OPENCODE_OT_console_conversation(bpy.types.Operator): + bl_idname = "opencode.console_conversation" + bl_label = "Open conversation" + bl_description = "Switch to a conversation in this folder, or start a new one" + session_id: bpy.props.StringProperty() + + def execute(self, _context): + if self.session_id and chat.pipes: + chat.send("open", session_id=self.session_id) + elif chat.state == "Ready" and chat.target: + chat.send("new_session", **chat.target) + return {"FINISHED"} + + class OPENCODE_MT_conversations(bpy.types.Menu): + bl_label = "Conversations" + + def draw(self, _context): + now = time.monotonic() + if chat.pipes and now - chat.menu_time >= 1: + chat.menu_time = now + chat.send("list") + for entry in chat.entries: + item = self.layout.operator( + "opencode.console_conversation", text=entry["title"], + icon="CHECKMARK" if entry["id"] == chat.selected else "NONE", + ) + item.session_id = entry["id"] + self.layout.operator("opencode.console_conversation", text="New conversation", icon="ADD").session_id = "" + + return OPENCODE_OT_console_conversation, OPENCODE_MT_conversations + + +_classes = () + + +def register(): + global _classes + # Blender 5.3 lists loaded _console_* modules (and imports them by this name on Enter). + sys.modules["_console_opencode"] = sys.modules[__name__] + _classes = _menu_classes() + for cls in _classes: + bpy.utils.register_class(cls) + bpy.types.CONSOLE_HT_header.append(_header) + bpy.app.timers.register(_drain, first_interval=0, persistent=True) + + +def unregister(keep_language=False): + global _classes + chat.close() + if bpy.app.timers.is_registered(_drain): + bpy.app.timers.unregister(_drain) + if "_console_opencode" in sys.modules: + bpy.types.CONSOLE_HT_header.remove(_header) + for cls in reversed(_classes): + bpy.utils.unregister_class(cls) + _classes = () + for screen in (() if keep_language else bpy.data.screens): + for area in screen.areas: + for space in area.spaces: + if space.type == "CONSOLE" and space.language == "opencode": + space.language = "python" + space.prompt = ">>> " + sys.modules.pop("_console_opencode") diff --git a/integrations/blender/host/opencode_link/addon.py b/integrations/blender/host/opencode_link/addon.py index 73ded6f..caca67f 100644 --- a/integrations/blender/host/opencode_link/addon.py +++ b/integrations/blender/host/opencode_link/addon.py @@ -15,6 +15,7 @@ from . import advertiser as advertiser_module from . import console +from . import _console_opencode as chat from .blender_app import BlenderApp from .core import HostCore, require_app_version from .process import state as process_state @@ -119,6 +120,7 @@ def pump(seconds, stop=None): _reload_at = None _quit_at = None _quit_requested = False +_reloading = False def schedule_quit(): @@ -159,7 +161,7 @@ def schedule_reload(): def run_pending_reload(): """Disable the add-on, drop its modules and enable it again from disk, which offers the session again: a new listener, token and script handle (references are invalidated), the same offer key.""" - global _reload_at + global _reload_at, _reloading if _reload_at is None: return None _reload_at = None @@ -171,7 +173,11 @@ def run_pending_reload(): return RELOAD_DELAY if _session is not None: process_state().revision = _session.app.revision() - addon_utils.disable(__package__, default_set=False, handle_error=None) + _reloading = True + try: + addon_utils.disable(__package__, default_set=False, handle_error=None) + finally: + _reloading = False for name in [name for name in sys.modules if name == __package__ or name.startswith(__package__ + ".")]: del sys.modules[name] addon_utils.enable(__package__, default_set=False, handle_error=None) @@ -317,6 +323,7 @@ def register(): if bpy.app.background: _start_offer() else: + chat.register() bpy.app.timers.register(_start_offer, first_interval=0.1, persistent=True) @@ -331,6 +338,7 @@ def _start_offer(): def unregister(): global _session + chat.unregister(keep_language=_reloading) console.capture().uninstall() _remove_handlers() if _session is not None: diff --git a/integrations/blender/host/opencode_link/advertiser.py b/integrations/blender/host/opencode_link/advertiser.py index 1dd1919..7fdad16 100644 --- a/integrations/blender/host/opencode_link/advertiser.py +++ b/integrations/blender/host/opencode_link/advertiser.py @@ -42,7 +42,9 @@ def _launch_key(): def offer_label(document): name = (document or "Untitled").replace("/", " ").replace("\\", " ") name = "".join(char for char in name if ord(char) >= 32 and char != "\x7f").strip() or "Untitled" - return ("Blender: %s" % name)[:LABEL_MAX] + # Public selector for the in-app console: two Blender processes can open the same file. + suffix = " [%s]" % os.getpid() + return ("Blender: %s" % name)[:LABEL_MAX - len(suffix)] + suffix class Advertiser(object): diff --git a/integrations/blender/host/opencode_link/blender_manifest.toml b/integrations/blender/host/opencode_link/blender_manifest.toml index b4a1603..d93cf8d 100644 --- a/integrations/blender/host/opencode_link/blender_manifest.toml +++ b/integrations/blender/host/opencode_link/blender_manifest.toml @@ -1,7 +1,7 @@ schema_version = "1.0.0" id = "opencode_link" -version = "0.4.8" +version = "0.5.0" name = "OpenCode Link" tagline = "Lets OpenCode work on this Blender session" maintainer = "NeuralNomads" diff --git a/integrations/blender/host/opencode_link/opencode_service.py b/integrations/blender/host/opencode_link/opencode_service.py index 5354867..41c5eca 100644 --- a/integrations/blender/host/opencode_link/opencode_service.py +++ b/integrations/blender/host/opencode_link/opencode_service.py @@ -29,6 +29,7 @@ import http.client import json import os +import shutil import re import time import urllib.error @@ -194,6 +195,14 @@ def _outcome(method, status, body): return value if status == 200 and value in OUTCOMES[method] else "error" +def panel_runtime(outcome, body): + if outcome in ("accepted", "renewed") and isinstance(body, dict): + runtime = body.get("output", {}).get("panel_runtime") + if isinstance(runtime, str) and os.path.isabs(runtime): + return {"panel_runtime": runtime} + return {} + + def _ready(service, rpc_id, directory, deadline): # Registration is asynchronous on cold Locations. Only the payload-free # status read is repeated; an advertisement/withdrawal is never a probe. @@ -213,6 +222,7 @@ def _each_service(method, rpc_id, payload, service_name, config_dir_setting, env results = [] for service in discover(service_name, env, timeout): outcome = "unavailable" + runtime = {} for directory in location_candidates(config_dir_setting, env): try: deadline = time.monotonic() + timeout @@ -233,11 +243,27 @@ def _each_service(method, rpc_id, payload, service_name, config_dir_setting, env outcome = "unavailable" else: outcome = _outcome(method, status, body) + if method == "advertise": + runtime = panel_runtime(outcome, body) break - results.append({"service": service.file, "outcome": outcome}) + results.append({"service": service.file, "outcome": outcome, **runtime}) return results +def panel_launcher(results, override, wait=False): + """Use the daemon's advertised executable, then the host override, then Node on PATH.""" + for result in results: + runtime = result.get("panel_runtime") + if result.get("outcome") in ("accepted", "renewed") and isinstance(runtime, str) and os.path.isabs(runtime) and shutil.which(runtime): + return runtime, True + if wait and not any(result.get("outcome") in ("accepted", "renewed") for result in results): + return None, False + for candidate in (os.environ.get(override), "node"): + if candidate and (node := shutil.which(candidate)): + return node, False + return None, False + + def advertise_all(rpc_id, offer, service_name=None, config_dir_setting=None, env=None, timeout=TIMEOUT): """Advertise one offer to every discovered service, or to the named one.""" return _each_service("advertise", rpc_id, offer, service_name, config_dir_setting, env, timeout) diff --git a/integrations/blender/host/ops.json b/integrations/blender/host/ops.json index 830d8a8..eebe592 100644 --- a/integrations/blender/host/ops.json +++ b/integrations/blender/host/ops.json @@ -1,6 +1,6 @@ { "addon": "opencode_link", - "version": "0.4.8", + "version": "0.5.0", "protocol": 1, "method": "apply", "wire": "params.operations: [{op, args}] with every op below (an edit batch); unknown ops and fields are refused", diff --git a/integrations/blender/plugin/NOTICE.md b/integrations/blender/plugin/NOTICE.md index 14f2baa..5f2bd2f 100644 --- a/integrations/blender/plugin/NOTICE.md +++ b/integrations/blender/plugin/NOTICE.md @@ -6,5 +6,6 @@ | The fixed programs the plugin runs inside Blender | `programs/` | GPL-3.0-or-later (SPDX header of each file; the GNU GPL version 3 text is the `LICENSE` inside the add-on archive) | | The OpenCode Link add-on, embedded as an archive | `host/blender/opencode_link-.zip` | GPL-3.0-or-later (`LICENSE` inside the archive); some handlers carry GPL-2.0-or-later headers, compatible with it | | Blender Lab's tool code, inside the add-on | `lab/` in the add-on archive | GPL-3.0-or-later, Blender Authors: copied from Blender Lab `blender_mcp` v1.0.3 (commit `2cea8d566dde07fbac28a61d698909d69724e853`), each file with its SPDX lines | +| Console chat's separate Node.js sidecar | `sidecar.cjs` in the add-on archive | MIT (integration kit and OpenCode client; bundled notices retained) | The `license` field of `package.json` is `MIT AND GPL-3.0-or-later`, as the repository's packaging rules require of a package that embeds a GPL-3.0-or-later application part: the plugin's licence and the add-on's. The programs run in Blender's Python like the add-on and share its licence. No Blender documentation is bundled: `blender_inspect` reads the running Blender and links the official documentation of its version. diff --git a/integrations/blender/plugin/README.md b/integrations/blender/plugin/README.md index 94fcdbf..e3fe61d 100644 --- a/integrations/blender/plugin/README.md +++ b/integrations/blender/plugin/README.md @@ -32,6 +32,14 @@ The **Plugins** section lists OpenCode for Blender as an integration: its version, whether the add-on is installed and up to date, and whether the conversation is attached; its menu installs or updates the add-on after a confirmation and detaches the conversation. **Plugins ▸ Add** also accepts the package name. +## Chat in Blender (prototype) + +With OpenCode running and OpenCode Link enabled, open a **Python Console** (`Shift–F4`) and choose **Console → Languages → Opencode**. It connects on its own, even for an unsaved scene, and keeps the current conversation when you open another file in the same folder. Use the conversation menu in the header, or `/list` then `/open `, to switch. **New conversation** (`/new`) stays empty until you send a message. `/stop` interrupts or clears queued messages; `/status` and `/help` are always available. The console uses OpenCode’s executable; Node.js 22+ (`NEURALNOMADS_BLENDER_NODE` or `PATH`) is only a fallback. The add-on preferences can target a named OpenCode service. + +The Console wraps lines and keeps its own Up-arrow history. An unfinished line appears when the stream finishes or the next newline arrives. **Copy as Script** copies this area's scrollback as plain text, not executable Python. Earlier messages stay in OpenCode when you reconnect; they are not replayed into Blender. `/allow` approves a single pending OpenCode permission once; `/reject` declines it. Use OpenCode to handle questions or multiple pending approvals. + +CodeNomad can stay attached separately. Blender cannot repaint or accept console input while a main-thread Python operation or bake is running. Output queues and appears once the main thread is free; `/stop` does not preempt Python already running in Blender. + ## How it works - **Discovery and consent.** While OpenCode Link is enabled, the add-on listens on `127.0.0.1` on a random port with a random 256-bit token kept in memory, and offers the session to every OpenCode service registered for your user (or to one: the add-on setting _OpenCode service_). Offers last 15 seconds and are renewed every 5 seconds. diff --git a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip b/integrations/blender/plugin/host/blender/opencode_link-0.5.0.zip similarity index 85% rename from integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip rename to integrations/blender/plugin/host/blender/opencode_link-0.5.0.zip index 03b5163..df44c70 100644 Binary files a/integrations/blender/plugin/host/blender/opencode_link-0.4.8.zip and b/integrations/blender/plugin/host/blender/opencode_link-0.5.0.zip differ diff --git a/integrations/blender/plugin/package.json b/integrations/blender/plugin/package.json index 849e5d0..2ff581e 100644 --- a/integrations/blender/plugin/package.json +++ b/integrations/blender/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@neuralnomads/opencode-blender", - "version": "0.4.8", + "version": "0.5.0", "description": "OpenCode for Blender: lets OpenCode read and change an open Blender scene through an authenticated local host, with typed edits, inspection, verification renders and background renders.", "license": "MIT AND GPL-3.0-or-later", "type": "module", @@ -47,6 +47,7 @@ } }, "devDependencies": { + "@opencode/client": "2.2.5", "@opencode/plugin": "2.2.5", "esbuild": "0.28.2" }, @@ -60,10 +61,10 @@ "host": { "app": "blender", "protocol": 1, - "range": "^0.4.8", + "range": "^0.5.0", "appVersions": ">=5.3", - "payload": "host/blender/opencode_link-0.4.8.zip", - "sha256": "d5b94052efdc503c2cd3e3ff183913733b22a52d9765a5e06e03d17d5f95a01b" + "payload": "host/blender/opencode_link-0.5.0.zip", + "sha256": "b8ce9b3bd4dc89b4d94003ea1d04e7ea59af5724ab2f60e16d513b481bc3cf50" } } } diff --git a/integrations/blender/plugin/scripts/host-payload.ts b/integrations/blender/plugin/scripts/host-payload.ts index e93cad8..0243b18 100644 --- a/integrations/blender/plugin/scripts/host-payload.ts +++ b/integrations/blender/plugin/scripts/host-payload.ts @@ -6,22 +6,15 @@ import { createHash } from "node:crypto" import { readdirSync, readFileSync } from "node:fs" import { join, relative, sep } from "node:path" import { fileURLToPath } from "node:url" +import { buildSync } from "esbuild" import { writeStoredZip } from "../src/zip.ts" export const pluginRoot = fileURLToPath(new URL("..", import.meta.url)) +const repoRoot = join(pluginRoot, "..", "..", "..") export const hostRoot = join(pluginRoot, "..", "host") export const addonRoot = join(hostRoot, "opencode_link") -export const kitServicePath = join( - pluginRoot, - "..", - "..", - "..", - "packages", - "integration-kit", - "python", - "opencode_service.py", -) +export const kitServicePath = join(repoRoot, "packages", "integration-kit", "python", "opencode_service.py") function walk(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }) @@ -50,9 +43,26 @@ export function payloadEntries(): Array<{ name: string; data: Buffer }> { .map((file) => relative(addonRoot, file).split(sep).join("/")) .filter((name) => !name.split("/").includes("__pycache__") && !name.endsWith(".pyc")) if (!files.includes("opencode_service.py")) files.push("opencode_service.py") - return files.sort().map((name) => ({ + const sidecar = buildSync({ + absWorkingDir: repoRoot, + entryPoints: [join(pluginRoot, "src", "sidecar.ts")], + preserveSymlinks: true, + bundle: true, + format: "cjs", + platform: "node", + target: "node22", + write: false, + legalComments: "eof", + }).outputFiles[0] + if (!sidecar) throw new Error("No Blender console sidecar was built") + return [...files, "sidecar.cjs"].sort().map((name) => ({ name, - data: name === "opencode_service.py" ? serviceBytes() : lf(readFileSync(join(addonRoot, name))), + data: + name === "sidecar.cjs" + ? Buffer.from(sidecar.contents) + : name === "opencode_service.py" + ? serviceBytes() + : lf(readFileSync(join(addonRoot, name))), })) } diff --git a/integrations/blender/plugin/src/console-panel.ts b/integrations/blender/plugin/src/console-panel.ts new file mode 100644 index 0000000..5df56ff --- /dev/null +++ b/integrations/blender/plugin/src/console-panel.ts @@ -0,0 +1,12 @@ +import type { PanelHost } from "../../../../packages/integration-kit/src/panel.ts" + +export const blenderPanel = { + app: "Blender", + rpcID: "neuralnomads.blender", + document: "document", + duplicateOffer: "Blender instances", + agent: true, + consoleEvents: true, + // Blender has no session-specific cancel/resume host methods. Interrupt the agent via OpenCode only. + hostControls: false, +} satisfies PanelHost diff --git a/integrations/blender/plugin/src/sidecar.ts b/integrations/blender/plugin/src/sidecar.ts new file mode 100644 index 0000000..989cd11 --- /dev/null +++ b/integrations/blender/plugin/src/sidecar.ts @@ -0,0 +1,4 @@ +import { runPanel } from "../../../../packages/integration-kit/src/panel-pipes.ts" +import { blenderPanel } from "./console-panel.ts" + +runPanel(blenderPanel) diff --git a/integrations/blender/test/console-chat.test.ts b/integrations/blender/test/console-chat.test.ts new file mode 100644 index 0000000..c3912a4 --- /dev/null +++ b/integrations/blender/test/console-chat.test.ts @@ -0,0 +1,182 @@ +import assert from "node:assert/strict" +import { spawnSync } from "node:child_process" +import { join } from "node:path" +import { it } from "node:test" +import { type Api, createPanel } from "../../../packages/integration-kit/src/panel.ts" +import { blenderPanel } from "../plugin/src/console-panel.ts" + +it("formats and fans out streamed lines in the Blender timer without bpy", () => { + const python = process.env.PYTHON ?? (process.platform === "win32" ? "python" : "python3") + const result = spawnSync(python, ["-I", join(import.meta.dirname, "console_chat_test.py")], { + encoding: "utf8", + windowsHide: true, + }) + assert.equal(result.status, 0, result.error?.message ?? result.stderr) +}) + +it("the sidecar resumes a folder conversation and streams wrapped tool names and interruption", async () => { + const calls: unknown[] = [] + const out: unknown[] = [] + const bindings = new Map([["ses_codenomad", "offer_here"]]) + const location = { directory: import.meta.dirname } + const session = { + id: "ses_console", + agent: "build", + time: { updated: 2 }, + model: { providerID: "ok", id: "model", variant: "default" }, + } + let push: (value: unknown) => void = () => {} + const api = { + rpc: (rpc: { id: string }) => { + assert.equal(rpc.id, "neuralnomads.blender") + return { + hosts: async () => ({ offers: [{ label: "Blender: test.blend [10]", offerID: "offer_here" }] }), + attachHost: async ({ offerID, sessionID }: { offerID: string; sessionID: string }) => { + bindings.set(sessionID, offerID) + return { outcome: "attached" } + }, + bindingRead: async ({ sessionID }: { sessionID: string }) => ({ + state: "attached", + binding: { offerID: bindings.get(sessionID) }, + }), + detachHost: async ({ sessionID }: { sessionID: string }) => bindings.delete(sessionID), + } + }, + session: { + list: async () => ({ data: [{ id: "ses_codenomad" }, session], cursor: {} }), + create: async () => assert.fail("Should resume the marked conversation"), + active: async () => ({}), + prompt: async (value: unknown) => calls.push(value), + interrupt: async (value: unknown) => calls.push(value), + }, + message: { + list: async (input: unknown) => { + assert.deepEqual(input, { sessionID: session.id, order: "desc", limit: 21 }) + return { + data: [ + { + type: "assistant", + content: [ + { + type: "tool", + name: "execute", + state: { status: "completed", input: { code: 'return search("context")' } }, + }, + { + type: "tool", + name: "execute", + state: { status: "completed", input: { code: "return tools.blender.context({})" } }, + }, + { type: "text", text: "Scene read." }, + ], + }, + ...Array.from({ length: 20 }, (_, i) => ({ type: "user", text: `Question ${i + 1}` })), + ], + } + }, + }, + model: { list: async () => ({ data: [] }), default: async () => ({ data: { providerID: "ok", id: "model" } }) }, + event: { + subscribe: async function* ({ signal }: { signal: AbortSignal }) { + while (!signal.aborted) { + const item = await new Promise((resolve) => { + const abort = () => resolve(undefined) + signal.addEventListener("abort", abort, { once: true }) + push = (value) => { + signal.removeEventListener("abort", abort) + resolve(value) + } + }) + if (item) yield item + } + }, + }, + } as unknown as Api + + const panel = createPanel(blenderPanel, { + discover: async (registration) => { + assert.equal(registration, "service-example.json") + return api + }, + send: (event) => out.push(event), + requestHost: async (...args) => { + calls.push(args) // Blender has no session-specific host cancel/resume. + return {} + }, + }) + const call = (method: string, params?: Record) => + panel.dispatch({ method, params, id: method, channel: "blender" }) + const event = (name: string, data: object) => ({ channel: "blender", event: name, data }) + const emit = async (type: string, data: object, sessionID = session.id) => { + push({ type, data: { sessionID, ...data } }) + await new Promise((resolve) => setImmediate(resolve)) + } + + try { + await call("connect", { + ...location, + host: "127.0.0.1", + port: 4242, + token: "a".repeat(64), + script_handle: "blend-test", + offer_label: "Blender: test.blend [10]", + document_key: "test.blend", + registration: "service-example.json", + }) + assert.ok(out.some((item) => JSON.stringify(item).includes('"resumed":true'))) + assert.ok(out.some((item) => JSON.stringify(item).includes('"model":"ok/model"'))) + assert.equal(bindings.get(session.id), "offer_here") + const recent = ( + out.find((item) => (item as { event?: string }).event === "history") as { + data: { messages: unknown[] } + } + ).data.messages + assert.deepEqual(recent[0], { role: "system", text: "Earlier messages are available in OpenCode." }) + assert.deepEqual(recent[1], { role: "user", text: "Question 19" }) + assert.deepEqual(recent.slice(-3), [ + { role: "user", text: "Question 1" }, + { role: "tool", text: "blender_context / completed", name: "blender_context", state: "completed" }, + { role: "assistant", text: "Scene read." }, + ]) + out.length = 0 + await call("prompt", { text: "hello" }) + await emit("session.text.delta", { delta: "not ours" }, "ses_codenomad") + await emit("session.text.delta", { delta: "hello\n" }) + await emit("session.tool.input.started", { id: "tool_1", name: "blender_context" }) + await emit("session.tool.success", { id: "tool_1" }) + await emit("session.tool.input.started", { id: "lookup", name: "execute" }) + await emit("session.tool.called", { id: "lookup", input: { code: 'return search({ namespace: "blender" })' } }) + await emit("session.tool.success", { id: "lookup" }) + await emit("session.tool.input.started", { id: "tool_2", name: "execute" }) + await emit("session.tool.called", { id: "tool_2", input: { code: "await tools.blender.context({})" } }) + await emit("session.tool.success", { id: "tool_2" }) + await call("interrupt") + await emit("session.execution.interrupted", {}) + assert.deepEqual(out.slice(0, 4), [ + event("user_message", { text: "hello" }), + { id: "prompt", result: {} }, + event("assistant_delta", { text: "hello\n" }), + event("tool", { id: "tool_1", name: "blender_context", state: "starting" }), + ]) + const completed = out[4] as { data: { name: string; state: string; duration_ms: number } } + assert.equal(completed.data.name, "blender_context") + assert.equal(completed.data.state, "completed") + assert.ok(completed.data.duration_ms >= 0) + assert.equal((out[5] as typeof completed).data.name, "blender_context") + assert.equal((out[6] as typeof completed).data.name, "blender_context") + assert.equal( + out.some((item) => JSON.stringify(item).includes('"name":"execute"')), + false, + ) + assert.deepEqual(out.at(-1), event("status", { state: "idle", interrupted: true })) + await emit("session.step.started", { model: { providerID: "ok", id: "model", variant: "high" } }) + assert.deepEqual(out.at(-1), event("profile", { agent: undefined, model: "ok/model#high" })) + assert.deepEqual(calls, [ + { sessionID: session.id, text: "hello" }, + { sessionID: session.id, resume: false }, + ]) + } finally { + await panel.closeAll() + } + assert.deepEqual([...bindings], [["ses_codenomad", "offer_here"]]) +}) diff --git a/integrations/blender/test/console_chat_test.py b/integrations/blender/test/console_chat_test.py new file mode 100644 index 0000000..dfcec39 --- /dev/null +++ b/integrations/blender/test/console_chat_test.py @@ -0,0 +1,103 @@ +"""Run without Blender: python integrations/blender/test/console_chat_test.py.""" + +from contextlib import contextmanager +from pathlib import Path +from queue import Queue +import sys +from types import SimpleNamespace as NS +import unittest + +sys.modules["bpy"] = NS() +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "host")) +from opencode_link import _console_opencode as console + + +class ConsoleTests(unittest.TestCase): + def test_banner_reports_ready_once_with_model(self): + console.bpy.data = NS(filepath="/project/shot.blend") + chat = console.Chat() + rows = [] + append = lambda kind, text: rows.append((kind, text)) + chat._event({"event": "session", "data": {"id": None}}, append) + self.assertEqual(rows, []) + chat._event({"event": "session", "data": {"id": "ses_shot", "model": "provider/model"}}, append) + self.assertEqual(rows, [ + ("INFO", "New conversation attached."), + ("INFO", "OpenCode | shot.blend | Ready | agent: default | model: provider/model"), + ]) + + def test_lines(self): + lines = console.Lines() + self.assertEqual(lines.feed("## Heading\r\n**hel"), ["Heading"]) + self.assertEqual(lines.feed("lo**\n``"), ["hello"]) + self.assertEqual(lines.feed("`py\nx = '**'\n```\nTail"), [" x = '**'"]) + self.assertEqual(lines.feed("", end=True), ["Tail"]) + self.assertEqual(lines.feed("## prose\n"), ["prose"]) + + def test_history_clears_and_uses_live_formats(self): + chat = console.Chat() + rows = [] + append = lambda kind, text: rows.append((kind, text)) + chat._event({"event": "assistant_delta", "data": {"text": "stale"}}, append) + chat._event({"event": "history", "data": {"messages": [ + {"role": "user", "text": "Read the scene."}, + {"role": "tool", "text": "blender_context / completed", "name": "blender_context", "state": "completed"}, + {"role": "assistant", "text": "**Done.**"}, + ]}}, append) + chat._event({"event": "assistant_delta", "data": {"text": "Live reply\n"}}, append) + self.assertEqual(rows, [ + ("CLEAR", ""), + ("INPUT", "> Read the scene."), + ("INFO", "Tool: blender_context — completed"), + ("OUTPUT", "Done."), + ("OUTPUT", "Live reply"), + ]) + + def test_timer_broadcasts_complete_lines_only_to_opencode_areas(self): + context = console.bpy.context = NS() + + @contextmanager + def override(**values): + context.area = values["area"] + yield + + def area(language): + result = NS(type="CONSOLE", spaces=NS(active=NS(language=language)), rows=[], + regions=[NS(type="WINDOW")], redraws=0) + result.tag_redraw = lambda: setattr(result, "redraws", result.redraws + 1) + return result + + first, second, python = area("opencode"), area("opencode"), area("python") + context.window_manager = NS(windows=[NS(screen=NS(areas=[first, python])), NS(screen=NS(areas=[second]))]) + context.temp_override = override + console.bpy.ops = NS(console=NS(scrollback_append=lambda **row: context.area.rows.append(row))) + chat = console.chat = console.Chat() + chat.pipes = NS(out=Queue(), inbox=Queue()) + chat.state = "Working" + console._sync = lambda append: None + + def add(event, **data): + chat.pipes.out.put({"event": event, "data": data}) + + add("assistant_delta", text="first\npar") + self.assertEqual(console._drain(), console.INTERVAL) + self.assertEqual(first.rows, [{"text": "first", "type": "OUTPUT"}]) + add("assistant_delta", text="tial") + add("tool", name="blender_context", state="completed", duration_ms=258) + add("assistant_end") + console._drain() + self.assertEqual(first.rows[-2:], [ + {"text": "Tool: blender_context — completed (0.26 s)", "type": "INFO"}, + {"text": "partial", "type": "OUTPUT"}, + ]) + self.assertEqual(second.rows, first.rows) + self.assertEqual(first.redraws, 2) + self.assertEqual(python.rows, []) + add("exit", message="") + self.assertEqual(console._drain(), console.INTERVAL) + self.assertIsNone(chat.pipes) + self.assertEqual(chat.state, "Connecting") + + +if __name__ == "__main__": + unittest.main() diff --git a/integrations/blender/test/e2e.test.ts b/integrations/blender/test/e2e.test.ts index 2b4eb2e..90c2ebd 100644 --- a/integrations/blender/test/e2e.test.ts +++ b/integrations/blender/test/e2e.test.ts @@ -49,7 +49,7 @@ describe("OpenCode 2.2.5 service with a background Blender", { skip }, () => { return listed.offers.length > 0 ? listed.offers : undefined }) assert.equal(offers.length, 1) - assert.equal(offers[0]?.label, "Blender: Untitled") + assert.match(offers[0]?.label ?? "", /^Blender: Untitled \[\d+\]$/) assert.equal(offers[0]?.protocol, "ok") assert.deepEqual(await rpc("attachHost", { offerID: offers[0]?.offerID, sessionID: session.id }), { outcome: "attached", diff --git a/integrations/blender/test/native-session-bindings.test.ts b/integrations/blender/test/native-session-bindings.test.ts index 81584be..91a8eb3 100644 --- a/integrations/blender/test/native-session-bindings.test.ts +++ b/integrations/blender/test/native-session-bindings.test.ts @@ -2,7 +2,7 @@ // Run after build with OPENCODE_TEST_BIN; this service has private config, state and credentials. import assert from "node:assert/strict" import { mkdirSync } from "node:fs" -import { join } from "node:path" +import { isAbsolute, join } from "node:path" import { it } from "node:test" import { startFakeHost } from "../../../packages/testing/src/index.ts" @@ -93,7 +93,9 @@ it("native exact-session binding: two Locations, move, delete, revocation and se assert.deepEqual(await read(a, "ses_native_missing"), { state: "unknown" }) const offer = announcement(host.endpoint, host.scriptHandle) - assert.deepEqual(await rpc(a, "advertise", offer), { outcome: "accepted" }) + const advertised = await rpc(a, "advertise", offer) + assert.equal(advertised.outcome, "accepted") + assert.ok(isAbsolute(advertised.panel_runtime)) const offerID = (await rpc(b, "hosts")).offers[0].offerID assert.deepEqual(await rpc(a, "attachHost", { offerID, sessionID: second.id }), { outcome: "refused" }) assert.deepEqual(await rpc(a, "attachHost", { offerID, sessionID: first.id }), { outcome: "attached" }) @@ -121,6 +123,7 @@ it("native exact-session binding: two Locations, move, delete, revocation and se const beforeLabel = await read(b, second.id) assert.deepEqual(await rpc(a, "advertise", { ...offer, label: "Blender: native renamed.blend" }), { + ...advertised, outcome: "renewed", }) const renamed = await read(b, second.id) diff --git a/integrations/blender/test/plugin.test.ts b/integrations/blender/test/plugin.test.ts index b320b9a..1931392 100644 --- a/integrations/blender/test/plugin.test.ts +++ b/integrations/blender/test/plugin.test.ts @@ -855,7 +855,7 @@ describe("tools", () => { const other = await plugin() await other.rpc("advertise", announcement(old.endpoint, old.scriptHandle)) other.registry.attach(other.registry.hosts().offers[0]?.offerID as string, "ses_test") - await assert.rejects(other.tool("blender_context"), /no scene method: install OpenCode Link 0\.4\.8/) + await assert.rejects(other.tool("blender_context"), /no scene method: install OpenCode Link 0\.5\.0/) assert.ok(loaded) }) }) diff --git a/integrations/blender/test/publication.test.ts b/integrations/blender/test/publication.test.ts index 45aec3b..f9e898a 100644 --- a/integrations/blender/test/publication.test.ts +++ b/integrations/blender/test/publication.test.ts @@ -6,7 +6,7 @@ test("only Blender is publishable, with public access and trusted-publishing met const plugin = new URL("../plugin/", import.meta.url) const pkg = JSON.parse(readFileSync(new URL("package.json", plugin), "utf8")) assert.equal(pkg.name, "@neuralnomads/opencode-blender") - assert.equal(pkg.version, "0.4.8") + assert.equal(pkg.version, "0.5.0") assert.equal(pkg.private, undefined) assert.equal(pkg.publishConfig.access, "public") assert.equal(pkg.repository.url, "https://github.com/NeuralNomadsAI/opencode-integrations") diff --git a/integrations/gaffer/host/manifest.json b/integrations/gaffer/host/manifest.json index 9992a34..3cacd42 100644 --- a/integrations/gaffer/host/manifest.json +++ b/integrations/gaffer/host/manifest.json @@ -1 +1 @@ -{ "name": "OpenCode Link for Gaffer", "version": "0.3.0", "protocol": 1, "license": "MIT" } +{ "name": "OpenCode Link for Gaffer", "version": "0.4.0", "protocol": 1, "license": "MIT" } diff --git a/integrations/gaffer/host/python/GafferOpenCode/Advertiser.py b/integrations/gaffer/host/python/GafferOpenCode/Advertiser.py index ce50907..6ab4e1b 100644 --- a/integrations/gaffer/host/python/GafferOpenCode/Advertiser.py +++ b/integrations/gaffer/host/python/GafferOpenCode/Advertiser.py @@ -104,12 +104,13 @@ def __renew( self, offers ) : results, failed = [], False for name, ( service, directory ) in targets.items() : for offer in offers : + body = None try : status, body = opencode_service.call( service, RPC_ID, "advertise", offer, directory, RENEW_TIMEOUT ) outcome = opencode_service._outcome( "advertise", status, body ) except ( OSError, ValueError ) : outcome = "error" - results.append( { "service" : name, "label" : offer["label"], "outcome" : outcome } ) + results.append( { "service" : name, "label" : offer["label"], "outcome" : outcome, **opencode_service.panel_runtime( outcome, body ) } ) failed = failed or outcome not in ( "accepted", "renewed" ) if not failed : return results @@ -128,21 +129,21 @@ def __renew( self, offers ) : if opencode_service._unavailable( status, body ) : continue if status != 200 : - outcomes = [ ( offer, "error" ) for offer in offers ] + outcomes = [ ( offer, "error", None ) for offer in offers ] else : for offer in offers : try : status, body = opencode_service.call( service, RPC_ID, "advertise", offer, directory, max( 0.5, deadline - time.monotonic() ) ) - outcomes.append( ( offer, opencode_service._outcome( "advertise", status, body ) ) ) + outcomes.append( ( offer, opencode_service._outcome( "advertise", status, body ), body ) ) except ( OSError, ValueError ) : - outcomes.append( ( offer, "error" ) ) + outcomes.append( ( offer, "error", None ) ) except ( OSError, ValueError ) : - outcomes = [ ( offer, "error" ) for offer in offers ] - for offer, outcome in outcomes : - results.append( { "service" : service.file, "label" : offer["label"], "outcome" : outcome } ) - if any( outcome in ( "accepted", "renewed" ) for _, outcome in outcomes ) : + outcomes = [ ( offer, "error", None ) for offer in offers ] + for offer, outcome, body in outcomes : + results.append( { "service" : service.file, "label" : offer["label"], "outcome" : outcome, **opencode_service.panel_runtime( outcome, body ) } ) + if any( outcome in ( "accepted", "renewed" ) for _, outcome, _ in outcomes ) : found[service.file] = ( service, directory ) break else : diff --git a/integrations/gaffer/host/python/GafferOpenCode/__init__.py b/integrations/gaffer/host/python/GafferOpenCode/__init__.py index 631d140..fa37df2 100644 --- a/integrations/gaffer/host/python/GafferOpenCode/__init__.py +++ b/integrations/gaffer/host/python/GafferOpenCode/__init__.py @@ -105,6 +105,11 @@ def offerInfo( script ) : return { "label" : label, "offer_key" : key, "advertising" : __advertiser is not None } +def panelServices() : + + return __advertiser.results if __advertiser is not None else [] + + def scriptHandle( script ) : if __host is None : diff --git a/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py b/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py index 2e1cb38..7e48849 100644 --- a/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py +++ b/integrations/gaffer/host/python/GafferOpenCodeUI/Client.py @@ -1,12 +1,13 @@ import json -import os import pathlib -import shutil +import time import uuid import weakref from Qt import QtCore +from GafferOpenCode import panelServices + class ClientProcess : @@ -29,10 +30,15 @@ def __init__( self ) : self.__process.finished.connect( self.__finished ) self.__process.errorOccurred.connect( self.__processError ) self.__channels = {} + self.__targets = {} self.__pending = [] self.__stdout = b"" self.__nextRequest = 0 - self.__start() + self.__problem = "" + self.__launchAt = time.monotonic() + 5 + self.__timer = QtCore.QTimer( self.__process ) + self.__timer.timeout.connect( self.__start ) + self.__timer.start( 1000 ) ## One panel's events; the callback is held weakly. def register( self, callback ) : @@ -51,18 +57,28 @@ def close( self, channel ) : return self.send( channel, "close", {} ) self.__channels.pop( channel, None ) + self.__targets.pop( channel, None ) + self.__pending = [item for item in self.__pending if item[0] != channel] def send( self, channel, method, params ) : - message = self.__message( channel, method, params ) + if method in ( "connect", "new_session" ) : + previous = self.__targets.get( channel, {} ) + if method == "new_session" or previous.get( "directory" ) != params.get( "directory" ) : + self.__pending = [item for item in self.__pending if item[0] != channel] + else : + params = { **params, "session_id" : previous.get( "session_id" ), "draft" : previous.get( "draft", False ) } + self.__targets[channel] = params if self.__process.state() == QtCore.QProcess.Running : - self.__process.write( message ) - else : + self.__process.write( self.__message( channel, method, params ) ) + elif method not in ( "connect", "new_session", "close" ) : + if method == "interrupt" : + self.__pending = [item for item in self.__pending if item[0] != channel or item[1] != "prompt"] if len( self.__pending ) >= 100 : self.__emit( channel, "error", { "message" : "OpenCode sidecar request queue is full" } ) return - self.__pending.append( message ) - self.__start() + self.__pending.append( ( channel, method, params ) ) + self.__start() def __message( self, channel, method, params ) : @@ -76,39 +92,55 @@ def __message( self, channel, method, params ) : def __start( self ) : - if self.__process.state() != QtCore.QProcess.NotRunning : - return - node = os.environ.get( "NEURALNOMADS_GAFFER_NODE" ) or shutil.which( "node" ) - if not node : - self.__pending = [] - self.__emitAll( "error", { "message" : "Install Node.js 22 or set NEURALNOMADS_GAFFER_NODE" } ) + if not self.__targets or self.__process.state() != QtCore.QProcess.NotRunning : return # Built into the installed part, beside the Python packages. sidecar = pathlib.Path( __file__ ).resolve().parents[2] / "sidecar.cjs" if not sidecar.is_file() : - self.__pending = [] - self.__emitAll( "error", { "message" : "OpenCode Link sidecar is missing; reinstall the application part." } ) + self.__blocked( "OpenCode Link sidecar is missing; reinstall the application part." ) + return + from GafferOpenCode.opencode_service import panel_launcher + + services = panelServices() + waiting = time.monotonic() < self.__launchAt + runtime, bun = panel_launcher( services, "NEURALNOMADS_GAFFER_NODE", wait = waiting ) + if not runtime : + if not waiting : + self.__blocked( "No OpenCode runtime, NEURALNOMADS_GAFFER_NODE executable, or Node on PATH." ) return - self.__process.setProgram( node ) + environment = QtCore.QProcessEnvironment.systemEnvironment() + environment.remove( "BUN_BE_BUN" ) + if bun : + environment.insert( "BUN_BE_BUN", "1" ) + self.__process.setProcessEnvironment( environment ) + self.__process.setProgram( runtime ) self.__process.setArguments( [ str( sidecar ) ] ) self.__process.setWorkingDirectory( str( sidecar.parent.parent ) ) self.__process.start() + def __blocked( self, message ) : + + if message != self.__problem : + self.__problem = message + self.__emitAll( "error", { "message" : message } ) + def __started( self ) : pending = self.__pending self.__pending = [] - for message in pending : - self.__process.write( message ) + self.__problem = "" + for channel, params in self.__targets.items() : + self.__process.write( self.__message( channel, "connect", params ) ) + for channel, method, params in pending : + self.__process.write( self.__message( channel, method, params ) ) def __finished( self, exitCode, unusedExitStatus ) : - self.__pending = [] - self.__emitAll( "error", { "message" : "OpenCode sidecar stopped with exit code " + str( exitCode ) } ) + self.__stdout = b"" + self.__emitAll( "status", { "state" : "connecting" } ) def __processError( self, unusedError ) : - self.__pending = [] self.__emitAll( "error", { "message" : "OpenCode sidecar process error: " + self.__process.errorString() } ) def __readStdout( self ) : @@ -126,8 +158,10 @@ def __readStdout( self ) : continue channel = message.get( "channel" ) if channel and message.get( "event" ) : + if message["event"] == "session" and channel in self.__targets : + self.__targets[channel] = { **self.__targets[channel], "session_id" : message["data"]["id"], "draft" : message["data"].get( "draft", False ) } self.__emit( channel, message["event"], message.get( "data" ) or {} ) - elif message.get( "error" ) : + elif message.get( "error" ) and not message.get( "id" ) : self.__emitAll( "error", message["error"] ) def __readStderr( self ) : diff --git a/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py b/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py index 339c6ec..eea4cc2 100644 --- a/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py +++ b/integrations/gaffer/host/python/GafferOpenCodeUI/OpenCodeEditor.py @@ -1,5 +1,4 @@ import functools -import hashlib import os import pathlib import weakref @@ -32,8 +31,9 @@ def __init__( self, scriptNode, **kw ) : self.__header = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 6 ) self.__brand = GafferUI.Label( "OpenCode for Gaffer" ) self.__brand._qtWidget().setObjectName( "gafferOpenCodeBrand" ) - self.__sessionLabel = GafferUI.Label( "SESSION disconnected" ) - self.__sessionLabel._qtWidget().setObjectName( "gafferOpenCodeSession" ) + self.__conversations = [] + self.__selected = None + self.__conversationButton = GafferUI.MenuButton( "New conversation", menu = GafferUI.Menu( Gaffer.WeakMethod( self.__conversationMenu ) ) ) self.__models = [] self.__model = "" self.__modelButton = GafferUI.MenuButton( @@ -41,18 +41,13 @@ def __init__( self, scriptNode, **kw ) : menu = GafferUI.Menu( Gaffer.WeakMethod( self.__modelMenuDefinition ), title = "Model" ), ) self.__modelButton.setEnabled( False ) - self.__newButton = GafferUI.Button( "New" ) - self.__newButton.setEnabled( False ) - self.__connectButton = GafferUI.Button( "Connect" ) self.__header.append( self.__brand ) - self.__header.append( self.__sessionLabel ) self.__header.append( GafferUI.Spacer( imath.V2i( 1 ), maximumSize = imath.V2i( 100000, 1 ) ), expand = True ) - self.__statusLabel = GafferUI.Label( "DISCONNECTED" ) + self.__statusLabel = GafferUI.Label( "CONNECTING" ) self.__statusLabel._qtWidget().setObjectName( "gafferOpenCodeStatus" ) self.__header.append( self.__statusLabel ) self.__header.append( self.__modelButton ) - self.__header.append( self.__newButton ) - self.__header.append( self.__connectButton ) + self.__header.append( self.__conversationButton ) self.__column.append( self.__header ) self.__transcript = GafferUI.MultiLineTextWidget( @@ -81,7 +76,7 @@ def __init__( self, scriptNode, **kw ) : wrapMode = GafferUI.MultiLineTextWidget.WrapMode.Word, ) self.__sendButton = GafferUI.Button( "Send" ) - self.__sendButton.setEnabled( False ) + self.__sendButton.setEnabled( True ) self.__stopButton = GafferUI.Button( "Stop" ) self.__stopButton.setEnabled( False ) self.__promptRow.append( self.__prompt, expand = True ) @@ -97,8 +92,6 @@ def __init__( self, scriptNode, **kw ) : "#gafferOpenCodeTranscript { border-top: 1px solid #34393e; border-bottom: 1px solid #34393e; }" ) - self.__newButton.clickedSignal().connect( Gaffer.WeakMethod( self.__newSession ) ) - self.__connectButton.clickedSignal().connect( Gaffer.WeakMethod( self.__toggleConnection ) ) self.__sendButton.clickedSignal().connect( Gaffer.WeakMethod( self.__send ) ) self.__stopButton.clickedSignal().connect( Gaffer.WeakMethod( self.__stop ) ) self.__allowButton.clickedSignal().connect( Gaffer.WeakMethod( self.__allow ) ) @@ -112,14 +105,18 @@ def __init__( self, scriptNode, **kw ) : # panel is open; the panel only attaches its own conversation to that offer. self.__client = None self.__channel = None - self.__active = False self.__connected = False if not GafferOpenCode.scriptHandle( scriptNode ) : raise RuntimeError( "OpenCodeEditor requires a ScriptNode registered with the Gaffer application" ) - self.__scriptKey = self.__currentScriptKey() self.__scriptConnections = [ scriptNode.plugSetSignal().connect( Gaffer.WeakMethod( self.__scriptPlugSet ), scoped = True ), ] + GafferOpenCode.acquirePanel( self.__ensureChannel() ) + self.__target = None + self.__sync() + self.__timer = QtCore.QTimer( self._qtWidget() ) + self.__timer.timeout.connect( Gaffer.WeakMethod( self.__sync ) ) + self.__timer.start( 500 ) def __repr__( self ) : @@ -142,50 +139,18 @@ def __ensureChannel( self ) : weakref.finalize( self, OpenCodeEditor.__release, self.__client, self.__channel ) return self.__channel - def __toggleConnection( self, unusedButton = None ) : - - if self.__active : - self.__disconnect() - else : - self.__connect( "connect" ) - - def __connect( self, method ) : - + def __sync( self ) : params = self.__connectParams() - if params is None : - return - channel = self.__ensureChannel() - GafferOpenCode.acquirePanel( channel ) - self.__active = True - self.__connected = False - self.__connectButton.setText( "Disconnect" ) - self.__newButton.setEnabled( True ) - self.__statusLabel.setText( "CONNECTING" ) - self.__sendButton.setEnabled( False ) - self.__client.send( channel, method, params ) - - def __disconnect( self ) : - - self.__active = False - self.__connected = False - if self.__channel is not None : - self.__client.send( self.__channel, "close", {} ) - GafferOpenCode.releasePanel( self.__channel ) - self.__connectButton.setText( "Connect" ) - self.__statusLabel.setText( "DISCONNECTED" ) - self.__sendButton.setEnabled( False ) - self.__stopButton.setEnabled( False ) - self.__newButton.setEnabled( False ) - self.__modelButton.setEnabled( False ) + if params != self.__target : + self.__target = params + self.__client.send( self.__channel, "connect", params ) def __event( self, name, data ) : - if not self.__active and name != "error" : - return # a reply to a connection this editor has since closed if name == "session" : self.__connected = True - self.__sessionLabel.setText( "SESSION " + str( data.get( "id", "" ) )[-8:] ) - self.__sessionLabel.setToolTip( "Workspace: " + str( data.get( "workspace", "" ) ) ) + self.__selected = data.get( "id" ) + self.__conversationButton.setToolTip( "Workspace: " + str( data.get( "workspace", "" ) ) ) self.__setModel( str( data.get( "model", "" ) ) ) self.__append( "system", "Resumed session" if data.get( "resumed" ) else "New session" ) elif name == "models" : @@ -195,9 +160,19 @@ def __event( self, name, data ) : elif name == "model" : self.__setModel( str( data.get( "selected", "" ) ) ) elif name == "history" : + self.__streaming = False self.__transcript.setText( "" ) for message in data.get( "messages", [] ) : self.__append( message.get( "role", "system" ), message.get( "text", "" ) ) + elif name == "conversations" : + self.__conversations = data["entries"] + self.__selected = data.get( "selected" ) + title = next( (item["title"] for item in self.__conversations if item["id"] == self.__selected), "New conversation" ) + self.__conversationButton.setText( title ) + elif name == "notice" : + self.__append( "system", data["message"] ) + elif name == "user_message" : + self.__append( "user", data["text"] ) elif name == "assistant_start" : self.__startAssistant() elif name == "assistant_delta" : @@ -215,9 +190,13 @@ def __event( self, name, data ) : elif name == "status" : state = str( data.get( "state", "unknown" ) ) self.__statusLabel.setText( state.upper() ) + if state == "connecting" : + self.__connected = False + self.__permissionRequest = None + self.__permissionRow.setVisible( False ) self.__busy = state in ( "busy", "retry" ) - self.__stopButton.setEnabled( self.__busy ) - self.__sendButton.setEnabled( self.__connected and not self.__busy ) + self.__stopButton.setEnabled( self.__busy or state == "connecting" ) + self.__sendButton.setEnabled( not self.__busy ) self.__prompt.setEnabled( not self.__busy ) self.__modelButton.setEnabled( self.__connected and bool( self.__models ) and not self.__busy ) elif name == "error" : @@ -226,7 +205,7 @@ def __event( self, name, data ) : self.__busy = False self.__streaming = False self.__stopButton.setEnabled( False ) - self.__sendButton.setEnabled( self.__connected ) + self.__sendButton.setEnabled( True ) self.__prompt.setEnabled( True ) self.__modelButton.setEnabled( self.__connected and bool( self.__models ) ) @@ -261,30 +240,33 @@ def __selectModel( self, unusedMenu = None, model = "" ) : return self.__client.send( self.__channel, "switch_model", { "model" : model } ) - ## The conversation marked for this script is taken back at Connect: a saved script by its file, an unsaved - # one while it stays open. - def __currentScriptKey( self ) : + def __conversationMenu( self ) : - scriptNode = self.scriptNode() - fileName = str( scriptNode["fileName"].getValue() ) - if not fileName : - return "untitled:" + GafferOpenCode.scriptHandle( scriptNode ) - return "document:" + hashlib.sha256( str( pathlib.Path( fileName ).resolve() ).encode( "utf-8" ) ).hexdigest() + self.__client.send( self.__channel, "list", {} ) + menu = IECore.MenuDefinition() + menu.append( "/New conversation", { "command" : Gaffer.WeakMethod( self.__newSession ), "checkBox" : self.__selected is None, "active" : not self.__busy } ) + for i, item in enumerate( self.__conversations, 1 ) : + title = (item.get( "title" ) or "Untitled").replace( "/", "/" ) + menu.append( f"/{i}. {title}", { + "command" : functools.partial( Gaffer.WeakMethod( self.__openConversation ), item["id"] ), + "checkBox" : item["id"] == self.__selected, + "active" : not self.__busy, + } ) + return menu + + def __openConversation( self, session, unusedMenu = None ) : + + self.__client.send( self.__channel, "open", { "session_id" : session } ) def __connectParams( self ) : scriptNode = self.scriptNode() offer = GafferOpenCode.offerInfo( scriptNode ) - if not offer.get( "advertising" ) or not offer.get( "label" ) : - self.__append( "error", "OpenCode Link does not offer this script to OpenCode." ) - return None fileName = str( scriptNode["fileName"].getValue() ) params = dict( GafferOpenCode.hostInfo() ) params.update( { "script_handle" : GafferOpenCode.scriptHandle( scriptNode ), - "offer_label" : offer["label"], - "script_key" : self.__scriptKey, - "script_name" : pathlib.Path( fileName ).name if fileName else scriptNode.getName(), + "offer_label" : offer.get( "label" ), "directory" : str( pathlib.Path( fileName ).resolve().parent ) if fileName else os.getcwd(), } ) return params @@ -293,25 +275,20 @@ def __scriptPlugSet( self, plug ) : if not plug.isSame( self.scriptNode()["fileName"] ) : return - previousKey = self.__scriptKey - self.__scriptKey = self.__currentScriptKey() - # Another file is another script's conversation: Connect takes that one. - if self.__scriptKey != previousKey and self.__active : - self.__disconnect() + self.__sync() - def __newSession( self, unusedButton ) : + def __newSession( self, unusedButton = None ) : - self.__connect( "new_session" ) + self.__client.send( self.__channel, "new_session", self.__target ) def __send( self, unusedWidget ) : - if self.__busy or not self.__connected : + if self.__busy : return text = self.__prompt.getText().strip() if not text : return self.__prompt.setText( "" ) - self.__append( "user", text ) self.__client.send( self.__channel, "prompt", { "text" : text } ) def __stop( self, unusedButton ) : diff --git a/integrations/gaffer/plugin/README.md b/integrations/gaffer/plugin/README.md index 72a645c..9fb37fe 100644 --- a/integrations/gaffer/plugin/README.md +++ b/integrations/gaffer/plugin/README.md @@ -1,6 +1,6 @@ # OpenCode for Gaffer (preview) -Read, change and check the scripts open in Gaffer from any OpenCode conversation: CodeNomad, the terminal, the desktop app, or the **OpenCode for Gaffer** panel inside Gaffer. Gaffer 1.6 or later and OpenCode 2.2 or later are required; the panel also needs Node.js 22 or later. +Read, change and check the scripts open in Gaffer from any OpenCode conversation: CodeNomad, the terminal, the desktop app, or the **OpenCode for Gaffer** panel inside Gaffer. Gaffer 1.6 or later and OpenCode 2.2 or later are required. ## Install @@ -41,7 +41,7 @@ A call that outlasts its wait says whether Gaffer still runs it (OpenCode Link a ## The OpenCode for Gaffer panel -The **OpenCode for Gaffer** editor is a conversation inside Gaffer. **Connect** attaches the panel's conversation to its script's own offer, resuming the conversation it had for this script; **New** starts another. Closing the panel releases its conversation only: the script stays offered and other conversations attached to it keep it. The panel and other conversations (CodeNomad's, for instance) can be attached to the same script together; both write to it, each change checked against its revision. The panel's conversation lives in the script's folder: the first Connect there waits while OpenCode opens that folder and loads its plugins. A failed Connect says which step failed and why. Node.js is found on `PATH`; `NEURALNOMADS_GAFFER_NODE` names another one. +The **OpenCode for Gaffer** editor connects automatically to the latest conversation in the script’s folder. Opening another version in that folder keeps the selected conversation. The selector next to the model lists the folder’s conversations; **New conversation** creates nothing until you send a message. **Stop** interrupts the turn or clears queued prompts. The panel uses OpenCode’s executable, with Node.js 22+ (`NEURALNOMADS_GAFFER_NODE` or `PATH`) as a fallback. ## Limits diff --git a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.4.0.zip similarity index 80% rename from integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip rename to integrations/gaffer/plugin/host/gaffer/opencode_link-0.4.0.zip index 36e5881..0607b32 100644 Binary files a/integrations/gaffer/plugin/host/gaffer/opencode_link-0.3.0.zip and b/integrations/gaffer/plugin/host/gaffer/opencode_link-0.4.0.zip differ diff --git a/integrations/gaffer/plugin/package.json b/integrations/gaffer/plugin/package.json index 53bca73..0dec469 100644 --- a/integrations/gaffer/plugin/package.json +++ b/integrations/gaffer/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@neuralnomads/opencode-gaffer", - "version": "0.3.0", + "version": "0.4.0", "description": "OpenCode for Gaffer: bounded graph editing through an authenticated local host, with an optional in-app conversation panel.", "license": "MIT", "type": "module", @@ -59,10 +59,10 @@ "host": { "app": "gaffer", "protocol": 1, - "range": "^0.3.0", + "range": "^0.4.0", "appVersions": ">=1.6", - "payload": "host/gaffer/opencode_link-0.3.0.zip", - "sha256": "0ad49be2c312d3a1b8fc2980980707cd717c56ad060aaf0bbb98703141d24e5b" + "payload": "host/gaffer/opencode_link-0.4.0.zip", + "sha256": "974f1c670359218641153e24ee46f6c90b372372aaf2abaa64f7bf34ad90c0d1" } } } diff --git a/integrations/gaffer/plugin/scripts/build-host.ts b/integrations/gaffer/plugin/scripts/build-host.ts index 074882f..747028a 100644 --- a/integrations/gaffer/plugin/scripts/build-host.ts +++ b/integrations/gaffer/plugin/scripts/build-host.ts @@ -13,6 +13,8 @@ const manifest = JSON.parse(readFileSync(join(host, "manifest.json"), "utf8")) if (manifest.version !== pkg.version) throw new Error("Host and plugin versions differ") const check = process.argv.includes("--check") const bundle = await build({ + absWorkingDir: join(root, "..", "..", ".."), + preserveSymlinks: true, entryPoints: [join(root, "src", "sidecar.ts")], bundle: true, format: "cjs", diff --git a/integrations/gaffer/plugin/src/service.ts b/integrations/gaffer/plugin/src/service.ts index 29aa3ef..781ec72 100644 --- a/integrations/gaffer/plugin/src/service.ts +++ b/integrations/gaffer/plugin/src/service.ts @@ -1,91 +1 @@ -import { readFile } from "node:fs/promises" -import { Agent, request } from "node:http" -import { homedir } from "node:os" -import { join } from "node:path" -import { Readable } from "node:stream" - -const agent = new Agent({ keepAlive: true, proxyEnv: {} }) - -function serviceURL(value: string) { - if (!/^http:\/\/(?:127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/.test(value)) - throw new Error("OpenCode service requires a literal loopback HTTP URL") - const url = new URL(value) - if (url.username || url.password || url.hash) throw new Error("Invalid OpenCode service URL") - return url -} - -// A dedicated HTTP agent bypasses environment/system proxies; redirects are never followed. -export function serviceFetch(baseUrl: string): typeof globalThis.fetch { - const origin = serviceURL(baseUrl).origin - return async (input, init) => { - const message = new Request(input, init) - if (serviceURL(message.url).origin !== origin) throw new Error("OpenCode service origin changed") - const body = message.body ? Buffer.from(await message.arrayBuffer()) : undefined - message.signal.throwIfAborted() - return new Promise((resolve, reject) => { - const req = request( - message.url, - { - agent, - method: message.method, - headers: Object.fromEntries(message.headers), - signal: message.signal, - }, - (response) => { - const status = response.statusCode ?? 500 - if (status >= 300 && status < 400) { - response.resume() - reject(new Error("OpenCode service redirect refused")) - return - } - const headers = new Headers() - for (const [key, value] of Object.entries(response.headers)) { - for (const item of Array.isArray(value) ? value : value === undefined ? [] : [value]) - headers.append(key, item) - } - resolve( - new Response( - message.method === "HEAD" || [204, 205, 304].includes(status) - ? null - : (Readable.toWeb(response) as ReadableStream), - { status, headers }, - ), - ) - }, - ) - req.on("error", reject) - req.once("abort", () => reject(message.signal.reason ?? new Error("OpenCode request aborted"))) - req.end(body) - }) - } -} - -export async function discoverService( - file = join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "opencode", "service.json"), -) { - try { - const registration = JSON.parse(await readFile(file, "utf8")) - if ( - typeof registration.url !== "string" || - !Number.isInteger(registration.pid) || - registration.pid <= 0 || - typeof registration.version !== "string" || - !registration.version - ) - return undefined - const fetch = serviceFetch(registration.url) - const headers: Record = {} - if (typeof registration.password === "string") - headers.authorization = `Basic ${Buffer.from(`opencode:${registration.password}`).toString("base64")}` - const response = await fetch(`${registration.url.replace(/\/$/, "")}/api/info`, { - headers, - signal: AbortSignal.timeout(3000), - }) - if (!response.ok) return undefined - const info = await response.json() - if (info?.pid !== registration.pid || info?.version !== registration.version) return undefined - return { url: registration.url as string, headers, fetch } - } catch { - return undefined - } -} +export { discoverService, serviceFetch } from "../../../../packages/integration-kit/src/panel-service.ts" diff --git a/integrations/gaffer/plugin/src/sidecar-core.ts b/integrations/gaffer/plugin/src/sidecar-core.ts index d09aa64..ca8d37a 100644 --- a/integrations/gaffer/plugin/src/sidecar-core.ts +++ b/integrations/gaffer/plugin/src/sidecar-core.ts @@ -1,375 +1,15 @@ -// The in-Gaffer panel's conversations: a plain client of the OpenCode service. Gaffer offers each open script by -// itself (the installed part); the panel only attaches its own conversation to its script's offer, and never -// announces or withdraws offers. Credentials stay in this process: SDK and host errors are never forwarded. -import type { OpenCode } from "@opencode/client" -import { rpcDefinition } from "../../../../packages/integration-kit/src/contract.ts" -import { requestHost as kitRequestHost } from "../../../../packages/integration-kit/src/host-client.ts" - -export type Api = ReturnType -type Rpc = Partial< - Record< - "hosts" | "attachHost" | "detachHost" | "bindingRead", - (input: object, options: object) => Promise> - > -> -type ModelRef = { id: string; providerID: string; variant?: string } -type Channel = { - id: string - directory: string - sessionID: string - label: string - offerID: string - host: { host: string; port: number; token: string } - handle: string - abort: AbortController - timer?: NodeJS.Timeout - checking: boolean - tools: Map - model?: ModelRef -} -export type PanelRequest = { id: string; channel: string; method: string; params?: Record } - -// The session metadata naming the Gaffer script a conversation belongs to: Connect takes that one back. -export const SCRIPT_MARKER = "opencode_gaffer_script" - -// A message of this sidecar's own, safe to show in the panel. -class PanelError extends Error {} - -// An error in one line for the panel: its first line, bounded, without a token, an authorization or a port. -export function briefly(error: unknown) { - const text = String((error as { message?: unknown } | null)?.message ?? error ?? "unknown error") - .split(/\r?\n/)[0] - ?.replace(/\b[0-9a-f]{32,}\b/gi, "…") - .replace(/(basic|bearer)\s+\S+/gi, "$1 …") - .replace(/\b(port\s+|:)\d{2,5}\b/gi, "$1…") - .slice(0, 240) - return `${text || "unknown error"}${/[.!?]$/.test(text ?? "") ? "" : "."}` -} - -const modelKey = (model: ModelRef | undefined) => - model ? `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}` : "" - -type Part = { type?: string; text?: string; name?: string; state?: { status?: string } } -type Message = { type?: string; text?: string; content?: Part[] } -type EventData = { - sessionID?: string - delta?: string - id?: string - name?: string - action?: string - resources?: string[] - model?: ModelRef -} - -function history(messages: ReadonlyArray) { - return messages.flatMap((message) => { - if (message.type === "user") return [{ role: "user", text: message.text ?? "" }] - if (message.type !== "assistant") return [] - return (message.content ?? []).flatMap((part) => { - if (part.type === "text") return [{ role: "assistant", text: part.text ?? "" }] - if (part.type === "tool") return [{ role: "tool", text: `${part.name} / ${part.state?.status ?? "unknown"}` }] - return [] - }) - }) -} - -export function createPanel(deps: { - // The running OpenCode service, or undefined when none is running (never started from here). - discover: () => Promise - send: (message: unknown) => void - requestHost?: typeof kitRequestHost - // How long Connect waits for this script's offer (Gaffer offers each script every few seconds). - offerWaitMs?: number - checkEveryMs?: number -}) { - const requestHost = deps.requestHost ?? kitRequestHost - // A Location opened for the panel loads its plugins first, which took tens of seconds in a trial. - const offerWaitMs = deps.offerWaitMs ?? 30_000 - const checkEveryMs = deps.checkEveryMs ?? 5_000 - const channels = new Map() - let client: Api | undefined - let rpc: Rpc = {} - const event = (c: { id: string }, name: string, data: object) => deps.send({ channel: c.id, event: name, data }) - const options = (c: { directory: string }) => ({ - location: { directory: c.directory }, - signal: AbortSignal.timeout(3000), - }) - const host = (c: Channel, method: "cancel" | "resume") => - requestHost(c.host, method, { script_handle: c.handle, session_id: c.sessionID }, { timeoutMs: 2000 }) - - async function api() { - if (client) return client - const found = await deps.discover() - if (!found) throw new PanelError("Start OpenCode before connecting the panel.") - client = found - rpc = found.rpc(rpcDefinition("neuralnomads.gaffer", "native") as never) as unknown as Rpc - return client - } - - // This script's offer: the one with its label among the offered hosts (offer keys stay private to the service). - async function findOffer(c: { directory: string; label: string }) { - const until = Date.now() + offerWaitMs - for (;;) { - let result: { offers?: unknown } | undefined - try { - result = (await rpc.hosts?.({}, options(c))) as typeof result - } catch (error) { - // The first call in the script's folder: OpenCode opens that Location and loads its plugins meanwhile, and - // the integration's RPC is not there yet (a CodeNomad conversation's own Location is long loaded). - if ( - !/RPC is unavailable/i.test(String((error as { message?: unknown })?.message ?? error)) || - Date.now() > until - ) - throw error - await new Promise((resolve) => setTimeout(resolve, 1_000)) - continue - } - const offers = ((result?.offers ?? []) as Array<{ label: string; offerID: string }>).filter( - (offer) => offer.label === c.label, - ) - if (offers.length > 1) - throw new PanelError(`Several scripts offer ${c.label}: attach this conversation from OpenCode (gaffer_hosts).`) - if (offers[0]) return offers[0] - if (Date.now() > until) throw new PanelError("This script is not offered to OpenCode yet; choose Connect again.") - await new Promise((resolve) => setTimeout(resolve, 1_000)) - } - } - - async function attached(c: Channel) { - const read = await rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)) - return read?.state === "attached" && (read.binding as { offerID?: string } | undefined)?.offerID === c.offerID - } - - // The script's own conversation, when one is marked for it and still open. - async function markedSession(service: Api, directory: string, key: string) { - let cursor: string | undefined - for (let page = 0; page < 10; page += 1) { - const listed = await service.session.list({ directory, order: "desc", limit: 100, cursor }) - const found = listed.data.find( - (candidate) => - !candidate.time?.archived && - (candidate.metadata as Record | undefined)?.[SCRIPT_MARKER] === key, - ) - if (found) return found - cursor = listed.cursor.next ?? undefined - if (!cursor) return undefined - } - return undefined - } - - // Closing releases this panel's conversation only: the offer stays for every other conversation. - async function close(c: Channel) { - if (channels.get(c.id) === c) channels.delete(c.id) - if (c.timer) clearInterval(c.timer) - c.abort.abort() - await host(c, "cancel").catch(() => {}) - // Another client may have moved the conversation to another host: never detach that binding. - await attached(c) - .then((still) => (still ? rpc.detachHost?.({ sessionID: c.sessionID }, options(c)) : undefined)) - .catch(() => {}) - } - - function forward(c: Channel, type: string, data: EventData) { - if (type === "session.model.selected") { - c.model = data.model - event(c, "model", { selected: modelKey(c.model) }) - } else if (type === "session.execution.started") event(c, "status", { state: "busy" }) - else if (type === "session.text.started") event(c, "assistant_start", {}) - else if (type === "session.text.delta") event(c, "assistant_delta", { text: data.delta ?? "" }) - else if (type === "session.text.ended") event(c, "assistant_end", {}) - else if (type === "session.tool.input.started") { - c.tools.set(String(data.id), String(data.name ?? "tool")) - event(c, "tool", { id: data.id, name: data.name, state: "starting" }) - } else if (type === "session.tool.success" || type === "session.tool.failed") { - const name = c.tools.get(String(data.id)) - c.tools.delete(String(data.id)) - event(c, "tool", { id: data.id, name, state: type === "session.tool.success" ? "completed" : "failed" }) - } else if (type === "permission.asked") - event(c, "permission", { request_id: data.id, action: data.action, resources: data.resources ?? [] }) - else if (type === "session.execution.succeeded" || type === "session.idle") event(c, "status", { state: "idle" }) - else if (type === "session.execution.interrupted" || type === "session.execution.failed") { - if (type === "session.execution.failed") event(c, "error", { message: "OpenCode execution failed." }) - event(c, "status", { state: "idle" }) - void host(c, "cancel").catch(() => {}) - } - } - - async function stream(c: Channel, service: Api) { - try { - for await (const item of service.event.subscribe({ signal: c.abort.signal })) { - const data = item.data as unknown as EventData - if (data?.sessionID === c.sessionID) forward(c, item.type, data) - } - } catch { - // ended below - } - if (!c.abort.signal.aborted) event(c, "error", { message: "OpenCode disconnected; choose Connect to reconnect." }) - } - - function watch(c: Channel) { - let warned = false - c.timer = setInterval(() => { - if (c.checking) return - c.checking = true - void api() - .then(() => attached(c)) - .then((still) => { - if (!still) throw new Error("detached") - warned = false - }) - .catch(() => { - client = undefined - if (!warned) - event(c, "error", { message: "Conversation detached or service unavailable; choose Connect to reconnect." }) - warned = true - }) - .finally(() => { - c.checking = false - }) - }, checkEveryMs) - c.timer.unref?.() - } - - // A failed Connect says which step failed and why, in a line (never a credential): the user knows what to check. - const step = async (doing: string, work: () => Promise): Promise => { - try { - return await work() - } catch (error) { - if (error instanceof PanelError) throw error - throw new PanelError( - `Connect failed while ${doing}: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - ) - } - } - - async function connect(id: string, params: Record, fresh: boolean) { - const previous = channels.get(id) - if (previous) await close(previous) - if (params.host !== "127.0.0.1" || !Number.isInteger(params.port) || !/^[0-9a-f]{64}$/.test(String(params.token))) - throw new Error("Invalid host endpoint.") - const directory = String(params.directory ?? "") - const label = String(params.offer_label ?? "") - const key = String(params.script_key ?? "") - const handle = String(params.script_handle ?? "") - if (!directory || !label || !key || !handle) throw new Error("Incomplete connect request.") - const service = await step("reaching OpenCode", api) - // The script's conversation, unless New asked for another one. - const known = fresh - ? undefined - : await step("finding this script's conversation", () => markedSession(service, directory, key)) - const session = - known ?? - (await step("creating this script's conversation", () => - service.session.create({ - title: `Gaffer: ${String(params.script_name || "untitled")}`, - location: { directory }, - metadata: { [SCRIPT_MARKER]: key }, - }), - )) - const c: Channel = { - id, - directory, - sessionID: session.id, - label, - offerID: "", - host: { host: "127.0.0.1", port: Number(params.port), token: String(params.token) }, - handle, - abort: new AbortController(), - checking: false, - tools: new Map(), - model: (session as { model?: ModelRef }).model, - } - try { - const offer = await step("finding this script's offer", () => findOffer(c)) - const result = await step("attaching the conversation to this script", async () => - rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID }, options(c)), - ) - if (result?.outcome === "busy") - throw new PanelError("This conversation is attached to another application; detach it there first.") - if (result?.outcome !== "attached") throw new PanelError("Gaffer attachment was refused.") - c.offerID = offer.offerID - channels.set(id, c) - watch(c) - void stream(c, service) - const [messages, models, configured, active] = await step("loading the conversation", () => - Promise.all([ - service.message.list({ sessionID: c.sessionID, order: "desc", limit: 200 }), - service.model.list({ location: { directory } }), - service.model.default({ location: { directory } }), - service.session.active(), - ]), - ) - if (!c.model && configured.data) c.model = configured.data as ModelRef - event(c, "session", { id: c.sessionID, resumed: Boolean(known), model: modelKey(c.model), workspace: directory }) - event(c, "models", { - selected: modelKey(c.model), - models: models.data - .filter((model) => model.enabled) - .map((model) => ({ id: model.id, provider_id: model.providerID, name: model.name })), - }) - event(c, "history", { messages: history([...messages.data].reverse() as never) }) - event(c, "status", { - state: (active as Record)[c.sessionID]?.type === "running" ? "busy" : "idle", - }) - } catch (error) { - await close(c) - throw error - } - } - - async function act(c: Channel, method: string, params: Record) { - if (method === "close") return await close(c) - const service = await api() - if (method === "interrupt") { - await host(c, "cancel").catch(() => {}) - await service.session.interrupt({ sessionID: c.sessionID, resume: false }) - } else if (method === "prompt") { - if (!(await attached(c))) throw new PanelError("Gaffer was detached; choose Connect to attach again.") - await host(c, "resume") - await service.session.prompt({ sessionID: c.sessionID, text: String(params.text ?? "") }) - } else if (method === "switch_model") { - const key = String(params.model ?? "") - const catalog = await service.model.list({ location: { directory: c.directory } }) - const selected = catalog.data.find((model) => model.enabled && `${model.providerID}/${model.id}` === key) - if (!selected) throw new PanelError("This model is not available in this workspace.") - c.model = { id: selected.id, providerID: selected.providerID } - await service.session.switchModel({ sessionID: c.sessionID, model: c.model }) - event(c, "model", { selected: modelKey(c.model) }) - } else if (method === "permission_reply") { - const decision = params.reply - if (decision !== "once" && decision !== "reject") throw new Error("Invalid permission answer.") - await service.permission.reply({ sessionID: c.sessionID, requestID: String(params.request_id), decision }) - } else throw new Error("Unknown panel action.") - } - - async function dispatch(request: PanelRequest) { - try { - const params = request.params ?? {} - if (request.method === "connect" || request.method === "new_session") - await connect(request.channel, params, request.method === "new_session") - else { - const c = channels.get(request.channel) - if (c) await act(c, request.method, params) - else if (request.method !== "close") throw new PanelError("Choose Connect first.") - } - deps.send({ id: request.id, result: {} }) - } catch (error) { - deps.send({ - channel: request.channel, - event: "error", - data: { - message: - error instanceof PanelError - ? error.message - : `The panel action failed: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - }, - }) - deps.send({ id: request.id, error: { message: "Panel action failed." } }) - } - } - - return { - dispatch, - closeAll: () => Promise.allSettled([...channels.values()].map(close)), - } -} +import { + createPanel as createChat, + type PanelDependencies, + type PanelHost, +} from "../../../../packages/integration-kit/src/panel.ts" + +export { type Api, briefly, type PanelRequest } from "../../../../packages/integration-kit/src/panel.ts" + +export const panelHost = { + app: "Gaffer", + rpcID: "neuralnomads.gaffer", + document: "script", + duplicateOffer: "scripts", +} satisfies PanelHost +export const createPanel = (deps: PanelDependencies) => createChat(panelHost, deps) diff --git a/integrations/gaffer/plugin/src/sidecar.ts b/integrations/gaffer/plugin/src/sidecar.ts index 2764498..535b9cc 100644 --- a/integrations/gaffer/plugin/src/sidecar.ts +++ b/integrations/gaffer/plugin/src/sidecar.ts @@ -1,35 +1,4 @@ -// The in-Gaffer panel's private JSONL client, built into the installed part as sidecar.cjs and run by Node. -import readline from "node:readline" -import { OpenCode } from "@opencode/client" -import { discoverService } from "./service.ts" -import { createPanel, type PanelRequest } from "./sidecar-core.ts" +import { runPanel } from "../../../../packages/integration-kit/src/panel-pipes.ts" +import { panelHost } from "./sidecar-core.ts" -const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`) -const panel = createPanel({ - send, - discover: async () => { - const endpoint = await discoverService() - return endpoint && OpenCode.make({ baseUrl: endpoint.url, headers: endpoint.headers, fetch: endpoint.fetch }) - }, -}) -const queues = new Map>() - -const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }) -input.on("line", (line) => { - if (!line.trim()) return - try { - if (Buffer.byteLength(line) > 1024 * 1024) throw new Error("Request too large") - const request = JSON.parse(line) as PanelRequest - if (!request.id || !request.channel || !request.method) throw new Error("Invalid request") - const next = (queues.get(request.channel) ?? Promise.resolve()).then(() => panel.dispatch(request)) - queues.set(request.channel, next) - void next.finally(() => { - if (queues.get(request.channel) === next) queues.delete(request.channel) - }) - } catch { - send({ error: { message: "Invalid panel request." } }) - } -}) -input.on("close", () => { - void panel.closeAll().finally(() => process.exit(0)) -}) +runPanel(panelHost) diff --git a/integrations/gaffer/test/panel.test.ts b/integrations/gaffer/test/panel.test.ts index 71abbbc..8a0ddcd 100644 --- a/integrations/gaffer/test/panel.test.ts +++ b/integrations/gaffer/test/panel.test.ts @@ -1,49 +1,23 @@ import assert from "node:assert/strict" import { spawnSync } from "node:child_process" -import { cpSync, mkdtempSync, rmSync } from "node:fs" +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" -import { join } from "node:path" +import { dirname, join } from "node:path" import { it } from "node:test" -import { build } from "esbuild" -import { type Api, createPanel, SCRIPT_MARKER } from "../plugin/src/sidecar-core.ts" +import { readStoredZip } from "../../../packages/integration-kit/src/zip.ts" +import marker from "../plugin/package.json" with { type: "json" } -const python = process.env.PYTHON ?? (process.platform === "win32" ? "python" : "python3") -const KEY = "document:shot" -const HOST = { host: "127.0.0.1", port: 4242, token: "a".repeat(64) } -const CONNECT = { - ...HOST, - protocol: 1, - script_handle: "gaffer:shot", - offer_label: "Gaffer: shot.gfr", - script_key: KEY, - script_name: "shot.gfr", - directory: join(tmpdir(), "gaffer-shots"), -} - -it("the installed panel runs its sidecar with Node: payload layout, Gaffer stubs, no Bun", async () => { +it("the installed Gaffer panel opens automatically, queues early input and follows Save As", () => { const payload = mkdtempSync(join(tmpdir(), "gaffer-panel-")) try { - cpSync(join(import.meta.dirname, "..", "host", "python"), join(payload, "python"), { recursive: true }) - // As the host build makes it: one CommonJS file for Node 22 at the payload root. - await build({ - entryPoints: [join(import.meta.dirname, "..", "plugin", "src", "sidecar.ts")], - bundle: true, - format: "cjs", - platform: "node", - target: "node22", - outfile: join(payload, "sidecar.cjs"), - logLevel: "warning", - }) - const sidecar = spawnSync(process.execPath, [join(payload, "sidecar.cjs")], { - input: "not json\n", - encoding: "utf8", - windowsHide: true, - timeout: 20_000, - // Never discover the OpenCode service of the computer running the test. - env: { ...process.env, XDG_STATE_HOME: join(payload, "state") }, - }) - assert.equal(sidecar.status, 0, sidecar.stderr) - assert.deepEqual(JSON.parse(sidecar.stdout), { error: { message: "Invalid panel request." } }) + for (const entry of readStoredZip( + readFileSync(join(import.meta.dirname, "../plugin", marker.opencodeIntegration.host.payload)), + )) { + const file = join(payload, entry.name) + mkdirSync(dirname(file), { recursive: true }) + writeFileSync(file, entry.data) + } + const python = process.env.PYTHON ?? (process.platform === "win32" ? "python" : "python3") const probe = spawnSync(python, ["-I", join(import.meta.dirname, "panel_probe.py"), payload], { encoding: "utf8", windowsHide: true, @@ -53,340 +27,3 @@ it("the installed panel runs its sidecar with Node: payload layout, Gaffer stubs rmSync(payload, { recursive: true, force: true }) } }) - -type Item = { type: string; data: Record } -type Input = { offerID: string; sessionID: string } -type Out = { id?: string; event?: string; error?: unknown; data: Record & { message?: string } } - -function fakeService() { - const calls: Array<[string, unknown]> = [] - const bindings = new Map() - const listeners = new Set<(item: Item) => void>() - let offers = [ - { offerID: "offer_other", label: "Gaffer: other.gfr", protocol: "ok" }, - { offerID: "offer_shot", label: "Gaffer: shot.gfr", protocol: "ok" }, - ] - let created = 0 - // The first calls of a Location OpenCode is still opening: the integration's RPC is not there yet. - let unavailable = 0 - const record = - (name: string, result: (input: Input) => unknown = () => ({})) => - async (input: Input) => { - calls.push([name, input]) - return result(input) - } - const rpc = new Proxy({} as Record, { - get: (_target, name: string) => { - const methods: Record unknown> = { - hosts: () => { - if (unavailable > 0) { - unavailable -= 1 - throw new Error("RPC is unavailable: neuralnomads.gaffer") - } - return { offers } - }, - attachHost: ({ offerID, sessionID }) => { - const bound = bindings.get(sessionID) - if (bound && bound !== offerID) return { outcome: "busy" } - bindings.set(sessionID, offerID) - return { outcome: "attached" } - }, - detachHost: ({ sessionID }) => ({ outcome: bindings.delete(sessionID) ? "detached" : "none" }), - bindingRead: ({ sessionID }) => - bindings.has(sessionID) - ? { state: "attached", binding: { offerID: bindings.get(sessionID), label: "x" } } - : { state: "none" }, - } - return record(`rpc.${name}`, methods[name] ?? (() => ({ outcome: "refused" }))) - }, - }) - const api = { - rpc: () => rpc, - session: { - list: record("session.list", () => ({ - data: [ - { id: "ses_archived", metadata: { [SCRIPT_MARKER]: KEY }, time: { archived: 1 } }, - { id: "ses_foreign", metadata: { [SCRIPT_MARKER]: "document:other" }, time: {} }, - { id: "ses_old", metadata: { [SCRIPT_MARKER]: KEY }, time: {} }, - ], - cursor: {}, - })), - create: record("session.create", () => ({ id: `ses_new${++created}` })), - prompt: record("session.prompt"), - interrupt: record("session.interrupt"), - switchModel: record("session.switchModel"), - active: record("session.active", () => ({})), - }, - message: { - list: record("message.list", () => ({ - data: [ - { type: "assistant", content: [{ type: "text", text: "Done." }] }, - { type: "user", text: "Add a sphere" }, - ], - })), - }, - model: { - list: record("model.list", () => ({ - data: [ - { id: "m1", providerID: "p", name: "M1", enabled: true }, - { id: "m2", providerID: "p", name: "M2", enabled: false }, - ], - })), - default: record("model.default", () => ({ data: { id: "m1", providerID: "p" } })), - }, - permission: { reply: record("permission.reply") }, - event: { - subscribe: ({ signal }: { signal: AbortSignal }) => - (async function* () { - const queue: Item[] = [] - let wake = () => {} - const listener = (item: Item) => { - queue.push(item) - wake() - } - listeners.add(listener) - signal.addEventListener("abort", () => wake(), { once: true }) - try { - while (!signal.aborted) { - const item = queue.shift() - if (item) yield item - else - await new Promise((resolve) => { - wake = resolve - }) - } - } finally { - listeners.delete(listener) - } - })(), - }, - } - return { - api: api as unknown as Api, - calls, - bindings, - setOffers: (next: typeof offers) => { - offers = next - }, - setUnavailable: (calls: number) => { - unavailable = calls - }, - push: async (item: Item) => { - for (const listener of listeners) listener(item) - await new Promise((resolve) => setImmediate(resolve)) - }, - } -} - -function harness(offerWaitMs = -1) { - const service = fakeService() - const out: Out[] = [] - const host: Array<[string, unknown]> = [] - const panel = createPanel({ - discover: async () => service.api, - send: (message) => out.push(message as Out), - requestHost: async (_endpoint, method, params) => { - host.push([method, params]) - return {} - }, - offerWaitMs, - checkEveryMs: 60_000, - }) - let id = 0 - const call = (method: string, params: Record = {}, channel = "panel") => - panel.dispatch({ id: String(++id), channel, method, params }) - const events = (name: string) => out.filter((message) => message.event === name).map((message) => message.data) - return { service, out, host, panel, call, events } -} - -it("Connect resumes the script's marked conversation and attaches it to that script's offer only", async () => { - const { service, host, panel, call, events } = harness() - try { - await call("connect", CONNECT) - assert.equal(service.calls.filter(([name]) => name === "session.create").length, 0) - assert.deepEqual(service.bindings, new Map([["ses_old", "offer_shot"]])) - assert.deepEqual(events("session")[0], { - id: "ses_old", - resumed: true, - model: "p/m1", - workspace: CONNECT.directory, - }) - assert.deepEqual(events("history")[0]?.messages, [ - { role: "user", text: "Add a sphere" }, - { role: "assistant", text: "Done." }, - ]) - assert.deepEqual(events("models")[0], { selected: "p/m1", models: [{ id: "m1", provider_id: "p", name: "M1" }] }) - assert.deepEqual(events("status").at(-1), { state: "idle" }) - - // Streaming: this conversation's events only. - await service.push({ type: "session.text.delta", data: { sessionID: "ses_other", delta: "no" } }) - await service.push({ type: "session.execution.started", data: { sessionID: "ses_old" } }) - await service.push({ type: "session.text.delta", data: { sessionID: "ses_old", delta: "Hel" } }) - await service.push({ type: "session.text.delta", data: { sessionID: "ses_old", delta: "lo" } }) - await service.push({ - type: "permission.asked", - data: { sessionID: "ses_old", id: "per_1", action: "gaffer_write" }, - }) - assert.deepEqual(events("assistant_delta"), [{ text: "Hel" }, { text: "lo" }]) - assert.deepEqual(events("status").at(-1), { state: "busy" }) - assert.deepEqual(events("permission"), [{ request_id: "per_1", action: "gaffer_write", resources: [] }]) - - await call("permission_reply", { request_id: "per_1", reply: "once" }) - await call("prompt", { text: "Add a light" }) - await call("switch_model", { model: "p/m1" }) - await call("interrupt") - const names = service.calls.map(([name]) => name) - assert.deepEqual(service.calls.find(([name]) => name === "permission.reply")?.[1], { - sessionID: "ses_old", - requestID: "per_1", - decision: "once", - }) - assert.deepEqual(service.calls.find(([name]) => name === "session.prompt")?.[1], { - sessionID: "ses_old", - text: "Add a light", - }) - assert.ok(names.includes("session.switchModel") && names.includes("session.interrupt")) - assert.deepEqual(host, [ - ["resume", { script_handle: "gaffer:shot", session_id: "ses_old" }], - ["cancel", { script_handle: "gaffer:shot", session_id: "ses_old" }], - ]) - - // New: another conversation, marked for the same script, on the same offer; the previous one is released. - await call("new_session", CONNECT) - const created = service.calls.find(([name]) => name === "session.create")?.[1] - assert.deepEqual(created, { - title: "Gaffer: shot.gfr", - location: { directory: CONNECT.directory }, - metadata: { [SCRIPT_MARKER]: KEY }, - }) - assert.deepEqual(service.bindings, new Map([["ses_new1", "offer_shot"]])) - assert.deepEqual(events("session").at(-1), { - id: "ses_new1", - resumed: false, - model: "p/m1", - workspace: CONNECT.directory, - }) - - // Close: this conversation only; the offer is never withdrawn and never announced by the panel. - await call("close") - assert.deepEqual(service.bindings, new Map()) - assert.deepEqual(host.at(-1), ["cancel", { script_handle: "gaffer:shot", session_id: "ses_new1" }]) - await call("prompt", { text: "late" }) - assert.equal(events("error").at(-1)?.message, "Choose Connect first.") - const rpcMethods = new Set(service.calls.map(([name]) => name).filter((name) => name.startsWith("rpc."))) - assert.deepEqual(rpcMethods, new Set(["rpc.hosts", "rpc.attachHost", "rpc.bindingRead", "rpc.detachHost"])) - } finally { - await panel.closeAll() - } -}) - -it("Connect refuses an ambiguous or absent offer, keeps a conversation attached elsewhere and hides SDK errors", async () => { - const { service, panel, call, events } = harness() - try { - service.setOffers([ - { offerID: "offer_a", label: "Gaffer: shot.gfr", protocol: "ok" }, - { offerID: "offer_b", label: "Gaffer: shot.gfr", protocol: "ok" }, - ]) - await call("connect", CONNECT) - assert.match(String(events("error").at(-1)?.message), /^Several scripts offer Gaffer: shot.gfr/) - service.setOffers([]) - await call("connect", CONNECT) - assert.equal(events("error").at(-1)?.message, "This script is not offered to OpenCode yet; choose Connect again.") - assert.equal(service.calls.filter(([name]) => name === "rpc.attachHost").length, 0) - - // The marked conversation is attached to another application: never taken from it. - service.setOffers([ - { offerID: "offer_shot", label: "Gaffer: shot.gfr", protocol: "ok" }, - { offerID: "offer_blender", label: "Blender: shot.blend", protocol: "ok" }, - ]) - service.bindings.set("ses_old", "offer_blender") - await call("connect", CONNECT) - assert.match(String(events("error").at(-1)?.message), /attached to another application/) - assert.equal(service.bindings.get("ses_old"), "offer_blender") - - // Attached here, then moved elsewhere by another client: closing leaves that binding alone. - service.bindings.clear() - await call("connect", CONNECT) - service.bindings.set("ses_old", "offer_blender") - await call("close") - assert.equal(service.bindings.get("ses_old"), "offer_blender") - - for (const bad of [{ token: "short" }, { host: "10.0.0.1" }, { offer_label: "" }]) { - await call("connect", { ...CONNECT, ...bad }) - assert.match( - String(events("error").at(-1)?.message), - /^The panel action failed: (Invalid host endpoint|Incomplete connect request)\. Check that OpenCode runs/, - ) - } - service.bindings.clear() - await call("connect", CONNECT) - ;(service.api.session as { prompt: unknown }).prompt = async () => { - throw new Error(`token ${HOST.token} on port ${HOST.port}`) - } - await call("prompt", { text: "x" }) - const message = events("error").at(-1)?.message as string - assert.ok(!message.includes(HOST.token) && !message.includes(String(HOST.port)), message) - } finally { - await panel.closeAll() - } -}) - -// Real trial: the first Connect failed while OpenCode opened the script's folder (its Location) and loaded its plugins -// ("RPC is unavailable"); it was read as the CodeNomad conversation attached to the same script holding it. -it("Connect waits for the Location OpenCode is still opening, next to a conversation attached to the same script", async () => { - const { service, panel, call, events } = harness(10_000) - try { - service.bindings.set("ses_codenomad", "offer_shot") - service.setUnavailable(2) - await call("connect", CONNECT) - assert.deepEqual(events("error"), []) - assert.equal(service.calls.filter(([name]) => name === "rpc.hosts").length, 3) - // Both conversations are attached to the script; closing the panel leaves the other one attached. - assert.deepEqual( - service.bindings, - new Map([ - ["ses_codenomad", "offer_shot"], - ["ses_old", "offer_shot"], - ]), - ) - await call("close") - assert.deepEqual(service.bindings, new Map([["ses_codenomad", "offer_shot"]])) - } finally { - await panel.closeAll() - } -}) - -it("a failed Connect says which step failed and why, without a credential", async () => { - const { service, panel, call, events } = harness(-1) - try { - service.setUnavailable(1) - await call("connect", CONNECT) - assert.equal( - events("error").at(-1)?.message, - "Connect failed while finding this script's offer: RPC is unavailable: neuralnomads.gaffer. Check that OpenCode runs, then choose Connect.", - ) - ;(service.api.session as { list: unknown }).list = async () => { - throw new Error(`refused by 127.0.0.1:${HOST.port} with Basic secret ${HOST.token}\nstack`) - } - await call("connect", CONNECT) - const message = String(events("error").at(-1)?.message) - assert.match( - message, - /^Connect failed while finding this script's conversation: refused by 127\.0\.0\.1:… with Basic …/, - ) - assert.ok( - !message.includes(HOST.token) && !message.includes(String(HOST.port)) && !message.includes("stack"), - message, - ) - } finally { - await panel.closeAll() - } -}) - -it("Connect without a running OpenCode says so", async () => { - const out: Out[] = [] - const panel = createPanel({ discover: async () => undefined, send: (message) => out.push(message as never) }) - await panel.dispatch({ id: "1", channel: "panel", method: "connect", params: CONNECT }) - assert.equal(out[0]?.data.message, "Start OpenCode before connecting the panel.") - assert.deepEqual(out[1], { id: "1", error: { message: "Panel action failed." } }) -}) diff --git a/integrations/gaffer/test/panel_probe.py b/integrations/gaffer/test/panel_probe.py index 33bda18..7164c01 100644 --- a/integrations/gaffer/test/panel_probe.py +++ b/integrations/gaffer/test/panel_probe.py @@ -3,7 +3,6 @@ Usage: python -I panel_probe.py """ import gc -import hashlib import pathlib import sys import types @@ -132,6 +131,10 @@ def emit(self, channel, name, data): api = Api() +api.__path__ = [] +api.panelServices = lambda: [] +service = types.ModuleType("GafferOpenCode.opencode_service") +service.panel_launcher = lambda results, override, wait=False: (sys.executable, True) gaffer = types.ModuleType("Gaffer") gaffer.WeakMethod = weak_method gafferui = types.ModuleType("GafferUI") @@ -146,6 +149,7 @@ def emit(self, channel, name, data): "Gaffer": gaffer, "GafferUI": gafferui, "GafferOpenCode": api, + "GafferOpenCode.opencode_service": service, "IECore": MagicMock(), "imath": MagicMock(), "Qt": qt, @@ -174,47 +178,31 @@ def test_installed_client_runs_node_sidecar(self): self.assertEqual(Editor.registered, ("OpenCode for Gaffer", GafferOpenCodeUI.OpenCodeEditor)) process = qt.QtCore.QProcess.return_value process.state.return_value = qt.QtCore.QProcess.NotRunning - with patch.dict("os.environ", {"NEURALNOMADS_GAFFER_NODE": ""}), patch.object( - client_module.shutil, "which", return_value="/usr/bin/node" - ) as which: - client_module.ClientProcess() - which.assert_called_with("node") - process.setProgram.assert_called_with("/usr/bin/node") + client = client_module.ClientProcess() + client.send("trial", "connect", {}) + process.setProgram.assert_called_with(sys.executable) + qt.QtCore.QProcessEnvironment.systemEnvironment.return_value.insert.assert_called_with("BUN_BE_BUN", "1") process.setArguments.assert_called_with([str(PAYLOAD / "sidecar.cjs")]) process.start.assert_called() self.assertTrue((PAYLOAD / "sidecar.cjs").is_file()) - # NEURALNOMADS_GAFFER_NODE names Node explicitly. - with patch.dict("os.environ", {"NEURALNOMADS_GAFFER_NODE": "/opt/node22/bin/node"}): - client_module.ClientProcess() - process.setProgram.assert_called_with("/opt/node22/bin/node") def test_connect_targets_this_scripts_offer_and_closing_never_withdraws(self): shot = pathlib.Path(PAYLOAD / "shots" / "shot.gfr") script = Script("gaffer:shot", str(shot)) api.offers[script.handle] = {"label": "Gaffer: shot.gfr", "offer_key": "gaffer-shot", "advertising": True} editor = GafferOpenCodeUI.OpenCodeEditor(script) - # Opening the panel attaches nothing: Gaffer already offers the script by itself. - self.assertEqual(api.calls, []) - self.assertEqual(self.client.sent, []) - - private(editor, "toggleConnection")() channel, method, params = self.client.sent[-1] self.assertEqual(api.calls, [("acquire", channel)]) self.assertEqual(method, "connect") - key = "document:" + hashlib.sha256(str(shot.resolve()).encode("utf-8")).hexdigest() self.assertEqual( params, { **HOST, "script_handle": "gaffer:shot", "offer_label": "Gaffer: shot.gfr", - "script_key": key, - "script_name": "shot.gfr", "directory": str(shot.resolve().parent), }, ) - self.client.emit(channel, "session", {"id": "ses_shot", "resumed": True}) - self.client.emit(channel, "status", {"state": "idle"}) prompt = private(editor, "prompt") prompt.getText.return_value = "Add a sphere" private(editor, "send")(None) @@ -224,28 +212,14 @@ def test_connect_targets_this_scripts_offer_and_closing_never_withdraws(self): private(editor, "newSession")(None) self.assertEqual(self.client.sent[-1], (channel, "new_session", params)) - # Disconnect releases the panel's conversation only. - private(editor, "toggleConnection")() - self.assertEqual(self.client.sent[-1], (channel, "close", {})) - self.assertEqual(api.calls[-1], ("release", channel)) - # A reply to the closed connection is ignored. - self.client.emit(channel, "session", {"id": "ses_late"}) - self.assertFalse(private(editor, "connected")) - - # Connect again asks for the same script's conversation: the sidecar resumes the session marked with it. - private(editor, "toggleConnection")() - self.assertEqual(self.client.sent[-1], (channel, "connect", params)) - - # Save As: another file is another script's conversation. + # Save As updates the offer but keeps the same folder. moved = PAYLOAD / "shots" / "shot_v2.gfr" api.offers[script.handle]["label"] = "Gaffer: shot_v2.gfr" script.setFileName(str(moved)) - self.assertEqual(self.client.sent[-1], (channel, "close", {})) - self.assertEqual(api.calls[-1], ("release", channel)) - private(editor, "toggleConnection")() + self.assertEqual(self.client.sent[-1][1], "connect") moved_params = self.client.sent[-1][2] self.assertEqual(moved_params["offer_label"], "Gaffer: shot_v2.gfr") - self.assertNotEqual(moved_params["script_key"], key) + self.assertEqual(moved_params["directory"], params["directory"]) # Closing the editor (its last reference gone) releases its conversation and the panel registration. del editor, prompt @@ -260,16 +234,13 @@ def test_each_script_has_its_own_offer_and_conversation(self): api.offers[first.handle] = {"label": "Gaffer: untitled", "offer_key": "gaffer-one", "advertising": True} api.offers[second.handle] = {"label": "Gaffer: untitled (2)", "offer_key": "gaffer-two", "advertising": True} editors = [GafferOpenCodeUI.OpenCodeEditor(first), GafferOpenCodeUI.OpenCodeEditor(second)] - for editor in editors: - private(editor, "toggleConnection")() (a, _, one), (b, _, two) = self.client.sent self.assertNotEqual(a, b) - self.assertEqual((one["offer_label"], one["script_key"]), ("Gaffer: untitled", "untitled:gaffer:one")) - self.assertEqual((two["offer_label"], two["script_key"]), ("Gaffer: untitled (2)", "untitled:gaffer:two")) + self.assertEqual(one["offer_label"], "Gaffer: untitled") + self.assertEqual(two["offer_label"], "Gaffer: untitled (2)") # A second panel on the same script takes back the same conversation. third = GafferOpenCodeUI.OpenCodeEditor(first) - private(third, "toggleConnection")() - self.assertEqual(self.client.sent[-1][2]["script_key"], "untitled:gaffer:one") + self.assertEqual(self.client.sent[-1][2]["directory"], one["directory"]) # Closing one panel leaves the others (and every offer) alone. del third gc.collect() @@ -277,17 +248,14 @@ def test_each_script_has_its_own_offer_and_conversation(self): self.assertEqual(api.calls[-1], ("release", "channel-2")) self.assertEqual([call for call in api.calls if call[0] == "release"], [("release", "channel-2")]) - def test_a_script_not_offered_is_said_without_connecting(self): + def test_a_missing_offer_is_left_to_the_shared_sidecar(self): script = Script("gaffer:private") api.offers[script.handle] = {"label": "Gaffer: untitled", "offer_key": "gaffer-private", "advertising": False} editor = GafferOpenCodeUI.OpenCodeEditor(script) append = MagicMock() setattr(editor, "_OpenCodeEditor__append", append) - private(editor, "toggleConnection")() - self.assertEqual(self.client.sent, []) - self.assertEqual(api.calls, []) - append.assert_called_once_with("error", "OpenCode Link does not offer this script to OpenCode.") - self.assertFalse(private(editor, "active")) + self.assertEqual(self.client.sent[0][1], "connect") + append.assert_not_called() if __name__ == "__main__": diff --git a/integrations/gaffer/test/python/real_host.py b/integrations/gaffer/test/python/real_host.py index 5cbed6f..9eae451 100644 --- a/integrations/gaffer/test/python/real_host.py +++ b/integrations/gaffer/test/python/real_host.py @@ -71,7 +71,7 @@ state.close() # --- the installed part as Gaffer's interface starts it, and the panel ------------------------------------------ -# Opening the panel does not start its sidecar nor touch the offers: Connect is the consent boundary. +# Opening the panel requests its own conversation immediately, without changing the script's offers. import GafferOpenCode from GafferOpenCodeUI.OpenCodeEditor import OpenCodeEditor root = Gaffer.ApplicationRoot("PrivatePanel") @@ -83,9 +83,9 @@ GafferOpenCode.initialise(types.SimpleNamespace(root=lambda: root), advertise=False) host = GafferOpenCode.currentHost() editor = OpenCodeEditor(script) -assert editor._OpenCodeEditor__channel is None -assert editor._OpenCodeEditor__client is None -assert editor._OpenCodeEditor__connectButton.getText() == "Connect" +assert editor._OpenCodeEditor__channel is not None +assert editor._OpenCodeEditor__client is not None +assert editor._OpenCodeEditor__conversationButton.getText() == "New conversation" print("GAFFER_PANEL_OK") # Each script is its own offer, labelled with its file (numbered when two scripts share it), under its own key. diff --git a/integrations/godot/host/addons/opencode_link/dock.gd b/integrations/godot/host/addons/opencode_link/dock.gd index 193d24a..57d450e 100644 --- a/integrations/godot/host/addons/opencode_link/dock.gd +++ b/integrations/godot/host/addons/opencode_link/dock.gd @@ -1,9 +1,7 @@ @tool extends VBoxContainer ## The OpenCode dock: this project's conversation inside the editor. A plain client of the OpenCode service through a -## Node sidecar (sidecar.cjs, beside this file; Node on PATH, or NEURALNOMADS_GODOT_NODE): Godot offers its project -## by itself (link.gd), the dock only attaches its own conversation to that offer, and Disconnect (or closing the -## editor) releases that conversation only. Other conversations attached to the same project stay attached. +## Private sidecar: Godot offers its project (link.gd), and this dock attaches the current folder's conversation. var link: RefCounted @@ -12,6 +10,13 @@ var _stdio: FileAccess var _stderr: FileAccess var _buffer := PackedByteArray() var _channel := "" +var _target := {} +var _pending: Array[Dictionary] = [] +var _selected := "" +var _draft := false +var _retry_at := 0 +var _launch_at := 0 +var _problem := "" var _next := 0 var _active := false var _connected := false @@ -21,12 +26,10 @@ var _permission := "" var _models: Array = [] var _model := "" -var _session_label := Label.new() var _status_label := Label.new() var _agent_label := Label.new() var _model_button := OptionButton.new() -var _new_button := Button.new() -var _connect_button := Button.new() +var _conversations := OptionButton.new() var _transcript := RichTextLabel.new() var _permission_row := HBoxContainer.new() var _permission_label := Label.new() @@ -37,19 +40,12 @@ var _stop_button := Button.new() func _ready() -> void: _channel = "dock-" + Crypto.new().generate_random_bytes(8).hex_encode() - visibility_changed.connect(func(): - if _active and not is_visible_in_tree(): - disconnect_dock() - ) var header := HBoxContainer.new() var brand := Label.new() brand.text = "OpenCode" header.add_child(brand) - _session_label.text = "disconnected" - _session_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL - _session_label.clip_text = true - header.add_child(_session_label) - _status_label.text = "DISCONNECTED" + header.add_spacer(false) + _status_label.text = "CONNECTING" header.add_child(_status_label) add_child(header) @@ -61,13 +57,19 @@ func _ready() -> void: _model_button.clip_text = true _model_button.item_selected.connect(_select_model) row.add_child(_model_button) - _new_button.text = "New" - _new_button.disabled = true - _new_button.pressed.connect(func(): _connect("new_session")) - row.add_child(_new_button) - _connect_button.text = "Connect" - _connect_button.pressed.connect(toggle_connection) - row.add_child(_connect_button) + _conversations.clip_text = true + _conversations.size_flags_horizontal = Control.SIZE_EXPAND_FILL + _conversations.add_item("New conversation") + _conversations.set_item_metadata(0, "") + _conversations.get_popup().about_to_popup.connect(func(): _send("list", {})) + _conversations.item_selected.connect(func(index: int): + var id: String = _conversations.get_item_metadata(index) + if id == "": + _send("new_session", _target) + else: + _send("open", {"session_id": id}) + ) + row.add_child(_conversations) add_child(row) _transcript.size_flags_vertical = Control.SIZE_EXPAND_FILL @@ -103,15 +105,12 @@ func _ready() -> void: _stop_button.pressed.connect(stop) buttons.add_child(_stop_button) _send_button.text = "Send" - _send_button.disabled = true _send_button.pressed.connect(func(): send_text(_prompt.text)) buttons.add_child(_send_button) add_child(buttons) func _exit_tree() -> void: - if _active: - disconnect_dock() if _stdio != null: # The sidecar ends once its input closes, after releasing its conversations. _stdio.close() @@ -120,19 +119,11 @@ func _exit_tree() -> void: # --- what a user (or a script driving the dock) does --- -func toggle_connection() -> void: - if _active: - disconnect_dock() - else: - _connect("connect") - - func send_text(text: String) -> void: text = text.strip_edges() - if _busy or not _connected or text == "": + if _busy or text == "": return _prompt.text = "" - _append("user", text) _send("prompt", {"text": text}) @@ -140,20 +131,6 @@ func stop() -> void: _send("interrupt", {}) -func disconnect_dock() -> void: - _active = false - _connected = false - _send("close", {}) - _connect_button.text = "Connect" - _status_label.text = "DISCONNECTED" - _permission = "" - _permission_row.hide() - _streaming = false - _set_busy(false) - _new_button.disabled = true - _model_button.disabled = true - - func transcript() -> String: return _transcript.get_parsed_text() @@ -166,7 +143,7 @@ func state() -> Dictionary: static func _node() -> String: var configured := OS.get_environment("NEURALNOMADS_GODOT_NODE") - if configured != "": + if configured != "" and FileAccess.file_exists(configured): return configured var windows := OS.get_name() == "Windows" for directory in OS.get_environment("PATH").split(";" if windows else ":", false): @@ -176,32 +153,70 @@ static func _node() -> String: return "" -func _start() -> bool: - if _pid > 0 and OS.is_process_running(_pid): - return true - var node := _node() - if node == "": - _append("error", "Install Node.js 22 or later, or set NEURALNOMADS_GODOT_NODE.") - return false +func _start() -> void: + var services: Array = link.advertiser_results() + var runtime := "" + var ready := false + var waiting := Time.get_ticks_msec() < _launch_at + for result in services: + if not result.get("outcome") in ["accepted", "renewed"]: + continue + ready = true + var advertised: String = result.get("panel_runtime", "") + if advertised.is_absolute_path() and FileAccess.file_exists(advertised): + runtime = advertised + break + var bun := runtime != "" + if not bun and (ready or not waiting): + runtime = _node() var sidecar := ProjectSettings.globalize_path(get_script().resource_path.get_base_dir().path_join("sidecar.cjs")) if not FileAccess.file_exists(sidecar): - _append("error", "The OpenCode dock's sidecar is missing: install OpenCode Link again (godot_install_host).") - return false - var started := OS.execute_with_pipe(node, [sidecar], false) + _blocked("The OpenCode dock's sidecar is missing: install OpenCode Link again (godot_install_host).") + return + if runtime == "": + if not waiting: + _blocked("No OpenCode runtime, NEURALNOMADS_GODOT_NODE executable, or Node on PATH.") + return + var inherited := OS.get_environment("BUN_BE_BUN") + var had_inherited := OS.has_environment("BUN_BE_BUN") + if bun: + OS.set_environment("BUN_BE_BUN", "1") + else: + OS.unset_environment("BUN_BE_BUN") + var started := OS.execute_with_pipe(runtime, [sidecar], false) + if had_inherited: + OS.set_environment("BUN_BE_BUN", inherited) + else: + OS.unset_environment("BUN_BE_BUN") if started.is_empty(): - _append("error", "Node.js did not start: %s" % node) - return false + _blocked("The OpenCode sidecar runtime did not start.") + return _pid = started.pid _stdio = started.stdio _stderr = started.stderr _buffer = PackedByteArray() - return true + _problem = "" + var params := _target.duplicate() + params.session_id = _selected + params.draft = _draft + _send("connect", params) + for item in _pending: + _send(item.method, item.params) + _pending.clear() + + +func _blocked(message: String) -> void: + if message != _problem: + _problem = message + _event("error", {"message": message}) func _send(method: String, params: Dictionary) -> void: - if method == "close" and (_stdio == null or not OS.is_process_running(_pid)): - return - if not _start(): + if _stdio == null or not OS.is_process_running(_pid): + if method == "interrupt": + _pending.clear() + elif method == "prompt": + _pending.append({"method": method, "params": params}) return _next += 1 var line := JSON.stringify({"id": str(_next), "channel": _channel, "method": method, "params": params}) + "\n" @@ -209,7 +224,16 @@ func _send(method: String, params: Dictionary) -> void: func _process(_delta: float) -> void: + if not _active: + if not is_visible_in_tree(): + return + _active = true + _launch_at = Time.get_ticks_msec() + 5000 + _sync() if _stdio == null: + if Time.get_ticks_msec() >= _retry_at: + _retry_at = Time.get_ticks_msec() + 1000 + _start() return var available := _stdio.get_length() if available > 0: @@ -225,7 +249,7 @@ func _process(_delta: float) -> void: var message: Dictionary = parser.data if message.get("channel") == _channel and message.get("event") is String: _event(message.event, message.get("data", {}) if message.get("data") is Dictionary else {}) - elif message.get("error") is Dictionary and message.get("channel") == null: + elif message.get("error") is Dictionary and not message.has("id"): _event("error", message.error) if _stderr != null and _stderr.get_length() > 0: _stderr.get_buffer(_stderr.get_length()) @@ -233,30 +257,30 @@ func _process(_delta: float) -> void: _stdio = null _stderr = null _pid = -1 - if _active: - _event("error", {"message": "The OpenCode sidecar stopped; choose Connect to start it again."}) + _event("status", {"state": "connecting"}) -func _connect(method: String) -> void: - if link == null or not link.advertising(): - _append("error", "OpenCode Link does not offer this project to OpenCode (OPENCODE_GODOT_OFFER=0?).") +func _sync() -> void: + if link == null or not _active: return var project: String = link.project_dir() + var scene := EditorInterface.get_edited_scene_root() + var directory := project + if scene != null and scene.scene_file_path.begins_with("res://"): + directory = link.native(ProjectSettings.globalize_path(scene.scene_file_path).get_base_dir()) var params: Dictionary = link.info() params.merge({ "script_handle": link.script_handle, "offer_label": link.label(), - "project_key": "project:" + project.to_lower().replace("\\", "/").sha256_text(), - "project_name": link.project_name(), - "directory": project, + "directory": directory, }) - _active = true - _connected = false - _connect_button.text = "Disconnect" - _new_button.disabled = false - _status_label.text = "CONNECTING" - _send_button.disabled = true - _send(method, params) + if params != _target: + if directory != _target.get("directory"): + _selected = "" + _draft = false + _pending.clear() + _target = params + _send("connect", params) func _select_model(index: int) -> void: @@ -282,8 +306,8 @@ func _reply_permission(reply: String) -> void: func _set_busy(busy: bool) -> void: _busy = busy - _stop_button.disabled = not busy - _send_button.disabled = not _connected or busy + _stop_button.disabled = not busy and _status_label.text != "CONNECTING" + _send_button.disabled = busy _prompt.editable = not busy _model_button.disabled = not _connected or busy or _models.is_empty() @@ -307,11 +331,27 @@ func _event(name: String, data: Dictionary) -> void: match name: "session": _connected = true - _session_label.text = "session " + str(data.get("id", "")).right(8) - _session_label.tooltip_text = "Workspace: " + str(data.get("workspace", "")) + _selected = str(data.id) if data.get("id") else "" + _draft = data.get("draft", false) + _conversations.tooltip_text = "Workspace: " + str(data.get("workspace", "")) _agent_label.text = str(data.get("agent", "")) if data.get("agent") else "default agent" _set_model(str(data.get("model", ""))) - _append("system", "Resumed conversation" if data.get("resumed") else "New conversation") + "conversations": + _conversations.clear() + _conversations.add_item("New conversation") + _conversations.set_item_metadata(0, "") + var index := 0 + for item in data.get("entries", []): + var title: String = item.get("title", "") + _conversations.add_item(title if title != "" else "Untitled") + _conversations.set_item_metadata(_conversations.item_count - 1, item.id) + if item.id == _selected: + index = _conversations.item_count - 1 + _conversations.select(index) + "notice": + _append("system", data.message) + "user_message": + _append("user", data.text) "models": _models = data.get("models", []) _model_button.clear() @@ -326,6 +366,7 @@ func _event(name: String, data: Dictionary) -> void: "agent": _agent_label.text = str(data.get("agent", "")) "history": + _streaming = false _transcript.clear() for message in data.get("messages", []): _append(str(message.get("role", "system")), str(message.get("text", ""))) @@ -348,6 +389,10 @@ func _event(name: String, data: Dictionary) -> void: "status": var value := str(data.get("state", "unknown")) _status_label.text = value.to_upper() + if value == "connecting": + _connected = false + _permission = "" + _permission_row.hide() _set_busy(value in ["busy", "retry"]) "error": _append("error", str(data.get("message", "Unknown OpenCode error"))) diff --git a/integrations/godot/host/addons/opencode_link/plugin.cfg b/integrations/godot/host/addons/opencode_link/plugin.cfg index 2c462dc..9db6aa3 100644 --- a/integrations/godot/host/addons/opencode_link/plugin.cfg +++ b/integrations/godot/host/addons/opencode_link/plugin.cfg @@ -3,5 +3,5 @@ name="OpenCode Link" description="Offers this project to OpenCode, and the OpenCode dock." author="NeuralNomads" -version="0.1.0" +version="0.2.0" script="plugin.gd" diff --git a/integrations/godot/host/addons/opencode_link/plugin.gd b/integrations/godot/host/addons/opencode_link/plugin.gd index 511238b..528e9ac 100644 --- a/integrations/godot/host/addons/opencode_link/plugin.gd +++ b/integrations/godot/host/addons/opencode_link/plugin.gd @@ -41,6 +41,8 @@ func _scene_changed(_value: Variant = null) -> void: if link != null: link.refresh_label() link.bump() + if dock != null: + dock._sync() func _process(_delta: float) -> void: diff --git a/integrations/godot/host/addons/opencode_link/service.gd b/integrations/godot/host/addons/opencode_link/service.gd index b76fa3d..7434ba1 100644 --- a/integrations/godot/host/addons/opencode_link/service.gd +++ b/integrations/godot/host/addons/opencode_link/service.gd @@ -247,6 +247,16 @@ func advertise_once() -> Variant: return results +static func _advertise_result(service: String, label: String, answer: Array) -> Dictionary: + var said := outcome("advertise", answer[0], answer[1]) + var result := {"service": service, "label": label, "outcome": said} + if said in ["accepted", "renewed"]: + var runtime: Variant = answer[1].output.get("panel_runtime") + if runtime is String and runtime.is_absolute_path(): + result.panel_runtime = runtime + return result + + func _renew(offers: Array, project: String) -> Array: _count += 1 var results := [] @@ -256,9 +266,9 @@ func _renew(offers: Array, project: String) -> Array: var target: Array = _targets[name] for offer in offers: var answer := call_rpc(target[0], "advertise", offer, target[1], RENEW_TIMEOUT_MS) - var said := outcome("advertise", answer[0], answer[1]) - results.append({"service": name, "label": offer.label, "outcome": said}) - failed = failed or not said in ["accepted", "renewed"] + var result := _advertise_result(name, offer.label, answer) + results.append(result) + failed = failed or not result.outcome in ["accepted", "renewed"] if not failed: return results var found := {} @@ -273,12 +283,12 @@ func _renew(offers: Array, project: String) -> Array: reached = true var taken := false for offer in offers: - var said := "error" + var sent := [500, null] if answer[0] == 200: - var sent := call_rpc(service, "advertise", offer, directory, maxi(500, deadline - Time.get_ticks_msec())) - said = outcome("advertise", sent[0], sent[1]) - results.append({"service": service.file, "label": offer.label, "outcome": said}) - taken = taken or said in ["accepted", "renewed"] + sent = call_rpc(service, "advertise", offer, directory, maxi(500, deadline - Time.get_ticks_msec())) + var result := _advertise_result(service.file, offer.label, sent) + results.append(result) + taken = taken or result.outcome in ["accepted", "renewed"] if taken: found[service.file] = [service, directory] break diff --git a/integrations/godot/plugin/README.md b/integrations/godot/plugin/README.md index 123183c..382e4e1 100644 --- a/integrations/godot/plugin/README.md +++ b/integrations/godot/plugin/README.md @@ -1,6 +1,6 @@ # OpenCode for Godot (preview) -Read, edit and check the project open in Godot from an OpenCode conversation. Requires Godot 4.7 or later in the 4.x series and OpenCode 2.2 or later. The optional editor dock needs Node.js 22 or later; discovery and the editor tools do not. +Read, edit and check the project open in Godot from an OpenCode conversation. Requires Godot 4.7 or later in the 4.x series and OpenCode 2.2 or later. ## Install @@ -31,9 +31,9 @@ Edits to scene-owned nodes and stored properties are grouped into one undo actio ## Editor dock -Open **OpenCode** and select **Connect**. It creates or resumes the project conversation and displays the agent, model, streamed replies and tool calls. Use **Stop** to interrupt a response and **Disconnect** to release the dock's attachment. You can connect an independent OpenCode conversation to the same editor. Duplicate offer labels are refused by the dock rather than choosing an editor arbitrarily. +Open the **OpenCode** dock. It automatically resumes the latest conversation in the scene’s folder, or the project folder when no saved scene is open. Open another scene in the same folder to keep the selected conversation. The selector lists the folder’s conversations; **New conversation** creates nothing until you send a message. Use **Stop** to interrupt or clear queued prompts. -The add-on handles discovery and editor requests in GDScript using the local offer protocol. The dock starts a Node client over private pipes, using OpenCode's SDK for sessions and events, following Gaffer's panel. Node is found on `PATH` or via `NEURALNOMADS_GODOT_NODE`. The dock never starts OpenCode. Set `OPENCODE_GODOT_OFFER=0` in the editor environment to disable advertising. +The dock uses OpenCode’s executable. Node.js 22+ (`NEURALNOMADS_GODOT_NODE` or `PATH`) is only a fallback. The dock never starts the OpenCode service. Set `OPENCODE_GODOT_OFFER=0` to disable advertising. ## Tests diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.2.0.zip similarity index 73% rename from integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip rename to integrations/godot/plugin/host/godot/opencode_link-0.2.0.zip index c34731c..65c6e82 100644 Binary files a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip and b/integrations/godot/plugin/host/godot/opencode_link-0.2.0.zip differ diff --git a/integrations/godot/plugin/package.json b/integrations/godot/plugin/package.json index 359f6d3..a91b08b 100644 --- a/integrations/godot/plugin/package.json +++ b/integrations/godot/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@neuralnomads/opencode-godot", - "version": "0.1.0", + "version": "0.2.0", "description": "OpenCode for Godot: GDScript in the editor as one undo action, checks and runs in a background Godot, through an authenticated local add-on, with an optional in-editor conversation dock.", "license": "MIT", "type": "module", @@ -59,10 +59,10 @@ "host": { "app": "godot", "protocol": 1, - "range": "^0.1.0", + "range": "^0.2.0", "appVersions": ">=4.7 <5", - "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "49bde399ddbaf859baae7d6686f8b4ee849ef82b15fad28fc132db9b7b0a5b2b" + "payload": "host/godot/opencode_link-0.2.0.zip", + "sha256": "43059cb68ada77d6cb55cf9d20b745c07ca46455a68c12551c1034ad7701e127" } } } diff --git a/integrations/godot/plugin/scripts/build-host.ts b/integrations/godot/plugin/scripts/build-host.ts index b9b5475..5653c6b 100644 --- a/integrations/godot/plugin/scripts/build-host.ts +++ b/integrations/godot/plugin/scripts/build-host.ts @@ -18,6 +18,8 @@ const version = /^version="([^"]+)"$/m.exec(readFileSync(join(addon, "plugin.cfg if (version !== pkg.version) throw new Error("Host and plugin versions differ") const check = process.argv.includes("--check") const bundle = await build({ + absWorkingDir: join(root, "..", "..", ".."), + preserveSymlinks: true, entryPoints: [join(root, "src", "sidecar.ts")], bundle: true, format: "cjs", diff --git a/integrations/godot/plugin/src/sidecar-core.ts b/integrations/godot/plugin/src/sidecar-core.ts index 8d15e74..251d504 100644 --- a/integrations/godot/plugin/src/sidecar-core.ts +++ b/integrations/godot/plugin/src/sidecar-core.ts @@ -1,385 +1,16 @@ -// The Godot dock's conversations: a plain client of the OpenCode service. The editor offers its project by itself -// (OpenCode Link); the dock only attaches its own conversation to that offer, and never announces or withdraws -// offers. Credentials stay in this process: SDK and host errors are never forwarded. -import type { OpenCode } from "@opencode/client" -import { rpcDefinition } from "../../../../packages/integration-kit/src/contract.ts" -import { requestHost as kitRequestHost } from "../../../../packages/integration-kit/src/host-client.ts" - -export type Api = ReturnType -type Rpc = Partial< - Record< - "hosts" | "attachHost" | "detachHost" | "bindingRead", - (input: object, options: object) => Promise> - > -> -type ModelRef = { id: string; providerID: string; variant?: string } -type Channel = { - id: string - directory: string - sessionID: string - label: string - offerID: string - host: { host: string; port: number; token: string } - handle: string - abort: AbortController - timer?: NodeJS.Timeout - checking: boolean - tools: Map - model?: ModelRef -} -export type PanelRequest = { id: string; channel: string; method: string; params?: Record } - -// The session metadata naming the Godot project a conversation belongs to: Connect takes that one back. -export const PROJECT_MARKER = "opencode_godot_project" - -// A message of this sidecar's own, safe to show in the panel. -class PanelError extends Error {} - -// An error in one line for the panel: its first line, bounded, without a token, an authorization or a port. -export function briefly(error: unknown) { - const text = String((error as { message?: unknown } | null)?.message ?? error ?? "unknown error") - .split(/\r?\n/)[0] - ?.replace(/\b[0-9a-f]{32,}\b/gi, "…") - .replace(/(basic|bearer)\s+\S+/gi, "$1 …") - .replace(/\b(port\s+|:)\d{2,5}\b/gi, "$1…") - .slice(0, 240) - return `${text || "unknown error"}${/[.!?]$/.test(text ?? "") ? "" : "."}` -} - -const modelKey = (model: ModelRef | undefined) => - model ? `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}` : "" - -type Part = { type?: string; text?: string; name?: string; state?: { status?: string } } -type Message = { type?: string; text?: string; content?: Part[] } -type EventData = { - sessionID?: string - delta?: string - id?: string - name?: string - action?: string - agent?: string - resources?: string[] - model?: ModelRef -} - -function history(messages: ReadonlyArray) { - return messages.flatMap((message) => { - if (message.type === "user") return [{ role: "user", text: message.text ?? "" }] - if (message.type !== "assistant") return [] - return (message.content ?? []).flatMap((part) => { - if (part.type === "text") return [{ role: "assistant", text: part.text ?? "" }] - if (part.type === "tool") return [{ role: "tool", text: `${part.name} / ${part.state?.status ?? "unknown"}` }] - return [] - }) - }) -} - -export function createPanel(deps: { - // The running OpenCode service, or undefined when none is running (never started from here). - discover: () => Promise - send: (message: unknown) => void - requestHost?: typeof kitRequestHost - // How long Connect waits for this project's offer (the editor offers it every few seconds). - offerWaitMs?: number - checkEveryMs?: number -}) { - const requestHost = deps.requestHost ?? kitRequestHost - // A Location opened for the panel loads its plugins first, which took tens of seconds in a trial. - const offerWaitMs = deps.offerWaitMs ?? 30_000 - const checkEveryMs = deps.checkEveryMs ?? 5_000 - const channels = new Map() - let client: Api | undefined - let rpc: Rpc = {} - const event = (c: { id: string }, name: string, data: object) => deps.send({ channel: c.id, event: name, data }) - const options = (c: { directory: string }) => ({ - location: { directory: c.directory }, - signal: AbortSignal.timeout(3000), - }) - const host = (c: Channel, method: "cancel" | "resume") => - requestHost(c.host, method, { script_handle: c.handle, session_id: c.sessionID }, { timeoutMs: 2000 }) - - async function api() { - if (client) return client - const found = await deps.discover() - if (!found) throw new PanelError("Start OpenCode before connecting the panel.") - client = found - rpc = found.rpc(rpcDefinition("neuralnomads.godot", "native") as never) as unknown as Rpc - return client - } - - // This project's offer: the one with its label among the offered hosts (offer keys stay private to the service). - async function findOffer(c: { directory: string; label: string }) { - const until = Date.now() + offerWaitMs - for (;;) { - let result: { offers?: unknown } | undefined - try { - result = (await rpc.hosts?.({}, options(c))) as typeof result - } catch (error) { - // The first call in the project's folder: OpenCode opens that Location and loads its plugins meanwhile, and - // the integration's RPC is not there yet (a CodeNomad conversation's own Location is long loaded). - if ( - !/RPC is unavailable/i.test(String((error as { message?: unknown })?.message ?? error)) || - Date.now() > until - ) - throw error - await new Promise((resolve) => setTimeout(resolve, 1_000)) - continue - } - const offers = ((result?.offers ?? []) as Array<{ label: string; offerID: string }>).filter( - (offer) => offer.label === c.label, - ) - if (offers.length > 1) - throw new PanelError( - `Several Godot editors offer ${c.label}: attach this conversation from OpenCode (godot_hosts).`, - ) - if (offers[0]) return offers[0] - if (Date.now() > until) throw new PanelError("This project is not offered to OpenCode yet; choose Connect again.") - await new Promise((resolve) => setTimeout(resolve, 1_000)) - } - } - - async function attached(c: Channel) { - const read = await rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)) - return read?.state === "attached" && (read.binding as { offerID?: string } | undefined)?.offerID === c.offerID - } - - // The project's own conversation, when one is marked for it and still open. - async function markedSession(service: Api, directory: string, key: string) { - let cursor: string | undefined - for (let page = 0; page < 10; page += 1) { - const listed = await service.session.list({ directory, order: "desc", limit: 100, cursor }) - const found = listed.data.find( - (candidate) => - !candidate.time?.archived && - (candidate.metadata as Record | undefined)?.[PROJECT_MARKER] === key, - ) - if (found) return found - cursor = listed.cursor.next ?? undefined - if (!cursor) return undefined - } - return undefined - } - - // Closing releases this panel's conversation only: the offer stays for every other conversation. - async function close(c: Channel) { - if (channels.get(c.id) === c) channels.delete(c.id) - if (c.timer) clearInterval(c.timer) - c.abort.abort() - await host(c, "cancel").catch(() => {}) - // Another client may have moved the conversation to another host: never detach that binding. - await attached(c) - .then((still) => (still ? rpc.detachHost?.({ sessionID: c.sessionID }, options(c)) : undefined)) - .catch(() => {}) - } - - function forward(c: Channel, type: string, data: EventData) { - if (type === "session.model.selected") { - c.model = data.model - event(c, "model", { selected: modelKey(c.model) }) - } else if (type === "session.agent.selected") event(c, "agent", { agent: data.agent ?? null }) - else if (type === "session.execution.started") event(c, "status", { state: "busy" }) - else if (type === "session.text.started") event(c, "assistant_start", {}) - else if (type === "session.text.delta") event(c, "assistant_delta", { text: data.delta ?? "" }) - else if (type === "session.text.ended") event(c, "assistant_end", {}) - else if (type === "session.tool.input.started") { - c.tools.set(String(data.id), String(data.name ?? "tool")) - event(c, "tool", { id: data.id, name: data.name, state: "starting" }) - } else if (type === "session.tool.success" || type === "session.tool.failed") { - const name = c.tools.get(String(data.id)) - c.tools.delete(String(data.id)) - event(c, "tool", { id: data.id, name, state: type === "session.tool.success" ? "completed" : "failed" }) - } else if (type === "permission.asked") - event(c, "permission", { request_id: data.id, action: data.action, resources: data.resources ?? [] }) - else if (type === "session.execution.succeeded" || type === "session.idle") event(c, "status", { state: "idle" }) - else if (type === "session.execution.interrupted" || type === "session.execution.failed") { - if (type === "session.execution.failed") event(c, "error", { message: "OpenCode execution failed." }) - event(c, "status", { state: "idle" }) - void host(c, "cancel").catch(() => {}) - } - } - - async function stream(c: Channel, service: Api) { - try { - for await (const item of service.event.subscribe({ signal: c.abort.signal })) { - const data = item.data as unknown as EventData - if (data?.sessionID === c.sessionID) forward(c, item.type, data) - } - } catch { - // ended below - } - if (!c.abort.signal.aborted) event(c, "error", { message: "OpenCode disconnected; choose Connect to reconnect." }) - } - - function watch(c: Channel) { - let warned = false - c.timer = setInterval(() => { - if (c.checking) return - c.checking = true - void api() - .then(() => attached(c)) - .then((still) => { - if (!still) throw new Error("detached") - warned = false - }) - .catch(() => { - client = undefined - if (!warned) - event(c, "error", { message: "Conversation detached or service unavailable; choose Connect to reconnect." }) - warned = true - }) - .finally(() => { - c.checking = false - }) - }, checkEveryMs) - c.timer.unref?.() - } - - // A failed Connect says which step failed and why, in a line (never a credential): the user knows what to check. - const step = async (doing: string, work: () => Promise): Promise => { - try { - return await work() - } catch (error) { - if (error instanceof PanelError) throw error - throw new PanelError( - `Connect failed while ${doing}: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - ) - } - } - - async function connect(id: string, params: Record, fresh: boolean) { - const previous = channels.get(id) - if (previous) await close(previous) - if (params.host !== "127.0.0.1" || !Number.isInteger(params.port) || !/^[0-9a-f]{64}$/.test(String(params.token))) - throw new Error("Invalid host endpoint.") - const directory = String(params.directory ?? "") - const label = String(params.offer_label ?? "") - const key = String(params.project_key ?? "") - const handle = String(params.script_handle ?? "") - if (!directory || !label || !key || !handle) throw new Error("Incomplete connect request.") - const service = await step("reaching OpenCode", api) - // The project's conversation, unless New asked for another one. - const known = fresh - ? undefined - : await step("finding this project's conversation", () => markedSession(service, directory, key)) - const session = - known ?? - (await step("creating this project's conversation", () => - service.session.create({ - title: `Godot: ${String(params.project_name || "project")}`, - location: { directory }, - metadata: { [PROJECT_MARKER]: key }, - }), - )) - const c: Channel = { - id, - directory, - sessionID: session.id, - label, - offerID: "", - host: { host: "127.0.0.1", port: Number(params.port), token: String(params.token) }, - handle, - abort: new AbortController(), - checking: false, - tools: new Map(), - model: (session as { model?: ModelRef }).model, - } - try { - const offer = await step("finding this project's offer", () => findOffer(c)) - const result = await step("attaching the conversation to this project", async () => - rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID }, options(c)), - ) - if (result?.outcome === "busy") - throw new PanelError("This conversation is attached to another application; detach it there first.") - if (result?.outcome !== "attached") throw new PanelError("Godot attachment was refused.") - c.offerID = offer.offerID - channels.set(id, c) - watch(c) - void stream(c, service) - const [messages, models, configured, active] = await step("loading the conversation", () => - Promise.all([ - service.message.list({ sessionID: c.sessionID, order: "desc", limit: 200 }), - service.model.list({ location: { directory } }), - service.model.default({ location: { directory } }), - service.session.active(), - ]), - ) - if (!c.model && configured.data) c.model = configured.data as ModelRef - event(c, "session", { - id: c.sessionID, - resumed: Boolean(known), - model: modelKey(c.model), - agent: (session as { agent?: string }).agent ?? null, - workspace: directory, - }) - event(c, "models", { - selected: modelKey(c.model), - models: models.data - .filter((model) => model.enabled) - .map((model) => ({ id: model.id, provider_id: model.providerID, name: model.name })), - }) - event(c, "history", { messages: history([...messages.data].reverse() as never) }) - event(c, "status", { - state: (active as Record)[c.sessionID]?.type === "running" ? "busy" : "idle", - }) - } catch (error) { - await close(c) - throw error - } - } - - async function act(c: Channel, method: string, params: Record) { - if (method === "close") return await close(c) - const service = await api() - if (method === "interrupt") { - await host(c, "cancel").catch(() => {}) - await service.session.interrupt({ sessionID: c.sessionID, resume: false }) - } else if (method === "prompt") { - if (!(await attached(c))) throw new PanelError("Godot was detached; choose Connect to attach again.") - await host(c, "resume") - await service.session.prompt({ sessionID: c.sessionID, text: String(params.text ?? "") }) - } else if (method === "switch_model") { - const key = String(params.model ?? "") - const catalog = await service.model.list({ location: { directory: c.directory } }) - const selected = catalog.data.find((model) => model.enabled && `${model.providerID}/${model.id}` === key) - if (!selected) throw new PanelError("This model is not available in this workspace.") - c.model = { id: selected.id, providerID: selected.providerID } - await service.session.switchModel({ sessionID: c.sessionID, model: c.model }) - event(c, "model", { selected: modelKey(c.model) }) - } else if (method === "permission_reply") { - const decision = params.reply - if (decision !== "once" && decision !== "reject") throw new Error("Invalid permission answer.") - await service.permission.reply({ sessionID: c.sessionID, requestID: String(params.request_id), decision }) - } else throw new Error("Unknown panel action.") - } - - async function dispatch(request: PanelRequest) { - try { - const params = request.params ?? {} - if (request.method === "connect" || request.method === "new_session") - await connect(request.channel, params, request.method === "new_session") - else { - const c = channels.get(request.channel) - if (c) await act(c, request.method, params) - else if (request.method !== "close") throw new PanelError("Choose Connect first.") - } - deps.send({ id: request.id, result: {} }) - } catch (error) { - deps.send({ - channel: request.channel, - event: "error", - data: { - message: - error instanceof PanelError - ? error.message - : `The panel action failed: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - }, - }) - deps.send({ id: request.id, error: { message: "Panel action failed." } }) - } - } - - return { - dispatch, - closeAll: () => Promise.allSettled([...channels.values()].map(close)), - } -} +import { + createPanel as createChat, + type PanelDependencies, + type PanelHost, +} from "../../../../packages/integration-kit/src/panel.ts" + +export { type Api, briefly, type PanelRequest } from "../../../../packages/integration-kit/src/panel.ts" + +export const panelHost = { + app: "Godot", + rpcID: "neuralnomads.godot", + document: "project", + duplicateOffer: "Godot editors", + agent: true, +} satisfies PanelHost +export const createPanel = (deps: PanelDependencies) => createChat(panelHost, deps) diff --git a/integrations/godot/plugin/src/sidecar.ts b/integrations/godot/plugin/src/sidecar.ts index 5aba5ff..535b9cc 100644 --- a/integrations/godot/plugin/src/sidecar.ts +++ b/integrations/godot/plugin/src/sidecar.ts @@ -1,35 +1,4 @@ -// The OpenCode dock's private JSONL client, built into the add-on as sidecar.cjs and run by Node from the editor. -import readline from "node:readline" -import { OpenCode } from "@opencode/client" -import { discoverService } from "./service.ts" -import { createPanel, type PanelRequest } from "./sidecar-core.ts" +import { runPanel } from "../../../../packages/integration-kit/src/panel-pipes.ts" +import { panelHost } from "./sidecar-core.ts" -const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`) -const panel = createPanel({ - send, - discover: async () => { - const endpoint = await discoverService() - return endpoint && OpenCode.make({ baseUrl: endpoint.url, headers: endpoint.headers, fetch: endpoint.fetch }) - }, -}) -const queues = new Map>() - -const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }) -input.on("line", (line) => { - if (!line.trim()) return - try { - if (Buffer.byteLength(line) > 1024 * 1024) throw new Error("Request too large") - const request = JSON.parse(line) as PanelRequest - if (!request.id || !request.channel || !request.method) throw new Error("Invalid request") - const next = (queues.get(request.channel) ?? Promise.resolve()).then(() => panel.dispatch(request)) - queues.set(request.channel, next) - void next.finally(() => { - if (queues.get(request.channel) === next) queues.delete(request.channel) - }) - } catch { - send({ error: { message: "Invalid panel request." } }) - } -}) -input.on("close", () => { - void panel.closeAll().finally(() => process.exit(0)) -}) +runPanel(panelHost) diff --git a/integrations/godot/test/godot.test.ts b/integrations/godot/test/godot.test.ts index 1469f8e..e69a579 100644 --- a/integrations/godot/test/godot.test.ts +++ b/integrations/godot/test/godot.test.ts @@ -224,22 +224,17 @@ describe("OpenCode Link in a real Godot editor", { skip: !godot, concurrency: fa assert.match(crash.crash, /Program crashed/) }) - it("the dock reaches its sidecar (Node) from the editor", async () => { + it("the visible dock starts its sidecar automatically", async () => { await code( - 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.found = dock != null\ndock.toggle_connection()', + 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.found = dock != null\ndock.reparent(EditorInterface.get_base_control())\ndock.show()', ) - const transcript = await until( - async () => { - const read = await code( - 'result.text = EditorInterface.get_base_control().find_child("OpenCode", true, false).transcript()', - { read_only: true }, - ) - return /Connect failed|Start OpenCode/.test(read.result.text) ? read.result.text : "" - }, - 30_000, - "the dock's answer", + await until(() => service.calls.some(({ method }) => method === "hosts"), 30_000, "the dock's offer lookup") + const read = await code( + 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.text = dock.transcript()\nresult.status = dock.state().status', + { read_only: true }, ) - assert.match(transcript, /Connect failed while finding this project's conversation|Start OpenCode/) + assert.equal(read.result.status, "CONNECTING", read.result.text) + assert.equal(read.result.text, "") }) it("says that the editor crashed, with its log", async () => { diff --git a/integrations/godot/test/helpers.ts b/integrations/godot/test/helpers.ts index 838f274..696f96e 100644 --- a/integrations/godot/test/helpers.ts +++ b/integrations/godot/test/helpers.ts @@ -205,7 +205,12 @@ export async function fakeService(plugin: LoadedPlugin, root: string, loadedAt: const input = ((await body(request)) as { input?: unknown })?.input const directory = url.searchParams.get("location[directory]") calls.push({ method: match[1] ?? "", directory }) - if (!directory || !loadedAt(directory)) return send(400, { _tag: "RpcError", type: "rpc.unavailable" }) + if (!directory || !loadedAt(directory)) + return send(400, { + _tag: "RpcError", + type: "rpc.unavailable", + message: "RPC is unavailable: neuralnomads.godot", + }) return send(200, { output: await plugin.rpc(match[1] ?? "", input as object) }) } send(404, { type: "not_found" }) diff --git a/integrations/godot/test/panel.test.ts b/integrations/godot/test/panel.test.ts deleted file mode 100644 index 1c70871..0000000 --- a/integrations/godot/test/panel.test.ts +++ /dev/null @@ -1,386 +0,0 @@ -import assert from "node:assert/strict" -import { spawnSync } from "node:child_process" -import { mkdtempSync, rmSync } from "node:fs" -import { tmpdir } from "node:os" -import { join } from "node:path" -import { it } from "node:test" -import { build } from "esbuild" -import { type Api, createPanel, PROJECT_MARKER } from "../plugin/src/sidecar-core.ts" - -const KEY = "project:trial" -const HOST = { host: "127.0.0.1", port: 4242, token: "a".repeat(64) } -const CONNECT = { - ...HOST, - protocol: 1, - script_handle: "godot:1:trial", - offer_label: "Godot: Trial — main.tscn", - project_key: KEY, - project_name: "Trial", - directory: join(tmpdir(), "godot-trial"), -} - -it("the add-on's sidecar runs with Node as the add-on ships it", async () => { - const folder = mkdtempSync(join(tmpdir(), "godot-dock-")) - try { - await build({ - entryPoints: [join(import.meta.dirname, "..", "plugin", "src", "sidecar.ts")], - bundle: true, - format: "cjs", - platform: "node", - target: "node22", - outfile: join(folder, "sidecar.cjs"), - logLevel: "warning", - }) - const sidecar = spawnSync(process.execPath, [join(folder, "sidecar.cjs")], { - input: "not json\n", - encoding: "utf8", - windowsHide: true, - timeout: 20_000, - // Never discover the OpenCode service of the computer running the test. - env: { ...process.env, XDG_STATE_HOME: join(folder, "state") }, - }) - assert.equal(sidecar.status, 0, sidecar.stderr) - assert.deepEqual(JSON.parse(sidecar.stdout), { error: { message: "Invalid panel request." } }) - } finally { - rmSync(folder, { recursive: true, force: true }) - } -}) - -type Item = { type: string; data: Record } -type Input = { offerID: string; sessionID: string } -type Out = { id?: string; event?: string; error?: unknown; data: Record & { message?: string } } - -function fakeService() { - const calls: Array<[string, unknown]> = [] - const bindings = new Map() - const listeners = new Set<(item: Item) => void>() - let offers = [ - { offerID: "offer_other", label: "Godot: Other — main.tscn", protocol: "ok" }, - { offerID: "offer_trial", label: "Godot: Trial — main.tscn", protocol: "ok" }, - ] - let created = 0 - // The first calls of a Location OpenCode is still opening: the integration's RPC is not there yet. - let unavailable = 0 - const record = - (name: string, result: (input: Input) => unknown = () => ({})) => - async (input: Input) => { - calls.push([name, input]) - return result(input) - } - const rpc = new Proxy({} as Record, { - get: (_target, name: string) => { - const methods: Record unknown> = { - hosts: () => { - if (unavailable > 0) { - unavailable -= 1 - throw new Error("RPC is unavailable: neuralnomads.godot") - } - return { offers } - }, - attachHost: ({ offerID, sessionID }) => { - const bound = bindings.get(sessionID) - if (bound && bound !== offerID) return { outcome: "busy" } - bindings.set(sessionID, offerID) - return { outcome: "attached" } - }, - detachHost: ({ sessionID }) => ({ outcome: bindings.delete(sessionID) ? "detached" : "none" }), - bindingRead: ({ sessionID }) => - bindings.has(sessionID) - ? { state: "attached", binding: { offerID: bindings.get(sessionID), label: "x" } } - : { state: "none" }, - } - return record(`rpc.${name}`, methods[name] ?? (() => ({ outcome: "refused" }))) - }, - }) - const api = { - rpc: () => rpc, - session: { - list: record("session.list", () => ({ - data: [ - { id: "ses_archived", metadata: { [PROJECT_MARKER]: KEY }, time: { archived: 1 } }, - { id: "ses_foreign", metadata: { [PROJECT_MARKER]: "project:other" }, time: {} }, - { id: "ses_old", metadata: { [PROJECT_MARKER]: KEY }, time: {} }, - ], - cursor: {}, - })), - create: record("session.create", () => ({ id: `ses_new${++created}` })), - prompt: record("session.prompt"), - interrupt: record("session.interrupt"), - switchModel: record("session.switchModel"), - active: record("session.active", () => ({})), - }, - message: { - list: record("message.list", () => ({ - data: [ - { type: "assistant", content: [{ type: "text", text: "Done." }] }, - { type: "user", text: "Add a sphere" }, - ], - })), - }, - model: { - list: record("model.list", () => ({ - data: [ - { id: "m1", providerID: "p", name: "M1", enabled: true }, - { id: "m2", providerID: "p", name: "M2", enabled: false }, - ], - })), - default: record("model.default", () => ({ data: { id: "m1", providerID: "p" } })), - }, - permission: { reply: record("permission.reply") }, - event: { - subscribe: ({ signal }: { signal: AbortSignal }) => - (async function* () { - const queue: Item[] = [] - let wake = () => {} - const listener = (item: Item) => { - queue.push(item) - wake() - } - listeners.add(listener) - signal.addEventListener("abort", () => wake(), { once: true }) - try { - while (!signal.aborted) { - const item = queue.shift() - if (item) yield item - else - await new Promise((resolve) => { - wake = resolve - }) - } - } finally { - listeners.delete(listener) - } - })(), - }, - } - return { - api: api as unknown as Api, - calls, - bindings, - setOffers: (next: typeof offers) => { - offers = next - }, - setUnavailable: (calls: number) => { - unavailable = calls - }, - push: async (item: Item) => { - for (const listener of listeners) listener(item) - await new Promise((resolve) => setImmediate(resolve)) - }, - } -} - -function harness(offerWaitMs = -1) { - const service = fakeService() - const out: Out[] = [] - const host: Array<[string, unknown]> = [] - const panel = createPanel({ - discover: async () => service.api, - send: (message) => out.push(message as Out), - requestHost: async (_endpoint, method, params) => { - host.push([method, params]) - return {} - }, - offerWaitMs, - checkEveryMs: 60_000, - }) - let id = 0 - const call = (method: string, params: Record = {}, channel = "panel") => - panel.dispatch({ id: String(++id), channel, method, params }) - const events = (name: string) => out.filter((message) => message.event === name).map((message) => message.data) - return { service, out, host, panel, call, events } -} - -it("Connect resumes the project's marked conversation and attaches it to that project's offer only", async () => { - const { service, host, panel, call, events } = harness() - try { - await call("connect", CONNECT) - assert.equal(service.calls.filter(([name]) => name === "session.create").length, 0) - assert.deepEqual(service.bindings, new Map([["ses_old", "offer_trial"]])) - assert.deepEqual(events("session")[0], { - id: "ses_old", - resumed: true, - model: "p/m1", - agent: null, - workspace: CONNECT.directory, - }) - assert.deepEqual(events("history")[0]?.messages, [ - { role: "user", text: "Add a sphere" }, - { role: "assistant", text: "Done." }, - ]) - assert.deepEqual(events("models")[0], { selected: "p/m1", models: [{ id: "m1", provider_id: "p", name: "M1" }] }) - assert.deepEqual(events("status").at(-1), { state: "idle" }) - - // Streaming: this conversation's events only. - await service.push({ type: "session.text.delta", data: { sessionID: "ses_other", delta: "no" } }) - await service.push({ type: "session.execution.started", data: { sessionID: "ses_old" } }) - await service.push({ type: "session.text.delta", data: { sessionID: "ses_old", delta: "Hel" } }) - await service.push({ type: "session.text.delta", data: { sessionID: "ses_old", delta: "lo" } }) - await service.push({ - type: "permission.asked", - data: { sessionID: "ses_old", id: "per_1", action: "godot_execute_code" }, - }) - assert.deepEqual(events("assistant_delta"), [{ text: "Hel" }, { text: "lo" }]) - assert.deepEqual(events("status").at(-1), { state: "busy" }) - assert.deepEqual(events("permission"), [{ request_id: "per_1", action: "godot_execute_code", resources: [] }]) - - await call("permission_reply", { request_id: "per_1", reply: "once" }) - await call("prompt", { text: "Add a light" }) - await call("switch_model", { model: "p/m1" }) - await call("interrupt") - const names = service.calls.map(([name]) => name) - assert.deepEqual(service.calls.find(([name]) => name === "permission.reply")?.[1], { - sessionID: "ses_old", - requestID: "per_1", - decision: "once", - }) - assert.deepEqual(service.calls.find(([name]) => name === "session.prompt")?.[1], { - sessionID: "ses_old", - text: "Add a light", - }) - assert.ok(names.includes("session.switchModel") && names.includes("session.interrupt")) - assert.deepEqual(host, [ - ["resume", { script_handle: "godot:1:trial", session_id: "ses_old" }], - ["cancel", { script_handle: "godot:1:trial", session_id: "ses_old" }], - ]) - - // New: another conversation, marked for the same project, on the same offer; the previous one is released. - await call("new_session", CONNECT) - const created = service.calls.find(([name]) => name === "session.create")?.[1] - assert.deepEqual(created, { - title: "Godot: Trial", - location: { directory: CONNECT.directory }, - metadata: { [PROJECT_MARKER]: KEY }, - }) - assert.deepEqual(service.bindings, new Map([["ses_new1", "offer_trial"]])) - assert.deepEqual(events("session").at(-1), { - id: "ses_new1", - resumed: false, - model: "p/m1", - agent: null, - workspace: CONNECT.directory, - }) - - // Close: this conversation only; the offer is never withdrawn and never announced by the panel. - await call("close") - assert.deepEqual(service.bindings, new Map()) - assert.deepEqual(host.at(-1), ["cancel", { script_handle: "godot:1:trial", session_id: "ses_new1" }]) - await call("prompt", { text: "late" }) - assert.equal(events("error").at(-1)?.message, "Choose Connect first.") - const rpcMethods = new Set(service.calls.map(([name]) => name).filter((name) => name.startsWith("rpc."))) - assert.deepEqual(rpcMethods, new Set(["rpc.hosts", "rpc.attachHost", "rpc.bindingRead", "rpc.detachHost"])) - } finally { - await panel.closeAll() - } -}) - -it("Connect refuses an ambiguous or absent offer, keeps a conversation attached elsewhere and hides SDK errors", async () => { - const { service, panel, call, events } = harness() - try { - service.setOffers([ - { offerID: "offer_a", label: "Godot: Trial — main.tscn", protocol: "ok" }, - { offerID: "offer_b", label: "Godot: Trial — main.tscn", protocol: "ok" }, - ]) - await call("connect", CONNECT) - assert.match(String(events("error").at(-1)?.message), /^Several Godot editors offer Godot: Trial — main\.tscn/) - service.setOffers([]) - await call("connect", CONNECT) - assert.equal(events("error").at(-1)?.message, "This project is not offered to OpenCode yet; choose Connect again.") - assert.equal(service.calls.filter(([name]) => name === "rpc.attachHost").length, 0) - - // The marked conversation is attached to another application: never taken from it. - service.setOffers([ - { offerID: "offer_trial", label: "Godot: Trial — main.tscn", protocol: "ok" }, - { offerID: "offer_blender", label: "Blender: trial.blend", protocol: "ok" }, - ]) - service.bindings.set("ses_old", "offer_blender") - await call("connect", CONNECT) - assert.match(String(events("error").at(-1)?.message), /attached to another application/) - assert.equal(service.bindings.get("ses_old"), "offer_blender") - - // Attached here, then moved elsewhere by another client: closing leaves that binding alone. - service.bindings.clear() - await call("connect", CONNECT) - service.bindings.set("ses_old", "offer_blender") - await call("close") - assert.equal(service.bindings.get("ses_old"), "offer_blender") - - for (const bad of [{ token: "short" }, { host: "10.0.0.1" }, { offer_label: "" }]) { - await call("connect", { ...CONNECT, ...bad }) - assert.match( - String(events("error").at(-1)?.message), - /^The panel action failed: (Invalid host endpoint|Incomplete connect request)\. Check that OpenCode runs/, - ) - } - service.bindings.clear() - await call("connect", CONNECT) - ;(service.api.session as { prompt: unknown }).prompt = async () => { - throw new Error(`token ${HOST.token} on port ${HOST.port}`) - } - await call("prompt", { text: "x" }) - const message = events("error").at(-1)?.message as string - assert.ok(!message.includes(HOST.token) && !message.includes(String(HOST.port)), message) - } finally { - await panel.closeAll() - } -}) - -// Real trial: the first Connect failed while OpenCode opened the script's folder (its Location) and loaded its plugins -// ("RPC is unavailable"); it was read as the CodeNomad conversation attached to the same script holding it. -it("Connect waits for the Location OpenCode is still opening, next to a conversation attached to the same project", async () => { - const { service, panel, call, events } = harness(10_000) - try { - service.bindings.set("ses_codenomad", "offer_trial") - service.setUnavailable(2) - await call("connect", CONNECT) - assert.deepEqual(events("error"), []) - assert.equal(service.calls.filter(([name]) => name === "rpc.hosts").length, 3) - // Both conversations are attached to the project; closing the dock leaves the other one attached. - assert.deepEqual( - service.bindings, - new Map([ - ["ses_codenomad", "offer_trial"], - ["ses_old", "offer_trial"], - ]), - ) - await call("close") - assert.deepEqual(service.bindings, new Map([["ses_codenomad", "offer_trial"]])) - } finally { - await panel.closeAll() - } -}) - -it("a failed Connect says which step failed and why, without a credential", async () => { - const { service, panel, call, events } = harness(-1) - try { - service.setUnavailable(1) - await call("connect", CONNECT) - assert.equal( - events("error").at(-1)?.message, - "Connect failed while finding this project's offer: RPC is unavailable: neuralnomads.godot. Check that OpenCode runs, then choose Connect.", - ) - ;(service.api.session as { list: unknown }).list = async () => { - throw new Error(`refused by 127.0.0.1:${HOST.port} with Basic secret ${HOST.token}\nstack`) - } - await call("connect", CONNECT) - const message = String(events("error").at(-1)?.message) - assert.match( - message, - /^Connect failed while finding this project's conversation: refused by 127\.0\.0\.1:… with Basic …/, - ) - assert.ok( - !message.includes(HOST.token) && !message.includes(String(HOST.port)) && !message.includes("stack"), - message, - ) - } finally { - await panel.closeAll() - } -}) - -it("Connect without a running OpenCode says so", async () => { - const out: Out[] = [] - const panel = createPanel({ discover: async () => undefined, send: (message) => out.push(message as never) }) - await panel.dispatch({ id: "1", channel: "panel", method: "connect", params: CONNECT }) - assert.equal(out[0]?.data.message, "Start OpenCode before connecting the panel.") - assert.deepEqual(out[1], { id: "1", error: { message: "Panel action failed." } }) -}) diff --git a/integrations/houdini/host/manifest.json b/integrations/houdini/host/manifest.json index c70c9a5..78b577b 100644 --- a/integrations/houdini/host/manifest.json +++ b/integrations/houdini/host/manifest.json @@ -1 +1 @@ -{ "name": "OpenCode Link", "version": "0.3.1", "protocol": 1, "license": "MIT", "appVersions": ">=21.0" } +{ "name": "OpenCode Link", "version": "0.4.0", "protocol": 1, "license": "MIT", "appVersions": ">=21.0" } diff --git a/integrations/houdini/host/scripts/opencode_houdini/__init__.py b/integrations/houdini/host/scripts/opencode_houdini/__init__.py index 4051ee0..98cb012 100644 --- a/integrations/houdini/host/scripts/opencode_houdini/__init__.py +++ b/integrations/houdini/host/scripts/opencode_houdini/__init__.py @@ -118,6 +118,10 @@ def offerInfo() -> dict: return {"label": _host.label, "offer_key": OFFER_KEY, "advertising": _advertiser is not None} +def panelServices() -> list: + return _advertiser.results if _advertiser is not None else [] + + def scriptHandle(script=None) -> str: if _host is None: raise RuntimeError("OpenCode Houdini host has not been initialised") diff --git a/integrations/houdini/host/scripts/opencode_houdini/advertiser.py b/integrations/houdini/host/scripts/opencode_houdini/advertiser.py index 929d238..51045f3 100644 --- a/integrations/houdini/host/scripts/opencode_houdini/advertiser.py +++ b/integrations/houdini/host/scripts/opencode_houdini/advertiser.py @@ -85,12 +85,13 @@ def _renew(self, offer: dict[str, Any]) -> list[dict[str, Any]]: if targets and self._count % DISCOVER_EVERY: results, kept = [], {} for name, (service, directory) in targets.items(): + body = None try: status, body = opencode_service.call(service, RPC_ID, "advertise", offer, directory, RENEW_TIMEOUT) outcome = opencode_service._outcome("advertise", status, body) except (OSError, ValueError): outcome = "error" - results.append({"service": name, "outcome": outcome}) + results.append({"service": name, "outcome": outcome, **opencode_service.panel_runtime(outcome, body)}) if outcome in ("accepted", "renewed"): kept[name] = (service, directory) self._targets = kept @@ -104,6 +105,7 @@ def _renew(self, offer: dict[str, Any]) -> list[dict[str, Any]]: services = [] for service in services: outcome = "unavailable" + body = None for directory in opencode_service.location_candidates(None, self._env): try: deadline = time.monotonic() + RENEW_TIMEOUT @@ -121,7 +123,7 @@ def _renew(self, offer: dict[str, Any]) -> list[dict[str, Any]]: if outcome in ("accepted", "renewed"): found[service.file] = (service, directory) break - results.append({"service": service.file, "outcome": outcome}) + results.append({"service": service.file, "outcome": outcome, **opencode_service.panel_runtime(outcome, body)}) self._targets = found return results diff --git a/integrations/houdini/host/scripts/opencode_houdini/panel.py b/integrations/houdini/host/scripts/opencode_houdini/panel.py index 60f5478..0159a40 100644 --- a/integrations/houdini/host/scripts/opencode_houdini/panel.py +++ b/integrations/houdini/host/scripts/opencode_houdini/panel.py @@ -3,7 +3,7 @@ import json import os from pathlib import Path -import shutil +import time import uuid import hou @@ -12,6 +12,12 @@ import opencode_houdini +def panel_launcher(results, override, wait=False): + from .opencode_service import panel_launcher as choose + + return choose(results, override, wait=wait) + + def _log(message: str) -> None: pass # Conversation data and host credentials stay in memory. @@ -37,29 +43,65 @@ def __init__(self, parent=None) -> None: self._process.errorOccurred.connect(self._process_error) self._process.finished.connect(self._finished) self._stdout = b"" - self._pending: list[bytes] = [] + self._pending: list[tuple] = [] + self._targets: dict[str, dict] = {} + self._problem = "" + self._launch_at = time.monotonic() + 5 self._request = 0 + self._timer = QtCore.QTimer(self) + self._timer.timeout.connect(self.start) + self._timer.start(1000) def start(self) -> None: - if self._process.state() != QtCore.QProcess.ProcessState.NotRunning: + if not self._targets or self._process.state() != QtCore.QProcess.ProcessState.NotRunning: return - node = os.environ.get("NEURALNOMADS_HOUDINI_NODE") or shutil.which("node") + services = opencode_houdini.panelServices() + waiting = time.monotonic() < self._launch_at + runtime, bun = panel_launcher(services, "NEURALNOMADS_HOUDINI_NODE", wait=waiting) sidecar = str(Path(__file__).resolve().parents[2] / "sidecar.cjs") - if not node: - self.diagnostic.emit("Install Node.js 22 or set NEURALNOMADS_HOUDINI_NODE") - return + problem = "" if not Path(sidecar).is_file(): - _log("sidecar missing: " + sidecar) - self.diagnostic.emit( - "OpenCode Link sidecar is missing; reinstall the application part." - ) + problem = "OpenCode Link sidecar is missing; reinstall the application part." + elif not runtime and not waiting: + problem = "No OpenCode runtime, NEURALNOMADS_HOUDINI_NODE executable, or Node on PATH." + if problem and problem != self._problem: + self.diagnostic.emit(problem) + self._problem = problem + if problem or not runtime: return - self._process.setProgram(node) + env = QtCore.QProcessEnvironment.systemEnvironment() + env.remove("BUN_BE_BUN") + if bun: + env.insert("BUN_BE_BUN", "1") + self._process.setProcessEnvironment(env) + self._process.setProgram(runtime) self._process.setArguments([sidecar]) self._process.setWorkingDirectory(str(Path(sidecar).resolve().parent.parent)) self._process.start() def send(self, channel: str, method: str, params: dict) -> None: + if method in ("connect", "new_session"): + previous = self._targets.get(channel, {}) + if method == "new_session" or previous.get("directory") != params.get("directory"): + self._pending = [item for item in self._pending if item[0] != channel] + else: + params = {**params, "session_id": previous.get("session_id"), "draft": previous.get("draft", False)} + self._targets[channel] = params + elif method == "close": + self._targets.pop(channel, None) + self._pending = [item for item in self._pending if item[0] != channel] + if self._process.state() == QtCore.QProcess.ProcessState.Running: + self._write(channel, method, params) + elif method not in ("connect", "new_session", "close"): + if method == "interrupt": + self._pending = [item for item in self._pending if item[0] != channel or item[1] != "prompt"] + if len(self._pending) >= 100: + self.diagnostic.emit("OpenCode sidecar request queue is full") + return + self._pending.append((channel, method, params)) + self.start() + + def _write(self, channel, method, params): self._request += 1 _log("send method=" + method + " channel=" + channel + " params=" + json.dumps({key: value for key, value in params.items() if key != "token"}, default=str)) message = ( @@ -69,13 +111,7 @@ def send(self, channel: str, method: str, params: dict) -> None: ) + "\n" ).encode("utf-8") - if self._process.state() == QtCore.QProcess.ProcessState.Running: - self._process.write(message) - elif len(self._pending) < 100: - self._pending.append(message) - self.start() - else: - self.diagnostic.emit("OpenCode sidecar request queue is full") + self._process.write(message) def stop(self) -> None: if self._process.state() != QtCore.QProcess.ProcessState.NotRunning: @@ -85,8 +121,11 @@ def stop(self) -> None: def _started(self) -> None: _log("sidecar started") pending, self._pending = self._pending, [] - for message in pending: - self._process.write(message) + self._problem = "" + for channel, params in self._targets.items(): + self._write(channel, "connect", params) + for item in pending: + self._write(*item) def _read_stdout(self) -> None: self._stdout += bytes(self._process.readAllStandardOutput()) @@ -98,12 +137,15 @@ def _read_stdout(self) -> None: message = json.loads(raw.decode("utf-8")) _log("recv " + json.dumps(message, default=str)[:2000]) if message.get("event"): + channel = str(message.get("channel", "")) + if message["event"] == "session" and channel in self._targets: + self._targets[channel] = {**self._targets[channel], "session_id": message["data"]["id"], "draft": message["data"].get("draft", False)} self.eventReceived.emit( - str(message.get("channel", "")), + channel, str(message["event"]), message.get("data") or {}, ) - elif message.get("error"): + elif message.get("error") and not message.get("id"): self.diagnostic.emit(str(message["error"].get("message", message["error"]))) except Exception: self.diagnostic.emit("Malformed sidecar output: " + raw[:200].decode("utf-8", "replace")) @@ -120,7 +162,9 @@ def _process_error(self, error) -> None: def _finished(self, exit_code, exit_status) -> None: _log("sidecar finished exit=" + str(exit_code) + " status=" + str(exit_status)) - self.diagnostic.emit("OpenCode sidecar stopped with exit code " + str(exit_code)) + self._stdout = b"" + for channel in self._targets: + self.eventReceived.emit(channel, "status", {"state": "connecting"}) class PromptEdit(QtWidgets.QPlainTextEdit): @@ -134,6 +178,14 @@ def keyPressEvent(self, event: QtGui.QKeyEvent) -> None: super().keyPressEvent(event) +class Conversations(QtWidgets.QComboBox): + opening = QtCore.Signal() + + def showPopup(self) -> None: + self.opening.emit() + super().showPopup() + + class OpenCodePanel(QtWidgets.QWidget): def __init__(self, parent=None) -> None: super().__init__(parent) @@ -150,7 +202,12 @@ def __init__(self, parent=None) -> None: self._client.diagnostic.connect(self._diagnostic) self.destroyed.connect(self._destroyed) hou.hipFile.addEventCallback(self._hip_event) - self._status.setText("DISCONNECTED") + opencode_houdini.acquirePanel(self._channel) + self._target = None + self._sync() + self._timer = QtCore.QTimer(self) + self._timer.timeout.connect(self._sync) + self._timer.start(500) def _build_ui(self) -> None: layout = QtWidgets.QVBoxLayout(self) @@ -159,19 +216,15 @@ def _build_ui(self) -> None: header = QtWidgets.QHBoxLayout() brand = QtWidgets.QLabel("OPENCODE / HOUDINI") brand.setObjectName("openCodeHoudiniBrand") - self._session = QtWidgets.QLabel("SESSION connecting") self._status = QtWidgets.QLabel("STARTING") self._status.setObjectName("openCodeHoudiniStatus") - self._new = QtWidgets.QPushButton("New") - self._connect_button = QtWidgets.QPushButton("Connect") - self._disconnect_button = QtWidgets.QPushButton("Disconnect") + self._conversations = Conversations() + self._conversations.setSizeAdjustPolicy(QtWidgets.QComboBox.SizeAdjustPolicy.AdjustToContents) + self._conversations.addItem("New conversation", None) header.addWidget(brand) - header.addWidget(self._session) header.addStretch(1) header.addWidget(self._status) - header.addWidget(self._new) - header.addWidget(self._connect_button) - header.addWidget(self._disconnect_button) + header.addWidget(self._conversations) layout.addLayout(header) self._transcript = QtWidgets.QTextEdit() @@ -200,8 +253,6 @@ def _build_ui(self) -> None: self._stop = QtWidgets.QPushButton("Stop") self._send = QtWidgets.QPushButton("Send") self._stop.setEnabled(False) - self._send.setEnabled(False) - self._prompt.setEnabled(False) prompt_row.addWidget(self._prompt, 1) prompt_row.addWidget(self._stop) prompt_row.addWidget(self._send) @@ -213,9 +264,8 @@ def _build_ui(self) -> None: "#openCodeHoudiniStatus { color: #d5a657; font-weight: 600; }" "#openCodeHoudiniTranscript { border: 1px solid #34393e; background: #191b1d; }" ) - self._new.clicked.connect(self._new_session) - self._connect_button.clicked.connect(self._connect) - self._disconnect_button.clicked.connect(self._disconnect) + self._conversations.activated.connect(self._choose_conversation) + self._conversations.opening.connect(lambda: self._client.send(self._channel, "list", {})) self._send.clicked.connect(self._send_prompt) self._prompt.sendRequested.connect(self._send_prompt) self._stop.clicked.connect(lambda: self._client.send(self._channel, "interrupt", {})) @@ -230,41 +280,30 @@ def _connect_params(self) -> dict: offer = opencode_houdini.offerInfo() return { **info, - # This Houdini offers itself (OpenCode Link starts with Houdini): the panel finds that offer by its - # label and attaches its own conversation to it, which it takes back per file next time. "offer_label": offer["label"], - "sessions_file": str(Path(__file__).resolve().parents[3].parent / "panel-sessions.json"), "script_handle": opencode_houdini.scriptHandle(), - "script_key": "untitled:" + opencode_houdini.scriptHandle() if is_untitled else str(Path(file_name).resolve()), - "script_name": hou.hipFile.basename(), "directory": directory, } - def _connect(self) -> None: + def _sync(self) -> None: if self._disposed: return - opencode_houdini.acquirePanel(self._channel) - self._connected = False - self._status.setText("CONNECTING") - self._send.setEnabled(False) - self._prompt.setEnabled(False) - self._client.send(self._channel, "connect", self._connect_params()) + params = self._connect_params() + if params != self._target: + self._target = params + self._client.send(self._channel, "connect", params) def _new_session(self) -> None: if self._disposed: return - opencode_houdini.acquirePanel(self._channel) - self._status.setText("CONNECTING") - self._client.send(self._channel, "new_session", self._connect_params()) + self._client.send(self._channel, "new_session", self._target) - def _disconnect(self) -> None: - # The host and its offer stay: other conversations attached to this Houdini keep it. - opencode_houdini.releasePanel(self._channel) - self._client.send(self._channel, "close", {}) - self._connected = False - self._send.setEnabled(False) - self._prompt.setEnabled(False) - self._status.setText("DISCONNECTED") + def _choose_conversation(self, index: int) -> None: + session = self._conversations.itemData(index) + if session: + self._client.send(self._channel, "open", {"session_id": session}) + else: + self._new_session() def _send_prompt(self) -> None: if self._busy: @@ -273,7 +312,6 @@ def _send_prompt(self) -> None: if not text: return self._prompt.clear() - self._append("user", text) self._client.send(self._channel, "prompt", {"text": text}) def _permission_reply(self, reply: str) -> None: @@ -293,12 +331,22 @@ def _event(self, channel: str, name: str, data: dict) -> None: return if name == "session": self._connected = True - self._session.setText("SESSION " + str(data.get("id", ""))[-8:]) self._append("system", "Resumed session" if data.get("resumed") else "New session") elif name == "history": + self._streaming = False self._transcript.clear() for message in data.get("messages", []): self._append(message.get("role", "system"), message.get("text", "")) + elif name == "conversations": + self._conversations.clear() + self._conversations.addItem("New conversation", None) + for entry in data["entries"]: + self._conversations.addItem(entry.get("title") or "Untitled", entry["id"]) + self._conversations.setCurrentIndex(max(0, self._conversations.findData(data.get("selected")))) + elif name == "notice": + self._append("system", data["message"]) + elif name == "user_message": + self._append("user", data["text"]) elif name == "assistant_start": self._start_assistant() elif name == "assistant_delta": @@ -316,10 +364,14 @@ def _event(self, channel: str, name: str, data: dict) -> None: elif name == "status": state = str(data.get("state", "unknown")) self._status.setText(state.upper()) + if state == "connecting": + self._connected = False + self._permission_request = None + self._permission.hide() self._busy = state in ("busy", "retry") - self._stop.setEnabled(self._busy) - self._send.setEnabled(self._connected and not self._busy) - self._prompt.setEnabled(self._connected and not self._busy) + self._stop.setEnabled(self._busy or state == "connecting") + self._send.setEnabled(not self._busy) + self._prompt.setEnabled(not self._busy) elif name == "graph_revision": self._status.setToolTip("Houdini graph revision " + str(data.get("revision"))) elif name == "error": @@ -327,8 +379,8 @@ def _event(self, channel: str, name: str, data: dict) -> None: self._status.setText("ERROR") self._busy = False self._stop.setEnabled(False) - self._send.setEnabled(self._connected) - self._prompt.setEnabled(self._connected) + self._send.setEnabled(True) + self._prompt.setEnabled(True) @QtCore.Slot(str) def _diagnostic(self, text: str) -> None: @@ -380,7 +432,7 @@ def _hip_event(self, event_type: hou.hipFileEventType) -> None: hou.hipFileEventType.AfterClear, hou.hipFileEventType.AfterLoad, ): - self._disconnect() + self._sync() def dispose(self) -> None: if self._disposed: diff --git a/integrations/houdini/plugin/README.md b/integrations/houdini/plugin/README.md index 0e8785a..77ae0ad 100644 --- a/integrations/houdini/plugin/README.md +++ b/integrations/houdini/plugin/README.md @@ -1,6 +1,6 @@ # OpenCode for Houdini (preview) -Read, change and check the scene open in Houdini from any OpenCode conversation: CodeNomad, the terminal, the desktop app, or the **OpenCode Link** panel inside Houdini. Houdini 21 or later and OpenCode 2.2 or later are required; the panel also needs Node.js 22 or later. +Read, change and check the scene open in Houdini from any OpenCode conversation: CodeNomad, the terminal, the desktop app, or the **OpenCode Link** panel inside Houdini. Houdini 21 or later and OpenCode 2.2 or later are required. ## Install @@ -41,7 +41,7 @@ A call that outlasts its wait says whether Houdini still runs it (OpenCode Link ## The OpenCode Link panel -The **OpenCode Link** Python panel is a conversation inside Houdini. **Connect** attaches the panel's conversation to this Houdini's own offer, taking back the conversation it had for this file; **New** starts another. Closing the panel releases its conversation only: Houdini stays offered and other conversations attached to it keep it. The panel and other conversations (CodeNomad's, for instance) can be attached to the same Houdini together; both write to the same scene, each change checked against its revision. The panel's conversation lives in its project folder: the first Connect there waits while OpenCode opens that folder and loads its plugins. A failed Connect says which step failed and why. Node.js is found on `PATH`; `NEURALNOMADS_HOUDINI_NODE` names another one. +The **OpenCode Link** Python panel connects automatically to the latest conversation in the HIP file’s folder. Opening another version in that folder keeps the selected conversation. Use the selector to switch or choose **New conversation**; nothing is created until you send a message. **Stop** interrupts or clears queued prompts. The panel uses OpenCode’s executable, with Node.js 22+ (`NEURALNOMADS_HOUDINI_NODE` or `PATH`) as a fallback. ## Limits diff --git a/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip b/integrations/houdini/plugin/host/houdini/opencode_link-0.4.0.zip similarity index 71% rename from integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip rename to integrations/houdini/plugin/host/houdini/opencode_link-0.4.0.zip index ce75f9e..95a6914 100644 Binary files a/integrations/houdini/plugin/host/houdini/opencode_link-0.3.1.zip and b/integrations/houdini/plugin/host/houdini/opencode_link-0.4.0.zip differ diff --git a/integrations/houdini/plugin/package.json b/integrations/houdini/plugin/package.json index 7b4312f..95ecd77 100644 --- a/integrations/houdini/plugin/package.json +++ b/integrations/houdini/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@neuralnomads/opencode-houdini", - "version": "0.3.1", + "version": "0.4.0", "description": "OpenCode for Houdini: read, change and check the open Houdini scene from any OpenCode conversation, with an optional panel inside Houdini.", "license": "MIT", "type": "module", @@ -61,10 +61,10 @@ "host": { "app": "houdini", "protocol": 1, - "range": "^0.3.1", + "range": "^0.4.0", "appVersions": ">=21.0", - "payload": "host/houdini/opencode_link-0.3.1.zip", - "sha256": "7efd8d521a82d7e409251ae89ad6390bfcf99cb85af72b64aa5ead05321a7aa0" + "payload": "host/houdini/opencode_link-0.4.0.zip", + "sha256": "7f46420f11134743afcae64115c62e2ab4a17e3481cf22b26abaabe305915b7a" } } } diff --git a/integrations/houdini/plugin/scripts/build-host.ts b/integrations/houdini/plugin/scripts/build-host.ts index ac585df..211489d 100644 --- a/integrations/houdini/plugin/scripts/build-host.ts +++ b/integrations/houdini/plugin/scripts/build-host.ts @@ -13,6 +13,8 @@ const manifest = JSON.parse(readFileSync(join(host, "manifest.json"), "utf8")) if (manifest.version !== pkg.version) throw new Error("Host and plugin versions differ") const check = process.argv.includes("--check") const bundle = await build({ + absWorkingDir: join(root, "..", "..", ".."), + preserveSymlinks: true, entryPoints: [join(root, "src", "sidecar.ts")], bundle: true, format: "cjs", diff --git a/integrations/houdini/plugin/src/sidecar-steps.ts b/integrations/houdini/plugin/src/sidecar-steps.ts deleted file mode 100644 index 2fed858..0000000 --- a/integrations/houdini/plugin/src/sidecar-steps.ts +++ /dev/null @@ -1,65 +0,0 @@ -// The panel's Connect steps that do not need OpenCode's client (sidecar.ts): finding this Houdini's offer while the -// service opens the panel's Location, and an error that says which step failed, safe to show in the panel. - -// A message of the sidecar's own, safe to show in the panel. -export class PanelError extends Error {} - -// How long Connect waits for this Houdini's own offer (it offers itself every 5 s from its start), and for a -// Location OpenCode opens for the panel to load its plugins (tens of seconds in a trial). -export const OFFER_WAIT_MS = 30_000 - -// An error in one line for the panel: its first line, bounded, without a token, an authorization or a port. -export function briefly(error: unknown) { - const text = String((error as { message?: unknown } | null)?.message ?? error ?? "unknown error") - .split(/\r?\n/)[0] - ?.replace(/\b[0-9a-f]{32,}\b/gi, "…") - .replace(/(basic|bearer)\s+\S+/gi, "$1 …") - .replace(/\b(port\s+|:)\d{2,5}\b/gi, "$1…") - .slice(0, 240) - return `${text || "unknown error"}${/[.!?]$/.test(text ?? "") ? "" : "."}` -} - -// A failed Connect says which step failed and why, in a line (never a credential): the user knows what to check. -export async function step(doing: string, work: () => Promise): Promise { - try { - return await work() - } catch (error) { - if (error instanceof PanelError) throw error - throw new PanelError( - `Connect failed while ${doing}: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - ) - } -} - -type Offer = { label: string; offerID: string } - -// This Houdini's offer: the one with its label among the offered hosts (Houdini offers itself; the panel never). -export async function findOffer( - hosts: () => Promise<{ offers?: unknown } | undefined>, - label: string, - wait = { ms: OFFER_WAIT_MS, sleep: (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) }, -): Promise { - const until = Date.now() + wait.ms - for (;;) { - let result: { offers?: unknown } | undefined - try { - result = await hosts() - } catch (error) { - // The first call in the panel's folder: OpenCode opens that Location and loads its plugins meanwhile, and the - // integration's RPC is not there yet (a CodeNomad conversation's own Location is long loaded). - if (!/RPC is unavailable/i.test(String((error as { message?: unknown })?.message ?? error)) || Date.now() > until) - throw error - await wait.sleep(1_000) - continue - } - const offers = ((result?.offers ?? []) as Offer[]).filter((offer) => offer.label === label) - if (offers.length > 1) - throw new PanelError(`Several Houdinis offer ${label}: attach this conversation from OpenCode (houdini_hosts).`) - if (offers[0]) return offers[0] - if (Date.now() > until) - throw new PanelError( - "This Houdini does not offer itself to OpenCode (OPENCODE_HOUDINI_OFFER=0, or OpenCode Link not started).", - ) - await wait.sleep(1_000) - } -} diff --git a/integrations/houdini/plugin/src/sidecar.ts b/integrations/houdini/plugin/src/sidecar.ts index 2ebc8b6..c1ffa0b 100644 --- a/integrations/houdini/plugin/src/sidecar.ts +++ b/integrations/houdini/plugin/src/sidecar.ts @@ -1,260 +1,3 @@ -// Private JSONL panel client. Built into the installed host; credentials never leave this process. -import { mkdirSync, readFileSync, writeFileSync } from "node:fs" -import { dirname } from "node:path" -import readline from "node:readline" -import { OpenCode } from "@opencode/client" -import { Service } from "@opencode/client/service" -import { rpcDefinition } from "../../../../packages/integration-kit/src/contract.ts" -import { requestHost } from "../../../../packages/integration-kit/src/host-client.ts" -import { briefly, findOffer, PanelError, step } from "./sidecar-steps.ts" +import { runPanel } from "../../../../packages/integration-kit/src/panel-pipes.ts" -type Channel = { - id: string - directory: string - sessionID: string - label: string - binding: { host: string; port: number; token: string } - handle: string - abort: AbortController - timer?: NodeJS.Timeout - pending: boolean -} -type Request = { id: string; channel: string; method: string; params: Record } -type Rpc = Record Promise>> -let client: ReturnType | undefined -let rpc: Rpc -const channels = new Map() -const queues = new Map>() -const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`) -const event = (c: Channel, name: string, data: object) => send({ channel: c.id, event: name, data }) -const options = (c: { directory: string }) => ({ - location: { directory: c.directory }, - signal: AbortSignal.timeout(3000), -}) -async function api() { - if (client) return client - const endpoint = await Service.discover() - if (!endpoint) throw new PanelError("Start OpenCode before connecting the panel.") - client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }) - rpc = client.rpc(rpcDefinition("neuralnomads.houdini", "native") as never) as unknown as Rpc - return client -} - -// The panel's conversation per Houdini file, kept next to the installed payloads: Connect takes it back. -type Sessions = Record -function readSessions(file: string): Sessions { - try { - const value = JSON.parse(readFileSync(file, "utf8")) as unknown - return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Sessions) : {} - } catch { - return {} - } -} -function rememberSession(file: string, key: string, session: string, directory: string) { - if (!file || !key || key.startsWith("untitled:")) return - try { - const sessions = readSessions(file) - sessions[key] = { session, directory } - const keys = Object.keys(sessions) - for (const old of keys.slice(0, Math.max(0, keys.length - 200))) delete sessions[old] - mkdirSync(dirname(file), { recursive: true }) - writeFileSync(file, `${JSON.stringify(sessions)}\n`) - } catch { - // a conversation that is not taken back next time - } -} - -async function attached(c: Channel) { - const read = await rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)) - return read?.state === "attached" && (read.binding as { label?: string } | undefined)?.label === c.label -} - -// Closing the panel releases its own conversation only: the offer stays, and other conversations attached to -// this Houdini (CodeNomad, a terminal) keep it. -async function close(c: Channel) { - channels.delete(c.id) - if (c.timer) clearInterval(c.timer) - c.abort.abort() - await requestHost( - c.binding, - "cancel", - { script_handle: c.handle, session_id: c.sessionID }, - { timeoutMs: 2000 }, - ).catch(() => {}) - // A different client may have moved the session to another host. Never detach that binding. - await attached(c) - .then((still) => (still ? rpc.detachHost?.({ sessionID: c.sessionID }, options(c)) : undefined)) - .catch(() => {}) -} - -async function stream(c: Channel) { - const service = await api() - try { - for await (const item of service.event.subscribe({ signal: c.abort.signal })) { - const data = item.data as unknown as Record - if (data.sessionID !== c.sessionID) continue - if (item.type === "session.text.delta") event(c, "assistant_delta", { text: data.delta ?? "" }) - else if (item.type === "session.text.ended") event(c, "assistant_end", {}) - else if (item.type === "session.execution.started") event(c, "status", { state: "busy" }) - else if (item.type === "session.execution.succeeded" || item.type === "session.execution.interrupted") - event(c, "status", { state: "idle" }) - else if (item.type === "session.execution.failed") event(c, "error", { message: "OpenCode execution failed." }) - else if (item.type === "permission.asked") - event(c, "permission", { request_id: data.id, action: data.action, resources: data.resources }) - } - } catch { - if (!c.abort.signal.aborted) event(c, "error", { message: "OpenCode disconnected; choose Connect to reconnect." }) - } -} - -async function connect(id: string, params: Record, fresh: boolean) { - const service = await step("reaching OpenCode", api) - const previous = channels.get(id) - if (previous) await close(previous) - if (params.host !== "127.0.0.1" || !Number.isInteger(params.port) || !/^[0-9a-f]{64}$/.test(String(params.token))) - throw new Error("Invalid host endpoint.") - const directory = String(params.directory ?? "") - if (!directory) throw new Error("Select a project directory.") - const label = String(params.offer_label ?? "") - if (!label) throw new PanelError("This Houdini's offer is unknown.") - const key = String(params.script_key ?? "") - const store = String(params.sessions_file ?? "") - // The file's conversation, when it still exists; otherwise (or with New) a new one. - let sessionID: string | undefined - let resumed = false - const known = !fresh && store ? readSessions(store)[key] : undefined - if (known?.session) { - try { - const found = (await service.session.get({ sessionID: known.session } as never)) as { id?: string } | undefined - if (found?.id === known.session) { - sessionID = known.session - resumed = true - } - } catch { - // gone: a new one - } - } - if (!sessionID) { - const label = String(params.script_name || "Houdini") - sessionID = ( - await step("creating this file's conversation", () => - service.session.create({ title: `Houdini: ${label}`, location: { directory } }), - ) - ).id - } - const c: Channel = { - id, - directory: resumed && known ? known.directory : directory, - sessionID, - label, - binding: { host: "127.0.0.1", port: Number(params.port), token: String(params.token) }, - handle: String(params.script_handle), - abort: new AbortController(), - pending: false, - } - try { - const offer = await step("finding this Houdini's offer", () => - findOffer(async () => rpc.hosts?.({}, options(c)), c.label), - ) - const result = await step("attaching the conversation to this Houdini", async () => - rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID }, options(c)), - ) - if (result?.outcome !== "attached") throw new PanelError("Houdini attachment was refused.") - rememberSession(store, key, c.sessionID, c.directory) - channels.set(id, c) - let warned = false - c.timer = setInterval(() => { - if (c.pending) return - c.pending = true - void api() - .then(() => attached(c)) - .then((still) => { - if (!still) throw new Error("detached") - }) - .catch(() => { - client = undefined - if (!warned) - event(c, "error", { message: "Conversation detached or service unavailable; choose Connect to reconnect." }) - warned = true - }) - .finally(() => { - c.pending = false - }) - }, 5000) - void stream(c) - event(c, "session", { id: c.sessionID, resumed }) - event(c, "history", { messages: [] }) - event(c, "status", { state: "idle" }) - } catch (error) { - await close(c) - throw error - } -} -async function dispatch(request: Request) { - try { - const params = request.params ?? {} - if (request.method === "connect" || request.method === "new_session") - await connect(request.channel, params, request.method === "new_session") - else { - const c = channels.get(request.channel) - if (!c) throw new Error("Choose Connect first.") - const service = await api() - if (request.method === "close") await close(c) - else if (request.method === "interrupt") { - await requestHost( - c.binding, - "cancel", - { script_handle: c.handle, session_id: c.sessionID }, - { timeoutMs: 2000 }, - ) - await service.session.interrupt({ sessionID: c.sessionID, resume: false }) - } else if (request.method === "prompt") { - if (!(await attached(c))) throw new PanelError("Houdini was detached; choose Connect to attach again.") - await requestHost( - c.binding, - "resume", - { script_handle: c.handle, session_id: c.sessionID }, - { timeoutMs: 2000 }, - ) - await service.session.prompt({ sessionID: c.sessionID, text: String(params.text ?? "") }) - } else if (request.method === "permission_reply") { - const decision = params.reply - if (decision !== "once" && decision !== "reject") throw new Error("Invalid permission answer.") - await service.permission.reply({ sessionID: c.sessionID, requestID: String(params.request_id), decision }) - } else throw new Error("Unknown panel action.") - } - send({ id: request.id, result: {} }) - } catch (error) { - // SDK and host errors in one line, without credentials or endpoints (briefly). - send({ - channel: request.channel, - event: "error", - data: { - message: - error instanceof PanelError - ? error.message - : `The panel action failed: ${briefly(error)} Check that OpenCode runs, then choose Connect.`, - }, - }) - send({ id: request.id, error: { message: "Panel action failed." } }) - } -} - -const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }) -input.on("line", (line) => { - try { - if (Buffer.byteLength(line) > 1024 * 1024) throw new Error("Request too large") - const request = JSON.parse(line) as Request - if (!request.id || !request.channel || !request.method) throw new Error("Invalid request") - const next = (queues.get(request.channel) ?? Promise.resolve()).then(() => dispatch(request)) - queues.set(request.channel, next) - void next.finally(() => { - if (queues.get(request.channel) === next) queues.delete(request.channel) - }) - } catch { - send({ error: { message: "Invalid panel request." } }) - } -}) -input.on("close", () => { - void Promise.allSettled([...channels.values()].map(close)).finally(() => process.exit(0)) -}) +runPanel({ app: "Houdini", rpcID: "neuralnomads.houdini", document: "file", duplicateOffer: "Houdini instances" }) diff --git a/integrations/houdini/test/host_probe.py b/integrations/houdini/test/host_probe.py index 3243a54..838cc18 100644 --- a/integrations/houdini/test/host_probe.py +++ b/integrations/houdini/test/host_probe.py @@ -341,6 +341,7 @@ def test_renewals_go_straight_to_the_service_and_discover_again_after_a_failure( fake._ready = lambda service, rpc, directory, deadline: (calls.append("status") or (200, {"output": {}})) fake._unavailable = lambda status, body: False fake._outcome = lambda method, status, body: body + fake.panel_runtime = lambda outcome, body: {} fake.call = lambda service, rpc, method, payload, directory, timeout: ( calls.append("%s:%.0f" % (method, timeout)) or (200, outcomes.pop(0) if outcomes else "renewed")) sys.modules["opencode_houdini.opencode_service"] = fake diff --git a/integrations/houdini/test/panel_probe.py b/integrations/houdini/test/panel_probe.py index 1eb6d40..ed1870d 100644 --- a/integrations/houdini/test/panel_probe.py +++ b/integrations/houdini/test/panel_probe.py @@ -32,7 +32,7 @@ class Widget: def closeEvent(self, event): event.accept() -qt.QtWidgets = types.SimpleNamespace(QWidget=Widget, QPlainTextEdit=object) +qt.QtWidgets = types.SimpleNamespace(QWidget=Widget, QPlainTextEdit=object, QComboBox=object) sys.modules["PySide6"] = qt @@ -72,10 +72,15 @@ def test_installed_import(self): process.state.return_value = 0 client = panel.JsonlClient.__new__(panel.JsonlClient) client._process = process - with patch.object(panel.shutil, "which", return_value=sys.executable): + client._targets = {"test": {}} + client._problem = "" + client._launch_at = 0 + qt.QtCore.QProcessEnvironment = Mock() + with patch.object(panel, "panel_launcher", return_value=(sys.executable, True)): client.start() process.setArguments.assert_called_once_with([str(root / "sidecar.cjs")]) process.start.assert_called_once() + qt.QtCore.QProcessEnvironment.systemEnvironment.return_value.insert.assert_called_once_with("BUN_BE_BUN", "1") self.assertTrue((root / "sidecar.cjs").is_file()) def test_shared_host_lifetime(self): @@ -100,12 +105,13 @@ def test_shared_host_lifetime(self): widget._status = Mock() widget._send = Mock() widget._prompt = Mock() - widget._session = Mock() widget._append = Mock() + widget._target = None + integration.acquirePanel(widget._channel) with patch.object(panel, "create_interface", return_value=widget): interfaces[index]["create_interface"] = panel.create_interface self.assertIs(interfaces[index]["onCreateInterface"](), widget) - widget._connect() + widget._sync() widget._event(widget._channel, "session", {"id": "session-" + str(index)}) endpoint = integration.hostInfo() host, server = integration._host, integration._server @@ -133,11 +139,6 @@ def ask(): self.assertEqual(result["result"]["script_handle"], state.handle) try: - first._disconnect() - client.send.assert_called_with(first._channel, "close", {}) - self.assertFalse(first._connected) - assert_live() - first._connect() first._new_session() interfaces[0]["onDestroyInterface"]() client.send.assert_called_with(first._channel, "close", {}) @@ -145,7 +146,7 @@ def ask(): sends = client.send.call_count interfaces[0]["onDestroyInterface"]() first._destroyed() - first._connect() + first._sync() self.assertEqual(client.send.call_count, sends) assert_live() # The last panel closing leaves the host with Houdini: its offer serves the other conversations. @@ -161,12 +162,13 @@ def ask(): client.send.side_effect = None # A new panel uses the same host, authority unchanged. third = panel.OpenCodePanel.__new__(panel.OpenCodePanel) - third.__dict__.update(second.__dict__, _disposed=False, _channel="third") - third._connect() + third.__dict__.update(second.__dict__, _disposed=False, _channel="third", _target=None) + integration.acquirePanel(third._channel) + third._sync() self.assertIs(integration._server, server) params = client.send.call_args.args[2] self.assertEqual(params["offer_label"], "Houdini: untitled.hip") - self.assertTrue(params["sessions_file"].endswith("panel-sessions.json")) + self.assertEqual(params["directory"], os.getcwd()) third._destroyed() self.assertTrue(server.running) finally: diff --git a/integrations/houdini/test/sidecar-steps.test.ts b/integrations/houdini/test/sidecar-steps.test.ts deleted file mode 100644 index 1423538..0000000 --- a/integrations/houdini/test/sidecar-steps.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -// The panel's Connect (sidecar.ts): its first call in a folder OpenCode is still opening waits for that Location's -// plugins ("RPC is unavailable"), and a failed Connect says which step failed and why, without a credential. Gaffer -// trial: the first Connect failed with "Connection or action failed" next to a CodeNomad conversation attached to -// the same application, and was read as that conversation holding it. - -import assert from "node:assert/strict" -import { it } from "node:test" - -import { briefly, findOffer, PanelError, step } from "../plugin/src/sidecar-steps.ts" - -const TOKEN = "a".repeat(64) -const offers = { offers: [{ offerID: "offer_shot", label: "Houdini: shot.hipnc" }] } - -it("Connect waits while OpenCode opens the panel's folder, then finds this Houdini's offer", async () => { - let calls = 0 - const slept: number[] = [] - const offer = await findOffer( - async () => { - calls += 1 - if (calls <= 2) throw new Error("RPC is unavailable: neuralnomads.houdini") - return offers - }, - "Houdini: shot.hipnc", - { ms: 30_000, sleep: async (ms) => void slept.push(ms) }, - ) - assert.equal(offer.offerID, "offer_shot") - assert.equal(calls, 3) - assert.deepEqual(slept, [1_000, 1_000]) -}) - -it("another error, or an RPC still unavailable at the deadline, ends the search", async () => { - await assert.rejects( - findOffer(async () => Promise.reject(new Error("socket hang up")), "Houdini: shot.hipnc", { - ms: 30_000, - sleep: async () => {}, - }), - /socket hang up/, - ) - await assert.rejects( - findOffer( - async () => Promise.reject(new Error("RPC is unavailable: neuralnomads.houdini")), - "Houdini: shot.hipnc", - { - ms: -1, - sleep: async () => {}, - }, - ), - /RPC is unavailable/, - ) - await assert.rejects( - findOffer(async () => ({ offers: [...offers.offers, ...offers.offers] }), "Houdini: shot.hipnc", { - ms: -1, - sleep: async () => {}, - }), - (error: Error) => error instanceof PanelError && /^Several Houdinis offer Houdini: shot\.hipnc/.test(error.message), - ) -}) - -it("a failed Connect says which step failed and why, without a credential", async () => { - await assert.rejects( - step("finding this Houdini's offer", async () => { - throw new Error("RPC is unavailable: neuralnomads.houdini") - }), - (error: Error) => - error instanceof PanelError && - error.message === - "Connect failed while finding this Houdini's offer: RPC is unavailable: neuralnomads.houdini. Check that OpenCode runs, then choose Connect.", - ) - await assert.rejects( - step("creating this file's conversation", async () => { - throw new Error(`refused by 127.0.0.1:4096 with Basic ${TOKEN} on port 51396\n at stack`) - }), - (error: Error) => { - assert.equal( - error.message, - "Connect failed while creating this file's conversation: refused by 127.0.0.1:… with Basic … on port …. Check that OpenCode runs, then choose Connect.", - ) - return true - }, - ) - // The panel's own messages pass as they are. - await assert.rejects( - step("reaching OpenCode", async () => { - throw new PanelError("Start OpenCode before connecting the panel.") - }), - (error: Error) => error instanceof PanelError && error.message === "Start OpenCode before connecting the panel.", - ) - assert.equal(briefly(new Error(`token ${TOKEN}`)), "token ….") -}) diff --git a/package-lock.json b/package-lock.json index 4099357..7ebf255 100644 --- a/package-lock.json +++ b/package-lock.json @@ -39,9 +39,10 @@ }, "integrations/blender/plugin": { "name": "@neuralnomads/opencode-blender", - "version": "0.4.8", + "version": "0.5.0", "license": "MIT AND GPL-3.0-or-later", "devDependencies": { + "@opencode/client": "2.2.5", "@opencode/plugin": "2.2.5", "esbuild": "0.28.2" }, @@ -56,7 +57,7 @@ }, "integrations/gaffer/plugin": { "name": "@neuralnomads/opencode-gaffer", - "version": "0.3.0", + "version": "0.4.0", "license": "MIT", "devDependencies": { "@opencode/client": "2.2.5", @@ -74,7 +75,7 @@ }, "integrations/godot/plugin": { "name": "@neuralnomads/opencode-godot", - "version": "0.1.0", + "version": "0.2.0", "license": "MIT", "devDependencies": { "@opencode/client": "2.2.5", @@ -92,7 +93,7 @@ }, "integrations/houdini/plugin": { "name": "@neuralnomads/opencode-houdini", - "version": "0.3.1", + "version": "0.4.0", "license": "MIT", "devDependencies": { "@opencode/client": "2.2.5", @@ -4871,6 +4872,7 @@ "semver": "7.8.5" }, "devDependencies": { + "@opencode/client": "2.2.5", "@opencode/plugin": "2.2.5" }, "peerDependencies": { diff --git a/packages/integration-kit/package.json b/packages/integration-kit/package.json index 78dda26..f1c910f 100644 --- a/packages/integration-kit/package.json +++ b/packages/integration-kit/package.json @@ -26,6 +26,7 @@ } }, "devDependencies": { + "@opencode/client": "2.2.5", "@opencode/plugin": "2.2.5" }, "dependencies": { diff --git a/packages/integration-kit/python/opencode_service.py b/packages/integration-kit/python/opencode_service.py index 5354867..41c5eca 100644 --- a/packages/integration-kit/python/opencode_service.py +++ b/packages/integration-kit/python/opencode_service.py @@ -29,6 +29,7 @@ import http.client import json import os +import shutil import re import time import urllib.error @@ -194,6 +195,14 @@ def _outcome(method, status, body): return value if status == 200 and value in OUTCOMES[method] else "error" +def panel_runtime(outcome, body): + if outcome in ("accepted", "renewed") and isinstance(body, dict): + runtime = body.get("output", {}).get("panel_runtime") + if isinstance(runtime, str) and os.path.isabs(runtime): + return {"panel_runtime": runtime} + return {} + + def _ready(service, rpc_id, directory, deadline): # Registration is asynchronous on cold Locations. Only the payload-free # status read is repeated; an advertisement/withdrawal is never a probe. @@ -213,6 +222,7 @@ def _each_service(method, rpc_id, payload, service_name, config_dir_setting, env results = [] for service in discover(service_name, env, timeout): outcome = "unavailable" + runtime = {} for directory in location_candidates(config_dir_setting, env): try: deadline = time.monotonic() + timeout @@ -233,11 +243,27 @@ def _each_service(method, rpc_id, payload, service_name, config_dir_setting, env outcome = "unavailable" else: outcome = _outcome(method, status, body) + if method == "advertise": + runtime = panel_runtime(outcome, body) break - results.append({"service": service.file, "outcome": outcome}) + results.append({"service": service.file, "outcome": outcome, **runtime}) return results +def panel_launcher(results, override, wait=False): + """Use the daemon's advertised executable, then the host override, then Node on PATH.""" + for result in results: + runtime = result.get("panel_runtime") + if result.get("outcome") in ("accepted", "renewed") and isinstance(runtime, str) and os.path.isabs(runtime) and shutil.which(runtime): + return runtime, True + if wait and not any(result.get("outcome") in ("accepted", "renewed") for result in results): + return None, False + for candidate in (os.environ.get(override), "node"): + if candidate and (node := shutil.which(candidate)): + return node, False + return None, False + + def advertise_all(rpc_id, offer, service_name=None, config_dir_setting=None, env=None, timeout=TIMEOUT): """Advertise one offer to every discovered service, or to the named one.""" return _each_service("advertise", rpc_id, offer, service_name, config_dir_setting, env, timeout) diff --git a/packages/integration-kit/src/contract.ts b/packages/integration-kit/src/contract.ts index 0ebb211..f4422cd 100644 --- a/packages/integration-kit/src/contract.ts +++ b/packages/integration-kit/src/contract.ts @@ -203,9 +203,16 @@ export const RPC_SCHEMAS = { properties: { offerID: { type: "string", pattern: OFFER_ID_PATTERN }, sessionID: { type: "string", pattern: SESSION_ID_PATTERN }, + takeover: { type: "boolean" }, + }, + }, + "attachHost.output": { + ...outcome(["attached", "busy", "gone", "refused"]), + properties: { + outcome: { enum: ["attached", "busy", "gone", "refused"] }, + replaced: { type: "boolean" }, }, }, - "attachHost.output": outcome(["attached", "busy", "gone", "refused"]), "detachHost.input": { type: "object", additionalProperties: false, @@ -242,7 +249,13 @@ export const RPC_SCHEMAS = { }, ], }, - "advertise.output": outcome(["accepted", "renewed", "refused"]), + "advertise.output": { + ...outcome(["accepted", "renewed", "refused"]), + properties: { + outcome: { enum: ["accepted", "renewed", "refused"] }, + panel_runtime: { type: "string", maxLength: 4096 }, + }, + }, "withdraw.output": outcome(["withdrawn", "none"]), "status_changed.event": empty(), "hosts_changed.event": empty(), diff --git a/packages/integration-kit/src/integration-rpc.ts b/packages/integration-kit/src/integration-rpc.ts index 193868f..bcaebee 100644 --- a/packages/integration-kit/src/integration-rpc.ts +++ b/packages/integration-kit/src/integration-rpc.ts @@ -107,13 +107,20 @@ export function createIntegrationRpc(options: IntegrationRpcOptions) { handlers.installHost = () => installHost() handlers.hosts = async () => registry.hosts() handlers.attachHost = async (input, context) => { - const { offerID, sessionID } = input as { offerID: string; sessionID: string } - return bindings.attach(offerID, sessionID, context?.signal) + const { offerID, sessionID, takeover } = input as { offerID: string; sessionID: string; takeover?: boolean } + return bindings.attach(offerID, sessionID, context?.signal, takeover) } handlers.detachHost = async (input, context) => bindings.detach((input as { sessionID: string }).sessionID, context?.signal) handlers.bindingRead = (input, context) => bindings.read(input, context?.signal) - handlers.advertise = (input) => registry.advertise(input) + handlers.advertise = async (input) => { + const result = await registry.advertise(input) + return result.outcome !== "refused" && + process.versions.bun && + !/^bun(?:\.exe)?$/i.test(process.execPath.split(/[/\\]/).at(-1) ?? "") + ? { ...result, panel_runtime: process.execPath } + : result + } handlers.withdraw = async (input) => registry.withdraw(input) } diff --git a/packages/integration-kit/src/offer-registry.ts b/packages/integration-kit/src/offer-registry.ts index 037b539..1b47f8d 100644 --- a/packages/integration-kit/src/offer-registry.ts +++ b/packages/integration-kit/src/offer-registry.ts @@ -59,7 +59,7 @@ export type OfferRegistry = { advertise(input: unknown): Promise<{ outcome: AdvertiseOutcome }> withdraw(input: unknown): { outcome: WithdrawOutcome } hosts(): { offers: HostOffer[] } - attach(offerID: string, sessionID: string): { outcome: AttachOutcome } + attach(offerID: string, sessionID: string, takeover?: boolean): { outcome: AttachOutcome; replaced?: boolean } detach(sessionID: string): { outcome: "detached" | "none" } binding(sessionID: string): HostBinding | null liveHellos(): LiveHello[] @@ -315,7 +315,7 @@ export function createOfferRegistry(options: OfferRegistryOptions): OfferRegistr } }, - attach(offerID, sessionID) { + attach(offerID, sessionID, takeover) { if (!active()) return { outcome: "refused" } if (typeof sessionID !== "string" || !SESSION_ID.test(sessionID)) return { outcome: "refused" } if (typeof offerID !== "string" || !OFFER_ID.test(offerID)) return { outcome: "gone" } @@ -325,11 +325,11 @@ export function createOfferRegistry(options: OfferRegistryOptions): OfferRegistr if (record.compatibility === "incompatible") return { outcome: "refused" } const bound = sessions.get(sessionID) if (bound === offerID) return { outcome: "attached" } - if (bound !== undefined) return { outcome: "busy" } - if (sessions.size >= MAX_SESSIONS) return { outcome: "refused" } + if (bound !== undefined && !takeover) return { outcome: "busy" } + if (bound === undefined && sessions.size >= MAX_SESSIONS) return { outcome: "refused" } sessions.set(sessionID, offerID) changed("status") - return { outcome: "attached" } + return bound !== undefined ? { outcome: "attached", replaced: true } : { outcome: "attached" } }, detach(sessionID) { diff --git a/packages/integration-kit/src/panel-pipes.ts b/packages/integration-kit/src/panel-pipes.ts new file mode 100644 index 0000000..598a190 --- /dev/null +++ b/packages/integration-kit/src/panel-pipes.ts @@ -0,0 +1,31 @@ +import readline from "node:readline" +import { OpenCode } from "@opencode/client" +import { createPanel, type PanelHost, type PanelRequest } from "./panel.ts" +import { discoverService } from "./panel-service.ts" + +export function runPanel(config: PanelHost) { + delete process.env.BUN_BE_BUN + const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`) + const panel = createPanel(config, { + send, + discover: async (registration) => { + const endpoint = await discoverService(undefined, registration) + return endpoint && OpenCode.make({ baseUrl: endpoint.url, headers: endpoint.headers, fetch: endpoint.fetch }) + }, + }) + const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }) + input.on("line", (line) => { + if (!line.trim()) return + try { + if (Buffer.byteLength(line) > 1024 * 1024) throw new Error("Request too large") + const request = JSON.parse(line) as PanelRequest + if (!request.id || !request.channel || !request.method) throw new Error("Invalid request") + void panel.dispatch(request) + } catch { + send({ error: { message: "Invalid panel request." } }) + } + }) + input.on("close", () => { + void panel.closeAll().finally(() => process.exit(0)) + }) +} diff --git a/integrations/godot/plugin/src/service.ts b/packages/integration-kit/src/panel-service.ts similarity index 93% rename from integrations/godot/plugin/src/service.ts rename to packages/integration-kit/src/panel-service.ts index 29aa3ef..8a6f8d1 100644 --- a/integrations/godot/plugin/src/service.ts +++ b/packages/integration-kit/src/panel-service.ts @@ -1,7 +1,7 @@ import { readFile } from "node:fs/promises" import { Agent, request } from "node:http" import { homedir } from "node:os" -import { join } from "node:path" +import { dirname, join } from "node:path" import { Readable } from "node:stream" const agent = new Agent({ keepAlive: true, proxyEnv: {} }) @@ -62,8 +62,13 @@ export function serviceFetch(baseUrl: string): typeof globalThis.fetch { export async function discoverService( file = join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "opencode", "service.json"), + registrationFile?: string, ) { try { + if (registrationFile) { + if (!/^service(?:-[A-Za-z0-9._-]{1,64})?\.json$/.test(registrationFile)) return undefined + file = join(dirname(file), registrationFile) + } const registration = JSON.parse(await readFile(file, "utf8")) if ( typeof registration.url !== "string" || diff --git a/packages/integration-kit/src/panel.ts b/packages/integration-kit/src/panel.ts new file mode 100644 index 0000000..3fa355c --- /dev/null +++ b/packages/integration-kit/src/panel.ts @@ -0,0 +1,623 @@ +// An in-app chat is a plain client: attach its conversation to the host's existing offer, never announce one. + +import { normalize } from "node:path" +import type { OpenCode, SessionMessageInfo } from "@opencode/client" +import { rpcDefinition } from "./contract.ts" +import { requestHost as kitRequestHost } from "./host-client.ts" + +export type Api = ReturnType +type Rpc = Partial< + Record< + "hosts" | "attachHost" | "detachHost" | "bindingRead", + (input: object, options: object) => Promise> + > +> +type ModelRef = { id: string; providerID: string; variant?: string } +type Channel = { + id: string + directory: string + sessionID: string + label: string + offerID: string + host: { host: string; port: number; token: string } + handle: string + rpc: Rpc + abort: AbortController + tools: Map + busy: boolean + model?: ModelRef +} +type Target = { + id: string + params?: Record + fresh?: boolean + empty?: boolean + selected?: string + taken?: boolean + pending: string[] + problem?: string + retry?: NodeJS.Timeout +} +export type PanelRequest = { id: string; channel: string; method: string; params?: Record } + +export type PanelHost = { + app: string + rpcID: string + document: string + duplicateOffer: string + agent?: boolean + consoleEvents?: boolean + hostControls?: false +} +export type PanelDependencies = { + // The running OpenCode service, or undefined when none is running (never started from here). + discover: (registration?: string) => Promise + send: (message: unknown) => void + requestHost?: typeof kitRequestHost + checkEveryMs?: number + retryMs?: number +} + +// A message of this sidecar's own, safe to show in the panel. +class PanelError extends Error {} +class WaitingForOffer extends Error {} + +function toolDisplay(name: string, input: unknown) { + if (name !== "execute") return name + const code = (input as { code?: unknown } | null)?.code + if (typeof code !== "string") return name + const names = new Set( + Array.from( + code.matchAll(/\btools\.(\w+)(?:\.(\w+)|\[['"]([\w-]+)['"]\])\s*\(/g), + ([, ns, dot, key]) => `${ns}_${dot ?? key}`, + ), + ) + if (names.size) return [...names].join(", ") + // Code Mode discovery is a separate execute call, not an application tool invocation. + return /\bsearch\s*\(/.test(code) ? null : name +} + +// An error in one line for the panel: its first line, bounded, without a token, an authorization or a port. +export function briefly(error: unknown) { + const text = String((error as { message?: unknown } | null)?.message ?? error ?? "unknown error") + .split(/\r?\n/)[0] + ?.replace(/\b[0-9a-f]{32,}\b/gi, "…") + .replace(/(basic|bearer)\s+\S+/gi, "$1 …") + .replace(/\b(port\s+|:)\d{2,5}\b/gi, "$1…") + .slice(0, 240) + return `${text || "unknown error"}${/[.!?]$/.test(text ?? "") ? "" : "."}` +} + +const modelKey = (model: ModelRef | undefined) => + model + ? `${model.providerID}/${model.id}${model.variant && model.variant !== "default" ? `#${model.variant}` : ""}` + : "" + +const HISTORY_LIMIT = 20 +type Conversation = { id: string; title?: string; time?: { updated?: number } } + +function conversationEntry({ id, title, time }: Conversation) { + const minutes = time?.updated ? Math.max(0, Math.floor((Date.now() - time.updated) / 60_000)) : 0 + const age = + minutes >= 1440 ? `${Math.floor(minutes / 1440)}d` : minutes >= 60 ? `${Math.floor(minutes / 60)}h` : `${minutes}m` + return { id, title: `${title || "Untitled"} (${age} ago)` } +} +type EventData = { + sessionID?: string + delta?: string + input?: unknown + id?: string + name?: string + action?: string + agent?: string + requestID?: string + resources?: string[] + model?: ModelRef +} + +function history(messages: ReadonlyArray) { + return messages.flatMap((message) => { + if (message.type === "user") return [{ role: "user", text: message.text ?? "" }] + if (message.type !== "assistant") return [] + return (message.content ?? []).flatMap((part) => { + if (part.type === "text") return [{ role: "assistant", text: part.text ?? "" }] + if (part.type === "tool") { + const name = toolDisplay(part.name || "tool", part.state?.input) + if (name === null) return [] + const state = + { running: "starting", streaming: "starting", error: "failed", completed: "completed" }[ + part.state?.status ?? "" + ] ?? "unknown" + return [{ role: "tool", text: `${name} / ${state}`, name, state }] + } + return [] + }) + }) +} + +export function createPanel(config: PanelHost, deps: PanelDependencies) { + const requestHost = deps.requestHost ?? kitRequestHost + const checkEveryMs = deps.checkEveryMs ?? 5_000 + const channels = new Map() + const targets = new Map() + const queues = new Map>() + let stopping = false + let client: Api | undefined + let registration: string | undefined + let rpc: Rpc = {} + const event = (c: { id: string }, name: string, data: object) => deps.send({ channel: c.id, event: name, data }) + const options = (c: { directory: string }) => ({ + location: { directory: c.directory }, + signal: AbortSignal.timeout(3000), + }) + const host = (c: Channel, method: "cancel" | "resume") => + config.hostControls === false + ? Promise.resolve() + : requestHost(c.host, method, { script_handle: c.handle, session_id: c.sessionID }, { timeoutMs: 2000 }) + + async function api() { + if (client) return client + const found = await deps.discover(registration) + if (!found) throw new PanelError("Start OpenCode to use this conversation.") + client = found + rpc = found.rpc(rpcDefinition(config.rpcID, "native") as never) as unknown as Rpc + return client + } + + // This project's offer: the one with its label among the offered hosts (offer keys stay private to the service). + async function findOffer(c: { directory: string; label: string }) { + let result: Record | undefined + try { + result = await rpc.hosts?.({}, options(c)) + } catch (error) { + // A new Location may still be loading its plugins. + if (/RPC is unavailable|timed out|TimeoutError/i.test(briefly(error))) throw new WaitingForOffer() + throw error + } + const offers = ((result?.offers ?? []) as Array<{ label: string; offerID: string }>).filter( + (offer) => offer.label === c.label, + ) + if (offers.length > 1) + throw new PanelError(`Several ${config.duplicateOffer} offer ${c.label}; this panel cannot pick one.`) + if (!offers[0]) throw new WaitingForOffer() + return offers[0] + } + + async function attached(c: Channel) { + const read = await c.rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)) + return read?.state === "attached" && (read.binding as { offerID?: string } | undefined)?.offerID === c.offerID + } + + async function folderSessions(service: Api, directory: string) { + let cursor: string | undefined + const sessions = [] + do { + const listed = await service.session.list({ directory, archived: false, order: "desc", limit: 100, cursor }) + sessions.push( + ...listed.data.filter( + (candidate) => + !candidate.time?.archived && + (!candidate.location || folderKey(candidate.location.directory) === folderKey(directory)), + ), + ) + cursor = listed.cursor.next ?? undefined + } while (cursor) + return sessions.sort((a, b) => (b.time?.updated ?? 0) - (a.time?.updated ?? 0)) + } + + function folderKey(path: unknown) { + const key = normalize(String(path ?? "")).replace(/[/\\]$/, "") + return process.platform === "win32" ? key.toLowerCase() : key + } + + async function conversationList(target: Target, directory: string) { + const sessions = await folderSessions(await api(), directory) + event(target, "conversations", { + selected: target.selected, + entries: sessions.map(conversationEntry), + }) + return sessions + } + + // Closing releases this panel's conversation only: the offer stays for every other conversation. + async function close(c: Channel) { + if (channels.get(c.id) === c) channels.delete(c.id) + c.abort.abort() + if ([...channels.values()].some((other) => other.sessionID === c.sessionID && other.offerID === c.offerID)) return + // Another client may have moved the conversation to another host: never detach that binding. + await attached(c) + .then((still) => (still ? c.rpc.detachHost?.({ sessionID: c.sessionID }, options(c)) : undefined)) + .catch(() => {}) + } + + function forward(c: Channel, type: string, data: EventData) { + if (type === "session.model.selected") { + c.model = data.model + event(c, "model", { selected: modelKey(c.model) }) + } else if (config.agent && type === "session.agent.selected") event(c, "agent", { agent: data.agent ?? null }) + else if (config.consoleEvents && type === "session.step.started") { + c.model = data.model + event(c, "profile", { agent: data.agent, model: modelKey(c.model) }) + } else if (type === "session.execution.started") status(c, true) + else if (type === "session.text.started") event(c, "assistant_start", {}) + else if (type === "session.text.delta") event(c, "assistant_delta", { text: data.delta ?? "" }) + else if (type === "session.text.ended") event(c, "assistant_end", {}) + else if (type === "session.tool.input.started") { + c.tools.set(String(data.id), { name: String(data.name ?? "tool"), started: performance.now() }) + if (data.name !== "execute") event(c, "tool", { id: data.id, name: data.name, state: "starting" }) + } else if (type === "session.tool.called") { + const tool = c.tools.get(String(data.id)) + if (tool?.name === "execute" && tool.display === undefined) { + tool.display = toolDisplay(tool.name, data.input) + if (tool.display !== null) event(c, "tool", { id: data.id, name: tool.display, state: "starting" }) + } + } else if (type === "session.tool.success" || type === "session.tool.failed") { + const tool = c.tools.get(String(data.id)) + c.tools.delete(String(data.id)) + if (tool?.display === null) return + event(c, "tool", { + id: data.id, + name: tool?.display ?? tool?.name, + state: type === "session.tool.success" ? "completed" : "failed", + ...(config.consoleEvents && tool ? { duration_ms: Math.round(performance.now() - tool.started) } : {}), + }) + } else if (type === "permission.asked") + event(c, "permission", { request_id: data.id, action: data.action, resources: data.resources ?? [] }) + else if (config.consoleEvents && type === "permission.replied") + event(c, "permission_done", { request_id: data.requestID }) + else if (type === "session.execution.succeeded" || type === "session.idle") status(c, false) + else if (type === "session.execution.interrupted" || type === "session.execution.failed") { + if (type === "session.execution.failed") event(c, "error", { message: "OpenCode execution failed." }) + status(c, false, config.consoleEvents && type === "session.execution.interrupted") + void host(c, "cancel").catch(() => {}) + } + } + + function status(c: Channel, busy: boolean, interrupted?: boolean) { + c.busy = busy + event(c, "status", { state: busy ? "busy" : "idle", ...(interrupted ? { interrupted: true } : {}) }) + } + + async function stream(c: Channel, service: Api) { + try { + for await (const item of service.event.subscribe({ signal: c.abort.signal })) { + const data = item.data as unknown as EventData + if (data?.sessionID !== c.sessionID) continue + if (item.type === "session.renamed") { + void serialize(c.id, async () => { + const target = targets.get(c.id) + if (target && channels.get(c.id) === c) await conversationList(target, c.directory) + }).catch(() => {}) // Opening the selector refreshes the list again. + } else forward(c, item.type, data) + } + } catch { + // ended below + } + if (!c.abort.signal.aborted) { + void serialize(c.id, async () => { + if (channels.get(c.id) !== c) return + const target = targets.get(c.id) + if (target) await reconnect(target, c) + }) + } + } + + // A failed Connect says which step failed and why, in a line (never a credential): the user knows what to check. + const step = async (doing: string, work: () => Promise): Promise => { + try { + return await work() + } catch (error) { + if (error instanceof PanelError || error instanceof WaitingForOffer) throw error + throw new PanelError(`Could not connect while ${doing}: ${briefly(error)}`) + } + } + + async function connect(target: Target, params: Record) { + const id = target.id + const previous = channels.get(id) + if (previous) await close(previous) + if (!params.token || !params.offer_label) throw new WaitingForOffer() + if (params.host !== "127.0.0.1" || !Number.isInteger(params.port) || !/^[0-9a-f]{64}$/.test(String(params.token))) + throw new Error("Invalid host endpoint.") + const directory = String(params.directory ?? "") + const label = String(params.offer_label ?? "") + const handle = String(params.script_handle ?? "") + if (!directory || !label || !handle) throw new Error("Incomplete connect request.") + const next = typeof params.registration === "string" ? params.registration : undefined + if (next !== registration) client = undefined + registration = next + const service = await step("reaching OpenCode", api) + const currentRpc = service.rpc(rpcDefinition(config.rpcID, "native") as never) as unknown as Rpc + const offer = await step(`finding this ${config.document}'s offer`, () => findOffer({ directory, label })) + // The project's conversation, unless New asked for another one. + const sessions = await step("listing conversations in this folder", () => folderSessions(service, directory)) + const known = target.fresh ? undefined : (sessions.find((s) => s.id === target.selected) ?? sessions[0]) + if (!known && !target.pending.length) { + if (!target.empty) { + target.empty = true + event(target, "session", { id: null, draft: Boolean(target.fresh), workspace: directory }) + event(target, "history", { messages: [] }) + event(target, "conversations", { + entries: sessions.map(conversationEntry), + }) + event(target, "status", { state: "idle" }) + } + return + } + const session = + known ?? + (await step(`creating this ${config.document}'s conversation`, () => + service.session.create({ + location: { directory }, + }), + )) + target.fresh = false + target.empty = false + target.selected = session.id + const c: Channel = { + id, + directory, + sessionID: session.id, + label, + offerID: offer.offerID, + host: { host: "127.0.0.1", port: Number(params.port), token: String(params.token) }, + handle, + rpc: currentRpc, + abort: new AbortController(), + tools: new Map(), + busy: false, + model: (session as { model?: ModelRef }).model, + } + try { + const result = await step(`attaching the conversation to this ${config.document}`, async () => + c.rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID, takeover: true }, options(c)), + ) + if (result?.outcome === "busy") + throw new PanelError("This conversation is attached to another application; detach it there first.") + if (result?.outcome !== "attached") throw new PanelError(`${config.app} attachment was refused.`) + channels.set(id, c) + const [messages, models, configured, active] = await step("loading the conversation", () => + Promise.all([ + service.message.list({ sessionID: c.sessionID, order: "desc", limit: HISTORY_LIMIT + 1 }), + service.model.list({ location: { directory } }), + service.model.default({ location: { directory } }), + service.session.active(), + ]), + ) + if (!c.model && configured.data) c.model = configured.data as ModelRef + const recent = history(messages.data.slice(0, HISTORY_LIMIT).reverse()) + if (messages.data.length > HISTORY_LIMIT) + recent.unshift({ role: "system", text: "Earlier messages are available in OpenCode." }) + event(c, "history", { messages: recent }) + event(c, "session", { + id: c.sessionID, + resumed: Boolean(known), + model: modelKey(c.model), + ...(config.agent ? { agent: (session as { agent?: string }).agent ?? null } : {}), + workspace: directory, + }) + event(c, "models", { + selected: modelKey(c.model), + models: models.data + .filter((model) => model.enabled) + .map((model) => ({ id: model.id, provider_id: model.providerID, name: model.name })), + }) + event(target, "conversations", { + selected: session.id, + entries: (known ? sessions : [session, ...sessions]).map(conversationEntry), + }) + if (result.replaced) event(c, "notice", { message: "Conversation moved from another host to this one." }) + status(c, (active as Record)[c.sessionID]?.type === "running") + void stream(c, service) + } catch (error) { + await close(c) + throw error + } + } + + async function act(c: Channel, method: string, params: Record) { + if (method === "close") return await close(c) + const service = await api() + if (method === "interrupt") { + await host(c, "cancel").catch(() => {}) + await service.session.interrupt({ sessionID: c.sessionID, resume: false }) + } else if (method === "switch_model") { + const key = String(params.model ?? "") + const catalog = await service.model.list({ location: { directory: c.directory } }) + const selected = catalog.data.find((model) => model.enabled && `${model.providerID}/${model.id}` === key) + if (!selected) throw new PanelError("This model is not available in this workspace.") + c.model = { id: selected.id, providerID: selected.providerID } + await service.session.switchModel({ sessionID: c.sessionID, model: c.model }) + event(c, "model", { selected: modelKey(c.model) }) + } else if (method === "permission_reply") { + const decision = params.reply + if (decision !== "once" && decision !== "reject") throw new Error("Invalid permission answer.") + await service.permission.reply({ sessionID: c.sessionID, requestID: String(params.request_id), decision }) + } else throw new Error("Unknown panel action.") + } + + function serialize(id: string, work: () => Promise) { + if (stopping) return Promise.resolve() + const next = (queues.get(id) ?? Promise.resolve()).then(work) + queues.set(id, next) + void next + .finally(() => { + if (queues.get(id) === next) queues.delete(id) + }) + .catch(() => {}) + return next + } + + function later(target: Target, ms: number) { + clearTimeout(target.retry) + if (stopping) return + target.retry = setTimeout(() => { + void serialize(target.id, async () => { + if (targets.get(target.id) !== target) return + const c = channels.get(target.id) + if (c && !(await attached(c).catch(() => false))) await reconnect(target, c) + else { + if (c?.busy) { + const active = await (await api()).session.active().catch(() => undefined) + if (active && (active as Record)[c.sessionID]?.type !== "running" && c.busy) + status(c, false) + } + await reconcile(target) + } + }) + }, ms) + target.retry.unref?.() + } + + async function reconnect(target: Target, c: Channel) { + const read = await c.rpc.bindingRead?.({ sessionID: c.sessionID }, options(c)).catch(() => undefined) + if (read?.state === "attached" && (read.binding as { offerID?: string }).offerID !== c.offerID) { + // Do not steal it back from the host whose user just opened it. + target.taken = true + await close(c) + event(target, "status", { state: "connecting" }) + event(target, "notice", { message: "Conversation moved to another host. Open it again here to take it back." }) + return + } + event(target, "status", { state: "connecting" }) + await close(c) + client = undefined + later(target, deps.retryMs ?? 1_000) + } + + async function reconcile(target: Target) { + if (!target.params || target.taken || stopping) return + let c = channels.get(target.id) + if (!c) { + try { + await connect(target, target.params) + target.problem = undefined + } catch (error) { + client = undefined + if (!(error instanceof WaitingForOffer)) { + const message = error instanceof PanelError ? error.message : `Could not connect: ${briefly(error)}` + if (message !== target.problem) event(target, "error", { message }) + target.problem = message + } + } + c = channels.get(target.id) + } + if (!c) { + if (!target.empty || target.pending.length) later(target, deps.retryMs ?? 1_000) + return + } + later(target, checkEveryMs) + while (target.pending.length) { + if (!(await attached(c).catch(() => false))) return await reconnect(target, c) + try { + await host(c, "resume") + } catch { + return later(target, deps.retryMs ?? 1_000) + } + const text = target.pending.shift() as string + event(target, "user_message", { text }) + try { + await (await api()).session.prompt({ sessionID: c.sessionID, text }) + } catch (error) { + // Delivery is uncertain once submitted: never replay automatically. + event(target, "error", { message: `Message delivery could not be confirmed: ${briefly(error)}` }) + } + } + } + + async function handle(request: PanelRequest) { + try { + const params = request.params ?? {} + const id = request.channel + const target = targets.get(id) ?? { id, pending: [] } + const c = channels.get(id) + if (request.method === "close") { + clearTimeout(target.retry) + targets.delete(id) + if (c) await close(c) + } else { + targets.set(id, target) + if (request.method === "list" && target.params) { + await conversationList(target, String(target.params.directory)) + } else if (request.method === "open" && target.params) { + const sessions = await folderSessions(await api(), String(target.params.directory)) + const selected = sessions.find((s) => s.id === params.session_id) + if (!selected) throw new PanelError("That conversation is not in this folder.") + target.selected = selected.id + target.taken = false + target.fresh = false + target.pending = [] + if (c?.sessionID !== selected.id) { + event(target, "status", { state: "connecting" }) + if (c) await close(c) + await reconcile(target) + } + } else if (request.method === "connect" || request.method === "new_session") { + const fresh = request.method === "new_session" + const moved = target.params && folderKey(target.params.directory) !== folderKey(params.directory) + if (moved) target.selected = undefined + if (!target.params) { + if (typeof params.session_id === "string") target.selected = params.session_id + target.fresh = params.draft === true + } + if (fresh || moved) { + if (target.pending.length) + event(target, "notice", { message: "Queued messages were not sent to the new conversation." }) + target.pending = [] + } + const previous = target.params + target.params = params + if ( + c && + previous && + !fresh && + !moved && + ["host", "port", "token", "registration", "script_handle"].every((key) => params[key] === previous[key]) + ) { + // A rename of the same live offer does not move the attachment or interrupt its stream. + deps.send({ id: request.id, result: {} }) + return + } + if (fresh || moved) { + target.selected = undefined + target.fresh = fresh + target.empty = false + } else if (target.empty) { + target.empty = false + } + target.taken = false + target.problem = undefined + event(target, "status", { state: "connecting" }) + if (c) await close(c) + await reconcile(target) + } else if (request.method === "prompt") { + target.pending.push(String(params.text ?? "")) + if (target.params) await reconcile(target) + } else if (request.method === "interrupt") { + target.pending = [] + if (c) await act(c, request.method, params) + } else if (c) await act(c, request.method, params) + } + deps.send({ id: request.id, result: {} }) + } catch (error) { + deps.send({ + channel: request.channel, + event: "error", + data: { + message: error instanceof PanelError ? error.message : `The panel action failed: ${briefly(error)}`, + }, + }) + deps.send({ id: request.id, error: { message: "Panel action failed." } }) + } + } + + return { + dispatch: (request: PanelRequest) => serialize(request.channel, () => handle(request)), + closeAll: async () => { + stopping = true + for (const target of targets.values()) clearTimeout(target.retry) + await Promise.allSettled(queues.values()) + await Promise.allSettled([...channels.values()].map(close)) + }, + } +} diff --git a/packages/integration-kit/src/session-bindings.ts b/packages/integration-kit/src/session-bindings.ts index 0e15276..3a04fa0 100644 --- a/packages/integration-kit/src/session-bindings.ts +++ b/packages/integration-kit/src/session-bindings.ts @@ -73,10 +73,10 @@ export function createSessionBindings(registry: OfferRegistry, native?: NativeSe return parseBindingReadOutput(registry.read(parsed.sessionID)) ?? { state: "unknown" } } - const attach = async (offerID: string, sessionID: string, signal?: AbortSignal) => { + const attach = async (offerID: string, sessionID: string, signal?: AbortSignal, takeover?: boolean) => { const authority = await snapshot(sessionID, signal) return authority && !signal?.aborted && registry.current(authority) - ? registry.attach(offerID, sessionID) + ? registry.attach(offerID, sessionID, takeover) : { outcome: "refused" as const } } const detach = async (sessionID: string, signal?: AbortSignal) => { diff --git a/packages/integration-kit/test/panel.test.ts b/packages/integration-kit/test/panel.test.ts new file mode 100644 index 0000000..d3c948f --- /dev/null +++ b/packages/integration-kit/test/panel.test.ts @@ -0,0 +1,170 @@ +import assert from "node:assert/strict" +import { spawnSync } from "node:child_process" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { it } from "node:test" +import { setTimeout as delay } from "node:timers/promises" +import { type Api, createPanel } from "../src/panel.ts" + +it("the Python hosts prefer the advertised executable over either Node fallback", () => { + const python = process.env.PYTHON ?? (process.platform === "win32" ? "python" : "python3") + const result = spawnSync(python, ["-I", join(import.meta.dirname, "panel_launcher_test.py")], { + encoding: "utf8", + windowsHide: true, + }) + assert.equal(result.status, 0, result.error?.message ?? result.stderr) +}) + +it("queues during startup, starts drafts lazily and selects/rebinds folder conversations", async () => { + const directory = join(tmpdir(), "shot") + const other = join(tmpdir(), "other") + const prompt: unknown[] = [] + const attached = new Map() + const sessions: Array<{ + id: string + title: string + location: { directory: string } + time: { updated: number; archived?: number } + }> = [] + let label = "" + let offer = "offer-a" + const out: { event: string; data: Record }[] = [] + const api = { + rpc: () => ({ + hosts: async () => ({ offers: label ? [{ label, offerID: offer }] : [] }), + attachHost: async ({ + offerID, + sessionID, + takeover, + }: { + offerID: string + sessionID: string + takeover: boolean + }) => { + assert.equal(takeover, true) + const replaced = attached.has(sessionID) && attached.get(sessionID) !== offerID + attached.set(sessionID, offerID) + return { outcome: "attached", replaced } + }, + bindingRead: async ({ sessionID }: { sessionID: string }) => + attached.has(sessionID) + ? { state: "attached", binding: { offerID: attached.get(sessionID) } } + : { state: "none" }, + detachHost: async ({ sessionID }: { sessionID: string }) => attached.delete(sessionID), + }), + session: { + list: async () => ({ data: sessions, cursor: {} }), + create: async (input: { location: { directory: string } }) => { + assert.deepEqual(input, { location: { directory } }) + const item = { + id: `created-${sessions.length}`, + title: "OpenCode default", + location: input.location, + time: { updated: 100 }, + } + sessions.push(item) + return item + }, + prompt: async (item: unknown) => prompt.push(item), + active: async () => ({}), + }, + model: { list: async () => ({ data: [] }), default: async () => ({}) }, + message: { list: async () => ({ data: [], cursor: { next: "end" } }) }, + event: { + subscribe: async function* ({ signal }: { signal: AbortSignal }) { + await new Promise((resolve) => signal.addEventListener("abort", resolve, { once: true })) + }, + }, + } as unknown as Api + const panel = createPanel( + { app: "Test", rpcID: "neuralnomads.test", document: "scene", duplicateOffer: "hosts" }, + { + discover: async () => api, + send: (value) => out.push(value as (typeof out)[number]), + requestHost: async () => ({}), + retryMs: 3, + checkEveryMs: 10, + }, + ) + const params = (offer_label: string, dir = directory) => ({ + host: "127.0.0.1", + port: 5555, + token: "a".repeat(64), + script_handle: offer_label, + offer_label, + directory: dir, + }) + const call = (method: string, params?: Record, channel = "panel") => + panel.dispatch({ id: method, channel, method, params }) + const until = async (condition: () => boolean) => { + for (let i = 0; i < 200; i++) { + if (condition()) return + await delay(5) + } + assert.fail("Panel did not reach the expected state") + } + const current = () => out.filter((item) => item.event === "session").at(-1)?.data.id + try { + await call("connect", params("v001")) + assert.equal( + out.some((item) => item.event === "error"), + false, + ) + assert.equal(sessions.length, 0) + await call("prompt", { text: "early" }) + assert.equal(prompt.length, 0) + label = "v001" + await until(() => prompt.length === 1) + assert.deepEqual(out.findLast(({ event }) => event === "history")?.data.messages, []) + assert.equal(sessions[0]?.title, "OpenCode default") + assert.deepEqual(prompt[0], { sessionID: "created-0", text: "early" }) + assert.deepEqual( + out.filter(({ event }) => event === "user_message").map(({ data }) => data.text), + ["early"], + ) + + sessions.push( + { id: "codenomad", title: "CodeNomad", location: { directory }, time: { updated: 200 } }, + { id: "archived", title: "Archived", location: { directory }, time: { updated: 300, archived: 301 } }, + { id: "different", title: "Different", location: { directory: other }, time: { updated: 400 } }, + ) + label = "v002" + await call("connect", params(label)) + assert.equal(current(), "created-0") + const first = sessions[0] + assert.ok(first) + first.title = "Generated from the first message" + await call("list") + const entries = out.findLast((item) => item.event === "conversations")?.data.entries as + | { id: string; title: string }[] + | undefined + assert.deepEqual( + entries?.map(({ id }) => id), + ["codenomad", "created-0"], + ) + assert.match(entries?.[1]?.title ?? "", /^Generated from the first message \(.+ ago\)$/) + attached.set("codenomad", "other-host") + await call("open", { session_id: "codenomad" }) + assert.equal(current(), "codenomad") + assert.equal(attached.get("codenomad"), offer) + assert.match(String(out.findLast((item) => item.event === "notice")?.data.message), /moved from another host/) + await call("new_session", params(label)) + assert.equal(current(), null) + assert.equal(sessions.length, 4) + await call("prompt", { text: "first in draft" }) + assert.equal(sessions.length, 5) + assert.equal(current(), "created-4") + attached.delete("created-4") + offer = "offer-restarted" + await until(() => attached.get("created-4") === offer) + await call("connect", params(label, other)) + assert.equal(current(), "different") + await call("connect", params(label), "newly-opened") + assert.equal(current(), "codenomad") + await call("connect", params(label, join(tmpdir(), "empty"))) + assert.equal(current(), null) + assert.equal(sessions.length, 5) + } finally { + await panel.closeAll() + } +}) diff --git a/packages/integration-kit/test/panel_launcher_test.py b/packages/integration-kit/test/panel_launcher_test.py new file mode 100644 index 0000000..2869a85 --- /dev/null +++ b/packages/integration-kit/test/panel_launcher_test.py @@ -0,0 +1,28 @@ +import os +from pathlib import Path +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "python")) +from opencode_service import panel_launcher + + +class LauncherTests(unittest.TestCase): + def test_selection_order_and_fallback(self): + override = "TEST_NODE" + advertised = os.path.abspath("opencode") + accepted = {"outcome": "accepted", "panel_runtime": advertised} + with patch.dict(os.environ, {override: "custom"}), patch("shutil.which") as which: + which.side_effect = lambda candidate: candidate + self.assertEqual(panel_launcher([accepted], override), (advertised, True)) + which.assert_called_once_with(advertised) + self.assertEqual(panel_launcher([], override), ("custom", False)) + which.side_effect = lambda candidate: "node" if candidate == "node" else None + self.assertEqual(panel_launcher([accepted], override), ("node", False)) + which.side_effect = lambda _: None + self.assertEqual(panel_launcher([accepted], override), (None, False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/spec/README.md b/spec/README.md index fec5418..2d00455 100644 --- a/spec/README.md +++ b/spec/README.md @@ -19,9 +19,9 @@ The integration's `package.json` carries a marker under `opencodeIntegration`, r "host": { "app": "blender", "protocol": 1, - "range": "^0.4.8", + "range": "^0.5.0", "appVersions": ">=5.3", - "payload": "host/blender/opencode_link-0.4.8.zip", + "payload": "host/blender/opencode_link-0.5.0.zip", "sha256": "" } }