
    Jj!                        U d Z ddlZddlZddlZddlZddlZddlmZ ddlZddl	Zddl
mZmZmZmZ ddlmZmZ ddlZddlmZ dZ G d d	          Zi Zeeef         ed
<   daeej                 ed<   d ZdefdZd Z G d de          Z  G d de          Z! G d de          Z" G d de          Z# G d de          Z$defdZ%dS )zJupyter notebook execution endpoints.

Provides per-cell execution with multi-session support. Each session gets its
own Jupyter kernel via nbclient. Requires the ``notebooks`` optional extra::

    pip install open-terminal[notebooks]
    N)Optional)	APIRouterDependsHTTPExceptionQuery)	BaseModelField)NotebookClienti  c                   &    e Zd ZdZdZdedefdZdS )_Sessionz/Wraps a NotebookClient for a specific notebook.)idpathnbclientbusy
created_at	last_used
session_idr   c                     || _         || _        || _        || _        d| _        t          j                    | _        t          j                    | _        d S )NF)r   r   r   r   r   timer   r   )selfr   r   r   r   s        q/home/rurouni/.cache/uv/archive-v0/6mr0qdqUAO9GXgnL/lib/python3.11/site-packages/open_terminal/utils/notebooks.py__init__z_Session.__init__%   sC    		)++    N)__name__
__module____qualname____doc__	__slots__strr    r   r   r   r       sA        99QI%3 %c % % % % % %r   r   	_sessions_cleanup_taskc                     K   	 t          j        d           d{V  t          j                    fdt                                          D             } | D ]}t          |           d{V  m)z>Periodically remove sessions idle for more than _IDLE_TIMEOUT.T<   Nc                 N    g | ]!\  }}|j         z
  t          k    |j        |"S r!   )r   _IDLE_TIMEOUTr   ).0sidsnows      r   
<listcomp>z&_idle_cleanup_loop.<locals>.<listcomp>8   s@     
 
 
QQ[ =000 000r   )asynciosleepr   r"   items_destroy_session)staler)   r+   s     @r   _idle_cleanup_loopr2   3   s      	(mBikk
 
 
 
#//++
 
 

  	( 	(C"3''''''''''	(r   r   c                    K   t                               | d           }|r:|j        r5	 |j                                         d {V  d S # t          $ r Y d S w xY wd S d S N)r"   popr   _async_cleanup_kernel	Exception)r   sessions     r   r0   r0   A   s      mmJ--G 7> 	.6688888888888 	 	 	DD	   s   A	 	
AAc                      t           t                                           r"t          j        t	                                a d S d S r4   )r#   doner-   create_taskr2   r!   r   r   _ensure_cleanup_taskr<   J   s<     2 2 4 4+,>,@,@AA r   c                   4    e Zd ZU  edd          Zeed<   dS )CreateSessionRequest.z!Absolute path to the .ipynb file.descriptionr   N)r   r   r   r	   r   r    __annotations__r!   r   r   r>   r>   U   s2         c'JKKKD#KKKKKr   r>   c                   .    e Zd ZU eed<   eed<   eed<   dS )CreateSessionResponser   kernelstatusNr   r   r   r    rA   r!   r   r   rC   rC   Y   s+         GGGKKKKKKKKr   rC   c                   d    e Zd ZU  edd          Zeed<    edd          Zee	         ed<   dS )ExecuteCellRequest.z!Zero-based cell index to execute.r?   
cell_indexNzJOverride cell source. If omitted, uses the source already in the notebook.source)
r   r   r   r	   rI   intrA   rJ   r   r    r!   r   r   rH   rH   _   sg         eC-PQQQJQQQ!Ef  FHSM     r   rH   c                   V    e Zd ZU eed<   dZee         ed<    ee	          Z
e	ed<   dS )ExecuteCellResponserE   Nexecution_count)default_factoryoutputs)r   r   r   r    rA   rN   r   rK   r	   listrP   r!   r   r   rM   rM   f   sL         KKK%)OXc])))E$///GT/////r   rM   c                   8    e Zd ZU eed<   eed<   eed<   eed<   dS )SessionStatusResponser   r   rD   rE   NrF   r!   r   r   rS   rS   l   s4         GGG
IIIKKKKKKKKr   rS   returnc                    t          ddgt          |           g          }|                    dt          dddd	          d
t          fd            }|                    dt
          dddd	          dt          d
t          fd            }|                    dt          ddd          dt          fd            }|
                    dddd          dt          fd            }|S )z;Create the notebooks router with the given auth dependency.z
