From 93e3ef0b44e77e154c60d5135e9e94404b7687b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Wed, 18 Nov 2026 12:54:43 +0100 Subject: [PATCH 1/2] feat(godot): add OpenCode for Godot 0.1.0 and editor dock --- .github/workflows/ci.yml | 23 + catalog.json | 18 + .../godot/host/addons/opencode_link/LICENSE | 21 + .../godot/host/addons/opencode_link/dock.gd | 374 ++++++++++++ .../godot/host/addons/opencode_link/hints.gd | 209 +++++++ .../godot/host/addons/opencode_link/link.gd | 451 ++++++++++++++ .../host/addons/opencode_link/plugin.cfg | 7 + .../godot/host/addons/opencode_link/plugin.gd | 48 ++ .../godot/host/addons/opencode_link/runner.gd | 502 +++++++++++++++ .../host/addons/opencode_link/service.gd | 312 ++++++++++ integrations/godot/plugin/LICENSE | 21 + integrations/godot/plugin/README.md | 40 ++ .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 0 -> 179665 bytes .../plugin/methods/tools/godot_context.json | 42 ++ .../methods/tools/godot_execute_code.json | 34 ++ .../plugin/methods/tools/godot_hosts.json | 20 + .../plugin/methods/tools/godot_inspect.json | 46 ++ .../methods/tools/godot_install_host.json | 16 + .../godot/plugin/methods/tools/godot_run.json | 47 ++ .../plugin/methods/tools/godot_save.json | 27 + .../plugin/methods/tools/godot_verify.json | 41 ++ integrations/godot/plugin/package.json | 68 +++ .../godot/plugin/programs/background.gd | 87 +++ integrations/godot/plugin/programs/checks.gd | 191 ++++++ integrations/godot/plugin/programs/copy.gd | 19 + integrations/godot/plugin/programs/inspect.gd | 253 ++++++++ integrations/godot/plugin/programs/save.gd | 54 ++ integrations/godot/plugin/programs/verify.gd | 12 + .../godot/plugin/scripts/build-host.ts | 63 ++ integrations/godot/plugin/scripts/build.ts | 38 ++ integrations/godot/plugin/src/closed.ts | 35 ++ integrations/godot/plugin/src/host-install.ts | 117 ++++ integrations/godot/plugin/src/integration.ts | 575 ++++++++++++++++++ integrations/godot/plugin/src/kit.ts | 1 + integrations/godot/plugin/src/method.ts | 24 + integrations/godot/plugin/src/options.ts | 18 + integrations/godot/plugin/src/paths.ts | 21 + integrations/godot/plugin/src/plugin.ts | 4 + integrations/godot/plugin/src/programs.ts | 25 + integrations/godot/plugin/src/service.ts | 91 +++ integrations/godot/plugin/src/sidecar-core.ts | 385 ++++++++++++ integrations/godot/plugin/src/sidecar.ts | 35 ++ integrations/godot/plugin/src/tasks.ts | 260 ++++++++ integrations/godot/plugin/tsconfig.json | 10 + integrations/godot/test/conformance.test.ts | 102 ++++ integrations/godot/test/godot.test.ts | 284 +++++++++ integrations/godot/test/helpers.ts | 263 ++++++++ integrations/godot/test/install.test.ts | 36 ++ integrations/godot/test/panel.test.ts | 386 ++++++++++++ integrations/godot/test/plugin.test.ts | 392 ++++++++++++ integrations/godot/test/registry.test.ts | 63 ++ integrations/godot/test/tasks.test.ts | 132 ++++ package-lock.json | 26 +- package.json | 2 +- 54 files changed, 6368 insertions(+), 3 deletions(-) create mode 100644 integrations/godot/host/addons/opencode_link/LICENSE create mode 100644 integrations/godot/host/addons/opencode_link/dock.gd create mode 100644 integrations/godot/host/addons/opencode_link/hints.gd create mode 100644 integrations/godot/host/addons/opencode_link/link.gd create mode 100644 integrations/godot/host/addons/opencode_link/plugin.cfg create mode 100644 integrations/godot/host/addons/opencode_link/plugin.gd create mode 100644 integrations/godot/host/addons/opencode_link/runner.gd create mode 100644 integrations/godot/host/addons/opencode_link/service.gd create mode 100644 integrations/godot/plugin/LICENSE create mode 100644 integrations/godot/plugin/README.md create mode 100644 integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip create mode 100644 integrations/godot/plugin/methods/tools/godot_context.json create mode 100644 integrations/godot/plugin/methods/tools/godot_execute_code.json create mode 100644 integrations/godot/plugin/methods/tools/godot_hosts.json create mode 100644 integrations/godot/plugin/methods/tools/godot_inspect.json create mode 100644 integrations/godot/plugin/methods/tools/godot_install_host.json create mode 100644 integrations/godot/plugin/methods/tools/godot_run.json create mode 100644 integrations/godot/plugin/methods/tools/godot_save.json create mode 100644 integrations/godot/plugin/methods/tools/godot_verify.json create mode 100644 integrations/godot/plugin/package.json create mode 100644 integrations/godot/plugin/programs/background.gd create mode 100644 integrations/godot/plugin/programs/checks.gd create mode 100644 integrations/godot/plugin/programs/copy.gd create mode 100644 integrations/godot/plugin/programs/inspect.gd create mode 100644 integrations/godot/plugin/programs/save.gd create mode 100644 integrations/godot/plugin/programs/verify.gd create mode 100644 integrations/godot/plugin/scripts/build-host.ts create mode 100644 integrations/godot/plugin/scripts/build.ts create mode 100644 integrations/godot/plugin/src/closed.ts create mode 100644 integrations/godot/plugin/src/host-install.ts create mode 100644 integrations/godot/plugin/src/integration.ts create mode 100644 integrations/godot/plugin/src/kit.ts create mode 100644 integrations/godot/plugin/src/method.ts create mode 100644 integrations/godot/plugin/src/options.ts create mode 100644 integrations/godot/plugin/src/paths.ts create mode 100644 integrations/godot/plugin/src/plugin.ts create mode 100644 integrations/godot/plugin/src/programs.ts create mode 100644 integrations/godot/plugin/src/service.ts create mode 100644 integrations/godot/plugin/src/sidecar-core.ts create mode 100644 integrations/godot/plugin/src/sidecar.ts create mode 100644 integrations/godot/plugin/src/tasks.ts create mode 100644 integrations/godot/plugin/tsconfig.json create mode 100644 integrations/godot/test/conformance.test.ts create mode 100644 integrations/godot/test/godot.test.ts create mode 100644 integrations/godot/test/helpers.ts create mode 100644 integrations/godot/test/install.test.ts create mode 100644 integrations/godot/test/panel.test.ts create mode 100644 integrations/godot/test/plugin.test.ts create mode 100644 integrations/godot/test/registry.test.ts create mode 100644 integrations/godot/test/tasks.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 463e647..31a1cb6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -133,6 +133,29 @@ jobs: export BLENDER_TEST_BIN="$HOME/blender-${{ matrix.blender }}/blender" node --test integrations/blender/test/extension.test.ts + godot: + name: Godot host and dock (4.7.2, headless) + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: npm + - run: npm ci + - name: Download Godot and exercise the packaged add-on + run: | + archive=Godot_v4.7.2-stable_linux.x86_64.zip + curl --fail --location --silent --show-error -o "$RUNNER_TEMP/$archive" "https://github.com/godotengine/godot/releases/download/4.7.2-stable/$archive" + echo "cadd3204e728a35d3f13adb7fd0d7902636b79f6b95c40c265eb73b6c35329e4 $RUNNER_TEMP/$archive" | sha256sum --check + unzip -q "$RUNNER_TEMP/$archive" -d "$RUNNER_TEMP/godot" + export GODOT_TEST_BIN="$RUNNER_TEMP/godot/${archive%.zip}" + "$GODOT_TEST_BIN" --headless --version + node --test integrations/godot/test/godot.test.ts + trace-scan: name: Trace scan runs-on: ubuntu-latest diff --git a/catalog.json b/catalog.json index 51fa497..7ac6b98 100644 --- a/catalog.json +++ b/catalog.json @@ -55,6 +55,24 @@ "status": "preview", "sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/gaffer/plugin"] } }, + { + "id": "godot", + "package": "@neuralnomads/opencode-godot", + "range": "^0.1", + "displayName": "OpenCode for Godot", + "family": "native", + "plugin": "neuralnomads.godot", + "rpc": "neuralnomads.godot", + "summary": { + "en": "Read, change and check the project open in the Godot editor from any OpenCode conversation: GDScript as one undo action, checks and runs in a background Godot, and an optional conversation dock in the editor.", + "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" }, + "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"] } + }, { "id": "houdini", "package": "@neuralnomads/opencode-houdini", diff --git a/integrations/godot/host/addons/opencode_link/LICENSE b/integrations/godot/host/addons/opencode_link/LICENSE new file mode 100644 index 0000000..64cabb5 --- /dev/null +++ b/integrations/godot/host/addons/opencode_link/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Neural Nomads + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/integrations/godot/host/addons/opencode_link/dock.gd b/integrations/godot/host/addons/opencode_link/dock.gd new file mode 100644 index 0000000..f92b726 --- /dev/null +++ b/integrations/godot/host/addons/opencode_link/dock.gd @@ -0,0 +1,374 @@ +@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. + +var link: RefCounted + +var _pid := -1 +var _stdio: FileAccess +var _stderr: FileAccess +var _buffer := PackedByteArray() +var _channel := "" +var _next := 0 +var _active := false +var _connected := false +var _busy := false +var _streaming := false +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 _transcript := RichTextLabel.new() +var _permission_row := HBoxContainer.new() +var _permission_label := Label.new() +var _prompt := TextEdit.new() +var _send_button := Button.new() +var _stop_button := Button.new() + + +func _ready() -> void: + _channel = "dock-" + Crypto.new().generate_random_bytes(8).hex_encode() + 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_child(_status_label) + add_child(header) + + var row := HBoxContainer.new() + _agent_label.text = "" + row.add_child(_agent_label) + _model_button.size_flags_horizontal = Control.SIZE_EXPAND_FILL + _model_button.disabled = true + _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) + add_child(row) + + _transcript.size_flags_vertical = Control.SIZE_EXPAND_FILL + _transcript.bbcode_enabled = true + _transcript.scroll_following = true + _transcript.selection_enabled = true + _transcript.custom_minimum_size = Vector2(0, 200) + add_child(_transcript) + + _permission_row.visible = false + _permission_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL + _permission_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + _permission_row.add_child(_permission_label) + var reject := Button.new() + reject.text = "Reject" + reject.pressed.connect(func(): _reply_permission("reject")) + _permission_row.add_child(reject) + var allow := Button.new() + allow.text = "Allow once" + allow.pressed.connect(func(): _reply_permission("once")) + _permission_row.add_child(allow) + add_child(_permission_row) + + _prompt.placeholder_text = "Ask OpenCode about this project... Ctrl+Enter to send" + _prompt.custom_minimum_size = Vector2(0, 80) + _prompt.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY + _prompt.gui_input.connect(_prompt_input) + add_child(_prompt) + var buttons := HBoxContainer.new() + buttons.alignment = BoxContainer.ALIGNMENT_END + _stop_button.text = "Stop" + _stop_button.disabled = true + _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: + _send("close", {}) + if _stdio != null: + # The sidecar ends once its input closes, after releasing its conversations. + _stdio.close() + _stdio = null + + +# --- 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 == "": + return + _prompt.text = "" + _append("user", text) + _send("prompt", {"text": text}) + + +func stop() -> void: + _send("interrupt", {}) + + +func disconnect_dock() -> void: + _active = false + _connected = false + _send("close", {}) + _connect_button.text = "Connect" + _status_label.text = "DISCONNECTED" + _set_busy(false) + _new_button.disabled = true + _model_button.disabled = true + + +func transcript() -> String: + return _transcript.get_parsed_text() + + +func state() -> Dictionary: + return {"active": _active, "connected": _connected, "busy": _busy, "status": _status_label.text, "model": _model} + + +# --- the sidecar --- + +static func _node() -> String: + var configured := OS.get_environment("NEURALNOMADS_GODOT_NODE") + if configured != "": + return configured + var windows := OS.get_name() == "Windows" + for directory in OS.get_environment("PATH").split(";" if windows else ":", false): + var candidate := directory.path_join("node.exe" if windows else "node") + if FileAccess.file_exists(candidate): + return candidate + 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 + 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) + if started.is_empty(): + _append("error", "Node.js did not start: %s" % node) + return false + _pid = started.pid + _stdio = started.stdio + _stderr = started.stderr + _buffer = PackedByteArray() + return true + + +func _send(method: String, params: Dictionary) -> void: + if method == "close" and (_stdio == null or not OS.is_process_running(_pid)): + return + if not _start(): + return + _next += 1 + var line := JSON.stringify({"id": str(_next), "channel": _channel, "method": method, "params": params}) + "\n" + _stdio.store_buffer(line.to_utf8_buffer()) + + +func _process(_delta: float) -> void: + if _stdio == null: + return + var available := _stdio.get_length() + if available > 0: + _buffer.append_array(_stdio.get_buffer(available)) + var newline := _buffer.find(10) + while newline >= 0: + var line := _buffer.slice(0, newline).get_string_from_utf8() + _buffer = _buffer.slice(newline + 1) + newline = _buffer.find(10) + var parser := JSON.new() + if line.strip_edges() == "" or parser.parse(line) != OK or not (parser.data is Dictionary): + continue + 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: + _event("error", message.error) + if _stderr != null and _stderr.get_length() > 0: + _stderr.get_buffer(_stderr.get_length()) + if not OS.is_process_running(_pid): + _stdio = null + _stderr = null + _pid = -1 + if _active: + _event("error", {"message": "The OpenCode sidecar stopped; choose Connect to start it again."}) + + +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?).") + return + var project: String = link.project_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, + }) + _active = true + _connected = false + _connect_button.text = "Disconnect" + _new_button.disabled = false + _status_label.text = "CONNECTING" + _send_button.disabled = true + _send(method, params) + + +func _select_model(index: int) -> void: + var key := _model_button.get_item_metadata(index) as String + if _busy or not _connected or key == "" or key == _model: + return + _send("switch_model", {"model": key}) + + +func _prompt_input(event: InputEvent) -> void: + if event is InputEventKey and event.pressed and event.keycode == KEY_ENTER and event.is_command_or_control_pressed(): + send_text(_prompt.text) + _prompt.accept_event() + + +func _reply_permission(reply: String) -> void: + if _permission == "": + return + _send("permission_reply", {"request_id": _permission, "reply": reply}) + _permission = "" + _permission_row.visible = false + + +func _set_busy(busy: bool) -> void: + _busy = busy + _stop_button.disabled = not busy + _send_button.disabled = not _connected or busy + _prompt.editable = not busy + _model_button.disabled = not _connected or busy or _models.is_empty() + + +func _set_model(model: String) -> void: + if model == "": + return + _model = model + for i in _model_button.item_count: + if _model_button.get_item_metadata(i) == model: + _model_button.select(i) + return + _model_button.add_item(model.get_slice("/", 1) if model.contains("/") else model) + _model_button.set_item_metadata(_model_button.item_count - 1, model) + _model_button.select(_model_button.item_count - 1) + + +func _event(name: String, data: Dictionary) -> void: + if not _active and name != "error": + return # a reply to a connection this dock has since closed + match name: + "session": + _connected = true + _session_label.text = "session " + str(data.get("id", "")).right(8) + _session_label.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") + "models": + _models = data.get("models", []) + _model_button.clear() + for model in _models: + var key := "%s/%s" % [model.get("provider_id", ""), model.get("id", "")] + _model_button.add_item(str(model.get("name", key))) + _model_button.set_item_metadata(_model_button.item_count - 1, key) + _set_model(str(data.get("selected", ""))) + _model_button.disabled = _models.is_empty() or _busy + "model": + _set_model(str(data.get("selected", ""))) + "agent": + _agent_label.text = str(data.get("agent", "")) + "history": + _transcript.clear() + for message in data.get("messages", []): + _append(str(message.get("role", "system")), str(message.get("text", ""))) + "assistant_start": + _start_assistant() + "assistant_delta": + if not _streaming: + _start_assistant() + _transcript.append_text(_escape(str(data.get("text", "")))) + "assistant_end": + _streaming = false + _transcript.append_text("\n") + "tool": + _append("tool", "%s / %s" % [data.get("name", data.get("id", "tool")), data.get("state", "")]) + "permission": + _permission = str(data.get("request_id", "")) + var resources: Array = data.get("resources", []) + _permission_label.text = "Permission: %s%s" % [data.get("action", ""), (" / " + ", ".join(resources)) if resources else ""] + _permission_row.visible = true + "status": + var value := str(data.get("state", "unknown")) + _status_label.text = value.to_upper() + _set_busy(value in ["busy", "retry"]) + "error": + _append("error", str(data.get("message", "Unknown OpenCode error"))) + _status_label.text = "ERROR" + _streaming = false + _set_busy(false) + + +static func _escape(text: String) -> String: + return text.replace("[", "[lb]") + + +const COLORS := {"user": "#e7e9eb", "assistant": "#b9ddd7", "tool": "#d5a657", "error": "#ef7777", "system": "#8e969c"} +const LABELS := {"user": "YOU", "assistant": "OPENCODE", "tool": "TOOL", "error": "ERROR", "system": "SYSTEM"} + + +func _append(role: String, text: String) -> void: + _streaming = false + var color: String = COLORS.get(role, COLORS.system) + if _transcript.get_parsed_text() != "": + _transcript.append_text("\n") + _transcript.append_text("[color=%s][b]%s[/b][/color]\n[color=%s]%s[/color]\n" % [COLORS.tool if role == "tool" else color, LABELS.get(role, role.to_upper()), color, _escape(text)]) + + +func _start_assistant() -> void: + if _streaming: + return + _streaming = true + if _transcript.get_parsed_text() != "": + _transcript.append_text("\n") + _transcript.append_text("[color=%s][b]OPENCODE[/b][/color]\n" % COLORS.assistant) diff --git a/integrations/godot/host/addons/opencode_link/hints.gd b/integrations/godot/host/addons/opencode_link/hints.gd new file mode 100644 index 0000000..325638c --- /dev/null +++ b/integrations/godot/host/addons/opencode_link/hints.gd @@ -0,0 +1,209 @@ +@tool +extends RefCounted +## What THIS Godot knows about a failed run, read from its ClassDB and the open scene: the closest class, property, +## method or signal names, a method's real signature, the closest children of a node path that was not found. + +const MAX_NAMES := 6 + + +static func _closest(word: String, names: Array, limit := MAX_NAMES) -> Array: + var lower := word.to_lower() + var scored := [] + for name in names: + var text := str(name) + var score := lower.similarity(text.to_lower()) + if text.to_lower().contains(lower) or lower.contains(text.to_lower()): + score += 0.3 + if score > 0.35: + scored.append([score, text]) + scored.sort_custom(func(a, b): return a[0] > b[0]) + var out := [] + for item in scored: + if not item[1] in out: + out.append(item[1]) + if out.size() >= limit: + break + return out + + +static func type_name(info: Dictionary) -> String: + if info.get("class_name", &"") != &"": + return str(info.class_name) + if info.type == TYPE_NIL: + return "Variant" if info.get("usage", 0) & PROPERTY_USAGE_NIL_IS_VARIANT else "void" + return type_string(info.type) + + +## A method as its class declares it: name(arg: Type = default, ...) -> Return. +static func signature(method: Dictionary) -> String: + var args := [] + var defaults: Array = method.get("default_args", []) + var first_default: int = method.args.size() - defaults.size() + for i in method.args.size(): + var arg: Dictionary = method.args[i] + var text := "%s: %s" % [arg.name, type_name(arg)] + if i >= first_default: + text += " = %s" % var_to_str(defaults[i - first_default]) + args.append(text) + if method.get("flags", 0) & METHOD_FLAG_VARARG: + args.append("...") + var prefix := "static " if method.get("flags", 0) & METHOD_FLAG_STATIC else "" + return "%s%s(%s) -> %s" % [prefix, method.name, ", ".join(args), type_name(method.get("return", {"type": TYPE_NIL}))] + + +static func _class_of(name: String) -> String: + if ClassDB.class_exists(name): + return name + for entry in ProjectSettings.get_global_class_list(): + if entry["class"] == name: + return entry.base + return "" + + +static func _methods(class_name_: String) -> Array: + return ClassDB.class_get_method_list(class_name_) if ClassDB.class_exists(class_name_) else [] + + +static func _method(class_name_: String, name: String) -> Variant: + for method in _methods(class_name_): + if method.name == name: + return method + return null + + +static func _members(class_name_: String) -> Array: + var names := [] + for property in ClassDB.class_get_property_list(class_name_): + var grouping := PROPERTY_USAGE_CATEGORY | PROPERTY_USAGE_GROUP | PROPERTY_USAGE_SUBGROUP + if property.usage & (PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_SCRIPT_VARIABLE) and not (property.usage & grouping): + names.append(property.name) + return names + + +static func _property(class_name_: String, name: String) -> Variant: + for property in ClassDB.class_get_property_list(class_name_): + if property.name == name: + return property + return null + + +static func _signatures(class_name_: String, names: Array) -> String: + var out := [] + for name in names: + var method: Variant = _method(class_name_, name) + if method != null: + out.append(signature(method)) + return "; ".join(out) + + +static func _members_hint(base: String, name: String) -> String: + var klass := _class_of(base) + if klass == "": + return "" + var properties := _closest(name, _members(klass)) + var methods := _closest(name, _methods(klass).map(func(method): return method.name)) + var parts := [] + if properties: + parts.append("closest properties of %s: %s" % [klass, ", ".join(properties)]) + if methods: + parts.append("closest methods: %s" % _signatures(klass, methods.slice(0, 4))) + return ". ".join(parts) + + +static func _signature_hint(base: String, name: String) -> String: + var klass := _class_of(base) + var method: Variant = _method(klass, name) if klass != "" else null + if method != null: + return "%s.%s" % [klass, signature(method)] + # The class is not said (a parse error): every class that declares the method. + var found := [] + for candidate in ClassDB.get_class_list(): + var own: Variant = null + for item in ClassDB.class_get_method_list(candidate, true): + if item.name == name: + own = item + break + if own != null: + found.append("%s.%s" % [candidate, signature(own)]) + if found.size() >= 4: + break + return "; ".join(found) + + +## The node a "Node not found" error was relative to, and the closest children where the path broke. +static func _node_hint(path: String, relative: String) -> String: + var tree := Engine.get_main_loop() as SceneTree + var base: Node = tree.root.get_node_or_null(NodePath(relative)) if tree != null and relative != "" else null + if base == null: + return "" + var node := base + for part in path.split("/", false): + if part == "..": + node = node.get_parent() + elif part != ".": + var next := node.get_node_or_null(NodePath(part)) + if next == null: + var names := node.get_children().map(func(child): return str(child.name)) + var closest := _closest(part, names) + return "No child %s under %s; its children: %s" % [part, node.name, ", ".join(closest if closest else names.slice(0, 12))] + node = next + if node == null: + return "" + return "" + + +static func _identifier_hint(name: String) -> String: + var names := Array(ClassDB.get_class_list()) + Array(Engine.get_singleton_list()) + for type in TYPE_MAX: + names.append(type_string(type)) + for entry in ProjectSettings.get_global_class_list(): + names.append(entry["class"]) + names += ["scene", "PARAMS", "result", "undo_redo", "EditorInterface"] + var closest := _closest(name, names) + return "closest names: %s" % ", ".join(closest) if closest else "" + + +static func _match(pattern: String, text: String) -> RegExMatch: + return RegEx.create_from_string(pattern).search(text) + + +static func explain(message: String, _root: Node, logged: Array) -> String: + var hints := [] + var found: RegExMatch + found = _match("Identifier \"(\\w+)\" not declared", message) + if found: + hints.append(_identifier_hint(found.get_string(1))) + found = _match("(?:assignment of|access to) property or key '([^']+)'(?: with value of type '[^']+')? on a base object of type '([^']+)'", message) + if found: + var property: Variant = _property(_class_of(found.get_string(2)), found.get_string(1)) if _class_of(found.get_string(2)) != "" else null + if property != null: + hints.append("%s.%s is %s" % [found.get_string(2), found.get_string(1), type_name(property)]) + else: + hints.append(_members_hint(found.get_string(2), found.get_string(1))) + found = _match("Nonexistent function '(\\w+)' in base '([^']+)'", message) + if found: + hints.append(_members_hint(found.get_string(2), found.get_string(1))) + found = _match("(?:Cannot find member|Cannot find property) \"(\\w+)\" in base \"([^\"]+)\"", message) + if found: + hints.append(_members_hint(found.get_string(2), found.get_string(1))) + found = _match("Function \"(\\w+)\\(\\)\" not found in base (\\w+)", message) + if found: + # A call of an unknown name on self: a mistyped class, type or function. + hints.append(_identifier_hint(found.get_string(1)) if found.get_string(2) == "self" else _members_hint(found.get_string(2), found.get_string(1))) + found = _match("(?:Invalid call to function|Invalid type in function) '(\\w+)' in base '([^']+)'", message) + if found: + hints.append(_signature_hint(found.get_string(2), found.get_string(1))) + found = _match("(?:Too (?:few|many) arguments for|Invalid argument for) \"(\\w+)\\(\\)\"", message) + if found: + hints.append(_signature_hint("", found.get_string(1))) + for entry in logged: + var text: String = entry.code + " " + entry.rationale + found = _match("Node not found: \"([^\"]+)\" \\(relative to \"([^\"]+)\"\\)", text) + if found: + hints.append(_node_hint(found.get_string(1), found.get_string(2))) + break + var out := [] + for hint in hints: + if hint != "" and not hint in out: + out.append(hint) + return ". ".join(out).left(1500) diff --git a/integrations/godot/host/addons/opencode_link/link.gd b/integrations/godot/host/addons/opencode_link/link.gd new file mode 100644 index 0000000..919de20 --- /dev/null +++ b/integrations/godot/host/addons/opencode_link/link.gd @@ -0,0 +1,451 @@ +@tool +extends RefCounted +## OpenCode Link for Godot: the editor's listener and its requests. +## +## Listens on 127.0.0.1 (a random port, a token kept in memory) and offers this editor's project to the OpenCode +## services every 5 seconds (service.gd), labelled "Godot: — ". Each request is one line of JSON on +## its own connection and thread. hello and status answer on that thread; every other request is queued for the +## editor's main loop (pump(), called by the EditorPlugin each frame), and a request the main loop has not taken +## within 10 s is answered busy, with what runs there and since when. + +const Service := preload("service.gd") +const Runner := preload("runner.gd") + +const PROTOCOL := 1 +const MAX_REQUEST_BYTES := 1024 * 1024 +const QUEUE_WAIT_MS := 10000 +const RUN_LIMIT_MS := 3600 * 1000 +const METHODS := ["hello", "status", "context", "execute_code", "release", "cancel", "resume"] +const MESSAGE_MAX := 2000 + +var plugin: EditorPlugin +var version := "0.0.0" +var script_handle := "" +var offer_key := "" +var token := "" +var port := 0 +var revision := 0 +var quarantine: Variant = null # {cause, release, ...} while a failed change could not be proven undone +var runner: RefCounted + +var _server := TCPServer.new() +var _serving := Thread.new() +var _handlers: Array = [] +var _stopping := false +var _advertiser: RefCounted = null +var _project := "" +var _hello := {} +var _label := "" + +var _mutex := Mutex.new() +var _jobs: Array = [] +var _running: Variant = null # [label, since] +var _cancelled := {} # session_id: true, after a panel's Stop + + +func _init(owner: EditorPlugin) -> void: + plugin = owner + var config := ConfigFile.new() + if config.load(get_script().resource_path.get_base_dir().path_join("plugin.cfg")) == OK: + version = str(config.get_value("plugin", "version", version)) + var crypto := Crypto.new() + token = crypto.generate_random_bytes(32).hex_encode() + script_handle = "godot:%d:%s" % [OS.get_process_id(), crypto.generate_random_bytes(6).hex_encode()] + offer_key = "godot-%d-%s" % [OS.get_process_id(), crypto.generate_random_bytes(8).hex_encode()] + _project = native(ProjectSettings.globalize_path("res://")) + runner = Runner.new(self) + var capabilities := { + "methods": METHODS.duplicate(), "operations": [], "undo": "grouped_best_effort", "background": false, + } + _hello = { + "protocol": PROTOCOL, + "host_version": version, + "app_version": Engine.get_version_info().string, + "capabilities": capabilities, + "capability_hash": JSON.stringify(capabilities, "", true).sha256_text(), + # The folder of this process's crash report (runner.gd's Capture writes it when Godot's crash handler runs). + "process": {"pid": OS.get_process_id(), "temp_dir": native(OS.get_user_data_dir())}, + } + refresh_label() + + +## A path as this computer writes it (Godot's own paths use forward slashes). +static func native(path: String) -> String: + var clean := path.trim_suffix("/") if path.length() > 3 else path + return clean.replace("/", "\\") if OS.get_name() == "Windows" else clean + + +func project_dir() -> String: + return _project + + +func project_name() -> String: + var name := str(ProjectSettings.get_setting("application/config/name", "")) + return name if name.strip_edges() != "" else _project.get_file() + + +static func _clean(text: String) -> String: + var out := "" + for character in text: + var code := character.unicode_at(0) + if code >= 32 and code != 127: + out += "-" if character in ["/", "\\"] else character + return out.strip_edges() + + +func scene_name() -> String: + var root := EditorInterface.get_edited_scene_root() + if root == null: + return "no scene" + return root.scene_file_path.get_file() if root.scene_file_path != "" else "%s (unsaved)" % root.name + + +## The offer's label follows the edited scene (read on the main thread). +func refresh_label() -> void: + var label := ("Godot: %s — %s" % [_clean(project_name()), _clean(scene_name())]).left(120) + _mutex.lock() + _label = label + _mutex.unlock() + + +func bump() -> void: + _mutex.lock() + revision += 1 + _mutex.unlock() + + +func label() -> String: + _mutex.lock() + var value := _label + _mutex.unlock() + return value + + +func start(advertise: bool) -> Error: + var error := _server.listen(0, "127.0.0.1") + if error != OK: + return error + port = _server.get_local_port() + _serving.start(_serve) + if advertise: + _advertiser = Service.new(_snapshot) + _advertiser.start() + return OK + + +func stop() -> void: + _stopping = true + if _advertiser != null: + _advertiser.stop(_project) + _advertiser = null + if _serving.is_started(): + _serving.wait_to_finish() + _server.stop() + for thread in _handlers: + thread.wait_to_finish() + _handlers.clear() + _mutex.lock() + for job in _jobs: + job.result = error("busy", "The Godot editor is closing.") + job.state = "done" + job.done.post() + _jobs.clear() + _mutex.unlock() + token = Crypto.new().generate_random_bytes(32).hex_encode() + runner.close() + + +func info() -> Dictionary: + return {"host": "127.0.0.1", "port": port, "token": token, "protocol": PROTOCOL} + + +func advertising() -> bool: + return _advertiser != null + + +func advertiser_results() -> Array: + return _advertiser.results() if _advertiser != null else [] + + +func _snapshot() -> Dictionary: + return {"port": port, "token": null if _stopping else token, "offers": [[script_handle, label(), offer_key]], "project": _project} + + +static func error(code: String, message: String, data := {}) -> Dictionary: + return {"__host_error": true, "code": code, "message": message.left(MESSAGE_MAX), "data": data} + + +static func is_error(value: Variant) -> bool: + return value is Dictionary and value.get("__host_error") == true + + +# --- the main loop's queue --- + +func running() -> Dictionary: + _mutex.lock() + var now: Variant = _running + var queued := _jobs.size() + _mutex.unlock() + if now == null: + return {"busy": false, "queued": queued} + return {"busy": true, "running": now[0], "seconds": snappedf((Time.get_ticks_msec() - now[1]) / 1000.0, 0.1), "queued": queued} + + +## Called by the EditorPlugin every frame, on the main thread. Never one request inside another. +func pump() -> void: + while true: + _mutex.lock() + if _running != null or _jobs.is_empty(): + _mutex.unlock() + return + var job: Dictionary = _jobs.pop_front() + job.state = "running" + _running = [job.label, Time.get_ticks_msec()] + _mutex.unlock() + var result: Variant = job.work.call() + if result == null: + result = error("internal", "OpenCode Link failed on this request; the editor's Output names the error.") + _mutex.lock() + job.result = result + job.state = "done" + _running = null + _mutex.unlock() + job.done.post() + + +func _on_main(label: String, work: Callable, session_id: String) -> Variant: + var job := {"label": label, "work": work, "state": "queued", "result": null, "done": Semaphore.new(), "session": session_id} + _mutex.lock() + _jobs.append(job) + _mutex.unlock() + var asked := Time.get_ticks_msec() + while true: + _mutex.lock() + var state: String = job.state + if state == "queued" and (Time.get_ticks_msec() - asked > QUEUE_WAIT_MS or _stopping): + _jobs.erase(job) + _mutex.unlock() + var now := running() + var doing: String = ( + "it still runs %s (%s s so far): nothing was done for this request; ask again once it has finished" % [now.running, now.seconds] + if now.busy else "a modal dialog, a long import or a script outside OpenCode holds it" + ) + return error("busy", "Godot's main thread did not take the request within %d s: %s" % [QUEUE_WAIT_MS / 1000, doing], + {"reason": "ui_timeout", "running": now.get("running"), "seconds": now.get("seconds")}) + _mutex.unlock() + if state != "queued": + break + OS.delay_msec(5) + while not job.done.try_wait(): + if Time.get_ticks_msec() - asked > RUN_LIMIT_MS: + return error("busy", "Godot did not finish the request within %d s" % (RUN_LIMIT_MS / 1000)) + OS.delay_msec(5) + return job.result + + +# --- requests --- + +func quick_hello(handle: Variant) -> Variant: + if handle is String and handle != "" and handle != script_handle: + return error("stale_handle", "Unknown or expired script_handle") + var hello := _hello.duplicate(true) + var label := label() + _mutex.lock() + hello.revision = revision + _mutex.unlock() + hello.script_handle = script_handle + hello.document = label.trim_prefix("Godot: ") + return hello + + +func dispatch(method: String, params: Dictionary) -> Variant: + if method == "status": + return running() + if method == "hello": + return quick_hello(params.get("script_handle")) + if not method in METHODS: + return error("method_not_found", "Unknown Godot host method: " + method) + if str(params.get("script_handle", "")) != script_handle: + return error("stale_handle", "Unknown or expired script_handle") + var session := str(params.get("session_id", "")) + if method in ["cancel", "resume"]: + if session == "": + return error("invalid_request", "session_id is required") + _mutex.lock() + if method == "cancel": + _cancelled[session] = true + for job in _jobs.duplicate(): + if job.session == session: + _jobs.erase(job) + job.result = error("busy", "The conversation was stopped before Godot ran this request.", {"reason": "cancelled"}) + job.state = "done" + job.done.post() + else: + _cancelled.erase(session) + _mutex.unlock() + return {"cancelled": method == "cancel"} + var work: Callable + if method == "context": + work = func(): return context(params) + elif method == "execute_code": + work = func(): return runner.execute(params) + else: + work = func(): return runner.release(params) + return _on_main(method, work, session) + + +func scene_root() -> Node: + return EditorInterface.get_edited_scene_root() + + +## A node path as the agent reads it: relative to the scene root ("." for the root itself). +static func path_of(root: Node, node: Node) -> String: + return "." if node == root else str(root.get_path_to(node)) + + +func context(params: Dictionary) -> Dictionary: + var root := scene_root() + var unsaved := Array(EditorInterface.get_unsaved_scenes()) + var out := { + "script_handle": script_handle, + "revision": revision, + "godot": Engine.get_version_info().string, + "executable": OS.get_executable_path(), + "project": { + "name": project_name(), "path": _project, + "main_scene": str(ProjectSettings.get_setting("application/run/main_scene", "")), + }, + "open_scenes": Array(EditorInterface.get_open_scenes()), + "scene": null, + } + if quarantine != null: + out.quarantined = true + out.quarantine = quarantine + if root == null: + return out + out.scene = { + "path": root.scene_file_path, "root": str(root.name), "class": root.get_class(), + "unsaved": root.scene_file_path == "" or root.scene_file_path in unsaved, + } + var selection := [] + for node in EditorInterface.get_selection().get_selected_nodes(): + if node == root or root.is_ancestor_of(node): + selection.append(path_of(root, node)) + out.selection = selection + var start: Node = root + if params.get("node") is String and params.node != "" and params.node != ".": + start = root.get_node_or_null(NodePath(params.node)) + if start == null: + return error("invalid_args", "No node %s in the open scene." % params.node, {"children": _children(root)}) + var limit := clampi(int(params.get("limit", 40)), 0, 500) + var depth := clampi(int(params.get("depth", 3)), 0, 32) + var pattern := str(params.get("match", "")) + var properties: Array = params.get("properties", []) if params.get("properties") is Array else [] + var nodes := [] + var total := 0 + var queue := [[start, 0]] + while not queue.is_empty(): + var item: Array = queue.pop_front() + var node: Node = item[0] + if node != root and node.owner != root: + continue + total += 1 + var picked := pattern == "" or node.name.matchn(pattern) or node.get_class().matchn(pattern) + if picked and nodes.size() < limit: + nodes.append(_card(root, node, properties)) + if item[1] < depth: + for child in node.get_children(): + queue.append([child, item[1] + 1]) + out.nodes = nodes + out.nodes_listed = nodes.size() + out.nodes_seen = total + return out + + +static func _children(node: Node) -> Array: + return node.get_children().map(func(child): return str(child.name)).slice(0, 50) + + +func _card(root: Node, node: Node, properties: Array) -> Dictionary: + var card := {"path": path_of(root, node), "class": node.get_class(), "children": node.get_child_count()} + var script: Variant = node.get_script() + if script is Script: + card.script = script.resource_path + if node != root and node.scene_file_path != "": + card.instance = node.scene_file_path + if properties: + var values := {} + for name in properties: + if name in node: + values[name] = Runner.json_value(node.get(name)) + card.values = values + return card + + +# --- the listener --- + +func _serve() -> void: + while not _stopping: + if _server.is_connection_available(): + var peer := _server.take_connection() + var thread := Thread.new() + _handlers.append(thread) + thread.start(_handle.bind(peer)) + else: + OS.delay_msec(10) + for thread in _handlers.duplicate(): + if not thread.is_alive(): + thread.wait_to_finish() + _handlers.erase(thread) + + +static func _same(a: String, b: String) -> bool: + if a.length() != b.length(): + return false + var difference := 0 + for i in a.length(): + difference |= a.unicode_at(i) ^ b.unicode_at(i) + return difference == 0 + + +func _handle(peer: StreamPeerTCP) -> void: + var buffer := PackedByteArray() + var until := Time.get_ticks_msec() + 130000 + var response := {} + var request_id: Variant = null + while true: + peer.poll() + if peer.get_status() != StreamPeerTCP.STATUS_CONNECTED or Time.get_ticks_msec() > until: + break + var available := peer.get_available_bytes() + if available > 0: + buffer.append_array(peer.get_partial_data(available)[1]) + if buffer.find(10) >= 0 or buffer.size() > MAX_REQUEST_BYTES: + break + else: + OS.delay_msec(2) + var newline := buffer.find(10) + var result: Variant + if newline < 0: + result = error("invalid_request", "Godot host request exceeded the size limit" if buffer.size() > MAX_REQUEST_BYTES else "Incomplete request") + else: + var parser := JSON.new() + if parser.parse(buffer.slice(0, newline).get_string_from_utf8()) != OK or not (parser.data is Dictionary): + result = error("invalid_request", "Malformed request") + else: + var request: Dictionary = parser.data + request_id = request.get("id") + if not _same(str(request.get("token", "")), token): + result = error("unauthorized", "Invalid Godot host token") + else: + var params: Variant = request.get("params") + result = dispatch(str(request.get("method", "")), params if params is Dictionary else {}) + if is_error(result): + var refusal := {"code": result.code, "message": result.message} + if not result.data.is_empty(): + refusal.data = Runner.json_value(result.data) + response = {"id": request_id, "ok": false, "error": refusal} + else: + response = {"id": request_id, "ok": true, "result": Runner.json_value(result)} + peer.put_data((JSON.stringify(response) + "\n").to_utf8_buffer()) + peer.disconnect_from_host() diff --git a/integrations/godot/host/addons/opencode_link/plugin.cfg b/integrations/godot/host/addons/opencode_link/plugin.cfg new file mode 100644 index 0000000..2c462dc --- /dev/null +++ b/integrations/godot/host/addons/opencode_link/plugin.cfg @@ -0,0 +1,7 @@ +[plugin] + +name="OpenCode Link" +description="Offers this project to OpenCode, and the OpenCode dock." +author="NeuralNomads" +version="0.1.0" +script="plugin.gd" diff --git a/integrations/godot/host/addons/opencode_link/plugin.gd b/integrations/godot/host/addons/opencode_link/plugin.gd new file mode 100644 index 0000000..511238b --- /dev/null +++ b/integrations/godot/host/addons/opencode_link/plugin.gd @@ -0,0 +1,48 @@ +@tool +extends EditorPlugin +## OpenCode Link for Godot: offers this editor's project to OpenCode from the editor's start, without any panel, and +## adds the optional OpenCode dock. OPENCODE_GODOT_OFFER=0 in the editor's environment keeps it from offering. + +const Link := preload("link.gd") +const Dock := preload("dock.gd") + +var link: RefCounted +var dock: Control + + +func _enter_tree() -> void: + link = Link.new(self) + var error: Error = link.start(OS.get_environment("OPENCODE_GODOT_OFFER") != "0") + if error != OK: + push_warning("OpenCode Link did not start: %s" % error_string(error)) + link = null + return + get_undo_redo().version_changed.connect(link.bump) + scene_changed.connect(_scene_changed) + scene_saved.connect(_scene_changed) + scene_closed.connect(_scene_changed) + dock = Dock.new() + dock.name = "OpenCode" + dock.link = link + add_control_to_dock(DOCK_SLOT_RIGHT_UL, dock) + + +func _exit_tree() -> void: + if dock != null: + remove_control_from_docks(dock) + dock.queue_free() + dock = null + if link != null: + link.stop() + link = null + + +func _scene_changed(_value: Variant = null) -> void: + if link != null: + link.refresh_label() + link.bump() + + +func _process(_delta: float) -> void: + if link != null: + link.pump() diff --git a/integrations/godot/host/addons/opencode_link/runner.gd b/integrations/godot/host/addons/opencode_link/runner.gd new file mode 100644 index 0000000..4587ef4 --- /dev/null +++ b/integrations/godot/host/addons/opencode_link/runner.gd @@ -0,0 +1,502 @@ +@tool +extends RefCounted +## execute_code and release: GDScript run in the editor on the open scene, as one undo action. +## +## Godot records no undo for a direct change (node.position = ...): the run's changes are read by comparing the scene +## before and after it (the stored properties of every node the scene owns and of its embedded resources, each +## node's parent, position, name and owner). A run that changed the scene becomes one EditorUndoRedoManager action, +## "OpenCode: code", whose undo puts every property, node and position back. A run that fails (a parse or script +## error) is reverted the same way at once and the scene compared with what it was: restored, or quarantined (changes +## refused, reads and read_only runs allowed) until the agent read it and releases it with that read's revision. A +## freed node cannot come back: its deletion is said, and a failed run that freed one is quarantined. +## The run's print() output and the errors Godot logs during it are captured by a Logger (Godot 4.5). + +const Hints := preload("hints.gd") + +const UNDO_STEP := "OpenCode: code" +const OUTPUT_MAX := 64 * 1024 +const LIST_MAX := 40 +const HEADER := "@tool\nextends RefCounted\nvar PARAMS = {}\nvar result = {}\nvar scene: Node\nvar undo_redo: EditorUndoRedoManager\n" +const QUARANTINED := ("A failed change could not be proven undone: changes are refused until you read the scene (godot_context) " + + "and release the quarantine with that read's revision (godot_context release_quarantine).") + + +## The run's output and errors, from Godot's loggers; only the main thread's, only while a run captures. Godot's +## editor writes no log of its own (unless started with --log-file, whose path it does not tell): when its crash +## handler writes "Program crashed", the crash and its backtrace go to crash_file, the crash report hello names. +class Capture extends Logger: + var active := false + var main := 0 + var output := "" + var errors: Array = [] + var crash_file := "" + var _crash: FileAccess = null + # Terminal colours of the editor's own messages. + var _ansi := RegEx.create_from_string(r"\x1b\[[0-9;]*[A-Za-z]") + + func _log_message(message: String, error: bool) -> void: + if error and (_crash != null or message.contains("Program crashed")): + if _crash == null: + # The editor saves through a temporary file renamed on close, which a crash never reaches: the file is + # created first, then written in place. + var created := FileAccess.open(crash_file, FileAccess.WRITE) + if created != null: + created.close() + _crash = FileAccess.open(crash_file, FileAccess.READ_WRITE) + if _crash != null: + _crash.store_string(message) + _crash.flush() + return + if active and OS.get_thread_caller_id() == main and output.length() < OUTPUT_MAX * 2: + output += _ansi.sub(message, "", true) + + func _log_error(function: String, file: String, line: int, code: String, rationale: String, _notify: bool, type: int, backtraces: Array) -> void: + if not active or OS.get_thread_caller_id() != main or errors.size() >= 200: + return + var frames := [] + for backtrace in backtraces: + for i in backtrace.get_frame_count(): + frames.append({"function": backtrace.get_frame_function(i), "file": backtrace.get_frame_file(i), "line": backtrace.get_frame_line(i)}) + errors.append({"function": function, "file": file, "line": line, "code": code, "rationale": rationale, "type": type, "frames": frames}) + + +var link: RefCounted +var capture := Capture.new() +# The control characters JSON may not carry raw (Godot's JSON leaves them as they are). +static var CONTROL := RegEx.create_from_string(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]") + + +func _init(owner: RefCounted) -> void: + link = owner + capture.main = OS.get_thread_caller_id() + DirAccess.make_dir_recursive_absolute(OS.get_user_data_dir()) + capture.crash_file = OS.get_user_data_dir().path_join("opencode-crash-%d.log" % OS.get_process_id()) + OS.add_logger(capture) + + +func close() -> void: + OS.remove_logger(capture) + + +# --- JSON values --- + +static func json_value(value: Variant, depth := 0) -> Variant: + if depth > 32: + return str(value) + match typeof(value): + TYPE_NIL, TYPE_BOOL, TYPE_INT: + return value + TYPE_STRING: + return CONTROL.sub(value, "", true) + TYPE_FLOAT: + if is_nan(value): + return "NaN" + if is_inf(value): + return "Infinity" if value > 0 else "-Infinity" + return value + TYPE_STRING_NAME, TYPE_NODE_PATH: + return str(value) + TYPE_VECTOR2, TYPE_VECTOR2I, TYPE_VECTOR3, TYPE_VECTOR3I, TYPE_VECTOR4, TYPE_VECTOR4I, TYPE_QUATERNION: + var items := [] + for i in {TYPE_VECTOR2: 2, TYPE_VECTOR2I: 2, TYPE_VECTOR3: 3, TYPE_VECTOR3I: 3}.get(typeof(value), 4): + items.append(json_value(value[i], depth + 1)) + return items + TYPE_COLOR: + return [value.r, value.g, value.b, value.a] + TYPE_RECT2, TYPE_RECT2I, TYPE_AABB: + return {"position": json_value(value.position, depth + 1), "size": json_value(value.size, depth + 1)} + TYPE_BASIS: + return [json_value(value.x, depth + 1), json_value(value.y, depth + 1), json_value(value.z, depth + 1)] + TYPE_TRANSFORM2D: + return {"x": json_value(value.x), "y": json_value(value.y), "origin": json_value(value.origin)} + TYPE_TRANSFORM3D: + return {"basis": json_value(value.basis, depth + 1), "origin": json_value(value.origin, depth + 1)} + TYPE_PLANE: + return {"normal": json_value(value.normal), "d": value.d} + TYPE_OBJECT: + if value == null or not is_instance_valid(value): + return null + if value is Node: + var root := EditorInterface.get_edited_scene_root() if Engine.is_editor_hint() else null + if root != null and (value == root or root.is_ancestor_of(value)): + return {"node": "." if value == root else str(root.get_path_to(value)), "class": value.get_class()} + return {"node": str(value.get_path()) if value.is_inside_tree() else str(value.name), "class": value.get_class()} + if value is Resource: + return {"resource": value.resource_path, "class": value.get_class()} if value.resource_path != "" else {"resource": null, "class": value.get_class()} + return {"object": value.get_class()} + TYPE_DICTIONARY: + var out := {} + for key in value: + out[str(key)] = json_value(value[key], depth + 1) + return out + TYPE_ARRAY, TYPE_PACKED_BYTE_ARRAY, TYPE_PACKED_INT32_ARRAY, TYPE_PACKED_INT64_ARRAY, TYPE_PACKED_FLOAT32_ARRAY, \ + TYPE_PACKED_FLOAT64_ARRAY, TYPE_PACKED_STRING_ARRAY, TYPE_PACKED_VECTOR2_ARRAY, TYPE_PACKED_VECTOR3_ARRAY, \ + TYPE_PACKED_COLOR_ARRAY, TYPE_PACKED_VECTOR4_ARRAY: + var items := [] + for i in mini(value.size(), 10000): + items.append(json_value(value[i], depth + 1)) + return items + return str(value) + + +# --- the scene before and after a run --- + +static func _local(resource: Resource) -> bool: + return resource.resource_path == "" or resource.resource_path.contains("::") + + +static func _copy(value: Variant) -> Variant: + return value.duplicate(true) if value is Array or value is Dictionary else value + + +static func _same(a: Variant, b: Variant) -> bool: + return typeof(a) == typeof(b) and (a == b or (a is float and is_nan(a) and is_nan(b))) + + +## The stored properties of an object; its embedded resources go to `resources`, each once. +static func _props(object: Object, resources: Dictionary) -> Dictionary: + var props := {} + for property in object.get_property_list(): + if not property.usage & PROPERTY_USAGE_STORAGE: + continue + var value: Variant = object.get(property.name) + props[property.name] = _copy(value) + if value is Resource and _local(value) and not resources.has(value.get_instance_id()): + resources[value.get_instance_id()] = {"object": value, "props": {}} + resources[value.get_instance_id()].props = _props(value, resources) + return props + + +## The scene's own nodes: the root and every descendant it owns, or that has no owner (added without one); the +## inside of an instanced scene belongs to that scene. +static func _members(root: Node) -> Array: + var out := [root] + var stack := [root] + while not stack.is_empty(): + var node: Node = stack.pop_back() + for child in node.get_children(): + if child.owner == root or child.owner == null: + out.append(child) + stack.append(child) + elif root.is_ancestor_of(child.owner) or child.owner == root: + stack.append(child) + return out + + +static func snapshot(root: Node) -> Dictionary: + var nodes := {} + var resources := {} + for node in _members(root): + nodes[node.get_instance_id()] = { + "node": node, "path": "." if node == root else str(root.get_path_to(node)), + "parent": node.get_parent() if node != root else null, "index": node.get_index(), "name": str(node.name), + "owner": node.owner, "props": _props(node, resources), + } + return {"nodes": nodes, "resources": resources} + + +static func _in_scene(root: Node, node: Variant) -> bool: + return is_instance_valid(node) and (node == root or root.is_ancestor_of(node)) + + +## What the run changed, as the undo action's operations ([object, kind, name, args]) and in words. +static func diff(root: Node, before: Dictionary) -> Dictionary: + var after := snapshot(root) + var do_ops := [] + var undo_ops := [] + var refs := {"do": [], "undo": []} + var said := {"properties": 0, "added": [], "removed": [], "moved": [], "renamed": [], "freed": []} + var properties := func(object: Object, old: Dictionary, new: Dictionary): + for name in new: + if old.has(name) and not _same(old[name], new[name]): + do_ops.append([object, "property", name, new[name]]) + undo_ops.append([object, "property", name, old[name]]) + said.properties += 1 + for id in before.nodes: + var was: Dictionary = before.nodes[id] + var node: Variant = was.node + if not is_instance_valid(node) or node.is_queued_for_deletion(): + said.freed.append(was.path) + continue + if not _in_scene(root, node): + # Removed from the scene: put back by the undo; only its topmost node moves. + var parent_id: int = was.parent.get_instance_id() if is_instance_valid(was.parent) else 0 + var topmost: bool = parent_id == 0 or not before.nodes.has(parent_id) or _in_scene(root, before.nodes[parent_id].node) + if topmost and is_instance_valid(was.parent): + do_ops.append([was.parent, "method", "remove_child", [node]]) + undo_ops.append([was.parent, "method", "add_child", [node, true]]) + undo_ops.append([was.parent, "method", "move_child", [node, was.index]]) + refs.undo.append(node) + said.removed.append(was.path) + if was.owner == root: + undo_ops.append([node, "property", "owner", root]) + properties.call(node, was.props, _props(node, {})) + continue + var now: Dictionary = after.nodes.get(id, {}) + if now.is_empty(): + continue + if now.parent != was.parent: + do_ops.append([node, "method", "reparent", [now.parent, false]]) + do_ops.append([now.parent, "method", "move_child", [node, now.index]]) + undo_ops.append([node, "method", "reparent", [was.parent, false]]) + undo_ops.append([was.parent, "method", "move_child", [node, was.index]]) + said.moved.append(was.path) + elif now.index != was.index: + do_ops.append([now.parent, "method", "move_child", [node, now.index]]) + undo_ops.append([was.parent, "method", "move_child", [node, was.index]]) + said.moved.append(was.path) + if now.name != was.name: + do_ops.append([node, "property", "name", now.name]) + undo_ops.append([node, "property", "name", was.name]) + said.renamed.append("%s -> %s" % [was.path, now.name]) + if now.owner != was.owner or now.parent != was.parent: + do_ops.append([node, "property", "owner", now.owner]) + undo_ops.append([node, "property", "owner", was.owner]) + properties.call(node, was.props, now.props) + for id in before.resources: + var was: Dictionary = before.resources[id] + if is_instance_valid(was.object): + properties.call(was.object, was.props, after.resources[id].props if after.resources.has(id) else _props(was.object, {})) + # Added nodes: the topmost ones go back in by the redo, before the moves and properties that may name them. + var adds := [] + var owners := [] + for id in after.nodes: + if before.nodes.has(id): + continue + var now: Dictionary = after.nodes[id] + if now.owner == root: + owners.append([now.node, "property", "owner", root]) + if after.nodes.has(now.parent.get_instance_id()) and not before.nodes.has(now.parent.get_instance_id()): + continue + adds.append([now.parent, "method", "add_child", [now.node, true]]) + adds.append([now.parent, "method", "move_child", [now.node, now.index]]) + undo_ops.append([now.parent, "method", "remove_child", [now.node]]) + refs.do.append(now.node) + said.added.append(now.path) + do_ops = adds + do_ops + owners + var unowned := [] + for id in after.nodes: + if after.nodes[id].owner == null and after.nodes[id].node != root: + unowned.append(after.nodes[id].path) + return {"do": do_ops, "undo": undo_ops, "refs": refs, "said": said, "unowned": unowned, "added_nodes": refs.do} + + +static func changed(changes: Dictionary) -> bool: + var said: Dictionary = changes.said + return said.properties > 0 or not (said.added.is_empty() and said.removed.is_empty() and said.moved.is_empty() + and said.renamed.is_empty() and said.freed.is_empty()) + + +static func _apply(op: Array) -> void: + if not is_instance_valid(op[0]): + return + if op[1] == "property": + op[0].set(op[2], op[3]) + else: + op[0].callv(op[2], op[3]) + + +## Puts the scene back as it was before the run (a failed run): the undo operations, at once; nodes the run added are +## freed. Then the scene is compared with the snapshot taken before. +static func revert(root: Node, before: Dictionary, changes: Dictionary) -> bool: + for op in changes.undo: + _apply(op) + for node in changes.added_nodes: + if is_instance_valid(node) and not node.is_inside_tree(): + node.queue_free() + if not changes.said.freed.is_empty(): + return false + var now := snapshot(root) + if now.nodes.keys().size() != before.nodes.keys().size(): + return false + for id in before.nodes: + var was: Dictionary = before.nodes[id] + var is_now: Dictionary = now.nodes.get(id, {}) + if is_now.is_empty() or is_now.parent != was.parent or is_now.index != was.index or is_now.name != was.name or is_now.owner != was.owner: + return false + for name in was.props: + if not _same(was.props[name], is_now.props.get(name)): + return false + for id in before.resources: + var was: Dictionary = before.resources[id] + var props: Dictionary = _props(was.object, {}) if is_instance_valid(was.object) else {} + for name in was.props: + if not _same(was.props[name], props.get(name)): + return false + return true + + +func _commit(root: Node, changes: Dictionary) -> void: + var undo: EditorUndoRedoManager = EditorInterface.get_editor_undo_redo() + undo.create_action(UNDO_STEP, UndoRedo.MERGE_DISABLE, root) + for op in changes.do: + if op[1] == "property": + undo.add_do_property(op[0], op[2], op[3]) + else: + undo.callv("add_do_method", [op[0], op[2]] + op[3]) + for op in changes.undo: + if op[1] == "property": + undo.add_undo_property(op[0], op[2], op[3]) + else: + undo.callv("add_undo_method", [op[0], op[2]] + op[3]) + for node in changes.refs.do: + undo.add_do_reference(node) + for node in changes.refs.undo: + undo.add_undo_reference(node) + undo.commit_action(false) + + +# --- the run --- + +static func _indent(code: String) -> String: + var unit := "\t" + for line in code.split("\n"): + if line.begins_with(" "): + unit = " " + break + if line.begins_with("\t"): + break + var out := PackedStringArray() + for line in code.split("\n"): + out.append(unit + line) + return "\n".join(out) + "\n" + unit + "pass\n" + + +## The script to compile: a body of statements becomes func run(); a script that has its own func run() (and helpers) +## is kept as it is. +static func source_of(code: String) -> Dictionary: + var script_mode := RegEx.create_from_string("(?m)^func run\\(").search(code) != null + if script_mode: + return {"source": HEADER + code + "\n", "offset": HEADER.count("\n")} + return {"source": HEADER + "func run():\n" + _indent(code), "offset": HEADER.count("\n") + 1} + + +func _failure(error: Dictionary, offset: int, file: String) -> Dictionary: + var line := int(error.line) - offset if error.file == file else -1 + for frame in error.frames: + if frame.file == file: + line = int(frame.line) - offset + break + var out := {"message": (error.code + (" " + error.rationale if error.rationale != "" else "")).left(2000)} + if line > 0: + out.line = line + var frames := [] + for frame in error.frames: + frames.append("%s (%s:%d)" % [frame.function, "" if frame.file == file else frame.file, int(frame.line) - offset if frame.file == file else int(frame.line)]) + if frames: + out.traceback = "\n".join(frames.slice(0, 20)) + return out + + +func execute(params: Dictionary) -> Dictionary: + var code: Variant = params.get("code") + if not (code is String) or code.strip_edges() == "": + return link.error("invalid_request", "code is required") + var read_only: bool = params.get("read_only") == true + if link.quarantine != null and not read_only: + return link.error("quarantined", QUARANTINED, {"reason": "script_quarantined", "quarantine": link.quarantine}) + var root: Node = link.scene_root() + var built := source_of(code) + var script := GDScript.new() + script.source_code = built.source + var file := "gdscript://%d.gd" % script.get_instance_id() + var revision_before: int = link.revision + capture.output = "" + capture.errors = [] + capture.active = true + var compiled := script.reload() + capture.active = false + var base := {"script_handle": link.script_handle, "revision_before": revision_before} + if compiled != OK: + var parse: Dictionary = capture.errors[0] if capture.errors else {"code": "The code does not compile (error %d)." % compiled, "file": file, "line": 0, "rationale": "", "frames": []} + var failed := _failure(parse, built.offset, file) + var hint: String = Hints.explain(failed.message, root, capture.errors) + return base.merged({"status": "failed", "result": {}, "stdout": "", "changed": false, "revision_after": link.revision}).merged(failed).merged({"hint": hint} if hint != "" else {}) + var before: Variant = snapshot(root) if root != null and not read_only else null + var instance: Object = script.new() + instance.set("PARAMS", params.get("params", {}) if params.get("params") is Dictionary else {}) + instance.set("scene", root) + instance.set("undo_redo", EditorInterface.get_editor_undo_redo()) + capture.output = "" + capture.errors = [] + capture.active = true + var returned: Variant = instance.call("run") + capture.active = false + var output := capture.output + var logged: Array = capture.errors + var script_error: Variant = null + for entry in logged: + if entry.type == Logger.ERROR_TYPE_SCRIPT: + script_error = entry + break + if script_error == null and returned is Object and is_instance_valid(returned) and returned.get_class() == "GDScriptFunctionState": + script_error = {"code": "await is not supported: the run ended at its first await, and the rest runs later outside OpenCode.", "file": "", "line": 0, "rationale": "", "frames": []} + var out := base.merged({ + "status": "failed" if script_error != null else "executed", + "result": json_value(instance.get("result")), + "stdout": output.left(OUTPUT_MAX), + "truncated": output.length() > OUTPUT_MAX, + }) + var notes := [] + for entry in logged: + if entry != script_error and entry.type != Logger.ERROR_TYPE_SCRIPT and notes.size() < 20: + notes.append(("%s: %s" % ["WARNING" if entry.type == Logger.ERROR_TYPE_WARNING else "ERROR", entry.code + (" " + entry.rationale if entry.rationale != "" else "")]).left(500)) + if notes: + out.errors = notes + if before != null and is_instance_valid(root): + var changes := diff(root, before) + var did := changed(changes) + out.changed = did + if did: + out.changes = _words(changes.said) + if script_error != null: + if did: + var restored := revert(root, before, changes) + out.restored = restored + if not restored: + link.quarantine = { + "cause": ("failed code: " + script_error.code).left(200), + "release": "read the scene (godot_context), check what may have changed, then release the quarantine with that read's revision", + } + if not changes.said.freed.is_empty(): + link.quarantine.freed = changes.said.freed.slice(0, LIST_MAX) + out.quarantine = link.quarantine + link.bump() + elif did: + _commit(root, changes) + out.undo_step = UNDO_STEP + if not changes.said.freed.is_empty(): + out.not_undoable = "Ctrl+Z cannot bring back a freed node (free, queue_free): %s. Remove a node with remove_child to keep it undoable." % ", ".join(changes.said.freed.slice(0, LIST_MAX)) + if not changes.unowned.is_empty(): + out.unowned = "Added without an owner, so not saved with the scene: %s. Set node.owner = scene on each." % ", ".join(changes.unowned.slice(0, LIST_MAX)) + else: + out.changed = false + if script_error != null: + var failed := _failure(script_error, built.offset, file) + out.merge(failed) + var hint: String = Hints.explain(failed.message, root, logged) + if hint != "": + out.hint = hint + out.revision_after = link.revision + return out + + +static func _words(said: Dictionary) -> Dictionary: + var out := {} + if said.properties: + out.properties = said.properties + for key in ["added", "removed", "moved", "renamed", "freed"]: + if not said[key].is_empty(): + out[key] = said[key].slice(0, LIST_MAX) + return out + + +func release(params: Dictionary) -> Dictionary: + if link.quarantine == null: + return {"released": false, "revision": link.revision} + var revision: Variant = params.get("revision") + if not (revision is float or revision is int) or int(revision) != link.revision: + return link.error("stale_revision", "Read the scene again (godot_context) and release with its revision.", + {"reason": "revision_conflict", "current_revision": link.revision}) + link.quarantine = null + return {"released": true, "revision": link.revision} diff --git a/integrations/godot/host/addons/opencode_link/service.gd b/integrations/godot/host/addons/opencode_link/service.gd new file mode 100644 index 0000000..b76fa3d --- /dev/null +++ b/integrations/godot/host/addons/opencode_link/service.gd @@ -0,0 +1,312 @@ +@tool +extends RefCounted +## The OpenCode services of this computer, and the offer of this editor to them (a GDScript port of the kit's +## opencode_service.py and of the other hosts' advertisers; Godot runs no Python). +## +## Discovery reads the registrations under $XDG_STATE_HOME/opencode (default ~/.local/state/opencode): service.json +## and service-.json. A registration counts when its URL is loopback and /api/info answers its pid and version. +## Requests never use a proxy and never follow a redirect. advertise and withdraw go to the global configuration +## Location ($XDG_CONFIG_HOME/opencode, default ~/.config/opencode), then to this project's folder when the plugin is +## not loaded there (a plugin declared in the project's own opencode.json). Every call runs off the main thread; +## nothing here logs the password or the token. + +const RPC_ID := "neuralnomads.godot" +const PROTOCOL := 1 +const TIMEOUT_MS := 3000 +# One renewal may wait this long for a busy service: an offer lasts 15 s, renewed every 5 s. +const RENEW_TIMEOUT_MS := 8000 +const RENEW_MS := 5000 +# Renewals go straight to the services that took the offer; every this many renewals (or after a failure) the +# services are discovered again, which finds a service started since. +const DISCOVER_EVERY := 12 +const OUTCOMES := {"advertise": ["accepted", "renewed", "refused"], "withdraw": ["withdrawn", "none"]} + +var _snapshot: Callable # () -> {port, token, offers: [[script_handle, label, offer_key]], project} +var _thread := Thread.new() +var _stop := false +var _mutex := Mutex.new() +var _results: Array = [] +var _count := 0 +var _targets := {} # service file: [service, directory] +var _offered := {} # offer_key: token + + +func _init(snapshot: Callable) -> void: + _snapshot = snapshot + + +static func _home() -> String: + # The daemon resolves its home like Node's os.homedir(): USERPROFILE on Windows, HOME elsewhere. + var names := ["USERPROFILE", "HOME"] if OS.get_name() == "Windows" else ["HOME"] + for name in names: + if OS.get_environment(name) != "": + return OS.get_environment(name) + return "" + + +static func _join(base: String, parts: Array) -> String: + var separator := "\\" if OS.get_name() == "Windows" else "/" + var path := base + for part in parts: + path = path.trim_suffix(separator) + separator + part + return path + + +static func state_dir() -> String: + var base := OS.get_environment("XDG_STATE_HOME") + return _join(base if base != "" else _join(_home(), [".local", "state"]), ["opencode"]) + + +static func config_dir() -> String: + var base := OS.get_environment("XDG_CONFIG_HOME") + return _join(base if base != "" else _join(_home(), [".config"]), ["opencode"]) + + +## The global configuration directory, then the project's folder. +static func location_candidates(project: String) -> Array: + var candidates := [config_dir()] + if project != "" and project.to_lower().replace("\\", "/") != candidates[0].to_lower().replace("\\", "/"): + candidates.append(project) + return candidates + + +static func _parse_url(url: String) -> Dictionary: + var found := RegEx.create_from_string("^http://(127\\.0\\.0\\.1|\\[::1\\])(?::(\\d{1,5}))?(/[^?#]*)?$").search(url) + if found == null: + return {} + var host := found.get_string(1) + return { + "host": "::1" if host == "[::1]" else host, + "port": int(found.get_string(2)) if found.get_string(2) != "" else 80, + "path": found.get_string(3).trim_suffix("/"), + } + + +static func _json(text: String) -> Variant: + var parser := JSON.new() + return parser.data if text != "" and parser.parse(text) == OK else null + + +## [status, body] of one request; status -1 when the service is unreachable or does not speak HTTP. +static func request(url: String, path: String, password: Variant, body: Variant, timeout_ms: int) -> Array: + var target := _parse_url(url) + if target.is_empty(): + return [-1, null] + var deadline := Time.get_ticks_msec() + timeout_ms + var client := HTTPClient.new() + if client.connect_to_host(target.host, target.port) != OK: + return [-1, null] + while client.get_status() in [HTTPClient.STATUS_RESOLVING, HTTPClient.STATUS_CONNECTING]: + client.poll() + if Time.get_ticks_msec() > deadline: + client.close() + return [-1, null] + OS.delay_msec(2) + if client.get_status() != HTTPClient.STATUS_CONNECTED: + client.close() + return [-1, null] + var headers := PackedStringArray(["content-type: application/json", "accept: application/json"]) + if password is String: + headers.append("authorization: Basic " + Marshalls.utf8_to_base64("opencode:" + password)) + var method := HTTPClient.METHOD_GET if body == null else HTTPClient.METHOD_POST + if client.request(method, target.path + path, headers, "" if body == null else JSON.stringify(body)) != OK: + client.close() + return [-1, null] + while client.get_status() == HTTPClient.STATUS_REQUESTING: + client.poll() + if Time.get_ticks_msec() > deadline: + client.close() + return [-1, null] + OS.delay_msec(2) + if not client.has_response(): + client.close() + return [-1, null] + var code := client.get_response_code() + var bytes := PackedByteArray() + while client.get_status() == HTTPClient.STATUS_BODY: + client.poll() + var chunk := client.read_response_body_chunk() + if chunk.is_empty(): + OS.delay_msec(1) + else: + bytes.append_array(chunk) + if Time.get_ticks_msec() > deadline or bytes.size() > 4 * 1024 * 1024: + client.close() + return [-1, null] + client.close() + return [code, _json(bytes.get_string_from_utf8())] + + +## Healthy registered services: [{file, url, version, password}]. +static func discover(timeout_ms := TIMEOUT_MS) -> Array: + var directory := state_dir() + if not DirAccess.dir_exists_absolute(directory): + return [] + var names := DirAccess.get_files_at(directory) + var pattern := RegEx.create_from_string("^service(-[A-Za-z0-9._-]{1,64})?\\.json$") + var found := [] + var sorted := Array(names) + sorted.sort() + for name in sorted: + if pattern.search(name) == null: + continue + var info: Variant = _json(FileAccess.get_file_as_string(directory.path_join(name))) + if not (info is Dictionary) or not (info.get("url") is String) or not (info.get("pid") is float): + continue + if _parse_url(info.url.rstrip("/")).is_empty() or not (info.get("version") is String): + continue + var password: Variant = info.password if info.get("password") is String else null + var answer := request(info.url, "/api/info", password, null, timeout_ms) + var body: Variant = answer[1] + if answer[0] != 200 or not (body is Dictionary) or not (body.get("pid") is float): + continue + if int(body.pid) != int(info.pid) or body.get("version") != info.version: + continue + found.append({"file": name, "url": info.url, "version": info.version, "password": password}) + return found + + +static func call_rpc(service: Dictionary, method: String, payload: Dictionary, directory: String, timeout_ms: int) -> Array: + var path := "/api/rpc/%s/%s?%s=%s" % [ + RPC_ID.uri_encode(), method.uri_encode(), "location[directory]".uri_encode(), directory.uri_encode() + ] + return request(service.url, path, service.password, {"input": payload}, timeout_ms) + + +static func unavailable(status: int, body: Variant) -> bool: + return status == 404 or (body is Dictionary and body.get("type") in ["rpc.unavailable", "rpc.method_not_found"]) + + +static func outcome(method: String, status: int, body: Variant) -> String: + var output: Variant = body.get("output") if body is Dictionary else null + var value: Variant = output.get("outcome") if output is Dictionary else null + return value if status == 200 and value in OUTCOMES[method] else "error" + + +## A cold Location registers its plugins asynchronously: only the payload-free status read is repeated, never an +## advertisement or a withdrawal. +static func ready(service: Dictionary, directory: String, deadline: int) -> Array: + while true: + var remaining := deadline - Time.get_ticks_msec() + if remaining <= 0: + return [400, {"_tag": "RpcError", "type": "rpc.unavailable"}] + var answer := call_rpc(service, "status", {}, directory, remaining) + var body: Variant = answer[1] + var loading: bool = (answer[0] in [400, 404] and body is Dictionary and body.get("_tag") == "RpcError" + and body.get("type") == "rpc.unavailable") + if not loading: + return answer + OS.delay_msec(50) + return [] + + +## Withdraws one offer from every service, at the first Location that has the plugin. +static func withdraw_all(offer_key: String, token: String, project: String) -> void: + for service in discover(): + for directory in location_candidates(project): + var answer := ready(service, directory, Time.get_ticks_msec() + TIMEOUT_MS) + if unavailable(answer[0], answer[1]): + continue + if answer[0] == 200: + call_rpc(service, "withdraw", {"offer_key": offer_key, "token": token}, directory, TIMEOUT_MS) + break + + +func start() -> void: + _thread.start(_loop) + + +func results() -> Array: + _mutex.lock() + var copy := _results.duplicate(true) + _mutex.unlock() + return copy + + +func advertise_once() -> Variant: + var now: Dictionary = _snapshot.call() + if now.get("token") == null: + return null + var offers := [] + for item in now.offers: + offers.append({ + "host": "127.0.0.1", "port": now.port, "token": now.token, "script_handle": item[0], "label": item[1], + "protocol": PROTOCOL, "offer_key": item[2], + }) + var keys := offers.map(func(offer): return offer.offer_key) + for key in _offered.keys(): + if not key in keys: + withdraw_all(key, _offered[key], now.project) + _offered.erase(key) + var results := _renew(offers, now.project) if offers else [] + for offer in offers: + _offered[offer.offer_key] = offer.token + _mutex.lock() + _results = results + _mutex.unlock() + return results + + +func _renew(offers: Array, project: String) -> Array: + _count += 1 + var results := [] + if not _targets.is_empty() and _count % DISCOVER_EVERY != 0: + var failed := false + for name in _targets: + 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"] + if not failed: + return results + var found := {} + results = [] + for service in discover(RENEW_TIMEOUT_MS): + var reached := false + for directory in location_candidates(project): + var deadline := Time.get_ticks_msec() + RENEW_TIMEOUT_MS + var answer := ready(service, directory, deadline) + if unavailable(answer[0], answer[1]): + continue + reached = true + var taken := false + for offer in offers: + var said := "error" + 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"] + if taken: + found[service.file] = [service, directory] + break + if not reached: + results.append({"service": service.file, "outcome": "unavailable"}) + _targets = found + return results + + +func _loop() -> void: + while not _stop: + var results: Variant = advertise_once() + var taken: bool = results is Array and not results.is_empty() + if taken: + for result in results: + taken = taken and result.get("outcome") in ["accepted", "renewed"] + # A renewal that failed is tried again soon: an offer lasts 15 s from the last one taken. + var wait := RENEW_MS if taken else 1000 + var until := Time.get_ticks_msec() + wait + while not _stop and Time.get_ticks_msec() < until: + OS.delay_msec(50) + + +## Stops renewing; withdraws every offer with the token it was announced with. +func stop(project: String) -> void: + _stop = true + if _thread.is_started(): + _thread.wait_to_finish() + for key in _offered.keys(): + withdraw_all(key, _offered[key], project) + _offered = {} diff --git a/integrations/godot/plugin/LICENSE b/integrations/godot/plugin/LICENSE new file mode 100644 index 0000000..64cabb5 --- /dev/null +++ b/integrations/godot/plugin/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Neural Nomads + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/integrations/godot/plugin/README.md b/integrations/godot/plugin/README.md new file mode 100644 index 0000000..123183c --- /dev/null +++ b/integrations/godot/plugin/README.md @@ -0,0 +1,40 @@ +# 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. + +## Install + +Add this entry to the `plugins` array in OpenCode's global `opencode.json(c)` after the package is published: + +```json +{ "package": "@neuralnomads/opencode-godot@^0.1" } +``` + +To try an unpublished build, run `npm ci` and `npm run build --workspace @neuralnomads/opencode-godot` from its checkout. Instead of the npm name, set `package` to the absolute path of `integrations/godot/plugin` (use forward slashes in JSON on Windows). + +With the Godot editor closed, call `godot_install_host` from a conversation in the project folder, or pass `project` as the absolute path to the folder containing `project.godot`. Accept the installation permission. Godot reads enabled editor plugins from each project's settings; there is no global editor-plugin installation. Open the project: the add-on is now enabled and advertises the editor without opening the dock. To remove it, disable **OpenCode Link** under **Project → Project Settings → Plugins**, then delete `addons/opencode_link`. + +## Use + +`godot_hosts` lists editors (`Godot: — `). The first tool call can attach the only compatible unheld editor. Otherwise pass its `offerID` to `godot_hosts attach`. Tools address the edited scene of that editor; other scene tabs are listed by `godot_context`. + +| Tool | Purpose | +| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `godot_context` | Read the project, scene, selection, nodes and revision. | +| `godot_inspect` | Query the running editor's ClassDB, a live node or the scene tree. | +| `godot_execute_code` | Run a GDScript body or `func run()` in the editor. Assign data to `result`; `scene` is the edited root. Requires permission. | +| `godot_verify` | Compare measured values, e.g. `{"expr":"node(\"Player\").position.x","op":">","value":0}`. `saved: true` reads the file in a separate headless Godot; `frames` runs the scene before measuring. Expressions and background execution require permission. | +| `godot_save` | Save the edited scene or a copy. | +| `godot_run` | Run a scene or `scene: "main"` as a background task. Query or cancel by `task`. `capture: true` uses Movie Maker with a separate rendering window; use a suitable display session. | + +Edits to scene-owned nodes and stored properties are grouped into one undo action when they can be recorded. To delete a node undoably, detach it with `remove_child`, not `free` or `queue_free`. Failed runs attempt to restore the scene and quarantine it if that cannot be proven. Read the scene with `godot_context`, inspect the changes, then pass its revision as `release_quarantine`. This is not a sandbox or a transaction over disk writes, external resources, engine side effects or asynchronous code. Do not use `await` in editor runs. + +## 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. + +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. + +## Tests + +Run `node --test integrations/godot/test/*.test.ts` from the repository root. Set `GODOT_TEST_BIN` to a Godot 4.7 editor executable (the console binary on Windows) to also run the real headless tests with private settings and a test service. CI pins Godot 4.7.2. diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip new file mode 100644 index 0000000000000000000000000000000000000000..9b5109bb0aeba5423ca0cb01c917d41a8a4a67cb GIT binary patch literal 179665 zcmc${%X6Gbk|$Pc(`H)2Ot&@dL67|^Yic^t1tuT$=x$WAI3S3s!ZZnB0I+ImKz3FF znEhi)lDazbd}6>(OCzX?mEeA?`tLvNxDq45!oKcvKCi)ziUbaQvz|oAgGrL4U0}oeT!m__R8C+MApW z)~eaK>WyAimxIX^4aUc_-f%P=omIW+1S74W=IklDnT}6qFM5*!D)+12bUHp6_RwF| zAD>)Z3`VowjN_dS&j-`0J$pK+S_j^uwW>k-gWmbdaD?6lReY*m3};WrSF>s|n9e4{ z6ZWxI4M!*ESAD_|pU;OELmz?7HT~%dAitVo28461x)}F|r~G%IXU zFeH$I8vQX)rV)P{oXl84$WO=T=i?Wg+R1p-A9B9a^_7)FeCi#KpAR$_Tiwxk22h1= zEr5WqRrOEPr@iy@>UiJ?!?-{%iqdp2yQ|~r3=2O5d0dVs8m~Fc4#xj>t2)^I`tbXW z{jF;IpxWEt{cijI*8Qrrae&{gwd(ur!*6#V9agBZzp-=pL$&*LwXyR<_51Ce`)k$K zKkV&q9UN4<`zzZI_a1C-p=^6+^TDJ0+dJP>_t0)<7bLt5LPn>DyA=oYuC}+(?(6E| z*8b+V=y~Jb_Ji%iAJ$gB-ag!6pI`6pR~yyd#{S{<=A#E2`_EZ@xXOzTJIre+z~8 z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tMu|D^ zL41&V1jB5I(I!YF#T2Tg$C(-S#xs`)^pUKzcBWZ8X$QPg1bkc*R3+;$96|Y?939*l z;C6z|;x5bpxNr@oK@3c4cX*(b&4SC?DRFbOh%_o4YEm1Q)<40LMB>g`pXn87@g!$B zZl2_Rso{zb?LaSVaC(y51yEg8r#^r~a?X+?GV&uM^jeTx#OxiOjlATAN?mKl;ywiX zJRgY!r~%b=`8voFTwx?QwQ|$XtAk_f325X=qesV_XM*R5YcDfQn~gQjD3filod+AFLY#56{UlzX-Ql#sd7sN2p?0MrmKhof$4Ym$CrBVW1~ zBI+sMax*_$m-#8IoQ&amR^V;ohja`dd_A1u_&r9-Q9k(jcYfoyF8$V}OMm4O{`=t4 z_x|-?{+-TmUb@6Tf0sqse>k@dUqv^Z`T}A-?|yOj_7>6-m0SANz2QIkuh%YJ;-9>w zL$qDn5_0uE?>yTtxAgIU`%nMsGJBqnn55}SKFHX=YRG;dmVg* zKlvno`M>A11>(c)Nd-N83 literal 0 HcmV?d00001 diff --git a/integrations/godot/plugin/methods/tools/godot_context.json b/integrations/godot/plugin/methods/tools/godot_context.json new file mode 100644 index 0000000..73a4b28 --- /dev/null +++ b/integrations/godot/plugin/methods/tools/godot_context.json @@ -0,0 +1,42 @@ +{ + "name": "godot_context", + "domain": "tools", + "description": "Bounded read of the attached Godot editor: revision, Godot version, the project (name, folder, main scene), open scenes, the edited scene (file, root, unsaved), selection, and node cards (path relative to the scene root, class, script, children, instanced scene) from node down depth levels, matching match (a glob on name or class). properties: values to read on the listed nodes. Call first. quarantined: changes wait until release_quarantine with this read's revision.", + "kind": "host-backed", + "risk": "read", + "args": { + "node": { + "type": "string", + "description": "Start below this node path (relative to the scene root)." + }, + "depth": { + "type": "integer", + "description": "Levels below node, 0 to 32.", + "default": 3 + }, + "match": { + "type": "string", + "description": "A glob on node names and classes (Player*, *Light3D)." + }, + "properties": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Property names to read on the listed nodes." + }, + "limit": { + "type": "integer", + "description": "Nodes listed, 0 to 500.", + "default": 40 + }, + "release_quarantine": { + "type": "integer", + "description": "After a failed change that could not be proven undone: the revision of the read that showed the scene, once you checked it; lifts the quarantine." + } + }, + "execution": { + "strategy": "host_method", + "method": "context" + } +} diff --git a/integrations/godot/plugin/methods/tools/godot_execute_code.json b/integrations/godot/plugin/methods/tools/godot_execute_code.json new file mode 100644 index 0000000..fbbe5af --- /dev/null +++ b/integrations/godot/plugin/methods/tools/godot_execute_code.json @@ -0,0 +1,34 @@ +{ + "name": "godot_execute_code", + "domain": "tools", + "dangerous": true, + "description": "DANGEROUS: run GDScript in the attached Godot editor (a @tool script, extending RefCounted), given as code or as a script file (path): statements (the body of func run()), or a script with its own func run() and helper functions. In scope: scene (the edited scene's root), EditorInterface, every engine class and singleton. Assign a JSON-able Dictionary to result; print() output is returned. A node you add needs node.owner = scene to be saved. A run that changes the scene is one undo action (OpenCode: code); a failing one (parse or script error) is undone and compared, and its error says what Godot knows (line, closest class, property or method names, real signatures, closest children of a missing node). No await. Every run asks permission.", + "kind": "host-backed", + "risk": "destructive", + "args": { + "code": { + "type": "string", + "description": "GDScript code (or path)." + }, + "path": { + "type": "string", + "description": "A .gd file to run instead of code, read as is (absolute or relative to the conversation's folder)." + }, + "read_only": { + "type": "boolean", + "description": "Inspection: no undo action, the scene is not compared." + }, + "timeout_s": { + "type": "integer", + "description": "Longest wait in seconds (1 to 3600).", + "default": 120 + } + }, + "execution": { + "strategy": "host_method", + "method": "execute_code" + }, + "requires": { + "hostMethods": ["execute_code"] + } +} diff --git a/integrations/godot/plugin/methods/tools/godot_hosts.json b/integrations/godot/plugin/methods/tools/godot_hosts.json new file mode 100644 index 0000000..470294a --- /dev/null +++ b/integrations/godot/plugin/methods/tools/godot_hosts.json @@ -0,0 +1,20 @@ +{ + "name": "godot_hosts", + "domain": "tools", + "description": "List the Godot editors offered to OpenCode on this computer (an editor whose project has OpenCode Link offers it when it starts, labelled with the project and the open scene): label, Godot version, and whether this conversation or another one is attached to each (attached_to: the one this conversation acts on), with the installed part's state. attach: attach one (its offerID) to this conversation, which asks permission; detach: release this conversation's editor. With one editor offered that no conversation uses, the first Godot tool call attaches it.", + "kind": "hostless", + "risk": "write", + "args": { + "attach": { + "type": "string", + "description": "An offerID from this list." + }, + "detach": { + "type": "boolean", + "description": "Release this conversation's editor." + } + }, + "execution": { + "strategy": "plugin" + } +} diff --git a/integrations/godot/plugin/methods/tools/godot_inspect.json b/integrations/godot/plugin/methods/tools/godot_inspect.json new file mode 100644 index 0000000..214f1d6 --- /dev/null +++ b/integrations/godot/plugin/methods/tools/godot_inspect.json @@ -0,0 +1,46 @@ +{ + "name": "godot_inspect", + "domain": "tools", + "description": "Ask THIS Godot what it really exposes, in one call: search (words found in class names and in the properties, methods with their signature and signals of every class of its ClassDB, and the project's script classes; ranked), a class (its inheritance, own properties with type, hint and default, methods with their real signatures, signals, enums, its documentation page; with match, the inherited members too), a live node of the open scene (class, script, instanced scene, children, groups, the property values that differ from the defaults, persistent connections, configuration warnings) and/or the open scene's tree. Entries beyond limit are named. Always says the Godot version and its documentation. Read only.", + "kind": "host-backed", + "risk": "read", + "args": { + "search": { + "type": "string", + "description": "Words, e.g. \"rigid body\", \"collision layer\", \"tween\"." + }, + "class": { + "type": "string", + "description": "A class: Node3D, CharacterBody2D, or a project script class." + }, + "node": { + "type": "string", + "description": "A node path in the open scene, relative to its root (Player/Camera3D)." + }, + "tree": { + "type": "boolean", + "description": "The open scene's tree." + }, + "depth": { + "type": "integer", + "description": "With tree: levels, 1 to 32.", + "default": 6 + }, + "match": { + "type": "string", + "description": "Keep the members matching: a glob on names (collision_*), or words found in them." + }, + "limit": { + "type": "integer", + "description": "Entries in detail (1 to 200).", + "default": 40 + } + }, + "execution": { + "strategy": "program", + "program": "programs/inspect.gd" + }, + "requires": { + "hostMethods": ["execute_code"] + } +} diff --git a/integrations/godot/plugin/methods/tools/godot_install_host.json b/integrations/godot/plugin/methods/tools/godot_install_host.json new file mode 100644 index 0000000..0ec4bfa --- /dev/null +++ b/integrations/godot/plugin/methods/tools/godot_install_host.json @@ -0,0 +1,16 @@ +{ + "name": "godot_install_host", + "domain": "tools", + "description": "Install or update OpenCode Link (the version of this plugin) in a Godot project: its add-on folder addons/opencode_link and its project.godot's enabled editor plugins. project: the project folder; by default the attached editor's project, else the conversation's folder. Asks permission; restart that project's editor afterwards if it is open.", + "kind": "hostless", + "risk": "write", + "args": { + "project": { + "type": "string", + "description": "A Godot project folder (with project.godot), absolute or relative to the conversation's folder." + } + }, + "execution": { + "strategy": "plugin" + } +} diff --git a/integrations/godot/plugin/methods/tools/godot_run.json b/integrations/godot/plugin/methods/tools/godot_run.json new file mode 100644 index 0000000..d52f8aa --- /dev/null +++ b/integrations/godot/plugin/methods/tools/godot_run.json @@ -0,0 +1,47 @@ +{ + "name": "godot_run", + "domain": "tools", + "description": "Run the project or a scene in a separate background Godot for some frames, as a task: the open editor stays usable and a crash there never touches it. Headless by default (the game's scripts run, its output and errors are read from its log); with capture, Godot's Movie Maker writes the frames as PNG images and the first, middle and last frames come back as images (a window of its own; hidden on Windows). It runs a working copy of the open scene (default), the scene as saved (source saved), a scene file, or the project's main scene (scene main). Returns a task: call again with task (and wait_s) for its state, or cancel.", + "kind": "host-backed", + "risk": "write", + "args": { + "scene": { + "type": "string", + "description": "A scene file (res://..., relative to the project, or absolute), or main for the project's main scene (default: the open scene)." + }, + "source": { + "type": "string", + "description": "For the open scene: copy (as it is now in the editor) or saved (its file).", + "enum": ["copy", "saved"], + "default": "copy" + }, + "frames": { + "type": "integer", + "description": "Frames to run (1 to 100000).", + "default": 60 + }, + "capture": { + "type": "any", + "description": "true, or {fps?: 1 to 240 (default 30), size?: [width, height]}: write the frames with Movie Maker." + }, + "task": { + "type": "string", + "description": "A task from an earlier call: its state." + }, + "wait_s": { + "type": "integer", + "description": "Wait up to this long for the task to finish (0 to 3600).", + "default": 0 + }, + "cancel": { + "type": "boolean", + "description": "With task: stop it." + } + }, + "execution": { + "strategy": "plugin" + }, + "requires": { + "hostMethods": ["execute_code"] + } +} diff --git a/integrations/godot/plugin/methods/tools/godot_save.json b/integrations/godot/plugin/methods/tools/godot_save.json new file mode 100644 index 0000000..98ac4a6 --- /dev/null +++ b/integrations/godot/plugin/methods/tools/godot_save.json @@ -0,0 +1,27 @@ +{ + "name": "godot_save", + "domain": "tools", + "description": "Save the open scene; with path, save it under that .tscn or .scn (as the open scene's file, or a copy with copy true: the open scene keeps its file). Relative paths are next to the open scene's file; an existing other file needs overwrite. Says what was written, read from the disk (path, file, bytes, time), the open file afterwards and whether unsaved changes remain. Project settings changed by code are saved by ProjectSettings.save() in godot_execute_code. godot_verify with saved reads the file back.", + "kind": "host-backed", + "risk": "write", + "args": { + "path": { + "type": "string" + }, + "copy": { + "type": "boolean", + "default": false + }, + "overwrite": { + "type": "boolean", + "default": false + } + }, + "execution": { + "strategy": "program", + "program": "programs/save.gd" + }, + "requires": { + "hostMethods": ["execute_code"] + } +} diff --git a/integrations/godot/plugin/methods/tools/godot_verify.json b/integrations/godot/plugin/methods/tools/godot_verify.json new file mode 100644 index 0000000..001e0fb --- /dev/null +++ b/integrations/godot/plugin/methods/tools/godot_verify.json @@ -0,0 +1,41 @@ +{ + "name": "godot_verify", + "domain": "tools", + "description": "Check a result by measurement. criteria: your own acceptance checks, each a Godot Expression measured on a scene and passed or failed with the measured value. errors (default on): the nodes whose script does not compile; with saved or frames, also the errors Godot logged loading and running the scene. Without saved or frames: the open scene, in the editor. saved: the same checks on the scene file as written on disk, read by a background --headless Godot (the editor stays free); check the delivered files before reporting. frames: run the scene that many frames first (its scripts run, as in the game; at a fixed 60 fps) for runtime values, in a background Godot, on a working copy of the open scene or on the saved file. Past timeout_s the background Godot is stopped and the answer says what it was doing. Nothing in the open scene changes.", + "kind": "host-backed", + "risk": "read", + "args": { + "criteria": { + "type": "array", + "items": { + "type": "object" + }, + "description": "Up to 50 checks: {expr: a Godot Expression; op: true (default) == != < <= > >= approx between in contains; value; tol (approx, default 1e-4); label}. In expr: scene and root (the scene's root node), node(path) (relative to the root), exists(path), prop(path, name), children(path), nodes(class) (paths), count(class), in_group(path, group), script_of(path), and Godot's own types and functions: node(\"Player\").position.y, count(\"MeshInstance3D\"), node(\"Light\").light_energy. Vectors and colors compare as [x, y, z] element by element." + }, + "errors": { + "type": "boolean", + "description": "Report the scripts that do not compile and the errors logged.", + "default": true + }, + "saved": { + "type": "any", + "description": "true: the open scene's file as saved on disk; or a scene file (res://..., a path relative to the project, or absolute)." + }, + "frames": { + "type": "integer", + "description": "Run the scene this many frames (at 60 fps) before measuring, in a background Godot." + }, + "timeout_s": { + "type": "integer", + "description": "For saved and frames: how long the background Godot may take (5 to 3600).", + "default": 300 + } + }, + "execution": { + "strategy": "program", + "program": "programs/verify.gd" + }, + "requires": { + "hostMethods": ["execute_code"] + } +} diff --git a/integrations/godot/plugin/package.json b/integrations/godot/plugin/package.json new file mode 100644 index 0000000..eb45a21 --- /dev/null +++ b/integrations/godot/plugin/package.json @@ -0,0 +1,68 @@ +{ + "name": "@neuralnomads/opencode-godot", + "version": "0.1.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", + "keywords": [ + "opencode-integration", + "opencode", + "godot" + ], + "repository": { + "type": "git", + "url": "https://github.com/NeuralNomadsAI/opencode-integrations", + "directory": "integrations/godot/plugin" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "files": [ + "dist", + "methods", + "programs", + "host", + "README.md", + "LICENSE" + ], + "publishConfig": { + "access": "public" + }, + "scripts": { + "build": "node scripts/build.ts", + "build:host": "node scripts/build-host.ts", + "typecheck": "tsc -p tsconfig.json" + }, + "peerDependencies": { + "@opencode/plugin": "^2.2.0 || ^0.0.0-dev" + }, + "peerDependenciesMeta": { + "@opencode/plugin": { + "optional": true + } + }, + "devDependencies": { + "@opencode/plugin": "2.2.5", + "@opencode/client": "2.2.5", + "esbuild": "0.28.2" + }, + "opencodeIntegration": { + "spec": 0, + "id": "godot", + "displayName": "OpenCode for Godot", + "family": "native", + "plugin": "neuralnomads.godot", + "rpc": "neuralnomads.godot", + "host": { + "app": "godot", + "protocol": 1, + "range": "^0.1.0", + "appVersions": ">=4.7 <5", + "payload": "host/godot/opencode_link-0.1.0.zip", + "sha256": "5d6ce783792f9b2233c6a576f82d465ef869b02543aedf80d5ab6432ff853790" + } + } +} diff --git a/integrations/godot/plugin/programs/background.gd b/integrations/godot/plugin/programs/background.gd new file mode 100644 index 0000000..ffca641 --- /dev/null +++ b/integrations/godot/plugin/programs/background.gd @@ -0,0 +1,87 @@ +## A background Godot's main loop (godot --headless --script): loads a scene file as written on disk, runs it for +## PARAMS.frames frames when given (its scripts run, as in the game), then measures the criteria (checks.gd) and +## writes the result to PARAMS.result. Each step is a line OPENCODE_STEP {json} in its log. + +var params: Dictionary = {} +var instance: Node +var left := 0 +var ran := 0 +var began := 0 +var capture := Capture.new() + + +class Capture extends Logger: + var errors: Array = [] + + func _log_error(_function: String, file: String, line: int, code: String, rationale: String, _notify: bool, type: int, _backtraces: Array) -> void: + if errors.size() < 50 and type != ERROR_TYPE_WARNING: + errors.append(("%s%s (%s:%d)" % [code, (" " + rationale) if rationale != "" else "", file, line]).left(500)) + + +func step(data: Dictionary) -> void: + data.at_s = snappedf((Time.get_ticks_msec() - began) / 1000.0, 0.1) + print("OPENCODE_STEP " + JSON.stringify(data)) + + +func _write(out: Dictionary) -> void: + var file := FileAccess.open(params.result + ".part", FileAccess.WRITE) + file.store_string(JSON.stringify(out)) + file.close() + DirAccess.rename_absolute(params.result + ".part", params.result) + + +func _initialize() -> void: + began = Time.get_ticks_msec() + OS.add_logger(capture) + var parser := JSON.new() + var args := OS.get_cmdline_user_args() + if args.is_empty() or parser.parse(FileAccess.get_file_as_string(args[0])) != OK: + push_error("OpenCode: no parameters") + quit(2) + return + params = parser.data + step({"step": "load"}) + var packed: Resource = ResourceLoader.load(params.scene, "PackedScene", ResourceLoader.CACHE_MODE_IGNORE) + if not (packed is PackedScene): + _write({"error": "%s did not load as a scene: %s" % [params.scene, "; ".join(capture.errors.slice(0, 5))]}) + quit(1) + return + instance = packed.instantiate() + if instance == null: + _write({"error": "%s did not instantiate: %s" % [params.scene, "; ".join(capture.errors.slice(0, 5))]}) + quit(1) + return + step({"step": "loaded", "seconds": snappedf((Time.get_ticks_msec() - began) / 1000.0, 0.01)}) + params.load_errors = capture.errors.duplicate() + capture.errors.clear() + left = int(params.get("frames", 0)) + if left > 0: + root.add_child(instance) + current_scene = instance + step({"step": "running", "frames": left}) + else: + _finish() + + +func _process(_delta: float) -> bool: + if left > 0: + left -= 1 + ran += 1 + if left == 0: + _finish() + return false + + +func _finish() -> void: + var out := {"criteria": measure(instance, params.get("criteria", []), step), "frames": ran} + out.passed = out.criteria.all(func(item): return item.passed) + if params.get("errors", true): + out.problems = problems(instance) + if not params.load_errors.is_empty(): + out.load_errors = params.load_errors + if not capture.errors.is_empty(): + out.runtime_errors = capture.errors + out.seconds = snappedf((Time.get_ticks_msec() - began) / 1000.0, 0.01) + step({"step": "done"}) + _write(out) + quit(0) diff --git a/integrations/godot/plugin/programs/checks.gd b/integrations/godot/plugin/programs/checks.gd new file mode 100644 index 0000000..b65cd0a --- /dev/null +++ b/integrations/godot/plugin/programs/checks.gd @@ -0,0 +1,191 @@ +## Shared by verify.gd (in the editor, on the open scene) and background.gd (a background Godot, on a file): the +## criteria, measured with Godot's Expression on a scene, and the scene's configuration warnings and script errors. + +class Probe extends RefCounted: + ## The functions a criterion's expression can call; `scene` and `root` name the scene's root node. + var root: Node + + func node(path: String) -> Node: + return root if path in ["", "."] else root.get_node_or_null(NodePath(path)) + + func exists(path: String) -> bool: + return node(path) != null + + func prop(path: String, name: String) -> Variant: + var found := node(path) + return found.get(name) if found != null else null + + func children(path: String = ".") -> Array: + var found := node(path) + return found.get_children().map(func(child): return str(child.name)) if found != null else [] + + func nodes(kind: String) -> Array: + var out := [] + for found in _all(): + if found.is_class(kind) or (found.get_script() != null and found.get_script().get_global_name() == kind): + out.append(path_of(found)) + return out + + func count(kind: String) -> int: + return nodes(kind).size() + + func in_group(path: String, group: String) -> bool: + var found := node(path) + return found != null and found.is_in_group(group) + + func script_of(path: String) -> String: + var found := node(path) + return found.get_script().resource_path if found != null and found.get_script() != null else "" + + func path_of(found: Node) -> String: + return "." if found == root else str(root.get_path_to(found)) + + func _all() -> Array: + var out := [root] + var stack := [root] + while not stack.is_empty(): + for child in stack.pop_back().get_children(): + out.append(child) + stack.append(child) + return out + + +static func plain(value: Variant, root: Node, depth := 0) -> Variant: + if depth > 16: + return str(value) + match typeof(value): + TYPE_NIL, TYPE_BOOL, TYPE_INT, TYPE_STRING: + return value + TYPE_FLOAT: + return value if is_finite(value) else str(value) + TYPE_STRING_NAME, TYPE_NODE_PATH: + return str(value) + TYPE_VECTOR2, TYPE_VECTOR2I: + return [value.x, value.y] + TYPE_VECTOR3, TYPE_VECTOR3I: + return [value.x, value.y, value.z] + TYPE_VECTOR4, TYPE_VECTOR4I, TYPE_QUATERNION: + return [value.x, value.y, value.z, value.w] + TYPE_COLOR: + return [value.r, value.g, value.b, value.a] + TYPE_RECT2, TYPE_RECT2I, TYPE_AABB: + return {"position": plain(value.position, root), "size": plain(value.size, root)} + TYPE_TRANSFORM3D: + return {"basis": [plain(value.basis.x, root), plain(value.basis.y, root), plain(value.basis.z, root)], "origin": plain(value.origin, root)} + TYPE_TRANSFORM2D: + return {"x": plain(value.x, root), "y": plain(value.y, root), "origin": plain(value.origin, root)} + TYPE_OBJECT: + if value == null or not is_instance_valid(value): + return null + if value is Node: + return {"node": "." if value == root else (str(root.get_path_to(value)) if root.is_ancestor_of(value) else str(value.name)), "class": value.get_class()} + if value is Resource: + return {"resource": value.resource_path if value.resource_path != "" else null, "class": value.get_class()} + return {"object": value.get_class()} + TYPE_DICTIONARY: + var out := {} + for key in value: + out[str(key)] = plain(value[key], root, depth + 1) + return out + if typeof(value) >= TYPE_ARRAY: + var items := [] + for i in mini(value.size(), 1000): + items.append(plain(value[i], root, depth + 1)) + return items + return str(value) + + +static func _numbers(value: Variant) -> Variant: + if value is int or value is float: + return [float(value)] + if value is Array: + var out := [] + for item in value: + var inner: Variant = _numbers(item) + if inner == null: + return null + out.append_array(inner) + return out + return null + + +static func compare(value: Variant, op: String, expected: Variant, tol: float) -> bool: + match op: + "", "true": + return bool(value) if value != null else false + "==": + return value == expected or (_numbers(value) != null and _numbers(value) == _numbers(expected)) + "!=": + return not compare(value, "==", expected, tol) + "approx": + var a: Variant = _numbers(value) + var b: Variant = _numbers(expected) + if a == null or b == null or a.size() != b.size(): + return false + for i in a.size(): + if absf(a[i] - b[i]) > tol: + return false + return true + "<", "<=", ">", ">=": + var a: Variant = _numbers(value) + var b: Variant = _numbers(expected) + if a == null or b == null or a.size() != b.size(): + return false + for i in a.size(): + var ok: bool = {"<": a[i] < b[i], "<=": a[i] <= b[i], ">": a[i] > b[i], ">=": a[i] >= b[i]}[op] + if not ok: + return false + return true + "between": + return expected is Array and expected.size() == 2 and compare(value, ">=", expected[0], tol) and compare(value, "<=", expected[1], tol) + "in": + return expected is Array and expected.any(func(item): return compare(value, "==", item, tol)) + "contains": + if value is String: + return value.contains(str(expected)) + return value is Array and value.any(func(item): return compare(item, "==", expected, tol)) + return false + + +## Each criterion measured on the scene: {label, expr, op, expected, value, passed} or its error. +static func measure(root: Node, criteria: Array, step := Callable()) -> Array: + var probe := Probe.new() + probe.root = root + var results := [] + for index in mini(criteria.size(), 50): + var criterion: Dictionary = criteria[index] if criteria[index] is Dictionary else {"expr": str(criteria[index])} + var label := str(criterion.get("label", criterion.get("expr", ""))) + if step.is_valid(): + step.call({"step": "criterion", "index": index + 1, "of": criteria.size(), "label": label}) + var expression := Expression.new() + var item := {"label": label, "expr": str(criterion.get("expr", "")), "op": str(criterion.get("op", "true"))} + if criterion.has("value"): + item.expected = criterion.value + if expression.parse(item.expr, ["scene", "root"]) != OK: + item.passed = false + item.error = expression.get_error_text() + results.append(item) + continue + var value: Variant = expression.execute([root, root], probe, false) + if expression.has_execute_failed(): + item.passed = false + item.error = expression.get_error_text() + else: + item.value = plain(value, root) + item.passed = compare(item.value, item.op, criterion.get("value"), float(criterion.get("tol", 0.0001))) + results.append(item) + return results + + +## The scene's nodes whose script does not compile (Godot then runs them without it). +static func problems(root: Node, limit := 50) -> Array: + var out := [] + var probe := Probe.new() + probe.root = root + for found in probe._all(): + var script: Variant = found.get_script() + if script is Script and not script.can_instantiate(): + out.append({"node": probe.path_of(found), "class": found.get_class(), "script": "%s does not compile" % script.resource_path}) + if out.size() >= limit: + break + return out diff --git a/integrations/godot/plugin/programs/copy.gd b/integrations/godot/plugin/programs/copy.gd new file mode 100644 index 0000000..a5fb4ca --- /dev/null +++ b/integrations/godot/plugin/programs/copy.gd @@ -0,0 +1,19 @@ +## A working copy of the open scene, as it is now in the editor, for a background Godot (godot_verify frames, +## godot_run): written to PARAMS.file; the open scene keeps its file and its unsaved changes. Read only. + +func run(): + if scene == null: + assert(false, "No scene is open in the editor: open one, or give a scene file.") + return + var packed := PackedScene.new() + var packing := packed.pack(scene) + if packing != OK: + assert(false, "The open scene could not be packed: %s" % error_string(packing)) + return + var saved := ResourceSaver.save(packed, PARAMS.file) + if saved != OK: + assert(false, "The working copy could not be written to %s: %s" % [PARAMS.file, error_string(saved)]) + return + result.file = PARAMS.file + result.scene = scene.scene_file_path + result.unsaved = scene.scene_file_path == "" or scene.scene_file_path in EditorInterface.get_unsaved_scenes() diff --git a/integrations/godot/plugin/programs/inspect.gd b/integrations/godot/plugin/programs/inspect.gd new file mode 100644 index 0000000..20085e3 --- /dev/null +++ b/integrations/godot/plugin/programs/inspect.gd @@ -0,0 +1,253 @@ +## godot_inspect: what THIS Godot exposes, read from its ClassDB, the project's script classes and the open scene. +## Read only. + +func _limit() -> int: + return clampi(int(PARAMS.get("limit", 40)), 1, 200) + + +static func _type(info: Dictionary) -> String: + if str(info.get("class_name", "")) != "": + return str(info.class_name) + if info.get("type", TYPE_NIL) == TYPE_NIL: + return "Variant" if info.get("usage", 0) & PROPERTY_USAGE_NIL_IS_VARIANT else "void" + return type_string(info.type) + + +static func _signature(method: Dictionary) -> String: + var args := [] + var defaults: Array = method.get("default_args", []) + var first: int = method.args.size() - defaults.size() + for i in method.args.size(): + var arg: Dictionary = method.args[i] + args.append("%s: %s%s" % [arg.name, _type(arg), (" = " + var_to_str(defaults[i - first])) if i >= first else ""]) + if method.get("flags", 0) & METHOD_FLAG_VARARG: + args.append("...") + return "%s%s(%s) -> %s" % ["static " if method.get("flags", 0) & METHOD_FLAG_STATIC else "", method.name, ", ".join(args), _type(method.get("return", {}))] + + +static func _signal(info: Dictionary) -> String: + return "%s(%s)" % [info.name, ", ".join(info.args.map(func(arg): return "%s: %s" % [arg.name, _type(arg)]))] + + +static func _words(text: String) -> Array: + return text.to_lower().replace("_", " ").replace(".", " ").split(" ", false) + + +static func _score(name: String, words: Array) -> int: + var lower := name.to_lower() + var flat := lower.replace("_", "") + var score := 0 + for word in words: + if lower == word or flat == word: + score += 4 + elif lower.contains(word) or flat.contains(word): + score += 2 + else: + return 0 + return score + + +func _docs(klass: String) -> String: + var info := Engine.get_version_info() + return "https://docs.godotengine.org/en/%d.%d/classes/class_%s.html" % [info.major, info.minor, klass.to_lower()] + + +func _script_classes() -> Dictionary: + var out := {} + for entry in ProjectSettings.get_global_class_list(): + out[str(entry["class"])] = entry + return out + + +func _search(text: String) -> Dictionary: + var words := _words(text) + var found := [] + for klass in ClassDB.get_class_list(): + var own := _score(klass, words) + if own: + found.append([own + 2, {"kind": "class", "class": klass, "inherits": ClassDB.get_parent_class(klass)}]) + for property in ClassDB.class_get_property_list(klass, true): + if property.usage & (PROPERTY_USAGE_CATEGORY | PROPERTY_USAGE_GROUP | PROPERTY_USAGE_SUBGROUP): + continue + var score := _score(property.name, words) + if score: + found.append([score, {"kind": "property", "class": klass, "name": property.name, "type": _type(property)}]) + for method in ClassDB.class_get_method_list(klass, true): + var score := _score(method.name, words) + if score and not method.name.begins_with("_"): + found.append([score, {"kind": "method", "class": klass, "signature": _signature(method)}]) + for info in ClassDB.class_get_signal_list(klass, true): + var score := _score(info.name, words) + if score: + found.append([score, {"kind": "signal", "class": klass, "signature": _signal(info)}]) + for name in _script_classes(): + var score := _score(name, words) + if score: + var entry: Dictionary = _script_classes()[name] + found.append([score + 2, {"kind": "script class", "class": name, "inherits": entry.base, "path": entry.path}]) + found.sort_custom(func(a, b): return a[0] > b[0] or (a[0] == b[0] and str(a[1]).length() < str(b[1]).length())) + var limit := _limit() + var more := found.slice(limit, limit + 60).map(func(item): return "%s.%s" % [item[1]["class"], item[1].get("name", item[1].get("signature", "")).get_slice("(", 0)]) + return {"words": words, "found": found.size(), "results": found.slice(0, limit).map(func(item): return item[1]), "also": more} + + +func _wanted(name: String) -> bool: + var pattern := str(PARAMS.get("match", "")) + if pattern == "": + return true + if pattern.contains("*") or pattern.contains("?"): + return name.matchn(pattern) + return _score(name, _words(pattern)) > 0 + + +func _class(klass: String) -> Dictionary: + var scripts := _script_classes() + var script: Script = null + if not ClassDB.class_exists(klass) and scripts.has(klass): + script = load(scripts[klass].path) + elif not ClassDB.class_exists(klass): + var names := Array(ClassDB.get_class_list()) + scripts.keys() + var close := names.filter(func(name): return klass.to_lower().similarity(name.to_lower()) > 0.5) + close.sort_custom(func(a, b): return klass.to_lower().similarity(a.to_lower()) > klass.to_lower().similarity(b.to_lower())) + return {"class": klass, "error": "Godot has no class %s." % klass, "closest": close.slice(0, 8)} + var inherited: bool = PARAMS.has("match") + var properties := [] + var methods := [] + var signals := [] + var list_properties: Array = script.get_script_property_list() if script else ClassDB.class_get_property_list(klass, not inherited) + var list_methods: Array = script.get_script_method_list() if script else ClassDB.class_get_method_list(klass, not inherited) + var list_signals: Array = script.get_script_signal_list() if script else ClassDB.class_get_signal_list(klass, not inherited) + for property in list_properties: + if property.usage & (PROPERTY_USAGE_CATEGORY | PROPERTY_USAGE_GROUP | PROPERTY_USAGE_SUBGROUP) or not _wanted(property.name): + continue + var item := {"name": property.name, "type": _type(property)} + if property.hint_string != "" and property.hint in [PROPERTY_HINT_ENUM, PROPERTY_HINT_RANGE, PROPERTY_HINT_FLAGS]: + item.hint = property.hint_string.left(200) + if not script: + var value: Variant = ClassDB.class_get_property_default_value(klass, property.name) + if value != null: + item.default = var_to_str(value).left(120) + properties.append(item) + for method in list_methods: + if not method.name.begins_with("_") or script: + if _wanted(method.name): + methods.append(_signature(method)) + for info in list_signals: + if _wanted(info.name): + signals.append(_signal(info)) + var limit := _limit() + var chain := [] + var parent: String = ClassDB.get_parent_class(klass) if not script else str(script.get_instance_base_type()) + while parent != "": + chain.append(parent) + parent = ClassDB.get_parent_class(parent) + var out := { + "class": klass, "inherits": chain, "properties": properties.slice(0, limit), "methods": methods.slice(0, limit), + "signals": signals.slice(0, limit), + } + if script: + out.path = script.resource_path + else: + out.docs = _docs(klass) + out.instantiable = ClassDB.can_instantiate(klass) + var enums := {} + for name in ClassDB.class_get_enum_list(klass, true): + enums[name] = Array(ClassDB.class_get_enum_constants(klass, name, true)) + if not enums.is_empty(): + out.enums = enums + var beyond := {"properties": properties.size() - limit, "methods": methods.size() - limit, "signals": signals.size() - limit} + for key in beyond: + if beyond[key] > 0: + out["%s_beyond_limit" % key] = beyond[key] + if not inherited: + out.note = "Own members only: give match (a glob or words) to search the inherited ones too." + return out + + +func _node(path: String) -> Dictionary: + if scene == null: + return {"error": "No scene is open in the editor."} + var found: Node = scene if path in ["", "."] else scene.get_node_or_null(NodePath(path)) + if found == null: + var parent := scene + var parts := path.split("/", false) + for part in parts: + var next := parent.get_node_or_null(NodePath(part)) + if next == null: + var names := parent.get_children().map(func(child): return str(child.name)) + names.sort_custom(func(a, b): return part.similarity(a) > part.similarity(b)) + return {"node": path, "error": "No child %s under %s." % [part, "." if parent == scene else str(scene.get_path_to(parent))], "children": names.slice(0, 20)} + parent = next + return {"node": path, "error": "No node %s." % path} + var out := { + "node": "." if found == scene else str(scene.get_path_to(found)), "class": found.get_class(), + "children": found.get_children().map(func(child): return "%s (%s)" % [child.name, child.get_class()]).slice(0, 50), + "groups": Array(found.get_groups()).map(func(group): return str(group)).filter(func(group): return not group.begins_with("_")), + } + if found.get_script() != null: + out.script = found.get_script().resource_path + if found != scene and found.scene_file_path != "": + out.instance = found.scene_file_path + var values := {} + var count := 0 + for property in found.get_property_list(): + if not property.usage & PROPERTY_USAGE_STORAGE or not _wanted(property.name): + continue + var value: Variant = found.get(property.name) + var default: Variant = ClassDB.class_get_property_default_value(found.get_class(), property.name) + if PARAMS.has("match") or default == null or str(value) != str(default): + values[property.name] = runner_value(value) + count += 1 + if count >= _limit(): + break + out.values = values + var connections := [] + for info in found.get_signal_list(): + for connection in found.get_signal_connection_list(info.name): + if connection.flags & Object.CONNECT_PERSIST: + connections.append("%s -> %s.%s" % [info.name, connection.callable.get_object(), connection.callable.get_method()]) + if connections: + out.connections = connections.slice(0, 40) + return out + + +func runner_value(value: Variant) -> Variant: + if value is Object: + if value is Resource: + return {"resource": value.resource_path if value.resource_path != "" else null, "class": value.get_class()} + if value is Node: + return {"node": str(scene.get_path_to(value)) if scene.is_ancestor_of(value) else str(value.name)} + return {"object": value.get_class()} + return var_to_str(value).left(300) if typeof(value) in [TYPE_TRANSFORM3D, TYPE_BASIS, TYPE_PROJECTION] else value + + +func _tree(depth: int) -> Array: + var lines := [] + if scene == null: + return lines + var stack := [[scene, 0]] + while not stack.is_empty() and lines.size() < 400: + var item: Array = stack.pop_back() + var node: Node = item[0] + lines.append("%s%s (%s)%s" % [" ".repeat(item[1]), node.name, node.get_class(), (" [%s]" % node.scene_file_path) if node != scene and node.scene_file_path != "" else ""]) + if item[1] < depth: + var children := node.get_children() + children.reverse() + for child in children: + if child.owner == scene or child.owner == null: + stack.append([child, item[1] + 1]) + return lines + + +func run(): + var info := Engine.get_version_info() + result.godot = info.string + result.docs = "https://docs.godotengine.org/en/%d.%d/" % [info.major, info.minor] + if PARAMS.has("search"): + result.search = _search(str(PARAMS.search)) + if PARAMS.has("class"): + result["class"] = _class(str(PARAMS["class"])) + if PARAMS.has("node"): + result.node = _node(str(PARAMS.node)) + if PARAMS.get("tree"): + result.tree = _tree(clampi(int(PARAMS.get("depth", 6)), 1, 32)) diff --git a/integrations/godot/plugin/programs/save.gd b/integrations/godot/plugin/programs/save.gd new file mode 100644 index 0000000..6f24ce8 --- /dev/null +++ b/integrations/godot/plugin/programs/save.gd @@ -0,0 +1,54 @@ +## godot_save: the open scene to its file, or under PARAMS.path (as the open scene's file, or a copy with copy true). +## Says what was written, read from the disk. + +func _target(path: String) -> String: + if path.begins_with("res://"): + return path + if path.is_absolute_path(): + var local := ProjectSettings.localize_path(path) + return local + var base := scene.scene_file_path.get_base_dir() if scene.scene_file_path != "" else "res://" + return base.path_join(path).simplify_path() + + +func run(): + if scene == null: + assert(false, "No scene is open in the editor.") + return + var path := str(PARAMS.get("path", "")) + var copy: bool = PARAMS.get("copy", false) == true + var target := scene.scene_file_path if path == "" else _target(path) + if target == "": + assert(false, "This scene was never saved: give path (a .tscn file in the project).") + return + if not target.get_extension() in ["tscn", "scn"]: + assert(false, "%s is not a .tscn or .scn file." % target) + return + if target != scene.scene_file_path and FileAccess.file_exists(target) and PARAMS.get("overwrite", false) != true: + assert(false, "%s exists: give overwrite true to replace it." % target) + return + if copy: + var packed := PackedScene.new() + var packing := packed.pack(scene) + var saved := ResourceSaver.save(packed, target) if packing == OK else packing + if saved != OK: + assert(false, "%s was not written: %s" % [target, error_string(saved)]) + return + elif target == scene.scene_file_path: + var saved := EditorInterface.save_scene() + if saved != OK: + assert(false, "%s was not written: %s" % [target, error_string(saved)]) + return + else: + EditorInterface.save_scene_as(target, true) + if not FileAccess.file_exists(target): + assert(false, "%s is not on disk after saving." % target) + return + var file := FileAccess.open(target, FileAccess.READ) + result.path = target + result.file = ProjectSettings.globalize_path(target) + result.bytes = file.get_length() if file != null else 0 + result.modified = Time.get_datetime_string_from_unix_time(FileAccess.get_modified_time(target), true) + result.copy = copy + result.open_file = scene.scene_file_path + result.unsaved = scene.scene_file_path == "" or scene.scene_file_path in EditorInterface.get_unsaved_scenes() diff --git a/integrations/godot/plugin/programs/verify.gd b/integrations/godot/plugin/programs/verify.gd new file mode 100644 index 0000000..e250ad7 --- /dev/null +++ b/integrations/godot/plugin/programs/verify.gd @@ -0,0 +1,12 @@ +## godot_verify on the open scene, in the editor: each criterion measured, and the scene's problems. Read only. + +func run(): + if scene == null: + assert(false, "No scene is open in the editor: open one, or give godot_verify saved with a scene file.") + return + result.scene = scene.scene_file_path + result.criteria = measure(scene, PARAMS.get("criteria", [])) + result.passed = result.criteria.all(func(item): return item.passed) + if PARAMS.get("errors", true): + result.problems = problems(scene) + result.unsaved = scene.scene_file_path == "" or scene.scene_file_path in EditorInterface.get_unsaved_scenes() diff --git a/integrations/godot/plugin/scripts/build-host.ts b/integrations/godot/plugin/scripts/build-host.ts new file mode 100644 index 0000000..b9b5475 --- /dev/null +++ b/integrations/godot/plugin/scripts/build-host.ts @@ -0,0 +1,63 @@ +// The installed part's payload: the add-on folder addons/opencode_link (GDScript, read by Godot as it is) and the +// dock's sidecar (sidecar.cjs, the plugin's own OpenCode client for Node), as a stored zip with the plugin's version. +// Usage: node scripts/build-host.ts [--check] + +import { createHash } from "node:crypto" +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs" +import { dirname, join, relative } from "node:path" +import { fileURLToPath } from "node:url" +import { build } from "esbuild" +import { writeStoredZip } from "../../../../packages/integration-kit/src/zip.ts" + +const root = fileURLToPath(new URL("..", import.meta.url)) +const host = join(root, "..", "host") +const addon = join(host, "addons", "opencode_link") +const pkgPath = join(root, "package.json") +const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) +const version = /^version="([^"]+)"$/m.exec(readFileSync(join(addon, "plugin.cfg"), "utf8"))?.[1] +if (version !== pkg.version) throw new Error("Host and plugin versions differ") +const check = process.argv.includes("--check") +const bundle = await build({ + entryPoints: [join(root, "src", "sidecar.ts")], + bundle: true, + format: "cjs", + platform: "node", + target: "node22", + write: false, + legalComments: "eof", + logLevel: "warning", +}) +const sidecar = Buffer.from(bundle.outputFiles?.[0]?.contents ?? []) +const walk = (dir: string): string[] => + readdirSync(dir, { withFileTypes: true }).flatMap((entry) => + entry.name === "sidecar.cjs" || entry.name.endsWith(".uid") + ? [] + : entry.isDirectory() + ? walk(join(dir, entry.name)) + : [join(dir, entry.name)], + ) +const entries = walk(addon).map((file) => ({ + name: relative(host, file).replaceAll("\\", "/"), + data: Buffer.from(readFileSync(file, "utf8").replaceAll("\r\n", "\n")), +})) +entries.push({ name: "addons/opencode_link/sidecar.cjs", data: sidecar }) +const payload = writeStoredZip(entries.sort((a, b) => (a.name < b.name ? -1 : 1))) +const name = `host/godot/opencode_link-${pkg.version}.zip` +const digest = createHash("sha256").update(payload).digest("hex") +const file = join(root, name) +if (check) { + if ( + !existsSync(file) || + !readFileSync(file).equals(payload) || + pkg.opencodeIntegration.host.sha256 !== digest || + pkg.opencodeIntegration.host.payload !== name + ) + throw new Error("Godot host payload is stale: run npm run build:host --workspace @neuralnomads/opencode-godot") +} else { + mkdirSync(dirname(file), { recursive: true }) + writeFileSync(file, payload) + pkg.opencodeIntegration.host.payload = name + pkg.opencodeIntegration.host.sha256 = digest + writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`) +} +console.log(`Godot host ${check ? "verified" : "built"}: ${pkg.version}`) diff --git a/integrations/godot/plugin/scripts/build.ts b/integrations/godot/plugin/scripts/build.ts new file mode 100644 index 0000000..2fcecf2 --- /dev/null +++ b/integrations/godot/plugin/scripts/build.ts @@ -0,0 +1,38 @@ +// Builds dist/: one ESM file bundling the plugin and the integration kit (the SDK stays external, +// the OpenCode binary provides it), and its type declaration. Fails when the host artifacts are stale. +// Usage: node scripts/build.ts + +import { execFileSync } from "node:child_process" +import { mkdirSync, rmSync, writeFileSync } from "node:fs" +import { join } from "node:path" +import { fileURLToPath } from "node:url" + +import { build } from "esbuild" + +const root = fileURLToPath(new URL("..", import.meta.url)) +const dist = join(root, "dist") + +execFileSync(process.execPath, [join(root, "scripts", "build-host.ts"), "--check"], { stdio: "inherit" }) + +rmSync(dist, { recursive: true, force: true }) +mkdirSync(dist, { recursive: true }) +await build({ + entryPoints: [join(root, "src", "plugin.ts")], + outfile: join(dist, "index.js"), + bundle: true, + format: "esm", + platform: "node", + target: "node22", + external: ["@opencode/plugin", "@opencode/plugin/*"], + // semver is CommonJS: give the bundle a require for Node's built-in modules. + banner: { + js: 'import { createRequire as __createRequire } from "node:module";\nconst require = __createRequire(import.meta.url);', + }, + legalComments: "eof", + logLevel: "warning", +}) +writeFileSync( + join(dist, "index.d.ts"), + 'import type { Plugin } from "@opencode/plugin"\n\ndeclare const plugin: Plugin.Plugin\nexport default plugin\n', +) +console.log("build: dist/index.js") diff --git a/integrations/godot/plugin/src/closed.ts b/integrations/godot/plugin/src/closed.ts new file mode 100644 index 0000000..ff10ef7 --- /dev/null +++ b/integrations/godot/plugin/src/closed.ts @@ -0,0 +1,35 @@ +// What became of a Godot editor that stopped answering a conversation (the kit's crashWatch). Godot's editor writes no +// log of its own; OpenCode Link writes what Godot's crash handler prints ("Program crashed" and the backtrace) to +// opencode-crash-.log in the project's user data folder, which its hello names. + +import { closeSync, openSync, readSync, statSync } from "node:fs" +import { join } from "node:path" + +import { crashWatch } from "./kit.ts" + +// The end of a log, where a crash is written. +export function logTail(path: string, bytes = 64 * 1024) { + try { + const size = statSync(path).size + const length = Math.min(size, bytes) + const buffer = Buffer.alloc(length) + const fd = openSync(path, "r") + try { + readSync(fd, buffer, 0, length, size - length) + } finally { + closeSync(fd) + } + return buffer.toString("utf8") + } catch { + return "" + } +} + +export const CRASHED = /Program crashed/ + +export const { crashReport, closedMessage, silentMessage } = crashWatch({ + appName: "Godot", + app: "godot", + part: "OpenCode Link", + isReport: (name, host) => name.endsWith(".log") && CRASHED.test(logTail(join(host.tempDir, name))), +}) diff --git a/integrations/godot/plugin/src/host-install.ts b/integrations/godot/plugin/src/host-install.ts new file mode 100644 index 0000000..25d50e0 --- /dev/null +++ b/integrations/godot/plugin/src/host-install.ts @@ -0,0 +1,117 @@ +// The installed part: the add-on addons/opencode_link of a Godot project, enabled in its project.godot +// ([editor_plugins] enabled). Godot 4 has no editor-wide add-ons: an editor plugin belongs to its project. + +import { createHash, randomUUID } from "node:crypto" +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs" +import { dirname, join } from "node:path" +import { readStoredZip } from "../../../../packages/integration-kit/src/zip.ts" +import type { HostInspection, InstallHostOutput, IntegrationMarker } from "./kit.ts" +import { godotProject, packageRoot } from "./paths.ts" + +export const ADDON = join("addons", "opencode_link") +export const PLUGIN_CFG = "res://addons/opencode_link/plugin.cfg" +// The add-on's own plugin.cfg says it is this integration's. +const OURS = /^name="OpenCode Link"$/m + +const versionOf = (cfg: string) => /^version="([^"]+)"$/m.exec(cfg)?.[1] + +function readText(file: string) { + try { + return readFileSync(file, "utf8") + } catch { + return undefined + } +} + +// The [editor_plugins] section's enabled list, or null when it does not name the add-on. +export function enabledIn(projectGodot: string) { + const section = /^\[editor_plugins\][^\n]*\n([\s\S]*?)(?=^\[|(?![\s\S]))/m.exec(projectGodot)?.[1] ?? "" + const list = /^enabled=PackedStringArray\(([^)]*)\)/m.exec(section)?.[1] ?? "" + return [...list.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((match) => match[1]) +} + +// project.godot with the add-on enabled, keeping every other line as it was. +export function enablePlugin(projectGodot: string): string { + const eol = projectGodot.includes("\r\n") ? "\r\n" : "\n" + const entry = `"${PLUGIN_CFG}"` + const header = /^\[editor_plugins\][^\n]*\n/m.exec(projectGodot) + if (!header) { + const base = projectGodot.endsWith("\n") || !projectGodot ? projectGodot : `${projectGodot}${eol}` + return `${base}${eol}[editor_plugins]${eol}${eol}enabled=PackedStringArray(${entry})${eol}` + } + const start = header.index + header[0].length + const rest = projectGodot.slice(start) + const end = /^\[/m.exec(rest)?.index ?? rest.length + const section = rest.slice(0, end) + const line = /^enabled=PackedStringArray\(([^)]*)\)/m.exec(section) + const updated = line + ? section.replace(line[0], `enabled=PackedStringArray(${line[1]?.trim() ? `${line[1].trim()}, ` : ""}${entry})`) + : `${eol}enabled=PackedStringArray(${entry})${eol}${section.replace(/^(\r?\n)+/, "")}` + return projectGodot.slice(0, start) + updated + rest.slice(end) +} + +// The installed version, when the add-on is in the project and enabled there. +export function inspectHost(project?: string): HostInspection { + const folder = godotProject(project) + if (!folder) return { kind: "not-inspected" } + const cfg = readText(join(folder, ADDON, "plugin.cfg")) + const settings = readText(join(folder, "project.godot")) ?? "" + const version = cfg && OURS.test(cfg) ? versionOf(cfg) : undefined + if (!version || !enabledIn(settings).includes(PLUGIN_CFG)) return { kind: "not-found" } + return { kind: "found", version } +} + +export function installHost(marker: IntegrationMarker, project?: string): InstallHostOutput { + const folder = godotProject(project) + if (!folder) + return { + outcome: "refused", + detail: + "Name a Godot project folder (the one with project.godot): godot_install_host project, or the conversation's folder.", + } + const host = marker.host + if (!host) return { outcome: "refused" } + const archive = readFileSync(join(packageRoot, host.payload)) + if (createHash("sha256").update(archive).digest("hex") !== host.sha256) + return { outcome: "failed", detail: "Host payload checksum mismatch." } + const entries = readStoredZip(archive) + const target = join(folder, ADDON) + const cfg = readText(join(target, "plugin.cfg")) + if (existsSync(target) && !(cfg && OURS.test(cfg))) + return { outcome: "refused", detail: `${target} exists and is not OpenCode Link: it was left untouched.` } + const settingsFile = join(folder, "project.godot") + const settings = readFileSync(settingsFile, "utf8") + const enabled = enabledIn(settings).includes(PLUGIN_CFG) + const prefix = "addons/opencode_link/" + const same = entries.every((entry) => { + const existing = join(target, entry.name.slice(prefix.length)) + return existsSync(existing) && readFileSync(existing).equals(entry.data) + }) + if (same && enabled) return { outcome: "unchanged" } + const staging = join(folder, "addons", `.opencode_link-${randomUUID()}`) + const previous = join(folder, "addons", `.opencode_link-old-${randomUUID()}`) + try { + if (!same) { + for (const entry of entries) { + const file = join(staging, entry.name.slice(prefix.length)) + mkdirSync(dirname(file), { recursive: true }) + writeFileSync(file, entry.data) + } + if (existsSync(target)) renameSync(target, previous) + renameSync(staging, target) + } + if (!enabled) { + const temporary = `${settingsFile}-${randomUUID()}` + writeFileSync(temporary, enablePlugin(settings)) + renameSync(temporary, settingsFile) + } + } finally { + rmSync(staging, { recursive: true, force: true }) + rmSync(previous, { recursive: true, force: true }) + } + return { + outcome: cfg && !same ? "updated" : "installed", + detail: + "Restart this project's Godot editor if it is open: OpenCode Link offers the project to OpenCode when the editor starts.", + } +} diff --git a/integrations/godot/plugin/src/integration.ts b/integrations/godot/plugin/src/integration.ts new file mode 100644 index 0000000..0636af8 --- /dev/null +++ b/integrations/godot/plugin/src/integration.ts @@ -0,0 +1,575 @@ +// OpenCode for Godot: RPC status contract, tools and the working method. Loading has no side effect: no socket, +// process or installation; the editor is reached only once a conversation is attached to an offer validated by +// hello. The conversations' attachment and host calls are the kit's host session, as for Blender, Houdini and Gaffer. + +import { readFileSync, statSync, writeFileSync } from "node:fs" +import { isAbsolute, join, resolve } from "node:path" +import { pathToFileURL } from "node:url" + +import type { Plugin } from "@opencode/plugin" +import type { ToolContext } from "@opencode/plugin/promise/tool" + +import { closedMessage, crashReport, silentMessage } from "./closed.ts" +import { inspectHost, installHost } from "./host-install.ts" +import { + type AttachmentStorage, + buildPluginTools, + createAttachments, + createHostSession, + createIntegrationRpc, + HELLO_TIMEOUT_MS, + HostError, + hostErrorWith, + type IntegrationMarker, + isWslDaemon, + loadMethodRegistry, + type OfferRegistry, + readScript, + registerPluginTools, + requestHost, + type SessionBindings, + sharedOfferRegistry, + type ToolContent, + trackAdvertise, +} from "./kit.ts" +import { type EntryPut, methodAttacher } from "./method.ts" +import { type GodotOptions, readOptions } from "./options.ts" +import { godotProject, methodsDir, packageRoot } from "./paths.ts" +import { backgroundScript, type ProgramName, programCode } from "./programs.ts" +import { + type Background, + cancelTask, + getTask, + previewFrames, + type Spawner, + startBackground, + taskStatus, + waitResult, + workDir, +} from "./tasks.ts" + +export const APP = "godot" +const NAMESPACE_DESCRIPTION = "Godot, through OpenCode Link: read and change the attached editor's project." + +export const PERMISSIONS = { + attach: "godot_attach", + install: "godot_install_host", + executeCode: "godot_execute_code", +} as const + +const MAX_TEXT = 100_000 +// Longest wait of one godot_run call that follows a task. +export const RUN_WAIT_MAX_S = 3_600 + +const HINTS: Record = { + stale_handle: "The attached Godot editor changed: godot_hosts shows the editors offered.", + stale_revision: "The scene changed since your last read: call godot_context and use its revision.", + busy: "Godot is busy (a modal dialog, an import or a long run): try again shortly.", + quarantined: + "A failed change could not be proven undone: read the scene (godot_context), check it, then give that read's revision as release_quarantine.", + method_disabled: "Code execution is not available in the attached Godot.", + method_not_found: + "The attached Godot's OpenCode Link lacks this method: install this plugin's OpenCode Link (godot_install_host) and restart the editor.", + invalid_args: "Godot refused the request.", + unreachable: "The attached Godot is unreachable: it may have closed or stopped offering its project.", + timeout: + "Godot did not answer in time; the change may still complete. Call godot_context before acting again: the scene may already hold it.", + cancelled: "The request was cancelled; a change may still complete in Godot. Call godot_context before acting again.", +} + +// The installed part's own text and data follow the hint (the kit's message after its "Host refused" prefix). +const hostError = hostErrorWith(HINTS, "Godot", (error: HostError) => + error.message.replace(/^Host refused the request \([^)]*\)[.:]?\s*/, ""), +) + +export type GodotDeps = { + env?: NodeJS.ProcessEnv + // A private registry for tests; the daemon shares one registry across Locations. + registry?: OfferRegistry + // The clock of the stored attachments' lease, for tests. + now?: () => number + wsl?: () => boolean + // How background Godots start, for tests. + spawn?: Spawner +} + +type PackageJson = { version: string; opencodeIntegration: IntegrationMarker } + +export function readPackage(): PackageJson { + return JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8")) as PackageJson +} + +// The offer list shared by the daemon's Locations, named after this version's host contract (the kit's +// sharedOfferRegistry). One Godot editor offers its project; hello names it. +export function createRegistry(marker: IntegrationMarker): OfferRegistry { + const host = marker.host as NonNullable + return sharedOfferRegistry(APP, { + expected: { protocol: host.protocol, range: host.range, appVersions: host.appVersions }, + hello: (endpoint, scriptHandle) => + requestHost(endpoint, "hello", { script_handle: scriptHandle }, { timeoutMs: HELLO_TIMEOUT_MS }), + }) +} + +function bounded(text: string) { + return text.length > MAX_TEXT + ? `${text.slice(0, MAX_TEXT)}\n[truncated: ${text.length - MAX_TEXT} more characters]` + : text +} + +const json = (value: unknown) => bounded(JSON.stringify(value)) + +// After a save: what reads the files back, as written on disk (the open scene can differ from them). +export function verifySavedHint(saved: true | string) { + return `godot_verify with saved: ${saved === true ? "true" : JSON.stringify(saved)} reads what this file holds.` +} + +type ProgramRun = { + result?: unknown + status?: string + message?: string + line?: number + traceback?: string + hint?: string +} +type EditorContext = { + executable: string + project: { path: string; main_scene: string } + scene: { path: string; unsaved: boolean } | null +} + +// Godot's own path form, forward slashes, for a background Godot's arguments. +const godotPath = (path: string) => path.replaceAll("\\", "/") + +export async function setupGodot(ctx: Plugin.Context, deps: GodotDeps = {}) { + const env = deps.env ?? process.env + const options: GodotOptions = readOptions(ctx.options as Record | undefined, env) + const pkg = readPackage() + const marker = pkg.opencodeIntegration + const registry = deps.registry ?? createRegistry(marker) + const manifests = loadMethodRegistry(methodsDir) + const wsl = deps.wsl ?? isWslDaemon + const locationProject = () => godotProject(ctx.location?.directory) + + const rpc = createIntegrationRpc({ + marker, + version: pkg.version, + registry, + nativeSession: { + location: ctx.location, + get: ctx.session?.get ? (input) => ctx.session.get(input as Parameters[0]) : undefined, + }, + inspectHost: async () => inspectHost(locationProject()), + installHost: async () => installHost(marker, locationProject()), + wsl: deps.wsl, + }) + const bindings = rpc.bindings as SessionBindings + // Attachments kept across an OpenCode restart and a scene change. + const attachments = createAttachments({ + app: APP, + registry, + storage: (ctx as unknown as { storage?: AttachmentStorage }).storage, + now: deps.now, + owns: (sessionID) => bindings.snapshot(sessionID), + }) + const handlers: Record Promise> = { + ...rpc.handlers, + advertise: trackAdvertise(registry, (input) => rpc.handlers.advertise?.(input) as Promise, APP), + attachHost: async (input: unknown, context?: { signal?: AbortSignal }) => { + const result = (await rpc.handlers.attachHost?.(input, context)) as { outcome?: string } + const sessionID = (input as { sessionID?: unknown } | null)?.sessionID + if (result?.outcome === "attached" && typeof sessionID === "string") await attachments.remember(sessionID) + return result + }, + // The stored attachment goes first, once the session is verifiably this Location's: the detach's own change + // event must not find it and attach the conversation back. + detachHost: async (input: unknown, context?: { signal?: AbortSignal }) => { + const sessionID = (input as { sessionID?: unknown } | null)?.sessionID + if (typeof sessionID === "string" && (await bindings.snapshot(sessionID, context?.signal))) + await attachments.forget(sessionID) + return rpc.handlers.detachHost?.(input, context) + }, + } + + const assert = async ( + context: ToolContext, + action: string, + resources: string[], + metadata?: Record, + ) => { + await ctx.permission.assert({ + sessionID: context.sessionID, + agent: context.agent, + action, + resources, + ...(metadata ? { metadata } : {}), + source: { type: "tool", messageID: context.messageID, id: context.id }, + } as Parameters[0]) + } + + // The method joins a conversation when it uses a Godot editor (an instructions entry, where OpenCode has them). + const instructions = (ctx as unknown as { session?: { instructions?: { entry?: { put?: EntryPut } } } }).session + const put = instructions?.instructions?.entry?.put + const attachMethod = methodAttacher(put ? (input) => put.call(instructions?.instructions?.entry, input) : undefined) + + const hostSession = createHostSession({ + texts: { + appName: "Godot", + app: APP, + part: "OpenCode Link", + partKind: "OpenCode Link", + noneOffered: + "No Godot editor is offered: open the project in Godot 4.7 or later with OpenCode Link installed in it (godot_install_host); the editor offers its project when it starts.", + installHint: `install OpenCode Link ${pkg.version} (godot_install_host) and restart the editor`, + }, + registry, + bindings, + attachments, + attachMethod, + crash: { crashReport, closedMessage, silentMessage }, + wsl: deps.wsl ?? (() => isWslDaemon()), + requestTimeoutMs: options.requestTimeoutMs, + hostError, + }) + const { attachedTo, ticket, callHost, maintain } = hostSession + + // Every host call names its conversation: the dock's Stop drops that conversation's queued requests. + const call = ( + context: ToolContext, + method: string, + params: Record, + timeoutMs?: number, + captured?: Parameters[4], + ) => callHost(context, method, { session_id: context.sessionID, ...params }, timeoutMs, captured) + + // A fixed program through the host's code execution, read only (programs.ts). + const program = async ( + context: ToolContext, + name: ProgramName, + params: unknown, + held?: Parameters[4], + ) => { + const out = (await call( + context, + "execute_code", + { code: programCode(name), params, read_only: true }, + undefined, + held, + )) as ProgramRun + if (out.status === "failed") + throw new Error( + `godot_${name}: ${String(out.message ?? "")}${out.hint ? `\n${out.hint}` : ""}${out.traceback ? `\n${String(out.traceback).slice(-1200)}` : ""}`, + ) + return out.result + } + + const editor = async (context: ToolContext) => + (await call(context, "context", { limit: 0, depth: 0 })) as EditorContext & Record + + // A scene file of the project: res://, a path relative to the project, or an absolute path. + const sceneFile = (path: string) => + path.startsWith("res://") || isAbsolute(path) ? godotPath(path) : `res://${godotPath(path).replace(/^\.?\//, "")}` + + // The scene a background Godot reads: a file, or a working copy of the open scene written by the editor. + const backgroundScene = async ( + context: ToolContext, + info: EditorContext, + work: string, + scene: unknown, + source: unknown, + held: Parameters[4], + ) => { + if (typeof scene === "string" && scene && scene !== "main") return sceneFile(scene) + if (!info.scene) throw new Error("No scene is open in the editor: give scene (a scene file of the project).") + if (source === "saved") { + if (!info.scene.path) throw new Error("The open scene was never saved: save it (godot_save path) first.") + return info.scene.path + } + const file = godotPath(join(work, "scene.tscn")) + await program(context, "copy", { file }, held) + return file + } + + const follow = async (id: string, waitS: unknown, context: ToolContext) => { + const task = getTask(id) + if (!task) throw new Error(`No Godot task ${id} in this OpenCode.`) + const until = Date.now() + Math.min(Math.max(Number(waitS ?? 0), 0), RUN_WAIT_MAX_S) * 1_000 + let status = taskStatus(task) + while (status.state === "running" && Date.now() < until && !context.signal.aborted) { + await new Promise((resolve) => setTimeout(resolve, 250)) + status = taskStatus(task) + } + return withFrames(task, status) + } + + // A finished capture's frames are attachments, never only paths in the text. + const withFrames = (task: Background, status: ReturnType): string | ToolContent[] => { + const frames = status.state === "done" ? previewFrames(task) : [] + if (!frames.length) return json(status) + return [ + { type: "text", text: json(status) }, + ...frames.map((frame) => ({ + type: "file" as const, + uri: pathToFileURL(frame).href, + mime: "image/png", + name: frame.split(/[\\/]/).at(-1) ?? "frame.png", + })), + ] + } + + const executors: Record< + string, + (args: Record, context: ToolContext) => Promise + > = { + async godot_hosts(args, context) { + const out = await hostSession.hosts(args, context, { + allow: (held, offer) => assert(held, PERMISSIONS.attach, [offer.label], { label: offer.label }), + status: () => rpc.status(), + list: "editors", + }) + // Two editors of the same project on the same scene offer the same label: said, so that the right one is attached. + const labels = registry.hosts().offers.map((offer) => offer.label) + const twice = [...new Set(labels.filter((label, index) => labels.indexOf(label) !== index))] + return json({ + ...out, + ...(twice.length + ? { + same_label: `Several Godot editors show the same project and scene (${twice.join(", ")}): their offers differ by offerID only; attach the one you mean, or close the others.`, + } + : {}), + }) + }, + + async godot_install_host(args, context) { + if (wsl()) return json(await handlers.installHost?.({})) + let project: string | undefined + if (typeof args.project === "string" && args.project) { + project = godotProject(resolve(ctx.location?.directory ?? process.cwd(), args.project)) + if (!project) throw new Error(`${args.project} is not a Godot project folder (no project.godot).`) + } else if (registry.binding(context.sessionID)) { + project = godotProject((await editor(context)).project.path) + } + project ??= locationProject() + await assert(context, PERMISSIONS.install, [project ?? "*"]) + return json(installHost(marker, project)) + }, + + async godot_context(args, context) { + const { release_quarantine: release, ...query } = args + if (release === undefined) + return json({ + ...((await call(context, "context", query)) as object), + attached_to: attachedTo(context.sessionID), + }) + // After a failed change whose undo could not be proven: the agent read the scene (this revision) and lifts the + // quarantine; the scene is read again with it. + const released = (await call(context, "release", { revision: release })) as { released?: boolean } + return json({ + ...((await call(context, "context", query)) as object), + attached_to: attachedTo(context.sessionID), + released: released.released === true, + }) + }, + + // The dangerous method: every run asks permission. + async godot_execute_code(args, context) { + // A script file is read here, byte for byte: no escaping of the code through a JSON or JavaScript string. + const script = + typeof args.path === "string" && args.path ? readScript(args.path, ctx.location?.directory) : undefined + if (script && args.code !== undefined) throw new Error("Give code or path, not both.") + const code = script?.code ?? String(args.code ?? "") + if (!code.trim()) throw new Error(script ? `${script.path} is empty.` : "code or path is required.") + const held = await ticket(context) + if (!held.bound.methods.includes("execute_code")) throw new HostError("method_disabled", "") + await assert(context, PERMISSIONS.executeCode, [script?.path ?? "*"], { + ...(script ? { path: script.path } : {}), + code: code.length > 4_000 ? `${code.slice(0, 4_000)}\n…` : code, + }) + const seconds = typeof args.timeout_s === "number" ? Math.min(Math.max(args.timeout_s, 1), 3_600) : undefined + const out = (await call( + context, + "execute_code", + { + code, + ...(script ? { filename: script.path } : {}), + ...(args.read_only === true ? { read_only: true } : {}), + }, + seconds ? seconds * 1_000 : undefined, + held, + )) as Record + return json(out) + }, + + async godot_inspect(args, context) { + if (args.search === undefined && args.class === undefined && args.node === undefined && args.tree !== true) + throw new Error("Give search, class, node and/or tree.") + return json(await program(context, "inspect", args)) + }, + + async godot_verify(args, context) { + const frames = typeof args.frames === "number" ? Math.min(Math.max(Math.round(args.frames), 0), 100_000) : 0 + const saved = args.saved !== undefined && args.saved !== false + if (saved && args.saved !== true && typeof args.saved !== "string") + throw new Error("saved: true (the open scene as saved) or a scene file.") + const checks = { criteria: args.criteria ?? [], errors: args.errors ?? true } + const held = await ticket(context) + if (saved || frames || (Array.isArray(checks.criteria) && checks.criteria.length > 0)) + await assert(context, PERMISSIONS.executeCode, [held.label ?? "*"], { verification: checks, frames }) + if (!saved && !frames) return json(await program(context, "verify", checks, held)) + // A background Godot reads the file (or a working copy of the open scene, for frames): the editor stays free. + const info = (await call(context, "context", { limit: 0, depth: 0 }, undefined, held)) as EditorContext + const work = workDir("verify") + const scene = await backgroundScene( + context, + info, + work, + typeof args.saved === "string" ? args.saved : undefined, + saved ? "saved" : "copy", + held, + ) + const timeoutS = + typeof args.timeout_s === "number" ? Math.min(Math.max(Math.round(args.timeout_s), 5), 3_600) : 300 + const result = join(work, "result.json") + writeFileSync(join(work, "background.gd"), backgroundScript()) + writeFileSync(join(work, "params.json"), JSON.stringify({ ...checks, scene, frames, result: godotPath(result) })) + const task = startBackground( + { + kind: "verify", + executable: info.executable, + project: info.project.path, + args: [ + "--headless", + ...(frames ? ["--fixed-fps", "60"] : []), + "--script", + godotPath(join(work, "background.gd")), + "--", + godotPath(join(work, "params.json")), + ], + work, + scene, + frames, + }, + deps.spawn, + ) + const measured = await waitResult(task, result, timeoutS, { signal: context.signal }) + let file: Record = {} + if (saved) { + const path = scene.startsWith("res://") ? join(info.project.path, scene.slice("res://".length)) : scene + try { + const stat = statSync(path) + file = { file: path, bytes: stat.size, saved_at: stat.mtime.toISOString() } + } catch {} + } + return json({ + ...measured, + read: { + scene, + ...file, + ...(frames ? { frames } : {}), + by: saved + ? "a background Godot on the file as written on disk, not the open scene" + : "a background Godot on a working copy of the open scene, run for these frames", + }, + }) + }, + + async godot_run(args, context) { + const { task: id, wait_s, cancel } = args + if (id !== undefined) { + const task = getTask(String(id)) + if (task && cancel === true) return json(cancelTask(task)) + return await follow(String(id), wait_s, context) + } + const held = await ticket(context) + await assert(context, "godot_run", [held.label ?? "*"], { scene: args.scene, capture: args.capture }) + const info = (await call(context, "context", { limit: 0, depth: 0 }, undefined, held)) as EditorContext + const frames = typeof args.frames === "number" ? Math.min(Math.max(Math.round(args.frames), 1), 100_000) : 60 + const capture = args.capture === true || (typeof args.capture === "object" && args.capture !== null) + const settings = (typeof args.capture === "object" && args.capture !== null ? args.capture : {}) as { + fps?: unknown + size?: unknown + } + const fps = typeof settings.fps === "number" ? Math.min(Math.max(Math.round(settings.fps), 1), 240) : 30 + const size = Array.isArray(settings.size) && settings.size.length === 2 ? settings.size.map(Number) : undefined + if (args.scene === "main" && !info.project.main_scene) + throw new Error("The project has no main scene: give scene (a scene file), or set one in the Project Settings.") + const work = workDir(capture ? "capture" : "run") + const scene = + args.scene === "main" ? "" : await backgroundScene(context, info, work, args.scene, args.source, held) + const movie = capture ? godotPath(join(work, "frame.png")) : undefined + const task = startBackground( + { + kind: capture ? "capture" : "run", + executable: info.executable, + project: info.project.path, + args: [ + ...(capture + ? [ + "--write-movie", + movie as string, + "--fixed-fps", + String(fps), + ...(size?.every((value) => Number.isInteger(value) && value >= 16 && value <= 8192) + ? ["--resolution", `${size[0]}x${size[1]}`] + : []), + ] + : ["--headless", "--fixed-fps", "60"]), + "--quit-after", + String(frames), + ...(scene ? [scene] : []), + ], + work, + scene: scene || info.project.main_scene, + frames, + ...(movie ? { movie } : {}), + }, + deps.spawn, + ) + return await follow(task.id, wait_s, context) + }, + + async godot_save(args, context) { + const result = (await program(context, "save", args)) as Record + return json({ ...result, check: verifySavedHint(result?.copy === true ? String(result.path) : true) }) + }, + } + + const allTools = buildPluginTools( + manifests.list().filter((manifest) => manifest.domain === "tools"), + APP, + async (manifest, args, context) => { + const executor = executors[manifest.name] + if (!executor) throw new Error(`No executor for ${manifest.name}`) + try { + return await executor(args, context) + } catch (error) { + throw hostError(error) + } + }, + ) + + const registrations: Array<{ dispose: () => Promise }> = [] + let disconnect = () => {} + let unsubscribe = () => {} + const cleanup = async () => { + unsubscribe() + disconnect() + for (const registration of registrations.splice(0).reverse()) await registration.dispose().catch(() => {}) + } + try { + await attachments.load() + const registration = await ctx.rpc.register(rpc.definition as never, handlers as never) + registrations.push(registration) + disconnect = rpc.connect(registration as never) + registrations.push( + await ctx.tool.transform((editor) => registerPluginTools(editor, APP, NAMESPACE_DESCRIPTION, allTools)), + ) + unsubscribe = registry.onChange(() => void maintain()) + void maintain() + } catch (error) { + await cleanup() + throw error + } + return Object.assign(cleanup, { + internals: { registry, rpc, handlers, tools: allTools, executors, options, attachments, maintain }, + }) +} diff --git a/integrations/godot/plugin/src/kit.ts b/integrations/godot/plugin/src/kit.ts new file mode 100644 index 0000000..5138c8d --- /dev/null +++ b/integrations/godot/plugin/src/kit.ts @@ -0,0 +1 @@ +export * from "../../../../packages/integration-kit/src/index.ts" diff --git a/integrations/godot/plugin/src/method.ts b/integrations/godot/plugin/src/method.ts new file mode 100644 index 0000000..83cb0b8 --- /dev/null +++ b/integrations/godot/plugin/src/method.ts @@ -0,0 +1,24 @@ +// The working method, attached once to a conversation when it attaches a Godot editor (a native instructions entry, +// not a skill): what to check before writing code, and how to verify a step. + +import { type EntryPut, methodAttacher as kitAttacher, resetMethodForTests as resetKit } from "./kit.ts" + +export const METHOD_KEY = "godot.method" +export const METHOD_TEXT = [ + "Working on the attached Godot project:", + "- Your knowledge of Godot's API may be older than it: read its version (godot_hosts, godot_inspect).", + "- Inspect the exact element before coding it (godot_inspect search, class, node, tree).", + "- After an error, read its hint and inspect again; never guess twice.", + "- Turn each requirement of your task into a measured check (godot_verify criteria; frames for runtime values).", + "- The saved files are what you deliver: save, then run every check on them with godot_verify saved: true.", + "- Report each requirement with its measured value from the files. A failed or unchecked one is not done: say so.", + "- Still unclear: the Godot documentation of THIS version (links in godot_inspect).", +].join("\n") + +export type { EntryPut } + +export const methodAttacher = (put: EntryPut | undefined) => kitAttacher(put, { key: METHOD_KEY, text: METHOD_TEXT }) + +export function resetMethodForTests() { + resetKit(METHOD_KEY) +} diff --git a/integrations/godot/plugin/src/options.ts b/integrations/godot/plugin/src/options.ts new file mode 100644 index 0000000..1454a8b --- /dev/null +++ b/integrations/godot/plugin/src/options.ts @@ -0,0 +1,18 @@ +// Plugin settings: the `options` of the plugin entry first, `NEURALNOMADS_GODOT_*` variables as a fallback. + +export type GodotOptions = { + // Longest wait for one host request (a tool may give a longer one, such as a code run). + requestTimeoutMs: number +} + +// OpenCode Link waits up to an hour for the editor's main loop to finish a request; a call waits this long by +// default, then says whether Godot still runs it (status). +const DEFAULT_TIMEOUT_MS = 120_000 + +export function readOptions(options: Record | undefined, env: NodeJS.ProcessEnv): GodotOptions { + const source = options ?? {} + const timeout = Number(source.requestTimeoutMs ?? env.NEURALNOMADS_GODOT_REQUEST_TIMEOUT_MS) + return { + requestTimeoutMs: Number.isFinite(timeout) && timeout >= 1_000 ? Math.min(timeout, 600_000) : DEFAULT_TIMEOUT_MS, + } +} diff --git a/integrations/godot/plugin/src/paths.ts b/integrations/godot/plugin/src/paths.ts new file mode 100644 index 0000000..e3932d3 --- /dev/null +++ b/integrations/godot/plugin/src/paths.ts @@ -0,0 +1,21 @@ +// Folders the plugin reads: its own package (methods, programs, host payload) and the Godot projects it installs into. + +import { existsSync, statSync } from "node:fs" +import { join, resolve } from "node:path" +import { fileURLToPath } from "node:url" + +// dist/index.js and src/*.ts both sit one level below the package root. +export const packageRoot = fileURLToPath(new URL("..", import.meta.url)) +export const methodsDir = join(packageRoot, "methods") +export const programsDir = join(packageRoot, "programs") + +// A Godot project: a folder with its project.godot. +export function godotProject(directory: string | undefined): string | undefined { + if (!directory) return undefined + const folder = resolve(directory) + try { + return existsSync(join(folder, "project.godot")) && statSync(folder).isDirectory() ? folder : undefined + } catch { + return undefined + } +} diff --git a/integrations/godot/plugin/src/plugin.ts b/integrations/godot/plugin/src/plugin.ts new file mode 100644 index 0000000..5ea2d83 --- /dev/null +++ b/integrations/godot/plugin/src/plugin.ts @@ -0,0 +1,4 @@ +import { Plugin } from "@opencode/plugin" +import { setupGodot } from "./integration.ts" + +export default Plugin.define({ id: "neuralnomads.godot", setup: setupGodot }) diff --git a/integrations/godot/plugin/src/programs.ts b/integrations/godot/plugin/src/programs.ts new file mode 100644 index 0000000..6f3d33f --- /dev/null +++ b/integrations/godot/plugin/src/programs.ts @@ -0,0 +1,25 @@ +// The fixed GDScript programs of godot_inspect, godot_verify, godot_save and the working copies (programs/*.gd in the +// package). They run through OpenCode Link's code execution, read only, with their parameters as data (PARAMS): the +// plugin's own code, never code from the model, so they ask no permission. background.gd is the main loop of a +// background Godot (godot --headless --script) that reads a scene file. + +import { readFileSync } from "node:fs" +import { join } from "node:path" + +import { programsDir } from "./paths.ts" + +const read = (file: string) => readFileSync(join(programsDir, file), "utf8").replaceAll("\r\n", "\n") +const checks = read("checks.gd") +const PROGRAMS = { + inspect: read("inspect.gd"), + verify: `${read("verify.gd")}\n${checks}`, + save: read("save.gd"), + copy: read("copy.gd"), +} + +export type ProgramName = keyof typeof PROGRAMS + +export const programCode = (name: ProgramName) => PROGRAMS[name] + +// The background Godot's main loop script. +export const backgroundScript = () => `extends SceneTree\n\n${read("background.gd")}\n${checks}` diff --git a/integrations/godot/plugin/src/service.ts b/integrations/godot/plugin/src/service.ts new file mode 100644 index 0000000..29aa3ef --- /dev/null +++ b/integrations/godot/plugin/src/service.ts @@ -0,0 +1,91 @@ +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 + } +} diff --git a/integrations/godot/plugin/src/sidecar-core.ts b/integrations/godot/plugin/src/sidecar-core.ts new file mode 100644 index 0000000..8d15e74 --- /dev/null +++ b/integrations/godot/plugin/src/sidecar-core.ts @@ -0,0 +1,385 @@ +// 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)), + } +} diff --git a/integrations/godot/plugin/src/sidecar.ts b/integrations/godot/plugin/src/sidecar.ts new file mode 100644 index 0000000..5aba5ff --- /dev/null +++ b/integrations/godot/plugin/src/sidecar.ts @@ -0,0 +1,35 @@ +// 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" + +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)) +}) diff --git a/integrations/godot/plugin/src/tasks.ts b/integrations/godot/plugin/src/tasks.ts new file mode 100644 index 0000000..4279d47 --- /dev/null +++ b/integrations/godot/plugin/src/tasks.ts @@ -0,0 +1,260 @@ +// Background Godots started by the plugin on this computer, with the attached editor's own executable: godot_run (the +// project or a scene for some frames, headless, or with Movie Maker for a capture) as a task, and godot_verify's reads +// of a scene file (background.gd) with bounded time. Each writes its log with --log-file; a crash is written there +// ("Program crashed") and never touches the open editor. + +import { type ChildProcess, execFileSync, spawn } from "node:child_process" +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +import { CRASHED, logTail } from "./closed.ts" + +export type Background = { + id: string + kind: "run" | "capture" | "verify" + pid: number + work: string + log: string + scene: string + started: number + frames: number + movie?: string + finished?: number + exit?: number | null + cancelled?: boolean + error?: string +} + +const shared = globalThis as { __neuralnomadsGodotTasks?: Map } +shared.__neuralnomadsGodotTasks ??= new Map() +const tasks = shared.__neuralnomadsGodotTasks + +export const workDir = (kind: string) => mkdtempSync(join(tmpdir(), `opencode-godot-${kind}-`)) + +export type Spawner = (command: string, args: string[]) => ChildProcess + +const defaultSpawn: Spawner = (command, args) => spawn(command, args, { windowsHide: true, stdio: "ignore" }) + +// Starts a background Godot on the project: `--path --log-file ...args`. +export function startBackground( + input: { + kind: Background["kind"] + executable: string + project: string + args: string[] + work: string + scene: string + frames: number + movie?: string + }, + run: Spawner = defaultSpawn, +): Background { + const log = join(input.work, "godot.log") + const child = run(input.executable, ["--path", input.project, "--log-file", log, ...input.args]) + const id = `${input.kind}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}` + const task: Background = { + id, + kind: input.kind, + pid: child.pid ?? 0, + work: input.work, + log, + scene: input.scene, + started: Date.now(), + frames: input.frames, + ...(input.movie ? { movie: input.movie } : {}), + } + child.once("error", (error) => { + task.error = `Godot did not start: ${error.message}` + task.exit ??= null + task.finished ??= Date.now() + }) + child.once("exit", (code) => { + task.exit = code + task.finished ??= Date.now() + }) + tasks.set(id, task) + return task +} + +export const getTask = (id: string) => tasks.get(id) + +const running = (task: Background) => task.finished === undefined + +// The errors Godot wrote: "ERROR: ..." and "SCRIPT ERROR: ..." lines with the "at:" line after each. +export function errorsOf(text: string, limit = 10) { + const lines = text.split(/\r?\n/) + const found: string[] = [] + for (let index = 0; index < lines.length && found.length < limit; index++) { + const line = lines[index] ?? "" + if (!/^(USER )?(SCRIPT )?ERROR: /.test(line)) continue + const at = lines[index + 1]?.trim().startsWith("at:") ? ` (${lines[index + 1]?.trim()})` : "" + found.push(`${line}${at}`.slice(0, 400)) + } + return found +} + +// A crash's first lines: what crashed and the innermost frames. +export function crashOf(text: string) { + const at = text.search(CRASHED) + if (at < 0) return undefined + return text + .slice(text.lastIndexOf("\n", at) + 1) + .split(/\r?\n/) + .filter((line) => line.trim() && !/^=+$/.test(line.trim())) + .slice(0, 8) + .join(" | ") + .slice(0, 800) +} + +const frameFiles = (task: Background) => { + if (!task.movie || !existsSync(task.work)) return [] + const base = "frame" + return readdirSync(task.work) + .filter((name) => name.startsWith(base) && name.endsWith(".png")) + .sort() + .map((name) => join(task.work, name)) +} + +export function taskStatus(task: Background) { + const text = logTail(task.log, 256 * 1024) + const crash = crashOf(text) + const errors = errorsOf(text) + const frames = frameFiles(task) + const failedExit = task.exit !== undefined && task.exit !== 0 + const state = task.cancelled + ? "cancelled" + : running(task) + ? "running" + : crash || failedExit || task.error || (task.kind === "capture" && !frames.length) + ? "failed" + : "done" + return { + task: task.id, + kind: task.kind, + state, + scene: task.scene, + frames: task.frames, + elapsed_s: Math.round(((task.finished ?? Date.now()) - task.started) / 100) / 10, + ...(task.exit !== undefined ? { exit_code: task.exit } : {}), + ...(crash ? { crash: `the background Godot crashed: ${crash}. The open editor is not affected.` } : {}), + ...(task.error ? { error: task.error } : {}), + ...(state === "failed" && !crash && !task.error && task.kind === "capture" && !frames.length + ? { error: "Movie Maker wrote no frame: see the log." } + : {}), + ...(errors.length ? { errors } : {}), + ...(task.movie + ? { movie: { folder: task.work, written: frames.length, first: frames[0], last: frames.at(-1) } } + : {}), + log: task.log, + } +} + +// The frames a capture shows: the first, the middle and the last. +export function previewFrames(task: Background) { + const frames = frameFiles(task) + if (frames.length <= 3) return frames + return [frames[0], frames[Math.floor(frames.length / 2)], frames.at(-1)] as string[] +} + +// A background Godot and the processes it started. +export function stopTree(pid: number) { + // A process that never started has no PID: never signal 0 (a process group). + if (!Number.isInteger(pid) || pid <= 0) return + if (process.platform === "win32") { + try { + execFileSync("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }) + return + } catch {} + } + try { + process.kill(pid) + } catch {} +} + +export function cancelTask(task: Background) { + task.cancelled = true + if (running(task)) stopTree(task.pid) + return taskStatus(task) +} + +type Step = { step?: string; at_s?: number; [key: string]: unknown } + +export function stepsOf(text: string): Step[] { + return text + .split(/\r?\n/) + .filter((line) => line.startsWith("OPENCODE_STEP ")) + .flatMap((line) => { + try { + return [JSON.parse(line.slice("OPENCODE_STEP ".length)) as Step] + } catch { + return [] + } + }) +} + +// What a step says the background Godot was doing, in words. +export function describeStep(step: Step | undefined, scene: string) { + switch (step?.step) { + case undefined: + return "starting (Godot had not loaded the scene yet)" + case "load": + return `loading ${scene}` + case "loaded": + return `loaded ${scene} in ${step.seconds} s` + case "running": + return `running ${step.frames} frames of ${scene}` + case "criterion": + return `measuring criterion ${step.index}/${step.of} "${step.label}"` + case "done": + return "writing its result" + default: + return String(step?.step) + } +} + +export type WaitDeps = { now?: () => number; sleep?: (ms: number) => Promise; signal?: AbortSignal } + +// Waits for a background Godot's result file, at most timeoutS from now; stopped past it, and the answer says where it +// was. Its folder is removed once it has exited. +export async function waitResult(task: Background, result: string, timeoutS: number, deps: WaitDeps = {}) { + const now = deps.now ?? Date.now + const sleep = deps.sleep ?? ((ms: number) => new Promise((done) => setTimeout(done, ms))) + const deadline = now() + timeoutS * 1_000 + try { + for (;;) { + if (existsSync(result) && statSync(result).size > 0) { + const got = JSON.parse(readFileSync(result, "utf8")) as Record + if (typeof got.error === "string") throw new Error(`the background Godot reading ${task.scene}: ${got.error}`) + return got + } + if (!running(task)) { + await sleep(200) + if (existsSync(result)) continue + const text = logTail(task.log) + const crash = crashOf(text) + const last = describeStep(stepsOf(text).at(-1), task.scene) + throw new Error( + crash + ? `the background Godot crashed while ${last}: ${crash}. The open editor is not affected. Log: ${task.log}` + : `the background Godot stopped without a result (exit code ${task.exit}) while ${last}${task.error ? `: ${task.error}` : ""}. ${errorsOf(text, 5).join(" | ")}`, + ) + } + if (deps.signal?.aborted || now() >= deadline) { + stopTree(task.pid) + const last = describeStep(stepsOf(logTail(task.log)).at(-1), task.scene) + throw new Error( + `${deps.signal?.aborted ? "godot_verify was cancelled" : `godot_verify stopped the background Godot after ${timeoutS} s (timeout_s)`}: it was ${last}. Give more time with timeout_s (up to 3600), or fewer frames.`, + ) + } + await sleep(250) + } + } finally { + void (async () => { + for (let attempt = 0; attempt < 50 && running(task); attempt++) await sleep(200) + rmSync(task.work, { recursive: true, force: true }) + })() + } +} + +export const ensureDir = (dir: string) => mkdirSync(dir, { recursive: true }) diff --git a/integrations/godot/plugin/tsconfig.json b/integrations/godot/plugin/tsconfig.json new file mode 100644 index 0000000..b30dc27 --- /dev/null +++ b/integrations/godot/plugin/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "../../..", + "noEmit": true, + "composite": false, + "declaration": false + }, + "include": ["src/**/*.ts", "scripts/**/*.ts", "../test/**/*.ts"] +} diff --git a/integrations/godot/test/conformance.test.ts b/integrations/godot/test/conformance.test.ts new file mode 100644 index 0000000..fe91877 --- /dev/null +++ b/integrations/godot/test/conformance.test.ts @@ -0,0 +1,102 @@ +import assert from "node:assert/strict" +import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { after, it } from "node:test" +import { + checkCodeExecutionGate, + type ManifestLike, + runSentinelScenario, + startFakeHost, +} from "../../../packages/testing/src/index.ts" +import { readPackage } from "../plugin/src/integration.ts" +import { methodsDir } from "../plugin/src/paths.ts" +import { announcement, loadPlugin } from "./helpers.ts" + +const scratch = mkdtempSync(join(tmpdir(), "godot-conformance-")) +after(() => rmSync(scratch, { recursive: true, force: true })) + +function manifests(): ManifestLike[] { + return readdirSync(methodsDir, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".json")) + .map((entry) => JSON.parse(readFileSync(join(entry.parentPath, entry.name), "utf8")) as ManifestLike) +} + +it("checkCodeExecutionGate: declared dangerous, listed by the host, asked on every call", async () => { + let marker = 0 + const cleanups: Array<() => Promise> = [] + const errors = await checkCodeExecutionGate({ + app: "godot", + manifests: manifests(), + async probe() { + // An editor whose execute_code does what the GDScript it is given says: write a file. + const host = await startFakeHost({ + hostVersion: readPackage().version, + appVersion: "4.7.2-stable (official)", + capabilities: { + methods: ["hello", "context", "execute_code"], + operations: [], + undo: "grouped_best_effort", + background: false, + }, + methods: { + execute_code: (params) => { + const file = /FileAccess\.open\("([^"]+)"/.exec(String(params.code))?.[1] + if (file) writeFileSync(file, "ran") + return { status: "executed" } + }, + }, + }) + let answer: "allow" | "deny" = "allow" + const plugin = await loadPlugin({ + answer: (action) => { + if (action === "godot_execute_code" && answer === "deny") throw new Error("Permission denied") + }, + }) + cleanups.push(async () => { + await plugin.cleanup() + await host.close() + }) + assert.deepEqual(await plugin.rpc("advertise", announcement(host.endpoint, host.scriptHandle)), { + outcome: "accepted", + }) + return { + helloMethods: (host.hello.capabilities as { methods: string[] }).methods, + toolNames: [...plugin.tools.keys()], + async call(permission) { + answer = permission + marker += 1 + const file = join(scratch, `executed-${marker}.txt`).replaceAll("\\", "/") + const code = `FileAccess.open("${file}", FileAccess.WRITE).store_string("ran")` + const asked = plugin.permissions.length + let error: string | undefined + try { + await plugin.tool("godot_execute_code", { code }) + } catch (thrown) { + error = String(thrown) + } + return { + executed: existsSync(file), + permissionsAsked: plugin.permissions.slice(asked), + ...(error ? { error } : {}), + } + }, + } + }, + }) + for (const cleanup of cleanups.splice(0)) await cleanup() + assert.deepEqual(errors, []) +}) + +it("RPC sentinels stay out of every output and event, including bindingRead", async () => { + const plugin = await loadPlugin() + try { + const result = await runSentinelScenario( + { call: (method, input) => plugin.rpc(method, input as object), events: plugin.events }, + { sessionID: "ses_test", hostVersion: readPackage().version, appVersion: "4.7.2-stable (official)" }, + ) + assert.deepEqual(result.errors, []) + } finally { + await plugin.cleanup() + } +}) diff --git a/integrations/godot/test/godot.test.ts b/integrations/godot/test/godot.test.ts new file mode 100644 index 0000000..1469f8e --- /dev/null +++ b/integrations/godot/test/godot.test.ts @@ -0,0 +1,284 @@ +// OpenCode Link in a real Godot editor (GODOT_TEST_BIN, run --headless with private settings): installed by the +// plugin, offered to a private OpenCode service bound to the plugin's RPC, then every tool against it. Skipped +// without GODOT_TEST_BIN. + +import assert from "node:assert/strict" +import type { ChildProcess } from "node:child_process" +import { existsSync, mkdtempSync, readFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { after, before, describe, it } from "node:test" + +import { requestHost } from "../../../packages/integration-kit/src/index.ts" +import { installHost } from "../plugin/src/host-install.ts" +import { readPackage } from "../plugin/src/integration.ts" +import { + content, + fakeService, + type LoadedPlugin, + loadPlugin, + makeProject, + privateEnv, + removeAll, + startEditor, + until, +} from "./helpers.ts" + +const godot = process.env.GODOT_TEST_BIN +const SCENE = `[gd_scene format=3] + +[node name="Main" type="Node3D"] + +[node name="Box" type="MeshInstance3D" parent="."] +` +const MOVER = "extends Node3D\n\nfunc _process(_delta):\n\tposition.x += 1.0\n" +const CRASHER = 'extends Node\n\nfunc _ready():\n\tOS.crash("test crash")\n' +const CRASH_SCENE = `[gd_scene format=3] + +[ext_resource type="Script" path="res://crasher.gd" id="1"] + +[node name="Crash" type="Node"] +script = ExtResource("1") +` +const norm = (path: string) => path.replaceAll("\\", "/").replace(/\/$/, "").toLowerCase() + +describe("OpenCode Link in a real Godot editor", { skip: !godot, concurrency: false }, () => { + let root: string + let project: string + let plugin: LoadedPlugin + let service: Awaited> + let editor: ChildProcess + let log: string + const code = async (source: string, extra: object = {}) => + content(await plugin.tool("godot_execute_code", { code: source, ...extra })) + + before(async () => { + root = mkdtempSync(join(tmpdir(), "godot-real-")) + const env = privateEnv(root) + env.NEURALNOMADS_GODOT_NODE = process.execPath + project = makeProject("Trial", { + "main.tscn": SCENE, + "mover.gd": MOVER, + "crasher.gd": CRASHER, + "crash.tscn": CRASH_SCENE, + }) + assert.equal(installHost(readPackage().opencodeIntegration, project).outcome, "installed") + plugin = await loadPlugin({ directory: project }) + const global = norm(join(root, "config", "opencode")) + service = await fakeService(plugin, root, (directory) => norm(directory) === global) + log = join(root, "editor.log") + editor = startEditor(godot as string, project, env, log) + await until(() => plugin.registry.hosts().offers[0], 120_000, "the editor's offer") + }) + + after(async () => { + if (editor && editor.exitCode === null) editor.kill() + await plugin?.cleanup() + await service?.close() + await new Promise((done) => setTimeout(done, 500)) + removeAll(project, root) + }) + + it("offers the project from the editor's start, labelled with the project and its scene", async () => { + const offer = plugin.registry.hosts().offers[0] + assert.equal(offer?.label, "Godot: Trial — no scene") + assert.match(String(offer?.appVersion), /^4\.\d+/) + const hosts = content(await plugin.tool("godot_hosts")) + assert.equal(hosts.editors.length, 1) + assert.equal(hosts.host.state, "ok") + // The advertise went to the global configuration Location, where the plugin is loaded. + assert.ok(service.calls.some((call) => call.method === "advertise")) + }) + + it("runs GDScript in the editor; a change is one undo action", async () => { + await code('EditorInterface.open_scene_from_path("res://main.tscn")') + await until(() => plugin.registry.hosts().offers[0]?.label === "Godot: Trial — main.tscn", 15_000, "the new label") + const context = content(await plugin.tool("godot_context")) + assert.equal(context.scene.path, "res://main.tscn") + assert.deepEqual( + context.nodes.map((node: { path: string }) => node.path), + [".", "Box"], + ) + const changed = await code( + 'var crate := MeshInstance3D.new()\ncrate.name = "Crate"\nscene.add_child(crate)\ncrate.owner = scene\nscene.get_node("Box").position = Vector3(1, 2, 3)\nprint("added")\nresult = {"children": scene.get_child_count()}', + ) + assert.equal(changed.status, "executed") + assert.equal(changed.undo_step, "OpenCode: code") + assert.deepEqual(changed.changes, { properties: 1, added: ["Crate"] }) + assert.deepEqual(changed.result, { children: 2 }) + assert.equal(changed.stdout, "added\n") + // The editor's own undo puts both back, and redo brings them again. + const undone = await code( + 'var history := EditorInterface.get_editor_undo_redo().get_history_undo_redo(EditorInterface.get_editor_undo_redo().get_object_history_id(scene))\nresult.action = history.get_current_action_name()\nresult.undone = history.undo()\nresult.crate = scene.has_node("Crate")\nresult.box = scene.get_node("Box").position\nhistory.redo()\nresult.again = scene.has_node("Crate") and scene.get_node("Box").position == Vector3(1, 2, 3)', + { read_only: true }, + ) + assert.deepEqual(undone.result, { + action: "OpenCode: code", + undone: true, + crate: false, + box: [0, 0, 0], + again: true, + }) + }) + + it("a failed run is put back, with the line and what Godot knows", async () => { + const failed = await code( + 'scene.get_node("Box").position = Vector3(5, 5, 5)\nscene.add_child(Node3D.new())\nscene.get_node("Box").positon = Vector3.ZERO', + ) + assert.equal(failed.status, "failed") + assert.equal(failed.line, 3) + assert.equal(failed.restored, true) + assert.match(failed.message, /positon/) + assert.match(failed.hint, /position/) + const box = content(await plugin.tool("godot_context", { properties: ["position"], match: "Box" })) + assert.deepEqual(box.nodes[0].values.position, [1, 2, 3]) + assert.equal(box.nodes.length, 1) + + const parse = await code("var a = Vectr3(1, 2, 3)\nresult.a = a") + + assert.equal(parse.status, "failed") + assert.equal(parse.line, 1) + assert.match(parse.hint, /Vector3/) + const method = await code("scene.add_chlid(Node.new())") + assert.match(method.hint, /add_child\(node: Node/) + const missing = await code('scene.get_node("Bx").position = Vector3.ZERO') + assert.match(missing.hint, /No child Bx under Main; its children: Box/) + }) + + it("quarantines a failed run it cannot prove undone, until the agent releases it", async () => { + const failed = await code('scene.get_node("Crate").free()\nvar missing = null\nmissing.call("nothing")') + assert.equal(failed.status, "failed") + assert.equal(failed.restored, false) + assert.deepEqual(failed.quarantine.freed, ["Crate"]) + await assert.rejects(plugin.tool("godot_execute_code", { code: "pass" }), /quarantine/) + const read = content(await plugin.tool("godot_context")) + assert.equal(read.quarantined, true) + const released = content(await plugin.tool("godot_context", { release_quarantine: read.revision })) + assert.equal(released.released, true) + assert.equal((await code("pass")).status, "executed") + }) + + it("answers busy within 10 s while a run holds the main loop, and hello meanwhile", async () => { + const long = plugin.tool("godot_execute_code", { code: "OS.delay_msec(13000)", read_only: true }) + await new Promise((done) => setTimeout(done, 500)) + const offer = plugin.registry.hosts().offers[0] + const bound = plugin.registry.binding("ses_test") + assert.ok(offer && bound) + const started = Date.now() + await requestHost(bound.endpoint, "hello", {}, { timeoutMs: 2_000 }) + assert.ok(Date.now() - started < 2_000) + await assert.rejects(plugin.tool("godot_context"), /still running execute_code/) + assert.ok(Date.now() - started < 12_000) + assert.equal(content(await long).status, "executed") + }) + + it("inspects THIS Godot: search, a class with real signatures, a live node, the tree", async () => { + const found = content(await plugin.tool("godot_inspect", { search: "rigid body", limit: 10 })) + assert.match(found.godot, /^4\./) + assert.ok(found.search.results.some((item: { class: string }) => item.class === "RigidBody3D")) + const node3d = content(await plugin.tool("godot_inspect", { class: "Node3D", match: "look_at" })) + assert.ok(node3d.class.methods.some((method: string) => method.startsWith("look_at(target: Vector3"))) + assert.match(node3d.class.docs, /class_node3d\.html$/) + const box = content(await plugin.tool("godot_inspect", { node: "Box", tree: true })) + assert.equal(box.node.class, "MeshInstance3D") + assert.ok(box.tree.some((line: string) => line.includes("Box (MeshInstance3D)"))) + const typo = content(await plugin.tool("godot_inspect", { class: "Node3d" })) + assert.ok(typo.class.closest.includes("Node3D")) + }) + + it("verifies the open scene, saves it, and reads the saved file in a background Godot", async () => { + const criteria = [ + { expr: 'node("Box").position', op: "approx", value: [1, 2, 3], label: "box placed" }, + { expr: 'count("MeshInstance3D")', op: ">=", value: 1 }, + ] + const open = content(await plugin.tool("godot_verify", { criteria })) + assert.equal(open.passed, true, JSON.stringify(open)) + // Saving prints the editor's coloured progress: its output stays valid JSON. + const saved = content(await plugin.tool("godot_save")) + assert.equal(saved.path, "res://main.tscn") + assert.ok(saved.bytes > 0) + assert.equal(saved.unsaved, false) + const read = content(await plugin.tool("godot_verify", { criteria, saved: true, timeout_s: 120 })) + assert.equal(read.passed, true, JSON.stringify(read)) + assert.match(read.read.by, /file as written on disk/) + }) + + it("runs a working copy for frames to measure runtime values", async () => { + await code('scene.get_node("Box").set_script(load("res://mover.gd"))') + const ran = content( + await plugin.tool("godot_verify", { + criteria: [{ expr: 'node("Box").position.x', op: ">", value: 5 }], + frames: 10, + timeout_s: 120, + }), + ) + assert.equal(ran.passed, true, JSON.stringify(ran)) + assert.equal(ran.frames, 10) + }) + + it("runs scenes as tasks and says when the background Godot crashed", async () => { + const run = content(await plugin.tool("godot_run", { frames: 20, wait_s: 120 })) + assert.equal(run.state, "done", JSON.stringify(run)) + const crash = content(await plugin.tool("godot_run", { scene: "crash.tscn", frames: 20, wait_s: 120 })) + assert.equal(crash.state, "failed") + assert.match(crash.crash, /Program crashed/) + }) + + it("the dock reaches its sidecar (Node) from the editor", async () => { + await code( + 'var dock = EditorInterface.get_base_control().find_child("OpenCode", true, false)\nresult.found = dock != null\ndock.toggle_connection()', + ) + 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", + ) + assert.match(transcript, /Connect failed while finding this project's conversation|Start OpenCode/) + }) + + it("says that the editor crashed, with its log", async () => { + assert.ok(existsSync(log)) + await assert.rejects( + plugin.tool("godot_execute_code", { code: 'OS.crash("editor test crash")' }), + (error: Error) => { + assert.match(error.message, /^Godot crashed \(Godot: Trial — [^)]+\): crash report .*opencode-crash-\d+\.log/) + return true + }, + ) + assert.match(readFileSync(log, "utf8"), /Program crashed/) + }) +}) + +// The plugin declared in the project's own opencode.json only: the global configuration Location has no such RPC, so +// the editor offers itself at its project's folder. +describe("OpenCode Link offers itself at its project's folder when the plugin is loaded there only", { + skip: !godot, +}, () => { + it("advertises at the project's Location", async () => { + const root = mkdtempSync(join(tmpdir(), "godot-local-")) + const project = makeProject("Local", { "main.tscn": SCENE }) + installHost(readPackage().opencodeIntegration, project) + const plugin = await loadPlugin({ directory: project }) + const service = await fakeService(plugin, root, (directory) => norm(directory) === norm(project)) + const editor = startEditor(godot as string, project, privateEnv(root), join(root, "editor.log")) + try { + await until(() => plugin.registry.hosts().offers[0], 120_000, "the editor's offer") + const advertised = service.calls.filter((call) => call.method === "advertise") + assert.ok(advertised.length > 0) + assert.ok(advertised.every((call) => norm(String(call.directory)) === norm(project))) + assert.ok(service.calls.some((call) => norm(String(call.directory)) === norm(join(root, "config", "opencode")))) + } finally { + editor.kill() + await plugin.cleanup() + await service.close() + await new Promise((done) => setTimeout(done, 500)) + removeAll(project, root) + } + }) +}) diff --git a/integrations/godot/test/helpers.ts b/integrations/godot/test/helpers.ts new file mode 100644 index 0000000..838f274 --- /dev/null +++ b/integrations/godot/test/helpers.ts @@ -0,0 +1,263 @@ +import { type ChildProcess, spawn } from "node:child_process" +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { createServer, type IncomingMessage } from "node:http" +import { tmpdir } from "node:os" +import { join, resolve } from "node:path" +import type { Plugin } from "@opencode/plugin" +import type { Info, ToolContext } from "@opencode/plugin/promise/tool" +import { createOfferRegistry, HELLO_TIMEOUT_MS, requestHost } from "../../../packages/integration-kit/src/index.ts" +import { type GodotDeps, readPackage, setupGodot } from "../plugin/src/integration.ts" +import { resetMethodForTests } from "../plugin/src/method.ts" + +// A plugin storage as OpenCode keeps it: JSON values by key, scanned by prefix in key order. +export function memoryStorage() { + const values = new Map() + return { + values, + async get(key: string) { + return values.get(key) + }, + async set(key: string, value: unknown) { + values.set(key, structuredClone(value)) + }, + async remove(key: string) { + values.delete(key) + }, + async scan({ prefix, after, limit = 100 }: { prefix: string; after?: string; limit?: number }) { + const keys = [...values.keys()].filter((key) => key.startsWith(prefix) && (!after || key > after)).sort() + const page = keys.slice(0, limit) + return { + entries: page.map((key) => ({ key, value: values.get(key) })), + ...(keys.length > limit ? { next: page.at(-1) } : {}), + } + }, + } +} + +export type Asked = { action: string; resources: string[]; metadata?: Record } + +export async function loadPlugin( + input: { + now?: () => number + answer?: (action: string) => Promise | void + options?: object + env?: NodeJS.ProcessEnv + wsl?: () => boolean + storage?: ReturnType + // The conversation's folder (its Location). + directory?: string + shared?: boolean + spawn?: GodotDeps["spawn"] + } = {}, +) { + resetMethodForTests() + const marker = readPackage().opencodeIntegration + const host = marker.host as NonNullable + const registry = createOfferRegistry({ + expected: { protocol: host.protocol, range: host.range, appVersions: host.appVersions }, + now: input.now, + hello: (endpoint, scriptHandle) => + requestHost(endpoint, "hello", { script_handle: scriptHandle }, { timeoutMs: HELLO_TIMEOUT_MS }), + }) + const handlers: Record Promise> = {} + const events: Array<{ name: string; data: unknown }> = [] + const tools = new Map() + const permissions: string[] = [] + const asked: Asked[] = [] + const methods: Array<{ sessionID: string; key: string }> = [] + const location = { directory: resolve(input.directory ?? "test-location") } + const sessions = new Map(["ses_test", "ses_other"].map((id) => [id, { id, location: { ...location } }])) + const storage = input.storage ?? memoryStorage() + const ctx = { + options: input.options, + location, + storage, + session: { + get: async ({ sessionID }: { sessionID: string }) => { + const session = sessions.get(sessionID) + if (!session) throw new Error("not found") + return session + }, + instructions: { + entry: { + put: async ({ sessionID, key }: { sessionID: string; key: string }) => { + methods.push({ sessionID, key }) + }, + }, + }, + }, + rpc: { + register: async (_definition: unknown, registered: typeof handlers) => { + Object.assign(handlers, registered) + return { + events: { + emit: async (name: string, data: unknown) => { + events.push({ name, data }) + }, + }, + dispose: async () => {}, + } + }, + }, + tool: { + transform: async (callback: (editor: object) => void) => { + callback({ namespace: () => {}, add: (tool: Info) => tools.set(`godot_${tool.name}`, tool) }) + return { dispose: async () => {} } + }, + }, + permission: { + assert: async (request: Asked) => { + permissions.push(request.action) + asked.push({ + action: request.action, + resources: request.resources, + ...(request.metadata ? { metadata: request.metadata } : {}), + }) + await input.answer?.(request.action) + }, + }, + } as unknown as Plugin.Context + const cleanup = await setupGodot(ctx, { + registry: input.shared ? undefined : registry, + env: input.env ?? {}, + wsl: input.wsl ?? (() => false), + now: input.now, + spawn: input.spawn, + }) + const signal = new AbortController().signal + return { + registry: cleanup.internals.registry, + cleanup, + events, + permissions, + asked, + methods, + tools, + storage, + sessions, + location, + rpc: async (name: string, payload: object = {}) => handlers[name]?.(payload, { signal }), + tool: async (name: string, payload: object = {}, sessionID = "ses_test") => { + const tool = tools.get(name) + if (!tool) throw new Error(`No tool ${name}`) + return tool.execute( + payload as never, + { sessionID, signal, agent: "build", messageID: "msg_test", id: "call_test" } as ToolContext, + ) + }, + } +} + +export type LoadedPlugin = Awaited> + +// What a tool returned, as JSON (the text part of a result with attachments). +export function content(result: unknown) { + const value = (result as { content?: unknown })?.content ?? result + const text = Array.isArray(value) ? (value.find((part) => part?.type === "text")?.text ?? "") : value + return JSON.parse(String(text)) +} + +export function announcement( + endpoint: { host: string; port: number; token: string }, + scriptHandle: string, + offerKey = "test-offer", + label = "Godot: Trial — main.tscn", +) { + return { ...endpoint, script_handle: scriptHandle, label, protocol: 1, offer_key: offerKey } +} + +// A Godot project of the test's own: project.godot, a scene, and optionally the add-on from the host folder. +export function makeProject(name = "Trial", files: Record = {}) { + const dir = mkdtempSync(join(tmpdir(), "godot-project-")) + writeFileSync(join(dir, "project.godot"), `config_version=5\n\n[application]\n\nconfig/name="${name}"\n`) + for (const [file, text] of Object.entries(files)) { + mkdirSync(join(dir, file, ".."), { recursive: true }) + writeFileSync(join(dir, file), text) + } + return dir +} + +export const addonSource = join(import.meta.dirname, "..", "host", "addons", "opencode_link") + +async function body(request: IncomingMessage): Promise { + let text = "" + for await (const chunk of request) text += chunk + return text ? JSON.parse(text) : null +} + +// An OpenCode service of the test's own, registered in a private state folder: /api/info, and the plugin's RPC at the +// Locations where it is "loaded" (others answer rpc.unavailable, as a Location without the plugin). +export async function fakeService(plugin: LoadedPlugin, root: string, loadedAt: (directory: string) => boolean) { + const password = "service-password-sentinel" + const calls: Array<{ method: string; directory: string | null }> = [] + const server = createServer(async (request, response) => { + const url = new URL(request.url ?? "/", "http://127.0.0.1") + const send = (status: number, value: unknown) => { + response.writeHead(status, { "content-type": "application/json" }) + response.end(JSON.stringify(value)) + } + if (request.headers.authorization !== `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`) + return send(401, { type: "unauthorized" }) + if (request.method === "GET" && url.pathname === "/api/info") + return send(200, { pid: process.pid, version: "2.2.5" }) + const match = /^\/api\/rpc\/neuralnomads\.godot\/([^/]+)$/.exec(url.pathname) + if (request.method === "POST" && match) { + 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" }) + return send(200, { output: await plugin.rpc(match[1] ?? "", input as object) }) + } + send(404, { type: "not_found" }) + }) + await new Promise((done) => server.listen(0, "127.0.0.1", () => done())) + const port = (server.address() as { port: number }).port + mkdirSync(join(root, "state", "opencode"), { recursive: true }) + writeFileSync( + join(root, "state", "opencode", "service.json"), + JSON.stringify({ url: `http://127.0.0.1:${port}`, pid: process.pid, version: "2.2.5", password }), + ) + return { calls, close: () => new Promise((done) => server.close(() => done())) } +} + +// The private folders of a Godot run: its settings (APPDATA, XDG), OpenCode's registrations, the user's home. +export function privateEnv(root: string): NodeJS.ProcessEnv { + const home = join(root, "home") + for (const dir of ["home", "appdata", "localappdata", "config", "data", "cache", "state"]) + mkdirSync(join(root, dir), { recursive: true }) + return { + ...process.env, + HOME: home, + USERPROFILE: home, + APPDATA: join(root, "appdata"), + LOCALAPPDATA: join(root, "localappdata"), + XDG_CONFIG_HOME: join(root, "config"), + XDG_DATA_HOME: join(root, "data"), + XDG_CACHE_HOME: join(root, "cache"), + XDG_STATE_HOME: join(root, "state"), + } +} + +// A Godot editor without a window (--headless) on a project where OpenCode Link is installed, writing its log. +export function startEditor(godot: string, project: string, env: NodeJS.ProcessEnv, log: string): ChildProcess { + return spawn(godot, ["--headless", "--editor", "--path", project, "--log-file", log], { + env, + windowsHide: true, + stdio: "ignore", + }) +} + +// Waits for a condition, polling. +export async function until(read: () => T | Promise, timeoutMs: number, what: string): Promise> { + const deadline = Date.now() + timeoutMs + for (;;) { + const value = await read() + if (value) return value as NonNullable + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`) + await new Promise((done) => setTimeout(done, 250)) + } +} + +export function removeAll(...dirs: string[]) { + for (const dir of dirs) rmSync(dir, { recursive: true, force: true, maxRetries: 5 }) +} diff --git a/integrations/godot/test/install.test.ts b/integrations/godot/test/install.test.ts new file mode 100644 index 0000000..003a595 --- /dev/null +++ b/integrations/godot/test/install.test.ts @@ -0,0 +1,36 @@ +// project.godot keeps every line it had when OpenCode Link is enabled in it. + +import assert from "node:assert/strict" +import { it } from "node:test" + +import { enabledIn, enablePlugin, PLUGIN_CFG } from "../plugin/src/host-install.ts" + +const ENTRY = `"${PLUGIN_CFG}"` + +it("adds the [editor_plugins] section when the project has none", () => { + const text = 'config_version=5\n\n[application]\n\nconfig/name="Game"\n' + const enabled = enablePlugin(text) + assert.equal(enabled, `${text}\n[editor_plugins]\n\nenabled=PackedStringArray(${ENTRY})\n`) + assert.deepEqual(enabledIn(enabled), [PLUGIN_CFG]) +}) + +it("adds the add-on next to the project's other editor plugins, in their section", () => { + const text = + '[application]\n\nconfig/name="Game"\n\n[editor_plugins]\n\nenabled=PackedStringArray("res://addons/other/plugin.cfg")\n\n[rendering]\n\nx=1\n' + const enabled = enablePlugin(text) + assert.equal( + enabled, + `[application]\n\nconfig/name="Game"\n\n[editor_plugins]\n\nenabled=PackedStringArray("res://addons/other/plugin.cfg", ${ENTRY})\n\n[rendering]\n\nx=1\n`, + ) + assert.deepEqual(enabledIn(enabled), ["res://addons/other/plugin.cfg", PLUGIN_CFG]) +}) + +it("fills an empty list and a section without one, keeping CRLF line ends", () => { + assert.deepEqual(enabledIn(enablePlugin("[editor_plugins]\n\nenabled=PackedStringArray()\n")), [PLUGIN_CFG]) + const crlf = '[editor_plugins]\r\n\r\n[gui]\r\n\r\ntheme="x"\r\n' + const enabled = enablePlugin(crlf) + assert.equal(enabled, `[editor_plugins]\r\n\r\nenabled=PackedStringArray(${ENTRY})\r\n[gui]\r\n\r\ntheme="x"\r\n`) + assert.deepEqual(enabledIn(enabled), [PLUGIN_CFG]) + // The list of another section is not this one's. + assert.deepEqual(enabledIn('[other]\nenabled=PackedStringArray("res://x")\n'), []) +}) diff --git a/integrations/godot/test/panel.test.ts b/integrations/godot/test/panel.test.ts new file mode 100644 index 0000000..1c70871 --- /dev/null +++ b/integrations/godot/test/panel.test.ts @@ -0,0 +1,386 @@ +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/godot/test/plugin.test.ts b/integrations/godot/test/plugin.test.ts new file mode 100644 index 0000000..224ce32 --- /dev/null +++ b/integrations/godot/test/plugin.test.ts @@ -0,0 +1,392 @@ +// OpenCode for Godot 0.1.0 against a fake installed part: the tools are the manifests', the conversation attaches +// itself to the only free editor, the working method joins it, code runs only with permission, the fixed programs +// ask none, and OpenCode Link installs into a Godot project. + +import assert from "node:assert/strict" +import { createHash } from "node:crypto" +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { describe, it } from "node:test" + +import { readStoredZip } from "../../../packages/integration-kit/src/zip.ts" +import { startFakeHost } from "../../../packages/testing/src/index.ts" +import { inspectHost } from "../plugin/src/host-install.ts" +import { readPackage } from "../plugin/src/integration.ts" +import { METHOD_KEY, METHOD_TEXT } from "../plugin/src/method.ts" +import { methodsDir, packageRoot } from "../plugin/src/paths.ts" +import { programCode } from "../plugin/src/programs.ts" +import { announcement, content, loadPlugin, makeProject } from "./helpers.ts" + +const version = readPackage().version +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +function capabilities(methods: string[]) { + return { + methods: [...new Set(["hello", "status", "context", "release", ...methods])], + operations: [], + undo: "grouped_best_effort" as const, + background: false, + } +} + +async function offered( + methods: Record) => unknown> = {}, + process?: { pid: number; temp_dir: string }, +) { + return await startFakeHost({ + hostVersion: version, + appVersion: "4.7.2-stable (official)", + capabilities: capabilities(Object.keys(methods)), + methods: { context: () => ({ revision: 3, nodes: [] }), ...methods }, + ...(process ? { helloOverride: (hello: Record) => ({ ...hello, process }) } : {}), + }) +} + +describe("OpenCode for Godot 0.1.0", () => { + it("registers one tool per manifest, under its manifest name", async () => { + const plugin = await loadPlugin() + try { + const names = readdirSync(join(methodsDir, "tools")) + .filter((file) => file.endsWith(".json")) + .map((file) => (JSON.parse(readFileSync(join(methodsDir, "tools", file), "utf8")) as { name: string }).name) + assert.deepEqual([...plugin.tools.keys()].sort(), names.sort()) + assert.deepEqual(names.sort(), [ + "godot_context", + "godot_execute_code", + "godot_hosts", + "godot_inspect", + "godot_install_host", + "godot_run", + "godot_save", + "godot_verify", + ]) + assert.ok(METHOD_TEXT.split("\n").length <= 10) + } finally { + await plugin.cleanup() + } + }) + + it("attaches the only free editor at the first call, with the working method; listing asks no permission", async () => { + const plugin = await loadPlugin() + const host = await offered() + try { + await plugin.rpc("advertise", announcement(host.endpoint, host.scriptHandle)) + const listed = content(await plugin.tool("godot_hosts")) + assert.equal(listed.editors.length, 1) + assert.equal(listed.attached_to, null) + const read = content(await plugin.tool("godot_context")) + assert.equal(read.revision, 3) + assert.equal(read.attached_to.label, "Godot: Trial — main.tscn") + assert.deepEqual(plugin.methods, [{ sessionID: "ses_test", key: METHOD_KEY }]) + assert.deepEqual(plugin.permissions, []) + await assert.rejects(plugin.tool("godot_context", {}, "ses_other"), /attached to another conversation/) + const shared = content(await plugin.tool("godot_hosts", { attach: listed.editors[0].offerID }, "ses_other")) + assert.match(shared.shared, /Another conversation is attached to this Godot too/) + assert.deepEqual(plugin.asked, [ + { + action: "godot_attach", + resources: ["Godot: Trial — main.tscn"], + metadata: { label: "Godot: Trial — main.tscn" }, + }, + ]) + } finally { + await plugin.cleanup() + await host.close() + } + }) + + // The dock attaches its conversation through the attachHost RPC, next to a CodeNomad conversation attached to the same + // project: both stay attached, and either one's detach leaves the other (no lock). + it("the dock's conversation and another one are attached to the same editor together", async () => { + const plugin = await loadPlugin() + const host = await offered() + try { + await plugin.rpc("advertise", announcement(host.endpoint, host.scriptHandle)) + const offerID = content(await plugin.tool("godot_hosts")).editors[0].offerID + assert.equal(content(await plugin.tool("godot_hosts", { attach: offerID })).attached, "attached") + assert.deepEqual(await plugin.rpc("attachHost", { offerID, sessionID: "ses_other" }), { outcome: "attached" }) + assert.equal(content(await plugin.tool("godot_context", {}, "ses_other")).revision, 3) + assert.deepEqual(await plugin.rpc("detachHost", { sessionID: "ses_other" }), { outcome: "detached" }) + assert.equal(content(await plugin.tool("godot_context")).attached_to.offerID, offerID) + } finally { + await plugin.cleanup() + await host.close() + } + }) + + it("two editors with the same label are said; attaching one of them asks godot_attach", async () => { + let deny = true + const plugin = await loadPlugin({ + answer: () => { + if (deny) throw new Error("Permission denied") + }, + }) + const first = await offered() + const second = await offered() + try { + await plugin.rpc("advertise", announcement(first.endpoint, first.scriptHandle, "first")) + assert.equal(content(await plugin.tool("godot_hosts")).same_label, undefined) + await plugin.rpc("advertise", announcement(second.endpoint, second.scriptHandle, "second")) + const listed = content(await plugin.tool("godot_hosts")) + assert.match(listed.same_label, /Several Godot editors show the same project and scene/) + await assert.rejects(plugin.tool("godot_context"), /godot_hosts attach/) + await assert.rejects(plugin.tool("godot_hosts", { attach: listed.editors[1].offerID }), /Permission denied/) + assert.equal(((await plugin.rpc("bindingRead", { sessionID: "ses_test" })) as { state: string }).state, "none") + deny = false + await plugin.tool("godot_hosts", { attach: listed.editors[1].offerID }) + assert.equal(content(await plugin.tool("godot_context")).attached_to.offerID, listed.editors[1].offerID) + } finally { + await plugin.cleanup() + await first.close() + await second.close() + } + }) + + it("says how to offer a project when none is", async () => { + const plugin = await loadPlugin() + try { + await assert.rejects( + plugin.tool("godot_context"), + /No Godot editor is offered: open the project in Godot 4\.7 or later with OpenCode Link installed in it \(godot_install_host\)/, + ) + } finally { + await plugin.cleanup() + } + }) + + it("execute_code asks godot_execute_code with the code for each run, reads a script file as is", async () => { + const plugin = await loadPlugin() + const dir = mkdtempSync(join(tmpdir(), "godot-script-")) + const runs: Array> = [] + const host = await offered({ + execute_code: (params) => { + runs.push(params) + return { status: "executed", result: { ok: 1 }, changed: true, undo_step: "OpenCode: code" } + }, + }) + try { + await plugin.rpc("advertise", announcement(host.endpoint, host.scriptHandle)) + const code = "result.count = scene.get_child_count()" + const out = content(await plugin.tool("godot_execute_code", { code, read_only: true })) + assert.deepEqual([out.status, out.result], ["executed", { ok: 1 }]) + assert.deepEqual(plugin.asked, [{ action: "godot_execute_code", resources: ["*"], metadata: { code } }]) + assert.deepEqual(runs[0], { session_id: "ses_test", code, read_only: true, script_handle: host.scriptHandle }) + const file = join(dir, "build.gd") + writeFileSync(file, 'func run():\n\tprint("é")\n') + await plugin.tool("godot_execute_code", { path: file }) + assert.equal(runs[1]?.code, 'func run():\n\tprint("é")\n') + assert.equal(runs[1]?.filename, file) + assert.deepEqual(plugin.asked[1], { + action: "godot_execute_code", + resources: [file], + metadata: { path: file, code: runs[1]?.code }, + }) + await assert.rejects(plugin.tool("godot_execute_code", { code: "x", path: file }), /code or path, not both/) + assert.equal(runs.length, 2) + } finally { + await plugin.cleanup() + await host.close() + rmSync(dir, { recursive: true, force: true }) + } + }) + + it("execute_code is refused before any permission when the editor does not list it", async () => { + const plugin = await loadPlugin() + const host = await offered() + try { + await plugin.rpc("advertise", announcement(host.endpoint, host.scriptHandle)) + await assert.rejects(plugin.tool("godot_execute_code", { code: "pass" }), /Code execution is not available/) + assert.deepEqual(plugin.permissions, []) + } finally { + await plugin.cleanup() + await host.close() + } + }) + + it("fixed programs take parameters as data; executing criteria asks permission", async () => { + const plugin = await loadPlugin() + const runs: Array> = [] + const host = await offered({ + execute_code: (params) => { + runs.push(params) + return { status: "executed", result: { passed: true, path: "res://main.tscn", copy: false } } + }, + }) + try { + await plugin.rpc("advertise", announcement(host.endpoint, host.scriptHandle)) + await plugin.tool("godot_inspect", { search: "rigid body" }) + const criteria = [{ expr: 'node("Box").position.x', op: ">", value: 0 }] + assert.equal(content(await plugin.tool("godot_verify", { criteria })).passed, true) + assert.match(content(await plugin.tool("godot_save")).check, /godot_verify with saved: true/) + assert.deepEqual(plugin.permissions, ["godot_execute_code"]) + assert.deepEqual( + runs.map((run) => [run.code, run.params, run.read_only]), + [ + [programCode("inspect"), { search: "rigid body", limit: 40, depth: 6 }, true], + [programCode("verify"), { criteria, errors: true }, true], + [programCode("save"), { copy: false, overwrite: false }, true], + ], + ) + await assert.rejects(plugin.tool("godot_inspect", {}), /Give search, class, node and\/or tree/) + } finally { + await plugin.cleanup() + await host.close() + } + }) + + it("a refusal reads the hint for its code with Godot's own text and data", async () => { + const plugin = await loadPlugin() + const host = await offered({ + release: () => { + throw { + code: "stale_revision", + message: "Read the scene again (godot_context) and release with its revision.", + data: { current_revision: 7, reason: "revision_conflict" }, + } + }, + }) + try { + await plugin.rpc("advertise", announcement(host.endpoint, host.scriptHandle)) + await assert.rejects( + plugin.tool("godot_context", { release_quarantine: 2 }), + /^Error: The scene changed since your last read: call godot_context and use its revision\. Read the scene again \(godot_context\) and release with its revision\. \{"current_revision":7,"reason":"revision_conflict"\}$/, + ) + } finally { + await plugin.cleanup() + await host.close() + } + }) + + it("a call that outlasts its wait says Godot still runs it (status off the main thread)", async () => { + const temp = mkdtempSync(join(tmpdir(), "godot_temp-")) + const plugin = await loadPlugin() + const host = await offered( + { + execute_code: () => sleep(5_000).then(() => ({ status: "executed" })), + status: () => ({ busy: true, running: "execute_code", seconds: 1.2, queued: 0 }), + }, + { pid: process.pid, temp_dir: temp }, + ) + try { + await plugin.rpc("advertise", announcement(host.endpoint, host.scriptHandle)) + await assert.rejects( + plugin.tool("godot_execute_code", { code: "OS.delay_msec(5000)", timeout_s: 1 }), + /Godot is still running execute_code \(1\.2 s so far\): it goes on in Godot, nothing is lost/, + ) + } finally { + await plugin.cleanup() + await host.close() + rmSync(temp, { recursive: true, force: true }) + } + }) + + it("installs OpenCode Link into the conversation's project, idempotently; never over another add-on", async () => { + const project = makeProject("Install") + const plugin = await loadPlugin({ directory: project }) + const elsewhere = await loadPlugin({ directory: tmpdir() }) + try { + const marker = readPackage().opencodeIntegration + const host = marker.host as NonNullable + const archive = readFileSync(join(packageRoot, host.payload)) + assert.equal(createHash("sha256").update(archive).digest("hex"), host.sha256) + const names = readStoredZip(archive).map((entry) => entry.name) + for (const file of ["plugin.cfg", "plugin.gd", "link.gd", "service.gd", "runner.gd", "hints.gd", "dock.gd"]) + assert.ok(names.includes(`addons/opencode_link/${file}`), file) + assert.ok(names.includes("addons/opencode_link/sidecar.cjs")) + + assert.equal(((await plugin.rpc("status")) as { host: { state: string } }).host.state, "absent") + assert.deepEqual(inspectHost(project), { kind: "not-found" }) + assert.deepEqual(await plugin.rpc("installHost"), { + outcome: "installed", + detail: + "Restart this project's Godot editor if it is open: OpenCode Link offers the project to OpenCode when the editor starts.", + }) + assert.deepEqual(inspectHost(project), { kind: "found", version }) + assert.match(readFileSync(join(project, "project.godot"), "utf8"), /^config\/name="Install"$/m) + assert.match( + readFileSync(join(project, "project.godot"), "utf8"), + /\[editor_plugins\]\n\nenabled=PackedStringArray\("res:\/\/addons\/opencode_link\/plugin\.cfg"\)\n$/, + ) + assert.equal(((await plugin.rpc("status")) as { host: { state: string } }).host.state, "unknown") + assert.deepEqual(await plugin.rpc("installHost"), { outcome: "unchanged" }) + assert.deepEqual(readdirSync(join(project, "addons")), ["opencode_link"]) + + // An older version is replaced whole. + const cfg = join(project, "addons", "opencode_link", "plugin.cfg") + writeFileSync(cfg, readFileSync(cfg, "utf8").replace(/version="[^"]+"/, 'version="0.0.9"')) + writeFileSync(join(project, "addons", "opencode_link", "stale.gd"), "") + assert.equal(((await plugin.rpc("status")) as { host: { state: string } }).host.state, "outdated") + assert.equal(((await plugin.rpc("installHost")) as { outcome: string }).outcome, "updated") + assert.equal(existsSync(join(project, "addons", "opencode_link", "stale.gd")), false) + + // Another add-on of the same folder name is left untouched. + rmSync(join(project, "addons", "opencode_link"), { recursive: true }) + mkdirSync(join(project, "addons", "opencode_link")) + writeFileSync(cfg, '[plugin]\nname="Someone else"\n') + assert.equal(((await plugin.rpc("installHost")) as { outcome: string }).outcome, "refused") + assert.equal(readFileSync(cfg, "utf8"), '[plugin]\nname="Someone else"\n') + + // A conversation outside any Godot project: nothing to install into. + assert.equal(((await elsewhere.rpc("installHost")) as { outcome: string }).outcome, "refused") + assert.equal(((await elsewhere.rpc("status")) as { host: { state: string } }).host.state, "unknown") + } finally { + await plugin.cleanup() + await elsewhere.cleanup() + rmSync(project, { recursive: true, force: true }) + } + }) + + it("godot_install_host asks its permission for the project it names; a WSL daemon refuses", async () => { + const project = makeProject("Named") + const plugin = await loadPlugin({ directory: tmpdir() }) + const wsl = await loadPlugin({ directory: project, wsl: () => true }) + try { + await assert.rejects(plugin.tool("godot_install_host", { project: tmpdir() }), /not a Godot project folder/) + assert.equal(content(await plugin.tool("godot_install_host", { project })).outcome, "installed") + assert.deepEqual(plugin.asked, [{ action: "godot_install_host", resources: [project] }]) + rmSync(join(project, "addons"), { recursive: true }) + assert.equal(((await wsl.rpc("status")) as { host: { state: string } }).host.state, "unsupported") + assert.equal(((await wsl.rpc("installHost")) as { outcome: string }).outcome, "refused") + assert.equal(existsSync(join(project, "addons")), false) + } finally { + await plugin.cleanup() + await wsl.cleanup() + rmSync(project, { recursive: true, force: true }) + } + }) + + it("attaches only this Location's conversations: ownership, detach, renewal and expiry", async () => { + let now = 10_000 + const plugin = await loadPlugin({ now: () => now }) + const host = await offered() + try { + const announced = announcement(host.endpoint, host.scriptHandle) + assert.deepEqual(await plugin.rpc("advertise", { ...announced, host: "localhost" }), { outcome: "refused" }) + assert.deepEqual(await plugin.rpc("advertise", { ...announced, token: "0".repeat(64) }), { outcome: "refused" }) + assert.deepEqual(await plugin.rpc("advertise", { ...announced, label: "Godot: a/b" }), { outcome: "refused" }) + assert.deepEqual(await plugin.rpc("advertise", announced), { outcome: "accepted" }) + // The label follows the edited scene: a renewal with the new label keeps the offer. + const offerID = plugin.registry.hosts().offers[0]?.offerID as string + assert.deepEqual(await plugin.rpc("advertise", { ...announced, label: "Godot: Trial — level.tscn" }), { + outcome: "renewed", + }) + assert.deepEqual( + plugin.registry.hosts().offers.map((offer) => [offer.offerID, offer.label]), + [[offerID, "Godot: Trial — level.tscn"]], + ) + assert.deepEqual(await plugin.rpc("attachHost", { offerID, sessionID: "ses_foreign" }), { outcome: "refused" }) + assert.deepEqual(await plugin.rpc("attachHost", { offerID, sessionID: "ses_test" }), { outcome: "attached" }) + plugin.sessions.set("ses_test", { id: "ses_test", location: { directory: join(tmpdir(), "foreign") } }) + assert.deepEqual(await plugin.rpc("bindingRead", { sessionID: "ses_test" }), { state: "unknown" }) + plugin.sessions.set("ses_test", { id: "ses_test", location: { ...plugin.location } }) + assert.deepEqual(await plugin.rpc("detachHost", { sessionID: "ses_test" }), { outcome: "detached" }) + now += 15_001 + assert.deepEqual(await plugin.rpc("hosts"), { offers: [] }) + assert.ok(plugin.events.every(({ data }) => JSON.stringify(data) === "{}")) + } finally { + await plugin.cleanup() + await host.close() + } + }) +}) diff --git a/integrations/godot/test/registry.test.ts b/integrations/godot/test/registry.test.ts new file mode 100644 index 0000000..09cd538 --- /dev/null +++ b/integrations/godot/test/registry.test.ts @@ -0,0 +1,63 @@ +// An upgrade without restarting OpenCode: the daemon loaded an older OpenCode for Godot, then this version in the same +// process. This version's offer list, named after its host contract, never reuses the older one, which judges hellos +// by the older range. + +import assert from "node:assert/strict" +import { after, it } from "node:test" + +import { + createOfferRegistry, + offerRegistryKey, + offerRegistryName, +} from "../../../packages/integration-kit/src/index.ts" +import { startFakeHost } from "../../../packages/testing/src/index.ts" +import { readPackage } from "../plugin/src/integration.ts" +import { announcement, loadPlugin } from "./helpers.ts" + +const marker = readPackage().opencodeIntegration +const host = marker.host as NonNullable +const expected = { protocol: host.protocol, range: host.range, appVersions: host.appVersions } +const store = globalThis as unknown as Record +const older = { ...expected, range: "^0.0.1" } +const keys = [ + offerRegistryKey(offerRegistryName("godot", older)), + offerRegistryKey(offerRegistryName("godot", expected)), +] +after(() => { + for (const key of keys) delete store[key] +}) + +it("a plugin loaded after an older version in the same process judges its own host ok", async () => { + const fake = await startFakeHost({ hostVersion: readPackage().version, appVersion: "4.7.2-stable (official)" }) + const previous = createOfferRegistry({ expected: older }) + store[offerRegistryKey(offerRegistryName("godot", older))] = { generation: 2, registry: previous } + const plugin = await loadPlugin({ shared: true }) + try { + assert.notEqual(plugin.registry, previous, "this version keeps its own list") + assert.deepEqual(await plugin.rpc("advertise", announcement(fake.endpoint, fake.scriptHandle, "after")), { + outcome: "accepted", + }) + assert.deepEqual( + plugin.registry.hosts().offers.map((offer) => offer.protocol), + ["ok"], + ) + await previous.advertise(announcement(fake.endpoint, fake.scriptHandle, "after")) + assert.equal(previous.hosts().offers[0]?.protocol, "incompatible") + } finally { + await plugin.cleanup() + await fake.close() + } +}) + +it("an editor of a Godot older than 4.7 is incompatible", async () => { + const fake = await startFakeHost({ hostVersion: readPackage().version, appVersion: "4.5.2-stable (official)" }) + const plugin = await loadPlugin() + try { + await plugin.rpc("advertise", announcement(fake.endpoint, fake.scriptHandle)) + assert.equal(plugin.registry.hosts().offers[0]?.protocol, "incompatible") + assert.equal(((await plugin.rpc("status")) as { host: { state: string } }).host.state, "incompatible") + } finally { + await plugin.cleanup() + await fake.close() + } +}) diff --git a/integrations/godot/test/tasks.test.ts b/integrations/godot/test/tasks.test.ts new file mode 100644 index 0000000..e402fe1 --- /dev/null +++ b/integrations/godot/test/tasks.test.ts @@ -0,0 +1,132 @@ +// Background Godots: what their log says (errors, a crash), their state as a task, and a read stopped past its time. + +import assert from "node:assert/strict" +import { spawn } from "node:child_process" +import { existsSync, mkdtempSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { it } from "node:test" + +import { + cancelTask, + crashOf, + describeStep, + errorsOf, + startBackground, + taskStatus, + waitResult, +} from "../plugin/src/tasks.ts" + +const LOG = `Godot Engine v4.7.2.stable.official +OPENCODE_STEP {"step":"load","at_s":0} +SCRIPT ERROR: Invalid access to property or key 'speed' on a base object of type 'null instance'. + at: _process (res://player.gd:12) +ERROR: Condition "!is_inside_tree()" is true. Returning: Transform3D() + at: get_global_transform (scene/3d/node_3d.cpp:348) +OPENCODE_STEP {"step":"running","frames":10,"at_s":0.2} + +================================================================ +CrashHandlerException: Program crashed with signal 11 +Engine version: Godot Engine v4.7.2.stable.official +Dumping the backtrace. +[1] 7ff6 (main+40d4d03) +-- END OF C++ BACKTRACE -- +` + +it("reads errors and a crash from a background Godot's log", () => { + assert.deepEqual(errorsOf(LOG), [ + "SCRIPT ERROR: Invalid access to property or key 'speed' on a base object of type 'null instance'. (at: _process (res://player.gd:12))", + 'ERROR: Condition "!is_inside_tree()" is true. Returning: Transform3D() (at: get_global_transform (scene/3d/node_3d.cpp:348))', + ]) + assert.match(String(crashOf(LOG)), /^CrashHandlerException: Program crashed with signal 11 \| Engine version/) + assert.equal(crashOf("all fine"), undefined) + assert.equal(describeStep({ step: "running", frames: 10 }, "res://main.tscn"), "running 10 frames of res://main.tscn") + assert.equal(describeStep(undefined, "x"), "starting (Godot had not loaded the scene yet)") +}) + +// A stand-in for Godot: Node, told what to do by its arguments, writing its log where Godot's --log-file says. +const standIn = (behaviour: string) => (_command: string, args: string[]) => { + const log = args[args.indexOf("--log-file") + 1] as string + return spawn(process.execPath, ["-e", behaviour, log], { windowsHide: true, stdio: "ignore" }) +} + +const work = () => mkdtempSync(join(tmpdir(), "godot-task-")) + +it("a run is running, then done when Godot exits 0; failed with its crash otherwise", async () => { + const ok = startBackground( + { kind: "run", executable: "godot", project: "p", args: [], work: work(), scene: "res://main.tscn", frames: 10 }, + standIn("require('fs').writeFileSync(process.argv[1], 'started\\n'); setTimeout(() => {}, 300)"), + ) + assert.equal(taskStatus(ok).state, "running") + await new Promise((done) => setTimeout(done, 1_500)) + assert.equal(taskStatus(ok).state, "done") + assert.equal(taskStatus(ok).exit_code, 0) + + const crashed = startBackground( + { kind: "run", executable: "godot", project: "p", args: [], work: work(), scene: "res://crash.tscn", frames: 10 }, + standIn(`require('fs').writeFileSync(process.argv[1], ${JSON.stringify(LOG)}); process.exit(3)`), + ) + await new Promise((done) => setTimeout(done, 1_500)) + const status = taskStatus(crashed) + assert.equal(status.state, "failed") + assert.match(String(status.crash), /Program crashed with signal 11.*The open editor is not affected/) + assert.equal(status.errors?.length, 2) + + const capture = startBackground( + { + kind: "capture", + executable: "godot", + project: "p", + args: [], + work: work(), + scene: "res://main.tscn", + frames: 3, + movie: "frame.png", + }, + standIn("require('fs').writeFileSync(process.argv[1], '')"), + ) + await new Promise((done) => setTimeout(done, 1_500)) + assert.equal(taskStatus(capture).state, "failed") + assert.match(String(taskStatus(capture).error), /Movie Maker wrote no frame/) +}) + +it("cancel stops a running Godot", async () => { + const task = startBackground( + { kind: "run", executable: "godot", project: "p", args: [], work: work(), scene: "s", frames: 1 }, + standIn("setTimeout(() => {}, 60000)"), + ) + await new Promise((done) => setTimeout(done, 300)) + assert.equal(cancelTask(task).state, "cancelled") + await new Promise((done) => setTimeout(done, 1_000)) + assert.notEqual(task.finished, undefined) +}) + +it("a read past timeout_s is stopped and says what Godot was doing; a result is read back", async () => { + const slow = work() + const task = startBackground( + { kind: "verify", executable: "godot", project: "p", args: [], work: slow, scene: "res://main.tscn", frames: 600 }, + standIn( + `require('fs').writeFileSync(process.argv[1], 'OPENCODE_STEP {"step":"running","frames":600}\\n'); setTimeout(() => {}, 60000)`, + ), + ) + await assert.rejects( + waitResult(task, join(slow, "result.json"), 1), + /stopped the background Godot after 1 s \(timeout_s\): it was running 600 frames of res:\/\/main\.tscn/, + ) + const fast = work() + const result = join(fast, "result.json") + const done = startBackground( + { kind: "verify", executable: "godot", project: "p", args: [], work: fast, scene: "res://main.tscn", frames: 0 }, + standIn(`require('fs').writeFileSync(${JSON.stringify(result)}, JSON.stringify({ passed: true }))`), + ) + assert.deepEqual(await waitResult(done, result, 30), { passed: true }) + await new Promise((resolve) => setTimeout(resolve, 1_500)) + assert.equal(existsSync(fast), false, "its folder is removed once it has exited") + const stopped = work() + writeFileSync(join(stopped, "unused"), "") + const quits = startBackground( + { kind: "verify", executable: "godot", project: "p", args: [], work: stopped, scene: "res://main.tscn", frames: 0 }, + standIn(`require('fs').writeFileSync(process.argv[1], ${JSON.stringify(LOG)}); process.exit(1)`), + ) + await assert.rejects(waitResult(quits, join(stopped, "result.json"), 30), /crashed while running 10 frames/) +}) diff --git a/package-lock.json b/package-lock.json index d5b04d7..4099357 100644 --- a/package-lock.json +++ b/package-lock.json @@ -56,7 +56,25 @@ }, "integrations/gaffer/plugin": { "name": "@neuralnomads/opencode-gaffer", - "version": "0.2.0", + "version": "0.3.0", + "license": "MIT", + "devDependencies": { + "@opencode/client": "2.2.5", + "@opencode/plugin": "2.2.5", + "esbuild": "0.28.2" + }, + "peerDependencies": { + "@opencode/plugin": "^2.2.0 || ^0.0.0-dev" + }, + "peerDependenciesMeta": { + "@opencode/plugin": { + "optional": true + } + } + }, + "integrations/godot/plugin": { + "name": "@neuralnomads/opencode-godot", + "version": "0.1.0", "license": "MIT", "devDependencies": { "@opencode/client": "2.2.5", @@ -74,7 +92,7 @@ }, "integrations/houdini/plugin": { "name": "@neuralnomads/opencode-houdini", - "version": "0.3.0", + "version": "0.3.1", "license": "MIT", "devDependencies": { "@opencode/client": "2.2.5", @@ -1405,6 +1423,10 @@ "resolved": "integrations/gaffer/plugin", "link": true }, + "node_modules/@neuralnomads/opencode-godot": { + "resolved": "integrations/godot/plugin", + "link": true + }, "node_modules/@neuralnomads/opencode-houdini": { "resolved": "integrations/houdini/plugin", "link": true diff --git a/package.json b/package.json index f77455c..25daffb 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "scripts": { "lint": "biome check .", "format": "biome format --write .", - "typecheck": "tsc -b packages/integration-kit && tsc -p packages/integration-kit/test && tsc -p packages/testing && tsc -p scripts && tsc -p integrations/affinity/plugin && tsc -p integrations/blender/plugin && tsc -p integrations/gaffer/plugin && tsc -p integrations/houdini/plugin && tsc -p integrations/m365/plugin && tsc -p integrations/resolve/plugin", + "typecheck": "tsc -b packages/integration-kit && tsc -p packages/integration-kit/test && tsc -p packages/testing && tsc -p scripts && tsc -p integrations/affinity/plugin && tsc -p integrations/blender/plugin && tsc -p integrations/gaffer/plugin && tsc -p integrations/godot/plugin && tsc -p integrations/houdini/plugin && tsc -p integrations/m365/plugin && tsc -p integrations/resolve/plugin", "build": "npm run build --workspaces --if-present", "test": "node --test \"packages/*/test/**/*.test.ts\" \"scripts/test/**/*.test.ts\" \"integrations/*/test/**/*.test.ts\"", "check:markers": "node packages/testing/src/cli.ts", From 0fa839985dbdd3c773bc1adba2745a8bddf73cdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Wed, 18 Nov 2026 12:57:57 +0100 Subject: [PATCH 2/2] fix(godot): detach hidden dock and retain the previous addon on install failure --- .../godot/host/addons/opencode_link/dock.gd | 9 +++++- .../godot/host/addons/opencode_link/link.gd | 9 ++++-- .../plugin/host/godot/opencode_link-0.1.0.zip | Bin 179665 -> 180080 bytes integrations/godot/plugin/package.json | 2 +- integrations/godot/plugin/src/closed.ts | 3 +- integrations/godot/plugin/src/host-install.ts | 29 ++++++++++++++++-- 6 files changed, 43 insertions(+), 9 deletions(-) diff --git a/integrations/godot/host/addons/opencode_link/dock.gd b/integrations/godot/host/addons/opencode_link/dock.gd index f92b726..193d24a 100644 --- a/integrations/godot/host/addons/opencode_link/dock.gd +++ b/integrations/godot/host/addons/opencode_link/dock.gd @@ -37,6 +37,10 @@ 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" @@ -107,7 +111,7 @@ func _ready() -> void: func _exit_tree() -> void: if _active: - _send("close", {}) + disconnect_dock() if _stdio != null: # The sidecar ends once its input closes, after releasing its conversations. _stdio.close() @@ -142,6 +146,9 @@ func disconnect_dock() -> void: _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 diff --git a/integrations/godot/host/addons/opencode_link/link.gd b/integrations/godot/host/addons/opencode_link/link.gd index 919de20..5e96802 100644 --- a/integrations/godot/host/addons/opencode_link/link.gd +++ b/integrations/godot/host/addons/opencode_link/link.gd @@ -216,6 +216,9 @@ func pump() -> void: func _on_main(label: String, work: Callable, session_id: String) -> Variant: var job := {"label": label, "work": work, "state": "queued", "result": null, "done": Semaphore.new(), "session": session_id} _mutex.lock() + if _cancelled.has(session_id): + _mutex.unlock() + return error("busy", "The conversation was stopped before Godot ran this request.", {"reason": "cancelled"}) _jobs.append(job) _mutex.unlock() var asked := Time.get_ticks_msec() @@ -415,18 +418,18 @@ func _handle(peer: StreamPeerTCP) -> void: var request_id: Variant = null while true: peer.poll() - if peer.get_status() != StreamPeerTCP.STATUS_CONNECTED or Time.get_ticks_msec() > until: + if _stopping or peer.get_status() != StreamPeerTCP.STATUS_CONNECTED or Time.get_ticks_msec() > until: break var available := peer.get_available_bytes() if available > 0: - buffer.append_array(peer.get_partial_data(available)[1]) + buffer.append_array(peer.get_partial_data(mini(available, MAX_REQUEST_BYTES + 1 - buffer.size()))[1]) if buffer.find(10) >= 0 or buffer.size() > MAX_REQUEST_BYTES: break else: OS.delay_msec(2) var newline := buffer.find(10) var result: Variant - if newline < 0: + if newline < 0 or newline >= MAX_REQUEST_BYTES: result = error("invalid_request", "Godot host request exceeded the size limit" if buffer.size() > MAX_REQUEST_BYTES else "Incomplete request") else: var parser := JSON.new() diff --git a/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip b/integrations/godot/plugin/host/godot/opencode_link-0.1.0.zip index 9b5109bb0aeba5423ca0cb01c917d41a8a4a67cb..c34731cecbf25d1712beee0f034c693523f912c0 100644 GIT binary patch delta 490 zcmccko9n|rt_@`@Tzl`!g`^rXFr*r8ZeVd>P0lRNOv=p3EUAo7&PdElPfgKF&d6>%%A4~GY7nkH06lCV5E94hV_Uk-vmYbQEsgYQgn3PKHYx#)P{>Oy&&kY7Rj{+g)M>>v`B%4U z^S`e4e_f2*|8+6t86bt~^s?PdQB3S+lMSbePk*_aNkRtUHwFe724vtC3RY#ZhsluX z@&quuZV!_Q)4GW;Hv9BTdzf^XwoC&GC`?z_%cRBh_cd5Dc`uU*^K2=`$$|Z1(>Ls8 Ml4jeuhY4sn0M3f2l>h($ delta 251 zcmezHkL%)Zt_@`@Tv@)E4F?Sv7!De2ZeVd>-K@?P&pG*%sL1A-!dsa(_lTXa^jGpSeBTXlbDo~I(cdLMkXt+$uoOZo9Fhl z&+TE{KDUP{&j87W>7sj?qL`9Rrx)&J(w9LP%fKMRfD9IefK-T2zr2^pkjbPU!jav_ zWWvNh0nTBcUbv4*he>oQL}c4OCS#_!S76R$gEw5$dG<4DG5?WZoP2Sb*mVE>Oww#Z JyP1Ht0044URh<9; diff --git a/integrations/godot/plugin/package.json b/integrations/godot/plugin/package.json index eb45a21..359f6d3 100644 --- a/integrations/godot/plugin/package.json +++ b/integrations/godot/plugin/package.json @@ -62,7 +62,7 @@ "range": "^0.1.0", "appVersions": ">=4.7 <5", "payload": "host/godot/opencode_link-0.1.0.zip", - "sha256": "5d6ce783792f9b2233c6a576f82d465ef869b02543aedf80d5ab6432ff853790" + "sha256": "49bde399ddbaf859baae7d6686f8b4ee849ef82b15fad28fc132db9b7b0a5b2b" } } } diff --git a/integrations/godot/plugin/src/closed.ts b/integrations/godot/plugin/src/closed.ts index ff10ef7..906e8fd 100644 --- a/integrations/godot/plugin/src/closed.ts +++ b/integrations/godot/plugin/src/closed.ts @@ -31,5 +31,6 @@ export const { crashReport, closedMessage, silentMessage } = crashWatch({ appName: "Godot", app: "godot", part: "OpenCode Link", - isReport: (name, host) => name.endsWith(".log") && CRASHED.test(logTail(join(host.tempDir, name))), + isReport: (name, host) => + name === `opencode-crash-${host.pid}.log` && CRASHED.test(logTail(join(host.tempDir, name))), }) diff --git a/integrations/godot/plugin/src/host-install.ts b/integrations/godot/plugin/src/host-install.ts index 25d50e0..8d3099c 100644 --- a/integrations/godot/plugin/src/host-install.ts +++ b/integrations/godot/plugin/src/host-install.ts @@ -90,6 +90,9 @@ export function installHost(marker: IntegrationMarker, project?: string): Instal if (same && enabled) return { outcome: "unchanged" } const staging = join(folder, "addons", `.opencode_link-${randomUUID()}`) const previous = join(folder, "addons", `.opencode_link-old-${randomUUID()}`) + const temporary = `${settingsFile}-${randomUUID()}` + let movedPrevious = false + let movedNew = false try { if (!same) { for (const entry of entries) { @@ -97,18 +100,38 @@ export function installHost(marker: IntegrationMarker, project?: string): Instal mkdirSync(dirname(file), { recursive: true }) writeFileSync(file, entry.data) } - if (existsSync(target)) renameSync(target, previous) + if (existsSync(target)) { + renameSync(target, previous) + movedPrevious = true + } renameSync(staging, target) + movedNew = true } if (!enabled) { - const temporary = `${settingsFile}-${randomUUID()}` writeFileSync(temporary, enablePlugin(settings)) + if (readFileSync(settingsFile, "utf8") !== settings) + throw new Error("Project settings changed during installation.") renameSync(temporary, settingsFile) } + } catch { + try { + if (movedNew) rmSync(target, { recursive: true, force: true }) + if (movedPrevious) renameSync(previous, target) + } catch { + return { + outcome: "failed", + detail: "Installation failed; the previous add-on may need restoring from addons/.opencode_link-old-*.", + } + } + return { + outcome: "failed", + detail: "Could not write the add-on or project settings. Close the editor before retrying.", + } } finally { rmSync(staging, { recursive: true, force: true }) - rmSync(previous, { recursive: true, force: true }) + rmSync(temporary, { force: true }) } + rmSync(previous, { recursive: true, force: true }) return { outcome: cfg && !same ? "updated" : "installed", detail: