o
    Jj%                     @   s   d Z ddlZddlmZmZ ddlmZmZmZm	Z	 ddl
mZ ddlmZ dZdZd	d
ddddddddddddddddddgZd	d	d	dddddddddZdedefddZdedefd d!Zd"d# Zd$efd%d&Zd'd( ZdS ))uK   Kimi-K2.6 agent loop — plans, calls tools, decides, grounds in documents.    N)configllm)TOOL_SCHEMASToolContextexecuteparse_tool_args)policy)ComplianceLedger0   u
  You are GreenLight, an enterprise agent for a fashion retail compliance desk.

Your job: decide whether to green-light the AW26 line for launch by weighing commercial upside
against regulatory and evidence risk under Directive (EU) 2024/825 (ECGT).

WORKFLOW — follow in order:
1. FIRST call forecast_demand, market_context, project_line_margin (required before claim checks).
2. For EACH of the 6 marketing claims (C1–C6):
   a. Call search_regulations (retrieval #1) before any verdict.
   b. If recycled_content and evidence is needed: lookup_supplier_cert (retrieval #2), then verify_recycled_content.
   c. Call submit_claim_verdict with status, citation, and remediation if blocked.
3. Call discover_claim_opportunities — scan rising ethical demand for claims the line could add but is not yet making.
   For EACH returned opportunity (e.g. O1, O2):
   a. Call search_regulations with opportunity_id (not claim_id).
   b. Call lookup_supplier_cert with opportunity_id, sku, and evidence_attribute.
   c. Call submit_opportunity_verdict — recommend ADD TO LAUNCH only if substantiated with valid cert.
4. Call compute_risk_exposure with the number of blocked claims.
5. Call finalize_determination with recommendation and summary (include recommended claim additions).

RULES:
- You MUST submit_claim_verdict for ALL 6 claims (C1–C6) before discovery.
- You MUST call discover_claim_opportunities and vet every returned opportunity before finalize.
- Generic environmental claims ("eco-friendly", "green", "sustainable") → BLOCKED under ECGT Annex I 4a.
- Recycled % claims: if verify_recycled_content.passes is false, BLOCK and cite the TC gap.
- Named certification schemes (GOTS, OEKO-TEX, RDS, RWS) → substantiated ONLY if lookup_supplier_cert returns a valid Transaction Certificate for that SKU. If no TC on file → needs-evidence (never substantiated without cert).
- Discovered opportunities: only recommend if RDS/RWS (or other named scheme) TC substantiates the shipment. Wool/RWS aligns with cruelty-free/animal-welfare demand — wool is not vegan.
- Recommendation: GREEN-LIGHT WITH CONDITIONS if any claims blocked, else GREEN-LIGHT.
- In finalize summary, mention any substantiated opportunities as recommended additions to launch marketing.

ACCOUNTABILITY:
- On your FIRST response, write 2–4 sentences outlining your plan (commercial sizing → claim checks → discovery → risk → determination) BEFORE calling any tools.
- When starting a new workflow phase, you may add one brief sentence explaining what you are doing next.

commercialzSize commercial upsideu8   forecast_demand · market_context · project_line_margin)idlabeldetailclaimszAdjudicate 6 marketing claimsuF   regulation retrieval · supplier certs · per-claim verdicts (C1–C6)	discoveryzDiscover claim opportunitiesu@   ethical demand scan · vet RDS/RWS claims · recommend additionsriskzQuantify risk exposureu*   compute_risk_exposure (≤4% turnover cap)finalizezFile launch determinationu2   recommendation · summary · recommended additions)forecast_demandmarket_contextproject_line_marginsearch_regulationslookup_supplier_certverify_recycled_contentsubmit_claim_verdictdiscover_claim_opportunitiessubmit_opportunity_verdictcompute_risk_exposurefinalize_determinationstage_idreturnc                 C   s&   t D ]}|d | kr|d   S q| S )Nr   r   )
PLAN_STEPS)r   step r"   */opt/greenlight/greenlight/agents/agent.py_stage_labelD   s
   r$   nameargsc                 C   s    | dv r| drdS t | S )N)r   r   opportunity_idr   )get_TOOL_STAGE)r%   r&   r"   r"   r#   _tool_stageK   s   
