
    'iYa                        S r SSKrSSKrSSKrSSKJrJr  SSKJr  SSKJ	r	J
r
JrJr  SSKJr   SSKJr  \" \5      R$                  R$                  S-  r\" \5         SSKJr  S	r SSKJrJr  S	r\ " S S5      5       r  " S S5      r!\ " S S5      5       r" " S S5      r#S r$\%S:X  a  \$" 5         gg! \ a     N`f = f! \ a    S
rSSKrSSKr Nmf = f! \ a    S
rSr Nrf = f)aI  
GENESIS GEMINI EXECUTOR
=======================
Direct Gemini API execution for Hyperdrive mode.
Uses $300 Google AI Studio credits.

No Antigravity proxy needed - direct API calls.

Models (January 2026 - Updated):
- gemini-2.0-flash: Primary workhorse (2K RPM, 4M TPM, Unlimited RPD)
- gemini-2.5-flash: Newer model (1K RPM, 1M TPM, 10K RPD)
- gemini-2.5-pro: Complex reasoning (150 RPM, 2M TPM, 10K RPD)
- gemini-2.0-flash-lite: High throughput simple tasks (4K RPM)

Integrated with GeminiRateMaximizer for intelligent rate limit management.

Usage:
    executor = GeminiExecutor()
    result = executor.execute("Implement feature X")
    print(result.response)

    # With rate limit awareness
    executor = GeminiExecutor(use_rate_maximizer=True)
    result = executor.execute_optimized("Analyze this code", task_type="code_review")
    N)datetime	timedelta)Path)DictOptionalAnyList)	dataclass)load_dotenvz.envTF)GeminiRateMaximizerTaskTypec                   t    \ rS rSr% Sr\\S'   \\S'   \\S'   \\S'   \	\S'   \	\S'   \\S	'   S
r
\\   \S'   Srg
)GeminiResponse=   zResponse from Gemini execution.successresponsemodeltokens_usedcost_estimateexecution_timetask_completeNerror )__name__
__module____qualname____firstlineno____doc__bool__annotations__strintfloatr   r   __static_attributes__r       )E:\genesis-system\core\gemini_executor.pyr   r   =   s:    )MMJE8C=r%   r   c                      \ rS rSrSr/ SQrSSSSSS	.rS
SSSSSS
S.rSSSSSSSSSS.	rS/S\	S\	S\
4S jjrS\\	   4S jr     S0S\	S\	S\	S\S\S\	S\4S jjr      S1S\	S\	S\	S\S\S \S\	S\4S! jjrS\\   4S" jrS2S#\S\	S\	4S$ jjr S3S\	S\	S\	S\S\S\	S\	4S% jjrS\	S\	S\	S\S\S\	4S& jrS'\S(\	4S) jr S4S*\S+\	S\4S, jjrS\4S- jrS.rg)5GeminiExecutorJ   z
Direct Gemini API executor for Genesis Hyperdrive.

