## Server-sent events over HTTPClient. ## ## HTTPRequest hands you the body only once it is complete, which is no use ## for streaming, so this drives HTTPClient directly: connect, send, then ## read body chunks as they arrive, cutting them into SSE events and handing ## each parsed one to a callback. ## ## It polls between awaits on process_frame rather than blocking, so the ## editor keeps drawing while a response streams in. class_name ClaudeGodotStreamClient extends Node ## Set by cancel(); checked in every wait loop. var _cancel_requested := false func cancel() -> void: _cancel_requested = true ## Sends one request and feeds each SSE event to on_event as a Dictionary. ## Returns {"status": int, "body": String} — body is the raw text, which for ## a non-200 carries the provider's error payload — or {"error": String}. func stream(url: String, headers: Array, body: String, on_event: Callable, timeout: float) -> Dictionary: _cancel_requested = false var parsed := _split_url(url) if parsed.is_empty(): return {"error": "Malformed URL: %s" % url} var http := HTTPClient.new() var err := http.connect_to_host(parsed["host"], parsed["port"], TLSOptions.client() if parsed["tls"] else null) if err != OK: return {"error": "Could not start a connection to %s: %s" % [parsed["host"], error_string(err)]} # timeout <= 0 means no deadline: a reasoning model can legitimately take # minutes, and the dock's Stop button cancels a request that is stuck. var deadline := -1 if timeout > 0.0: deadline = Time.get_ticks_msec() + int(timeout * 1000.0) while http.get_status() in [HTTPClient.STATUS_CONNECTING, HTTPClient.STATUS_RESOLVING]: http.poll() var waited := await _tick(deadline) if waited != "": return {"error": waited} if http.get_status() != HTTPClient.STATUS_CONNECTED: return {"error": ClaudeGodotHttpError.transport_error(HTTPRequest.RESULT_CANT_CONNECT, url, timeout)} err = http.request(HTTPClient.METHOD_POST, parsed["path"], PackedStringArray(headers), body) if err != OK: return {"error": "Could not send the request to %s: %s" % [parsed["host"], error_string(err)]} while http.get_status() == HTTPClient.STATUS_REQUESTING: http.poll() var waited := await _tick(deadline) if waited != "": return {"error": waited} if not http.has_response(): return {"error": ClaudeGodotHttpError.transport_error(HTTPRequest.RESULT_NO_RESPONSE, url, timeout)} var status := http.get_response_code() var raw := PackedByteArray() var pending := "" while http.get_status() == HTTPClient.STATUS_BODY: http.poll() var chunk := http.read_response_body_chunk() if chunk.size() > 0: raw.append_array(chunk) # Only a 2xx is a stream; anything else is an error document and # is returned whole for the caller to report. if status == 200: pending += chunk.get_string_from_utf8() pending = _drain_events(pending, on_event) else: var waited := await _tick(deadline) if waited != "": return {"error": waited} http.close() return {"status": status, "body": raw.get_string_from_utf8()} ## Waits a frame. Returns "" to continue, or why the wait ended. func _tick(deadline: int) -> String: if _cancel_requested: return "Cancelled." if deadline > 0 and Time.get_ticks_msec() > deadline: return "The provider stopped responding partway through the stream." await get_tree().process_frame return "" ## Consumes whole SSE events from the buffer, returning the incomplete tail. ## Events are separated by a blank line, and a partial one at the end of a ## chunk has to wait for the rest rather than being parsed as truncated JSON. func _drain_events(buffer: String, on_event: Callable) -> String: while true: var split := buffer.find("\n\n") if split == -1: return buffer var block := buffer.substr(0, split) buffer = buffer.substr(split + 2) for line in block.split("\n"): if not line.begins_with("data:"): continue var payload := line.substr(5).strip_edges() if payload == "" or payload == "[DONE]": continue var json := JSON.new() if json.parse(payload) != OK: continue var event = json.get_data() if event is Dictionary: on_event.call(event) return buffer static func _split_url(url: String) -> Dictionary: var tls := url.begins_with("https://") var rest := url.trim_prefix("https://").trim_prefix("http://") var slash := rest.find("/") var authority := rest.substr(0, slash) if slash != -1 else rest var path := rest.substr(slash) if slash != -1 else "/" if authority == "": return {} var port := 443 if tls else 80 var colon := authority.rfind(":") if colon != -1: port = int(authority.substr(colon + 1)) authority = authority.substr(0, colon) return {"host": authority, "port": port, "path": path, "tls": tls}