- 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>
238 lines
8.8 KiB
GDScript
238 lines
8.8 KiB
GDScript
## One background task: a second agent, given a single instruction and left to
|
|
## carry it out while the main chat carries on.
|
|
##
|
|
## It is a real turn loop, not a shortcut — the same provider, the same tools,
|
|
## the same step cap. What it does not have is a user. Nothing in a background
|
|
## run can ask a question, so the instruction it starts with is everything it
|
|
## will ever be told. That is the trade for running unattended, and it is why
|
|
## a task brief should say what "finished" looks like.
|
|
##
|
|
## Concurrency here is the editor's, not the operating system's: every call
|
|
## out to a provider is awaited, and awaiting hands control back, so several
|
|
## runs and the main chat interleave on one thread. No locks, no races on
|
|
## GDScript state — but also no parallelism in the tools themselves. Two runs
|
|
## told to edit the same file will still overwrite each other.
|
|
class_name ClaudeGodotTaskRun
|
|
extends Node
|
|
|
|
## Anything worth redrawing for: a step finished, a tool ran, the run ended.
|
|
signal changed(run: ClaudeGodotTaskRun)
|
|
|
|
enum State { RUNNING, DONE, FAILED, STOPPED }
|
|
|
|
## Tools a background run does not get.
|
|
##
|
|
## `task` would let a run start runs, nesting without a bound. The session
|
|
## tools all act on the *main* chat — resuming or renaming it from a detached
|
|
## run would move the ground under the user mid-sentence. `reload` restarts
|
|
## the editor, which takes every other run down with it, the main chat
|
|
## included.
|
|
const DENIED_TOOLS := [
|
|
"task", "reload", "resume_session", "list_sessions", "update_session_description",
|
|
"compact", "eval",
|
|
]
|
|
|
|
## Per entry, and how many entries are kept. A run that reads twenty files
|
|
## should not be able to push its own status report past a context window.
|
|
const MAX_ENTRY_CHARS := 1200
|
|
const MAX_ENTRIES := 80
|
|
|
|
var id := ""
|
|
var brief := ""
|
|
var label := ""
|
|
var state: State = State.RUNNING
|
|
var steps := 0
|
|
var max_steps := 20
|
|
var started_msec := 0
|
|
var ended_msec := 0
|
|
## The run's closing words: the last text it produced before stopping.
|
|
var summary := ""
|
|
var error := ""
|
|
var input_tokens := 0
|
|
var output_tokens := 0
|
|
var cost := 0.0
|
|
|
|
## [{"kind": "text"|"tool"|"error", "text": String}] — the trail the main
|
|
## agent reads when it checks in. Trimmed from the front, so a long run keeps
|
|
## its most recent history rather than its first.
|
|
var entries: Array = []
|
|
|
|
var _provider
|
|
var _stop_requested := false
|
|
## The tool surface this run was given; see setup().
|
|
var _tools: Array = []
|
|
var _execute: Callable = Callable()
|
|
|
|
## `context` is what the chat agent hands down so a run is the same agent
|
|
## elsewhere: its preset, model and key, the tool schemas it may use, and a
|
|
## callable that runs one. Injected rather than looked up, because the tool
|
|
## registry preloads the tool that starts these runs — reaching back into it
|
|
## from here would close a reference cycle GDScript resolves badly.
|
|
func setup(task_id: String, task_brief: String, task_label: String, context: Dictionary, step_cap: int) -> void:
|
|
id = task_id
|
|
brief = task_brief
|
|
label = task_label if task_label != "" else task_brief.substr(0, 60)
|
|
max_steps = step_cap
|
|
started_msec = Time.get_ticks_msec()
|
|
_tools = context.get("tools", [])
|
|
_execute = context.get("execute", Callable())
|
|
|
|
# Streaming buys a live character count for the dock's progress line. A
|
|
# background run has nowhere to show one, and the buffered path is the
|
|
# simpler of the two, so it takes that.
|
|
_provider = ClaudeGodotAgentConfig.build_provider(
|
|
context.get("preset", {}), str(context.get("model", "")), str(context.get("api_key", "")), false
|
|
)
|
|
add_child(_provider)
|
|
|
|
## Fire and forget: this is deliberately not awaited by its caller, so the
|
|
## tool that started the run returns an id immediately and the loop proceeds
|
|
## on its own from the first await.
|
|
func start() -> void:
|
|
_provider.add_user_message(brief)
|
|
_run()
|
|
|
|
func stop() -> void:
|
|
if state != State.RUNNING:
|
|
return
|
|
_stop_requested = true
|
|
if _provider:
|
|
_provider.cancel()
|
|
|
|
func is_running() -> bool:
|
|
return state == State.RUNNING
|
|
|
|
func elapsed_seconds() -> int:
|
|
var end: int = ended_msec if ended_msec > 0 else Time.get_ticks_msec()
|
|
return int((end - started_msec) / 1000.0)
|
|
|
|
func state_name() -> String:
|
|
match state:
|
|
State.RUNNING: return "running"
|
|
State.DONE: return "done"
|
|
State.FAILED: return "failed"
|
|
State.STOPPED: return "stopped"
|
|
return "unknown"
|
|
|
|
func _run() -> void:
|
|
|
|
while not _stop_requested:
|
|
if steps >= max_steps:
|
|
_log("error", "Stopped at the %d-step cap without reporting a result." % max_steps)
|
|
_end(State.FAILED, "Hit the %d-step cap." % max_steps)
|
|
return
|
|
|
|
var result: Dictionary = await _provider.step(_system_prompt(), _tools)
|
|
steps += 1
|
|
|
|
if _stop_requested:
|
|
break
|
|
|
|
if result.has("error"):
|
|
_log("error", str(result["error"]))
|
|
_end(State.FAILED, str(result["error"]))
|
|
return
|
|
|
|
_add_usage(result.get("usage", {}))
|
|
|
|
for t in result.get("text", []):
|
|
if t != null and str(t) != "":
|
|
summary = str(t)
|
|
_log("text", str(t))
|
|
|
|
var calls: Array = result.get("tool_calls", [])
|
|
if calls.is_empty():
|
|
_end(State.DONE, "")
|
|
return
|
|
|
|
var tool_results: Array = []
|
|
for call in calls:
|
|
var tr: Dictionary = _execute.call(call["name"], call["input"])
|
|
var content: String = tr.get("content", "")
|
|
|
|
# A background run has no vision path: an image would have to ride
|
|
# along as an extra user message, and there is no user here to
|
|
# attribute it to. The text result still says what was captured.
|
|
if tr.has("image"):
|
|
content += "\n\n[the image itself is not attached: background tasks run without vision.]"
|
|
|
|
_log("tool", "%s → %s" % [call["name"], content.strip_edges()])
|
|
|
|
if content.length() > ClaudeGodotAgentConfig.MAX_TOOL_RESULT_CHARS:
|
|
content = content.substr(0, ClaudeGodotAgentConfig.MAX_TOOL_RESULT_CHARS) + "\n\n[truncated: %d characters total]" % 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)
|
|
changed.emit(self)
|
|
|
|
_end(State.STOPPED, "Stopped on request after %d steps." % steps)
|
|
|
|
## The main agent's prompt plus what makes this run different: no user, one
|
|
## instruction, and an ending it has to declare for itself.
|
|
func _system_prompt() -> String:
|
|
return "%s\n\nYou are running as a background task inside that editor session, not as the chat itself. There is no user reading this conversation and no way to ask a question — the instruction below is all you get, so make reasonable assumptions and record them in your final message rather than stopping to check. Work until the instruction is carried out, then reply in plain text with what you did, what you changed, and anything you had to assume or could not finish. That plain-text reply ends the task, so do not send one until you are done. Another agent is working in the same project at the same time: prefer reading a file immediately before editing it, and say so if something changed underneath you." % ClaudeGodotAgentConfig.SYSTEM_PROMPT
|
|
|
|
func _log(kind: String, text: String) -> void:
|
|
var clipped := text
|
|
if clipped.length() > MAX_ENTRY_CHARS:
|
|
clipped = clipped.substr(0, MAX_ENTRY_CHARS) + "… (+%d chars)" % (text.length() - MAX_ENTRY_CHARS)
|
|
entries.append({"kind": kind, "text": clipped, "step": steps})
|
|
while entries.size() > MAX_ENTRIES:
|
|
entries.pop_front()
|
|
|
|
func _add_usage(usage: Dictionary) -> void:
|
|
if usage.is_empty():
|
|
return
|
|
input_tokens += int(usage.get("input", 0))
|
|
output_tokens += int(usage.get("output", 0))
|
|
cost += float(usage.get("cost", 0.0))
|
|
|
|
func _end(final_state: State, message: String) -> void:
|
|
state = final_state
|
|
error = message if final_state == State.FAILED else ""
|
|
if final_state != State.DONE and summary == "":
|
|
summary = message
|
|
ended_msec = Time.get_ticks_msec()
|
|
changed.emit(self)
|
|
|
|
## A one-line header for lists and for the dock.
|
|
func headline() -> String:
|
|
return "[%s] %s — %s, %d step%s, %ds" % [
|
|
id, label, state_name(), steps, "" if steps == 1 else "s", elapsed_seconds(),
|
|
]
|
|
|
|
## The full picture for the agent checking in: the header, then the trail.
|
|
func report(include_log: bool) -> String:
|
|
var lines: Array = [headline()]
|
|
if brief != label:
|
|
lines.append("Brief: %s" % brief)
|
|
if input_tokens > 0 or output_tokens > 0:
|
|
lines.append("Tokens: %d in, %d out%s" % [
|
|
input_tokens, output_tokens, "" if cost <= 0.0 else ", $%.4f" % cost,
|
|
])
|
|
|
|
if include_log and not entries.is_empty():
|
|
lines.append("")
|
|
lines.append("Trail:")
|
|
for entry in entries:
|
|
var prefix := "·"
|
|
match entry["kind"]:
|
|
"tool": prefix = "⚙"
|
|
"error": prefix = "✗"
|
|
lines.append("%s %s" % [prefix, entry["text"]])
|
|
|
|
if state != State.RUNNING and summary != "":
|
|
lines.append("")
|
|
lines.append("Result: %s" % summary)
|
|
elif state == State.RUNNING:
|
|
lines.append("")
|
|
lines.append("Still running. Check again later, or carry on with something else — it keeps going between your turns.")
|
|
|
|
return "\n".join(lines)
|