Uses $300 in Google AI Studio credits.
No proxy needed - direct API calls.
)GEMINI_API_KEYGOOGLE_API_KEYzJE:/genesis-system/Credentials/GoogleAIStudio-Gemini-AgileAdapt-API-KEY.txtgemini-3-flash-previewgemini-2.5-flashgemini-3-pro-previewgemini-2.0-flash-litegemini-2.0-flash-exp)flashflash2proliteexpg?g333333?g      @g333333?g333333?)zgemini-2.0-flashr,   r.   r-   zgemini-2.5-pror/   r0   )	researchcode_generationcode_reviewarchitecturesimple_extractionclassificationsummarizationagentic_visiondeep_visionNapi_keydefault_modeluse_rate_maximizerc                    U=(       d    U R                  5       U l        U R                  R                  X"5      U l        [        S5      U l        SU l        S U l        U(       a  [        (       a   [        5       U l        [        (       a1  U R                  (       a  [        R                  " U R                  S9  g g g ! [         a  n[        SU 35         S nANZS nAff = f)Nz)E:/genesis-system/data/gemini_usage.jsonl        z.Warning: Could not initialize rate maximizer: r?   )_load_api_keyr?   MODELSgetr@   r   usage_log_pathtotal_spentrate_maximizerRATE_MAXIMIZER_AVAILABLEr   	ExceptionprintGENAI_AVAILABLEgenai	configure)selfr?   r@   rA   es        r&   __init__GeminiExecutor.__init__z   s    6$"4"4"6![[__]J"#NO #":":L&9&;# ?t||OODLL1  ,?  LFqcJKKLs   0B< <
CCCreturnc                 p   U R                   SS  H-  n[        R                  R                  U5      nU(       d  M+  Us  $    [	        U R                   S   5      nUR                  5       (       aI  UR                  5       R                  5       nSU;   a#  UR                  SS5      S   R                  5       $ U$ g)z&Load API key from environment or file.N   =   )	API_KEY_SOURCESosenvironrG   r   exists	read_textstripsplit)rQ   env_varkeykey_filecontents        r&   rE   GeminiExecutor._load_api_key   s     ++BQ/G**..)Cs
 0 ,,Q/0??((*002Gg~}}S!,Q/5577Nr%   promptr   system_prompt
max_tokenstemperaturecached_content_namec                    U(       a  U R                   R                  X"5      OU R                  n[        R                  " 5       nU R                  (       d  [        SSUSSSSSS9$  [        (       a  U R                  XX4XV5      n	OU R                  XX4U5      n	[        R                  " 5       U-
  n
[        U	R                  5       5      S-  nUS-  U R                  R                  US5      -  nS	U	;   n[        S
U	U[        U5      UU
US9nU R                  XSS 5        U =R                  U-  sl        U R                  (       aS  [        UR                  5       5      S-  nU(       a  SnU R                  R!                  U[        U5      [        U5      S
S9  U$ ! ["         a9  n[        SSUSS[        R                  " 5       U-
  S[%        U5      S9s SnA$ SnAff = f)ag  
Execute a prompt with Gemini.

Args:
    prompt: The task/prompt to execute
    model: Model to use (flash, pro, exp, or full model name)
    system_prompt: Optional system instruction
    max_tokens: Max output tokens
    temperature: Sampling temperature
    cached_content_name: Optional Titan Memory name to use

Returns:
    GeminiResponse with results
F r   zNo API key configured)r   r   r   r   r   r   r   r   ?i@B       ?TASK_COMPLETET)r   r   r   r   r   r   r   Nd   )input_tokensoutput_tokensr   )rF   rG   r@   timer?   r   rN   _execute_with_sdk_execute_with_restlenr`   COSTSr"   
_log_usagerI   rJ   record_usagerL   r!   )rQ   rf   r   rg   rh   ri   rj   
model_name
start_timer   r   tokens_estimatecostr   resultrq   rR   s                    r&   executeGeminiExecutor.execute   s   . 7<T[[__U2ASAS
YY[
||!  #-	 	;	11;
  22; "YY[:5N "(.."23c9O#i/4::>>*d3SSD ,x7M#! 0"-+F OOF4CL1$ """6<<>2S8&#$L##00!$\!2"%o"6 	 1  M 
	! #yy{Z7#!f	 	
	s   &D3F 
G$.GGG	task_typepriorityc           	      L   [        [        UR                  5       5      S-  5      U-   nU R                  (       a  [        (       a  Sn	[
        (       a   [        U5      n	U R                  R                  UU	=(       d    [
        R                  US9n
U
R                  nU
R                  S:  a   [        R                  " U
R                  5        O%U R                  R                  X R                  5      nU R!                  UUUUUUS9$ ! [         a    [
        R                  n	 Nf = f)a;  
Execute with intelligent model selection and rate limit awareness.

Uses the GeminiRateMaximizer to select the best available model
based on current utilization and task type.

Args:
    prompt: The task/prompt to execute
    task_type: Type of task for routing (research, code_generation, etc.)
    system_prompt: Optional system instruction
    max_tokens: Max output tokens
    temperature: Sampling temperature
    priority: Request priority (1-10, lower = higher)
    cached_content_name: Optional Titan Memory name to use

Returns:
    GeminiResponse with results
rm   N)token_estimater   r   r   )rf   r   rg   rh   ri   rj   )r"   rv   r`   rJ   rK   r   
ValueErrorGENERALschedule_requestr   delay_secondsrs   sleepTASK_ROUTINGrG   r@   r   )rQ   rf   r   rg   rh   ri   r   rj   r   task_type_enum	scheduledr   s               r&   execute_optimized GeminiExecutor.execute_optimized  s   : S0367*D #;#;!Nx6%-i%8N
 ++<<-(<H,<,<! = I OOE &&*

9223 %%)))5G5GHE ||'!# 3  
 	
) " 6%-%5%5N6s   D D#"D#c                     U R                   (       aT  U R                   R                  5       nUR                  UR                  UR                  UR
                  UR                  S.$ g)zx
Get current rate limit utilization report.

Returns:
    Utilization report dict or None if rate maximizer unavailable
)	timestamp
best_modeltotal_capacity_usedmodelsrecommendationsN)rJ   get_utilization_reportr   r   r   r   r   )rQ   reports     r&   r   %GeminiExecutor.get_utilization_reportD  s[     ((??AF#--$//'-'A'A --#)#9#9  r%   r   c                 (   U R                   (       a=  [        (       a2  [        (       a'   [        U5      nU R                   R                  X5      $ U R                  R                  X R                  5      $ ! [         a    [        R                  n N\f = f)z
Get best available model for a request.

Args:
    token_estimate: Estimated tokens needed
    task_type: Type of task

Returns:
    Model name
)	rJ   rK   r   r   r   get_best_modelr   rG   r@   )rQ   r   r   r   s       r&   r   GeminiExecutor.get_best_modelV  sx     #;#;2!))!4 &&55nUU  $$Y0B0BCC	  2!)!1!12s   A4 4BBc                    U(       aH   [         R                  R                  R                  U5      n[         R                  R                  US9nO[         R                  " UUS9n[         R                  " UUS9n
UR                  UU
S9nUR                  $ ! [         a0  n	[        SU SU	 35        [         R                  " UUS9n Sn	A	NfSn	A	ff = f)z&Execute using google-generativeai SDK.)cached_contentz*Titan Memory Warning: Failed to use cache : )rz   system_instructionN)max_output_tokensri   )generation_config)rO   cachingCachedContentrG   GenerativeModelfrom_cached_contentrL   rM   GenerationConfiggenerate_contenttext)rQ   rf   r   rg   rh   ri   rj   cache	model_objrR   r   r   s               r&   rt    GeminiExecutor._execute_with_sdkj  s     33778KL!11EEUZE[	 -- #0I
 "22(#

 --/ . 

 }}/  BCVBWWYZ[Y\]^!11$'4	s   AB 
C &CCc                 x   SU SU R                    3nSSU0/0/UUS.S.nU(       a
  SSU0/0US'   [        R                  " U5      R                  5       n[        R
                  R                  UUSS	0S
9n	[        R
                  R                  U	SS9 n
[        R                  " U
R                  5       R                  5       5      nSSS5        WR                  S/ 5      nU(       aA  US   R                  S0 5      R                  S/ 5      nU(       a  US   R                  SS5      $ g! , (       d  f       Ni= f)z Execute using REST API directly.z8https://generativelanguage.googleapis.com/v1beta/models/z:generateContent?key=partsr   )maxOutputTokensri   )contentsgenerationConfigsystemInstructionzContent-Typeapplication/json)dataheadersx   )timeoutN
candidatesr   rd   rl   )r?   jsondumpsencodeurllibrequestRequesturlopenloadsreaddecoderG   )rQ   rf   r   rg   rh   ri   urlpayloadr   reqrespr~   r   r   s                 r&   ru   !GeminiExecutor._execute_with_rest  s<    IOdeieqeqdrs "VV$4#567#-*!
 ,3v}6M5N+OG'(zz'"))+nn$$#%78 % 
 ^^##C#5ZZ		 2 2 45F 6 ZZb1
qM%%i488"EEQx||FB// 65s   3D++
D9r~   prompt_previewc           	         U R                   R                  R                  SSS9  [        R                  " 5       R                  5       UR                  UR                  UR                  UR                  UR                  UR                  US.n[        U R                   S5       nUR                  [        R                  " U5      S-   5        SSS5        g! , (       d  f       g= f)zLog usage for budget tracking.T)parentsexist_ok)r   r   tokensr}   r   r   r   r   a
N)rH   parentmkdirr   now	isoformatr   r   r   r   r   r   openwriter   r   )rQ   r~   r   entryfs        r&   rx   GeminiExecutor._log_usage  s    ""(((E "113\\(((($33~~#11,	
 $%%s+qGGDJJu%,- ,++s   #)C
C#taskworking_dirc                 z   UR                  SS5      nUR                  SS5      nUR                  S/ 5      nUR                  SS5      nSR                  U Vs/ s H/  nS[        U[        5      (       a  UR                  SU5      OU 3PM1     sn5      nS	U S
U SU SU SU S3n	Sn
U R	                  XS9$ s  snf )zx
Execute a task from tasks.json format.

Builds a proper prompt with acceptance criteria
and verification instructions.
titlezUnknown Taskdescriptionrl   acceptance_criteriacontextr   z- z$# GENESIS HYPERDRIVE TASK

## Task: z

## Description
z

## Acceptance Criteria
z

## Context
z

## Working Directory
a  

## Instructions
1. Analyze this task carefully
2. Implement the solution
3. Verify against EACH acceptance criterion
4. Report PASS or FAIL for each criterion
5. If ALL criteria pass, include: TASK_COMPLETE
6. If ANY fail, explain what needs to be fixed

## Response Format
```
CRITERION 1: [PASS/FAIL] - [explanation]
CRITERION 2: [PASS/FAIL] - [explanation]
...

IMPLEMENTATION:
[Your implementation or explanation]

STATUS: [TASK_COMPLETE or TASK_INCOMPLETE]
```

Execute now.zYou are a Genesis Hyperdrive agent executing autonomous tasks.
You have full authority to implement solutions.
Be precise, verify your work, and report accurately.
Never claim completion without actual verification.)rg   )rG   join
isinstancedictr   )rQ   r   r   r   r   criteriar   ccriteria_textrf   rg   s              r&   execute_taskGeminiExecutor.execute_task  s     .1hh}b188126((9b)		#
 Jq$,?,?}a(QGH#
 


      		 
  $L7
 ||F|@@a#
s   6B8c           	      r   SnSnSnU R                   R                  5       (       aW  [        U R                   5       nU H3  n [        R                  " U5      nX&R                  SS5      -  nUS-  nM5     SSS5        UUX-
  UUS:  a  X#-  OS[        X-
  S-  5      S.$ !    Mg  = f! , (       d  f       N9= f)	z Get current budget usage status.g     r@rC   r   r}   rY   Nrn   )total_budgetspent	remaining
iterationsavg_cost_per_iterationestimated_iterations_left)rH   r]   r   r   r   rG   r"   )rQ   r   r   r   r   liner   s          r&   get_budget_status GeminiExecutor.get_budget_status  s     
%%''d))*aD $

4 061!55"a
	  + )%-$<FNe&8PT),l.Bd-J)K
 	
 +*s#   B(/B 1B( B%"B((