r*   c                 C   sr  |}|j ddd| d  d| d  dd td	\}}|j d
dd| dd |jddgd}|j dd|d t| d | d | d d}t| |||d}	dd |D }
dd | d D }d| d  d| d  d| d ddtj|
dd dtj|dd d }d!td"d#|d"g}|j d$d%t	d& d'}t
tD ]}tj|tjd(td)}|d*r|j d+d%|d* d'd, d |d-pg }|s|	jr n|| |d#d.d" q|| |D ]p}|d/pi }|d0d1}t|d2}t||}|r||kr|}|j d3d%|t||d4d5 |j d6d%|||d7 |d8 t|||	}|d9|d:|tj|td;d'd< d= |	jrJ|rH|j d3d%|t|d>d?  nq|	jrQ nq|jsgd@dAlm} t|	 ||| n|jdBsrt|	 tjdCt|jdD\}}|tj kr|j d
d|!  dE| dd |jdFdgd}|j dd|d |jr|jdG nd>}|j dHd|d |S )Iz3Agent-driven line review. Returns ComplianceLedger.taskcoordinatorzReview brand seasonz line for launchtext	gate_line
escalationzASK human: gate line review? ()z'Approve GreenLight review of this line?approve)optionshuman_replyhumanannual_turnover_eur)r-   r/   turnover_eur)lineplan_claimsledgereventsc              
   S   s:   g | ]}|d  |d |d |d | di  ddqS )claim_idskur1   typemetaclaimed_recycled_pct)r?   r@   r1   rA   rC   r(   ).0cr"   r"   r#   
<listcomp>b   s    zrun.<locals>.<listcomp>c                 S   s0   g | ]}|d  |d | dg | ddqS )r@   r%   
attributescomposition)r@   r%   rH   rI   rD   )rE   sr"   r"   r#   rG   m   s    "skuszReview line for u   . Annual turnover €z,.0fz. Marketing claims:
   )indentu_   

Line materials (for discovery — some ethical claims may be possible but not yet declared):
z

Use tools for every step. Adjudicate all 6 claims, discover rising-demand opportunities, vet each opportunity, then finalize.system)rolecontentuser
agent_planz	Kimi-K2.6)stepsNi   )model
max_tokenstoolsrP   agentiX  
tool_callsuj   Continue — use tools to adjudicate remaining claims, discover opportunities, and finalize_determination.functionr%    	argumentsagent_stageactive)r   r   toolstatus	tool_call   )r^   r&   
agent_turnr   r^   r   )defaulti  )rO   tool_call_idrP   done)r   r   r_   r   )determinationprojected_contribution_eurpublish_determination)blocked_claimsz: file determination? (zFile the launch determination?recommendationdecision)"emitr   decideaskr	   r   jsondumpsSYSTEMr    range	MAX_TURNSr   chatr   MODEL_BRAINr   r(   finishedappendr   r*   r$   r   strrf   greenlight.agents_backfill_commercial
synthesizer   lenblockedPROCEEDupper)r;   r<   r>   r8   evgatewhyreplyr=   ctxclaims_brief
line_attrsuser_msgmessagescurrent_stageturnmsgrX   tcfnr%   r&   r   resultrf   gate2why2reply2recr"   r"   r#   runQ   s   &





 r   r   c                 C   sB   | j }|jdrdS tdddi|  tdi |  tdi |  dS )zFEnsure commercial metrics exist if the agent skipped those tool calls.rg   Nr   category	Outerwearr   r   )r=   r   r(   r   )r   r=   r"   r"   r#   rz      s   rz   c              
   C   s\   t  sdS zt| |||W S  ty- } z|jddd| dd W Y d}~dS d}~ww )zLRun Kimi agent when enabled; fall back to deterministic pipeline on failure.NerrorAgentzAgent loop failed (u   ) — deterministic fallbackr0   )r   	use_agentr   	Exceptionrl   )r;   r<   r>   r8   excr"   r"   r#   run_or_fallback   s   r   )__doc__ro   
greenlightr   r   greenlight.agents.toolingr   r   r   r   greenlight.enginer   greenlight.engine.ledgerr	   rs   rq   r    r)   rx   r$   dictr*   r   rz   r   r"   r"   r"   r#   <module>   s>    
#



	s
