@datalayer/agent-runtimes 1.3.102 → 1.3.104
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-embed/chunks/{AgentDetails-CO9iM59C.js → AgentDetails-eWkEnFI1.js} +1 -1
- package/dist-embed/chunks/{AgentDetailsDialog-DmD6xm6k.js → AgentDetailsDialog-BXJek5nf.js} +1 -1
- package/dist-embed/chunks/{AgentInspector-kDMuvh45.js → AgentInspector-B1wLMu4Z.js} +1 -1
- package/dist-embed/chunks/{AgentInspectorDialog-fT96Pb4Z.js → AgentInspectorDialog-DcLrhdWo.js} +1 -1
- package/dist-embed/chunks/Avatar-BrPfm89P.js +1 -0
- package/dist-embed/chunks/{CellSidebarExtension-B-vao30u.js → CellSidebarExtension-BWsHtuqs.js} +2 -2
- package/dist-embed/chunks/ChatView-ef0jot57.js +32 -0
- package/dist-embed/chunks/DatalayerAgentBridge-DvlGUOdE.js +1 -0
- package/dist-embed/chunks/{DeckComponent-Fp6Vw8vN.js → DeckComponent-BfOXdQhk.js} +1 -1
- package/dist-embed/chunks/{DocumentView-DKUbyyJg.js → DocumentView-DCgaQoOU.js} +1 -1
- package/dist-embed/chunks/{EphemeralDocument-CgYPEfGC.js → EphemeralDocument-DVAfnQWS.js} +1 -1
- package/dist-embed/chunks/{EphemeralNotebook-DvDbCKnr.js → EphemeralNotebook-C1ANS_1u.js} +1 -1
- package/dist-embed/chunks/{ExcalidrawComponent-BehqBpwC.js → ExcalidrawComponent-0e3KqmKJ.js} +1 -1
- package/dist-embed/chunks/{ExcalidrawModal-B2sXbVJB.js → ExcalidrawModal-C5Or1sZ5.js} +1 -1
- package/dist-embed/chunks/{Flash-DdFxPtBI.js → Flash-C3nF3s4G.js} +1 -1
- package/dist-embed/chunks/{JupyterLexicalExtension-CUsjvchq.js → JupyterLexicalExtension-CEjN8cLT.js} +7 -7
- package/dist-embed/chunks/{KernelVariables-BUmOt4yF.js → KernelVariables-DyYN9sSS.js} +1 -1
- package/dist-embed/chunks/{NotebookSkeleton-D9WNoiWD.js → NotebookSkeleton-z8GKB7Tb.js} +1 -1
- package/dist-embed/chunks/{NotebookToolbar-C2_ZC9Ej.js → NotebookToolbar-Dv7QkxKA.js} +1 -1
- package/dist-embed/chunks/{NotebookView-BActuABH.js → NotebookView-CNHzc28A.js} +1 -1
- package/dist-embed/chunks/{SandboxDetailsDialog-C0afmOA7.js → SandboxDetailsDialog-D4HA7PZA.js} +1 -1
- package/dist-embed/chunks/{SchemaForm-B351kd79.js → SchemaForm-bWlj1cVy.js} +1 -1
- package/dist-embed/chunks/{Toolbar-B6ROXJ-2.js → Toolbar-BxAi9T92.js} +1 -1
- package/dist-embed/chunks/{YouTubePlugin-CqA-IwCx.js → YouTubePlugin-ZawlUPsx.js} +1 -1
- package/dist-embed/chunks/{ar-SA-G6X2FPQ2-DhQlC4AZ.js → ar-SA-G6X2FPQ2-DqE6ftcU.js} +1 -1
- package/dist-embed/chunks/{az-AZ-76LH7QW2-CDvJeI6H.js → az-AZ-76LH7QW2-8y_pqJhn.js} +1 -1
- package/dist-embed/chunks/{bg-BG-XCXSNQG7-B_2t7dwS.js → bg-BG-XCXSNQG7-4NX5jouU.js} +1 -1
- package/dist-embed/chunks/{bn-BD-2XOGV67Q-B7nTDj-4.js → bn-BD-2XOGV67Q-BB87_pS6.js} +1 -1
- package/dist-embed/chunks/{ca-ES-6MX7JW3Y-llJD_i9l.js → ca-ES-6MX7JW3Y-B9gyglRE.js} +1 -1
- package/dist-embed/chunks/{cs-CZ-2BRQDIVT-Cm_uiYT0.js → cs-CZ-2BRQDIVT-CmZhtHam.js} +1 -1
- package/dist-embed/chunks/{da-DK-5WZEPLOC-B0lo6-wZ.js → da-DK-5WZEPLOC-CU6rP6vm.js} +1 -1
- package/dist-embed/chunks/{de-DE-XR44H4JA-DZrN-mJo.js → de-DE-XR44H4JA-wk6_Fx0e.js} +1 -1
- package/dist-embed/chunks/{el-GR-BZB4AONW-C4D5ZbOc.js → el-GR-BZB4AONW-Cy5yeukb.js} +1 -1
- package/dist-embed/chunks/{es-ES-U4NZUMDT-D1yiS-ZI.js → es-ES-U4NZUMDT-Ccr3g95I.js} +1 -1
- package/dist-embed/chunks/{eu-ES-A7QVB2H4-Zm3lJsL6.js → eu-ES-A7QVB2H4-u0DKk40F.js} +1 -1
- package/dist-embed/chunks/{fa-IR-HGAKTJCU-Dhv2lg_O.js → fa-IR-HGAKTJCU-BYSSU2Gx.js} +1 -1
- package/dist-embed/chunks/{fi-FI-Z5N7JZ37-QeFFEfyg.js → fi-FI-Z5N7JZ37-98vDI-0h.js} +1 -1
- package/dist-embed/chunks/{fr-FR-RHASNOE6-DjbRpOS6.js → fr-FR-RHASNOE6-D2BvErn0.js} +1 -1
- package/dist-embed/chunks/{gl-ES-HMX3MZ6V-C-ev9dqC.js → gl-ES-HMX3MZ6V-DP7FRXtT.js} +1 -1
- package/dist-embed/chunks/{he-IL-6SHJWFNN-DHoNpuA6.js → he-IL-6SHJWFNN-B92ZDKBK.js} +1 -1
- package/dist-embed/chunks/{hi-IN-IWLTKZ5I-JZJZPoWj.js → hi-IN-IWLTKZ5I-Dw2EhOq2.js} +1 -1
- package/dist-embed/chunks/{hu-HU-A5ZG7DT2-RzCikyBW.js → hu-HU-A5ZG7DT2-CVh5JW9n.js} +1 -1
- package/dist-embed/chunks/{id-ID-SAP4L64H-Bn08nS9B.js → id-ID-SAP4L64H-CaKn7Yw0.js} +1 -1
- package/dist-embed/chunks/{index-DIHzcHI1.js → index-5Mm_lDnH.js} +1 -1
- package/dist-embed/chunks/{index-B1StFYI5.js → index-B46RcdCt.js} +1 -1
- package/dist-embed/chunks/{index-qzUKNibz.js → index-B6RMWdb4.js} +1 -1
- package/dist-embed/chunks/{index-88CEdMmU.js → index-BI_ojvKX.js} +1 -1
- package/dist-embed/chunks/{index-uutAM7NJ.js → index-BWxQD9cP.js} +1 -1
- package/dist-embed/chunks/{index-DCX_IqLg.js → index-B_WAs-60.js} +1 -1
- package/dist-embed/chunks/{index-BYofH50G.js → index-BaEB7wmN.js} +1 -1
- package/dist-embed/chunks/{index-C0iUgNwj.js → index-BmSB4k4X.js} +1 -1
- package/dist-embed/chunks/{index-KWzHwvvN.js → index-BsGIdntV.js} +4 -4
- package/dist-embed/chunks/{index-DgnVcOqG.js → index-BsP7mWx7.js} +1 -1
- package/dist-embed/chunks/{index-aX9x7qni.js → index-BzZvBTsd.js} +1 -1
- package/dist-embed/chunks/{index-BA2STD4N.js → index-C0ac25cM.js} +2 -2
- package/dist-embed/chunks/{index-DLk6Znxv.js → index-C0fJQ9v3.js} +1 -1
- package/dist-embed/chunks/{index-Bs1pVq7E.js → index-C0p6TrSH.js} +1 -1
- package/dist-embed/chunks/{index-DZN9JYOE.js → index-C9mAUugR.js} +1 -1
- package/dist-embed/chunks/{index-B1Egld01.js → index-CNBMan5A.js} +1 -1
- package/dist-embed/chunks/{index-1Ekpl0uC.js → index-CawAyW3R.js} +1 -1
- package/dist-embed/chunks/{index-DeYQGrTz.js → index-Cb-91zWU.js} +1 -1
- package/dist-embed/chunks/{index-B2dtLxcg.js → index-CkMGJGPw.js} +1 -1
- package/dist-embed/chunks/{index-Cqur_rhw.js → index-CsbfZWj5.js} +1 -1
- package/dist-embed/chunks/{index-DsX9nIHt.js → index-D1HhRyAi.js} +1 -1
- package/dist-embed/chunks/{index-C5xKtdLU.js → index-D3ml5vHy.js} +1 -1
- package/dist-embed/chunks/{index-CqKV027P.js → index-D7SzNRox.js} +1 -1
- package/dist-embed/chunks/{index-BUbwVG__.js → index-DAwoO3Uu.js} +1 -1
- package/dist-embed/chunks/{index-DHVYKZ44.js → index-DQaxtq0S.js} +1 -1
- package/dist-embed/chunks/{index-BbsUSk_Q.js → index-DbPtsB38.js} +1 -1
- package/dist-embed/chunks/{index-DJomc4za.js → index-DoYPeIKg.js} +1 -1
- package/dist-embed/chunks/{index-hqa_ODOD.js → index-Dr_NppDz.js} +1 -1
- package/dist-embed/chunks/{index-D7rnWGLu.js → index-DuDsMDnx.js} +3 -3
- package/dist-embed/chunks/{index-B5MiaXUV.js → index-IIxS-G5t.js} +1 -1
- package/dist-embed/chunks/{index-90Ss7516.js → index-W7nq_bBb.js} +1 -1
- package/dist-embed/chunks/{index-Cjx6uk6z.js → index-r_7Z9Uyr.js} +1 -1
- package/dist-embed/chunks/{index.esm-DlPZAW-m.js → index.esm-D5bfliIL.js} +1 -1
- package/dist-embed/chunks/{it-IT-JPQ66NNP-C2vJMuKM.js → it-IT-JPQ66NNP-CJGzhajv.js} +1 -1
- package/dist-embed/chunks/{ja-JP-DBVTYXUO-C8KOKQt9.js → ja-JP-DBVTYXUO-Jm7LgxUu.js} +1 -1
- package/dist-embed/chunks/{kaa-6HZHGXH3-CvxJbmMB.js → kaa-6HZHGXH3-DH21E_2q.js} +1 -1
- package/dist-embed/chunks/{kab-KAB-ZGHBKWFO-CQJhf9Nn.js → kab-KAB-ZGHBKWFO-2Cx_3mmx.js} +1 -1
- package/dist-embed/chunks/{kk-KZ-P5N5QNE5-Dl6YC0GH.js → kk-KZ-P5N5QNE5-C2v01t5f.js} +1 -1
- package/dist-embed/chunks/{km-KH-HSX4SM5Z-QYB-tJ4i.js → km-KH-HSX4SM5Z-WL_JAugw.js} +1 -1
- package/dist-embed/chunks/{ko-KR-MTYHY66A-D6yzBqJ5.js → ko-KR-MTYHY66A-DWjrj8WD.js} +1 -1
- package/dist-embed/chunks/{ku-TR-6OUDTVRD-C43l2362.js → ku-TR-6OUDTVRD-CwTRLeeu.js} +1 -1
- package/dist-embed/chunks/{lt-LT-XHIRWOB4-BG1v5NwF.js → lt-LT-XHIRWOB4-GVGjjS1d.js} +1 -1
- package/dist-embed/chunks/{lv-LV-5QDEKY6T-CAwm1y_0.js → lv-LV-5QDEKY6T-C29ftTES.js} +1 -1
- package/dist-embed/chunks/{markdown-CH2i4TVR.js → markdown-Bf4-A1yl.js} +1 -1
- package/dist-embed/chunks/{mr-IN-CRQNXWMA-DSk6q1fp.js → mr-IN-CRQNXWMA-Cyym_1yB.js} +1 -1
- package/dist-embed/chunks/{my-MM-5M5IBNSE-BRiKXulk.js → my-MM-5M5IBNSE-BOkGbWeI.js} +1 -1
- package/dist-embed/chunks/{nb-NO-T6EIAALU-CCDnctVd.js → nb-NO-T6EIAALU-BjaVTNUf.js} +1 -1
- package/dist-embed/chunks/{nl-NL-IS3SIHDZ-DwStD_Ch.js → nl-NL-IS3SIHDZ-DSVCFPQj.js} +1 -1
- package/dist-embed/chunks/{nn-NO-6E72VCQL-DNcfjETk.js → nn-NO-6E72VCQL-D5-_rRv0.js} +1 -1
- package/dist-embed/chunks/{oc-FR-POXYY2M6-BOjjS12P.js → oc-FR-POXYY2M6-CxKcn1R4.js} +1 -1
- package/dist-embed/chunks/{pa-IN-N4M65BXN-B4y5cv2_.js → pa-IN-N4M65BXN-D9r6O5PP.js} +1 -1
- package/dist-embed/chunks/{percentages-BXMCSKIN-BpahO1D1.js → percentages-BXMCSKIN-917PkDRT.js} +3 -3
- package/dist-embed/chunks/{pl-PL-T2D74RX3-CfuLoYHB.js → pl-PL-T2D74RX3-CFXCTA5m.js} +1 -1
- package/dist-embed/chunks/{plugin-BMH63P5M.js → plugin-CA_0EWiO.js} +1 -1
- package/dist-embed/chunks/plugin-LDJjixuG.js +1 -0
- package/dist-embed/chunks/{pt-BR-5N22H2LF-Fk60PfdA.js → pt-BR-5N22H2LF-7A-3KOon.js} +1 -1
- package/dist-embed/chunks/{pt-PT-UZXXM6DQ-SNAgJ5Vr.js → pt-PT-UZXXM6DQ-BJLo5w79.js} +1 -1
- package/dist-embed/chunks/{ro-RO-JPDTUUEW-YkxpKkWn.js → ro-RO-JPDTUUEW-DtvOR1_K.js} +1 -1
- package/dist-embed/chunks/{ru-RU-B4JR7IUQ-CaI1rtvc.js → ru-RU-B4JR7IUQ-CGQ0z7l6.js} +1 -1
- package/dist-embed/chunks/{sessions-ZDYLkdi_.js → sessions-By2lggFS.js} +2 -2
- package/dist-embed/chunks/{si-LK-N5RQ5JYF-CQz29xmh.js → si-LK-N5RQ5JYF-D13wg56d.js} +1 -1
- package/dist-embed/chunks/{sk-SK-C5VTKIMK-CZg7PVzd.js → sk-SK-C5VTKIMK-BqAZ0R3f.js} +1 -1
- package/dist-embed/chunks/{sl-SI-NN7IZMDC-D-EjMWyZ.js → sl-SI-NN7IZMDC-BjPUGdws.js} +1 -1
- package/dist-embed/chunks/{standalone-oyxre9MX.js → standalone-DyCMuq_1.js} +1 -1
- package/dist-embed/chunks/{subset-shared.chunk-BIvvzzX2.js → subset-shared.chunk-D-GUkcCO.js} +1 -1
- package/dist-embed/chunks/{subset-worker.chunk-DGgI6iRY.js → subset-worker.chunk-Bz8aK3Nt.js} +1 -1
- package/dist-embed/chunks/{sv-SE-XGPEYMSR-D8CsNMON.js → sv-SE-XGPEYMSR-DrXTnEWd.js} +1 -1
- package/dist-embed/chunks/{ta-IN-2NMHFXQM-CvuxKO7t.js → ta-IN-2NMHFXQM-bK104VxM.js} +1 -1
- package/dist-embed/chunks/{th-TH-HPSO5L25-NgQJigwq.js → th-TH-HPSO5L25-BSo6r7L4.js} +1 -1
- package/dist-embed/chunks/{tr-TR-DEFEU3FU-eu9-qLmi.js → tr-TR-DEFEU3FU-pYKvN-ro.js} +1 -1
- package/dist-embed/chunks/{uk-UA-QMV73CPH-CbjmuLVL.js → uk-UA-QMV73CPH-DFR0z9gx.js} +1 -1
- package/dist-embed/chunks/{usePrimerThemeBridge-LgREOVgz.js → usePrimerThemeBridge-CuRRiOcg.js} +1 -1
- package/dist-embed/chunks/{vi-VN-M7AON7JQ-u84yOuJ-.js → vi-VN-M7AON7JQ-BwMeNi1s.js} +1 -1
- package/dist-embed/chunks/{zh-CN-LNUGB5OW-ojkSgl-t.js → zh-CN-LNUGB5OW-QC_JIHYo.js} +1 -1
- package/dist-embed/chunks/{zh-HK-E62DVLB3-C6M89-Da.js → zh-HK-E62DVLB3-BHs8J1Gl.js} +1 -1
- package/dist-embed/chunks/{zh-TW-RAJ6MFWO-BaTtFORh.js → zh-TW-RAJ6MFWO-DpqpYlIS.js} +1 -1
- package/dist-embed/datalayer-app-main.js +330 -59
- package/lib/apps/apps/AppBrowserSandbox.d.ts +7 -0
- package/lib/apps/apps/AppBrowserSandbox.js +52 -0
- package/lib/apps/apps/AppRenderer.js +11 -2
- package/lib/apps/apps/appspec.js +31 -0
- package/lib/apps/apps/browserSandbox.d.ts +69 -0
- package/lib/apps/apps/browserSandbox.js +159 -0
- package/lib/apps/apps/index.d.ts +2 -0
- package/lib/apps/apps/index.js +2 -0
- package/lib/apps/plugins/chat/ChatView.js +59 -7
- package/lib/components/inspector/a2aSpans.js +5 -1
- package/lib/runtimes/browser/a2aPeer.d.ts +7 -0
- package/lib/runtimes/browser/a2aPeer.js +27 -5
- package/lib/specs/apps.js +345 -8
- package/lib/specs/appspecSchema.js +79 -0
- package/lib/types/agentspecs.d.ts +28 -0
- package/package.json +1 -1
- package/scripts/codegen/generate_apps.py +3 -2
- package/dist-embed/chunks/Avatar-Dqz3ZWjZ.js +0 -1
- package/dist-embed/chunks/ChatView-CubqJum2.js +0 -288
- package/dist-embed/chunks/DatalayerAgentBridge-BmJbZ2Lk.js +0 -1
- package/dist-embed/chunks/plugin-DZPXm2dP.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{v as te,r as z,j as e,B as n,H as F,cQ as ae,T as i,c as L,eN as Re,e$ as le,f0 as Ve,f1 as He,f2 as De,f3 as me,f4 as Pe,f5 as qe,f6 as Be,f7 as Ge,f8 as Ke,f9 as Je,fa as V,n as ce,
|
|
1
|
+
import{v as te,r as z,j as e,B as n,H as F,cQ as ae,T as i,c as L,eN as Re,e$ as le,f0 as Ve,f1 as He,f2 as De,f3 as me,f4 as Pe,f5 as qe,f6 as Be,f7 as Ge,f8 as Ke,f9 as Je,fa as V,n as ce,bt as Ye,cP as Xe,L as A,aP as Qe,fb as Ze,fc as et,fd as tt,fe as Oe,ff as nt,dw as st,cN as ot,I as Me,eK as it,fg as rt,fh as lt,fi as at,fj as ct,fk as dt,fl as ut,fm as ft,fn as pt,fo as ht,fp as gt,fq as ne,fr as se,cO as xt,fs as mt}from"../datalayer-app-main.js";import{A as bt}from"./ArrowLeftIcon-Y3PTljcl.js";import{A as yt,T as jt,M as We,U as $e,F as St}from"./UnlinkIcon-DuVqPyB-.js";import Ie from"./index-hib7vWC6.js";import{L as de}from"./LinkIcon-DUI0jw25.js";import{F as wt}from"./Flash-C3nF3s4G.js";import{A as kt}from"./Avatar-BrPfm89P.js";function vt(t,s){if(Object.is(t,s))return!0;if(typeof t!="object"||t===null||typeof s!="object"||s===null)return!1;if(t instanceof Map&&s instanceof Map){if(t.size!==s.size)return!1;for(const[l,o]of t)if(!Object.is(o,s.get(l)))return!1;return!0}if(t instanceof Set&&s instanceof Set){if(t.size!==s.size)return!1;for(const l of t)if(!s.has(l))return!1;return!0}const r=Object.keys(t);if(r.length!==Object.keys(s).length)return!1;for(const l of r)if(!Object.prototype.hasOwnProperty.call(s,l)||!Object.is(t[l],s[l]))return!1;return!0}const{useRef:zt}=te;function Ne(t){const s=zt();return r=>{const l=t(r);return vt(s.current,l)?s.current:s.current=l}}function D(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function Te(t){if(!Number.isFinite(t)||Number.isNaN(t)||t<0)return"0ms";if(t<1)return`${Math.max(0,Math.round(t*1e3))}ms`;if(t<60)return`${t.toFixed(1)}s`;const s=Math.floor(t/60),r=Math.round(t%60);return`${s}m ${r}s`}function Ct(t){const s=String(t??"");return/[",\n]/.test(s)?`"${s.replace(/"/g,'""')}"`:s}function It(t){const s=[];s.push(["Context Usage Snapshot for Agent",t.agentId]),s.push(["Generated At",new Date().toISOString()]),s.push([]),s.push(["Summary"]),s.push(["Total Tokens",t.totalTokens]),s.push(["Context Window",t.contextWindow]),s.push(["System Prompt Tokens",t.systemPromptTokens]),s.push(["Tool Tokens",t.toolTokens]),s.push(["History Tokens",t.historyTokens]),s.push(["Current Message Tokens",t.currentMessageTokens]),s.push(["User Message Tokens",t.userMessageTokens]),s.push(["Assistant Message Tokens",t.assistantMessageTokens]),s.push([]),t.sessionUsage&&(s.push(["Session Usage"]),s.push(["Input Tokens",t.sessionUsage.inputTokens]),s.push(["Output Tokens",t.sessionUsage.outputTokens]),s.push(["Requests",t.sessionUsage.requests]),s.push(["Tool Calls",t.sessionUsage.toolCalls]),s.push(["Turns",t.sessionUsage.turns]),s.push(["Duration Seconds",t.sessionUsage.durationSeconds]),s.push([])),t.turnUsage&&(s.push(["Last Turn Usage"]),s.push(["Input Tokens",t.turnUsage.inputTokens]),s.push(["Output Tokens",t.turnUsage.outputTokens]),s.push(["Requests",t.turnUsage.requests]),s.push(["Tool Calls",t.turnUsage.toolCalls]),s.push(["Duration Seconds",t.turnUsage.durationSeconds]),s.push([])),s.push(["Distribution"]),s.push(["Category","Tokens"]);for(const c of t.distribution?.children??[])s.push([c.name,c.value]);if(s.push([]),t.perRequestUsage.length>0){s.push(["Per Request Usage"]),s.push(["Request #","Input Tokens","Output Tokens","Duration Ms","Tool Names","Timestamp","Turn ID"]);for(const c of t.perRequestUsage)s.push([c.requestNum,c.inputTokens,c.outputTokens,c.durationMs,c.toolNames.join("; "),c.timestamp??"",c.turnId??""])}const r=s.map(c=>c.map(Ct).join(",")).join(`
|
|
2
2
|
`),l=new Blob([r],{type:"text/csv;charset=utf-8;"}),o=URL.createObjectURL(l),a=document.createElement("a");a.href=o;const d=new Date().toISOString().replace(/[:.]/g,"-");a.download=`context-usage-${t.agentId}-${d}.csv`,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)}function Tt(t){switch(t.toLowerCase()){case"messages":case"history":return Ge;case"tools":case"tool definitions":return Be;case"system":case"system prompts":return qe;case"cache":return Pe;default:return me}}function At({agentId:t,apiBase:s,liveData:r,messageCount:l=0,defaultView:o="overview",chartHeight:a="200px"}){const[d,c]=z.useState(o),[h,f]=z.useState(!1),S=r!==void 0,u=r,b=!S,m=z.useMemo(()=>{if(!u?.perRequestUsage||u.perRequestUsage.length===0)return null;const g=u.perRequestUsage;let C=0,N=0;const B=[],M=[],w=[],X=[];return g.forEach(W=>{C+=W.inputTokens,N+=W.outputTokens,B.push(`#${W.requestNum}`),M.push(C),w.push(N),X.push(C+N)}),{tooltip:{trigger:"axis",formatter:W=>{let U=`<strong>${W[0]?.axisValue||""}</strong><br/>`;return W.forEach($=>{U+=`${$.marker} ${$.seriesName}: ${D($.value)}<br/>`}),U}},legend:{data:["Input","Output","Total"],bottom:0,textStyle:{fontSize:10}},grid:{left:45,right:15,top:10,bottom:35},xAxis:{type:"category",data:B,axisLabel:{fontSize:10}},yAxis:{type:"value",axisLabel:{fontSize:10,formatter:W=>D(W)}},series:[{name:"Input",type:"line",data:M,smooth:!0,lineStyle:{width:2},areaStyle:{opacity:.2},itemStyle:{color:"#3B82F6"}},{name:"Output",type:"line",data:w,smooth:!0,lineStyle:{width:2},areaStyle:{opacity:.2},itemStyle:{color:"#10B981"}},{name:"Total",type:"line",data:X,smooth:!0,lineStyle:{width:2,type:"dashed"},itemStyle:{color:"#8B5CF6"}}]}},[u?.perRequestUsage]),R=z.useMemo(()=>{if(!u?.distribution)return null;const{distribution:g}=u,C=g.children&&g.children.length>0;return{tooltip:{formatter:N=>`${N.name}: ${D(N.value)} tokens`},series:[{type:"treemap",data:C?g.children:[{name:"No data",value:1}],roam:!1,breadcrumb:{show:!1},label:{show:!0,formatter:"{b}",fontSize:11},itemStyle:{borderColor:"#fff",borderWidth:2},levels:[{itemStyle:{borderColor:"#777",borderWidth:0,gapWidth:1}},{itemStyle:{borderColor:"#555",borderWidth:5,gapWidth:1},colorSaturation:[.35,.5]},{colorSaturation:[.35,.5]}]}]}},[u?.distribution]);if(b)return e.jsxs(n,{children:[e.jsx(F,{as:"h4",sx:{fontSize:1,fontWeight:"semibold",mb:2,color:"fg.muted"},children:"Context Usage"}),e.jsxs(n,{p:3,bg:"canvas.subtle",borderRadius:2,border:"1px solid",borderColor:"border.default",display:"flex",alignItems:"center",gap:2,children:[e.jsx(ae,{size:"small"}),e.jsx(i,{sx:{fontSize:1,color:"fg.muted"},children:"Loading context details..."})]})]});if(!u)return e.jsxs(n,{children:[e.jsx(F,{as:"h4",sx:{fontSize:1,fontWeight:"semibold",mb:2,color:"fg.muted"},children:"Context Usage"}),e.jsx(n,{p:3,bg:"attention.subtle",borderRadius:2,border:"1px solid",borderColor:"attention.muted",children:e.jsx(i,{sx:{fontSize:1,color:"attention.fg"},children:"Waiting for context data from WebSocket stream..."})})]});const{totalTokens:P,contextWindow:y,sessionUsage:p,turnUsage:j,distribution:E}=u,I=l>0?l:Math.max(p?.turns??0,u.perRequestUsage?.length>0?1:0),O=E?.children&&E.children.length>0;return e.jsxs(n,{children:[e.jsxs(n,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[e.jsx(F,{as:"h4",sx:{fontSize:1,fontWeight:"semibold",color:"fg.muted"},children:"Context Usage"}),e.jsxs(n,{display:"flex",alignItems:"center",gap:2,children:[I>0&&e.jsxs(i,{sx:{fontSize:0,color:"fg.muted"},children:[I," ",I===1?"message sent":"messages sent"]}),e.jsx(L,{size:"small",variant:"invisible",leadingVisual:Re,onClick:()=>It(u),children:"Download"})]})]}),e.jsxs(n,{p:3,bg:"canvas.subtle",borderRadius:2,border:"1px solid",borderColor:"border.default",children:[e.jsx(n,{mb:3,children:e.jsxs(i,{sx:{fontSize:1,fontWeight:"semibold"},children:["Total usage: ",D(P)]})}),(p||j)&&e.jsxs(n,{display:"flex",gap:3,mb:3,flexWrap:"wrap",children:[p&&e.jsxs(n,{flex:1,minWidth:120,p:2,bg:"canvas.default",borderRadius:2,border:"1px solid",borderColor:"border.muted",children:[e.jsxs(i,{sx:{fontSize:0,color:"fg.muted",display:"block"},children:["Session (",p.turns," turns)"]}),e.jsx(i,{sx:{fontSize:1,fontWeight:"semibold"},children:D(p.inputTokens+p.outputTokens)}),e.jsxs(i,{sx:{fontSize:0,color:"fg.muted"},children:[" ","in ",Te(p.durationSeconds)]})]}),j&&e.jsxs(n,{flex:1,minWidth:120,p:2,bg:"canvas.default",borderRadius:2,border:"1px solid",borderColor:"border.muted",children:[e.jsxs(i,{sx:{fontSize:0,color:"fg.muted",display:"block"},children:["Last Turn (",j.requests," reqs)"]}),e.jsx(i,{sx:{fontSize:1,fontWeight:"semibold"},children:D(j.inputTokens+j.outputTokens)}),e.jsxs(i,{sx:{fontSize:0,color:"fg.muted"},children:[" ","in ",Te(j.durationSeconds)]})]})]}),e.jsxs(n,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[e.jsxs(le,{"aria-label":"View mode",size:"small",onChange:g=>{c(["overview","distribution","history"][g])},children:[e.jsx(le.IconButton,{"aria-label":"Overview",selected:d==="overview",icon:Ve}),e.jsx(le.IconButton,{"aria-label":"Distribution",selected:d==="distribution",icon:yt,disabled:!O}),e.jsx(le.IconButton,{"aria-label":"History",selected:d==="history",icon:He})]}),d==="overview"&&e.jsx(L,{size:"small",variant:"invisible",onClick:()=>f(!h),children:h?"Less":"More"})]}),d==="overview"&&e.jsxs(n,{children:[e.jsxs(n,{display:"flex",flexDirection:"column",gap:2,children:[O&&E.children.map(g=>{const C=Tt(g.name),N=g.value/y*100;return e.jsxs(n,{display:"flex",alignItems:"center",gap:2,children:[e.jsx(n,{color:"fg.muted",width:20,children:e.jsx(C,{size:16})}),e.jsx(i,{sx:{fontSize:1,flex:1},children:g.name}),e.jsx(i,{sx:{fontSize:0,color:"fg.muted",minWidth:60},children:D(g.value)}),e.jsx(n,{width:80,children:e.jsx(De,{progress:N,sx:{height:4}})})]},g.name)}),!O&&e.jsx(i,{sx:{color:"fg.muted",fontSize:1,textAlign:"center",py:2},children:"No context data yet. Start a conversation to see usage."})]}),h&&O&&e.jsxs(n,{mt:3,p:2,bg:"canvas.default",borderRadius:2,border:"1px solid",borderColor:"border.muted",fontSize:0,children:[u.systemPromptTokens>0&&e.jsxs(n,{mb:2,children:[e.jsxs(i,{sx:{fontWeight:"semibold"},children:["System Prompts:"," ",D(u.systemPromptTokens)," tokens"]}),u.systemPrompts.slice(0,2).map((g,C)=>e.jsxs(i,{sx:{display:"block",ml:2,mt:1,color:"fg.muted"},children:["•"," ",g.length>80?g.slice(0,80)+"...":g]},C))]}),u.toolTokens>0&&e.jsxs(n,{mb:2,children:[e.jsxs(i,{sx:{fontWeight:"semibold"},children:["Tools: ",D(u.toolTokens)," tokens (",u.tools.length," tools)"]}),e.jsxs(n,{ml:2,mt:1,children:[u.tools.slice(0,4).map((g,C)=>e.jsxs(i,{sx:{display:"block",color:"fg.muted"},children:["• ",g.name,": ",D(g.totalTokens)]},C)),u.tools.length>4&&e.jsxs(i,{sx:{color:"fg.muted",fontStyle:"italic"},children:["...and ",u.tools.length-4," more"]})]})]}),(u.userMessageTokens>0||u.assistantMessageTokens>0)&&e.jsxs(n,{mb:2,children:[e.jsxs(i,{sx:{fontWeight:"semibold"},children:["Messages:"," ",D(u.userMessageTokens+u.assistantMessageTokens)," ","tokens"]}),e.jsxs(n,{ml:2,mt:1,children:[e.jsxs(i,{sx:{display:"block",color:"fg.muted"},children:["• User: ",D(u.userMessageTokens)]}),e.jsxs(i,{sx:{display:"block",color:"fg.muted"},children:["• Assistant:"," ",D(u.assistantMessageTokens)]}),u.toolCallTokens>0&&e.jsxs(i,{sx:{display:"block",color:"fg.muted"},children:["• Tool calls:"," ",D(u.toolCallTokens)]})]})]})]})]}),d==="distribution"&&R&&e.jsx(Ie,{option:R,style:{height:a},opts:{renderer:"svg"}}),d==="history"&&m&&e.jsxs(n,{children:[e.jsx(Ie,{option:m,style:{height:a},opts:{renderer:"svg"}}),h&&u.perRequestUsage.length>0&&e.jsx(n,{mt:2,maxHeight:"150px",overflowY:"auto",fontSize:0,children:u.perRequestUsage.slice(-10).reverse().map((g,C)=>e.jsxs(n,{display:"flex",gap:2,py:1,borderBottom:C<9?"1px solid":"none",borderColor:"border.muted",children:[e.jsxs(i,{sx:{fontWeight:"semibold",minWidth:30},children:["#",g.requestNum]}),e.jsxs(i,{sx:{color:"#3B82F6"},children:["↓",D(g.inputTokens)]}),e.jsxs(i,{sx:{color:"#10B981"},children:["↑",D(g.outputTokens)]}),g.toolNames.length>0&&e.jsxs(i,{sx:{color:"fg.muted"},children:["🔧 ",g.toolNames.join(", ")]})]},g.requestNum))})]}),d==="history"&&!m&&e.jsx(n,{py:3,children:e.jsx(i,{sx:{color:"fg.muted",fontSize:1},children:"No history"})})]})]})}function q(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function ee({title:t,icon:s,count:r,tokens:l,defaultExpanded:o=!1,children:a}){const[d,c]=z.useState(o);return e.jsxs(n,{mb:2,children:[e.jsxs(n,{as:"button",onClick:()=>c(!d),display:"flex",alignItems:"center",gap:2,width:"100%",p:2,bg:"canvas.subtle",border:"1px solid",borderColor:"border.default",borderRadius:2,cursor:"pointer",hover:{bg:"canvas.inset"},children:[d?e.jsx(Ye,{size:16}):e.jsx(Xe,{size:16}),te.createElement(s,{size:16}),e.jsx(i,{sx:{fontWeight:"semibold",flex:1,textAlign:"left"},children:t}),r!==void 0&&e.jsx(A,{variant:"secondary",size:"small",children:r}),l!==void 0&&l>0&&e.jsxs(i,{sx:{fontSize:0,color:"fg.muted"},children:[q(l)," tokens"]})]}),d&&e.jsx(n,{border:"1px solid",borderColor:"border.default",borderTop:"none",borderRadius:"0 0 6px 6px",p:2,children:a})]})}function Et({tool:t}){const[s,r]=z.useState(!1),[l,o]=z.useState(!1);return e.jsxs(n,{p:2,mb:2,bg:"canvas.default",border:"1px solid",borderColor:"border.muted",borderRadius:2,children:[e.jsxs(n,{display:"flex",alignItems:"center",gap:2,mb:1,children:[e.jsx(i,{sx:{fontWeight:"bold",fontFamily:"mono",fontSize:1},children:t.name}),e.jsx(A,{size:"small",variant:"secondary",children:t.sourceType}),t.isAsync&&e.jsx(A,{size:"small",variant:"accent",children:"async"}),t.requiresApproval&&e.jsx(A,{size:"small",variant:"attention",children:"requires approval"}),e.jsxs(i,{sx:{fontSize:0,color:"fg.muted",ml:"auto"},children:[q(t.totalTokens)," tokens"]})]}),t.description&&e.jsx(i,{sx:{fontSize:1,color:"fg.muted",display:"block",mb:2},children:t.description}),e.jsxs(n,{display:"flex",gap:2,children:[e.jsxs(L,{size:"small",variant:"invisible",onClick:()=>r(!s),children:[s?"Hide":"Show"," Schema"]}),t.sourceCode&&e.jsxs(L,{size:"small",variant:"invisible",onClick:()=>o(!l),children:[l?"Hide":"Show"," Source"]})]}),s&&e.jsx(n,{as:"pre",mt:2,p:2,bg:"canvas.inset",borderRadius:2,fontSize:0,overflow:"auto",maxHeight:200,children:JSON.stringify(t.parametersSchema,null,2)}),l&&t.sourceCode&&e.jsx(n,{as:"pre",mt:2,p:2,bg:"canvas.inset",borderRadius:2,fontSize:0,overflow:"auto",maxHeight:300,children:t.sourceCode})]})}function Ut({agentId:t,apiBase:s,liveData:r}){const l=r!==void 0,o=r;if(!l)return e.jsx(n,{p:3,display:"flex",alignItems:"center",justifyContent:"center",children:e.jsx(i,{sx:{color:"fg.muted"},children:"Waiting for context data from WebSocket stream..."})});if(!o)return e.jsx(n,{p:3,bg:"attention.subtle",borderRadius:2,border:"1px solid",borderColor:"attention.muted",children:e.jsx(i,{sx:{color:"attention.fg"},children:"No context data available."})});if(o.error)return e.jsx(n,{p:3,bg:"attention.subtle",borderRadius:2,border:"1px solid",borderColor:"attention.muted",children:e.jsx(i,{sx:{color:"attention.fg"},children:o.error})});const{tokenSummary:a,modelConfiguration:d}=o;return e.jsxs(n,{children:[e.jsxs(n,{mb:3,children:[e.jsxs(i,{sx:{fontSize:1,fontWeight:"semibold"},children:["Total usage: ",q(a.total)," /"," ",q(a.contextWindow)," (",Math.round(a.usagePercent),"%)"]}),e.jsx(De,{progress:Math.min(a.usagePercent,100),sx:{mt:2,height:8},bg:a.usagePercent>90?"danger.emphasis":a.usagePercent>70?"attention.emphasis":"success.emphasis"}),e.jsxs(n,{display:"flex",gap:3,mt:2,flexWrap:"wrap",fontSize:0,color:"fg.muted",children:[e.jsxs(i,{children:["System: ",q(a.systemPrompts)]}),e.jsxs(i,{children:["Tools: ",q(a.tools)]}),a.memory>0&&e.jsxs(i,{children:["Memory: ",q(a.memory)]}),e.jsxs(i,{children:["History: ",q(a.history)]}),e.jsxs(i,{children:["Current: ",q(a.current)]})]})]}),e.jsx(ee,{title:"Model Configuration",icon:Ke,defaultExpanded:!1,children:e.jsxs(n,{display:"grid",gridTemplateColumns:"1fr 2fr",gap:2,children:[e.jsx(i,{sx:{fontWeight:"semibold",fontSize:1},children:"Model:"}),e.jsx(i,{sx:{fontSize:1,fontFamily:"mono"},children:d.modelName||"Not specified"}),e.jsx(i,{sx:{fontWeight:"semibold",fontSize:1},children:"Context Window:"}),e.jsxs(i,{sx:{fontSize:1},children:[q(d.contextWindow)," tokens"]}),Object.keys(d.settings).length>0&&e.jsxs(e.Fragment,{children:[e.jsx(i,{sx:{fontWeight:"semibold",fontSize:1},children:"Settings:"}),e.jsx(n,{as:"pre",fontSize:0,p:2,bg:"canvas.inset",borderRadius:2,overflow:"auto",children:JSON.stringify(d.settings,null,2)})]})]})}),e.jsx(ee,{title:"System Prompts",icon:Je,count:o.systemPrompts.length,tokens:o.systemPromptTokens,children:o.systemPrompts.length===0?e.jsx(i,{sx:{color:"fg.muted",fontSize:1},children:"No system prompts configured"}):o.systemPrompts.map((c,h)=>e.jsxs(n,{p:2,mb:2,bg:"canvas.inset",borderRadius:2,border:"1px solid",borderColor:"border.muted",children:[e.jsxs(n,{display:"flex",justifyContent:"space-between",mb:1,children:[e.jsxs(i,{sx:{fontWeight:"semibold",fontSize:0},children:["Prompt ",h+1]}),e.jsxs(i,{sx:{fontSize:0,color:"fg.muted"},children:[q(c.tokens)," tokens"]})]}),e.jsx(i,{as:"pre",sx:{fontSize:0,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:200,overflow:"auto"},children:c.content})]},h))}),e.jsx(ee,{title:"Tool Definitions",icon:jt,count:o.tools.length,tokens:o.toolTokens,children:o.tools.length===0?e.jsx(i,{sx:{color:"fg.muted",fontSize:1},children:"No tools configured"}):o.tools.map((c,h)=>e.jsx(Et,{tool:c},h))}),o.memoryBlocks.length>0&&e.jsx(ee,{title:"Memory Blocks",icon:Pe,count:o.memoryBlocks.length,tokens:o.memoryTokens,children:o.memoryBlocks.map((c,h)=>e.jsx(n,{as:"pre",p:2,mb:2,bg:"canvas.inset",borderRadius:2,fontSize:0,overflow:"auto",children:JSON.stringify(c,null,2)},h))}),Object.keys(o.toolEnvironment).length>0&&e.jsx(ee,{title:"Tool Environment",icon:V,count:Object.keys(o.toolEnvironment).length,children:e.jsx(n,{display:"grid",gridTemplateColumns:"1fr 2fr",gap:2,children:Object.entries(o.toolEnvironment).map(([c,h])=>e.jsxs(te.Fragment,{children:[e.jsx(i,{sx:{fontFamily:"mono",fontSize:1,fontWeight:"semibold"},children:c}),e.jsx(i,{sx:{fontFamily:"mono",fontSize:1,color:"fg.muted"},children:h})]},c))})}),o.toolRules.length>0&&e.jsx(ee,{title:"Tool Rules",icon:ce,count:o.toolRules.length,children:o.toolRules.map((c,h)=>e.jsx(n,{as:"pre",p:2,mb:2,bg:"canvas.inset",borderRadius:2,fontSize:0,overflow:"auto",children:JSON.stringify(c,null,2)},h))})]})}const ye={provider:"github",displayName:"GitHub",iconUrl:"https://github.githubassets.com/favicons/favicon.svg",authorizationUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",userInfoUrl:"https://api.github.com/user",revocationUrl:"https://api.github.com/applications/{client_id}/token",defaultScopes:["read:user","user:email"]},je={provider:"google",displayName:"Google",iconUrl:"https://www.google.com/favicon.ico",authorizationUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",userInfoUrl:"https://www.googleapis.com/oauth2/v2/userinfo",revocationUrl:"https://oauth2.googleapis.com/revoke",defaultScopes:["openid","email","profile"],additionalParams:{access_type:"offline",prompt:"consent"}},Se={provider:"kaggle",displayName:"Kaggle",iconUrl:"https://www.kaggle.com/static/images/favicon.ico",authorizationUrl:"https://www.kaggle.com/oauth/authorize",tokenUrl:"https://www.kaggle.com/oauth/token",userInfoUrl:"https://www.kaggle.com/api/v1/me",defaultScopes:["datasets:read","notebooks:read"]};function _t(t=64){const s=Math.max(43,Math.min(128,t)),r=new Uint8Array(s);return crypto.getRandomValues(r),we(r)}async function Rt(t){const r=new TextEncoder().encode(t),l=await crypto.subtle.digest("SHA-256",r);return we(new Uint8Array(l))}function Dt(){const t=new Uint8Array(32);return crypto.getRandomValues(t),we(t)}function we(t){let s="";const r=new Uint8Array(t);for(let l=0;l<r.length;l++)s+=String.fromCharCode(r[l]);return s=btoa(s),s.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function Pt(){const t=_t(),s=await Rt(t);return{codeVerifier:t,codeChallenge:s}}const Ot="datalayer-agent-identities",Ae="/api/v1/identity/oauth/token",Mt="/api/v1/identity/oauth/userinfo",Wt="/api/v1/identity/oauth/revoke",$t={identities:new Map,pendingAuthorization:null,providerConfigs:new Map,isLoading:!1,error:null};function Nt(t,s,r,l){const o=new URLSearchParams({client_id:t.clientId,redirect_uri:t.redirectUri,response_type:"code",scope:s.join(" "),state:r,code_challenge:l,code_challenge_method:"S256",...t.additionalParams});return`${t.authorizationUrl}?${o.toString()}`}const T=Qe()(Ze(et(tt((t,s)=>({...$t,configureProvider:r=>{t(l=>{const o=new Map(l.providerConfigs);return o.set(r.provider,r),{providerConfigs:o}})},startAuthorization:async(r,l,o)=>{const d=s().providerConfigs.get(r);if(!d)throw new Error(`Provider ${r} is not configured`);const{codeVerifier:c,codeChallenge:h}=await Pt(),f=Dt(),S=l||d.defaultScopes,u=Nt(d,S,f,h),b={requestId:`auth-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,provider:r,authUrl:u,state:f,codeVerifier:c,scopes:S,requestedAt:Date.now(),onComplete:o?.onComplete,onError:o?.onError};return t({pendingAuthorization:b,error:null}),u},completeAuthorization:async r=>{const l=s(),o=l.pendingAuthorization;if(!o)throw new Error("No pending authorization request");if(r.state!==o.state){const a=new Error("State mismatch - possible CSRF attack");throw o.onError?.(a),t({pendingAuthorization:null,error:a}),a}if(r.error){const a=new Error(r.errorDescription||r.error);throw o.onError?.(a),t({pendingAuthorization:null,error:a}),a}t({isLoading:!0});try{const a=l.providerConfigs.get(o.provider);if(!a)throw new Error(`Provider ${o.provider} is not configured`);const d=a.redirectUri.split("/").slice(0,3).join("/"),c=await fetch(`${d}${Ae}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:o.provider,code:r.code,code_verifier:o.codeVerifier,redirect_uri:a.redirectUri})});if(!c.ok){const b=await c.json().catch(()=>({}));throw new Error(b.detail||`Token exchange failed: ${c.status}`)}const h=await c.json(),f={accessToken:h.access_token,tokenType:h.token_type||"Bearer",expiresAt:h.expires_in?Date.now()+h.expires_in*1e3:void 0,refreshToken:h.refresh_token,scopes:o.scopes};let S;if(a.userInfoUrl)try{const b=await fetch(`${d}${Mt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:o.provider,access_token:f.accessToken})});if(b.ok){const m=await b.json();S={id:m.id?.toString()||m.sub,username:m.login||m.username,name:m.name,email:m.email,avatarUrl:m.avatar_url||m.picture,profileUrl:m.html_url||m.profile,raw:m}}}catch(b){console.warn("Failed to fetch user info:",b)}const u={provider:o.provider,displayName:a.displayName,iconUrl:a.iconUrl,scopes:o.scopes,isConnected:!0,connectedAt:Date.now(),userInfo:S,token:f};return t(b=>{const m=new Map(b.identities);return m.set(o.provider,u),{identities:m,pendingAuthorization:null,isLoading:!1,error:null}}),o.onComplete?.(u),u}catch(a){const d=a instanceof Error?a:new Error(String(a));throw o.onError?.(d),t({isLoading:!1,error:d,pendingAuthorization:null}),d}},cancelAuthorization:()=>{const r=s().pendingAuthorization;r?.onError&&r.onError(new Error("Authorization cancelled")),t({pendingAuthorization:null})},connectWithToken:async(r,l,o)=>{t({isLoading:!0,error:null});try{const a={accessToken:l,tokenType:"Bearer",scopes:[]},d={kaggle:{displayName:"Kaggle",iconUrl:"https://www.kaggle.com/static/images/favicon.ico"}}[r]||{displayName:r,iconUrl:void 0},c={provider:r,authType:"token",displayName:o?.displayName||d.displayName,iconUrl:o?.iconUrl||d.iconUrl,scopes:[],isConnected:!0,connectedAt:Date.now(),userInfo:o?.userInfo,token:a};return t(h=>{const f=new Map(h.identities);return f.set(r,c),{identities:f,isLoading:!1,error:null}}),c}catch(a){const d=a instanceof Error?a:new Error(String(a));throw t({isLoading:!1,error:d}),d}},disconnect:async r=>{const l=s(),o=l.identities.get(r),a=l.providerConfigs.get(r);if(!o||!o.token){t(d=>{const c=new Map(d.identities);return c.delete(r),{identities:c}});return}if(o.authType==="token"){t(d=>{const c=new Map(d.identities);return c.delete(r),{identities:c}});return}if(a?.revocationUrl)try{const d=a.redirectUri.split("/").slice(0,3).join("/");await fetch(`${d}${Wt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r,access_token:o.token.accessToken})})}catch(d){console.warn("Failed to revoke token:",d)}t(d=>{const c=new Map(d.identities);return c.delete(r),{identities:c}})},refreshToken:async r=>{const l=s(),o=l.identities.get(r),a=l.providerConfigs.get(r);if(!o||!o.token?.refreshToken)throw new Error(`No refresh token available for ${r}`);if(!a)throw new Error(`Provider ${r} is not configured`);const d=a.redirectUri.split("/").slice(0,3).join("/"),c=await fetch(`${d}${Ae}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r,grant_type:"refresh_token",refresh_token:o.token.refreshToken})});if(!c.ok)throw new Error(`Token refresh failed: ${c.status}`);const h=await c.json(),f={accessToken:h.access_token,tokenType:h.token_type||"Bearer",expiresAt:h.expires_in?Date.now()+h.expires_in*1e3:void 0,refreshToken:h.refresh_token||o.token.refreshToken,scopes:o.scopes};return t(S=>{const u=new Map(S.identities);return u.set(r,{...o,token:f}),{identities:u}}),f},getIdentity:r=>s().identities.get(r),isConnected:r=>s().identities.get(r)?.isConnected??!1,getToken:async r=>{const o=s().identities.get(r);if(!o||!o.token)return null;const a=o.token.expiresAt;if(a&&a-Date.now()<300*1e3){if(o.token.refreshToken)try{return await s().refreshToken(r)}catch(d){return console.warn("Token refresh failed:",d),null}return null}return o.token},clearAll:()=>{t({identities:new Map,pendingAuthorization:null,error:null})},setError:r=>{t({error:r})}}),{name:Ot,storage:{getItem:t=>{const s=localStorage.getItem(t);if(!s)return null;const r=JSON.parse(s),l=new URLSearchParams(window.location.search),o=l.has("code")&&l.has("state");return{state:{...r.state,identities:new Map(r.state.identities||[]),providerConfigs:new Map(r.state.providerConfigs||[]),pendingAuthorization:o&&r.state.pendingAuthorization||null,isLoading:!1,error:null}}},setItem:(t,s)=>{const r={state:{...s.state,identities:Array.from(s.state.identities.entries()),providerConfigs:Array.from(s.state.providerConfigs.entries()),pendingAuthorization:s.state.pendingAuthorization?{...s.state.pendingAuthorization,onComplete:void 0,onError:void 0}:null,isLoading:!1,error:null}};localStorage.setItem(t,JSON.stringify(r))},removeItem:t=>localStorage.removeItem(t)},partialize:t=>({identities:t.identities,providerConfigs:t.providerConfigs,pendingAuthorization:t.pendingAuthorization})})),{name:"IdentityStore"}));function Lt(){return T(Ne(t=>Array.from(t.identities.values()).filter(s=>s.isConnected)))}function Ft(){return T(Ne(t=>Array.from(t.identities.entries()).filter(([s,r])=>r.isConnected).map(([s])=>s)))}function Vt(){return T(t=>t.pendingAuthorization)}function Ht(){return T(t=>t.isLoading)}function qt(){return T(t=>t.error)}function pe(t){const s=T.getState();t.github&&s.configureProvider({...ye,clientId:t.github.clientId,redirectUri:t.github.redirectUri}),t.google&&s.configureProvider({...je,clientId:t.google.clientId,redirectUri:t.google.redirectUri}),t.kaggle&&s.configureProvider({...Se,clientId:t.kaggle.clientId,redirectUri:t.kaggle.redirectUri})}function ke(t={}){const{providers:s,baseUrl:r=typeof window<"u"?window.location.origin:"",callbackPath:l=typeof window<"u"?window.location.pathname:"/oauth/callback",autoHandleCallback:o=!0}=t,a=Lt(),d=Ft(),c=Vt(),h=Ht(),f=qt(),S=T(x=>x.startAuthorization),u=T(x=>x.completeAuthorization),b=T(x=>x.cancelAuthorization),m=T(x=>x.disconnect),R=T(x=>x.getIdentity),P=T(x=>x.isConnected),y=T(x=>x.getToken),p=T(x=>x.configureProvider);z.useEffect(()=>{if(!s)return;const x=`${r}${l}`;s.github&&pe({github:{clientId:s.github.clientId,redirectUri:s.github.redirectUri||x}}),s.google&&pe({google:{clientId:s.google.clientId,redirectUri:s.google.redirectUri||x}}),s.kaggle&&pe({kaggle:{clientId:s.kaggle.clientId,redirectUri:s.kaggle.redirectUri||x}}),s.custom&&s.custom.forEach(U=>{p(U)})},[s,r,l,p]),z.useEffect(()=>{if(!o||typeof window>"u")return;const x=new URLSearchParams(window.location.search),U=x.get("code"),$=x.get("state"),G=x.get("error"),H=x.get("error_description");(U&&$||G)&&u({code:U||"",state:$||"",error:G||void 0,errorDescription:H||void 0}).then(()=>{const K=window.location.pathname;window.history.replaceState({},"",K)}).catch(K=>{console.error("OAuth callback error:",K);const Q=window.location.pathname;window.history.replaceState({},"",Q)})},[o,u]);const j=z.useCallback(async(x,U)=>{const $=await S(x,U);window.location.href=$},[S]),E=z.useCallback(async(x,U)=>{const $=await S(x,U,{onComplete:()=>{},onError:()=>{}});return new Promise((G,H)=>{const K=T.getState();K.pendingAuthorization&&(K.pendingAuthorization.onComplete=G,K.pendingAuthorization.onError=H);const Q=600,k=700,ue=window.screenX+(window.outerWidth-Q)/2,v=window.screenY+(window.outerHeight-k)/2,_=window.open($,"oauth_popup",`width=${Q},height=${k},left=${ue},top=${v},toolbar=no,menubar=no`);if(!_){H(new Error("Failed to open popup window"));return}const J=Y=>{if(Y.origin===window.location.origin)if(Y.data?.type==="oauth-callback-success"){window.removeEventListener("message",J),clearInterval(oe),_.close();const ie=Y.data.provider,re=Y.data.identity;if(console.debug("[Identity] Received oauth-callback-success for provider:",ie),console.debug("[Identity] Identity from popup:",re),re){const ve=T.getState().identities,Z=new Map(ve);Z.set(ie,re),T.setState({identities:Z,pendingAuthorization:null}),console.debug("[Identity] Store updated with identity from popup, identities count:",Z.size),G(re);return}setTimeout(()=>{const Z=localStorage.getItem("agent-runtimes-identity");if(console.debug("[Identity] Fallback: reading from localStorage"),Z)try{const Le=JSON.parse(Z).state?.identities||[],fe=new Map(Le).get(ie);if(fe){const Fe=T.getState().identities,Ce=new Map(Fe);Ce.set(ie,fe),T.setState({identities:Ce,pendingAuthorization:null}),G(fe);return}}catch(ze){console.error("[Identity] Failed to parse identity from localStorage:",ze)}T.setState({pendingAuthorization:null}),H(new Error("Identity not found after OAuth success"))},100)}else Y.data?.type==="oauth-callback-error"?(window.removeEventListener("message",J),clearInterval(oe),_.close(),T.setState({pendingAuthorization:null}),H(new Error(Y.data.error||"OAuth authentication failed"))):Y.data?.type==="oauth_callback"&&(window.removeEventListener("message",J),clearInterval(oe),_.close(),u(Y.data.payload).then(G).catch(H))};window.addEventListener("message",J);const oe=setInterval(()=>{_.closed&&(clearInterval(oe),window.removeEventListener("message",J),T.getState().pendingAuthorization&&(b(),H(new Error("Popup closed by user"))))},500)})},[S,u,b]),I=T(x=>x.connectWithToken),O=z.useCallback(async(x,U,$)=>I(x,U,$),[I]),g=z.useCallback(async x=>{await m(x)},[m]),C=z.useCallback(async x=>u(x),[u]),N=z.useCallback(()=>{b()},[b]),B=z.useCallback(x=>P(x),[P]),M=z.useCallback(x=>R(x),[R]),w=z.useCallback(async x=>(await y(x))?.accessToken??null,[y]),X=z.useCallback(x=>{p(x)},[p]),W=c!==null;return z.useMemo(()=>({identities:a,connectedProviders:d,isAuthorizing:W,isLoading:h,error:f,pendingAuthorization:c,connect:j,connectWithPopup:E,connectWithToken:O,disconnect:g,completeAuthorization:C,cancelAuthorization:N,isConnected:B,getIdentity:M,getAccessToken:w,configureProvider:X}),[a,d,W,h,f,c,j,E,O,g,C,N,B,M,w,X])}const Ee={github:{name:"GitHub",icon:We,color:"#24292f",description:"Access GitHub repositories and APIs"},google:{name:"Google",icon:V,color:"#4285f4",description:"Access Google services and APIs"},kaggle:{name:"Kaggle",icon:V,color:"#20beff",description:"Access Kaggle datasets and notebooks"},linkedin:{name:"LinkedIn",icon:V,color:"#0077b5",description:"Access LinkedIn profile and connections"},slack:{name:"Slack",icon:V,color:"#4a154b",description:"Access Slack workspaces and channels"},notion:{name:"Notion",icon:V,color:"#000000",description:"Access Notion pages and databases"},custom:{name:"Custom",icon:de,color:"#6f42c1",description:"Custom OAuth provider"}},Bt={github:["read:user","user:email"],google:["openid","profile","email"],kaggle:["read"],linkedin:["r_liteprofile","r_emailaddress"],slack:["users:read","channels:read"],notion:["read_content"],custom:[]},Gt=({provider:t,clientId:s,providerConfig:r,scopes:l,disabled:o=!1,size:a="medium",variant:d="full",onConnect:c,onDisconnect:h,onError:f})=>{const{identities:S,isAuthorizing:u,error:b,connectWithPopup:m,disconnect:R,configureProvider:P}=ke(),y=Ee[t]||Ee.custom,p=S.find(g=>g.provider===t),j=!!p,E=u;te.useEffect(()=>{if(s){const g=t==="github"?ye:t==="google"?je:t==="kaggle"?Se:void 0;if(g){const C=r?.redirectUri||(typeof window<"u"?`${window.location.origin}${window.location.pathname}`:"");P({...g,...r,provider:t,clientId:s,redirectUri:C})}}},[s,t,r,P]);const I=z.useCallback(async()=>{try{if(j)await R(t),h?.(t);else{const g=await m(t,l||Bt[t]);c?.(g)}}catch(g){const C=g instanceof Error?g.message:String(g);C!=="Popup closed by user"&&f?.(g instanceof Error?g:new Error(C))}},[j,t,l,m,R,c,h,f]);te.useEffect(()=>{b&&f?.(b instanceof Error?b:new Error(String(b)))},[b,f]);const O={onClick:I,disabled:o||E||!s&&!j,size:a==="large"?"large":a==="small"?"small":"medium"};return d==="icon"?e.jsx(L,{...O,variant:j?"primary":"default","aria-label":j?`Disconnect ${y.name}`:`Connect ${y.name}`,sx:{width:a==="small"?28:a==="large"?44:36,height:a==="small"?28:a==="large"?44:36,p:0},children:E?e.jsx(n,{as:"span",className:"anim-rotate",display:"inline-block",children:"⏳"}):e.jsx(y.icon,{size:a==="small"?14:18})}):d==="compact"?e.jsx(L,{...O,variant:j?"primary":"default",leadingVisual:y.icon,trailingVisual:j?Oe:void 0,children:E?"Connecting...":y.name}):e.jsxs(n,{display:"flex",flexDirection:"column",gap:2,p:2,border:"1px solid",borderColor:j?"success.muted":"border.default",borderRadius:2,backgroundColor:j?"success.subtle":"canvas.subtle",children:[e.jsxs(n,{display:"flex",alignItems:"center",gap:2,children:[e.jsx(n,{width:40,height:40,borderRadius:2,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:y.color,color:"white",children:e.jsx(y.icon,{size:20})}),e.jsxs(n,{flex:1,children:[e.jsx(i,{sx:{fontWeight:"bold",display:"block"},children:y.name}),e.jsx(i,{sx:{fontSize:0,color:"fg.muted",display:"block"},children:j&&p?.userInfo?`Connected as ${p.userInfo.name||p.userInfo.email}`:y.description})]}),!j&&e.jsx(L,{...O,variant:"primary",leadingVisual:de,children:E?"Working...":"Connect"})]}),j&&p&&e.jsxs(n,{display:"flex",flexDirection:"column",gap:2,children:[e.jsxs(n,{display:"flex",alignItems:"center",gap:2,pl:1,children:[p.userInfo?.avatarUrl&&e.jsx("a",{href:p.userInfo.profileUrl||`https://github.com/${p.userInfo.username}`,target:"_blank",rel:"noopener noreferrer",style:{display:"block",lineHeight:0},children:e.jsx("img",{src:p.userInfo.avatarUrl,alt:p.userInfo.name||"User avatar",style:{width:32,height:32,borderRadius:"50%",cursor:"pointer"}})}),e.jsxs(n,{flex:1,children:[p.userInfo?.username&&e.jsx("a",{href:p.userInfo.profileUrl||`https://github.com/${p.userInfo.username}`,target:"_blank",rel:"noopener noreferrer",style:{textDecoration:"none"},children:e.jsxs(i,{sx:{fontSize:1,color:"fg.muted",display:"block",":hover":{textDecoration:"underline"}},children:["@",p.userInfo.username]})}),e.jsx(i,{sx:{fontSize:0,color:"fg.muted",display:"block"},children:p.token?.expiresAt?`Expires ${new Date(p.token.expiresAt).toLocaleDateString()}`:"Token does not expire"})]})]}),p.scopes&&p.scopes.length>0&&e.jsx(n,{display:"flex",flexWrap:"wrap",gap:1,pl:1,children:p.scopes.map(g=>e.jsx(i,{sx:{fontSize:0,px:2,py:1,bg:"neutral.muted",borderRadius:2,color:"fg.muted"},children:g},g))}),e.jsxs(L,{...O,variant:"danger",leadingVisual:$e,children:["Disconnect from ",y.name]})]})]})},Ue={github:{name:"GitHub",icon:We,color:"#24292f",description:"Access GitHub repositories and APIs"},google:{name:"Google",icon:V,color:"#4285f4",description:"Access Google services and APIs"},kaggle:{name:"Kaggle",icon:V,color:"#20beff",description:"Access Kaggle datasets and notebooks"},linkedin:{name:"LinkedIn",icon:V,color:"#0077b5",description:"Access LinkedIn profile"},slack:{name:"Slack",icon:V,color:"#4a154b",description:"Access Slack workspaces"},notion:{name:"Notion",icon:V,color:"#000000",description:"Access Notion pages"},custom:{name:"Custom",icon:de,color:"#6f42c1",description:"Custom OAuth provider"}},Kt={github:["read:user","user:email","repo"],google:["openid","profile","email"],kaggle:["read"],linkedin:["r_liteprofile","r_emailaddress"],slack:["users:read","channels:read"],notion:["read_content"],custom:[]};function Jt(t){if(!t)return{isExpired:!1,isExpiringSoon:!1};const s=Date.now(),r=new Date(t),l=t-s,o=s-t,a=300*1e3;return{isExpired:l<0,isExpiringSoon:l>0&&l<a,expiresAt:r,timeUntilExpiry:l>0?l:void 0,timeSinceExpiry:l<0?o:void 0}}function he(t){const s=Math.floor(t/1e3),r=Math.floor(s/60),l=Math.floor(r/60),o=Math.floor(l/24);return o>0?o===1?"1 day":`${o} days`:l>0?l===1?"1 hour":`${l} hours`:r>0?r===1?"1 minute":`${r} minutes`:s===1?"1 second":`${s} seconds`}function Yt(t){return t.isExpired&&t.timeSinceExpiry?`Expired ${he(t.timeSinceExpiry)} ago`:t.timeUntilExpiry?t.isExpiringSoon?`Expires in ${he(t.timeUntilExpiry)}`:`Expires in ${he(t.timeUntilExpiry)}`:"Token does not expire"}function Xt({identity:t,providerConfig:s,showExpirationDetails:r=!0,allowReconnect:l=!0,onConnect:o,onDisconnect:a,onError:d}){const{connect:c,disconnect:h,configureProvider:f,isAuthorizing:S}=ke(),u=t.provider,b=Ue[u]||Ue.custom,m=z.useMemo(()=>Jt(t.token?.expiresAt),[t.token?.expiresAt]);te.useEffect(()=>{if(s?.clientId){const y=u==="github"?ye:u==="google"?je:u==="kaggle"?Se:void 0;if(y){const p=s.config?.redirectUri||(typeof window<"u"?`${window.location.origin}${window.location.pathname}`:"");f({...y,...s.config,provider:u,clientId:s.clientId,redirectUri:p})}}},[s,u,f]);const R=z.useCallback(async()=>{try{const y=s?.scopes||Kt[u];await c(u,y)}catch(y){d?.(y instanceof Error?y:new Error(String(y)))}},[u,s?.scopes,c,d]),P=z.useCallback(async()=>{try{await h(u),a?.(u)}catch(y){d?.(y instanceof Error?y:new Error(String(y)))}},[u,h,a,d]);return e.jsxs(n,{display:"flex",flexDirection:"column",gap:2,p:3,border:"1px solid",borderColor:m.isExpired?"danger.muted":m.isExpiringSoon?"attention.muted":"success.muted",borderRadius:2,backgroundColor:m.isExpired?"danger.subtle":m.isExpiringSoon?"attention.subtle":"success.subtle",children:[e.jsxs(n,{display:"flex",alignItems:"center",gap:2,children:[e.jsx(n,{width:32,height:32,borderRadius:2,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:b.color,color:"white",children:e.jsx(b.icon,{size:16})}),e.jsxs(n,{flex:1,display:"flex",alignItems:"center",gap:2,children:[e.jsx(i,{sx:{fontWeight:"semibold",fontSize:1},children:b.name}),e.jsx(A,{size:"small",variant:"secondary",children:t.authType==="token"?"API Key":"OAuth"})]}),m.isExpired?e.jsx(A,{variant:"danger",size:"small",children:e.jsxs(n,{display:"inline-flex",alignItems:"center",gap:1,children:[e.jsx(nt,{size:12})," Expired"]})}):m.isExpiringSoon?e.jsx(A,{variant:"attention",size:"small",children:e.jsxs(n,{display:"inline-flex",alignItems:"center",gap:1,children:[e.jsx(me,{size:12})," Expiring Soon"]})}):e.jsx(A,{variant:"success",size:"small",children:e.jsxs(n,{display:"inline-flex",alignItems:"center",gap:1,children:[e.jsx(Oe,{size:12})," Connected"]})})]}),e.jsxs(n,{display:"flex",alignItems:"center",gap:2,children:[t.userInfo?.avatarUrl&&e.jsx("a",{href:t.userInfo.profileUrl||(u==="github"?`https://github.com/${t.userInfo.username}`:void 0),target:"_blank",rel:"noopener noreferrer",style:{display:"block",lineHeight:0},children:e.jsx(kt,{src:t.userInfo.avatarUrl,size:32,alt:t.userInfo.name||t.userInfo.username||b.name,sx:{cursor:"pointer"}})}),e.jsxs(n,{flex:1,minWidth:0,children:[t.userInfo?.name&&e.jsx(i,{sx:{fontWeight:"semibold",fontSize:1,display:"block"},children:t.userInfo.name}),(t.userInfo?.username||t.userInfo?.email)&&e.jsx("a",{href:t.userInfo.profileUrl||(u==="github"?`https://github.com/${t.userInfo.username}`:void 0),target:"_blank",rel:"noopener noreferrer",style:{textDecoration:"none"},children:e.jsx(i,{sx:{fontSize:0,color:"fg.muted",display:"block",":hover":{textDecoration:"underline"}},children:t.userInfo.username?`@${t.userInfo.username}`:t.userInfo.email})})]})]}),r&&e.jsxs(n,{display:"flex",alignItems:"center",gap:1,children:[e.jsx(me,{size:12}),e.jsx(i,{sx:{fontSize:0,color:m.isExpired?"danger.fg":m.isExpiringSoon?"attention.fg":"fg.muted"},children:Yt(m)})]}),t.scopes&&t.scopes.length>0&&e.jsx(n,{display:"flex",flexWrap:"wrap",gap:1,children:t.scopes.map(y=>e.jsx(A,{size:"small",variant:"secondary",children:y},y))}),e.jsxs(n,{display:"flex",gap:2,mt:1,children:[m.isExpired&&l&&s?.clientId&&e.jsx(st,{text:"Reconnect to refresh token",children:e.jsx(L,{variant:"primary",size:"small",leadingVisual:ot,onClick:R,disabled:S,children:S?"Connecting...":"Reconnect"})}),e.jsxs(L,{variant:m.isExpired?"invisible":"danger",size:"small",leadingVisual:$e,onClick:P,disabled:S,children:["Disconnect from ",b.name]})]})]})}function Qt({providers:t,title:s="Connected Accounts",showHeader:r=!0,showDescription:l=!0,description:o="Connected identities for this agent. Agents can use these to access external services on your behalf.",showExpirationDetails:a=!0,allowReconnect:d=!0,onConnect:c,onDisconnect:h,onError:f}){const{identities:S,error:u}=ke(),b=z.useMemo(()=>{if(t){const p=Object.keys(t);return S.filter(j=>p.includes(j.provider)||j.authType==="token"&&j.isConnected)}return S},[S,t]),m=z.useMemo(()=>new Set(S.map(p=>p.provider)),[S]),R=z.useMemo(()=>{if(!t)return{};const p=Object.keys(t),j={};for(const E of p)m.has(E)||(j[E]=t[E]);return j},[t,m]),P=Object.keys(R).length>0,y=z.useCallback(p=>j=>{f?.(p,j)},[f]);return b.length===0&&!t?null:e.jsxs(n,{children:[r&&e.jsxs(n,{display:"flex",alignItems:"center",gap:2,mb:2,children:[e.jsx(V,{size:16}),e.jsx(i,{sx:{fontSize:1,fontWeight:"semibold",color:"fg.muted"},children:s})]}),e.jsxs(n,{p:3,bg:"canvas.subtle",borderRadius:2,border:"1px solid",borderColor:"border.default",children:[l&&e.jsx(i,{sx:{fontSize:0,color:"fg.muted",display:"block",mb:b.length>0?3:0},children:o}),u&&e.jsx(wt,{variant:"danger",sx:{mb:3},children:u instanceof Error?u.message:String(u)}),b.length>0?e.jsx(n,{display:"flex",flexDirection:"column",gap:2,children:b.map(p=>e.jsx(Xt,{identity:p,providerConfig:t?.[p.provider],showExpirationDetails:a,allowReconnect:d,onConnect:c,onDisconnect:h,onError:y(p.provider)},p.provider))}):P?null:e.jsxs(n,{display:"flex",alignItems:"center",gap:2,color:"fg.muted",children:[e.jsx(de,{size:16}),e.jsx(i,{sx:{fontSize:1},children:"No connected accounts"})]}),P&&e.jsxs(n,{mt:b.length>0?3:0,children:[b.length>0&&e.jsx(i,{sx:{fontSize:0,color:"fg.muted",display:"block",mb:2},children:"Connect additional accounts:"}),e.jsx(n,{display:"flex",flexDirection:"column",gap:2,children:Object.keys(R).map(p=>{const j=R[p];return e.jsx(Gt,{provider:p,clientId:j.clientId,scopes:j.scopes,providerConfig:j.config,size:"medium",variant:"full",onConnect:c,onDisconnect:h,onError:y(p)},p)})})]})]})]})}const ge=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),xe=t=>{if(t==null)return"null";if(typeof t=="number"||typeof t=="boolean")return String(t);const s=String(t);return s===""?"''":/^[a-zA-Z0-9._/-]+$/.test(s)?s:JSON.stringify(s)},be=(t,s=0)=>{const r=" ".repeat(s);if(Array.isArray(t))return t.length===0?"[]":t.map(l=>ge(l)||Array.isArray(l)?`${r}-
|
|
3
3
|
${be(l,s+1)}`:`${r}- ${xe(l)}`).join(`
|
|
4
4
|
`);if(ge(t)){const l=Object.entries(t).filter(([,o])=>o!==void 0);return l.length===0?"{}":l.map(([o,a])=>ge(a)||Array.isArray(a)?`${r}${o}:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as n,Q as l,j as s,D as o,a as m}from"../datalayer-app-main.js";import{AgentDetails as p}from"./AgentDetails-
|
|
1
|
+
import{r as n,Q as l,j as s,D as o,a as m}from"../datalayer-app-main.js";import{AgentDetails as p}from"./AgentDetails-eWkEnFI1.js";import"./ArrowLeftIcon-Y3PTljcl.js";import"./UnlinkIcon-DuVqPyB-.js";import"./index-hib7vWC6.js";import"./LinkIcon-DUI0jw25.js";import"./Flash-C3nF3s4G.js";import"./Avatar-BrPfm89P.js";function B({about:e,name:r,onClose:t}){const a=n.useMemo(()=>new l,[]),i=!!(e.agentId&&e.apiBase);return s.jsx(o,{title:`${e.name??r} · Agent Details`,onClose:t,width:"xlarge",height:"large",children:s.jsx("div",{"data-assistant-agent-details":"",children:s.jsx(m,{client:a,children:s.jsx(p,{name:e.name??r,protocol:e.protocol??(i?"agent-runtimes":"browser"),url:e.url??"",messageCount:0,agentId:e.agentId,apiBase:e.apiBase,onBack:t,showBackHeader:!1,showUsage:i,padded:!1,runtime:i,summary:{spec:e.spec,model:e.model,where:e.where,description:e.description,skills:e.skills}})})})})}export{B as AgentDetailsDialog,B as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as f,j as e,B as l,cQ as ie,eJ as se,T as c,bm as W,cP as F,L as D,I as oe,eK as le,eL as V,c as U,P as ae,eM as de,k as ce,eN as ue,dx as H,bd as M,eO as xe,eP as fe,eQ as K,eR as pe,eS as he}from"../datalayer-app-main.js";import{B,U as $}from"./index-DIHzcHI1.js";function E(t){const n=Number(t);return!isNaN(n)&&n>1e15?n/1e6:!isNaN(n)&&n>1e12?n/1e3:isNaN(n)?new Date(String(t)).getTime():n}function J(t){return t==null?"—":t<.001?"<1µs":t<1?`${(t*1e3).toFixed(0)}µs`:t<1e3?`${t.toFixed(1)}ms`:t<6e4?`${(t/1e3).toFixed(2)}s`:`${(t/6e4).toFixed(1)}m`}function me(t){if(t==null||t==="")return"—";try{const n=E(t),r=new Date(n);return isNaN(r.getTime())?String(t):r.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3})}catch{return String(t)}}const X=["#0969da","#1a7f37","#cf222e","#8250df","#bf8700","#0550ae","#116329","#a40e26","#6639ba","#953800","#0e8a16","#e36209"];function ge(t){let n=0;for(let r=0;r<t.length;r++)n=n*31+t.charCodeAt(r)|0;return X[Math.abs(n)%X.length]}function q(t){const n=new Map,r=t.map(o=>({...o,children:[],depth:0}));for(const o of r)n.set(o.span_id,o);const i=[];for(const o of r)if(o.parent_span_id&&n.has(o.parent_span_id)){const x=n.get(o.parent_span_id);x.children=x.children??[],x.children.push(o)}else i.push(o);function a(o,x){o.depth=x;for(const p of o.children??[])a(p,x+1)}for(const o of i)a(o,0);return i}const be="peer.service";function je(t,n){return t.service_name===n||t.attributes?.[be]===n}function Se(t,n){return n?t.filter(r=>je(r,n)):[...t]}const Q=[],_e=()=>()=>{};function we(t){return f.useSyncExternalStore(t?t.subscribe:_e,()=>t?t.spans():Q,()=>t?t.spans():Q)}const ye="140px 1fr 160px 90px",ve="96px minmax(0, 1fr) 96px 64px";function ke(t){const n=t.attributes;if(!n)return null;const r=n["gen_ai.usage.input_tokens"]!=null?Number(n["gen_ai.usage.input_tokens"]):void 0,i=n["gen_ai.usage.output_tokens"]!=null?Number(n["gen_ai.usage.output_tokens"]):void 0;return r==null&&i==null?null:{input:r,output:i}}const Ce=({spans:t,loading:n,selectedSpanId:r,onSelectSpan:i,emptyText:a,compact:o=!1,defaultExpanded:x=!1,renderSpanMark:p,describeSpan:u})=>{const[h,d]=f.useState(new Set),m=f.useMemo(()=>({has:s=>x?!h.has(s):h.has(s)}),[h,x]),j=o?ve:ye,S=f.useMemo(()=>q(t),[t]),g=f.useMemo(()=>{const s=[];function y(b,O){const v=b.children??[];if(s.push({span:b,depth:O,hasChildren:v.length>0}),m.has(b.span_id))for(const T of v)y(T,O+1)}for(const b of S)y(b,0);return s},[S,m]),A=f.useCallback(s=>{d(y=>{const b=new Set(y);return b.has(s)?b.delete(s):b.add(s),b})},[]);return n?e.jsx(l,{display:"flex",justifyContent:"center",p:5,children:e.jsx(ie,{size:"medium"})}):t.length===0?e.jsxs(B,{children:[e.jsx(B.Visual,{children:e.jsx(se,{size:24})}),e.jsx(B.Heading,{children:"No traces found"}),e.jsx(B.Description,{children:a??"Send some telemetry data first."})]}):e.jsxs(l,{width:"100%",flex:1,minHeight:0,overflow:"auto",children:[e.jsx(l,{display:"grid",gridTemplateColumns:j,gap:2,px:3,position:"sticky",top:0,bg:"canvas.subtle",zIndex:1,borderBottom:"2px solid",borderColor:"border.default",children:["Time","Message","Scope","Duration"].map(s=>e.jsx(c,{sx:{fontWeight:"bold",fontSize:0,color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em",py:2,...s==="Duration"?{textAlign:"right"}:{}},children:s},s))}),g.map(({span:s,depth:y,hasChildren:b},O)=>{const v=r===s.span_id,T=m.has(s.span_id),C=y*(o?12:20),k=u?.(s);return e.jsxs(l,{"data-otel-span":s.span_id,"data-otel-span-name":s.span_name,onClick:()=>{b&&A(s.span_id),i?.(s)},display:"grid",gridTemplateColumns:j,gap:2,px:3,py:"5px",cursor:"pointer",bg:v?"accent.subtle":y>0?"canvas.inset":"canvas.default",borderBottom:"1px solid",borderColor:"border.muted",hover:{bg:v?"accent.subtle":"canvas.subtle"},children:[e.jsx(c,{sx:{fontSize:o?0:1,fontFamily:"mono",color:"fg.muted",whiteSpace:"nowrap",lineHeight:"22px"},children:me(s.start_time)}),e.jsxs(l,{display:"flex",alignItems:"center",gap:1,overflow:"hidden",lineHeight:"22px",pl:`${C}px`,children:[b?e.jsx(l,{flexShrink:0,color:"fg.muted",display:"flex",alignItems:"center",children:T?e.jsx(W,{size:14}):e.jsx(F,{size:14})}):y>0?e.jsx(l,{flexShrink:0,width:"14px",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.subtle",fontSize:0,children:"─"}):null,p?.(s),e.jsx(c,{sx:{fontSize:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:k?0:1,maxWidth:k?"60%":void 0},title:s.span_name,children:s.span_name}),s.in_progress&&e.jsx(D,{variant:"attention",size:"small",children:"running"}),s.status_code==="ERROR"&&e.jsx(D,{variant:"danger",size:"small",children:"ERROR"}),(()=>{const I=ke(s);return I?e.jsxs(l,{display:"inline-flex",alignItems:"center",gap:"2px",border:"1px solid",borderColor:"border.default",borderRadius:2,px:1,fontSize:"10px",fontFamily:"mono",color:"fg.muted",flexShrink:0,lineHeight:"16px",children:[I.input!=null&&e.jsxs(l,{display:"inline-flex",alignItems:"center",gap:"1px",children:[e.jsx(c,{sx:{fontSize:"9px",color:"fg.subtle"},children:"↗"}),e.jsx(c,{children:I.input})]}),I.output!=null&&e.jsxs(l,{display:"inline-flex",alignItems:"center",gap:"1px",children:[e.jsx(c,{sx:{fontSize:"9px",color:"fg.subtle"},children:"↙"}),e.jsx(c,{children:I.output})]})]}):null})(),k&&e.jsx(c,{sx:{fontSize:1,color:"fg.muted",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},title:k,"data-otel-span-description":"",children:k}),s.otel_scope_name&&!o&&e.jsx(D,{size:"small",variant:"secondary",sx:{flexShrink:0,fontSize:"10px"},children:s.otel_scope_name})]}),e.jsx(c,{sx:{fontSize:1,color:"fg.muted",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:"22px"},title:`${s.service_name} / ${s.otel_scope_name??""}`,children:s.service_name}),e.jsx(c,{sx:{fontSize:1,fontFamily:"mono",textAlign:"right",lineHeight:"22px",color:s.duration_ms!=null&&s.duration_ms>1e3?"danger.fg":"fg.default"},children:s.in_progress?"…":J(s.duration_ms)})]},`${s.trace_id}-${s.span_id}-${O}`)})]})},ze=20,Z=({span:t,depth:n,selectedSpanId:r,onSelectSpan:i,expandedIds:a,toggleExpanded:o,traceMinTime:x,traceDuration:p})=>{const u=(t.children?.length??0)>0,h=a.has(t.span_id),d=r===t.span_id,m=ge(t.service_name),j=(E(t.start_time)-x)/p*100,S=Math.max((t.duration_ms||0)/p*100,.5);return e.jsxs(e.Fragment,{children:[e.jsxs(l,{display:"flex",alignItems:"center",height:28,pl:`${n*ze}px`,pr:2,cursor:"pointer",bg:d?"accent.subtle":"canvas.default",borderBottom:"1px solid",borderColor:"border.muted",hover:{bg:d?"accent.subtle":"canvas.subtle"},onClick:()=>i?.(t),children:[e.jsx(l,{width:20,textAlign:"center",color:"fg.muted",userSelect:"none",flexShrink:0,cursor:u?"pointer":"default",onClick:g=>{g.stopPropagation(),u&&o(t.span_id)},children:u?h?e.jsx(W,{size:12}):e.jsx(F,{size:12}):e.jsx(c,{sx:{color:"fg.subtle",fontSize:0},children:"·"})}),e.jsx(l,{width:8,height:8,borderRadius:"50%",bg:m,flexShrink:0,mr:1}),e.jsx(c,{sx:{flex:"0 0 200px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:1,fontWeight:d?"bold":"normal"},title:`${t.service_name} / ${t.span_name}`,children:t.span_name}),e.jsx(l,{flex:1,position:"relative",height:12,bg:"canvas.subtle",borderRadius:1,mx:2,overflow:"hidden",children:e.jsx(l,{position:"absolute",left:`${j}%`,width:`${S}%`,height:"100%",bg:m,borderRadius:1,opacity:d?1:.7})}),e.jsx(c,{sx:{minWidth:60,textAlign:"right",fontSize:0,fontFamily:"mono",color:"fg.muted",flexShrink:0},children:J(t.duration_ms)})]}),u&&h&&t.children.map(g=>e.jsx(Z,{span:g,depth:n+1,selectedSpanId:r,onSelectSpan:i,expandedIds:a,toggleExpanded:o,traceMinTime:x,traceDuration:p},g.span_id))]})},Ie=({spans:t,selectedSpanId:n,onSelectSpan:r,defaultExpandDepth:i=2})=>{const a=f.useMemo(()=>{const d=new Set;function m(j,S){for(const g of j)S<i&&d.add(g.span_id),g.children&&m(g.children,S+1)}return m(t,0),d},[t,i]),[o,x]=f.useState(a),p=f.useCallback(d=>{x(m=>{const j=new Set(m);return j.has(d)?j.delete(d):j.add(d),j})},[]),{traceMinTime:u,traceDuration:h}=f.useMemo(()=>{let d=1/0,m=-1/0;function j(S){for(const g of S){const A=E(g.start_time),s=E(g.end_time);A<d&&(d=A),s>m&&(m=s),g.children&&j(g.children)}}return j(t),d===1/0?{traceMinTime:0,traceDuration:1}:{traceMinTime:d,traceDuration:m-d||1}},[t]);return t.length===0?e.jsx(l,{p:3,color:"fg.muted",textAlign:"center",children:e.jsx(c,{children:"No span tree to display."})}):e.jsxs(l,{width:"100%",overflow:"auto",children:[e.jsxs(l,{display:"flex",alignItems:"center",height:28,px:2,borderBottom:"2px solid",borderColor:"border.default",bg:"canvas.subtle",children:[e.jsx(l,{width:20}),e.jsx(l,{width:8,mr:1}),e.jsx(c,{sx:{flex:"0 0 200px",fontSize:0,fontWeight:"bold",color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Span"}),e.jsx(c,{sx:{flex:1,mx:2,fontSize:0,fontWeight:"bold",color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Timeline"}),e.jsx(c,{sx:{minWidth:60,textAlign:"right",fontSize:0,fontWeight:"bold",color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Duration"})]}),t.map(d=>e.jsx(Z,{span:d,depth:0,selectedSpanId:n,onSelectSpan:r,expandedIds:o,toggleExpanded:p,traceMinTime:u,traceDuration:h},d.span_id))]})},w=({label:t,value:n,mono:r=!1})=>n==null||n===""?null:e.jsxs(l,{display:"flex",py:1,borderBottom:"1px solid",borderColor:"border.muted",gap:2,children:[e.jsx(c,{sx:{width:140,minWidth:140,color:"fg.muted",fontSize:1,fontWeight:"bold"},children:t}),e.jsx(c,{sx:{fontSize:1,fontFamily:r?"mono":"normal",wordBreak:"break-all"},children:String(n)})]}),Y=({title:t,data:n,defaultOpen:r=!1})=>{const[i,a]=f.useState(r);return!n||Object.keys(n).length===0?null:e.jsxs(l,{mt:3,children:[e.jsxs(l,{display:"flex",alignItems:"center",gap:1,cursor:"pointer",py:1,userSelect:"none",onClick:()=>a(!i),children:[i?e.jsx(W,{size:16}):e.jsx(F,{size:16}),e.jsx(c,{sx:{fontSize:1,fontWeight:"bold"},children:t}),e.jsx(V,{children:Object.keys(n).length})]}),i&&e.jsx(l,{bg:"canvas.subtle",borderRadius:2,border:"1px solid",borderColor:"border.default",p:2,mt:1,overflowX:"auto",children:Object.entries(n).map(([o,x])=>e.jsx(L,{attrKey:o,value:x,depth:0},o))})]})};function Te(t){if(typeof t!="string")return t;const n=t.trim();if(!/^[[{]/.test(n))return t;try{const r=JSON.parse(n);return typeof r=="object"&&r!==null?r:t}catch{return t}}const L=({attrKey:t,value:n,depth:r})=>{const i=f.useMemo(()=>Te(n),[n]),[a,o]=f.useState(r<1),x=typeof i=="object"&&i!==null&&!Array.isArray(i),p=Array.isArray(i),u=x||p;return e.jsxs(l,{borderBottom:r===0?"1px solid":"none",borderColor:"border.muted",pb:r===0?1:0,mb:r===0?1:0,children:[e.jsxs(l,{display:"flex",gap:2,py:1,pl:r*16+"px",alignItems:"flex-start",children:[u?e.jsx(l,{cursor:"pointer",color:"fg.muted",userSelect:"none",width:16,flexShrink:0,onClick:()=>o(!a),children:a?e.jsx(W,{size:12}):e.jsx(F,{size:12})}):e.jsx(l,{width:16,flexShrink:0}),e.jsx(c,{sx:{color:"accent.fg",fontSize:1,fontFamily:"mono",minWidth:180,wordBreak:"break-all",flexShrink:0},children:t}),!u&&e.jsx(c,{sx:{fontSize:1,fontFamily:"mono",whiteSpace:"pre-wrap",wordBreak:"break-word",color:typeof i=="string"?"accent.emphasis":"attention.fg"},children:typeof i=="string"?i:JSON.stringify(i)}),u&&!a&&e.jsx(c,{sx:{fontSize:0,color:"fg.muted",fontFamily:"mono"},children:p?`[${i.length} items]`:`{${Object.keys(i).length} keys}`})]}),u&&a&&e.jsx(l,{children:p?i.map((h,d)=>e.jsx(L,{attrKey:`[${d}]`,value:h,depth:r+1},d)):Object.entries(i).map(([h,d])=>e.jsx(L,{attrKey:h,value:d,depth:r+1},h))})]})},Ae=({span:t,traceSpans:n,onClose:r})=>{const[i,a]=f.useState("details");if(!t)return e.jsx(l,{p:5,color:"fg.muted",textAlign:"center",children:e.jsx(c,{children:"Select a span to view details."})});const o={},x={};if(t.attributes)for(const[u,h]of Object.entries(t.attributes))u.startsWith("gen_ai.")||u.startsWith("model_request")?o[u]=h:x[u]=h;const p=n&&n.length>0?q(n):void 0;return e.jsxs(l,{height:"100%",overflow:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.default",display:"flex",flexDirection:"column",children:[e.jsxs(l,{px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",display:"flex",justifyContent:"space-between",alignItems:"center",bg:"canvas.subtle",flexShrink:0,children:[e.jsx(c,{sx:{fontSize:2,fontWeight:"bold"},children:t.span_name}),r&&e.jsx(oe,{icon:le,"aria-label":"Close detail panel",variant:"invisible",size:"small",onClick:r})]}),e.jsxs($,{"aria-label":"Span detail tabs",children:[e.jsx($.Item,{"aria-current":i==="details"?"page":void 0,onClick:()=>a("details"),children:"Details"}),p&&e.jsx($.Item,{"aria-current":i==="tree"?"page":void 0,onClick:()=>a("tree"),children:"Trace Tree"}),e.jsx($.Item,{"aria-current":i==="raw"?"page":void 0,onClick:()=>a("raw"),children:"Raw Data"})]}),e.jsxs(l,{flex:1,overflow:"auto",children:[i==="details"&&e.jsxs(l,{p:3,children:[e.jsx(w,{label:"span_name",value:t.span_name}),e.jsx(w,{label:"service_name",value:t.service_name}),e.jsx(w,{label:"otel_scope_name",value:t.otel_scope_name}),e.jsx(w,{label:"kind",value:t.kind}),e.jsx(w,{label:"trace_id",value:t.trace_id,mono:!0}),e.jsx(w,{label:"span_id",value:t.span_id,mono:!0}),e.jsx(w,{label:"parent_span_id",value:t.parent_span_id,mono:!0}),e.jsx(w,{label:"duration",value:J(t.duration_ms)}),e.jsx(w,{label:"start_time",value:t.start_time,mono:!0}),e.jsx(w,{label:"end_time",value:t.end_time,mono:!0}),e.jsx(w,{label:"status_code",value:t.status_code}),e.jsx(w,{label:"status_message",value:t.status_message}),e.jsx(Y,{title:"Arguments",data:o,defaultOpen:Object.keys(o).length>0}),e.jsx(Y,{title:"Attributes",data:x}),t.events&&t.events.length>0&&e.jsxs(l,{mt:3,children:[e.jsxs(l,{display:"flex",alignItems:"center",gap:1,children:[e.jsx(c,{sx:{fontWeight:"bold",fontSize:1},children:"Events"}),e.jsx(V,{children:t.events.length})]}),t.events.map((u,h)=>e.jsxs(l,{bg:"canvas.subtle",borderRadius:2,border:"1px solid",borderColor:"border.default",p:2,mt:2,children:[e.jsxs(l,{display:"flex",gap:2,children:[e.jsx(D,{children:u.name}),e.jsx(c,{sx:{fontSize:0,color:"fg.muted",fontFamily:"mono"},children:u.timestamp})]}),u.attributes&&Object.keys(u.attributes).length>0&&e.jsx(l,{mt:1,children:Object.entries(u.attributes).map(([d,m])=>e.jsx(L,{attrKey:d,value:m,depth:0},d))})]},h))]}),t.links&&t.links.length>0&&e.jsxs(l,{mt:3,children:[e.jsxs(l,{display:"flex",alignItems:"center",gap:1,children:[e.jsx(c,{sx:{fontWeight:"bold",fontSize:1},children:"Links"}),e.jsx(V,{children:t.links.length})]}),t.links.map((u,h)=>e.jsxs(c,{sx:{display:"block",fontSize:1,fontFamily:"mono",py:1,borderBottom:"1px solid",borderColor:"border.muted"},children:["trace: ",u.trace_id," → span: ",u.span_id]},h))]})]}),i==="tree"&&p&&e.jsx(Ie,{spans:p,selectedSpanId:t.span_id,defaultExpandDepth:4}),i==="raw"&&e.jsx(l,{as:"pre",p:3,fontSize:0,fontFamily:"mono",whiteSpace:"pre-wrap",wordBreak:"break-word",m:0,bg:"canvas.subtle",children:JSON.stringify(t,null,2)})]})]})},Oe=[{label:"Service",value:t=>t.service_name},{label:"Kind",value:t=>t.kind}];function Ne(t,n,r){return t.filter(i=>n.every((a,o)=>{const x=r[o];if(!x?.size)return!0;const p=a.value(i);return p!==void 0&&x.has(p)}))}function Re(t,n){const r=new Set(t);return r.has(n)?r.delete(n):r.add(n),r}function Ee({facet:t,options:n,selected:r,onChange:i}){const a=t.name??(o=>o);return e.jsxs(H,{children:[e.jsxs(H.Button,{size:"small","data-otel-facet":t.label.toLowerCase(),children:[t.label,r.size?` · ${r.size}`:""]}),e.jsx(H.Overlay,{width:"auto",children:e.jsxs(M,{selectionVariant:"multiple","aria-label":t.label,children:[e.jsx(M.Item,{selected:!r.size,onSelect:()=>i(new Set),children:"All"}),e.jsx(M.Divider,{}),n.map(o=>e.jsx(M.Item,{selected:r.has(o),onSelect:()=>i(Re(r,o)),children:a(o)},o))]})})]})}function Me(t,n){const r=new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.href=i,a.download=`${t}.json`,a.click(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}const Be=({tracer:t,spans:n,service:r,facets:i=Oe,compact:a=!1,maxHeight:o=420,detailPlacement:x="below",emptyText:p="Nothing recorded yet.",exportName:u="otel-spans",label:h="Spans",renderSpanMark:d,describeSpan:m})=>{const j=we(n?null:t),S=n??j,[g,A]=f.useState(0),[s,y]=f.useState(null),[b,O]=f.useState(()=>i.map(()=>new Set)),[v,T]=f.useState(null),C=f.useMemo(()=>{const _=Se(S,r);return g?_.filter(z=>E(z.start_time)>=g):_},[S,r,g]),k=s??C,I=s?C.length-s.length:0,ee=f.useMemo(()=>i.map(_=>[...new Set(C.map(z=>_.value(z)).filter(z=>z!==void 0))].sort()),[i,C]),N=f.useMemo(()=>Ne(k,i,b),[k,i,b]),R=f.useMemo(()=>v?S.find(_=>_.span_id===v)??null:null,[S,v]),te=f.useMemo(()=>R?S.filter(_=>_.trace_id===R.trace_id):[],[S,R]),P=x==="side"&&!a;return e.jsxs(l,{"data-otel-live-spans":"",border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.default",color:"fg.default",minWidth:0,children:[e.jsxs(l,{role:"toolbar","aria-label":h,display:"flex",flexWrap:"wrap",gap:2,alignItems:"center",p:2,borderBottom:"1px solid",borderColor:"border.default",children:[i.map((_,z)=>e.jsx(Ee,{facet:_,options:ee[z]??[],selected:b[z]??new Set,onChange:ne=>O(re=>i.map((Le,G)=>G===z?ne:re[G]??new Set))},_.label)),e.jsx(l,{flex:1}),e.jsxs(c,{sx:{fontSize:0,color:"fg.muted"},"data-otel-span-count":"",children:[N.length===k.length?`${N.length} ${N.length===1?"span":"spans"}`:`${N.length} of ${k.length}`,I>0?` · ${I} new`:""]}),e.jsx(U,{size:"small",leadingVisual:s?ae:de,"aria-pressed":s!==null,onClick:()=>y(s?null:C),"data-otel-pause":"",children:s?"Resume":"Pause"}),e.jsx(U,{size:"small",leadingVisual:ce,onClick:()=>{y(null),T(null),t&&!n&&!r?t.clear():A(Date.now())},"data-otel-clear":"",children:"Clear"}),e.jsx(U,{size:"small",leadingVisual:ue,disabled:!C.length,onClick:()=>Me(u,{exportedAt:new Date().toISOString(),spans:[...C]}),"data-otel-export":"",children:"Export"})]}),e.jsxs(l,{display:P?"grid":"block",gridTemplateColumns:P?"minmax(0, 3fr) minmax(0, 2fr)":void 0,children:[e.jsx(l,{maxHeight:o,overflowY:"auto",minWidth:0,children:e.jsx(Ce,{spans:N,selectedSpanId:v,onSelectSpan:_=>T(_.span_id),emptyText:p,compact:a,defaultExpanded:!0,renderSpanMark:d,describeSpan:m})}),R&&e.jsx(l,{"data-otel-live-detail":"",maxHeight:o,overflowY:"auto",minWidth:0,borderTop:P?"none":"1px solid",borderColor:"border.default",children:e.jsx(Ae,{span:R,traceSpans:te,onClose:()=>T(null)})})]})]})},$e=[{label:"Source",value:fe,name:t=>xe[t]??t},{label:"Operation",value:t=>{const n=t.attributes??{},r=n[K.operation]??n["rpc.method"];return r===void 0?void 0:String(r)}},{label:"Agent",value:t=>t.service_name}];function De(t){const n=t.attributes?.[K.markIcon],r=t.attributes?.[K.markEmoji];return n||r?e.jsx(he,{icon:typeof n=="string"?n:void 0,emoji:typeof r=="string"?r:void 0,size:14}):null}function Pe({tracer:t,spans:n,agent:r,maxHeight:i=420,compact:a=!1,emptyText:o="Nothing recorded yet.",exportName:x="agent-inspector"}){return e.jsx("div",{"data-agent-inspector":r??"",children:e.jsx(Be,{tracer:t,spans:n,service:r,facets:$e,compact:a,maxHeight:i,detailPlacement:"side",emptyText:o,exportName:x,label:r?`${r}'s Agent Inspector`:"Agent Inspector",renderSpanMark:De,describeSpan:pe})})}export{$e as AGENT_INSPECTOR_FACETS,Pe as AgentInspector,Pe as default};
|
|
1
|
+
import{r as f,j as e,B as l,cQ as ie,eJ as se,T as c,bt as W,cP as F,L as D,I as oe,eK as le,eL as V,c as U,P as ae,eM as de,k as ce,eN as ue,dx as H,bk as M,eO as xe,eP as fe,eQ as K,eR as pe,eS as he}from"../datalayer-app-main.js";import{B,U as $}from"./index-5Mm_lDnH.js";function E(t){const n=Number(t);return!isNaN(n)&&n>1e15?n/1e6:!isNaN(n)&&n>1e12?n/1e3:isNaN(n)?new Date(String(t)).getTime():n}function J(t){return t==null?"—":t<.001?"<1µs":t<1?`${(t*1e3).toFixed(0)}µs`:t<1e3?`${t.toFixed(1)}ms`:t<6e4?`${(t/1e3).toFixed(2)}s`:`${(t/6e4).toFixed(1)}m`}function me(t){if(t==null||t==="")return"—";try{const n=E(t),r=new Date(n);return isNaN(r.getTime())?String(t):r.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3})}catch{return String(t)}}const X=["#0969da","#1a7f37","#cf222e","#8250df","#bf8700","#0550ae","#116329","#a40e26","#6639ba","#953800","#0e8a16","#e36209"];function ge(t){let n=0;for(let r=0;r<t.length;r++)n=n*31+t.charCodeAt(r)|0;return X[Math.abs(n)%X.length]}function q(t){const n=new Map,r=t.map(o=>({...o,children:[],depth:0}));for(const o of r)n.set(o.span_id,o);const i=[];for(const o of r)if(o.parent_span_id&&n.has(o.parent_span_id)){const x=n.get(o.parent_span_id);x.children=x.children??[],x.children.push(o)}else i.push(o);function a(o,x){o.depth=x;for(const p of o.children??[])a(p,x+1)}for(const o of i)a(o,0);return i}const be="peer.service";function je(t,n){return t.service_name===n||t.attributes?.[be]===n}function Se(t,n){return n?t.filter(r=>je(r,n)):[...t]}const Q=[],_e=()=>()=>{};function we(t){return f.useSyncExternalStore(t?t.subscribe:_e,()=>t?t.spans():Q,()=>t?t.spans():Q)}const ye="140px 1fr 160px 90px",ve="96px minmax(0, 1fr) 96px 64px";function ke(t){const n=t.attributes;if(!n)return null;const r=n["gen_ai.usage.input_tokens"]!=null?Number(n["gen_ai.usage.input_tokens"]):void 0,i=n["gen_ai.usage.output_tokens"]!=null?Number(n["gen_ai.usage.output_tokens"]):void 0;return r==null&&i==null?null:{input:r,output:i}}const Ce=({spans:t,loading:n,selectedSpanId:r,onSelectSpan:i,emptyText:a,compact:o=!1,defaultExpanded:x=!1,renderSpanMark:p,describeSpan:u})=>{const[h,d]=f.useState(new Set),m=f.useMemo(()=>({has:s=>x?!h.has(s):h.has(s)}),[h,x]),j=o?ve:ye,S=f.useMemo(()=>q(t),[t]),g=f.useMemo(()=>{const s=[];function y(b,O){const v=b.children??[];if(s.push({span:b,depth:O,hasChildren:v.length>0}),m.has(b.span_id))for(const T of v)y(T,O+1)}for(const b of S)y(b,0);return s},[S,m]),A=f.useCallback(s=>{d(y=>{const b=new Set(y);return b.has(s)?b.delete(s):b.add(s),b})},[]);return n?e.jsx(l,{display:"flex",justifyContent:"center",p:5,children:e.jsx(ie,{size:"medium"})}):t.length===0?e.jsxs(B,{children:[e.jsx(B.Visual,{children:e.jsx(se,{size:24})}),e.jsx(B.Heading,{children:"No traces found"}),e.jsx(B.Description,{children:a??"Send some telemetry data first."})]}):e.jsxs(l,{width:"100%",flex:1,minHeight:0,overflow:"auto",children:[e.jsx(l,{display:"grid",gridTemplateColumns:j,gap:2,px:3,position:"sticky",top:0,bg:"canvas.subtle",zIndex:1,borderBottom:"2px solid",borderColor:"border.default",children:["Time","Message","Scope","Duration"].map(s=>e.jsx(c,{sx:{fontWeight:"bold",fontSize:0,color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em",py:2,...s==="Duration"?{textAlign:"right"}:{}},children:s},s))}),g.map(({span:s,depth:y,hasChildren:b},O)=>{const v=r===s.span_id,T=m.has(s.span_id),C=y*(o?12:20),k=u?.(s);return e.jsxs(l,{"data-otel-span":s.span_id,"data-otel-span-name":s.span_name,onClick:()=>{b&&A(s.span_id),i?.(s)},display:"grid",gridTemplateColumns:j,gap:2,px:3,py:"5px",cursor:"pointer",bg:v?"accent.subtle":y>0?"canvas.inset":"canvas.default",borderBottom:"1px solid",borderColor:"border.muted",hover:{bg:v?"accent.subtle":"canvas.subtle"},children:[e.jsx(c,{sx:{fontSize:o?0:1,fontFamily:"mono",color:"fg.muted",whiteSpace:"nowrap",lineHeight:"22px"},children:me(s.start_time)}),e.jsxs(l,{display:"flex",alignItems:"center",gap:1,overflow:"hidden",lineHeight:"22px",pl:`${C}px`,children:[b?e.jsx(l,{flexShrink:0,color:"fg.muted",display:"flex",alignItems:"center",children:T?e.jsx(W,{size:14}):e.jsx(F,{size:14})}):y>0?e.jsx(l,{flexShrink:0,width:"14px",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.subtle",fontSize:0,children:"─"}):null,p?.(s),e.jsx(c,{sx:{fontSize:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:k?0:1,maxWidth:k?"60%":void 0},title:s.span_name,children:s.span_name}),s.in_progress&&e.jsx(D,{variant:"attention",size:"small",children:"running"}),s.status_code==="ERROR"&&e.jsx(D,{variant:"danger",size:"small",children:"ERROR"}),(()=>{const I=ke(s);return I?e.jsxs(l,{display:"inline-flex",alignItems:"center",gap:"2px",border:"1px solid",borderColor:"border.default",borderRadius:2,px:1,fontSize:"10px",fontFamily:"mono",color:"fg.muted",flexShrink:0,lineHeight:"16px",children:[I.input!=null&&e.jsxs(l,{display:"inline-flex",alignItems:"center",gap:"1px",children:[e.jsx(c,{sx:{fontSize:"9px",color:"fg.subtle"},children:"↗"}),e.jsx(c,{children:I.input})]}),I.output!=null&&e.jsxs(l,{display:"inline-flex",alignItems:"center",gap:"1px",children:[e.jsx(c,{sx:{fontSize:"9px",color:"fg.subtle"},children:"↙"}),e.jsx(c,{children:I.output})]})]}):null})(),k&&e.jsx(c,{sx:{fontSize:1,color:"fg.muted",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},title:k,"data-otel-span-description":"",children:k}),s.otel_scope_name&&!o&&e.jsx(D,{size:"small",variant:"secondary",sx:{flexShrink:0,fontSize:"10px"},children:s.otel_scope_name})]}),e.jsx(c,{sx:{fontSize:1,color:"fg.muted",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:"22px"},title:`${s.service_name} / ${s.otel_scope_name??""}`,children:s.service_name}),e.jsx(c,{sx:{fontSize:1,fontFamily:"mono",textAlign:"right",lineHeight:"22px",color:s.duration_ms!=null&&s.duration_ms>1e3?"danger.fg":"fg.default"},children:s.in_progress?"…":J(s.duration_ms)})]},`${s.trace_id}-${s.span_id}-${O}`)})]})},ze=20,Z=({span:t,depth:n,selectedSpanId:r,onSelectSpan:i,expandedIds:a,toggleExpanded:o,traceMinTime:x,traceDuration:p})=>{const u=(t.children?.length??0)>0,h=a.has(t.span_id),d=r===t.span_id,m=ge(t.service_name),j=(E(t.start_time)-x)/p*100,S=Math.max((t.duration_ms||0)/p*100,.5);return e.jsxs(e.Fragment,{children:[e.jsxs(l,{display:"flex",alignItems:"center",height:28,pl:`${n*ze}px`,pr:2,cursor:"pointer",bg:d?"accent.subtle":"canvas.default",borderBottom:"1px solid",borderColor:"border.muted",hover:{bg:d?"accent.subtle":"canvas.subtle"},onClick:()=>i?.(t),children:[e.jsx(l,{width:20,textAlign:"center",color:"fg.muted",userSelect:"none",flexShrink:0,cursor:u?"pointer":"default",onClick:g=>{g.stopPropagation(),u&&o(t.span_id)},children:u?h?e.jsx(W,{size:12}):e.jsx(F,{size:12}):e.jsx(c,{sx:{color:"fg.subtle",fontSize:0},children:"·"})}),e.jsx(l,{width:8,height:8,borderRadius:"50%",bg:m,flexShrink:0,mr:1}),e.jsx(c,{sx:{flex:"0 0 200px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:1,fontWeight:d?"bold":"normal"},title:`${t.service_name} / ${t.span_name}`,children:t.span_name}),e.jsx(l,{flex:1,position:"relative",height:12,bg:"canvas.subtle",borderRadius:1,mx:2,overflow:"hidden",children:e.jsx(l,{position:"absolute",left:`${j}%`,width:`${S}%`,height:"100%",bg:m,borderRadius:1,opacity:d?1:.7})}),e.jsx(c,{sx:{minWidth:60,textAlign:"right",fontSize:0,fontFamily:"mono",color:"fg.muted",flexShrink:0},children:J(t.duration_ms)})]}),u&&h&&t.children.map(g=>e.jsx(Z,{span:g,depth:n+1,selectedSpanId:r,onSelectSpan:i,expandedIds:a,toggleExpanded:o,traceMinTime:x,traceDuration:p},g.span_id))]})},Ie=({spans:t,selectedSpanId:n,onSelectSpan:r,defaultExpandDepth:i=2})=>{const a=f.useMemo(()=>{const d=new Set;function m(j,S){for(const g of j)S<i&&d.add(g.span_id),g.children&&m(g.children,S+1)}return m(t,0),d},[t,i]),[o,x]=f.useState(a),p=f.useCallback(d=>{x(m=>{const j=new Set(m);return j.has(d)?j.delete(d):j.add(d),j})},[]),{traceMinTime:u,traceDuration:h}=f.useMemo(()=>{let d=1/0,m=-1/0;function j(S){for(const g of S){const A=E(g.start_time),s=E(g.end_time);A<d&&(d=A),s>m&&(m=s),g.children&&j(g.children)}}return j(t),d===1/0?{traceMinTime:0,traceDuration:1}:{traceMinTime:d,traceDuration:m-d||1}},[t]);return t.length===0?e.jsx(l,{p:3,color:"fg.muted",textAlign:"center",children:e.jsx(c,{children:"No span tree to display."})}):e.jsxs(l,{width:"100%",overflow:"auto",children:[e.jsxs(l,{display:"flex",alignItems:"center",height:28,px:2,borderBottom:"2px solid",borderColor:"border.default",bg:"canvas.subtle",children:[e.jsx(l,{width:20}),e.jsx(l,{width:8,mr:1}),e.jsx(c,{sx:{flex:"0 0 200px",fontSize:0,fontWeight:"bold",color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Span"}),e.jsx(c,{sx:{flex:1,mx:2,fontSize:0,fontWeight:"bold",color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Timeline"}),e.jsx(c,{sx:{minWidth:60,textAlign:"right",fontSize:0,fontWeight:"bold",color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Duration"})]}),t.map(d=>e.jsx(Z,{span:d,depth:0,selectedSpanId:n,onSelectSpan:r,expandedIds:o,toggleExpanded:p,traceMinTime:u,traceDuration:h},d.span_id))]})},w=({label:t,value:n,mono:r=!1})=>n==null||n===""?null:e.jsxs(l,{display:"flex",py:1,borderBottom:"1px solid",borderColor:"border.muted",gap:2,children:[e.jsx(c,{sx:{width:140,minWidth:140,color:"fg.muted",fontSize:1,fontWeight:"bold"},children:t}),e.jsx(c,{sx:{fontSize:1,fontFamily:r?"mono":"normal",wordBreak:"break-all"},children:String(n)})]}),Y=({title:t,data:n,defaultOpen:r=!1})=>{const[i,a]=f.useState(r);return!n||Object.keys(n).length===0?null:e.jsxs(l,{mt:3,children:[e.jsxs(l,{display:"flex",alignItems:"center",gap:1,cursor:"pointer",py:1,userSelect:"none",onClick:()=>a(!i),children:[i?e.jsx(W,{size:16}):e.jsx(F,{size:16}),e.jsx(c,{sx:{fontSize:1,fontWeight:"bold"},children:t}),e.jsx(V,{children:Object.keys(n).length})]}),i&&e.jsx(l,{bg:"canvas.subtle",borderRadius:2,border:"1px solid",borderColor:"border.default",p:2,mt:1,overflowX:"auto",children:Object.entries(n).map(([o,x])=>e.jsx(L,{attrKey:o,value:x,depth:0},o))})]})};function Te(t){if(typeof t!="string")return t;const n=t.trim();if(!/^[[{]/.test(n))return t;try{const r=JSON.parse(n);return typeof r=="object"&&r!==null?r:t}catch{return t}}const L=({attrKey:t,value:n,depth:r})=>{const i=f.useMemo(()=>Te(n),[n]),[a,o]=f.useState(r<1),x=typeof i=="object"&&i!==null&&!Array.isArray(i),p=Array.isArray(i),u=x||p;return e.jsxs(l,{borderBottom:r===0?"1px solid":"none",borderColor:"border.muted",pb:r===0?1:0,mb:r===0?1:0,children:[e.jsxs(l,{display:"flex",gap:2,py:1,pl:r*16+"px",alignItems:"flex-start",children:[u?e.jsx(l,{cursor:"pointer",color:"fg.muted",userSelect:"none",width:16,flexShrink:0,onClick:()=>o(!a),children:a?e.jsx(W,{size:12}):e.jsx(F,{size:12})}):e.jsx(l,{width:16,flexShrink:0}),e.jsx(c,{sx:{color:"accent.fg",fontSize:1,fontFamily:"mono",minWidth:180,wordBreak:"break-all",flexShrink:0},children:t}),!u&&e.jsx(c,{sx:{fontSize:1,fontFamily:"mono",whiteSpace:"pre-wrap",wordBreak:"break-word",color:typeof i=="string"?"accent.emphasis":"attention.fg"},children:typeof i=="string"?i:JSON.stringify(i)}),u&&!a&&e.jsx(c,{sx:{fontSize:0,color:"fg.muted",fontFamily:"mono"},children:p?`[${i.length} items]`:`{${Object.keys(i).length} keys}`})]}),u&&a&&e.jsx(l,{children:p?i.map((h,d)=>e.jsx(L,{attrKey:`[${d}]`,value:h,depth:r+1},d)):Object.entries(i).map(([h,d])=>e.jsx(L,{attrKey:h,value:d,depth:r+1},h))})]})},Ae=({span:t,traceSpans:n,onClose:r})=>{const[i,a]=f.useState("details");if(!t)return e.jsx(l,{p:5,color:"fg.muted",textAlign:"center",children:e.jsx(c,{children:"Select a span to view details."})});const o={},x={};if(t.attributes)for(const[u,h]of Object.entries(t.attributes))u.startsWith("gen_ai.")||u.startsWith("model_request")?o[u]=h:x[u]=h;const p=n&&n.length>0?q(n):void 0;return e.jsxs(l,{height:"100%",overflow:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.default",display:"flex",flexDirection:"column",children:[e.jsxs(l,{px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",display:"flex",justifyContent:"space-between",alignItems:"center",bg:"canvas.subtle",flexShrink:0,children:[e.jsx(c,{sx:{fontSize:2,fontWeight:"bold"},children:t.span_name}),r&&e.jsx(oe,{icon:le,"aria-label":"Close detail panel",variant:"invisible",size:"small",onClick:r})]}),e.jsxs($,{"aria-label":"Span detail tabs",children:[e.jsx($.Item,{"aria-current":i==="details"?"page":void 0,onClick:()=>a("details"),children:"Details"}),p&&e.jsx($.Item,{"aria-current":i==="tree"?"page":void 0,onClick:()=>a("tree"),children:"Trace Tree"}),e.jsx($.Item,{"aria-current":i==="raw"?"page":void 0,onClick:()=>a("raw"),children:"Raw Data"})]}),e.jsxs(l,{flex:1,overflow:"auto",children:[i==="details"&&e.jsxs(l,{p:3,children:[e.jsx(w,{label:"span_name",value:t.span_name}),e.jsx(w,{label:"service_name",value:t.service_name}),e.jsx(w,{label:"otel_scope_name",value:t.otel_scope_name}),e.jsx(w,{label:"kind",value:t.kind}),e.jsx(w,{label:"trace_id",value:t.trace_id,mono:!0}),e.jsx(w,{label:"span_id",value:t.span_id,mono:!0}),e.jsx(w,{label:"parent_span_id",value:t.parent_span_id,mono:!0}),e.jsx(w,{label:"duration",value:J(t.duration_ms)}),e.jsx(w,{label:"start_time",value:t.start_time,mono:!0}),e.jsx(w,{label:"end_time",value:t.end_time,mono:!0}),e.jsx(w,{label:"status_code",value:t.status_code}),e.jsx(w,{label:"status_message",value:t.status_message}),e.jsx(Y,{title:"Arguments",data:o,defaultOpen:Object.keys(o).length>0}),e.jsx(Y,{title:"Attributes",data:x}),t.events&&t.events.length>0&&e.jsxs(l,{mt:3,children:[e.jsxs(l,{display:"flex",alignItems:"center",gap:1,children:[e.jsx(c,{sx:{fontWeight:"bold",fontSize:1},children:"Events"}),e.jsx(V,{children:t.events.length})]}),t.events.map((u,h)=>e.jsxs(l,{bg:"canvas.subtle",borderRadius:2,border:"1px solid",borderColor:"border.default",p:2,mt:2,children:[e.jsxs(l,{display:"flex",gap:2,children:[e.jsx(D,{children:u.name}),e.jsx(c,{sx:{fontSize:0,color:"fg.muted",fontFamily:"mono"},children:u.timestamp})]}),u.attributes&&Object.keys(u.attributes).length>0&&e.jsx(l,{mt:1,children:Object.entries(u.attributes).map(([d,m])=>e.jsx(L,{attrKey:d,value:m,depth:0},d))})]},h))]}),t.links&&t.links.length>0&&e.jsxs(l,{mt:3,children:[e.jsxs(l,{display:"flex",alignItems:"center",gap:1,children:[e.jsx(c,{sx:{fontWeight:"bold",fontSize:1},children:"Links"}),e.jsx(V,{children:t.links.length})]}),t.links.map((u,h)=>e.jsxs(c,{sx:{display:"block",fontSize:1,fontFamily:"mono",py:1,borderBottom:"1px solid",borderColor:"border.muted"},children:["trace: ",u.trace_id," → span: ",u.span_id]},h))]})]}),i==="tree"&&p&&e.jsx(Ie,{spans:p,selectedSpanId:t.span_id,defaultExpandDepth:4}),i==="raw"&&e.jsx(l,{as:"pre",p:3,fontSize:0,fontFamily:"mono",whiteSpace:"pre-wrap",wordBreak:"break-word",m:0,bg:"canvas.subtle",children:JSON.stringify(t,null,2)})]})]})},Oe=[{label:"Service",value:t=>t.service_name},{label:"Kind",value:t=>t.kind}];function Ne(t,n,r){return t.filter(i=>n.every((a,o)=>{const x=r[o];if(!x?.size)return!0;const p=a.value(i);return p!==void 0&&x.has(p)}))}function Re(t,n){const r=new Set(t);return r.has(n)?r.delete(n):r.add(n),r}function Ee({facet:t,options:n,selected:r,onChange:i}){const a=t.name??(o=>o);return e.jsxs(H,{children:[e.jsxs(H.Button,{size:"small","data-otel-facet":t.label.toLowerCase(),children:[t.label,r.size?` · ${r.size}`:""]}),e.jsx(H.Overlay,{width:"auto",children:e.jsxs(M,{selectionVariant:"multiple","aria-label":t.label,children:[e.jsx(M.Item,{selected:!r.size,onSelect:()=>i(new Set),children:"All"}),e.jsx(M.Divider,{}),n.map(o=>e.jsx(M.Item,{selected:r.has(o),onSelect:()=>i(Re(r,o)),children:a(o)},o))]})})]})}function Me(t,n){const r=new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.href=i,a.download=`${t}.json`,a.click(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}const Be=({tracer:t,spans:n,service:r,facets:i=Oe,compact:a=!1,maxHeight:o=420,detailPlacement:x="below",emptyText:p="Nothing recorded yet.",exportName:u="otel-spans",label:h="Spans",renderSpanMark:d,describeSpan:m})=>{const j=we(n?null:t),S=n??j,[g,A]=f.useState(0),[s,y]=f.useState(null),[b,O]=f.useState(()=>i.map(()=>new Set)),[v,T]=f.useState(null),C=f.useMemo(()=>{const _=Se(S,r);return g?_.filter(z=>E(z.start_time)>=g):_},[S,r,g]),k=s??C,I=s?C.length-s.length:0,ee=f.useMemo(()=>i.map(_=>[...new Set(C.map(z=>_.value(z)).filter(z=>z!==void 0))].sort()),[i,C]),N=f.useMemo(()=>Ne(k,i,b),[k,i,b]),R=f.useMemo(()=>v?S.find(_=>_.span_id===v)??null:null,[S,v]),te=f.useMemo(()=>R?S.filter(_=>_.trace_id===R.trace_id):[],[S,R]),P=x==="side"&&!a;return e.jsxs(l,{"data-otel-live-spans":"",border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.default",color:"fg.default",minWidth:0,children:[e.jsxs(l,{role:"toolbar","aria-label":h,display:"flex",flexWrap:"wrap",gap:2,alignItems:"center",p:2,borderBottom:"1px solid",borderColor:"border.default",children:[i.map((_,z)=>e.jsx(Ee,{facet:_,options:ee[z]??[],selected:b[z]??new Set,onChange:ne=>O(re=>i.map((Le,G)=>G===z?ne:re[G]??new Set))},_.label)),e.jsx(l,{flex:1}),e.jsxs(c,{sx:{fontSize:0,color:"fg.muted"},"data-otel-span-count":"",children:[N.length===k.length?`${N.length} ${N.length===1?"span":"spans"}`:`${N.length} of ${k.length}`,I>0?` · ${I} new`:""]}),e.jsx(U,{size:"small",leadingVisual:s?ae:de,"aria-pressed":s!==null,onClick:()=>y(s?null:C),"data-otel-pause":"",children:s?"Resume":"Pause"}),e.jsx(U,{size:"small",leadingVisual:ce,onClick:()=>{y(null),T(null),t&&!n&&!r?t.clear():A(Date.now())},"data-otel-clear":"",children:"Clear"}),e.jsx(U,{size:"small",leadingVisual:ue,disabled:!C.length,onClick:()=>Me(u,{exportedAt:new Date().toISOString(),spans:[...C]}),"data-otel-export":"",children:"Export"})]}),e.jsxs(l,{display:P?"grid":"block",gridTemplateColumns:P?"minmax(0, 3fr) minmax(0, 2fr)":void 0,children:[e.jsx(l,{maxHeight:o,overflowY:"auto",minWidth:0,children:e.jsx(Ce,{spans:N,selectedSpanId:v,onSelectSpan:_=>T(_.span_id),emptyText:p,compact:a,defaultExpanded:!0,renderSpanMark:d,describeSpan:m})}),R&&e.jsx(l,{"data-otel-live-detail":"",maxHeight:o,overflowY:"auto",minWidth:0,borderTop:P?"none":"1px solid",borderColor:"border.default",children:e.jsx(Ae,{span:R,traceSpans:te,onClose:()=>T(null)})})]})]})},$e=[{label:"Source",value:fe,name:t=>xe[t]??t},{label:"Operation",value:t=>{const n=t.attributes??{},r=n[K.operation]??n["rpc.method"];return r===void 0?void 0:String(r)}},{label:"Agent",value:t=>t.service_name}];function De(t){const n=t.attributes?.[K.markIcon],r=t.attributes?.[K.markEmoji];return n||r?e.jsx(he,{icon:typeof n=="string"?n:void 0,emoji:typeof r=="string"?r:void 0,size:14}):null}function Pe({tracer:t,spans:n,agent:r,maxHeight:i=420,compact:a=!1,emptyText:o="Nothing recorded yet.",exportName:x="agent-inspector"}){return e.jsx("div",{"data-agent-inspector":r??"",children:e.jsx(Be,{tracer:t,spans:n,service:r,facets:$e,compact:a,maxHeight:i,detailPlacement:"side",emptyText:o,exportName:x,label:r?`${r}'s Agent Inspector`:"Agent Inspector",renderSpanMark:De,describeSpan:pe})})}export{$e as AGENT_INSPECTOR_FACETS,Pe as AgentInspector,Pe as default};
|
package/dist-embed/chunks/{AgentInspectorDialog-fT96Pb4Z.js → AgentInspectorDialog-DcLrhdWo.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as e,D as n,r as t,T as i,_ as c}from"../datalayer-app-main.js";const g=t.lazy(()=>c(()=>import("./AgentInspector-
|
|
1
|
+
import{j as e,D as n,r as t,T as i,_ as c}from"../datalayer-app-main.js";const g=t.lazy(()=>c(()=>import("./AgentInspector-B1wLMu4Z.js"),[],import.meta.url));function d({tracer:r,title:a="Agent Inspector",agent:o,onClose:s}){return e.jsx(n,{title:a,onClose:s,width:"xlarge",height:"large","data-agent-inspector-dialog":"",children:e.jsx(t.Suspense,{fallback:e.jsx(i,{sx:{color:"fg.muted"},children:"Loading the Agent Inspector…"}),children:e.jsx(g,{tracer:r,agent:o,maxHeight:"calc(80vh - 140px)",emptyText:"Nothing recorded yet: what the agent does shows here as it does it."})})})}export{d as AgentInspectorDialog,d as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v as $,bl as g,cD as q,cE as y,j as D,bn as V}from"../datalayer-app-main.js";var k={Avatar:"prc-Avatar-Avatar-ZRS-m"};const w=20,T=$.forwardRef(function(A,u){const s=g.c(29);let o,l,a,i,v,d,f;s[0]!==A?({alt:v,size:d,square:f,sx:i,className:o,style:a,...l}=A,s[0]=A,s[1]=o,s[2]=l,s[3]=a,s[4]=i,s[5]=v,s[6]=d,s[7]=f):(o=s[1],l=s[2],a=s[3],i=s[4],v=s[5],d=s[6],f=s[7]);const m=v===void 0?"":v,t=d===void 0?w:d,b=f===void 0?!1:f;let p;s[8]!==t?(p=q(t),s[8]=t,s[9]=p):p=s[9];const r=p;let e;if(s[10]!==r||s[11]!==t){if(e={},r)for(const[h,j]of Object.entries(t))e[`--avatarSize-${h}`]=`${j}px`;else e["--avatarSize-regular"]=`${t}px`;s[10]=r,s[11]=t,s[12]=e}else e=s[12];let c;s[13]!==o?(c=y(o,k.Avatar),s[13]=o,s[14]=c):c=s[14];const R=r?"":void 0,z=b?"":void 0,E=r?void 0:t,S=r?void 0:t;let n;s[15]!==e||s[16]!==a?(n=a?{...e,...a}:e,s[15]=e,s[16]=a,s[17]=n):n=s[17];let x;return s[18]!==m||s[19]!==u||s[20]!==l||s[21]!==i||s[22]!==n||s[23]!==c||s[24]!==R||s[25]!==z||s[26]!==E||s[27]!==S?(x=D.jsx(V,{as:"img","data-component":"Avatar",className:c,ref:u,alt:m,"data-responsive":R,"data-square":z,width:E,height:S,style:n,sx:i,...l}),s[18]=m,s[19]=u,s[20]=l,s[21]=i,s[22]=n,s[23]=c,s[24]=R,s[25]=z,s[26]=E,s[27]=S,s[28]=x):x=s[28],x});export{T as A,w as D};
|
package/dist-embed/chunks/{CellSidebarExtension-B-vao30u.js → CellSidebarExtension-BWsHtuqs.js}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as _,v as qe,j as u,j9 as jt,I as U,eK as Ge,cE as pe,be as ge,c as J,ff as Pt,f9 as Ue,fq as Tt,ja as Dt,jb as At,jc as Je,jd as Ye,cj as W,je as It,jf as Nt,jg as Lt,bC as Te,jh as ct,ji as ht,jj as Rt,jk as fe,az as Ot,by as ut,jl as ft,jm as Ft,jn as Xe,F as A,jo as Ze,jp as me,jq as Bt,jr as Wt,js as Vt,ao as _e,jt as Ie,ju as Qe,cA as ke,cz as ee,b9 as $t,em as Gt,cg as z,jv as Ht,aa as mt,ag as zt,co as Kt,ai as Z,cW as qt,dm as Ut,i1 as Fe,h$ as pt,jw as xe,jx as de,jy as Jt,ar as Yt,aj as Xt,jz as Zt,ak as Qt,jA as gt,hK as H,jB as en,jC as R,jD as tn,df as nn,jE as _t,jF as sn,e7 as on,e8 as rn,ee as ce,e9 as Ne,ea as an,jG as ln,jH as dn,jI as cn,eH as ne,B as ue,a9 as hn,d3 as un,dY as et,_ as fn,ab as mn,jJ as pn,jK as gn,jL as _n,jM as vn,e0 as tt,e1 as he,e2 as yn,e3 as Cn,e4 as bn,ct as wn,l as kn,jN as xn,jO as vt,fR as Mn,jP as ae,bd as T,C as le,cL as nt,bp as yt,dx as Sn,cP as En,bm as Me,i as jn,P as Pn,as as Tn,aC as Dn}from"../datalayer-app-main.js";import{c as An,N as Be}from"./NotebookSkeleton-D9WNoiWD.js";import{a as In,W as st}from"./renderer-jz0zn1Az.js";import{C as Se,S as Ee}from"./SquareIcon-e3ygcjpv.js";function Nn(...r){return _.useCallback(e=>{for(const t of r)typeof t=="function"?t(e):t&&(t.current=e)},r)}var Q={Banner:"prc-Banner-Banner-IR8eJ",BannerContainer:"prc-Banner-BannerContainer-lbx3d",BannerContent:"prc-Banner-BannerContent-zTITK",BannerActions:"prc-Banner-BannerActions-XCfHL",BannerTitle:"prc-Banner-BannerTitle-TcuJl",BannerIcon:"prc-Banner-BannerIcon-WuOyf",BannerDismiss:"prc-Banner-BannerDismiss-uBZVm",BannerActionsContainer:"prc-Banner-BannerActionsContainer-ukGMH"};const Ln={critical:u.jsx(Dt,{}),info:u.jsx(Ue,{}),success:u.jsx(Tt,{}),upsell:u.jsx(Ue,{}),warning:u.jsx(Pt,{})},Rn={critical:"Critical",info:"Information",success:"Success",upsell:"Recommendation",warning:"Warning"},On=qe.forwardRef(function({"aria-label":e,children:t,className:n,description:s,hideTitle:o,icon:i,onDismiss:a,primaryAction:l,secondaryAction:d,title:c,variant:h="info",...f},m){const C=!!a,x=l||d,I=qe.useRef(null),L=Nn(m,I),g=h==="info"||h==="upsell";return u.jsxs("section",{...f,"aria-label":e??Rn[h],className:pe(n,Q.Banner),"data-dismissible":a?"":void 0,"data-title-hidden":o?"":void 0,"data-variant":h,tabIndex:-1,ref:L,children:[u.jsx("div",{className:Q.BannerIcon,children:i&&g?i:Ln[h]}),u.jsxs("div",{className:Q.BannerContainer,children:[u.jsxs("div",{className:Q.BannerContent,children:[c?o?u.jsx(jt,{children:u.jsx(We,{children:c})}):u.jsx(We,{children:c}):null,s?u.jsx(Ct,{children:s}):null,t]}),x?u.jsx(Fn,{primaryAction:l,secondaryAction:d}):null]}),C?u.jsx(U,{"aria-label":"Dismiss banner",onClick:a,className:Q.BannerDismiss,icon:Ge,variant:"invisible"}):null]})});function We(r){const e=ge.c(12);let t,n,s,o;e[0]!==r?({as:o,className:n,children:t,...s}=r,e[0]=r,e[1]=t,e[2]=n,e[3]=s,e[4]=o):(t=e[1],n=e[2],s=e[3],o=e[4]);const i=o===void 0?"h2":o;let a;e[5]!==n?(a=pe(n,Q.BannerTitle),e[5]=n,e[6]=a):a=e[6];let l;return e[7]!==i||e[8]!==t||e[9]!==s||e[10]!==a?(l=u.jsx(i,{...s,className:a,"data-banner-title":"",children:t}),e[7]=i,e[8]=t,e[9]=s,e[10]=a,e[11]=l):l=e[11],l}function Ct(r){const e=ge.c(10);let t,n,s;e[0]!==r?({children:t,className:n,...s}=r,e[0]=r,e[1]=t,e[2]=n,e[3]=s):(t=e[1],n=e[2],s=e[3]);let o;e[4]!==n?(o=pe("BannerDescription",n),e[4]=n,e[5]=o):o=e[5];let i;return e[6]!==t||e[7]!==s||e[8]!==o?(i=u.jsx("div",{...s,className:o,children:t}),e[6]=t,e[7]=s,e[8]=o,e[9]=i):i=e[9],i}function Fn(r){const e=ge.c(9),{primaryAction:t,secondaryAction:n}=r,s=n??null,o=t??null;let i;e[0]!==s||e[1]!==o?(i=u.jsxs("div",{className:Q.BannerActionsContainer,"data-primary-action":"trailing",children:[s,o]}),e[0]=s,e[1]=o,e[2]=i):i=e[2];const a=t??null,l=n??null;let d;e[3]!==a||e[4]!==l?(d=u.jsxs("div",{className:Q.BannerActionsContainer,"data-primary-action":"leading",children:[a,l]}),e[3]=a,e[4]=l,e[5]=d):d=e[5];let c;return e[6]!==i||e[7]!==d?(c=u.jsxs("div",{className:Q.BannerActions,children:[i,d]}),e[6]=i,e[7]=d,e[8]=c):c=e[8],c}const bt=_.forwardRef((r,e)=>{const t=ge.c(11);let n,s,o;t[0]!==r?({children:n,className:s,...o}=r,t[0]=r,t[1]=n,t[2]=s,t[3]=o):(n=t[1],s=t[2],o=t[3]);let i;t[4]!==s?(i=pe("BannerPrimaryAction",s),t[4]=s,t[5]=i):i=t[5];let a;return t[6]!==n||t[7]!==e||t[8]!==o||t[9]!==i?(a=u.jsx(J,{ref:e,className:i,variant:"default",...o,children:n}),t[6]=n,t[7]=e,t[8]=o,t[9]=i,t[10]=a):a=t[10],a});bt.displayName="BannerPrimaryAction";const wt=_.forwardRef((r,e)=>{const t=ge.c(11);let n,s,o;t[0]!==r?({children:n,className:s,...o}=r,t[0]=r,t[1]=n,t[2]=s,t[3]=o):(n=t[1],s=t[2],o=t[3]);let i;t[4]!==s?(i=pe("BannerPrimaryAction",s),t[4]=s,t[5]=i):i=t[5];let a;return t[6]!==n||t[7]!==e||t[8]!==o||t[9]!==i?(a=u.jsx(J,{ref:e,className:i,variant:"link",...o,children:n}),t[6]=n,t[7]=e,t[8]=o,t[9]=i,t[10]=a):a=t[10],a});wt.displayName="BannerSecondaryAction";const Bn=Object.assign(On,{Title:We,Description:Ct,PrimaryAction:bt,SecondaryAction:wt}),ve=Nt.define({combine(r){return r[r.length-1]}}),Wn=Te.baseTheme({".jp-remote-cursor":{borderLeft:"1px solid black",marginLeft:"-1px"},".jp-remote-cursor.jp-mod-primary":{borderLeftWidth:"2px"},".jp-remote-selection":{opacity:.5},".cm-tooltip":{border:"none"},".cm-tooltip.jp-remote-userInfo":{color:"var(--fgColor-onEmphasis, #ffffff)",padding:"0px 2px"}});function He(r,e){const t=r?.username||r?.display_name||r?.name||String(e),{theme:n,colorMode:s}=Ot.getState(),o=s==="auto"?typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":s;return An(t,n,o)}const De=Lt.define();class kt{style;marker;constructor(e,t){this.style=e,this.marker=t}draw(){const e=this.marker.draw();for(const[t,n]of Object.entries(this.style))e.style[t]=n;return e}eq(e){return this.marker.eq(e.marker)&&W.deepEqual(this.style,e.style)}update(e,t){for(const[n,s]of Object.entries(this.style))e.style[n]=s;return this.marker.update(e,t.marker)}}const Vn=ct({above:!0,markers(r){const{awareness:e,ytext:t}=r.state.facet(ve),n=t.doc,s=[];return e.getStates().forEach((o,i)=>{if(i===e.doc.clientID)return;const a=o.cursors;for(const l of a??[]){if(!l?.anchor||!l?.head)return;const d=fe(l.anchor,n),c=fe(l.head,n);if(d?.type!==t||c?.type!==t)return;const h=l.primary??!0?"jp-remote-cursor jp-mod-primary":"jp-remote-cursor",f=ut.cursor(c.index,c.index>d.index?-1:1);for(const m of ft.forRange(r,h,f))s.push(new kt({borderLeftColor:He(o.user,i)},m))}}),s},update(r,e){return!!r.transactions.find(t=>t.annotation(De))},class:"jp-remote-cursors"});function ot(r){const e=new Array,{awareness:t,ytext:n}=r.facet(ve),s=n.doc;for(const[o,i]of t.getStates())if(o!==t.doc.clientID)for(const a of i.cursors??[]){if(!a?.head)continue;const l=fe(a.head,s);l?.type===n&&e.push({pos:l.index,above:!0,create:()=>{const d=document.createElement("div");return d.classList.add("jp-remote-userInfo"),d.style.backgroundColor=He(i.user,o),d.textContent=i.user?.display_name??"Anonymous",{dom:d}}})}return e}const $n=ht.define({create:ot,update(r,e){return e.annotation(De)?ot(e.state):r},provide(r){return Rt.computeN([r],e=>e.field(r))}}),Gn=ct({above:!1,markers(r){const{awareness:e,ytext:t}=r.state.facet(ve),n=t.doc,s=[];return e.getStates().forEach((o,i)=>{if(i===e.doc.clientID)return;const a=o.cursors;for(const l of a??[]){if((l.empty??!0)||!l?.anchor||!l?.head)return;const d=fe(l.anchor,n),c=fe(l.head,n);if(d?.type!==t||c?.type!==t)return;const h="jp-remote-selection";for(const f of ft.forRange(r,h,ut.range(d.index,c.index)))s.push(new kt({backgroundColor:He(o.user,i)},f))}}),s},update(r,e){return!!r.transactions.find(t=>t.annotation(De))},class:"jp-remote-selections"}),Hn=At.fromClass(class{editorAwareness;_listener;constructor(r){this.editorAwareness=r.state.facet(ve),this._listener=({added:e,updated:t,removed:n})=>{e.concat(t).concat(n).findIndex(o=>o!==this.editorAwareness.awareness.doc.clientID)>=0&&r.dispatch({annotations:[De.of([])]})},this.editorAwareness.awareness.on("change",this._listener)}destroy(){this.editorAwareness.awareness.off("change",this._listener)}update(r){if(!r.docChanged&&!r.selectionSet)return;const{awareness:e,ytext:t}=this.editorAwareness,n=e.getLocalState();if(n){const s=r.view.hasFocus&&r.view.dom.ownerDocument.hasFocus(),o=r.state.selection,i=new Array;if(s&&o){for(const a of o.ranges){const l=a===o.main,d=Je(t,a.anchor),c=Je(t,a.head);i.push({anchor:d,head:c,primary:l,empty:a.empty})}if(!n.cursors||i.length>0){const a=n.cursors?.map(l=>({...l,anchor:l?.anchor?Ye(l.anchor):null,head:l?.head?Ye(l.head):null}));W.deepEqual(i,a)||e.setLocalStateField("cursors",i)}}}}},{provide:()=>[Wn,Vn,Gn,$n,It({position:"absolute",parent:document.body})]});function zn(r){return[ve.of(r),Hn]}class Ae extends Ft{constructor(e={}){var t;super(),this.version="2.0.0",this.ymeta=this.ydoc.getMap("meta"),this._onMetaChanged=n=>{const s=n.find(i=>i.target===this.ymeta.get("metadata"));if(s){const i=s.changes.keys,a=this.ymeta.get("metadata");s.changes.keys.forEach((l,d)=>{switch(l.action){case"add":this._metadataChanged.emit({key:d,type:"add",newValue:a.get(d)});break;case"delete":this._metadataChanged.emit({key:d,type:"remove",oldValue:l.oldValue});break;case"update":{const c=a.get(d),h=l.oldValue;let f=!0;typeof h=="object"&&typeof c=="object"?f=W.deepEqual(h,c):f=h===c,f||this._metadataChanged.emit({key:d,type:"change",oldValue:h,newValue:c})}break}}),this._changed.emit({metadataChange:i})}const o=n.find(i=>i.target===this.ymeta);if(o){if(o.keysChanged.has("metadata")){const i=o.changes.keys.get("metadata");if(i?.action==="add"&&!i.oldValue){const a=new Map;for(const l of Object.keys(this.metadata))a.set(l,{action:"add",oldValue:void 0}),this._metadataChanged.emit({key:l,type:"add",newValue:this.getMetadata(l)});this._changed.emit({metadataChange:a})}}if(o.keysChanged.has("nbformat")){const i=o.changes.keys.get("nbformat"),a={key:"nbformat",oldValue:i?.oldValue?i.oldValue:void 0,newValue:this.nbformat};this._changed.emit({nbformatChanged:a})}if(o.keysChanged.has("nbformat_minor")){const i=o.changes.keys.get("nbformat_minor"),a={key:"nbformat_minor",oldValue:i?.oldValue?i.oldValue:void 0,newValue:this.nbformat_minor};this._changed.emit({nbformatChanged:a})}}},this._onYCellsChanged=n=>{n.changes.added.forEach(i=>{const a=i.content.type;if(!this._ycellMapping.has(a)){const l=Xe(a,{notebook:this});this._ycellMapping.set(a,l)}}),n.changes.deleted.forEach(i=>{const a=i.content.type,l=this._ycellMapping.get(a);l&&(l.dispose(),this._ycellMapping.delete(a))});let s=0;const o=[];n.changes.delta.forEach(i=>{if(i.insert!=null){const a=i.insert.map(l=>this._ycellMapping.get(l));o.push({insert:a}),this.cells.splice(s,0,...a),s+=i.insert.length}else i.delete!=null?(o.push(i),this.cells.splice(s,i.delete)):i.retain!=null&&(o.push(i),s+=i.retain)}),this._changed.emit({cellsChange:o})},this._metadataChanged=new A(this),this._ycells=this.ydoc.getArray("cells"),this._ycellMapping=new WeakMap,this._disableDocumentWideUndoRedo=(t=e.disableDocumentWideUndoRedo)!==null&&t!==void 0?t:!1,this.cells=this._ycells.toArray().map(n=>(this._ycellMapping.has(n)||this._ycellMapping.set(n,Xe(n,{notebook:this})),this._ycellMapping.get(n))),this.undoManager.addToScope(this._ycells),this._ycells.observe(this._onYCellsChanged),this.ymeta.observeDeep(this._onMetaChanged)}static create(e={}){var t,n,s,o,i,a,l,d,c;const h=new Ae({disableDocumentWideUndoRedo:(t=e.disableDocumentWideUndoRedo)!==null&&t!==void 0?t:!1}),f={cells:(s=(n=e.data)===null||n===void 0?void 0:n.cells)!==null&&s!==void 0?s:[],nbformat:(i=(o=e.data)===null||o===void 0?void 0:o.nbformat)!==null&&i!==void 0?i:4,nbformat_minor:(l=(a=e.data)===null||a===void 0?void 0:a.nbformat_minor)!==null&&l!==void 0?l:5,metadata:(c=(d=e.data)===null||d===void 0?void 0:d.metadata)!==null&&c!==void 0?c:{}};return h.setSource(f),h}get disableDocumentWideUndoRedo(){return this._disableDocumentWideUndoRedo}get metadata(){return this.getMetadata()}set metadata(e){this.setMetadata(e)}get metadataChanged(){return this._metadataChanged}get nbformat(){return this.ymeta.get("nbformat")}set nbformat(e){this.transact(()=>{this.ymeta.set("nbformat",e)},!1)}get nbformat_minor(){return this.ymeta.get("nbformat_minor")}set nbformat_minor(e){this.transact(()=>{this.ymeta.set("nbformat_minor",e)},!1)}dispose(){this.isDisposed||(this._ycells.unobserve(this._onYCellsChanged),this.ymeta.unobserveDeep(this._onMetaChanged),super.dispose())}getCell(e){return this.cells[e]}addCell(e){return this.insertCell(this._ycells.length,e)}insertCell(e,t){return this.insertCells(e,[t])[0]}insertCells(e,t){const n=t.map(s=>{const o=Ze(s,this);return this._ycellMapping.set(o.ymodel,o),o});return this.transact(()=>{this._ycells.insert(e,n.map(s=>s.ymodel))}),this.dirty=!0,n}moveCell(e,t){this.moveCells(e,t)}moveCells(e,t,n=1){const s=new Array(n).fill(!0).map((o,i)=>this.getCell(e+i).toJSON());this.transact(()=>{this._ycells.delete(e,n),this._ycells.insert(e>t?t:t-n+1,s.map(o=>Ze(o,this).ymodel))}),this.dirty=!0}deleteCell(e){this.deleteCellRange(e,e+1)}deleteCellRange(e,t){this.transact(()=>{this._ycells.delete(e,t-e)}),this.dirty=!0}deleteMetadata(e){if(typeof this.getMetadata(e)>"u")return;const t=this.metadata;delete t[e],this.setMetadata(t)}getMetadata(e){const t=this.ymeta.get("metadata");if(t!==void 0)if(typeof e=="string"){const n=t.get(e);return typeof n>"u"?void 0:W.deepCopy(n)}else return W.deepCopy(t.toJSON())}setMetadata(e,t){var n;if(typeof e=="string"){if(typeof t>"u")throw new TypeError(`Metadata value for ${e} cannot be 'undefined'; use deleteMetadata.`);if(W.deepEqual((n=this.getMetadata(e))!==null&&n!==void 0?n:null,t))return;const s={};s[e]=t,this.updateMetadata(s)}else if(!this.metadata||!W.deepEqual(this.metadata,e)){const s=W.deepCopy(e),o=this.ymeta.get("metadata");if(o===void 0)return;this.transact(()=>{o.clear();for(const[i,a]of Object.entries(s))o.set(i,a)}),this.dirty=!0}}updateMetadata(e){const t=W.deepCopy(e),n=this.ymeta.get("metadata");n!==void 0&&(this.transact(()=>{for(const[s,o]of Object.entries(t))n.set(s,o)}),this.dirty=!0)}getSource(){return this.toJSON()}setSource(e){this.fromJSON(e),this.dirty=!1}fromJSON(e){this.transact(()=>{this.nbformat=e.nbformat,this.nbformat_minor=e.nbformat_minor;const t=e.metadata;if(t.orig_nbformat!==void 0&&delete t.orig_nbformat,this.metadata)this.metadata=t;else{const o=new me;for(const[i,a]of Object.entries(t))o.set(i,a);this.ymeta.set("metadata",o)}const n=e.nbformat===4&&e.nbformat_minor>=5,s=e.cells.map(o=>(n||delete o.id,o));this.insertCells(this.cells.length,s),this.deleteCellRange(0,this.cells.length)})}toJSON(){const e=this.nbformat===4&&this.nbformat_minor<=4;return{metadata:this.metadata,nbformat_minor:this.nbformat_minor,nbformat:this.nbformat,cells:this.cells.map(t=>{const n=t.toJSON();return e&&delete n.id,n})}}}class Kn{constructor(e){this.model=e,this._cellMap=new WeakMap,this._changed=new A(this),this._isDisposed=!1,this._insertCells(0,this.model.cells),this.model.changed.connect(this._onSharedModelChanged,this)}get changed(){return this._changed}get isDisposed(){return this._isDisposed}get length(){return this.model.cells.length}*[Symbol.iterator](){for(const e of this.model.cells)yield this._cellMap.get(e)}dispose(){var e;if(!this._isDisposed){this._isDisposed=!0;for(const t of this.model.cells)(e=this._cellMap.get(t))===null||e===void 0||e.dispose();A.clearData(this)}}get(e){return this._cellMap.get(this.model.cells[e])}_insertCells(e,t){return t.forEach(n=>{let s;switch(n.cell_type){case"code":{s=new Vt({sharedModel:n});break}case"markdown":{s=new Wt({sharedModel:n});break}default:s=new Bt({sharedModel:n})}this._cellMap.set(n,s),n.disposed.connect(()=>{s.dispose(),this._cellMap.delete(n)})}),this.length}_onSharedModelChanged(e,t){var n;let s=0;const o=new Array;(n=t.cellsChange)===null||n===void 0||n.forEach(i=>{i.insert!=null?(this._insertCells(s,i.insert),o.push({type:"add",newIndex:s,newValues:i.insert.map(a=>this._cellMap.get(a)),oldIndex:-2,oldValues:[]}),s+=i.insert.length):i.delete!=null?o.push({type:"remove",newIndex:-1,newValues:[],oldIndex:s,oldValues:new Array(i.delete).fill(void 0)}):i.retain!=null&&(s+=i.retain)}),o.forEach(i=>this._changed.emit(i))}}class qn{constructor(e){this._requestBatchSize=10,this._cursor=0,this._hasSession=!1,this._history=[],this._placeholder="",this._kernelSession="",this._setByHistory=!1,this._isDisposed=!1,this._editor=null,this._filtered=[],this._kernel=null,this._sessionContext=e.sessionContext,this._trans=(e.translator||_e).load("jupyterlab"),this._handleKernel().then(()=>{this._sessionContext.kernelChanged.connect(this._handleKernel,this)}),this._toRequest=this._requestBatchSize}get editor(){return this._editor}set editor(e){if(this._editor===e)return;const t=this._editor;t&&t.model.sharedModel.changed.disconnect(this.onTextChange,this),this._editor=e,e&&e.model.sharedModel.changed.connect(this.onTextChange,this)}get placeholder(){return this._placeholder}get kernelSession(){return this._kernelSession}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed=!0,this._history.length=0,A.clearData(this)}async checkSession(e){var t;this._hasSession||(await this._retrieveHistory(),this._hasSession=!0,this.editor=e.editor,this._placeholder=((t=this._editor)===null||t===void 0?void 0:t.model.sharedModel.getSource())||"",this.setFilter(this._placeholder),this._cursor=this._filtered.length-1)}async back(e){return await this.checkSession(e),--this._cursor,this._cursor<0&&await this.fetchBatch(),this._cursor=Math.max(0,this._cursor),this._filtered[this._cursor]}async forward(e){return await this.checkSession(e),++this._cursor,this._cursor=Math.min(this._filtered.length-1,this._cursor),this._filtered[this._cursor]}updateEditor(e,t){var n,s;if(e){const o=(n=e.editor)===null||n===void 0?void 0:n.model,i=o?.sharedModel.getSource();if(this.isDisposed||!t||i===t)return;this._setByHistory=!0,o?.sharedModel.setSource(t);let a=0;a=t.indexOf(`
|
|
1
|
+
import{r as _,v as qe,j as u,j9 as jt,I as U,eK as Ge,cE as pe,bl as ge,c as J,ff as Pt,f9 as Ue,fq as Tt,ja as Dt,jb as At,jc as Je,jd as Ye,cj as W,je as It,jf as Nt,jg as Lt,bJ as Te,jh as ct,ji as ht,jj as Rt,jk as fe,az as Ot,bF as ut,jl as ft,jm as Ft,jn as Xe,F as A,jo as Ze,jp as me,jq as Bt,jr as Wt,js as Vt,ao as _e,jt as Ie,ju as Qe,cA as ke,cz as ee,b9 as $t,em as Gt,cg as z,jv as Ht,aa as mt,ag as zt,co as Kt,ai as Z,cW as qt,dm as Ut,i1 as Fe,h$ as pt,jw as xe,jx as de,jy as Jt,ar as Yt,aj as Xt,jz as Zt,ak as Qt,jA as gt,hK as H,jB as en,jC as R,jD as tn,df as nn,jE as _t,jF as sn,e7 as on,e8 as rn,ee as ce,e9 as Ne,ea as an,jG as ln,jH as dn,jI as cn,eH as ne,B as ue,a9 as hn,d3 as un,dY as et,_ as fn,ab as mn,jJ as pn,jK as gn,jL as _n,jM as vn,e0 as tt,e1 as he,e2 as yn,e3 as Cn,e4 as bn,ct as wn,l as kn,jN as xn,jO as vt,fz as Mn,jP as ae,bk as T,C as le,cL as nt,bw as yt,dx as Sn,cP as En,bt as Me,i as jn,P as Pn,as as Tn,aC as Dn}from"../datalayer-app-main.js";import{c as An,N as Be}from"./NotebookSkeleton-z8GKB7Tb.js";import{a as In,W as st}from"./renderer-jz0zn1Az.js";import{C as Se,S as Ee}from"./SquareIcon-e3ygcjpv.js";function Nn(...r){return _.useCallback(e=>{for(const t of r)typeof t=="function"?t(e):t&&(t.current=e)},r)}var Q={Banner:"prc-Banner-Banner-IR8eJ",BannerContainer:"prc-Banner-BannerContainer-lbx3d",BannerContent:"prc-Banner-BannerContent-zTITK",BannerActions:"prc-Banner-BannerActions-XCfHL",BannerTitle:"prc-Banner-BannerTitle-TcuJl",BannerIcon:"prc-Banner-BannerIcon-WuOyf",BannerDismiss:"prc-Banner-BannerDismiss-uBZVm",BannerActionsContainer:"prc-Banner-BannerActionsContainer-ukGMH"};const Ln={critical:u.jsx(Dt,{}),info:u.jsx(Ue,{}),success:u.jsx(Tt,{}),upsell:u.jsx(Ue,{}),warning:u.jsx(Pt,{})},Rn={critical:"Critical",info:"Information",success:"Success",upsell:"Recommendation",warning:"Warning"},On=qe.forwardRef(function({"aria-label":e,children:t,className:n,description:s,hideTitle:o,icon:i,onDismiss:a,primaryAction:l,secondaryAction:d,title:c,variant:h="info",...f},m){const C=!!a,x=l||d,I=qe.useRef(null),L=Nn(m,I),g=h==="info"||h==="upsell";return u.jsxs("section",{...f,"aria-label":e??Rn[h],className:pe(n,Q.Banner),"data-dismissible":a?"":void 0,"data-title-hidden":o?"":void 0,"data-variant":h,tabIndex:-1,ref:L,children:[u.jsx("div",{className:Q.BannerIcon,children:i&&g?i:Ln[h]}),u.jsxs("div",{className:Q.BannerContainer,children:[u.jsxs("div",{className:Q.BannerContent,children:[c?o?u.jsx(jt,{children:u.jsx(We,{children:c})}):u.jsx(We,{children:c}):null,s?u.jsx(Ct,{children:s}):null,t]}),x?u.jsx(Fn,{primaryAction:l,secondaryAction:d}):null]}),C?u.jsx(U,{"aria-label":"Dismiss banner",onClick:a,className:Q.BannerDismiss,icon:Ge,variant:"invisible"}):null]})});function We(r){const e=ge.c(12);let t,n,s,o;e[0]!==r?({as:o,className:n,children:t,...s}=r,e[0]=r,e[1]=t,e[2]=n,e[3]=s,e[4]=o):(t=e[1],n=e[2],s=e[3],o=e[4]);const i=o===void 0?"h2":o;let a;e[5]!==n?(a=pe(n,Q.BannerTitle),e[5]=n,e[6]=a):a=e[6];let l;return e[7]!==i||e[8]!==t||e[9]!==s||e[10]!==a?(l=u.jsx(i,{...s,className:a,"data-banner-title":"",children:t}),e[7]=i,e[8]=t,e[9]=s,e[10]=a,e[11]=l):l=e[11],l}function Ct(r){const e=ge.c(10);let t,n,s;e[0]!==r?({children:t,className:n,...s}=r,e[0]=r,e[1]=t,e[2]=n,e[3]=s):(t=e[1],n=e[2],s=e[3]);let o;e[4]!==n?(o=pe("BannerDescription",n),e[4]=n,e[5]=o):o=e[5];let i;return e[6]!==t||e[7]!==s||e[8]!==o?(i=u.jsx("div",{...s,className:o,children:t}),e[6]=t,e[7]=s,e[8]=o,e[9]=i):i=e[9],i}function Fn(r){const e=ge.c(9),{primaryAction:t,secondaryAction:n}=r,s=n??null,o=t??null;let i;e[0]!==s||e[1]!==o?(i=u.jsxs("div",{className:Q.BannerActionsContainer,"data-primary-action":"trailing",children:[s,o]}),e[0]=s,e[1]=o,e[2]=i):i=e[2];const a=t??null,l=n??null;let d;e[3]!==a||e[4]!==l?(d=u.jsxs("div",{className:Q.BannerActionsContainer,"data-primary-action":"leading",children:[a,l]}),e[3]=a,e[4]=l,e[5]=d):d=e[5];let c;return e[6]!==i||e[7]!==d?(c=u.jsxs("div",{className:Q.BannerActions,children:[i,d]}),e[6]=i,e[7]=d,e[8]=c):c=e[8],c}const bt=_.forwardRef((r,e)=>{const t=ge.c(11);let n,s,o;t[0]!==r?({children:n,className:s,...o}=r,t[0]=r,t[1]=n,t[2]=s,t[3]=o):(n=t[1],s=t[2],o=t[3]);let i;t[4]!==s?(i=pe("BannerPrimaryAction",s),t[4]=s,t[5]=i):i=t[5];let a;return t[6]!==n||t[7]!==e||t[8]!==o||t[9]!==i?(a=u.jsx(J,{ref:e,className:i,variant:"default",...o,children:n}),t[6]=n,t[7]=e,t[8]=o,t[9]=i,t[10]=a):a=t[10],a});bt.displayName="BannerPrimaryAction";const wt=_.forwardRef((r,e)=>{const t=ge.c(11);let n,s,o;t[0]!==r?({children:n,className:s,...o}=r,t[0]=r,t[1]=n,t[2]=s,t[3]=o):(n=t[1],s=t[2],o=t[3]);let i;t[4]!==s?(i=pe("BannerPrimaryAction",s),t[4]=s,t[5]=i):i=t[5];let a;return t[6]!==n||t[7]!==e||t[8]!==o||t[9]!==i?(a=u.jsx(J,{ref:e,className:i,variant:"link",...o,children:n}),t[6]=n,t[7]=e,t[8]=o,t[9]=i,t[10]=a):a=t[10],a});wt.displayName="BannerSecondaryAction";const Bn=Object.assign(On,{Title:We,Description:Ct,PrimaryAction:bt,SecondaryAction:wt}),ve=Nt.define({combine(r){return r[r.length-1]}}),Wn=Te.baseTheme({".jp-remote-cursor":{borderLeft:"1px solid black",marginLeft:"-1px"},".jp-remote-cursor.jp-mod-primary":{borderLeftWidth:"2px"},".jp-remote-selection":{opacity:.5},".cm-tooltip":{border:"none"},".cm-tooltip.jp-remote-userInfo":{color:"var(--fgColor-onEmphasis, #ffffff)",padding:"0px 2px"}});function He(r,e){const t=r?.username||r?.display_name||r?.name||String(e),{theme:n,colorMode:s}=Ot.getState(),o=s==="auto"?typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":s;return An(t,n,o)}const De=Lt.define();class kt{style;marker;constructor(e,t){this.style=e,this.marker=t}draw(){const e=this.marker.draw();for(const[t,n]of Object.entries(this.style))e.style[t]=n;return e}eq(e){return this.marker.eq(e.marker)&&W.deepEqual(this.style,e.style)}update(e,t){for(const[n,s]of Object.entries(this.style))e.style[n]=s;return this.marker.update(e,t.marker)}}const Vn=ct({above:!0,markers(r){const{awareness:e,ytext:t}=r.state.facet(ve),n=t.doc,s=[];return e.getStates().forEach((o,i)=>{if(i===e.doc.clientID)return;const a=o.cursors;for(const l of a??[]){if(!l?.anchor||!l?.head)return;const d=fe(l.anchor,n),c=fe(l.head,n);if(d?.type!==t||c?.type!==t)return;const h=l.primary??!0?"jp-remote-cursor jp-mod-primary":"jp-remote-cursor",f=ut.cursor(c.index,c.index>d.index?-1:1);for(const m of ft.forRange(r,h,f))s.push(new kt({borderLeftColor:He(o.user,i)},m))}}),s},update(r,e){return!!r.transactions.find(t=>t.annotation(De))},class:"jp-remote-cursors"});function ot(r){const e=new Array,{awareness:t,ytext:n}=r.facet(ve),s=n.doc;for(const[o,i]of t.getStates())if(o!==t.doc.clientID)for(const a of i.cursors??[]){if(!a?.head)continue;const l=fe(a.head,s);l?.type===n&&e.push({pos:l.index,above:!0,create:()=>{const d=document.createElement("div");return d.classList.add("jp-remote-userInfo"),d.style.backgroundColor=He(i.user,o),d.textContent=i.user?.display_name??"Anonymous",{dom:d}}})}return e}const $n=ht.define({create:ot,update(r,e){return e.annotation(De)?ot(e.state):r},provide(r){return Rt.computeN([r],e=>e.field(r))}}),Gn=ct({above:!1,markers(r){const{awareness:e,ytext:t}=r.state.facet(ve),n=t.doc,s=[];return e.getStates().forEach((o,i)=>{if(i===e.doc.clientID)return;const a=o.cursors;for(const l of a??[]){if((l.empty??!0)||!l?.anchor||!l?.head)return;const d=fe(l.anchor,n),c=fe(l.head,n);if(d?.type!==t||c?.type!==t)return;const h="jp-remote-selection";for(const f of ft.forRange(r,h,ut.range(d.index,c.index)))s.push(new kt({backgroundColor:He(o.user,i)},f))}}),s},update(r,e){return!!r.transactions.find(t=>t.annotation(De))},class:"jp-remote-selections"}),Hn=At.fromClass(class{editorAwareness;_listener;constructor(r){this.editorAwareness=r.state.facet(ve),this._listener=({added:e,updated:t,removed:n})=>{e.concat(t).concat(n).findIndex(o=>o!==this.editorAwareness.awareness.doc.clientID)>=0&&r.dispatch({annotations:[De.of([])]})},this.editorAwareness.awareness.on("change",this._listener)}destroy(){this.editorAwareness.awareness.off("change",this._listener)}update(r){if(!r.docChanged&&!r.selectionSet)return;const{awareness:e,ytext:t}=this.editorAwareness,n=e.getLocalState();if(n){const s=r.view.hasFocus&&r.view.dom.ownerDocument.hasFocus(),o=r.state.selection,i=new Array;if(s&&o){for(const a of o.ranges){const l=a===o.main,d=Je(t,a.anchor),c=Je(t,a.head);i.push({anchor:d,head:c,primary:l,empty:a.empty})}if(!n.cursors||i.length>0){const a=n.cursors?.map(l=>({...l,anchor:l?.anchor?Ye(l.anchor):null,head:l?.head?Ye(l.head):null}));W.deepEqual(i,a)||e.setLocalStateField("cursors",i)}}}}},{provide:()=>[Wn,Vn,Gn,$n,It({position:"absolute",parent:document.body})]});function zn(r){return[ve.of(r),Hn]}class Ae extends Ft{constructor(e={}){var t;super(),this.version="2.0.0",this.ymeta=this.ydoc.getMap("meta"),this._onMetaChanged=n=>{const s=n.find(i=>i.target===this.ymeta.get("metadata"));if(s){const i=s.changes.keys,a=this.ymeta.get("metadata");s.changes.keys.forEach((l,d)=>{switch(l.action){case"add":this._metadataChanged.emit({key:d,type:"add",newValue:a.get(d)});break;case"delete":this._metadataChanged.emit({key:d,type:"remove",oldValue:l.oldValue});break;case"update":{const c=a.get(d),h=l.oldValue;let f=!0;typeof h=="object"&&typeof c=="object"?f=W.deepEqual(h,c):f=h===c,f||this._metadataChanged.emit({key:d,type:"change",oldValue:h,newValue:c})}break}}),this._changed.emit({metadataChange:i})}const o=n.find(i=>i.target===this.ymeta);if(o){if(o.keysChanged.has("metadata")){const i=o.changes.keys.get("metadata");if(i?.action==="add"&&!i.oldValue){const a=new Map;for(const l of Object.keys(this.metadata))a.set(l,{action:"add",oldValue:void 0}),this._metadataChanged.emit({key:l,type:"add",newValue:this.getMetadata(l)});this._changed.emit({metadataChange:a})}}if(o.keysChanged.has("nbformat")){const i=o.changes.keys.get("nbformat"),a={key:"nbformat",oldValue:i?.oldValue?i.oldValue:void 0,newValue:this.nbformat};this._changed.emit({nbformatChanged:a})}if(o.keysChanged.has("nbformat_minor")){const i=o.changes.keys.get("nbformat_minor"),a={key:"nbformat_minor",oldValue:i?.oldValue?i.oldValue:void 0,newValue:this.nbformat_minor};this._changed.emit({nbformatChanged:a})}}},this._onYCellsChanged=n=>{n.changes.added.forEach(i=>{const a=i.content.type;if(!this._ycellMapping.has(a)){const l=Xe(a,{notebook:this});this._ycellMapping.set(a,l)}}),n.changes.deleted.forEach(i=>{const a=i.content.type,l=this._ycellMapping.get(a);l&&(l.dispose(),this._ycellMapping.delete(a))});let s=0;const o=[];n.changes.delta.forEach(i=>{if(i.insert!=null){const a=i.insert.map(l=>this._ycellMapping.get(l));o.push({insert:a}),this.cells.splice(s,0,...a),s+=i.insert.length}else i.delete!=null?(o.push(i),this.cells.splice(s,i.delete)):i.retain!=null&&(o.push(i),s+=i.retain)}),this._changed.emit({cellsChange:o})},this._metadataChanged=new A(this),this._ycells=this.ydoc.getArray("cells"),this._ycellMapping=new WeakMap,this._disableDocumentWideUndoRedo=(t=e.disableDocumentWideUndoRedo)!==null&&t!==void 0?t:!1,this.cells=this._ycells.toArray().map(n=>(this._ycellMapping.has(n)||this._ycellMapping.set(n,Xe(n,{notebook:this})),this._ycellMapping.get(n))),this.undoManager.addToScope(this._ycells),this._ycells.observe(this._onYCellsChanged),this.ymeta.observeDeep(this._onMetaChanged)}static create(e={}){var t,n,s,o,i,a,l,d,c;const h=new Ae({disableDocumentWideUndoRedo:(t=e.disableDocumentWideUndoRedo)!==null&&t!==void 0?t:!1}),f={cells:(s=(n=e.data)===null||n===void 0?void 0:n.cells)!==null&&s!==void 0?s:[],nbformat:(i=(o=e.data)===null||o===void 0?void 0:o.nbformat)!==null&&i!==void 0?i:4,nbformat_minor:(l=(a=e.data)===null||a===void 0?void 0:a.nbformat_minor)!==null&&l!==void 0?l:5,metadata:(c=(d=e.data)===null||d===void 0?void 0:d.metadata)!==null&&c!==void 0?c:{}};return h.setSource(f),h}get disableDocumentWideUndoRedo(){return this._disableDocumentWideUndoRedo}get metadata(){return this.getMetadata()}set metadata(e){this.setMetadata(e)}get metadataChanged(){return this._metadataChanged}get nbformat(){return this.ymeta.get("nbformat")}set nbformat(e){this.transact(()=>{this.ymeta.set("nbformat",e)},!1)}get nbformat_minor(){return this.ymeta.get("nbformat_minor")}set nbformat_minor(e){this.transact(()=>{this.ymeta.set("nbformat_minor",e)},!1)}dispose(){this.isDisposed||(this._ycells.unobserve(this._onYCellsChanged),this.ymeta.unobserveDeep(this._onMetaChanged),super.dispose())}getCell(e){return this.cells[e]}addCell(e){return this.insertCell(this._ycells.length,e)}insertCell(e,t){return this.insertCells(e,[t])[0]}insertCells(e,t){const n=t.map(s=>{const o=Ze(s,this);return this._ycellMapping.set(o.ymodel,o),o});return this.transact(()=>{this._ycells.insert(e,n.map(s=>s.ymodel))}),this.dirty=!0,n}moveCell(e,t){this.moveCells(e,t)}moveCells(e,t,n=1){const s=new Array(n).fill(!0).map((o,i)=>this.getCell(e+i).toJSON());this.transact(()=>{this._ycells.delete(e,n),this._ycells.insert(e>t?t:t-n+1,s.map(o=>Ze(o,this).ymodel))}),this.dirty=!0}deleteCell(e){this.deleteCellRange(e,e+1)}deleteCellRange(e,t){this.transact(()=>{this._ycells.delete(e,t-e)}),this.dirty=!0}deleteMetadata(e){if(typeof this.getMetadata(e)>"u")return;const t=this.metadata;delete t[e],this.setMetadata(t)}getMetadata(e){const t=this.ymeta.get("metadata");if(t!==void 0)if(typeof e=="string"){const n=t.get(e);return typeof n>"u"?void 0:W.deepCopy(n)}else return W.deepCopy(t.toJSON())}setMetadata(e,t){var n;if(typeof e=="string"){if(typeof t>"u")throw new TypeError(`Metadata value for ${e} cannot be 'undefined'; use deleteMetadata.`);if(W.deepEqual((n=this.getMetadata(e))!==null&&n!==void 0?n:null,t))return;const s={};s[e]=t,this.updateMetadata(s)}else if(!this.metadata||!W.deepEqual(this.metadata,e)){const s=W.deepCopy(e),o=this.ymeta.get("metadata");if(o===void 0)return;this.transact(()=>{o.clear();for(const[i,a]of Object.entries(s))o.set(i,a)}),this.dirty=!0}}updateMetadata(e){const t=W.deepCopy(e),n=this.ymeta.get("metadata");n!==void 0&&(this.transact(()=>{for(const[s,o]of Object.entries(t))n.set(s,o)}),this.dirty=!0)}getSource(){return this.toJSON()}setSource(e){this.fromJSON(e),this.dirty=!1}fromJSON(e){this.transact(()=>{this.nbformat=e.nbformat,this.nbformat_minor=e.nbformat_minor;const t=e.metadata;if(t.orig_nbformat!==void 0&&delete t.orig_nbformat,this.metadata)this.metadata=t;else{const o=new me;for(const[i,a]of Object.entries(t))o.set(i,a);this.ymeta.set("metadata",o)}const n=e.nbformat===4&&e.nbformat_minor>=5,s=e.cells.map(o=>(n||delete o.id,o));this.insertCells(this.cells.length,s),this.deleteCellRange(0,this.cells.length)})}toJSON(){const e=this.nbformat===4&&this.nbformat_minor<=4;return{metadata:this.metadata,nbformat_minor:this.nbformat_minor,nbformat:this.nbformat,cells:this.cells.map(t=>{const n=t.toJSON();return e&&delete n.id,n})}}}class Kn{constructor(e){this.model=e,this._cellMap=new WeakMap,this._changed=new A(this),this._isDisposed=!1,this._insertCells(0,this.model.cells),this.model.changed.connect(this._onSharedModelChanged,this)}get changed(){return this._changed}get isDisposed(){return this._isDisposed}get length(){return this.model.cells.length}*[Symbol.iterator](){for(const e of this.model.cells)yield this._cellMap.get(e)}dispose(){var e;if(!this._isDisposed){this._isDisposed=!0;for(const t of this.model.cells)(e=this._cellMap.get(t))===null||e===void 0||e.dispose();A.clearData(this)}}get(e){return this._cellMap.get(this.model.cells[e])}_insertCells(e,t){return t.forEach(n=>{let s;switch(n.cell_type){case"code":{s=new Vt({sharedModel:n});break}case"markdown":{s=new Wt({sharedModel:n});break}default:s=new Bt({sharedModel:n})}this._cellMap.set(n,s),n.disposed.connect(()=>{s.dispose(),this._cellMap.delete(n)})}),this.length}_onSharedModelChanged(e,t){var n;let s=0;const o=new Array;(n=t.cellsChange)===null||n===void 0||n.forEach(i=>{i.insert!=null?(this._insertCells(s,i.insert),o.push({type:"add",newIndex:s,newValues:i.insert.map(a=>this._cellMap.get(a)),oldIndex:-2,oldValues:[]}),s+=i.insert.length):i.delete!=null?o.push({type:"remove",newIndex:-1,newValues:[],oldIndex:s,oldValues:new Array(i.delete).fill(void 0)}):i.retain!=null&&(s+=i.retain)}),o.forEach(i=>this._changed.emit(i))}}class qn{constructor(e){this._requestBatchSize=10,this._cursor=0,this._hasSession=!1,this._history=[],this._placeholder="",this._kernelSession="",this._setByHistory=!1,this._isDisposed=!1,this._editor=null,this._filtered=[],this._kernel=null,this._sessionContext=e.sessionContext,this._trans=(e.translator||_e).load("jupyterlab"),this._handleKernel().then(()=>{this._sessionContext.kernelChanged.connect(this._handleKernel,this)}),this._toRequest=this._requestBatchSize}get editor(){return this._editor}set editor(e){if(this._editor===e)return;const t=this._editor;t&&t.model.sharedModel.changed.disconnect(this.onTextChange,this),this._editor=e,e&&e.model.sharedModel.changed.connect(this.onTextChange,this)}get placeholder(){return this._placeholder}get kernelSession(){return this._kernelSession}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed=!0,this._history.length=0,A.clearData(this)}async checkSession(e){var t;this._hasSession||(await this._retrieveHistory(),this._hasSession=!0,this.editor=e.editor,this._placeholder=((t=this._editor)===null||t===void 0?void 0:t.model.sharedModel.getSource())||"",this.setFilter(this._placeholder),this._cursor=this._filtered.length-1)}async back(e){return await this.checkSession(e),--this._cursor,this._cursor<0&&await this.fetchBatch(),this._cursor=Math.max(0,this._cursor),this._filtered[this._cursor]}async forward(e){return await this.checkSession(e),++this._cursor,this._cursor=Math.min(this._filtered.length-1,this._cursor),this._filtered[this._cursor]}updateEditor(e,t){var n,s;if(e){const o=(n=e.editor)===null||n===void 0?void 0:n.model,i=o?.sharedModel.getSource();if(this.isDisposed||!t||i===t)return;this._setByHistory=!0,o?.sharedModel.setSource(t);let a=0;a=t.indexOf(`
|
|
2
2
|
`),a<0&&(a=t.length),(s=e.editor)===null||s===void 0||s.setCursorPosition({line:0,column:a})}}reset(){this._hasSession=!1,this._placeholder="",this._toRequest=this._requestBatchSize}async fetchBatch(){this._toRequest+=this._requestBatchSize;let e=this._filtered.slice().reverse(),t=this._history.slice();await this._retrieveHistory().then(()=>{this.setFilter(this._placeholder);let n=0,s=this._filtered.slice().reverse();for(let o=0;o<e.length;o++){let i=e[o];for(let a=o+n;a<s.length&&i!==s[a];a++)n+=1}this._cursor=this._filtered.length-(e.length+1)-n}),this._cursor<0&&this._history.length>t.length&&await this.fetchBatch()}onHistory(e,t){this._history.length=0;let n=["","",""],s=["","",""],o="";if(e.content.status==="ok"){for(let i=0;i<e.content.history.length;i++)s=e.content.history[i],s!==n&&(o=e.content.history[i][0],this._history.push(n=s));this.kernelSession||s[2]==t?.model.sharedModel.getSource()&&(this._kernelSession=o)}}onTextChange(){if(this._setByHistory){this._setByHistory=!1;return}this.reset()}async _handleKernel(){var e;if(this._kernel=(e=this._sessionContext.session)===null||e===void 0?void 0:e.kernel,!this._kernel){this._history.length=0;return}await this._retrieveHistory().catch()}async _retrieveHistory(e){var t;return await((t=this._kernel)===null||t===void 0?void 0:t.requestHistory(Un(this._toRequest)).then(n=>{this.onHistory(n,e)}).catch(()=>{console.warn(this._trans.__("History was unable to be retrieved"))}))}setFilter(e=""){this._filtered.length=0;let t="",n="";for(let s=0;s<this._history.length;s++)n=this._history[s][2],n!==t&&e!==n&&this._filtered.push(t=n);this._filtered.push(e)}}function Un(r){return{output:!1,raw:!0,hist_access_type:"tail",n:r}}class Ve{constructor(e={}){var t,n;this.standaloneModel=!1,this._readOnly=!1,this._contentChanged=new A(this),this._stateChanged=new A(this),this._isDisposed=!1,this._metadataChanged=new A(this),this.standaloneModel=typeof e.sharedModel>"u",e.sharedModel?this.sharedModel=e.sharedModel:this.sharedModel=Ae.create({disableDocumentWideUndoRedo:(t=e.disableDocumentWideUndoRedo)!==null&&t!==void 0?t:!0,data:{nbformat:Qe,nbformat_minor:Ie,metadata:{kernelspec:{name:"",display_name:""},language_info:{name:(n=e.languagePreference)!==null&&n!==void 0?n:""}}}}),this._cells=new Kn(this.sharedModel),this._trans=(e.translator||_e).load("jupyterlab"),this._deletedCells=[],this._collaborationEnabled=!!e?.collaborationEnabled,this._cells.changed.connect(this._onCellsChanged,this),this.sharedModel.changed.connect(this._onStateChanged,this),this.sharedModel.metadataChanged.connect(this._onMetadataChanged,this)}get contentChanged(){return this._contentChanged}get metadataChanged(){return this._metadataChanged}get stateChanged(){return this._stateChanged}get cells(){return this._cells}get dirty(){return this.sharedModel.dirty}set dirty(e){const t=this.dirty;e!==t&&(this.sharedModel.dirty=e)}get readOnly(){return this._readOnly}set readOnly(e){if(e===this._readOnly)return;const t=this._readOnly;this._readOnly=e,this.triggerStateChange({name:"readOnly",oldValue:t,newValue:e})}get metadata(){return this.sharedModel.metadata}get nbformat(){return this.sharedModel.nbformat}get nbformatMinor(){return this.sharedModel.nbformat_minor}get defaultKernelName(){var e;const t=this.getMetadata("kernelspec");return(e=t?.name)!==null&&e!==void 0?e:""}get deletedCells(){return this._deletedCells}get defaultKernelLanguage(){var e;const t=this.getMetadata("language_info");return(e=t?.name)!==null&&e!==void 0?e:""}get collaborative(){return this._collaborationEnabled}dispose(){if(this.isDisposed)return;this._isDisposed=!0;const e=this.cells;this._cells=null,e.dispose(),this.standaloneModel&&this.sharedModel.dispose(),A.clearData(this)}deleteMetadata(e){return this.sharedModel.deleteMetadata(e)}getMetadata(e){return this.sharedModel.getMetadata(e)}setMetadata(e,t){typeof t>"u"?this.sharedModel.deleteMetadata(e):this.sharedModel.setMetadata(e,t)}toString(){return JSON.stringify(this.toJSON())}fromString(e){this.fromJSON(JSON.parse(e))}toJSON(){return this._ensureMetadata(),this.sharedModel.toJSON()}fromJSON(e){var t,n;const s=W.deepCopy(e),o=e.metadata.orig_nbformat;if(s.nbformat=Math.max(e.nbformat,Qe),(s.nbformat!==e.nbformat||s.nbformat_minor<Ie)&&(s.nbformat_minor=Ie),o!==void 0&&s.nbformat!==o){const i=s.nbformat>o;let a;i?a=this._trans.__(`This notebook has been converted from an older notebook format (v%1)
|
|
3
3
|
to the current notebook format (v%2).
|
|
4
4
|
The next time you save this notebook, the current notebook format (v%2) will be used.
|
|
@@ -36,7 +36,7 @@ or load the version on disk (revert)?`,this.path),s=ee.okButton({label:this._tra
|
|
|
36
36
|
`).map(n=>n+`
|
|
37
37
|
`);return e?t.pop():t.push(t.pop().slice(0,-1)),t}class ys{_commands;_panel;_notebook;_context;_defaultCellType="code";_kernelInfo=null;_variant;_registered=new Map;constructor(e,t,n,s=gt){this._commands=e,this._panel=t,this._notebook=t.content,this._context=n,this._variant=s,s==="marimo"&&H.executed.connect(this.onExecuted,this)}get variant(){return this._variant}onExecuted(e,t){const{notebook:n,cell:s,success:o}=t;if(n!==this._notebook||!o||s.model.type!=="code")return;const i=this._context.sessionContext.session?.kernel;if(!i)return;const a=en.for(i);a.reacting||this.react(a,s.model.sharedModel.getId())}async react(e,t){const n=new Set;for(const s of this._notebook.widgets){if(s.model.type!=="code")continue;const o=s.model.sharedModel.getId(),i=s.model.sharedModel.getSource();n.add(o),e.bindRunner(o,()=>this.runOne(o)),this._registered.get(o)!==i&&((await e.register(o,i)).error?this._registered.delete(o):this._registered.set(o,i))}for(const s of Array.from(this._registered.keys()))n.has(s)||(this._registered.delete(s),await e.remove(s));await e.react(t)}async runOne(e){const t=this._notebook.widgets.findIndex(n=>n.model.sharedModel.getId()===e);t<0||(this._notebook.deselectAll(),this._notebook.activeCellIndex=t,await H.run(this._notebook,this._context.sessionContext))}get commands(){return this._commands}get panel(){return this._panel}get notebook(){return this._notebook}get context(){return this._context}get sessionContext(){return this._panel.sessionContext}get kernel(){return this._panel.sessionContext?.session?.kernel??null}get kernelInfo(){return this._kernelInfo}async fetchKernelInfo(){if(this._kernelInfo)return this._kernelInfo;const e=this.kernel;return e?(this._kernelInfo=await e.info,this._kernelInfo):null}assignKernel(e){this._kernelInfo=null,this._context?.sessionContext.changeKernel({id:e.id})}setDefaultCellType(e){this._defaultCellType=e}get defaultCellType(){return this._defaultCellType}insertAbove(e){const t=this._notebook;H.insertAbove(t),H.changeCellType(t,this._defaultCellType),e&&t.activeCell&&t.activeCell.model.sharedModel.setSource(e),t.mode="edit"}insertBelow(e){const t=this._notebook;H.insertBelow(t),H.changeCellType(t,this._defaultCellType),e&&t.activeCell&&t.activeCell.model.sharedModel.setSource(e),t.mode="edit"}changeCellType(e){const t=this._notebook;t.activeCell&&t.activeCell.model.type!==e&&H.changeCellType(t,e)}deleteCells(){const e=this._notebook;H.deleteCells(e)}get model(){return this._context.model}undo(){const e=this._notebook;if(e.mode==="edit"&&e.activeCell?.editor){const t=e.activeCell.editor;if(t&&typeof t.undo=="function"){t.undo();return}}H.undo(e)}redo(){const e=this._notebook;if(e.mode==="edit"&&e.activeCell?.editor){const t=e.activeCell.editor;if(t&&typeof t.redo=="function"){t.redo();return}}H.redo(e)}setActiveCell(e){const t=this._notebook,n=t.model?.cells.length??0;e>=0&&e<n&&(t.activeCellIndex=e)}getCells(){const e=this._notebook.model?.cells;if(!e)return[];const t=[];for(let n=0;n<e.length;n++){const s=e.get(n);if(s){const o={index:n,type:s.type,source:s.sharedModel.getSource(),outputs:s.type==="code"?s.outputs?.toJSON():void 0};t.push(o)}}return t}readAllCells(e="brief"){return this.getCells().map((n,s)=>{const o=this._notebook.model?.cells.get(s),i=o?.type==="code"?o.executionCount??null:null;return e==="brief"?{index:s,type:n.type,preview:n.source.substring(0,40)}:{index:s,type:n.type,source:n.source,execution_count:i,outputs:n.outputs}})}getCellCount(){return this._notebook.model?.cells.length??0}insertAt(e,t){const n=this.getCellCount();if(e<-1||e>n)throw new Error(`Index ${e} is outside valid range [-1, ${n}]. Use -1 to append at end.`);const s=e===-1?n:e;s>=n?(n>0&&this.setActiveCell(n-1),this.insertBelow(t)):(this.setActiveCell(s),this.insertAbove(t))}insertCell(e,t,n){const s=this.getCellCount();this.setDefaultCellType(e);const o=t??s;try{this.insertAt(o,n)}catch(a){throw console.error(`[NotebookAdapter] insertCell failed at index ${o}:`,a),a}const i=this.getCellCount();i<=s&&console.warn(`[NotebookAdapter] insertCell at index ${o}: cell count did not increase (before=${s}, after=${i}). The Yjs shared model may not be properly initialised.`)}insertCells(e,t){let n=t;for(const s of e)this.setDefaultCellType(s.type),this.insertAt(n,s.source),n++}deleteCell(e){const n=this._notebook.model?.cells?.length??0;for(const o of e)if(o<0||o>=n)throw new Error(`Cell index ${o} is out of range. Notebook has ${n} cells.`);const s=[...e].sort((o,i)=>i-o);for(const o of s)this.setActiveCell(o),this.deleteCells()}updateCell(e,t){const n=this._notebook.model?.sharedModel.cells.length??0;if(e<0||e>=n)throw new Error(`Cell index ${e} is out of range. Notebook has ${n} cells.`);const s=this._notebook.model?.cells.get(e);if(!s)throw new Error(`Cell at index ${e} not found.`);const o=s.sharedModel.getSource();return s.sharedModel.setSource(t),_s(`cell_${e}`,o,t,"before","after",{context:3})}getCell(e,t=!0){if(e!==void 0){const s=this.getCells()[e];if(!s)return;const o=this._notebook.model?.cells.get(e),i=o?.type==="code"?o.executionCount??null:null;return{type:s.type,source:s.source,execution_count:i,outputs:t?s.outputs:void 0}}else{const n=this._notebook.activeCell;if(!n)return;const s=n.model.type==="code"?n.model.executionCount??null:null;return{type:n.model.type,source:n.model.sharedModel.getSource(),execution_count:s,outputs:t&&n.model.type==="code"?n.model.outputs?.toJSON():void 0}}}async runCell(e){const{index:t}=e||{};t!==void 0&&this.setActiveCell(t);const n=t??this._notebook.activeCellIndex;if(n===-1)throw new Error("No active cell to execute");await H.run(this._notebook,this._context.sessionContext),await new Promise(i=>setTimeout(i,100));const s=this.getCell(n,!0);if(!s)return{execution_count:null,outputs:[]};const o=[];if(s.outputs&&Array.isArray(s.outputs)){for(const i of s.outputs)if(typeof i=="string")o.push(i);else if(i&&typeof i=="object"){const a=i;if(a.output_type==="stream"){const l=a.text;typeof l=="string"?o.push(l):Array.isArray(l)&&o.push(l.join(""))}else if(a.output_type==="execute_result"||a.output_type==="display_data"){const l=a.data;if(l&&l["text/plain"]){const d=l["text/plain"];typeof d=="string"?o.push(d):Array.isArray(d)&&o.push(d.join(""))}}else if(a.output_type==="error"){const l=a.ename??"Error",d=a.evalue??"",c=a.traceback;Array.isArray(c)&&c.length>0?o.push(`[ERROR: ${l}: ${d}]
|
|
38
38
|
${c.join(`
|
|
39
|
-
`)}`):o.push(`[ERROR: ${l}: ${d}]`)}}}return{execution_count:s.execution_count,outputs:o}}runAllCells(){this._commands.execute(R.runAll)}clearAllOutputs(){H.clearAllOutputs(this._notebook)}_lastExecuteOutputs=null;get lastExecuteOutputs(){return this._lastExecuteOutputs}async executeCode(e,t={}){const n=this._panel.sessionContext;if(!n||!n.session?.kernel)return{success:!1,error:"No active kernel session"};const s=n.session.kernel;try{const o=s.requestExecute({code:e,stop_on_error:!0,store_history:!1,silent:!1,allow_stdin:!1}),i=[];let a;const l=new tn({trusted:!0});this._lastExecuteOutputs=l,o.onIOPub=f=>{const m=f.header.msg_type;m==="stream"?(i.push({type:"stream",content:f.content}),l.add({output_type:"stream",...f.content})):m==="execute_result"?(i.push({type:"execute_result",content:f.content}),a=f.content.execution_count,l.add({output_type:"execute_result",...f.content})):m==="display_data"?(i.push({type:"display_data",content:f.content}),l.add({output_type:"display_data",...f.content})):m==="error"&&(i.push({type:"error",content:f.content}),l.add({output_type:"error",...f.content}))};const d=(t.timeout??30)*1e3,c=o.done,h=new Promise((f,m)=>{setTimeout(()=>{m(new Error(`Execution timeout after ${t.timeout??30} seconds`))},d)});try{await Promise.race([c,h])}catch(f){console.warn(`Cell execution timed out after ${t.timeout??30} seconds:`,f);try{await s.interrupt()}catch(m){console.warn("Failed to interrupt kernel after execution timeout:",m)}return{success:!1,error:`Execution exceeded ${t.timeout??30} seconds and was interrupted`,outputs:i}}return{success:!0,outputs:i,executionCount:a}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}dispose(){}}const Re=1e3,Cs=new Array,Mt=".datalayer/";function bs(r){const e=r.replace(/[/\\]/g," ").replace(/\s+/g," ").trim()||"notebook",t=e.endsWith(".ipynb")?e:`${e}.ipynb`;return`${Mt}${t}`}function ws(r){return r.startsWith(Mt)}function ks(r){const e=new vt;return r&&e.insert(0,r),e}function dt(r){return new me(Object.entries(r))}function xs(r){const e=W.deepCopy(r);if(e.output_type==="stream"&&e.text!==void 0){const{text:t,...n}=e,s=new vt,o=t instanceof Array?t.join(""):t;return o&&s.insert(0,o),new me([...Object.entries(n),["text",s]])}return new me(Object.entries(e))}function Ms(r){return r==null?"":typeof r=="string"?r:r.join("")}function Ss(r,e){const t=new me;if(t.set("cell_type",r.cell_type),t.set("source",ks(Ms(r.source))),t.set("metadata",dt(W.deepCopy(r.metadata??{}))),e&&r.id&&t.set("id",r.id),r.cell_type==="code"){const n=r,s=new xn,o=(n.outputs??[]).map(i=>xs(i));o.length>0&&s.insert(0,o),t.set("outputs",s),t.set("execution_count",n.execution_count??null)}if(r.cell_type==="markdown"||r.cell_type==="raw"){const n=r.attachments;n&&t.set("attachments",dt(W.deepCopy(n)))}return t}function Es(r,e,t){const n=r.sharedModel,s=e.nbformat??4,o=e.nbformat_minor??5,i=s===4&&o>=5,a=W.deepCopy(e.metadata??{});delete a.orig_nbformat;const l=e.cells.map(d=>({...d,metadata:{...d.metadata??{},editable:!t}}));n.transact(()=>{n.nbformat=s,n.nbformat_minor=o,n.metadata=a;const d=n._ycells;d.delete(0,d.length);const c=l.map(h=>Ss(h,i));c.length>0&&d.insert(0,c)})}function Oe(r){const e={};return r&&r.forEach(t=>{const n=t.schema?.default;e[t.identifier]={enabled:!0,debouncerDelay:n?.debouncerDelay??200,timeout:n?.timeout??15e3,autoFillInMiddle:!0}}),e}function js(r){const{commands:e,extensions:t=Cs,kernelId:n,sessionOnly:s,renderers:o,serviceManager:i,model:a,onSessionConnection:l,synced:d=!0,variant:c=gt}=r,[h,f]=_.useState(!0),[m,C]=_.useState(!1),x=_t(p=>p.backgroundColor),[I,L]=_.useState(new Array),[g,y]=_.useState(null),[M,S]=_.useState(null),E=_.useMemo(()=>r.id||sn(),[r.id]),K=_.useMemo(()=>r.path||bs(E),[E,r.path]),O=_.useMemo(()=>new As({commands:e,renderers:o}),[e,o]),ye=_.useMemo(()=>new pt.ContentFactory({editorFactory:O.editorServices.factoryService.newInlineEditor}),[O.editorServices.factoryService.newInlineEditor]);_.useEffect(()=>{const p=new on({model:new rn}),v=new Z,j=Oe(r.inlineProviders),D=r.providers&&r.providers.length>0?[new ce,...r.providers]:[new ce],k=new Ne({context:{widget:v},providers:D,inlineProviders:r.inlineProviders,inlineProvidersSettings:j,timeout:Re});let w;if(r.inlineProviders&&r.inlineProviders.length>0){const ie=_e.load("jupyterlab");w=new te({model:new te.Model,trans:ie});const N={};r.inlineProviders?.forEach(G=>{N[G.identifier]={enabled:!0}}),w.configure({...te.defaultSettings,showWidget:"always",showShortcuts:!0,streamingAnimation:"none",suppressIfTabCompleterActive:!1,minLines:1,maxLines:10,editorResizeDelay:250,reserveSpaceForLongest:!1,providers:N}),Z.attach(w,document.body);const q=G=>{if(G.key==="Tab"&&!G.shiftKey&&!G.ctrlKey&&!G.metaKey&&!G.altKey){if(w&&w.model&&w.current)return G.preventDefault(),G.stopPropagation(),w.accept(),!1;w&&w.model&&w.model.reset()}if(G.key==="Escape"&&w&&w.model&&w.current)return G.preventDefault(),G.stopPropagation(),w.model.reset(),!1};document.addEventListener("keydown",q,!0);const re=()=>{document.removeEventListener("keydown",q,!0)};w._keyboardCleanup=re}const $=new an({completer:p,reconciliator:k,inlineCompleter:w});return p.hide(),Z.attach(p,document.body),y($),()=>{queueMicrotask(()=>{$.dispose(),p.dispose(),w&&(w._keyboardCleanup&&w._keyboardCleanup(),w.dispose()),v.dispose()})}},[r.inlineProviders]);const[oe,Ce]=_.useState(null);_.useEffect(()=>{const p=new Zn({name:"Notebook",label:"Notebook",modelName:"notebook",fileTypes:["notebook"],defaultFor:["notebook"],preferKernel:!0,autoStartDefault:!1,canStartKernel:!1,shutdownOnClose:!1,rendermime:O.rendermime,contentFactory:ye,mimeTypeService:O.editorServices.mimeTypeService,notebookConfig:{...Fe.defaultNotebookConfig,windowingMode:"none",recordTiming:!0}});return Ce(p),()=>{p.dispose(),Ce(v=>v===p?null:v)}},[ye,O]);const B=_.useMemo(()=>new ln,[]),[V,X]=_.useState(null);_.useEffect(()=>{const p=g?new Xn({namespace:E}):null,v=g?dn(O.commands,g,p,B,r.path):null;return X(p),()=>{v?.dispose(),p?.dispose(),X(j=>j===p?null:j)}},[g,E,O.commands,r.path,B]);const[F,be]=_.useState(null),ze=_.useRef(n);_.useEffect(()=>{const p=new Is(a),v=new Yn({factory:p,manager:i??new Ls,path:K,kernelPreference:ze.current?{id:ze.current,shouldStart:!1,canStart:!1,autoStartDefault:!1,shutdownOnDispose:!1}:{shouldStart:!1,canStart:!1,autoStartDefault:!1,shutdownOnDispose:!1}});return Ns(v,E,!s&&!ws(K)?K:void 0,l,!i),be(v),()=>{v.dispose(),p.dispose(),be(j=>j===v?null:j)}},[E,i,a,K]),_.useEffect(()=>{if(!F||!n||F.sessionContext.isDisposed)return;(async()=>{try{if(F.sessionContext.session||await F.sessionContext.initialize(),F.sessionContext.isDisposed)return;await F.sessionContext.changeKernel({id:n})}catch(v){console.error("Failed to change kernel model.",v)}})()},[F,n]);const[P,Ke]=_.useState(null);return _.useEffect(()=>{let p=null,v=null,j=null;if(F&&(p=oe?.createNew(F)??null,p)){B.setPanel(p,F),v=new ys(O.commands,p,F,c),S(v),L(t.map(k=>(k.init({notebookId:E,commands:O.commands,panel:p}),k.createNew(p,F),k.component??u.jsx(u.Fragment,{}))));const D=p.content.rendermime;j=new In(F,D,{saveState:!1}),D.addFactory({safe:!0,mimeTypes:[cn],defaultRank:1,createRenderer:k=>new st(k,j)},1);for(const k of p.content.widgets)if(k.model.type==="code")for(const w of k.outputArea.widgets)for(const $ of Array.from(w.children()))$ instanceof st&&($.manager=j);f(!1)}return Ke(p),p||(L([]),S(null)),()=>{B.setPanel(null,null),queueMicrotask(()=>{if(j?.dispose(),v&&v.dispose(),p&&!p.isDisposed){p.content&&A.clearData(p.content);try{p.isAttached&&Z.detach(p),p.dispose()}catch{}}}),Ke(D=>D===p?null:D),S(D=>D===v?null:D)}},[F,t,O.commands,oe,B]),_.useEffect(()=>{if(C(!1),!!P)return cs(P,{synced:d,onPainted:()=>C(!0)})},[P,d]),_.useEffect(()=>{if(M){const p=ne.getState().notebooks,v=new Map(p);v.set(E,{adapter:M,model:M.model??void 0,portals:[]}),ne.getState().setNotebooks(v)}else{const p=ne.getState().notebooks;if(p.has(E)){const v=new Map(p);v.delete(E),ne.getState().setNotebooks(v)}}},[M,E]),_.useEffect(()=>{if(!P)return;const p=P.context.sessionContext,v=[],j=N=>{N&&ne.getState().changeKernelStatus({id:E,kernelStatus:N})},D=(N,q)=>{j(q)};p.statusChanged.connect(D);let k=null;const w=(N,q)=>{j(q)},$=()=>{const N=p.session?.kernel??null;if(N!==k&&(k?.statusChanged.disconnect(w),k=N,k?.statusChanged.connect(w),j(k?.status),N)){const q=()=>{k!==N||N.status!=="unknown"||kn.KernelAPI.getKernelModel(N.id,N.serverSettings).then(re=>{re?.execution_state&&k===N&&N.status==="unknown"&&(j(re.execution_state),v.push(setTimeout(q,5e3)))}).catch(()=>{})};q(),N.status==="unknown"&&Promise.resolve(N.requestKernelInfo?.()).catch(()=>{})}},ie=()=>$();return p.kernelChanged.connect(ie),$(),p.ready.then($),()=>{v.forEach(clearTimeout),p.statusChanged.disconnect(D),p.kernelChanged.disconnect(ie),k?.statusChanged.disconnect(w)}},[P,E]),_.useEffect(()=>{let p=!0,v=null,j=null;return P&&(V&&!P.isDisposed&&!V.has(P)&&V.add(P).catch(D=>{console.error(`Failed to track the notebook panel '${E}'.`)}),g&&(v=(D,k)=>{k&&k.ready.then(()=>{g.editor=k?.editor})},j=(D,k)=>{if(!p)return;const w=P.content.activeCell?.editor,$=new ce,ie=Oe(r.inlineProviders),N=k.newValue||{},q=r.providers&&r.providers.length>0?[$,...r.providers]:[$],re=new Ne({context:{widget:P,editor:w,session:N},providers:q,inlineProviders:r.inlineProviders,inlineProvidersSettings:ie,timeout:Re});g.inlineCompleter&&(g.inlineCompleter.editor=w),g.editor=w,g.reconciliator=re},P.context.sessionContext.sessionChanged.connect(j),P.context.sessionContext.ready.then(()=>{j?.(P.context.sessionContext,{name:"session",oldValue:null,newValue:P.context.sessionContext.session})}),P.content.activeCellChanged.connect(v))),()=>{if(p=!1,g){v&&P?.content.activeCellChanged.disconnect(v),j&&P?.context.sessionContext.sessionChanged.disconnect(j),g.editor=null;const D=Oe(r.inlineProviders),k=r.providers&&r.providers.length>0?[new ce,...r.providers]:[new ce];g.reconciliator=new Ne({context:{widget:new Z},providers:k,inlineProviders:r.inlineProviders,inlineProvidersSettings:D,timeout:Re})}}},[g,P,V]),_.useEffect(()=>{const p=P?.node;if(!p)return;const v=j=>{const D=j.target;!D||!p.contains(D)||O.commands.processKeydownEvent(j)};return window.addEventListener("keydown",v,!0),()=>{window.removeEventListener("keydown",v,!0)}},[O.commands,P]),_.useEffect(()=>()=>{const p=ne.getState().notebooks;if(p.has(E)){const v=new Map(p);v.delete(E),ne.getState().setNotebooks(v)}},[E]),u.jsxs(u.Fragment,{children:[I.map((p,v)=>u.jsx(ue,{children:p},`${p}-${v}`)),h?u.jsx(Be,{},"notebook-loader"):P?u.jsxs(ue,{sx:{height:"100%",position:"relative"},children:[u.jsx(hn,{id:E,children:P},"notebook-container"),m?null:u.jsx(ue,{sx:{position:"absolute",inset:0,zIndex:1,overflow:"hidden",bg:x??"var(--bgColor-default)"},children:u.jsx(Be,{})},"notebook-first-paint")]}):u.jsx(Bn,{variant:"critical",description:"Unable to create the notebook view.",hideTitle:!0,title:"Error"},"notebook-error")]})}function Ps(r={}){const{kernel:e,kernels:t,requestedKernelId:n,startDefaultKernel:s=!1}=r,o=e?.id,[i,a]=_.useState(o),[l,d]=_.useState(void 0);return _.useEffect(()=>{let c=!0;if(o){a(h=>h!==o?o:h);return}return t&&(async()=>{let h;if(await t.ready,n){const f=()=>{for(const m of t.running())if(m.id===n)return!0;return!1};if(!f())try{await t.refreshRunning()}catch(m){console.warn("Failed to list the running kernels.",m)}f()&&(h=n)}if(!h&&s&&c){await t.refreshRunning();const f=[...t.running()];if(f.length>0){const m=t.connectTo({model:f[0]});c?(h=m.id,a(h)):m.dispose()}else{const m=await t.startNew();c?(h=m.id,a(h),d(m)):m.dispose()}}c&&a(f=>f!==h?h:f)})(),()=>{c=!1}},[t,o,n,s]),_.useEffect(()=>()=>{l&&l.shutdown().catch(c=>{console.warn(`Failed to shutdown kernel '${l?.id}'.`,c)}).finally(()=>{l?.dispose()})},[l]),i}function Ts(r){const{collaborationProvider:e,nbformat:t,readonly:n=!1,url:s,path:o,serviceManager:i,id:a}=r,[l,d]=_.useState(null);return _.useEffect(()=>{let c=!0;const h=new nn;if(e&&i&&a)(async()=>{try{const m=new Ae;if(await e.connect(m,a,{serviceManager:i,path:o}),c){const C=new Ve({collaborationEnabled:!0,disableDocumentWideUndoRedo:!0,sharedModel:m});C.readOnly=n,d(C),h.add({dispose:()=>{e.disconnect()},get isDisposed(){return!1}})}}catch(m){console.error("Failed to setup collaboration:",m)}})();else{const f=m=>{const C=new Ve;m&&Es(C,m,n),C.readOnly=n,d(C)};!t&&s?Ds(s).then(m=>{c&&f(m)}):f(t)}return()=>{c=!1,h.dispose()}},[e,t,n,s,o,i,a]),l}async function Ds(r){return fetch(r).then(e=>e.text()).then(e=>JSON.parse(e))}class As{_commands;_editorServices;_rendermime;constructor(e={}){this._commands=e.commands??new un;const t=new et;for(const d of et.getDefaultLanguages())t.addLanguage(d);t.addLanguage({name:"ipythongfm",mime:"text/x-ipythongfm",load:async()=>(await fn(()=>import("./index-KWzHwvvN.js"),[],import.meta.url)).markdown({codeLanguages:c=>t.findBest(c)})});const n=mn.filter(d=>d.mimeTypes[0]!=="text/javascript").concat([pn,gn]).concat(e.renderers??[]);this._rendermime=new mt({initialFactories:n,latexTypesetter:vn(),markdownParser:_n(t)});const s=new bn(t),o=new tt;for(const d of tt.getDefaultThemes())o.addTheme(d);const i=new he;for(const d of he.getDefaultExtensions({themes:o}))i.addExtension(d);i.addExtension({name:"shared-model-binding",factory:d=>{const c=d.model.sharedModel;return he.createImmutableExtension(yn({ytext:c.ysource,undoManager:c.undoManager??void 0}))}}),i.addExtension({name:"remote-user-cursors",factory(d){const{awareness:c,ysource:h}=d.model.sharedModel;return he.createImmutableExtension(zn({awareness:c,ytext:h}))}});const a=Rs();a&&i.addExtension({name:"csp-nonce",factory(){return he.createImmutableExtension(Te.cspNonce.of(a))}});const l=new Cn({extensions:i,languages:t});this._editorServices={factoryService:l,mimeTypeService:s}}get commands(){return this._commands}get editorServices(){return this._editorServices}get rendermime(){return this._rendermime}}class Is extends Jn{model;constructor(e){super(),this.model=e}get collaborative(){return!1}createNew(e){return this.model}}function Ns(r,e,t,n,s=!1){const o=!t;r.sessionContext._initialize=async()=>{const i=r.sessionContext.sessionManager;await i.ready,await i.refreshRunning();const a=wn(i.running(),l=>l.kernel?.id===(r.sessionContext.kernelPreference.id??""));if(a)try{const l=i.connectTo({model:{...a,path:t??a.path,name:t??a.name},kernelConnectionOptions:{handleComms:!0}});r.sessionContext._handleNewSession(l)}catch(l){return r.sessionContext._handleSessionError(l),Promise.reject(l)}return await r.sessionContext._startIfNecessary()},r.dispose=()=>{r.isDisposed||(r._isDisposed=!0,r.sessionContext.dispose(),r._disposed.emit(void 0),A.clearData(r))},o&&(r._populate=async()=>{if(r._isPopulated=!0,r._isReady=!0,r._populatedPromise.resolve(void 0),r.isDisposed)return;const i=r._model.defaultKernelName||r.sessionContext.kernelPreference.name;r.sessionContext.kernelPreference={...r.sessionContext.kernelPreference,name:i,language:r._model.defaultKernelLanguage},s||r.sessionContext.initialize().then(a=>{a&&r._dialogs.selectKernel(r.sessionContext.sessionContext)})},r.initialize=async i=>{r.model.dirty=!1;const a=new Date().toISOString(),l={path:e,name:e,type:"notebook",content:void 0,writable:!0,created:a,last_modified:a,mimetype:"application/x-ipynb+json",format:"json"};r._updateContentsModel(l),await r._populate(),r.model.sharedModel.clearUndoHistory()}),r.sessionContext.sessionChanged.connect((i,a)=>{const l=a.newValue;n?.(l??void 0)}),r.sessionContext.kernelChanged.connect((i,a)=>{const l=a.newValue;l&&!l.handleComms&&(l.handleComms=!0)}),r.sessionContext.ready.then(()=>{n?.(r?.sessionContext.session??void 0)}),r.initialize(!t)}class Ls{_additionalDrives=new Set;contents=Object.freeze({fileChanged:{connect:()=>{}},getSharedModelFactory(e){return null},localPath:e=>{const t=e.split("/"),n=t[0].split(":");return n.length===1||!this._additionalDrives.has(n[0])?z.PathExt.removeSlash(e):z.PathExt.join(n.slice(1).join(":"),...t.slice(1))},normalize(e){const t=e.split(":");return t.length===1?z.PathExt.normalize(e):`${t[0]}:${z.PathExt.normalize(t.slice(1).join(":"))}`}});kernelspecs=Object.freeze({ready:new Promise(()=>{})});sessions=Object.freeze({ready:new Promise(()=>{})});ready=Promise.resolve()}function Rs(){const r=document.querySelector('meta[property="csp-nonce"]');return r?r.getAttribute("content"):null}const Os=Mn`
|
|
39
|
+
`)}`):o.push(`[ERROR: ${l}: ${d}]`)}}}return{execution_count:s.execution_count,outputs:o}}runAllCells(){this._commands.execute(R.runAll)}clearAllOutputs(){H.clearAllOutputs(this._notebook)}_lastExecuteOutputs=null;get lastExecuteOutputs(){return this._lastExecuteOutputs}async executeCode(e,t={}){const n=this._panel.sessionContext;if(!n||!n.session?.kernel)return{success:!1,error:"No active kernel session"};const s=n.session.kernel;try{const o=s.requestExecute({code:e,stop_on_error:!0,store_history:!1,silent:!1,allow_stdin:!1}),i=[];let a;const l=new tn({trusted:!0});this._lastExecuteOutputs=l,o.onIOPub=f=>{const m=f.header.msg_type;m==="stream"?(i.push({type:"stream",content:f.content}),l.add({output_type:"stream",...f.content})):m==="execute_result"?(i.push({type:"execute_result",content:f.content}),a=f.content.execution_count,l.add({output_type:"execute_result",...f.content})):m==="display_data"?(i.push({type:"display_data",content:f.content}),l.add({output_type:"display_data",...f.content})):m==="error"&&(i.push({type:"error",content:f.content}),l.add({output_type:"error",...f.content}))};const d=(t.timeout??30)*1e3,c=o.done,h=new Promise((f,m)=>{setTimeout(()=>{m(new Error(`Execution timeout after ${t.timeout??30} seconds`))},d)});try{await Promise.race([c,h])}catch(f){console.warn(`Cell execution timed out after ${t.timeout??30} seconds:`,f);try{await s.interrupt()}catch(m){console.warn("Failed to interrupt kernel after execution timeout:",m)}return{success:!1,error:`Execution exceeded ${t.timeout??30} seconds and was interrupted`,outputs:i}}return{success:!0,outputs:i,executionCount:a}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}dispose(){}}const Re=1e3,Cs=new Array,Mt=".datalayer/";function bs(r){const e=r.replace(/[/\\]/g," ").replace(/\s+/g," ").trim()||"notebook",t=e.endsWith(".ipynb")?e:`${e}.ipynb`;return`${Mt}${t}`}function ws(r){return r.startsWith(Mt)}function ks(r){const e=new vt;return r&&e.insert(0,r),e}function dt(r){return new me(Object.entries(r))}function xs(r){const e=W.deepCopy(r);if(e.output_type==="stream"&&e.text!==void 0){const{text:t,...n}=e,s=new vt,o=t instanceof Array?t.join(""):t;return o&&s.insert(0,o),new me([...Object.entries(n),["text",s]])}return new me(Object.entries(e))}function Ms(r){return r==null?"":typeof r=="string"?r:r.join("")}function Ss(r,e){const t=new me;if(t.set("cell_type",r.cell_type),t.set("source",ks(Ms(r.source))),t.set("metadata",dt(W.deepCopy(r.metadata??{}))),e&&r.id&&t.set("id",r.id),r.cell_type==="code"){const n=r,s=new xn,o=(n.outputs??[]).map(i=>xs(i));o.length>0&&s.insert(0,o),t.set("outputs",s),t.set("execution_count",n.execution_count??null)}if(r.cell_type==="markdown"||r.cell_type==="raw"){const n=r.attachments;n&&t.set("attachments",dt(W.deepCopy(n)))}return t}function Es(r,e,t){const n=r.sharedModel,s=e.nbformat??4,o=e.nbformat_minor??5,i=s===4&&o>=5,a=W.deepCopy(e.metadata??{});delete a.orig_nbformat;const l=e.cells.map(d=>({...d,metadata:{...d.metadata??{},editable:!t}}));n.transact(()=>{n.nbformat=s,n.nbformat_minor=o,n.metadata=a;const d=n._ycells;d.delete(0,d.length);const c=l.map(h=>Ss(h,i));c.length>0&&d.insert(0,c)})}function Oe(r){const e={};return r&&r.forEach(t=>{const n=t.schema?.default;e[t.identifier]={enabled:!0,debouncerDelay:n?.debouncerDelay??200,timeout:n?.timeout??15e3,autoFillInMiddle:!0}}),e}function js(r){const{commands:e,extensions:t=Cs,kernelId:n,sessionOnly:s,renderers:o,serviceManager:i,model:a,onSessionConnection:l,synced:d=!0,variant:c=gt}=r,[h,f]=_.useState(!0),[m,C]=_.useState(!1),x=_t(p=>p.backgroundColor),[I,L]=_.useState(new Array),[g,y]=_.useState(null),[M,S]=_.useState(null),E=_.useMemo(()=>r.id||sn(),[r.id]),K=_.useMemo(()=>r.path||bs(E),[E,r.path]),O=_.useMemo(()=>new As({commands:e,renderers:o}),[e,o]),ye=_.useMemo(()=>new pt.ContentFactory({editorFactory:O.editorServices.factoryService.newInlineEditor}),[O.editorServices.factoryService.newInlineEditor]);_.useEffect(()=>{const p=new on({model:new rn}),v=new Z,j=Oe(r.inlineProviders),D=r.providers&&r.providers.length>0?[new ce,...r.providers]:[new ce],k=new Ne({context:{widget:v},providers:D,inlineProviders:r.inlineProviders,inlineProvidersSettings:j,timeout:Re});let w;if(r.inlineProviders&&r.inlineProviders.length>0){const ie=_e.load("jupyterlab");w=new te({model:new te.Model,trans:ie});const N={};r.inlineProviders?.forEach(G=>{N[G.identifier]={enabled:!0}}),w.configure({...te.defaultSettings,showWidget:"always",showShortcuts:!0,streamingAnimation:"none",suppressIfTabCompleterActive:!1,minLines:1,maxLines:10,editorResizeDelay:250,reserveSpaceForLongest:!1,providers:N}),Z.attach(w,document.body);const q=G=>{if(G.key==="Tab"&&!G.shiftKey&&!G.ctrlKey&&!G.metaKey&&!G.altKey){if(w&&w.model&&w.current)return G.preventDefault(),G.stopPropagation(),w.accept(),!1;w&&w.model&&w.model.reset()}if(G.key==="Escape"&&w&&w.model&&w.current)return G.preventDefault(),G.stopPropagation(),w.model.reset(),!1};document.addEventListener("keydown",q,!0);const re=()=>{document.removeEventListener("keydown",q,!0)};w._keyboardCleanup=re}const $=new an({completer:p,reconciliator:k,inlineCompleter:w});return p.hide(),Z.attach(p,document.body),y($),()=>{queueMicrotask(()=>{$.dispose(),p.dispose(),w&&(w._keyboardCleanup&&w._keyboardCleanup(),w.dispose()),v.dispose()})}},[r.inlineProviders]);const[oe,Ce]=_.useState(null);_.useEffect(()=>{const p=new Zn({name:"Notebook",label:"Notebook",modelName:"notebook",fileTypes:["notebook"],defaultFor:["notebook"],preferKernel:!0,autoStartDefault:!1,canStartKernel:!1,shutdownOnClose:!1,rendermime:O.rendermime,contentFactory:ye,mimeTypeService:O.editorServices.mimeTypeService,notebookConfig:{...Fe.defaultNotebookConfig,windowingMode:"none",recordTiming:!0}});return Ce(p),()=>{p.dispose(),Ce(v=>v===p?null:v)}},[ye,O]);const B=_.useMemo(()=>new ln,[]),[V,X]=_.useState(null);_.useEffect(()=>{const p=g?new Xn({namespace:E}):null,v=g?dn(O.commands,g,p,B,r.path):null;return X(p),()=>{v?.dispose(),p?.dispose(),X(j=>j===p?null:j)}},[g,E,O.commands,r.path,B]);const[F,be]=_.useState(null),ze=_.useRef(n);_.useEffect(()=>{const p=new Is(a),v=new Yn({factory:p,manager:i??new Ls,path:K,kernelPreference:ze.current?{id:ze.current,shouldStart:!1,canStart:!1,autoStartDefault:!1,shutdownOnDispose:!1}:{shouldStart:!1,canStart:!1,autoStartDefault:!1,shutdownOnDispose:!1}});return Ns(v,E,!s&&!ws(K)?K:void 0,l,!i),be(v),()=>{v.dispose(),p.dispose(),be(j=>j===v?null:j)}},[E,i,a,K]),_.useEffect(()=>{if(!F||!n||F.sessionContext.isDisposed)return;(async()=>{try{if(F.sessionContext.session||await F.sessionContext.initialize(),F.sessionContext.isDisposed)return;await F.sessionContext.changeKernel({id:n})}catch(v){console.error("Failed to change kernel model.",v)}})()},[F,n]);const[P,Ke]=_.useState(null);return _.useEffect(()=>{let p=null,v=null,j=null;if(F&&(p=oe?.createNew(F)??null,p)){B.setPanel(p,F),v=new ys(O.commands,p,F,c),S(v),L(t.map(k=>(k.init({notebookId:E,commands:O.commands,panel:p}),k.createNew(p,F),k.component??u.jsx(u.Fragment,{}))));const D=p.content.rendermime;j=new In(F,D,{saveState:!1}),D.addFactory({safe:!0,mimeTypes:[cn],defaultRank:1,createRenderer:k=>new st(k,j)},1);for(const k of p.content.widgets)if(k.model.type==="code")for(const w of k.outputArea.widgets)for(const $ of Array.from(w.children()))$ instanceof st&&($.manager=j);f(!1)}return Ke(p),p||(L([]),S(null)),()=>{B.setPanel(null,null),queueMicrotask(()=>{if(j?.dispose(),v&&v.dispose(),p&&!p.isDisposed){p.content&&A.clearData(p.content);try{p.isAttached&&Z.detach(p),p.dispose()}catch{}}}),Ke(D=>D===p?null:D),S(D=>D===v?null:D)}},[F,t,O.commands,oe,B]),_.useEffect(()=>{if(C(!1),!!P)return cs(P,{synced:d,onPainted:()=>C(!0)})},[P,d]),_.useEffect(()=>{if(M){const p=ne.getState().notebooks,v=new Map(p);v.set(E,{adapter:M,model:M.model??void 0,portals:[]}),ne.getState().setNotebooks(v)}else{const p=ne.getState().notebooks;if(p.has(E)){const v=new Map(p);v.delete(E),ne.getState().setNotebooks(v)}}},[M,E]),_.useEffect(()=>{if(!P)return;const p=P.context.sessionContext,v=[],j=N=>{N&&ne.getState().changeKernelStatus({id:E,kernelStatus:N})},D=(N,q)=>{j(q)};p.statusChanged.connect(D);let k=null;const w=(N,q)=>{j(q)},$=()=>{const N=p.session?.kernel??null;if(N!==k&&(k?.statusChanged.disconnect(w),k=N,k?.statusChanged.connect(w),j(k?.status),N)){const q=()=>{k!==N||N.status!=="unknown"||kn.KernelAPI.getKernelModel(N.id,N.serverSettings).then(re=>{re?.execution_state&&k===N&&N.status==="unknown"&&(j(re.execution_state),v.push(setTimeout(q,5e3)))}).catch(()=>{})};q(),N.status==="unknown"&&Promise.resolve(N.requestKernelInfo?.()).catch(()=>{})}},ie=()=>$();return p.kernelChanged.connect(ie),$(),p.ready.then($),()=>{v.forEach(clearTimeout),p.statusChanged.disconnect(D),p.kernelChanged.disconnect(ie),k?.statusChanged.disconnect(w)}},[P,E]),_.useEffect(()=>{let p=!0,v=null,j=null;return P&&(V&&!P.isDisposed&&!V.has(P)&&V.add(P).catch(D=>{console.error(`Failed to track the notebook panel '${E}'.`)}),g&&(v=(D,k)=>{k&&k.ready.then(()=>{g.editor=k?.editor})},j=(D,k)=>{if(!p)return;const w=P.content.activeCell?.editor,$=new ce,ie=Oe(r.inlineProviders),N=k.newValue||{},q=r.providers&&r.providers.length>0?[$,...r.providers]:[$],re=new Ne({context:{widget:P,editor:w,session:N},providers:q,inlineProviders:r.inlineProviders,inlineProvidersSettings:ie,timeout:Re});g.inlineCompleter&&(g.inlineCompleter.editor=w),g.editor=w,g.reconciliator=re},P.context.sessionContext.sessionChanged.connect(j),P.context.sessionContext.ready.then(()=>{j?.(P.context.sessionContext,{name:"session",oldValue:null,newValue:P.context.sessionContext.session})}),P.content.activeCellChanged.connect(v))),()=>{if(p=!1,g){v&&P?.content.activeCellChanged.disconnect(v),j&&P?.context.sessionContext.sessionChanged.disconnect(j),g.editor=null;const D=Oe(r.inlineProviders),k=r.providers&&r.providers.length>0?[new ce,...r.providers]:[new ce];g.reconciliator=new Ne({context:{widget:new Z},providers:k,inlineProviders:r.inlineProviders,inlineProvidersSettings:D,timeout:Re})}}},[g,P,V]),_.useEffect(()=>{const p=P?.node;if(!p)return;const v=j=>{const D=j.target;!D||!p.contains(D)||O.commands.processKeydownEvent(j)};return window.addEventListener("keydown",v,!0),()=>{window.removeEventListener("keydown",v,!0)}},[O.commands,P]),_.useEffect(()=>()=>{const p=ne.getState().notebooks;if(p.has(E)){const v=new Map(p);v.delete(E),ne.getState().setNotebooks(v)}},[E]),u.jsxs(u.Fragment,{children:[I.map((p,v)=>u.jsx(ue,{children:p},`${p}-${v}`)),h?u.jsx(Be,{},"notebook-loader"):P?u.jsxs(ue,{sx:{height:"100%",position:"relative"},children:[u.jsx(hn,{id:E,children:P},"notebook-container"),m?null:u.jsx(ue,{sx:{position:"absolute",inset:0,zIndex:1,overflow:"hidden",bg:x??"var(--bgColor-default)"},children:u.jsx(Be,{})},"notebook-first-paint")]}):u.jsx(Bn,{variant:"critical",description:"Unable to create the notebook view.",hideTitle:!0,title:"Error"},"notebook-error")]})}function Ps(r={}){const{kernel:e,kernels:t,requestedKernelId:n,startDefaultKernel:s=!1}=r,o=e?.id,[i,a]=_.useState(o),[l,d]=_.useState(void 0);return _.useEffect(()=>{let c=!0;if(o){a(h=>h!==o?o:h);return}return t&&(async()=>{let h;if(await t.ready,n){const f=()=>{for(const m of t.running())if(m.id===n)return!0;return!1};if(!f())try{await t.refreshRunning()}catch(m){console.warn("Failed to list the running kernels.",m)}f()&&(h=n)}if(!h&&s&&c){await t.refreshRunning();const f=[...t.running()];if(f.length>0){const m=t.connectTo({model:f[0]});c?(h=m.id,a(h)):m.dispose()}else{const m=await t.startNew();c?(h=m.id,a(h),d(m)):m.dispose()}}c&&a(f=>f!==h?h:f)})(),()=>{c=!1}},[t,o,n,s]),_.useEffect(()=>()=>{l&&l.shutdown().catch(c=>{console.warn(`Failed to shutdown kernel '${l?.id}'.`,c)}).finally(()=>{l?.dispose()})},[l]),i}function Ts(r){const{collaborationProvider:e,nbformat:t,readonly:n=!1,url:s,path:o,serviceManager:i,id:a}=r,[l,d]=_.useState(null);return _.useEffect(()=>{let c=!0;const h=new nn;if(e&&i&&a)(async()=>{try{const m=new Ae;if(await e.connect(m,a,{serviceManager:i,path:o}),c){const C=new Ve({collaborationEnabled:!0,disableDocumentWideUndoRedo:!0,sharedModel:m});C.readOnly=n,d(C),h.add({dispose:()=>{e.disconnect()},get isDisposed(){return!1}})}}catch(m){console.error("Failed to setup collaboration:",m)}})();else{const f=m=>{const C=new Ve;m&&Es(C,m,n),C.readOnly=n,d(C)};!t&&s?Ds(s).then(m=>{c&&f(m)}):f(t)}return()=>{c=!1,h.dispose()}},[e,t,n,s,o,i,a]),l}async function Ds(r){return fetch(r).then(e=>e.text()).then(e=>JSON.parse(e))}class As{_commands;_editorServices;_rendermime;constructor(e={}){this._commands=e.commands??new un;const t=new et;for(const d of et.getDefaultLanguages())t.addLanguage(d);t.addLanguage({name:"ipythongfm",mime:"text/x-ipythongfm",load:async()=>(await fn(()=>import("./index-BsGIdntV.js"),[],import.meta.url)).markdown({codeLanguages:c=>t.findBest(c)})});const n=mn.filter(d=>d.mimeTypes[0]!=="text/javascript").concat([pn,gn]).concat(e.renderers??[]);this._rendermime=new mt({initialFactories:n,latexTypesetter:vn(),markdownParser:_n(t)});const s=new bn(t),o=new tt;for(const d of tt.getDefaultThemes())o.addTheme(d);const i=new he;for(const d of he.getDefaultExtensions({themes:o}))i.addExtension(d);i.addExtension({name:"shared-model-binding",factory:d=>{const c=d.model.sharedModel;return he.createImmutableExtension(yn({ytext:c.ysource,undoManager:c.undoManager??void 0}))}}),i.addExtension({name:"remote-user-cursors",factory(d){const{awareness:c,ysource:h}=d.model.sharedModel;return he.createImmutableExtension(zn({awareness:c,ytext:h}))}});const a=Rs();a&&i.addExtension({name:"csp-nonce",factory(){return he.createImmutableExtension(Te.cspNonce.of(a))}});const l=new Cn({extensions:i,languages:t});this._editorServices={factoryService:l,mimeTypeService:s}}get commands(){return this._commands}get editorServices(){return this._editorServices}get rendermime(){return this._rendermime}}class Is extends Jn{model;constructor(e){super(),this.model=e}get collaborative(){return!1}createNew(e){return this.model}}function Ns(r,e,t,n,s=!1){const o=!t;r.sessionContext._initialize=async()=>{const i=r.sessionContext.sessionManager;await i.ready,await i.refreshRunning();const a=wn(i.running(),l=>l.kernel?.id===(r.sessionContext.kernelPreference.id??""));if(a)try{const l=i.connectTo({model:{...a,path:t??a.path,name:t??a.name},kernelConnectionOptions:{handleComms:!0}});r.sessionContext._handleNewSession(l)}catch(l){return r.sessionContext._handleSessionError(l),Promise.reject(l)}return await r.sessionContext._startIfNecessary()},r.dispose=()=>{r.isDisposed||(r._isDisposed=!0,r.sessionContext.dispose(),r._disposed.emit(void 0),A.clearData(r))},o&&(r._populate=async()=>{if(r._isPopulated=!0,r._isReady=!0,r._populatedPromise.resolve(void 0),r.isDisposed)return;const i=r._model.defaultKernelName||r.sessionContext.kernelPreference.name;r.sessionContext.kernelPreference={...r.sessionContext.kernelPreference,name:i,language:r._model.defaultKernelLanguage},s||r.sessionContext.initialize().then(a=>{a&&r._dialogs.selectKernel(r.sessionContext.sessionContext)})},r.initialize=async i=>{r.model.dirty=!1;const a=new Date().toISOString(),l={path:e,name:e,type:"notebook",content:void 0,writable:!0,created:a,last_modified:a,mimetype:"application/x-ipynb+json",format:"json"};r._updateContentsModel(l),await r._populate(),r.model.sharedModel.clearUndoHistory()}),r.sessionContext.sessionChanged.connect((i,a)=>{const l=a.newValue;n?.(l??void 0)}),r.sessionContext.kernelChanged.connect((i,a)=>{const l=a.newValue;l&&!l.handleComms&&(l.handleComms=!0)}),r.sessionContext.ready.then(()=>{n?.(r?.sessionContext.session??void 0)}),r.initialize(!t)}class Ls{_additionalDrives=new Set;contents=Object.freeze({fileChanged:{connect:()=>{}},getSharedModelFactory(e){return null},localPath:e=>{const t=e.split("/"),n=t[0].split(":");return n.length===1||!this._additionalDrives.has(n[0])?z.PathExt.removeSlash(e):z.PathExt.join(n.slice(1).join(":"),...t.slice(1))},normalize(e){const t=e.split(":");return t.length===1?z.PathExt.normalize(e):`${t[0]}:${z.PathExt.normalize(t.slice(1).join(":"))}`}});kernelspecs=Object.freeze({ready:new Promise(()=>{})});sessions=Object.freeze({ready:new Promise(()=>{})});ready=Promise.resolve()}function Rs(){const r=document.querySelector('meta[property="csp-nonce"]');return r?r.getAttribute("content"):null}const Os=Mn`
|
|
40
40
|
.dla-Box-Notebook .jp-Cell .dla-CellSidebar-Container {
|
|
41
41
|
display: none;
|
|
42
42
|
}
|