B6)r?   r@   rJ   rI   rH   )Nr1   T)NN    ffffff?N)generalNr   r      N)i  r   )N)zE:/genesis-system)r   r   r   r   r   rZ   rF   rw   r   r!   r   rS   r   rE   r"   r#   r   r   r   r   r   r   rt   ru   rx   r   r   r$   r   r%   r&   r(   r(   J   ss   O *$%'%F !"& $ !% $E -3-.4112-
L2 23 2^b 2"x} , ! #'aa a 	a
 a a !a 
aL #! #'A
A
 A
 	A

 A
 A
 A
 !A
 
A
F $DS DC DX[ D6 $()) ) 	)
 ) ) !) 
)V'' ' 	'
 ' ' 
'R. . .* /@A@A @A 
	@AF
4 
r%   r(   c                   Z    \ rS rSr% Sr\\S'   \\S'   \\S'   \\S'   \\S'   Sr\\S	'   S
r	g)TitanMemoryi/  z
Represents a 'Titan' persistent memory block (Context Cache).

This holds the reference to the cached content on Google's servers.
namedisplay_namer   expire_timetoken_counti  ttl_secondsr   N)
r   r   r   r   r   r!   r    r"   r   r$   r   r%   r&   r   r   /  s/    
 IJKr%   r   c                       \ rS rSrSrS\4S jr   SS\\   S\S\S	\	S