/notebooks	notebooks)prefixtagsdependencies create_notebook_sessionzCreate a notebook sessionzaStart a Jupyter kernel for the given notebook. Returns a session ID for subsequent execute calls.F)response_modeloperation_idsummaryr@   include_in_schemareqc                   K   t                       t          j                            | j                  }t          j        j                            |           d {V st          dd|           t	          j        |d          4 d {V }|                                 d {V }d d d           d {V  n# 1 d {V swxY w Y   	 t          j
        |d          }n&# t          $ r}t          dd	|           d }~ww xY w|j                            d
i                               dd          }t          ||d          }	 |                                 |                                 d {V  |                                 d {V  n)# t          $ r}t          dd| d|           d }~ww xY wt%          j                    j        d d         }t+          ||||          t,          |<   t/          ||d          S )N  zNotebook not found: status_codedetailutf-8encoding   )
as_version  zInvalid notebook: 
kernelspecnamepython3x   )kernel_nametimeouti  zFailed to start kernel 'z':    ready)r   rD   rE   )r<   osr   abspathaiofilesisfiler   openreadnbformatreadsr7   metadatagetr
   create_kernel_managerasync_start_new_kernelasync_start_new_kernel_clientuuiduuid4hexr   r"   rC   )	r`   r   fcontentr   erp   r   r   s	            r   create_sessionz/create_notebooks_router.<locals>.create_session   s      	wsx(([%,,T22222222 	WC8Ut8U8UVVVV =888 	% 	% 	% 	% 	% 	% 	%AFFHHnnnnnnG	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%	RA666BB 	R 	R 	RC8PQ8P8PQQQQ	R koolB77;;FINN  SIII	((***//111111111668888888888 	 	 	E+EE!EE   	 Z\\%crc*
 (T2v F F	*$+g
 
 
 	
sC   B<<
C	CC% %
D/DDAF 
F< F77F<z/{session_id}/executeexecute_notebook_cellzExecute a notebook cellzExecute a single cell in the given session. Optionally override the cell source. Updates the .ipynb file in place after execution.r   c           
         K   t                               |           }|st          dd          |j        rt          dd          |j        }|j        dk     s|j        t          |j                  k    r2t          dd|j         d	t          |j                  d
z
   d          |j        |j                 }|j        |j        |_        d|_        t          j	                    |_
        	 |j                            ||j                   d {V  nb# t          $ rU}d|_        t          ddt          |          j        t#          |          t#          |          gdg          cY d }~S d }~ww xY wd|_        t          j	                    |_
        g }|j        D ]B}t'          |          }d|v rt'          |d                   |d<   |                    |           C|                    d          }		 t+          j        |          }
t/          j        |j        dd          4 d {V }|                    |
           d {V  d d d           d {V  n# 1 d {V swxY w Y   n# t          $ r Y nw xY wt          d|	|          S )Nrb   Session not foundrc   i  zCell already executingr   rk   zcell_index z out of range (0..   )TFerror)output_typeenameevalue	traceback)rE   rP   datarN   wrf   rg   ok)rE   rN   rP   )r"   r}   r   r   r   rI   lencellsrJ   r   r   r   async_execute_cellr7   rM   typer   r    rP   dictappendrz   writesrv   rx   r   write)r   r`   r8   r   cellr   rP   oodecnb_jsonr   s               r   execute_cellz-create_notebooks_router.<locals>.execute_cell   sq      --
++ 	MC8KLLLL< 	RC8PQQQQZ>A3rx==!@!@[S^[[s28}}WXGX[[[   
 x':!*DK IKK	.33D#.IIIIIIIIII 	 	 	 GL& (/!%a!1"%a&&&)!ffX	 
 
 
 
 
 
 
 
 
	  IKK  	 	AaB||!"V*--6
NN2XX'((	ob))G}W\3III ' ' ' ' ' ' 'Qggg&&&&&&&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 	 	 	D	 #W
 
 
 	
sU   .&D 
E4A
E/)E4/E486I. .I
I. 
I&&I. )I&*I. .
I;:I;z/{session_id}get_notebook_sessionzGet notebook session status)r\   r]   r^   r_   c                   K   t                               |           }|st          dd          |j        j                            di                               dd          }|j        rdnd}t          |j        |j        ||	          S )
Nrb   r   rc   rl   rm   rn   r   rs   )r   r   rD   rE   )	r"   r}   r   r   r|   r   rS   r   r   )r   r8   rp   rE   s       r   get_sessionz,create_notebooks_router.<locals>.get_session   s       --
++ 	MC8KLLLLj)--lB??CCI
 
 #<4W$z[
 
 
 	
r   delete_notebook_sessionzStop a notebook session)r]   r^   r_   c                 l   K   | t           vrt          dd          t          |            d {V  ddiS )Nrb   r   rc   rE   stopped)r"   r   r0   )r   s    r   delete_sessionz/create_notebooks_router.<locals>.delete_session  sR       Y&&C8KLLLLz*********)$$r   )r   r   postrC   r>   rM   r    rH   r}   rS   delete)verify_api_keyrouterr   r   r   r   s         r   create_notebooks_routerr   x   su    ]n--.  F [[
,.+w   $
"6 $
 $
 $
 $
L [[*,)<   ?
s ?
1C ?
 ?
 ?
 ?
B ZZ,+-   
c 
 
 
 
 ]].)	   % % % % % Mr   )&r   r-   jsonrt   r   r   typingr   rv   aiofiles.osfastapir   r   r   r   pydanticr   r	   rz   nbclientr
   r'   r   r"   r   r    rA   r#   Taskr2   r0   r<   r>   rC   rH   rM   rS   r   r!   r   r   <module>r      sd       				              < < < < < < < < < < < < % % % % % % % %  # # # # # # % % % % % % % % "$	4X # # #(,x% , , ,( ( (s    B B BL L L L L9 L L L    I          0 0 0 0 0) 0 0 0    I   cy c c c c c cr   