- app/: app demo (Kivy/buildozer) da API do robo - software/: servidor RoboMovel (SLAM, profundidade, navegacao) e firmware da base movel (movido de firmware/) - simulacao/: projeto Godot do robo e script de lancamento servidor + simulacao - modelos/: planta do 5o andar do bloco D, cena Blender do corredor e modelo real do robo - partes/mdf/: chapas identificadas e nesting da base do robo (DXF/SVG/FCStd) - projeto/render, relatorio/imagens, slides: renders finais e apresentacoes de progresso - ferramentas/scripts: encaixe de chapas, planta do bloco D e render do corredor no Blender - .gitignore: ignora backups do Blender/FreeCAD e .godot/ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
695 lines
29 KiB
GDScript
695 lines
29 KiB
GDScript
class_name ClaudeGodotAgent
|
|
extends Node
|
|
|
|
signal turn_started
|
|
signal assistant_text(text: String)
|
|
## Commentary the model makes before acting (Responses API "reasoning" items,
|
|
## Anthropic "thinking" blocks, OpenAI-compatible reasoning/reasoning_content).
|
|
signal assistant_reasoning(text: String)
|
|
signal step_limit_reached(steps: int)
|
|
signal tool_call(tool_name: String, input: Dictionary)
|
|
signal tool_result(tool_name: String, result: Dictionary)
|
|
signal turn_finished
|
|
signal agent_error(message: String)
|
|
signal usage_updated(total_input_tokens: int, total_output_tokens: int)
|
|
## The dock swapped to a different session — rebuild the transcript.
|
|
signal session_changed(session_id: String)
|
|
## The model gave the current session a title.
|
|
signal session_described(title: String)
|
|
## Live progress while a response streams: characters seen so far this turn.
|
|
signal stream_progress(characters: int)
|
|
## A message typed while a turn was running, waiting its turn.
|
|
signal message_queued(id: int, text: String)
|
|
## That message is now being sent for real.
|
|
signal message_dequeued(id: int, text: String)
|
|
signal message_cancelled(id: int)
|
|
## A background task moved: a step, a tool call, or the end of the run.
|
|
signal background_task_changed(run: ClaudeGodotTaskRun)
|
|
## …and once, when it ends, so the dock can say so without watching for it.
|
|
signal background_task_finished(run: ClaudeGodotTaskRun)
|
|
## The conversation was compacted: the earlier messages were replaced by a
|
|
## summary, freeing context. `source` is "auto", "manual" or "overflow".
|
|
signal context_compacted(before_tokens: int, after_tokens: int, source: String)
|
|
|
|
|
|
## Compaction is what keeps a long session alive: when the context nears the
|
|
## model's window, the earlier messages are replaced by a summary the model
|
|
## writes itself, and the most recent turns are kept. Two things trigger it —
|
|
## the threshold below, and the `compact` tool when the user asks.
|
|
##
|
|
## The window is not read from providers.csv (it differs per model and per
|
|
## release): it comes from the context_window preference, with an optional
|
|
## context_window:<model> override, and a conservative default otherwise.
|
|
const DEFAULT_CONTEXT_WINDOW := 128_000
|
|
const COMPACT_TRIGGER_RATIO := 0.8
|
|
## Budget for the tail kept verbatim, as a fraction of the window.
|
|
const COMPACT_TAIL_RATIO := 0.25
|
|
## Real user turns kept after the summary, budget permitting.
|
|
const COMPACT_KEEP_USER_TURNS := 2
|
|
## Below this many messages there is nothing worth summarizing.
|
|
const COMPACT_MIN_MESSAGES := 6
|
|
|
|
const COMPACT_PROMPT := "Your task is to summarize the conversation above so it can be continued in a smaller context. Reply with the summary only, in plain text, and do not call any tools.\n\nWrite in the same language the user has been using. Cover, concretely:\n1. What the user asked for, including any correction or change of direction they gave.\n2. What you did, and the state you left things in — files and settings touched with their paths, and which changes were actually applied.\n3. Errors hit and how they were resolved.\n4. What is still unfinished, and the next step.\n5. Any fact needed to continue: a decision, a constraint, an id.\n\nBe specific about file paths and names, and do not pad it — a summary too long to read is no better than none."
|
|
|
|
## Written in front of the summary when it goes back into the history, so a
|
|
## later turn reads it as its own notes rather than as something the user
|
|
## said.
|
|
const COMPACT_SUMMARY_PREFIX := "[The earlier part of this conversation was compacted to free context. Below is your own summary of it, followed by the most recent turns kept verbatim. Treat the summary as notes, not proof: verify anything load-bearing before relying on it.]\n\n"
|
|
|
|
|
|
## Untyped on purpose: the two provider classes are duck-typed (model, api_key,
|
|
## reset(), add_user_message(), add_tool_results(), step(), cancel()) rather
|
|
## than sharing a common base class, so static typing here would reject
|
|
## valid calls.
|
|
var provider
|
|
var preset: Dictionary = ClaudeGodotProviderPresets.get_preset("anthropic")
|
|
|
|
var total_input_tokens := 0
|
|
var total_output_tokens := 0
|
|
## Only what the provider actually reported charging. Stays 0 where none
|
|
## does, which the dock shows as unknown rather than as free.
|
|
var total_cost := 0.0
|
|
var total_cached_tokens := 0
|
|
var total_reasoning_tokens := 0
|
|
|
|
var session_id := ClaudeGodotSessionStore.new_session_id()
|
|
## Set by the update_session_description tool; empty until the model names
|
|
## the session, which is what triggers the nudge in _system_prompt().
|
|
var session_title := ""
|
|
var session_objective := ""
|
|
var session_keywords: Array = []
|
|
## A resume asked for mid-turn. Applying it immediately would append the
|
|
## pending tool_result to a history where its tool_use doesn't exist, which
|
|
## every provider rejects — so it waits for the turn to end.
|
|
var _pending_resume := ""
|
|
## Like a resume: restarting mid-turn would tear down the dock hosting the
|
|
## call. Deferred to the end of the turn, after the session is saved.
|
|
var _pending_restart := false
|
|
|
|
## Cap on model calls per user message, so a tool loop can't run away. On
|
|
## hitting it the agent doesn't just stop: it makes one more call with no
|
|
## tools offered, so the model has to answer in plain text and can tell the
|
|
## user where it got to. Override in preferences.csv as max_steps_per_turn.
|
|
var max_steps_per_turn := int(ClaudeGodotPreferences.get_value("max_steps_per_turn", "25"))
|
|
## Streaming is what makes the live indicator possible. Set to false in
|
|
## preferences.csv to fall back to waiting for whole responses.
|
|
var streaming := ClaudeGodotPreferences.get_value("streaming", "true") != "false"
|
|
var _streamed_characters := 0
|
|
## Reasoning captured this session. Two of the three protocols keep thinking
|
|
## in the wire history already; Chat Completions doesn't, and it must not be
|
|
## sent back (DeepSeek documents reasoning_content as not for resubmission),
|
|
## so it is recorded here instead and written as its own lines.
|
|
var _session_reasoning: Array = []
|
|
|
|
## Messages typed mid-turn. They can't go straight into the history — a user
|
|
## message landing between a tool_use and its tool_result makes the next
|
|
## request invalid — so they wait here and are released one per turn end,
|
|
## the way kimi-code drains its nudge queue.
|
|
var _queue: Array = []
|
|
var _next_queue_id := 1
|
|
var _turn_running := false
|
|
|
|
## Task ids already announced as finished. A run emits `changed` on its last
|
|
## step and again on ending, so without this the dock would report the same
|
|
## finish twice.
|
|
var _announced_tasks: Dictionary = {}
|
|
|
|
## Input tokens of the most recent request, i.e. the size the next one starts
|
|
## from. Distinct from total_input_tokens, which accumulates across the whole
|
|
## session; this is what the compaction threshold is measured against.
|
|
var _last_input_tokens := 0
|
|
## At most one compaction per turn: one that did not bring the count down
|
|
## would otherwise re-run on every step and spend the turn summarizing.
|
|
var _compacted_this_turn := false
|
|
## Set by the compact tool, handled at the top of the next step.
|
|
var _pending_compact := false
|
|
var _pending_compact_instruction := ""
|
|
## Guards the summary call from re-entering the turn loop's compaction check.
|
|
var _compacting := false
|
|
|
|
|
|
func _ready() -> void:
|
|
set_preset("anthropic")
|
|
# The agent parents the background runs: they need a place in the tree for
|
|
# their HTTP requests, and they have to outlive the turn that started them.
|
|
ClaudeGodotBackgroundTasks.bind(self, _on_background_task_changed)
|
|
|
|
## Everything a background run needs to be this same agent working elsewhere:
|
|
## the provider it is pointed at, and the tools it may use.
|
|
##
|
|
## Gathered here, and handed down, because a run must not reach back into the
|
|
## tool registry: the registry preloads the `task` tool that starts runs, so a
|
|
## lookup in the other direction closes a reference cycle.
|
|
func background_task_context() -> Dictionary:
|
|
return {
|
|
"preset": preset,
|
|
"model": provider.model if provider else "",
|
|
"api_key": provider.api_key if provider else "",
|
|
"tools": ClaudeGodotTools.get_tool_definitions(ClaudeGodotTaskRun.DENIED_TOOLS),
|
|
"execute": func(tool_name: String, input: Dictionary) -> Dictionary:
|
|
return ClaudeGodotTools.execute(tool_name, input),
|
|
}
|
|
|
|
## A background run made progress or ended. Forwarded so the dock can redraw
|
|
## without polling, and announced once when a run finishes so a result isn't
|
|
## sitting unread in a tool the model never thinks to call again.
|
|
func _on_background_task_changed(run: ClaudeGodotTaskRun) -> void:
|
|
background_task_changed.emit(run)
|
|
if not run.is_running() and not _announced_tasks.has(run.id):
|
|
_announced_tasks[run.id] = true
|
|
background_task_finished.emit(run)
|
|
|
|
## Swaps the active provider. Existing conversation history (and the token
|
|
## counter) is reset since each provider keeps history in its own wire format.
|
|
func set_preset(preset_id: String, model_override: String = "", api_key: String = "") -> void:
|
|
if provider:
|
|
provider.queue_free()
|
|
|
|
preset = ClaudeGodotProviderPresets.get_preset(preset_id)
|
|
provider = ClaudeGodotAgentConfig.build_provider(preset, model_override, api_key, streaming)
|
|
provider.stream_delta.connect(_on_stream_delta)
|
|
add_child(provider)
|
|
|
|
total_input_tokens = 0
|
|
total_output_tokens = 0
|
|
total_cost = 0.0
|
|
total_cached_tokens = 0
|
|
total_reasoning_tokens = 0
|
|
usage_updated.emit(0, 0)
|
|
|
|
func reset() -> void:
|
|
provider.reset()
|
|
total_input_tokens = 0
|
|
total_output_tokens = 0
|
|
total_cost = 0.0
|
|
total_cached_tokens = 0
|
|
total_reasoning_tokens = 0
|
|
usage_updated.emit(0, 0)
|
|
|
|
## Whether the selected model is known to accept images. Unknown (no entry
|
|
## in providers.csv) counts as yes: the attempt is worth making, and a
|
|
## provider that refuses now reports why precisely.
|
|
func supports_vision() -> bool:
|
|
var known: Dictionary = preset.get("model_vision", {})
|
|
var model: String = provider.model if provider else ""
|
|
return bool(known.get(model, true))
|
|
|
|
## The model's context window, in tokens. The per-model preference comes
|
|
## first, then the general one, then the default; anything blank or
|
|
## non-numeric falls through.
|
|
func context_window() -> int:
|
|
var model: String = provider.model if provider else ""
|
|
var per_model := ClaudeGodotPreferences.get_value("context_window:" + model, "")
|
|
if per_model.is_valid_int() and int(per_model) > 0:
|
|
return int(per_model)
|
|
var general := ClaudeGodotPreferences.get_value("context_window", "")
|
|
if general.is_valid_int() and int(general) > 0:
|
|
return int(general)
|
|
return DEFAULT_CONTEXT_WINDOW
|
|
|
|
## Auto-compaction can be turned off (preferences.csv `auto_compact=false`) to
|
|
## leave only the compact tool, for someone who would rather choose when.
|
|
func auto_compact_enabled() -> bool:
|
|
return ClaudeGodotPreferences.get_value("auto_compact", "true") != "false"
|
|
|
|
## Whether the next step should compact first. Measured against the previous
|
|
## request's own reported input count — the real size of the context — rather
|
|
## than an estimate from characters.
|
|
func should_auto_compact() -> bool:
|
|
if not auto_compact_enabled() or _compacted_this_turn or _pending_compact or _compacting:
|
|
return false
|
|
if _last_input_tokens <= 0 or provider == null:
|
|
return false
|
|
if provider.get_history().size() < COMPACT_MIN_MESSAGES:
|
|
return false
|
|
return _last_input_tokens >= int(context_window() * COMPACT_TRIGGER_RATIO)
|
|
|
|
## Replaces the earlier messages with a summary the model writes itself,
|
|
## keeping the most recent turns verbatim. Returns true when the history was
|
|
## replaced.
|
|
##
|
|
## The summary is asked for through the same provider, so it costs one call
|
|
## and its usage is counted. If that call overflows — the context is already
|
|
## too big for it — the last tool output is dropped and it is retried once,
|
|
## which is what lets compaction serve as overflow recovery and not only as
|
|
## prevention.
|
|
func compact_conversation(source: String, instruction: String) -> bool:
|
|
if provider == null or _compacting:
|
|
return false
|
|
var history_before: Array = provider.get_history()
|
|
if history_before.size() < COMPACT_MIN_MESSAGES:
|
|
return false
|
|
|
|
_compacting = true
|
|
var before_tokens := _last_input_tokens
|
|
var prompt := COMPACT_PROMPT
|
|
if instruction.strip_edges() != "":
|
|
prompt += "\n\nExtra instruction from the user for this summary:\n" + instruction.strip_edges()
|
|
|
|
provider.add_user_message(prompt)
|
|
var result: Dictionary = await provider.step(_system_prompt(), [])
|
|
if result.has("error") and _is_context_overflow(str(result["error"])):
|
|
provider.shrink_last_tool_results("[removed to make room to compact the conversation]")
|
|
result = await provider.step(_system_prompt(), [])
|
|
if result.has("error"):
|
|
provider.set_history(history_before)
|
|
_compacting = false
|
|
agent_error.emit("Compaction failed, keeping the conversation as it was: %s" % result["error"])
|
|
return false
|
|
_report_usage(result)
|
|
|
|
var summary := ""
|
|
for t in result.get("text", []):
|
|
if t != null and str(t) != "":
|
|
summary += ("\n" if summary != "" else "") + str(t)
|
|
if summary.strip_edges() == "":
|
|
provider.set_history(history_before)
|
|
_compacting = false
|
|
agent_error.emit("Compaction produced no summary; the conversation was left unchanged.")
|
|
return false
|
|
|
|
var budget_chars: int = int(context_window() * COMPACT_TAIL_RATIO) * 4
|
|
var start: int = _tail_start(history_before, budget_chars)
|
|
var tail: Array = history_before.slice(start)
|
|
|
|
# reset() then add_user_message() builds the summary in this protocol's own
|
|
# shape; the tail is already in that shape, so appending the two is enough.
|
|
provider.reset()
|
|
provider.add_user_message(COMPACT_SUMMARY_PREFIX + summary.strip_edges())
|
|
var rebuilt: Array = provider.get_history()
|
|
rebuilt.append_array(tail)
|
|
provider.set_history(rebuilt)
|
|
|
|
_last_input_tokens = _estimate_tokens(rebuilt, 0)
|
|
_compacting = false
|
|
context_compacted.emit(before_tokens, _last_input_tokens, source)
|
|
save_session()
|
|
return true
|
|
|
|
## Where the kept tail begins: the earliest of the last COMPACT_KEEP_USER_TURNS
|
|
## real user turns, dropping to fewer if that would keep more than the budget.
|
|
## Starting on a real user turn is what keeps the tail valid on its own — a
|
|
## tool result at the head would reference a call that was summarized away.
|
|
func _tail_start(history: Array, budget_chars: int) -> int:
|
|
var user_indices: Array = []
|
|
for i in range(history.size()):
|
|
if provider.is_real_user_turn(history[i]):
|
|
user_indices.append(i)
|
|
if user_indices.is_empty():
|
|
var start: int = maxi(history.size() - COMPACT_MIN_MESSAGES, 0)
|
|
while start < history.size() and provider.is_tool_result(history[start]):
|
|
start += 1
|
|
return start
|
|
|
|
var keep: int = mini(COMPACT_KEEP_USER_TURNS, user_indices.size())
|
|
var chosen: int = user_indices[user_indices.size() - keep]
|
|
while keep > 1 and _estimate_tokens(history, chosen) > budget_chars:
|
|
keep -= 1
|
|
chosen = user_indices[user_indices.size() - keep]
|
|
return chosen
|
|
|
|
## Rough token estimate for a slice of history: its serialised size over four.
|
|
## Used only for the tail budget, never to decide whether to compact — that
|
|
## uses the provider's own input count.
|
|
func _estimate_tokens(history: Array, from: int) -> int:
|
|
var chars := 0
|
|
for i in range(from, history.size()):
|
|
chars += JSON.stringify(history[i]).length()
|
|
return int(chars / 4.0)
|
|
|
|
## Interrupts the current turn, if one is running. The in-flight request is
|
|
## aborted and _run_turn() unwinds via the normal {"error": ...} path.
|
|
func cancel() -> void:
|
|
if provider:
|
|
provider.cancel()
|
|
|
|
## images: Array of {"bytes": PackedByteArray, "mime": String}.
|
|
## Sends now if idle, queues if a turn is in flight.
|
|
func send_user_message(text: String, images: Array = []) -> void:
|
|
if _turn_running:
|
|
var id := _next_queue_id
|
|
_next_queue_id += 1
|
|
_queue.append({"id": id, "text": text, "images": images})
|
|
message_queued.emit(id, text)
|
|
return
|
|
|
|
provider.add_user_message(text, images)
|
|
await _run_turn()
|
|
|
|
## Drops a message that hasn't been sent yet. Returns its text so the dock
|
|
## can put it back in the input box.
|
|
func cancel_queued(id: int) -> String:
|
|
for i in range(_queue.size()):
|
|
if _queue[i]["id"] == id:
|
|
var text: String = _queue[i]["text"]
|
|
_queue.remove_at(i)
|
|
message_cancelled.emit(id)
|
|
return text
|
|
return ""
|
|
|
|
## Exact input tokens for the conversation plus a draft, when the provider
|
|
## has an endpoint for it. -1 means it doesn't and the caller should estimate.
|
|
func count_input_tokens(draft: String) -> int:
|
|
if provider == null or _turn_running:
|
|
return -1
|
|
return await provider.count_input_tokens(_system_prompt(), ClaudeGodotTools.get_tool_definitions(), draft)
|
|
|
|
func is_turn_running() -> bool:
|
|
return _turn_running
|
|
|
|
func queued_count() -> int:
|
|
return _queue.size()
|
|
|
|
## One per turn end, so each gets a full turn of its own.
|
|
func _drain_queue() -> void:
|
|
if _queue.is_empty():
|
|
return
|
|
var next: Dictionary = _queue.pop_front()
|
|
message_dequeued.emit(next["id"], next["text"])
|
|
provider.add_user_message(next["text"], next["images"])
|
|
await _run_turn()
|
|
|
|
## The base prompt, plus a nudge to name the session while it has no title.
|
|
## Composed per call so it disappears the moment the model names it, and
|
|
## reappears on switching to an untitled session.
|
|
func _system_prompt() -> String:
|
|
var prompt := ClaudeGodotAgentConfig.SYSTEM_PROMPT
|
|
|
|
if session_title == "":
|
|
prompt += " This chat session has no title yet. Once you can tell what it is actually about — not from a first vague message — call update_session_description with a short title, a one-sentence objective, and a few keywords, so it can be found again in the session list."
|
|
|
|
# Composed per call, so a task that finishes between two steps of the same
|
|
# turn is visible on the next one. Without this the model would only learn
|
|
# a task ended by thinking to poll it, which it reliably forgets to do.
|
|
var tasks := ClaudeGodotBackgroundTasks.summary_lines()
|
|
if tasks != "":
|
|
prompt += "\nBackground tasks you have started this session:\n%s\nRead any of them with the task tool. A finished one is waiting to be read; a running one is still working while you reply." % tasks
|
|
|
|
# The index is injected in full every turn, which is why the spec insists
|
|
# it stays an index. Individual memory files are read on demand.
|
|
prompt += "\n" + ClaudeGodotMemory.SPEC
|
|
var index := ClaudeGodotMemory.read_index()
|
|
if index == "":
|
|
prompt += "\nNo memories have been written yet; %s does not exist." % ClaudeGodotMemory.INDEX
|
|
else:
|
|
prompt += "\nCurrent %s:\n%s" % [ClaudeGodotMemory.INDEX, index]
|
|
|
|
return prompt
|
|
|
|
## Characters, not tokens: the real count only arrives with the final usage.
|
|
## The dock labels it as an estimate until then.
|
|
func _on_stream_delta(text: String) -> void:
|
|
_streamed_characters += text.length()
|
|
stream_progress.emit(_streamed_characters)
|
|
|
|
func _run_turn() -> void:
|
|
_streamed_characters = 0
|
|
_turn_running = true
|
|
_compacted_this_turn = false
|
|
turn_started.emit()
|
|
var tools := ClaudeGodotTools.get_tool_definitions()
|
|
var steps := 0
|
|
# Once per turn: if trimming didn't help, the next failure is reported.
|
|
var recovered_overflow := false
|
|
|
|
while true:
|
|
# Checked before the call, like kimi-code does, so the limit counts
|
|
# model calls rather than being discovered after one too many.
|
|
if max_steps_per_turn > 0 and steps >= max_steps_per_turn:
|
|
step_limit_reached.emit(steps)
|
|
await _wrap_up(steps)
|
|
break
|
|
|
|
# Before sending, not after the provider refuses: compaction replaces
|
|
# the earlier messages with a summary, which costs one call but keeps
|
|
# the conversation going. `compact` asks for it explicitly; the
|
|
# threshold asks for it on its own.
|
|
if _pending_compact or should_auto_compact():
|
|
var source := "manual" if _pending_compact else "auto"
|
|
var instruction := _pending_compact_instruction
|
|
_pending_compact = false
|
|
_pending_compact_instruction = ""
|
|
await compact_conversation(source, instruction)
|
|
_compacted_this_turn = true
|
|
|
|
var result: Dictionary = await provider.step(_system_prompt(), tools)
|
|
steps += 1
|
|
if result.has("error"):
|
|
# An over-long context doesn't fix itself: the same history goes
|
|
# out every retry, so the conversation is stuck until the thing
|
|
# that overflowed it is taken back out. Compaction is the thorough
|
|
# fix; dropping the last tool output is the cheap one and the
|
|
# backstop when there is nothing worth summarizing.
|
|
if _is_context_overflow(result["error"]):
|
|
if not _compacted_this_turn:
|
|
var compacted: bool = await compact_conversation("overflow", "")
|
|
if compacted:
|
|
_compacted_this_turn = true
|
|
continue
|
|
if not recovered_overflow:
|
|
var note := "[removed: this result was too large to keep in the conversation. Read the file in parts with offset and limit, or search it with the remote tool.]"
|
|
var dropped: int = provider.shrink_last_tool_results(note)
|
|
if dropped > 0:
|
|
recovered_overflow = true
|
|
agent_error.emit("%s Dropped %s characters of tool output from the conversation and retrying." % [result["error"], _format_thousands(dropped)])
|
|
continue
|
|
agent_error.emit(result["error"])
|
|
_finish_turn()
|
|
return
|
|
|
|
_report_usage(result)
|
|
|
|
# Commentary first, then the answer, then the tools it asked for —
|
|
# so the user reads why something is about to happen before it does.
|
|
for r in result.get("reasoning", []):
|
|
if r != null and r != "":
|
|
_session_reasoning.append({"after_message": provider.get_history().size(), "text": str(r)})
|
|
assistant_reasoning.emit(r)
|
|
|
|
for t in result.get("text", []):
|
|
if t != null and t != "":
|
|
assistant_text.emit(t)
|
|
|
|
var calls: Array = result.get("tool_calls", [])
|
|
if calls.is_empty():
|
|
break
|
|
|
|
var tool_results: Array = []
|
|
var images: Array = []
|
|
for call in calls:
|
|
tool_call.emit(call["name"], call["input"])
|
|
var tr := ClaudeGodotTools.execute(call["name"], call["input"])
|
|
tool_result.emit(call["name"], tr)
|
|
|
|
var content: String = tr.get("content", "")
|
|
# A tool result is text in every protocol we speak — only
|
|
# Anthropic allows an image inside tool_result, and the
|
|
# OpenAI-style ones don't at all. So an image rides along as a
|
|
# separate user message instead, which all three accept.
|
|
if tr.has("session_description"):
|
|
var description: Dictionary = tr["session_description"]
|
|
session_title = str(description.get("title", ""))
|
|
session_objective = str(description.get("objective", ""))
|
|
session_keywords = description.get("keywords", [])
|
|
session_described.emit(session_title)
|
|
|
|
if tr.has("restart_editor"):
|
|
_pending_restart = true
|
|
|
|
if tr.has("resume_session"):
|
|
request_resume(str(tr["resume_session"]))
|
|
|
|
if tr.has("compact"):
|
|
_pending_compact = true
|
|
_pending_compact_instruction = str(tr.get("compact_instruction", ""))
|
|
|
|
if tr.has("image"):
|
|
if supports_vision():
|
|
images.append(tr["image"])
|
|
else:
|
|
content += "\n\nNot attaching it: %s isn't marked as accepting images in providers.csv." % provider.model
|
|
|
|
if content.length() > ClaudeGodotAgentConfig.MAX_TOOL_RESULT_CHARS:
|
|
content = content.substr(0, ClaudeGodotAgentConfig.MAX_TOOL_RESULT_CHARS) + "\n\n[truncated: %d characters total, over this session's per-result limit]" % content.length()
|
|
|
|
tool_results.append({
|
|
"id": call["id"],
|
|
"name": call["name"],
|
|
"content": content,
|
|
"is_error": tr.get("is_error", false),
|
|
})
|
|
provider.add_tool_results(tool_results)
|
|
|
|
if not images.is_empty():
|
|
var names := []
|
|
for image in images:
|
|
names.append(str(image.get("path", "image")))
|
|
provider.add_user_message("Image%s from the tool call above: %s" % ["" if images.size() == 1 else "s", ", ".join(names)], images)
|
|
|
|
save_session()
|
|
if _pending_restart:
|
|
_pending_restart = false
|
|
# Saved above, so the conversation survives the restart.
|
|
EditorInterface.restart_editor(true)
|
|
return
|
|
if _pending_resume != "":
|
|
var target := _pending_resume
|
|
_pending_resume = ""
|
|
resume_session(target)
|
|
_finish_turn()
|
|
|
|
func _finish_turn() -> void:
|
|
_turn_running = false
|
|
turn_finished.emit()
|
|
await _drain_queue()
|
|
|
|
## One last call with no tools offered, so the model can only reply in text.
|
|
func _wrap_up(steps: int) -> void:
|
|
provider.add_user_message(
|
|
"You have reached this session's limit of %d tool-use steps for one message, so no further tools are available. Reply in plain text: what you did, what you found, what is still unfinished, and what you would do next." % steps
|
|
)
|
|
var result: Dictionary = await provider.step(_system_prompt(), [])
|
|
if result.has("error"):
|
|
agent_error.emit(result["error"])
|
|
return
|
|
|
|
_report_usage(result)
|
|
for t in result.get("text", []):
|
|
if t != null and t != "":
|
|
assistant_text.emit(t)
|
|
|
|
## Writes the current conversation to user://.claude-godot/sessions/.
|
|
func save_session() -> void:
|
|
if provider == null or provider.get_history().is_empty():
|
|
return
|
|
ClaudeGodotSessionStore.save(session_id, export_chat())
|
|
|
|
## Starts a fresh session, leaving the old one on disk.
|
|
func new_session() -> void:
|
|
save_session()
|
|
session_id = ClaudeGodotSessionStore.new_session_id()
|
|
session_title = ""
|
|
session_objective = ""
|
|
session_keywords = []
|
|
_session_reasoning = []
|
|
provider.reset()
|
|
total_input_tokens = 0
|
|
total_output_tokens = 0
|
|
total_cost = 0.0
|
|
total_cached_tokens = 0
|
|
total_reasoning_tokens = 0
|
|
usage_updated.emit(0, 0)
|
|
session_changed.emit(session_id)
|
|
|
|
## Loads a session, switching provider and model to the ones it was recorded
|
|
## with — its messages are in that protocol's wire shape and are not portable
|
|
## to another. Returns {} or {"error": String}.
|
|
func resume_session(target_id: String) -> Dictionary:
|
|
var loaded := ClaudeGodotSessionStore.load_session(target_id)
|
|
if loaded.has("error"):
|
|
return loaded
|
|
|
|
save_session()
|
|
|
|
var header: Dictionary = loaded["header"]
|
|
var recorded_provider: String = header.get("provider", "")
|
|
var recorded_model: String = header.get("model", "")
|
|
if recorded_provider != "":
|
|
var key: String = provider.api_key if provider else ""
|
|
set_preset(recorded_provider, recorded_model, key)
|
|
|
|
session_id = target_id
|
|
session_title = str(header.get("title", ""))
|
|
session_objective = str(header.get("objective", ""))
|
|
session_keywords = header.get("keywords", [])
|
|
_session_reasoning = loaded.get("reasoning", [])
|
|
provider.set_history(loaded["messages"])
|
|
total_input_tokens = int(header.get("total_input_tokens", 0))
|
|
total_output_tokens = int(header.get("total_output_tokens", 0))
|
|
total_cost = float(header.get("total_cost", 0.0))
|
|
total_cached_tokens = int(header.get("total_cached_tokens", 0))
|
|
total_reasoning_tokens = int(header.get("total_reasoning_tokens", 0))
|
|
usage_updated.emit(total_input_tokens, total_output_tokens)
|
|
session_changed.emit(session_id)
|
|
return {}
|
|
|
|
## Called by the resume_session tool. Deferred: see _pending_resume.
|
|
func request_resume(target_id: String) -> void:
|
|
_pending_resume = target_id
|
|
|
|
## The body of a .chat file: a session header, then one line per message
|
|
## exactly as it goes to the provider (shapes differ per protocol — that's
|
|
## the point, it's the real context, not a re-render of the chat log), then
|
|
## the reasoning. The store adds the format marker on top. Never includes the
|
|
## API key; that lives in an HTTP header, not in the history.
|
|
func export_chat() -> String:
|
|
var lines: Array = [JSON.stringify({
|
|
"type": "session",
|
|
"session_id": session_id,
|
|
"title": session_title,
|
|
"objective": session_objective,
|
|
"keywords": session_keywords,
|
|
"exported_at": Time.get_datetime_string_from_system(true),
|
|
"provider": preset.get("id", ""),
|
|
"provider_label": preset.get("label", ""),
|
|
"protocol": preset.get("kind", ""),
|
|
"endpoint": preset.get("base_url", ""),
|
|
"model": provider.model if provider else "",
|
|
"system_prompt": ClaudeGodotAgentConfig.SYSTEM_PROMPT,
|
|
"max_steps_per_turn": max_steps_per_turn,
|
|
"total_input_tokens": total_input_tokens,
|
|
"total_output_tokens": total_output_tokens,
|
|
"total_cost": total_cost,
|
|
"total_cached_tokens": total_cached_tokens,
|
|
"total_reasoning_tokens": total_reasoning_tokens,
|
|
})]
|
|
|
|
var history: Array = provider.get_history() if provider else []
|
|
for i in range(history.size()):
|
|
lines.append(JSON.stringify({"type": "message", "index": i, "message": history[i]}))
|
|
|
|
# after_message says where each one occurred, so the ordering survives
|
|
# even though they are written after the messages.
|
|
for entry in _session_reasoning:
|
|
lines.append(JSON.stringify({
|
|
"type": "reasoning",
|
|
"after_message": entry.get("after_message", 0),
|
|
"text": entry.get("text", ""),
|
|
}))
|
|
|
|
return "\n".join(lines) + "\n"
|
|
|
|
## Providers word it differently but all name the limit and the request.
|
|
static func _is_context_overflow(message: String) -> bool:
|
|
var lowered := message.to_lower()
|
|
for phrase in ["maximum context length", "context length exceeded", "context_length_exceeded", "too many tokens", "prompt is too long", "request too large"]:
|
|
if lowered.contains(phrase):
|
|
return true
|
|
return false
|
|
|
|
static func _format_thousands(n: int) -> String:
|
|
var text := str(n)
|
|
var out := ""
|
|
var count := 0
|
|
for i in range(text.length() - 1, -1, -1):
|
|
out = text[i] + out
|
|
count += 1
|
|
if count % 3 == 0 and i > 0:
|
|
out = "," + out
|
|
return out
|
|
|
|
func _report_usage(result: Dictionary) -> void:
|
|
var usage: Dictionary = result.get("usage", {})
|
|
if usage.is_empty():
|
|
return
|
|
# The reported input count is the size the next request starts from, and
|
|
# what the compaction threshold is compared against. `context` is the full
|
|
# prompt where `input` alone would exclude cached tokens.
|
|
_last_input_tokens = int(usage.get("context", usage.get("input", 0)))
|
|
total_input_tokens += int(usage.get("input", 0))
|
|
total_output_tokens += int(usage.get("output", 0))
|
|
total_cost += float(usage.get("cost", 0.0))
|
|
total_cached_tokens += int(usage.get("cached", 0))
|
|
total_reasoning_tokens += int(usage.get("reasoning", 0))
|
|
usage_updated.emit(total_input_tokens, total_output_tokens)
|