import json from afk_developer.backends.base import ( CoderBackend, ReasonerBackend, ResearcherBackend, ValidatorBackend, ) from afk_developer.backends.models import ( AcceptanceValidationResult, BackendResponse, BackendUsage, DiscoveryProposalResult, ResearchProposalResult, TaskExecutionResult, ) from afk_developer.config import Config, LintMode from afk_developer.planner.task_model import DiscoveryContract, TaskFailureKind, TaskNode, TaskStatus from afk_developer.scheduler.discovery_checkpoint import DiscoveryCheckpointDraft from afk_developer.scheduler.tools.dispatch import dispatch_tool_call from afk_developer.scheduler.tools.schemas import build_tool_schemas, to_openai_tool_definitions from afk_developer.secrets import resolve_secret_ref from afk_developer.utils import extract_json def _usage_value(usage, *paths: tuple[str, ...]) -> int: """Return the first non-empty provider usage value from common SDK shapes.""" for path in paths: value = usage for part in path: value = value.get(part) if isinstance(value, dict) else getattr(value, part, None) if value is None: break if value is not None: return int(value or 0) return 0 def _normalize_openai_usage(usage) -> BackendUsage: """Preserve standard and optional OpenAI-compatible usage detail fields.""" return BackendUsage( prompt_tokens=_usage_value(usage, ("prompt_tokens",)), completion_tokens=_usage_value(usage, ("completion_tokens",)), total_tokens=_usage_value(usage, ("total_tokens",)), cache_read_tokens=_usage_value( usage, ("prompt_tokens_details", "cached_tokens"), ("prompt_cache_hit_tokens",), ("cache_read_input_tokens",), ), cache_write_tokens=_usage_value( usage, ("prompt_tokens_details", "cache_creation_tokens"), ("cache_creation_input_tokens",), ("cache_write_tokens",), ), reasoning_tokens=_usage_value( usage, ("completion_tokens_details", "reasoning_tokens"), ("reasoning_tokens",), ), api_calls=1, ) class OpenAICompatibleReasoner(ReasonerBackend): """OpenAI chat-completions adapter for planning and synthesis calls.""" def __init__(self, config: Config, role: str): self.config = config self.role = role def complete( self, *, system_prompt: str, user_prompt: str, temperature: float = 0.0, ) -> BackendResponse: from openai import OpenAI route = self.config.route_for(self.role) endpoint = self.config.endpoint_for(self.role) api_key = ( resolve_secret_ref(endpoint.api_key_ref) if endpoint.api_key_ref else self.config.api_key ) if not api_key: raise ValueError( f"Endpoint '{endpoint.name}' requires an API key. " "Run 'afk setup' or configure the endpoint secret." ) client = OpenAI( api_key=api_key, base_url=endpoint.base_url or self.config.base_url, ) response = client.chat.completions.create( model=route.model, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ], temperature=temperature, ) usage = response.usage normalized_usage = _normalize_openai_usage(usage) return BackendResponse( content=response.choices[0].message.content or "", model=route.model, endpoint=endpoint.name, usage=normalized_usage, ) class OpenAICompatibleCoder(CoderBackend): """Placeholder for migration of the existing OpenAI tool-call worker loop.""" def __init__(self, config: Config, role: str): self.config = config self.role = role def execute_task( self, *, task: TaskNode, project_dir: str, context: str, hitl_mode: bool, max_turns: int, project_name: str = "", ) -> TaskExecutionResult: raise NotImplementedError( "OpenAI-compatible coder migration is pending; the legacy Worker remains active." ) class OpenAICompatibleResearcher(ResearcherBackend): """OpenAI-compatible read-only researcher adapters.""" def __init__(self, config: Config, role: str): self.config = config self.role = role def propose_evidence( self, *, task: TaskNode, project_dir: str, context: str, max_turns: int, project_name: str = "", ) -> ResearchProposalResult: del task, project_dir, context, max_turns, project_name raise NotImplementedError( "OpenAI-compatible research is not available because it has no constrained " "read-only tool adapter. Configure a Copilot researcher route." ) def propose_discovery( self, *, task: TaskNode, project_dir: str, contract: DiscoveryContract, context: str, max_turns: int, project_name: str = "", ) -> DiscoveryProposalResult: """Produce one local discovery draft through bounded read-only tools.""" from openai import OpenAI route = self.config.route_for(self.role) endpoint = self.config.endpoint_for(self.role) api_key = ( resolve_secret_ref(endpoint.api_key_ref) if endpoint.api_key_ref else self.config.api_key ) if not api_key: return DiscoveryProposalResult( status=TaskStatus.ESCALATED, summary=f"Endpoint '{endpoint.name}' requires an API key.", failure_kind=TaskFailureKind.PROVIDER_UNAVAILABLE, ) tool_schemas = [ schema for schema in build_tool_schemas( read_only=True, has_evidence_roots=False, allow_baseline_compare=self.config.lint_mode is LintMode.BASELINE, ) if schema[0] not in {"task_complete", "task_blocked"} ] tools = to_openai_tool_definitions(tool_schemas) tools.append( { "type": "function", "function": { "name": "submit_discovery_proposal", "description": "Submit exactly one structured local discovery proposal.", "parameters": _DISCOVERY_DRAFT_TOOL_SCHEMA, }, } ) tools.append( { "type": "function", "function": { "name": "task_blocked", "description": "Report the precise missing local evidence.", "parameters": { "type": "object", "additionalProperties": False, "properties": { "reason": {"type": "string"}, "missing_evidence": {"type": "string"}, }, "required": ["reason", "missing_evidence"], }, }, } ) system_prompt = ( "You are AFK's read-only local discovery researcher. Inspect only the target project " "using the provided read-only tools. Never modify files, run a general shell command, " "commit, merge, push, access a network, or cite paths outside the declared input manifest. " "Answer only the declared questions. Submit exactly one structured proposal with " "submit_discovery_proposal. Every source_paths and canonical_paths value must name a " "declared manifest path: they are existing, hashed evidence only. Never list an allowed " "future output path in either field; refer to it only in approved_next_action or summary. " "The trusted AFK runner, not you, validates hashes and persists " "the checkpoint.\n\n--- Discovery Contract ---\n" "Questions:\n" + "\n".join(f"- {item}" for item in contract.questions) + "\nAllowed outputs after discovery:\n" + "\n".join(f"- {item}" for item in contract.allowed_output_paths) + "\nExclusions:\n" + ("\n".join(f"- {item}" for item in contract.exclusions) or "- (none)") + "\n\n--- Bounded Task Context ---\n" + context ) messages: list[dict] = [ {"role": "system", "content": system_prompt}, { "role": "user", "content": ( f"TASK: {task.title}\n{task.description}\n\n" f"Use at most {max_turns} tool-guided turns. Submit the discovery proposal " "once the declared questions are answered." ), }, ] client = OpenAI(api_key=api_key, base_url=endpoint.base_url or self.config.base_url) last_content = "" for turn in range(max_turns): try: response = client.chat.completions.create( model=route.model, messages=messages, tools=tools, temperature=0.0, ) except Exception as exc: return DiscoveryProposalResult( status=TaskStatus.ESCALATED, summary=f"OpenAI-compatible discovery error on turn {turn + 1}: {exc}", failure_kind=TaskFailureKind.PROVIDER_UNAVAILABLE, ) usage = _normalize_openai_usage(response.usage) self.config.record_usage(usage, role=self.role) self.config.stats.total_turns += 1 message = response.choices[0].message last_content = message.content or last_content if not message.tool_calls: draft = _parse_discovery_draft(last_content) if draft is not None: return DiscoveryProposalResult( status=TaskStatus.PASSED, summary="Read-only discovery proposal returned as structured JSON.", draft=draft, usage=usage, ) break messages.append( { "role": "assistant", "content": message.content or "", "tool_calls": [ { "id": call.id, "type": "function", "function": { "name": call.function.name, "arguments": call.function.arguments, }, } for call in message.tool_calls ], } ) for call in message.tool_calls: try: arguments = json.loads(call.function.arguments) except json.JSONDecodeError: arguments = None if arguments is None: tool_result = "REJECTED: Tool arguments must be valid JSON." elif call.function.name == "submit_discovery_proposal": try: draft = DiscoveryCheckpointDraft.model_validate(arguments) except ValueError as exc: tool_result = f"REJECTED: Invalid discovery proposal: {exc}" else: return DiscoveryProposalResult( status=TaskStatus.PASSED, summary="Read-only discovery proposal submitted for trusted validation.", draft=draft, usage=usage, ) elif call.function.name == "task_blocked": return DiscoveryProposalResult( status=TaskStatus.ESCALATED, summary=( "RESEARCH_INSUFFICIENT: " f"{arguments.get('reason', 'Required local evidence is unavailable.')} " f"Missing evidence: {arguments.get('missing_evidence', 'not specified.')}" ), failure_kind=TaskFailureKind.RESEARCH_INSUFFICIENT, usage=usage, ) else: tool_result = dispatch_tool_call( call.function.name, arguments, project_dir=project_dir, evidence_roots=[], config=self.config, project_name=project_name, ) messages.append( {"role": "tool", "tool_call_id": call.id, "content": tool_result} ) return DiscoveryProposalResult( status=TaskStatus.FAILED, summary="OpenAI-compatible researcher ended without a valid discovery proposal.", raw_response=last_content[:5_000], ) _DISCOVERY_DRAFT_TOOL_SCHEMA = { "type": "object", "additionalProperties": False, "properties": { "source_paths": {"type": "array", "items": {"type": "string"}}, "canonical_paths": {"type": "array", "items": {"type": "string"}}, "canonical_symbols": {"type": "array", "items": {"type": "string"}}, "conclusions": {"type": "array", "items": {"type": "string"}}, "approved_next_action": {"type": "string"}, "summary": {"type": "string"}, }, "required": ["source_paths", "conclusions", "approved_next_action", "summary"], } def _parse_discovery_draft(content: str) -> DiscoveryCheckpointDraft | None: try: return DiscoveryCheckpointDraft.model_validate(extract_json(content)) except (TypeError, ValueError, json.JSONDecodeError): return None class OpenAICompatibleValidator(ValidatorBackend): """Explicitly unavailable until a constrained OpenAI validation adapter exists.""" def __init__(self, config: Config, role: str): self.config = config self.role = role def validate( self, *, task: TaskNode, project_dir: str, context: str, max_turns: int, project_name: str = "", ) -> AcceptanceValidationResult: del task, project_dir, context, max_turns, project_name raise NotImplementedError( "OpenAI-compatible acceptance validation is not available because it has no " "constrained read-only tool adapter. Configure a Copilot validator route." )