File size: 2,341 Bytes
219250e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import json
from pathlib import Path

from agent_core.agent import agent_loop
from agent_core.config import WORKDIR


def content_to_text(content) -> str:
    if isinstance(content, str):
        return content
    if not isinstance(content, list):
        return ""

    texts = []
    for block in content:
        text = getattr(block, "text", None)
        if text:
            texts.append(text)
    return "\n".join(texts).strip()


def resolve_display_path(path: str | None) -> str | None:
    if not path:
        return None

    candidate = Path(path)
    if not candidate.is_absolute():
        candidate = WORKDIR / candidate
    candidate = candidate.resolve()
    return str(candidate) if candidate.exists() else None


def latest_tool_payload(messages: list) -> dict:
    latest = {}
    for message in messages:
        content = message.get("content")
        if not isinstance(content, list):
            continue
        for item in content:
            if not isinstance(item, dict) or item.get("type") != "tool_result":
                continue
            try:
                payload = json.loads(item.get("content", ""))
            except json.JSONDecodeError:
                continue
            if isinstance(payload, dict):
                latest = payload
    return latest


def run_chat_turn(messages: list, user_text: str, image_path: str | None = None) -> dict:
    text = user_text.strip()
    if image_path:
        text = f"{text}\n\nUploaded image path for image-to-3D generation: {image_path}".strip()

    messages.append({"role": "user", "content": text})
    agent_loop(messages)

    assistant_text = content_to_text(messages[-1].get("content"))
    tool_payload = latest_tool_payload(messages)
    output_path = tool_payload.get("output_path")
    preview_path = tool_payload.get("preview_path") or output_path

    return {
        "messages": messages,
        "assistant_text": assistant_text,
        "tool_payload": tool_payload,
        "preview_path": resolve_display_path(preview_path),
        "download_path": resolve_display_path(output_path),
        "run_id": tool_payload.get("run_id"),
        "run_dir": tool_payload.get("run_dir"),
        "manifest_path": tool_payload.get("manifest_path"),
        "ok": tool_payload.get("ok"),
        "error": tool_payload.get("error"),
    }