import json import os from amc_server.config import EVENTS_DIR # Prefixes for system-injected content that appears as user messages # but was not typed by the human (hook outputs, system reminders, etc.) _SYSTEM_INJECTED_PREFIXES = ( "", "", "", "", "", "", "# AGENTS.md instructions", ) if any(text.startswith(p) for p in skip_prefixes): continue text_parts.append(text) if role == "user" and text_parts: # Flush any pending tool calls before user message if pending_tool_calls: messages.append({ "id": f"codex-{session_id[:8]}-{msg_id}", "role": "assistant", "content": "", "tool_calls": pending_tool_calls, "timestamp": timestamp, }) msg_id += 1 pending_tool_calls = [] messages.append({ "id": f"codex-{session_id[:8]}-{msg_id}", "role": "user", "content": "\n".join(text_parts), "timestamp": timestamp, }) msg_id += 1 elif role == "assistant": msg = { "id": f"codex-{session_id[:8]}-{msg_id}", "role": "assistant", "content": "\n".join(text_parts) if text_parts else "", "timestamp": timestamp, } # Attach any pending tool calls to this assistant message if pending_tool_calls: msg["tool_calls"] = pending_tool_calls pending_tool_calls = [] if text_parts or msg.get("tool_calls"): messages.append(msg) msg_id += 1 except json.JSONDecodeError: continue # Flush any remaining pending tool calls if pending_tool_calls: messages.append({ "id": f"codex-{session_id[:8]}-{msg_id}", "role": "assistant", "content": "", "tool_calls": pending_tool_calls, "timestamp": "", }) except OSError: pass return messages def _parse_codex_arguments(self, arguments_str): """Parse Codex function_call arguments (JSON string or dict).""" if isinstance(arguments_str, dict): return arguments_str if isinstance(arguments_str, str): try: return json.loads(arguments_str) except json.JSONDecodeError: return {"raw": arguments_str} return {}