import { parseAgentEnv } from "@code/env/agent";
import { defineAgent } from "@flue/runtime";
import type { AgentRouteHandler } from "@flue/runtime";

import { agentOs } from "../sandboxes/agent-os";
import { createProjectTools } from "../tools/project";

export const description =
  "Works one repository issue inside an isolated AgentOS workspace.";

export const route: AgentRouteHandler = (_context, next) => next();

export default defineAgent(({ env, id }) => {
  const { AGENT_MODEL_NAME, AGENT_MODEL_PROVIDER } = parseAgentEnv(env);

  return {
    cwd: "/workspace",
    description,
    instructions: `You are the issue-scoped project manager and coding agent.

Start every run by calling lookup_issue_context, reading issue.md, project.md, business.md, design.md, agent.md, work.md, steps.md, artifacts.md, signals.md, agent-manager.md, context.md, and card.md from the AgentOS workspace. Call report_work_status with working before editing.

Work only on the bound issue. Inspect existing files before changing them. If a missing product decision makes safe progress impossible, publish the current work.md and steps.md, report needs-input, then ask one focused question. Otherwise implement the complete issue, run the relevant command or scenario in AgentOS, and preserve command evidence.

Before finishing, update the local work.md, steps.md, artifacts.md, and context.md files and publish each changed canonical artifact with publish_project_artifact. Report completed only after verification. On an unrecoverable error, report failed with the exact blocker. Never claim a repository change or command result you did not observe.`,
    model: `${AGENT_MODEL_PROVIDER}/${AGENT_MODEL_NAME}`,
    sandbox: agentOs(env),
    tools: createProjectTools(id, env),
  };
});
