## Chat sessions on disk, as JSON Lines under user://.claude-godot/sessions/. ## ## A .chat file is JSON Lines with one non-JSON line at the top: ## ## # CHAT: v1.0 ## {"type":"session", …} ## {"type":"message", …} ## {"type":"reasoning", …} ## ## The marker names the format and its version in a way that survives being ## opened in anything — a reader that only knows JSON skips it as a comment. ## Then a header line describing the session, one line per message exactly as ## it goes to the provider, and the reasoning. Resuming is reading the lines ## back, and the file doubles as a portable transcript of the real context. ## ## Because the message lines are in the provider's own wire format, a ## session is tied to the protocol that produced it. The header records ## which, and resuming switches the dock to that provider rather than ## feeding Responses API items to an Anthropic endpoint. class_name ClaudeGodotSessionStore extends RefCounted const DIR := "user://.claude-godot/sessions" const EXTENSION := ".chat" ## Bumped when the shape changes in a way a reader must notice. const VERSION := "1.0" const MARKER := "# CHAT: v" + VERSION ## Sessions written before the format was named. Still read, never written. const LEGACY_EXTENSION := ".jsonl" static func _ensure_dir() -> void: DirAccess.make_dir_recursive_absolute(DIR) static func path_for(session_id: String) -> String: var path := "%s/%s%s" % [DIR, session_id, EXTENSION] if FileAccess.file_exists(path): return path var legacy := "%s/%s%s" % [DIR, session_id, LEGACY_EXTENSION] return legacy if FileAccess.file_exists(legacy) else path ## Sortable and filename-safe: 2026-09-12T16-30-00. static func new_session_id() -> String: return Time.get_datetime_string_from_system(false, false).replace(":", "-") static func save(session_id: String, body: String) -> Dictionary: _ensure_dir() # Always writes the current extension, even when resuming a legacy file. var f := FileAccess.open("%s/%s%s" % [DIR, session_id, EXTENSION], FileAccess.WRITE) if f == null: return {"error": "Could not write session %s: %s" % [session_id, error_string(FileAccess.get_open_error())]} f.store_string(MARKER + "\n" + body) f.close() return {} ## Returns {"header", "messages", "reasoning"} or {"error": String}. ## Unknown line types are skipped rather than failing the load, so a file ## written by a newer format version still opens for the parts we know. static func load_session(session_id: String) -> Dictionary: var path := path_for(session_id) if not FileAccess.file_exists(path): return {"error": "No session named %s." % session_id} var f := FileAccess.open(path, FileAccess.READ) if f == null: return {"error": "Could not read %s: %s" % [path, error_string(FileAccess.get_open_error())]} var text := f.get_as_text() f.close() var header := {} var messages: Array = [] var reasoning: Array = [] var version := "" for line in text.split("\n"): var trimmed := line.strip_edges() if trimmed == "": continue if trimmed.begins_with("# CHAT:"): version = trimmed.trim_prefix("# CHAT:").strip_edges().trim_prefix("v") continue var json := JSON.new() if json.parse(line) != OK: continue var entry = json.get_data() if not (entry is Dictionary): continue if entry.get("type", "") == "session": header = entry elif entry.get("type", "") == "message" and entry.has("message"): messages.append(entry["message"]) elif entry.get("type", "") == "reasoning": reasoning.append({ "after_message": int(entry.get("after_message", 0)), "text": str(entry.get("text", "")), }) return {"header": header, "messages": messages, "reasoning": reasoning, "version": version} ## Newest first: [{id, modified, provider, model, messages, title}]. static func delete(session_id: String) -> Dictionary: var path := path_for(session_id) if not FileAccess.file_exists(path): return {"error": "No session named %s." % session_id} var err := DirAccess.remove_absolute(ProjectSettings.globalize_path(path)) if err != OK: return {"error": "Could not delete %s: %s" % [session_id, error_string(err)]} return {} static func list_sessions() -> Array: _ensure_dir() var dir := DirAccess.open(DIR) if dir == null: return [] var found: Array = [] dir.list_dir_begin() var name := dir.get_next() while name != "": if not dir.current_is_dir() and (name.ends_with(EXTENSION) or name.ends_with(LEGACY_EXTENSION)): var session_id := name.trim_suffix(EXTENSION).trim_suffix(LEGACY_EXTENSION) var loaded := load_session(session_id) if not loaded.has("error"): var header: Dictionary = loaded["header"] found.append({ "id": session_id, "modified": FileAccess.get_modified_time(path_for(session_id)), "provider": header.get("provider", ""), "model": header.get("model", ""), "messages": (loaded["messages"] as Array).size(), # The model's own title when it named the session, the # first thing the user asked when it hasn't yet. "title": header.get("title", "") if str(header.get("title", "")) != "" else _title_of(loaded["messages"]), "titled": str(header.get("title", "")) != "", "objective": header.get("objective", ""), "keywords": header.get("keywords", []), }) name = dir.get_next() dir.list_dir_end() found.sort_custom(func(a, b): return a["modified"] > b["modified"]) return found ## Fallback title: the first thing the user actually typed, dug out of ## whichever wire shape this session was recorded in, so an unnamed session ## still reads as something in the dropdown. static func _title_of(messages: Array) -> String: for message in messages: if not (message is Dictionary) or message.get("role", "") != "user": continue var content = message.get("content", "") if content is String: return _clip(content) if content is Array: for part in content: if not (part is Dictionary): continue # "text" is Chat Completions, "input_text" is the Responses API. if part.get("type", "") in ["text", "input_text"]: return _clip(str(part.get("text", ""))) return "(no user message)" static func _clip(text: String) -> String: var single_line := text.strip_edges().replace("\n", " ") return single_line if single_line.length() <= 50 else single_line.substr(0, 50) + "…"