\
\   4
S jjrS\S
\
\   4S jrS
\\   4S jrSrg)TitanMemoryManageri>  z5
Manages the 'Titan' memory layer (Context Caching).
r?   c                 d    Xl         [        (       a  [        R                  " U R                   S9  g g )NrD   )r?   rN   rO   rP   )rQ   r?   s     r&   rS   TitanMemoryManager.__init__C  s!    ?OODLL1 r%   Nfilesr   r   ttl_minutesrU   c           
      p   [         (       d  [        S5        g U=(       d!    S[        [        R                  " 5       5       3n/ n[        S[	        U5       S35        U H  nUR                  5       (       d  M  SnUR                  S:X  a  SnO8UR                  S	:X  a  S
nO%UR                  S:X  a  SnOUR                  S:X  a  Sn[        R                  " XgUR                  S9nUR                  U5        M     [        S5        U Hq  n	U	R                  R                  S:X  d  M  [        R                  " S5        [        R                  " U	R                  5      n	U	R                  R                  S:X  a  MR  Ms     [        SU S35        [        R                  R                  R!                  UUSU[#        US9S9n
[%        U
R                  U
R&                  U
R(                  [+        U
R,                  5      U
R.                  R0                  US-  S9$ ! [2         a  n[        SU 35         SnAgSnAff = f)z7
Create a new Titan Memory block from a list of files.
z4Error: Titan Memory requires google-generativeai SDKNgenesis_memory_zTitan Memory: Uploading z	 files...z
text/plainz.pyztext/x-pythonz.mdztext/markdownz.jsonr   z.htmlz	text/html)path	mime_typer   z,Titan Memory: Waiting for file processing...
PROCESSINGrY   zTitan Memory: creating cache 'z'...ztYou are the Genesis System. You have full recursive knowledge of your own source code provided in this memory block.)minutes)r   r   r   r   ttl<   )r   r   r   r   r   r   zTitan Memory Error: )rN   rM   r"   rs   rv   r]   suffixrO   upload_filer   appendstater   get_filer   r   creater   r   r   r   r!   r   usage_metadatatotal_token_countrL   )rQ   r   r   r   r   uploaded_files	file_pathr  pfr   r   rR   s               r&   create_memory TitanMemoryManager.create_memoryH  s    HI0	'O_S=M<N+OLN ,SZL	BC"	 ''))(	##u,/i%%.O	%%0>P)%%0k)&&IYbYgYgh%%b) # @A#gglll2JJqMqvv.A gglll2 $ 2<.EFMM//66) $Z'k2 7 E ZZ"//kk 1 12!00BB'",   	(,-	s&   D	H &AH 8BH 
H5H00H5r   c                 2   [         (       d  g [        R                  R                  R	                  U5      n[        UR                  UR                  UR                  [        UR                  5      UR                  R                  S9$ ! [         a     gf = f)z"Retrieve an existing memory block.Nr   r   r   r   r   )rN   rO   r   r   rG   r   r   r   r   r!   r   r  r  rL   )rQ   r   r   s      r&   
get_memoryTitanMemoryManager.get_memory  s}    t
	MM//33D9EZZ"//kk 1 12!00BB   		s   A:B	 	
BBc                 h   [         (       d  / $ / n [        R                  R                  R	                  5        Hd  nUR                  [        UR                  UR                  UR                  [        UR                  5      UR                  R                  S95        Mf     U$ ! [         a     U$ f = f)zList all active memories.r  )rN   rO   r   r   listr
  r   r   r   r   r!   r   r  r  rL   )rQ   memoriesr   s      r&   list_memories TitanMemoryManager.list_memories  s    r	
	4499;!&!3!3++ #E$5$5 6 % 4 4 F F!  <   		s   BB# #
B10B1rD   )Nzgemini-2.0-flash-001r  )r   r   r   r   r   r!   rS   r	   r   r"   r   r   r  r  r  r$   r   r%   r&   r   r   >  s    2 2 !+>Dz> > 	>
 > 
+	>@s x'< tK0 r%   r   c                  f   [        5       n [        S5        U R                  (       d  [        S5        g[        SU R                  SS  SU R                  SS  35        [        SU R                   35        [        S	5        U R	                  S
SS9n[        SUR
                   35        [        SUR                  SS  35        [        SUR                   35        [        SUR                  S 35        [        SUR                  S S35        [        (       a+  [        S5        [        U R                  5      n[        S5        UR                  (       a  [        SUR                   35        [        S5        U R                  5       nUR                  5        H  u  pE[        U SU 35        M     g)zQuick test of Gemini execution.z=== GEMINI EXECUTOR TEST ===\nzERROR: No API key found!Nz	API Key: 
   z...zDefault Model: z\n--- Testing Simple Prompt ---z*What is 2 + 2? Reply with just the number.r1   )r   z	Success: z
Response: rp   zTokens: zCost: $z.4fzTime: z.2fsz)\n--- Testing Titan Memory Capability ---zTitan Manager initialized.zError: z\n--- Budget Status ---r   )r(   rM   r?   r@   r   r   r   r   r   r   rN   r   r   r   items)executorr~   titanstatusrb   values         r&   test_geminir'    s   H	
+, ()	Ih&&s+,C0@0@0E/F
GH	OH223
45 

,-4  F
 
Ifnn%
&'	Jvt,-
./	HV''(
)*	GF((-
./	F6((-Q
/0 :;"8#3#34*+ ||~&' 

$%'')Flln
Rw  %r%   __main__)&r   r[   r   rs   r   r   pathlibr   typingr   r   r   r	   dataclassesr
   dotenvr   __file__r   	_env_pathImportErrorgoogle.generativeaigenerativeairO   rN   urllib.requestr   urllib.errorcore.gemini_rate_maximizerr   r   rK   r   r(   r   r   r'  r   r   r%   r&   <module>r5     s  4 
   (  , , !	"X%%,,v5I	
'OH# 	  	  	 b
 b
J   h hV*!Z zM ]  		  O  $Hs5   -B5 C '
C 5B>=B>CC
C$#C$