openpond 0.2.71 → 0.2.73
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/app-server.js +1 -1
- package/dist/chunks/{acp-VWPJ2EL4.js → acp-35QBGOMJ.js} +1 -1
- package/dist/chunks/{acp-agent-OZHZMQ6R.js → acp-agent-4PKMX52I.js} +1 -1
- package/dist/chunks/{app-layer-OHPIYEOJ.js → app-layer-42ZKHTPN.js} +1 -1
- package/dist/chunks/{app-server-evaluations-Y5UEF2Y7.js → app-server-evaluations-5JVNCET7.js} +1 -1
- package/dist/chunks/{app-server-harness-services-GUHAIIPS.js → app-server-harness-services-4E236TXE.js} +1 -1
- package/dist/chunks/{app-server-runtime-CH5STRJP.js → app-server-runtime-CI2NTKX7.js} +1 -1
- package/dist/chunks/{apps-DNLT6P4J.js → apps-EGFRTFAJ.js} +1 -1
- package/dist/chunks/chunk-2IECLXB2.js +2 -0
- package/dist/chunks/{chunk-XBAB3HMA.js → chunk-2IIVBBF5.js} +1 -1
- package/dist/chunks/{chunk-5LKEVB2P.js → chunk-3BIB6KKL.js} +1 -1
- package/dist/chunks/{chunk-PXQZOVSV.js → chunk-3V2XAYYA.js} +1 -1
- package/dist/chunks/{chunk-WAUFXZ5B.js → chunk-3XNUG4FO.js} +1 -1
- package/dist/chunks/{chunk-HUMNLSCV.js → chunk-4KG7GJ5O.js} +1 -1
- package/dist/chunks/chunk-5AV2EWFX.js +2 -0
- package/dist/chunks/{chunk-SNBFWBJI.js → chunk-5VQK3CCJ.js} +1 -1
- package/dist/chunks/{chunk-3JYPUOK4.js → chunk-645T6LH7.js} +1 -1
- package/dist/chunks/{chunk-QN4CFJQC.js → chunk-6IKIGVJF.js} +1 -1
- package/dist/chunks/{chunk-AT3ZYNX4.js → chunk-6KKWSUEW.js} +1 -1
- package/dist/chunks/{chunk-PHZZBXDO.js → chunk-A4HLKWQD.js} +1 -1
- package/dist/chunks/{chunk-6BTX66SV.js → chunk-AWUSAHXG.js} +1 -1
- package/dist/chunks/{chunk-33UVQ7DU.js → chunk-E5HDJCKK.js} +1 -1
- package/dist/chunks/{chunk-E57PUTV2.js → chunk-E7SQBMYW.js} +1 -1
- package/dist/chunks/{chunk-OFV26C2U.js → chunk-EAW5FHU4.js} +2 -2
- package/dist/chunks/{chunk-VV4K5YPD.js → chunk-EZ435RGA.js} +1 -1
- package/dist/chunks/{chunk-SSHE6B7Z.js → chunk-F64TR23C.js} +1 -1
- package/dist/chunks/{chunk-B7SCVTE6.js → chunk-FA3GXQYA.js} +1 -1
- package/dist/chunks/{chunk-WXG3G2O6.js → chunk-FCC24XUI.js} +1 -1
- package/dist/chunks/{chunk-U7D6Q744.js → chunk-FDYWGE2Y.js} +1 -1
- package/dist/chunks/{chunk-OTG77H7U.js → chunk-FRQYH4QD.js} +1 -1
- package/dist/chunks/{chunk-OEAKX5TS.js → chunk-G2P2PYEO.js} +1 -1
- package/dist/chunks/{chunk-KASHK2U5.js → chunk-H2YQ4AA2.js} +1 -1
- package/dist/chunks/{chunk-ZG3DBXQG.js → chunk-H5EHSILL.js} +1 -1
- package/dist/chunks/{chunk-DNNWMOMG.js → chunk-HIPKU57Y.js} +1 -1
- package/dist/chunks/{chunk-OQ4RWCYI.js → chunk-IXMY4EKS.js} +1 -1
- package/dist/chunks/{chunk-PLROXHG2.js → chunk-JAIFVT3D.js} +1 -1
- package/dist/chunks/{chunk-XNPTLJ5Z.js → chunk-JG6JA7YT.js} +1 -1
- package/dist/chunks/{chunk-PJJSQ4ZI.js → chunk-KE5PYRJ6.js} +1 -1
- package/dist/chunks/{chunk-RP4DPUN2.js → chunk-KH42V27F.js} +1 -1
- package/dist/chunks/{chunk-ASMQTMQB.js → chunk-KOLVSUOS.js} +1 -1
- package/dist/chunks/{chunk-D2V2Y3FB.js → chunk-KQ7RFPG5.js} +1 -1
- package/dist/chunks/{chunk-GUWNSMGH.js → chunk-LWF5MQJ4.js} +1 -1
- package/dist/chunks/{chunk-USTDWGR4.js → chunk-MHSSPMLB.js} +1 -1
- package/dist/chunks/{chunk-UMRQKE3W.js → chunk-MXDSB2C5.js} +1 -1
- package/dist/chunks/{chunk-IJJ7FYZE.js → chunk-O6L4NO3M.js} +1 -1
- package/dist/chunks/{chunk-SRJTQS2D.js → chunk-OBMMO5NC.js} +3 -3
- package/dist/chunks/{chunk-USKCFST5.js → chunk-ODH5XGE6.js} +1 -1
- package/dist/chunks/{chunk-OKPV6MBX.js → chunk-OFC5N6R3.js} +6 -6
- package/dist/chunks/{chunk-ESOIZG2G.js → chunk-ONR2AKRI.js} +4 -4
- package/dist/chunks/{chunk-IFMWAOBR.js → chunk-OUOOKEU3.js} +1 -1
- package/dist/chunks/{chunk-VJYOKU3C.js → chunk-OVEQAEKR.js} +1 -1
- package/dist/chunks/{chunk-7PDF2UX2.js → chunk-OXUS4QOT.js} +1 -1
- package/dist/chunks/{chunk-VND53FAU.js → chunk-P7RLDDPN.js} +1 -1
- package/dist/chunks/{chunk-TWLPZHH7.js → chunk-SUILNZQJ.js} +1 -1
- package/dist/chunks/{chunk-3JVZ7OCQ.js → chunk-TP222CV2.js} +1 -1
- package/dist/chunks/{chunk-AVEHWUML.js → chunk-TRXOE7TT.js} +1 -1
- package/dist/chunks/{chunk-O5ZOW474.js → chunk-U73T66FP.js} +1 -1
- package/dist/chunks/{chunk-ER2VONWQ.js → chunk-WAWVFSIQ.js} +1 -1
- package/dist/chunks/{chunk-F2EUZG2W.js → chunk-WBV6A6NS.js} +1 -1
- package/dist/chunks/{chunk-UKTPX2EE.js → chunk-WOYBWRRV.js} +1 -1
- package/dist/chunks/{chunk-7SOHV5BH.js → chunk-X4CN3FIN.js} +1 -1
- package/dist/chunks/{chunk-RJY4EI46.js → chunk-XN5BXPAT.js} +1 -1
- package/dist/chunks/{chunk-23YW5PAQ.js → chunk-XSDWRRZP.js} +1 -1
- package/dist/chunks/{chunk-LMLGEOKV.js → chunk-YIZE3M5S.js} +1 -1
- package/dist/chunks/{cli-5JARGJOD.js → cli-NHRYN2G3.js} +1 -1
- package/dist/chunks/{command-AI3SMEAH.js → command-54MMVWS2.js} +3 -3
- package/dist/chunks/{configuration-command-NPA46ZOT.js → configuration-command-XMXTU2FQ.js} +1 -1
- package/dist/chunks/{connected-app-executor-DLC23O43.js → connected-app-executor-WJEDXUA4.js} +1 -1
- package/dist/chunks/{connected-evidence-TVORI55Q.js → connected-evidence-NFQPO5E3.js} +1 -1
- package/dist/chunks/{connected-starting-assets-WGGBWH4K.js → connected-starting-assets-M54PSOEP.js} +1 -1
- package/dist/chunks/{continual-UHQI2EQD.js → continual-C2YWPEJZ.js} +1 -1
- package/dist/chunks/{core-commands-QNZUBKOC.js → core-commands-SY4I5FHE.js} +1 -1
- package/dist/chunks/{dataset-preparation-authoring-OBMJLGA4.js → dataset-preparation-authoring-CH6Z4NE6.js} +1 -1
- package/dist/chunks/{datasets-USJLJOEQ.js → datasets-2OQDMF7E.js} +1 -1
- package/dist/chunks/{desktop-test-IYHAOR47.js → desktop-test-VNMR5H4I.js} +1 -1
- package/dist/chunks/{evaluation-coordination-UJENK4WQ.js → evaluation-coordination-GULGPATI.js} +1 -1
- package/dist/chunks/{experiment-improvements-6GJMKIER.js → experiment-improvements-XNXTU6ZA.js} +1 -1
- package/dist/chunks/{experiments-FZHILSC6.js → experiments-DZX6ZU6F.js} +1 -1
- package/dist/chunks/{experiments-signal-E32CWBS4.js → experiments-signal-QDVPO3M5.js} +1 -1
- package/dist/chunks/{help-32DLAPJR.js → help-UCN67FN7.js} +1 -1
- package/dist/chunks/{host-profile-evaluation-tools-QAV2UGSB.js → host-profile-evaluation-tools-XMGGHVH3.js} +1 -1
- package/dist/chunks/{hosted-app-server-composition-5DVBKNV3.js → hosted-app-server-composition-U7WGMN5B.js} +1 -1
- package/dist/chunks/{hosted-experiment-improvement-YQ24C54D.js → hosted-experiment-improvement-VQN6PJKR.js} +1 -1
- package/dist/chunks/{hosted-harness-runtime-KLIORGWV.js → hosted-harness-runtime-O6E5LCGN.js} +1 -1
- package/dist/chunks/{hosted-profile-candidate-RCWFLOVJ.js → hosted-profile-candidate-HQ544PNP.js} +1 -1
- package/dist/chunks/{hosted-profile-compiler-UDG4BCEW.js → hosted-profile-compiler-K4OACT7S.js} +1 -1
- package/dist/chunks/{hosted-profile-evaluation-control-4R3L4FTK.js → hosted-profile-evaluation-control-TKYM73YY.js} +1 -1
- package/dist/chunks/{hosted-profile-evaluation-inspection-NA4SSY7N.js → hosted-profile-evaluation-inspection-HFCFUYQ4.js} +1 -1
- package/dist/chunks/{hosted-profile-evaluation-preparation-B4BW6JTB.js → hosted-profile-evaluation-preparation-OJ6AR5P5.js} +1 -1
- package/dist/chunks/{human-review-D6QCZLYN.js → human-review-DNVIVJRK.js} +1 -1
- package/dist/chunks/{import-UCG75PN5.js → import-QT5AKEA3.js} +1 -1
- package/dist/chunks/{local-harness-improvement-runtime-GZBMBZB2.js → local-harness-improvement-runtime-BWZBMOGL.js} +1 -1
- package/dist/chunks/{local-harness-taskset-review-YVP2ZQJG.js → local-harness-taskset-review-JL2XNXML.js} +1 -1
- package/dist/chunks/{opchat-APJUUTT7.js → opchat-7PWUXQSY.js} +1 -1
- package/dist/chunks/{opchat-bounded-chat-PBUSUAY2.js → opchat-bounded-chat-B3GOCGWY.js} +1 -1
- package/dist/chunks/{organizations-WK6EZ6L3.js → organizations-TWBMN7KF.js} +1 -1
- package/dist/chunks/{profile-BQMS7ALQ.js → profile-RVARQYG4.js} +1 -1
- package/dist/chunks/{project-action-payload-CGV77JSA.js → project-action-payload-65MTQMQW.js} +1 -1
- package/dist/chunks/{project-agent-XVFYTEUQ.js → project-agent-ZC33YRZE.js} +1 -1
- package/dist/chunks/{published-experiment-source-2CYFIRBL.js → published-experiment-source-L7BER6AE.js} +1 -1
- package/dist/chunks/{refiner-profile-service-OLJHA4DI.js → refiner-profile-service-56776J7B.js} +1 -1
- package/dist/chunks/{runtime-32KYSVZR.js → runtime-GN2H2R7L.js} +2 -2
- package/dist/chunks/{sandbox-command-OY3VZXGG.js → sandbox-command-HWIAH6JA.js} +1 -1
- package/dist/chunks/{sandbox-template-YOOSJ4FK.js → sandbox-template-MNZ6OXQQ.js} +1 -1
- package/dist/chunks/{saved-work-L4KNWLZB.js → saved-work-OMBDT3ZR.js} +1 -1
- package/dist/chunks/{send-turn-YLY3YNEQ.js → send-turn-VQRLIHOE.js} +1 -1
- package/dist/chunks/{setup-EU6CMRXQ.js → setup-C6673TJK.js} +1 -1
- package/dist/chunks/{src-3DJR7OAH.js → src-HHFJIPL5.js} +1 -1
- package/dist/chunks/{src-HYOTHMRX.js → src-UHNSXT34.js} +2 -2
- package/dist/chunks/{store-chat-resources-HISLEZZM.js → store-chat-resources-TYR7D2UP.js} +1 -1
- package/dist/chunks/{store-continual-support-reviews-ORWHS57V.js → store-continual-support-reviews-63YCKG3P.js} +1 -1
- package/dist/chunks/{store-conversation-serving-5UGYKEGJ.js → store-conversation-serving-PDSBGL3E.js} +1 -1
- package/dist/chunks/{store-create-improve-APLPTVYQ.js → store-create-improve-RYASTT56.js} +1 -1
- package/dist/chunks/{store-datasets-HDW6IYBL.js → store-datasets-PELTRO4A.js} +1 -1
- package/dist/chunks/{store-evaluation-results-KB2UDCF3.js → store-evaluation-results-OUTNEMAY.js} +1 -1
- package/dist/chunks/{store-human-review-IURNTX3C.js → store-human-review-GIMAXCJQ.js} +1 -1
- package/dist/chunks/{store-learned-preference-migration-validation-TH2LKQWV.js → store-learned-preference-migration-validation-DHOSHA6C.js} +1 -1
- package/dist/chunks/{store-local-experiments-M4V5RLHJ.js → store-local-experiments-AH4Z6RWX.js} +1 -1
- package/dist/chunks/{store-model-batch-review-DDZLWVTG.js → store-model-batch-review-UUW6ZLDH.js} +1 -1
- package/dist/chunks/{store-model-configuration-ATOFA5OH.js → store-model-configuration-4U5A6DU7.js} +1 -1
- package/dist/chunks/{store-model-project-preparation-ZRSCQEQR.js → store-model-project-preparation-MYHO43VH.js} +1 -1
- package/dist/chunks/{store-modification-recordings-YJIDUPVJ.js → store-modification-recordings-OZBLFYCT.js} +1 -1
- package/dist/chunks/{store-sidebar-file-bookmarks-WLMYDA4E.js → store-sidebar-file-bookmarks-NQ3ZLTGZ.js} +1 -1
- package/dist/chunks/{store-sidebar-preferences-AFMYIDWT.js → store-sidebar-preferences-L6J7J5WC.js} +1 -1
- package/dist/chunks/{store-subagents-KFPVSTRO.js → store-subagents-6FHGHQ6V.js} +1 -1
- package/dist/chunks/{store-task-inbox-L53OT6ZC.js → store-task-inbox-M7YZNCRF.js} +1 -1
- package/dist/chunks/{store-task-inventory-R2JJGAHW.js → store-task-inventory-TTJQAM3T.js} +1 -1
- package/dist/chunks/{store-taskset-drafts-FPNJPFPO.js → store-taskset-drafts-4GVHDLJJ.js} +1 -1
- package/dist/chunks/{store-training-DIBW7OMP.js → store-training-MGGTGTV2.js} +1 -1
- package/dist/chunks/{store-training-jobs-K7I4SXWW.js → store-training-jobs-XKDUX4SV.js} +1 -1
- package/dist/chunks/{store-training-models-LCSB37YY.js → store-training-models-4S4ZT3BL.js} +1 -1
- package/dist/chunks/{taskset-XI5SJBJL.js → taskset-SLQSCYJI.js} +1 -1
- package/dist/chunks/{teams-bot-CYC5TR64.js → teams-bot-7U6JOV6T.js} +1 -1
- package/dist/chunks/{tool-learning-52QZIJIR.js → tool-learning-25Z2JOBS.js} +1 -1
- package/dist/chunks/{training-GDLLLXSV.js → training-2LUQ2IZM.js} +1 -1
- package/dist/chunks/{training-RL7UUBER.js → training-JA5ZQABE.js} +1 -1
- package/dist/chunks/{training-UJ62NOJJ.js → training-NL5GYZKU.js} +1 -1
- package/dist/chunks/training-hosted-NLXMISNL.js +2 -0
- package/dist/chunks/{training-hosted-alphaedit-R5PVATV4.js → training-hosted-alphaedit-WGMJ3L2D.js} +1 -1
- package/dist/chunks/{training-hosted-decision-WNK5DE3M.js → training-hosted-decision-66EUMUIW.js} +1 -1
- package/dist/chunks/{training-hosted-engram-ZQDOKXAV.js → training-hosted-engram-QDXSJ77I.js} +1 -1
- package/dist/chunks/{training-hosted-modification-comparison-KKI5CKOH.js → training-hosted-modification-comparison-2MH5FZMZ.js} +1 -1
- package/dist/chunks/{training-hosted-neuron-training-CFWEDRSR.js → training-hosted-neuron-training-3QXKIEKT.js} +1 -1
- package/dist/chunks/{training-hosted-serving-report-N4NF5AVW.js → training-hosted-serving-report-ZG75ACZK.js} +1 -1
- package/dist/chunks/{training-hosted-steering-4MDUQ2YV.js → training-hosted-steering-KFMTKCTX.js} +1 -1
- package/dist/chunks/{training-model-start-NOA6TYQK.js → training-model-start-NMQ55UHZ.js} +1 -1
- package/dist/chunks/{workspaces-EK62ANTB.js → workspaces-ROFG76XK.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/skills/manifest.json +1 -1
- package/dist/web/assets/{App-L7RV4D0A.js → App-CV1p0_Zy.js} +4 -4
- package/dist/web/assets/{AppDialog-B2V84J7f.js → AppDialog-DdGt7aU1.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-DfYpUDKT.js → AppTerminalPanel-B2p_tYh5.js} +2 -2
- package/dist/web/assets/{AppToastContext-DuiPouLz.js → AppToastContext-D7z0w1PS.js} +1 -1
- package/dist/web/assets/{AppsView-B20RHDCy.js → AppsView-B-Ts-M_V.js} +1 -1
- package/dist/web/assets/{AttachmentTypeIcon-l-GRNxaz.js → AttachmentTypeIcon-BJ5i12im.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-Ce0ToS2O.js → BrowserSidebar-BVHthjXU.js} +1 -1
- package/dist/web/assets/{CartesianChart-CtfMRAfp.js → CartesianChart-BuJ1wFS7.js} +1 -1
- package/dist/web/assets/{ChatTimelineEntry-DzcucW20.js → ChatTimelineEntry-CfiiTrK4.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-BpmKjNAC.js → CollaborationTabs-1t9zAhDC.js} +1 -1
- package/dist/web/assets/{CommandMenu-JXsoxijv.js → CommandMenu-DTB6xjGG.js} +1 -1
- package/dist/web/assets/{CommunityView-ggdn8pcH.js → CommunityView-BjeZ56id.js} +1 -1
- package/dist/web/assets/{ComposerAttachments-BMmALUs_.js → ComposerAttachments-C_K_05H9.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-DcM1bkfu.js → ComposerCreateImproveStrip-A38jnNGd.js} +1 -1
- package/dist/web/assets/{ConversationImportsSettings-BKNeARHI.js → ConversationImportsSettings-jwaoKQZt.js} +1 -1
- package/dist/web/assets/{DatasetReviewImport-DyFOE0Q0.js → DatasetReviewImport-DZA1s3XG.js} +1 -1
- package/dist/web/assets/{ExperimentTrainingDataWorkspace-CfOyoMrq.js → ExperimentTrainingDataWorkspace-DowPuAXk.js} +2 -2
- package/dist/web/assets/{FilePagePreview-B7bWObJN.js → FilePagePreview-11ZNRtdT.js} +2 -2
- package/dist/web/assets/{GetStartedView-BYbFl93M.js → GetStartedView-bLVKmjqg.js} +1 -1
- package/dist/web/assets/{GettingStartedDialog-UgreDozV.js → GettingStartedDialog-BeimFLZh.js} +1 -1
- package/dist/web/assets/{HostedModelLearningReview-C_kng2U_.js → HostedModelLearningReview-DiFVb3WK.js} +1 -1
- package/dist/web/assets/{HostedModelLearningSettings-aesD_ifF.js → HostedModelLearningSettings-DtUF5ejq.js} +1 -1
- package/dist/web/assets/{HtmlVisual-nvl1x-jh.js → HtmlVisual-CgVTWr64.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-DrdoNvI-.js → LabModelVersionDetailPage-BvinwnBN.js} +1 -1
- package/dist/web/assets/{LabModelWorkspace-CHlhzG3q.js → LabModelWorkspace-Q5DG2mLP.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-CqHeZzoj.js → LabSkillSidebar-cmhZzr4f.js} +1 -1
- package/dist/web/assets/{LabsRoute-DzEbPpMK.js → LabsRoute-DS_mlprv.js} +4 -4
- package/dist/web/assets/{LearningBatchesPage-A2dFQW2j.js → LearningBatchesPage-Cm-btgWc.js} +1 -1
- package/dist/web/assets/{MainChatThread-BSvKu4e5.js → MainChatThread-DbTn4Bag.js} +2 -2
- package/dist/web/assets/{MainPane-DiWIAxMj.js → MainPane-BtzUF6O_.js} +6 -6
- package/dist/web/assets/{ModelProjectPageHeader-lu6iRXHK.js → ModelProjectPageHeader-C4mgVJGx.js} +1 -1
- package/dist/web/assets/{NativeSetupTerminal-kZ-nFPE8.js → NativeSetupTerminal-bJpDkKk1.js} +2 -2
- package/dist/web/assets/{NativeSkillSidebar-DkkD1uH2.js → NativeSkillSidebar-BuToZvK-.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-Dg8dMEpc.js → NewProjectDialog-F0BPQy0S.js} +1 -1
- package/dist/web/assets/{OutputsPage-Dz190U9t.js → OutputsPage-DC4g59_8.js} +1 -1
- package/dist/web/assets/{PageChrome-Bncv-ps0.js → PageChrome-ufq2jePD.js} +1 -1
- package/dist/web/assets/{ProjectsPage-DVkYvLtd.js → ProjectsPage-7mbOvMfO.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-CP4leenI.js → RightChatPanelStack-sR9xN3RP.js} +1 -1
- package/dist/web/assets/RightSidebarHomePanel-joZavyR9.js +1 -0
- package/dist/web/assets/{ScheduledWorkPage-DI0mgt82.js → ScheduledWorkPage-s9CN6nR_.js} +1 -1
- package/dist/web/assets/{SettingsView-cCtkr089.js → SettingsView-CZNWYK-D.js} +3 -3
- package/dist/web/assets/{TasksetDraftEditorPrimitives-DCQTuswJ.js → TasksetDraftEditorPrimitives-BnMqzE-T.js} +1 -1
- package/dist/web/assets/{TeamChatView-BBEomfQ7.js → TeamChatView-XthM6n4S.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-Dj5NUDMp.js → TerminalOverlay--HCFZaQW.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-Ds4PLfsd.js → TrainingCreationPanel-D2F6kPg_.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-BAuh_BF3.js → TrainingDraftPanel-BurWPp9F.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-DbzeatcW.js → UsageSettingsSection-D7jdscDm.js} +1 -1
- package/dist/web/assets/WorkSidebarPanel-CmdXCmrZ.js +1 -0
- package/dist/web/assets/{WorkspaceDiffPanel-xk-ve1MO.js → WorkspaceDiffPanel-CPaCC1_p.js} +3 -3
- package/dist/web/assets/{WorkspaceEnvironmentMenu-D8GSuoYz.js → WorkspaceEnvironmentMenu-BZxu6mUS.js} +1 -1
- package/dist/web/assets/{WorkspaceFileLocation-Dl8M2ZKN.js → WorkspaceFileLocation-C4K_D_yh.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-9BhLjYx4.js → WorkspaceGitDialogs-C0Yf29V0.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-DYPuC7pj.js → WorkspaceMonacoEditor-BRPLaFZS.js} +3 -3
- package/dist/web/assets/{WorkspacePdfPreview-B7BI9tLR.js → WorkspacePdfPreview-9wypyV6H.js} +2 -2
- package/dist/web/assets/{WorkspacePresentationPreview-sP7JUT7m.js → WorkspacePresentationPreview-C-Cn-9pj.js} +1 -1
- package/dist/web/assets/{bot-D7M8ZtE6.js → bot-BuaAVlz6.js} +1 -1
- package/dist/web/assets/{chat-resources-DhKAnljP.js → chat-resources-DMPHClhQ.js} +1 -1
- package/dist/web/assets/chevron-down-CkifKd_O.js +1 -0
- package/dist/web/assets/chevron-right-LsMXJ5SB.js +1 -0
- package/dist/web/assets/chevron-up-Dt5T2Sf5.js +1 -0
- package/dist/web/assets/{chunk-C3TS766N-DENE60SE.js → chunk-C3TS766N-BXUEjt7d.js} +1 -1
- package/dist/web/assets/{client-gy7zrd7a.js → client-C-ZuakZR.js} +1 -1
- package/dist/web/assets/{client-choice-storage-DYZsrVr9.js → client-choice-storage-DWIA0Vou.js} +1 -1
- package/dist/web/assets/{cloud-upload-De-XSMUr.js → cloud-upload-B5LqiNCG.js} +1 -1
- package/dist/web/assets/{copy-DEK20zbZ.js → copy-BYIypHbq.js} +1 -1
- package/dist/web/assets/{cssMode-Dau-Fhqf.js → cssMode-ByypIqUN.js} +1 -1
- package/dist/web/assets/{external-link-DwDry0Fb.js → external-link-Cv7TDVPT.js} +1 -1
- package/dist/web/assets/{folder-open-DOb4AjV6.js → folder-open-DlIP3g5o.js} +1 -1
- package/dist/web/assets/{folder-plus-BAouDaXv.js → folder-plus-CXwFJqcY.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-DZbHXcai.js → git-commit-horizontal-DMh_-WxU.js} +1 -1
- package/dist/web/assets/{htmlMode-DlNEe6hu.js → htmlMode-CQGeb-h5.js} +1 -1
- package/dist/web/assets/{icons-OQhKVrDc.js → icons-CYvTltSH.js} +1 -1
- package/dist/web/assets/{image-BkYJDChH.js → image-Ci1JxTQX.js} +1 -1
- package/dist/web/assets/{index-M_h2Ok4V.js → index-CDtTBysF.js} +2 -2
- package/dist/web/assets/{info-Mj5lp4Ic.js → info-EjyMkVzV.js} +1 -1
- package/dist/web/assets/{jsonMode-CyOEyonV.js → jsonMode-Dm6YK6Dw.js} +1 -1
- package/dist/web/assets/loader-circle-AjP2mDJA.js +1 -0
- package/dist/web/assets/{lspLanguageFeatures-DAYPzatg.js → lspLanguageFeatures-BjtOz-Ln.js} +1 -1
- package/dist/web/assets/{maximize-2-BwFXSX6b.js → maximize-2-CvvoALtI.js} +1 -1
- package/dist/web/assets/{message-square-C2nqfNLn.js → message-square-CPtIPRtf.js} +1 -1
- package/dist/web/assets/{monaco.contribution-KyLdVay7.js → monaco.contribution-ClH8Tmjq.js} +2 -2
- package/dist/web/assets/{monaco.contribution-BZcNCJER.js → monaco.contribution-VSFFgrfZ.js} +2 -2
- package/dist/web/assets/{monaco.contribution-D7_X8TXe.js → monaco.contribution-e5DNaEix.js} +2 -2
- package/dist/web/assets/{monaco.contribution-BZkfRhss.js → monaco.contribution-wpC0-Kxw.js} +2 -2
- package/dist/web/assets/{monitor-B0Qj5Wea.js → monitor-BroZpIvk.js} +1 -1
- package/dist/web/assets/{paperclip-CmrRruxi.js → paperclip-DYZEL_Gi.js} +1 -1
- package/dist/web/assets/{pdf-BM-9_48p.js → pdf-DkU37Bi0.js} +1 -1
- package/dist/web/assets/play-BrvX67t1.js +1 -0
- package/dist/web/assets/plus-DFjCZeRE.js +1 -0
- package/dist/web/assets/{presentation-BYxhoSIo.js → presentation-CddfsTzp.js} +1 -1
- package/dist/web/assets/{python-B3Mj03I5.js → python-CMdyfF2B.js} +1 -1
- package/dist/web/assets/{refresh-cw-CwEmO71D.js → refresh-cw-Cx_7Zlbl.js} +1 -1
- package/dist/web/assets/{save-S--FOuce.js → save-BaeHeBBw.js} +1 -1
- package/dist/web/assets/{settings-lists-ChqDppMP.js → settings-lists-CVg9h-5z.js} +1 -1
- package/dist/web/assets/square-Di5JBnVr.js +1 -0
- package/dist/web/assets/{square-terminal-CawpQtCi.js → square-terminal-CBlQtWQw.js} +1 -1
- package/dist/web/assets/{submit-issue-command-CFitxxmO.js → submit-issue-command-L5--gt9i.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-D-cMCvXx.js → toggleHighContrast-hftC_Rxs.js} +1 -1
- package/dist/web/assets/training-CGYukv2L.js +1 -0
- package/dist/web/assets/{training-model-data-G-D64935.js → training-model-data-vvvphDlO.js} +1 -1
- package/dist/web/assets/{tsMode-9kzS1ijG.js → tsMode-B0sZU1HD.js} +1 -1
- package/dist/web/assets/{upload-CtYsSYrM.js → upload-Bzt1ooBz.js} +1 -1
- package/dist/web/assets/{useAccountSettings-DYYa6puz.js → useAccountSettings-BnxwetkP.js} +1 -1
- package/dist/web/assets/{useAgentInventory-c5B_Tszj.js → useAgentInventory-D_qS4ols.js} +1 -1
- package/dist/web/assets/{useChatContextSelection-DOISZpTz.js → useChatContextSelection-D8aSVtCm.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-QJ8RsMKm.js → useLocalAgentSchedules-CUQ1MW4l.js} +1 -1
- package/dist/web/assets/{useQuery-DuTGOe2b.js → useQuery-9SCnxwmR.js} +1 -1
- package/dist/web/assets/{wifi-off-BOfP4Vmg.js → wifi-off-DWtVm7W7.js} +1 -1
- package/dist/web/assets/{workers-BwGpyrdj.js → workers-B3jA6AOv.js} +1 -1
- package/dist/web/assets/x-EG07vYCF.js +1 -0
- package/dist/web/assets/{yaml-BU4IWV_7.js → yaml-BEUL30-5.js} +1 -1
- package/dist/web/index.html +1 -1
- package/docs/command-reference.md +3 -1
- package/package.json +1 -1
- package/dist/chunks/chunk-NK2L5HA2.js +0 -2
- package/dist/chunks/chunk-XJU47QS2.js +0 -2
- package/dist/chunks/training-hosted-V5CHG3M3.js +0 -2
- package/dist/web/assets/RightSidebarHomePanel-C0etQXpt.js +0 -1
- package/dist/web/assets/WorkSidebarPanel-BaNuXoZc.js +0 -1
- package/dist/web/assets/chevron-down-BAEcJitl.js +0 -1
- package/dist/web/assets/chevron-right-3G9s2cQ9.js +0 -1
- package/dist/web/assets/chevron-up-DTYF52H1.js +0 -1
- package/dist/web/assets/loader-circle-DXVtGvuV.js +0 -1
- package/dist/web/assets/play-CkACZ6Zo.js +0 -1
- package/dist/web/assets/plus-CB258e62.js +0 -1
- package/dist/web/assets/square-BmPfHjGU.js +0 -1
- package/dist/web/assets/training-CzbWtx75.js +0 -1
- package/dist/web/assets/x-5_iy6IDd.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
3
|
-
import{a as Bq,b as $q,c as Nq}from"./chunk-YXMYK5P7.js";import"./chunk-S4WILIRA.js";import{c as kq}from"./chunk-MPEK4ZNY.js";import{a as Sq,b as Pq,c as Rq,d as xq,e as _q,f as Eq,g as Tq,h as Cq,i as Aq,j as Mq}from"./chunk-6BTX66SV.js";import{a as or,b as Op,c as xa,d as iy,e as sy,f as Ei}from"./chunk-27OJ2OLP.js";import{a as jq,b as Oq,c as Hq,d as M,e as Dq,f as Ti,g as z,h as cy,j as Lq}from"./chunk-PXQZOVSV.js";import{a as ay,b as Iq}from"./chunk-5JVJQA5H.js";import{a as DU,b as zU,c as hR,d as WU,e as VU,f as GU,g as JU,h as KU,j as YU}from"./chunk-ZG3DBXQG.js";import{A as fR,a as jU,c as OU,g as HU,k as ey,l as Fo,m as LU,n as Pa,o as ty,p as BU,q as Ri,r as ry,s as $U,t as Ra,u as ny,v as xi,w as NU,x as UU,y as qU,z as FU}from"./chunk-OEAKX5TS.js";import{a as XU,b as QU,c as oy,d as ZU,e as _i,f as Je,g as eq,h as Pe,i as tq,j as rq,k as nq,l as oq,m as aq,n as iq,o as sq,p as cq,q as dq,r as lq,s as uq,t as $r,u as Pr,v as pe,w as pq}from"./chunk-GUWNSMGH.js";import{a as mq,b as fq}from"./chunk-YFHQRDNQ.js";import{a as hq,b as gq}from"./chunk-AT3ZYNX4.js";import{c as mR}from"./chunk-UMRQKE3W.js";import{a as wq,b as yq,c as vq}from"./chunk-VV4K5YPD.js";import"./chunk-33UVQ7DU.js";import{a as Yw,b as vU,c as IU,d as bU,e as kU}from"./chunk-TWLPZHH7.js";import{a as Sa,c as Ww,d as Ud,e as mU,f as fU,g as kr,h as hU,i as Gw,j as gU,k as Sr,l as Jw,m as wU,n as Yr,o as Kw,p as yU,r as RU}from"./chunk-ER2VONWQ.js";import{a as Xw,b as SU,c as pR}from"./chunk-EFP75UEX.js";import{b as PU,c as Qw}from"./chunk-XBAB3HMA.js";import{a as un}from"./chunk-XTT3K3TR.js";import"./chunk-S7A2OGL2.js";import{a as uU,e as Vw}from"./chunk-HUMNLSCV.js";import{a as xS,b as WM}from"./chunk-EICS777E.js";import{a as xU}from"./chunk-OQ4RWCYI.js";import"./chunk-WLQEONBF.js";import"./chunk-USTDWGR4.js";import{b as _U}from"./chunk-EXAJ2B4I.js";import{a as EU,b as Zw,c as TU,d as CU,e as AU}from"./chunk-OTG77H7U.js";import{b as MU}from"./chunk-PJJSQ4ZI.js";import{a as nU,b as oU,c as Uw,d as qw}from"./chunk-XVDFJ3ZF.js";import{b as lU}from"./chunk-B7SCVTE6.js";import{b as dU,c as lR}from"./chunk-Q3WXB465.js";import"./chunk-UKTPX2EE.js";import{a as cU}from"./chunk-FEAKTSRS.js";import"./chunk-OIIE5GUK.js";import{a as oo,b as zw,c as uR,d as pU}from"./chunk-TPOAAJKA.js";import"./chunk-CX4T7I47.js";import{a as eU,b as tU,c as rU}from"./chunk-I6KTJ3GH.js";import{h as oe}from"./chunk-O5ZOW474.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{a as K2,b as $w}from"./chunk-NDNSLCPE.js";import{a as Ns,b as Nw,c as Q2,d as Z2}from"./chunk-IUYGQO2K.js";import"./chunk-W45RKGM6.js";import"./chunk-CWE2N3JI.js";import{a as Lw,d as Bw,f as Y2,g as X2}from"./chunk-O4YHISU2.js";import{a as J2}from"./chunk-Z5R4OSGC.js";import{b as V2,c as G2,d as Nd,f as Dw,g as Mp}from"./chunk-QKGNAYSC.js";import{b as jp,c as ka}from"./chunk-HT6ILPD6.js";import"./chunk-BTEBZYK3.js";import{a as no,b as z2,c as W2}from"./chunk-MWS2NAHJ.js";import{a as D2,d as L2,f as B2,g as $2,h as N2,i as ba,j as U2,k as Hw,n as Ap}from"./chunk-F2EUZG2W.js";import{a as q2,b as F2}from"./chunk-CBD554GZ.js";import{c as U$,d as uw,i as q$}from"./chunk-D2V2Y3FB.js";import{b as jw,d as $d,l as E2,n as Ow}from"./chunk-RP4DPUN2.js";import"./chunk-DRMOHADV.js";import{A as dg,c as sg,d as tH,e as rH,f as nH,h as oH,i as aH,j as iH,p as sH,u as wi,v as cH,x as dH,z as cg}from"./chunk-OTXGAKFH.js";import{a as yH,d as vH,g as EH}from"./chunk-VMW23TIZ.js";import{a as a$,b as d$,c as l$,d as O$,e as lw,f as B$,g as $$,h as N$,i as F$,j as TN,k as O2,m as bq}from"./chunk-SRJTQS2D.js";import{a as aU}from"./chunk-ESOIZG2G.js";import{a as pt,b as i$,c as s$,d as JP,e as tN,f as mw,g as fw,h as rN}from"./chunk-PKJHN666.js";import{a as iU,b as Fw,c as sU}from"./chunk-5LKEVB2P.js";import{b as Ad,c as Md,d as VP}from"./chunk-JH4RACOB.js";import{b as dw}from"./chunk-JVEIK4RH.js";import{$ as k2,A as MN,B as Kr,C as jN,D as ON,E as NN,F as UN,G as qN,H as FN,I as zN,J as t2,K as r2,L as aR,M as n2,N as l2,O as u2,P as p2,Q as f2,R as iR,S as w2,T as Cw,U as Ls,V as qo,W as to,X as I2,Y as Tp,Z as b2,_ as ro,aa as Aw,b as u$,ba as S2,c as _$,ca as P2,d as E$,da as br,e as C$,ea as Bs,f as G$,fa as R2,g as Od,ga as Ia,h as J$,ha as sR,i as X$,ia as cR,j as Q$,ja as Cp,k as nN,ka as dR,l as vN,la as Mw,m as IN,ma as _2,n as bN,na as T2,o as kN,oa as H2,p as SN,q as QP,r as PN,s as RN,t as xN,u as _N,x as EN,y as CN,z as ZP}from"./chunk-OFV26C2U.js";import{g as C2,h as A2,i as M2,j as j2}from"./chunk-USKCFST5.js";import{a as T$}from"./chunk-PYNW5OFA.js";import{A as eR,B as tR,F as WN,M as y2,a as W$,b as V$,c as GP,m as yN,q as yw}from"./chunk-23YW5PAQ.js";import{b as $s,c as x2,d as Br}from"./chunk-RHMULF56.js";import"./chunk-VFH5C6D2.js";import{a as g2}from"./chunk-UOFDKMRU.js";import{a as wN}from"./chunk-AN525SPP.js";import{a as z$}from"./chunk-IZ6DLEVY.js";import{a as Hs,b as UP,c as Sp,d as Pp,e as Td,f as aw,g as qP,h as Rp,i as Cn,j as R$,k as fe,l as x$,m as zP}from"./chunk-DNRC6TPJ.js";import{b as h$}from"./chunk-6YR5IYHH.js";import"./chunk-SYUKES6H.js";import{a as H$,b as D$,c as L$,d as cw}from"./chunk-XLZMSD5K.js";import"./chunk-SVLVIYH2.js";import{B as m2,J as v2,b as VM,z as AN}from"./chunk-6I5AUTVO.js";import{b as A$,i as M$,j as j$,m as Cd,n as WP}from"./chunk-BQNU4HZW.js";import{a as kp,b as bi}from"./chunk-OOKHHOIU.js";import{a as NP,g as p$,h as m$,j as f$}from"./chunk-JCHLDNCX.js";import"./chunk-7PXZ4X4P.js";import"./chunk-N73MU2C3.js";import"./chunk-7SOHV5BH.js";import"./chunk-AVEHWUML.js";import"./chunk-SNBFWBJI.js";import{A as Pi,B as oR,C as Sw,D as XN,E as Pw,F as QN,G as _p,J as Rw,K as ZN,L as xw,M as e2,N as Bd,d as HN,f as DN,g as LN,h as BN,i as $N,m as vw,n as Iw,o as VN,p as GN,q as Ld,r as JN,s as rR,t as KN,u as bw,v as kw,w as Uo,x as Ds,y as nR,z as YN}from"./chunk-IFMWAOBR.js";import"./chunk-VS2LOUCT.js";import"./chunk-DMFUEUAZ.js";import"./chunk-AFKFN25T.js";import"./chunk-G4747MOW.js";import{a as $o,b as No,c as Wt}from"./chunk-GF55VEMR.js";import"./chunk-FAKDGLZQ.js";import"./chunk-KCJVFLBB.js";import{a as Z$,b as eN}from"./chunk-GW766ZSO.js";import{a as s2,b as c2,c as d2,d as Tw,f as h2}from"./chunk-VJYOKU3C.js";import{a as o2,b as Ep,c as a2,d as _w,e as i2,f as Ew}from"./chunk-SSJV3VX7.js";import{a as jd}from"./chunk-7KWD2I6W.js";import{a as Dr,b as g$,c as Lr,d as w$,e as iw,f as sw,g as FP,h as y$,i as ki,k as v$,l as I$,m as b$,n as k$,o as S$,p as P$}from"./chunk-2ACX7IW5.js";import{A as NM,C as UM,D as qM,E as Qn,d as RM,e as xM,f as _M,g as EM,h as SS,i as TM,j as CM,k as AM,l as MM,m as jM,n as xh,o as OM,p as PS,q as HM,r as DM,s as rr,t as LM,u as ut,v as St,w as BM,x as $M,y as Du,z as _h}from"./chunk-OFJPOTES.js";import{c as lN,d as KP,e as uN,f as pN,g as mN,h as fN,i as Dd,j as ww,k as Bo,l as hN,m as YP,n as gN,o as XP}from"./chunk-PLROXHG2.js";import{A as dN,C as gw,b as pw,d as K$,e as Y$,h as oN,k as aN,l as iN,m as Hd,n as sN,p as hw,q as cN,s as xp}from"./chunk-YU3C6U5V.js";import"./chunk-PHZZBXDO.js";import{a as Si}from"./chunk-KVTBX2UP.js";import{a as ye,b as zt,c as Ed,d as ce,f as c$}from"./chunk-U7D6Q744.js";import{$ as nL,$a as ML,$b as cp,$c as $P,A as AD,Aa as fL,Ac as KB,Ba as hL,Ca as gL,Cb as Zg,Cc as YB,Db as AB,Dc as XB,E as MD,Ea as Pd,Eb as MB,Ec as Os,F as jD,Fa as wL,Fb as Lo,Fc as QB,G as Lg,Gb as jB,H as OD,Ha as tp,Hb as js,I as qD,Ia as Fg,Ib as OB,Ic as st,J as FD,Ja as yL,Jc as HP,K as Oo,Ka as SP,Kc as up,La as vL,Lc as pp,M as zD,Ma as IL,Mc as ZB,N as WD,Na as PP,Nc as DP,O as VD,Oa as bL,Oc as mp,P as GD,Pa as kL,Pc as fp,Q as JD,Qa as SL,Qc as e$,Ra as PL,Rc as LP,S as KD,Sa as RL,Sc as hp,T as Bg,Ta as xL,Tc as gp,U as YD,Ua as _L,Uc as t$,V as XD,Va as RP,Vb as HB,Vc as wp,W as QD,Wa as EL,Wc as r$,X as ZD,Xa as TL,Xb as DB,Xc as BP,Y as eL,Ya as CL,Yb as ip,Yc as yp,Z as tL,Za as AL,Zb as LB,Zc as vp,_ as rL,_a as xP,_b as sp,_c as n$,aa as oL,ab as jL,ac as MP,ad as Ip,b as bd,ba as aL,bb as OL,bc as BB,bd as bp,ca as iL,cb as HL,cc as dp,cd as o$,da as sL,db as DL,dc as $B,e as yD,ea as cL,eb as LL,ec as ew,fb as BL,fc as NB,g as vP,ga as $g,gb as $L,gc as UB,h as vD,ha as dL,hb as NL,hc as qB,i as Hr,ia as Zn,ic as FB,j as Qu,ja as Ng,jc as tw,k as Ts,ka as kP,kb as UL,kc as rw,l as IP,la as Ug,lb as qL,m as ID,mb as FL,n as bD,na as qg,nb as zL,nc as zB,o as kD,oa as Zu,ob as WL,p as SD,pb as rp,pc as Ii,q as PD,qa as lL,r as RD,rb as zg,rc as nw,s as Dg,sb as VL,sc as WB,ta as Sd,tb as GL,tc as lp,ua as Ho,ub as JL,uc as ow,v as va,va as uL,vb as Cs,vc as VB,w as kd,wa as ep,wb as KL,wc as GB,x as TD,xc as jP,y as CD,ya as pL,yb as CB,yc as JB,za as mL,zc as OP}from"./chunk-WXG3G2O6.js";import{d as SM}from"./chunk-OQPJ7FJF.js";import"./chunk-BL3CZWWD.js";import{b as HD,c as DD,d as LD,e as BD,f as $D,g as ND,h as UD}from"./chunk-FYWQWKVS.js";import{b as xD,c as Hg}from"./chunk-GD3RCUDH.js";import{$ as Ms,A as Ir,C as lB,D as uB,E as pB,F as AP,G as mB,H as fB,I as hB,K as Jg,L as gB,a as Wg,aa as wB,b as YL,ba as eo,c as _P,ca as yB,d as Do,da as vB,e as XL,ea as IB,f as QL,fa as yi,g as ZL,ga as xd,h as EP,ha as Kg,i as As,ia as bB,j as eB,ja as kB,k as tB,ka as SB,l as rB,la as op,m as TP,ma as _d,n as np,na as Yg,o as nB,oa as PB,p as Vg,pa as Xg,q as oB,qa as vi,r as aB,ra as RB,s as Rd,sa as xB,t as iB,ta as _B,u as Gg,ua as Qg,v as sB,va as EB,w as cB,wa as ap,x as CP,xa as TB,z as dB}from"./chunk-OXRN2257.js";import"./chunk-UTIELP6F.js";import{g as TH,j as CH,l as yd,m as AH,o as pg,s as mg}from"./chunk-TOWY6Y23.js";import"./chunk-4V73I4OL.js";import"./chunk-LE75SVEL.js";import{e as _D,g as ED,h as bP,j as wt}from"./chunk-6ESBAHWK.js";import{a as jne,b as JM,c as _S,d as ES}from"./chunk-LZPCA6DH.js";import{b as dd,c as PM}from"./chunk-L3KS6MOV.js";import"./chunk-7J2NMUTK.js";import{$b as zu,$k as Z1,Ad as zH,Af as o1,Al as dD,Bd as WH,Be as YH,Bg as mP,Bh as hP,Bk as X1,Bl as Se,Df as uP,Ej as O1,Gj as H1,Hi as Xu,Hj as yP,Ii as P1,Ij as D1,Ji as R1,Mj as L1,Nj as B1,Od as VH,Oe as XH,Oh as m1,Pd as GH,Qh as f1,Qj as $1,Re as QH,Rf as a1,Rj as N1,Sd as Wu,Sg as d1,Sh as h1,Si as x1,Sj as U1,Ta as BH,Td as Vu,Th as g1,Ub as $H,Uf as Ig,Uj as q1,Vf as bg,Vg as xg,Vh as Ku,Vi as _1,Wf as kg,Wg as _g,Wh as w1,Wi as E1,Wj as F1,Xf as i1,Xg as Eg,Xh as y1,Xi as T1,Y as Fu,Ye as ZH,Yg as l1,Yk as Q1,Ze as gg,Zi as C1,_b as NH,_i as A1,a as MH,ag as pP,aj as M1,b as Ge,bf as e1,bh as fP,cl as eD,df as Ju,dk as z1,dl as tD,ei as v1,el as rD,fa as fg,fk as Mg,fl as nD,gj as j1,gl as oD,hl as aD,if as vd,ii as Yu,ja as jH,je as Gu,jf as t1,ji as I1,ka as OH,ki as b1,kk as W1,la as hg,ld as UH,lf as r1,lk as V1,ma as HH,mk as jg,na as DH,nk as G1,ok as J1,pd as Tn,qf as n1,qg as s1,qh as u1,ql as Id,tg as Sg,th as Tg,ti as k1,tl as iD,ue as JH,ug as Pg,uh as Cg,vg as Rg,vh as Ag,vk as K1,wa as LH,wg as c1,wh as p1,xe as KH,xf as wg,xj as gP,xl as sD,yd as qH,yf as yg,yi as S1,zd as FH,zf as vg,zj as wP,zk as Y1,zl as cD}from"./chunk-NK2L5HA2.js";import"./chunk-W45RKGM6.js";import{a as lD,b as uD,c as pD,d as mD,e as fD,f as hD,g as Jr,h as gD,j as Og,k as wD}from"./chunk-73COPJ32.js";import{a as qu}from"./chunk-UGDBMRCT.js";import{t as pO}from"./chunk-3JYPUOK4.js";import{b as iO,c as sO,f as cO,g as dO,h as lO}from"./chunk-YG3HITOU.js";import{a as aO,b as Fh}from"./chunk-SSHE6B7Z.js";import{a as One}from"./chunk-JFXINDOQ.js";import"./chunk-EDYCSW22.js";import{b as ug,c as PH,e as RH,f as Uu,g as dP,k as lP,l as xH,m as _H}from"./chunk-Z6HWSTEP.js";import"./chunk-XGY4OQLC.js";import{d as hH,h as gH,i as wH}from"./chunk-2PVW2XFF.js";import{d as hd,e as Nu,f as QO,g as ZO,h as eH,j as sP,l as cP}from"./chunk-64EDQ7UV.js";import{$ as SO,G as yO,H as vO,J as GS,L as IO,R as bO,S as fi,U as kO,Y as Wh,Z as Vh,_ as Gh,aa as JS,ba as XS,ca as QS,da as eg,ea as ZS,fa as eP,ga as tP,ia as rP,ja as nP,ka as oP,la as aP,u as wO}from"./chunk-DLOJG7LP.js";import"./chunk-ULTV6INR.js";import{A as Xh,C as Qh,D as Zh,E as ya,a as PO,b as RO,c as Jh,f as Kh,h as KS,i as YS,k as $u,m as xO,o as _O,p as EO,r as Yh,s as TO,u as CO}from"./chunk-XKDOPNQ5.js";import"./chunk-JXLDEYRW.js";import{i as kH,m as SH}from"./chunk-GR4MJJCE.js";import{a as lH,f as uH,g as nr,r as gd,t as pH,u as mH,v as lg,w as fH,z as wd}from"./chunk-GG6PM7TB.js";import{b as Es,d as IH,f as bH}from"./chunk-2GEZ3ZY7.js";import{Ba as ag,C as NO,Ca as ln,Da as XO,F as fd,Fa as ig,H as UO,Ia as gi,J as qO,L as FO,N as zO,O as WO,W as VO,aa as hi,ba as GO,c as AO,ga as JO,ha as KO,i as MO,ja as mt,l as jO,m as OO,n as HO,o as DO,oa as ng,p as LO,q as tg,r as iP,s as BO,t as $O,u as rg,wa as jo,xa as YO,za as og}from"./chunk-BYVE4TMU.js";import"./chunk-LVXL7T5O.js";import{f as zS,m as md}from"./chunk-HIQPGYVH.js";import{E as fO,K as Bu,M as hO,N as zh,Q as gO,U as VS,V as Et,b as Lu,c as WS,i as uO,j as me,l as Xe,x as dn,y as mO}from"./chunk-3VT2PPKW.js";import"./chunk-5ZBDHIIE.js";import"./chunk-MTP3B2SU.js";import"./chunk-BLNEHU62.js";import{a as tO,b as nO}from"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import{b as rO,e as oO}from"./chunk-LK77GI6M.js";import{k as RS}from"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import{Ba as Wj,Ua as Vj,Wa as Uh,ba as jj,bb as NS,d as Tj,db as Gj,f as $h,fb as Jj,gb as qh,hb as Kj,l as Cj,lb as Yj,m as Aj,ob as Xj,pa as Oj,sb as US,ub as qS,va as zj,wb as Qj,x as Mj,xb as Zj,yb as eO,zb as FS}from"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import{A as Lj,E as Bj,F as $j,G as Nh,H as Nj,I as Uj,J as qj,N as Fj,h as Hj,z as Dj}from"./chunk-OKKNDQJF.js";import{Cb as ud,Db as wa,Eb as pd,F as wj,Jb as Rj,L as Ve,Lb as xj,M as _t,O as yj,Q as vj,Qb as _j,S as Mo,Ta as Bh,Xb as Ej,ba as Ij,d as mj,da as bj,g as fj,i as hj,j as gj,ob as kj,pb as mi,qb as It,rb as Sj,ub as Pj}from"./chunk-ZEOYNUHL.js";import{$a as Dh,A as Oh,Aa as He,B as TS,C as xs,Cb as lj,D as _s,Db as uj,Eb as pj,F as YM,Fb as Lh,H as XM,I as QM,Ja as tj,La as rj,M as CS,N as AS,O as MS,Oa as nj,P as jS,Q as OS,R as HS,Ra as oj,S as DS,Sa as aj,T as LS,Wa as ij,a as GM,bb as $S,fb as sj,ga as ZM,hb as cj,kb as dj,n as KM,o as Ch,p as Ah,q as Mh,qa as Hh,r as jh,ra as ej,v as pi,va as BS}from"./chunk-ZY32SZ2P.js";import{q as zM,r as ld,s as Th}from"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import{c as F0}from"./chunk-EJOV6Z6F.js";import"./chunk-GY7YSD6J.js";import{a as IM,b as bM,c as En,d as Ph,e as Rs,f as Hu,g as kS,h as Rh,i as kM,k as Eh,n as FM}from"./chunk-KUE46HTH.js";import{d as U0,e as q0,g as vM}from"./chunk-MZKCW6CB.js";import{a as Ou}from"./chunk-6FA3GG5B.js";import{C as sM,D as cM,I as uM,K as yS,L as vS,M as pM,S as IS,U as mM,V as bS,Z as fM,_ as hM,ca as gM,da as wM,f as Mu,fa as Ps,ga as yM,ha as Sh,v as cd,x as ju}from"./chunk-SV7ZBEK2.js";import{M as sd,O as nM,Q as oM,R as aM,S as iM,a as Ss,b as J0,c as Gr,d as _n,e as K0,f as yh,g as Y0,h as X0,i as vh,j as Ih,l as Q0,m as Z0,n as eM,o as tM,p as rM,z as wS}from"./chunk-2MEOUS24.js";import{b as G0,d as wh,e as Xn,f as Ft}from"./chunk-HNQPEOJD.js";import{g as hh,h as gS,i as V0,l as ot,m as Ee,n as T,o as gh}from"./chunk-RCT3O3HQ.js";import{a as z0,c as ks,f as fh,h as Au,i as W0,m as bh,p as dM,r as ha,s as lM,t as ga,u as kh}from"./chunk-UGOK7VTC.js";import"./chunk-ZFJWA4JK.js";import{A as v,d as Re}from"./chunk-X2J2P5ZT.js";import{a as i,b as qe,c as Be,e as xn}from"./chunk-FTQLQJQV.js";var _a=Be((H0e,GF)=>{"use strict";var WF=["nodebuffer","arraybuffer","fragments"],VF=typeof Blob<"u";VF&&WF.push("blob");GF.exports={BINARY_TYPES:WF,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:VF,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:i(()=>{},"NOOP")}});var qp=Be((L0e,wy)=>{"use strict";var{EMPTY_BUFFER:qoe}=_a(),BR=Buffer[Symbol.species];function Foe(e,t){if(e.length===0)return qoe;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let o=0;o<e.length;o++){let a=e[o];r.set(a,n),n+=a.length}return n<t?new BR(r.buffer,r.byteOffset,n):r}i(Foe,"concat");function JF(e,t,r,n,o){for(let a=0;a<o;a++)r[n+a]=e[a]^t[a&3]}i(JF,"_mask");function KF(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}i(KF,"_unmask");function zoe(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}i(zoe,"toArrayBuffer");function $R(e){if($R.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new BR(e):ArrayBuffer.isView(e)?t=new BR(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),$R.readOnly=!1),t}i($R,"toBuffer");wy.exports={concat:Foe,mask:JF,toArrayBuffer:zoe,toBuffer:$R,unmask:KF};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=qe("bufferutil");wy.exports.mask=function(t,r,n,o,a){a<48?JF(t,r,n,o,a):e.mask(t,r,n,o,a)},wy.exports.unmask=function(t,r){t.length<32?KF(t,r):e.unmask(t,r)}}catch{}});var QF=Be(($0e,XF)=>{"use strict";var YF=Symbol("kDone"),NR=Symbol("kRun"),UR=class{static{i(this,"Limiter")}constructor(t){this[YF]=()=>{this.pending--,this[NR]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[NR]()}[NR](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[YF])}}};XF.exports=UR});var Kd=Be((U0e,rz)=>{"use strict";var Fp=qe("zlib"),ZF=qp(),Woe=QF(),{kStatusCode:ez}=_a(),Voe=Buffer[Symbol.species],Goe=Buffer.from([0,0,255,255]),vy=Symbol("permessage-deflate"),Ea=Symbol("total-length"),Gd=Symbol("callback"),ji=Symbol("buffers"),Jd=Symbol("error"),yy,qR=class{static{i(this,"PerMessageDeflate")}constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!yy){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;yy=new Woe(r)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[Gd];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,n=t.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(t){let r=t[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(t){return t.forEach(r=>{Object.keys(r).forEach(n=>{let o=r[n];if(o.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else if(n==="server_max_window_bits"){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=a}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=o})}),t}decompress(t,r,n){yy.add(o=>{this._decompress(t,r,(a,s)=>{o(),n(a,s)})})}compress(t,r,n){yy.add(o=>{this._compress(t,r,(a,s)=>{o(),n(a,s)})})}_decompress(t,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let a=`${o}_max_window_bits`,s=typeof this.params[a]!="number"?Fp.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=Fp.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[vy]=this,this._inflate[Ea]=0,this._inflate[ji]=[],this._inflate.on("error",Koe),this._inflate.on("data",tz)}this._inflate[Gd]=n,this._inflate.write(t),r&&this._inflate.write(Goe),this._inflate.flush(()=>{let a=this._inflate[Jd];if(a){this._inflate.close(),this._inflate=null,n(a);return}let s=ZF.concat(this._inflate[ji],this._inflate[Ea]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ea]=0,this._inflate[ji]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,s)})}_compress(t,r,n){let o=this._isServer?"server":"client";if(!this._deflate){let a=`${o}_max_window_bits`,s=typeof this.params[a]!="number"?Fp.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=Fp.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Ea]=0,this._deflate[ji]=[],this._deflate.on("data",Joe)}this._deflate[Gd]=n,this._deflate.write(t),this._deflate.flush(Fp.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=ZF.concat(this._deflate[ji],this._deflate[Ea]);r&&(a=new Voe(a.buffer,a.byteOffset,a.length-4)),this._deflate[Gd]=null,this._deflate[Ea]=0,this._deflate[ji]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,a)})}};rz.exports=qR;function Joe(e){this[ji].push(e),this[Ea]+=e.length}i(Joe,"deflateOnData");function tz(e){if(this[Ea]+=e.length,this[vy]._maxPayload<1||this[Ea]<=this[vy]._maxPayload){this[ji].push(e);return}this[Jd]=new RangeError("Max payload size exceeded"),this[Jd].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Jd][ez]=1009,this.removeListener("data",tz),this.reset()}i(tz,"inflateOnData");function Koe(e){if(this[vy]._inflate=null,this[Jd]){this[Gd](this[Jd]);return}e[ez]=1007,this[Gd](e)}i(Koe,"inflateOnError")});var Yd=Be((F0e,Iy)=>{"use strict";var{isUtf8:nz}=qe("buffer"),{hasBlob:Yoe}=_a(),Xoe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Qoe(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}i(Qoe,"isValidStatusCode");function FR(e){let t=e.length,r=0;for(;r<t;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}i(FR,"_isValidUTF8");function Zoe(e){return Yoe&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}i(Zoe,"isBlob");Iy.exports={isBlob:Zoe,isValidStatusCode:Qoe,isValidUTF8:FR,tokenChars:Xoe};if(nz)Iy.exports.isValidUTF8=function(e){return e.length<24?FR(e):nz(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=qe("utf-8-validate");Iy.exports.isValidUTF8=function(t){return t.length<32?FR(t):e(t)}}catch{}});var JR=Be((W0e,lz)=>{"use strict";var{Writable:eae}=qe("stream"),oz=Kd(),{BINARY_TYPES:tae,EMPTY_BUFFER:az,kStatusCode:rae,kWebSocket:nae}=_a(),{concat:zR,toArrayBuffer:oae,unmask:aae}=qp(),{isValidStatusCode:iae,isValidUTF8:iz}=Yd(),by=Buffer[Symbol.species],Mn=0,sz=1,cz=2,dz=3,WR=4,VR=5,ky=6,GR=class extends eae{static{i(this,"Receiver")}constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||tae[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[nae]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Mn}_write(t,r,n){if(this._opcode===8&&this._state==Mn)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(n)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new by(n.buffer,n.byteOffset+t,n.length-t),new by(n.buffer,n.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let n=this._buffers[0],o=r.length-t;t>=n.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,t),o),this._buffers[0]=new by(n.buffer,n.byteOffset+t,n.length-t)),t-=n.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case Mn:this.getInfo(t);break;case sz:this.getPayloadLength16(t);break;case cz:this.getPayloadLength64(t);break;case dz:this.getMask();break;case WR:this.getData(t);break;case VR:case ky:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[oz.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(o);return}if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(o);return}this._payloadLength===126?this._state=sz:this._payloadLength===127?this._state=cz:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(r);return}this._masked?this._state=dz:this._state=WR}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=WR}getData(t){let r=az;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&aae(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(n);return}if(this._compressed){this._state=VR,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[oz.extensionName].decompress(t,this._fin,(o,a)=>{if(o)return r(o);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(s);return}this._fragments.push(a)}this.dataMessage(r),this._state===Mn&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=Mn;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=zR(n,r):this._binaryType==="arraybuffer"?o=oae(zR(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Mn):(this._state=ky,setImmediate(()=>{this.emit("message",o,!0),this._state=Mn,this.startLoop(t)}))}else{let o=zR(n,r);if(!this._skipUTF8Validation&&!iz(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(a);return}this._state===VR||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Mn):(this._state=ky,setImmediate(()=>{this.emit("message",o,!1),this._state=Mn,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,az),this.end();else{let n=t.readUInt16BE(0);if(!iae(n)){let a=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(a);return}let o=new by(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!iz(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(a);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=Mn;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=Mn):(this._state=ky,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=Mn,this.startLoop(r)}))}createError(t,r,n,o,a){this._loop=!1,this._errored=!0;let s=new t(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(s,this.createError),s.code=a,s[rae]=o,s}};lz.exports=GR});var XR=Be((J0e,mz)=>{"use strict";var{Duplex:G0e}=qe("stream"),{randomFillSync:sae}=qe("crypto"),{types:{isUint8Array:cae}}=qe("util"),uz=Kd(),{EMPTY_BUFFER:dae,kWebSocket:lae,NOOP:uae}=_a(),{isBlob:Xd,isValidStatusCode:pae}=Yd(),{mask:pz,toBuffer:zs}=qp(),jn=Symbol("kByteLength"),mae=Buffer.alloc(4),Sy=8*1024,Ws,Qd=Sy,ao=0,fae=1,hae=2,KR=class e{static{i(this,"Sender")}constructor(t,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ao,this.onerror=uae,this[lae]=void 0}static frame(t,r){let n,o=!1,a=2,s=!1;r.mask&&(n=r.maskBuffer||mae,r.generateMask?r.generateMask(n):(Qd===Sy&&(Ws===void 0&&(Ws=Buffer.alloc(Sy)),sae(Ws,0,Sy),Qd=0),n[0]=Ws[Qd++],n[1]=Ws[Qd++],n[2]=Ws[Qd++],n[3]=Ws[Qd++]),s=(n[0]|n[1]|n[2]|n[3])===0,a=6);let c;typeof t=="string"?(!r.mask||s)&&r[jn]!==void 0?c=r[jn]:(t=Buffer.from(t),c=t.length):(c=t.length,o=r.mask&&r.readOnly&&!s);let d=c;c>=65536?(a+=8,d=127):c>125&&(a+=2,d=126);let l=Buffer.allocUnsafe(o?c+a:a);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=d,d===126?l.writeUInt16BE(c,2):d===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),r.mask?(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],s?[l,t]:o?(pz(t,n,l,a,c),[l]):(pz(t,n,t,0,c),[l,t])):[l,t]}close(t,r,n,o){let a;if(t===void 0)a=dae;else{if(typeof t!="number"||!pae(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(a=Buffer.allocUnsafe(2+c),a.writeUInt16BE(t,0),typeof r=="string")a.write(r,2);else if(cae(r))a.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[jn]:a.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ao?this.enqueue([this.dispatch,a,!1,s,o]):this.sendFrame(e.frame(a,s),o)}ping(t,r,n){let o,a;if(typeof t=="string"?(o=Buffer.byteLength(t),a=!1):Xd(t)?(o=t.size,a=!1):(t=zs(t),o=t.length,a=zs.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[jn]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};Xd(t)?this._state!==ao?this.enqueue([this.getBlobData,t,!1,s,n]):this.getBlobData(t,!1,s,n):this._state!==ao?this.enqueue([this.dispatch,t,!1,s,n]):this.sendFrame(e.frame(t,s),n)}pong(t,r,n){let o,a;if(typeof t=="string"?(o=Buffer.byteLength(t),a=!1):Xd(t)?(o=t.size,a=!1):(t=zs(t),o=t.length,a=zs.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[jn]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};Xd(t)?this._state!==ao?this.enqueue([this.getBlobData,t,!1,s,n]):this.getBlobData(t,!1,s,n):this._state!==ao?this.enqueue([this.dispatch,t,!1,s,n]):this.sendFrame(e.frame(t,s),n)}send(t,r,n){let o=this._extensions[uz.extensionName],a=r.binary?2:1,s=r.compress,c,d;typeof t=="string"?(c=Buffer.byteLength(t),d=!1):Xd(t)?(c=t.size,d=!1):(t=zs(t),c=t.length,d=zs.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=c>=o._threshold),this._compress=s):(s=!1,a=0),r.fin&&(this._firstFragment=!0);let l={[jn]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:d,rsv1:s};Xd(t)?this._state!==ao?this.enqueue([this.getBlobData,t,this._compress,l,n]):this.getBlobData(t,this._compress,l,n):this._state!==ao?this.enqueue([this.dispatch,t,this._compress,l,n]):this.dispatch(t,this._compress,l,n)}getBlobData(t,r,n,o){this._bufferedBytes+=n[jn],this._state=hae,t.arrayBuffer().then(a=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(YR,this,c,o);return}this._bufferedBytes-=n[jn];let s=zs(a);r?this.dispatch(s,r,n,o):(this._state=ao,this.sendFrame(e.frame(s,n),o),this.dequeue())}).catch(a=>{process.nextTick(gae,this,a,o)})}dispatch(t,r,n,o){if(!r){this.sendFrame(e.frame(t,n),o);return}let a=this._extensions[uz.extensionName];this._bufferedBytes+=n[jn],this._state=fae,a.compress(t,n.fin,(s,c)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");YR(this,d,o);return}this._bufferedBytes-=n[jn],this._state=ao,n.readOnly=!1,this.sendFrame(e.frame(c,n),o),this.dequeue()})}dequeue(){for(;this._state===ao&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][jn],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][jn],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};mz.exports=KR;function YR(e,t,r){typeof r=="function"&&r(t);for(let n=0;n<e._queue.length;n++){let o=e._queue[n],a=o[o.length-1];typeof a=="function"&&a(t)}}i(YR,"callCallbacks");function gae(e,t,r){YR(e,t,r),e.onerror(t)}i(gae,"onError")});var kz=Be((Y0e,bz)=>{"use strict";var{kForOnEventAttribute:zp,kListener:QR}=_a(),fz=Symbol("kCode"),hz=Symbol("kData"),gz=Symbol("kError"),wz=Symbol("kMessage"),yz=Symbol("kReason"),Zd=Symbol("kTarget"),vz=Symbol("kType"),Iz=Symbol("kWasClean"),Ta=class{static{i(this,"Event")}constructor(t){this[Zd]=null,this[vz]=t}get target(){return this[Zd]}get type(){return this[vz]}};Object.defineProperty(Ta.prototype,"target",{enumerable:!0});Object.defineProperty(Ta.prototype,"type",{enumerable:!0});var Vs=class extends Ta{static{i(this,"CloseEvent")}constructor(t,r={}){super(t),this[fz]=r.code===void 0?0:r.code,this[yz]=r.reason===void 0?"":r.reason,this[Iz]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[fz]}get reason(){return this[yz]}get wasClean(){return this[Iz]}};Object.defineProperty(Vs.prototype,"code",{enumerable:!0});Object.defineProperty(Vs.prototype,"reason",{enumerable:!0});Object.defineProperty(Vs.prototype,"wasClean",{enumerable:!0});var el=class extends Ta{static{i(this,"ErrorEvent")}constructor(t,r={}){super(t),this[gz]=r.error===void 0?null:r.error,this[wz]=r.message===void 0?"":r.message}get error(){return this[gz]}get message(){return this[wz]}};Object.defineProperty(el.prototype,"error",{enumerable:!0});Object.defineProperty(el.prototype,"message",{enumerable:!0});var Wp=class extends Ta{static{i(this,"MessageEvent")}constructor(t,r={}){super(t),this[hz]=r.data===void 0?null:r.data}get data(){return this[hz]}};Object.defineProperty(Wp.prototype,"data",{enumerable:!0});var wae={addEventListener(e,t,r={}){for(let o of this.listeners(e))if(!r[zp]&&o[QR]===t&&!o[zp])return;let n;if(e==="message")n=i(function(a,s){let c=new Wp("message",{data:s?a:a.toString()});c[Zd]=this,Py(t,this,c)},"onMessage");else if(e==="close")n=i(function(a,s){let c=new Vs("close",{code:a,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Zd]=this,Py(t,this,c)},"onClose");else if(e==="error")n=i(function(a){let s=new el("error",{error:a,message:a.message});s[Zd]=this,Py(t,this,s)},"onError");else if(e==="open")n=i(function(){let a=new Ta("open");a[Zd]=this,Py(t,this,a)},"onOpen");else return;n[zp]=!!r[zp],n[QR]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[QR]===t&&!r[zp]){this.removeListener(e,r);break}}};bz.exports={CloseEvent:Vs,ErrorEvent:el,Event:Ta,EventTarget:wae,MessageEvent:Wp};function Py(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}i(Py,"callListener")});var Ry=Be((Q0e,Sz)=>{"use strict";var{tokenChars:Vp}=Yd();function zo(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}i(zo,"push");function yae(e){let t=Object.create(null),r=Object.create(null),n=!1,o=!1,a=!1,s,c,d=-1,l=-1,u=-1,p=0;for(;p<e.length;p++)if(l=e.charCodeAt(p),s===void 0)if(u===-1&&Vp[l]===1)d===-1&&(d=p);else if(p!==0&&(l===32||l===9))u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let g=e.slice(d,u);l===44?(zo(t,g,r),r=Object.create(null)):s=g,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===void 0)if(u===-1&&Vp[l]===1)d===-1&&(d=p);else if(l===32||l===9)u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),zo(r,e.slice(d,u),!0),l===44&&(zo(t,s,r),r=Object.create(null),s=void 0),d=u=-1}else if(l===61&&d!==-1&&u===-1)c=e.slice(d,p),d=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(Vp[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1?d=p:n||(n=!0),o=!1}else if(a)if(Vp[l]===1)d===-1&&(d=p);else if(l===34&&d!==-1)a=!1,u=p;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&e.charCodeAt(p-1)===61)a=!0;else if(u===-1&&Vp[l]===1)d===-1&&(d=p);else if(d!==-1&&(l===32||l===9))u===-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let g=e.slice(d,u);n&&(g=g.replace(/\\/g,""),n=!1),zo(r,c,g),l===44&&(zo(t,s,r),r=Object.create(null),s=void 0),c=void 0,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(d===-1||a||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let m=e.slice(d,u);return s===void 0?zo(t,m,r):(c===void 0?zo(r,m,!0):n?zo(r,c,m.replace(/\\/g,"")):zo(r,c,m),zo(t,s,r)),t}i(yae,"parse");function vae(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(n=>[t].concat(Object.keys(n).map(o=>{let a=n[o];return Array.isArray(a)||(a=[a]),a.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}i(vae,"format");Sz.exports={format:vae,parse:yae}});var Ty=Be((rMe,Hz)=>{"use strict";var Iae=qe("events"),bae=qe("https"),kae=qe("http"),xz=qe("net"),Sae=qe("tls"),{randomBytes:Pae,createHash:Rae}=qe("crypto"),{Duplex:eMe,Readable:tMe}=qe("stream"),{URL:ZR}=qe("url"),Oi=Kd(),xae=JR(),_ae=XR(),{isBlob:Eae}=Yd(),{BINARY_TYPES:Pz,CLOSE_TIMEOUT:Tae,EMPTY_BUFFER:xy,GUID:Cae,kForOnEventAttribute:ex,kListener:Aae,kStatusCode:Mae,kWebSocket:Vt,NOOP:_z}=_a(),{EventTarget:{addEventListener:jae,removeEventListener:Oae}}=kz(),{format:Hae,parse:Dae}=Ry(),{toBuffer:Lae}=qp(),Ez=Symbol("kAborted"),tx=[8,13],Ca=["CONNECTING","OPEN","CLOSING","CLOSED"],Bae=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,yt=class e extends Iae{static{i(this,"WebSocket")}constructor(t,r,n){super(),this._binaryType=Pz[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=xy,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),Tz(this,t,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){Pz.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,n){let o=new xae({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),a=new _ae(t,this._extensions,n.generateMask);this._receiver=o,this._sender=a,this._socket=t,o[Vt]=this,a[Vt]=this,t[Vt]=this,o.on("conclude",Uae),o.on("drain",qae),o.on("error",Fae),o.on("message",zae),o.on("ping",Wae),o.on("pong",Vae),a.onerror=Gae,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",Mz),t.on("data",Ey),t.on("end",jz),t.on("error",Oz),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Oi.extensionName]&&this._extensions[Oi.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){pn(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Az(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){rx(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||xy,r,n)}pong(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){rx(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||xy,r,n)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){rx(this,t,n);return}let o={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Oi.extensionName]||(o.compress=!1),this._sender.send(t||xy,o,n)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){pn(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(yt,"CONNECTING",{enumerable:!0,value:Ca.indexOf("CONNECTING")});Object.defineProperty(yt.prototype,"CONNECTING",{enumerable:!0,value:Ca.indexOf("CONNECTING")});Object.defineProperty(yt,"OPEN",{enumerable:!0,value:Ca.indexOf("OPEN")});Object.defineProperty(yt.prototype,"OPEN",{enumerable:!0,value:Ca.indexOf("OPEN")});Object.defineProperty(yt,"CLOSING",{enumerable:!0,value:Ca.indexOf("CLOSING")});Object.defineProperty(yt.prototype,"CLOSING",{enumerable:!0,value:Ca.indexOf("CLOSING")});Object.defineProperty(yt,"CLOSED",{enumerable:!0,value:Ca.indexOf("CLOSED")});Object.defineProperty(yt.prototype,"CLOSED",{enumerable:!0,value:Ca.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(yt.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(yt.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[ex])return t[Aae];return null},set(t){for(let r of this.listeners(e))if(r[ex]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[ex]:!0})}})});yt.prototype.addEventListener=jae;yt.prototype.removeEventListener=Oae;Hz.exports=yt;function Tz(e,t,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Tae,protocolVersion:tx[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!tx.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${tx.join(", ")})`);let a;if(t instanceof ZR)a=t;else try{a=new ZR(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),e._url=a.href;let s=a.protocol==="wss:",c=a.protocol==="ws+unix:",d;if(a.protocol!=="ws:"&&!s&&!c?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!a.pathname?d="The URL's pathname is empty":a.hash&&(d="The URL contains a fragment identifier"),d){let h=new SyntaxError(d);if(e._redirects===0)throw h;_y(e,h);return}let l=s?443:80,u=Pae(16).toString("base64"),p=s?bae.request:kae.request,m=new Set,g;if(o.createConnection=o.createConnection||(s?Nae:$ae),o.defaultPort=o.defaultPort||l,o.port=a.port||l,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(g=new Oi({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Hae({[Oi.extensionName]:g.offer()})),r.length){for(let h of r){if(typeof h!="string"||!Bae.test(h)||m.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(h)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),c){let h=o.path.split(":");o.socketPath=h[0],o.path=h[1]}let w;if(o.followRedirects){if(e._redirects===0){e._originalIpc=c,e._originalSecure=s,e._originalHostOrSocketPath=c?o.socketPath:a.host;let h=n&&n.headers;if(n={...n,headers:{}},h)for(let[y,f]of Object.entries(h))n.headers[y.toLowerCase()]=f}else if(e.listenerCount("redirect")===0){let h=c?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:a.host===e._originalHostOrSocketPath;(!h||e._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,h||delete o.headers.host,o.auth=void 0)}o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),w=e._req=p(o),e._redirects&&e.emit("redirect",e.url,w)}else w=e._req=p(o);o.timeout&&w.on("timeout",()=>{pn(e,w,"Opening handshake has timed out")}),w.on("error",h=>{w===null||w[Ez]||(w=e._req=null,_y(e,h))}),w.on("response",h=>{let y=h.headers.location,f=h.statusCode;if(y&&o.followRedirects&&f>=300&&f<400){if(++e._redirects>o.maxRedirects){pn(e,w,"Maximum redirects exceeded");return}w.abort();let S;try{S=new ZR(y,t)}catch{let I=new SyntaxError(`Invalid URL: ${y}`);_y(e,I);return}Tz(e,S,r,n)}else e.emit("unexpected-response",w,h)||pn(e,w,`Unexpected server response: ${h.statusCode}`)}),w.on("upgrade",(h,y,f)=>{if(e.emit("upgrade",h),e.readyState!==yt.CONNECTING)return;w=e._req=null;let S=h.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){pn(e,y,"Invalid Upgrade header");return}let k=Rae("sha1").update(u+Cae).digest("base64");if(h.headers["sec-websocket-accept"]!==k){pn(e,y,"Invalid Sec-WebSocket-Accept header");return}let I=h.headers["sec-websocket-protocol"],b;if(I!==void 0?m.size?m.has(I)||(b="Server sent an invalid subprotocol"):b="Server sent a subprotocol but none was requested":m.size&&(b="Server sent no subprotocol"),b){pn(e,y,b);return}I&&(e._protocol=I);let R=h.headers["sec-websocket-extensions"];if(R!==void 0){if(!g){pn(e,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let _;try{_=Dae(R)}catch{pn(e,y,"Invalid Sec-WebSocket-Extensions header");return}let P=Object.keys(_);if(P.length!==1||P[0]!==Oi.extensionName){pn(e,y,"Server indicated an extension that was not requested");return}try{g.accept(_[Oi.extensionName])}catch{pn(e,y,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[Oi.extensionName]=g}e.setSocket(y,f,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(w,e):w.end()}i(Tz,"initAsClient");function _y(e,t){e._readyState=yt.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}i(_y,"emitErrorAndClose");function $ae(e){return e.path=e.socketPath,xz.connect(e)}i($ae,"netConnect");function Nae(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=xz.isIP(e.host)?"":e.host),Sae.connect(e)}i(Nae,"tlsConnect");function pn(e,t,r){e._readyState=yt.CLOSING;let n=new Error(r);Error.captureStackTrace(n,pn),t.setHeader?(t[Ez]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(_y,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}i(pn,"abortHandshake");function rx(e,t,r){if(t){let n=Eae(t)?t.size:Lae(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${e.readyState} (${Ca[e.readyState]})`);process.nextTick(r,n)}}i(rx,"sendAfterClose");function Uae(e,t){let r=this[Vt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[Vt]!==void 0&&(r._socket.removeListener("data",Ey),process.nextTick(Cz,r._socket),e===1005?r.close():r.close(e,t))}i(Uae,"receiverOnConclude");function qae(){let e=this[Vt];e.isPaused||e._socket.resume()}i(qae,"receiverOnDrain");function Fae(e){let t=this[Vt];t._socket[Vt]!==void 0&&(t._socket.removeListener("data",Ey),process.nextTick(Cz,t._socket),t.close(e[Mae])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}i(Fae,"receiverOnError");function Rz(){this[Vt].emitClose()}i(Rz,"receiverOnFinish");function zae(e,t){this[Vt].emit("message",e,t)}i(zae,"receiverOnMessage");function Wae(e){let t=this[Vt];t._autoPong&&t.pong(e,!this._isServer,_z),t.emit("ping",e)}i(Wae,"receiverOnPing");function Vae(e){this[Vt].emit("pong",e)}i(Vae,"receiverOnPong");function Cz(e){e.resume()}i(Cz,"resume");function Gae(e){let t=this[Vt];t.readyState!==yt.CLOSED&&(t.readyState===yt.OPEN&&(t._readyState=yt.CLOSING,Az(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}i(Gae,"senderOnError");function Az(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}i(Az,"setCloseTimer");function Mz(){let e=this[Vt];if(this.removeListener("close",Mz),this.removeListener("data",Ey),this.removeListener("end",jz),e._readyState=yt.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[Vt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Rz),e._receiver.on("finish",Rz))}i(Mz,"socketOnClose");function Ey(e){this[Vt]._receiver.write(e)||this.pause()}i(Ey,"socketOnData");function jz(){let e=this[Vt];e._readyState=yt.CLOSING,e._receiver.end(),this.end()}i(jz,"socketOnEnd");function Oz(){let e=this[Vt];this.removeListener("error",Oz),this.on("error",_z),e&&(e._readyState=yt.CLOSING,this.destroy())}i(Oz,"socketOnError")});var $z=Be((aMe,Bz)=>{"use strict";var oMe=Ty(),{Duplex:Jae}=qe("stream");function Dz(e){e.emit("close")}i(Dz,"emitClose");function Kae(){!this.destroyed&&this._writableState.finished&&this.destroy()}i(Kae,"duplexOnEnd");function Lz(e){this.removeListener("error",Lz),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}i(Lz,"duplexOnError");function Yae(e,t){let r=!0,n=new Jae({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",i(function(a,s){let c=!s&&n._readableState.objectMode?a.toString():a;n.push(c)||e.pause()},"message")),e.once("error",i(function(a){n.destroyed||(r=!1,n.destroy(a))},"error")),e.once("close",i(function(){n.destroyed||n.push(null)},"close")),n._destroy=function(o,a){if(e.readyState===e.CLOSED){a(o),process.nextTick(Dz,n);return}let s=!1;e.once("error",i(function(d){s=!0,a(d)},"error")),e.once("close",i(function(){s||a(o),process.nextTick(Dz,n)},"close")),r&&e.terminate()},n._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",i(function(){n._final(o)},"open"));return}e._socket!==null&&(e._socket._writableState.finished?(o(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",i(function(){o()},"finish")),e.close()))},n._read=function(){e.isPaused&&e.resume()},n._write=function(o,a,s){if(e.readyState===e.CONNECTING){e.once("open",i(function(){n._write(o,a,s)},"open"));return}e.send(o,s)},n.on("end",Kae),n.on("error",Lz),n}i(Yae,"createWebSocketStream");Bz.exports=Yae});var nx=Be((sMe,Nz)=>{"use strict";var{tokenChars:Xae}=Yd();function Qae(e){let t=new Set,r=-1,n=-1,o=0;for(o;o<e.length;o++){let s=e.charCodeAt(o);if(n===-1&&Xae[s]===1)r===-1&&(r=o);else if(o!==0&&(s===32||s===9))n===-1&&r!==-1&&(n=o);else if(s===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let c=e.slice(r,n);if(t.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);t.add(c),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let a=e.slice(r,o);if(t.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return t.add(a),t}i(Qae,"parse");Nz.exports={parse:Qae}});var Gz=Be((lMe,Vz)=>{"use strict";var Zae=qe("events"),Cy=qe("http"),{Duplex:dMe}=qe("stream"),{createHash:eie}=qe("crypto"),Uz=Ry(),Gs=Kd(),tie=nx(),rie=Ty(),{CLOSE_TIMEOUT:nie,GUID:oie,kWebSocket:aie}=_a(),iie=/^[+/0-9A-Za-z]{22}==$/,qz=0,Fz=1,Wz=2,ox=class extends Zae{static{i(this,"WebSocketServer")}constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:nie,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:rie,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=Cy.createServer((n,o)=>{let a=Cy.STATUS_CODES[426];o.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),o.end(a)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=sie(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:i((o,a,s)=>{this.handleUpgrade(o,a,s,n)},"upgrade")})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=qz}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===Wz){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Gp,this);return}if(t&&this.once("close",t),this._state!==Fz)if(this._state=Fz,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Gp,this):process.nextTick(Gp,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Gp(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,n,o){r.on("error",zz);let a=t.headers["sec-websocket-key"],s=t.headers.upgrade,c=+t.headers["sec-websocket-version"];if(t.method!=="GET"){Js(this,t,r,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Js(this,t,r,400,"Invalid Upgrade header");return}if(a===void 0||!iie.test(a)){Js(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Js(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Jp(r,400);return}let d=t.headers["sec-websocket-protocol"],l=new Set;if(d!==void 0)try{l=tie.parse(d)}catch{Js(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=t.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let m=new Gs({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Uz.parse(u);g[Gs.extensionName]&&(m.accept(g[Gs.extensionName]),p[Gs.extensionName]=m)}catch{Js(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:t.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(g,w,h,y)=>{if(!g)return Jp(r,w||401,h,y);this.completeUpgrade(p,a,l,t,r,n,o)});return}if(!this.options.verifyClient(m))return Jp(r,401)}this.completeUpgrade(p,a,l,t,r,n,o)}completeUpgrade(t,r,n,o,a,s,c){if(!a.readable||!a.writable)return a.destroy();if(a[aie])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>qz)return Jp(a,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${eie("sha1").update(r+oie).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,o):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(t[Gs.extensionName]){let p=t[Gs.extensionName].params,m=Uz.format({[Gs.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),u._extensions=t}this.emit("headers",l,o),a.write(l.concat(`\r
|
|
3
|
+
import{a as Bq,b as $q,c as Nq}from"./chunk-YXMYK5P7.js";import"./chunk-S4WILIRA.js";import{c as kq}from"./chunk-MPEK4ZNY.js";import{a as Sq,b as Pq,c as Rq,d as xq,e as _q,f as Eq,g as Tq,h as Cq,i as Aq,j as Mq}from"./chunk-AWUSAHXG.js";import{a as or,b as Op,c as xa,d as iy,e as sy,f as Ei}from"./chunk-27OJ2OLP.js";import{a as jq,b as Oq,c as Hq,d as M,e as Dq,f as Ti,g as z,h as cy,j as Lq}from"./chunk-3V2XAYYA.js";import{a as ay,b as Iq}from"./chunk-5JVJQA5H.js";import{a as DU,b as zU,c as hR,d as WU,e as VU,f as GU,g as JU,h as KU,j as YU}from"./chunk-H5EHSILL.js";import{A as fR,a as jU,c as OU,g as HU,k as ey,l as Fo,m as LU,n as Pa,o as ty,p as BU,q as Ri,r as ry,s as $U,t as Ra,u as ny,v as xi,w as NU,x as UU,y as qU,z as FU}from"./chunk-G2P2PYEO.js";import{a as XU,b as QU,c as oy,d as ZU,e as _i,f as Je,g as eq,h as Pe,i as tq,j as rq,k as nq,l as oq,m as aq,n as iq,o as sq,p as cq,q as dq,r as lq,s as uq,t as $r,u as Pr,v as pe,w as pq}from"./chunk-LWF5MQJ4.js";import{a as mq,b as fq}from"./chunk-YFHQRDNQ.js";import{a as hq,b as gq}from"./chunk-6KKWSUEW.js";import{c as mR}from"./chunk-MXDSB2C5.js";import{a as wq,b as yq,c as vq}from"./chunk-EZ435RGA.js";import"./chunk-E5HDJCKK.js";import{a as Yw,b as vU,c as IU,d as bU,e as kU}from"./chunk-SUILNZQJ.js";import{a as Sa,c as Ww,d as Ud,e as mU,f as fU,g as kr,h as hU,i as Gw,j as gU,k as Sr,l as Jw,m as wU,n as Yr,o as Kw,p as yU,r as RU}from"./chunk-WAWVFSIQ.js";import{a as Xw,b as SU,c as pR}from"./chunk-EFP75UEX.js";import{b as PU,c as Qw}from"./chunk-2IIVBBF5.js";import{a as un}from"./chunk-XTT3K3TR.js";import"./chunk-S7A2OGL2.js";import{a as uU,e as Vw}from"./chunk-4KG7GJ5O.js";import{a as xS,b as WM}from"./chunk-EICS777E.js";import{a as xU}from"./chunk-IXMY4EKS.js";import"./chunk-WLQEONBF.js";import"./chunk-MHSSPMLB.js";import{b as _U}from"./chunk-EXAJ2B4I.js";import{a as EU,b as Zw,c as TU,d as CU,e as AU}from"./chunk-FRQYH4QD.js";import{b as MU}from"./chunk-KE5PYRJ6.js";import{a as nU,b as oU,c as Uw,d as qw}from"./chunk-XVDFJ3ZF.js";import{b as lU}from"./chunk-FA3GXQYA.js";import{b as dU,c as lR}from"./chunk-Q3WXB465.js";import"./chunk-WOYBWRRV.js";import{a as cU}from"./chunk-FEAKTSRS.js";import"./chunk-OIIE5GUK.js";import{a as oo,b as zw,c as uR,d as pU}from"./chunk-TPOAAJKA.js";import"./chunk-CX4T7I47.js";import{a as eU,b as tU,c as rU}from"./chunk-I6KTJ3GH.js";import{h as oe}from"./chunk-U73T66FP.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{a as K2,b as $w}from"./chunk-NDNSLCPE.js";import{a as Ns,b as Nw,c as Q2,d as Z2}from"./chunk-IUYGQO2K.js";import"./chunk-W45RKGM6.js";import"./chunk-CWE2N3JI.js";import{a as Lw,d as Bw,f as Y2,g as X2}from"./chunk-O4YHISU2.js";import{a as J2}from"./chunk-Z5R4OSGC.js";import{b as V2,c as G2,d as Nd,f as Dw,g as Mp}from"./chunk-QKGNAYSC.js";import{b as jp,c as ka}from"./chunk-HT6ILPD6.js";import"./chunk-BTEBZYK3.js";import{a as no,b as z2,c as W2}from"./chunk-MWS2NAHJ.js";import{a as D2,d as L2,f as B2,g as $2,h as N2,i as ba,j as U2,k as Hw,n as Ap}from"./chunk-WBV6A6NS.js";import{a as q2,b as F2}from"./chunk-CBD554GZ.js";import{c as U$,d as uw,i as q$}from"./chunk-KQ7RFPG5.js";import{b as jw,d as $d,l as E2,n as Ow}from"./chunk-KH42V27F.js";import"./chunk-DRMOHADV.js";import{A as dg,c as sg,d as tH,e as rH,f as nH,h as oH,i as aH,j as iH,p as sH,u as wi,v as cH,x as dH,z as cg}from"./chunk-OTXGAKFH.js";import{a as yH,d as vH,g as EH}from"./chunk-VMW23TIZ.js";import{a as a$,b as d$,c as l$,d as O$,e as lw,f as B$,g as $$,h as N$,i as F$,j as TN,k as O2,m as bq}from"./chunk-OBMMO5NC.js";import{a as aU}from"./chunk-ONR2AKRI.js";import{a as pt,b as i$,c as s$,d as JP,e as tN,f as mw,g as fw,h as rN}from"./chunk-PKJHN666.js";import{a as iU,b as Fw,c as sU}from"./chunk-3BIB6KKL.js";import{b as Ad,c as Md,d as VP}from"./chunk-JH4RACOB.js";import{b as dw}from"./chunk-JVEIK4RH.js";import{$ as k2,A as MN,B as Kr,C as jN,D as ON,E as NN,F as UN,G as qN,H as FN,I as zN,J as t2,K as r2,L as aR,M as n2,N as l2,O as u2,P as p2,Q as f2,R as iR,S as w2,T as Cw,U as Ls,V as qo,W as to,X as I2,Y as Tp,Z as b2,_ as ro,aa as Aw,b as u$,ba as S2,c as _$,ca as P2,d as E$,da as br,e as C$,ea as Bs,f as G$,fa as R2,g as Od,ga as Ia,h as J$,ha as sR,i as X$,ia as cR,j as Q$,ja as Cp,k as nN,ka as dR,l as vN,la as Mw,m as IN,ma as _2,n as bN,na as T2,o as kN,oa as H2,p as SN,q as QP,r as PN,s as RN,t as xN,u as _N,x as EN,y as CN,z as ZP}from"./chunk-EAW5FHU4.js";import{g as C2,h as A2,i as M2,j as j2}from"./chunk-ODH5XGE6.js";import{a as T$}from"./chunk-PYNW5OFA.js";import{A as eR,B as tR,F as WN,M as y2,a as W$,b as V$,c as GP,m as yN,q as yw}from"./chunk-XSDWRRZP.js";import{b as $s,c as x2,d as Br}from"./chunk-RHMULF56.js";import"./chunk-VFH5C6D2.js";import{a as g2}from"./chunk-UOFDKMRU.js";import{a as wN}from"./chunk-AN525SPP.js";import{a as z$}from"./chunk-IZ6DLEVY.js";import{a as Hs,b as UP,c as Sp,d as Pp,e as Td,f as aw,g as qP,h as Rp,i as Cn,j as R$,k as fe,l as x$,m as zP}from"./chunk-DNRC6TPJ.js";import{b as h$}from"./chunk-6YR5IYHH.js";import"./chunk-SYUKES6H.js";import{a as H$,b as D$,c as L$,d as cw}from"./chunk-XLZMSD5K.js";import"./chunk-SVLVIYH2.js";import{B as m2,J as v2,b as VM,z as AN}from"./chunk-6I5AUTVO.js";import{b as A$,i as M$,j as j$,m as Cd,n as WP}from"./chunk-BQNU4HZW.js";import{a as kp,b as bi}from"./chunk-OOKHHOIU.js";import{a as NP,g as p$,h as m$,j as f$}from"./chunk-JCHLDNCX.js";import"./chunk-7PXZ4X4P.js";import"./chunk-N73MU2C3.js";import"./chunk-X4CN3FIN.js";import"./chunk-TRXOE7TT.js";import"./chunk-5VQK3CCJ.js";import{A as Pi,B as oR,C as Sw,D as XN,E as Pw,F as QN,G as _p,J as Rw,K as ZN,L as xw,M as e2,N as Bd,d as HN,f as DN,g as LN,h as BN,i as $N,m as vw,n as Iw,o as VN,p as GN,q as Ld,r as JN,s as rR,t as KN,u as bw,v as kw,w as Uo,x as Ds,y as nR,z as YN}from"./chunk-OUOOKEU3.js";import"./chunk-VS2LOUCT.js";import"./chunk-DMFUEUAZ.js";import"./chunk-AFKFN25T.js";import"./chunk-G4747MOW.js";import{a as $o,b as No,c as Wt}from"./chunk-GF55VEMR.js";import"./chunk-FAKDGLZQ.js";import"./chunk-KCJVFLBB.js";import{a as Z$,b as eN}from"./chunk-GW766ZSO.js";import{a as s2,b as c2,c as d2,d as Tw,f as h2}from"./chunk-OVEQAEKR.js";import{a as o2,b as Ep,c as a2,d as _w,e as i2,f as Ew}from"./chunk-SSJV3VX7.js";import{a as jd}from"./chunk-7KWD2I6W.js";import{a as Dr,b as g$,c as Lr,d as w$,e as iw,f as sw,g as FP,h as y$,i as ki,k as v$,l as I$,m as b$,n as k$,o as S$,p as P$}from"./chunk-2ACX7IW5.js";import{A as NM,C as UM,D as qM,E as Qn,d as RM,e as xM,f as _M,g as EM,h as SS,i as TM,j as CM,k as AM,l as MM,m as jM,n as xh,o as OM,p as PS,q as HM,r as DM,s as rr,t as LM,u as ut,v as St,w as BM,x as $M,y as Du,z as _h}from"./chunk-OFJPOTES.js";import{c as lN,d as KP,e as uN,f as pN,g as mN,h as fN,i as Dd,j as ww,k as Bo,l as hN,m as YP,n as gN,o as XP}from"./chunk-JAIFVT3D.js";import{A as dN,C as gw,b as pw,d as K$,e as Y$,h as oN,k as aN,l as iN,m as Hd,n as sN,p as hw,q as cN,s as xp}from"./chunk-YU3C6U5V.js";import"./chunk-A4HLKWQD.js";import{a as Si}from"./chunk-KVTBX2UP.js";import{a as ye,b as zt,c as Ed,d as ce,f as c$}from"./chunk-FDYWGE2Y.js";import{$ as nL,$a as ML,$b as cp,$c as $P,A as AD,Aa as fL,Ac as KB,Ba as hL,Ca as gL,Cb as Zg,Cc as YB,Db as AB,Dc as XB,E as MD,Ea as Pd,Eb as MB,Ec as Os,F as jD,Fa as wL,Fb as Lo,Fc as QB,G as Lg,Gb as jB,H as OD,Ha as tp,Hb as js,I as qD,Ia as Fg,Ib as OB,Ic as st,J as FD,Ja as yL,Jc as HP,K as Oo,Ka as SP,Kc as up,La as vL,Lc as pp,M as zD,Ma as IL,Mc as ZB,N as WD,Na as PP,Nc as DP,O as VD,Oa as bL,Oc as mp,P as GD,Pa as kL,Pc as fp,Q as JD,Qa as SL,Qc as e$,Ra as PL,Rc as LP,S as KD,Sa as RL,Sc as hp,T as Bg,Ta as xL,Tc as gp,U as YD,Ua as _L,Uc as t$,V as XD,Va as RP,Vb as HB,Vc as wp,W as QD,Wa as EL,Wc as r$,X as ZD,Xa as TL,Xb as DB,Xc as BP,Y as eL,Ya as CL,Yb as ip,Yc as yp,Z as tL,Za as AL,Zb as LB,Zc as vp,_ as rL,_a as xP,_b as sp,_c as n$,aa as oL,ab as jL,ac as MP,ad as Ip,b as bd,ba as aL,bb as OL,bc as BB,bd as bp,ca as iL,cb as HL,cc as dp,cd as o$,da as sL,db as DL,dc as $B,e as yD,ea as cL,eb as LL,ec as ew,fb as BL,fc as NB,g as vP,ga as $g,gb as $L,gc as UB,h as vD,ha as dL,hb as NL,hc as qB,i as Hr,ia as Zn,ic as FB,j as Qu,ja as Ng,jc as tw,k as Ts,ka as kP,kb as UL,kc as rw,l as IP,la as Ug,lb as qL,m as ID,mb as FL,n as bD,na as qg,nb as zL,nc as zB,o as kD,oa as Zu,ob as WL,p as SD,pb as rp,pc as Ii,q as PD,qa as lL,r as RD,rb as zg,rc as nw,s as Dg,sb as VL,sc as WB,ta as Sd,tb as GL,tc as lp,ua as Ho,ub as JL,uc as ow,v as va,va as uL,vb as Cs,vc as VB,w as kd,wa as ep,wb as KL,wc as GB,x as TD,xc as jP,y as CD,ya as pL,yb as CB,yc as JB,za as mL,zc as OP}from"./chunk-FCC24XUI.js";import{d as SM}from"./chunk-OQPJ7FJF.js";import"./chunk-BL3CZWWD.js";import{b as HD,c as DD,d as LD,e as BD,f as $D,g as ND,h as UD}from"./chunk-FYWQWKVS.js";import{b as xD,c as Hg}from"./chunk-GD3RCUDH.js";import{$ as Ms,A as Ir,C as lB,D as uB,E as pB,F as AP,G as mB,H as fB,I as hB,K as Jg,L as gB,a as Wg,aa as wB,b as YL,ba as eo,c as _P,ca as yB,d as Do,da as vB,e as XL,ea as IB,f as QL,fa as yi,g as ZL,ga as xd,h as EP,ha as Kg,i as As,ia as bB,j as eB,ja as kB,k as tB,ka as SB,l as rB,la as op,m as TP,ma as _d,n as np,na as Yg,o as nB,oa as PB,p as Vg,pa as Xg,q as oB,qa as vi,r as aB,ra as RB,s as Rd,sa as xB,t as iB,ta as _B,u as Gg,ua as Qg,v as sB,va as EB,w as cB,wa as ap,x as CP,xa as TB,z as dB}from"./chunk-OXRN2257.js";import"./chunk-UTIELP6F.js";import{g as TH,j as CH,l as yd,m as AH,o as pg,s as mg}from"./chunk-TOWY6Y23.js";import"./chunk-4V73I4OL.js";import"./chunk-LE75SVEL.js";import{e as _D,g as ED,h as bP,j as wt}from"./chunk-6ESBAHWK.js";import{a as jne,b as JM,c as _S,d as ES}from"./chunk-LZPCA6DH.js";import{b as dd,c as PM}from"./chunk-L3KS6MOV.js";import"./chunk-7J2NMUTK.js";import{$b as zu,$k as Z1,Ad as zH,Af as o1,Al as dD,Bd as WH,Be as YH,Bg as mP,Bh as hP,Bk as X1,Bl as Se,Df as uP,Ej as O1,Gj as H1,Hi as Xu,Hj as yP,Ii as P1,Ij as D1,Ji as R1,Mj as L1,Nj as B1,Od as VH,Oe as XH,Oh as m1,Pd as GH,Qh as f1,Qj as $1,Re as QH,Rf as a1,Rj as N1,Sd as Wu,Sg as d1,Sh as h1,Si as x1,Sj as U1,Ta as BH,Td as Vu,Th as g1,Ub as $H,Uf as Ig,Uj as q1,Vf as bg,Vg as xg,Vh as Ku,Vi as _1,Wf as kg,Wg as _g,Wh as w1,Wi as E1,Wj as F1,Xf as i1,Xg as Eg,Xh as y1,Xi as T1,Y as Fu,Ye as ZH,Yg as l1,Yk as Q1,Ze as gg,Zi as C1,_b as NH,_i as A1,a as MH,ag as pP,aj as M1,b as Ge,bf as e1,bh as fP,cl as eD,df as Ju,dk as z1,dl as tD,ei as v1,el as rD,fa as fg,fk as Mg,fl as nD,gj as j1,gl as oD,hl as aD,if as vd,ii as Yu,ja as jH,je as Gu,jf as t1,ji as I1,ka as OH,ki as b1,kk as W1,la as hg,ld as UH,lf as r1,lk as V1,ma as HH,mk as jg,na as DH,nk as G1,ok as J1,pd as Tn,qf as n1,qg as s1,qh as u1,ql as Id,tg as Sg,th as Tg,ti as k1,tl as iD,ue as JH,ug as Pg,uh as Cg,vg as Rg,vh as Ag,vk as K1,wa as LH,wg as c1,wh as p1,xe as KH,xf as wg,xj as gP,xl as sD,yd as qH,yf as yg,yi as S1,zd as FH,zf as vg,zj as wP,zk as Y1,zl as cD}from"./chunk-2IECLXB2.js";import"./chunk-W45RKGM6.js";import{a as lD,b as uD,c as pD,d as mD,e as fD,f as hD,g as Jr,h as gD,j as Og,k as wD}from"./chunk-73COPJ32.js";import{a as qu}from"./chunk-UGDBMRCT.js";import{t as pO}from"./chunk-645T6LH7.js";import{b as iO,c as sO,f as cO,g as dO,h as lO}from"./chunk-YG3HITOU.js";import{a as aO,b as Fh}from"./chunk-F64TR23C.js";import{a as One}from"./chunk-JFXINDOQ.js";import"./chunk-EDYCSW22.js";import{b as ug,c as PH,e as RH,f as Uu,g as dP,k as lP,l as xH,m as _H}from"./chunk-Z6HWSTEP.js";import"./chunk-XGY4OQLC.js";import{d as hH,h as gH,i as wH}from"./chunk-2PVW2XFF.js";import{d as hd,e as Nu,f as QO,g as ZO,h as eH,j as sP,l as cP}from"./chunk-64EDQ7UV.js";import{$ as SO,G as yO,H as vO,J as GS,L as IO,R as bO,S as fi,U as kO,Y as Wh,Z as Vh,_ as Gh,aa as JS,ba as XS,ca as QS,da as eg,ea as ZS,fa as eP,ga as tP,ia as rP,ja as nP,ka as oP,la as aP,u as wO}from"./chunk-DLOJG7LP.js";import"./chunk-ULTV6INR.js";import{A as Xh,C as Qh,D as Zh,E as ya,a as PO,b as RO,c as Jh,f as Kh,h as KS,i as YS,k as $u,m as xO,o as _O,p as EO,r as Yh,s as TO,u as CO}from"./chunk-XKDOPNQ5.js";import"./chunk-JXLDEYRW.js";import{i as kH,m as SH}from"./chunk-GR4MJJCE.js";import{a as lH,f as uH,g as nr,r as gd,t as pH,u as mH,v as lg,w as fH,z as wd}from"./chunk-GG6PM7TB.js";import{b as Es,d as IH,f as bH}from"./chunk-2GEZ3ZY7.js";import{Ba as ag,C as NO,Ca as ln,Da as XO,F as fd,Fa as ig,H as UO,Ia as gi,J as qO,L as FO,N as zO,O as WO,W as VO,aa as hi,ba as GO,c as AO,ga as JO,ha as KO,i as MO,ja as mt,l as jO,m as OO,n as HO,o as DO,oa as ng,p as LO,q as tg,r as iP,s as BO,t as $O,u as rg,wa as jo,xa as YO,za as og}from"./chunk-BYVE4TMU.js";import"./chunk-LVXL7T5O.js";import{f as zS,m as md}from"./chunk-HIQPGYVH.js";import{E as fO,K as Bu,M as hO,N as zh,Q as gO,U as VS,V as Et,b as Lu,c as WS,i as uO,j as me,l as Xe,x as dn,y as mO}from"./chunk-3VT2PPKW.js";import"./chunk-5ZBDHIIE.js";import"./chunk-MTP3B2SU.js";import"./chunk-BLNEHU62.js";import{a as tO,b as nO}from"./chunk-UN2LKLGV.js";import"./chunk-HLJJAOI2.js";import"./chunk-AMC4Z7G4.js";import{b as rO,e as oO}from"./chunk-LK77GI6M.js";import{k as RS}from"./chunk-HVM2GUM3.js";import"./chunk-I6VMRQF4.js";import{Ba as Wj,Ua as Vj,Wa as Uh,ba as jj,bb as NS,d as Tj,db as Gj,f as $h,fb as Jj,gb as qh,hb as Kj,l as Cj,lb as Yj,m as Aj,ob as Xj,pa as Oj,sb as US,ub as qS,va as zj,wb as Qj,x as Mj,xb as Zj,yb as eO,zb as FS}from"./chunk-D6L6UNUQ.js";import"./chunk-AJXWJLZA.js";import{A as Lj,E as Bj,F as $j,G as Nh,H as Nj,I as Uj,J as qj,N as Fj,h as Hj,z as Dj}from"./chunk-OKKNDQJF.js";import{Cb as ud,Db as wa,Eb as pd,F as wj,Jb as Rj,L as Ve,Lb as xj,M as _t,O as yj,Q as vj,Qb as _j,S as Mo,Ta as Bh,Xb as Ej,ba as Ij,d as mj,da as bj,g as fj,i as hj,j as gj,ob as kj,pb as mi,qb as It,rb as Sj,ub as Pj}from"./chunk-ZEOYNUHL.js";import{$a as Dh,A as Oh,Aa as He,B as TS,C as xs,Cb as lj,D as _s,Db as uj,Eb as pj,F as YM,Fb as Lh,H as XM,I as QM,Ja as tj,La as rj,M as CS,N as AS,O as MS,Oa as nj,P as jS,Q as OS,R as HS,Ra as oj,S as DS,Sa as aj,T as LS,Wa as ij,a as GM,bb as $S,fb as sj,ga as ZM,hb as cj,kb as dj,n as KM,o as Ch,p as Ah,q as Mh,qa as Hh,r as jh,ra as ej,v as pi,va as BS}from"./chunk-ZY32SZ2P.js";import{q as zM,r as ld,s as Th}from"./chunk-OTDDXEQ6.js";import"./chunk-ECOH24MC.js";import{c as F0}from"./chunk-EJOV6Z6F.js";import"./chunk-GY7YSD6J.js";import{a as IM,b as bM,c as En,d as Ph,e as Rs,f as Hu,g as kS,h as Rh,i as kM,k as Eh,n as FM}from"./chunk-KUE46HTH.js";import{d as U0,e as q0,g as vM}from"./chunk-MZKCW6CB.js";import{a as Ou}from"./chunk-6FA3GG5B.js";import{C as sM,D as cM,I as uM,K as yS,L as vS,M as pM,S as IS,U as mM,V as bS,Z as fM,_ as hM,ca as gM,da as wM,f as Mu,fa as Ps,ga as yM,ha as Sh,v as cd,x as ju}from"./chunk-SV7ZBEK2.js";import{M as sd,O as nM,Q as oM,R as aM,S as iM,a as Ss,b as J0,c as Gr,d as _n,e as K0,f as yh,g as Y0,h as X0,i as vh,j as Ih,l as Q0,m as Z0,n as eM,o as tM,p as rM,z as wS}from"./chunk-2MEOUS24.js";import{b as G0,d as wh,e as Xn,f as Ft}from"./chunk-HNQPEOJD.js";import{g as hh,h as gS,i as V0,l as ot,m as Ee,n as T,o as gh}from"./chunk-RCT3O3HQ.js";import{a as z0,c as ks,f as fh,h as Au,i as W0,m as bh,p as dM,r as ha,s as lM,t as ga,u as kh}from"./chunk-UGOK7VTC.js";import"./chunk-ZFJWA4JK.js";import{A as v,d as Re}from"./chunk-X2J2P5ZT.js";import{a as i,b as qe,c as Be,e as xn}from"./chunk-FTQLQJQV.js";var _a=Be((H0e,GF)=>{"use strict";var WF=["nodebuffer","arraybuffer","fragments"],VF=typeof Blob<"u";VF&&WF.push("blob");GF.exports={BINARY_TYPES:WF,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:VF,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:i(()=>{},"NOOP")}});var qp=Be((L0e,wy)=>{"use strict";var{EMPTY_BUFFER:qoe}=_a(),BR=Buffer[Symbol.species];function Foe(e,t){if(e.length===0)return qoe;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let o=0;o<e.length;o++){let a=e[o];r.set(a,n),n+=a.length}return n<t?new BR(r.buffer,r.byteOffset,n):r}i(Foe,"concat");function JF(e,t,r,n,o){for(let a=0;a<o;a++)r[n+a]=e[a]^t[a&3]}i(JF,"_mask");function KF(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}i(KF,"_unmask");function zoe(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}i(zoe,"toArrayBuffer");function $R(e){if($R.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new BR(e):ArrayBuffer.isView(e)?t=new BR(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),$R.readOnly=!1),t}i($R,"toBuffer");wy.exports={concat:Foe,mask:JF,toArrayBuffer:zoe,toBuffer:$R,unmask:KF};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=qe("bufferutil");wy.exports.mask=function(t,r,n,o,a){a<48?JF(t,r,n,o,a):e.mask(t,r,n,o,a)},wy.exports.unmask=function(t,r){t.length<32?KF(t,r):e.unmask(t,r)}}catch{}});var QF=Be(($0e,XF)=>{"use strict";var YF=Symbol("kDone"),NR=Symbol("kRun"),UR=class{static{i(this,"Limiter")}constructor(t){this[YF]=()=>{this.pending--,this[NR]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[NR]()}[NR](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[YF])}}};XF.exports=UR});var Kd=Be((U0e,rz)=>{"use strict";var Fp=qe("zlib"),ZF=qp(),Woe=QF(),{kStatusCode:ez}=_a(),Voe=Buffer[Symbol.species],Goe=Buffer.from([0,0,255,255]),vy=Symbol("permessage-deflate"),Ea=Symbol("total-length"),Gd=Symbol("callback"),ji=Symbol("buffers"),Jd=Symbol("error"),yy,qR=class{static{i(this,"PerMessageDeflate")}constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!yy){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;yy=new Woe(r)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[Gd];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,n=t.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(t){let r=t[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(t){return t.forEach(r=>{Object.keys(r).forEach(n=>{let o=r[n];if(o.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else if(n==="server_max_window_bits"){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=a}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=o})}),t}decompress(t,r,n){yy.add(o=>{this._decompress(t,r,(a,s)=>{o(),n(a,s)})})}compress(t,r,n){yy.add(o=>{this._compress(t,r,(a,s)=>{o(),n(a,s)})})}_decompress(t,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let a=`${o}_max_window_bits`,s=typeof this.params[a]!="number"?Fp.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=Fp.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[vy]=this,this._inflate[Ea]=0,this._inflate[ji]=[],this._inflate.on("error",Koe),this._inflate.on("data",tz)}this._inflate[Gd]=n,this._inflate.write(t),r&&this._inflate.write(Goe),this._inflate.flush(()=>{let a=this._inflate[Jd];if(a){this._inflate.close(),this._inflate=null,n(a);return}let s=ZF.concat(this._inflate[ji],this._inflate[Ea]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ea]=0,this._inflate[ji]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,s)})}_compress(t,r,n){let o=this._isServer?"server":"client";if(!this._deflate){let a=`${o}_max_window_bits`,s=typeof this.params[a]!="number"?Fp.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=Fp.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Ea]=0,this._deflate[ji]=[],this._deflate.on("data",Joe)}this._deflate[Gd]=n,this._deflate.write(t),this._deflate.flush(Fp.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=ZF.concat(this._deflate[ji],this._deflate[Ea]);r&&(a=new Voe(a.buffer,a.byteOffset,a.length-4)),this._deflate[Gd]=null,this._deflate[Ea]=0,this._deflate[ji]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,a)})}};rz.exports=qR;function Joe(e){this[ji].push(e),this[Ea]+=e.length}i(Joe,"deflateOnData");function tz(e){if(this[Ea]+=e.length,this[vy]._maxPayload<1||this[Ea]<=this[vy]._maxPayload){this[ji].push(e);return}this[Jd]=new RangeError("Max payload size exceeded"),this[Jd].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Jd][ez]=1009,this.removeListener("data",tz),this.reset()}i(tz,"inflateOnData");function Koe(e){if(this[vy]._inflate=null,this[Jd]){this[Gd](this[Jd]);return}e[ez]=1007,this[Gd](e)}i(Koe,"inflateOnError")});var Yd=Be((F0e,Iy)=>{"use strict";var{isUtf8:nz}=qe("buffer"),{hasBlob:Yoe}=_a(),Xoe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Qoe(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}i(Qoe,"isValidStatusCode");function FR(e){let t=e.length,r=0;for(;r<t;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}i(FR,"_isValidUTF8");function Zoe(e){return Yoe&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}i(Zoe,"isBlob");Iy.exports={isBlob:Zoe,isValidStatusCode:Qoe,isValidUTF8:FR,tokenChars:Xoe};if(nz)Iy.exports.isValidUTF8=function(e){return e.length<24?FR(e):nz(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=qe("utf-8-validate");Iy.exports.isValidUTF8=function(t){return t.length<32?FR(t):e(t)}}catch{}});var JR=Be((W0e,lz)=>{"use strict";var{Writable:eae}=qe("stream"),oz=Kd(),{BINARY_TYPES:tae,EMPTY_BUFFER:az,kStatusCode:rae,kWebSocket:nae}=_a(),{concat:zR,toArrayBuffer:oae,unmask:aae}=qp(),{isValidStatusCode:iae,isValidUTF8:iz}=Yd(),by=Buffer[Symbol.species],Mn=0,sz=1,cz=2,dz=3,WR=4,VR=5,ky=6,GR=class extends eae{static{i(this,"Receiver")}constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||tae[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[nae]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Mn}_write(t,r,n){if(this._opcode===8&&this._state==Mn)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(n)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new by(n.buffer,n.byteOffset+t,n.length-t),new by(n.buffer,n.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let n=this._buffers[0],o=r.length-t;t>=n.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,t),o),this._buffers[0]=new by(n.buffer,n.byteOffset+t,n.length-t)),t-=n.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case Mn:this.getInfo(t);break;case sz:this.getPayloadLength16(t);break;case cz:this.getPayloadLength64(t);break;case dz:this.getMask();break;case WR:this.getData(t);break;case VR:case ky:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[oz.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(o);return}if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(o);return}this._payloadLength===126?this._state=sz:this._payloadLength===127?this._state=cz:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(r);return}this._masked?this._state=dz:this._state=WR}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=WR}getData(t){let r=az;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&aae(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(n);return}if(this._compressed){this._state=VR,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[oz.extensionName].decompress(t,this._fin,(o,a)=>{if(o)return r(o);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(s);return}this._fragments.push(a)}this.dataMessage(r),this._state===Mn&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=Mn;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=zR(n,r):this._binaryType==="arraybuffer"?o=oae(zR(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Mn):(this._state=ky,setImmediate(()=>{this.emit("message",o,!0),this._state=Mn,this.startLoop(t)}))}else{let o=zR(n,r);if(!this._skipUTF8Validation&&!iz(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(a);return}this._state===VR||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Mn):(this._state=ky,setImmediate(()=>{this.emit("message",o,!1),this._state=Mn,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,az),this.end();else{let n=t.readUInt16BE(0);if(!iae(n)){let a=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(a);return}let o=new by(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!iz(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(a);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=Mn;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=Mn):(this._state=ky,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=Mn,this.startLoop(r)}))}createError(t,r,n,o,a){this._loop=!1,this._errored=!0;let s=new t(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(s,this.createError),s.code=a,s[rae]=o,s}};lz.exports=GR});var XR=Be((J0e,mz)=>{"use strict";var{Duplex:G0e}=qe("stream"),{randomFillSync:sae}=qe("crypto"),{types:{isUint8Array:cae}}=qe("util"),uz=Kd(),{EMPTY_BUFFER:dae,kWebSocket:lae,NOOP:uae}=_a(),{isBlob:Xd,isValidStatusCode:pae}=Yd(),{mask:pz,toBuffer:zs}=qp(),jn=Symbol("kByteLength"),mae=Buffer.alloc(4),Sy=8*1024,Ws,Qd=Sy,ao=0,fae=1,hae=2,KR=class e{static{i(this,"Sender")}constructor(t,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ao,this.onerror=uae,this[lae]=void 0}static frame(t,r){let n,o=!1,a=2,s=!1;r.mask&&(n=r.maskBuffer||mae,r.generateMask?r.generateMask(n):(Qd===Sy&&(Ws===void 0&&(Ws=Buffer.alloc(Sy)),sae(Ws,0,Sy),Qd=0),n[0]=Ws[Qd++],n[1]=Ws[Qd++],n[2]=Ws[Qd++],n[3]=Ws[Qd++]),s=(n[0]|n[1]|n[2]|n[3])===0,a=6);let c;typeof t=="string"?(!r.mask||s)&&r[jn]!==void 0?c=r[jn]:(t=Buffer.from(t),c=t.length):(c=t.length,o=r.mask&&r.readOnly&&!s);let d=c;c>=65536?(a+=8,d=127):c>125&&(a+=2,d=126);let l=Buffer.allocUnsafe(o?c+a:a);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=d,d===126?l.writeUInt16BE(c,2):d===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),r.mask?(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],s?[l,t]:o?(pz(t,n,l,a,c),[l]):(pz(t,n,t,0,c),[l,t])):[l,t]}close(t,r,n,o){let a;if(t===void 0)a=dae;else{if(typeof t!="number"||!pae(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(a=Buffer.allocUnsafe(2+c),a.writeUInt16BE(t,0),typeof r=="string")a.write(r,2);else if(cae(r))a.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[jn]:a.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ao?this.enqueue([this.dispatch,a,!1,s,o]):this.sendFrame(e.frame(a,s),o)}ping(t,r,n){let o,a;if(typeof t=="string"?(o=Buffer.byteLength(t),a=!1):Xd(t)?(o=t.size,a=!1):(t=zs(t),o=t.length,a=zs.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[jn]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};Xd(t)?this._state!==ao?this.enqueue([this.getBlobData,t,!1,s,n]):this.getBlobData(t,!1,s,n):this._state!==ao?this.enqueue([this.dispatch,t,!1,s,n]):this.sendFrame(e.frame(t,s),n)}pong(t,r,n){let o,a;if(typeof t=="string"?(o=Buffer.byteLength(t),a=!1):Xd(t)?(o=t.size,a=!1):(t=zs(t),o=t.length,a=zs.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[jn]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};Xd(t)?this._state!==ao?this.enqueue([this.getBlobData,t,!1,s,n]):this.getBlobData(t,!1,s,n):this._state!==ao?this.enqueue([this.dispatch,t,!1,s,n]):this.sendFrame(e.frame(t,s),n)}send(t,r,n){let o=this._extensions[uz.extensionName],a=r.binary?2:1,s=r.compress,c,d;typeof t=="string"?(c=Buffer.byteLength(t),d=!1):Xd(t)?(c=t.size,d=!1):(t=zs(t),c=t.length,d=zs.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=c>=o._threshold),this._compress=s):(s=!1,a=0),r.fin&&(this._firstFragment=!0);let l={[jn]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:d,rsv1:s};Xd(t)?this._state!==ao?this.enqueue([this.getBlobData,t,this._compress,l,n]):this.getBlobData(t,this._compress,l,n):this._state!==ao?this.enqueue([this.dispatch,t,this._compress,l,n]):this.dispatch(t,this._compress,l,n)}getBlobData(t,r,n,o){this._bufferedBytes+=n[jn],this._state=hae,t.arrayBuffer().then(a=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(YR,this,c,o);return}this._bufferedBytes-=n[jn];let s=zs(a);r?this.dispatch(s,r,n,o):(this._state=ao,this.sendFrame(e.frame(s,n),o),this.dequeue())}).catch(a=>{process.nextTick(gae,this,a,o)})}dispatch(t,r,n,o){if(!r){this.sendFrame(e.frame(t,n),o);return}let a=this._extensions[uz.extensionName];this._bufferedBytes+=n[jn],this._state=fae,a.compress(t,n.fin,(s,c)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");YR(this,d,o);return}this._bufferedBytes-=n[jn],this._state=ao,n.readOnly=!1,this.sendFrame(e.frame(c,n),o),this.dequeue()})}dequeue(){for(;this._state===ao&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][jn],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][jn],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};mz.exports=KR;function YR(e,t,r){typeof r=="function"&&r(t);for(let n=0;n<e._queue.length;n++){let o=e._queue[n],a=o[o.length-1];typeof a=="function"&&a(t)}}i(YR,"callCallbacks");function gae(e,t,r){YR(e,t,r),e.onerror(t)}i(gae,"onError")});var kz=Be((Y0e,bz)=>{"use strict";var{kForOnEventAttribute:zp,kListener:QR}=_a(),fz=Symbol("kCode"),hz=Symbol("kData"),gz=Symbol("kError"),wz=Symbol("kMessage"),yz=Symbol("kReason"),Zd=Symbol("kTarget"),vz=Symbol("kType"),Iz=Symbol("kWasClean"),Ta=class{static{i(this,"Event")}constructor(t){this[Zd]=null,this[vz]=t}get target(){return this[Zd]}get type(){return this[vz]}};Object.defineProperty(Ta.prototype,"target",{enumerable:!0});Object.defineProperty(Ta.prototype,"type",{enumerable:!0});var Vs=class extends Ta{static{i(this,"CloseEvent")}constructor(t,r={}){super(t),this[fz]=r.code===void 0?0:r.code,this[yz]=r.reason===void 0?"":r.reason,this[Iz]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[fz]}get reason(){return this[yz]}get wasClean(){return this[Iz]}};Object.defineProperty(Vs.prototype,"code",{enumerable:!0});Object.defineProperty(Vs.prototype,"reason",{enumerable:!0});Object.defineProperty(Vs.prototype,"wasClean",{enumerable:!0});var el=class extends Ta{static{i(this,"ErrorEvent")}constructor(t,r={}){super(t),this[gz]=r.error===void 0?null:r.error,this[wz]=r.message===void 0?"":r.message}get error(){return this[gz]}get message(){return this[wz]}};Object.defineProperty(el.prototype,"error",{enumerable:!0});Object.defineProperty(el.prototype,"message",{enumerable:!0});var Wp=class extends Ta{static{i(this,"MessageEvent")}constructor(t,r={}){super(t),this[hz]=r.data===void 0?null:r.data}get data(){return this[hz]}};Object.defineProperty(Wp.prototype,"data",{enumerable:!0});var wae={addEventListener(e,t,r={}){for(let o of this.listeners(e))if(!r[zp]&&o[QR]===t&&!o[zp])return;let n;if(e==="message")n=i(function(a,s){let c=new Wp("message",{data:s?a:a.toString()});c[Zd]=this,Py(t,this,c)},"onMessage");else if(e==="close")n=i(function(a,s){let c=new Vs("close",{code:a,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Zd]=this,Py(t,this,c)},"onClose");else if(e==="error")n=i(function(a){let s=new el("error",{error:a,message:a.message});s[Zd]=this,Py(t,this,s)},"onError");else if(e==="open")n=i(function(){let a=new Ta("open");a[Zd]=this,Py(t,this,a)},"onOpen");else return;n[zp]=!!r[zp],n[QR]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[QR]===t&&!r[zp]){this.removeListener(e,r);break}}};bz.exports={CloseEvent:Vs,ErrorEvent:el,Event:Ta,EventTarget:wae,MessageEvent:Wp};function Py(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}i(Py,"callListener")});var Ry=Be((Q0e,Sz)=>{"use strict";var{tokenChars:Vp}=Yd();function zo(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}i(zo,"push");function yae(e){let t=Object.create(null),r=Object.create(null),n=!1,o=!1,a=!1,s,c,d=-1,l=-1,u=-1,p=0;for(;p<e.length;p++)if(l=e.charCodeAt(p),s===void 0)if(u===-1&&Vp[l]===1)d===-1&&(d=p);else if(p!==0&&(l===32||l===9))u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let g=e.slice(d,u);l===44?(zo(t,g,r),r=Object.create(null)):s=g,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===void 0)if(u===-1&&Vp[l]===1)d===-1&&(d=p);else if(l===32||l===9)u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),zo(r,e.slice(d,u),!0),l===44&&(zo(t,s,r),r=Object.create(null),s=void 0),d=u=-1}else if(l===61&&d!==-1&&u===-1)c=e.slice(d,p),d=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(Vp[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1?d=p:n||(n=!0),o=!1}else if(a)if(Vp[l]===1)d===-1&&(d=p);else if(l===34&&d!==-1)a=!1,u=p;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&e.charCodeAt(p-1)===61)a=!0;else if(u===-1&&Vp[l]===1)d===-1&&(d=p);else if(d!==-1&&(l===32||l===9))u===-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let g=e.slice(d,u);n&&(g=g.replace(/\\/g,""),n=!1),zo(r,c,g),l===44&&(zo(t,s,r),r=Object.create(null),s=void 0),c=void 0,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(d===-1||a||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let m=e.slice(d,u);return s===void 0?zo(t,m,r):(c===void 0?zo(r,m,!0):n?zo(r,c,m.replace(/\\/g,"")):zo(r,c,m),zo(t,s,r)),t}i(yae,"parse");function vae(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(n=>[t].concat(Object.keys(n).map(o=>{let a=n[o];return Array.isArray(a)||(a=[a]),a.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}i(vae,"format");Sz.exports={format:vae,parse:yae}});var Ty=Be((rMe,Hz)=>{"use strict";var Iae=qe("events"),bae=qe("https"),kae=qe("http"),xz=qe("net"),Sae=qe("tls"),{randomBytes:Pae,createHash:Rae}=qe("crypto"),{Duplex:eMe,Readable:tMe}=qe("stream"),{URL:ZR}=qe("url"),Oi=Kd(),xae=JR(),_ae=XR(),{isBlob:Eae}=Yd(),{BINARY_TYPES:Pz,CLOSE_TIMEOUT:Tae,EMPTY_BUFFER:xy,GUID:Cae,kForOnEventAttribute:ex,kListener:Aae,kStatusCode:Mae,kWebSocket:Vt,NOOP:_z}=_a(),{EventTarget:{addEventListener:jae,removeEventListener:Oae}}=kz(),{format:Hae,parse:Dae}=Ry(),{toBuffer:Lae}=qp(),Ez=Symbol("kAborted"),tx=[8,13],Ca=["CONNECTING","OPEN","CLOSING","CLOSED"],Bae=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,yt=class e extends Iae{static{i(this,"WebSocket")}constructor(t,r,n){super(),this._binaryType=Pz[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=xy,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),Tz(this,t,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){Pz.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,n){let o=new xae({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),a=new _ae(t,this._extensions,n.generateMask);this._receiver=o,this._sender=a,this._socket=t,o[Vt]=this,a[Vt]=this,t[Vt]=this,o.on("conclude",Uae),o.on("drain",qae),o.on("error",Fae),o.on("message",zae),o.on("ping",Wae),o.on("pong",Vae),a.onerror=Gae,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",Mz),t.on("data",Ey),t.on("end",jz),t.on("error",Oz),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Oi.extensionName]&&this._extensions[Oi.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){pn(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Az(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){rx(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||xy,r,n)}pong(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){rx(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||xy,r,n)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){rx(this,t,n);return}let o={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Oi.extensionName]||(o.compress=!1),this._sender.send(t||xy,o,n)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){pn(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(yt,"CONNECTING",{enumerable:!0,value:Ca.indexOf("CONNECTING")});Object.defineProperty(yt.prototype,"CONNECTING",{enumerable:!0,value:Ca.indexOf("CONNECTING")});Object.defineProperty(yt,"OPEN",{enumerable:!0,value:Ca.indexOf("OPEN")});Object.defineProperty(yt.prototype,"OPEN",{enumerable:!0,value:Ca.indexOf("OPEN")});Object.defineProperty(yt,"CLOSING",{enumerable:!0,value:Ca.indexOf("CLOSING")});Object.defineProperty(yt.prototype,"CLOSING",{enumerable:!0,value:Ca.indexOf("CLOSING")});Object.defineProperty(yt,"CLOSED",{enumerable:!0,value:Ca.indexOf("CLOSED")});Object.defineProperty(yt.prototype,"CLOSED",{enumerable:!0,value:Ca.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(yt.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(yt.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[ex])return t[Aae];return null},set(t){for(let r of this.listeners(e))if(r[ex]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[ex]:!0})}})});yt.prototype.addEventListener=jae;yt.prototype.removeEventListener=Oae;Hz.exports=yt;function Tz(e,t,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Tae,protocolVersion:tx[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!tx.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${tx.join(", ")})`);let a;if(t instanceof ZR)a=t;else try{a=new ZR(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),e._url=a.href;let s=a.protocol==="wss:",c=a.protocol==="ws+unix:",d;if(a.protocol!=="ws:"&&!s&&!c?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!a.pathname?d="The URL's pathname is empty":a.hash&&(d="The URL contains a fragment identifier"),d){let h=new SyntaxError(d);if(e._redirects===0)throw h;_y(e,h);return}let l=s?443:80,u=Pae(16).toString("base64"),p=s?bae.request:kae.request,m=new Set,g;if(o.createConnection=o.createConnection||(s?Nae:$ae),o.defaultPort=o.defaultPort||l,o.port=a.port||l,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(g=new Oi({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Hae({[Oi.extensionName]:g.offer()})),r.length){for(let h of r){if(typeof h!="string"||!Bae.test(h)||m.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(h)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),c){let h=o.path.split(":");o.socketPath=h[0],o.path=h[1]}let w;if(o.followRedirects){if(e._redirects===0){e._originalIpc=c,e._originalSecure=s,e._originalHostOrSocketPath=c?o.socketPath:a.host;let h=n&&n.headers;if(n={...n,headers:{}},h)for(let[y,f]of Object.entries(h))n.headers[y.toLowerCase()]=f}else if(e.listenerCount("redirect")===0){let h=c?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:a.host===e._originalHostOrSocketPath;(!h||e._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,h||delete o.headers.host,o.auth=void 0)}o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),w=e._req=p(o),e._redirects&&e.emit("redirect",e.url,w)}else w=e._req=p(o);o.timeout&&w.on("timeout",()=>{pn(e,w,"Opening handshake has timed out")}),w.on("error",h=>{w===null||w[Ez]||(w=e._req=null,_y(e,h))}),w.on("response",h=>{let y=h.headers.location,f=h.statusCode;if(y&&o.followRedirects&&f>=300&&f<400){if(++e._redirects>o.maxRedirects){pn(e,w,"Maximum redirects exceeded");return}w.abort();let S;try{S=new ZR(y,t)}catch{let I=new SyntaxError(`Invalid URL: ${y}`);_y(e,I);return}Tz(e,S,r,n)}else e.emit("unexpected-response",w,h)||pn(e,w,`Unexpected server response: ${h.statusCode}`)}),w.on("upgrade",(h,y,f)=>{if(e.emit("upgrade",h),e.readyState!==yt.CONNECTING)return;w=e._req=null;let S=h.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){pn(e,y,"Invalid Upgrade header");return}let k=Rae("sha1").update(u+Cae).digest("base64");if(h.headers["sec-websocket-accept"]!==k){pn(e,y,"Invalid Sec-WebSocket-Accept header");return}let I=h.headers["sec-websocket-protocol"],b;if(I!==void 0?m.size?m.has(I)||(b="Server sent an invalid subprotocol"):b="Server sent a subprotocol but none was requested":m.size&&(b="Server sent no subprotocol"),b){pn(e,y,b);return}I&&(e._protocol=I);let R=h.headers["sec-websocket-extensions"];if(R!==void 0){if(!g){pn(e,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let _;try{_=Dae(R)}catch{pn(e,y,"Invalid Sec-WebSocket-Extensions header");return}let P=Object.keys(_);if(P.length!==1||P[0]!==Oi.extensionName){pn(e,y,"Server indicated an extension that was not requested");return}try{g.accept(_[Oi.extensionName])}catch{pn(e,y,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[Oi.extensionName]=g}e.setSocket(y,f,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(w,e):w.end()}i(Tz,"initAsClient");function _y(e,t){e._readyState=yt.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}i(_y,"emitErrorAndClose");function $ae(e){return e.path=e.socketPath,xz.connect(e)}i($ae,"netConnect");function Nae(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=xz.isIP(e.host)?"":e.host),Sae.connect(e)}i(Nae,"tlsConnect");function pn(e,t,r){e._readyState=yt.CLOSING;let n=new Error(r);Error.captureStackTrace(n,pn),t.setHeader?(t[Ez]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(_y,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}i(pn,"abortHandshake");function rx(e,t,r){if(t){let n=Eae(t)?t.size:Lae(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${e.readyState} (${Ca[e.readyState]})`);process.nextTick(r,n)}}i(rx,"sendAfterClose");function Uae(e,t){let r=this[Vt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[Vt]!==void 0&&(r._socket.removeListener("data",Ey),process.nextTick(Cz,r._socket),e===1005?r.close():r.close(e,t))}i(Uae,"receiverOnConclude");function qae(){let e=this[Vt];e.isPaused||e._socket.resume()}i(qae,"receiverOnDrain");function Fae(e){let t=this[Vt];t._socket[Vt]!==void 0&&(t._socket.removeListener("data",Ey),process.nextTick(Cz,t._socket),t.close(e[Mae])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}i(Fae,"receiverOnError");function Rz(){this[Vt].emitClose()}i(Rz,"receiverOnFinish");function zae(e,t){this[Vt].emit("message",e,t)}i(zae,"receiverOnMessage");function Wae(e){let t=this[Vt];t._autoPong&&t.pong(e,!this._isServer,_z),t.emit("ping",e)}i(Wae,"receiverOnPing");function Vae(e){this[Vt].emit("pong",e)}i(Vae,"receiverOnPong");function Cz(e){e.resume()}i(Cz,"resume");function Gae(e){let t=this[Vt];t.readyState!==yt.CLOSED&&(t.readyState===yt.OPEN&&(t._readyState=yt.CLOSING,Az(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}i(Gae,"senderOnError");function Az(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}i(Az,"setCloseTimer");function Mz(){let e=this[Vt];if(this.removeListener("close",Mz),this.removeListener("data",Ey),this.removeListener("end",jz),e._readyState=yt.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[Vt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Rz),e._receiver.on("finish",Rz))}i(Mz,"socketOnClose");function Ey(e){this[Vt]._receiver.write(e)||this.pause()}i(Ey,"socketOnData");function jz(){let e=this[Vt];e._readyState=yt.CLOSING,e._receiver.end(),this.end()}i(jz,"socketOnEnd");function Oz(){let e=this[Vt];this.removeListener("error",Oz),this.on("error",_z),e&&(e._readyState=yt.CLOSING,this.destroy())}i(Oz,"socketOnError")});var $z=Be((aMe,Bz)=>{"use strict";var oMe=Ty(),{Duplex:Jae}=qe("stream");function Dz(e){e.emit("close")}i(Dz,"emitClose");function Kae(){!this.destroyed&&this._writableState.finished&&this.destroy()}i(Kae,"duplexOnEnd");function Lz(e){this.removeListener("error",Lz),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}i(Lz,"duplexOnError");function Yae(e,t){let r=!0,n=new Jae({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",i(function(a,s){let c=!s&&n._readableState.objectMode?a.toString():a;n.push(c)||e.pause()},"message")),e.once("error",i(function(a){n.destroyed||(r=!1,n.destroy(a))},"error")),e.once("close",i(function(){n.destroyed||n.push(null)},"close")),n._destroy=function(o,a){if(e.readyState===e.CLOSED){a(o),process.nextTick(Dz,n);return}let s=!1;e.once("error",i(function(d){s=!0,a(d)},"error")),e.once("close",i(function(){s||a(o),process.nextTick(Dz,n)},"close")),r&&e.terminate()},n._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",i(function(){n._final(o)},"open"));return}e._socket!==null&&(e._socket._writableState.finished?(o(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",i(function(){o()},"finish")),e.close()))},n._read=function(){e.isPaused&&e.resume()},n._write=function(o,a,s){if(e.readyState===e.CONNECTING){e.once("open",i(function(){n._write(o,a,s)},"open"));return}e.send(o,s)},n.on("end",Kae),n.on("error",Lz),n}i(Yae,"createWebSocketStream");Bz.exports=Yae});var nx=Be((sMe,Nz)=>{"use strict";var{tokenChars:Xae}=Yd();function Qae(e){let t=new Set,r=-1,n=-1,o=0;for(o;o<e.length;o++){let s=e.charCodeAt(o);if(n===-1&&Xae[s]===1)r===-1&&(r=o);else if(o!==0&&(s===32||s===9))n===-1&&r!==-1&&(n=o);else if(s===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let c=e.slice(r,n);if(t.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);t.add(c),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let a=e.slice(r,o);if(t.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return t.add(a),t}i(Qae,"parse");Nz.exports={parse:Qae}});var Gz=Be((lMe,Vz)=>{"use strict";var Zae=qe("events"),Cy=qe("http"),{Duplex:dMe}=qe("stream"),{createHash:eie}=qe("crypto"),Uz=Ry(),Gs=Kd(),tie=nx(),rie=Ty(),{CLOSE_TIMEOUT:nie,GUID:oie,kWebSocket:aie}=_a(),iie=/^[+/0-9A-Za-z]{22}==$/,qz=0,Fz=1,Wz=2,ox=class extends Zae{static{i(this,"WebSocketServer")}constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:nie,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:rie,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=Cy.createServer((n,o)=>{let a=Cy.STATUS_CODES[426];o.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),o.end(a)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=sie(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:i((o,a,s)=>{this.handleUpgrade(o,a,s,n)},"upgrade")})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=qz}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===Wz){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Gp,this);return}if(t&&this.once("close",t),this._state!==Fz)if(this._state=Fz,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Gp,this):process.nextTick(Gp,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Gp(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,n,o){r.on("error",zz);let a=t.headers["sec-websocket-key"],s=t.headers.upgrade,c=+t.headers["sec-websocket-version"];if(t.method!=="GET"){Js(this,t,r,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Js(this,t,r,400,"Invalid Upgrade header");return}if(a===void 0||!iie.test(a)){Js(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Js(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Jp(r,400);return}let d=t.headers["sec-websocket-protocol"],l=new Set;if(d!==void 0)try{l=tie.parse(d)}catch{Js(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=t.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let m=new Gs({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Uz.parse(u);g[Gs.extensionName]&&(m.accept(g[Gs.extensionName]),p[Gs.extensionName]=m)}catch{Js(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:t.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(g,w,h,y)=>{if(!g)return Jp(r,w||401,h,y);this.completeUpgrade(p,a,l,t,r,n,o)});return}if(!this.options.verifyClient(m))return Jp(r,401)}this.completeUpgrade(p,a,l,t,r,n,o)}completeUpgrade(t,r,n,o,a,s,c){if(!a.readable||!a.writable)return a.destroy();if(a[aie])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>qz)return Jp(a,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${eie("sha1").update(r+oie).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,o):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(t[Gs.extensionName]){let p=t[Gs.extensionName].params,m=Uz.format({[Gs.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),u._extensions=t}this.emit("headers",l,o),a.write(l.concat(`\r
|
|
4
4
|
`).join(`\r
|
|
5
5
|
`)),a.removeListener("error",zz),u.setSocket(a,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Gp,this)})),c(u,o)}};Vz.exports=ox;function sie(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return i(function(){for(let n of Object.keys(t))e.removeListener(n,t[n])},"removeListeners")}i(sie,"addListeners");function Gp(e){e._state=Wz,e.emit("close")}i(Gp,"emitClose");function zz(){this.destroy()}i(zz,"socketOnError");function Jp(e,t,r,n){r=r||Cy.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${Cy.STATUS_CODES[t]}\r
|
|
6
6
|
`+Object.keys(n).map(o=>`${o}: ${n[o]}`).join(`\r
|
|
@@ -57,7 +57,7 @@ process.on("message",(message)=>{const value=message;
|
|
|
57
57
|
`)}i(iue,"policyDeveloperInstructions");function sue(e,t){return[`Evaluation seed label: ${String(t.seed??0)}.`,"Conversation JSON:",JSON.stringify(e),"Produce the next assistant action now."].join(`
|
|
58
58
|
|
|
59
59
|
`)}i(sue,"policyTurnPrompt");function cue(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)).map(t=>({...t})):[]}i(cue,"policyMessages");function due(e){return Array.isArray(e)?e.map(t=>{let r=f_(t,"benchmark tool");if(r.type!=="function")throw new Error("codex_taskset_policy_tool_type_unsupported");let n=f_(r.function,"benchmark tool function"),o=wm(n.name,"benchmark tool name");return{type:"function",name:o,description:typeof n.description=="string"?n.description:`Execute ${o}.`,inputSchema:n.parameters??{type:"object",additionalProperties:!0}}}):[]}i(due,"policyTools");function lue(e,t){if(!e)return;let r=Jo(t.params);if(t.method==="item/completed"){let d=Jo(r?.item);d?.type==="agentMessage"&&typeof d.text=="string"&&d.text.trim()&&(e.agentMessages.push({text:d.text,phase:typeof d.phase=="string"?d.phase:null}),e.toolCalls.length&&(e.acceptingToolCalls=!1));return}if(t.method!=="thread/tokenUsage/updated")return;let n=Jo(r?.tokenUsage),o=Jo(n?.total);if(!o)return;let a=m_(o.inputTokens),s=m_(o.outputTokens),c=m_(o.totalTokens);a===null||s===null||c===null||(e.usage={promptTokens:a,completionTokens:s,totalTokens:c})}i(lue,"captureNotification");async function uue(e,t){if(t.method!=="item/tool/call")return An(t);if(!e)return $v("No benchmark policy request is active.");let r=f_(t.params,"Codex dynamic tool call"),n=wm(r.threadId,"Codex dynamic tool thread ID"),o=wm(r.turnId,"Codex dynamic tool turn ID"),a=wm(r.tool,"Codex dynamic tool name"),s=wm(r.callId,"Codex dynamic tool call ID");return e.threadId&&e.threadId!==n||e.turnId&&e.turnId!==o?$v("This tool call does not belong to the active benchmark request."):e.toolNames.has(a)?e.acceptingToolCalls?(e.toolCalls.push({id:s,type:"function",function:{name:a,arguments:JSON.stringify(r.arguments??{})}}),{result:{contentItems:[{type:"inputText",text:"The benchmark host captured this function call. End this response now; the real function result will be supplied in the next policy request."}],success:!0}}):$v("The benchmark host already captured the next policy action."):$v("This function is not part of the frozen benchmark tool contract.")}i(uue,"captureToolCall");function $v(e){return{result:{contentItems:[{type:"inputText",text:e}],success:!1}}}i($v,"failedToolResponse");async function pue(e,t,r,n){if(n.aborted)throw n.reason??new Error("codex_taskset_policy_aborted");let o=i(()=>{},"removeAbort"),a=new Promise((s,c)=>{let d=i(()=>{e.interruptTurn({threadId:t,turnId:r}).catch(()=>{}),c(n.reason??new Error("codex_taskset_policy_aborted"))},"listener");n.addEventListener("abort",d,{once:!0}),o=i(()=>n.removeEventListener("abort",d),"removeAbort")});try{await Promise.race([e.waitForTurn(r,10*6e4),a])}finally{o()}}i(pue,"waitForTurnWithSignal");function mue(e){return([...e].reverse().find(r=>r.phase==="final_answer")??e.at(-1))?.text.trim()||null}i(mue,"finalAgentMessage");function Jo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}i(Jo,"record");function f_(e,t){let r=Jo(e);if(!r)throw new Error(`${t} must be an object.`);return r}i(f_,"requiredRecord");function wm(e,t){if(typeof e!="string"||!e.trim())throw new Error(`${t} must be a non-empty string.`);return e.trim()}i(wm,"requiredString");function m_(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}i(m_,"nonnegativeInteger");var yue=v.object({response:v.object({choices:v.array(v.object({message:v.object({content:v.string().nullable(),tool_calls:v.array(v.object({id:v.string(),type:v.literal("function"),function:v.object({name:v.string(),arguments:v.string()})}))})})).length(1)}),usage:v.object({promptTokens:v.number().int().nonnegative(),completionTokens:v.number().int().nonnegative(),totalTokens:v.number().int().nonnegative()}).optional()});function fn(e){throw new oe("codex_experiment_not_ready",e,422)}i(fn,"fail");function Uv(e){async function t(r){e.status||fn("The signed-in Codex runtime is unavailable.");let n=await e.status(),o=h_(n.account);(!n.available||n.authHealth!=="signed_in"||!o||!n.version||!n.binaryPath)&&fn("Sign in to Codex with your ChatGPT account before evaluating.");let a=await e.state();a.settings.providers.codex?.enabled||fn("Enable Codex in Settings before evaluating.");let c=(await Bv(a.settings,n)).modelCaches.codex?.models.filter(u=>u.capabilities.reasoningEfforts?.includes("low"))??[];if(!r)return{status:n,accountHash:o,models:c};let d=c.find(u=>u.id===r);d||fn("Refresh the installed Codex catalog and select a model supporting Lite reasoning.");let l=T({providerId:"codex",modelId:r,accountHash:o,binaryPath:n.binaryPath,version:n.version,capabilities:d.capabilities,reasoningEffort:"low",isolation:"openpond.codex-text-evaluation.v1"});return{status:n,accountHash:o,models:c,model:d,configurationHash:l}}return i(t,"resolve"),{async readiness(){try{let r=await t();return{ready:!0,choices:await Promise.all(r.models.map(async n=>{let o=await t(n.id);return{id:n.id,name:n.displayName+" \xB7 Lite",providerId:"codex",configurationHash:o.configurationHash,accountHash:o.accountHash,reasoningEffort:"low",outputLimit:4096}}))}}catch(r){if(!(r instanceof oe))throw r;return{ready:!1,reason:r.message,choices:[]}}},async prepare(r){let n=r.request.policy;(!["hosted_chat","hosted_harness"].includes(n.kind)||!("localRuntime"in n)||n.localRuntime?.providerId!=="codex")&&fn("Select an exact Codex experiment runtime."),n.kind!=="hosted_chat"&&n.kind!=="hosted_harness"&&fn("Select a supported Codex target.");let o=n.kind==="hosted_harness",a=n.localRuntime,s=await t(n.modelId);(s.configurationHash!==a.configurationHash||s.accountHash!==a.accountHash||a.reasoningEffort!=="low")&&fn("Codex account, model or runtime changed. Review its current model pin."),(n.candidate||n.kind==="hosted_chat"&&(n.harness||n.temperature!==0||n.topP!==1||n.maxOutputTokens>4096)||a.maximumRequestCostUsd>r.maximumCostUsd)&&fn("Codex evaluation requires its qualified text or Profile owner and a supported request allocation.");let c=n.kind==="hosted_chat"?n.maxOutputTokens:4096,d=n.kind==="hosted_chat"?n.messages??[]:[],l={providerId:"codex",modelId:n.modelId,maxOutputTokens:c,messages:d,configurationHash:T({modelId:n.modelId,runtime:a,messages:d,maxOutputTokens:c})};return{model:l,pricing:null,maximumChargeUsd:a.maximumRequestCostUsd,streamFactory(u){return async function*(p){let m=await t(l.modelId);m.configurationHash!==a.configurationHash&&fn("Codex account or runtime changed before dispatch."),!o&&p.tools?.length&&fn("Codex text evaluations do not admit environment tools."),Buffer.byteLength(JSON.stringify(p.messages))>262144&&fn("Codex evaluation input exceeds its retained text allowance.");let g=await fue(wue.join(gue.tmpdir(),"openpond-codex-eval-")),w=(e.runtime??Nv)({modelId:l.modelId,runId:u.executionId,cwd:g,binaryPath:m.status.binaryPath,reasoningEffort:a.reasoningEffort,isolatedAccountHash:a.accountHash}),h=AbortSignal.timeout(a.requestTimeoutMs),y=p.signal?AbortSignal.any([p.signal,h]):h,f=i(()=>{w.close().catch(()=>{})},"abort");y.addEventListener("abort",f,{once:!0});try{y.throwIfAborted();let S=yue.parse(await w.complete({messages:p.messages,tools:o?p.tools??[]:[],deliveryId:u.caseId,turnIndex:p.requestId},y));y.throwIfAborted();let k=S.response.choices[0].message;(!o&&k.tool_calls.length||!k.tool_calls.length&&k.content===null)&&fn("The Codex model did not return an admitted task response."),k.content!==null&&Buffer.byteLength(k.content)>Math.min(262144,l.maxOutputTokens*4)&&fn("Codex output exceeds this run's retained output allowance."),k.content!==null&&(yield{type:"text_delta",text:k.content,raw:{}}),k.tool_calls.length&&(yield{type:"tool_call_delta",toolCalls:k.tool_calls,raw:{}}),S.usage&&(yield{type:"usage",usage:{prompt_tokens:S.usage.promptTokens,completion_tokens:S.usage.completionTokens,total_tokens:S.usage.totalTokens},raw:{}}),yield{type:"finish",finishReason:k.tool_calls.length?"tool_calls":"stop",raw:{}}}finally{y.removeEventListener("abort",f),await w.close(),await hue(g,{recursive:!0,force:!0})}}}}}}}i(Uv,"createCodexExperimentOwner");import{cp as vue,mkdtemp as Iue,rm as bue}from"node:fs/promises";import{tmpdir as kue}from"node:os";import Sue from"node:path";function lo(e){throw new He(e,409)}i(lo,"fail");function Pue(e,t){let r=e.decisions.at(-1);return(e.kind!=="author"||e.status!=="accepted"||r?.taskProposalHash!==t)&&lo("human_task_proposal_not_accepted"),e.submissions.find(n=>r.submissions.some(o=>o.id===n.id&&o.contentHash===n.contentHash)&&n.taskProposal?.contentHash===t)?.taskProposal??lo("human_task_proposal_unavailable")}i(Pue,"selected");async function qv(e){let t=Pue(e.review,e.proposalHash),r=e.baseline.taskset.metadata,n=r.sourceTasksetId,o=r.sourceTasksetHash;(typeof n!="string"||typeof o!="string")&&lo("human_local_authored_source_unavailable");let a=await e.store.getTasksetRevision(n,e.baseline.taskset.revision,o);a||lo("human_local_authored_source_unavailable");let s=await e.store.readHumanPublishedTasksetDraft(a.profileId,{id:a.id,revision:a.revision,contentHash:a.contentHash});s||lo("human_local_authored_source_unavailable");let c=`human-author-${T([e.actorId,e.review.scope,e.review.id,e.proposalHash])}`,d={reviewId:e.review.id,proposalHash:e.proposalHash,actorId:e.actorId,scope:e.review.scope,projectId:e.review.projectId,baseline:e.review.evidence.dataset},l=await e.store.getTasksetDraft(c);if(l&&T(l.metadata.humanTaskProposal)!==T(d)&&lo("human_task_publication_operation_conflict"),!l){let y=await Iue(Sue.join(kue(),"human-author-"));try{await vue(s.workspace.workspacePath,y,{recursive:!0,errorOnExist:!1,force:!1}),await yH({...s.draft,id:c,revision:1,status:"draft",modelScope:null,tasks:Oh(s.draft.tasks,t),metadata:{...s.draft.metadata,humanTaskProposal:d}},y),l=await e.store.importTasksetDraftPackage({packagePath:y,profileId:a.profileId})}finally{await bue(y,{recursive:!0,force:!0})}}if(l.status!=="published"){T(l.tasks)!==T(Oh(s.draft.tasks,t))&&lo("human_task_publication_draft_changed"),l.publishedTasksetRef||(l=await e.store.saveTasksetDraft({...l,publishedTasksetRef:s.draft.publishedTasksetRef},l.revision));let y=await e.store.getTasksetDraftWorkspace(l.id);y||lo("human_task_publication_source_missing");let f=wd({draft:l,now:l.updatedAt,sourcePackageHash:y.packageHash}),S=await e.store.materializePublishedTasksetPackage({draftId:l.id,taskset:f});l=(await e.store.finalizeTasksetDraftPublication({draft:l,packageHash:y.packageHash,taskset:S.taskset})).draft}let u=l.publishedTasksetRef??lo("human_task_publication_missing"),p=await e.store.getTasksetRevision(u.id,u.revision,u.contentHash);p||lo("human_task_publication_missing");let m=gi({taskset:p,rewardExecution:await Pa(e.store,p),adapterId:Bw(p)}),g=await $w({storeDir:e.storeDir,taskset:p,content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:m.tasksetRelease,environment:m.environmentRelease,verifierSet:m.verifierSetRelease,...e.baseline.modelResources?{modelResources:e.baseline.modelResources}:{},...e.baseline.learningResources?{learningResources:e.baseline.learningResources}:{}}}),w=e.baseline.taskset,h=g.taskset;return(T(Oh(w.tasks,t))!==T(h.tasks)||["policy","tools","capabilities","graders"].some(y=>T(w[y])!==T(h[y])))&&lo("human_task_publication_contract_mismatch"),await jp(e.storeDir,g),g}i(qv,"publishLocalHumanTaskProposal");async function g_(e){let t=T(e.release),r=new Set(e.ancestors);if(r.has(t)||r.size>=100)throw new He("human_task_publication_lineage_cycle",409);r.add(t);let n=await e.store.humanReviewRepository().transaction(e.scope,async m=>{let g=[],w;do{let h=await m.list({projectId:e.projectId,afterId:w,limit:100});g.push(...h.items.filter(y=>y.authorPublication&&T(y.authorPublication.dataset)===t)),w=h.nextCursor??void 0}while(w);return g});if(!n.length)return null;if(n.length!==1)throw new He("human_task_publication_identity_conflict",409);let o=YM.parse(n[0]),{contentHash:a,...s}=o;if(a!==T(s)||o.scope!==e.scope||o.projectId!==e.projectId||o.createdBy!==e.actorId||o.authorPublication?.publishedBy!==e.actorId)throw new He("human_task_publication_source_denied",403);let c=o.authorPublication.proposalHash,d=`human-author-${T([e.actorId,e.scope,o.id,c])}`,l=await e.store.getTasksetDraft(d);if(!l||l.status!=="published")throw new He("human_task_publication_source_unavailable",409);let u=await g_({...e,release:o.evidence.dataset,ancestors:r})??await e.loadBaseline(o.evidence.dataset),p=await qv({store:e.store,storeDir:e.storeDir,actorId:e.actorId,review:o,proposalHash:c,baseline:u});if(T({id:p.taskset.id,revision:p.taskset.revision,contentHash:p.taskset.contentHash})!==t)throw new He("human_task_publication_release_changed",409);return p}i(g_,"resolveLocalHumanPublishedPackage");function On(e){throw new oe("local_inference_not_qualified",e,422)}i(On,"fail");function Fv(e){async function t(r){let n=await e(),o=n.settings.providers["custom-openai-compatible"],a=n.settings.modelCaches["custom-openai-compatible"]?.models.find(l=>l.id===r);(!o?.enabled||!a)&&On("Enable the local OpenAI-compatible provider and refresh its model catalog.");let s;try{s=a2({providerId:"custom-openai-compatible",settings:n.settings,secrets:n.secrets,modelId:r})}catch(l){On(l instanceof Error?l.message:"The local provider configuration is incomplete.")}let c=new URL(s.baseUrl);["localhost","127.0.0.1","[::1]","::1"].includes(c.hostname)||On("This local inference adapter requires an explicit loopback endpoint."),(!a.contextWindow||!a.outputLimit||!a.capabilities.streaming)&&On("The current local model catalog must report context/output bounds and streaming support.");let d={providerId:s.providerId,modelId:r,endpointHash:T(s.baseUrl),contextWindow:a.contextWindow,outputLimit:a.outputLimit,capabilities:a.capabilities};return{current:n,model:a,configurationHash:T(d)}}return i(t,"resolve"),{async choices(){let r=await e(),n=r.settings.modelCaches["custom-openai-compatible"]?.models??[],o=[];for(let a of n)try{let s=await t(a.id);o.push({id:a.id,name:a.displayName,providerId:"custom-openai-compatible",configurationHash:s.configurationHash,contextWindow:a.contextWindow,outputLimit:a.outputLimit})}catch(s){if(!(s instanceof oe))throw s}return o},async prepare(r){let n=r.request.policy;(n.kind!=="hosted_chat"||n.localRuntime?.providerId!=="custom-openai-compatible")&&On("Select an explicit local inference runtime.");let o=await t(n.modelId),a=n.localRuntime;o.configurationHash!==a.configurationHash&&On("The local provider configuration changed. Review its current model before starting."),(n.harness||n.candidate)&&On("This model-only local inference adapter does not admit a native Harness or candidate runtime."),(n.maxOutputTokens>o.model.outputLimit||a.maximumRequestCostUsd>r.maximumCostUsd)&&On("The selected output/request allocation exceeds this run's limits.");let s=o.model.raw?.capabilities,c=s?.samplingParameters===!0;!c&&(n.temperature!==0||n.topP!==1)&&On("This local model has not declared configurable sampling.");let d={providerId:"custom-openai-compatible",modelId:n.modelId,maxOutputTokens:n.maxOutputTokens,...c?{temperature:n.temperature,topP:n.topP}:{},messages:n.messages??[]};return{model:{...d,configurationHash:T({model:d,runtime:a})},pricing:null,maximumChargeUsd:a.maximumRequestCostUsd,stream:i(async function*(l){let u=await t(d.modelId);u.configurationHash!==a.configurationHash&&On("The local provider changed before dispatch."),l.tools?.length&&!u.model.capabilities.toolCalling&&On("This local model has not declared tool calling."),new TextEncoder().encode(JSON.stringify(l.messages)).byteLength>Math.min(2097152,u.model.contextWindow*2)&&On("Policy-visible messages exceed this local model's bounded input allowance.");for await(let m of Ew({providerId:"custom-openai-compatible",settings:u.current.settings,secrets:u.current.secrets,modelId:d.modelId,messages:l.messages,tools:l.tools,requestId:l.requestId,maxOutputTokens:l.maxTokens,temperature:l.temperature,topP:l.topP,signal:l.signal,requestTimeoutMs:a.requestTimeoutMs}))m.type==="usage"?yield{type:"usage",usage:m.usage,raw:m.raw}:m.type!=="reasoning_delta"&&(yield m)},"stream")}}}}i(Fv,"createLocalInferenceOwner");async function b5(e,t,r){let n=uD.parse(r),[o,a]=await Promise.all([e.localExperimentDiagnosticTrace({teamId:t.teamId,id:t.id,afterSequence:n.afterSequence}),e.readLocalExecutionCharges(t.teamId,t.id)]),s=[...a].sort((u,p)=>u.requestId<p.requestId?-1:u.requestId>p.requestId?1:0).filter(u=>!n.afterCallId||u.requestId>n.afterCallId).slice(0,101),c=i(u=>typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null,"amount"),d=a.filter(u=>u.status==="settled"&&u.costUsd!==null),l=a.filter(u=>["reserved","dispatched","unknown"].includes(u.status));return pD({schemaVersion:"openpond.runDiagnostics.v1",teamId:t.teamId,runId:t.id,location:"local",manifestHash:t.executionHash,observedAt:new Date().toISOString(),status:t.status,startedAt:null,completedAt:t.completedAt,error:fD(t.error),resultAvailable:t.counts.completed+t.counts.failed>0,parent:null,accounting:{maximumUsd:t.maximumCostUsd,settledUsd:d.length?d.reduce((u,p)=>u+p.costUsd,0):null,outstandingUsd:t.usage.heldUsd,outstandingCount:l.length,final:t.completedAt!==null&&t.usage.costUsd!==null&&d.length>0&&l.length===0&&t.usage.heldUsd===0,receiptCount:d.length},events:o.items.map(u=>mD({id:`local:${u.sequence}`,sequence:u.sequence,at:null,type:u.type,payload:{...u.payload!==null&&typeof u.payload=="object"?u.payload:{},taskId:u.taskId}})),eventCount:o.count,nextEventCursor:o.nextCursor,calls:s.slice(0,100).map(u=>{let p=u.usage!==null&&typeof u.usage=="object"?u.usage:{};return{id:u.requestId,kind:"policy",status:u.status,receiptId:null,maximumUsd:u.maximumUsd,settledUsd:u.status==="settled"?u.costUsd:null,model:t.model.modelId,durationMs:c(p.durationMs),inputTokens:c(p.inputTokens??p.promptTokens),outputTokens:c(p.outputTokens??p.completionTokens),totalTokens:c(p.totalTokens)}}),nextCallCursor:s.length>100?s[99].requestId:null,callCount:a.length,limitations:["Local execution records retain creation time but no measured execution start. Elapsed execution time is unknown.","Local event records retain sequence but not wall timestamps; phase duration is unknown unless separately retained.","Local provider charges may not retain token or timing receipts. Missing values remain unknown.",`Local resource cleanup: ${t.cleanupComplete?"confirmed":"not confirmed"}.`,`Selected execution hash: ${t.executionHash}.`]})}i(b5,"readLocalRunDiagnostics");function sc(e){let t=v.object({taskId:v.string(),status:v.string(),output:v.string().nullable(),error:v.string().nullable(),messages:v.array(v.unknown()).max(4002),environmentCleanupComplete:v.boolean(),contentHash:v.string(),externalProcess:Jh.optional(),native:UB.optional(),profileNative:qB.optional()}).passthrough().parse(e),{contentHash:r,...n}=t;if(T(n)!==r)throw new oe("local_case_integrity_failed","Retained case output differs from its sealed receipt.");if(t.externalProcess&&t.externalProcess.outputHash!==T(t.output))throw new oe("local_process_output_conflict","Retained process receipt changed its exact output.");if(!t.environmentCleanupComplete)throw new oe("local_case_cleanup_unconfirmed","The case executor has not confirmed environment cleanup.");return t}i(sc,"localRetainedAttempt");function Lt(e){let t=v.object({attempt:v.unknown(),grade:Kh.nullable(),contentHash:v.string()}).strict().parse(e),{contentHash:r,...n}=t;if(r!==T(n))throw new oe("local_case_result_integrity_failed","Retained local case evidence changed.");return{...t,attempt:sc(t.attempt)}}i(Lt,"localRetainedCase");function gl(e,t){sc(e);let r={attempt:e,grade:t};return{...r,contentHash:T(r)}}i(gl,"sealLocalRetainedCase");function zv(e){if(!e.snapshot)return null;let t=v.object({definition:v.record(v.string(),v.unknown()),initialStateHash:v.string(),finalStateHash:v.string(),state:v.record(v.string(),v.unknown()),events:v.array(v.unknown())}).passthrough().parse(e.snapshot);return{environment:{status:e.status,collected:e.collected===!0,definition:t.definition,initialStateHash:t.initialStateHash,finalStateHash:t.finalStateHash,finalState:t.state,events:t.events}}}i(zv,"localEvaluatorContext");var Rue=v.object({provider:v.literal("claude-code"),sessionId:v.uuid(),requestId:v.string(),modelId:v.string(),runtime:PO,sourceHash:v.string(),startedAt:v.iso.datetime()}),xue=v.object({sessionId:v.uuid(),confirmed:v.literal(!0),completedAt:v.iso.datetime()});async function ym(e){let t=[],r;do{let n=await e.store.localExperimentTrace({teamId:e.teamId,id:e.executionId,caseId:e.caseId,limit:500,...r?{afterSequence:r}:{}});if(t.push(...n.items.filter(o=>o.type.startsWith("external."))),t.length>2e4)throw new oe("claude_trace_limit","Retained process trace exceeds its exact population bound.",422);r=n.nextCursor??void 0}while(r);return t}i(ym,"readClaudeProcessEvents");async function w_(e){let t=sc(e.attempt),r=await ym(e),n=r.find(p=>p.type==="external.start"),o=[...r].reverse().find(p=>p.type==="external.cleanup");if(!n||!o)throw new oe("claude_cleanup_unconfirmed","The process owner has not retained its actual session/cleanup receipt.",422);let a=Rue.parse(n.payload),s=xue.parse(o.payload);if(a.sessionId!==s.sessionId||r.some(p=>{let m=v.record(v.string(),v.unknown()).parse(p.payload);return m.sessionId!==void 0&&m.sessionId!==a.sessionId}))throw new oe("claude_trace_identity_conflict","Retained events changed the admitted process session.",422);let c=Jh.parse({provider:a.provider,sessionId:a.sessionId,requestId:a.requestId,modelId:a.modelId,runtime:a.runtime,sourceHash:a.sourceHash,outputHash:T(t.output),traceHash:T(r),runtimeEventRefs:r.map(p=>String(p.sequence)),eventCount:r.length,startedAt:a.startedAt,completedAt:s.completedAt,cleanupComplete:!0}),{contentHash:d,...l}=t,u={...l,externalProcess:c};return{...u,contentHash:T(u)}}i(w_,"retainClaudeProcessEvidence");import{randomUUID as Eue}from"node:crypto";import{AsyncLocalStorage as Tue}from"node:async_hooks";async function Wv(e){let t=e.judgeProvider??Fo(),r=i(async l=>{if(e.selectedRewards){let p=e.selectedRewards.assets.find(m=>m.id===l.id);if(!p)throw new Error("The exact selected Reward asset is unavailable.");return import("./learning-3XDYMYBE.js").then(m=>m.verifyLearningTextAsset(p,l))}let u=e.package?.files.find(p=>p.asset.id===l.id);if(!u||T(u.asset)!==T(l)||u.asset.visibility==="policy")throw new oe("local_private_grader_asset_missing","The exact private grader asset is unavailable.",422);return new TextDecoder("utf-8",{fatal:!0}).decode(hi(u))},"readPrivate"),n=e.selectedRewards?ic(e.selectedRewards).specs:e.package.taskset.graders,o=e.graders.map(l=>{let u=n.find(p=>p.id===l.id&&p.version===l.version&&T(p)===l.contentHash);if(!u)throw new oe("local_grader_pin_unavailable","The scoring pass requires the exact retained grader release.",422);return u});if(o.some(l=>l.kind==="custom_verifier"&&l.runtime==="sandbox_process")&&(!e.package||e.selectedRewards))throw new oe("local_private_process_package_required","Process grading requires the exact retained Dataset package and its private assets.",422);let a=e.evidence.output&&typeof e.evidence.output=="object"&&Array.isArray(e.evidence.output.artifacts)?e.evidence.output.artifacts:[],s=[];for(let[l,u]of o.entries()){e.signal.throwIfAborted();let p=e.graders[l],m=CO({input:e.task.input,expectedOutput:e.task.expectedOutput,output:e.evidence.output,evaluatorContext:e.evaluatorContext},p.mappings??[]),g={...e.task,input:m.input,expectedOutput:m.expectedOutput},w={...e.evidence,output:m.output};await e.beforeDispatch?.();let h=await rj({task:g,evidence:w,evaluatorContext:m.evaluatorContext,graders:[u],signal:e.signal,modelJudge:mj({readRubric:r,async executeBudgeted(y,f){let S=await t.prepare(y,{scope:e.teamId,run:{id:e.executionId,requestedBy:"local-capability-owner"}}),k=fj({maximumCharge:i(()=>S.maximumChargeUsd,"maximumCharge"),dispatch:i(async(b,R)=>(await e.beforeDispatch?.(),R?.throwIfAborted(),S.dispatch(R)),"dispatch"),store:{transaction:i((b,R)=>e.store.localJudgeBudgetTransaction({teamId:e.teamId,id:e.executionId,ownerId:e.ownerId,caseId:e.caseId,intent:b},R),"transaction")}}),I=`local-judge-${T([e.executionId,e.caseId,p,y]).slice(0,48)}`;try{return await k(I,y,f)}catch(b){throw b instanceof Uw&&b.executionId===e.executionId&&await e.store.localJudgeBudgetTransaction({teamId:e.teamId,id:e.executionId,ownerId:e.ownerId,caseId:e.caseId,intent:"settle"},R=>{let _=R.calls.find(P=>P.id===I);if(!_||_.requestHash!==T(y)||_.status!=="reserved"||_.response!==null)throw new oe("local_judge_no_dispatch_conflict","The unused judge reservation changed before settlement.");return{calls:R.calls.map(P=>P.id===I?{...P,status:"not_dispatched"}:P),result:null}}),b}}}),customVerifier:i(async({grader:y,task:f,evidence:S})=>{await e.beforeDispatch?.();let k=y.runtime==="sandbox_process"?await uU({packageValue:e.package,grader:y,task:f,evidence:{...S,artifacts:a},signal:e.signal,authorize:i(async()=>{await e.beforeDispatch?.()},"authorize")}):await Vw({source:await r(y.verifierRef),exportName:y.exportName,runtime:y.runtime,timeoutMs:y.timeoutMs,signal:e.signal,value:{task:f,attempt:S,input:f.input,output:S.output,artifacts:a,expectedOutput:f.expectedOutput,evaluatorContext:m.evaluatorContext,infrastructureError:S.infrastructureError??null}});return await e.beforeDispatch?.(),{score:k.score,passed:k.passed,rewardEligible:y.rewardEligible,failureClass:null,feedback:[k.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:k.evidenceRefs}},"customVerifier")});await e.beforeDispatch?.(),s.push(h)}let c=tj({graders:o,components:s.flatMap(l=>l.components)}),d={schemaVersion:"openpond.experimentAttemptGrade.v1",selectionHash:T(e.graders),grades:s,...c};return Kh.parse({...d,contentHash:T(d)})}i(Wv,"gradeLocalExperimentCase");function k5(e){async function t(o,a){if(e.closing())throw new oe("local_runtime_closing","The local execution owner is closing.",503);let s=o.request.teamId;await e.requireTeam(s),e.assertScope(o);let c=await e.actorId();if(!c.trim())throw new oe("local_account_required","Sign in before running a local Experiment.",403);let d=T({ownerActorId:c,intent:a}),l=await e.store.recoverLocalExperimentOperation(s,o.operationId,"run",d);return l?{prior:await e.ownedRecord(s,dp.parse(l).id),ownerActorId:c,intentHash:d}:(o.sourceExperimentId&&await e.ownedRecord(s,o.sourceExperimentId),{prior:null,ownerActorId:c,intentHash:d})}i(t,"begin");async function r(o,a,s){let c=mt(a),d=o.request.teamId,{sourceExperimentId:l,...u}=o,p={...u,expectedRevision:0};await e.authorize(p);let m=await e.preflight(p,c),g=e.prepareModel?await e.prepareModel(p):o.request.policy.kind==="hosted_chat"&&o.request.policy.localRuntime?await(e.localInference?.prepare(p)??Promise.reject(new oe("local_inference_unavailable","The configured local inference owner is unavailable.",422))):await Ra(o.request.policy,e.catalog,m.native);if(g.maximumChargeUsd>o.maximumCostUsd+1e-12)throw new oe("experiment_budget_exhausted",`The $${o.maximumCostUsd} cap cannot cover this model's $${g.maximumChargeUsd.toFixed(6)} maximum request reservation. Increase the cap before starting; no model call was made.`,422);await e.requireActor(s),await e.requireTeam(d);let w=`local-run-${T([d,s,o.operationId]).slice(0,48)}`,h=new Date().toISOString(),y={schemaVersion:"openpond.localExperimentDefinition.v1",location:"local",id:`local-configuration-${T([d,s,o.operationId]).slice(0,40)}`,teamId:d,ownerActorId:s,revision:1,configuration:p,model:g.model,packageHash:c.contentHash,graders:Jw(c,o.graders),availableGraders:Sr(c),createdAt:h,updatedAt:h},f=DB.parse({...y,contentHash:T(y)}),S={configuration:o,model:f.model,packageHash:f.packageHash,graders:f.graders,availableGraders:f.availableGraders},k=BB.parse({...S,configurationHash:T(S)}),I=wU(f,c,w,m.native,m.environment,m.profile);return{definition:f,snapshot:k,admissions:I,model:g,value:c,id:w,now:h}}i(r,"qualify");async function n(o,a,s){let{definition:c,snapshot:d,admissions:l,model:u,value:p,id:m,now:g}=await r(o,a,s.ownerActorId),w=o.request.teamId,h=s.ownerActorId,y={id:c.id,revision:1,contentHash:c.contentHash},f=sp.parse({schemaVersion:"openpond.localExperimentExecution.v1",location:"local",id:m,teamId:w,ownerActorId:h,kind:"target",operationId:o.operationId,definition:y,packageHash:p.contentHash,maximumCostUsd:o.maximumCostUsd,executionHash:T({id:m,teamId:w,configurationHash:d.configurationHash,packageHash:p.contentHash,admissions:l}),sourceExecution:null,status:"queued",createdAt:g,completedAt:null,counts:{pending:l.length,running:0,completed:0,failed:0,cancelled:0,unknown:0},usage:{knownCostUsd:0,costUsd:0,heldUsd:0,uncertainRequests:0},cleanupComplete:!1,error:null}),S=await e.store.admitLocalExperimentRun({ownerId:e.ownerId,intentHash:s.intentHash,definition:c,snapshot:d,package:p,execution:f,admissions:l}),k=await e.ownedRecord(w,S.id);return k.status==="queued"&&e.schedule(f,l,u),k}return i(n,"admit"),{authorize:i(async o=>{let a=MP.parse(o),s=a.configuration;await e.requireTeam(s.request.teamId),e.assertScope(s);let c=await e.actorId();if(!c.trim())throw new oe("local_account_required","Sign in before qualifying local evaluation.",403);s.sourceExperimentId&&await e.ownedRecord(s.request.teamId,s.sourceExperimentId);let d=mt(await e.package(a));if(a.expectedPackageHash&&d.contentHash!==a.expectedPackageHash)throw new oe("local_package_pin_conflict","The exact Dataset package changed.",409);await r(s,d,c),await e.requireActor(c),await e.requireTeam(s.request.teamId)},"authorize"),run:i(async o=>{let a=cp.parse(o),s=mt(a.package),c=await t(a.configuration,{kind:"package",configuration:a.configuration,packageHash:s.contentHash});return c.prior??n(a.configuration,s,c)},"run"),runFromRelease:i(async o=>{let a=MP.parse(o),s=await t(a.configuration,{kind:"release",input:a});if(s.prior)return s.prior;let c=mt(await e.package(a));if(a.expectedPackageHash&&c.contentHash!==a.expectedPackageHash)throw new oe("local_package_pin_conflict","The retained Dataset package differs from the reviewed release.",409);return n(a.configuration,c,s)},"runFromRelease")}}i(k5,"createLocalExperimentRunAdmission");function S5(e){async function t(a,s,c=!1){await e.requireTeam(s);let d=ew.omit({graderPackage:!0,graders:!0}).extend({graders:qu.shape.graders,mappings:qu.shape.mappings}),l=c?d.parse(a):ew.parse(a);await e.requireExecution(s,l.execution.id);let u=await e.store.readLocalExecution(s,l.execution.id);await e.requireActor(u.execution.ownerActorId);let p=T({ownerActorId:u.execution.ownerActorId,input:l}),m=await e.store.recoverLocalExperimentOperation(s,l.operationId,"score",p);if(m)return(await e.store.readLocalExecution(s,sp.parse(m).id)).execution;if(u.execution.executionHash!==l.execution.executionHash||u.execution.kind!=="target")throw new oe("local_scoring_source_conflict","Select the exact original local execution.");let g=c?await e.resolveSelectedRewards?.(s,u.execution.ownerActorId,d.parse(l)):void 0;if(c&&!g)throw new Error("This owner cannot resolve the exact selected Reward closure.");let w=g?.closure??mt("graderPackage"in l?l.graderPackage:null),h=g?.graders??Jw(mt(w),ew.parse(l).graders),y=`local-score-${T([s,l.operationId]).slice(0,48)}`,f=sp.parse({...u.execution,id:y,operationId:l.operationId,kind:"scoring",sourceExecution:l.execution,executionHash:T({id:y,source:l.execution,graderPackage:w.contentHash,graders:h,maximumCostUsd:l.maximumCostUsd}),maximumCostUsd:l.maximumCostUsd,status:"queued",createdAt:new Date().toISOString(),completedAt:null,counts:{pending:u.cases.length,running:0,completed:0,failed:0,cancelled:0,unknown:0},usage:{knownCostUsd:0,costUsd:0,heldUsd:0,uncertainRequests:0},cleanupComplete:!1,error:null}),S=await e.store.startLocalScoringPass({operationId:l.operationId,intentHash:p,ownerId:e.ownerId,execution:f,admissions:u.cases.map(k=>k.admission),package:w,graders:h});if(!e.active.has(y)){let k=r(S).finally(()=>{e.active.delete(y),e.controllers.delete(y)});e.active.set(y,k)}return S}i(t,"score");async function r(a){let s=new AbortController;e.controllers.set(a.id,s);let c=null;try{let d=await e.store.readLocalScoringSelection(a.teamId,a.id),l=typeof d.package=="object"&&d.package!==null&&"schemaVersion"in d.package&&d.package.schemaVersion==="openpond.localSelectedRewardClosure.v1"?ic(d.package).closure:null,u=l?null:mt(d.package),p=await e.store.readLocalExecution(a.teamId,d.sourceExecutionId),m=await e.store.readLocalExperiment(a.teamId,p.execution.definition.id,p.execution.definition.revision),g=mt(m.package),w=l?{graders:l.rewards.map(y=>({id:y.id,revision:y.revision,contentHash:y.contentHash})),mappings:d.graders.map(y=>({graderId:y.id,fields:y.mappings??[]}))}:null;async function h(){s.signal.throwIfAborted();let y=await e.store.readLocalExecution(a.teamId,a.id);if(!["queued","running"].includes(y.execution.status))throw new Error("The actual local grading pass is no longer active.");if(await e.requireTeam(a.teamId),await e.requireActor(a.ownerActorId),await e.requireExecution(a.teamId,d.sourceExecutionId),l){let f=await e.resolveSelectedRewards?.(a.teamId,a.ownerActorId,w);if(!f||T(f.closure)!==T(l))throw new Error("The selected Reward source changed during grading.");await f.authorize()}s.signal.throwIfAborted()}i(h,"current"),await h();for(let y of p.cases){if(!await e.store.admitLocalCase(a.teamId,a.id,y.receiptId,e.ownerId))break;try{if(s.signal.throwIfAborted(),!y.result)throw new oe("local_scoring_evidence_missing","This original case has no retained target output.",422);let f=Lt(y.result),S=g.taskset.tasks.find(b=>b.id===y.admission.taskId),k=await Yw({storeDir:e.storeDir,attempt:f.attempt,signal:s.signal,events:i(async b=>{if(!e.runtimeEventsForTurn)throw new Error("The actual artifact trace owner is unavailable.");return e.runtimeEventsForTurn(b)},"events"),authorize:h}),I=await Wv({store:e.store,ownerId:e.ownerId,teamId:a.teamId,executionId:a.id,caseId:y.receiptId,...l?{selectedRewards:l}:{package:u},beforeDispatch:h,task:S,evidence:{output:{text:f.attempt.output??"",...k.length?{artifacts:k}:{}},runtimeEventRefs:f.attempt.native?.runtimeEventRefs??f.attempt.profileNative?.runtimeEventRefs??[],artifactRefs:Array.isArray(f.attempt.artifactRefs)?f.attempt.artifactRefs.map(b=>{if(!b||typeof b!="object"||!("id"in b)||typeof b.id!="string")throw new Error("The retained artifact identity changed.");return b.id}):[],infrastructureError:y.status==="completed"?null:y.error??y.status},evaluatorContext:zv(f.attempt),graders:d.graders,signal:s.signal,judgeProvider:Fo({stream:e.streamForActor(a.ownerActorId,a.teamId),catalog:e.catalog})});await h(),await e.store.settleLocalCase({teamId:a.teamId,id:a.id,receiptId:y.receiptId,ownerId:e.ownerId,status:"completed",result:gl(f.attempt,I),error:null})}catch(f){c=(f instanceof Error?f.message:"Local scoring failed.").slice(0,2e3),await e.store.settleLocalCase({teamId:a.teamId,id:a.id,receiptId:y.receiptId,ownerId:e.ownerId,status:s.signal.aborted?"cancelled":"failed",result:y.result?gl(Lt(y.result).attempt,null):null,error:c});break}}await e.store.finishLocalExecution(a.teamId,a.id,e.ownerId,c)}catch(d){c=(d instanceof Error?d.message:"Local scoring failed.").slice(0,2e3),await e.store.finishLocalExecution(a.teamId,a.id,e.ownerId,c).catch(()=>{})}}i(r,"run");async function n(a){let s=v.object({teamId:v.string().min(1),executionId:v.string().min(1),afterId:v.string().optional(),limit:v.number().int().min(1).max(100).default(30)}).strict().parse(a);return await e.requireTeam(s.teamId),await e.requireActor((await e.store.readLocalExecution(s.teamId,s.executionId)).execution.ownerActorId),await e.requireExecution(s.teamId,s.executionId),e.store.listLocalScoringPasses(s.teamId,s.executionId,s.afterId,s.limit)}i(n,"passes");async function o(a){let s=v.object({teamId:v.string().min(1),id:v.string().min(1)}).strict().parse(a);await e.requireTeam(s.teamId);let c=(await e.store.readLocalExecution(s.teamId,s.id)).execution,d=await e.store.readLocalScoringSelection(s.teamId,s.id);return await e.requireExecution(s.teamId,s.id),await e.requireActor(c.ownerActorId),{execution:c,graders:d.graders,graderPackageHash:typeof d.package=="object"&&d.package!==null&&"schemaVersion"in d.package&&d.package.schemaVersion==="openpond.localSelectedRewardClosure.v1"?ic(d.package).closure.contentHash:mt(d.package).contentHash}}return i(o,"pass"),{score:t,scoreSelected:i((a,s)=>t(a,s,!0),"scoreSelected"),passes:n,pass:o}}i(S5,"createLocalExperimentScoring");function P5(e){let{execution:t,cases:r}=e.retained,n=e.definition,o=mt(e.package);if(gh(n,"Local Experiment definition"),t.definition.id!==n.id||t.definition.revision!==n.revision||t.definition.contentHash!==n.contentHash||t.teamId!==n.teamId||t.ownerActorId!==n.ownerActorId||t.packageHash!==o.contentHash||n.packageHash!==o.contentHash)throw new oe("local_portable_source_conflict","Retained execution differs from its exact definition or Dataset package.");if(!t.completedAt||r.some(g=>g.status==="pending"||g.status==="running"))throw new oe("local_comparison_not_terminal","Wait for the complete retained execution before comparing.",422);if(e.retainedConfigurationHash&&e.retainedConfigurationHash!==n.contentHash)throw new oe("local_portable_source_conflict","Historical configuration differs from its sealed original hash.");let a=n.configuration.request.policy,s=a.kind==="fixture"?{kind:"fixture",configurationHash:T(a)}:a.kind==="hosted_harness"?{kind:"harness",source:a.source,model:{modelId:n.model.modelId,configurationHash:n.model.configurationHash}}:a.harness?{kind:"agent",source:a.harness,model:{modelId:n.model.modelId,configurationHash:n.model.configurationHash}}:{kind:"model",modelId:n.model.modelId,configurationHash:n.model.configurationHash},c=n.configuration.request.population,d=new Map(c.map(g=>[g.receiptId,g]));if(d.size!==r.length||new Set(r.map(g=>g.receiptId)).size!==r.length)throw new oe("local_portable_population_conflict","Retained cases differ from the admitted population.");let l=lj({schemaVersion:"openpond.experimentManifest.v1",id:t.id,name:n.configuration.request.name??"Experiment",teamId:t.teamId,operationId:t.operationId,maximumCostUsd:t.maximumCostUsd,dataset:n.configuration.request.taskset,target:s,execution:{packageHash:o.contentHash,runtimeTargetHash:T({adapter:s.kind==="model"?n.model.providerId==="claude-code"?"openpond.local-claude-process.v1":"openpond.local-model-case.v1":s.kind==="agent"?"openpond.local-native-harness-case.v1":"openpond.local-profile-case.v1",placement:"local",...n.configuration.request.policy.kind==="hosted_chat"&&n.configuration.request.policy.localRuntime?{runtime:n.configuration.request.policy.localRuntime}:{},environment:o.taskset.environment,tools:o.taskset.tools,capabilities:o.taskset.capabilities,source:s.kind==="agent"||s.kind==="harness"?s.source:null}),metricPolicyHash:T(Mj(o.taskset)),...e.retainedConfigurationHash?{}:{compatibility:{protocol:"openpond.evaluation-execution.v1",targetKind:s.kind}}},lineage:{definition:e.retainedConfigurationHash?t.definition:null,execution:t.sourceExecution?{id:t.sourceExecution.id,contentHash:t.sourceExecution.executionHash}:{id:t.id,contentHash:t.executionHash},scoringPassId:t.kind==="scoring"?t.id:null},evaluators:e.graders.map(g=>({release:g.release??{id:g.id,revision:g.version,contentHash:g.contentHash},feedbackKey:g.feedbackKey,configurationHash:T({graderHash:g.contentHash,mappings:g.mappings??[]}),output:"score",categories:[]})),population:c.map(g=>({caseId:g.taskId,seed:g.seed,fixtureId:g.fixtureId})),createdAt:t.createdAt}),u=uj({schemaVersion:"openpond.experimentResult.v1",manifest:{id:l.id,contentHash:l.contentHash},status:t.status==="completed"?"completed":t.status==="cancelled"?"cancelled":"failed",completedAt:t.completedAt,cases:r.map(g=>{let w=d.get(g.receiptId);if(!w||w.taskId!==g.admission.taskId||w.seed!==g.admission.seed)throw new oe("local_portable_population_conflict","Retained task or seed differs from its admitted population.");let h=g.result?Lt(g.result):null;if(h?.grade&&h.grade.selectionHash!==T(e.graders))throw new oe("local_portable_grader_conflict","Retained grades differ from their exact selected grader pins.");let y=h?.attempt.native??h?.attempt.profileNative??h?.attempt.externalProcess,f=g.status==="completed"&&h?.attempt.status==="completed"&&g.error===null,S=new Map(h?.grade?.grades.flatMap(k=>k.components).map(k=>[k.graderId,k]));return{identity:{caseId:w.taskId,seed:w.seed,fixtureId:w.fixtureId},status:f?"completed":g.status==="cancelled"?"cancelled":"failed",output:h?.attempt.output??null,error:f?null:{code:`local_case_${g.status}`,message:(g.error??h?.attempt.error??"Verified successful case output is unavailable.").slice(0,2e3)},feedback:l.evaluators.map((k,I)=>{let b=S.get(e.graders[I].id),R=f&&b?.score!==null&&b?.score!==void 0;return{feedbackKey:k.feedbackKey,evaluator:k.release,status:f&&b?.status==="pending"?"pending":R?"scored":"unavailable",value:R?b.score:null,passed:R?b.passed:null,reasoning:b?.feedback.join(`
|
|
60
|
-
`).slice(0,2e4)??null,evidenceRefs:[]}}),usage:_ue(e.charges.filter(k=>k.caseId===g.receiptId)),traceRef:h?{id:g.receiptId,contentHash:y?.traceHash??h.attempt.contentHash,mediaType:"application/json",sizeBytes:null}:null,startedAt:y?.startedAt??null,completedAt:y?.completedAt??null}})},l),{definition:p,...m}=t;return{execution:m,manifest:l,result:u}}i(P5,"localPortableExperiment");function _ue(e){let t=e.filter(s=>s.status!=="released"),r=t.every(s=>s.status==="settled"&&s.costUsd!==null),n=i(s=>{if(!t.length)return null;let c=t.map(d=>d.usage&&typeof d.usage=="object"?d.usage[s]:null);return c.every(d=>typeof d=="number"&&Number.isSafeInteger(d)&&d>=0)?c.reduce((d,l)=>d+l,0):null},"tokenSum"),o=n("promptTokens"),a=n("completionTokens");return{inputTokens:o,outputTokens:a,totalTokens:o===null||a===null?null:o+a,costUsd:r?t.reduce((s,c)=>s+c.costUsd,0):null,latencyMs:null}}i(_ue,"localCaseUsage");async function vm(e){let t=await e.store.getHarnessReleaseRecord(e.source.harnessRelease.contentHash);if(!t||t.harnessRelease.id!==e.source.harnessRelease.id)throw new oe("local_harness_source_unavailable","The exact released Harness is unavailable on this computer.",404);if(cj(t))throw new oe("local_harness_profile_required","This release requires its exact Profile composition. Select Model + Harness + Profile.",422);let r=await e.store.getHarnessWorkspace(t.workspaceId);if(!r)throw new oe("local_harness_origin_authority_missing","The cached Harness has no persisted owning workspace.",403);if(!(r.location==="local"&&r.ownerScope.kind==="personal"&&r.ownerScope.id===H$&&r.metadata.sourceLayout==="openpond.harnessSourceManifest.v1"&&r.metadata.selectionEligible!==!1&&typeof t.agentSnapshot.metadata.profileRepositoryId!="string"&&typeof t.harnessRelease.metadata.profileRepositoryId!="string")){if(e.authorizeRemote)return await e.authorizeRemote(e.source,r),r;throw new oe("local_harness_origin_authority_missing","This cached Harness needs an authenticated origin-access check. Import a device-owned local Harness or refresh its authorized source.",403)}return r}i(vm,"authorizeLocalExperimentSource");async function R5(e,t){if(e.kind!=="hosted_chat"||!e.harness)return!1;if(t?.qualified!==!0)throw new oe("local_harness_not_qualified","This released Harness requires a qualified native execution owner; it cannot run as a model-only case.",422);if(e.messages?.length)throw new oe("local_harness_prompt_not_qualified","Standalone Harness cases use released instructions. Additional raw model messages are not admitted.",422);return await t.resolve(e.harness),!0}i(R5,"admitLocalNativeHarness");function x5(e){let t=i(async(a,s)=>{if((await vm({store:e.store,source:a,authorizeRemote:e.authorizeRemote})).id!==s.id)throw new oe("local_harness_origin_access_denied","The source owning workspace changed during admission.",403)},"authorizeWorkspace"),r=fq({...e,authorizeWorkspace:t});async function n(a){let s=await e.actorId(),c=await e.teamId();if(!s.trim()||!c.trim())throw new oe("local_account_required","Sign in and select a workspace before using a native Harness.",403);await vm({store:e.store,source:a,authorizeRemote:e.authorizeRemote});let d=await mq({store:e.store,source:a,authorizeWorkspace:t});if(g2(d.runtime.release),await e.actorId()!==s||await e.teamId()!==c)throw new oe("local_workspace_denied","The signed-in account or workspace changed during native source admission.",403)}return i(n,"resolve"),{native:{qualified:!0,resolve:n,execute:i(async a=>(await n(a.source),r.execute(a)),"execute")},resolveSessionModelStream:r.resolveSessionModelStream}}i(x5,"createLocalNativeExperimentOwner");function Vv(e){let t=e.ownerId??Eue(),r=new Map,n=new Map,o=new Map,a=new Tue,s=new Map,c=!1,d,l=hq({resolvePolicy:i(async D=>{let O=s.get(D.id);if(!O||T(O.admission.request)!==T(D))throw new oe("local_case_admission_missing","Only the durable local execution owner may dispatch a case.");return gq({request:D,stream:ny({store:e.store,ownerId:t,teamId:O.execution.teamId,executionId:O.execution.id,caseId:O.admission.receiptId,admission:g(O.model,O.execution.ownerActorId,O.execution.teamId,O.execution.id),stream:w(O.execution.ownerActorId,O.execution.teamId,O.execution.id)})})},"resolvePolicy"),executeProfile:i(async()=>{throw new oe("local_profile_not_qualified","Profile targets require the shared released-target adapter.",422)},"executeProfile"),resolveEnvironment:e.environment?async D=>{let O=s.get(D.id);if(!O||T(O.admission.request)!==T(D)||!e.environment)throw new oe("local_environment_owner_missing","Only the durable case owner may resolve this exact environment.",422);return e.environment.resolve(D,N=>e.store.appendLocalExperimentEvent({teamId:O.execution.teamId,id:O.execution.id,caseId:O.admission.receiptId,ownerId:t,type:"environment.operation",payload:N}))}:void 0,executeHarness:i(async(D,O)=>{let N=s.get(D.id),$=e.nativeHarness;if(!N||T(N.admission.request)!==T(D)||$?.qualified!==!0||!D.harness)throw new oe("local_native_owner_missing","Only the durable case owner may dispatch the admitted native Harness.",422);let J=await $.execute({executionId:N.execution.id,request:D,source:D.harness,stream:ny({store:e.store,ownerId:t,teamId:N.execution.teamId,executionId:N.execution.id,caseId:N.admission.receiptId,admission:g(N.model,N.execution.ownerActorId,N.execution.teamId,N.execution.id),stream:w(N.execution.ownerActorId,N.execution.teamId,N.execution.id)}),signal:O,maxOutputBytes:262144}),K=sc(J.attempt),F=K.native;if(K.taskId!==D.taskId||!F||F.admissionHash!==D.admissionHash||F.modelConfigurationHash!==D.model.configurationHash||T(F.source)!==T(D.harness)||F.sessionId!==J.sessionId||F.turnId!==J.turn.id||F.traceHash!==J.traceHash||T(F.runtimeEventRefs)!==T(J.runtimeEventRefs))throw new oe("local_native_receipt_conflict","Native output or trace differs from the exact admitted case.");return J.attempt},"executeHarness")});async function u(D){if(await e.teamId()!==D)throw new oe("local_workspace_denied","Select this workspace before accessing its local Experiments.",403)}i(u,"requireTeam");async function p(D){if(await e.actorId()!==D)throw new oe("local_resource_denied","This local resource is unavailable to the current account.",404)}i(p,"requireActor");async function m(D,O,N,$){let J=N?n.get(N):void 0;try{await p(D),await u(O),N&&await e.authorizeTransport?.(N),J&&N&&($.signal?.throwIfAborted(),J.assertExecution(N))}catch(K){throw J&&N&&$.requestId?new Uw(N,$.requestId,K):K}}i(m,"beforeTransport");function g(D,O,N,$){if(D.streamFactory){let K=D.streamFactory;return{...D,streamFactory:i(F=>{let G=K(F);return async function*(te){await m(O,N,$,te),yield*G(te)}},"streamFactory")}}if(!D.stream)return D;let J=D.stream;return{...D,stream:i(async function*(K){await m(O,N,$,K),yield*J(K)},"stream")}}i(g,"modelForActor");function w(D,O,N){return async function*($){await m(D,O,N,$),yield*(e.stream??ki)($)}}i(w,"streamForActor");async function h(D,O,N){let $=await e.store.readLocalExperiment(D,O,N);if(await p($.definition.ownerActorId),a.getStore()&&$.definition.configuration.request.project?.id!==a.getStore())throw new oe("local_project_resource_denied","This Experiment does not belong to the selected Project.",404);return $}i(h,"ownedDefinition");async function y(D,O){await u(D);let N=await e.store.readLocalExecution(D,O);await p(N.execution.ownerActorId);let $=await e.store.readLocalExperimentRecord(D,O);if(a.getStore()&&$.configuration.request.project?.id!==a.getStore())throw new oe("local_project_resource_denied","This Experiment does not belong to the selected Project.",404);return await p($.ownerActorId),await u(D),$}i(y,"ownedRecord");async function f(D,O){let N=await e.store.readLocalExecution(D,O);await p(N.execution.ownerActorId);let $=N.execution.kind==="target"?O:N.execution.sourceExecution.id;return await y(D,$),N}i(f,"ownedExecution");let S=S5({...e,ownerId:t,requireTeam:u,requireActor:p,requireExecution:i(async(D,O)=>{await f(D,O)},"requireExecution"),streamForActor:w,active:r,controllers:o});async function k(D,O){if(D.request.policy.kind!=="hosted_harness")return!1;if(!e.profile)throw new oe("local_profile_not_qualified","This local server has no qualified exact Profile owner.",422);return await e.profile.resolve(D,O),!0}i(k,"admitProfile");let I=k5({localInference:e.localInference,prepareModel:e.prepareModel,store:e.store,ownerId:t,catalog:e.catalog,actorId:e.actorId,requireActor:p,requireTeam:u,ownedRecord:y,closing:i(()=>c,"closing"),assertScope:i(D=>{if(a.getStore()&&D.request.project?.id!==a.getStore())throw new oe("local_project_resource_denied","This Experiment does not belong to the selected Project.",404)},"assertScope"),authorize:i(async D=>{await e.authorizeProject?.(D)},"authorize"),preflight:i(async(D,O)=>{let N=await k(D,O),$=await R5(D.request.policy,e.nativeHarness);return await e.environment?.preflight(O),{profile:N,native:$,environment:!!e.environment}},"preflight"),package:i(async D=>{let{sourceExperimentId:O,...N}=D.configuration,$={...N,expectedRevision:0};if($.request.policy.kind==="hosted_harness"&&e.profile)return e.profile.package($);if(!e.resolvePackage)throw new oe("local_release_transfer_unavailable","This server cannot read an exact retained Dataset release.",503);return e.resolvePackage({configuration:$,...D.expectedPackageHash?{expectedPackageHash:D.expectedPackageHash}:{}})},"package"),schedule:i((D,O,N)=>{if(r.has(D.id))return;let $=nU();$&&n.set(D.id,$);let J=b(D,O,N).finally(()=>{r.delete(D.id),o.delete(D.id),n.delete(D.id)});r.set(D.id,J)},"schedule")});async function b(D,O,N){let $=null,J=!0,K=new AbortController;o.set(D.id,K);let F=await e.store.readLocalExperiment(D.teamId,D.definition.id,D.definition.revision),G=mt(F.package),te=F.definition;try{for(let le of O){if(c||!await e.store.admitLocalCase(D.teamId,D.id,le.receiptId,t))break;s.set(le.request.id,{execution:D,admission:le,model:N});let ae=null;try{K.signal.throwIfAborted();let ne=te.configuration.request.policy.kind==="hosted_harness"&&e.profile?await e.profile.execute({executionId:D.id,admission:le,configuration:te.configuration,package:G,stream:ny({store:e.store,ownerId:t,teamId:D.teamId,executionId:D.id,caseId:le.receiptId,admission:g(N,D.ownerActorId,D.teamId,D.id),stream:w(D.ownerActorId,D.teamId,D.id)}),signal:K.signal}):await l.execute(le.request);ae=ne,te.model.providerId==="claude-code"&&(ne=await w_({store:e.store,teamId:D.teamId,executionId:D.id,caseId:le.receiptId,attempt:ne})),ae=ne;let re=sc(ne);if(te.configuration.request.policy.kind==="hosted_harness"){let ue=re.profileNative;if(!ue||ue.admissionHash!==le.request.admissionHash||ue.modelConfigurationHash!==te.model.configurationHash||T(ue.source)!==T(te.configuration.request.policy.source))throw new oe("local_profile_receipt_conflict","Profile output or trace differs from the exact admitted case.")}let Ce=G.taskset.tasks.find(ue=>ue.id===le.taskId),he=await Yw({storeDir:e.storeDir,attempt:re,signal:K.signal,events:i(async ue=>{if(!e.runtimeEventsForTurn)throw new Error("The actual artifact trace owner is unavailable.");return e.runtimeEventsForTurn(ue)},"events"),authorize:i(async()=>{await p(D.ownerActorId),await u(D.teamId),K.signal.throwIfAborted()},"authorize")}),de=await Wv({store:e.store,ownerId:t,teamId:D.teamId,executionId:D.id,caseId:le.receiptId,package:G,task:Ce,evidence:{output:{text:re.output??"",...he.length?{artifacts:he}:{}},runtimeEventRefs:re.native?.runtimeEventRefs??re.profileNative?.runtimeEventRefs??re.externalProcess?.runtimeEventRefs??[],artifactRefs:he.map(ue=>ue.reference.id),infrastructureError:re.status==="completed"?null:re.error??re.status},evaluatorContext:zv(re),graders:te.graders,signal:K.signal,beforeDispatch:i(async()=>{await p(D.ownerActorId),await u(D.teamId),K.signal.throwIfAborted(),te.configuration.request.policy.kind==="hosted_harness"&&e.profile&&await e.profile.resolve(te.configuration,G),K.signal.throwIfAborted()},"beforeDispatch"),judgeProvider:Fo({stream:w(D.ownerActorId,D.teamId,D.id),catalog:e.catalog})});await e.store.settleLocalCase({teamId:D.teamId,id:D.id,receiptId:le.receiptId,ownerId:t,status:re.status==="completed"?"completed":re.status==="cancelled"?"cancelled":"failed",result:gl(ne,de),error:re.error}),re.status!=="completed"&&($=re.error??re.status)}catch(ne){$=_5(ne);let re=null;if(ae)try{te.model.providerId==="claude-code"&&(ae=await w_({store:e.store,teamId:D.teamId,executionId:D.id,caseId:le.receiptId,attempt:ae})),re=gl(ae,null)}catch{J=!1}else J=!1;await e.store.settleLocalCase({teamId:D.teamId,id:D.id,receiptId:le.receiptId,ownerId:t,status:K.signal.aborted?"cancelled":"failed",result:re,error:$})}finally{s.delete(le.request.id)}if($)break}c&&await e.store.cancelLocalExecution(D.teamId,D.id),await e.store.finishLocalExecution(D.teamId,D.id,t,$,J)}catch(le){$=_5(le),await e.store.finishLocalExecution(D.teamId,D.id,t,$,!1).catch(()=>{})}}i(b,"executeAdmissions");async function R(D){let O=$B.parse(D);await u(O.teamId);let N=await y(O.teamId,O.id);if(O.configurationHash&&N.configurationHash!==O.configurationHash)throw new oe("local_configuration_pin_conflict","The retained Experiment differs from the requested configuration.");return N}i(R,"read");async function _(D){let O=LB.parse(D);await u(O.teamId);let N=await e.actorId(),$=await e.store.listLocalExperimentRecords({...O,ownerActorId:N});return await u(O.teamId),await p(N),$}i(_,"list");async function P(D,O){let N=(await f(D,O)).execution;if(N.kind==="target")return y(D,O);let{definition:$,...J}=N;return J}i(P,"publicExecution");async function x(D){let O=ip.parse(D);return await u(O.teamId),P(O.teamId,O.id)}i(x,"status");async function E(D){let O=v.object({teamId:v.string().min(1),id:v.string().min(1),afterSequence:v.number().int().nonnegative().optional(),afterCallId:v.string().min(1).optional()}).strict().parse(D),N=await y(O.teamId,O.id);return b5(e.store,N,{afterSequence:O.afterSequence,afterCallId:O.afterCallId})}i(E,"diagnostics");async function C(D){let O=ip.parse(D);await u(O.teamId),await f(O.teamId,O.id);let N=await e.store.cancelLocalExecution(O.teamId,O.id);o.get(O.id)?.abort(new Error("local_experiment_cancelled"));for(let $ of s.values())$.execution.id===O.id&&$.execution.teamId===O.teamId&&l.cancel($.admission.request.id);return P(O.teamId,O.id)}i(C,"cancel");async function A(D){let O=ip.parse(D);await u(O.teamId);let N=await f(O.teamId,O.id),$={execution:await P(O.teamId,O.id),cases:N.cases.map(J=>({receiptId:J.receiptId,taskId:J.admission.taskId,seed:J.admission.seed,status:J.status,input:J.admission.request.input,policyVisibleContext:J.admission.request.policyVisibleContext,output:J.result?Lt(J.result).attempt.output:null,messages:J.result?Lt(J.result).attempt.messages:[],grade:J.result?Lt(J.result).grade:null,error:J.error,...J.result&&Lt(J.result).attempt.native?{native:Lt(J.result).attempt.native}:{},...J.result&&Lt(J.result).attempt.externalProcess?{externalProcess:Lt(J.result).attempt.externalProcess}:{},...J.result&&Lt(J.result).attempt.profileNative?{profileNative:Lt(J.result).attempt.profileNative}:{}}))};return{...$,contentHash:T($)}}i(A,"result");async function j(D){let O=v.object({teamId:v.string().min(1),id:v.string().min(1),receiptId:v.string().min(1),afterSequence:v.number().int().nonnegative().optional(),limit:v.number().int().min(1).max(500).default(100)}).strict().parse(D),N=await A({teamId:O.teamId,id:O.id}),$=N.cases.find(K=>K.receiptId===O.receiptId);if(!$)throw new oe("local_case_not_found","The selected case does not belong to this execution.",404);let J=await e.store.localExperimentTrace({teamId:O.teamId,id:O.id,caseId:O.receiptId,afterSequence:O.afterSequence,limit:O.limit});return{location:"local",execution:N.execution,case:$,trace:J}}i(j,"inspectCase");async function H(D){let O=v.object({teamId:v.string().min(1),baselineId:v.string().min(1),candidateId:v.string().min(1)}).strict().parse(D);await u(O.teamId);let N=i(async F=>{let G=await f(O.teamId,F),te=await h(O.teamId,G.execution.definition.id,G.execution.definition.revision),le=G.execution.kind==="scoring"?(await e.store.readLocalScoringSelection(O.teamId,F)).graders:te.definition.graders,ae=await e.store.readLocalExecutionCharges(O.teamId,F);await u(O.teamId),await p(G.execution.ownerActorId);let ne=await y(O.teamId,G.execution.sourceExecution?.id??F);return P5({retained:G,definition:te.definition,package:te.package,graders:le,charges:ae,retainedConfigurationHash:ne.retainedConfigurationHash})},"source"),$=N(O.baselineId),[J,K]=await Promise.all([$,O.candidateId===O.baselineId?$:N(O.candidateId)]);return{location:"local",baseline:J,candidate:K}}i(H,"compare");let L=nv();async function B(D){let O=ip.parse(D),N=await y(O.teamId,O.id);if(!N.completedAt)throw new oe("local_result_unavailable","This Experiment has no complete retained result yet.",422);return L(T({teamId:N.teamId,actorId:N.ownerActorId,id:N.id,executionHash:N.executionHash}),async()=>{let $=(await H({teamId:O.teamId,baselineId:O.id,candidateId:O.id})).baseline;return rv({experimentId:N.id,executionManifestHash:N.executionHash,total:N.configuration.request.population.length,graders:N.graders,evidence:$})})}i(B,"feedbackSummary");async function q(D){let O=v.object({teamId:v.string().min(1).max(200),projectId:v.string().min(1).max(200).nullable().optional(),action:v.enum(["claudeReadiness","claudeControl","localInferenceChoices","sourceDataset","sourceChoices","prepareHarness","run","runFromRelease","read","get","list","status","cancel","result","score","scoreRetained","passes","pass","compare","feedbackSummary","case","diagnostics"]),payload:v.unknown()}).strict().parse(D),N=await e.actorId();if(!N.trim())throw new oe("local_account_required","Sign in before accessing local Experiments.",403);let $=await a.run(O.projectId??null,()=>W(O));return await u(O.teamId),await p(N),$}i(q,"request");async function W(D){await u(D.teamId);let O=i(()=>({...v.record(v.string(),v.unknown()).parse(D.payload),teamId:D.teamId,...D.projectId&&D.action==="list"?{projectId:D.projectId}:{}}),"scoped");if(D.action==="claudeReadiness"){if(!e.localInference?.claudeReadiness)throw new oe("claude_runtime_unavailable","Claude process owner is unavailable.",503);return e.localInference.claudeReadiness()}if(D.action==="claudeControl"){let $=v.object({id:v.string().min(1)}).passthrough().parse(D.payload);if(await f(D.teamId,$.id),!e.localInference?.claudeControl)throw new oe("claude_runtime_unavailable","Claude process owner is unavailable.",503);return e.localInference.claudeControl(D.teamId,D.payload)}if(D.action==="localInferenceChoices"){if(!e.localInference)throw new oe("local_inference_unavailable","Local inference owner is unavailable.",503);return e.localInference.choices()}if(D.action==="sourceDataset"){let $=await e.actorId();if(!e.sourceDataset)throw new oe("local_source_catalog_unavailable","The local source catalog is unavailable.",503);let J=await e.sourceDataset(D.payload,D.teamId);return await u(D.teamId),await p($),J}if(D.action==="sourceChoices"){let $=await e.actorId(),J=ow.parse(await e.sourceChoices?.()??{location:"local",harnesses:[],profiles:[]});return await u(D.teamId),await p($),J}if(D.action==="prepareHarness"){if(!e.profile)throw new oe("local_profile_not_qualified","This local server has no qualified Profile owner.",422);return e.profile.prepare(D.payload,D.teamId)}if(D.action==="scoreRetained"){if(c)throw new oe("local_runtime_closing","The local execution owner is closing.",503);let $=NB.parse(D.payload),J=(await f(D.teamId,$.execution.id)).execution,K=await h(D.teamId,J.definition.id,J.definition.revision),F=await S.score({...$,graderPackage:K.package},D.teamId);return P(D.teamId,F.id)}if(D.action==="run"||D.action==="runFromRelease"){if(v.object({configuration:v.object({request:v.object({teamId:v.string()}).passthrough()}).passthrough()}).passthrough().parse(D.payload).configuration.request.teamId!==D.teamId)throw new oe("local_workspace_conflict","The configuration belongs to another workspace.",403);return I[D.action](D.payload)}if(D.action==="score"){if(c)throw new oe("local_runtime_closing","The local execution owner is closing.",503);let $=await S.score(D.payload,D.teamId);return P(D.teamId,$.id)}return{read:R,get:R,list:_,status:x,cancel:C,result:A,passes:i(async $=>{let J=await S.passes($);return{...J,items:J.items.map(K=>{let{definition:F,...G}=K;return G})}},"passes"),pass:i(async $=>{let J=await S.pass($),{definition:K,...F}=J.execution;return{...J,execution:F}},"pass"),compare:H,feedbackSummary:B,case:j,diagnostics:E}[D.action](O())}i(W,"handleCommand");async function Z(D,O,N){await u(D);let $=await e.actorId();if(!e.readHumanTaskPackage)throw new oe("human_task_source_unavailable","The exact task release resolver is unavailable.",503);let J=mt(await e.readHumanTaskPackage(D,O,N));if(await u(D),await p($),T({id:J.taskset.id,revision:J.taskset.revision,contentHash:J.taskset.contentHash})!==T(N))throw new oe("human_task_release_changed","The Dataset release changed.",409);return J}i(Z,"readHumanTaskPackage");async function Y(D,O){await u(D);let N=await e.store.findLocalExperimentRunOperation(D,O);if(!N)return null;let $=await y(D,N.id);if($.operationId!==O)throw new oe("local_operation_conflict","Original operation identity changed.",409);return $}return i(Y,"findRunOperation"),{authorize:I.authorize,findRunOperation:Y,readHumanTaskPackage:Z,run:I.run,runFromRelease:I.runFromRelease,read:R,list:_,status:x,cancel:C,result:A,inspectCase:j,compare:H,score:S.score,scoreSelected:i(async(D,O)=>{if(c)throw new oe("local_runtime_closing","The local owner is closing.",503);let N=await S.scoreSelected(O,D);return P(D,N.id)},"scoreSelected"),passes:S.passes,pass:S.pass,request:q,async recover(){if(e.managesRuntimeLease===!1)return[];await e.store.claimLocalExperimentOwner(t);let D=await e.store.recoverLocalExperiments(t);return d=setInterval(()=>{e.store.renewLocalExperimentOwner(t).catch(()=>{c=!0;for(let O of o.values())O.abort(new Error("local_runtime_lease_lost"));l.close()})},5e3),d.unref(),D},async close(){c=!0;for(let D of o.values())D.abort(new Error("local_runtime_closed"));await l.close(),await Promise.allSettled([...r.values()]),d&&clearInterval(d),e.managesRuntimeLease!==!1&&await e.store.releaseLocalExperimentOwner(t)},async wait(D){await r.get(D)}}}i(Vv,"createLocalExperimentService");function _5(e){return(e instanceof Error?e.message:"Local execution failed.").slice(0,2e3)}i(_5,"message");function Gv(){let e;async function t(){if((await mR({source:"export function collect(v) { return {state:v.state,observation:{ready:v.services.js.cases[0]===7&&v.services.sql.status==='completed'}}; }",operation:"collect",timeoutMs:1e4,value:{input:{sql:"SELECT 1"},state:{},initialState:{source:"export function check(v){return v;}",cases:[{input:7}],snapshot:{tables:[]}},action:null},executionServices:[{id:"js",kind:"javascript.v1",operation:"collect",timeoutMs:4e3,source:{scope:"initialState",path:["source"]},cases:{scope:"initialState",path:["cases"]},exportName:"check",maxCases:1,maxResultBytes:256},{id:"sql",kind:"sqlite.v1",operation:"collect",timeoutMs:4e3,sql:{scope:"input",path:["sql"]},snapshot:{scope:"initialState",path:["snapshot"]},maxRows:1,maxResultBytes:256}]})).observation.ready!==!0)throw new Error("local_environment_runtime_unavailable")}return i(t,"checkRuntime"),{async preflight(r){let n=GO(r);if(!n)return;let o=n.execution.javascript,a=n.assets.find(s=>s.id===o.module.id);if(!a)throw new oe("local_environment_assets_missing","The exact environment module is unavailable.",422);if(Mo(a,o.module),o.executionServices?.some(s=>s.kind!=="javascript.v1"&&s.kind!=="sqlite.v1"))throw new oe("local_environment_service_unavailable","This Dataset requires an unsupported local execution service.",422);e??=t().catch(s=>{throw e=void 0,s});try{await e}catch{throw new oe("local_environment_runtime_unavailable","The local isolated JavaScript/SQL runtime is unavailable.",503)}},resolve(r,n){if(r.environment.kind!=="javascript")throw new Error("local_environment_required");let o=r.environment,{definition:a,asset:s}=o,c=Mo(s,a.module),d=0,l=T({}),u=!1;return async p=>{if(p.signal?.throwIfAborted(),u)throw new Error("local_environment_operation_in_progress");if(p.source!==c)throw new Error("local_environment_source_mismatch");if(T(p.value.initialState)!==T(o.initialState)||T(p.value.input)!==T(r.input)||p.value.seed!==o.seed||T(p.value.state)!==l)throw new Error("local_environment_private_state_mismatch");let m=p.value.action,g=a.executionServices?.filter(h=>h.operation===p.operation&&(p.operation!=="step"||h.toolName===m?.name))??[];if(T(p.executionServices??[])!==T(g))throw new Error("local_environment_service_mismatch");pi(p.value,4194304);let w={ordinal:d++,operation:p.operation,definitionHash:a.contentHash,servicesHash:T(g),requestHash:T(p.value),runtime:"desktop-local-evals-process"};await n({...w,status:"admitted"}),u=!0;try{let h=await mR(p);return l=T(h.state),await n({...w,status:"completed",resultHash:T(h),childCleanupComplete:!0}),h}catch(h){throw await n({...w,status:p.signal?.aborted?"cancelled":"failed",childCleanupComplete:!0}),h}finally{u=!1}}}}}i(Gv,"createLocalExperimentEnvironment");async function E5(e){let t=Qh.extend({profileRef:va,profileSource:v.object({sourceRevision:v.string().min(1).max(500),harnessRelease:v.object({id:v.string().min(1),contentHash:v.string().regex(/^[a-f0-9]{64}$/)}).strict()}).strict().optional()}).parse(e.raw);if(t.profileRef.repositoryId!==t.profileRepositoryId)throw new oe("local_profile_origin_not_qualified","Choose an accepted device-local Profile repository.",403);if(t.reasoningEffort)throw new oe("local_profile_sampling_not_qualified","This local Profile owner does not admit reasoning overrides.",422);if(t.localRuntime&&(t.maxOutputTokens!==void 0||t.temperature!==void 0||t.topP!==void 0))throw new oe("local_profile_sampling_not_qualified","This native provider runtime does not admit output or sampling overrides.",422);let r=t.localRuntime?void 0:$u(t),n=await e.prepare({id:`local-profile-review-${T([e.teamId,t.operationId]).slice(0,40)}`,createdAt:"1970-01-01T00:00:00.000Z",profileRef:t.profileRef,...t.profileSource?{profileSource:t.profileSource}:{},definitionId:t.definitionId,externalDatasetBinding:t.externalDatasetBinding,modelRef:{providerId:t.localRuntime?.providerId??"openpond",modelId:t.modelId},maximumSpendUsd:t.maximumCostUsd},{modelSampling:r}),o=n.manifest.profileEvaluation,a=await e.loadPackage(n),s={kind:"hosted_harness",modelId:t.modelId,profileRepositoryId:t.profileRepositoryId,...r,source:o,modelConfigurationHash:n.modelConfigurationHash,packageHash:a.contentHash,...o.externalDatasetBinding?{externalDatasetBinding:o.externalDatasetBinding}:{},...t.localRuntime?{localRuntime:t.localRuntime}:{}},c={schemaVersion:"openpond.modelTasksetRunRequest.v1",operationId:t.operationId,teamId:e.teamId,modelProjectId:null,name:o.definitionId,taskset:{id:n.taskset.id,revision:n.taskset.revision,contentHash:n.taskset.contentHash},policy:s,population:n.manifest.population},d={operationId:t.operationId,expectedRevision:0,request:c,maximumCostUsd:t.maximumCostUsd};return await e.resolve(d,a),Zh.parse({request:c,manifest:n.manifest,maximumCostUsd:t.maximumCostUsd,graders:Sr(a)})}i(E5,"prepareLocalProfileExperiment");function T5(e){let t=i(async(a,s,c)=>{let d=await e.store.getHarnessReleaseRecord(c.contentHash),l=d&&await e.store.getHarnessWorkspace(d.workspaceId);if(l?.metadata.profileExperimentOrigin!==void 0||l?.metadata.experimentCandidateOrigin!==void 0){if(!e.resolveProfileRef)throw new Error("The Profile origin is not authenticated.");return e.resolveProfileRef(a,s,c)}return{source:"local",repositoryId:a,profileId:s}},"profileRef"),r=new Map;async function n(a,s){let c=a.request.policy;if(c.kind!=="hosted_harness")throw new oe("local_profile_policy_required","Select an exact prepared Profile target.",422);if(c.localRuntime&&(c.maxOutputTokens!==void 0||c.temperature!==void 0||c.topP!==void 0))throw new oe("local_profile_sampling_not_qualified","This native provider runtime does not admit output or sampling overrides.",422);let d=await e.actorId(),l=await e.teamId();if(!d||l!==a.request.teamId)throw new oe("local_workspace_denied","The Profile belongs to another account or workspace.",403);if(c.localRuntime){if(!e.prepareNativeModel)throw new oe("local_profile_model_unavailable","The native Profile model owner is unavailable.",422);await e.prepareNativeModel(a)}let u=await e.prepare({id:`local-profile-${T(a).slice(0,40)}`,createdAt:"1970-01-01T00:00:00.000Z",profileRef:await t(c.profileRepositoryId,c.source.profileId,c.source.harnessRelease),profileSource:{sourceRevision:c.source.sourceRevision,harnessRelease:c.source.harnessRelease},externalDatasetBinding:c.source.externalDatasetBinding,definitionId:c.source.definitionId,modelRef:{providerId:c.localRuntime?.providerId??"openpond",modelId:c.modelId},maximumSpendUsd:a.maximumCostUsd},{modelSampling:c.localRuntime?void 0:$u(c)});if(await Yr(e.store,c.source.harnessRelease,u.profileRef,e.authorizeOrigin),u.manifest.runtimeTarget.placement!=="local"||T(u.manifest.profileEvaluation)!==T(c.source)||u.profileRef.repositoryId!==c.profileRepositoryId||u.modelConfigurationHash!==c.modelConfigurationHash||u.manifest.packageHash!==c.packageHash||s.contentHash!==c.packageHash||u.taskset.contentHash!==s.taskset.contentHash)throw new oe("local_profile_source_conflict","Prepare this exact Profile and Dataset through the local runtime before running. Hosted or changed source receipts are not local authority.",422);if(!Gw(s))throw new oe("local_profile_environment_not_qualified","This Profile requires an additional admitted local tool or Work environment.",422);let p=a.request.population,m=u.manifest.population,g=new Set(p.map(w=>JSON.stringify([w.taskId,w.seed])));if(p.length!==m.length||g.size!==m.length||m.some(w=>!g.has(JSON.stringify([w.taskId,w.seed]))))throw new oe("local_profile_population_conflict","This Profile evaluation requires its complete declared task and seed population.",422);if(await e.actorId()!==d||await e.teamId()!==l)throw new oe("local_workspace_denied","The account changed during Profile source admission.",403);return u}i(n,"resolve");async function o(a){let s=await n(a.configuration,a.package),c=s.manifest.profileEvaluation,d=await Yr(e.store,c.harnessRelease,s.profileRef,e.authorizeOrigin);dj(d.release);let l=s.taskset.tasks.find(b=>b.id===a.admission.taskId),u=l.artifactRefs.map(b=>{if(b.visibility!=="policy"||b.mediaType!=="application/pdf"||b.sizeBytes>qD.maxAttachmentBytes)throw new Error("The target input needs a bounded policy PDF.");let R=a.package.files.find(_=>T(_.asset)===T(b));if(!R)throw new Error("The exact policy input artifact is unavailable.");return hi(R),Oo.parse({id:b.id,name:b.path.split("/").at(-1),kind:"file",mediaType:b.mediaType,sizeBytes:b.sizeBytes,contentsBase64:R.base64})}),p={executionId:a.executionId,admissionHash:a.admission.request.admissionHash,source:c,modelConfigurationHash:a.admission.request.model.configurationHash},m=a.signal,g=await e.actorId(),w=i(async function*(b){if(b.model!==a.admission.request.model.modelId)throw new Error("Profile Experiment requested another model.");yield*a.stream({...b,maxTokens:a.admission.request.model.maxOutputTokens,temperature:a.admission.request.model.temperature,topP:a.admission.request.model.topP,signal:b.signal?AbortSignal.any([m,b.signal]):m})},"stream"),h=c.externalDatasetBinding?await e.resolveExternalDataset?.(c.externalDatasetBinding,{profileRef:s.profileRef,sourceRevision:c.sourceRevision,harnessRelease:c.harnessRelease}):void 0;if(c.externalDatasetBinding&&!h)throw new Error("The external target has no actual isolated Dataset authority.");let y=lU({storeDir:e.storeDir,release:d.release,getTurn:i(b=>e.store.getTurn(b),"getTurn"),getSession:i(async b=>{let R=await e.store.getSession(b);if(!R)throw new Error("The target Session is unavailable.");return R},"getSession"),saveOutput:e.saveOutput,recordOutput:e.recordOutput,authorize:i(async b=>{if(b.bindingHash!==(c.externalDatasetBinding?.contentHash??T(c))||b.manifestHash!==s.manifest.contentHash||b.taskId!==a.admission.taskId||b.seed!==a.admission.seed)throw new Error("The isolated target requested another exact case.");if(await h?.authorize(),await e.actorId()!==g||await e.teamId()!==a.configuration.request.teamId)throw new Error("The current target workspace changed.");await Yr(e.store,c.harnessRelease,s.profileRef,e.authorizeOrigin),m.throwIfAborted()},"authorize")}),f,S=!1,k,I=vU({...s,attachments:u,requiredOutputs:l.requiredOutputs??[],createSession:i(async b=>(m.throwIfAborted(),await Yr(e.store,c.harnessRelease,s.profileRef,e.authorizeOrigin),m.throwIfAborted(),e.createSession(b)),"createSession"),sendTurn:i((b,R,_)=>e.sendTurn(b,R,void 0,void 0,_),"sendTurn"),interruptSessionTurn:e.interruptSessionTurn,runtimeEventsForTurn:i(b=>e.store.runtimeEventsForTurn(b),"runtimeEventsForTurn"),maximumOutputBytes:262144,retainOutputLimitEvidence:!0,onOutputLimit:i(b=>{k=b},"onOutputLimit"),validateTerminalTurn:i(async(b,R)=>{if(R.sessionId!==b.id||!R.profileSnapshot||T(R.profileSnapshot.ref)!==T(s.profileRef)||R.profileSnapshot.revision!==c.sourceRevision||R.profileSnapshot.sourceHash!==c.harnessRelease.contentHash)throw new Error("Local Profile terminal receipt changed its exact source binding.");if((await e.store.runtimeEventsForTurn(R.id)).some(P=>P.sessionId!==b.id||P.turnId!==R.id))throw new Error("Profile trace contains another case's evidence.")},"validateTerminalTurn"),onInterrupt:i(b=>{S=b==="timed_out"},"onInterrupt"),assertSpendAuthority:i(async b=>{if(b.contentHash!==s.manifest.contentHash||b.limits.maximumSpendUsd===null)throw new Error("Local Profile spend admission changed.");m.throwIfAborted()},"assertSpendAuthority"),ownedSessionMetadata:{localProfileExperiment:p},admitSession:i(async b=>{if(await Yr(e.store,c.harnessRelease,s.profileRef,e.authorizeOrigin),T(b.currentProfile)!==T(s.profileRef))throw new Error("Local Profile session acquired another Profile.");await dw({store:e.store,runId:b.id,workspace:d.workspace,harnessRelease:c.harnessRelease,admittedAt:b.createdAt}),f=b.id,y&&await y.admitSession(b,s.manifest,a.admission.taskId,a.admission.seed,u),r.set(b.id,{binding:p,stream:w,profile:s.profileRef,source:c,isolated:y})},"admitSession")});try{let b=await I({task:{id:l.id,input:a.admission.request.input,policyVisibleContext:a.admission.request.policyVisibleContext,artifactRefs:l.artifactRefs,tags:l.tags},seed:a.admission.seed,source:c,signal:m}),R=k?null:b.evidence.output?.text??null,_={schemaVersion:"openpond.localProfileExperimentAttempt.v1",taskId:l.id,status:m.aborted?"cancelled":S?"timed_out":b.terminal?"completed":"policy_failure",output:R,error:b.evidence.infrastructureError??null,messages:[],environmentCleanupComplete:!0,collected:b.terminal,snapshot:null,artifactRefs:b.artifactRefs,profileNative:{...b.retainedEvidenceRef,source:c,profileRef:s.profileRef,admissionHash:a.admission.request.admissionHash,modelConfigurationHash:a.admission.request.model.configurationHash,traceHash:b.traceHash,runtimeEventRefs:b.evidence.runtimeEventRefs,startedAt:b.startedAt,completedAt:b.completedAt,outputHash:k??T(R??""),partialOutputAvailable:k!==void 0||!b.terminal&&!!R}};return{..._,contentHash:T(_)}}finally{f&&r.delete(f),y?.close()}}return i(o,"execute"),{profile:{resolve:n,execute:o,prepare:i((a,s)=>E5({raw:a,teamId:s,prepare:e.prepare,loadPackage:e.loadPackage,resolve:n}),"prepare"),package:i(async a=>{let s=a.request.policy;if(s.kind!=="hosted_harness")throw new Error("An exact Profile policy is required.");let c=await e.prepare({id:`local-profile-package-${T(a).slice(0,40)}`,createdAt:"1970-01-01T00:00:00.000Z",profileRef:await t(s.profileRepositoryId,s.source.profileId,s.source.harnessRelease),profileSource:{sourceRevision:s.source.sourceRevision,harnessRelease:s.source.harnessRelease},externalDatasetBinding:s.source.externalDatasetBinding,definitionId:s.source.definitionId,modelRef:{providerId:s.localRuntime?.providerId??"openpond",modelId:s.modelId},maximumSpendUsd:a.maximumCostUsd},{modelSampling:s.localRuntime?void 0:$u(s)}),d=await e.loadPackage(c);return await n(a,d),d},"package")},async isolatedProfileEvaluationForTurn(a){if(a.metadata?.localProfileExperiment===void 0)return!1;let s=r.get(a.id);if(!s)throw new Error("This target Session has no actual admitted case owner.");return!!s.isolated},async resolveModelTools(a){if(a.session.metadata?.localProfileExperiment===void 0)return null;let s=r.get(a.session.id);if(!s)throw new Error("This target Session has no actual admitted case owner.");return s.isolated?s.isolated.resolveTools(a):null},async executeProfileEvaluationAction(a){let s=r.get(a.session.id);if(!s?.isolated)throw new Error("This initial target Agent action has no actual isolated case owner.");return s.isolated.executeAction(a)},close(){for(let a of r.values())a.isolated?.close();r.clear()},async resolveSessionModelStream(a,s){let c=a.metadata?.localProfileExperiment;if(c===void 0)return null;let d=r.get(a.id);if(!d||T(c)!==T(d.binding)||T(a.currentProfile)!==T(d.profile)||s.sessionId!==a.id||!s.profileSnapshot||T(s.profileSnapshot.ref)!==T(d.profile)||s.profileSnapshot.revision!==d.source?.sourceRevision||s.profileSnapshot.sourceHash!==d.source.harnessRelease.contentHash)throw new Error("Local Profile Experiment has no matching active execution owner.");return d.stream}}}i(T5,"createLocalProfileExperimentOwner");async function Jv(e){let t=mt(e);if(Sr(t),t.taskset.metrics?.aggregation==="custom")throw new Error("The native Profile owner has not qualified its authored aggregate metric executor.");for(let r of t.taskset.graders){if(r.kind==="model_judge"&&r.calibrationStatus!=="passed")throw new Error("Select a calibrated private model judge before dispatch.");let n="verifierRef"in r?r.verifierRef:"rubricRef"in r?r.rubricRef:null;if(!n)continue;let o=t.files.find(a=>a.asset.id===n.id);if(!o||o.asset.visibility==="policy"||T(o.asset)!==T(n))throw new Error("The private grader differs from its actual pinned package asset.");new TextDecoder("utf8",{fatal:!0}).decode(hi(o))}}i(Jv,"assertNativeProfilePrivateGrading");import{readFile as Cue}from"node:fs/promises";import Aue from"node:path";function C5(e){async function t(){let r=new Map,n=[],o=[];for(let s of await e.store.listHarnessWorkspaces()){if(n.length>=100)break;for(let c of await e.store.listHarnessReleaseRecords(s.id)){if(n.length>=100)break;try{let d={id:c.harnessRelease.id,contentHash:c.harnessRelease.contentHash},l;if(s.location==="local"&&s.ownerScope.kind==="personal"&&s.ownerScope.id==="desktop-personal"){let u={harnessRelease:d,agentSnapshot:{id:c.agentSnapshot.id,contentHash:c.agentSnapshot.contentHash},sourcePackageHash:"0".repeat(64)};await vm({store:e.store,source:u});let p=new Map;for(let g of c.harnessRelease.files)p.set(g.path,await Cue(Aue.join(c.bundlePath,"source",...g.path.split("/"))));let m=ld({agentSnapshot:c.agentSnapshot,harnessRelease:c.harnessRelease,files:p});l={...u,sourcePackageHash:m.contentHash}}else{if(!e.remoteSource)continue;l=await e.remoteSource(s,d)}await e.native.resolve(l),n.push({id:`harness-${l.harnessRelease.contentHash}`,name:s.name,source:l})}catch{}}}let a=await(e.library??ut)();for(let s of[...a.profiles.filter(c=>c.ref.source==="local"),...await e.originProfiles?.()??[]])if(!(o.length>=100))try{let c=await e.workflows(s.ref);await Yr(e.store,c.harnessRelease,s.ref,e.authorizeOrigin);let d=await un({store:e.store,ref:s.ref,sourceRevision:c.sourceRevision,harnessRelease:c.harnessRelease});for(let l of d.definitions){if(o.length>=100)break;let u=mt(await e.loadPackage(l,s.ref.profileId,d.harnessRelease));if(u.taskset.id!==l.tasksetRelease.id||u.taskset.contentHash!==l.tasksetRelease.contentHash)throw new Error("Local Profile Dataset changed its exact binding.");if(u.taskset.tasks.length>1e4||!Gw(u)||u.taskset.tasks.some(m=>m.artifactRefs.some(g=>g.visibility!=="policy"||g.mediaType!=="application/pdf"||g.sizeBytes>1e7)))continue;await Jv(u);let p=`local-profile-${T([s.ref,d.harnessRelease,l.id])}`;r.set(p,u),o.push({id:p,name:`${s.name}, ${l.label}`,profileRef:s.ref,sourceRevision:d.sourceRevision,harnessRelease:d.harnessRelease,definitionId:l.id,definitionHash:T(l),taskset:{id:u.taskset.id,revision:u.taskset.revision,contentHash:u.taskset.contentHash},taskCount:u.taskset.tasks.length,taskIds:l.taskIds,seeds:l.seeds})}}catch{}return{choices:ow.parse({location:"local",harnesses:n,profiles:o}),packages:r}}return i(t,"discover"),{list:i(async()=>(await t()).choices,"list"),packageByRelease:i(async r=>{let n=[...(await t()).packages.values()].filter(o=>o.taskset.id===r.id&&o.taskset.revision===r.revision&&o.taskset.contentHash===r.contentHash);if(new Set(n.map(o=>o.contentHash)).size>1)throw new Error("The local Dataset has conflicting immutable package closures.");return n[0]??null},"packageByRelease"),population:i(async(r,n)=>{let o=v.object({id:v.string().min(1).max(240),view:v.enum(["ids","policy"]).default("ids"),afterId:v.string().optional(),limit:v.number().int().min(1).max(1e4).default(100)}).strict().parse(r);if(o.view==="policy"&&o.limit>100)throw new Error("Local Dataset policy previews are bounded to100 tasks.");let a=await t(),s=a.packages.get(o.id);if(!s)throw new Error("This exact local Profile Dataset is unavailable to the current account.");let c=[...s.taskset.tasks].sort((p,m)=>p.id<m.id?-1:p.id>m.id?1:0),d=c.filter(p=>!o.afterId||p.id>o.afterId).slice(0,o.limit),l=d.map(p=>({id:p.id,split:p.split,...o.view==="policy"?{input:p.input,policyVisibleContext:p.policyVisibleContext,artifacts:[]}:{}})),u={schemaVersion:"openpond.datasetPopulationPage.v1",teamId:n,release:{id:s.taskset.id,revision:s.taskset.revision,contentHash:s.taskset.contentHash},view:o.view,taskCount:c.length,items:l,graders:Sr(s),nextCursor:d.length===o.limit&&c.some(p=>p.id>d.at(-1).id)?d.at(-1).id:null};return Q2.parse({...u,contentHash:T(u)})},"population")}}i(C5,"createLocalExperimentSourceChoices");function y_(e){return async(t,r)=>{let n=await e.resolveAccess(),o=t.ownerScope;if(o.kind==="team"&&o.id!==n.teamId||o.kind==="personal"&&o.id!==n.actorId)throw new oe("local_harness_origin_access_denied","The cached Harness belongs to a different account or workspace.",403);let a=pe(n.token);a.set("x-openpond-team-id",n.teamId);let s=await Se({baseUrl:n.apiBaseUrl,headers:a,fetch:e.fetch}).getHarnessSource(r);if(s.harnessRelease.id!==r.id||s.harnessRelease.contentHash!==r.contentHash)throw new oe("local_harness_authorized_source_conflict","The authorized source differs from its original published release.",409);return{harnessRelease:r,agentSnapshot:{id:s.agentSnapshot.id,contentHash:s.agentSnapshot.contentHash},sourcePackageHash:s.contentHash}}}i(y_,"createLocalExperimentRemoteSourceLookup");function A5(e){let t=y_(e);return async(r,n)=>{let o=await t(n,r.harnessRelease);if(T(o)!==T(r))throw new oe("local_harness_authorized_source_conflict","The authorized published source differs from this immutable Harness closure.",409)}}i(A5,"createLocalExperimentRemoteSourceAuthority");function v_(e){return async t=>{let r=t.request;if(!r.project)return;let n=await e.resolveAccess(),o=await new ir({baseUrl:n.apiBaseUrl,apiKey:n.token,teamId:r.teamId,fetch:e.fetch}).get(r.project.id);if(o.archived||o.revision!==r.project.revision||T(o.content)!==r.project.contentHash)throw new oe("local_project_pin_conflict","The selected Project changed. Reload its configuration before saving or starting.",409);if(r.project.targetId!==null)throw new oe("local_project_target_not_qualified","Choose the explicit local model or prepare a local Profile target without inheriting a hosted Project target.",422)}}i(v_,"createLocalExperimentProjectAuthorizer");function M5(e){return async t=>{let r=await e.resolveAccess(),n=t.configuration.request,o={baseUrl:r.apiBaseUrl,apiKey:r.token,teamId:n.teamId,fetch:e.fetch};return await v_(e)(t.configuration),new nr(o).getByRelease(n.taskset,{expectedPackageHash:t.expectedPackageHash})}}i(M5,"createLocalExperimentPackageResolver");function j5(e){let{store:t,storeDir:r}=e,n=e.localInferenceState?Uv({state:e.localInferenceState,status:e.codexStatus}):void 0,o=i(P=>{let x=P.request.policy;if(x.kind!=="hosted_harness"||!x.localRuntime||!n)throw new Error("The native Profile model owner is unavailable.");return n.prepare(P)},"prepareNativeModel"),a=i(async()=>({...await e.resolveAccess(),teamId:await e.teamId(),actorId:await e.actorId()}),"sourceAccess"),s=Hi({store:t,storeDir:r,resolveAccess:a}),c=e.candidateOrigins,d=i(async(P,x,E)=>P.metadata.experimentCandidateOrigin!==void 0?c?c.authority(P,x,E):Promise.reject(new Error("Candidate origin authority is unavailable.")):s.authority(P,x,E),"authorizeOrigin"),l=i(async(P,x,E)=>c&&await c.hasOrigin(E)?c.resolveRef(P,x,E):s.resolveRef(P,x,E),"resolveProfileRef"),u=i(async(P,x)=>P&&x&&c&&await c.hasOrigin(x.harnessRelease)?c.workflows(P,x):P?.source==="openpond_git"?s.workflows(P,x):e.workflows(P,x),"workflows"),p=i(async(P,x)=>{let E=P.profileRef,C=P.profileSource;return E&&C&&c&&await c.hasOrigin(C.harnessRelease)?e.prepare(P,{...x,selectedWorkflows:await c.workflows(E,C)}):E?.source!=="openpond_git"?e.prepare(P,x):e.prepare(P,{...x,selectedWorkflows:await s.workflows(E,C)})},"prepare"),m=x5({...e,authorizeRemote:A5({resolveAccess:a})}),g=Kw({store:t,storeDir:r,remote:tl({store:t,storeDir:r,resolveAccess:e.resolveAccess,identity:i(async()=>({actorId:await e.actorId(),teamId:await e.teamId()}),"identity")})}).resolveExternalDataset,w=T5({...e,prepare:p,prepareNativeModel:o,authorizeOrigin:d,resolveProfileRef:l,resolveExternalDataset:g,loadPackage:i(async P=>{let x=P.manifest.profileEvaluation;if(x.externalDatasetBinding){let A=await g(x.externalDatasetBinding,{profileRef:P.profileRef,sourceRevision:P.binding.sourceRevision,harnessRelease:P.binding.harnessRelease});return await A.authorize(),A.packageValue}let C=(await un({store:t,ref:P.profileRef,sourceRevision:x.sourceRevision,harnessRelease:x.harnessRelease})).definitions.find(A=>A.id===x.definitionId&&T(A)===x.definitionHash);if(!C)throw new Error("The exact local Profile Dataset definition is unavailable.");return Sa({store:t,storeDir:r,definition:C,profileId:x.profileId,harnessRelease:x.harnessRelease})},"loadPackage")}),h=C5({store:t,native:m.native,workflows:u,originProfiles:s.discover,authorizeOrigin:d,loadPackage:i((P,x,E)=>Sa({store:t,storeDir:r,definition:P,profileId:x,harnessRelease:E}),"loadPackage"),remoteSource:y_({resolveAccess:a})}),y=M5({resolveAccess:e.resolveAccess}),f=i(async(P,x,E)=>{let C=await a();if(C.teamId!==P)throw new Error("Local publication workspace changed.");let A={baseUrl:C.apiBaseUrl,apiKey:C.token,teamId:P};if((await new ir(A).get(x)).archived)throw new Error("The Project is archived.");return g_({store:t,storeDir:r,scope:P,actorId:C.actorId,projectId:x,release:E,loadBaseline:i(async H=>await h.packageByRelease(H)??await new nr(A).getByRelease(H),"loadBaseline")})},"publishedPackage"),S=e.localInferenceState?Fv(e.localInferenceState):void 0,k=e.localInferenceState?Lv({state:e.localInferenceState,store:t,ownerId:e.ownerId,actorId:e.actorId,teamId:e.teamId}):void 0,I=S&&k?{choices:S.choices,claudeReadiness:k.readiness,claudeControl:k.control,prepare:i(P=>P.request.policy.kind==="hosted_chat"&&P.request.policy.localRuntime?.providerId==="claude-code"?k.prepare(P):S.prepare(P),"prepare")}:void 0,b=f5({resolveAccess:e.resolveAccess,identity:i(async()=>({actorId:await e.actorId(),teamId:await e.teamId()}),"identity")}),R=Vv({resolveSelectedRewards:b,localInference:I,store:t,storeDir:r,runtimeEventsForTurn:i(P=>t.runtimeEventsForTurn(P),"runtimeEventsForTurn"),ownerId:e.ownerId,stream:ki,prepareModel:i(P=>P.request.policy.kind==="hosted_harness"&&P.request.policy.localRuntime?o(P):P.request.policy.kind==="hosted_chat"&&P.request.policy.localRuntime?I.prepare(P):Ra(P.request.policy),"prepareModel"),actorId:e.actorId,teamId:e.teamId,nativeHarness:m.native,profile:w.profile,sourceChoices:h.list,sourceDataset:h.population,environment:Gv(),authorizeProject:v_({resolveAccess:e.resolveAccess}),readHumanTaskPackage:i(async(P,x,E)=>{let C=await e.resolveAccess(),A={baseUrl:C.apiBaseUrl,apiKey:C.token,teamId:P};if((await new ir(A).get(x)).archived)throw new Error("The Project is archived.");return await f(P,x,E)??await h.packageByRelease(E)??await new nr(A).getByRelease(E)},"readHumanTaskPackage"),resolvePackage:i(async P=>await(P.configuration.request.project?.id?f(P.configuration.request.teamId,P.configuration.request.project.id,P.configuration.request.taskset):Promise.resolve(null))??await h.packageByRelease(P.configuration.request.taskset)??await y(P),"resolvePackage")}),_=R.close;return R.close=async()=>{try{await _()}finally{w.close()}},{localExperiments:R,localNativeOwner:m,localProfileOwner:w}}i(j5,"createLocalExperimentsRuntime");var I_=v.string().trim().min(1).max(240),b_=st.extend({projectId:I_.nullable(),action:v.enum(["capability","compile","prepare","start","cancel","get","list"]),id:I_.optional(),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:v.unknown().optional(),query:fP.optional(),capabilityQuery:Tn.optional()}).strict(),Tt=class extends Error{constructor(r,n){super(n);this.code=r}code;static{i(this,"HostedAlphaEditExecutionError")}status=409};function O5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let o=await e.currentIdentity();if(!o||o.teamId!==e.teamId||o.actorId!==e.actorId||new URL(o.apiOrigin).origin!==t)throw new Tt("alphaedit_account_changed","The active account changed. Recover this experiment in its original account.")}i(r,"fence");let n=Se({baseUrl:e.access.apiBaseUrl,headers:i(()=>{let o=pe(e.access.token);return o.set("x-openpond-team-id",e.teamId),o},"headers"),fetch:i(async(...o)=>{await r();let a=await fetch(...o);return await r(),a},"fetch")});return{async perform(o){let a=b_.parse(o);if(a.teamId!==e.teamId||a.actorId!==e.actorId||a.apiOrigin!==t)throw new Tt("alphaedit_account_changed","This experiment belongs to another account or hosted API.");if(await r(),a.action==="capability"){let l=Tn.parse(a.capabilityQuery);if(l.teamId!==a.teamId)throw La();let u=await n.alphaEditExecutionCapability(l);if(await r(),u.actorId!==a.actorId)throw La();return u}if(a.action==="compile"){let l=d1.parse(a.command);if(l.teamId!==a.teamId||l.projectId!==a.projectId)throw La();let u=await n.compileAlphaEditExecution(l);if(await r(),u.actorId!==a.actorId)throw La();return u}if(a.action==="list"){let l=fP.parse(a.query??{});if(a.projectId!==null&&l.projectId!==a.projectId)throw La();let u=await n.listAlphaEditExecutions(a.teamId,l,{ownerUserId:a.actorId});return await r(),u}if(a.action==="get"){let l=await n.getAlphaEditExecution(a.teamId,I_.parse(a.id));if(await r(),l.ownerUserId!==a.actorId||a.projectId!==null&&l.projectId!==a.projectId)throw La();return l}let s=a.action==="prepare"?xg.parse(a.command):a.action==="start"?_g.parse(a.command):Eg.parse(a.command);if(s.teamId!==a.teamId||"projectId"in s&&s.projectId!==a.projectId||"id"in s&&s.id!==a.id)throw La();let c=await e.assertRetained({action:a.action,projectId:a.projectId,command:s,intentHash:v.string().regex(/^[a-f0-9]{64}$/).parse(a.intentHash)});if(await r(),c&&"action"in s){let l=l1.parse(c);if(l.id!==s.id||l.teamId!==a.teamId||l.ownerUserId!==a.actorId||l.projectId!==a.projectId||l.plan.contentHash!==s.planHash||l.revision!==s.expectedRevision||s.action==="start"&&l.plan.maximumSpendUsd!==s.approvedMaximumSpendUsd)throw La()}let d="action"in s?s.action==="start"?await n.startAlphaEditExecution(s):await n.cancelAlphaEditExecution(s):await n.prepareAlphaEditExecution(s);if(await r(),d.execution.ownerUserId!==a.actorId||d.execution.projectId!==a.projectId||c&&(d.execution.sourceContentHash!==c.sourceContentHash||me(d.execution.plan)!==me(c.plan)))throw La();return d}}}i(O5,"createHostedAlphaEditExecutions");function La(){return new Tt("alphaedit_scope_mismatch","Retain the exact experiment, creator, workspace and Project before continuing.")}i(La,"scopeError");var k_=st.extend({projectId:v.string().min(1).max(240).nullable(),executionId:v.string().min(1).max(240),action:v.enum(["options","save"]),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:Wu.optional()}).strict();function H5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let c=await e.currentIdentity();if(c.teamId!==e.teamId||c.actorId!==e.actorId||new URL(c.apiOrigin).origin!==t)throw new Tt("alphaedit_save_account_changed","Recover this Model save in its original account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=i(async(...c)=>{await r();let d=await fetch(...c);return await r(),d},"fetchScoped"),a=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o}),s=Et({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o});return{async perform(c){let d=k_.parse(c);if(d.teamId!==e.teamId||d.actorId!==e.actorId||d.apiOrigin!==t)throw new Tt("alphaedit_save_account_changed","Use the result's original configured account and workspace.");if(await r(),d.action==="options"){let p=await a.getAlphaEditExecution(d.teamId,d.executionId);if(await r(),p.ownerUserId!==e.actorId||p.projectId!==d.projectId||p.method!=="alphaedit"||p.phase!=="completed"||!p.result)throw new Tt("alphaedit_save_result_unavailable","Read your completed alphaedit result before saving a Model.");let m=(await s.list()).filter(g=>{let w=g.trainingSetup.baseModel??g.defaultBaseModel;return w?.modelId===p.request.model.modelId&&w.revision===p.request.model.revision});return await r(),n$.parse({account:{teamId:e.teamId,actorId:e.actorId,apiOrigin:t},projectId:d.projectId,executionId:d.executionId,models:m})}let l=Wu.parse(d.command);if(l.teamId!==d.teamId||l.executionId!==d.executionId)throw new Tt("alphaedit_save_scope_mismatch","Retry the original result and Model save command.");await e.assertRetained(l,v.string().regex(/^[a-f0-9]{64}$/).parse(d.intentHash),d.projectId),await r();let u=await a.saveAlphaEditResultModel(l);if(await r(),u.actorId!==d.actorId||u.version.source.executionId!==d.executionId)throw new Tt("alphaedit_save_receipt_mismatch","The publication receipt differs from its original creator or Project.");return u}}}i(H5,"createHostedAlphaEditPublication");var S_=v.string().trim().min(1).max(240),P_=st.extend({projectId:S_.nullable(),action:v.enum(["capability","compile","prepare","start","cancel","get","list"]),id:S_.optional(),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:v.unknown().optional(),query:hP.optional(),capabilityQuery:Tn.optional()}).strict(),Ct=class extends Error{constructor(r,n){super(n);this.code=r}code;static{i(this,"HostedNeuronTrainingExecutionError")}status=409};function D5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let o=await e.currentIdentity();if(!o||o.teamId!==e.teamId||o.actorId!==e.actorId||new URL(o.apiOrigin).origin!==t)throw new Ct("neuron_training_account_changed","The active account changed. Recover this experiment in its original account.")}i(r,"fence");let n=Se({baseUrl:e.access.apiBaseUrl,headers:i(()=>{let o=pe(e.access.token);return o.set("x-openpond-team-id",e.teamId),o},"headers"),fetch:i(async(...o)=>{await r();let a=await fetch(...o);return await r(),a},"fetch")});return{async perform(o){let a=P_.parse(o);if(a.teamId!==e.teamId||a.actorId!==e.actorId||a.apiOrigin!==t)throw new Ct("neuron_training_account_changed","This experiment belongs to another account or hosted API.");if(await r(),a.action==="capability"){let l=Tn.parse(a.capabilityQuery);if(l.teamId!==a.teamId)throw Ba();let u=await n.neuronTrainingExecutionCapability(l);if(await r(),u.actorId!==a.actorId)throw Ba();return u}if(a.action==="compile"){let l=u1.parse(a.command);if(l.teamId!==a.teamId||l.projectId!==a.projectId)throw Ba();let u=await n.compileNeuronTrainingExecution(l);if(await r(),u.actorId!==a.actorId)throw Ba();return u}if(a.action==="list"){let l=hP.parse(a.query??{});if(a.projectId!==null&&l.projectId!==a.projectId)throw Ba();let u=await n.listNeuronTrainingExecutions(a.teamId,l,{ownerUserId:a.actorId});return await r(),u}if(a.action==="get"){let l=await n.getNeuronTrainingExecution(a.teamId,S_.parse(a.id));if(await r(),l.ownerUserId!==a.actorId||a.projectId!==null&&l.projectId!==a.projectId)throw Ba();return l}let s=a.action==="prepare"?Tg.parse(a.command):a.action==="start"?Cg.parse(a.command):Ag.parse(a.command);if(s.teamId!==a.teamId||"projectId"in s&&s.projectId!==a.projectId||"id"in s&&s.id!==a.id)throw Ba();let c=await e.assertRetained({action:a.action,projectId:a.projectId,command:s,intentHash:v.string().regex(/^[a-f0-9]{64}$/).parse(a.intentHash)});if(await r(),c&&"action"in s){let l=p1.parse(c);if(l.id!==s.id||l.teamId!==a.teamId||l.ownerUserId!==a.actorId||l.projectId!==a.projectId||l.plan.contentHash!==s.planHash||l.revision!==s.expectedRevision||s.action==="start"&&l.plan.maximumSpendUsd!==s.approvedMaximumSpendUsd)throw Ba()}let d="action"in s?s.action==="start"?await n.startNeuronTrainingExecution(s):await n.cancelNeuronTrainingExecution(s):await n.prepareNeuronTrainingExecution(s);if(await r(),d.execution.ownerUserId!==a.actorId||d.execution.projectId!==a.projectId||c&&(d.execution.sourceContentHash!==c.sourceContentHash||me(d.execution.plan)!==me(c.plan)))throw Ba();return d}}}i(D5,"createHostedNeuronTrainingExecutions");function Ba(){return new Ct("neuron_training_scope_mismatch","Retain the exact experiment, creator, workspace and Project before continuing.")}i(Ba,"scopeError");var R_=st.extend({projectId:v.string().min(1).max(240).nullable(),executionId:v.string().min(1).max(240),action:v.enum(["options","save"]),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:Vu.optional()}).strict();function L5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let c=await e.currentIdentity();if(c.teamId!==e.teamId||c.actorId!==e.actorId||new URL(c.apiOrigin).origin!==t)throw new Ct("neuron_training_save_account_changed","Recover this Model save in its original account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=i(async(...c)=>{await r();let d=await fetch(...c);return await r(),d},"fetchScoped"),a=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o}),s=Et({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o});return{async perform(c){let d=R_.parse(c);if(d.teamId!==e.teamId||d.actorId!==e.actorId||d.apiOrigin!==t)throw new Ct("neuron_training_save_account_changed","Use the result's original configured account and workspace.");if(await r(),d.action==="options"){let p=await a.getNeuronTrainingExecution(d.teamId,d.executionId);if(await r(),p.ownerUserId!==e.actorId||p.projectId!==d.projectId||p.method!=="selective_neuron_training"||p.phase!=="completed"||!p.result)throw new Ct("neuron_training_save_result_unavailable","Read your completed neuron_training result before saving a Model.");let m=(await s.list()).filter(g=>{let w=g.trainingSetup.baseModel??g.defaultBaseModel;return w?.modelId===p.request.model.modelId&&w.revision===p.request.model.revision});return await r(),o$.parse({account:{teamId:e.teamId,actorId:e.actorId,apiOrigin:t},projectId:d.projectId,executionId:d.executionId,models:m})}let l=Vu.parse(d.command);if(l.teamId!==d.teamId||l.executionId!==d.executionId)throw new Ct("neuron_training_save_scope_mismatch","Retry the original result and Model save command.");await e.assertRetained(l,v.string().regex(/^[a-f0-9]{64}$/).parse(d.intentHash),d.projectId),await r();let u=await a.saveNeuronTrainingResultModel(l);if(await r(),u.actorId!==d.actorId||u.version.source.executionId!==d.executionId)throw new Ct("neuron_training_save_receipt_mismatch","The publication receipt differs from its original creator or Project.");return u}}}i(L5,"createHostedNeuronTrainingPublication");var x_=v.string().trim().min(1).max(240),__=st.extend({projectId:x_.nullable(),action:v.enum(["capability","compile","prepare","start","cancel","get","list"]),id:x_.optional(),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:v.unknown().optional(),query:mP.optional(),capabilityQuery:Tn.optional()}).strict(),Qe=class extends Error{constructor(r,n){super(n);this.code=r}code;static{i(this,"HostedDecisionExecutionError")}status=409};function B5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let o=await e.currentIdentity();if(!o||o.teamId!==e.teamId||o.actorId!==e.actorId||new URL(o.apiOrigin).origin!==t)throw new Qe("decision_account_changed","The active account changed. Recover this experiment in its original account.")}i(r,"fence");let n=Se({baseUrl:e.access.apiBaseUrl,headers:i(()=>{let o=pe(e.access.token);return o.set("x-openpond-team-id",e.teamId),o},"headers"),fetch:i(async(...o)=>{await r();let a=await fetch(...o);return await r(),a},"fetch")});return{async perform(o){let a=__.parse(o);if(a.teamId!==e.teamId||a.actorId!==e.actorId||a.apiOrigin!==t)throw new Qe("decision_account_changed","This experiment belongs to another account or hosted API.");if(await r(),a.action==="capability"){let l=Tn.parse(a.capabilityQuery);if(l.teamId!==a.teamId)throw $a();let u=await n.decisionExecutionCapability(l);if(await r(),u.actorId!==a.actorId)throw $a();return u}if(a.action==="compile"){let l=s1.parse(a.command);if(l.teamId!==a.teamId||l.projectId!==a.projectId)throw $a();let u=await n.compileDecisionExecution(l);if(await r(),u.actorId!==a.actorId)throw $a();return u}if(a.action==="list"){let l=mP.parse(a.query??{});if(a.projectId!==null&&l.projectId!==a.projectId)throw $a();let u=await n.listDecisionExecutions(a.teamId,l,{ownerUserId:a.actorId});return await r(),u}if(a.action==="get"){let l=await n.getDecisionExecution(a.teamId,x_.parse(a.id));if(await r(),l.ownerUserId!==a.actorId||a.projectId!==null&&l.projectId!==a.projectId)throw $a();return l}let s=a.action==="prepare"?Sg.parse(a.command):a.action==="start"?Pg.parse(a.command):Rg.parse(a.command);if(s.teamId!==a.teamId||"projectId"in s&&s.projectId!==a.projectId||"id"in s&&s.id!==a.id)throw $a();let c=await e.assertRetained({action:a.action,projectId:a.projectId,command:s,intentHash:v.string().regex(/^[a-f0-9]{64}$/).parse(a.intentHash)});if(await r(),c&&"action"in s){let l=c1.parse(c);if(l.id!==s.id||l.teamId!==a.teamId||l.ownerUserId!==a.actorId||l.projectId!==a.projectId||l.plan.contentHash!==s.planHash||l.revision!==s.expectedRevision||s.action==="start"&&l.plan.maximumSpendUsd!==s.approvedMaximumSpendUsd)throw $a()}let d="action"in s?s.action==="start"?await n.startDecisionExecution(s):await n.cancelDecisionExecution(s):await n.prepareDecisionExecution(s);if(await r(),d.execution.ownerUserId!==a.actorId||d.execution.projectId!==a.projectId||c&&(d.execution.sourceContentHash!==c.sourceContentHash||me(d.execution.plan)!==me(c.plan)))throw $a();return d}}}i(B5,"createHostedDecisionExecutions");function $a(){return new Qe("decision_scope_mismatch","Retain the exact experiment, creator, workspace and Project before continuing.")}i($a,"scopeError");var E_=st.extend({projectId:v.string().trim().min(1).max(240).nullable(),modelProjectId:v.string().trim().min(1).max(240),command:S1,intentHash:v.string().regex(/^[a-f0-9]{64}$/)}).strict();function $5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let a=await e.currentIdentity();if(a.teamId!==e.teamId||a.actorId!==e.actorId||new URL(a.apiOrigin).origin!==t)throw new Qe("decision_score_account_changed","Recover this score in its original configured account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:i(async(a,s)=>{await r();let c=await fetch(a,{...s,signal:AbortSignal.any([AbortSignal.timeout(33e4),...s?.signal?[s.signal]:[]])});return await r(),c},"fetch")});return{async perform(a){let s=E_.parse(a);if(s.teamId!==e.teamId||s.actorId!==e.actorId||s.apiOrigin!==t||s.command.teamId!==s.teamId)throw new Qe("decision_score_account_changed","Score this exact Model in its original account and workspace.");await r(),await e.assertRetained({modelProjectId:s.modelProjectId,request:s.command},s.intentHash,s.projectId),await r();let c=await o.scoreDecisionModel(s.modelProjectId,s.command,{actorId:e.actorId});return await r(),c}}}i($5,"createHostedDecisionScoring");var T_=st.extend({projectId:v.string().min(1).max(240).nullable(),executionId:v.string().min(1).max(240),action:v.enum(["options","save"]),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:zu.optional()}).strict();function N5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let c=await e.currentIdentity();if(c.teamId!==e.teamId||c.actorId!==e.actorId||new URL(c.apiOrigin).origin!==t)throw new Qe("decision_save_account_changed","Recover this Model save in its original account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=i(async(...c)=>{await r();let d=await fetch(...c);return await r(),d},"fetchScoped"),a=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o}),s=Et({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o});return{async perform(c){let d=T_.parse(c);if(d.teamId!==e.teamId||d.actorId!==e.actorId||d.apiOrigin!==t)throw new Qe("decision_save_account_changed","Use the result's original configured account and workspace.");if(await r(),d.action==="options"){let p=await a.getDecisionExecution(d.teamId,d.executionId);if(await r(),p.ownerUserId!==e.actorId||p.projectId!==d.projectId||p.method!=="decision_model"||p.phase!=="completed"||p.mode!=="train"||!p.result)throw new Qe("decision_save_result_unavailable","Read your completed decision result before saving a Model.");let m=(await s.list()).filter(g=>{let w=g.trainingSetup.baseModel??g.defaultBaseModel;return w?.modelId===p.request.model.source.modelId&&w.revision===p.request.model.source.revision});return await r(),t$.parse({account:{teamId:e.teamId,actorId:e.actorId,apiOrigin:t},projectId:d.projectId,executionId:d.executionId,models:m})}let l=zu.parse(d.command);if(l.teamId!==d.teamId||l.executionId!==d.executionId)throw new Qe("decision_save_scope_mismatch","Retry the original result and Model save command.");await e.assertRetained(l,v.string().regex(/^[a-f0-9]{64}$/).parse(d.intentHash),d.projectId),await r();let u=await a.saveDecisionResultModel(l);if(await r(),u.actorId!==d.actorId||u.version.source.executionId!==d.executionId)throw new Qe("decision_save_receipt_mismatch","The publication receipt differs from its original creator or Project.");return u}}}i(N5,"createHostedDecisionPublication");var C_=v.string().trim().min(1).max(240),A_=st.extend({projectId:C_.nullable(),action:v.enum(["capability","compile","prepare","start","cancel","get","list"]),id:C_.optional(),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:v.unknown().optional(),query:pP.optional(),capabilityQuery:Tn.optional()}).strict(),At=class extends Error{constructor(r,n){super(n);this.code=r}code;static{i(this,"HostedEngramExecutionError")}status=409};function U5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let o=await e.currentIdentity();if(!o||o.teamId!==e.teamId||o.actorId!==e.actorId||new URL(o.apiOrigin).origin!==t)throw new At("engram_account_changed","The active account changed. Recover this experiment in its original account.")}i(r,"fence");let n=Se({baseUrl:e.access.apiBaseUrl,headers:i(()=>{let o=pe(e.access.token);return o.set("x-openpond-team-id",e.teamId),o},"headers"),fetch:i(async(...o)=>{await r();let a=await fetch(...o);return await r(),a},"fetch")});return{async perform(o){let a=A_.parse(o);if(a.teamId!==e.teamId||a.actorId!==e.actorId||a.apiOrigin!==t)throw new At("engram_account_changed","This experiment belongs to another account or hosted API.");if(await r(),a.action==="capability"){let l=Tn.parse(a.capabilityQuery);if(l.teamId!==a.teamId)throw Na();let u=await n.engramExecutionCapability(l);if(await r(),u.actorId!==a.actorId)throw Na();return u}if(a.action==="compile"){let l=a1.parse(a.command);if(l.teamId!==a.teamId||l.projectId!==a.projectId)throw Na();let u=await n.compileEngramExecution(l);if(await r(),u.actorId!==a.actorId)throw Na();return u}if(a.action==="list"){let l=pP.parse(a.query??{});if(a.projectId!==null&&l.projectId!==a.projectId)throw Na();let u=await n.listEngramExecutions(a.teamId,l,{ownerUserId:a.actorId});return await r(),u}if(a.action==="get"){let l=await n.getEngramExecution(a.teamId,C_.parse(a.id));if(await r(),l.ownerUserId!==a.actorId||l.projectId!==a.projectId)throw Na();return l}let s=a.action==="prepare"?Ig.parse(a.command):a.action==="start"?bg.parse(a.command):kg.parse(a.command);if(s.teamId!==a.teamId||"projectId"in s&&s.projectId!==a.projectId||"id"in s&&s.id!==a.id)throw Na();let c=await e.assertRetained({action:a.action,projectId:a.projectId,command:s,intentHash:v.string().regex(/^[a-f0-9]{64}$/).parse(a.intentHash)});if(await r(),c&&"action"in s){let l=i1.parse(c);if(l.id!==s.id||l.teamId!==a.teamId||l.ownerUserId!==a.actorId||l.projectId!==a.projectId||l.plan.contentHash!==s.planHash||l.revision!==s.expectedRevision||s.action==="start"&&l.plan.maximumSpendUsd!==s.approvedMaximumSpendUsd)throw Na()}let d="action"in s?s.action==="start"?await n.startEngramExecution(s):await n.cancelEngramExecution(s):await n.prepareEngramExecution(s);if(await r(),d.execution.ownerUserId!==a.actorId||d.execution.projectId!==a.projectId||c&&(d.execution.sourceContentHash!==c.sourceContentHash||me(d.execution.plan)!==me(c.plan)))throw Na();return d}}}i(U5,"createHostedEngramExecutions");function Na(){return new At("engram_scope_mismatch","Retain the exact experiment, creator, workspace and Project before continuing.")}i(Na,"scopeError");var M_=st.extend({projectId:v.string().min(1).max(240).nullable(),executionId:v.string().min(1).max(240),action:v.enum(["options","save"]),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:Fu.optional()}).strict();function q5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let c=await e.currentIdentity();if(c.teamId!==e.teamId||c.actorId!==e.actorId||new URL(c.apiOrigin).origin!==t)throw new At("engram_save_account_changed","Recover this Model save in its original account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=i(async(...c)=>{await r();let d=await fetch(...c);return await r(),d},"fetchScoped"),a=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o}),s=Et({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o});return{async perform(c){let d=M_.parse(c);if(d.teamId!==e.teamId||d.actorId!==e.actorId||d.apiOrigin!==t)throw new At("engram_save_account_changed","Use the result's original configured account and workspace.");if(await r(),d.action==="options"){let p=await a.getEngramExecution(d.teamId,d.executionId);if(await r(),p.ownerUserId!==e.actorId||p.projectId!==d.projectId||p.method!=="engram_adapter"||p.phase!=="completed"||!p.result)throw new At("engram_save_result_unavailable","Read your completed engram result before saving a Model.");let m=(await s.list()).filter(g=>{let w=g.trainingSetup.baseModel??g.defaultBaseModel;return w?.modelId===p.request.model.modelId&&w.revision===p.request.model.revision});return await r(),e$.parse({account:{teamId:e.teamId,actorId:e.actorId,apiOrigin:t},projectId:d.projectId,executionId:d.executionId,models:m})}let l=Fu.parse(d.command);if(l.teamId!==d.teamId||l.executionId!==d.executionId)throw new At("engram_save_scope_mismatch","Retry the original result and Model save command.");await e.assertRetained(l,v.string().regex(/^[a-f0-9]{64}$/).parse(d.intentHash),d.projectId),await r();let u=await a.saveEngramResultModel(l);if(await r(),u.actorId!==d.actorId||u.version.source.executionId!==d.executionId)throw new At("engram_save_receipt_mismatch","The publication receipt differs from its original creator or Project.");return u}}}i(q5,"createHostedEngramPublication");var j_=v.string().trim().min(1).max(240),O_=st.extend({projectId:j_.nullable(),action:v.enum(["compile","prepare","start","cancel","get","list"]),id:j_.optional(),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:v.unknown().optional(),query:uP.optional()}).strict(),Mt=class extends Error{constructor(r,n){super(n);this.code=r}code;static{i(this,"HostedModificationExecutionError")}status=409};function F5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let o=await e.currentIdentity();if(!o||o.teamId!==e.teamId||o.actorId!==e.actorId||new URL(o.apiOrigin).origin!==t)throw new Mt("modification_account_changed","The active account changed. Recover this experiment in its original account.")}i(r,"fence");let n=Se({baseUrl:e.access.apiBaseUrl,headers:i(()=>{let o=pe(e.access.token);return o.set("x-openpond-team-id",e.teamId),o},"headers"),fetch:i(async(...o)=>{await r();let a=await fetch(...o);return await r(),a},"fetch")});return{async perform(o){let a=O_.parse(o);if(a.teamId!==e.teamId||a.actorId!==e.actorId||a.apiOrigin!==t)throw new Mt("modification_account_changed","This experiment belongs to another account or hosted API.");if(await r(),a.action==="compile"){let l=n1.parse(a.command);if(l.teamId!==a.teamId||l.projectId!==a.projectId)throw cc();let u=await n.compileModificationExecution(l);if(await r(),u.actorId!==a.actorId)throw cc();return u}if(a.action==="list"){let l=uP.parse(a.query??{});if(a.projectId!==null&&l.projectId!==a.projectId)throw cc();let u=await n.listModificationExecutions(a.teamId,l,{ownerUserId:a.actorId});return await r(),u}if(a.action==="get"){let l=await n.getModificationExecution(a.teamId,j_.parse(a.id));if(await r(),l.ownerUserId!==a.actorId||l.projectId!==a.projectId)throw cc();return l}let s=a.action==="prepare"?wg.parse(a.command):a.action==="start"?yg.parse(a.command):vg.parse(a.command);if(s.teamId!==a.teamId||"projectId"in s&&s.projectId!==a.projectId||"id"in s&&s.id!==a.id)throw cc();let c=await e.assertRetained({action:a.action,projectId:a.projectId,command:s,intentHash:v.string().regex(/^[a-f0-9]{64}$/).parse(a.intentHash)});if(await r(),c&&"action"in s){let l=o1.parse(c);if(l.id!==s.id||l.teamId!==a.teamId||l.ownerUserId!==a.actorId||l.projectId!==a.projectId||l.plan.contentHash!==s.planHash||l.revision!==s.expectedRevision||s.action==="start"&&l.plan.maximumSpendUsd!==s.approvedMaximumSpendUsd)throw cc()}let d="action"in s?s.action==="start"?await n.startModificationExecution(s):await n.cancelModificationExecution(s):await n.prepareModificationExecution(s);if(await r(),d.execution.ownerUserId!==a.actorId||d.execution.projectId!==a.projectId||c&&(d.execution.sourceContentHash!==c.sourceContentHash||me(d.execution.plan)!==me(c.plan)))throw cc();return d}}}i(F5,"createHostedModificationExecutions");function cc(){return new Mt("modification_scope_mismatch","Retain the exact experiment, creator, workspace and Project before continuing.")}i(cc,"scopeError");var H_=st.extend({projectId:v.string().min(1).max(240).nullable(),executionId:v.string().min(1).max(240),action:v.enum(["options","save"]),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:Gu.optional()}).strict();function z5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let c=await e.currentIdentity();if(c.teamId!==e.teamId||c.actorId!==e.actorId||new URL(c.apiOrigin).origin!==t)throw new Mt("steering_save_account_changed","Recover this Model save in its original account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=i(async(...c)=>{await r();let d=await fetch(...c);return await r(),d},"fetchScoped"),a=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o}),s=Et({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o});return{async perform(c){let d=H_.parse(c);if(d.teamId!==e.teamId||d.actorId!==e.actorId||d.apiOrigin!==t)throw new Mt("steering_save_account_changed","Use the result's original configured account and workspace.");if(await r(),d.action==="options"){let p=await a.getModificationExecution(d.teamId,d.executionId);if(await r(),p.ownerUserId!==e.actorId||p.projectId!==d.projectId||p.method!=="neuron_steering"||p.phase!=="completed"||!p.result)throw new Mt("steering_save_result_unavailable","Read your completed steering result before saving a Model.");let m=(await s.list()).filter(g=>{let w=g.trainingSetup.baseModel??g.defaultBaseModel;return w?.modelId===p.request.model.modelId&&w.revision===p.request.model.revision});return await r(),ZB.parse({account:{teamId:e.teamId,actorId:e.actorId,apiOrigin:t},projectId:d.projectId,executionId:d.executionId,models:m})}let l=Gu.parse(d.command);if(l.teamId!==d.teamId||l.executionId!==d.executionId)throw new Mt("steering_save_scope_mismatch","Retry the original result and Model save command.");await e.assertRetained(l,v.string().regex(/^[a-f0-9]{64}$/).parse(d.intentHash),d.projectId),await r();let u=await a.saveModificationResultModel(l);if(await r(),u.actorId!==d.actorId||u.record.publication.projectId!==d.projectId)throw new Mt("steering_save_receipt_mismatch","The publication receipt differs from its original creator or Project.");return u}}}i(z5,"createHostedSteeringPublication");function dc(e){throw new He(e,409)}i(dc,"fail");async function Kv(e,t){let r=Ch.parse(t),n=await e.actorId();r.scope!==await e.teamId()&&dc("human_local_scope_changed");let o,a,s,c=[];for(let l of r.selections){await e.store.localExperimentTrace({teamId:r.scope,id:l.executionId,caseId:l.receiptId,limit:1});let u=await e.store.humanReviewLocalEvidence(r.scope,l.executionId),p=u.released.definition;(u.execution.ownerActorId!==n||p.ownerActorId!==n||u.execution.kind!=="target"||!u.execution.completedAt||!u.execution.cleanupComplete||p.configuration.request.project?.id!==r.projectId)&&dc("human_local_publication_source_denied");let m=u.cases.find(b=>b.receiptId===l.receiptId);m?.result||dc("human_local_publication_receipt_missing");let g=mt(u.released.package),w=g.taskset.tasks.find(b=>b.id===m.admission.taskId),h=g.taskset.graders.find(b=>b.id===r.graderId);(!w||h?.kind!=="human"||!h.form)&&dc("human_local_publication_grader_required");let y={id:g.taskset.id,revision:g.taskset.revision,contentHash:g.taskset.contentHash};(o&&T(o)!==T(y)||a&&a!==T(h))&&dc("human_local_publication_pair_conflict"),o=y,a=T(h),s=u.execution.completedAt;let f=Lt(m.result).attempt,S;if(f.externalProcess){let b=await ym({store:e.store,teamId:r.scope,executionId:l.executionId,caseId:l.receiptId});T(b)!==f.externalProcess.traceHash&&dc("human_local_publication_trace_changed"),S=b.filter(R=>["external.stream","external.human_intervention","external.control_receipt"].includes(R.type)).map(R=>{let _=R.payload;if(R.type==="external.stream"){let P=_.event;return{sequence:R.sequence,type:R.type,...Object.fromEntries(["type","message","result","usage","is_error"].filter(x=>P[x]!==void 0).map(x=>[x,x==="message"?Object.fromEntries(["role","content"].filter(E=>P.message[E]!==void 0).map(E=>[E,P.message[E]])):P[x]]))}}return{sequence:R.sequence,type:R.type,...Object.fromEntries(["action","text","occurredAt","state"].filter(P=>_[P]!==void 0).map(P=>[P,_[P]]))}})}else S=f.messages.map((b,R)=>{let _=b;return{sequence:R,...Object.fromEntries(["role","content","kind","name","input","output"].filter(P=>_[P]!==void 0).map(P=>[P,_[P]]))}});let k=[],I=0;for(let b of S){let R=Buffer.byteLength(JSON.stringify(b));if(k.length>=1e3||I+R>35e4)break;k.push(b),I+=R}c.push({origin:{kind:"owner_attested_local",ownerActorId:n,teamId:r.scope,executionHash:u.execution.executionHash,configurationHash:T(p.configuration),retainedAttemptHash:f.contentHash,traceHash:f.externalProcess?.traceHash??f.native?.traceHash??f.profileNative?.traceHash??f.contentHash,publicationCutoffHash:T(k)},executionId:u.execution.id,receiptId:m.receiptId,taskId:w.id,targetId:p.model.modelId,familyKey:w.clusterKey,split:w.split,input:w.input,policyVisibleContext:w.policyVisibleContext,output:f.output,error:f.error,events:k,coverage:{sourceEventCount:S.length,publishedEventCount:k.length,traceLimited:S.length>k.length,artifactsIncluded:!1}})}(await e.actorId()!==n||await e.teamId()!==r.scope)&&dc("human_local_scope_changed");let d=KM.parse(QM({schemaVersion:"openpond.humanLocalEvidenceExport.v1",actorId:n,scope:r.scope,projectId:r.projectId,dataset:o,graderId:r.graderId,compiledGraderHash:a,attempts:c,sealedAt:s}));return pi(d,9e5),d}i(Kv,"exportLocalHumanEvidence");async function W5(e,t,r){let n=Ah.parse(t),o=await e.actorId(),a=await e.teamId();async function s(){if(await e.actorId()!==o||await e.teamId()!==a||n.scope!==a)throw new He("human_scope_changed",403)}i(s,"current"),await s();let c=v.object({scope:v.string(),actorId:v.string(),projectId:v.string()}).strict().parse(await e.hosted.request({endpoint:"publication_access",scope:a,projectId:n.projectId},r));if(c.actorId!==o||c.scope!==a||c.projectId!==n.projectId)throw new He("human_publication_project_denied",403);await s();let d=await Kv(e,{endpoint:"export_local",scope:n.scope,projectId:n.projectId,graderId:n.graderId,selections:n.selections});await s();let l=v.object({evidence:_s,form:xs}).strict().parse(await e.hosted.request({endpoint:"publish_local",scope:a,projectId:n.projectId,operationId:n.operationId,audience:n.audience,workspaceVisible:n.workspaceVisible,evidence:d},r));await s();let u=TS.parse(l.evidence.publication);if(l.evidence.attempts.some((p,m)=>p.experimentId!==d.attempts[m]?.executionId||p.attemptId!==d.attempts[m]?.receiptId)||l.evidence.attempts.length!==d.attempts.length)throw new He("human_publication_identity_changed",409);for(let p of d.attempts)await e.store.rememberHumanLocalPublication({scope:a,actorId:o,executionId:p.executionId,executionHash:p.origin.executionHash,operationId:n.operationId,publication:u});return await s(),l}i(W5,"shareLocalHumanEvidence");async function V5(e,t){let r=Mh.parse(t),n=await e.actorId();if(r.scope!==await e.teamId())throw new He("human_scope_changed",403);let o=v.array(TS).max(1e3).parse(await e.store.humanLocalPublications({scope:r.scope,actorId:n,executionId:r.executionId}));if(n!==await e.actorId()||r.scope!==await e.teamId())throw new He("human_scope_changed",403);return o}i(V5,"readLocalHumanPublicationRefs");async function G5(e,t,r){let n=jh.parse(t),o=await e.actorId();if(n.scope!==await e.teamId())throw new He("human_scope_changed",403);let a=v.object({revoked:v.literal(!0)}).strict().parse(await e.hosted.request({endpoint:"revoke_publication",scope:n.scope,publication:n.publication},r));if(await e.actorId()!==o||await e.teamId()!==n.scope)throw new He("human_scope_changed",403);return await e.store.forgetHumanLocalPublication({scope:n.scope,actorId:o,publicationId:n.publication.id}),a}i(G5,"revokeLocalHumanPublication");function J5(e){async function t(){let o=await e.currentIdentity();if(o?.teamId!==e.teamId||o.actorId!==e.actorId)throw new Error("The active account changed. Reopen candidate evaluation setup.")}i(t,"fence");let r=UP(async(o,a)=>{await t();let s=pe(e.access.token);s.set("x-openpond-team-id",e.teamId),s.set("content-type","application/json");let c=await fetch(`${e.access.apiBaseUrl.replace(/\/+$/,"")}${o}`,{...a,headers:s,redirect:"error",signal:AbortSignal.timeout(3e4)}),d=c.body?.getReader();if(!d)throw new Error("Candidate evaluation returned no retained receipt.");let l=[],u=0;try{for(;;){let m=await d.read();if(m.done)break;if(u+=m.value.byteLength,u>8388608)throw new Error("Candidate response exceeded its bound.");l.push(m.value)}}finally{await d.cancel(),d.releaseLock()}await t();let p=JSON.parse(Buffer.concat(l).toString("utf8"));if(!c.ok)throw new Error(typeof p.message=="string"?p.message:`Candidate evaluation failed (${c.status}).`);return p});async function n(o){let a=await o;if(a.ownerUserId!==e.actorId)throw new Error("The candidate owner changed.");return a}return i(n,"owner"),{options:i(o=>n(r.options(e.teamId,o)),"options"),save:i(o=>{if(o.teamId!==e.teamId)throw new Error("The candidate workspace changed.");return n(r.save(o))},"save"),read:i(o=>n(r.get(e.teamId,o)),"read"),control:i((o,a,s)=>n(r.control(e.teamId,o,a,s)),"control")}}i(J5,"createHostedCandidateEvaluations");function K5(e){async function t(){let r=await e.currentIdentity();if(r?.teamId!==e.teamId||r.actorId!==e.actorId)throw new Error("The active account changed. Reopen the Experiment result.")}return i(t,"fence"),{async read(r,n=null){await t();let o=new URLSearchParams({teamId:e.teamId,executionId:r});n&&o.set("passId",n);let a=pe(e.access.token);a.set("x-openpond-team-id",e.teamId);let s=await fetch(`${e.access.apiBaseUrl.replace(/\/+$/,"")}/v1/training/experiment-handoff?${o}`,{headers:a,redirect:"error",signal:AbortSignal.timeout(2e4)});if(!s.ok)throw new Error(`Experiment training handoff is unavailable (${s.status}).`);let c=s.body?.getReader();if(!c)throw new Error("The handoff returned no retained evidence.");let d=[],l=0;try{for(;;){let p=await c.read();if(p.done)break;if(l+=p.value.byteLength,l>262144)throw new Error("Experiment handoff exceeded its response limit.");d.push(p.value)}}finally{await c.cancel(),c.releaseLock()}await t();let u=XS.parse(JSON.parse(Buffer.concat(d).toString("utf8")));if(u.origin){let{contentHash:p,...m}=u.origin;if(p!==await Xe(m)||m.teamId!==e.teamId||m.source.executionId!==r||m.source.passId!==n)throw new Error("The handoff does not match the exact selected result.")}return u}}}i(K5,"createHostedExperimentTrainingHandoff");var Yv=v.string().min(1).max(200),Y5=v.string().trim().min(1).max(240);function D_(e){async function t(){let m=await e.currentIdentity();if(m?.teamId!==e.teamId||m.actorId!==e.actorId)throw new Error("The active account changed. Reopen training setup.")}i(t,"fence");let r=i(()=>{let m=pe(e.access.token);return m.set("x-openpond-team-id",e.teamId),m},"headers"),n=i(async(...m)=>{await t();let g=await fetch(...m);return await t(),g},"scopedFetch"),o=Et({baseUrl:e.access.apiBaseUrl,headers:r,fetch:n}),a=Se({baseUrl:e.access.apiBaseUrl,headers:r,fetch:n}),s=new bi({baseUrl:e.access.apiBaseUrl,apiKey:e.access.token,scope:e.teamId,fetch:n}),c=new ir({baseUrl:e.access.apiBaseUrl,apiKey:e.access.token,teamId:e.teamId,fetch:n}),d=new Jr({baseUrl:e.access.apiBaseUrl,apiKey:e.access.token,teamId:e.teamId,fetch:n});async function l(m){let g=[],w,h=new Set;for(let y=0;;y++){if(y>=100)throw new Error("The complete learning catalog exceeds the supported setup bound.");let f=await s.list(m,{limit:100,...w?{afterId:w}:{}});if(g.push(...f.items),!f.nextCursor)return g;if(h.has(f.nextCursor))throw new Error("Learning pagination did not advance.");h.add(f.nextCursor),w=f.nextCursor}}i(l,"all");async function u(m,g){await t();let w=r();w.set("content-type","application/json");let h=await n(`${e.access.apiBaseUrl.replace(/\/+$/,"")}${m}`,{method:"POST",headers:w,body:JSON.stringify(g),redirect:"error",signal:AbortSignal.timeout(3e4)}),y=h.body?.getReader();if(!y)throw new Error("Training setup returned no receipt.");let f=[],S=0;try{for(;;){let I=await y.read();if(I.done)break;if(S+=I.value.byteLength,S>8388608)throw new Error("The setup response exceeded its bound.");f.push(I.value)}}finally{await y.cancel(),y.releaseLock()}await t();let k=JSON.parse(Buffer.concat(f).toString("utf8"));if(!h.ok)throw new Error(typeof k.message=="string"?k.message:`Training setup failed (${h.status}).`);return k}i(u,"publicRequest");async function p(m){let g=(await o.list()).find(w=>w.portableProjectId===m);if(!g)throw new Error("The current account cannot read this policy\u2019s exact hosted training configuration.");return g}return i(p,"policyConfiguration"),{async draftInputs(m){if(await t(),m.projectId&&(await c.get(m.projectId)).archived)throw new Error("Restore this Project before starting an experiment.");let[g,w,h]=await Promise.all([o.configurationCandidates(),a.capabilities(),s.list("batch",{limit:100,...m.cursor?{afterId:m.cursor}:{}})]);return await t(),e1.parse({schemaVersion:"openpond.trainingExperimentInputsPage.v1",teamId:e.teamId,actorId:e.actorId,projectId:m.projectId,models:g,methods:w.methods,billingModes:w.billingModes,batches:h.items.map(y=>({reference:Ve(y),rewardBinding:y.rewardBinding,purpose:y.purpose,exampleCount:y.examples.length,sealedAt:y.sealedAt})),nextCursor:h.nextCursor})},async policyRead(m,g){await t();let w=await s.get("policy",Yv.parse(m)),h=await p(w.modelProjectId);if(w.executionOwner!=="hosted"||h.portableProjectId!==w.modelProjectId)throw new Error("The policy has no exact hosted training configuration.");let[y,f]=await Promise.all([s.inspectPolicy(Ve(w)),s.list("iteration",{parentId:w.id,limit:100,afterId:g})]),S=await Promise.all(f.items.map(async k=>{if(k.policy.id!==w.id)throw new Error("Iteration belongs to another learning policy.");return{iteration:k,evals:k.trainingJob?await a.postTraining.get(e.teamId,k.trainingJob.id):null}}));return await t(),oP.parse({teamId:e.teamId,actorId:e.actorId,configuration:h,policy:w,inspection:y,iterations:S,nextCursor:f.nextCursor})},async policyControl(m){await t();let g=aP.parse(m),w=await s.get("policy",g.id,g.expectedRevision);if(w.contentHash!==g.policyHash||w.executionOwner!=="hosted")throw new Error("The exact reviewed policy changed.");if((await p(w.modelProjectId)).portableProjectId!==w.modelProjectId)throw new Error("The exact policy configuration changed.");if(g.action==="pause"||g.action==="resume"){let{contentHash:f,...S}=w;return s.command({action:"publish",operationId:g.operationId,kind:"policy",expectedRevision:g.expectedRevision,content:{...S,revision:w.revision+1,enabled:g.action==="resume"}})}if(g.action==="reserve")return s.command({action:"reserve_iteration",operationId:g.operationId,policy:Ve(w),trigger:{kind:"manual",identity:g.operationId}});if(!g.iterationId||!g.iterationRevision)throw new Error("Choose the exact current iteration before controlling it.");let y=await s.get("iteration",g.iterationId,g.iterationRevision);if(y.policy.id!==w.id)throw new Error("The iteration belongs to another policy.");return s.command({action:g.action==="cancel-iteration"?"cancel_iteration":"retry_iteration_dispatch",operationId:g.operationId,iterationId:y.id,expectedRevision:y.revision})},async catalog(m){await t();let g=(await o.get(Yv.parse(m.configurationId))).project;if(m.projectId){let b=await c.get(m.projectId);if(b.archived||!b.content.resources.some(R=>R.kind==="training_configuration"&&R.resourceId===g.id))throw new Error("Link this exact training configuration to the current Project before setup.")}let[w,h,y]=await Promise.all([l("batch"),l("source"),l("definition")]),f=[],S,k=new Set;for(let b=0;;b++){if(b>=100)throw new Error("The complete evaluation catalog exceeds the supported setup bound.");let R=await d.list({projectId:m.projectId??void 0,limit:100,afterId:S});for(let _ of R.items)_.request.policy.kind!=="fixture"&&f.push({id:_.summary.id,name:_.request.name??_.summary.id,configuration:ya.parse({request:_.request,maximumCostUsd:_.configuration.maximumCostUsd,graders:_.configuration.graders.map(P=>({id:P.id,version:P.version,contentHash:P.contentHash,mappings:P.mappings??[]})),operationId:_.request.operationId}),graders:_.configuration.graders.map(P=>({feedbackKey:P.feedbackKey,name:P.feedbackKey,ref:{id:P.release?.id??P.id,contentHash:P.release?.contentHash??P.contentHash}}))});if(!R.nextCursor)break;if(k.has(R.nextCursor))throw new Error("Evaluation pagination did not advance.");k.add(R.nextCursor),S=R.nextCursor}let I=g.trainingSetup.rewardBindingRef;return await t(),rP.parse({teamId:e.teamId,actorId:e.actorId,projectId:m.projectId,configuration:g,batches:w.filter(b=>b.purpose==="reward_training"&&I&&_t(b.rewardBinding,I)),sources:h.filter(b=>y.some(R=>_t(Ve(R),b.taskDefinition)&&I&&_t(R.rewardBinding,I))),definitions:y,experiments:f})},async perform(m,g){if(await t(),m==="review-dataset"){let y=bH.parse(g);if(y.teamId!==e.teamId)throw new Error("The Dataset review workspace changed.");let f=await a.reviewDataset(y);return await t(),O1(f,y,e.actorId)}if(m==="funding"||m==="funding-handoff"){let y=m==="funding"?gP.parse(g):wP.parse(g);if(y.teamId!==e.teamId)throw new Error("The funding workspace changed.");let f=m==="funding"?await a.funding(gP.parse(y)):await a.fundingHandoff(wP.parse(y));if(await t(),f.actorId!==e.actorId)throw new Error("Funding returned another account.");return f}if(m==="estimate"){let{TrainingEstimateRequestSchema:y}=await import("./training-RL7UUBER.js"),f=y.parse(g);if(f.teamId!==e.teamId)throw new Error("Choose this workspace's estimate inputs.");return a.estimate(f)}if(m==="hardware-catalog"){let y=await a.hardwareCatalog();return await t(),y}if(m==="gpu-catalog"){let{TrainingGpuCatalogQuerySchema:y}=await import("./training-RL7UUBER.js"),f=y.parse(g);if(f.teamId!==e.teamId)throw new Error("The compute workspace changed.");let S=await a.gpuCatalog(f);return await t(),S}if(m==="modification-capabilities"){let{ModelModificationCapabilitiesQuerySchema:y,parseAndVerifyModelModificationCapabilities:f}=await import("./training-RL7UUBER.js"),S=y.parse(g);if(S.teamId!==e.teamId)throw new Error("The model capability workspace changed.");let k=await a.modificationCapabilities(S);return await t(),f(k,S,e.actorId)}if(m==="list-drafts"){let y=await a.listExperimentDrafts(e.teamId,r1.parse(g??{}));if(await t(),y.ownerUserId!==e.actorId)throw new Error("Draft history returned another owner.");return y}if(m==="get-draft"){let y=v.object({id:Y5}).strict().parse(g),f=await a.getExperimentDraft(e.teamId,y.id);if(await t(),f.ownerUserId!==e.actorId)throw new Error("This draft belongs to another owner.");return f}if(m==="save-draft"||m==="archive-draft"){let y=m==="save-draft"?vd.parse(g):v.object({id:Y5,control:t1}).strict().parse(g);if(("control"in y?y.control.teamId:y.teamId)!==e.teamId)throw new Error("The draft workspace changed.");let S="control"in y?await a.archiveExperimentDraft(y.id,y.control):await a.saveExperimentDraft(y);if(await t(),S.record.ownerUserId!==e.actorId)throw new Error("The saved draft belongs to another owner.");return S}if(m==="save-experiment-learning"){let y=j1.parse(g);if(y.teamId!==e.teamId)throw new Error("Training workspace changed.");return a.saveExperimentLearning(y)}if(m==="prepare-draft"){let y=gg.parse(g);if(y.teamId!==e.teamId)throw new Error("Training workspace changed.");return a.prepareExperiment(y)}if(m==="prepare"){let y=KH.parse(g);if(y.teamId!==e.teamId)throw new Error("Training workspace changed.");return a.prepareRun(y)}if(m==="start"||m==="cancel"){let y=v.object({id:Yv,control:YH}).strict().parse(g);if(y.control.teamId!==e.teamId)throw new Error("Training workspace changed.");return m==="start"?a.startPreparation(y.id,y.control):a.cancelPreparation(y.id,y.control)}if(m==="attach"){let y=eP.parse(g);return a.postTraining.attach(e.teamId,y)}let w=v.object({operationId:Yv,command:v.unknown(),attachment:QS.nullable()}).strict().parse(g),h=wa.parse({scope:e.teamId,command:w.command}).command;if(h.action!=="publish"||h.kind!=="policy")throw new Error("Publish one exact hosted learning policy.");if(w.attachment){let y=await u("/v1/training/post-training-policies",{operationId:w.operationId,command:h,attachment:w.attachment}),f=wj.parse(y.policy),S=tP(y.plan);if(yj(f),f.id!==h.content.id||f.revision!==h.content.revision||S.attachment.binding.contentHash!==f.contentHash||S.ownerUserId!==e.actorId)throw new Error("Publication returned a different policy, plan or owner.");return{policy:f,plan:S}}return s.command(h)}}}i(D_,"createHostedTrainingSetup");var Mue=v.object({kind:v.enum(["training","experiment"]),id:v.string().min(1),name:v.string(),phase:v.string(),href:v.string(),updatedAt:v.iso.datetime()}).strict(),jue=v.object({scope:v.object({teamId:v.string().min(1),projectId:v.string().nullable()}).strict(),generatedAt:v.iso.datetime(),counts:v.object({training:v.number().int().nonnegative(),experiments:v.number().int().nonnegative()}).strict(),items:v.array(Mue).max(300),hasMore:v.boolean()}).strict();function Oue(e,t,r){return JSON.stringify([e,t,r])}i(Oue,"executionActivityScopeKey");function X5(e){return i(async function(r){let n=v.object({teamId:v.string().min(1),projectId:v.string().nullable()}).strict().parse(r),o=await e.actorId();if(!o.trim()||await e.teamId()!==n.teamId)throw new Error("Activity workspace is unavailable to this account.");n.projectId&&await e.authorizeProject(n.teamId,o,n.projectId);let[a,s,c]=await Promise.all([e.store.readExecutionActivity({...n,actorId:o}),e.store.readTrainingExecutionActivity({...n,actorId:o}),e.hosted(n.teamId,n.projectId)]),d=jue.parse(c);if(d.scope.teamId!==n.teamId||d.scope.projectId!==n.projectId)throw new Error("Activity response belongs to another scope.");if(await e.actorId()!==o||await e.teamId()!==n.teamId)throw new Error("Activity account changed during refresh.");let l=[...a.items,...s.items,...d.items.map(u=>({...u,location:"hosted"}))].sort((u,p)=>p.updatedAt.localeCompare(u.updatedAt));if(new Set(l.map(u=>JSON.stringify([u.kind,u.location,u.id]))).size!==l.length)throw new Error("Activity response contains duplicate executions.");return{scopeKey:Oue(n.teamId,o,n.projectId),generatedAt:d.generatedAt,counts:{training:d.counts.training+s.count,experiments:d.counts.experiments+a.count},items:l.slice(0,100),hasMore:d.hasMore||l.length>100||a.count>a.items.length||s.count>s.items.length}},"read")}i(X5,"createExecutionActivityService");async function Q5(e,t,r){let n=new URLSearchParams(r?{projectId:r}:{}),o=pe(e.token);o.set("x-openpond-team-id",t);let a=await fetch(`${e.apiBaseUrl.replace(/\/+$/,"")}/v1/training/activity?${n}`,{headers:o,redirect:"error",signal:AbortSignal.timeout(2e4)});if(!a.ok)throw new Error(`Execution activity is unavailable (${a.status}).`);let s=a.body?.getReader();if(!s)throw new Error("Execution activity returned no body.");let c=[],d=0;try{for(;;){let l=await s.read();if(l.done)break;if(d+=l.value.byteLength,d>524288)throw new Error("Execution activity exceeded its bounded response.");c.push(l.value)}}finally{await s.cancel(),s.releaseLock()}return JSON.parse(Buffer.concat(c).toString("utf8"))}i(Q5,"readHostedExecutionActivity");var lc=class extends Error{constructor(r,n,o=r){super(o);this.code=r;this.status=n;this.name="HumanReviewBridgeError"}code;status;static{i(this,"HumanReviewBridgeError")}};function Z5(e){return{async request(t,r){pi(t,1048576);let n=v.object({scope:v.string().trim().min(1).max(191)}).passthrough().parse(t),o=await e.resolveAccess();if(n.scope!==o.teamId)throw new He("human_scope_changed",403,"The active workspace changed. Refresh before continuing.");let a=pe(o.token);a.set("x-openpond-team-id",o.teamId),a.set("content-type","application/json");let s=await fetch(`${o.apiBaseUrl.replace(/\/+$/,"")}/v1/human-review`,{method:"POST",redirect:"error",headers:a,body:JSON.stringify(n),signal:r?AbortSignal.any([r,AbortSignal.timeout(3e4)]):AbortSignal.timeout(3e4)}),c=s.body?.getReader();if(!c)throw new lc("human_response_unavailable",502);let d=[],l=0;try{for(;;){let m=await c.read();if(m.done)break;if(l+=m.value.byteLength,l>2097152)throw new lc("human_response_too_large",502);d.push(m.value)}}finally{await c.cancel(),c.releaseLock()}let u=JSON.parse(Buffer.concat(d).toString("utf8"));if(!s.ok){let m=v.object({code:v.string().optional(),error:v.string().optional()}).passthrough().safeParse(u);throw new lc(m.success?m.data.code??"human_request_failed":"human_request_failed",s.status,m.success?m.data.error:void 0)}let p=await e.resolveAccess();if(p.teamId!==o.teamId||p.token!==o.token||new URL(p.apiBaseUrl).origin!==new URL(o.apiBaseUrl).origin)throw new He("human_scope_changed",403,"The active account or workspace changed. Refresh before continuing.");return u}}}i(Z5,"createHostedHumanReviewBridge");var uo=i((e,t)=>({label:e.slice(0,200),value:String(t).slice(0,12e3),severity:"info"}),"fact");function Xv(e){return[...["schemaVersion","trainingStepId","inputPolicyVersion","outputPolicyVersion","localPolicyTransitionSha256","contentHash","normalization","advantageEpsilon"].flatMap(t=>["string","number"].includes(typeof e[t])?[uo(t,e[t])]:[]),...Array.isArray(e.scores)?e.scores.slice(0,128).flatMap(t=>!t||typeof t!="object"||!("rolloutId"in t)||typeof t.rolloutId!="string"?[]:[uo(`Source rollout ${t.rolloutId}`,"reward"in t&&typeof t.reward=="number"?`Reward ${t.reward}`:"Reward not retained")]):[]].slice(0,95)}i(Xv,"optimizerReceiptFacts");function eG(e){let t=e.job.inputBundle?.recovery;if(!t?.groups)return[];let r=new Set(e.rolloutGroups.map(n=>n.groupIndex));return t.groups.filter(n=>n.groupIndex<t.completedGroups&&!r.has(n.groupIndex)).map(n=>{let o=n.optimizerDisposition==="applied",a=typeof n.optimizerEvidence.outputPolicyVersion=="number"?n.optimizerEvidence.outputPolicyVersion:void 0,s=o&&a!==void 0?`v${n.policyVersion} \u2192 v${a}`:`Policy v${n.policyVersion} unchanged`,c=[uo("Evidence origin","Inherited from checkpoint recovery; not re-executed in this run"),uo("Source run",n.sourceJobId),uo("Source group",n.id),uo("Recovery checkpoint",t.checkpointId),uo("Retained state",n.state),uo("Optimizer outcome",o?"Update applied":"Skipped \xB7 no signal"),...Xv(n.optimizerEvidence)].slice(0,100),d=[...["Rollouts","Grade"].map(l=>({label:l,state:"done",status:"Inherited",detail:"Consumed in source run",inLoop:!0,diagnostics:c})),{label:"Update adapter",state:o?"done":"missing",status:o?"Inherited update":"Skipped \xB7 no signal",detail:s,inLoop:!0,diagnostics:c},...["Save checkpoint","Activate policy"].map(l=>({label:l,state:"missing",status:"Source evidence",detail:"Inspect the source run",inLoop:!0,diagnostics:c}))];return{index:n.groupIndex,state:n.state,optimizerDisposition:n.optimizerDisposition,inherited:{sourceJobId:n.sourceJobId,checkpointId:t.checkpointId,checkpointJobId:t.checkpointJobId??t.sourceJobId,optimizerDisposition:n.optimizerDisposition,inputPolicyVersion:n.policyVersion,...a!==void 0?{outputPolicyVersion:a}:{}},meanReward:null,plannedSlots:0,attempts:[],diagnostics:c,nodes:d}})}i(eG,"inheritedRecoveryGroups");function L_(e){let t=e.job.inputBundle?.recovery;return t?.undurableProgress?.groups.map(r=>({sourceJobId:r.sourceJobId,checkpointId:t.checkpointId,checkpointJobId:t.checkpointJobId??t.sourceJobId,groupId:r.id,groupIndex:r.groupIndex,optimizerDisposition:r.optimizerDisposition,inputPolicyVersion:r.policyVersion,...typeof r.optimizerEvidence.outputPolicyVersion=="number"?{outputPolicyVersion:r.optimizerEvidence.outputPolicyVersion}:{}}))??[]}i(L_,"recoveryReplayOrigins");function tG(e){let t=new Set(e.rolloutGroups.map(r=>r.groupIndex));return L_(e).filter(r=>!t.has(r.groupIndex)).map(r=>{let n=e.job.inputBundle.recovery.undurableProgress.groups.find(a=>a.id===r.groupId),o=[uo("Replay boundary","Prior output was not checkpoint durable and was not restored. Replay is required."),uo("Prior attempt source run",r.sourceJobId),uo("Prior source group",r.groupId),...Xv(n.optimizerEvidence)];return{index:r.groupIndex,state:"replay_pending",replay:r,meanReward:null,plannedSlots:0,attempts:[],diagnostics:o,nodes:["Rollouts","Grade","Update adapter","Save checkpoint","Activate policy"].map(a=>({label:a,inLoop:!0,state:e.job.state==="failed"?"missing":"pending",status:"Replay pending",detail:"Prior output not restored",diagnostics:o}))}})}i(tG,"pendingReplayGroups");var Hue={Prepare:["start_inference"],"Load parent adapter":["materialize_checkpoint"],"Update adapter":["train_step"],"Save checkpoint":["upload_checkpoint","qualify_checkpoint"],"Activate policy":["start_inference"],Grade:["score_reward_model"],Finish:["stop"]},po=i(e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},"record"),rG=new WeakMap;function Due(e){let t=new Map;for(let r of e.rollouts){let n=t.get(r.groupId)??[];n.push(r),t.set(r.groupId,n)}return{attemptsByGroup:t,rollout:new Map(e.rollouts.map(r=>[r.id,r])),trajectory:new Map(e.trajectories.map(r=>[r.rolloutId,r]))}}i(Due,"buildIndex");function oG(e){let t=rG.get(e)??Due(e);return rG.set(e,t),t}i(oG,"index");var nG=i(e=>(typeof e=="number"||typeof e=="string"&&e.trim())&&Number.isFinite(Number(e))?Number(e):null,"metricNumber");function je(e,t,r="info"){let n=typeof t=="string"?t:JSON.stringify(t)??"Not retained";return{label:e,value:n.length>4e3?`${n.slice(0,3960)}\u2026 (retained excerpt)`:n,severity:r}}i(je,"fact");function Lue(e){let t=[],r=0,n=i((o,a,s="")=>{if(a>8||++r>2e3||t.length>=80)return;if(typeof o=="string"&&s==="feedback"&&o.length<512e3){try{n(JSON.parse(o),a+1)}catch{}return}if(Array.isArray(o)){for(let l of o.slice(0,100))n(l,a+1);return}let c=po(o),d=po(c.diagnostics);if(Array.isArray(d.differences))for(let l of d.differences.slice(0,80-t.length)){let u=po(l);typeof u.kind!="string"||typeof u.path!="string"||t.push(je(`${u.kind.replaceAll("_"," ")} \xB7 ${u.path}`,`Expected: ${JSON.stringify(u.expected)??"Not retained"}
|
|
60
|
+
`).slice(0,2e4)??null,evidenceRefs:[]}}),usage:_ue(e.charges.filter(k=>k.caseId===g.receiptId)),traceRef:h?{id:g.receiptId,contentHash:y?.traceHash??h.attempt.contentHash,mediaType:"application/json",sizeBytes:null}:null,startedAt:y?.startedAt??null,completedAt:y?.completedAt??null}})},l),{definition:p,...m}=t;return{execution:m,manifest:l,result:u}}i(P5,"localPortableExperiment");function _ue(e){let t=e.filter(s=>s.status!=="released"),r=t.every(s=>s.status==="settled"&&s.costUsd!==null),n=i(s=>{if(!t.length)return null;let c=t.map(d=>d.usage&&typeof d.usage=="object"?d.usage[s]:null);return c.every(d=>typeof d=="number"&&Number.isSafeInteger(d)&&d>=0)?c.reduce((d,l)=>d+l,0):null},"tokenSum"),o=n("promptTokens"),a=n("completionTokens");return{inputTokens:o,outputTokens:a,totalTokens:o===null||a===null?null:o+a,costUsd:r?t.reduce((s,c)=>s+c.costUsd,0):null,latencyMs:null}}i(_ue,"localCaseUsage");async function vm(e){let t=await e.store.getHarnessReleaseRecord(e.source.harnessRelease.contentHash);if(!t||t.harnessRelease.id!==e.source.harnessRelease.id)throw new oe("local_harness_source_unavailable","The exact released Harness is unavailable on this computer.",404);if(cj(t))throw new oe("local_harness_profile_required","This release requires its exact Profile composition. Select Model + Harness + Profile.",422);let r=await e.store.getHarnessWorkspace(t.workspaceId);if(!r)throw new oe("local_harness_origin_authority_missing","The cached Harness has no persisted owning workspace.",403);if(!(r.location==="local"&&r.ownerScope.kind==="personal"&&r.ownerScope.id===H$&&r.metadata.sourceLayout==="openpond.harnessSourceManifest.v1"&&r.metadata.selectionEligible!==!1&&typeof t.agentSnapshot.metadata.profileRepositoryId!="string"&&typeof t.harnessRelease.metadata.profileRepositoryId!="string")){if(e.authorizeRemote)return await e.authorizeRemote(e.source,r),r;throw new oe("local_harness_origin_authority_missing","This cached Harness needs an authenticated origin-access check. Import a device-owned local Harness or refresh its authorized source.",403)}return r}i(vm,"authorizeLocalExperimentSource");async function R5(e,t){if(e.kind!=="hosted_chat"||!e.harness)return!1;if(t?.qualified!==!0)throw new oe("local_harness_not_qualified","This released Harness requires a qualified native execution owner; it cannot run as a model-only case.",422);if(e.messages?.length)throw new oe("local_harness_prompt_not_qualified","Standalone Harness cases use released instructions. Additional raw model messages are not admitted.",422);return await t.resolve(e.harness),!0}i(R5,"admitLocalNativeHarness");function x5(e){let t=i(async(a,s)=>{if((await vm({store:e.store,source:a,authorizeRemote:e.authorizeRemote})).id!==s.id)throw new oe("local_harness_origin_access_denied","The source owning workspace changed during admission.",403)},"authorizeWorkspace"),r=fq({...e,authorizeWorkspace:t});async function n(a){let s=await e.actorId(),c=await e.teamId();if(!s.trim()||!c.trim())throw new oe("local_account_required","Sign in and select a workspace before using a native Harness.",403);await vm({store:e.store,source:a,authorizeRemote:e.authorizeRemote});let d=await mq({store:e.store,source:a,authorizeWorkspace:t});if(g2(d.runtime.release),await e.actorId()!==s||await e.teamId()!==c)throw new oe("local_workspace_denied","The signed-in account or workspace changed during native source admission.",403)}return i(n,"resolve"),{native:{qualified:!0,resolve:n,execute:i(async a=>(await n(a.source),r.execute(a)),"execute")},resolveSessionModelStream:r.resolveSessionModelStream}}i(x5,"createLocalNativeExperimentOwner");function Vv(e){let t=e.ownerId??Eue(),r=new Map,n=new Map,o=new Map,a=new Tue,s=new Map,c=!1,d,l=hq({resolvePolicy:i(async D=>{let O=s.get(D.id);if(!O||T(O.admission.request)!==T(D))throw new oe("local_case_admission_missing","Only the durable local execution owner may dispatch a case.");return gq({request:D,stream:ny({store:e.store,ownerId:t,teamId:O.execution.teamId,executionId:O.execution.id,caseId:O.admission.receiptId,admission:g(O.model,O.execution.ownerActorId,O.execution.teamId,O.execution.id),stream:w(O.execution.ownerActorId,O.execution.teamId,O.execution.id)})})},"resolvePolicy"),executeProfile:i(async()=>{throw new oe("local_profile_not_qualified","Profile targets require the shared released-target adapter.",422)},"executeProfile"),resolveEnvironment:e.environment?async D=>{let O=s.get(D.id);if(!O||T(O.admission.request)!==T(D)||!e.environment)throw new oe("local_environment_owner_missing","Only the durable case owner may resolve this exact environment.",422);return e.environment.resolve(D,N=>e.store.appendLocalExperimentEvent({teamId:O.execution.teamId,id:O.execution.id,caseId:O.admission.receiptId,ownerId:t,type:"environment.operation",payload:N}))}:void 0,executeHarness:i(async(D,O)=>{let N=s.get(D.id),$=e.nativeHarness;if(!N||T(N.admission.request)!==T(D)||$?.qualified!==!0||!D.harness)throw new oe("local_native_owner_missing","Only the durable case owner may dispatch the admitted native Harness.",422);let J=await $.execute({executionId:N.execution.id,request:D,source:D.harness,stream:ny({store:e.store,ownerId:t,teamId:N.execution.teamId,executionId:N.execution.id,caseId:N.admission.receiptId,admission:g(N.model,N.execution.ownerActorId,N.execution.teamId,N.execution.id),stream:w(N.execution.ownerActorId,N.execution.teamId,N.execution.id)}),signal:O,maxOutputBytes:262144}),K=sc(J.attempt),F=K.native;if(K.taskId!==D.taskId||!F||F.admissionHash!==D.admissionHash||F.modelConfigurationHash!==D.model.configurationHash||T(F.source)!==T(D.harness)||F.sessionId!==J.sessionId||F.turnId!==J.turn.id||F.traceHash!==J.traceHash||T(F.runtimeEventRefs)!==T(J.runtimeEventRefs))throw new oe("local_native_receipt_conflict","Native output or trace differs from the exact admitted case.");return J.attempt},"executeHarness")});async function u(D){if(await e.teamId()!==D)throw new oe("local_workspace_denied","Select this workspace before accessing its local Experiments.",403)}i(u,"requireTeam");async function p(D){if(await e.actorId()!==D)throw new oe("local_resource_denied","This local resource is unavailable to the current account.",404)}i(p,"requireActor");async function m(D,O,N,$){let J=N?n.get(N):void 0;try{await p(D),await u(O),N&&await e.authorizeTransport?.(N),J&&N&&($.signal?.throwIfAborted(),J.assertExecution(N))}catch(K){throw J&&N&&$.requestId?new Uw(N,$.requestId,K):K}}i(m,"beforeTransport");function g(D,O,N,$){if(D.streamFactory){let K=D.streamFactory;return{...D,streamFactory:i(F=>{let G=K(F);return async function*(te){await m(O,N,$,te),yield*G(te)}},"streamFactory")}}if(!D.stream)return D;let J=D.stream;return{...D,stream:i(async function*(K){await m(O,N,$,K),yield*J(K)},"stream")}}i(g,"modelForActor");function w(D,O,N){return async function*($){await m(D,O,N,$),yield*(e.stream??ki)($)}}i(w,"streamForActor");async function h(D,O,N){let $=await e.store.readLocalExperiment(D,O,N);if(await p($.definition.ownerActorId),a.getStore()&&$.definition.configuration.request.project?.id!==a.getStore())throw new oe("local_project_resource_denied","This Experiment does not belong to the selected Project.",404);return $}i(h,"ownedDefinition");async function y(D,O){await u(D);let N=await e.store.readLocalExecution(D,O);await p(N.execution.ownerActorId);let $=await e.store.readLocalExperimentRecord(D,O);if(a.getStore()&&$.configuration.request.project?.id!==a.getStore())throw new oe("local_project_resource_denied","This Experiment does not belong to the selected Project.",404);return await p($.ownerActorId),await u(D),$}i(y,"ownedRecord");async function f(D,O){let N=await e.store.readLocalExecution(D,O);await p(N.execution.ownerActorId);let $=N.execution.kind==="target"?O:N.execution.sourceExecution.id;return await y(D,$),N}i(f,"ownedExecution");let S=S5({...e,ownerId:t,requireTeam:u,requireActor:p,requireExecution:i(async(D,O)=>{await f(D,O)},"requireExecution"),streamForActor:w,active:r,controllers:o});async function k(D,O){if(D.request.policy.kind!=="hosted_harness")return!1;if(!e.profile)throw new oe("local_profile_not_qualified","This local server has no qualified exact Profile owner.",422);return await e.profile.resolve(D,O),!0}i(k,"admitProfile");let I=k5({localInference:e.localInference,prepareModel:e.prepareModel,store:e.store,ownerId:t,catalog:e.catalog,actorId:e.actorId,requireActor:p,requireTeam:u,ownedRecord:y,closing:i(()=>c,"closing"),assertScope:i(D=>{if(a.getStore()&&D.request.project?.id!==a.getStore())throw new oe("local_project_resource_denied","This Experiment does not belong to the selected Project.",404)},"assertScope"),authorize:i(async D=>{await e.authorizeProject?.(D)},"authorize"),preflight:i(async(D,O)=>{let N=await k(D,O),$=await R5(D.request.policy,e.nativeHarness);return await e.environment?.preflight(O),{profile:N,native:$,environment:!!e.environment}},"preflight"),package:i(async D=>{let{sourceExperimentId:O,...N}=D.configuration,$={...N,expectedRevision:0};if($.request.policy.kind==="hosted_harness"&&e.profile)return e.profile.package($);if(!e.resolvePackage)throw new oe("local_release_transfer_unavailable","This server cannot read an exact retained Dataset release.",503);return e.resolvePackage({configuration:$,...D.expectedPackageHash?{expectedPackageHash:D.expectedPackageHash}:{}})},"package"),schedule:i((D,O,N)=>{if(r.has(D.id))return;let $=nU();$&&n.set(D.id,$);let J=b(D,O,N).finally(()=>{r.delete(D.id),o.delete(D.id),n.delete(D.id)});r.set(D.id,J)},"schedule")});async function b(D,O,N){let $=null,J=!0,K=new AbortController;o.set(D.id,K);let F=await e.store.readLocalExperiment(D.teamId,D.definition.id,D.definition.revision),G=mt(F.package),te=F.definition;try{for(let le of O){if(c||!await e.store.admitLocalCase(D.teamId,D.id,le.receiptId,t))break;s.set(le.request.id,{execution:D,admission:le,model:N});let ae=null;try{K.signal.throwIfAborted();let ne=te.configuration.request.policy.kind==="hosted_harness"&&e.profile?await e.profile.execute({executionId:D.id,admission:le,configuration:te.configuration,package:G,stream:ny({store:e.store,ownerId:t,teamId:D.teamId,executionId:D.id,caseId:le.receiptId,admission:g(N,D.ownerActorId,D.teamId,D.id),stream:w(D.ownerActorId,D.teamId,D.id)}),signal:K.signal}):await l.execute(le.request);ae=ne,te.model.providerId==="claude-code"&&(ne=await w_({store:e.store,teamId:D.teamId,executionId:D.id,caseId:le.receiptId,attempt:ne})),ae=ne;let re=sc(ne);if(te.configuration.request.policy.kind==="hosted_harness"){let ue=re.profileNative;if(!ue||ue.admissionHash!==le.request.admissionHash||ue.modelConfigurationHash!==te.model.configurationHash||T(ue.source)!==T(te.configuration.request.policy.source))throw new oe("local_profile_receipt_conflict","Profile output or trace differs from the exact admitted case.")}let Ce=G.taskset.tasks.find(ue=>ue.id===le.taskId),he=await Yw({storeDir:e.storeDir,attempt:re,signal:K.signal,events:i(async ue=>{if(!e.runtimeEventsForTurn)throw new Error("The actual artifact trace owner is unavailable.");return e.runtimeEventsForTurn(ue)},"events"),authorize:i(async()=>{await p(D.ownerActorId),await u(D.teamId),K.signal.throwIfAborted()},"authorize")}),de=await Wv({store:e.store,ownerId:t,teamId:D.teamId,executionId:D.id,caseId:le.receiptId,package:G,task:Ce,evidence:{output:{text:re.output??"",...he.length?{artifacts:he}:{}},runtimeEventRefs:re.native?.runtimeEventRefs??re.profileNative?.runtimeEventRefs??re.externalProcess?.runtimeEventRefs??[],artifactRefs:he.map(ue=>ue.reference.id),infrastructureError:re.status==="completed"?null:re.error??re.status},evaluatorContext:zv(re),graders:te.graders,signal:K.signal,beforeDispatch:i(async()=>{await p(D.ownerActorId),await u(D.teamId),K.signal.throwIfAborted(),te.configuration.request.policy.kind==="hosted_harness"&&e.profile&&await e.profile.resolve(te.configuration,G),K.signal.throwIfAborted()},"beforeDispatch"),judgeProvider:Fo({stream:w(D.ownerActorId,D.teamId,D.id),catalog:e.catalog})});await e.store.settleLocalCase({teamId:D.teamId,id:D.id,receiptId:le.receiptId,ownerId:t,status:re.status==="completed"?"completed":re.status==="cancelled"?"cancelled":"failed",result:gl(ne,de),error:re.error}),re.status!=="completed"&&($=re.error??re.status)}catch(ne){$=_5(ne);let re=null;if(ae)try{te.model.providerId==="claude-code"&&(ae=await w_({store:e.store,teamId:D.teamId,executionId:D.id,caseId:le.receiptId,attempt:ae})),re=gl(ae,null)}catch{J=!1}else J=!1;await e.store.settleLocalCase({teamId:D.teamId,id:D.id,receiptId:le.receiptId,ownerId:t,status:K.signal.aborted?"cancelled":"failed",result:re,error:$})}finally{s.delete(le.request.id)}if($)break}c&&await e.store.cancelLocalExecution(D.teamId,D.id),await e.store.finishLocalExecution(D.teamId,D.id,t,$,J)}catch(le){$=_5(le),await e.store.finishLocalExecution(D.teamId,D.id,t,$,!1).catch(()=>{})}}i(b,"executeAdmissions");async function R(D){let O=$B.parse(D);await u(O.teamId);let N=await y(O.teamId,O.id);if(O.configurationHash&&N.configurationHash!==O.configurationHash)throw new oe("local_configuration_pin_conflict","The retained Experiment differs from the requested configuration.");return N}i(R,"read");async function _(D){let O=LB.parse(D);await u(O.teamId);let N=await e.actorId(),$=await e.store.listLocalExperimentRecords({...O,ownerActorId:N});return await u(O.teamId),await p(N),$}i(_,"list");async function P(D,O){let N=(await f(D,O)).execution;if(N.kind==="target")return y(D,O);let{definition:$,...J}=N;return J}i(P,"publicExecution");async function x(D){let O=ip.parse(D);return await u(O.teamId),P(O.teamId,O.id)}i(x,"status");async function E(D){let O=v.object({teamId:v.string().min(1),id:v.string().min(1),afterSequence:v.number().int().nonnegative().optional(),afterCallId:v.string().min(1).optional()}).strict().parse(D),N=await y(O.teamId,O.id);return b5(e.store,N,{afterSequence:O.afterSequence,afterCallId:O.afterCallId})}i(E,"diagnostics");async function C(D){let O=ip.parse(D);await u(O.teamId),await f(O.teamId,O.id);let N=await e.store.cancelLocalExecution(O.teamId,O.id);o.get(O.id)?.abort(new Error("local_experiment_cancelled"));for(let $ of s.values())$.execution.id===O.id&&$.execution.teamId===O.teamId&&l.cancel($.admission.request.id);return P(O.teamId,O.id)}i(C,"cancel");async function A(D){let O=ip.parse(D);await u(O.teamId);let N=await f(O.teamId,O.id),$={execution:await P(O.teamId,O.id),cases:N.cases.map(J=>({receiptId:J.receiptId,taskId:J.admission.taskId,seed:J.admission.seed,status:J.status,input:J.admission.request.input,policyVisibleContext:J.admission.request.policyVisibleContext,output:J.result?Lt(J.result).attempt.output:null,messages:J.result?Lt(J.result).attempt.messages:[],grade:J.result?Lt(J.result).grade:null,error:J.error,...J.result&&Lt(J.result).attempt.native?{native:Lt(J.result).attempt.native}:{},...J.result&&Lt(J.result).attempt.externalProcess?{externalProcess:Lt(J.result).attempt.externalProcess}:{},...J.result&&Lt(J.result).attempt.profileNative?{profileNative:Lt(J.result).attempt.profileNative}:{}}))};return{...$,contentHash:T($)}}i(A,"result");async function j(D){let O=v.object({teamId:v.string().min(1),id:v.string().min(1),receiptId:v.string().min(1),afterSequence:v.number().int().nonnegative().optional(),limit:v.number().int().min(1).max(500).default(100)}).strict().parse(D),N=await A({teamId:O.teamId,id:O.id}),$=N.cases.find(K=>K.receiptId===O.receiptId);if(!$)throw new oe("local_case_not_found","The selected case does not belong to this execution.",404);let J=await e.store.localExperimentTrace({teamId:O.teamId,id:O.id,caseId:O.receiptId,afterSequence:O.afterSequence,limit:O.limit});return{location:"local",execution:N.execution,case:$,trace:J}}i(j,"inspectCase");async function H(D){let O=v.object({teamId:v.string().min(1),baselineId:v.string().min(1),candidateId:v.string().min(1)}).strict().parse(D);await u(O.teamId);let N=i(async F=>{let G=await f(O.teamId,F),te=await h(O.teamId,G.execution.definition.id,G.execution.definition.revision),le=G.execution.kind==="scoring"?(await e.store.readLocalScoringSelection(O.teamId,F)).graders:te.definition.graders,ae=await e.store.readLocalExecutionCharges(O.teamId,F);await u(O.teamId),await p(G.execution.ownerActorId);let ne=await y(O.teamId,G.execution.sourceExecution?.id??F);return P5({retained:G,definition:te.definition,package:te.package,graders:le,charges:ae,retainedConfigurationHash:ne.retainedConfigurationHash})},"source"),$=N(O.baselineId),[J,K]=await Promise.all([$,O.candidateId===O.baselineId?$:N(O.candidateId)]);return{location:"local",baseline:J,candidate:K}}i(H,"compare");let L=nv();async function B(D){let O=ip.parse(D),N=await y(O.teamId,O.id);if(!N.completedAt)throw new oe("local_result_unavailable","This Experiment has no complete retained result yet.",422);return L(T({teamId:N.teamId,actorId:N.ownerActorId,id:N.id,executionHash:N.executionHash}),async()=>{let $=(await H({teamId:O.teamId,baselineId:O.id,candidateId:O.id})).baseline;return rv({experimentId:N.id,executionManifestHash:N.executionHash,total:N.configuration.request.population.length,graders:N.graders,evidence:$})})}i(B,"feedbackSummary");async function q(D){let O=v.object({teamId:v.string().min(1).max(200),projectId:v.string().min(1).max(200).nullable().optional(),action:v.enum(["claudeReadiness","claudeControl","localInferenceChoices","sourceDataset","sourceChoices","prepareHarness","run","runFromRelease","read","get","list","status","cancel","result","score","scoreRetained","passes","pass","compare","feedbackSummary","case","diagnostics"]),payload:v.unknown()}).strict().parse(D),N=await e.actorId();if(!N.trim())throw new oe("local_account_required","Sign in before accessing local Experiments.",403);let $=await a.run(O.projectId??null,()=>W(O));return await u(O.teamId),await p(N),$}i(q,"request");async function W(D){await u(D.teamId);let O=i(()=>({...v.record(v.string(),v.unknown()).parse(D.payload),teamId:D.teamId,...D.projectId&&D.action==="list"?{projectId:D.projectId}:{}}),"scoped");if(D.action==="claudeReadiness"){if(!e.localInference?.claudeReadiness)throw new oe("claude_runtime_unavailable","Claude process owner is unavailable.",503);return e.localInference.claudeReadiness()}if(D.action==="claudeControl"){let $=v.object({id:v.string().min(1)}).passthrough().parse(D.payload);if(await f(D.teamId,$.id),!e.localInference?.claudeControl)throw new oe("claude_runtime_unavailable","Claude process owner is unavailable.",503);return e.localInference.claudeControl(D.teamId,D.payload)}if(D.action==="localInferenceChoices"){if(!e.localInference)throw new oe("local_inference_unavailable","Local inference owner is unavailable.",503);return e.localInference.choices()}if(D.action==="sourceDataset"){let $=await e.actorId();if(!e.sourceDataset)throw new oe("local_source_catalog_unavailable","The local source catalog is unavailable.",503);let J=await e.sourceDataset(D.payload,D.teamId);return await u(D.teamId),await p($),J}if(D.action==="sourceChoices"){let $=await e.actorId(),J=ow.parse(await e.sourceChoices?.()??{location:"local",harnesses:[],profiles:[]});return await u(D.teamId),await p($),J}if(D.action==="prepareHarness"){if(!e.profile)throw new oe("local_profile_not_qualified","This local server has no qualified Profile owner.",422);return e.profile.prepare(D.payload,D.teamId)}if(D.action==="scoreRetained"){if(c)throw new oe("local_runtime_closing","The local execution owner is closing.",503);let $=NB.parse(D.payload),J=(await f(D.teamId,$.execution.id)).execution,K=await h(D.teamId,J.definition.id,J.definition.revision),F=await S.score({...$,graderPackage:K.package},D.teamId);return P(D.teamId,F.id)}if(D.action==="run"||D.action==="runFromRelease"){if(v.object({configuration:v.object({request:v.object({teamId:v.string()}).passthrough()}).passthrough()}).passthrough().parse(D.payload).configuration.request.teamId!==D.teamId)throw new oe("local_workspace_conflict","The configuration belongs to another workspace.",403);return I[D.action](D.payload)}if(D.action==="score"){if(c)throw new oe("local_runtime_closing","The local execution owner is closing.",503);let $=await S.score(D.payload,D.teamId);return P(D.teamId,$.id)}return{read:R,get:R,list:_,status:x,cancel:C,result:A,passes:i(async $=>{let J=await S.passes($);return{...J,items:J.items.map(K=>{let{definition:F,...G}=K;return G})}},"passes"),pass:i(async $=>{let J=await S.pass($),{definition:K,...F}=J.execution;return{...J,execution:F}},"pass"),compare:H,feedbackSummary:B,case:j,diagnostics:E}[D.action](O())}i(W,"handleCommand");async function Z(D,O,N){await u(D);let $=await e.actorId();if(!e.readHumanTaskPackage)throw new oe("human_task_source_unavailable","The exact task release resolver is unavailable.",503);let J=mt(await e.readHumanTaskPackage(D,O,N));if(await u(D),await p($),T({id:J.taskset.id,revision:J.taskset.revision,contentHash:J.taskset.contentHash})!==T(N))throw new oe("human_task_release_changed","The Dataset release changed.",409);return J}i(Z,"readHumanTaskPackage");async function Y(D,O){await u(D);let N=await e.store.findLocalExperimentRunOperation(D,O);if(!N)return null;let $=await y(D,N.id);if($.operationId!==O)throw new oe("local_operation_conflict","Original operation identity changed.",409);return $}return i(Y,"findRunOperation"),{authorize:I.authorize,findRunOperation:Y,readHumanTaskPackage:Z,run:I.run,runFromRelease:I.runFromRelease,read:R,list:_,status:x,cancel:C,result:A,inspectCase:j,compare:H,score:S.score,scoreSelected:i(async(D,O)=>{if(c)throw new oe("local_runtime_closing","The local owner is closing.",503);let N=await S.scoreSelected(O,D);return P(D,N.id)},"scoreSelected"),passes:S.passes,pass:S.pass,request:q,async recover(){if(e.managesRuntimeLease===!1)return[];await e.store.claimLocalExperimentOwner(t);let D=await e.store.recoverLocalExperiments(t);return d=setInterval(()=>{e.store.renewLocalExperimentOwner(t).catch(()=>{c=!0;for(let O of o.values())O.abort(new Error("local_runtime_lease_lost"));l.close()})},5e3),d.unref(),D},async close(){c=!0;for(let D of o.values())D.abort(new Error("local_runtime_closed"));await l.close(),await Promise.allSettled([...r.values()]),d&&clearInterval(d),e.managesRuntimeLease!==!1&&await e.store.releaseLocalExperimentOwner(t)},async wait(D){await r.get(D)}}}i(Vv,"createLocalExperimentService");function _5(e){return(e instanceof Error?e.message:"Local execution failed.").slice(0,2e3)}i(_5,"message");function Gv(){let e;async function t(){if((await mR({source:"export function collect(v) { return {state:v.state,observation:{ready:v.services.js.cases[0]===7&&v.services.sql.status==='completed'}}; }",operation:"collect",timeoutMs:1e4,value:{input:{sql:"SELECT 1"},state:{},initialState:{source:"export function check(v){return v;}",cases:[{input:7}],snapshot:{tables:[]}},action:null},executionServices:[{id:"js",kind:"javascript.v1",operation:"collect",timeoutMs:4e3,source:{scope:"initialState",path:["source"]},cases:{scope:"initialState",path:["cases"]},exportName:"check",maxCases:1,maxResultBytes:256},{id:"sql",kind:"sqlite.v1",operation:"collect",timeoutMs:4e3,sql:{scope:"input",path:["sql"]},snapshot:{scope:"initialState",path:["snapshot"]},maxRows:1,maxResultBytes:256}]})).observation.ready!==!0)throw new Error("local_environment_runtime_unavailable")}return i(t,"checkRuntime"),{async preflight(r){let n=GO(r);if(!n)return;let o=n.execution.javascript,a=n.assets.find(s=>s.id===o.module.id);if(!a)throw new oe("local_environment_assets_missing","The exact environment module is unavailable.",422);if(Mo(a,o.module),o.executionServices?.some(s=>s.kind!=="javascript.v1"&&s.kind!=="sqlite.v1"))throw new oe("local_environment_service_unavailable","This Dataset requires an unsupported local execution service.",422);e??=t().catch(s=>{throw e=void 0,s});try{await e}catch{throw new oe("local_environment_runtime_unavailable","The local isolated JavaScript/SQL runtime is unavailable.",503)}},resolve(r,n){if(r.environment.kind!=="javascript")throw new Error("local_environment_required");let o=r.environment,{definition:a,asset:s}=o,c=Mo(s,a.module),d=0,l=T({}),u=!1;return async p=>{if(p.signal?.throwIfAborted(),u)throw new Error("local_environment_operation_in_progress");if(p.source!==c)throw new Error("local_environment_source_mismatch");if(T(p.value.initialState)!==T(o.initialState)||T(p.value.input)!==T(r.input)||p.value.seed!==o.seed||T(p.value.state)!==l)throw new Error("local_environment_private_state_mismatch");let m=p.value.action,g=a.executionServices?.filter(h=>h.operation===p.operation&&(p.operation!=="step"||h.toolName===m?.name))??[];if(T(p.executionServices??[])!==T(g))throw new Error("local_environment_service_mismatch");pi(p.value,4194304);let w={ordinal:d++,operation:p.operation,definitionHash:a.contentHash,servicesHash:T(g),requestHash:T(p.value),runtime:"desktop-local-evals-process"};await n({...w,status:"admitted"}),u=!0;try{let h=await mR(p);return l=T(h.state),await n({...w,status:"completed",resultHash:T(h),childCleanupComplete:!0}),h}catch(h){throw await n({...w,status:p.signal?.aborted?"cancelled":"failed",childCleanupComplete:!0}),h}finally{u=!1}}}}}i(Gv,"createLocalExperimentEnvironment");async function E5(e){let t=Qh.extend({profileRef:va,profileSource:v.object({sourceRevision:v.string().min(1).max(500),harnessRelease:v.object({id:v.string().min(1),contentHash:v.string().regex(/^[a-f0-9]{64}$/)}).strict()}).strict().optional()}).parse(e.raw);if(t.profileRef.repositoryId!==t.profileRepositoryId)throw new oe("local_profile_origin_not_qualified","Choose an accepted device-local Profile repository.",403);if(t.reasoningEffort)throw new oe("local_profile_sampling_not_qualified","This local Profile owner does not admit reasoning overrides.",422);if(t.localRuntime&&(t.maxOutputTokens!==void 0||t.temperature!==void 0||t.topP!==void 0))throw new oe("local_profile_sampling_not_qualified","This native provider runtime does not admit output or sampling overrides.",422);let r=t.localRuntime?void 0:$u(t),n=await e.prepare({id:`local-profile-review-${T([e.teamId,t.operationId]).slice(0,40)}`,createdAt:"1970-01-01T00:00:00.000Z",profileRef:t.profileRef,...t.profileSource?{profileSource:t.profileSource}:{},definitionId:t.definitionId,externalDatasetBinding:t.externalDatasetBinding,modelRef:{providerId:t.localRuntime?.providerId??"openpond",modelId:t.modelId},maximumSpendUsd:t.maximumCostUsd},{modelSampling:r}),o=n.manifest.profileEvaluation,a=await e.loadPackage(n),s={kind:"hosted_harness",modelId:t.modelId,profileRepositoryId:t.profileRepositoryId,...r,source:o,modelConfigurationHash:n.modelConfigurationHash,packageHash:a.contentHash,...o.externalDatasetBinding?{externalDatasetBinding:o.externalDatasetBinding}:{},...t.localRuntime?{localRuntime:t.localRuntime}:{}},c={schemaVersion:"openpond.modelTasksetRunRequest.v1",operationId:t.operationId,teamId:e.teamId,modelProjectId:null,name:o.definitionId,taskset:{id:n.taskset.id,revision:n.taskset.revision,contentHash:n.taskset.contentHash},policy:s,population:n.manifest.population},d={operationId:t.operationId,expectedRevision:0,request:c,maximumCostUsd:t.maximumCostUsd};return await e.resolve(d,a),Zh.parse({request:c,manifest:n.manifest,maximumCostUsd:t.maximumCostUsd,graders:Sr(a)})}i(E5,"prepareLocalProfileExperiment");function T5(e){let t=i(async(a,s,c)=>{let d=await e.store.getHarnessReleaseRecord(c.contentHash),l=d&&await e.store.getHarnessWorkspace(d.workspaceId);if(l?.metadata.profileExperimentOrigin!==void 0||l?.metadata.experimentCandidateOrigin!==void 0){if(!e.resolveProfileRef)throw new Error("The Profile origin is not authenticated.");return e.resolveProfileRef(a,s,c)}return{source:"local",repositoryId:a,profileId:s}},"profileRef"),r=new Map;async function n(a,s){let c=a.request.policy;if(c.kind!=="hosted_harness")throw new oe("local_profile_policy_required","Select an exact prepared Profile target.",422);if(c.localRuntime&&(c.maxOutputTokens!==void 0||c.temperature!==void 0||c.topP!==void 0))throw new oe("local_profile_sampling_not_qualified","This native provider runtime does not admit output or sampling overrides.",422);let d=await e.actorId(),l=await e.teamId();if(!d||l!==a.request.teamId)throw new oe("local_workspace_denied","The Profile belongs to another account or workspace.",403);if(c.localRuntime){if(!e.prepareNativeModel)throw new oe("local_profile_model_unavailable","The native Profile model owner is unavailable.",422);await e.prepareNativeModel(a)}let u=await e.prepare({id:`local-profile-${T(a).slice(0,40)}`,createdAt:"1970-01-01T00:00:00.000Z",profileRef:await t(c.profileRepositoryId,c.source.profileId,c.source.harnessRelease),profileSource:{sourceRevision:c.source.sourceRevision,harnessRelease:c.source.harnessRelease},externalDatasetBinding:c.source.externalDatasetBinding,definitionId:c.source.definitionId,modelRef:{providerId:c.localRuntime?.providerId??"openpond",modelId:c.modelId},maximumSpendUsd:a.maximumCostUsd},{modelSampling:c.localRuntime?void 0:$u(c)});if(await Yr(e.store,c.source.harnessRelease,u.profileRef,e.authorizeOrigin),u.manifest.runtimeTarget.placement!=="local"||T(u.manifest.profileEvaluation)!==T(c.source)||u.profileRef.repositoryId!==c.profileRepositoryId||u.modelConfigurationHash!==c.modelConfigurationHash||u.manifest.packageHash!==c.packageHash||s.contentHash!==c.packageHash||u.taskset.contentHash!==s.taskset.contentHash)throw new oe("local_profile_source_conflict","Prepare this exact Profile and Dataset through the local runtime before running. Hosted or changed source receipts are not local authority.",422);if(!Gw(s))throw new oe("local_profile_environment_not_qualified","This Profile requires an additional admitted local tool or Work environment.",422);let p=a.request.population,m=u.manifest.population,g=new Set(p.map(w=>JSON.stringify([w.taskId,w.seed])));if(p.length!==m.length||g.size!==m.length||m.some(w=>!g.has(JSON.stringify([w.taskId,w.seed]))))throw new oe("local_profile_population_conflict","This Profile evaluation requires its complete declared task and seed population.",422);if(await e.actorId()!==d||await e.teamId()!==l)throw new oe("local_workspace_denied","The account changed during Profile source admission.",403);return u}i(n,"resolve");async function o(a){let s=await n(a.configuration,a.package),c=s.manifest.profileEvaluation,d=await Yr(e.store,c.harnessRelease,s.profileRef,e.authorizeOrigin);dj(d.release);let l=s.taskset.tasks.find(b=>b.id===a.admission.taskId),u=l.artifactRefs.map(b=>{if(b.visibility!=="policy"||b.mediaType!=="application/pdf"||b.sizeBytes>qD.maxAttachmentBytes)throw new Error("The target input needs a bounded policy PDF.");let R=a.package.files.find(_=>T(_.asset)===T(b));if(!R)throw new Error("The exact policy input artifact is unavailable.");return hi(R),Oo.parse({id:b.id,name:b.path.split("/").at(-1),kind:"file",mediaType:b.mediaType,sizeBytes:b.sizeBytes,contentsBase64:R.base64})}),p={executionId:a.executionId,admissionHash:a.admission.request.admissionHash,source:c,modelConfigurationHash:a.admission.request.model.configurationHash},m=a.signal,g=await e.actorId(),w=i(async function*(b){if(b.model!==a.admission.request.model.modelId)throw new Error("Profile Experiment requested another model.");yield*a.stream({...b,maxTokens:a.admission.request.model.maxOutputTokens,temperature:a.admission.request.model.temperature,topP:a.admission.request.model.topP,signal:b.signal?AbortSignal.any([m,b.signal]):m})},"stream"),h=c.externalDatasetBinding?await e.resolveExternalDataset?.(c.externalDatasetBinding,{profileRef:s.profileRef,sourceRevision:c.sourceRevision,harnessRelease:c.harnessRelease}):void 0;if(c.externalDatasetBinding&&!h)throw new Error("The external target has no actual isolated Dataset authority.");let y=lU({storeDir:e.storeDir,release:d.release,getTurn:i(b=>e.store.getTurn(b),"getTurn"),getSession:i(async b=>{let R=await e.store.getSession(b);if(!R)throw new Error("The target Session is unavailable.");return R},"getSession"),saveOutput:e.saveOutput,recordOutput:e.recordOutput,authorize:i(async b=>{if(b.bindingHash!==(c.externalDatasetBinding?.contentHash??T(c))||b.manifestHash!==s.manifest.contentHash||b.taskId!==a.admission.taskId||b.seed!==a.admission.seed)throw new Error("The isolated target requested another exact case.");if(await h?.authorize(),await e.actorId()!==g||await e.teamId()!==a.configuration.request.teamId)throw new Error("The current target workspace changed.");await Yr(e.store,c.harnessRelease,s.profileRef,e.authorizeOrigin),m.throwIfAborted()},"authorize")}),f,S=!1,k,I=vU({...s,attachments:u,requiredOutputs:l.requiredOutputs??[],createSession:i(async b=>(m.throwIfAborted(),await Yr(e.store,c.harnessRelease,s.profileRef,e.authorizeOrigin),m.throwIfAborted(),e.createSession(b)),"createSession"),sendTurn:i((b,R,_)=>e.sendTurn(b,R,void 0,void 0,_),"sendTurn"),interruptSessionTurn:e.interruptSessionTurn,runtimeEventsForTurn:i(b=>e.store.runtimeEventsForTurn(b),"runtimeEventsForTurn"),maximumOutputBytes:262144,retainOutputLimitEvidence:!0,onOutputLimit:i(b=>{k=b},"onOutputLimit"),validateTerminalTurn:i(async(b,R)=>{if(R.sessionId!==b.id||!R.profileSnapshot||T(R.profileSnapshot.ref)!==T(s.profileRef)||R.profileSnapshot.revision!==c.sourceRevision||R.profileSnapshot.sourceHash!==c.harnessRelease.contentHash)throw new Error("Local Profile terminal receipt changed its exact source binding.");if((await e.store.runtimeEventsForTurn(R.id)).some(P=>P.sessionId!==b.id||P.turnId!==R.id))throw new Error("Profile trace contains another case's evidence.")},"validateTerminalTurn"),onInterrupt:i(b=>{S=b==="timed_out"},"onInterrupt"),assertSpendAuthority:i(async b=>{if(b.contentHash!==s.manifest.contentHash||b.limits.maximumSpendUsd===null)throw new Error("Local Profile spend admission changed.");m.throwIfAborted()},"assertSpendAuthority"),ownedSessionMetadata:{localProfileExperiment:p},admitSession:i(async b=>{if(await Yr(e.store,c.harnessRelease,s.profileRef,e.authorizeOrigin),T(b.currentProfile)!==T(s.profileRef))throw new Error("Local Profile session acquired another Profile.");await dw({store:e.store,runId:b.id,workspace:d.workspace,harnessRelease:c.harnessRelease,admittedAt:b.createdAt}),f=b.id,y&&await y.admitSession(b,s.manifest,a.admission.taskId,a.admission.seed,u),r.set(b.id,{binding:p,stream:w,profile:s.profileRef,source:c,isolated:y})},"admitSession")});try{let b=await I({task:{id:l.id,input:a.admission.request.input,policyVisibleContext:a.admission.request.policyVisibleContext,artifactRefs:l.artifactRefs,tags:l.tags},seed:a.admission.seed,source:c,signal:m}),R=k?null:b.evidence.output?.text??null,_={schemaVersion:"openpond.localProfileExperimentAttempt.v1",taskId:l.id,status:m.aborted?"cancelled":S?"timed_out":b.terminal?"completed":"policy_failure",output:R,error:b.evidence.infrastructureError??null,messages:[],environmentCleanupComplete:!0,collected:b.terminal,snapshot:null,artifactRefs:b.artifactRefs,profileNative:{...b.retainedEvidenceRef,source:c,profileRef:s.profileRef,admissionHash:a.admission.request.admissionHash,modelConfigurationHash:a.admission.request.model.configurationHash,traceHash:b.traceHash,runtimeEventRefs:b.evidence.runtimeEventRefs,startedAt:b.startedAt,completedAt:b.completedAt,outputHash:k??T(R??""),partialOutputAvailable:k!==void 0||!b.terminal&&!!R}};return{..._,contentHash:T(_)}}finally{f&&r.delete(f),y?.close()}}return i(o,"execute"),{profile:{resolve:n,execute:o,prepare:i((a,s)=>E5({raw:a,teamId:s,prepare:e.prepare,loadPackage:e.loadPackage,resolve:n}),"prepare"),package:i(async a=>{let s=a.request.policy;if(s.kind!=="hosted_harness")throw new Error("An exact Profile policy is required.");let c=await e.prepare({id:`local-profile-package-${T(a).slice(0,40)}`,createdAt:"1970-01-01T00:00:00.000Z",profileRef:await t(s.profileRepositoryId,s.source.profileId,s.source.harnessRelease),profileSource:{sourceRevision:s.source.sourceRevision,harnessRelease:s.source.harnessRelease},externalDatasetBinding:s.source.externalDatasetBinding,definitionId:s.source.definitionId,modelRef:{providerId:s.localRuntime?.providerId??"openpond",modelId:s.modelId},maximumSpendUsd:a.maximumCostUsd},{modelSampling:s.localRuntime?void 0:$u(s)}),d=await e.loadPackage(c);return await n(a,d),d},"package")},async isolatedProfileEvaluationForTurn(a){if(a.metadata?.localProfileExperiment===void 0)return!1;let s=r.get(a.id);if(!s)throw new Error("This target Session has no actual admitted case owner.");return!!s.isolated},async resolveModelTools(a){if(a.session.metadata?.localProfileExperiment===void 0)return null;let s=r.get(a.session.id);if(!s)throw new Error("This target Session has no actual admitted case owner.");return s.isolated?s.isolated.resolveTools(a):null},async executeProfileEvaluationAction(a){let s=r.get(a.session.id);if(!s?.isolated)throw new Error("This initial target Agent action has no actual isolated case owner.");return s.isolated.executeAction(a)},close(){for(let a of r.values())a.isolated?.close();r.clear()},async resolveSessionModelStream(a,s){let c=a.metadata?.localProfileExperiment;if(c===void 0)return null;let d=r.get(a.id);if(!d||T(c)!==T(d.binding)||T(a.currentProfile)!==T(d.profile)||s.sessionId!==a.id||!s.profileSnapshot||T(s.profileSnapshot.ref)!==T(d.profile)||s.profileSnapshot.revision!==d.source?.sourceRevision||s.profileSnapshot.sourceHash!==d.source.harnessRelease.contentHash)throw new Error("Local Profile Experiment has no matching active execution owner.");return d.stream}}}i(T5,"createLocalProfileExperimentOwner");async function Jv(e){let t=mt(e);if(Sr(t),t.taskset.metrics?.aggregation==="custom")throw new Error("The native Profile owner has not qualified its authored aggregate metric executor.");for(let r of t.taskset.graders){if(r.kind==="model_judge"&&r.calibrationStatus!=="passed")throw new Error("Select a calibrated private model judge before dispatch.");let n="verifierRef"in r?r.verifierRef:"rubricRef"in r?r.rubricRef:null;if(!n)continue;let o=t.files.find(a=>a.asset.id===n.id);if(!o||o.asset.visibility==="policy"||T(o.asset)!==T(n))throw new Error("The private grader differs from its actual pinned package asset.");new TextDecoder("utf8",{fatal:!0}).decode(hi(o))}}i(Jv,"assertNativeProfilePrivateGrading");import{readFile as Cue}from"node:fs/promises";import Aue from"node:path";function C5(e){async function t(){let r=new Map,n=[],o=[];for(let s of await e.store.listHarnessWorkspaces()){if(n.length>=100)break;for(let c of await e.store.listHarnessReleaseRecords(s.id)){if(n.length>=100)break;try{let d={id:c.harnessRelease.id,contentHash:c.harnessRelease.contentHash},l;if(s.location==="local"&&s.ownerScope.kind==="personal"&&s.ownerScope.id==="desktop-personal"){let u={harnessRelease:d,agentSnapshot:{id:c.agentSnapshot.id,contentHash:c.agentSnapshot.contentHash},sourcePackageHash:"0".repeat(64)};await vm({store:e.store,source:u});let p=new Map;for(let g of c.harnessRelease.files)p.set(g.path,await Cue(Aue.join(c.bundlePath,"source",...g.path.split("/"))));let m=ld({agentSnapshot:c.agentSnapshot,harnessRelease:c.harnessRelease,files:p});l={...u,sourcePackageHash:m.contentHash}}else{if(!e.remoteSource)continue;l=await e.remoteSource(s,d)}await e.native.resolve(l),n.push({id:`harness-${l.harnessRelease.contentHash}`,name:s.name,source:l})}catch{}}}let a=await(e.library??ut)();for(let s of[...a.profiles.filter(c=>c.ref.source==="local"),...await e.originProfiles?.()??[]])if(!(o.length>=100))try{let c=await e.workflows(s.ref);await Yr(e.store,c.harnessRelease,s.ref,e.authorizeOrigin);let d=await un({store:e.store,ref:s.ref,sourceRevision:c.sourceRevision,harnessRelease:c.harnessRelease});for(let l of d.definitions){if(o.length>=100)break;let u=mt(await e.loadPackage(l,s.ref.profileId,d.harnessRelease));if(u.taskset.id!==l.tasksetRelease.id||u.taskset.contentHash!==l.tasksetRelease.contentHash)throw new Error("Local Profile Dataset changed its exact binding.");if(u.taskset.tasks.length>1e4||!Gw(u)||u.taskset.tasks.some(m=>m.artifactRefs.some(g=>g.visibility!=="policy"||g.mediaType!=="application/pdf"||g.sizeBytes>1e7)))continue;await Jv(u);let p=`local-profile-${T([s.ref,d.harnessRelease,l.id])}`;r.set(p,u),o.push({id:p,name:`${s.name}, ${l.label}`,profileRef:s.ref,sourceRevision:d.sourceRevision,harnessRelease:d.harnessRelease,definitionId:l.id,definitionHash:T(l),taskset:{id:u.taskset.id,revision:u.taskset.revision,contentHash:u.taskset.contentHash},taskCount:u.taskset.tasks.length,taskIds:l.taskIds,seeds:l.seeds})}}catch{}return{choices:ow.parse({location:"local",harnesses:n,profiles:o}),packages:r}}return i(t,"discover"),{list:i(async()=>(await t()).choices,"list"),packageByRelease:i(async r=>{let n=[...(await t()).packages.values()].filter(o=>o.taskset.id===r.id&&o.taskset.revision===r.revision&&o.taskset.contentHash===r.contentHash);if(new Set(n.map(o=>o.contentHash)).size>1)throw new Error("The local Dataset has conflicting immutable package closures.");return n[0]??null},"packageByRelease"),population:i(async(r,n)=>{let o=v.object({id:v.string().min(1).max(240),view:v.enum(["ids","policy"]).default("ids"),afterId:v.string().optional(),limit:v.number().int().min(1).max(1e4).default(100)}).strict().parse(r);if(o.view==="policy"&&o.limit>100)throw new Error("Local Dataset policy previews are bounded to100 tasks.");let a=await t(),s=a.packages.get(o.id);if(!s)throw new Error("This exact local Profile Dataset is unavailable to the current account.");let c=[...s.taskset.tasks].sort((p,m)=>p.id<m.id?-1:p.id>m.id?1:0),d=c.filter(p=>!o.afterId||p.id>o.afterId).slice(0,o.limit),l=d.map(p=>({id:p.id,split:p.split,...o.view==="policy"?{input:p.input,policyVisibleContext:p.policyVisibleContext,artifacts:[]}:{}})),u={schemaVersion:"openpond.datasetPopulationPage.v1",teamId:n,release:{id:s.taskset.id,revision:s.taskset.revision,contentHash:s.taskset.contentHash},view:o.view,taskCount:c.length,items:l,graders:Sr(s),nextCursor:d.length===o.limit&&c.some(p=>p.id>d.at(-1).id)?d.at(-1).id:null};return Q2.parse({...u,contentHash:T(u)})},"population")}}i(C5,"createLocalExperimentSourceChoices");function y_(e){return async(t,r)=>{let n=await e.resolveAccess(),o=t.ownerScope;if(o.kind==="team"&&o.id!==n.teamId||o.kind==="personal"&&o.id!==n.actorId)throw new oe("local_harness_origin_access_denied","The cached Harness belongs to a different account or workspace.",403);let a=pe(n.token);a.set("x-openpond-team-id",n.teamId);let s=await Se({baseUrl:n.apiBaseUrl,headers:a,fetch:e.fetch}).getHarnessSource(r);if(s.harnessRelease.id!==r.id||s.harnessRelease.contentHash!==r.contentHash)throw new oe("local_harness_authorized_source_conflict","The authorized source differs from its original published release.",409);return{harnessRelease:r,agentSnapshot:{id:s.agentSnapshot.id,contentHash:s.agentSnapshot.contentHash},sourcePackageHash:s.contentHash}}}i(y_,"createLocalExperimentRemoteSourceLookup");function A5(e){let t=y_(e);return async(r,n)=>{let o=await t(n,r.harnessRelease);if(T(o)!==T(r))throw new oe("local_harness_authorized_source_conflict","The authorized published source differs from this immutable Harness closure.",409)}}i(A5,"createLocalExperimentRemoteSourceAuthority");function v_(e){return async t=>{let r=t.request;if(!r.project)return;let n=await e.resolveAccess(),o=await new ir({baseUrl:n.apiBaseUrl,apiKey:n.token,teamId:r.teamId,fetch:e.fetch}).get(r.project.id);if(o.archived||o.revision!==r.project.revision||T(o.content)!==r.project.contentHash)throw new oe("local_project_pin_conflict","The selected Project changed. Reload its configuration before saving or starting.",409);if(r.project.targetId!==null)throw new oe("local_project_target_not_qualified","Choose the explicit local model or prepare a local Profile target without inheriting a hosted Project target.",422)}}i(v_,"createLocalExperimentProjectAuthorizer");function M5(e){return async t=>{let r=await e.resolveAccess(),n=t.configuration.request,o={baseUrl:r.apiBaseUrl,apiKey:r.token,teamId:n.teamId,fetch:e.fetch};return await v_(e)(t.configuration),new nr(o).getByRelease(n.taskset,{expectedPackageHash:t.expectedPackageHash})}}i(M5,"createLocalExperimentPackageResolver");function j5(e){let{store:t,storeDir:r}=e,n=e.localInferenceState?Uv({state:e.localInferenceState,status:e.codexStatus}):void 0,o=i(P=>{let x=P.request.policy;if(x.kind!=="hosted_harness"||!x.localRuntime||!n)throw new Error("The native Profile model owner is unavailable.");return n.prepare(P)},"prepareNativeModel"),a=i(async()=>({...await e.resolveAccess(),teamId:await e.teamId(),actorId:await e.actorId()}),"sourceAccess"),s=Hi({store:t,storeDir:r,resolveAccess:a}),c=e.candidateOrigins,d=i(async(P,x,E)=>P.metadata.experimentCandidateOrigin!==void 0?c?c.authority(P,x,E):Promise.reject(new Error("Candidate origin authority is unavailable.")):s.authority(P,x,E),"authorizeOrigin"),l=i(async(P,x,E)=>c&&await c.hasOrigin(E)?c.resolveRef(P,x,E):s.resolveRef(P,x,E),"resolveProfileRef"),u=i(async(P,x)=>P&&x&&c&&await c.hasOrigin(x.harnessRelease)?c.workflows(P,x):P?.source==="openpond_git"?s.workflows(P,x):e.workflows(P,x),"workflows"),p=i(async(P,x)=>{let E=P.profileRef,C=P.profileSource;return E&&C&&c&&await c.hasOrigin(C.harnessRelease)?e.prepare(P,{...x,selectedWorkflows:await c.workflows(E,C)}):E?.source!=="openpond_git"?e.prepare(P,x):e.prepare(P,{...x,selectedWorkflows:await s.workflows(E,C)})},"prepare"),m=x5({...e,authorizeRemote:A5({resolveAccess:a})}),g=Kw({store:t,storeDir:r,remote:tl({store:t,storeDir:r,resolveAccess:e.resolveAccess,identity:i(async()=>({actorId:await e.actorId(),teamId:await e.teamId()}),"identity")})}).resolveExternalDataset,w=T5({...e,prepare:p,prepareNativeModel:o,authorizeOrigin:d,resolveProfileRef:l,resolveExternalDataset:g,loadPackage:i(async P=>{let x=P.manifest.profileEvaluation;if(x.externalDatasetBinding){let A=await g(x.externalDatasetBinding,{profileRef:P.profileRef,sourceRevision:P.binding.sourceRevision,harnessRelease:P.binding.harnessRelease});return await A.authorize(),A.packageValue}let C=(await un({store:t,ref:P.profileRef,sourceRevision:x.sourceRevision,harnessRelease:x.harnessRelease})).definitions.find(A=>A.id===x.definitionId&&T(A)===x.definitionHash);if(!C)throw new Error("The exact local Profile Dataset definition is unavailable.");return Sa({store:t,storeDir:r,definition:C,profileId:x.profileId,harnessRelease:x.harnessRelease})},"loadPackage")}),h=C5({store:t,native:m.native,workflows:u,originProfiles:s.discover,authorizeOrigin:d,loadPackage:i((P,x,E)=>Sa({store:t,storeDir:r,definition:P,profileId:x,harnessRelease:E}),"loadPackage"),remoteSource:y_({resolveAccess:a})}),y=M5({resolveAccess:e.resolveAccess}),f=i(async(P,x,E)=>{let C=await a();if(C.teamId!==P)throw new Error("Local publication workspace changed.");let A={baseUrl:C.apiBaseUrl,apiKey:C.token,teamId:P};if((await new ir(A).get(x)).archived)throw new Error("The Project is archived.");return g_({store:t,storeDir:r,scope:P,actorId:C.actorId,projectId:x,release:E,loadBaseline:i(async H=>await h.packageByRelease(H)??await new nr(A).getByRelease(H),"loadBaseline")})},"publishedPackage"),S=e.localInferenceState?Fv(e.localInferenceState):void 0,k=e.localInferenceState?Lv({state:e.localInferenceState,store:t,ownerId:e.ownerId,actorId:e.actorId,teamId:e.teamId}):void 0,I=S&&k?{choices:S.choices,claudeReadiness:k.readiness,claudeControl:k.control,prepare:i(P=>P.request.policy.kind==="hosted_chat"&&P.request.policy.localRuntime?.providerId==="claude-code"?k.prepare(P):S.prepare(P),"prepare")}:void 0,b=f5({resolveAccess:e.resolveAccess,identity:i(async()=>({actorId:await e.actorId(),teamId:await e.teamId()}),"identity")}),R=Vv({resolveSelectedRewards:b,localInference:I,store:t,storeDir:r,runtimeEventsForTurn:i(P=>t.runtimeEventsForTurn(P),"runtimeEventsForTurn"),ownerId:e.ownerId,stream:ki,prepareModel:i(P=>P.request.policy.kind==="hosted_harness"&&P.request.policy.localRuntime?o(P):P.request.policy.kind==="hosted_chat"&&P.request.policy.localRuntime?I.prepare(P):Ra(P.request.policy),"prepareModel"),actorId:e.actorId,teamId:e.teamId,nativeHarness:m.native,profile:w.profile,sourceChoices:h.list,sourceDataset:h.population,environment:Gv(),authorizeProject:v_({resolveAccess:e.resolveAccess}),readHumanTaskPackage:i(async(P,x,E)=>{let C=await e.resolveAccess(),A={baseUrl:C.apiBaseUrl,apiKey:C.token,teamId:P};if((await new ir(A).get(x)).archived)throw new Error("The Project is archived.");return await f(P,x,E)??await h.packageByRelease(E)??await new nr(A).getByRelease(E)},"readHumanTaskPackage"),resolvePackage:i(async P=>await(P.configuration.request.project?.id?f(P.configuration.request.teamId,P.configuration.request.project.id,P.configuration.request.taskset):Promise.resolve(null))??await h.packageByRelease(P.configuration.request.taskset)??await y(P),"resolvePackage")}),_=R.close;return R.close=async()=>{try{await _()}finally{w.close()}},{localExperiments:R,localNativeOwner:m,localProfileOwner:w}}i(j5,"createLocalExperimentsRuntime");var I_=v.string().trim().min(1).max(240),b_=st.extend({projectId:I_.nullable(),action:v.enum(["capability","compile","prepare","start","cancel","get","list"]),id:I_.optional(),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:v.unknown().optional(),query:fP.optional(),capabilityQuery:Tn.optional()}).strict(),Tt=class extends Error{constructor(r,n){super(n);this.code=r}code;static{i(this,"HostedAlphaEditExecutionError")}status=409};function O5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let o=await e.currentIdentity();if(!o||o.teamId!==e.teamId||o.actorId!==e.actorId||new URL(o.apiOrigin).origin!==t)throw new Tt("alphaedit_account_changed","The active account changed. Recover this experiment in its original account.")}i(r,"fence");let n=Se({baseUrl:e.access.apiBaseUrl,headers:i(()=>{let o=pe(e.access.token);return o.set("x-openpond-team-id",e.teamId),o},"headers"),fetch:i(async(...o)=>{await r();let a=await fetch(...o);return await r(),a},"fetch")});return{async perform(o){let a=b_.parse(o);if(a.teamId!==e.teamId||a.actorId!==e.actorId||a.apiOrigin!==t)throw new Tt("alphaedit_account_changed","This experiment belongs to another account or hosted API.");if(await r(),a.action==="capability"){let l=Tn.parse(a.capabilityQuery);if(l.teamId!==a.teamId)throw La();let u=await n.alphaEditExecutionCapability(l);if(await r(),u.actorId!==a.actorId)throw La();return u}if(a.action==="compile"){let l=d1.parse(a.command);if(l.teamId!==a.teamId||l.projectId!==a.projectId)throw La();let u=await n.compileAlphaEditExecution(l);if(await r(),u.actorId!==a.actorId)throw La();return u}if(a.action==="list"){let l=fP.parse(a.query??{});if(a.projectId!==null&&l.projectId!==a.projectId)throw La();let u=await n.listAlphaEditExecutions(a.teamId,l,{ownerUserId:a.actorId});return await r(),u}if(a.action==="get"){let l=await n.getAlphaEditExecution(a.teamId,I_.parse(a.id));if(await r(),l.ownerUserId!==a.actorId||a.projectId!==null&&l.projectId!==a.projectId)throw La();return l}let s=a.action==="prepare"?xg.parse(a.command):a.action==="start"?_g.parse(a.command):Eg.parse(a.command);if(s.teamId!==a.teamId||"projectId"in s&&s.projectId!==a.projectId||"id"in s&&s.id!==a.id)throw La();let c=await e.assertRetained({action:a.action,projectId:a.projectId,command:s,intentHash:v.string().regex(/^[a-f0-9]{64}$/).parse(a.intentHash)});if(await r(),c&&"action"in s){let l=l1.parse(c);if(l.id!==s.id||l.teamId!==a.teamId||l.ownerUserId!==a.actorId||l.projectId!==a.projectId||l.plan.contentHash!==s.planHash||l.revision!==s.expectedRevision||s.action==="start"&&l.plan.maximumSpendUsd!==s.approvedMaximumSpendUsd)throw La()}let d="action"in s?s.action==="start"?await n.startAlphaEditExecution(s):await n.cancelAlphaEditExecution(s):await n.prepareAlphaEditExecution(s);if(await r(),d.execution.ownerUserId!==a.actorId||d.execution.projectId!==a.projectId||c&&(d.execution.sourceContentHash!==c.sourceContentHash||me(d.execution.plan)!==me(c.plan)))throw La();return d}}}i(O5,"createHostedAlphaEditExecutions");function La(){return new Tt("alphaedit_scope_mismatch","Retain the exact experiment, creator, workspace and Project before continuing.")}i(La,"scopeError");var k_=st.extend({projectId:v.string().min(1).max(240).nullable(),executionId:v.string().min(1).max(240),action:v.enum(["options","save"]),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:Wu.optional()}).strict();function H5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let c=await e.currentIdentity();if(c.teamId!==e.teamId||c.actorId!==e.actorId||new URL(c.apiOrigin).origin!==t)throw new Tt("alphaedit_save_account_changed","Recover this Model save in its original account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=i(async(...c)=>{await r();let d=await fetch(...c);return await r(),d},"fetchScoped"),a=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o}),s=Et({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o});return{async perform(c){let d=k_.parse(c);if(d.teamId!==e.teamId||d.actorId!==e.actorId||d.apiOrigin!==t)throw new Tt("alphaedit_save_account_changed","Use the result's original configured account and workspace.");if(await r(),d.action==="options"){let p=await a.getAlphaEditExecution(d.teamId,d.executionId);if(await r(),p.ownerUserId!==e.actorId||p.projectId!==d.projectId||p.method!=="alphaedit"||p.phase!=="completed"||!p.result)throw new Tt("alphaedit_save_result_unavailable","Read your completed alphaedit result before saving a Model.");let m=(await s.list()).filter(g=>{let w=g.trainingSetup.baseModel??g.defaultBaseModel;return w?.modelId===p.request.model.modelId&&w.revision===p.request.model.revision});return await r(),n$.parse({account:{teamId:e.teamId,actorId:e.actorId,apiOrigin:t},projectId:d.projectId,executionId:d.executionId,models:m})}let l=Wu.parse(d.command);if(l.teamId!==d.teamId||l.executionId!==d.executionId)throw new Tt("alphaedit_save_scope_mismatch","Retry the original result and Model save command.");await e.assertRetained(l,v.string().regex(/^[a-f0-9]{64}$/).parse(d.intentHash),d.projectId),await r();let u=await a.saveAlphaEditResultModel(l);if(await r(),u.actorId!==d.actorId||u.version.source.executionId!==d.executionId)throw new Tt("alphaedit_save_receipt_mismatch","The publication receipt differs from its original creator or Project.");return u}}}i(H5,"createHostedAlphaEditPublication");var S_=v.string().trim().min(1).max(240),P_=st.extend({projectId:S_.nullable(),action:v.enum(["capability","compile","prepare","start","cancel","get","list"]),id:S_.optional(),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:v.unknown().optional(),query:hP.optional(),capabilityQuery:Tn.optional()}).strict(),Ct=class extends Error{constructor(r,n){super(n);this.code=r}code;static{i(this,"HostedNeuronTrainingExecutionError")}status=409};function D5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let o=await e.currentIdentity();if(!o||o.teamId!==e.teamId||o.actorId!==e.actorId||new URL(o.apiOrigin).origin!==t)throw new Ct("neuron_training_account_changed","The active account changed. Recover this experiment in its original account.")}i(r,"fence");let n=Se({baseUrl:e.access.apiBaseUrl,headers:i(()=>{let o=pe(e.access.token);return o.set("x-openpond-team-id",e.teamId),o},"headers"),fetch:i(async(...o)=>{await r();let a=await fetch(...o);return await r(),a},"fetch")});return{async perform(o){let a=P_.parse(o);if(a.teamId!==e.teamId||a.actorId!==e.actorId||a.apiOrigin!==t)throw new Ct("neuron_training_account_changed","This experiment belongs to another account or hosted API.");if(await r(),a.action==="capability"){let l=Tn.parse(a.capabilityQuery);if(l.teamId!==a.teamId)throw Ba();let u=await n.neuronTrainingExecutionCapability(l);if(await r(),u.actorId!==a.actorId)throw Ba();return u}if(a.action==="compile"){let l=u1.parse(a.command);if(l.teamId!==a.teamId||l.projectId!==a.projectId)throw Ba();let u=await n.compileNeuronTrainingExecution(l);if(await r(),u.actorId!==a.actorId)throw Ba();return u}if(a.action==="list"){let l=hP.parse(a.query??{});if(a.projectId!==null&&l.projectId!==a.projectId)throw Ba();let u=await n.listNeuronTrainingExecutions(a.teamId,l,{ownerUserId:a.actorId});return await r(),u}if(a.action==="get"){let l=await n.getNeuronTrainingExecution(a.teamId,S_.parse(a.id));if(await r(),l.ownerUserId!==a.actorId||a.projectId!==null&&l.projectId!==a.projectId)throw Ba();return l}let s=a.action==="prepare"?Tg.parse(a.command):a.action==="start"?Cg.parse(a.command):Ag.parse(a.command);if(s.teamId!==a.teamId||"projectId"in s&&s.projectId!==a.projectId||"id"in s&&s.id!==a.id)throw Ba();let c=await e.assertRetained({action:a.action,projectId:a.projectId,command:s,intentHash:v.string().regex(/^[a-f0-9]{64}$/).parse(a.intentHash)});if(await r(),c&&"action"in s){let l=p1.parse(c);if(l.id!==s.id||l.teamId!==a.teamId||l.ownerUserId!==a.actorId||l.projectId!==a.projectId||l.plan.contentHash!==s.planHash||l.revision!==s.expectedRevision||s.action==="start"&&l.plan.maximumSpendUsd!==s.approvedMaximumSpendUsd)throw Ba()}let d="action"in s?s.action==="start"?await n.startNeuronTrainingExecution(s):await n.cancelNeuronTrainingExecution(s):await n.prepareNeuronTrainingExecution(s);if(await r(),d.execution.ownerUserId!==a.actorId||d.execution.projectId!==a.projectId||c&&(d.execution.sourceContentHash!==c.sourceContentHash||me(d.execution.plan)!==me(c.plan)))throw Ba();return d}}}i(D5,"createHostedNeuronTrainingExecutions");function Ba(){return new Ct("neuron_training_scope_mismatch","Retain the exact experiment, creator, workspace and Project before continuing.")}i(Ba,"scopeError");var R_=st.extend({projectId:v.string().min(1).max(240).nullable(),executionId:v.string().min(1).max(240),action:v.enum(["options","save"]),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:Vu.optional()}).strict();function L5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let c=await e.currentIdentity();if(c.teamId!==e.teamId||c.actorId!==e.actorId||new URL(c.apiOrigin).origin!==t)throw new Ct("neuron_training_save_account_changed","Recover this Model save in its original account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=i(async(...c)=>{await r();let d=await fetch(...c);return await r(),d},"fetchScoped"),a=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o}),s=Et({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o});return{async perform(c){let d=R_.parse(c);if(d.teamId!==e.teamId||d.actorId!==e.actorId||d.apiOrigin!==t)throw new Ct("neuron_training_save_account_changed","Use the result's original configured account and workspace.");if(await r(),d.action==="options"){let p=await a.getNeuronTrainingExecution(d.teamId,d.executionId);if(await r(),p.ownerUserId!==e.actorId||p.projectId!==d.projectId||p.method!=="selective_neuron_training"||p.phase!=="completed"||!p.result)throw new Ct("neuron_training_save_result_unavailable","Read your completed neuron_training result before saving a Model.");let m=(await s.list()).filter(g=>{let w=g.trainingSetup.baseModel??g.defaultBaseModel;return w?.modelId===p.request.model.modelId&&w.revision===p.request.model.revision});return await r(),o$.parse({account:{teamId:e.teamId,actorId:e.actorId,apiOrigin:t},projectId:d.projectId,executionId:d.executionId,models:m})}let l=Vu.parse(d.command);if(l.teamId!==d.teamId||l.executionId!==d.executionId)throw new Ct("neuron_training_save_scope_mismatch","Retry the original result and Model save command.");await e.assertRetained(l,v.string().regex(/^[a-f0-9]{64}$/).parse(d.intentHash),d.projectId),await r();let u=await a.saveNeuronTrainingResultModel(l);if(await r(),u.actorId!==d.actorId||u.version.source.executionId!==d.executionId)throw new Ct("neuron_training_save_receipt_mismatch","The publication receipt differs from its original creator or Project.");return u}}}i(L5,"createHostedNeuronTrainingPublication");var x_=v.string().trim().min(1).max(240),__=st.extend({projectId:x_.nullable(),action:v.enum(["capability","compile","prepare","start","cancel","get","list"]),id:x_.optional(),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:v.unknown().optional(),query:mP.optional(),capabilityQuery:Tn.optional()}).strict(),Qe=class extends Error{constructor(r,n){super(n);this.code=r}code;static{i(this,"HostedDecisionExecutionError")}status=409};function B5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let o=await e.currentIdentity();if(!o||o.teamId!==e.teamId||o.actorId!==e.actorId||new URL(o.apiOrigin).origin!==t)throw new Qe("decision_account_changed","The active account changed. Recover this experiment in its original account.")}i(r,"fence");let n=Se({baseUrl:e.access.apiBaseUrl,headers:i(()=>{let o=pe(e.access.token);return o.set("x-openpond-team-id",e.teamId),o},"headers"),fetch:i(async(...o)=>{await r();let a=await fetch(...o);return await r(),a},"fetch")});return{async perform(o){let a=__.parse(o);if(a.teamId!==e.teamId||a.actorId!==e.actorId||a.apiOrigin!==t)throw new Qe("decision_account_changed","This experiment belongs to another account or hosted API.");if(await r(),a.action==="capability"){let l=Tn.parse(a.capabilityQuery);if(l.teamId!==a.teamId)throw $a();let u=await n.decisionExecutionCapability(l);if(await r(),u.actorId!==a.actorId)throw $a();return u}if(a.action==="compile"){let l=s1.parse(a.command);if(l.teamId!==a.teamId||l.projectId!==a.projectId)throw $a();let u=await n.compileDecisionExecution(l);if(await r(),u.actorId!==a.actorId)throw $a();return u}if(a.action==="list"){let l=mP.parse(a.query??{});if(a.projectId!==null&&l.projectId!==a.projectId)throw $a();let u=await n.listDecisionExecutions(a.teamId,l,{ownerUserId:a.actorId});return await r(),u}if(a.action==="get"){let l=await n.getDecisionExecution(a.teamId,x_.parse(a.id));if(await r(),l.ownerUserId!==a.actorId||a.projectId!==null&&l.projectId!==a.projectId)throw $a();return l}let s=a.action==="prepare"?Sg.parse(a.command):a.action==="start"?Pg.parse(a.command):Rg.parse(a.command);if(s.teamId!==a.teamId||"projectId"in s&&s.projectId!==a.projectId||"id"in s&&s.id!==a.id)throw $a();let c=await e.assertRetained({action:a.action,projectId:a.projectId,command:s,intentHash:v.string().regex(/^[a-f0-9]{64}$/).parse(a.intentHash)});if(await r(),c&&"action"in s){let l=c1.parse(c);if(l.id!==s.id||l.teamId!==a.teamId||l.ownerUserId!==a.actorId||l.projectId!==a.projectId||l.plan.contentHash!==s.planHash||l.revision!==s.expectedRevision||s.action==="start"&&l.plan.maximumSpendUsd!==s.approvedMaximumSpendUsd)throw $a()}let d="action"in s?s.action==="start"?await n.startDecisionExecution(s):await n.cancelDecisionExecution(s):await n.prepareDecisionExecution(s);if(await r(),d.execution.ownerUserId!==a.actorId||d.execution.projectId!==a.projectId||c&&(d.execution.sourceContentHash!==c.sourceContentHash||me(d.execution.plan)!==me(c.plan)))throw $a();return d}}}i(B5,"createHostedDecisionExecutions");function $a(){return new Qe("decision_scope_mismatch","Retain the exact experiment, creator, workspace and Project before continuing.")}i($a,"scopeError");var E_=st.extend({projectId:v.string().trim().min(1).max(240).nullable(),modelProjectId:v.string().trim().min(1).max(240),command:S1,intentHash:v.string().regex(/^[a-f0-9]{64}$/)}).strict();function $5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let a=await e.currentIdentity();if(a.teamId!==e.teamId||a.actorId!==e.actorId||new URL(a.apiOrigin).origin!==t)throw new Qe("decision_score_account_changed","Recover this score in its original configured account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:i(async(a,s)=>{await r();let c=await fetch(a,{...s,signal:AbortSignal.any([AbortSignal.timeout(33e4),...s?.signal?[s.signal]:[]])});return await r(),c},"fetch")});return{async perform(a){let s=E_.parse(a);if(s.teamId!==e.teamId||s.actorId!==e.actorId||s.apiOrigin!==t||s.command.teamId!==s.teamId)throw new Qe("decision_score_account_changed","Score this exact Model in its original account and workspace.");await r(),await e.assertRetained({modelProjectId:s.modelProjectId,request:s.command},s.intentHash,s.projectId),await r();let c=await o.scoreDecisionModel(s.modelProjectId,s.command,{actorId:e.actorId});return await r(),c}}}i($5,"createHostedDecisionScoring");var T_=st.extend({projectId:v.string().min(1).max(240).nullable(),executionId:v.string().min(1).max(240),action:v.enum(["options","save"]),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:zu.optional()}).strict();function N5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let c=await e.currentIdentity();if(c.teamId!==e.teamId||c.actorId!==e.actorId||new URL(c.apiOrigin).origin!==t)throw new Qe("decision_save_account_changed","Recover this Model save in its original account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=i(async(...c)=>{await r();let d=await fetch(...c);return await r(),d},"fetchScoped"),a=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o}),s=Et({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o});return{async perform(c){let d=T_.parse(c);if(d.teamId!==e.teamId||d.actorId!==e.actorId||d.apiOrigin!==t)throw new Qe("decision_save_account_changed","Use the result's original configured account and workspace.");if(await r(),d.action==="options"){let p=await a.getDecisionExecution(d.teamId,d.executionId);if(await r(),p.ownerUserId!==e.actorId||p.projectId!==d.projectId||p.method!=="decision_model"||p.phase!=="completed"||p.mode!=="train"||!p.result)throw new Qe("decision_save_result_unavailable","Read your completed decision result before saving a Model.");let m=(await s.list()).filter(g=>{let w=g.trainingSetup.baseModel??g.defaultBaseModel;return w?.modelId===p.request.model.source.modelId&&w.revision===p.request.model.source.revision});return await r(),t$.parse({account:{teamId:e.teamId,actorId:e.actorId,apiOrigin:t},projectId:d.projectId,executionId:d.executionId,models:m})}let l=zu.parse(d.command);if(l.teamId!==d.teamId||l.executionId!==d.executionId)throw new Qe("decision_save_scope_mismatch","Retry the original result and Model save command.");await e.assertRetained(l,v.string().regex(/^[a-f0-9]{64}$/).parse(d.intentHash),d.projectId),await r();let u=await a.saveDecisionResultModel(l);if(await r(),u.actorId!==d.actorId||u.version.source.executionId!==d.executionId)throw new Qe("decision_save_receipt_mismatch","The publication receipt differs from its original creator or Project.");return u}}}i(N5,"createHostedDecisionPublication");var C_=v.string().trim().min(1).max(240),A_=st.extend({projectId:C_.nullable(),action:v.enum(["capability","compile","prepare","start","cancel","get","list"]),id:C_.optional(),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:v.unknown().optional(),query:pP.optional(),capabilityQuery:Tn.optional()}).strict(),At=class extends Error{constructor(r,n){super(n);this.code=r}code;static{i(this,"HostedEngramExecutionError")}status=409};function U5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let o=await e.currentIdentity();if(!o||o.teamId!==e.teamId||o.actorId!==e.actorId||new URL(o.apiOrigin).origin!==t)throw new At("engram_account_changed","The active account changed. Recover this experiment in its original account.")}i(r,"fence");let n=Se({baseUrl:e.access.apiBaseUrl,headers:i(()=>{let o=pe(e.access.token);return o.set("x-openpond-team-id",e.teamId),o},"headers"),fetch:i(async(...o)=>{await r();let a=await fetch(...o);return await r(),a},"fetch")});return{async perform(o){let a=A_.parse(o);if(a.teamId!==e.teamId||a.actorId!==e.actorId||a.apiOrigin!==t)throw new At("engram_account_changed","This experiment belongs to another account or hosted API.");if(await r(),a.action==="capability"){let l=Tn.parse(a.capabilityQuery);if(l.teamId!==a.teamId)throw Na();let u=await n.engramExecutionCapability(l);if(await r(),u.actorId!==a.actorId)throw Na();return u}if(a.action==="compile"){let l=a1.parse(a.command);if(l.teamId!==a.teamId||l.projectId!==a.projectId)throw Na();let u=await n.compileEngramExecution(l);if(await r(),u.actorId!==a.actorId)throw Na();return u}if(a.action==="list"){let l=pP.parse(a.query??{});if(a.projectId!==null&&l.projectId!==a.projectId)throw Na();let u=await n.listEngramExecutions(a.teamId,l,{ownerUserId:a.actorId});return await r(),u}if(a.action==="get"){let l=await n.getEngramExecution(a.teamId,C_.parse(a.id));if(await r(),l.ownerUserId!==a.actorId||l.projectId!==a.projectId)throw Na();return l}let s=a.action==="prepare"?Ig.parse(a.command):a.action==="start"?bg.parse(a.command):kg.parse(a.command);if(s.teamId!==a.teamId||"projectId"in s&&s.projectId!==a.projectId||"id"in s&&s.id!==a.id)throw Na();let c=await e.assertRetained({action:a.action,projectId:a.projectId,command:s,intentHash:v.string().regex(/^[a-f0-9]{64}$/).parse(a.intentHash)});if(await r(),c&&"action"in s){let l=i1.parse(c);if(l.id!==s.id||l.teamId!==a.teamId||l.ownerUserId!==a.actorId||l.projectId!==a.projectId||l.plan.contentHash!==s.planHash||l.revision!==s.expectedRevision||s.action==="start"&&l.plan.maximumSpendUsd!==s.approvedMaximumSpendUsd)throw Na()}let d="action"in s?s.action==="start"?await n.startEngramExecution(s):await n.cancelEngramExecution(s):await n.prepareEngramExecution(s);if(await r(),d.execution.ownerUserId!==a.actorId||d.execution.projectId!==a.projectId||c&&(d.execution.sourceContentHash!==c.sourceContentHash||me(d.execution.plan)!==me(c.plan)))throw Na();return d}}}i(U5,"createHostedEngramExecutions");function Na(){return new At("engram_scope_mismatch","Retain the exact experiment, creator, workspace and Project before continuing.")}i(Na,"scopeError");var M_=st.extend({projectId:v.string().min(1).max(240).nullable(),executionId:v.string().min(1).max(240),action:v.enum(["options","save"]),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:Fu.optional()}).strict();function q5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let c=await e.currentIdentity();if(c.teamId!==e.teamId||c.actorId!==e.actorId||new URL(c.apiOrigin).origin!==t)throw new At("engram_save_account_changed","Recover this Model save in its original account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=i(async(...c)=>{await r();let d=await fetch(...c);return await r(),d},"fetchScoped"),a=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o}),s=Et({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o});return{async perform(c){let d=M_.parse(c);if(d.teamId!==e.teamId||d.actorId!==e.actorId||d.apiOrigin!==t)throw new At("engram_save_account_changed","Use the result's original configured account and workspace.");if(await r(),d.action==="options"){let p=await a.getEngramExecution(d.teamId,d.executionId);if(await r(),p.ownerUserId!==e.actorId||p.projectId!==d.projectId||p.method!=="engram_adapter"||p.phase!=="completed"||!p.result)throw new At("engram_save_result_unavailable","Read your completed engram result before saving a Model.");let m=(await s.list()).filter(g=>{let w=g.trainingSetup.baseModel??g.defaultBaseModel;return w?.modelId===p.request.model.modelId&&w.revision===p.request.model.revision});return await r(),e$.parse({account:{teamId:e.teamId,actorId:e.actorId,apiOrigin:t},projectId:d.projectId,executionId:d.executionId,models:m})}let l=Fu.parse(d.command);if(l.teamId!==d.teamId||l.executionId!==d.executionId)throw new At("engram_save_scope_mismatch","Retry the original result and Model save command.");await e.assertRetained(l,v.string().regex(/^[a-f0-9]{64}$/).parse(d.intentHash),d.projectId),await r();let u=await a.saveEngramResultModel(l);if(await r(),u.actorId!==d.actorId||u.version.source.executionId!==d.executionId)throw new At("engram_save_receipt_mismatch","The publication receipt differs from its original creator or Project.");return u}}}i(q5,"createHostedEngramPublication");var j_=v.string().trim().min(1).max(240),O_=st.extend({projectId:j_.nullable(),action:v.enum(["compile","prepare","start","cancel","get","list"]),id:j_.optional(),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:v.unknown().optional(),query:uP.optional()}).strict(),Mt=class extends Error{constructor(r,n){super(n);this.code=r}code;static{i(this,"HostedModificationExecutionError")}status=409};function F5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let o=await e.currentIdentity();if(!o||o.teamId!==e.teamId||o.actorId!==e.actorId||new URL(o.apiOrigin).origin!==t)throw new Mt("modification_account_changed","The active account changed. Recover this experiment in its original account.")}i(r,"fence");let n=Se({baseUrl:e.access.apiBaseUrl,headers:i(()=>{let o=pe(e.access.token);return o.set("x-openpond-team-id",e.teamId),o},"headers"),fetch:i(async(...o)=>{await r();let a=await fetch(...o);return await r(),a},"fetch")});return{async perform(o){let a=O_.parse(o);if(a.teamId!==e.teamId||a.actorId!==e.actorId||a.apiOrigin!==t)throw new Mt("modification_account_changed","This experiment belongs to another account or hosted API.");if(await r(),a.action==="compile"){let l=n1.parse(a.command);if(l.teamId!==a.teamId||l.projectId!==a.projectId)throw cc();let u=await n.compileModificationExecution(l);if(await r(),u.actorId!==a.actorId)throw cc();return u}if(a.action==="list"){let l=uP.parse(a.query??{});if(a.projectId!==null&&l.projectId!==a.projectId)throw cc();let u=await n.listModificationExecutions(a.teamId,l,{ownerUserId:a.actorId});return await r(),u}if(a.action==="get"){let l=await n.getModificationExecution(a.teamId,j_.parse(a.id));if(await r(),l.ownerUserId!==a.actorId||l.projectId!==a.projectId)throw cc();return l}let s=a.action==="prepare"?wg.parse(a.command):a.action==="start"?yg.parse(a.command):vg.parse(a.command);if(s.teamId!==a.teamId||"projectId"in s&&s.projectId!==a.projectId||"id"in s&&s.id!==a.id)throw cc();let c=await e.assertRetained({action:a.action,projectId:a.projectId,command:s,intentHash:v.string().regex(/^[a-f0-9]{64}$/).parse(a.intentHash)});if(await r(),c&&"action"in s){let l=o1.parse(c);if(l.id!==s.id||l.teamId!==a.teamId||l.ownerUserId!==a.actorId||l.projectId!==a.projectId||l.plan.contentHash!==s.planHash||l.revision!==s.expectedRevision||s.action==="start"&&l.plan.maximumSpendUsd!==s.approvedMaximumSpendUsd)throw cc()}let d="action"in s?s.action==="start"?await n.startModificationExecution(s):await n.cancelModificationExecution(s):await n.prepareModificationExecution(s);if(await r(),d.execution.ownerUserId!==a.actorId||d.execution.projectId!==a.projectId||c&&(d.execution.sourceContentHash!==c.sourceContentHash||me(d.execution.plan)!==me(c.plan)))throw cc();return d}}}i(F5,"createHostedModificationExecutions");function cc(){return new Mt("modification_scope_mismatch","Retain the exact experiment, creator, workspace and Project before continuing.")}i(cc,"scopeError");var H_=st.extend({projectId:v.string().min(1).max(240).nullable(),executionId:v.string().min(1).max(240),action:v.enum(["options","save"]),intentHash:v.string().regex(/^[a-f0-9]{64}$/).optional(),command:Gu.optional()}).strict();function z5(e){let t=new URL(e.access.apiBaseUrl).origin;async function r(){let c=await e.currentIdentity();if(c.teamId!==e.teamId||c.actorId!==e.actorId||new URL(c.apiOrigin).origin!==t)throw new Mt("steering_save_account_changed","Recover this Model save in its original account.")}i(r,"fence");let n=pe(e.access.token);n.set("x-openpond-team-id",e.teamId);let o=i(async(...c)=>{await r();let d=await fetch(...c);return await r(),d},"fetchScoped"),a=Se({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o}),s=Et({baseUrl:e.access.apiBaseUrl,headers:n,fetch:o});return{async perform(c){let d=H_.parse(c);if(d.teamId!==e.teamId||d.actorId!==e.actorId||d.apiOrigin!==t)throw new Mt("steering_save_account_changed","Use the result's original configured account and workspace.");if(await r(),d.action==="options"){let p=await a.getModificationExecution(d.teamId,d.executionId);if(await r(),p.ownerUserId!==e.actorId||p.projectId!==d.projectId||p.method!=="neuron_steering"||p.phase!=="completed"||!p.result)throw new Mt("steering_save_result_unavailable","Read your completed steering result before saving a Model.");let m=(await s.list()).filter(g=>{let w=g.trainingSetup.baseModel??g.defaultBaseModel;return w?.modelId===p.request.model.modelId&&w.revision===p.request.model.revision});return await r(),ZB.parse({account:{teamId:e.teamId,actorId:e.actorId,apiOrigin:t},projectId:d.projectId,executionId:d.executionId,models:m})}let l=Gu.parse(d.command);if(l.teamId!==d.teamId||l.executionId!==d.executionId)throw new Mt("steering_save_scope_mismatch","Retry the original result and Model save command.");await e.assertRetained(l,v.string().regex(/^[a-f0-9]{64}$/).parse(d.intentHash),d.projectId),await r();let u=await a.saveModificationResultModel(l);if(await r(),u.actorId!==d.actorId||u.record.publication.projectId!==d.projectId)throw new Mt("steering_save_receipt_mismatch","The publication receipt differs from its original creator or Project.");return u}}}i(z5,"createHostedSteeringPublication");function dc(e){throw new He(e,409)}i(dc,"fail");async function Kv(e,t){let r=Ch.parse(t),n=await e.actorId();r.scope!==await e.teamId()&&dc("human_local_scope_changed");let o,a,s,c=[];for(let l of r.selections){await e.store.localExperimentTrace({teamId:r.scope,id:l.executionId,caseId:l.receiptId,limit:1});let u=await e.store.humanReviewLocalEvidence(r.scope,l.executionId),p=u.released.definition;(u.execution.ownerActorId!==n||p.ownerActorId!==n||u.execution.kind!=="target"||!u.execution.completedAt||!u.execution.cleanupComplete||p.configuration.request.project?.id!==r.projectId)&&dc("human_local_publication_source_denied");let m=u.cases.find(b=>b.receiptId===l.receiptId);m?.result||dc("human_local_publication_receipt_missing");let g=mt(u.released.package),w=g.taskset.tasks.find(b=>b.id===m.admission.taskId),h=g.taskset.graders.find(b=>b.id===r.graderId);(!w||h?.kind!=="human"||!h.form)&&dc("human_local_publication_grader_required");let y={id:g.taskset.id,revision:g.taskset.revision,contentHash:g.taskset.contentHash};(o&&T(o)!==T(y)||a&&a!==T(h))&&dc("human_local_publication_pair_conflict"),o=y,a=T(h),s=u.execution.completedAt;let f=Lt(m.result).attempt,S;if(f.externalProcess){let b=await ym({store:e.store,teamId:r.scope,executionId:l.executionId,caseId:l.receiptId});T(b)!==f.externalProcess.traceHash&&dc("human_local_publication_trace_changed"),S=b.filter(R=>["external.stream","external.human_intervention","external.control_receipt"].includes(R.type)).map(R=>{let _=R.payload;if(R.type==="external.stream"){let P=_.event;return{sequence:R.sequence,type:R.type,...Object.fromEntries(["type","message","result","usage","is_error"].filter(x=>P[x]!==void 0).map(x=>[x,x==="message"?Object.fromEntries(["role","content"].filter(E=>P.message[E]!==void 0).map(E=>[E,P.message[E]])):P[x]]))}}return{sequence:R.sequence,type:R.type,...Object.fromEntries(["action","text","occurredAt","state"].filter(P=>_[P]!==void 0).map(P=>[P,_[P]]))}})}else S=f.messages.map((b,R)=>{let _=b;return{sequence:R,...Object.fromEntries(["role","content","kind","name","input","output"].filter(P=>_[P]!==void 0).map(P=>[P,_[P]]))}});let k=[],I=0;for(let b of S){let R=Buffer.byteLength(JSON.stringify(b));if(k.length>=1e3||I+R>35e4)break;k.push(b),I+=R}c.push({origin:{kind:"owner_attested_local",ownerActorId:n,teamId:r.scope,executionHash:u.execution.executionHash,configurationHash:T(p.configuration),retainedAttemptHash:f.contentHash,traceHash:f.externalProcess?.traceHash??f.native?.traceHash??f.profileNative?.traceHash??f.contentHash,publicationCutoffHash:T(k)},executionId:u.execution.id,receiptId:m.receiptId,taskId:w.id,targetId:p.model.modelId,familyKey:w.clusterKey,split:w.split,input:w.input,policyVisibleContext:w.policyVisibleContext,output:f.output,error:f.error,events:k,coverage:{sourceEventCount:S.length,publishedEventCount:k.length,traceLimited:S.length>k.length,artifactsIncluded:!1}})}(await e.actorId()!==n||await e.teamId()!==r.scope)&&dc("human_local_scope_changed");let d=KM.parse(QM({schemaVersion:"openpond.humanLocalEvidenceExport.v1",actorId:n,scope:r.scope,projectId:r.projectId,dataset:o,graderId:r.graderId,compiledGraderHash:a,attempts:c,sealedAt:s}));return pi(d,9e5),d}i(Kv,"exportLocalHumanEvidence");async function W5(e,t,r){let n=Ah.parse(t),o=await e.actorId(),a=await e.teamId();async function s(){if(await e.actorId()!==o||await e.teamId()!==a||n.scope!==a)throw new He("human_scope_changed",403)}i(s,"current"),await s();let c=v.object({scope:v.string(),actorId:v.string(),projectId:v.string()}).strict().parse(await e.hosted.request({endpoint:"publication_access",scope:a,projectId:n.projectId},r));if(c.actorId!==o||c.scope!==a||c.projectId!==n.projectId)throw new He("human_publication_project_denied",403);await s();let d=await Kv(e,{endpoint:"export_local",scope:n.scope,projectId:n.projectId,graderId:n.graderId,selections:n.selections});await s();let l=v.object({evidence:_s,form:xs}).strict().parse(await e.hosted.request({endpoint:"publish_local",scope:a,projectId:n.projectId,operationId:n.operationId,audience:n.audience,workspaceVisible:n.workspaceVisible,evidence:d},r));await s();let u=TS.parse(l.evidence.publication);if(l.evidence.attempts.some((p,m)=>p.experimentId!==d.attempts[m]?.executionId||p.attemptId!==d.attempts[m]?.receiptId)||l.evidence.attempts.length!==d.attempts.length)throw new He("human_publication_identity_changed",409);for(let p of d.attempts)await e.store.rememberHumanLocalPublication({scope:a,actorId:o,executionId:p.executionId,executionHash:p.origin.executionHash,operationId:n.operationId,publication:u});return await s(),l}i(W5,"shareLocalHumanEvidence");async function V5(e,t){let r=Mh.parse(t),n=await e.actorId();if(r.scope!==await e.teamId())throw new He("human_scope_changed",403);let o=v.array(TS).max(1e3).parse(await e.store.humanLocalPublications({scope:r.scope,actorId:n,executionId:r.executionId}));if(n!==await e.actorId()||r.scope!==await e.teamId())throw new He("human_scope_changed",403);return o}i(V5,"readLocalHumanPublicationRefs");async function G5(e,t,r){let n=jh.parse(t),o=await e.actorId();if(n.scope!==await e.teamId())throw new He("human_scope_changed",403);let a=v.object({revoked:v.literal(!0)}).strict().parse(await e.hosted.request({endpoint:"revoke_publication",scope:n.scope,publication:n.publication},r));if(await e.actorId()!==o||await e.teamId()!==n.scope)throw new He("human_scope_changed",403);return await e.store.forgetHumanLocalPublication({scope:n.scope,actorId:o,publicationId:n.publication.id}),a}i(G5,"revokeLocalHumanPublication");function J5(e){async function t(){let o=await e.currentIdentity();if(o?.teamId!==e.teamId||o.actorId!==e.actorId)throw new Error("The active account changed. Reopen candidate evaluation setup.")}i(t,"fence");let r=UP(async(o,a)=>{await t();let s=pe(e.access.token);s.set("x-openpond-team-id",e.teamId),s.set("content-type","application/json");let c=await fetch(`${e.access.apiBaseUrl.replace(/\/+$/,"")}${o}`,{...a,headers:s,redirect:"error",signal:AbortSignal.timeout(3e4)}),d=c.body?.getReader();if(!d)throw new Error("Candidate evaluation returned no retained receipt.");let l=[],u=0;try{for(;;){let m=await d.read();if(m.done)break;if(u+=m.value.byteLength,u>8388608)throw new Error("Candidate response exceeded its bound.");l.push(m.value)}}finally{await d.cancel(),d.releaseLock()}await t();let p=JSON.parse(Buffer.concat(l).toString("utf8"));if(!c.ok)throw new Error(typeof p.message=="string"?p.message:`Candidate evaluation failed (${c.status}).`);return p});async function n(o){let a=await o;if(a.ownerUserId!==e.actorId)throw new Error("The candidate owner changed.");return a}return i(n,"owner"),{options:i(o=>n(r.options(e.teamId,o)),"options"),save:i(o=>{if(o.teamId!==e.teamId)throw new Error("The candidate workspace changed.");return n(r.save(o))},"save"),read:i(o=>n(r.get(e.teamId,o)),"read"),control:i((o,a,s)=>n(r.control(e.teamId,o,a,s)),"control")}}i(J5,"createHostedCandidateEvaluations");function K5(e){async function t(){let r=await e.currentIdentity();if(r?.teamId!==e.teamId||r.actorId!==e.actorId)throw new Error("The active account changed. Reopen the Experiment result.")}return i(t,"fence"),{async read(r,n=null){await t();let o=new URLSearchParams({teamId:e.teamId,executionId:r});n&&o.set("passId",n);let a=pe(e.access.token);a.set("x-openpond-team-id",e.teamId);let s=await fetch(`${e.access.apiBaseUrl.replace(/\/+$/,"")}/v1/training/experiment-handoff?${o}`,{headers:a,redirect:"error",signal:AbortSignal.timeout(2e4)});if(!s.ok)throw new Error(`Experiment training handoff is unavailable (${s.status}).`);let c=s.body?.getReader();if(!c)throw new Error("The handoff returned no retained evidence.");let d=[],l=0;try{for(;;){let p=await c.read();if(p.done)break;if(l+=p.value.byteLength,l>262144)throw new Error("Experiment handoff exceeded its response limit.");d.push(p.value)}}finally{await c.cancel(),c.releaseLock()}await t();let u=XS.parse(JSON.parse(Buffer.concat(d).toString("utf8")));if(u.origin){let{contentHash:p,...m}=u.origin;if(p!==await Xe(m)||m.teamId!==e.teamId||m.source.executionId!==r||m.source.passId!==n)throw new Error("The handoff does not match the exact selected result.")}return u}}}i(K5,"createHostedExperimentTrainingHandoff");var Yv=v.string().min(1).max(200),Y5=v.string().trim().min(1).max(240);function D_(e){async function t(){let m=await e.currentIdentity();if(m?.teamId!==e.teamId||m.actorId!==e.actorId)throw new Error("The active account changed. Reopen training setup.")}i(t,"fence");let r=i(()=>{let m=pe(e.access.token);return m.set("x-openpond-team-id",e.teamId),m},"headers"),n=i(async(...m)=>{await t();let g=await fetch(...m);return await t(),g},"scopedFetch"),o=Et({baseUrl:e.access.apiBaseUrl,headers:r,fetch:n}),a=Se({baseUrl:e.access.apiBaseUrl,headers:r,fetch:n}),s=new bi({baseUrl:e.access.apiBaseUrl,apiKey:e.access.token,scope:e.teamId,fetch:n}),c=new ir({baseUrl:e.access.apiBaseUrl,apiKey:e.access.token,teamId:e.teamId,fetch:n}),d=new Jr({baseUrl:e.access.apiBaseUrl,apiKey:e.access.token,teamId:e.teamId,fetch:n});async function l(m){let g=[],w,h=new Set;for(let y=0;;y++){if(y>=100)throw new Error("The complete learning catalog exceeds the supported setup bound.");let f=await s.list(m,{limit:100,...w?{afterId:w}:{}});if(g.push(...f.items),!f.nextCursor)return g;if(h.has(f.nextCursor))throw new Error("Learning pagination did not advance.");h.add(f.nextCursor),w=f.nextCursor}}i(l,"all");async function u(m,g){await t();let w=r();w.set("content-type","application/json");let h=await n(`${e.access.apiBaseUrl.replace(/\/+$/,"")}${m}`,{method:"POST",headers:w,body:JSON.stringify(g),redirect:"error",signal:AbortSignal.timeout(3e4)}),y=h.body?.getReader();if(!y)throw new Error("Training setup returned no receipt.");let f=[],S=0;try{for(;;){let I=await y.read();if(I.done)break;if(S+=I.value.byteLength,S>8388608)throw new Error("The setup response exceeded its bound.");f.push(I.value)}}finally{await y.cancel(),y.releaseLock()}await t();let k=JSON.parse(Buffer.concat(f).toString("utf8"));if(!h.ok)throw new Error(typeof k.message=="string"?k.message:`Training setup failed (${h.status}).`);return k}i(u,"publicRequest");async function p(m){let g=(await o.list()).find(w=>w.portableProjectId===m);if(!g)throw new Error("The current account cannot read this policy\u2019s exact hosted training configuration.");return g}return i(p,"policyConfiguration"),{async draftInputs(m){if(await t(),m.projectId&&(await c.get(m.projectId)).archived)throw new Error("Restore this Project before starting an experiment.");let[g,w,h]=await Promise.all([o.configurationCandidates(),a.capabilities(),s.list("batch",{limit:100,...m.cursor?{afterId:m.cursor}:{}})]);return await t(),e1.parse({schemaVersion:"openpond.trainingExperimentInputsPage.v1",teamId:e.teamId,actorId:e.actorId,projectId:m.projectId,models:g,methods:w.methods,billingModes:w.billingModes,batches:h.items.map(y=>({reference:Ve(y),rewardBinding:y.rewardBinding,purpose:y.purpose,exampleCount:y.examples.length,sealedAt:y.sealedAt})),nextCursor:h.nextCursor})},async policyRead(m,g){await t();let w=await s.get("policy",Yv.parse(m)),h=await p(w.modelProjectId);if(w.executionOwner!=="hosted"||h.portableProjectId!==w.modelProjectId)throw new Error("The policy has no exact hosted training configuration.");let[y,f]=await Promise.all([s.inspectPolicy(Ve(w)),s.list("iteration",{parentId:w.id,limit:100,afterId:g})]),S=await Promise.all(f.items.map(async k=>{if(k.policy.id!==w.id)throw new Error("Iteration belongs to another learning policy.");return{iteration:k,evals:k.trainingJob?await a.postTraining.get(e.teamId,k.trainingJob.id):null}}));return await t(),oP.parse({teamId:e.teamId,actorId:e.actorId,configuration:h,policy:w,inspection:y,iterations:S,nextCursor:f.nextCursor})},async policyControl(m){await t();let g=aP.parse(m),w=await s.get("policy",g.id,g.expectedRevision);if(w.contentHash!==g.policyHash||w.executionOwner!=="hosted")throw new Error("The exact reviewed policy changed.");if((await p(w.modelProjectId)).portableProjectId!==w.modelProjectId)throw new Error("The exact policy configuration changed.");if(g.action==="pause"||g.action==="resume"){let{contentHash:f,...S}=w;return s.command({action:"publish",operationId:g.operationId,kind:"policy",expectedRevision:g.expectedRevision,content:{...S,revision:w.revision+1,enabled:g.action==="resume"}})}if(g.action==="reserve")return s.command({action:"reserve_iteration",operationId:g.operationId,policy:Ve(w),trigger:{kind:"manual",identity:g.operationId}});if(!g.iterationId||!g.iterationRevision)throw new Error("Choose the exact current iteration before controlling it.");let y=await s.get("iteration",g.iterationId,g.iterationRevision);if(y.policy.id!==w.id)throw new Error("The iteration belongs to another policy.");return s.command({action:g.action==="cancel-iteration"?"cancel_iteration":"retry_iteration_dispatch",operationId:g.operationId,iterationId:y.id,expectedRevision:y.revision})},async catalog(m){await t();let g=(await o.get(Yv.parse(m.configurationId))).project;if(m.projectId){let b=await c.get(m.projectId);if(b.archived||!b.content.resources.some(R=>R.kind==="training_configuration"&&R.resourceId===g.id))throw new Error("Link this exact training configuration to the current Project before setup.")}let[w,h,y]=await Promise.all([l("batch"),l("source"),l("definition")]),f=[],S,k=new Set;for(let b=0;;b++){if(b>=100)throw new Error("The complete evaluation catalog exceeds the supported setup bound.");let R=await d.list({projectId:m.projectId??void 0,limit:100,afterId:S});for(let _ of R.items)_.request.policy.kind!=="fixture"&&f.push({id:_.summary.id,name:_.request.name??_.summary.id,configuration:ya.parse({request:_.request,maximumCostUsd:_.configuration.maximumCostUsd,graders:_.configuration.graders.map(P=>({id:P.id,version:P.version,contentHash:P.contentHash,mappings:P.mappings??[]})),operationId:_.request.operationId}),graders:_.configuration.graders.map(P=>({feedbackKey:P.feedbackKey,name:P.feedbackKey,ref:{id:P.release?.id??P.id,contentHash:P.release?.contentHash??P.contentHash}}))});if(!R.nextCursor)break;if(k.has(R.nextCursor))throw new Error("Evaluation pagination did not advance.");k.add(R.nextCursor),S=R.nextCursor}let I=g.trainingSetup.rewardBindingRef;return await t(),rP.parse({teamId:e.teamId,actorId:e.actorId,projectId:m.projectId,configuration:g,batches:w.filter(b=>b.purpose==="reward_training"&&I&&_t(b.rewardBinding,I)),sources:h.filter(b=>y.some(R=>_t(Ve(R),b.taskDefinition)&&I&&_t(R.rewardBinding,I))),definitions:y,experiments:f})},async perform(m,g){if(await t(),m==="review-dataset"){let y=bH.parse(g);if(y.teamId!==e.teamId)throw new Error("The Dataset review workspace changed.");let f=await a.reviewDataset(y);return await t(),O1(f,y,e.actorId)}if(m==="funding"||m==="funding-handoff"){let y=m==="funding"?gP.parse(g):wP.parse(g);if(y.teamId!==e.teamId)throw new Error("The funding workspace changed.");let f=m==="funding"?await a.funding(gP.parse(y)):await a.fundingHandoff(wP.parse(y));if(await t(),f.actorId!==e.actorId)throw new Error("Funding returned another account.");return f}if(m==="estimate"){let{TrainingEstimateRequestSchema:y}=await import("./training-JA5ZQABE.js"),f=y.parse(g);if(f.teamId!==e.teamId)throw new Error("Choose this workspace's estimate inputs.");return a.estimate(f)}if(m==="hardware-catalog"){let y=await a.hardwareCatalog();return await t(),y}if(m==="gpu-catalog"){let{TrainingGpuCatalogQuerySchema:y}=await import("./training-JA5ZQABE.js"),f=y.parse(g);if(f.teamId!==e.teamId)throw new Error("The compute workspace changed.");let S=await a.gpuCatalog(f);return await t(),S}if(m==="modification-capabilities"){let{ModelModificationCapabilitiesQuerySchema:y,parseAndVerifyModelModificationCapabilities:f}=await import("./training-JA5ZQABE.js"),S=y.parse(g);if(S.teamId!==e.teamId)throw new Error("The model capability workspace changed.");let k=await a.modificationCapabilities(S);return await t(),f(k,S,e.actorId)}if(m==="list-drafts"){let y=await a.listExperimentDrafts(e.teamId,r1.parse(g??{}));if(await t(),y.ownerUserId!==e.actorId)throw new Error("Draft history returned another owner.");return y}if(m==="get-draft"){let y=v.object({id:Y5}).strict().parse(g),f=await a.getExperimentDraft(e.teamId,y.id);if(await t(),f.ownerUserId!==e.actorId)throw new Error("This draft belongs to another owner.");return f}if(m==="save-draft"||m==="archive-draft"){let y=m==="save-draft"?vd.parse(g):v.object({id:Y5,control:t1}).strict().parse(g);if(("control"in y?y.control.teamId:y.teamId)!==e.teamId)throw new Error("The draft workspace changed.");let S="control"in y?await a.archiveExperimentDraft(y.id,y.control):await a.saveExperimentDraft(y);if(await t(),S.record.ownerUserId!==e.actorId)throw new Error("The saved draft belongs to another owner.");return S}if(m==="save-experiment-learning"){let y=j1.parse(g);if(y.teamId!==e.teamId)throw new Error("Training workspace changed.");return a.saveExperimentLearning(y)}if(m==="prepare-draft"){let y=gg.parse(g);if(y.teamId!==e.teamId)throw new Error("Training workspace changed.");return a.prepareExperiment(y)}if(m==="prepare"){let y=KH.parse(g);if(y.teamId!==e.teamId)throw new Error("Training workspace changed.");return a.prepareRun(y)}if(m==="start"||m==="cancel"){let y=v.object({id:Yv,control:YH}).strict().parse(g);if(y.control.teamId!==e.teamId)throw new Error("Training workspace changed.");return m==="start"?a.startPreparation(y.id,y.control):a.cancelPreparation(y.id,y.control)}if(m==="attach"){let y=eP.parse(g);return a.postTraining.attach(e.teamId,y)}let w=v.object({operationId:Yv,command:v.unknown(),attachment:QS.nullable()}).strict().parse(g),h=wa.parse({scope:e.teamId,command:w.command}).command;if(h.action!=="publish"||h.kind!=="policy")throw new Error("Publish one exact hosted learning policy.");if(w.attachment){let y=await u("/v1/training/post-training-policies",{operationId:w.operationId,command:h,attachment:w.attachment}),f=wj.parse(y.policy),S=tP(y.plan);if(yj(f),f.id!==h.content.id||f.revision!==h.content.revision||S.attachment.binding.contentHash!==f.contentHash||S.ownerUserId!==e.actorId)throw new Error("Publication returned a different policy, plan or owner.");return{policy:f,plan:S}}return s.command(h)}}}i(D_,"createHostedTrainingSetup");var Mue=v.object({kind:v.enum(["training","experiment"]),id:v.string().min(1),name:v.string(),phase:v.string(),href:v.string(),updatedAt:v.iso.datetime()}).strict(),jue=v.object({scope:v.object({teamId:v.string().min(1),projectId:v.string().nullable()}).strict(),generatedAt:v.iso.datetime(),counts:v.object({training:v.number().int().nonnegative(),experiments:v.number().int().nonnegative()}).strict(),items:v.array(Mue).max(300),hasMore:v.boolean()}).strict();function Oue(e,t,r){return JSON.stringify([e,t,r])}i(Oue,"executionActivityScopeKey");function X5(e){return i(async function(r){let n=v.object({teamId:v.string().min(1),projectId:v.string().nullable()}).strict().parse(r),o=await e.actorId();if(!o.trim()||await e.teamId()!==n.teamId)throw new Error("Activity workspace is unavailable to this account.");n.projectId&&await e.authorizeProject(n.teamId,o,n.projectId);let[a,s,c]=await Promise.all([e.store.readExecutionActivity({...n,actorId:o}),e.store.readTrainingExecutionActivity({...n,actorId:o}),e.hosted(n.teamId,n.projectId)]),d=jue.parse(c);if(d.scope.teamId!==n.teamId||d.scope.projectId!==n.projectId)throw new Error("Activity response belongs to another scope.");if(await e.actorId()!==o||await e.teamId()!==n.teamId)throw new Error("Activity account changed during refresh.");let l=[...a.items,...s.items,...d.items.map(u=>({...u,location:"hosted"}))].sort((u,p)=>p.updatedAt.localeCompare(u.updatedAt));if(new Set(l.map(u=>JSON.stringify([u.kind,u.location,u.id]))).size!==l.length)throw new Error("Activity response contains duplicate executions.");return{scopeKey:Oue(n.teamId,o,n.projectId),generatedAt:d.generatedAt,counts:{training:d.counts.training+s.count,experiments:d.counts.experiments+a.count},items:l.slice(0,100),hasMore:d.hasMore||l.length>100||a.count>a.items.length||s.count>s.items.length}},"read")}i(X5,"createExecutionActivityService");async function Q5(e,t,r){let n=new URLSearchParams(r?{projectId:r}:{}),o=pe(e.token);o.set("x-openpond-team-id",t);let a=await fetch(`${e.apiBaseUrl.replace(/\/+$/,"")}/v1/training/activity?${n}`,{headers:o,redirect:"error",signal:AbortSignal.timeout(2e4)});if(!a.ok)throw new Error(`Execution activity is unavailable (${a.status}).`);let s=a.body?.getReader();if(!s)throw new Error("Execution activity returned no body.");let c=[],d=0;try{for(;;){let l=await s.read();if(l.done)break;if(d+=l.value.byteLength,d>524288)throw new Error("Execution activity exceeded its bounded response.");c.push(l.value)}}finally{await s.cancel(),s.releaseLock()}return JSON.parse(Buffer.concat(c).toString("utf8"))}i(Q5,"readHostedExecutionActivity");var lc=class extends Error{constructor(r,n,o=r){super(o);this.code=r;this.status=n;this.name="HumanReviewBridgeError"}code;status;static{i(this,"HumanReviewBridgeError")}};function Z5(e){return{async request(t,r){pi(t,1048576);let n=v.object({scope:v.string().trim().min(1).max(191)}).passthrough().parse(t),o=await e.resolveAccess();if(n.scope!==o.teamId)throw new He("human_scope_changed",403,"The active workspace changed. Refresh before continuing.");let a=pe(o.token);a.set("x-openpond-team-id",o.teamId),a.set("content-type","application/json");let s=await fetch(`${o.apiBaseUrl.replace(/\/+$/,"")}/v1/human-review`,{method:"POST",redirect:"error",headers:a,body:JSON.stringify(n),signal:r?AbortSignal.any([r,AbortSignal.timeout(3e4)]):AbortSignal.timeout(3e4)}),c=s.body?.getReader();if(!c)throw new lc("human_response_unavailable",502);let d=[],l=0;try{for(;;){let m=await c.read();if(m.done)break;if(l+=m.value.byteLength,l>2097152)throw new lc("human_response_too_large",502);d.push(m.value)}}finally{await c.cancel(),c.releaseLock()}let u=JSON.parse(Buffer.concat(d).toString("utf8"));if(!s.ok){let m=v.object({code:v.string().optional(),error:v.string().optional()}).passthrough().safeParse(u);throw new lc(m.success?m.data.code??"human_request_failed":"human_request_failed",s.status,m.success?m.data.error:void 0)}let p=await e.resolveAccess();if(p.teamId!==o.teamId||p.token!==o.token||new URL(p.apiBaseUrl).origin!==new URL(o.apiBaseUrl).origin)throw new He("human_scope_changed",403,"The active account or workspace changed. Refresh before continuing.");return u}}}i(Z5,"createHostedHumanReviewBridge");var uo=i((e,t)=>({label:e.slice(0,200),value:String(t).slice(0,12e3),severity:"info"}),"fact");function Xv(e){return[...["schemaVersion","trainingStepId","inputPolicyVersion","outputPolicyVersion","localPolicyTransitionSha256","contentHash","normalization","advantageEpsilon"].flatMap(t=>["string","number"].includes(typeof e[t])?[uo(t,e[t])]:[]),...Array.isArray(e.scores)?e.scores.slice(0,128).flatMap(t=>!t||typeof t!="object"||!("rolloutId"in t)||typeof t.rolloutId!="string"?[]:[uo(`Source rollout ${t.rolloutId}`,"reward"in t&&typeof t.reward=="number"?`Reward ${t.reward}`:"Reward not retained")]):[]].slice(0,95)}i(Xv,"optimizerReceiptFacts");function eG(e){let t=e.job.inputBundle?.recovery;if(!t?.groups)return[];let r=new Set(e.rolloutGroups.map(n=>n.groupIndex));return t.groups.filter(n=>n.groupIndex<t.completedGroups&&!r.has(n.groupIndex)).map(n=>{let o=n.optimizerDisposition==="applied",a=typeof n.optimizerEvidence.outputPolicyVersion=="number"?n.optimizerEvidence.outputPolicyVersion:void 0,s=o&&a!==void 0?`v${n.policyVersion} \u2192 v${a}`:`Policy v${n.policyVersion} unchanged`,c=[uo("Evidence origin","Inherited from checkpoint recovery; not re-executed in this run"),uo("Source run",n.sourceJobId),uo("Source group",n.id),uo("Recovery checkpoint",t.checkpointId),uo("Retained state",n.state),uo("Optimizer outcome",o?"Update applied":"Skipped \xB7 no signal"),...Xv(n.optimizerEvidence)].slice(0,100),d=[...["Rollouts","Grade"].map(l=>({label:l,state:"done",status:"Inherited",detail:"Consumed in source run",inLoop:!0,diagnostics:c})),{label:"Update adapter",state:o?"done":"missing",status:o?"Inherited update":"Skipped \xB7 no signal",detail:s,inLoop:!0,diagnostics:c},...["Save checkpoint","Activate policy"].map(l=>({label:l,state:"missing",status:"Source evidence",detail:"Inspect the source run",inLoop:!0,diagnostics:c}))];return{index:n.groupIndex,state:n.state,optimizerDisposition:n.optimizerDisposition,inherited:{sourceJobId:n.sourceJobId,checkpointId:t.checkpointId,checkpointJobId:t.checkpointJobId??t.sourceJobId,optimizerDisposition:n.optimizerDisposition,inputPolicyVersion:n.policyVersion,...a!==void 0?{outputPolicyVersion:a}:{}},meanReward:null,plannedSlots:0,attempts:[],diagnostics:c,nodes:d}})}i(eG,"inheritedRecoveryGroups");function L_(e){let t=e.job.inputBundle?.recovery;return t?.undurableProgress?.groups.map(r=>({sourceJobId:r.sourceJobId,checkpointId:t.checkpointId,checkpointJobId:t.checkpointJobId??t.sourceJobId,groupId:r.id,groupIndex:r.groupIndex,optimizerDisposition:r.optimizerDisposition,inputPolicyVersion:r.policyVersion,...typeof r.optimizerEvidence.outputPolicyVersion=="number"?{outputPolicyVersion:r.optimizerEvidence.outputPolicyVersion}:{}}))??[]}i(L_,"recoveryReplayOrigins");function tG(e){let t=new Set(e.rolloutGroups.map(r=>r.groupIndex));return L_(e).filter(r=>!t.has(r.groupIndex)).map(r=>{let n=e.job.inputBundle.recovery.undurableProgress.groups.find(a=>a.id===r.groupId),o=[uo("Replay boundary","Prior output was not checkpoint durable and was not restored. Replay is required."),uo("Prior attempt source run",r.sourceJobId),uo("Prior source group",r.groupId),...Xv(n.optimizerEvidence)];return{index:r.groupIndex,state:"replay_pending",replay:r,meanReward:null,plannedSlots:0,attempts:[],diagnostics:o,nodes:["Rollouts","Grade","Update adapter","Save checkpoint","Activate policy"].map(a=>({label:a,inLoop:!0,state:e.job.state==="failed"?"missing":"pending",status:"Replay pending",detail:"Prior output not restored",diagnostics:o}))}})}i(tG,"pendingReplayGroups");var Hue={Prepare:["start_inference"],"Load parent adapter":["materialize_checkpoint"],"Update adapter":["train_step"],"Save checkpoint":["upload_checkpoint","qualify_checkpoint"],"Activate policy":["start_inference"],Grade:["score_reward_model"],Finish:["stop"]},po=i(e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},"record"),rG=new WeakMap;function Due(e){let t=new Map;for(let r of e.rollouts){let n=t.get(r.groupId)??[];n.push(r),t.set(r.groupId,n)}return{attemptsByGroup:t,rollout:new Map(e.rollouts.map(r=>[r.id,r])),trajectory:new Map(e.trajectories.map(r=>[r.rolloutId,r]))}}i(Due,"buildIndex");function oG(e){let t=rG.get(e)??Due(e);return rG.set(e,t),t}i(oG,"index");var nG=i(e=>(typeof e=="number"||typeof e=="string"&&e.trim())&&Number.isFinite(Number(e))?Number(e):null,"metricNumber");function je(e,t,r="info"){let n=typeof t=="string"?t:JSON.stringify(t)??"Not retained";return{label:e,value:n.length>4e3?`${n.slice(0,3960)}\u2026 (retained excerpt)`:n,severity:r}}i(je,"fact");function Lue(e){let t=[],r=0,n=i((o,a,s="")=>{if(a>8||++r>2e3||t.length>=80)return;if(typeof o=="string"&&s==="feedback"&&o.length<512e3){try{n(JSON.parse(o),a+1)}catch{}return}if(Array.isArray(o)){for(let l of o.slice(0,100))n(l,a+1);return}let c=po(o),d=po(c.diagnostics);if(Array.isArray(d.differences))for(let l of d.differences.slice(0,80-t.length)){let u=po(l);typeof u.kind!="string"||typeof u.path!="string"||t.push(je(`${u.kind.replaceAll("_"," ")} \xB7 ${u.path}`,`Expected: ${JSON.stringify(u.expected)??"Not retained"}
|
|
61
61
|
Actual: ${JSON.stringify(u.actual)??"Not retained"}`,"warning"))}for(let[l,u]of Object.entries(c))l!=="diagnostics"&&n(u,a+1,l)},"visit");return n(e,0),t}i(Lue,"graderDifferences");function aG(e,t){let r=oG(e),n=r.rollout.get(t),o=r.trajectory.get(t);if(!n)return[];let a=[je("Attempt execution",n.state),je("Rollout ID",n.id)];if(n.policyVersion!==void 0&&a.push(je("Policy version",n.policyVersion)),o){a.push(je("Reward",o.reward??"Not scored")),typeof o.rewardEligible=="boolean"&&a.push(je("Training eligibility",o.rewardEligible?"Eligible":"Not eligible",o.rewardEligible?"info":"warning")),o.terminalClass&&a.push(je("Terminal class",o.terminalClass));let s=po(o.rewardComponents);Object.keys(s).length&&a.push(je("Retained reward components",s)),a.push(...Lue(s))}else a.push(je("Grader feedback","No trajectory or grading receipt retained for this attempt."));for(let s of["errorCode","failureReason","terminalReason"])typeof n[s]=="string"&&a.push(je(s,n[s],"warning"));return a.slice(0,100)}i(aG,"attemptDiagnostics");function B_(e,t,r){let n=oG(e),o=n.attemptsByGroup.get(t)??[],a=o.flatMap(u=>{let p=n.trajectory.get(u.id);return p?[p]:[]}),s=a.filter(u=>u.reward!==null&&Number.isFinite(Number(u.reward))),c=e.rolloutGroups.find(u=>u.id===t),d=e.trainingSteps.filter(u=>u.groupId===t||a.some(p=>p.consumedTrainingStepId===u.id)),l=o.filter(u=>/failed|cancelled|timed_out|expired/.test(u.state));return[je("Group execution",r),je("Retained attempts",o.length),je("Group mean reward",c?.rewardMean??"Not retained"),...c?.policyVersion!==void 0?[je("Input policy",c.policyVersion)]:[],...c?.eligibleTrajectoryCount!==void 0?[je("Eligible trajectories recorded by group",c.eligibleTrajectoryCount)]:[],je("Scored trajectories",s.length),je("Failed attempts",l.length,l.length?"warning":"info"),je("Reward range",s.length?`${Math.min(...s.map(u=>Number(u.reward)))} \u2013 ${Math.max(...s.map(u=>Number(u.reward)))}`:"No scored trajectories"),je("Retained trajectory eligibility",`${a.filter(u=>u.rewardEligible===!0).length} eligible \xB7 ${a.filter(u=>u.rewardEligible===!1).length} ineligible \xB7 ${a.filter(u=>typeof u.rewardEligible!="boolean").length} not retained`),...d.length?d.slice(-10).flatMap(u=>[je("Optimizer step",`${u.id} \xB7 ${u.state}`,u.state.startsWith("failed")?"warning":"info"),...u.inputPolicyVersion!==void 0&&u.outputPolicyVersion!==void 0?[je("Policy transition",`v${u.inputPolicyVersion} \u2192 v${u.outputPolicyVersion}`)]:[],...Object.keys(po(u.metrics)).length?[je("Retained optimizer metrics",u.metrics)]:[]]):[je("Optimizer evidence","No optimizer-step record retained for this group.")]].slice(0,100)}i(B_,"groupDiagnostics");function Qv(e,t){let r=[je("Meaning of execution status","Recorded or completed describes execution evidence. It does not mean the model passed quality evaluation.")];for(let n of e.commands.filter(o=>Hue[t]?.includes(o.commandType)).slice(-20)){r.push(je(n.commandType,n.state,n.state==="failed"?"error":"info")),n.errorCode&&r.push(je("Retained command error",n.errorCode,"error")),r.push(je("Command updated",n.updatedAt));for(let o of["timings","inferenceDiagnostics","inferenceFailureOutput","contextAdmission"])n[o]!==void 0&&n[o]!==null&&r.push(je(o,n[o],o==="inferenceFailureOutput"?"warning":"info"))}if(["Rollouts","Grade"].includes(t))for(let n of e.rolloutGroups.slice(-8))r.push(...B_(e,n.id,n.state).map(o=>({...o,label:`Group ${n.groupIndex+1} \xB7 ${o.label}`})));if(["Evaluate","Baseline evaluation"].includes(t)){let n=e.evaluations.filter(o=>o.kind===(t==="Evaluate"?"candidate":"baseline"));n.length||r.push(je("Evaluation evidence","No evaluation receipt retained for this stage; quality is not established."));for(let o of n){r.push(je("Evaluation execution",o.state,/failed|cancelled|timed_out/.test(o.state)?"error":"info"),je("Score",o.score??"Not retained"));let a=po(o.metrics),s=nG(a.improvement),c=nG(a.improvementThreshold);o.kind==="baseline"?r.push(je("Baseline receipt",o.state==="completed"?"Baseline recorded":o.state)):s!==null&&c!==null?(r.push(je("Improvement comparison",`${a.improvement} \xB7 required ${a.improvementThreshold}`)),r.push(je("Improvement threshold outcome",o.passed===!0?"Improvement threshold met":o.passed===!1?"Improvement threshold not met":"No comparison verdict retained",o.passed===!1?"warning":"info"))):typeof o.passed=="boolean"&&r.push(je("Recorded evaluation acceptance flag",`${o.passed}; improvement comparison not retained`));let d=typeof a.passRate=="number"?a.passRate:typeof a.passRate=="string"&&a.passRate.trim()?Number(a.passRate):null,l=typeof a.taskCount=="number"&&Number.isInteger(a.taskCount)&&a.taskCount>=0?a.taskCount:null;if(d!==null&&Number.isFinite(d)&&d>=0&&d<=1){let u=l!==null&&l>0?d*l:null,p=u!==null&&Math.abs(u-Math.round(u))<1e-6?`${Math.round(u)}/${l} tasks`:l!==null?`${l} tasks`:"Task count not retained";r.push(je("Retained task pass rate",`${p} \xB7 ${(d*100).toFixed(1)}%`,d<1?"warning":"info"))}if(o.metrics){let u={};for(let p of["passRate","taskCount","targetTaskCount","comparison","improvement","baselineScore","candidateScore","improvementThreshold","panelSha256","rewardAssetsInRequest","rolloutFilesystemUsed","expectedAnswerInRequest"]){let m=a[p];(m===null||["string","number","boolean"].includes(typeof m))&&(u[p]=m)}Array.isArray(a.taskResults)&&(u.taskResults=a.taskResults.slice(0,100).map(p=>{let m=po(p);return Object.fromEntries(["taskId","taskSha256","resultSha256","score","passed","state","status"].flatMap(g=>m[g]===null||["string","number","boolean"].includes(typeof m[g])?[[g,m[g]]]:[]))})),r.push(je("Retained evaluation evidence",u))}}}if(t==="Update adapter")for(let n of e.rolloutGroups)typeof n.optimizerDisposition=="string"&&r.push(je("Optimizer disposition",n.optimizerDisposition)),r.push(...Xv(po(n.optimizerEvidence)));if(t==="Update adapter")for(let n of e.trainingSteps.slice(-15))r.push(je("Optimizer step",`${n.id} \xB7 ${n.state}`,/failed/.test(n.state)?"error":"info")),n.inputPolicyVersion!==void 0&&n.outputPolicyVersion!==void 0&&r.push(je("Policy transition",`v${n.inputPolicyVersion} \u2192 v${n.outputPolicyVersion}`)),r.push(je("Optimizer commit",n.optimizerCommitSha256??"No commit retained")),Object.keys(po(n.metrics)).length&&r.push(je("Retained optimizer metrics",n.metrics));if(t==="Activate policy")for(let n of e.policyVersions.slice(-15))r.push(je("Serving policy",`v${n.version} \xB7 ${n.served?"Served":"No serving attestation"}`)),typeof n.servedAttestationSha256=="string"&&r.push(je("Serving attestation",n.servedAttestationSha256));if(t==="Save checkpoint")for(let n of e.checkpoints.slice(-10))r.push(je("Checkpoint",`${n.id??"ID not retained"} \xB7 ${n.state??"State not retained"}`));return t==="Finish"&&e.job.terminalReason&&r.push(je("Run terminal reason",e.job.terminalReason,e.job.state==="completed"?"info":"warning")),r.slice(0,60)}i(Qv,"stageDiagnostics");function Zv(e,t){return t==="Grade"?e.trajectories.slice(-20).flatMap(r=>typeof r.id=="string"?[{kind:"trajectory",id:r.id}]:[]):["Evaluate","Baseline evaluation"].includes(t)?e.evaluations.filter(r=>r.kind===(t==="Evaluate"?"candidate":"baseline")).flatMap(r=>{let n=r.metrics?.taskResults;return typeof r.id!="string"||!Array.isArray(n)?[]:n.flatMap(o=>typeof po(o).taskId=="string"?[{kind:"evaluation",id:r.id,taskId:po(o).taskId}]:[])}).slice(0,100):[]}i(Zv,"stageFeedbackTargets");function iG(e,t,r){let n=e.rolloutGroups.find(f=>f.id===t);if(!n)return[];let o=e.rollouts.filter(f=>f.groupId===t),a=new Set(o.map(f=>f.id)),s=e.trajectories.filter(f=>a.has(f.rolloutId)),c=new Set(s.map(f=>f.consumedTrainingStepId).filter(f=>typeof f=="string")),d=e.trainingSteps.filter(f=>f.groupId===t||c.has(f.id)),l=new Set(d.flatMap(f=>typeof f.optimizerCommitSha256=="string"&&f.optimizerCommitSha256.length>0&&f.inputPolicyVersion!==void 0&&f.outputPolicyVersion!==void 0&&f.outputPolicyVersion>f.inputPolicyVersion?[f.outputPolicyVersion]:[])),u=e.checkpoints.filter(f=>typeof f.policyVersion=="number"&&l.has(f.policyVersion)),p=e.policyVersions.filter(f=>l.has(f.version)),m={...e,rolloutGroups:[n],rollouts:o,trajectories:s,trainingSteps:d,checkpoints:u,policyVersions:p,commands:[],evaluations:[]},g=s.filter(f=>f.reward!==null&&Number.isFinite(Number(f.reward))).length,w=d.filter(f=>typeof f.optimizerCommitSha256=="string"&&f.optimizerCommitSha256.length>0).length,h=i(f=>f.some(S=>/failed|cancelled|timed_out|expired/.test(S)),"failure");return[{label:"Rollouts",done:["scoring","eligible","consumed"].includes(n.state),active:n.state==="running",failed:h(o.map(f=>f.state)),detail:`${o.length} retained attempts`},{label:"Grade",done:["eligible","consumed"].includes(n.state),active:n.state==="scoring",failed:s.some(f=>["grader_failure","validation_failure","infrastructure_failure"].includes(String(f.terminalClass))),detail:`${g} graded${n.rewardMean===null?"":` \xB7 avg ${Number(n.rewardMean).toFixed(3)}`}`},{label:"Update adapter",done:w>0,active:d.some(f=>["running","leased"].includes(f.state)),failed:h(d.map(f=>f.state)),detail:n.optimizerDisposition==="skipped_no_signal"?`No optimizer update \xB7 policy v${n.policyVersion}`:`${w} optimizer commit${w===1?"":"s"} \xB7 ${d.length} linked step${d.length===1?"":"s"}`},{label:"Save checkpoint",done:u.some(f=>f.state==="ready"&&!!f.adapterSha256),active:!1,failed:h(u.flatMap(f=>f.state?[f.state]:[])),detail:`${u.filter(f=>f.state==="ready"&&f.adapterSha256).length} durable \xB7 ${u.length} checkpoint receipts`},{label:"Activate policy",done:p.some(f=>f.served),active:!1,failed:!1,detail:p.some(f=>f.served)?`Serving v${p.find(f=>f.served).version}`:"No linked serving attestation"}].filter(f=>e.job.inputBundle?.executionIntent?.purpose!=="collection"||["Rollouts","Grade"].includes(f.label)).map(f=>({label:f.label,inLoop:!0,state:f.failed?"failed":f.done?"done":r&&f.active?"active":r?"pending":"missing",status:f.label==="Update adapter"&&n.optimizerDisposition==="skipped_no_signal"?"Skipped \xB7 no signal":f.failed?"Issues recorded":f.done?"Recorded":r&&f.active?"In progress":"Not recorded",detail:f.detail,diagnostics:Qv(m,f.label),feedback:Zv(m,f.label)}))}i(iG,"groupStageEvidence");var wl=i(e=>e!=null&&Number.isFinite(Number(e))?Number(e):null,"number"),Ko=i(e=>v.array(e).max(1e4).default([]),"collection"),sG=v.object({id:v.string(),groupIndex:v.number().int().nonnegative(),policyVersion:v.number().int().nonnegative(),state:v.literal("consumed"),optimizerDisposition:v.enum(["applied","skipped_no_signal"]),optimizerEvidence:v.record(v.string(),v.unknown()),sourceJobId:v.string()}),Bue=v.object({job:v.object({id:v.string(),teamId:v.string(),modelProjectId:v.string(),state:v.string(),targetGroups:v.number().int().nonnegative(),completedGroups:v.number().int().nonnegative(),optimizerUpdatesApplied:v.number().int().nonnegative().default(0),currentPolicyVersion:v.number().int().nonnegative(),terminalReason:v.string().nullish(),canonicalPublishFailureCode:v.string().nullish(),inputBundle:v.object({recipe:v.object({rolloutGroupSize:v.number().int().min(0).max(1e3),adapter:v.object({rank:v.number().int().positive()}).passthrough().optional()}).passthrough().optional(),executionIntent:v.object({purpose:v.string().nullish()}).passthrough().nullish(),recovery:v.object({sourceJobId:v.string(),checkpointId:v.string(),checkpointPolicyVersion:v.number().int().positive(),completedGroups:v.number().int().positive(),checkpointJobId:v.string().optional(),optimizerUpdatesApplied:v.number().int().nonnegative().optional(),optimizerUpdatesSkipped:v.number().int().nonnegative().optional(),groups:v.array(sG).max(128).optional(),undurableProgress:v.object({completedGroups:v.number(),policyVersion:v.number(),optimizerUpdatesApplied:v.number(),optimizerUpdatesSkipped:v.number(),groups:v.array(sG).max(128)}).optional()}).passthrough().optional(),continuation:v.object({parentJobId:v.string(),parentArtifact:v.object({id:v.string()}).passthrough(),parentCheckpoint:v.object({id:v.string()}).passthrough(),optimizerMode:v.enum(["continue","reset"]),compatibility:v.object({adapter:v.object({rank:v.number().int().positive()}).passthrough()}).passthrough().optional()}).passthrough().nullish()}).passthrough().optional()}).passthrough(),gpuLeases:Ko(v.object({state:v.string(),gpuType:v.string(),observedHourlyUsd:v.union([v.string(),v.number()]).nullable(),readyAt:v.string().nullable(),terminatedAt:v.string().nullable(),updatedAt:v.string()}).passthrough()),rolloutGroups:Ko(v.object({id:v.string(),groupIndex:v.number().int().nonnegative(),state:v.string(),rewardMean:v.union([v.string(),v.number()]).nullable()}).passthrough()),rollouts:Ko(v.object({id:v.string(),groupId:v.string(),workerSlot:v.number().int().nonnegative(),attempt:v.number().int().positive(),state:v.string()}).passthrough()),trajectories:Ko(v.object({id:v.string().optional(),rolloutId:v.string(),reward:v.union([v.string(),v.number()]).nullable()}).passthrough()),checkpoints:Ko(v.object({id:v.string().optional(),state:v.string().optional(),adapterSha256:v.string().nullable().optional()}).passthrough()),commands:Ko(v.object({commandType:v.string(),state:v.string(),errorCode:v.string().nullish(),updatedAt:v.string()}).passthrough()),trainingSteps:Ko(v.object({id:v.string(),state:v.string(),groupId:v.string().optional(),inputPolicyVersion:v.number().optional(),outputPolicyVersion:v.number().optional()}).passthrough()),policyVersions:Ko(v.object({version:v.number().int().nonnegative(),served:v.boolean()}).passthrough()),evaluations:Ko(v.object({kind:v.string(),state:v.string(),score:v.union([v.string(),v.number()]).nullable(),metrics:v.object({taskCount:v.number().int().nonnegative().optional(),targetTaskCount:v.number().int().positive().optional()}).passthrough().optional()}).passthrough())}).passthrough(),$ue=v.object({entries:Ko(v.object({id:v.string(),timestamp:v.string(),source:v.string(),message:v.string(),level:v.string()}).passthrough())}).passthrough();function cG(e,t,r){let n=Bue.parse(e),o=n.job;if(o.id!==r.jobId||o.teamId!==r.teamId||o.modelProjectId!==r.modelProjectId)throw new Error("Flow evidence belongs to a different training run.");let a=!["completed","cancelled","failed","budget_exhausted"].includes(o.state),s=o.inputBundle?.executionIntent?.purpose==="collection",c=o.inputBundle?.recovery?.optimizerUpdatesApplied??0,d=eG(n),l=L_(n),u=new Map(l.map(B=>[B.groupIndex,B])),p=new Map([...d,...tG(n)].map(B=>[B.index,B])),m=Math.max(0,o.optimizerUpdatesApplied-c),g=!s&&n.evaluations.some(B=>B.kind==="candidate"),w=s?void 0:n.evaluations.find(B=>B.kind==="baseline"),h=w?.metrics?.taskCount,y=w?.metrics?.targetTaskCount,f=h!==void 0&&y!==void 0&&h<=y,S=w?.state==="completed"?wl(w.score):null,k=n.gpuLeases.find(B=>!B.terminatedAt)??[...n.gpuLeases].sort((B,q)=>q.updatedAt.localeCompare(B.updatedAt))[0],I=!!(k?.readyAt&&!k.terminatedAt&&a),b=n.trajectories.filter(B=>wl(B.reward)!==null).length,R=Nue(n),_=o.inputBundle?.continuation,P=[...n.commands].filter(B=>B.commandType==="materialize_checkpoint").sort((B,q)=>q.updatedAt.localeCompare(B.updatedAt))[0],x=P?.state==="succeeded",E=[{label:"Prepare",done:n.gpuLeases.some(B=>B.readyAt),active:["draft","validating","admitted","provisioning_gpu","provisioning_rollouts","warming"].includes(o.state)&&!w},{label:"Load parent adapter",skip:!_,done:x,active:!!(P&&!x&&a&&!["failed","cancelled"].includes(P.state)),detail:_?`Checkpoint ${_.parentCheckpoint.id}; optimizer ${_.optimizerMode}`:""},{label:"Baseline evaluation",done:w?.state==="completed",active:w?.state==="running",skip:!w,detail:[f?`${h}/${y} cases graded`:"Case counts not recorded",S!==null?`score ${S.toFixed(3)}`:null].filter(Boolean).join("; "),...f?{progress:h/y}:{}},{label:"Rollouts",done:o.targetGroups>0&&o.completedGroups>=o.targetGroups,active:!g&&["rollout_phase","draining"].includes(o.state)&&!n.rolloutGroups.some(B=>B.state==="scoring"),inLoop:!0,detail:`${o.completedGroups}/${o.targetGroups} groups; ${b} graded`,progress:o.targetGroups?Math.min(1,o.completedGroups/o.targetGroups):0},{label:"Grade",done:o.targetGroups>0&&n.rolloutGroups.length+d.length>=o.targetGroups&&n.rolloutGroups.every(B=>["eligible","consumed"].includes(B.state)),active:n.rolloutGroups.some(B=>B.state==="scoring")||n.rollouts.some(B=>B.state==="scoring"),inLoop:!0,detail:`${b} graded`},{label:"Update adapter",done:m>0,active:o.state==="update_phase",inLoop:!0,skip:s,detail:`${m} new updates${c?`; ${c} reused`:""}`},{label:"Save checkpoint",detail:n.checkpoints.some(B=>B.state==="ready"&&B.adapterSha256)?"Durable checkpoint recorded":!a&&n.checkpoints.length?"Upload interrupted \xB7 0 durable":"Write to storage",done:n.checkpoints.some(B=>B.state==="ready"&&B.adapterSha256),active:a&&n.checkpoints.some(B=>B.state==="uploading"),inLoop:!0,skip:s},{label:"Activate policy",done:n.policyVersions.some(B=>B.version>0&&B.served),active:o.state==="reloading",inLoop:!0,skip:s,detail:`Policy v${o.currentPolicyVersion}`},{label:"Evaluate",done:n.evaluations.some(B=>B.kind==="candidate"&&B.state==="completed"),active:n.evaluations.some(B=>B.kind==="candidate"&&B.state==="running"),skip:s},{label:"Finish",done:o.state==="completed",active:!1}],C=new Map(n.trajectories.map(B=>[B.rolloutId,wl(B.reward)])),A=[...n.rolloutGroups].sort((B,q)=>B.groupIndex-q.groupIndex).slice(-50),j=Math.max(o.targetGroups,...A.map(B=>B.groupIndex+1),0),H=o.inputBundle?.recovery,L=Array.from({length:Math.min(j,50)},(B,q)=>{let W=Math.max(0,j-50)+q;return A.find(Z=>Z.groupIndex===W)??{id:"",groupIndex:W,state:"planned",rewardMean:null}});return lp.parse({jobId:o.id,teamId:o.teamId,modelProjectId:o.modelProjectId,state:o.state,policyVersion:o.currentPolicyVersion,groupsCompleted:o.completedGroups,groupsTarget:o.targetGroups,live:a,..._?{continuation:{sourceJobId:_.parentJobId,artifactId:_.parentArtifact.id,checkpointId:_.parentCheckpoint.id,optimizerMode:_.optimizerMode,materialized:x,parentRank:_.compatibility?.adapter.rank,trainableRank:o.inputBundle?.recipe?.adapter?.rank}}:{},...H?{recovery:{sourceJobId:H.sourceJobId,checkpointId:H.checkpointId,checkpointJobId:H.checkpointJobId??H.sourceJobId,policyVersion:H.checkpointPolicyVersion,completedGroups:H.completedGroups,optimizerUpdatesApplied:c,...l.length?{replayGroups:l,replayCompleted:l.every(B=>n.rolloutGroups.some(q=>q.groupIndex===B.groupIndex&&q.state==="consumed")),undurablePolicyVersion:H.undurableProgress?.policyVersion}:{},optimizerStateRestored:n.commands.some(B=>B.commandType==="materialize_checkpoint"&&B.state==="succeeded")}}:{},nodes:E.filter(B=>!B.skip).map(B=>({label:B.label,diagnostics:Qv(n,B.label),feedback:Zv(n,B.label),state:R[B.label]?"failed":a&&B.active?"active":B.done?"done":a?"pending":"missing",status:R[B.label]?"Error recorded":a&&B.active?"In progress":B.done?"Recorded":a?"Pending":"Not recorded",...B.inLoop?{inLoop:!0}:{},...B.detail?{detail:B.detail}:{},...R[B.label]?{error:R[B.label]}:{},...B.progress!==void 0?{progress:B.progress}:{}})),inference:k?{label:k.gpuType.replace(/^NVIDIA\s+/i,"").replace(/-SXM\d*-?/," "),state:I?"active":k.readyAt?"done":a?"pending":"missing",status:I?"Worker ready":k.state.replaceAll("_"," "),...wl(k.observedHourlyUsd)!==null?{detail:`$${wl(k.observedHourlyUsd).toFixed(2)}/hr`}:{}}:null,groups:(L.length?L:Array.from({length:Math.min(o.targetGroups,50)},(B,q)=>({id:"",groupIndex:q,state:"planned",rewardMean:null}))).map(B=>{let q=B.id?void 0:p.get(B.groupIndex);return q||{index:B.groupIndex,...u.has(B.groupIndex)?{replay:u.get(B.groupIndex)}:{},..."optimizerDisposition"in B&&["applied","skipped_no_signal"].includes(String(B.optimizerDisposition))?{optimizerDisposition:B.optimizerDisposition}:{},...B.id?{nodes:iG(n,B.id,a)}:{},state:B.state,meanReward:wl(B.rewardMean),plannedSlots:B.state==="reused"?0:o.inputBundle?.recipe?.rolloutGroupSize??0,diagnostics:B_(n,B.id,B.state),attempts:n.rollouts.filter(W=>W.groupId===B.id).slice(-1e3).map(W=>({id:W.id,slot:W.workerSlot,attempt:W.attempt,state:W.state,reward:C.get(W.id)??null,diagnostics:aG(n,W.id),feedback:n.trajectories.filter(Z=>Z.rolloutId===W.id&&typeof Z.id=="string").slice(-1).map(Z=>({kind:"trajectory",id:Z.id}))}))}}),groupCount:j,logs:$ue.parse(t).entries.slice(-200).map(B=>({id:B.id,at:B.timestamp,source:B.source.replaceAll("_"," "),message:B.message,level:B.level}))})}i(cG,"hostedRunStageEvidence");function Nue(e){let t={},r={train_step:"Update adapter",upload_checkpoint:"Save checkpoint",qualify_checkpoint:"Save checkpoint",start_inference:e.policyVersions.some(s=>s.version>0)?"Activate policy":"Prepare",score_reward_model:"Grade",stop:"Finish",materialize_checkpoint:e.job.inputBundle?.continuation?"Load parent adapter":"Prepare"},n=new Map;for(let s of e.commands){let c=n.get(s.commandType);(!c||s.updatedAt>c.updatedAt)&&n.set(s.commandType,s)}for(let[s,c]of n){let d=r[s];d&&c.state==="failed"&&(t[d]=`${s}: ${c.errorCode??"Worker command failed"}`)}let o=e.rollouts.filter(s=>s.state.endsWith("failed"));o.length&&(t.Rollouts=`${o.length} failed attempt(s). Inspect the rollout records for details.`),e.evaluations.some(s=>s.kind==="candidate"&&s.state==="failed")&&(t.Evaluate=`Candidate evaluation failed. ${e.job.terminalReason??"Inspect evaluation records for details."}`),e.evaluations.some(s=>s.kind==="baseline"&&s.state==="failed")&&(t["Baseline evaluation"]=`Baseline evaluation failed. ${e.job.terminalReason??"Inspect evaluation records for details."}`);let a=e.checkpoints.find(s=>s.state==="failed");return a&&!t["Save checkpoint"]&&(t["Save checkpoint"]=a.id?`Checkpoint ${a.id} failed.`:"Checkpoint failed."),e.job.state==="failed"&&!e.gpuLeases.some(s=>s.readyAt)&&(t.Prepare=e.job.terminalReason??"Run preparation failed."),e.job.canonicalPublishFailureCode&&(t.Finish=e.job.canonicalPublishFailureCode),e.job.state==="failed"&&(t.Finish=[t.Finish,e.job.terminalReason??"Run failed; no terminal reason retained."].filter(Boolean).join(" \xB7 ")),t}i(Nue,"stageErrors");var Qr=v.string().trim().min(1).max(240),dG=v.object({job:GS,events:v.array(IO).max(1e4),outputs:kO,evals:eg.nullable(),flow:lp.nullable(),flowError:v.string().nullable()}).strict();function Im(e){async function t(){let a=await e.currentIdentity();if(a?.teamId!==e.teamId||a.actorId!==e.actorId||new URL(a.apiOrigin).origin!==new URL(e.access.apiBaseUrl).origin)throw new Error("The active account changed. Reload this training run.")}i(t,"fence");async function r(a,s,c=4194304){await t();let d=pe(e.access.token);d.set("x-openpond-team-id",e.teamId),a.startsWith("/v1/training/")&&(d.set("Accept",Lu),s?.body&&d.set("Content-Type",Lu));let l=await fetch(`${e.access.apiBaseUrl.replace(/\/+$/,"")}${a}`,{...s,headers:d,redirect:"error",signal:AbortSignal.timeout(2e4)}),u=l.body?.getReader();if(!u)throw new Error("Training evidence returned no body.");let p=[],m=0;try{for(;;){let w=await u.read();if(w.done)break;if(m+=w.value.byteLength,m>c)throw new Error("Training evidence exceeded its bounded response.");p.push(w.value)}}finally{await u.cancel(),u.releaseLock()}await t();let g=JSON.parse(Buffer.concat(p).toString("utf8"));if(!l.ok){let w=MH.safeParse(g);throw new Ge(l.status,w.success?w.data:{schemaVersion:"openpond.trainingApiError.v2",code:"training_read_unavailable",message:`Training run is unavailable (${l.status}).`,retryable:!1,requestId:null,details:{}})}return g}i(r,"request");let n=i(a=>`/v1/training/jobs/${encodeURIComponent(Qr.parse(a))}`,"path");async function o(a){Qr.parse(a);let s=await r(`/v1/managed-rl/jobs/${encodeURIComponent(a)}?view=console`,void 0,67108864),c=v.string().min(1).parse(s.job?.job?.modelProjectId),d=cG(s.job,{entries:[]},{jobId:a,teamId:e.teamId,modelProjectId:c});return await t(),d}return i(o,"readFlow"),{readFlow:o,async controlModelServing(a,s){let c=Qr.parse(a),d=$1.parse(s);if(d.teamId!==e.teamId)throw new Error("Control serving in this Model's original workspace.");return q1(await r(`/v1/training/models/${encodeURIComponent(c)}/serving`,{method:"POST",body:JSON.stringify(d)},16777216),{modelProjectId:c,request:d,actorId:e.actorId})},async modelServing(a,s){let c=Qr.parse(a),d=F1.parse(s);if(d.teamId!==e.teamId)throw new Error("Read serving in this Model's original workspace.");return z1(await r(`/v1/training/models/${encodeURIComponent(c)}/serving?${new URLSearchParams(d)}`,void 0,16777216),{modelProjectId:c,...d})},async savedModelServing(a,s){let c=Qr.parse(a),d=K1.parse(s);if(d.teamId!==e.teamId)throw new Error("Read serving in this Model's original workspace.");let l=await X1(await r(`/v1/training/models/${encodeURIComponent(c)}/serving?${new URLSearchParams(d)}`,void 0,16777216),{modelProjectId:c,...d});if(l.schemaVersion==="openpond.decisionModelServing.v1"&&l.version.ownerUserId!==e.actorId)throw new Error("Read your exact decision Model in its original account.");return l},async controlNeuronTrainingModelServing(a,s){let c=Qr.parse(a),d=Yu.parse(s);if(d.teamId!==e.teamId)throw new Error("Control serving in this Model's original workspace.");return k1(await r(`/v1/training/models/${encodeURIComponent(c)}/serving`,{method:"POST",body:JSON.stringify(d)},16777216),{modelProjectId:c,request:d,actorId:e.actorId})},async controlAlphaEditModelServing(a,s){let c=Qr.parse(a),d=Ku.parse(s);if(d.teamId!==e.teamId)throw new Error("Control serving in this Model's original workspace.");return v1(await r(`/v1/training/models/${encodeURIComponent(c)}/serving`,{method:"POST",body:JSON.stringify(d)},16777216),{modelProjectId:c,request:d,actorId:e.actorId})},async controlDecisionModelServing(a,s){let c=Qr.parse(a),d=Xu.parse(s);if(d.teamId!==e.teamId)throw new Error("Control serving in this Model's original workspace.");return x1(await r(`/v1/training/models/${encodeURIComponent(c)}/serving`,{method:"POST",body:JSON.stringify(d)},16777216),{modelProjectId:c,request:d,actorId:e.actorId})},async controlEngramModelServing(a,s){let c=Qr.parse(a),d=hg.parse(s);if(d.teamId!==e.teamId)throw new Error("Control serving in this Model's original workspace.");return LH(await r(`/v1/training/models/${encodeURIComponent(c)}/serving`,{method:"POST",body:JSON.stringify(d)},16777216),{modelProjectId:c,request:d,actorId:e.actorId})},async controlSteeringModelServing(a,s){let c=Qr.parse(a),d=jg.parse(s);if(d.teamId!==e.teamId)throw new Error("Control serving in this Model's original workspace.");return Y1(await r(`/v1/training/models/${encodeURIComponent(c)}/serving`,{method:"POST",body:JSON.stringify(d)},16777216),{modelProjectId:c,request:d,actorId:e.actorId})},async savedVersion(a,s){let c=Qr.parse(a),d=new URLSearchParams({teamId:e.teamId});s!==void 0&&d.set("versionHash",v.string().regex(/^[a-f0-9]{64}$/).parse(s));let l=await JH(await r(`/v1/training/models/${encodeURIComponent(c)}/version?${d}`,void 0,16777216),e.teamId,c,s);if(l.version?.schemaVersion==="openpond.decisionModelVersion.v1"&&l.version.ownerUserId!==e.actorId)throw new Error("Read your exact decision Model in its original account.");return l},async savedModel(a){let s=Qr.parse(a);return L1(await r(`/v1/training/models/${encodeURIComponent(s)}?${new URLSearchParams({teamId:e.teamId})}`,void 0,16777216),{teamId:e.teamId,modelProjectId:s})},async saveModel(a,s){let c=H1.parse(s);if(c.teamId!==e.teamId)throw new Error("Save this Model in its original workspace.");let d=await B1(await r(`${n(a)}/model`,{method:"POST",body:JSON.stringify(c)},16777216),{jobId:a,request:c,actorId:e.actorId});return await t(),d},async result(a){return BH(await r(`${n(a)}/result`,void 0,16777216),{teamId:e.teamId,jobId:a})},async feedback(a,s){Qr.parse(a);let c=nw.parse(s),d=new URLSearchParams({kind:c.kind,id:c.id,...c.taskId?{taskId:c.taskId}:{}}),l=WB.parse(await r(`/v1/managed-rl/jobs/${encodeURIComponent(a)}/feedback?${d}`,void 0,262144));if(l.jobId!==a||l.kind!==c.kind||l.id!==c.id||l.taskId!==c.taskId)throw new Error("Grader feedback belongs to another run or attempt.");return l},async summary(a){let s=await r(n(a)),c=GS.parse(s.job);if(c.id!==a||c.teamId!==e.teamId)throw new Error("Training summary belongs to another run.");return c},async logs(a){Qr.parse(a);let s=await r(`/v1/managed-rl/jobs/${encodeURIComponent(a)}/logs`),c=v.object({entries:v.array(v.object({id:v.string(),timestamp:v.string(),source:v.string(),message:v.string(),level:v.string()}).passthrough()).max(1e4)}).passthrough().parse(s).entries;return lp.shape.logs.parse(c.slice(-200).map(d=>({id:d.id,at:d.timestamp,source:d.source.replaceAll("_"," "),message:d.message,level:d.level})))},async read(a,s={}){let c=n(a),[d,l,u,p]=await Promise.all([r(c),r(`${c}/events`),r(`${c}/outputs`),r(`${c}/post-training`)]),m=dG.omit({flow:!0,flowError:!0}).parse({job:d.job,events:l.events,outputs:u,evals:p});if(m.job.id!==a||m.job.teamId!==e.teamId||m.events.some(h=>h.jobId!==a)||m.evals&&(m.evals.teamId!==e.teamId||m.evals.jobId!==a))throw new Error("Training evidence belongs to another run.");let g=null,w=null;if(s.includeFlow!==!1)try{if(g=await o(a),g.modelProjectId!==m.job.modelProjectId)throw new Error("Flow evidence belongs to a different Model Project.")}catch(h){w=h instanceof v.ZodError?"The hosted run returned invalid graph evidence.":h instanceof Error?h.message:"Run graph is unavailable."}return await t(),dG.parse({...m,flow:g,flowError:w})},async control(a,s,c){let d=ZS.parse(c),l=eg.parse(await r(`${n(a)}/post-training/${s}`,{method:"POST",body:JSON.stringify(d)}));if(l.jobId!==a||l.teamId!==e.teamId||l.planHash!==d.planHash)throw new Error("The evaluation command returned a different run or plan.");return l}}}i(Im,"createHostedTrainingRunDetail");function lG(e){return async(t,r,n,o)=>{if(t==="hosted_training_model_serving_control"){let a=v.object({teamId:v.string().min(1),modelProjectId:v.string().min(1).max(240),command:v.unknown(),review:v.object({intentHash:v.string().regex(/^[a-f0-9]{64}$/),projectId:v.string().min(1).max(240).nullable()}).strict().optional()}).strict().parse(r),[s,c,d]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]);if(a.teamId!==s)throw new Error("The active workspace changed. Reload this Model.");let l=v.union([Xu,Ku,Yu]).safeParse(a.command);if(l.success){if(!a.review)throw new Qe("decision_serving_review_required","Recover the original reviewed decision serving control.");let p=a.review.projectId,m=new URL(d.apiBaseUrl).origin,g={modelProjectId:a.modelProjectId,request:l.data},w=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:c,apiOrigin:m,teamId:s,projectId:p}),action:"training-model-serving-control",intentHash:a.review.intentHash,id:l.data.operationId});if(w.phase!=="dispatching"||T(w.command)!==T(g))throw new Qe("decision_serving_review_required","Recover the original reviewed decision serving control.");Rr({action:"training-model-serving-control",id:l.data.operationId,actorId:c,teamId:s,projectId:p,intent:w.reviewedIntent,command:g})}let u=Im({teamId:s,actorId:c,access:d,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity")});return Ku.safeParse(a.command).success?u.controlAlphaEditModelServing(a.modelProjectId,a.command):Yu.safeParse(a.command).success?u.controlNeuronTrainingModelServing(a.modelProjectId,a.command):Xu.safeParse(a.command).success?u.controlDecisionModelServing(a.modelProjectId,a.command):hg.safeParse(a.command).success?u.controlEngramModelServing(a.modelProjectId,a.command):jg.safeParse(a.command).success?u.controlSteeringModelServing(a.modelProjectId,a.command):u.controlModelServing(a.modelProjectId,a.command)}if(t==="hosted_training_model_serving"){let a=v.object({teamId:v.string().min(1),modelProjectId:v.string().min(1).max(240),versionHash:v.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(r),[s,c,d]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]);if(a.teamId!==s)throw new Error("The active workspace changed. Reload this Model.");return Im({teamId:s,actorId:c,access:d,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity")}).savedModelServing(a.modelProjectId,{teamId:s,versionHash:a.versionHash})}if(t==="hosted_training_saved_model"||t==="hosted_training_saved_version"){let a=v.object({teamId:v.string().min(1),modelProjectId:v.string().min(1).max(240),versionHash:v.string().regex(/^[a-f0-9]{64}$/).optional()}).strict().parse(r),[s,c,d]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]);if(a.teamId!==s)throw new Error("The active workspace changed. Reload this Model.");let l=Im({teamId:s,actorId:c,access:d,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity")});return t==="hosted_training_saved_version"?l.savedVersion(a.modelProjectId,a.versionHash):l.savedModel(a.modelProjectId)}if(["hosted_training_detail","hosted_training_result","hosted_training_save_model","hosted_training_flow","hosted_training_summary","hosted_training_logs","hosted_training_feedback","hosted_training_control"].includes(t)){let a=v.object({teamId:v.string().min(1),jobId:v.string().min(1).max(200),includeFlow:v.boolean().optional(),feedbackTarget:nw.optional(),action:v.enum(["start","retry","cancel"]).optional(),command:v.unknown().optional()}).strict().parse(r),[s,c,d]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]);if(a.teamId!==s)throw new Error("The active workspace changed. Reload this training run.");let l=Im({teamId:s,actorId:c,access:d,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity")});return t==="hosted_training_detail"?l.read(a.jobId,{includeFlow:a.includeFlow}):t==="hosted_training_result"?l.result(a.jobId):t==="hosted_training_save_model"?l.saveModel(a.jobId,a.command):t==="hosted_training_flow"?l.readFlow(a.jobId):t==="hosted_training_summary"?l.summary(a.jobId):t==="hosted_training_logs"?l.logs(a.jobId):t==="hosted_training_feedback"?l.feedback(a.jobId,a.feedbackTarget):l.control(a.jobId,v.enum(["start","retry","cancel"]).parse(a.action),a.command)}return e.trainingRequest(t,r,n,o)}}i(lG,"createHostedTrainingDetailTransport");async function uG(e){let t=e.review.evidence.attempts[e.slotIndex],r=await e.experiments.inspectCase({teamId:e.scope,id:t.experimentId,receiptId:t.attemptId,limit:100}),n=e.afterId===void 0?0:Number(e.afterId);if(!Number.isSafeInteger(n)||n<0)throw new He("human_inspection_cursor_invalid",422);let o=r.case.messages;if(r.case.externalProcess){let c=r.case.externalProcess,d=await ym({store:e.store,teamId:e.scope,executionId:t.experimentId,caseId:t.attemptId});if(T(d)!==c.traceHash||d.length!==c.eventCount||T(d.map(l=>String(l.sequence)))!==T(c.runtimeEventRefs)||t.trace?.contentHash!==c.traceHash)throw new He("human_process_trace_revision_changed",409);o=d}let a=[],s=0;for(let c of o.slice(n,n+100)){let d=Buffer.byteLength(JSON.stringify(c));if(a.length&&s+d>2097152)break;a.push(c),s+=d}return{reviewId:e.review.id,reviewRevision:e.review.revision,evidenceHash:T(e.review.evidence),slot:e.review.evidence.attempts.length===2?e.slotIndex===0?"A":"B":"Attempt",slotIndex:e.slotIndex,nextEventCursor:n+a.length<o.length?String(n+a.length):null,input:r.case.input,output:r.case.output,error:r.case.error,events:a,eventCount:o.length,evidenceLimited:r.case.status!=="completed"}}i(uG,"inspectLocalHumanAttempt");function $_(e,t,r,n){let o=mt(e),a=o.taskset.graders.find(d=>d.id===t),s=Sr(o).find(d=>d.id===t);if(!a||a.kind!=="human"||!a.form||a.form.mode!=="individual"||!s||n.some(d=>!o.taskset.tasks.some(l=>l.id===d)))throw new He("human_structured_task_grader_required",409);let c=s.release??{id:a.id,revision:Number(a.version),contentHash:T(a)};return{evidence:_s.parse({dataset:r,grader:c,graderBinding:{id:a.id,version:a.version,contentHash:T(a)},rubric:{id:a.rubricRef.id,revision:1,contentHash:a.rubricRef.contentHash},attempts:[],taskIds:n}),form:xs.parse(a.form)}}i($_,"localHumanTasks");var pG=v.object({endpoint:v.literal("snapshot"),scope:v.string().min(1),projectId:v.string().min(1),graderId:v.string().min(1),selections:v.array(v.object({executionId:v.string().min(1),receiptId:v.string().min(1)}).strict()).min(1).max(2)}).strict();function Le(e,t=409){throw new He(e,t)}i(Le,"fail");function eI(e){async function t(l){(!l.actorId||l.actorId!==await e.actorId()||l.scope!==await e.teamId())&&Le("human_local_scope_denied",403)}i(t,"member");async function r(l,u,p,m,g){let w,h,y,f,S,k=[];for(let I of g){let b=await e.store.humanReviewLocalEvidence(l,I.executionId),R=b.released.definition;(b.execution.ownerActorId!==u||R.ownerActorId!==u)&&Le("human_local_evidence_not_found",404),R.configuration.request.project?.id!==p&&Le("human_project_attempt_mismatch"),b.execution.completedAt||Le("human_attempt_not_sealed");let _=mt(b.released.package),P=_.taskset,x=P.graders.find(B=>B.id===m),E=R.graders.find(B=>B.id===m);(!x||x.kind!=="human"||!x.form||!E||E.contentHash!==T(x))&&Le("human_structured_grader_required");let C=b.cases.find(B=>B.receiptId===I.receiptId);C?.result||Le("human_retained_behavior_unavailable");let A=Lt(C.result),j=P.tasks.find(B=>B.id===C.admission.taskId);j||Le("human_task_unavailable");let H={id:P.id,revision:P.revision,contentHash:P.contentHash},L=E.release?{id:E.release.id,revision:Number(E.release.revision),contentHash:E.release.contentHash}:{id:x.id,revision:Number(x.version),contentHash:T(x)};(!Number.isSafeInteger(L.revision)||L.revision<1)&&Le("human_grader_release_required"),(w&&T(w)!==T(H)||h&&T(h)!==T(L))&&Le("human_pair_releases_differ"),w=H,h=L,y={id:x.rubricRef.id,revision:1,contentHash:x.rubricRef.contentHash},f={id:x.id,version:x.version,contentHash:T(x)},S=xs.parse(x.form),k.push({localSource:{kind:"native_local",ownerActorId:u,teamId:l,executionHash:b.execution.executionHash,configurationHash:T(R.configuration),retainedAttemptHash:A.attempt.contentHash,traceHash:A.attempt.native?.traceHash??A.attempt.profileNative?.traceHash??A.attempt.externalProcess?.traceHash??A.attempt.contentHash},experimentId:b.execution.id,attemptId:C.receiptId,taskId:j.id,targetId:R.model.modelId,output:{id:C.receiptId,revision:1,contentHash:A.attempt.contentHash},trace:{id:C.receiptId,revision:1,contentHash:A.attempt.native?.traceHash??A.attempt.profileNative?.traceHash??A.attempt.externalProcess?.traceHash??A.attempt.contentHash},familyKey:j.clusterKey,split:j.split})}return{evidence:_s.parse({dataset:w,grader:h,graderBinding:f,rubric:y,attempts:k}),form:xs.parse(S)}}i(r,"snapshot");let n=new Map,o=i((l,u,p,m)=>T([l,u,p,m]),"key"),a=new Map,s={member:t,async owner(l,u){return await t(l),!0},async evidence(l,u){await t(l);let p=u.evidence.attempts.length?await r(l.scope,l.actorId,u.projectId,u.evidence.graderBinding.id,u.evidence.attempts.map(m=>({executionId:m.experimentId,receiptId:m.attemptId}))):$_(n.get(o(l.scope,l.actorId,u.projectId,u.evidence.dataset))??Le("human_task_source_unavailable"),u.evidence.graderBinding.id,u.evidence.dataset,u.evidence.taskIds??[]);(T(p.evidence)!==T(u.evidence)||T(p.form)!==T(u.form))&&Le("human_evidence_revision_changed")},async publication(l,u,p,m){let g=a.get(`${u.id}:${m}`);(!g||g.taskset.id!==p.id||g.taskset.revision!==p.revision||g.taskset.contentHash!==p.contentHash)&&Le("human_task_publication_owner_unavailable")},async completeExecution(l,u,p){(!p||!u.execution?.executionId)&&Le("human_execution_result_required");let m=await e.store.humanReviewLocalEvidence(l.scope,u.execution.executionId);(!m.execution.completedAt||m.execution.counts.pending||m.execution.counts.running)&&Le("human_execution_not_sealed");let g={execution:m.execution,cases:m.cases};(p.id!==m.execution.id||p.revision!==1||p.contentHash!==T(g))&&Le("human_execution_result_stale")},async execution(l,u,p){p.executionId||Le("human_execution_not_bound");let m=await e.store.humanReviewLocalEvidence(l.scope,p.executionId);(m.execution.ownerActorId!==l.actorId||m.execution.operationId!==p.operationId)&&Le("human_execution_binding_conflict");let{expectedRevision:g,...w}=m.released.definition.configuration;T(w)!==p.configurationHash&&Le("human_execution_binding_conflict")},async assignee(l,u,p){u!==l.actorId&&Le("human_local_publish_required",403),await s.evidence(l,p)}},c=e.store.humanReviewRepository(),d=tO(c,s);return{async projectComparison(l){let u={scope:l.scope,actorId:l.actorId};return oO({...l,teamId:l.scope,authorize:i(()=>t(u),"authorize"),async readReview(p){let m=await d.get(u,p.id);return(m.revision!==p.revision||m.contentHash!==p.contentHash)&&Le("human_comparison_review_changed"),(await d.view(u,m)).permissions.owner||Le("human_comparison_owner_required",403),m},async caseIdentity(p){await t(u);let m=await e.store.humanReviewLocalEvidence(l.scope,p.experimentId);(m.execution.ownerActorId!==u.actorId||m.released.definition.configuration.request.project?.id!==l.projectId)&&Le("human_comparison_source_denied",403);let g=m.released.definition.configuration.request.population.find(w=>w.receiptId===p.attemptId);return(!g||g.taskId!==p.taskId)&&Le("human_comparison_receipt_changed"),{caseId:g.taskId,seed:g.seed,fixtureId:g.fixtureId}}})},async request(l){pi(l,1048576);let u=v.object({scope:v.string().min(1)}).parse(l).scope,p={scope:u,actorId:await e.actorId()};await t(p);let m=await c.transaction(u,async h=>{let y=v.object({id:v.string().optional(),command:v.object({id:v.string().optional(),action:v.string(),projectId:v.string().optional(),evidence:_s.optional()}).passthrough().optional(),endpoint:v.string()}).passthrough().parse(l);if(y.command?.action==="create")return y.command.evidence?[{projectId:y.command.projectId,evidence:y.command.evidence}]:[];if(y.id||y.command?.id){let k=await h.get(y.id??y.command.id);return k?[k]:[]}if(y.endpoint!=="inbox")return[];let f=[],S;do{let k=await h.list({afterId:S,limit:100});f.push(...k.items),S=k.nextCursor??void 0}while(S);return f});for(let h of m)if(!h.evidence.attempts.length){let y=await e.localExperiments.readHumanTaskPackage(u,h.projectId,h.evidence.dataset);n.set(o(u,p.actorId,h.projectId,h.evidence.dataset),y)}if(LS.safeParse(l).success){let h=LS.parse(l);return(await e.localExperiments.readHumanTaskPackage(u,h.projectId,h.dataset)).taskset.graders.flatMap(f=>f.kind==="human"&&f.form?[{id:f.id,name:f.rubricRef.id,version:f.version,contentHash:T(f),mode:f.form.mode}]:[])}if(CS.safeParse(l).success){let h=CS.parse(l),y=await e.localExperiments.readHumanTaskPackage(u,h.projectId,h.dataset),f=h.all?y.taskset.tasks.map(S=>S.id):h.taskIds;return f.length>1e3&&Le("human_assignment_batch_limit_1000",422),$_(y,h.graderId,h.dataset,f)}if(HS.safeParse(l).success){let h=HS.parse(l),y=await d.get(p,h.id),f=await d.view(p,y);if(f.permissions.owner||Le("human_task_publication_owner_required",403),y.authorPublication)return y.authorPublication.proposalHash!==h.proposalHash&&Le("human_task_publication_stale"),f;y.revision!==h.expectedRevision&&Le("human_review_revision_stale");let S=n.get(o(u,p.actorId,y.projectId,y.evidence.dataset))??Le("human_task_source_unavailable"),k=await qv({store:e.store,storeDir:e.storeDir,actorId:p.actorId,review:y,proposalHash:h.proposalHash,baseline:S});return a.set(`${y.id}:${h.proposalHash}`,k),d.view(p,await d.command(p,{action:"bind_author_publication",id:y.id,operationId:h.operationId,expectedRevision:h.expectedRevision,proposalHash:h.proposalHash,dataset:{id:k.taskset.id,revision:k.taskset.revision,contentHash:k.taskset.contentHash}}))}if(DS.safeParse(l).success){let h=DS.parse(l),y=await d.get(p,h.id),f=await d.view(p,y);(y.kind!=="author"||!f.permissions.reviewer&&!f.permissions.manager)&&Le("human_task_author_denied",403),h.includeReference&&!f.permissions.owner&&Le("human_reference_read_owner_required",403);let S=n.get(o(u,p.actorId,y.projectId,y.evidence.dataset))??Le("human_task_source_unavailable");return{dataset:y.evidence.dataset,tasks:(y.evidence.taskIds??[]).map(k=>{let I=S.taskset.tasks.find(b=>b.id===k)??Le("human_task_unavailable");return{taskId:k,input:I.input,policyVisibleContext:I.policyVisibleContext,...h.includeReference?{expectedOutput:I.expectedOutput}:{},tags:I.tags}})}}if(jS.safeParse(l).success){let h=jS.parse(l),y=await d.get(p,h.id),f=ya.parse(h.configuration);(f.request.project?.id!==y.projectId||T(f.request.taskset)!==T(y.evidence.dataset)||f.request.population.some(k=>!y.evidence.taskIds?.includes(k.taskId))||new Set(f.request.population.map(k=>k.taskId)).size!==y.evidence.taskIds?.length)&&Le("human_execution_resource_mismatch"),f.graders&&!f.graders.some(k=>k.id===y.evidence.graderBinding.id&&k.version===y.evidence.graderBinding.version&&k.contentHash===y.evidence.graderBinding.contentHash)&&Le("human_execution_grader_mismatch");let S=await nO({service:d,context:p,request:h,configuration:f,dispatch:i(async k=>e.localExperiments.runFromRelease({configuration:k}),"dispatch"),recover:i(async k=>{let I=await e.localExperiments.findRunOperation(u,k.execution.operationId);return I?(await s.execution(p,k,{...k.execution,executionId:I.id}),{id:I.id}):null},"recover"),cancel:i(async k=>{await t(p),await e.localExperiments.cancel({teamId:u,id:k.execution.executionId})},"cancel")});return d.view(p,S)}if(OS.safeParse(l).success){let h=OS.parse(l),y=await d.get(p,h.id),f=await d.view(p,y);return h.action==="cancel"&&!f.permissions.manager&&!f.permissions.reviewer&&Le("human_execution_control_denied",403),y.execution?.executionId||Le("human_execution_not_bound"),h.action==="cancel"?e.localExperiments.cancel({teamId:u,id:y.execution.executionId}):h.action==="result"?(async()=>({...await c.transaction(u,async()=>{let k=await e.store.humanReviewLocalEvidence(u,y.execution.executionId);return k.execution.completedAt||Le("human_execution_not_sealed"),{result:{id:k.execution.id,revision:1,contentHash:T({execution:k.execution,cases:k.cases})}}}),evidence:await e.localExperiments.result({teamId:u,id:y.execution.executionId})}))():e.localExperiments.status({teamId:u,id:y.execution.executionId})}if(MS.safeParse(l).success){let h=MS.parse(l),y=await e.localExperiments.read({teamId:u,id:h.executionId}),f=await c.transaction(u,async k=>{let I=[],b;do{let R=await k.list({afterId:b,limit:100});I.push(...R.items.filter(_=>_.evidence.attempts.some(P=>P.experimentId===h.executionId))),b=R.nextCursor??void 0}while(b);return I}),S=h.selection?await Promise.all(h.selection.map(async k=>{let I=await d.get(p,k.id,k.revision);return I.contentHash!==k.contentHash&&Le("human_result_selection_mismatch"),I})):await Promise.all(f.map(k=>d.get(p,k.id)));return rO({executionId:h.executionId,executionHash:y.executionHash,reviews:S})}if(pG.safeParse(l).success){let h=pG.parse(l);return c.transaction(u,async()=>r(u,p.actorId,h.projectId,h.graderId,h.selections))}if(AS.safeParse(l).success){let h=AS.parse(l),y=await d.get(p,h.id);if(!y.evidence.attempts.length){let k=n.get(o(u,p.actorId,y.projectId,y.evidence.dataset))??Le("human_task_source_unavailable");return(y.evidence.taskIds??[]).map((I,b)=>{let R=k.taskset.tasks.find(_=>_.id===I)??Le("human_task_unavailable");return{reviewId:y.id,reviewRevision:y.revision,evidenceHash:T(y.evidence),slot:R.id,slotIndex:b,input:R.input,output:null,error:null,events:[],eventCount:0,evidenceLimited:!1,nextEventCursor:null}})}h.slot!==void 0&&!y.evidence.attempts[h.slot]&&Le("human_inspection_slot_invalid");let f=await Promise.all(y.evidence.attempts.map((k,I)=>I).filter(k=>h.slot===void 0||k===h.slot).map(k=>uG({store:e.store,experiments:e.localExperiments,scope:u,review:y,slotIndex:k,...h.afterId===void 0?{}:{afterId:h.afterId}})));return(await d.get(p,y.id)).revision!==y.revision&&Le("human_inspection_revision_changed"),f}let g=XM.parse(l);if(g.endpoint==="command"){let h=await d.command(p,g.command);if(g.command.action==="cancel"&&h.execution){let y=await d.get(p,h.id);if(!y.execution?.executionId){let f=await e.localExperiments.findRunOperation(u,y.execution.operationId);if(!f)throw new He("human_execution_admission_recovery_pending",409,"The original execution admission is unavailable. Recover its retained owner outcome before retrying cancellation.");y=await d.command(p,{action:"bind_execution",id:y.id,expectedRevision:y.revision,operationId:`bind-${y.execution.operationId}`,generation:y.generation,runOperationId:y.execution.operationId,configurationHash:y.execution.configurationHash,executionId:f.id})}return await t(p),await e.localExperiments.cancel({teamId:u,id:y.execution.executionId}),d.view(p,y)}return d.view(p,h)}if(g.endpoint==="get")return d.view(p,await d.get(p,g.id,g.revision));let w=await d.inbox(p,g);return{...w,items:await Promise.all(w.items.map(h=>d.view(p,h)))}}}}i(eI,"createLocalHumanReviewRuntime");function mG(e){let t=lG(e),r=e.humanReview??eI(e),n=Z5({resolveAccess:i(async()=>({...await e.resolveAccess(),teamId:await e.teamId()}),"resolveAccess")}),o=X5({...e,authorizeProject:i(async(a,s,c)=>{let d=await e.resolveAccess();await new ir({baseUrl:d.apiBaseUrl,apiKey:d.token,teamId:a}).get(c)},"authorizeProject"),hosted:i(async(a,s)=>Q5(await e.resolveAccess(),a,s),"hosted")});return async(a,s,c,d)=>{if(a==="hosted_alphaedit_publication"){let u=k_.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return H5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async(h,y,f)=>{let S=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:f}),action:"training-alphaedit-result-save",intentHash:y,id:h.operationId});if(S.phase!=="dispatching"||T(S.command)!==T(h))throw new Tt("alphaedit_save_review_required","Recover the original reviewed Model save before dispatch.");let k=vp.parse(S.reviewedIntent);if(T(k.account)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new Tt("alphaedit_save_account_changed","Return to this Model save's original account.");Rr({action:"training-alphaedit-result-save",id:h.operationId,actorId:m,teamId:p,projectId:f,intent:S.reviewedIntent,command:h})},"assertRetained")}).perform(u)}if(a==="hosted_alphaedit_execution"){let u=b_.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return O5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async({action:h,command:y,intentHash:f,projectId:S})=>{let k=`training:${h}-alphaedit`,I=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:S}),action:k,intentHash:f,id:y.operationId});if(I.phase!=="dispatching"||T(I.command)!==T(y))throw new Tt("alphaedit_review_required","Recover the exact reviewed experiment operation before dispatch.");let b=st.parse(v.object({account:v.unknown()}).parse(I.reviewedIntent).account);if(T(b)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new Tt("alphaedit_account_changed","The retained experiment belongs to another original account.");if(Rr({action:k,id:y.operationId,actorId:m,teamId:p,projectId:S,intent:I.reviewedIntent,command:y}),h==="prepare")return null;let R=yp.parse(I.reviewedIntent);return R.preparationOperationId===null?R.execution:null},"assertRetained")}).perform(u)}if(a==="hosted_neuron_training_publication"){let u=R_.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return L5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async(h,y,f)=>{let S=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:f}),action:"training-neuron-training-result-save",intentHash:y,id:h.operationId});if(S.phase!=="dispatching"||T(S.command)!==T(h))throw new Ct("neuron_training_save_review_required","Recover the original reviewed Model save before dispatch.");let k=bp.parse(S.reviewedIntent);if(T(k.account)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new Ct("neuron_training_save_account_changed","Return to this Model save's original account.");Rr({action:"training-neuron-training-result-save",id:h.operationId,actorId:m,teamId:p,projectId:f,intent:S.reviewedIntent,command:h})},"assertRetained")}).perform(u)}if(a==="hosted_neuron_training_execution"){let u=P_.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return D5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async({action:h,command:y,intentHash:f,projectId:S})=>{let k=`training:${h}-neuron-training`,I=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:S}),action:k,intentHash:f,id:y.operationId});if(I.phase!=="dispatching"||T(I.command)!==T(y))throw new Ct("neuron_training_review_required","Recover the exact reviewed experiment operation before dispatch.");let b=st.parse(v.object({account:v.unknown()}).parse(I.reviewedIntent).account);if(T(b)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new Ct("neuron_training_account_changed","The retained experiment belongs to another original account.");if(Rr({action:k,id:y.operationId,actorId:m,teamId:p,projectId:S,intent:I.reviewedIntent,command:y}),h==="prepare")return null;let R=Ip.parse(I.reviewedIntent);return R.preparationOperationId===null?R.execution:null},"assertRetained")}).perform(u)}if(a==="hosted_decision_publication"){let u=T_.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return N5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async(h,y,f)=>{let S=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:f}),action:"training-decision-result-save",intentHash:y,id:h.operationId});if(S.phase!=="dispatching"||T(S.command)!==T(h))throw new Qe("decision_save_review_required","Recover the original reviewed Model save before dispatch.");let k=gp.parse(S.reviewedIntent);if(T(k.account)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new Qe("decision_save_account_changed","Return to this Model save's original account.");Rr({action:"training-decision-result-save",id:h.operationId,actorId:m,teamId:p,projectId:f,intent:S.reviewedIntent,command:h})},"assertRetained")}).perform(u)}if(a==="hosted_engram_publication"){let u=M_.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return q5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async(h,y,f)=>{let S=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:f}),action:"training-engram-result-save",intentHash:y,id:h.operationId});if(S.phase!=="dispatching"||T(S.command)!==T(h))throw new At("engram_save_review_required","Recover the original reviewed Model save before dispatch.");let k=fp.parse(S.reviewedIntent);if(T(k.account)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new At("engram_save_account_changed","Return to this Model save's original account.");Rr({action:"training-engram-result-save",id:h.operationId,actorId:m,teamId:p,projectId:f,intent:S.reviewedIntent,command:h})},"assertRetained")}).perform(u)}if(a==="hosted_steering_publication"){let u=H_.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return z5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async(h,y,f)=>{let S=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:f}),action:"training-steering-result-save",intentHash:y,id:h.operationId});if(S.phase!=="dispatching"||T(S.command)!==T(h))throw new Mt("steering_save_review_required","Recover the original reviewed Model save before dispatch.");let k=pp.parse(S.reviewedIntent);if(T(k.account)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new Mt("steering_save_account_changed","Return to this Model save's original account.");Rr({action:"training-steering-result-save",id:h.operationId,actorId:m,teamId:p,projectId:f,intent:S.reviewedIntent,command:h})},"assertRetained")}).perform(u)}if(a==="hosted_decision_execution"){let u=__.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return B5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async({action:h,command:y,intentHash:f,projectId:S})=>{let k=`training:${h}-decision`,I=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:S}),action:k,intentHash:f,id:y.operationId});if(I.phase!=="dispatching"||T(I.command)!==T(y))throw new Qe("decision_review_required","Recover the exact reviewed experiment operation before dispatch.");let b=st.parse(v.object({account:v.unknown()}).parse(I.reviewedIntent).account);if(T(b)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new Qe("decision_account_changed","The retained experiment belongs to another original account.");if(Rr({action:k,id:y.operationId,actorId:m,teamId:p,projectId:S,intent:I.reviewedIntent,command:y}),h==="prepare")return null;let R=hp.parse(I.reviewedIntent);return R.preparationOperationId===null?R.execution:null},"assertRetained")}).perform(u)}if(a==="hosted_engram_execution"){let u=A_.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return U5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async({action:h,command:y,intentHash:f,projectId:S})=>{let k=`training:${h}-engram`,I=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:S}),action:k,intentHash:f,id:y.operationId});if(I.phase!=="dispatching"||T(I.command)!==T(y))throw new At("engram_review_required","Recover the exact reviewed experiment operation before dispatch.");let b=st.parse(v.object({account:v.unknown()}).parse(I.reviewedIntent).account);if(T(b)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new At("engram_account_changed","The retained experiment belongs to another original account.");if(Rr({action:k,id:y.operationId,actorId:m,teamId:p,projectId:S,intent:I.reviewedIntent,command:y}),h==="prepare")return null;let R=mp.parse(I.reviewedIntent);return R.preparationOperationId===null?R.execution:null},"assertRetained")}).perform(u)}if(a==="hosted_modification_execution"){let u=O_.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return F5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async({action:h,command:y,intentHash:f,projectId:S})=>{let k=`training:${h}-modification`,I=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:S}),action:k,intentHash:f,id:y.operationId});if(I.phase!=="dispatching"||T(I.command)!==T(y))throw new Mt("modification_review_required","Recover the exact reviewed experiment operation before dispatch.");let b=st.parse(v.object({account:v.unknown()}).parse(I.reviewedIntent).account);if(T(b)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new Mt("modification_account_changed","The retained experiment belongs to another original account.");if(Rr({action:k,id:y.operationId,actorId:m,teamId:p,projectId:S,intent:I.reviewedIntent,command:y}),h==="prepare")return null;let R=up.parse(I.reviewedIntent);return R.preparationOperationId===null?R.execution:null},"assertRetained")}).perform(u)}if(a==="hosted_candidate_evaluation"){let u=v.object({teamId:v.string().min(1),id:v.string().min(1).max(200).optional(),action:v.enum(["options","save","read","prepare","run","cancel"]),query:v.object({afterId:v.string().optional(),projectId:v.string().optional()}).strict().optional(),command:v.unknown().optional()}).strict().parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]);if(u.teamId!==p)throw new Error("The active workspace changed. Reopen trained-version evaluation.");let w=J5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId()}),"currentIdentity")});if(u.action==="options")return w.options(u.query??{});if(u.action==="save")return w.save(u.command);let h=v.string().min(1).parse(u.id);return u.action==="read"?w.read(h):w.control(h,u.action,u.command)}if(a==="hosted_training_policy"){let u=v.object({teamId:v.string().min(1),id:v.string().min(1).max(200),afterId:v.string().min(1).max(200).nullable().optional(),command:v.unknown().optional()}).strict().parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]);if(u.teamId!==p)throw new Error("The active workspace changed. Reopen this policy.");let w=D_({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId()}),"currentIdentity")});if(u.command!==void 0){if(v.object({id:v.string()}).passthrough().parse(u.command).id!==u.id)throw new Error("This command belongs to another policy.");return w.policyControl(u.command)}return w.policyRead(u.id,u.afterId??void 0)}if(a==="hosted_training_setup"){let u=v.object({teamId:v.string().min(1),draftInputs:v.boolean().optional(),cursor:v.string().min(1).max(500).nullable().optional(),configurationId:v.string().min(1).max(200).nullable().optional(),projectId:v.string().min(1).max(200).nullable().optional(),action:nP.optional(),command:v.unknown().optional()}).strict().parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]);if(u.teamId!==p)throw new Error("The active workspace changed. Reopen training setup.");let w=D_({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity")});return u.action?w.perform(u.action,u.command):u.draftInputs?w.draftInputs({projectId:u.projectId??null,...u.cursor?{cursor:u.cursor}:{}}):w.catalog({configurationId:v.string().min(1).parse(u.configurationId),projectId:u.projectId??null})}if(a==="experiment_training_handoff"){let u=v.object({teamId:v.string().min(1),executionId:v.string().min(1).max(200),passId:v.string().min(1).max(200).nullable()}).strict().parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]);if(u.teamId!==p)throw new Error("The active workspace changed. Reload this result.");return K5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity")}).read(u.executionId,u.passId)}if(a==="hosted_decision_score"){let u=E_.parse(s),[p,m,g]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]),w=new URL(g.apiBaseUrl).origin;return $5({teamId:p,actorId:m,access:g,currentIdentity:i(async()=>({teamId:await e.teamId(),actorId:await e.actorId(),apiOrigin:(await e.resolveAccess()).apiBaseUrl}),"currentIdentity"),assertRetained:i(async(h,y,f)=>{let S=await e.store.readPendingEvaluationOperation({scopeHash:T({actorId:m,apiOrigin:w,teamId:p,projectId:f}),action:"training-decision-score",intentHash:y,id:h.request.requestId});if(S.phase!=="dispatching"||T(S.command)!==T(h))throw new Qe("decision_score_review_required","Recover the original reviewed typed score before dispatch.");let k=wp.parse(S.reviewedIntent);if(T(k.account)!==T({teamId:p,actorId:m,apiOrigin:w}))throw new Qe("decision_score_account_changed","Return to this score's original account.");Rr({action:"training-decision-score",id:h.request.requestId,actorId:m,teamId:p,projectId:f,intent:S.reviewedIntent,command:h})},"assertRetained")}).perform(u)}if(a==="execution_activity")return o(s);if(a!=="human_review")return t(a,s,c,d);let l=c?.searchParams.get("location")??"hosted";if(l==="local")return jh.safeParse(s).success?G5({...e,hosted:n},s,d):Ch.safeParse(s).success?Kv(e,s):Ah.safeParse(s).success?W5({...e,hosted:n},s,d):Mh.safeParse(s).success?V5(e,s):r.request(s);if(l==="hosted")return n.request(s,d);throw new Error("Choose a valid review execution location.")}}i(mG,"createReviewAndActivityTransport");import Uue from"node:path";function fG(e){let t=bh(Uue.join(e.storeDir,"library","harnesses","experiment-improvement-budget.sqlite"));t.exec(`CREATE TABLE IF NOT EXISTS improvement_calls(candidate_id TEXT NOT NULL,request_id TEXT NOT NULL,actor_id TEXT NOT NULL,team_id TEXT NOT NULL,request_hash TEXT NOT NULL,source_hash TEXT NOT NULL,configuration_hash TEXT NOT NULL,maximum_usd REAL NOT NULL,status TEXT NOT NULL,cost_usd REAL,usage TEXT,created_at TEXT NOT NULL,completed_at TEXT,PRIMARY KEY(candidate_id,request_id));
|
|
62
62
|
CREATE TABLE IF NOT EXISTS improvement_call_receipts(candidate_id TEXT NOT NULL,request_id TEXT NOT NULL,content_hash TEXT NOT NULL,payload TEXT NOT NULL,PRIMARY KEY(candidate_id,request_id));`);async function r(o,a){let s=await e.store.getTurn(a.id),c=await e.store.getSession(o.id),d=s?.metadata.refinementCandidate;if(!s||!c||s.sessionId!==o.id||s.status!=="in_progress"||s.metadata.source!=="experiment-improvement"||!d||typeof d!="object"||!("candidateId"in d)||typeof d.candidateId!="string")throw new Error("Candidate inference has no actual admitted Work turn.");let l={actorId:await e.actorId(),teamId:await e.teamId()},u=await e.improvements.read(l,d.candidateId);if(u.status!=="authoring"||!u.work||u.work.sessionId!==o.id||u.work.turnId!==a.id||T(d)!==T({candidateId:u.id,authoringRevision:u.work.revision,...l})||T(c.currentProfile)!==T(u.profileRef))throw new Error("Candidate inference source or owner changed.");let p=await e.improvements.partition(l,u.id);return{actor:l,state:u,partition:p,turn:s}}i(r,"authority");let n=e.stream??ki;return{async resolveSessionModelStream(o,a){let s=await e.store.getTurn(a.id);if(s?.metadata.source!=="experiment-improvement"&&s?.metadata.refinementCandidate===void 0)return null;let c=await r(o,a),d=c.turn.modelRef??o.modelRef;if(o.provider!=="openpond"||d?.providerId!=="openpond"||!d.modelId)throw new Error("Candidate Work requires an explicitly selected OpenPond hosted-tool model.");let l=await Ra({kind:"hosted_chat",modelId:d.modelId,maxOutputTokens:4096,temperature:0,topP:1});return async function*(u){let p=await r(o,a),m=p.state.id,g=u.requestId;if(!g||u.model!==l.model.modelId)throw new Error("Candidate inference changed its admitted request/model identity.");let w=p.state.limits.maximumDurationMs-(Date.now()-Date.parse(p.state.work.startedAt));if(w<=0)throw new Error("Candidate Work reached its admitted duration limit.");if(u.maxTokens!==void 0&&u.maxTokens>l.model.maxOutputTokens)throw new Error("Candidate inference exceeds its admitted output token ceiling.");let h=new AbortController,y=setTimeout(()=>h.abort(new Error("Candidate authoring duration limit reached.")),w),f=u.signal?AbortSignal.any([u.signal,h.signal]):h.signal,S={...u,maxTokens:Math.min(u.maxTokens??l.model.maxOutputTokens,l.model.maxOutputTokens),temperature:l.model.temperature,topP:l.model.topP,signal:f},{signal:k,...I}=S,b=T(I),R=T({state:p.state.contentHash,partition:p.partition.contentHash}),_=!1,P=!1,x=!1,E=null;try{t.exec("BEGIN IMMEDIATE");try{if(t.prepare("SELECT 1 FROM improvement_calls WHERE candidate_id=? AND request_id=?").get(m,g))throw new Error("This candidate request already has an immutable dispatch receipt; never redispatch an uncertain call.");let C=t.prepare("SELECT status,cost_usd,maximum_usd FROM improvement_calls WHERE candidate_id=? AND actor_id=? AND team_id=?").all(m,p.actor.actorId,p.actor.teamId);if(C.some(j=>!["settled","not_dispatched"].includes(String(j.status))))throw new Error("Reconcile the pending or unknown candidate inference charge before another paid call.");let A=C.reduce((j,H)=>j+(H.status==="not_dispatched"?0:Number(H.cost_usd)),0);if(C.length+p.state.authoringSteps>=p.state.limits.maximumAuthoringSteps||A+l.maximumChargeUsd>p.state.limits.maximumCostUsd)throw new Error("Candidate authoring reached its admitted call or cost ceiling.");t.prepare("INSERT INTO improvement_calls(candidate_id,request_id,actor_id,team_id,request_hash,source_hash,configuration_hash,maximum_usd,status,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)").run(m,g,p.actor.actorId,p.actor.teamId,b,R,l.model.configurationHash,l.maximumChargeUsd,"reserved",new Date().toISOString()),t.exec("COMMIT"),_=!0}catch(C){throw t.exec("ROLLBACK"),C}await r(o,a),f.throwIfAborted(),t.prepare("UPDATE improvement_calls SET status='dispatched' WHERE candidate_id=? AND request_id=? AND status='reserved'").run(m,g),P=!0;for await(let C of n(S))await r(o,a),f.throwIfAborted(),C.type==="usage"&&(E=C.usage),C.type==="finish"&&(x=!0),yield C}finally{clearTimeout(y),h.abort();let C=t.prepare("SELECT * FROM improvement_calls WHERE candidate_id=? AND request_id=?").get(m,g);if(_&&C&&C.status!=="settled"&&C.status!=="unknown"&&C.status!=="not_dispatched"){let A=jd(E),j=P&&x&&A.promptTokens!==null&&A.completionTokens!==null&&l.pricing?ey(E,l.pricing):null,H=P?j===null?"unknown":"settled":"not_dispatched",L=new Date().toISOString(),B={schemaVersion:"openpond.improvementModelCall.v1",candidateId:m,requestId:g,actorId:p.actor.actorId,teamId:p.actor.teamId,requestHash:b,sourceHash:R,configurationHash:l.model.configurationHash,maximumUsd:l.maximumChargeUsd,status:H,costUsd:j,usage:E===null?null:A,completedAt:L},q=T(B);t.exec("BEGIN IMMEDIATE");try{t.prepare("UPDATE improvement_calls SET status=?,cost_usd=?,usage=?,completed_at=? WHERE candidate_id=? AND request_id=?").run(H,j,JSON.stringify(B.usage),L,m,g),t.prepare("INSERT INTO improvement_call_receipts(candidate_id,request_id,content_hash,payload) VALUES(?,?,?,?)").run(m,g,q,JSON.stringify({...B,contentHash:q})),t.exec("COMMIT")}catch(W){throw t.exec("ROLLBACK"),W}}}}},close:i(()=>t.close(),"close")}}i(fG,"createExperimentImprovementBudget");function hG(e){return async(t,r,n,o,a)=>{if(!r.projectId||r.actorId!==t.actorId||r.teamId!==t.teamId)throw new Error("human_comparison_owner_changed");await e.authorize(t,r);let s=await e.humanReview().projectComparison({scope:t.teamId,actorId:t.actorId,projectId:r.projectId,selections:n,baseline:o,candidate:a});return await e.authorize(t,r),s}}i(hG,"createAcceptedHumanComparisonProjector");function gG(e){async function t(u){if(await e.actorId()!==u.actorId||await e.teamId()!==u.teamId)throw new Error("Improvement account or workspace changed.")}i(t,"current");let r=Hi({store:e.store,storeDir:e.storeDir,resolveAccess:i(async()=>({...await e.resolveAccess(),actorId:await e.actorId(),teamId:await e.teamId()}),"resolveAccess")});async function n(u,p){await t(u);let m;if(p.id.startsWith("local-"))m=(await e.localExperiments().compare({teamId:u.teamId,baselineId:p.id,candidateId:p.id})).baseline;else{let w=await e.resolveAccess(),h=new Jr({baseUrl:w.apiBaseUrl,apiKey:w.token,teamId:u.teamId});m=p.id.startsWith("score_")?await h.scoringResult(p.id):await h.result(p.id)}let g=pj(m);if(g.manifest.id!==p.id||g.result.contentHash!==p.contentHash||g.manifest.teamId!==u.teamId)throw new Error("Improvement evidence differs from its actual owner result.");return await t(u),g}i(n,"loadEvidence");let o=i(async(u,p,m,g,w)=>{await t(u),await Yr(e.store,p.currentChannel.release,m,(y,f,S)=>r.authority(y,f,S,{requireCurrentRevision:w.requireCurrentBase}));let h=await St(m);if(m.source==="local"){if(h.error||h.activeProfile!==m.profileId||h.mode!=="local"||!h.repoPath||!h.sourcePath)throw new Error("The original Profile is not installed for this owner.");let f=(await e.store.getHarnessReleaseRecord(p.currentChannel.release.contentHash))?.harnessRelease.metadata.profile;if(w.requireCurrentBase&&(!h.git?.head||h.git.dirty||h.git.head!==f?.sourceRevision))throw new Error("Commit or reconcile the changed original Profile before authoring this candidate.")}if(g){let y=await e.resolveAccess();if((await new ir({apiKey:y.token,baseUrl:y.apiBaseUrl,teamId:u.teamId}).get(g)).archived)throw new Error("The selected Project is archived.")}await t(u)},"authorizeOwner"),a=e.humanReview?hG({humanReview:e.humanReview,authorize:i(async(u,p)=>{let m=await e.store.getHarnessWorkspace(p.ownerWorkspaceId);if(!m)throw new Error("The original Human comparison owner is unavailable.");await o(u,m,p.profileRef,p.projectId,{requireCurrentBase:!1})},"authorize")}):void 0,s=_q({...e,authorizeOwner:o,projectHumanComparison:a,loadEvidence:n}),c=fG({...e,improvements:s}),d=Eq({...e,improvements:s,loadProfile:St}),l=EW({...e,improvements:s,authorizeBaseOrigin:r.authority});return{service:s,loadEvidence:n,tools:d,candidateOrigins:l,resolveSessionModelStream:c.resolveSessionModelStream,close:i(async()=>{await s.close(),c.close()},"close")}}i(gG,"createExperimentImprovementRuntime");import{promises as cr}from"node:fs";import Zr from"node:path";import{randomUUID as que}from"node:crypto";var N_=v.object({schemaVersion:v.literal("openpond.candidateProfileGitIntent.v1"),operationId:v.string(),actorId:v.string(),teamId:v.string(),candidateId:v.string(),stateFrozenHash:v.string(),repo:v.string(),branch:v.string(),expectedCommit:v.string().regex(/^[a-f0-9]{40}$/),commit:v.string().regex(/^[a-f0-9]{40}$/),testedRelease:v.object({id:v.string(),contentHash:v.string()}).strict(),createdAt:v.string(),contentHash:v.string()}).strict();function wG(e){let t=Zr.join(e.storeDir,"library","harnesses","profile-adoptions");async function r(p,m){if(p.actorId!==m.actorId||p.teamId!==m.teamId||await e.actorId()!==p.actorId||await e.teamId()!==p.teamId)throw new Error("Profile adoption owner changed.")}i(r,"authorize");function n(p,m){return Zr.join(t,T([p.actorId,p.teamId,m]))}i(n,"location");async function o(p,m){await cr.mkdir(Zr.dirname(p),{recursive:!0,mode:448});let g=`${p}.${que()}.tmp`,w=await cr.open(g,"wx",384);try{await w.writeFile(ot(m)),await w.sync()}finally{await w.close()}await cr.rename(g,p);let h=await cr.open(Zr.dirname(p),"r");try{await h.sync()}finally{await h.close()}}i(o,"atomic");async function a(p){let m=p.agentSnapshot.metadata.workspaceId,g=await Cd({workspaceId:typeof m=="string"?m:p.workspaceId,sourceDir:Zr.join(p.bundlePath,"source")});if(g.harnessRelease.contentHash!==p.harnessRelease.contentHash||g.sourceRevision!==p.sourceRevision)throw new Error("Released candidate source changed.");return g}i(a,"compiled");async function s(p){let m=await e.store.getHarnessReleaseRecord(p.baseRelease.contentHash);if(!m||m.harnessRelease.id!==p.baseRelease.id)throw new Error("Original baseline release is unavailable.");return a(m)}i(s,"baseline");async function c(p){return(await cr.readFile(`/proc/${p}/stat`,"utf8").catch(()=>null))?.split(") ")[1]?.split(" ")[19]??null}i(c,"processStart");async function d(p,m){await cr.mkdir(t,{recursive:!0,mode:448});let g=Zr.join(t,`owner-${T(p)}.lock`),w;try{w=await cr.open(g,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h;let y=await cr.readFile(g,"utf8"),f=v.object({pid:v.number().int().positive(),start:v.string().nullable(),createdAt:v.string()}).strict().parse(JSON.parse(y));if(f.start===null||await c(f.pid)===f.start)throw new Error("Another Profile source operation holds this owner; await its durable receipt.");let S=await cr.open(`${g}.reclaim`,"wx",384);try{if(await cr.readFile(g,"utf8")!==y)throw new Error("Profile owner lock changed during recovery.");await cr.rm(g),w=await cr.open(g,"wx",384)}finally{await S.close(),await cr.rm(`${g}.reclaim`)}}try{return await w.writeFile(ot({pid:process.pid,start:await c(process.pid),createdAt:new Date().toISOString()})),await w.sync(),await m()}finally{await w.close(),await cr.rm(g)}}i(d,"withLock");async function l(p,m,g){let w=await cr.readFile(Zr.join(n(p,g),"intent.json"),"utf8").catch(S=>{if(S.code==="ENOENT")return null;throw S});if(!w)return null;let h=N_.parse(JSON.parse(w)),{contentHash:y,...f}=h;if(T(f)!==y||h.actorId!==p.actorId||h.teamId!==p.teamId||h.candidateId!==m.id||h.operationId!==g||h.stateFrozenHash!==T(m.frozen))throw new Error("Original Profile adoption intent differs from its exact tested revision.");return h}i(l,"readIntent");async function u(p,m,g){await r(p,m);let w=await Op(m,e.loadProfile);if(w.repo!==g.repo||await or(w.repo,["symbolic-ref","-q","HEAD"])!==g.branch)throw new Error("The original Profile Git owner or selected branch changed.");let h=await or(w.repo,["rev-parse","HEAD"]);if(h===g.expectedCommit)await xa(w.repo,g.expectedCommit),await r(p,m),await or(w.repo,["update-ref",g.branch,g.commit,g.expectedCommit]);else if(h!==g.commit)throw new Error("The original Profile changed after its adoption intent; reconcile the exact owner revision.");let y=await or(w.repo,["write-tree"]),f=await or(w.repo,["rev-parse",`${g.expectedCommit}^{tree}`]),S=await or(w.repo,["rev-parse",`${g.commit}^{tree}`]);if(y===f){if(await or(w.repo,["diff-files","--name-only"]))throw new Error("Source edits prevent recovery of the committed Profile adoption.");await or(w.repo,["read-tree","-u","-m",g.expectedCommit,g.commit])}else if(y!==S)throw new Error("The Profile index changed during adoption; reconcile it before recovering.");await xa(w.repo,g.commit),await r(p,m);let k=await(e.loadProfile??St)(m.profileRef),I=await s(m),b=await Ei({...e,state:m,profile:k,sourceRevision:g.commit,base:I}),R=await e.store.getHarnessReleaseRecord(g.testedRelease.contentHash);if(!R||R.harnessRelease.id!==g.testedRelease.id)throw new Error("The tested release is unavailable during adoption readback.");let _=zw(await a(R),b,g.commit),P=await Ad({...e,ref:m.profileRef,profile:k,reloadProfile:i(()=>(e.loadProfile??St)(m.profileRef),"reloadProfile")});if(P.harnessRelease.contentHash!==b.harnessRelease.contentHash)throw new Error("The active compiled Profile differs from the qualified original source.");let x=pU({schemaVersion:"openpond.candidateProfileAdoption.v1",id:`profile-adoption-${T([p,g.operationId]).slice(0,40)}`,operationId:g.operationId,...p,candidateId:m.id,testedCandidateRelease:g.testedRelease,activeRelease:P.harnessRelease,expectedCommit:g.expectedCommit,committedProfileGit:g.commit,equivalence:_,createdAt:g.createdAt});return await o(Zr.join(n(p,g.operationId),"receipt.json"),x),{receipt:{id:x.id,contentHash:x.contentHash},activeRelease:x.activeRelease,testedCandidateRelease:x.testedCandidateRelease,executableSourceHash:_.contentHash,protectedClosureHash:_.protectedClosureHash}}return i(u,"finish"),{async freezeProfile(p,m,g){if(await r(p,m),m.profileRef.source==="openpond_git"){let f=await s(m),S=await a(g.release);return Aq({...e,state:m},async k=>{if((await Ei({...e,state:m,profile:k.profile,sourceRevision:m.baseProfileSourceRevision,base:f})).harnessRelease.contentHash!==m.baseRelease.contentHash)throw new Error("The committed remote Profile archive differs from the exact baseline.");await sy({...k,state:m,base:f,candidate:S});let b=await Ei({...e,state:m,profile:await Du(k.root,m.profileRef.profileId),sourceRevision:g.profileSourceRevision,base:f});if(oo(b).protectedClosureHash!==oo(f).protectedClosureHash)throw new Error("Candidate authoring changed the actual remote protected closure.");let R=await WP({...e,workspaceId:g.release.workspaceId,compiled:b,createdAt:g.release.createdAt});return{...g,release:R,executableIdentity:oo(b)}})}let w=await Op(m,e.loadProfile,!0);await xa(w.repo,m.baseProfileSourceRevision);let h=await s(m),y=await a(g.release);return iy({...e,state:m,commit:m.baseProfileSourceRevision,allowRemoteSnapshot:!0},async f=>{if((await Ei({...e,state:m,profile:f.profile,sourceRevision:m.baseProfileSourceRevision,base:h})).harnessRelease.contentHash!==m.baseRelease.contentHash)throw new Error("The original Profile no longer compiles to the admitted baseline.");await sy({...f,state:m,base:h,candidate:y});let k=await _h({repoPath:f.root,profileId:m.profileRef.profileId}),I=await Ei({...e,state:m,profile:k,sourceRevision:g.profileSourceRevision,base:h});if(oo(I).protectedClosureHash!==oo(h).protectedClosureHash)throw new Error("The authored Profile changed its protected evaluator closure.");let b=await WP({...e,workspaceId:g.release.workspaceId,compiled:I,createdAt:g.release.createdAt});return await r(p,m),await xa(w.repo,m.baseProfileSourceRevision),{...g,release:b,executableIdentity:oo(I)}})},async readAdoption(p,m,g){await r(p,m);let w=await l(p,m,g);return w?d(w.repo,()=>u(p,m,w)):null},async adopt(p,m,g,w){await r(p,m);let h=await Op(m,e.loadProfile);return d(h.repo,async()=>{let y=await l(p,m,w);if(y)return u(p,m,y);await xa(h.repo,m.baseProfileSourceRevision);let f=await or(h.repo,["symbolic-ref","-q","HEAD"]);if(!f.startsWith("refs/heads/"))throw new Error("Select the original Profile branch before adopting.");let S=await s(m),k=await a(g),I=await iy({...e,state:m,commit:m.baseProfileSourceRevision},async _=>{let P=await sy({..._,state:m,base:S,candidate:k});if(!P.length)throw new Error("The candidate has no original Profile source changes to adopt.");await or(_.root,["add","--",...P.map(C=>Zr.join(Zr.relative(_.root,_.source),C))]),await or(_.root,["-c","core.hooksPath=/dev/null","-c","commit.gpgSign=false","commit","-m",`Adopt tested Experiment candidate ${m.id}`],{GIT_AUTHOR_NAME:"OpenPond",GIT_AUTHOR_EMAIL:"profile-candidate@openpond.local",GIT_COMMITTER_NAME:"OpenPond",GIT_COMMITTER_EMAIL:"profile-candidate@openpond.local"});let x=await or(_.root,["rev-parse","HEAD"]),E=await _h({repoPath:_.root,profileId:m.profileRef.profileId});return zw(k,await Ei({...e,state:m,profile:E,sourceRevision:x,base:S}),x),x});await r(p,m),await xa(h.repo,m.baseProfileSourceRevision);let b={schemaVersion:"openpond.candidateProfileGitIntent.v1",operationId:w,...p,candidateId:m.id,stateFrozenHash:T(m.frozen),repo:h.repo,branch:f,expectedCommit:m.baseProfileSourceRevision,commit:I,testedRelease:{id:g.harnessRelease.id,contentHash:g.harnessRelease.contentHash},createdAt:new Date().toISOString()},R=N_.parse({...b,contentHash:T(b)});return await o(Zr.join(n(p,w),"intent.json"),R),u(p,m,R)})},async rollback(p,m,g){if(await r(p,m),!m.acceptance||!m.adoptionIntent)throw new Error("Only an accepted exact Profile adoption can be rolled back.");let w=uR.parse(JSON.parse(await cr.readFile(Zr.join(n(p,m.adoptionIntent.operationId),"receipt.json"),"utf8"))),{contentHash:h,...y}=w;if(T(y)!==h||w.actorId!==p.actorId||w.teamId!==p.teamId||w.candidateId!==m.id||h!==m.acceptance.contentHash)throw new Error("The accepted adoption receipt changed.");let f=await Op(m,e.loadProfile);return d(f.repo,async()=>{let S=await l(p,m,g);if(S)return u(p,m,S);await xa(f.repo,w.committedProfileGit);let k=await or(f.repo,["symbolic-ref","-q","HEAD"]),I=await s(m),b=await iy({...e,state:m,commit:w.committedProfileGit},async P=>{await or(P.root,["-c","core.hooksPath=/dev/null","revert","--no-commit",w.committedProfileGit]),await or(P.root,["-c","core.hooksPath=/dev/null","-c","commit.gpgSign=false","commit","-m",`Roll back tested Experiment candidate ${m.id}`],{GIT_AUTHOR_NAME:"OpenPond",GIT_AUTHOR_EMAIL:"profile-candidate@openpond.local",GIT_COMMITTER_NAME:"OpenPond",GIT_COMMITTER_EMAIL:"profile-candidate@openpond.local"});let x=await or(P.root,["rev-parse","HEAD"]),E=await _h({repoPath:P.root,profileId:m.profileRef.profileId});return zw(I,await Ei({...e,state:m,profile:E,sourceRevision:x,base:I}),x),x});await r(p,m),await xa(f.repo,w.committedProfileGit);let R={schemaVersion:"openpond.candidateProfileGitIntent.v1",operationId:g,...p,candidateId:m.id,stateFrozenHash:T(m.frozen),repo:f.repo,branch:k,expectedCommit:w.committedProfileGit,commit:b,testedRelease:m.baseRelease,createdAt:new Date().toISOString()},_=N_.parse({...R,contentHash:T(R)});return await o(Zr.join(n(p,g),"intent.json"),_),u(p,m,_)})},async adoptionReceipt(p,m,g){await r(p,m);let w=uR.parse(JSON.parse(await cr.readFile(Zr.join(n(p,g),"receipt.json"),"utf8"))),{contentHash:h,...y}=w;if(T(y)!==h||w.actorId!==p.actorId||w.teamId!==p.teamId||w.candidateId!==m.id)throw new Error("Adoption receipt owner or integrity changed.");return w}}}i(wG,"createLocalProfileGitCandidateAdoption");import{promises as zue}from"node:fs";import{randomUUID as Wue}from"node:crypto";import{promises as Fue}from"node:fs";import{randomUUID as yG}from"node:crypto";function vG(e){async function t(l){return(await Fue.readFile(`/proc/${l}/stat`,"utf8").catch(()=>null))?.split(") ")[1]?.split(" ")[19]??null}i(t,"processStart");async function r(l,u){let p={actorId:l.actorId,teamId:l.teamId};l=await e.improvements.read(p,l.id);let m={kind:u,token:yG(),pid:process.pid,processStart:await t(process.pid),startedAt:new Date().toISOString()};l=await e.improvements.beginTestDispatch(p,l.id,l.revision,m);try{if(!l.frozen||!l.test||l.test.cancelRequestedAt)throw new Error("The candidate test has no durable frozen recipe.");let{recipe:g}=l.test,w=u==="baseline"?l.test.baselineOperationId:l.test.candidateOperationId,h=u==="baseline"?{sourceRevision:l.baseProfileSourceRevision,harnessRelease:l.baseRelease}:{sourceRevision:l.frozen.profileSourceRevision,harnessRelease:l.frozen.release},y=Zh.parse(await e.localExperiments().request({teamId:l.teamId,projectId:l.projectId,action:"prepareHarness",payload:{operationId:w,profileRepositoryId:l.profileRef.repositoryId,profileRef:l.profileRef,profileSource:h,definitionId:ej(g.externalDatasetBinding),externalDatasetBinding:g.externalDatasetBinding,modelId:g.modelId,maximumCostUsd:g.maximumCostUsd}}));if(T(y.request.taskset)!==T(g.externalDatasetBinding.dataset)||y.request.policy.kind!=="hosted_harness"||T(y.request.policy.source.harnessRelease)!==T(h.harnessRelease)||T(y.request.policy.source.externalDatasetBinding)!==T(g.externalDatasetBinding))throw new Error("The prepared run changed the exact target source or selected Dataset recipe.");let f=g.scoring?y.graders.map(k=>({id:k.id,version:k.version,contentHash:k.contentHash,mappings:k.mappings??[]})):g.externalDatasetBinding.evaluators.map(k=>{let I=y.graders.find(b=>b.feedbackKey===k.feedbackKey&&T(b.release??{id:b.id,revision:b.version,contentHash:b.contentHash})===T(k.release));if(!I)throw new Error("The prepared run changed its selected grader release.");return{id:I.id,version:I.version,contentHash:I.contentHash,mappings:g.externalDatasetBinding.fieldMappings.find(b=>b.graderId===I.id)?.fields??[]}}),S=await e.improvements.read(p,l.id);if(S.test?.cancelRequestedAt||S.test?.dispatching?.token!==m.token)throw new Error("The owner cancelled test admission before dispatch.");return await e.localExperiments().request({teamId:l.teamId,projectId:l.projectId,action:"runFromRelease",payload:{configuration:{operationId:w,request:{...y.request,name:`${u==="baseline"?"Baseline":"Candidate"} ${l.id}`},maximumCostUsd:g.maximumCostUsd,graders:f},expectedPackageHash:g.externalDatasetBinding.packageHash}})}finally{let g=await e.improvements.read(p,l.id);g.status==="testing"&&g.test?.dispatching?.token===m.token&&await e.improvements.endTestDispatch(p,l.id,g.revision,m.token)}}i(r,"execute");function n(l,u){if(!l.test)throw new Error("The test is not admitted.");return`local-run-${T([l.teamId,l.actorId,u==="baseline"?l.test.baselineOperationId:l.test.candidateOperationId]).slice(0,48)}`}i(n,"executionId");function o(l,u){return`local-score-${T([l.teamId,`improve-grade-${T([l.id,l.test.recipeHash,u]).slice(0,40)}`]).slice(0,48)}`}i(o,"scoringId");async function a(l){let u=l.test?.recipe.scoring;if(!u)return;await e.improvements.read({actorId:l.actorId,teamId:l.teamId},l.id);let p=await e.resolveAccess(),m=new Jr({baseUrl:p.apiBaseUrl,apiKey:p.token,teamId:l.teamId}),g=await m.scoringPass(u.sourcePass.id);if(g.contentHash!==u.sourcePass.contentHash||g.status!=="completed"||g.id!==l.evidence.manifest.lineage?.scoringPassId||T(g.request.graders)!==T(u.graders)||T(g.request.mappings??[])!==T(u.mappings??[]))throw new Error("The original selected grading changed.");await e.improvements.read({actorId:l.actorId,teamId:l.teamId},l.id)}i(a,"originalScoring");async function s(l){if(!l.test?.cancelRequestedAt)for(let u of["baseline","candidate"])try{await e.localExperiments().status({teamId:l.teamId,id:n(l,u)})}catch(p){if(!(p instanceof oe)||p.code!=="local_execution_not_found")throw p;await r(l,u)}}i(s,"recover");async function c(l){if(!l.test?.cancelRequestedAt)throw new Error("Persist the cancellation intent before stopping test dispatch.");for(let u of["baseline","candidate"])for(let p of[n(l,u),...l.test.recipe.scoring?[o(l,u)]:[]])try{await e.localExperiments().status({teamId:l.teamId,id:p}),await e.localExperiments().cancel({teamId:l.teamId,id:p})}catch(m){if(!(m instanceof oe)||m.code!=="local_execution_not_found")throw m}}i(c,"cancel");async function d(l,u){let p=await e.improvements.read(l,u.id);if(p.actorId!==l.actorId||p.teamId!==l.teamId||p.status!=="testing"||!p.test||p.test.cancelRequestedAt)throw new Error("The current paired Human comparison is unavailable.");let m=e.localExperiments();for(let h of["baseline","candidate"]){let y=await m.status({teamId:l.teamId,id:n(p,h)});if(y.status!=="completed"||!y.cleanupComplete)throw new Error("Wait for both original target executions and cleanup before selecting Human assessments.");if(p.test.recipe.scoring){let f=await m.status({teamId:l.teamId,id:o(p,h)});if(f.status!=="completed"||!f.cleanupComplete)throw new Error("Wait for both original selected grading passes before selecting Human assessments.")}}let g=await m.compare({teamId:l.teamId,baselineId:p.test.recipe.scoring?o(p,"baseline"):n(p,"baseline"),candidateId:p.test.recipe.scoring?o(p,"candidate"):n(p,"candidate")}),w=await e.improvements.read(l,p.id);if(w.revision!==p.revision||w.test?.cancelRequestedAt)throw new Error("The test changed during accepted Human discovery.");return CH(w,{baseline:g.baseline,candidate:g.candidate})}return i(d,"readComparison"),{execute:r,executionId:n,recover:s,cancel:c,readComparison:d,async settle(l,u){if(u.status!=="testing"||!u.test)return u;if(u.test.dispatching){let k=u.test.dispatching;if(k.processStart===null||await t(k.pid)===k.processStart)return u;u=await e.improvements.endTestDispatch(l,u.id,u.revision,k.token)}if(u.test.cancelRequestedAt){await c(u);let k=!1;for(let I of["baseline","candidate"])for(let b of[n(u,I),...u.test.recipe.scoring?[o(u,I)]:[]])try{let R=await e.localExperiments().status({teamId:l.teamId,id:b});(!["completed","failed","cancelled","interrupted"].includes(R.status)||!R.cleanupComplete)&&(k=!0)}catch(R){if(!(R instanceof oe)||R.code!=="local_execution_not_found")throw R}return k?u:e.improvements.failTesting(l,u.id,u.revision,"The owner cancelled the exact paired test. Missing executions were never dispatched; retained admitted executions completed cleanup.",!0)}if(await s(u),u=await e.improvements.read(l,u.id),u.status!=="testing")return u;if(u.test?.cancelRequestedAt)return this.settle(l,u);let p=n(u,"baseline"),m=n(u,"candidate"),g=e.localExperiments(),[w,h]=await Promise.all([g.status({teamId:l.teamId,id:p}),g.status({teamId:l.teamId,id:m})]);if(w.status!=="completed"||h.status!=="completed"){let k=new Set(["completed","failed","cancelled","interrupted"]);return k.has(w.status)&&k.has(h.status)&&w.cleanupComplete&&h.cleanupComplete?e.improvements.failTesting(l,u.id,u.revision,`The actual baseline/candidate test ended ${w.status}/${h.status}; inspect retained output and grader evidence before creating a new candidate.`,w.status==="cancelled"||h.status==="cancelled"):u}let y=p,f=m;if(u.test.recipe.scoring){await a(u);let k=u.test.recipe.scoring;for(let[I,b]of[["baseline",p],["candidate",m]]){let R=await e.improvements.read(l,u.id);if(R.test?.cancelRequestedAt)return this.settle(l,R);let _=await g.status({teamId:l.teamId,id:b}),P={kind:I,token:yG(),pid:process.pid,processStart:await t(process.pid),startedAt:new Date().toISOString()};u=await e.improvements.beginTestDispatch(l,u.id,R.revision,P);let x;try{if((await e.improvements.read(l,u.id)).test?.cancelRequestedAt)throw new Error("The owner cancelled selected grading before admission.");x=await g.scoreSelected(l.teamId,{operationId:`improve-grade-${T([u.id,u.test.recipeHash,I]).slice(0,40)}`,execution:{id:b,executionHash:_.executionHash},graders:k.graders,mappings:k.mappings,maximumCostUsd:k.maximumCostUsd})}finally{let E=await e.improvements.read(l,u.id);E.test?.dispatching?.token===P.token&&(u=await e.improvements.endTestDispatch(l,u.id,E.revision,P.token))}if(!["completed","failed","cancelled","interrupted"].includes(x.status)||!x.cleanupComplete)return u;if(x.status!=="completed")return e.improvements.failTesting(l,u.id,u.revision,"The selected local grading pass did not complete.",x.status==="cancelled")}y=o(u,"baseline"),f=o(u,"candidate")}let S=await g.compare({teamId:l.teamId,baselineId:y,candidateId:f});return[...S.baseline.result.cases,...S.candidate.result.cases].some(k=>k.feedback.some(I=>I.status!=="scored"))?u:e.improvements.completeComparison(l,u.id,u.revision,S.baseline,S.candidate)}}}i(vG,"createExperimentImprovementTesting");function IG(e){let t=e.runtime.service,r=vG({improvements:t,localExperiments:e.localExperiments,resolveAccess:e.resolveAccess}),n=new Map,o=Dv(e);return i(async function(s){let c=v.object({teamId:v.string().min(1),request:TH}).strict().parse(s),d=c.request,l={actorId:await e.actorId(),teamId:await e.teamId()};if(!l.actorId||l.teamId!==c.teamId)throw new Error("Select the signed-in Improve workspace.");if(d.operation==="options")return o(l,d.evidence);if(d.operation==="list")return t.list(l,d.limit,d.cursor);if(d.operation==="start")return t.start(l,d.request);let u=await t.read(l,d.id);if(d.operation==="read"){if(u.status==="authoring"&&u.work){let p=await e.store.getTurn(u.work.turnId);p&&p.status!=="in_progress"&&(u=await t.finishAuthoring(l,u.id,u.revision))}return u.status==="testing"&&(u=await r.settle(l,u)),u.status==="adopting"&&u.adoptionIntent&&(u=await t.useCandidate(l,u.id,u.revision)),u}if(d.operation==="humanComparisonOptions")return r.readComparison(l,u);if(d.operation==="instructions"){let p=await t.partition(l,u.id),m=await A$(p.sourceRoot,u.component.path),g=await zue.readFile(m);if(g.length>25e4)throw new Error("The selected instruction source exceeds the editor size limit.");let w=g.toString("utf8");if(u.component.kind==="workflow"){let h=JSON.parse(w),y=h.workflows?.find(f=>f.id===u.component.workflowId);if(y?.invocation?.kind!=="instructions")throw new Error("This Workflow requires code authoring through Work.");w=y.invocation.instructions}return{candidateId:u.id,candidateRevision:u.revision,path:u.component.path,text:w,textHash:Ee(w),contentHash:Ee(g)}}if(!("revision"in d)||u.revision!==d.revision)throw new Error("The candidate changed; reload its current revision.");if(d.operation==="mode")return t.setMode(l,u.id,d.revision,d.mode);if(d.operation==="edit")return t.edit(l,u.id,d.revision,d.expectedFileHash,d.text);if(d.operation==="freeze")return t.freeze(l,u.id,u.revision);if(d.operation==="finishAuthoring")return t.finishAuthoring(l,u.id,u.revision);if(d.operation==="useCandidate")return t.useCandidate(l,u.id,u.revision);if(d.operation==="rollback")return t.rollback(l,u.id,u.revision);if(d.operation==="discard")return t.discard(l,u.id,u.revision);if(d.operation==="cancel")return u.status==="authoring"&&u.work&&(await e.interruptSessionTurn(u.work.sessionId,"The owner cancelled candidate authoring."),u=await t.finishAuthoring(l,u.id,(await t.read(l,u.id)).revision)),u.status==="testing"?(u=await t.cancelTesting(l,u.id,u.revision),await r.cancel(u),r.settle(l,u)):t.discard(l,u.id,u.revision,!0);if(d.operation==="compare"){let p=await e.localExperiments().compare({teamId:l.teamId,baselineId:d.baseline.id,candidateId:d.candidate.id});if(p.baseline.result.contentHash!==d.baseline.contentHash||p.candidate.result.contentHash!==d.candidate.contentHash)throw new Error("The compared execution evidence changed.");return t.completeComparison(l,u.id,u.revision,p.baseline,p.candidate,d.humanSelections)}if(d.operation==="test")return u=await t.beginTesting(l,u.id,u.revision,d.recipe),await r.execute(u,"baseline"),await r.execute(u,"candidate"),t.read(l,u.id);if(d.operation==="author"){if(u.mode!=="llm_assisted"||u.status!=="draft"||n.has(u.id))throw new Error("Start authoring only a settled LLM candidate draft.");let p=await t.partition(l,u.id),m=await e.createSession({experience:"work",provider:"openpond",modelRef:{providerId:"openpond",modelId:d.modelId},title:`Improve ${u.component.kind}`,hiddenFromDefaultSidebar:!0,cwd:p.sourceRoot,currentProfile:u.profileRef,cloudTeamId:l.teamId,metadata:{source:"experiment-improvement",candidateId:u.id}}),g=Wue(),w,h,y=new Promise((S,k)=>{w=S,h=k}),f=e.sendTurn(m.id,{prompt:d.prompt,modelRef:{providerId:"openpond",modelId:d.modelId}},g,{beforeExecute:i(async(S,k)=>{if(S.id!==m.id||k.id!==g)throw new Error("The actual candidate Work admission changed.");let I={candidateId:u.id,authoringRevision:u.revision+1,...l};k.metadata={...k.metadata,source:"experiment-improvement",refinementCandidate:I},await e.store.updateTurn(k.id,b=>({...b,metadata:{...b.metadata,source:"experiment-improvement",refinementCandidate:I}})),await t.bindAuthoringTurn(l,u.id,u.revision,m.id,g),w()},"beforeExecute")});return n.set(u.id,f),f.catch(h).finally(async()=>{n.delete(u.id);let S=await t.read(l,u.id).catch(()=>null);S?.status==="authoring"&&await t.finishAuthoring(l,S.id,S.revision).catch(()=>{})}),await y,t.read(l,u.id)}throw new Error("Unknown Improve lifecycle operation.")},"payload")}i(IG,"createExperimentImprovementPayload");function bG(e){let t,r,n=i(()=>{if(!t)throw new Error("The canonical local Experiment owner is not ready.");return r??=eI({...e,localExperiments:t.localExperiments})},"humanReview"),o=wG(e),a=m5({...e,local:o}),s=gG({...e,...a,humanReview:n,localExperiments:i(()=>{if(!t)throw new Error("Experiment evidence is not ready.");return t.localExperiments},"localExperiments")});try{t=j5({...e,candidateOrigins:s.candidateOrigins});let c=mG({...e,localExperiments:t.localExperiments,humanReview:n()}),d=IG({...e,runtime:s,localExperiments:i(()=>t.localExperiments,"localExperiments")}),{executeCandidateWorkspaceTool:l,...u}=s.tools;return{...t,improvements:s,trainingPayload:c,experimentImprovementPayload:d,turnTools:u,executeCandidateWorkspaceTool:l}}catch(c){throw Promise.allSettled([s.close(),...t?[t.localExperiments.close()]:[]]),c}}i(bG,"createCoordinatedEvaluationRuntime");var Ua=class extends Error{constructor(r,n,o){super(o);this.code=r;this.status=n}code;status;static{i(this,"ModificationRecordingError")}},U_=v.string().trim().min(1).max(240);function kG(e){async function t(n){let[o,a,s]=await Promise.all([e.teamId(),e.actorId(),e.resolveAccess()]);if(n!==o)throw new Ua("modification_recording_scope_mismatch",403,"Choose the current workspace.");return{teamId:n,actorId:a,accountScopeHash:await Xe({teamId:n,actorId:a,apiOrigin:new URL(s.apiBaseUrl).origin})}}i(t,"scope");async function r(n){if((await t(n.teamId)).accountScopeHash!==n.accountScopeHash)throw new Ua("modification_recording_account_changed",409,"The active account changed. Reopen this observation.")}return i(r,"fence"),{async record(n){let o=await nD(n),a=await t(o.teamId),s={request:o.request,result:o.result},c={schemaVersion:"openpond.modificationRecording.v1",id:`observation-${await Xe({scope:a.accountScopeHash,operationId:o.operationId})}`,...a,operationId:o.operationId,commandHash:await Xe(o),name:o.name,projectId:o.projectId,method:o.method,custody:"local",provenance:"external_observation",measurementAttestation:"unattested",model:o.request.model,inputHash:await Xe(o.request),resultHash:o.result.contentHash,artifact:{contentHash:await Xe(s),sizeBytes:Buffer.byteLength(me(s))},counts:{prompts:o.request.prompts.length,variants:o.request.variants.length,outcomes:o.result.outcomes.length,captures:o.result.captures.length},createdAt:new Date().toISOString()},d=Z1.parse({...c,contentHash:await Xe(c)});await r(a);let l;try{l=await e.store.retainModificationRecording(a,{recording:d,document:s})}catch(u){throw u instanceof Error&&u.message==="modification_recording_operation_conflict"?new Ua(u.message,409,"This operation already retains different observation settings. Retry its original request."):u}return await r(a),(await aD(l,a.teamId,a.actorId)).recording},async read(n,o){let a=await t(U_.parse(o)),s=await e.store.readModificationRecording(a,U_.parse(n));if(await r(a),!s)throw new Ua("modification_recording_not_found",404,"Observation not found in this account.");if(s.recording.accountScopeHash!==a.accountScopeHash)throw new Error("modification_recording_scope_corrupt");return s},async list(n){let o=tD.parse(n),a=await t(o.teamId),s=await Xe({...a,projectId:o.projectId??null,search:o.search??""}),c;if(o.cursor)try{let l=v.object({version:v.literal(1),scopeHash:v.string(),afterId:U_}).strict().parse(JSON.parse(Buffer.from(o.cursor,"base64url").toString()));if(l.scopeHash!==s)throw new Error("scope");c=l.afterId}catch{throw new Ua("modification_recording_cursor_invalid",400,"Refresh the observation list before continuing.")}let d=await e.store.listModificationRecordings(a,{...o,afterId:c});await r(a);for(let l of d.items)if(await oD(l,a.teamId,a.actorId),l.accountScopeHash!==a.accountScopeHash)throw new Error("modification_recording_scope_corrupt");return rD.parse({...a,projectId:o.projectId??null,items:d.items,nextCursor:d.hasMore?Buffer.from(JSON.stringify({version:1,scopeHash:s,afterId:d.items.at(-1).id})).toString("base64url"):null})}}}i(kG,"createLocalModificationRecordings");function SG(e){return{async actorId(){let t=await e.account();if(t.state!=="signed_in"||!t.profile?.id)throw new Error("Sign in before accessing this workspace.");return t.profile.id},async teamId(){let t=(await e.defaultTeam())?.trim();if(!t)throw new Error("Select a workspace before accessing its reviews, Experiments or training.");return t}}}i(SG,"createCurrentWorkspaceIdentity");async function PG(e,t){let r=t.manifest.profileEvaluation;if(!r)throw new Error("Saved experiment has no Profile source.");let n={profileRef:t.profileRef,sourceRevision:r.sourceRevision,harnessRelease:r.harnessRelease},o=i(()=>un({store:e.store,ref:t.profileRef,...n}),"loadCatalog"),a;if(r.externalDatasetBinding){let s=await e.resolveExternalDataset(r.externalDatasetBinding,n);await s.authorize();let c=await Ww({manifest:t.manifest,taskset:s.packageValue.taskset,selected:n,loadCatalog:o,resolveExternalDataset:e.resolveExternalDataset});if(!c)throw new Error("The saved experiment's external Dataset owner is unavailable.");a=c.packageValue}else{let c=(await o()).definitions.find(d=>d.id===r.definitionId&&T(d)===r.definitionHash);if(!c)throw new Error("Saved experiment definition differs from its frozen Profile release.");a=await Sa({store:e.store,storeDir:e.home,definition:c,profileId:t.profileRef.profileId,harnessRelease:r.harnessRelease})}if(a.contentHash!==t.manifest.packageHash)throw new Error("Saved experiment Dataset differs from its frozen package pin.");return a}i(PG,"loadChatProfilePackage");function RG(e){async function t(c){let d=await e.selectedProfileRef();if(!d||T(d)!==T(c))throw new Error("Select the Profile that owns this saved experiment.");return d}i(t,"authorize");async function r(c){let d=await e.loadPackage(c),l=d.taskset.metadata,u=typeof l.sourceTasksetId=="string"&&typeof l.sourcePackageHash=="string"?await e.store.readLocalDatasetByWorkspaceHash(l.sourceTasksetId,l.sourcePackageHash):null;if(u&&u.ownerId===await e.store.localResourceOwnerId())return[kr(u),...Ud(u).map(g=>({...g,rows:[]}))];let p=d.taskset;return[{kind:"dataset",id:p.id,revision:p.revision,name:p.id,state:"Pinned",profileRef:c.profileRef,contentHash:p.contentHash,taskCount:c.manifest.population.length,graderCount:p.graders.length,rows:[]},...p.graders.map(g=>({kind:"grader",id:`grader-${T([p.id,g.id]).slice(0,40)}`,revision:p.revision,name:Sr(d).find(w=>w.id===g.id)?.name??g.id,state:"Pinned",profileRef:c.profileRef,contentHash:T(g),graderId:g.id,graderType:g.kind,datasetId:p.id,datasetRevision:p.revision,description:`Version ${g.version}`,rows:[]}))]}i(r,"inputs");async function n(c,d){let l=await e.store.getProfileEvaluationRun(c);if(!l||d&&T(l.profileRef)!==T(d))throw new Error("Saved Profile experiment was not found for this owner.");await t(l.profileRef);let u=await Qw({store:e.store,profileRef:l.profileRef,runId:l.manifest.id}),p=await r(l),m=p.find(f=>f.kind==="dataset"),g=u.cases.filter(f=>f.gradingStatus==="scored"&&f.score!==null),w=u.cases.filter(f=>f.passed===!1),h={kind:"experiment",id:l.manifest.id,revision:1,name:l.manifest.profileEvaluation.definitionId,state:"completed",location:"local",profileRef:l.profileRef,contentHash:l.contentHash,model:l.manifest.policy.kind==="model"?`${l.manifest.policy.model.provider}/${l.manifest.policy.model.model}`:void 0,datasetId:m.id,datasetRevision:m.revision,taskCount:l.manifest.population.length,graderCount:p.length-1,scoreLabel:l.metric.policy.aggregation==="pass_rate"?"Pass rate":"Task metric",score:l.metric.value,evaluatedCount:g.length,failedCount:w.length,ungradedCount:u.cases.length-g.length,costUsd:l.manifest.policy.kind==="model"&&l.manifest.policy.model.provider==="codex"?null:u.cases.every(f=>f.costUsd!==null)?u.cases.reduce((f,S)=>f+S.costUsd,0):null,rows:u.cases.slice(0,3).map(f=>({id:f.receiptId,label:f.taskId,detail:f.failureClass??f.gradingStatus,score:f.score}))},y={contentHash:l.contentHash,scope:l.manifest.contentHash,graders:null,cases:u.cases.map(f=>({id:f.receiptId,taskId:f.taskId,seed:f.seed,status:f.gradingStatus,output:null,error:f.failureClass,score:f.score}))};return await t(l.profileRef),{summary:h,inputs:p,evidence:u,view:y}}i(n,"inspect");async function o(c){let{invocationToken:d,...l}=v.object({invocationToken:v.string().optional()}).passthrough().parse(c),u=d?await e.resolveInvocation(d):null,p=await e.execute(l);if(u){await t(p.profileRef);let m=await e.selectedProfile();if(T(m.ref)!==T(p.profileRef)||m.sourceRevision!==p.manifest.profileEvaluation.sourceRevision)throw new Error("Profile source changed before chat attachment.");let g=await n(p.manifest.id,p.profileRef);await e.attach(u,[...g.inputs,g.summary])}return p}i(o,"request");async function a(c){if(c===void 0)return e.discover();let{invocationToken:d,...l}=v.object({invocationToken:v.string().optional()}).passthrough().parse(c),u=d?await e.resolveInvocation(d):null,p=await e.discover(l);if(u&&typeof l.runId=="string"&&await e.store.getProfileEvaluationRun(l.runId)){let m=await n(l.runId);await e.attach(u,[...m.inputs,m.summary])}return p}i(a,"discover");async function s(c){let{invocationToken:d,...l}=v.object({invocationToken:v.string().optional()}).passthrough().parse(c),u=d?await e.resolveInvocation(d):null,p=await e.prepare(l);if(u){let m=await e.selectedProfile(),g=p.manifest.profileEvaluation;if(await t(m.ref),!g||g.profileId!==m.ref.profileId||g.sourceRevision!==m.sourceRevision||l.profileRef&&T(l.profileRef)!==T(m.ref))throw new Error("Prepared inputs belong to another Profile source.");await e.attach(u,await r({profileRef:m.ref,manifest:p.manifest}))}return p}return i(s,"prepare"),{request:o,inspect:n,authorize:t,discover:a,prepare:s}}i(RG,"createChatProfileExperiments");function xG(e){let t=i(async()=>{let d=await e.workflows();return{ref:d.profileRef,sourceRevision:d.sourceRevision}},"selectedEvaluationProfile"),r=i(d=>un({...d,store:e.store}),"loadCatalog"),n=i((d,l,u)=>Sa({store:e.store,storeDir:e.storeDir,definition:d,profileId:l,harnessRelease:u}),"loadTasksetPackage"),o=IU({...e,loadCatalog:r,selectedProfile:t,loadTasksetPackage:n,resolveExternalDataset:e.resolveExternalDataset}),a=bU({store:e.store,loadCatalog:r,selectedProfile:t,executeCase:o,loadTasksetPackage:n,resolveExternalDataset:e.resolveExternalDataset,privateGrading:i((d,l,u)=>RU({manifest:d,packageValue:l,signal:u,authorize:i(async()=>{let p=await t(),m=d.profileEvaluation;if(!m||p.ref.profileId!==m.profileId||p.sourceRevision!==m.sourceRevision)throw new Error("The private grading Profile authority changed.");let g=await r({...p,harnessRelease:m.harnessRelease});if(m.externalDatasetBinding){let w=await Ww({manifest:d,taskset:l.taskset,selected:{profileRef:p.ref,sourceRevision:p.sourceRevision,harnessRelease:m.harnessRelease},loadCatalog:r,resolveExternalDataset:e.resolveExternalDataset});if(!w||w.packageValue.contentHash!==l.contentHash)throw new Error("The private grading external Dataset owner changed.")}else if(g.catalogHash!==m.catalogHash)throw new Error("The private grading catalog changed.")},"authorize")}),"privateGrading")}),s=i(async d=>a(await e.prepare(d,{requireExpectedManifestHash:!0})),"profileEvaluationRunPayload"),c=kU({store:e.store,loadCatalog:r,selectedWorkflows:e.workflows,prepareRun:e.prepare,executeRun:a});return{selectedEvaluationProfile:t,executeProfileEvaluationCase:o,executeProfileEvaluationRun:a,profileEvaluationRunPayload:s,profileEvaluationRunSuitePayload:c}}i(xG,"createProfileEvaluationRuntime");import si from"node:path";import{randomUUID as f0}from"node:crypto";import{promises as FTe}from"node:fs";function _G(e){Lq(e).catch(t=>{console.error(t instanceof Error?t.stack??t.message:String(t)),process.exit(1)})}i(_G,"runOpenPondServerCliEntrypoint");function EG({home:e,safeUpsertModelUsageRecord:t,streamOpenPondHostedChatTurn:r,localByokRuntimeState:n,providerSecretPaths:o}){return i(async function(s){let c={recorder:null,finalized:!1};async function d(l){!c.recorder||c.finalized||(c.finalized=!0,await c.recorder.fail(l,l instanceof Error&&l.name==="AbortError"?"interrupted":"failed"))}i(d,"failUsageRecorder");try{let l=await f2({session:s.session,events:s.events,provider:s.provider,model:s.model,maxContextTokens:s.maxContextTokens,streamCompactionChatTurn:i(async function*(u){await Sh(e,s.configuration),c.recorder=await h2({session:s.session,turn:null,provider:s.provider,model:u.model??s.model??"unknown",requestId:s.requestId,requestOrdinal:0,requestKind:"context_compaction",upsert:t});try{if(s.route==="openpond_hosted"){for await(let m of r({model:u.model,messages:u.messages,requestId:u.requestId,signal:u.signal}))m.type==="text_delta"&&m.text&&c.recorder.observeDelta({text:m.text}),m.type==="reasoning_delta"&&m.text&&c.recorder.observeDelta({reasoningText:m.text}),m.type==="usage"&&c.recorder.observeDelta({usage:m.usage}),m.type==="text_delta"&&m.text&&(yield{text:m.text,raw:m.raw}),m.type==="reasoning_delta"&&m.text&&(yield{reasoningText:m.text,raw:m.raw}),m.type==="usage"&&(yield{usage:m.usage,raw:m.raw});return}let p=await n();for await(let m of Tw({providerId:u.provider,settings:p.settings,secrets:p.secrets,modelId:u.model,messages:u.messages,requestId:u.requestId,promptCacheKey:s.session.id,signal:u.signal,saveChatGptSubscriptionCredential:i(async(g,w)=>{await Fs({paths:o,providerId:g,credential:w,expected:p.secrets.providers[g]??{},timestamp:ye()})},"saveChatGptSubscriptionCredential")}))m.type==="text_delta"&&m.text&&c.recorder.observeDelta({text:m.text}),m.type==="reasoning_delta"&&m.text&&c.recorder.observeDelta({reasoningText:m.text}),m.type==="usage"&&c.recorder.observeDelta({usage:m.usage}),m.type==="text_delta"&&m.text&&(yield{text:m.text,raw:m.raw}),m.type==="reasoning_delta"&&m.text&&(yield{reasoningText:m.text,raw:m.raw}),m.type==="usage"&&(yield{usage:m.usage,raw:m.raw})}catch(p){throw await d(p),p}},"streamCompactionChatTurn")});return c.recorder&&!c.finalized&&(c.finalized=!0,await c.recorder.complete()),l}catch(l){throw await d(l),l}},"runRecordedManualHostedContextCompaction")}i(EG,"createManualCompactionRecorder");import{promises as Yo}from"node:fs";import uc from"node:path";var TG=xn(jne(),1);function tI(e,t){if(!/^[a-z][a-z0-9_-]{0,119}$/.test(t))throw new Error("Invalid Profile Workflow identity.");return uc.join(e,"workflows",t)}i(tI,"packageDirectory");function CG(e){let t=JM.parse({name:e.name,description:e.description,...e.skillPaths.length?{skillPaths:e.skillPaths}:{},...e.assetPaths?.length?{assetPaths:e.assetPaths}:{}});if(!e.instructions.trim())throw new Error("Profile Workflow prompt is empty.");return`---
|
|
63
63
|
${(0,TG.stringify)(t)}---
|