openpond 0.2.61 → 0.2.63
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/README.md +2 -0
- package/dist/app-server.d.ts +4713 -477
- package/dist/app-server.js +1 -1
- package/dist/chunks/{acp-FUAWCKBH.js → acp-H3MJCPHX.js} +1 -1
- package/dist/chunks/{acp-agent-XBSJ27KI.js → acp-agent-DWA7272M.js} +1 -1
- package/dist/chunks/actions-command-IIYOO4LL.js +2 -0
- package/dist/chunks/{app-layer-4BFMOMKM.js → app-layer-K7H2WJ56.js} +1 -1
- package/dist/chunks/app-server-connected-apps-RM5E2VWF.js +2 -0
- package/dist/chunks/{app-server-evaluations-HAAYVEXB.js → app-server-evaluations-XGMGS67X.js} +1 -1
- package/dist/chunks/app-server-harness-services-BHD6S5II.js +2 -0
- package/dist/chunks/app-server-runtime-LFIL6F7D.js +2 -0
- package/dist/chunks/apps-QKAHJGQ4.js +2 -0
- package/dist/chunks/chunk-25XXZS3E.js +2 -0
- package/dist/chunks/chunk-27JGS3KB.js +12 -0
- package/dist/chunks/{chunk-KK626T3Z.js → chunk-2EPR4HLF.js} +1 -1
- package/dist/chunks/{chunk-HN2ZK6EV.js → chunk-2HAWOMZK.js} +1 -1
- package/dist/chunks/chunk-2LJCJOJ7.js +2 -0
- package/dist/chunks/{chunk-BDCTN4PU.js → chunk-2V4LPUBH.js} +1 -1
- package/dist/chunks/{chunk-CN5OXQ7A.js → chunk-3YXYBYWK.js} +1 -1
- package/dist/chunks/{chunk-LHENAWLH.js → chunk-42V4NV2F.js} +1 -1
- package/dist/chunks/{chunk-DW3GJRY3.js → chunk-4FNCBA3Y.js} +1 -1
- package/dist/chunks/{chunk-TXBIZDXG.js → chunk-4L6DU6Z2.js} +1 -1
- package/dist/chunks/{chunk-BFKYRQMA.js → chunk-4N4EH3RJ.js} +1 -1
- package/dist/chunks/{chunk-MLTKB5G3.js → chunk-4SZ3HKHU.js} +1 -1
- package/dist/chunks/{chunk-SCCYSPQ5.js → chunk-4ZBOYWQ3.js} +1 -1
- package/dist/chunks/chunk-5EP2DZLJ.js +2 -0
- package/dist/chunks/chunk-5FU5RLML.js +2 -0
- package/dist/chunks/{chunk-TH6Y4K5Z.js → chunk-5MHYGMJG.js} +1 -1
- package/dist/chunks/chunk-6EBCS57F.js +2 -0
- package/dist/chunks/chunk-6RS4NAOY.js +2 -0
- package/dist/chunks/chunk-6XSSM4WT.js +3 -0
- package/dist/chunks/{chunk-NVHZRKXB.js → chunk-7HRLWPPZ.js} +1 -1
- package/dist/chunks/chunk-7O6Z3VOZ.js +2 -0
- package/dist/chunks/{chunk-BQUWZRWU.js → chunk-7WYL2IDD.js} +1 -1
- package/dist/chunks/chunk-7YLXGILH.js +2 -0
- package/dist/chunks/chunk-7ZLXFKRI.js +2 -0
- package/dist/chunks/{chunk-M6JRS5PA.js → chunk-ABF3W2MO.js} +1 -1
- package/dist/chunks/{chunk-TTN63EAM.js → chunk-AH26AQN7.js} +1 -1
- package/dist/chunks/chunk-AHOBCBVZ.js +2 -0
- package/dist/chunks/chunk-AZ7BL5FL.js +2 -0
- package/dist/chunks/{chunk-3DVWJCOA.js → chunk-B4RKHHF7.js} +1 -1
- package/dist/chunks/chunk-B5R53U74.js +2 -0
- package/dist/chunks/chunk-BKEDG3A4.js +22 -0
- package/dist/chunks/{chunk-CO3OJFPU.js → chunk-BPZOABMC.js} +1 -1
- package/dist/chunks/{chunk-5VPU7OS7.js → chunk-BSPFY3Y5.js} +1 -1
- package/dist/chunks/{chunk-U4HZD2GM.js → chunk-BU27SLZP.js} +2 -2
- package/dist/chunks/chunk-C2AXMKK4.js +2 -0
- package/dist/chunks/{chunk-SIV5P6JO.js → chunk-C2LAEGOW.js} +2 -2
- package/dist/chunks/{chunk-ORLJJGZZ.js → chunk-CZ5R4JXZ.js} +1 -1
- package/dist/chunks/{chunk-D4JZALZ4.js → chunk-DABBHWSF.js} +1 -1
- package/dist/chunks/{chunk-ROE24PN5.js → chunk-DLANLLKH.js} +1 -1
- package/dist/chunks/{chunk-57RY3LSR.js → chunk-DQI5TE6A.js} +2 -2
- package/dist/chunks/chunk-DTTFUANI.js +12 -0
- package/dist/chunks/{chunk-VBW2X42G.js → chunk-DUL6DXOI.js} +1 -1
- package/dist/chunks/{chunk-OQUKSRU3.js → chunk-ELX7VRSU.js} +1 -1
- package/dist/chunks/chunk-ERL2M773.js +3 -0
- package/dist/chunks/chunk-ERT32RZA.js +86 -0
- package/dist/chunks/{chunk-RPOD6I64.js → chunk-EZRUWIP6.js} +1 -1
- package/dist/chunks/{chunk-MCIIGQT7.js → chunk-F6UQ6PPK.js} +1 -1
- package/dist/chunks/chunk-F7QTIHXX.js +2 -0
- package/dist/chunks/chunk-FAKDGLZQ.js +8 -0
- package/dist/chunks/{chunk-BWY4D3BN.js → chunk-FVRII5XO.js} +1 -1
- package/dist/chunks/{chunk-GEXKTGLY.js → chunk-FYYYECHE.js} +50 -48
- package/dist/chunks/chunk-G32BO6M5.js +4 -0
- package/dist/chunks/{chunk-TSAW2QVU.js → chunk-G6OR5NB6.js} +1 -1
- package/dist/chunks/{chunk-65SM7Y2G.js → chunk-GGJUWIGR.js} +1 -1
- package/dist/chunks/{chunk-Q66LWQGF.js → chunk-GPL2Z65R.js} +1 -1
- package/dist/chunks/{chunk-LNRFRAV5.js → chunk-GS6ZUSIN.js} +2 -2
- package/dist/chunks/{chunk-OFVUN4KI.js → chunk-GVARQXYI.js} +1 -1
- package/dist/chunks/chunk-GXCUH2VV.js +17 -0
- package/dist/chunks/{chunk-IUGK6BBY.js → chunk-GXZCMO6S.js} +1 -1
- package/dist/chunks/{chunk-CLFYRN46.js → chunk-H6C4MAUN.js} +1 -1
- package/dist/chunks/{chunk-SGK4GR44.js → chunk-HFJUXKT5.js} +1 -1
- package/dist/chunks/{chunk-I3W27VK4.js → chunk-HUCBKXTU.js} +1 -1
- package/dist/chunks/{chunk-P4XM7LUT.js → chunk-IHB5GTOJ.js} +2 -2
- package/dist/chunks/{chunk-U447MS3Y.js → chunk-IWWXIUAQ.js} +1 -1
- package/dist/chunks/chunk-J572ANHX.js +13 -0
- package/dist/chunks/{chunk-CGAL7IHZ.js → chunk-J7ZTPXRQ.js} +1 -1
- package/dist/chunks/chunk-JCLTFDVW.js +2 -0
- package/dist/chunks/{chunk-25RDE7DV.js → chunk-JEISPWWM.js} +1 -1
- package/dist/chunks/{chunk-ELYRVTTG.js → chunk-JORRZ4BB.js} +1 -1
- package/dist/chunks/{chunk-H2AUR7OT.js → chunk-JQRMDFF3.js} +1 -1
- package/dist/chunks/chunk-JSQRLLN6.js +2 -0
- package/dist/chunks/chunk-KCOTDUGW.js +2 -0
- package/dist/chunks/{chunk-NK4JKB7C.js → chunk-KHTAAVC2.js} +1 -1
- package/dist/chunks/{chunk-CM5USMXN.js → chunk-KOKX7PBS.js} +1 -1
- package/dist/chunks/{chunk-3ZWLRBYZ.js → chunk-KUPJNBWG.js} +1 -1
- package/dist/chunks/{chunk-MHYI7ATG.js → chunk-LK2K3SPM.js} +2 -2
- package/dist/chunks/{chunk-FJ3HMHT6.js → chunk-LKKMLBOH.js} +1 -1
- package/dist/chunks/{chunk-BNZTJPK7.js → chunk-LSZJ5M3X.js} +1 -1
- package/dist/chunks/chunk-M3FLEZ4E.js +4 -0
- package/dist/chunks/{chunk-4LZLO4OW.js → chunk-M3SCON53.js} +1 -1
- package/dist/chunks/{chunk-VPDG2V2R.js → chunk-MEGKXGW3.js} +1 -1
- package/dist/chunks/{chunk-TYHCBVQT.js → chunk-MILEWROZ.js} +1 -1
- package/dist/chunks/chunk-MPNJ2BB4.js +2 -0
- package/dist/chunks/{chunk-VFLSBDNZ.js → chunk-N33D7KCW.js} +1 -1
- package/dist/chunks/chunk-N42HT64M.js +2 -0
- package/dist/chunks/{chunk-L3GA2CQI.js → chunk-N4VHLJBZ.js} +1 -1
- package/dist/chunks/chunk-NEJLJ2XY.js +2 -0
- package/dist/chunks/chunk-NG2L6D7G.js +2 -0
- package/dist/chunks/{chunk-7EAWLYYB.js → chunk-NLYZ5K7U.js} +2 -2
- package/dist/chunks/{chunk-B47JMAVW.js → chunk-NT7N6KLE.js} +1 -1
- package/dist/chunks/{chunk-6MWT6BVU.js → chunk-NWQL6FNF.js} +1 -1
- package/dist/chunks/{chunk-PAZDQRYU.js → chunk-NZTCH6K5.js} +1 -1
- package/dist/chunks/{chunk-CQF6QZEL.js → chunk-OG33QAG6.js} +1 -1
- package/dist/chunks/chunk-OTUBJV6C.js +6 -0
- package/dist/chunks/{chunk-TMMFF6DO.js → chunk-PBTXLQAU.js} +1 -1
- package/dist/chunks/chunk-Q34IF4PW.js +2 -0
- package/dist/chunks/{chunk-I3X6M6ZO.js → chunk-QJ6KUVAR.js} +1 -1
- package/dist/chunks/{chunk-SID4X3YN.js → chunk-QU4UE73E.js} +1 -1
- package/dist/chunks/{chunk-I7JCARVH.js → chunk-R6VJDOQM.js} +3 -3
- package/dist/chunks/{chunk-6RVF2J47.js → chunk-R6WMY6AH.js} +1 -1
- package/dist/chunks/{chunk-ZUNG6YDO.js → chunk-RDSVU6F6.js} +1 -1
- package/dist/chunks/{chunk-R4PDSOB4.js → chunk-RFMME46Z.js} +1 -1
- package/dist/chunks/{chunk-GQUS7MCH.js → chunk-RZUCVF2Q.js} +1 -1
- package/dist/chunks/chunk-SFKZITAG.js +9 -0
- package/dist/chunks/{chunk-MF35MALN.js → chunk-SHJY5RLU.js} +1 -1
- package/dist/chunks/chunk-SI5W5LBV.js +2 -0
- package/dist/chunks/chunk-SO42ZB5K.js +2 -0
- package/dist/chunks/{chunk-TNHDD3LO.js → chunk-SXMR6E2W.js} +1 -1
- package/dist/chunks/{chunk-OMICIPPY.js → chunk-T6JN4PND.js} +1 -1
- package/dist/chunks/{chunk-ZISYLRH6.js → chunk-TCOTXCV6.js} +1 -1
- package/dist/chunks/{chunk-QCSLEMZF.js → chunk-U2K7QJCG.js} +1 -1
- package/dist/chunks/{chunk-ISIXFK6U.js → chunk-UH4JSSRL.js} +28 -28
- package/dist/chunks/chunk-UPWJSNL5.js +2 -0
- package/dist/chunks/chunk-URNMC46H.js +157 -0
- package/dist/chunks/{chunk-OJFDI7VM.js → chunk-UTNGEMW5.js} +1 -1
- package/dist/chunks/{chunk-WFVOG5PU.js → chunk-V7KR74NO.js} +1 -1
- package/dist/chunks/{chunk-QDBYLJGH.js → chunk-VHXDWAEH.js} +1 -1
- package/dist/chunks/{chunk-VZXZ6CHS.js → chunk-W2TICQ62.js} +1 -1
- package/dist/chunks/{chunk-QRJPLZF7.js → chunk-W5W4IODW.js} +1 -1
- package/dist/chunks/chunk-WP2L2NY2.js +2 -0
- package/dist/chunks/chunk-WSOUMXH3.js +24 -0
- package/dist/chunks/chunk-WWQNMC7C.js +6 -0
- package/dist/chunks/chunk-XMHIQ3SK.js +5 -0
- package/dist/chunks/{chunk-5MTN6KXV.js → chunk-XNOMIWEY.js} +1 -1
- package/dist/chunks/{chunk-T4LLJC5N.js → chunk-XOB6FKQV.js} +1 -1
- package/dist/chunks/chunk-Y766IN7Y.js +2 -0
- package/dist/chunks/chunk-YCZZ62C2.js +2 -0
- package/dist/chunks/chunk-YM4PSVFW.js +4 -0
- package/dist/chunks/chunk-YNQWJWIC.js +10 -0
- package/dist/chunks/{chunk-LBBXVOVR.js → chunk-Z3BWCFLV.js} +1 -1
- package/dist/chunks/{chunk-WRQEYW3V.js → chunk-ZG6353RM.js} +1 -1
- package/dist/chunks/{chunk-PE7UKJXK.js → chunk-ZPTKR3GB.js} +1 -1
- package/dist/chunks/{chunk-2VXL6AU3.js → chunk-ZYVHOVKL.js} +1 -1
- package/dist/chunks/chunk-ZZHXQCNB.js +22 -0
- package/dist/chunks/cli-PSXMIJTF.js +2 -0
- package/dist/chunks/{configuration-command-ONGI2BJD.js → configuration-command-XYKMXIWF.js} +1 -1
- package/dist/chunks/connected-app-executor-6G2LA3PQ.js +2 -0
- package/dist/chunks/connected-evidence-IRXYN6YD.js +2 -0
- package/dist/chunks/{connected-starting-assets-OXLT7S4O.js → connected-starting-assets-JONPTII6.js} +1 -1
- package/dist/chunks/{connection-HJWE6SEW.js → connection-XMAAGMXJ.js} +1 -1
- package/dist/chunks/{continual-CJUZM5ZQ.js → continual-Z7MO2PF6.js} +1 -1
- package/dist/chunks/core-commands-WWN7X3XC.js +2 -0
- package/dist/chunks/dataset-preparation-authoring-F3OZIQSP.js +4 -0
- package/dist/chunks/datasets-2PC2HP7N.js +2 -0
- package/dist/chunks/desktop-test-VU6AFAMO.js +3 -0
- package/dist/chunks/dist-47AYOIH6.js +2 -0
- package/dist/chunks/{dist-X64FC6NA.js → dist-HSC43RG4.js} +1 -1
- package/dist/chunks/{dist-DCSLPBO2.js → dist-MXBEBM4D.js} +1 -1
- package/dist/chunks/evaluation-coordination-UOWZHHC5.js +2 -0
- package/dist/chunks/experiment-improvements-EB2CV5RA.js +2 -0
- package/dist/chunks/experiments-SZQYR6MH.js +2 -0
- package/dist/chunks/experiments-signal-2KJCP25D.js +2 -0
- package/dist/chunks/{extension-C33NUFDL.js → extension-ZM6NI5O5.js} +1 -1
- package/dist/chunks/{help-M2VQGPVC.js → help-7HXFWIKS.js} +1 -1
- package/dist/chunks/host-profile-evaluation-tools-Y2LQ4WQN.js +2 -0
- package/dist/chunks/host-profile-external-dataset-FRIGXOO7.js +2 -0
- package/dist/chunks/hosted-app-server-composition-PGKQNDW6.js +2 -0
- package/dist/chunks/hosted-experiment-improvement-UXC542SZ.js +3 -0
- package/dist/chunks/hosted-harness-runtime-6PEI7F2U.js +2 -0
- package/dist/chunks/hosted-profile-candidate-HM44BIUX.js +3 -0
- package/dist/chunks/hosted-profile-compiler-UAZ4PHYE.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-control-EUL57FAB.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-inspection-7USY75Z4.js +3 -0
- package/dist/chunks/{hosted-profile-evaluation-preparation-ZAOGDQXO.js → hosted-profile-evaluation-preparation-2LSMZQNA.js} +1 -1
- package/dist/chunks/{hosted-tasksets-CVUP7MS6.js → hosted-tasksets-WGXGXJ7E.js} +1 -1
- package/dist/chunks/human-review-M26UKGJL.js +2 -0
- package/dist/chunks/{import-WLLUIDS6.js → import-6SI4BEKS.js} +2 -2
- package/dist/chunks/learning-HM3NWOV5.js +2 -0
- package/dist/chunks/local-harness-improvement-runtime-QGWFWNSR.js +2 -0
- package/dist/chunks/local-harness-taskset-review-KS4WPMN6.js +2 -0
- package/dist/chunks/model-projects-YUAMBQTO.js +2 -0
- package/dist/chunks/opchat-AG4CWVY4.js +3 -0
- package/dist/chunks/opchat-bounded-chat-IQMP5IIO.js +2 -0
- package/dist/chunks/organizations-KDKX77XZ.js +2 -0
- package/dist/chunks/{profile-JRS3JNRC.js → profile-O5HL5DTQ.js} +1 -1
- package/dist/chunks/project-action-payload-QA24HYGF.js +2 -0
- package/dist/chunks/project-agent-XBOOM5TS.js +2 -0
- package/dist/chunks/published-experiment-source-GZGN354O.js +2 -0
- package/dist/chunks/refiner-profile-service-BJMOYKTC.js +2 -0
- package/dist/chunks/{runtime-CBJF5GMB.js → runtime-XBA744HJ.js} +2 -2
- package/dist/chunks/sandbox-command-5ECGS7DG.js +2 -0
- package/dist/chunks/{sandbox-template-FTANKQIA.js → sandbox-template-27U3FQN7.js} +1 -1
- package/dist/chunks/saved-work-KUNVTJ7O.js +2 -0
- package/dist/chunks/{send-turn-5UB7ZBJV.js → send-turn-FIPWOXWV.js} +1 -1
- package/dist/chunks/src-BLWX6DRG.js +424 -0
- package/dist/chunks/{src-4YZF6L6H.js → src-PU7QTFO5.js} +1 -1
- package/dist/chunks/standalone-experiment-turn-owner-XIE46VNH.js +2 -0
- package/dist/chunks/store-chat-resources-YOEJ2BI6.js +2 -0
- package/dist/chunks/{store-continual-support-reviews-GWI2FRII.js → store-continual-support-reviews-FOMYYS25.js} +1 -1
- package/dist/chunks/{store-conversation-serving-637AHKBP.js → store-conversation-serving-K324SQTO.js} +1 -1
- package/dist/chunks/{store-create-improve-ZG653Z63.js → store-create-improve-3LQMIYAP.js} +1 -1
- package/dist/chunks/{store-datasets-IW6F2QZM.js → store-datasets-3KSX7RSO.js} +1 -1
- package/dist/chunks/store-evaluation-results-LHCCNNE6.js +7 -0
- package/dist/chunks/{store-harness-evaluation-review-settings-I2R3HPO3.js → store-harness-evaluation-review-settings-AAN7KKJ5.js} +1 -1
- package/dist/chunks/{store-harness-refinement-candidates-SUT45FQX.js → store-harness-refinement-candidates-3PHL3BUY.js} +1 -1
- package/dist/chunks/store-harness-workspaces-ZHNCNWVI.js +2 -0
- package/dist/chunks/store-human-review-QJY3ZPPF.js +7 -0
- package/dist/chunks/store-learned-preference-migration-validation-X32SRBOM.js +2 -0
- package/dist/chunks/{store-learning-MFS4DGQR.js → store-learning-DW3QLQXU.js} +1 -1
- package/dist/chunks/{store-learning-credentials-BECWEG2Y.js → store-learning-credentials-67QNTPA7.js} +1 -1
- package/dist/chunks/{store-local-experiments-A2UWYPVQ.js → store-local-experiments-QTVHJAEP.js} +1 -1
- package/dist/chunks/store-model-batch-review-PBYQZJJJ.js +2 -0
- package/dist/chunks/store-model-configuration-3SU73CMS.js +3 -0
- package/dist/chunks/store-model-project-preparation-TFCG2F2F.js +2 -0
- package/dist/chunks/store-ponder-history-WDLMXBIJ.js +2 -0
- package/dist/chunks/store-ponder-hosted-DX6E2BVW.js +4 -0
- package/dist/chunks/{store-preference-comparison-HTOXLWKF.js → store-preference-comparison-DWV5XSMY.js} +1 -1
- package/dist/chunks/{store-schedules-QVWT7AEB.js → store-schedules-2KUY4T6M.js} +1 -1
- package/dist/chunks/{store-sidebar-file-bookmarks-G5Z6NZWL.js → store-sidebar-file-bookmarks-A4XCS7RM.js} +1 -1
- package/dist/chunks/{store-sidebar-preferences-27FFMUWU.js → store-sidebar-preferences-V2PKRXUZ.js} +1 -1
- package/dist/chunks/{store-subagents-PK7ZWLPR.js → store-subagents-UGVEFA6M.js} +1 -1
- package/dist/chunks/store-task-inbox-QABI4ZAH.js +33 -0
- package/dist/chunks/{store-task-inventory-IG6HGWSQ.js → store-task-inventory-GEQIZELY.js} +1 -1
- package/dist/chunks/store-taskset-drafts-GXABQR5G.js +9 -0
- package/dist/chunks/{store-training-NQRRPKEZ.js → store-training-CQV7PL3V.js} +1 -1
- package/dist/chunks/{store-training-jobs-F6Y2ZTXP.js → store-training-jobs-XKN6K66J.js} +18 -10
- package/dist/chunks/{store-training-models-NRSLSBEW.js → store-training-models-Q7DTTR4S.js} +1 -1
- package/dist/chunks/{store-usage-GFHQYT34.js → store-usage-XGAX7NLB.js} +1 -1
- package/dist/chunks/{taskset-NYLUYX6K.js → taskset-ARKJQKYQ.js} +1 -1
- package/dist/chunks/taskset-packages-X4K65DTW.js +2 -0
- package/dist/chunks/taskset-packages-XK7FSD45.js +2 -0
- package/dist/chunks/{teams-bot-FMAEDGSD.js → teams-bot-UTQAJA6H.js} +1 -1
- package/dist/chunks/training-3IWW4256.js +2 -0
- package/dist/chunks/{training-UBX6E7SK.js → training-RVIESURJ.js} +1 -1
- package/dist/chunks/training-error-2EWDOQ4G.js +2 -0
- package/dist/chunks/training-hosted-PFJHYTEU.js +2 -0
- package/dist/chunks/training-hosted-checkpoint-evaluation-JJPP7KFW.js +2 -0
- package/dist/chunks/training-hosted-feedback-5B2KJGOT.js +2 -0
- package/dist/chunks/training-hosted-learning-Y7NHRY4V.js +2 -0
- package/dist/chunks/training-hosted-report-UVGTPDOK.js +2 -0
- package/dist/chunks/training-hosted-serving-QAV7ZGGV.js +2 -0
- package/dist/chunks/training-hosted-serving-report-OX4A5OKB.js +2 -0
- package/dist/chunks/training-hosted-workers-LST4ZUXN.js +2 -0
- package/dist/chunks/training-model-start-ROLS3E4V.js +2 -0
- package/dist/chunks/training-project-preparation-XWGRY5ME.js +3 -0
- package/dist/chunks/{web-search-Q4OQVUNH.js → web-search-7FBUBZ66.js} +1 -1
- package/dist/chunks/{workspaces-XREEVSTS.js → workspaces-G3CMY7ZA.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/hosted-chat.d.ts +28 -0
- package/dist/index.js +1 -1
- package/dist/sandbox/url.d.ts +3 -1
- package/dist/skills/LICENSE +21 -0
- package/dist/skills/manifest.json +168 -0
- package/dist/skills/openpond-agent-authoring/SKILL.md +9 -3
- package/dist/skills/openpond-agent-authoring/references/profile-layout.md +1 -1
- package/dist/skills/openpond-agent-authoring/references/validation-and-repair.md +2 -2
- package/dist/skills/openpond-cli/SKILL.md +24 -7
- package/dist/skills/openpond-cli/references/compact-resource-tables.md +3 -3
- package/dist/skills/openpond-cli/references/diagnose-and-improve.md +4 -2
- package/dist/skills/openpond-cli/references/experiments-and-training.md +156 -11
- package/dist/skills/openpond-refiner-authoring/SKILL.md +4 -0
- package/dist/skills/openpond-skill-authoring/SKILL.md +5 -1
- package/dist/skills/openpond-taskset-authoring/SKILL.md +5 -4
- package/dist/skills/openpond-taskset-authoring/artifact.json +7 -7
- package/dist/skills/openpond-taskset-authoring/references/failure-diagnosis.md +52 -1
- package/dist/web/assets/App-DY2R8Z6r.js +53 -0
- package/dist/web/assets/App-DpFKLxuA.css +1 -0
- package/dist/web/assets/AppDialog-8Y0FYalT.js +1 -0
- package/dist/web/assets/AppTerminalPanel-YcnBD5DF.js +2 -0
- package/dist/web/assets/{AppToastContext-BB_2hRfw.js → AppToastContext-BiQbbVxq.js} +1 -1
- package/dist/web/assets/AppsView-Dtte4h6e.js +1 -0
- package/dist/web/assets/{AttachmentTypeIcon-DOAsVQjt.js → AttachmentTypeIcon-DgADV7dn.js} +1 -1
- package/dist/web/assets/BrowserSidebar-BUqDvEv9.js +1 -0
- package/dist/web/assets/{CartesianChart-DO76yfJb.js → CartesianChart-J4ChOjvG.js} +1 -1
- package/dist/web/assets/ChatTimelineEntry-DC93wlDa.js +8 -0
- package/dist/web/assets/ChatTimelineEntry-DztFb85D.css +1 -0
- package/dist/web/assets/{CollaborationTabs-DNoknVMD.js → CollaborationTabs-CFCpk2Ck.js} +1 -1
- package/dist/web/assets/CommandMenu-EPPjB14H.js +1 -0
- package/dist/web/assets/CommunityView-Okydjpqm.js +1 -0
- package/dist/web/assets/ComposerAttachments-RXCiE88M.js +2 -0
- package/dist/web/assets/ComposerCreateImproveStrip-CSngc8-V.js +1 -0
- package/dist/web/assets/ConversationImportsSettings-DS73kyfj.js +1 -0
- package/dist/web/assets/FilePagePreview-Qc4B0vue.js +2 -0
- package/dist/web/assets/GetStartedView-DGFPQ1We.js +1 -0
- package/dist/web/assets/GettingStartedDialog-DFBYQdHz.js +1 -0
- package/dist/web/assets/GettingStartedDialog-EsH-8Diz.css +1 -0
- package/dist/web/assets/{HostedModelLearningReview-B0rbIVvn.js → HostedModelLearningReview-BDu3FlcU.js} +1 -1
- package/dist/web/assets/HostedModelLearningSettings-CHaTHwC8.js +1 -0
- package/dist/web/assets/HtmlVisual-C7GlEVfH.css +1 -0
- package/dist/web/assets/HtmlVisual-D9Mh7xds.js +81 -0
- package/dist/web/assets/LabModelVersionDetailPage-DgY7lAu5.js +1 -0
- package/dist/web/assets/LabSkillSidebar-BwtlThO7.js +1 -0
- package/dist/web/assets/LabsRoute-BV7ZJGEw.js +101 -0
- package/dist/web/assets/MainChatThread-pzHKd_YN.js +2 -0
- package/dist/web/assets/MainPane-6OlLiKKb.js +10 -0
- package/dist/web/assets/MainPane-Dje-hfUM.css +1 -0
- package/dist/web/assets/NativeSetupTerminal-3eR9D_R3.css +1 -0
- package/dist/web/assets/NativeSetupTerminal-CPDChcMi.js +2 -0
- package/dist/web/assets/NativeSkillSidebar-BEJvt5_H.js +1 -0
- package/dist/web/assets/NewProjectDialog-CjrjgkTN.js +1 -0
- package/dist/web/assets/OutputsPage-jzx93QQ3.js +1 -0
- package/dist/web/assets/{PageChrome-BBnWAENV.js → PageChrome-C1M13qG2.js} +1 -1
- package/dist/web/assets/ProjectsPage-DZrjlMp2.js +1 -0
- package/dist/web/assets/RightChatPanelStack-BsxJg9sy.js +1 -0
- package/dist/web/assets/RightSidebarHomePanel-CCVQ9LMB.js +1 -0
- package/dist/web/assets/ScheduledWorkPage-Cw1ja2GF.js +1 -0
- package/dist/web/assets/{SettingsView-Y8f98GSE.css → SettingsView-Cc0376pY.css} +1 -1
- package/dist/web/assets/SettingsView-CckoIki3.js +5 -0
- package/dist/web/assets/TasksetDraftEditorPrimitives-ByC8bDjp.js +1 -0
- package/dist/web/assets/TeamChatView-OprnSKLF.js +1 -0
- package/dist/web/assets/TerminalOverlay-d7A2F9Lx.js +16 -0
- package/dist/web/assets/TrainingCreationPanel-Cyn6R6I6.js +1 -0
- package/dist/web/assets/{TrainingDraftPanel-HznyNCJ4.js → TrainingDraftPanel-Mpb5e7t5.js} +1 -1
- package/dist/web/assets/TrainingRunLineage-PXzWR65d.css +1 -0
- package/dist/web/assets/TrainingRunLineage-VcKz7dIR.js +1 -0
- package/dist/web/assets/{UsageSettingsSection-C3oZ1UEP.js → UsageSettingsSection-FhYymrfc.js} +2 -2
- package/dist/web/assets/WorkSidebarPanel-u87uptH0.js +1 -0
- package/dist/web/assets/WorkspaceDiffPanel-B5rlW7bA.js +11 -0
- package/dist/web/assets/WorkspaceEnvironmentMenu-C8y3537a.js +35 -0
- package/dist/web/assets/WorkspaceFileLocation-LrEWj4UK.js +1 -0
- package/dist/web/assets/WorkspaceGitDialogs-NRIMXnkS.js +1 -0
- package/dist/web/assets/{WorkspaceMonacoEditor-DfsL1WIi.js → WorkspaceMonacoEditor-CvDGjKAL.js} +3 -3
- package/dist/web/assets/WorkspacePdfPreview-BZ0BbnHv.js +2 -0
- package/dist/web/assets/{WorkspacePresentationPreview-WuS_B45u.js → WorkspacePresentationPreview-DJrjrvT0.js} +1 -1
- package/dist/web/assets/app-models-CUA9XB9U.js +1 -0
- package/dist/web/assets/bot-6OhUEmkE.js +1 -0
- package/dist/web/assets/browser-sidebar-links-ZyYiYBBd.js +1 -0
- package/dist/web/assets/chat-resources-CI8KFVO5.js +1 -0
- package/dist/web/assets/{chevron-down-Bnma8EMP.js → chevron-down-jmVA1BIf.js} +1 -1
- package/dist/web/assets/chevron-right-BYmDQ7ti.js +1 -0
- package/dist/web/assets/chevron-up-CstyLXH3.js +1 -0
- package/dist/web/assets/{chunk-GAIDBPFY-BLuHpurI.js → chunk-ONGOAEY6-C__DQmRT.js} +5 -5
- package/dist/web/assets/{chunk-24N6A6SF-BUjzKvRC.js → chunk-SQBYHWZU-DumrB9SB.js} +1 -1
- package/dist/web/assets/{client-choice-storage-BuNdhYSV.js → client-choice-storage-BdQ_YDuk.js} +1 -1
- package/dist/web/assets/{cloud-upload-DOftANif.js → cloud-upload-Ck1ufAr8.js} +1 -1
- package/dist/web/assets/connected-app-mentions-D3wRZLwI.js +1 -0
- package/dist/web/assets/contracts-BLiqJxBv.js +1 -0
- package/dist/web/assets/copy-CPkbMfXt.js +1 -0
- package/dist/web/assets/{createLucideIcon-C4b2afqG.js → createLucideIcon-CXQny8HU.js} +1 -1
- package/dist/web/assets/{cssMode-0Hn7tCrE.js → cssMode-CYxYl_om.js} +1 -1
- package/dist/web/assets/external-link-CDKOLG_v.js +1 -0
- package/dist/web/assets/{folder-open-wJwCoIDs.js → folder-open-CEtOb_lK.js} +1 -1
- package/dist/web/assets/{folder-plus-DnTN6mcP.js → folder-plus-CVMYZs3e.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-98y7PP6G.js → git-commit-horizontal-DDyhPjxS.js} +1 -1
- package/dist/web/assets/{htmlMode-JO_QluNH.js → htmlMode-DoY4V_j0.js} +1 -1
- package/dist/web/assets/icons-D7jkCa2d.js +1 -0
- package/dist/web/assets/{image-C7HVlg3X.js → image-B-PjDSwU.js} +1 -1
- package/dist/web/assets/{index-BsPUniZy.js → index-D9WbJMSq.js} +2 -2
- package/dist/web/assets/index-g7UqJhnX.css +1 -0
- package/dist/web/assets/{info-BLWDShaz.js → info-CCnw-K3b.js} +1 -1
- package/dist/web/assets/intake-contracts-BW0Y0C2R.js +1 -0
- package/dist/web/assets/{jsonMode-BfTXJted.js → jsonMode-CeOpZdPj.js} +1 -1
- package/dist/web/assets/loader-circle-CPaJeTDy.js +1 -0
- package/dist/web/assets/{lspLanguageFeatures-68cAgnuv.js → lspLanguageFeatures-DAbgLCqZ.js} +1 -1
- package/dist/web/assets/{maximize-2-DUWvLap6.js → maximize-2-BZX38cpr.js} +1 -1
- package/dist/web/assets/message-square-CvgSecgD.js +1 -0
- package/dist/web/assets/{monaco.contribution-_3aU1TTb.js → monaco.contribution-CF2JDhi4.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CWeY6ia1.js → monaco.contribution-cbDqt48m.js} +2 -2
- package/dist/web/assets/{monaco.contribution-h8U8HXFT.js → monaco.contribution-m2ze2EsL.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DOiiDDen.js → monaco.contribution-yeyow_-Q.js} +2 -2
- package/dist/web/assets/{monitor-B6OuAu13.js → monitor-By0s4hxb.js} +1 -1
- package/dist/web/assets/{paperclip-DSHxP9CY.js → paperclip-BJ2QgJLa.js} +1 -1
- package/dist/web/assets/{pdf-RXlFwNte.js → pdf-C4x-1jjP.js} +1 -1
- package/dist/web/assets/pdf.worker.min-BrEVksTu.js +1 -0
- package/dist/web/assets/play-D_SuGDBM.js +1 -0
- package/dist/web/assets/plus-yw95Iaj8.js +1 -0
- package/dist/web/assets/{presentation-C9WnPDVr.js → presentation-I86G1Gd9.js} +1 -1
- package/dist/web/assets/profile-agent-labels-Duh96b8x.js +1 -0
- package/dist/web/assets/{python-BQXo7wMt.js → python-CqFTPj8r.js} +1 -1
- package/dist/web/assets/{refresh-cw-NXOER_CD.js → refresh-cw-Dga35Eay.js} +1 -1
- package/dist/web/assets/requests-BCbaFiqV.js +1 -0
- package/dist/web/assets/{reward-checks-5AOStF27.js → reward-checks-Bcq9ETCA.js} +1 -1
- package/dist/web/assets/{save-BxXc21N6.js → save-BLKjYtzR.js} +1 -1
- package/dist/web/assets/settings-D7C-Auyi.js +21 -0
- package/dist/web/assets/settings-lists-DMKA1lCN.js +5 -0
- package/dist/web/assets/square-BY5lG2Ol.js +1 -0
- package/dist/web/assets/square-terminal-B-n7vUex.js +1 -0
- package/dist/web/assets/submit-issue-command-B7Hrt2tU.js +3 -0
- package/dist/web/assets/{toggleHighContrast-Di1cRuQ4.js → toggleHighContrast-BhmBE5XE.js} +1 -1
- package/dist/web/assets/training-QrdkRQZQ.js +2 -0
- package/dist/web/assets/{training-model-data-CmVo80ZR.js → training-model-data-DB-jg6L_.js} +12 -12
- package/dist/web/assets/{tsMode-PxisJRYB.js → tsMode-BSWEII2p.js} +1 -1
- package/dist/web/assets/ui-theme.generated-D-mc26qt.js +144 -0
- package/dist/web/assets/{upload-NXasN1wU.js → upload-C4MPhQn8.js} +1 -1
- package/dist/web/assets/{useAccountSettings-Dqqt1vUY.js → useAccountSettings-9oqWdRLs.js} +1 -1
- package/dist/web/assets/useAgentInventory-isO79ui9.js +1 -0
- package/dist/web/assets/{useLocalAgentSchedules-Cc0M_qax.js → useLocalAgentSchedules-CZX6PxoK.js} +1 -1
- package/dist/web/assets/{useQuery-ByaRC9SK.js → useQuery-BD0Uexmh.js} +1 -1
- package/dist/web/assets/{wifi-off-aVJ3AvT_.js → wifi-off-Cloe0WuQ.js} +1 -1
- package/dist/web/assets/{workers-u92Boudu.js → workers-BXagz5eg.js} +1 -1
- package/dist/web/assets/x-Dqpel42h.js +1 -0
- package/dist/web/assets/{yaml-BxQUS0ew.js → yaml-sBdvVbCc.js} +1 -1
- package/dist/web/index.html +12 -3
- package/docs/command-reference.md +49 -5
- package/package.json +6 -2
- package/dist/chunks/actions-command-LOHNQUWP.js +0 -2
- package/dist/chunks/app-server-connected-apps-Q2VWWJNX.js +0 -2
- package/dist/chunks/app-server-harness-services-2PSZBT7U.js +0 -2
- package/dist/chunks/app-server-runtime-B6BAJA6L.js +0 -2
- package/dist/chunks/apps-7PIBF32Q.js +0 -2
- package/dist/chunks/chunk-3TYCIYW6.js +0 -17
- package/dist/chunks/chunk-4GZ2FPB5.js +0 -2
- package/dist/chunks/chunk-4M3YW3EQ.js +0 -13
- package/dist/chunks/chunk-4N3UF3U5.js +0 -2
- package/dist/chunks/chunk-4P3X2RXA.js +0 -2
- package/dist/chunks/chunk-4RHM4WN2.js +0 -2
- package/dist/chunks/chunk-6DCXAXVD.js +0 -22
- package/dist/chunks/chunk-AWPYTDH4.js +0 -4
- package/dist/chunks/chunk-BLKTUFGB.js +0 -2
- package/dist/chunks/chunk-BN5AVRUG.js +0 -2
- package/dist/chunks/chunk-D5ADDBS5.js +0 -2
- package/dist/chunks/chunk-DGPGOBYZ.js +0 -5
- package/dist/chunks/chunk-E3EKBPCB.js +0 -2
- package/dist/chunks/chunk-E67M5WGY.js +0 -2
- package/dist/chunks/chunk-EIIGTADO.js +0 -2
- package/dist/chunks/chunk-F5JDBDYL.js +0 -2
- package/dist/chunks/chunk-FWIPHEVA.js +0 -12
- package/dist/chunks/chunk-GLVR74PX.js +0 -2
- package/dist/chunks/chunk-HZLV773Y.js +0 -22
- package/dist/chunks/chunk-JEVA7YQL.js +0 -3
- package/dist/chunks/chunk-KC7I6E6W.js +0 -2
- package/dist/chunks/chunk-M4ZRCRJM.js +0 -10
- package/dist/chunks/chunk-N663LL27.js +0 -2
- package/dist/chunks/chunk-NR5VASQB.js +0 -2
- package/dist/chunks/chunk-OJSK4NSW.js +0 -151
- package/dist/chunks/chunk-OZ6LRNRE.js +0 -2
- package/dist/chunks/chunk-Q324ZA5M.js +0 -2
- package/dist/chunks/chunk-UBCLPZSQ.js +0 -4
- package/dist/chunks/chunk-UJBEWIR3.js +0 -8
- package/dist/chunks/chunk-V67IFV26.js +0 -86
- package/dist/chunks/chunk-VSUHJ46L.js +0 -18
- package/dist/chunks/chunk-VWJ5IYQP.js +0 -2
- package/dist/chunks/chunk-X3WEQL3O.js +0 -2
- package/dist/chunks/chunk-XK7SPL63.js +0 -2
- package/dist/chunks/chunk-XLULTQLZ.js +0 -12
- package/dist/chunks/chunk-YR5ID2SS.js +0 -2
- package/dist/chunks/chunk-ZBBVRYU3.js +0 -6
- package/dist/chunks/chunk-ZHFH2TZN.js +0 -2
- package/dist/chunks/chunk-ZZWAQBA2.js +0 -2
- package/dist/chunks/cli-WC45SI7E.js +0 -2
- package/dist/chunks/connected-app-executor-TZJB25UZ.js +0 -2
- package/dist/chunks/connected-evidence-4J3YXU4O.js +0 -2
- package/dist/chunks/core-commands-JGXU6B4C.js +0 -2
- package/dist/chunks/dataset-preparation-authoring-DFGJBMVF.js +0 -4
- package/dist/chunks/datasets-MNHZAZIB.js +0 -2
- package/dist/chunks/desktop-test-P23MHAIG.js +0 -3
- package/dist/chunks/dist-IIFTZWNR.js +0 -2
- package/dist/chunks/evaluation-coordination-6NQEH5WU.js +0 -2
- package/dist/chunks/experiment-improvements-M27Z5OF4.js +0 -2
- package/dist/chunks/experiments-IWSCFDBB.js +0 -2
- package/dist/chunks/experiments-signal-R3NNH7WR.js +0 -2
- package/dist/chunks/host-profile-evaluation-tools-EFB2YIK2.js +0 -2
- package/dist/chunks/host-profile-external-dataset-KSNREH3Q.js +0 -2
- package/dist/chunks/hosted-app-server-composition-VV545TYL.js +0 -2
- package/dist/chunks/hosted-experiment-improvement-NYLADI7S.js +0 -3
- package/dist/chunks/hosted-harness-runtime-Z54E5MD7.js +0 -2
- package/dist/chunks/hosted-profile-candidate-37ZFY2LH.js +0 -3
- package/dist/chunks/hosted-profile-compiler-SW2RWTDZ.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-control-UQBMML6K.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-inspection-YASS4T6L.js +0 -3
- package/dist/chunks/human-review-IJETDOWB.js +0 -2
- package/dist/chunks/learning-KVLTMRLD.js +0 -2
- package/dist/chunks/local-harness-improvement-runtime-KB4OP3SM.js +0 -2
- package/dist/chunks/local-harness-taskset-review-SUDEUGUU.js +0 -2
- package/dist/chunks/model-projects-AVBQDNYG.js +0 -2
- package/dist/chunks/opchat-KSOJEL4W.js +0 -3
- package/dist/chunks/organizations-DJRJWC5I.js +0 -2
- package/dist/chunks/project-action-payload-SQ5BSQHY.js +0 -2
- package/dist/chunks/project-agent-2KNJFNZI.js +0 -2
- package/dist/chunks/published-experiment-source-LFYHKFAO.js +0 -2
- package/dist/chunks/refiner-profile-service-UWI4NAZ3.js +0 -2
- package/dist/chunks/sandbox-command-IIGTPYN3.js +0 -2
- package/dist/chunks/saved-work-QA46KCME.js +0 -2
- package/dist/chunks/src-E7NWAN5B.js +0 -420
- package/dist/chunks/standalone-experiment-turn-owner-SQJ5HXDZ.js +0 -2
- package/dist/chunks/store-chat-resources-CGW7PDCG.js +0 -2
- package/dist/chunks/store-evaluation-results-V5J6L4NV.js +0 -7
- package/dist/chunks/store-harness-workspaces-HHMM6GNK.js +0 -2
- package/dist/chunks/store-human-review-V5H4QDHR.js +0 -7
- package/dist/chunks/store-learned-preference-migration-validation-KOCW5NOZ.js +0 -2
- package/dist/chunks/store-model-batch-review-KMYPYWJR.js +0 -2
- package/dist/chunks/store-model-configuration-UXNC4PGY.js +0 -3
- package/dist/chunks/store-task-inbox-LNDCZOYE.js +0 -33
- package/dist/chunks/store-taskset-drafts-TA6X245D.js +0 -9
- package/dist/chunks/taskset-packages-I7I5KBFP.js +0 -2
- package/dist/chunks/training-error-AYOGHHL2.js +0 -2
- package/dist/chunks/training-hosted-4R4QTSAN.js +0 -2
- package/dist/chunks/training-hosted-report-UQVK6FTG.js +0 -2
- package/dist/chunks/training-hosted-workers-KI767T4Y.js +0 -2
- package/dist/skills/openpond-desktop-harness/SKILL.md +0 -113
- package/dist/skills/openpond-desktop-harness/agents/openai.yaml +0 -4
- package/dist/web/assets/App-Df7uYQGj.css +0 -1
- package/dist/web/assets/App-Yy3l2sdD.js +0 -56
- package/dist/web/assets/AppTerminalPanel-Dqr6VS3I.js +0 -2
- package/dist/web/assets/AppsView-27Fl_-49.js +0 -1
- package/dist/web/assets/BrowserSidebar-bnI3sSZO.js +0 -1
- package/dist/web/assets/ChatTimelineEntry-IKzZsHoI.js +0 -1
- package/dist/web/assets/CommandMenu-CBY2AJxV.js +0 -1
- package/dist/web/assets/CommunityView-CFKM7FTY.js +0 -1
- package/dist/web/assets/ComposerAttachments-BdjBddKf.js +0 -2
- package/dist/web/assets/ComposerCreateImproveStrip-ViJ5E0We.js +0 -1
- package/dist/web/assets/ConversationImportsSettings-xLl-7G9R.js +0 -1
- package/dist/web/assets/FilePagePreview-CTHuPzJt.js +0 -2
- package/dist/web/assets/GetStartedView-DvV_RMgM.js +0 -1
- package/dist/web/assets/GettingStartedDialog-B1jFmfgd.js +0 -1
- package/dist/web/assets/GettingStartedDialog-C73Bdcz2.css +0 -1
- package/dist/web/assets/HostedModelLearningSettings-DzAiutjq.js +0 -1
- package/dist/web/assets/LabModelVersionDetailPage-CF8FkRUY.js +0 -1
- package/dist/web/assets/LabSkillSidebar-gjbl9Nlv.js +0 -1
- package/dist/web/assets/LabsRoute-DOnw39du.js +0 -101
- package/dist/web/assets/MainChatThread-BUKup-JB.js +0 -2
- package/dist/web/assets/MainPane-BpE7AKXu.js +0 -92
- package/dist/web/assets/MainPane-CuBUBA9F.css +0 -1
- package/dist/web/assets/NativeSkillSidebar-Br5Lk6iU.js +0 -1
- package/dist/web/assets/NewProjectDialog-DyuKPOvF.js +0 -1
- package/dist/web/assets/OutputsPage-Dl63CVrw.js +0 -1
- package/dist/web/assets/ProjectsPage-BNF1TiyR.js +0 -1
- package/dist/web/assets/RightChatPanelStack-CxVAAbp-.js +0 -1
- package/dist/web/assets/RightSidebarHomePanel-D46ktZg-.js +0 -1
- package/dist/web/assets/ScheduledWorkPage-Cp0Hf-hs.js +0 -1
- package/dist/web/assets/SettingsView-BT57Q5Wx.js +0 -5
- package/dist/web/assets/TeamChatView-BmxTJ9E5.js +0 -1
- package/dist/web/assets/TerminalOverlay-D-Yq8av_.js +0 -16
- package/dist/web/assets/TrainingCreationPanel-CwfNPj_G.js +0 -1
- package/dist/web/assets/TrainingMetricWorkbench-BmzHLwIP.js +0 -1
- package/dist/web/assets/WorkSidebarPanel-myTA9tsh.js +0 -1
- package/dist/web/assets/WorkspaceDiffPanel-D0dzFgzW.js +0 -11
- package/dist/web/assets/WorkspaceEnvironmentMenu-AUzME1eX.js +0 -35
- package/dist/web/assets/WorkspaceFileLocation-Ai8Tz2Mz.js +0 -1
- package/dist/web/assets/WorkspaceGitDialogs-D-UCCckC.js +0 -1
- package/dist/web/assets/app-models-BviS9b7U.js +0 -1
- package/dist/web/assets/browser-sidebar-links-ujSvTf5h.js +0 -1
- package/dist/web/assets/chat-resources-CItQ4mZD.js +0 -1
- package/dist/web/assets/chevron-right-Cxv_xBz5.js +0 -1
- package/dist/web/assets/contracts-BHTOD1nd.js +0 -1
- package/dist/web/assets/git-dialogs-C631EFyO.css +0 -1
- package/dist/web/assets/icons-kaq6k88m.js +0 -1
- package/dist/web/assets/index-DUMDOdB2.css +0 -1
- package/dist/web/assets/play-BPPQoqMl.js +0 -1
- package/dist/web/assets/plus-D18vYzHF.js +0 -1
- package/dist/web/assets/settings-BKmRueaw.js +0 -21
- package/dist/web/assets/settings-lists-DMNPkGYk.js +0 -5
- package/dist/web/assets/square-Da8RuqW4.js +0 -1
- package/dist/web/assets/training-managed-adapter-81RrdT1k.js +0 -1
- package/dist/web/assets/ui-theme.generated-R0MY_Jy0.js +0 -136
- package/dist/web/assets/useAgentInventory-BV4CUWzJ.js +0 -1
- /package/dist/chunks/{chunk-GLDYJM7O.js → chunk-T4QXKU5Y.js} +0 -0
|
@@ -1,45 +1,45 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a as
|
|
2
|
+
import{a as xs}from"./chunk-JFXINDOQ.js";import{a as ce,b as Te,d as ut,e as we}from"./chunk-YBNKGA5C.js";import{a as lt,b as Ee,c as $,g as Oe,h as pt,i as Be}from"./chunk-LV3CQ72P.js";import{a as dt,n as O}from"./chunk-VVNV4NNW.js";import{A as Y}from"./chunk-PF56N7ZY.js";import{a as p,e as Ns}from"./chunk-FTQLQJQV.js";var ft={codex:"Codex",claude_code:"Claude Code",hermes:"Hermes",openclaw:"OpenClaw",opencode:"OpenCode",grok_build:"Grok Build",pi:"Pi",oh_my_pi:"Oh My Pi"},L=32*1024*1024;import{homedir as ks}from"node:os";import{realpath as St,stat as ze,readdir as Ds,readFile as Ms}from"node:fs/promises";import{resolve as Je,join as X,isAbsolute as $s}from"node:path";function ht(s,e){let t=0;for(let i of e){if(!Number.isSafeInteger(i)||i<t||i>s.length)throw new RangeError("Canonical array prefix lengths must be ascending and within the array");t=i}let n=new dt().update("["),r=0;return e.map(i=>{for(;r<i;){let a=JSON.stringify([Pe(s[r])],null,2).slice(2,-2);n.update(r?`,
|
|
3
3
|
`:`
|
|
4
4
|
`).update(a),r++}return n.clone().update(r?`
|
|
5
5
|
]
|
|
6
6
|
`:`]
|
|
7
|
-
`).digestHex()})}p(ft,"contentHashArrayPrefixes");function Pe(s){if(s===null||typeof s=="boolean"||typeof s=="number"||typeof s=="string")return s;if(Array.isArray(s))return Array.from({length:s.length},(t,n)=>{let r=Object.getOwnPropertyDescriptor(s,n);if(!r||r.get||r.set)throw new TypeError("Canonical array prefixes require plain JSON values");return Pe(r.value)});let e=s&&typeof s=="object"?Object.getPrototypeOf(s):void 0;if(s&&typeof s=="object"&&(e===Object.prototype||e===null))return Object.fromEntries(Object.keys(s).sort((t,n)=>t.localeCompare(n)).map(t=>{let n=Object.getOwnPropertyDescriptor(s,t);if(n.get||n.set)throw new TypeError("Canonical array prefixes require plain JSON values");return[t,Pe(n.value)]}));throw new TypeError("Canonical array prefixes require plain JSON values")}p(Pe,"sortJsonValue");import{opendir as Ns,readFile as xs,stat as Ce}from"node:fs/promises";import{basename as Cs,dirname as Rs,join as D,resolve as je}from"node:path";function gt(s,e){let t=e.HERMES_HOME?.trim();if(t){let r=t.replace(/\$(\w+)|\$\{([^}]+)\}/gu,(i,a,o)=>e[a||o]??i);return je(r==="~"?s:r.startsWith("~/")?D(s,r.slice(2)):r)}let n=e.HERMES_DATA_DIR_SUFFIX||"";return process.platform==="win32"?D(e.LOCALAPPDATA?.trim()||D(s,"AppData","Local"),`hermes${n}`):D(s,`.hermes${n}`)}p(gt,"hermesHome");var ht=p(s=>Ce(s).then(e=>e.isDirectory()).catch(()=>!1),"isDirectory"),mt=p(s=>Ce(s).then(e=>e.isFile()).catch(()=>!1),"isFile");async function We(s,e){let t=[],n=await Ns(s).catch(()=>null);if(!n)return t;let r=0;for await(let i of n){if(++r>100)throw new Error("More than 100 profile entries. Select the exact --source-path.");i.isDirectory()&&!i.isSymbolicLink()&&e(i.name)&&t.push(i.name)}return t.sort()}p(We,"profileNames");async function yt(s){if(Cs(Rs(s))==="profiles")return[{root:s}];let e=D(s,"profiles");try{let t=await We(e,a=>/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(a)),n=[];for(let a of t)await Ce(D(e,".deleted",a)).then(()=>!0).catch(()=>!1)||await mt(D(e,a,"state.db"))&&n.push({root:D(e,a)});let r="",i=D(s,"active_profile");if(await Ce(i).then(a=>a.isFile()&&a.size<=1024).catch(()=>!1)&&(r=(await xs(i,"utf8")).replace(/^\uFEFF/u,"").trim().toLowerCase()),r&&r!=="default"){if(!/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(r))return[{root:s,reason:"Hermes active profile is invalid. Select the exact --source-path."}];let a=n.findIndex(o=>o.root===D(e,r));a<0?n.unshift({root:D(e,r),reason:"Hermes active profile has no retained live state database. Select a profile explicitly."}):n.unshift(...n.splice(a,1))}return(await mt(D(s,"state.db"))||!n.length)&&n.push({root:s}),n}catch(t){return[{root:s,reason:t instanceof Error?t.message:"Cannot inventory Hermes profiles. Select the exact --source-path."}]}}p(yt,"hermesLocations");function xe(s){return/^[a-z0-9][a-z0-9._-]{0,63}$/u.test(s)&&!s.endsWith(".")&&!/^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/iu.test(s)}p(xe,"validOmpProfile");async function Et(s,e){let t=D(s,e.PI_CONFIG_DIR||".omp"),n=(e.OMP_PROFILE!==void 0?e.OMP_PROFILE:e.PI_PROFILE)?.trim();if(n&&n!=="default"&&!xe(n))return[{root:t,reason:"Oh My Pi profile is invalid. Select the exact --source-path."}];if(e.PI_CODING_AGENT_SESSION_DIR)return[{root:je(e.PI_CODING_AGENT_SESSION_DIR)}];let r=(process.platform==="linux"||process.platform==="darwin")&&e.XDG_DATA_HOME?D(e.XDG_DATA_HOME,"omp"):void 0;async function i(a){let o=a?D(t,"profiles",a,"agent"):D(t,"agent"),l=e.PI_PROFILE?.trim(),c=l&&xe(l)?D(t,"profiles",l,"agent"):void 0,f=!a&&e.PI_CODING_AGENT_DIR&&e.PI_CODING_AGENT_DIR!==c?je(e.PI_CODING_AGENT_DIR):void 0,u=r&&(a?D(r,"profiles",a):r);return{root:(!f||f===o)&&u&&await ht(u)?u:f||o}}if(p(i,"location"),n||e.OMP_PROFILE!==void 0||e.PI_PROFILE!==void 0||e.PI_CODING_AGENT_DIR)return[await i(n&&n!=="default"?n:void 0)];try{let a=new Set(await We(D(t,"profiles"),xe));if(r)for(let l of await We(D(r,"profiles"),xe))a.add(l);let o=[await i()];for(let l of[...a].sort()){let c=await i(l);await ht(D(c.root,"sessions"))&&o.push(c)}return o}catch(a){return[{root:t,reason:a instanceof Error?a.message:"Cannot inventory Oh My Pi profiles. Select the exact --source-path."}]}}p(Et,"ompLocations");async function ar(s){let e=s.home??As(),t=s.environment??process.env,n={codex:t.CODEX_HOME||X(e,".codex"),claude_code:t.CLAUDE_CONFIG_DIR||X(e,".claude"),hermes:gt(e,t),openclaw:t.OPENCLAW_STATE_DIR||X(e,".openclaw"),opencode:X(t.XDG_DATA_HOME||X(e,".local/share"),"opencode"),grok_build:t.GROK_HOME||X(e,".grok"),pi:t.PI_CODING_AGENT_DIR||X(e,".pi/agent"),oh_my_pi:X(e,".omp/agent")},r=n.pi,i=!1;if(t.PI_CODING_AGENT_SESSION_DIR)n.pi=Je(t.PI_CODING_AGENT_SESSION_DIR);else if(!s.locations?.pi)try{let o=X(r,"settings.json");if((await ze(o)).size<=1024*1024){let l=JSON.parse(await ks(o,"utf8"));typeof l.sessionDir=="string"&&l.sessionDir.trim()&&(Ds(l.sessionDir)?n.pi=l.sessionDir:i=!0)}}catch{}let a=[];for(let o of Object.keys(ut)){let l=s.locations?.[o]?[{root:s.locations[o]}]:o==="hermes"?await yt(Je(n.hermes)):o==="oh_my_pi"?await Et(e,t):[{root:n[o]}];for(let c of l){let f=Je(c.root),u=!1,h=!1;try{f=await wt(f);let g=await ze(f);h=g.isFile(),u=g.isDirectory()||h}catch{}if(c.reason&&(u=!1),o==="openclaw"&&u&&!h){let g=X(f,"agents"),w=await Ls(g,{withFileTypes:!0}).catch(()=>[]),y=[];for(let m of w.slice(0,100)){if(!m.isDirectory()||m.isSymbolicLink())continue;let d=X(g,m.name,"agent","openclaw-agent.sqlite");await ze(d).then(E=>E.isFile()).catch(()=>!1)&&y.push(await wt(d))}if(y.length){for(let m of y)a.push({source:o,root:m,machineId:s.machineId,instanceId:`native-${O([s.machineId,o,m]).slice(0,40)}`,acquisition:"sqlite",available:!0,capabilities:{history:!0,live:!0,nativeResume:!1}});continue}}if(o==="pi"&&i&&!s.locations?.pi){a.push({source:o,root:f,machineId:s.machineId,instanceId:`native-${O([s.machineId,o,f]).slice(0,40)}`,acquisition:"files",available:!1,capabilities:{history:!1,live:!1,nativeResume:!1},reason:"Pi config uses a working-directory-relative sessionDir. Select its resolved directory with --source-path."});continue}a.push({source:o,root:f,machineId:s.machineId,instanceId:`native-${O([s.machineId,o,f]).slice(0,40)}`,acquisition:h&&!/\.(?:db|sqlite)$/u.test(f)?"files":o==="hermes"||o==="opencode"||o==="openclaw"&&h?"sqlite":o==="openclaw"?"bundle":"files",available:u,capabilities:{history:u,live:u&&(o!=="openclaw"||h),nativeResume:!1},...u?{}:{reason:c.reason??"Source location is missing or unreadable. Select a custom location."}})}}return a.filter((o,l)=>a.findIndex(c=>c.instanceId===o.instanceId)===l)}p(ar,"discoverSources");var Se=class extends Error{static{p(this,"ConnectedSessionWithoutUserRequestError")}constructor(){super("The session has no retained user request.")}};function F(s,e="milliseconds"){if(typeof s!="number"&&typeof s!="string")return null;let t=new Date(typeof s=="number"&&e==="seconds"?s*1e3:s);return Number.isFinite(t.getTime())?t.toISOString():null}p(F,"connectedTimestamp");function Ge(s){return{path:s.path,contentHash:O(s.text),sizeBytes:new TextEncoder().encode(s.text).length}}p(Ge,"connectedFileIdentity");function U(s){if(s.events.length+(s.unmappedEvents?.length??0)>$.events)throw new Error("connected_event_limit");let e=s.events.map((c,f)=>({...c,sequence:f}));if(new Set(e.map(c=>c.id)).size!==e.length)throw new Error("connected_duplicate_event");let t=e.flatMap((c,f)=>c.kind==="message"&&c.role==="user"?[f]:[]);if(!t.length)throw new Se;if(t.length+(s.includeConversation===!1?0:1)>$.boundaries)throw new Error("connected_boundary_limit");let n=`family-${O([s.origin,...s.acquisition?[s.acquisition.sourceInstanceId]:[],s.parentSessionId??s.sessionId]).slice(0,32)}`,r=ft(e,t.map(c=>c+1)),i=e.findIndex(c=>c.kind==="compaction"),a=t.map((c,f)=>{let u=t[f+1]??e.length,h=e.slice(c+1,u),g=h.filter(Be).at(-1),w=h.filter(v=>v.kind==="tool_call"||v.kind==="tool_result"),y=new Set(w.filter(v=>v.kind==="tool_call").map(v=>v.callId)),m=new Set(w.filter(v=>v.kind==="tool_result").map(v=>v.callId)),d=w.some(v=>!v.callId)||[...y].some(v=>!m.has(v))||[...m].some(v=>!y.has(v)),E=[...h].reverse().find(v=>v.kind==="terminal"),S=E&&typeof E.content=="object"&&E.content!==null&&!Array.isArray(E.content)?E.content.status:null,b=i>=0&&i<=c,N=h.some(v=>v.kind==="unknown");return{id:`case-${O([s.origin,...s.acquisition?[s.acquisition.sourceInstanceId]:[],s.sessionId,s.branchId??null,e[c].id]).slice(0,40)}`,familyKey:n,projection:"turn",requestEventId:e[c].id,start:c,end:u,inputHash:r[f],outputHash:g?O(g.content):null,revisionHash:O(h),terminal:S==="completed"||S==="failed"||S==="cancelled"?S:"unknown",coverage:{answer:!!g,context:s.contextComplete===!1?"unknown":b?"compacted":"retained",process:w.length?d||N?"partial":"retained":N?"partial":"absent",artifacts:h.some(v=>v.kind==="artifact")?"references_only":"absent",replay:"unavailable",gaps:[...g?[]:["No recorded assistant answer."],...s.contextComplete===!1?["The source omits preceding context."]:[],...b?["Earlier context was compacted by the source."]:[],...d?["Tool call/result correlation is incomplete."]:[],...N?["Some source events have no supported process mapping."]:[],...E?[]:["No terminal receipt was recorded."],"No resettable execution environment was admitted."]}}});if(s.includeConversation!==!1){let c=a[0],f=a.at(-1),u=e.slice(c.start+1),h=u.filter(Be);a.push({...c,id:`conversation-${O([s.origin,...s.acquisition?[s.acquisition.sourceInstanceId]:[],s.sessionId,s.branchId??null]).slice(0,40)}`,projection:"conversation",end:e.length,outputHash:h.length?O(h.map(g=>g.content)):null,revisionHash:O(u),terminal:f.terminal,coverage:{...c.coverage,answer:h.length>0,process:a.some(g=>g.coverage.process==="partial")?"partial":a.some(g=>g.coverage.process==="retained")?"retained":"absent",context:a.some(g=>g.coverage.context==="unknown")?"unknown":a.some(g=>g.coverage.context==="compacted")?"compacted":"retained",artifacts:a.some(g=>g.coverage.artifacts==="references_only")?"references_only":"absent",gaps:[...new Set(a.flatMap(g=>g.coverage.gaps))].slice(0,100)}})}let o={schemaVersion:dt,normalizerVersion:Ee,origin:s.origin,sessionId:s.sessionId,branchId:s.branchId??null,parentSessionId:s.parentSessionId??null,exporterVersion:s.exporterVersion??null,sourceFiles:s.files.map(Ge).sort((c,f)=>c.path.localeCompare(f.path)),...s.acquisition?{acquisition:s.acquisition}:{},...s.repositoryContext?{repositoryContext:s.repositoryContext}:{},events:e,unmappedEvents:(s.unmappedEvents??[]).map((c,f)=>({...c,sequence:f})),boundaries:a,warnings:s.warnings??[]},l=lt.parse({...o,contentHash:O(o)});if(new TextEncoder().encode(JSON.stringify(l)).length>$.decodedBytes)throw new Error("connected_normalized_size_limit");return l}p(U,"normalizeConnectedSession");function Q(s){if(new TextEncoder().encode(s.text).length>$.decodedBytes)throw new Error("Decoded source files exceed 64 MiB.");let e=s.text.replace(/^\uFEFF/u,"").split(/\r?\n/u);if(e.length>$.events+1)throw new Error("connected_event_limit");return e.flatMap((t,n)=>{if(!t.trim())return[];if(new TextEncoder().encode(t).length>$.lineBytes)throw new Error(`Source line ${n+1} exceeds the limit.`);let r;try{r=JSON.parse(t)}catch{throw new Error(`Invalid JSON on line ${n+1}.`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Unsupported record on line ${n+1}.`);return[r]})}p(Q,"connectedJsonLines");function _(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)?s:{}}p(_,"object");function I(s){return{sequence:0,occurredAt:null,role:null,callId:null,parentId:null,usage:null,...s}}p(I,"event");function T(s){return JSON.parse(JSON.stringify(s??null))}p(T,"json");function z(s,e,t="reported_invocation"){let n=_(s),r=p((...c)=>{let f=c.find(u=>typeof u=="number"&&Number.isSafeInteger(u)&&u>=0);return typeof f=="number"?f:null},"number"),i=r(n.input_tokens,n.prompt_tokens),a=r(n.output_tokens,n.completion_tokens),o=r(n.cache_read_input_tokens,n.cached_input_tokens,_(n.input_tokens_details).cached_tokens),l=r(n.total_tokens);return i===null&&a===null&&o===null&&l===null?null:{invocationId:e,inputTokens:i,outputTokens:a,cachedInputTokens:o,totalTokens:l,provenance:t}}p(z,"sourceUsage");function St(s,e){let t=new Set(e.map(c=>_(c.params).sessionId).filter(c=>typeof c=="string"));if(t.size!==1)throw new Error("Grok Build updates must identify exactly one retained session.");let n=[],r=new Set,i=new Map,a=null,o=null,l=!0;for(let c of e){let f=_(c.params),u=_(f.update),h=_(f._meta),g=u.sessionUpdate;if(typeof h.eventId!="string"||r.has(h.eventId))throw new Error("Grok Build updates require unique native event IDs.");r.add(h.eventId);let w=h.eventId,y=F(h.agentTimestampMs??(typeof c.timestamp=="number"?c.timestamp*1e3:null)),m=_(u.content);if(g==="user_message_chunk"){if(m.type!=="text"||typeof m.text!="string")throw new Error("Grok user content type requires a qualified adapter.");!a||l?(a=I({id:w,kind:"message",role:"user",occurredAt:y,content:m.text}),n.push(a),o=null,l=!1):a.content=String(a.content)+m.text}else if(g==="agent_message_chunk"){if(m.type!=="text"||typeof m.text!="string"){n.push(I({id:w,kind:"unknown",occurredAt:y,content:T(u)}));continue}o?o.content=String(o.content)+m.text:(o=I({id:w,kind:"message",role:"assistant",occurredAt:y,content:m.text}),n.push(o))}else if(g==="tool_call"||g==="tool_call_update"){let d=typeof u.toolCallId=="string"?u.toolCallId:null;if(!d){n.push(I({id:w,kind:"unknown",occurredAt:y,content:T(u)}));continue}let E=i.get(d);E?u.rawInput!==void 0&&(E.content=T({title:u.title,input:u.rawInput})):(E=I({id:`${w}:call`,kind:"tool_call",callId:d,occurredAt:y,content:T({title:u.title,input:u.rawInput})}),i.set(d,E),n.push(E)),(u.status==="completed"||u.status==="failed")&&n.push(I({id:`${w}:result`,kind:"tool_result",role:"tool",callId:d,occurredAt:y,content:T({status:u.status,output:u.rawOutput,content:u.content})}))}else if(g==="turn_completed"){let d=_(u.usage),E=typeof u.prompt_id=="string"?u.prompt_id:w;n.push(I({id:w,kind:"terminal",occurredAt:y,content:{status:u.stop_reason==="end_turn"?"completed":u.stop_reason==="cancelled"?"cancelled":"failed"},usage:z({input_tokens:d.inputTokens,output_tokens:d.outputTokens,cached_input_tokens:d.cachedReadTokens,total_tokens:d.totalTokens},E)})),l=!0,o=null,a=null}else g!=="agent_thought_chunk"&&n.push(I({id:w,kind:"unknown",occurredAt:y,content:T(u)}))}return U({origin:"grok_build",sessionId:String([...t][0]),files:[s],events:n,contextComplete:!1,warnings:["Grok retained ACP updates omit system context and encrypted reasoning. Tool coverage reflects only logged updates."]})}p(St,"parseGrokBuildSession");function _t(s,e,t,n){let r=e.filter(d=>d.type==="session"),i=r[0];if(r.length!==1||!i||!(t==="openclaw"?[3,4].includes(Number(i.version)):i.version===3)||typeof i.id!="string")throw new Error("Unsupported native session tree version.");let a,l=(t!=="openclaw"?e:e.map(d=>{if(d.type==="session")return d;if(d.type==="leaf"){if(typeof d.targetId!="string")throw new Error("OpenClaw leaf control does not select a retained entry.");return a=d.targetId,d}if(typeof d.id!="string")throw new Error("OpenClaw transcript entry is missing its native identity.");let E=d.parentId===void 0?a??null:d.parentId;return d.appendMode!=="side"&&(a=d.id),{...d,parentId:E}})).filter(d=>d.type!=="session"&&d.type!=="title"&&d.type!=="leaf"),c=new Map,f=new Set;for(let d of l){if(typeof d.id!="string"||c.has(d.id))throw new Error("Session tree has missing or duplicate entry identities.");c.set(d.id,d),typeof d.parentId=="string"&&f.add(d.parentId)}n??=a;let u=[...c.keys()].filter(d=>!f.has(d));if(!n&&u.length!==1)throw new Error("Select a branch leaf for this branched session.");let h=n??u[0];if(!h||!c.has(h))throw new Error("The selected session branch is unavailable.");let g=[],w=new Set,y=h;for(;y;){if(w.has(y))throw new Error("Session branch contains a cycle.");w.add(y);let d=c.get(y);if(!d)throw new Error("Session branch has a missing ancestor.");g.push(d),y=typeof d.parentId=="string"?d.parentId:null}g.reverse();let m=[];for(let d of g){let E=String(d.id),S={occurredAt:F(d.timestamp),parentId:typeof d.parentId=="string"?d.parentId:null};if(d.type==="compaction"||d.type==="branch_summary"){m.push(I({...S,id:E,kind:"compaction",content:T({summary:d.summary,firstKeptEntryId:d.firstKeptEntryId})}));continue}if(d.type!=="message")continue;let b=_(d.message),N=b.role;if(N==="toolResult"){m.push(I({...S,id:E,kind:"tool_result",role:"tool",callId:typeof b.toolCallId=="string"?b.toolCallId:null,content:T({content:b.content,isError:b.isError===!0})}));continue}if(N!=="user"&&N!=="assistant"&&N!=="system"){m.push(I({...S,id:E,kind:"unknown",content:T({role:N,content:b.content})}));continue}let v=Array.isArray(b.content)?b.content.map(_):[],L=typeof b.content=="string"?b.content:v.filter(C=>C.type==="text").map(C=>String(C.text??"")).join(`
|
|
8
|
-
`),
|
|
9
|
-
`),g=_(o.tokens),w=_(g.cache),y=z({input_tokens:g.input,output_tokens:g.output,cached_input_tokens:w.read,total_tokens:g.total},o.id);h||c==="user"?r.push(I({...f,id:o.id,kind:"message",role:c,content:h,usage:y})):y&&r.push(I({...f,id:`${o.id}:usage`,kind:"usage",content:null,usage:y}));for(let m of u){let d=String(m.id);if(m.type==="tool"){let E=_(m.state),S=typeof m.callID=="string"?m.callID:null;r.push(I({...f,id:`${d}:call`,kind:"tool_call",callId:S,content:T({name:m.tool,arguments:E.input})})),(E.status==="completed"||E.status==="error")&&r.push(I({...f,id:`${d}:result`,kind:"tool_result",role:"tool",callId:S,content:T({output:E.output,error:E.error,status:E.status})}))}else m.type==="compaction"?r.push(I({...f,id:d,kind:"compaction",content:T(m)})):["text","reasoning","step-start","step-finish"].includes(String(m.type))||r.push(I({...f,id:d,kind:"unknown",content:T(m)}))}c==="assistant"&&(o.finish==="stop"||o.error)&&r.push(I({...f,id:`${o.id}:terminal`,kind:"terminal",content:{status:o.error?"failed":"completed"}}))}return U({origin:"opencode",sessionId:n.id,parentSessionId:typeof n.parentID=="string"?n.parentID:null,exporterVersion:typeof n.version=="string"?n.version:null,files:[s],events:r,warnings:["Source-reported usage is not an OpenPond billing receipt."]})}p(
|
|
7
|
+
`).digestHex()})}p(ht,"contentHashArrayPrefixes");function Pe(s){if(s===null||typeof s=="boolean"||typeof s=="number"||typeof s=="string")return s;if(Array.isArray(s))return Array.from({length:s.length},(t,n)=>{let r=Object.getOwnPropertyDescriptor(s,n);if(!r||r.get||r.set)throw new TypeError("Canonical array prefixes require plain JSON values");return Pe(r.value)});let e=s&&typeof s=="object"?Object.getPrototypeOf(s):void 0;if(s&&typeof s=="object"&&(e===Object.prototype||e===null))return Object.fromEntries(Object.keys(s).sort((t,n)=>t.localeCompare(n)).map(t=>{let n=Object.getOwnPropertyDescriptor(s,t);if(n.get||n.set)throw new TypeError("Canonical array prefixes require plain JSON values");return[t,Pe(n.value)]}));throw new TypeError("Canonical array prefixes require plain JSON values")}p(Pe,"sortJsonValue");import{opendir as Cs,readFile as Rs,stat as xe}from"node:fs/promises";import{basename as As,dirname as Ls,join as k,resolve as je}from"node:path";function yt(s,e){let t=e.HERMES_HOME?.trim();if(t){let r=t.replace(/\$(\w+)|\$\{([^}]+)\}/gu,(i,a,o)=>e[a||o]??i);return je(r==="~"?s:r.startsWith("~/")?k(s,r.slice(2)):r)}let n=e.HERMES_DATA_DIR_SUFFIX||"";return process.platform==="win32"?k(e.LOCALAPPDATA?.trim()||k(s,"AppData","Local"),`hermes${n}`):k(s,`.hermes${n}`)}p(yt,"hermesHome");var mt=p(s=>xe(s).then(e=>e.isDirectory()).catch(()=>!1),"isDirectory"),gt=p(s=>xe(s).then(e=>e.isFile()).catch(()=>!1),"isFile");async function We(s,e){let t=[],n=await Cs(s).catch(()=>null);if(!n)return t;let r=0;for await(let i of n){if(++r>100)throw new Error("More than 100 profile entries. Select the exact --source-path.");i.isDirectory()&&!i.isSymbolicLink()&&e(i.name)&&t.push(i.name)}return t.sort()}p(We,"profileNames");async function Et(s){if(As(Ls(s))==="profiles")return[{root:s}];let e=k(s,"profiles");try{let t=await We(e,a=>/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(a)),n=[];for(let a of t)await xe(k(e,".deleted",a)).then(()=>!0).catch(()=>!1)||await gt(k(e,a,"state.db"))&&n.push({root:k(e,a)});let r="",i=k(s,"active_profile");if(await xe(i).then(a=>a.isFile()&&a.size<=1024).catch(()=>!1)&&(r=(await Rs(i,"utf8")).replace(/^\uFEFF/u,"").trim().toLowerCase()),r&&r!=="default"){if(!/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(r))return[{root:s,reason:"Hermes active profile is invalid. Select the exact --source-path."}];let a=n.findIndex(o=>o.root===k(e,r));a<0?n.unshift({root:k(e,r),reason:"Hermes active profile has no retained live state database. Select a profile explicitly."}):n.unshift(...n.splice(a,1))}return(await gt(k(s,"state.db"))||!n.length)&&n.push({root:s}),n}catch(t){return[{root:s,reason:t instanceof Error?t.message:"Cannot inventory Hermes profiles. Select the exact --source-path."}]}}p(Et,"hermesLocations");function Ne(s){return/^[a-z0-9][a-z0-9._-]{0,63}$/u.test(s)&&!s.endsWith(".")&&!/^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/iu.test(s)}p(Ne,"validOmpProfile");async function wt(s,e){let t=k(s,e.PI_CONFIG_DIR||".omp"),n=(e.OMP_PROFILE!==void 0?e.OMP_PROFILE:e.PI_PROFILE)?.trim();if(n&&n!=="default"&&!Ne(n))return[{root:t,reason:"Oh My Pi profile is invalid. Select the exact --source-path."}];if(e.PI_CODING_AGENT_SESSION_DIR)return[{root:je(e.PI_CODING_AGENT_SESSION_DIR)}];let r=(process.platform==="linux"||process.platform==="darwin")&&e.XDG_DATA_HOME?k(e.XDG_DATA_HOME,"omp"):void 0;async function i(a){let o=a?k(t,"profiles",a,"agent"):k(t,"agent"),l=e.PI_PROFILE?.trim(),c=l&&Ne(l)?k(t,"profiles",l,"agent"):void 0,f=!a&&e.PI_CODING_AGENT_DIR&&e.PI_CODING_AGENT_DIR!==c?je(e.PI_CODING_AGENT_DIR):void 0,u=r&&(a?k(r,"profiles",a):r);return{root:(!f||f===o)&&u&&await mt(u)?u:f||o}}if(p(i,"location"),n||e.OMP_PROFILE!==void 0||e.PI_PROFILE!==void 0||e.PI_CODING_AGENT_DIR)return[await i(n&&n!=="default"?n:void 0)];try{let a=new Set(await We(k(t,"profiles"),Ne));if(r)for(let l of await We(k(r,"profiles"),Ne))a.add(l);let o=[await i()];for(let l of[...a].sort()){let c=await i(l);await mt(k(c.root,"sessions"))&&o.push(c)}return o}catch(a){return[{root:t,reason:a instanceof Error?a.message:"Cannot inventory Oh My Pi profiles. Select the exact --source-path."}]}}p(wt,"ompLocations");async function cr(s){let e=s.home??ks(),t=s.environment??process.env,n={codex:t.CODEX_HOME||X(e,".codex"),claude_code:t.CLAUDE_CONFIG_DIR||X(e,".claude"),hermes:yt(e,t),openclaw:t.OPENCLAW_STATE_DIR||X(e,".openclaw"),opencode:X(t.XDG_DATA_HOME||X(e,".local/share"),"opencode"),grok_build:t.GROK_HOME||X(e,".grok"),pi:t.PI_CODING_AGENT_DIR||X(e,".pi/agent"),oh_my_pi:X(e,".omp/agent")},r=n.pi,i=!1;if(t.PI_CODING_AGENT_SESSION_DIR)n.pi=Je(t.PI_CODING_AGENT_SESSION_DIR);else if(!s.locations?.pi)try{let o=X(r,"settings.json");if((await ze(o)).size<=1024*1024){let l=JSON.parse(await Ms(o,"utf8"));typeof l.sessionDir=="string"&&l.sessionDir.trim()&&($s(l.sessionDir)?n.pi=l.sessionDir:i=!0)}}catch{}let a=[];for(let o of Object.keys(ft)){let l=s.locations?.[o]?[{root:s.locations[o]}]:o==="hermes"?await Et(Je(n.hermes)):o==="oh_my_pi"?await wt(e,t):[{root:n[o]}];for(let c of l){let f=Je(c.root),u=!1,h=!1;try{f=await St(f);let g=await ze(f);h=g.isFile(),u=g.isDirectory()||h}catch{}if(c.reason&&(u=!1),o==="openclaw"&&u&&!h){let g=X(f,"agents"),w=await Ds(g,{withFileTypes:!0}).catch(()=>[]),y=[];for(let m of w.slice(0,100)){if(!m.isDirectory()||m.isSymbolicLink())continue;let d=X(g,m.name,"agent","openclaw-agent.sqlite");await ze(d).then(E=>E.isFile()).catch(()=>!1)&&y.push(await St(d))}if(y.length){for(let m of y)a.push({source:o,root:m,machineId:s.machineId,instanceId:`native-${O([s.machineId,o,m]).slice(0,40)}`,acquisition:"sqlite",available:!0,capabilities:{history:!0,live:!0,nativeResume:!1}});continue}}if(o==="pi"&&i&&!s.locations?.pi){a.push({source:o,root:f,machineId:s.machineId,instanceId:`native-${O([s.machineId,o,f]).slice(0,40)}`,acquisition:"files",available:!1,capabilities:{history:!1,live:!1,nativeResume:!1},reason:"Pi config uses a working-directory-relative sessionDir. Select its resolved directory with --source-path."});continue}a.push({source:o,root:f,machineId:s.machineId,instanceId:`native-${O([s.machineId,o,f]).slice(0,40)}`,acquisition:h&&!/\.(?:db|sqlite)$/u.test(f)?"files":o==="hermes"||o==="opencode"||o==="openclaw"&&h?"sqlite":o==="openclaw"?"bundle":"files",available:u,capabilities:{history:u,live:u&&(o!=="openclaw"||h),nativeResume:!1},...u?{}:{reason:c.reason??"Source location is missing or unreadable. Select a custom location."}})}}return a.filter((o,l)=>a.findIndex(c=>c.instanceId===o.instanceId)===l)}p(cr,"discoverSources");var Se=class extends Error{static{p(this,"ConnectedSessionWithoutUserRequestError")}constructor(){super("The session has no retained user request.")}};function F(s,e="milliseconds"){if(typeof s!="number"&&typeof s!="string")return null;let t=new Date(typeof s=="number"&&e==="seconds"?s*1e3:s);return Number.isFinite(t.getTime())?t.toISOString():null}p(F,"connectedTimestamp");function Ge(s){return{path:s.path,contentHash:O(s.text),sizeBytes:new TextEncoder().encode(s.text).length}}p(Ge,"connectedFileIdentity");function U(s){if(s.events.length+(s.unmappedEvents?.length??0)>$.events)throw new Error("connected_event_limit");let e=s.events.map((c,f)=>({...c,sequence:f}));if(new Set(e.map(c=>c.id)).size!==e.length)throw new Error("connected_duplicate_event");let t=e.flatMap((c,f)=>c.kind==="message"&&c.role==="user"?[f]:[]);if(!t.length)throw new Se;if(t.length+(s.includeConversation===!1?0:1)>$.boundaries)throw new Error("connected_boundary_limit");let n=`family-${O([s.origin,...s.acquisition?[s.acquisition.sourceInstanceId]:[],s.parentSessionId??s.sessionId]).slice(0,32)}`,r=ht(e,t.map(c=>c+1)),i=e.findIndex(c=>c.kind==="compaction"),a=t.map((c,f)=>{let u=t[f+1]??e.length,h=e.slice(c+1,u),g=h.filter(Be).at(-1),w=h.filter(v=>v.kind==="tool_call"||v.kind==="tool_result"),y=new Set(w.filter(v=>v.kind==="tool_call").map(v=>v.callId)),m=new Set(w.filter(v=>v.kind==="tool_result").map(v=>v.callId)),d=w.some(v=>!v.callId)||[...y].some(v=>!m.has(v))||[...m].some(v=>!y.has(v)),E=[...h].reverse().find(v=>v.kind==="terminal"),S=E&&typeof E.content=="object"&&E.content!==null&&!Array.isArray(E.content)?E.content.status:null,b=i>=0&&i<=c,N=h.some(v=>v.kind==="unknown");return{id:`case-${O([s.origin,...s.acquisition?[s.acquisition.sourceInstanceId]:[],s.sessionId,s.branchId??null,e[c].id]).slice(0,40)}`,familyKey:n,projection:"turn",requestEventId:e[c].id,start:c,end:u,inputHash:r[f],outputHash:g?O(g.content):null,revisionHash:O(h),terminal:S==="completed"||S==="failed"||S==="cancelled"?S:"unknown",coverage:{answer:!!g,context:s.contextComplete===!1?"unknown":b?"compacted":"retained",process:w.length?d||N?"partial":"retained":N?"partial":"absent",artifacts:h.some(v=>v.kind==="artifact")?"references_only":"absent",replay:"unavailable",gaps:[...g?[]:["No recorded assistant answer."],...s.contextComplete===!1?["The source omits preceding context."]:[],...b?["Earlier context was compacted by the source."]:[],...d?["Tool call/result correlation is incomplete."]:[],...N?["Some source events have no supported process mapping."]:[],...E?[]:["No terminal receipt was recorded."],"No resettable execution environment was admitted."]}}});if(s.includeConversation!==!1){let c=a[0],f=a.at(-1),u=e.slice(c.start+1),h=u.filter(Be);a.push({...c,id:`conversation-${O([s.origin,...s.acquisition?[s.acquisition.sourceInstanceId]:[],s.sessionId,s.branchId??null]).slice(0,40)}`,projection:"conversation",end:e.length,outputHash:h.length?O(h.map(g=>g.content)):null,revisionHash:O(u),terminal:f.terminal,coverage:{...c.coverage,answer:h.length>0,process:a.some(g=>g.coverage.process==="partial")?"partial":a.some(g=>g.coverage.process==="retained")?"retained":"absent",context:a.some(g=>g.coverage.context==="unknown")?"unknown":a.some(g=>g.coverage.context==="compacted")?"compacted":"retained",artifacts:a.some(g=>g.coverage.artifacts==="references_only")?"references_only":"absent",gaps:[...new Set(a.flatMap(g=>g.coverage.gaps))].slice(0,100)}})}let o={schemaVersion:lt,normalizerVersion:Ee,origin:s.origin,sessionId:s.sessionId,branchId:s.branchId??null,parentSessionId:s.parentSessionId??null,exporterVersion:s.exporterVersion??null,sourceFiles:s.files.map(Ge).sort((c,f)=>c.path.localeCompare(f.path)),...s.acquisition?{acquisition:s.acquisition}:{},...s.repositoryContext?{repositoryContext:s.repositoryContext}:{},events:e,unmappedEvents:(s.unmappedEvents??[]).map((c,f)=>({...c,sequence:f})),boundaries:a,warnings:s.warnings??[]},l=pt.parse({...o,contentHash:O(o)});if(new TextEncoder().encode(JSON.stringify(l)).length>$.decodedBytes)throw new Error("connected_normalized_size_limit");return l}p(U,"normalizeConnectedSession");function Q(s){if(new TextEncoder().encode(s.text).length>$.decodedBytes)throw new Error("Decoded source files exceed 64 MiB.");let e=s.text.replace(/^\uFEFF/u,"").split(/\r?\n/u);if(e.length>$.events+1)throw new Error("connected_event_limit");return e.flatMap((t,n)=>{if(!t.trim())return[];if(new TextEncoder().encode(t).length>$.lineBytes)throw new Error(`Source line ${n+1} exceeds the limit.`);let r;try{r=JSON.parse(t)}catch{throw new Error(`Invalid JSON on line ${n+1}.`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`Unsupported record on line ${n+1}.`);return[r]})}p(Q,"connectedJsonLines");function _(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)?s:{}}p(_,"object");function I(s){return{sequence:0,occurredAt:null,role:null,callId:null,parentId:null,usage:null,...s}}p(I,"event");function T(s){return JSON.parse(JSON.stringify(s??null))}p(T,"json");function z(s,e,t="reported_invocation"){let n=_(s),r=p((...c)=>{let f=c.find(u=>typeof u=="number"&&Number.isSafeInteger(u)&&u>=0);return typeof f=="number"?f:null},"number"),i=r(n.input_tokens,n.prompt_tokens),a=r(n.output_tokens,n.completion_tokens),o=r(n.cache_read_input_tokens,n.cached_input_tokens,_(n.input_tokens_details).cached_tokens),l=r(n.total_tokens);return i===null&&a===null&&o===null&&l===null?null:{invocationId:e,inputTokens:i,outputTokens:a,cachedInputTokens:o,totalTokens:l,provenance:t}}p(z,"sourceUsage");function _t(s,e){let t=new Set(e.map(c=>_(c.params).sessionId).filter(c=>typeof c=="string"));if(t.size!==1)throw new Error("Grok Build updates must identify exactly one retained session.");let n=[],r=new Set,i=new Map,a=null,o=null,l=!0;for(let c of e){let f=_(c.params),u=_(f.update),h=_(f._meta),g=u.sessionUpdate;if(typeof h.eventId!="string"||r.has(h.eventId))throw new Error("Grok Build updates require unique native event IDs.");r.add(h.eventId);let w=h.eventId,y=F(h.agentTimestampMs??(typeof c.timestamp=="number"?c.timestamp*1e3:null)),m=_(u.content);if(g==="user_message_chunk"){if(m.type!=="text"||typeof m.text!="string")throw new Error("Grok user content type requires a qualified adapter.");!a||l?(a=I({id:w,kind:"message",role:"user",occurredAt:y,content:m.text}),n.push(a),o=null,l=!1):a.content=String(a.content)+m.text}else if(g==="agent_message_chunk"){if(m.type!=="text"||typeof m.text!="string"){n.push(I({id:w,kind:"unknown",occurredAt:y,content:T(u)}));continue}o?o.content=String(o.content)+m.text:(o=I({id:w,kind:"message",role:"assistant",occurredAt:y,content:m.text}),n.push(o))}else if(g==="tool_call"||g==="tool_call_update"){let d=typeof u.toolCallId=="string"?u.toolCallId:null;if(!d){n.push(I({id:w,kind:"unknown",occurredAt:y,content:T(u)}));continue}let E=i.get(d);E?u.rawInput!==void 0&&(E.content=T({title:u.title,input:u.rawInput})):(E=I({id:`${w}:call`,kind:"tool_call",callId:d,occurredAt:y,content:T({title:u.title,input:u.rawInput})}),i.set(d,E),n.push(E)),(u.status==="completed"||u.status==="failed")&&n.push(I({id:`${w}:result`,kind:"tool_result",role:"tool",callId:d,occurredAt:y,content:T({status:u.status,output:u.rawOutput,content:u.content})}))}else if(g==="turn_completed"){let d=_(u.usage),E=typeof u.prompt_id=="string"?u.prompt_id:w;n.push(I({id:w,kind:"terminal",occurredAt:y,content:{status:u.stop_reason==="end_turn"?"completed":u.stop_reason==="cancelled"?"cancelled":"failed"},usage:z({input_tokens:d.inputTokens,output_tokens:d.outputTokens,cached_input_tokens:d.cachedReadTokens,total_tokens:d.totalTokens},E)})),l=!0,o=null,a=null}else g!=="agent_thought_chunk"&&n.push(I({id:w,kind:"unknown",occurredAt:y,content:T(u)}))}return U({origin:"grok_build",sessionId:String([...t][0]),files:[s],events:n,contextComplete:!1,warnings:["Grok retained ACP updates omit system context and encrypted reasoning. Tool coverage reflects only logged updates."]})}p(_t,"parseGrokBuildSession");function bt(s,e,t,n){let r=e.filter(d=>d.type==="session"),i=r[0];if(r.length!==1||!i||!(t==="openclaw"?[3,4].includes(Number(i.version)):i.version===3)||typeof i.id!="string")throw new Error("Unsupported native session tree version.");let a,l=(t!=="openclaw"?e:e.map(d=>{if(d.type==="session")return d;if(d.type==="leaf"){if(typeof d.targetId!="string")throw new Error("OpenClaw leaf control does not select a retained entry.");return a=d.targetId,d}if(typeof d.id!="string")throw new Error("OpenClaw transcript entry is missing its native identity.");let E=d.parentId===void 0?a??null:d.parentId;return d.appendMode!=="side"&&(a=d.id),{...d,parentId:E}})).filter(d=>d.type!=="session"&&d.type!=="title"&&d.type!=="leaf"),c=new Map,f=new Set;for(let d of l){if(typeof d.id!="string"||c.has(d.id))throw new Error("Session tree has missing or duplicate entry identities.");c.set(d.id,d),typeof d.parentId=="string"&&f.add(d.parentId)}n??=a;let u=[...c.keys()].filter(d=>!f.has(d));if(!n&&u.length!==1)throw new Error("Select a branch leaf for this branched session.");let h=n??u[0];if(!h||!c.has(h))throw new Error("The selected session branch is unavailable.");let g=[],w=new Set,y=h;for(;y;){if(w.has(y))throw new Error("Session branch contains a cycle.");w.add(y);let d=c.get(y);if(!d)throw new Error("Session branch has a missing ancestor.");g.push(d),y=typeof d.parentId=="string"?d.parentId:null}g.reverse();let m=[];for(let d of g){let E=String(d.id),S={occurredAt:F(d.timestamp),parentId:typeof d.parentId=="string"?d.parentId:null};if(d.type==="compaction"||d.type==="branch_summary"){m.push(I({...S,id:E,kind:"compaction",content:T({summary:d.summary,firstKeptEntryId:d.firstKeptEntryId})}));continue}if(d.type!=="message")continue;let b=_(d.message),N=b.role;if(N==="toolResult"){m.push(I({...S,id:E,kind:"tool_result",role:"tool",callId:typeof b.toolCallId=="string"?b.toolCallId:null,content:T({content:b.content,isError:b.isError===!0})}));continue}if(N!=="user"&&N!=="assistant"&&N!=="system"){m.push(I({...S,id:E,kind:"unknown",content:T({role:N,content:b.content})}));continue}let v=Array.isArray(b.content)?b.content.map(_):[],A=typeof b.content=="string"?b.content:v.filter(R=>R.type==="text").map(R=>String(R.text??"")).join(`
|
|
8
|
+
`),M=_(b.usage),x=z({input_tokens:M.input,output_tokens:M.output,cached_input_tokens:M.cacheRead,total_tokens:M.totalTokens},E);A||N!=="assistant"?m.push(I({...S,id:E,kind:"message",role:N,content:N==="system"&&!A&&b.sections?T(b.sections):A,usage:x})):x&&m.push(I({...S,id:`${E}:usage`,kind:"usage",content:null,usage:x}));for(let[R,C]of v.entries())C.type==="toolCall"?m.push(I({...S,id:`${E}:call:${R}`,kind:"tool_call",callId:typeof C.id=="string"?C.id:null,content:T({name:C.name,arguments:C.arguments})})):C.type!=="text"&&C.type!=="thinking"&&m.push(I({...S,id:`${E}:block:${R}`,kind:"unknown",content:T(C)}));N==="assistant"&&["stop","error","aborted"].includes(String(b.stopReason))&&m.push(I({...S,id:`${E}:terminal`,kind:"terminal",content:{status:b.stopReason==="stop"?"completed":b.stopReason==="aborted"?"cancelled":"failed"}}))}return U({origin:t,sessionId:i.id,branchId:null,...t==="openclaw"?{contextComplete:!1}:{},files:[s],events:m,exporterVersion:`session-v${i.version}`,warnings:["Only the selected branch is included. Private provider payloads and credential metadata are excluded."]})}p(bt,"parsePiSession");function vt(s,e){let t=_(e),n=_(t.info);if(typeof n.id!="string"||!Array.isArray(t.messages))throw new Error("OpenCode requires its native JSON session export (info and messages).");let r=[];for(let i of t.messages){let a=_(i),o=_(a.info),l=_(o.time);if(typeof o.id!="string"||o.sessionID!==n.id||!Array.isArray(a.parts))throw new Error("OpenCode message identity does not match its session.");let c=o.role;if(c!=="user"&&c!=="assistant")throw new Error("Unsupported OpenCode message role.");let f={occurredAt:F(l.created),parentId:typeof o.parentID=="string"?o.parentID:null},u=a.parts.map(_);if(u.some(m=>m.sessionID!==n.id||m.messageID!==o.id||typeof m.id!="string"))throw new Error("OpenCode part identity does not match its message.");let h=u.filter(m=>m.type==="text").map(m=>String(m.text??"")).join(`
|
|
9
|
+
`),g=_(o.tokens),w=_(g.cache),y=z({input_tokens:g.input,output_tokens:g.output,cached_input_tokens:w.read,total_tokens:g.total},o.id);h||c==="user"?r.push(I({...f,id:o.id,kind:"message",role:c,content:h,usage:y})):y&&r.push(I({...f,id:`${o.id}:usage`,kind:"usage",content:null,usage:y}));for(let m of u){let d=String(m.id);if(m.type==="tool"){let E=_(m.state),S=typeof m.callID=="string"?m.callID:null;r.push(I({...f,id:`${d}:call`,kind:"tool_call",callId:S,content:T({name:m.tool,arguments:E.input})})),(E.status==="completed"||E.status==="error")&&r.push(I({...f,id:`${d}:result`,kind:"tool_result",role:"tool",callId:S,content:T({output:E.output,error:E.error,status:E.status})}))}else m.type==="compaction"?r.push(I({...f,id:d,kind:"compaction",content:T(m)})):["text","reasoning","step-start","step-finish"].includes(String(m.type))||r.push(I({...f,id:d,kind:"unknown",content:T(m)}))}c==="assistant"&&(o.finish==="stop"||o.error)&&r.push(I({...f,id:`${o.id}:terminal`,kind:"terminal",content:{status:o.error?"failed":"completed"}}))}return U({origin:"opencode",sessionId:n.id,parentSessionId:typeof n.parentID=="string"?n.parentID:null,exporterVersion:typeof n.version=="string"?n.version:null,files:[s],events:r,warnings:["Source-reported usage is not an OpenPond billing receipt."]})}p(vt,"parseOpenCodeSession");var Xe="codex-native-authorization-v1",Hs=Xe;function It(s){let e=[],t=p((i,a,o)=>{let l={policy:Hs,sourcePath:i,sourceHash:O(a),entries:o};return e.push(l),l},"omit"),n=p((i,a)=>i.replace(/<permissions instructions>[\s\S]*?<\/permissions instructions>/gu,o=>o.replace(/^## Approved command prefixes\r?\n[\s\S]*?(?=^## |<\/permissions instructions>)/gmu,l=>{let c=t(a,l,null);return`## Approved command prefixes
|
|
10
10
|
[Native authorization rules omitted; policy ${c.policy}; source hash ${c.sourceHash}]
|
|
11
|
-
`})),"permissionsText"),r=_(s.payload);if(s.type==="response_item"&&r.type==="message"&&["system","developer"].includes(String(r.role))){let i=typeof r.content=="string"?n(r.content,"/payload/content"):Array.isArray(r.content)?r.content.map((a,o)=>{let l=_(a);return typeof l.text=="string"?{...l,text:n(l.text,`/payload/content/${o}/text`)}:a}):r.content;return{row:{...s,payload:{...r,content:i}},omissions:e}}if(s.type==="world_state"){let i=_(r.state),a=_(i.permissions);if(Array.isArray(a.approved_command_prefixes)){let o=t("/payload/state/permissions/approved_command_prefixes",a.approved_command_prefixes,a.approved_command_prefixes.length);return{row:{...s,payload:{...r,state:{...i,permissions:{...a,approved_command_prefixes:{omitted:"native_authorization_state",...o}}}}},omissions:e}}}return{row:s,omissions:e}}p(vt,"projectCodexAuthorization");var ce=class{static{p(this,"CodexMetadataChain")}metadata=null;parentId=null;closed=!1;ids=new Set;accept(e){if(e.type!=="session_meta")return this.closed=!0,!0;let t=e.payload;if(this.closed||!t||typeof t!="object"||Array.isArray(t))return!1;let n=t;if(typeof n.id!="string"||!n.id||n.id.length>500||this.ids.has(n.id)||this.ids.size>=16)return!1;if(this.metadata){if(n.id!==this.parentId)return!1;for(let r of["creator_user_id","creator_account_id"])if(this.metadata[r]!=null&&n[r]!=null&&this.metadata[r]!==n[r])return!1}else this.metadata=n;return this.ids.add(n.id),this.parentId=typeof n.forked_from_id=="string"?n.forked_from_id:null,!0}};function It(s,e){let t=new ce;if(e.some(c=>!t.accept(c)))throw new Error("Codex rollout metadata does not match its declared fork ancestry.");let n=t.metadata??{};if(typeof n.id!="string")throw new Error("This is not a supported Codex rollout: session_meta.id is missing.");let r=_(n.git),i=typeof r.commit_hash=="string"&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(r.commit_hash)?{schemaVersion:"openpond.connectedRepositoryContext.v1",kind:"git",commitHash:r.commit_hash,branch:typeof r.branch=="string"&&r.branch.length>0&&r.branch.length<=500?r.branch:null,recordedAt:F(n.timestamp),sourceFileHash:Ge(s).contentHash,metadataHash:O(r)}:void 0;i&&typeof n.cwd=="string"&&Object.assign(i,{workingDirectoryHash:O(n.cwd)});let a=[],o=null,l=0;for(let[c,f]of e.entries()){let u=vt(f);l+=u.omissions.length;let h=_(u.row.payload);if(f.type==="session_meta")continue;if(f.type==="turn_context"){o=typeof h.turn_id=="string"?h.turn_id:o;continue}let w={id:typeof h.id=="string"?h.id:`codex-event-${O([c,f]).slice(0,32)}`,occurredAt:F(f.timestamp),parentId:o};if(f.type==="response_item")h.type==="message"&&["user","assistant","system","developer"].includes(String(h.role))?a.push(I({...w,kind:"message",role:h.role==="developer"?"system":h.role,content:T(h.content)})):h.type==="function_call"||h.type==="custom_tool_call"?a.push(I({...w,kind:"tool_call",callId:typeof h.call_id=="string"?h.call_id:null,content:T(h)})):h.type==="function_call_output"||h.type==="custom_tool_call_output"?a.push(I({...w,kind:"tool_result",role:"tool",callId:typeof h.call_id=="string"?h.call_id:null,content:T(h.output)})):a.push(I({...w,kind:"unknown",content:T(h)}));else if(f.type==="compacted")a.push(I({...w,kind:"compaction",content:T(h)}));else if(f.type==="event_msg"){if(["user_message","agent_message","agent_reasoning","task_started"].includes(String(h.type)))continue;if(h.type==="task_complete"||h.type==="turn_aborted")a.push(I({...w,kind:"terminal",content:{status:h.type==="task_complete"?"completed":"cancelled",source:T(h)}}));else if(h.type==="token_count"){let y=_(h.info),m=z(y.total_token_usage,`codex-cumulative:${n.id}:${c}`,"reported_cumulative");a.push(I({...w,kind:"usage",usage:m,content:T(h)}))}else a.push(I({...w,kind:"unknown",content:T(h)}))}else a.push(I({...w,kind:"unknown",content:T(u.row)}))}return U({origin:"codex",sessionId:n.id,parentSessionId:typeof n.forked_from_id=="string"?n.forked_from_id:null,exporterVersion:typeof n.cli_version=="string"?n.cli_version:null,files:[s],events:a,...i?{repositoryContext:i}:{},warnings:["Codex cumulative usage is retained as reported totals and is not summed as billed invocations.","Referenced files are unavailable unless separately admitted.",...l?[`Codex native authorization state excluded by codex-native-authorization-v1 from ${l} locations. Omission markers retain source-section hashes; sourceFiles retains original byte hashes. Other conversation evidence is unchanged and still requires privacy admission.`]:[]]})}p(It,"parseCodexSession");function _e(s){let e=s.filter(u=>(u.type==="user"||u.type==="assistant")&&typeof u.uuid=="string"),t=new Set(e.flatMap(u=>typeof u.sessionId=="string"?[u.sessionId]:[]));if(t.size!==1||!e.length)throw new Error("A supported Claude Code transcript must identify one session with UUID messages.");let n=[...t][0],r=s.filter(u=>typeof u.uuid=="string"&&u.sessionId===n),i=new Map(r.map(u=>[u.uuid,u]));if(i.size!==r.length)throw new Error("Claude Code transcript contains duplicate message UUIDs.");let a=new Set(r.flatMap(u=>typeof u.parentUuid=="string"?[u.parentUuid]:[])),o=r.filter(u=>!a.has(u.uuid));if(!o.length)throw new Error("Claude Code transcript has no selectable branch leaf.");function l(u){let h=i.get(u);if(!h)throw new Error("The selected Claude Code branch leaf is missing.");let g=[],w=new Set,y=!1;for(;h;){let m=h.uuid;if(w.has(m))throw new Error("Claude Code branch contains a parent cycle.");w.add(m),g.unshift(h);let d=h.parentUuid;if(typeof d!="string")break;h=i.get(d),h||(y=!0)}return{chain:g,missingParent:y,chainHash:O(g)}}p(l,"select");function c(){if(o.length>256)throw new Error("This transcript exceeds the 256-branch inspection limit.");return o.map(u=>{let h=l(u.uuid),g=h.chain.filter(d=>d.type==="user"||d.type==="assistant"),w=g.at(-1),y=_(w?.message).content,m=typeof y=="string"?y:Array.isArray(y)?y.flatMap(d=>typeof _(d).text=="string"?[_(d).text]:[]).join(" "):"";return{leafId:u.uuid,chainHash:h.chainHash,title:m.slice(0,180),updatedAt:F(w?.timestamp),messages:g.length}})}p(c,"branches");function f(){let u=new Set;for(let w of o){let y=w,m=new Set;for(;y;){let d=y.uuid;if(m.has(d))throw new Error("Claude Code branch contains a parent cycle.");if(m.add(d),y.type==="user"||y.type==="assistant"){u.add(d);break}y=typeof y.parentUuid=="string"?i.get(y.parentUuid):void 0}}let h,g;for(let w of r){let y=w.uuid;u.has(y)&&(g=y,!w.isSidechain&&!w.teamName&&!w.isMeta&&(h=y))}if(!h&&!g)throw new Error("Claude Code transcript has no conversation message.");return h??g}return p(f,"latestLeafId"),{sessionId:n,leaves:o,select:l,branches:c,latestLeafId:f}}p(_e,"claudeGraph");function Ot(s,e,t){let n=_e(e);if(!t&&n.leaves.length!==1)throw new Error("This transcript has multiple branches. Select a branch leaf UUID before importing.");let{chain:r,missingParent:i}=n.select(t??n.leaves[0].uuid),a=[];for(let o of r){if(o.type!=="user"&&o.type!=="assistant")continue;let l=_(o.message),c=l.content,f={occurredAt:F(o.timestamp),parentId:typeof o.parentUuid=="string"?o.parentUuid:null},u=o.type==="user"?"user":"assistant",h=Array.isArray(c)?c:[{type:"text",text:c}],g=h.filter(w=>_(w).type==="text");g.length&&a.push(I({...f,id:o.uuid,kind:"message",role:u,content:T(g)})),u==="assistant"&&l.usage&&a.push(I({...f,id:`${o.uuid}:usage`,kind:"usage",content:T(l.usage),usage:z(l.usage,typeof l.id=="string"?l.id:o.uuid)}));for(let[w,y]of h.entries()){let m=_(y);if(m.type==="text"||m.type==="thinking"||m.type==="redacted_thinking")continue;let d=`${o.uuid}:${w}`;m.type==="tool_use"?a.push(I({...f,id:d,kind:"tool_call",callId:typeof m.id=="string"?m.id:null,content:T(m)})):m.type==="tool_result"?a.push(I({...f,id:d,kind:"tool_result",role:"tool",callId:typeof m.tool_use_id=="string"?m.tool_use_id:null,content:T({...m,...o.tool_use_result!==void 0?{nativeToolResult:o.tool_use_result}:{}})})):a.push(I({...f,id:d,kind:"unknown",content:T(m)}))}l.stop_reason==="end_turn"&&a.push(I({...f,id:`${o.uuid}:terminal`,kind:"terminal",content:{status:"completed"}}))}return e.some(o=>o.type==="system"&&o.subtype==="compact_boundary")&&a.unshift(I({id:`compaction-${O(e.filter(o=>o.subtype==="compact_boundary")).slice(0,32)}`,kind:"compaction",content:{source:"claude_compact_boundary"}})),U({origin:"claude_code",sessionId:n.sessionId,branchId:null,parentSessionId:typeof r[0]?.parentSessionId=="string"?r[0].parentSessionId:null,exporterVersion:typeof r.at(-1)?.version=="string"?r.at(-1).version:null,files:[s],events:a,contextComplete:!i,warnings:[...i?["The transcript omits an ancestor; complete context is unavailable."]:[],...r.some(o=>o.isSidechain)?["This is a subagent/sidechain transcript; parent context is not implicitly imported."]:[],"Claude Code transcript schema is internal; only the declared message shapes are normalized."]})}p(Ot,"parseClaudeSession");function Tt(s,e){let t=[];for(let[n,r]of s.entries()){let i=_(r),a=typeof i.entryId=="string"?i.entryId:typeof i.id=="string"?i.id:typeof i.id=="number"&&Number.isSafeInteger(i.id)?String(i.id):typeof i.message_id=="string"?i.message_id:`${e}-${O([n,i]).slice(0,32)}`,o={occurredAt:F(i.timestamp,e==="hermes"?"seconds":"milliseconds"),parentId:typeof i.parentId=="string"?i.parentId:null};if(i.role==="tool"){t.push(I({...o,id:a,kind:"tool_result",role:"tool",callId:typeof i.tool_call_id=="string"?i.tool_call_id:null,content:T(i.content)}));continue}if(!["user","assistant","system"].includes(String(i.role))){t.push(I({...o,id:a,kind:"unknown",content:T(i)}));continue}if(t.push(I({...o,id:a,kind:"message",role:i.role,content:T(i.content),usage:z(i.usage,a)})),Array.isArray(i.tool_calls))for(let[l,c]of i.tool_calls.entries()){let f=_(c);t.push(I({...o,id:`${a}:call:${l}`,kind:"tool_call",callId:typeof f.id=="string"?f.id:null,content:T(f)}))}(i.finish_reason==="stop"||i.stop_reason==="end_turn")&&t.push(I({...o,id:`${a}:terminal`,kind:"terminal",content:{status:"completed"}}))}return t}p(Tt,"historyEvents");function Nt(s,e){let t=typeof e.id=="string"?e.id:typeof e.session_id=="string"?e.session_id:null;if(!t||!Array.isArray(e.messages))throw new Error("Hermes requires a full-session export with id or session_id and messages.");if(e.message_count!==void 0&&e.message_count!==e.messages.length)throw new Error("Hermes full-session message count differs from the retained messages.");let n=Array.isArray(e.lineage_session_ids)?e.lineage_session_ids.find(i=>typeof i=="string"&&i):null,r=Tt(e.messages,"hermes");return typeof e.system_prompt=="string"&&e.system_prompt.trim()&&r.unshift(I({id:`hermes-system-${O(e.system_prompt).slice(0,32)}`,kind:"message",role:"system",content:e.system_prompt})),U({origin:"hermes",sessionId:t,parentSessionId:typeof n=="string"?n:typeof e.parent_session_id=="string"?e.parent_session_id:null,exporterVersion:typeof e.version=="string"?e.version:null,files:[s],events:r,warnings:["Reported usage is not an OpenPond billing receipt.","Exporter redaction and missing tools/artifacts remain evidence gaps.",...e.session_id&&!e.id?["This is a Hermes session backup. Exporter version and terminal receipts may be unavailable."]:[]]})}p(Nt,"parseHermesEvidence");function xt(s){let e=p(u=>{let h=s.find(g=>g.path===u);if(!h)throw new Error(`OpenClaw bundle is missing ${u}.`);return h},"read"),t=_(JSON.parse(e("manifest.json").text)),n=_(JSON.parse(e("session-branch.json").text)),r=e("events.jsonl"),i=Q(r);if(t.traceSchema!=="openclaw-trajectory"||t.schemaVersion!==1||typeof t.sessionId!="string"||typeof t.traceId!="string")throw new Error("Unsupported OpenClaw trajectory manifest.");if(t.leafId!==n.leafId||t.eventCount!==i.length||i.some(u=>u.traceSchema!==t.traceSchema||u.schemaVersion!==1||u.sessionId!==t.sessionId||u.traceId!==t.traceId))throw new Error("OpenClaw bundle identity/count does not match its manifest.");if(!Array.isArray(n.entries))throw new Error("OpenClaw active branch entries are missing.");if(n.header&&_(n.header).id!==t.sessionId)throw new Error("OpenClaw branch header differs from the manifest session.");let a=new Set,o=[];for(let[u,h]of n.entries.entries()){let g=_(h);if(typeof g.id!="string"||a.has(g.id)||u>0&&g.parentId!==_(n.entries[u-1]).id)throw new Error("OpenClaw active branch is duplicate, incomplete or unordered.");a.add(g.id),g.type==="message"&&o.push({..._(g.message),entryId:g.id,parentId:g.parentId??null,timestamp:g.timestamp??_(g.message).timestamp})}if(n.entries.length&&_(n.entries.at(-1)).id!==n.leafId)throw new Error("OpenClaw branch does not reach its leaf.");let l=Tt(o,"openclaw"),c=[],f=new Set;for(let[u,h]of i.entries()){if(!Number.isSafeInteger(h.seq)||h.seq<0||f.has(h.seq)||u>0&&Number(i[u-1].seq)>=Number(h.seq))throw new Error("OpenClaw events have invalid/duplicate/unordered sequences.");f.add(h.seq),c.push(I({id:`trajectory:${t.traceId}:${h.seq}`,kind:"unknown",occurredAt:F(h.ts),content:T(h)}))}return U({origin:"openclaw",sessionId:t.sessionId,files:s,events:l,unmappedEvents:c,exporterVersion:typeof t.openclawVersion=="string"?t.openclawVersion:null,warnings:["Raw trajectory events are retained; unqualified event types are not advertised as complete process grading.",...Array.isArray(t.warnings)?t.warnings.map(u=>typeof _(u).message=="string"?String(_(u).message).slice(0,500):"The source exporter reports incomplete evidence."):[]].slice(0,100)})}p(xt,"parseOpenClawEvidence");function Re(s){return s==="codex"?`${Ee}/${Xe}/fork-repository-starting-state-v1`:Ee}p(Re,"agentImportNormalizerRevision");function Ct(s){if(!s.files.length||s.files.length>$.files)throw new Error("Choose between 1 and 100 source files.");let e=new Set,t=0;for(let o of s.files){if(o.path.length>500||o.path.startsWith("/")||o.path.includes("\\")||o.path.split("/").some(l=>!l||l==="."||l==="..")||e.has(o.path))throw new Error("Unsafe or duplicate source file path.");e.add(o.path),t+=new TextEncoder().encode(o.text).length}if(t>$.decodedBytes)throw new Error("Decoded source files exceed 64 MiB.");let n=[],r=[],i=p((o,l)=>{try{n.push(...l().map(c=>s.acquisition?U({origin:c.origin,sessionId:c.sessionId,branchId:c.branchId,parentSessionId:c.parentSessionId,exporterVersion:c.exporterVersion,files:s.files.filter(f=>c.sourceFiles.some(u=>u.path===f.path)),events:c.events,unmappedEvents:c.unmappedEvents,warnings:c.warnings,contextComplete:!c.boundaries.some(f=>f.coverage.context==="unknown"),acquisition:s.acquisition,...c.repositoryContext?{repositoryContext:c.repositoryContext}:{}}):c))}catch(c){r.push({file:o,...c instanceof Se?{code:"no_user_request"}:{},message:c instanceof Error?c.message:"Unsupported session."})}},"attempt");if(s.source==="openclaw"&&s.files.some(o=>o.path.endsWith("manifest.json")))i("manifest.json",()=>{let o=s.files[0].path.split("/")[0],l=!s.files.some(c=>c.path==="manifest.json")&&s.files.every(c=>c.path.startsWith(`${o}/`))?s.files.map(c=>({...c,path:c.path.slice(o.length+1)})):s.files;return[xt(l)]});else for(let o of s.files)i(o.path,()=>{if(s.source==="opencode")return[bt(o,JSON.parse(o.text))];let l;if(s.source==="hermes"&&o.path.endsWith(".json")){let c=JSON.parse(o.text.replace(/^\uFEFF/u,""));if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Hermes session backup must be one JSON object.");l=[c]}else l=Q(o);if(s.source==="grok_build")return[St(o,l)];if(s.source==="pi"||s.source==="oh_my_pi"||s.source==="openclaw")return[_t(o,l,s.source,s.branchLeafId)];if(s.source==="codex")return[It(o,l)];if(s.source==="claude_code")return[Ot(o,l,s.branchLeafId)];if(s.source==="hermes")return l.map(c=>Nt(o,c));throw new Error("Unsupported source adapter.")});if(n.length>$.sessions||n.reduce((o,l)=>o+l.events.length+l.unmappedEvents.length,0)>$.events||n.reduce((o,l)=>o+l.boundaries.length,0)>$.boundaries)throw new Error("Import exceeds the session/event/boundary limit.");let a=new Map;for(let o of n){let l=JSON.stringify([o.origin,o.sessionId,o.branchId]),c=a.get(l);if(c&&c!==o.contentHash)throw new Error("The same session has different contents in this selection. Choose one export.");a.set(l,o.contentHash)}return{schemaVersion:"openpond.agentImportPreview.v1",source:s.source,sourceHash:O({source:s.source,files:[...s.files].sort((o,l)=>o.path.localeCompare(l.path)),branchLeafId:s.branchLeafId??null}),sessions:n.filter((o,l)=>n.findIndex(c=>c.contentHash===o.contentHash)===l),issues:r}}p(Ct,"previewAgentImport");import{open as Xs,lstat as Ks,readdir as Ys,readFile as Vs,realpath as zt,stat as Gt}from"node:fs/promises";import{basename as le,dirname as Zs,isAbsolute as Ke,join as ke,relative as Qs,resolve as en,sep as tn}from"node:path";import{zstdDecompressSync as sn}from"node:zlib";import{DatabaseSync as Ws}from"node:sqlite";import{join as zs}from"node:path";import{DatabaseSync as Ps}from"node:sqlite";import{zstdDecompressSync as Mt}from"node:zlib";import{createHash as js}from"node:crypto";import{createHash as $s}from"node:crypto";import{readFileSync as Hs,realpathSync as Rt,statSync as Fs}from"node:fs";import{basename as Us,dirname as At,join as Lt,relative as qs,sep as kt}from"node:path";import{zstdDecompressSync as Bs}from"node:zlib";function Dt(s,e,t){let n=s.prepare("SELECT generation,archive_name,archive_sha256,event_count,raw_bytes,archive_bytes,last_seq,storage,length(archive_blob) AS blob_bytes FROM session_transcript_cold_archives WHERE session_id=?").get(t);if(!n)return null;if(Number(n.archive_bytes)>k||Number(n.raw_bytes)>k||Number(n.event_count)>1e5)throw new Error("OpenClaw cold archive exceeds the retained size limit.");let r;if(n.storage==="sqlite"){if(Number(n.blob_bytes)!==Number(n.archive_bytes))throw new Error("OpenClaw cold archive size differs from its receipt.");let h=s.prepare("SELECT archive_blob FROM session_transcript_cold_archives WHERE session_id=?").get(t);if(!(h.archive_blob instanceof Uint8Array))throw new Error("OpenClaw cold archive is unavailable.");r=h.archive_blob}else if(n.storage==="file"){let h=String(n.archive_name);if(!/^[a-f0-9]{64}\.jsonl\.zst$/.test(h))throw new Error("Invalid OpenClaw cold archive name.");let g=At(e.root),w=Us(g)==="agent"?Lt(At(g),"sessions"):g,y=Rt(w),m=Rt(Lt(w,"cold",h)),d=qs(y,m);if(d===".."||d.startsWith(`..${kt}`)||d.startsWith(kt))throw new Error("OpenClaw cold archive leaves the selected agent directory.");let E=Fs(m);if(!E.isFile()||E.size!==Number(n.archive_bytes))throw new Error("OpenClaw cold archive size differs from its receipt.");r=Hs(m)}else throw new Error("Unsupported OpenClaw cold archive storage.");if(r.length!==Number(n.archive_bytes)||$s("sha256").update(r).digest("hex")!==n.archive_sha256)throw new Error("OpenClaw cold archive checksum differs from its receipt.");let i=Bs(r,{maxOutputLength:k}),a=new TextDecoder("utf8",{fatal:!0}).decode(i).trimEnd().split(`
|
|
11
|
+
`})),"permissionsText"),r=_(s.payload);if(s.type==="response_item"&&r.type==="message"&&["system","developer"].includes(String(r.role))){let i=typeof r.content=="string"?n(r.content,"/payload/content"):Array.isArray(r.content)?r.content.map((a,o)=>{let l=_(a);return typeof l.text=="string"?{...l,text:n(l.text,`/payload/content/${o}/text`)}:a}):r.content;return{row:{...s,payload:{...r,content:i}},omissions:e}}if(s.type==="world_state"){let i=_(r.state),a=_(i.permissions);if(Array.isArray(a.approved_command_prefixes)){let o=t("/payload/state/permissions/approved_command_prefixes",a.approved_command_prefixes,a.approved_command_prefixes.length);return{row:{...s,payload:{...r,state:{...i,permissions:{...a,approved_command_prefixes:{omitted:"native_authorization_state",...o}}}}},omissions:e}}}return{row:s,omissions:e}}p(It,"projectCodexAuthorization");var de=class{static{p(this,"CodexMetadataChain")}metadata=null;parentId=null;closed=!1;ids=new Set;accept(e){if(e.type!=="session_meta")return this.closed=!0,!0;let t=e.payload;if(this.closed||!t||typeof t!="object"||Array.isArray(t))return!1;let n=t;if(typeof n.id!="string"||!n.id||n.id.length>500||this.ids.has(n.id)||this.ids.size>=16)return!1;if(this.metadata){if(n.id!==this.parentId)return!1;for(let r of["creator_user_id","creator_account_id"])if(this.metadata[r]!=null&&n[r]!=null&&this.metadata[r]!==n[r])return!1}else this.metadata=n;return this.ids.add(n.id),this.parentId=typeof n.forked_from_id=="string"?n.forked_from_id:null,!0}};function Ot(s,e){let t=new de;if(e.some(c=>!t.accept(c)))throw new Error("Codex rollout metadata does not match its declared fork ancestry.");let n=t.metadata??{};if(typeof n.id!="string")throw new Error("This is not a supported Codex rollout: session_meta.id is missing.");let r=_(n.git),i=typeof r.commit_hash=="string"&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(r.commit_hash)?{schemaVersion:"openpond.connectedRepositoryContext.v1",kind:"git",commitHash:r.commit_hash,branch:typeof r.branch=="string"&&r.branch.length>0&&r.branch.length<=500?r.branch:null,recordedAt:F(n.timestamp),sourceFileHash:Ge(s).contentHash,metadataHash:O(r)}:void 0;i&&typeof n.cwd=="string"&&Object.assign(i,{workingDirectoryHash:O(n.cwd)});let a=[],o=null,l=0;for(let[c,f]of e.entries()){let u=It(f);l+=u.omissions.length;let h=_(u.row.payload);if(f.type==="session_meta")continue;if(f.type==="turn_context"){o=typeof h.turn_id=="string"?h.turn_id:o;continue}let w={id:typeof h.id=="string"?h.id:`codex-event-${O([c,f]).slice(0,32)}`,occurredAt:F(f.timestamp),parentId:o};if(f.type==="response_item")h.type==="message"&&["user","assistant","system","developer"].includes(String(h.role))?a.push(I({...w,kind:"message",role:h.role==="developer"?"system":h.role,content:T(h.content)})):h.type==="function_call"||h.type==="custom_tool_call"?a.push(I({...w,kind:"tool_call",callId:typeof h.call_id=="string"?h.call_id:null,content:T(h)})):h.type==="function_call_output"||h.type==="custom_tool_call_output"?a.push(I({...w,kind:"tool_result",role:"tool",callId:typeof h.call_id=="string"?h.call_id:null,content:T(h.output)})):a.push(I({...w,kind:"unknown",content:T(h)}));else if(f.type==="compacted")a.push(I({...w,kind:"compaction",content:T(h)}));else if(f.type==="event_msg"){if(["user_message","agent_message","agent_reasoning","task_started"].includes(String(h.type)))continue;if(h.type==="task_complete"||h.type==="turn_aborted")a.push(I({...w,kind:"terminal",content:{status:h.type==="task_complete"?"completed":"cancelled",source:T(h)}}));else if(h.type==="token_count"){let y=_(h.info),m=z(y.total_token_usage,`codex-cumulative:${n.id}:${c}`,"reported_cumulative");a.push(I({...w,kind:"usage",usage:m,content:T(h)}))}else a.push(I({...w,kind:"unknown",content:T(h)}))}else a.push(I({...w,kind:"unknown",content:T(u.row)}))}return U({origin:"codex",sessionId:n.id,parentSessionId:typeof n.forked_from_id=="string"?n.forked_from_id:null,exporterVersion:typeof n.cli_version=="string"?n.cli_version:null,files:[s],events:a,...i?{repositoryContext:i}:{},warnings:["Codex cumulative usage is retained as reported totals and is not summed as billed invocations.","Referenced files are unavailable unless separately admitted.",...l?[`Codex native authorization state excluded by codex-native-authorization-v1 from ${l} locations. Omission markers retain source-section hashes; sourceFiles retains original byte hashes. Other conversation evidence is unchanged and still requires privacy admission.`]:[]]})}p(Ot,"parseCodexSession");function Ce(s){let e=s.filter(u=>(u.type==="user"||u.type==="assistant")&&typeof u.uuid=="string"),t=new Set(e.flatMap(u=>typeof u.sessionId=="string"?[u.sessionId]:[]));if(t.size!==1||!e.length)throw new Error("A supported Claude Code transcript must identify one session with UUID messages.");let n=[...t][0],r=s.filter(u=>typeof u.uuid=="string"&&u.sessionId===n),i=new Map(r.map(u=>[u.uuid,u]));if(i.size!==r.length)throw new Error("Claude Code transcript contains duplicate message UUIDs.");let a=new Set(r.flatMap(u=>typeof u.parentUuid=="string"?[u.parentUuid]:[])),o=r.filter(u=>!a.has(u.uuid));if(!o.length)throw new Error("Claude Code transcript has no selectable branch leaf.");function l(u){let h=i.get(u);if(!h)throw new Error("The selected Claude Code branch leaf is missing.");let g=[],w=new Set,y=!1;for(;h;){let m=h.uuid;if(w.has(m))throw new Error("Claude Code branch contains a parent cycle.");w.add(m),g.unshift(h);let d=h.parentUuid;if(typeof d!="string")break;h=i.get(d),h||(y=!0)}return{chain:g,missingParent:y,chainHash:O(g)}}p(l,"select");function c(){if(o.length>256)throw new Error("This transcript exceeds the 256-branch inspection limit.");return o.map(u=>{let h=l(u.uuid),g=h.chain.filter(d=>d.type==="user"||d.type==="assistant"),w=g.at(-1),y=_(w?.message).content,m=typeof y=="string"?y:Array.isArray(y)?y.flatMap(d=>typeof _(d).text=="string"?[_(d).text]:[]).join(" "):"";return{leafId:u.uuid,chainHash:h.chainHash,title:m.slice(0,180),updatedAt:F(w?.timestamp),messages:g.length}})}p(c,"branches");function f(){let u=new Set;for(let w of o){let y=w,m=new Set;for(;y;){let d=y.uuid;if(m.has(d))throw new Error("Claude Code branch contains a parent cycle.");if(m.add(d),y.type==="user"||y.type==="assistant"){u.add(d);break}y=typeof y.parentUuid=="string"?i.get(y.parentUuid):void 0}}let h,g;for(let w of r){let y=w.uuid;u.has(y)&&(g=y,!w.isSidechain&&!w.teamName&&!w.isMeta&&(h=y))}if(!h&&!g)throw new Error("Claude Code transcript has no conversation message.");return h??g}return p(f,"latestLeafId"),{sessionId:n,leaves:o,select:l,branches:c,latestLeafId:f}}p(Ce,"claudeGraph");function Tt(s,e,t){let n=Ce(e);if(!t&&n.leaves.length!==1)throw new Error("This transcript has multiple branches. Select a branch leaf UUID before importing.");let{chain:r,missingParent:i}=n.select(t??n.leaves[0].uuid),a=[];for(let o of r){if(o.type!=="user"&&o.type!=="assistant")continue;let l=_(o.message),c=l.content,f={occurredAt:F(o.timestamp),parentId:typeof o.parentUuid=="string"?o.parentUuid:null},u=o.type==="user"?"user":"assistant",h=Array.isArray(c)?c:[{type:"text",text:c}],g=h.filter(w=>_(w).type==="text");g.length&&a.push(I({...f,id:o.uuid,kind:"message",role:u,content:T(g)})),u==="assistant"&&l.usage&&a.push(I({...f,id:`${o.uuid}:usage`,kind:"usage",content:T(l.usage),usage:z(l.usage,typeof l.id=="string"?l.id:o.uuid)}));for(let[w,y]of h.entries()){let m=_(y);if(m.type==="text"||m.type==="thinking"||m.type==="redacted_thinking")continue;let d=`${o.uuid}:${w}`;m.type==="tool_use"?a.push(I({...f,id:d,kind:"tool_call",callId:typeof m.id=="string"?m.id:null,content:T(m)})):m.type==="tool_result"?a.push(I({...f,id:d,kind:"tool_result",role:"tool",callId:typeof m.tool_use_id=="string"?m.tool_use_id:null,content:T({...m,...o.tool_use_result!==void 0?{nativeToolResult:o.tool_use_result}:{}})})):a.push(I({...f,id:d,kind:"unknown",content:T(m)}))}l.stop_reason==="end_turn"&&a.push(I({...f,id:`${o.uuid}:terminal`,kind:"terminal",content:{status:"completed"}}))}return e.some(o=>o.type==="system"&&o.subtype==="compact_boundary")&&a.unshift(I({id:`compaction-${O(e.filter(o=>o.subtype==="compact_boundary")).slice(0,32)}`,kind:"compaction",content:{source:"claude_compact_boundary"}})),U({origin:"claude_code",sessionId:n.sessionId,branchId:null,parentSessionId:typeof r[0]?.parentSessionId=="string"?r[0].parentSessionId:null,exporterVersion:typeof r.at(-1)?.version=="string"?r.at(-1).version:null,files:[s],events:a,contextComplete:!i,warnings:[...i?["The transcript omits an ancestor; complete context is unavailable."]:[],...r.some(o=>o.isSidechain)?["This is a subagent/sidechain transcript; parent context is not implicitly imported."]:[],"Claude Code transcript schema is internal; only the declared message shapes are normalized."]})}p(Tt,"parseClaudeSession");function Nt(s,e){let t=[];for(let[n,r]of s.entries()){let i=_(r),a=typeof i.entryId=="string"?i.entryId:typeof i.id=="string"?i.id:typeof i.id=="number"&&Number.isSafeInteger(i.id)?String(i.id):typeof i.message_id=="string"?i.message_id:`${e}-${O([n,i]).slice(0,32)}`,o={occurredAt:F(i.timestamp,e==="hermes"?"seconds":"milliseconds"),parentId:typeof i.parentId=="string"?i.parentId:null};if(i.role==="tool"){t.push(I({...o,id:a,kind:"tool_result",role:"tool",callId:typeof i.tool_call_id=="string"?i.tool_call_id:null,content:T(i.content)}));continue}if(!["user","assistant","system"].includes(String(i.role))){t.push(I({...o,id:a,kind:"unknown",content:T(i)}));continue}if(t.push(I({...o,id:a,kind:"message",role:i.role,content:T(i.content),usage:z(i.usage,a)})),Array.isArray(i.tool_calls))for(let[l,c]of i.tool_calls.entries()){let f=_(c);t.push(I({...o,id:`${a}:call:${l}`,kind:"tool_call",callId:typeof f.id=="string"?f.id:null,content:T(f)}))}(i.finish_reason==="stop"||i.stop_reason==="end_turn")&&t.push(I({...o,id:`${a}:terminal`,kind:"terminal",content:{status:"completed"}}))}return t}p(Nt,"historyEvents");function xt(s,e){let t=typeof e.id=="string"?e.id:typeof e.session_id=="string"?e.session_id:null;if(!t||!Array.isArray(e.messages))throw new Error("Hermes requires a full-session export with id or session_id and messages.");if(e.message_count!==void 0&&e.message_count!==e.messages.length)throw new Error("Hermes full-session message count differs from the retained messages.");let n=Array.isArray(e.lineage_session_ids)?e.lineage_session_ids.find(i=>typeof i=="string"&&i):null,r=Nt(e.messages,"hermes");return typeof e.system_prompt=="string"&&e.system_prompt.trim()&&r.unshift(I({id:`hermes-system-${O(e.system_prompt).slice(0,32)}`,kind:"message",role:"system",content:e.system_prompt})),U({origin:"hermes",sessionId:t,parentSessionId:typeof n=="string"?n:typeof e.parent_session_id=="string"?e.parent_session_id:null,exporterVersion:typeof e.version=="string"?e.version:null,files:[s],events:r,warnings:["Reported usage is not an OpenPond billing receipt.","Exporter redaction and missing tools/artifacts remain evidence gaps.",...e.session_id&&!e.id?["This is a Hermes session backup. Exporter version and terminal receipts may be unavailable."]:[]]})}p(xt,"parseHermesEvidence");function Ct(s){let e=p(u=>{let h=s.find(g=>g.path===u);if(!h)throw new Error(`OpenClaw bundle is missing ${u}.`);return h},"read"),t=_(JSON.parse(e("manifest.json").text)),n=_(JSON.parse(e("session-branch.json").text)),r=e("events.jsonl"),i=Q(r);if(t.traceSchema!=="openclaw-trajectory"||t.schemaVersion!==1||typeof t.sessionId!="string"||typeof t.traceId!="string")throw new Error("Unsupported OpenClaw trajectory manifest.");if(t.leafId!==n.leafId||t.eventCount!==i.length||i.some(u=>u.traceSchema!==t.traceSchema||u.schemaVersion!==1||u.sessionId!==t.sessionId||u.traceId!==t.traceId))throw new Error("OpenClaw bundle identity/count does not match its manifest.");if(!Array.isArray(n.entries))throw new Error("OpenClaw active branch entries are missing.");if(n.header&&_(n.header).id!==t.sessionId)throw new Error("OpenClaw branch header differs from the manifest session.");let a=new Set,o=[];for(let[u,h]of n.entries.entries()){let g=_(h);if(typeof g.id!="string"||a.has(g.id)||u>0&&g.parentId!==_(n.entries[u-1]).id)throw new Error("OpenClaw active branch is duplicate, incomplete or unordered.");a.add(g.id),g.type==="message"&&o.push({..._(g.message),entryId:g.id,parentId:g.parentId??null,timestamp:g.timestamp??_(g.message).timestamp})}if(n.entries.length&&_(n.entries.at(-1)).id!==n.leafId)throw new Error("OpenClaw branch does not reach its leaf.");let l=Nt(o,"openclaw"),c=[],f=new Set;for(let[u,h]of i.entries()){if(!Number.isSafeInteger(h.seq)||h.seq<0||f.has(h.seq)||u>0&&Number(i[u-1].seq)>=Number(h.seq))throw new Error("OpenClaw events have invalid/duplicate/unordered sequences.");f.add(h.seq),c.push(I({id:`trajectory:${t.traceId}:${h.seq}`,kind:"unknown",occurredAt:F(h.ts),content:T(h)}))}return U({origin:"openclaw",sessionId:t.sessionId,files:s,events:l,unmappedEvents:c,exporterVersion:typeof t.openclawVersion=="string"?t.openclawVersion:null,warnings:["Raw trajectory events are retained; unqualified event types are not advertised as complete process grading.",...Array.isArray(t.warnings)?t.warnings.map(u=>typeof _(u).message=="string"?String(_(u).message).slice(0,500):"The source exporter reports incomplete evidence."):[]].slice(0,100)})}p(Ct,"parseOpenClawEvidence");function Re(s){return s==="codex"?`${Ee}/${Xe}/fork-repository-starting-state-v1`:Ee}p(Re,"agentImportNormalizerRevision");function Rt(s){if(!s.files.length||s.files.length>$.files)throw new Error("Choose between 1 and 100 source files.");let e=new Set,t=0;for(let o of s.files){if(o.path.length>500||o.path.startsWith("/")||o.path.includes("\\")||o.path.split("/").some(l=>!l||l==="."||l==="..")||e.has(o.path))throw new Error("Unsafe or duplicate source file path.");e.add(o.path),t+=new TextEncoder().encode(o.text).length}if(t>$.decodedBytes)throw new Error("Decoded source files exceed 64 MiB.");let n=[],r=[],i=p((o,l)=>{try{n.push(...l().map(c=>s.acquisition?U({origin:c.origin,sessionId:c.sessionId,branchId:c.branchId,parentSessionId:c.parentSessionId,exporterVersion:c.exporterVersion,files:s.files.filter(f=>c.sourceFiles.some(u=>u.path===f.path)),events:c.events,unmappedEvents:c.unmappedEvents,warnings:c.warnings,contextComplete:!c.boundaries.some(f=>f.coverage.context==="unknown"),acquisition:s.acquisition,...c.repositoryContext?{repositoryContext:c.repositoryContext}:{}}):c))}catch(c){r.push({file:o,...c instanceof Se?{code:"no_user_request"}:{},message:c instanceof Error?c.message:"Unsupported session."})}},"attempt");if(s.source==="openclaw"&&s.files.some(o=>o.path.endsWith("manifest.json")))i("manifest.json",()=>{let o=s.files[0].path.split("/")[0],l=!s.files.some(c=>c.path==="manifest.json")&&s.files.every(c=>c.path.startsWith(`${o}/`))?s.files.map(c=>({...c,path:c.path.slice(o.length+1)})):s.files;return[Ct(l)]});else for(let o of s.files)i(o.path,()=>{if(s.source==="opencode")return[vt(o,JSON.parse(o.text))];let l;if(s.source==="hermes"&&o.path.endsWith(".json")){let c=JSON.parse(o.text.replace(/^\uFEFF/u,""));if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Hermes session backup must be one JSON object.");l=[c]}else l=Q(o);if(s.source==="grok_build")return[_t(o,l)];if(s.source==="pi"||s.source==="oh_my_pi"||s.source==="openclaw")return[bt(o,l,s.source,s.branchLeafId)];if(s.source==="codex")return[Ot(o,l)];if(s.source==="claude_code")return[Tt(o,l,s.branchLeafId)];if(s.source==="hermes")return l.map(c=>xt(o,c));throw new Error("Unsupported source adapter.")});if(n.length>$.sessions||n.reduce((o,l)=>o+l.events.length+l.unmappedEvents.length,0)>$.events||n.reduce((o,l)=>o+l.boundaries.length,0)>$.boundaries)throw new Error("Import exceeds the session/event/boundary limit.");let a=new Map;for(let o of n){let l=JSON.stringify([o.origin,o.sessionId,o.branchId]),c=a.get(l);if(c&&c!==o.contentHash)throw new Error("The same session has different contents in this selection. Choose one export.");a.set(l,o.contentHash)}return{schemaVersion:"openpond.agentImportPreview.v1",source:s.source,sourceHash:O({source:s.source,files:[...s.files].sort((o,l)=>o.path.localeCompare(l.path)),branchLeafId:s.branchLeafId??null}),sessions:n.filter((o,l)=>n.findIndex(c=>c.contentHash===o.contentHash)===l),issues:r}}p(Rt,"previewAgentImport");import{open as Ys,lstat as Vs,readdir as Zs,readFile as Qs,realpath as Jt,stat as Xt}from"node:fs/promises";import{basename as ee,dirname as Ke,isAbsolute as Ye,join as ke,relative as en,resolve as tn,sep as sn}from"node:path";import{zstdDecompressSync as nn}from"node:zlib";import{DatabaseSync as Js}from"node:sqlite";import{join as Gs}from"node:path";import{DatabaseSync as Ws}from"node:sqlite";import{zstdDecompressSync as $t}from"node:zlib";import{createHash as zs}from"node:crypto";import{createHash as Fs}from"node:crypto";import{readFileSync as Us,realpathSync as At,statSync as qs}from"node:fs";import{basename as Bs,dirname as Lt,join as kt,relative as Ps,sep as Dt}from"node:path";import{zstdDecompressSync as js}from"node:zlib";function Mt(s,e,t){let n=s.prepare("SELECT generation,archive_name,archive_sha256,event_count,raw_bytes,archive_bytes,last_seq,storage,length(archive_blob) AS blob_bytes FROM session_transcript_cold_archives WHERE session_id=?").get(t);if(!n)return null;if(Number(n.archive_bytes)>L||Number(n.raw_bytes)>L||Number(n.event_count)>1e5)throw new Error("OpenClaw cold archive exceeds the retained size limit.");let r;if(n.storage==="sqlite"){if(Number(n.blob_bytes)!==Number(n.archive_bytes))throw new Error("OpenClaw cold archive size differs from its receipt.");let h=s.prepare("SELECT archive_blob FROM session_transcript_cold_archives WHERE session_id=?").get(t);if(!(h.archive_blob instanceof Uint8Array))throw new Error("OpenClaw cold archive is unavailable.");r=h.archive_blob}else if(n.storage==="file"){let h=String(n.archive_name);if(!/^[a-f0-9]{64}\.jsonl\.zst$/.test(h))throw new Error("Invalid OpenClaw cold archive name.");let g=Lt(e.root),w=Bs(g)==="agent"?kt(Lt(g),"sessions"):g,y=At(w),m=At(kt(w,"cold",h)),d=Ps(y,m);if(d===".."||d.startsWith(`..${Dt}`)||d.startsWith(Dt))throw new Error("OpenClaw cold archive leaves the selected agent directory.");let E=qs(m);if(!E.isFile()||E.size!==Number(n.archive_bytes))throw new Error("OpenClaw cold archive size differs from its receipt.");r=Us(m)}else throw new Error("Unsupported OpenClaw cold archive storage.");if(r.length!==Number(n.archive_bytes)||Fs("sha256").update(r).digest("hex")!==n.archive_sha256)throw new Error("OpenClaw cold archive checksum differs from its receipt.");let i=js(r,{maxOutputLength:L}),a=new TextDecoder("utf8",{fatal:!0}).decode(i).trimEnd().split(`
|
|
12
12
|
`),o=JSON.parse(a.shift()??"null");if(o?.kind!=="header"||o.version!==1||o.sessionId!==t||o.generation!==n.generation)throw new Error("OpenClaw cold archive identity differs from its receipt.");let l=[],c=-1,f=0;for(let h of a){let g=JSON.parse(h);if(!["event","identity","active","index","fts"].includes(g?.kind))throw new Error("Unsupported OpenClaw cold archive record.");if(g.kind==="event"){if(!Number.isSafeInteger(g.row?.seq)||g.row.seq<=c||typeof g.row.event_json!="string")throw new Error("Invalid OpenClaw cold archive event sequence.");c=g.row.seq,f+=Buffer.byteLength(g.row.event_json),l.push(g.row.event_json)}}if(l.length!==Number(n.event_count)||c!==Number(n.last_seq)||f+l.length-1!==Number(n.raw_bytes))throw new Error("OpenClaw cold archive contents differ from its receipt.");let u=JSON.parse(l[0]??"null");if(u?.type!=="session"||u.id!==t)throw new Error("OpenClaw transcript identity differs from selected session.");return{path:`${t}.jsonl`,text:l.join(`
|
|
13
13
|
`)+`
|
|
14
|
-
`}}p(
|
|
14
|
+
`}}p(Mt,"readOpenClawColdArchive");function Ht(s){let e=new Ws(s.root,{readOnly:!0,allowExtension:!1,enableDoubleQuotedStringLiterals:!1});return e.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=1000; BEGIN"),e}p(Ht,"open");function Ae(s,e){return!!s.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(e)}p(Ae,"has");function Ft(s,e){let t=Ht(s);try{let n=Ae(t,"session_transcript_archives")?"UNION ALL SELECT session_id AS id,created_at AS updated,archive_sha256 AS revision FROM session_transcript_archives":"",r=Ae(t,"session_transcript_cold_archives")?"UNION ALL SELECT session_id AS id,archived_at AS updated,archive_sha256 AS revision FROM session_transcript_cold_archives":"",i=t.prepare(`SELECT id,MAX(updated) AS updated,MAX(revision) AS revision FROM (
|
|
15
15
|
SELECT session_id AS id,MAX(created_at) AS updated,CAST(MAX(seq) AS TEXT) AS revision FROM transcript_events GROUP BY session_id
|
|
16
|
-
${n} ${r}) WHERE id > ? GROUP BY id ORDER BY id LIMIT ?`).all(e.cursor??"",e.limit+1),a=i.slice(0,e.limit).map(o=>({nativeSessionId:String(o.id),sourceInstanceId:s.instanceId,path:String(o.id),title:String(o.id),cwd:null,updatedAt:new Date(Number(o.updated)||0).toISOString()}));return{items:a,nextCursor:i.length>e.limit?a.at(-1).nativeSessionId:null}}finally{t.close()}}p(
|
|
17
|
-
`,1)[0]);if(g.type!=="session"||g.id!==e)throw new Error("OpenClaw archive identity differs from selected session.");return{path:`${e}.jsonl`,text:h}}let r=t.prepare("SELECT COUNT(*) AS n,SUM(COALESCE(event_utf8_bytes,length(CAST(event_json AS BLOB)),0)) AS bytes FROM transcript_events WHERE session_id=?").get(e);if(Number(r.n)>1e5||Number(r.bytes)>
|
|
16
|
+
${n} ${r}) WHERE id > ? GROUP BY id ORDER BY id LIMIT ?`).all(e.cursor??"",e.limit+1),a=i.slice(0,e.limit).map(o=>({nativeSessionId:String(o.id),sourceInstanceId:s.instanceId,path:String(o.id),title:String(o.id),cwd:null,updatedAt:new Date(Number(o.updated)||0).toISOString()}));return{items:a,nextCursor:i.length>e.limit?a.at(-1).nativeSessionId:null}}finally{t.close()}}p(Ft,"listOpenClawSessions");function Ut(s,e){let t=Ht(s);try{if(Ae(t,"session_transcript_cold_archives")){let c=Mt(t,s,e);if(c)return c}if(!t.prepare("SELECT 1 FROM transcript_events WHERE session_id=? LIMIT 1").get(e)){if(!Ae(t,"session_transcript_archives"))throw new Error("OpenClaw archive is unavailable.");let c=t.prepare("SELECT archive_name,length(archive_blob) AS bytes FROM session_transcript_archives WHERE session_id=? ORDER BY created_at DESC LIMIT 1").get(e);if(!c||Number(c.bytes)>L)throw new Error("OpenClaw archive is missing or exceeds the retained byte limit.");let f=t.prepare("SELECT archive_blob,archive_sha256,encoding FROM session_transcript_archives WHERE archive_name=? AND session_id=?").get(String(c.archive_name),e);if(!(f.archive_blob instanceof Uint8Array)||zs("sha256").update(f.archive_blob).digest("hex")!==f.archive_sha256)throw new Error("OpenClaw archive checksum differs from its retained receipt.");if(f.encoding!=="zstd"&&f.encoding!=="identity")throw new Error("Unsupported OpenClaw archive encoding.");let u=f.encoding==="zstd"?$t(f.archive_blob,{maxOutputLength:L}):f.archive_blob,h=new TextDecoder("utf8",{fatal:!0}).decode(u),g=JSON.parse(h.split(`
|
|
17
|
+
`,1)[0]);if(g.type!=="session"||g.id!==e)throw new Error("OpenClaw archive identity differs from selected session.");return{path:`${e}.jsonl`,text:h}}let r=t.prepare("SELECT COUNT(*) AS n,SUM(COALESCE(event_utf8_bytes,length(CAST(event_json AS BLOB)),0)) AS bytes FROM transcript_events WHERE session_id=?").get(e);if(Number(r.n)>1e5||Number(r.bytes)>L)throw new Error("OpenClaw transcript exceeds the retained size limit.");let i=t.prepare("SELECT seq,event_json,event_zstd,event_utf8_bytes FROM transcript_events WHERE session_id=? ORDER BY seq LIMIT 100001").all(e),a=0,o=i.map(c=>{let f;if(typeof c.event_json=="string")f=c.event_json;else{if(!(c.event_zstd instanceof Uint8Array)||Number(c.event_utf8_bytes)>L)throw new Error("Unsupported OpenClaw compressed transcript record.");let u=$t(c.event_zstd,{maxOutputLength:L});if(u.length!==Number(c.event_utf8_bytes))throw new Error("OpenClaw compressed transcript size differs from its receipt.");f=new TextDecoder("utf8",{fatal:!0}).decode(u)}if(a+=Buffer.byteLength(f),a>L)throw new Error("OpenClaw transcript exceeds retained size limit.");return f});if(!o.length)throw new Error("OpenClaw transcript is unavailable.");let l=JSON.parse(o[0]);if(l.type!=="session"||l.id!==e)throw new Error("OpenClaw transcript identity differs from selected session.");return{path:`${e}.jsonl`,text:o.join(`
|
|
18
18
|
`)+`
|
|
19
|
-
`}}finally{t.close()}}p(
|
|
19
|
+
`}}finally{t.close()}}p(Ut,"readOpenClawSession");function qt(s){let e=s.root.endsWith(".db")?s.root:Gs(s.root,s.source==="opencode"?"opencode.db":"state.db"),t=new Js(e,{readOnly:!0,allowExtension:!1,enableDoubleQuotedStringLiterals:!1});return t.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=1000; BEGIN"),t}p(qt,"open");function Bt(s,e){if(s.source==="openclaw")return Ft(s,e);let t=qt(s);try{let n=e.since?Date.parse(e.since):0,r=s.source==="opencode"?t.prepare("SELECT id,title,directory AS cwd,time_updated AS updated, time_updated || ':' || COALESCE((SELECT MAX(time_updated) FROM message WHERE session_id=session.id),0) || ':' || COALESCE((SELECT MAX(time_updated) FROM part WHERE session_id=session.id),0) || ':' || (SELECT COUNT(*) FROM part WHERE session_id=session.id) AS revision FROM session WHERE id > ? AND time_updated >= ? ORDER BY id LIMIT ?").all(e.cursor??"",n,e.limit+1):t.prepare("SELECT id,title,cwd,MAX(COALESCE(last_activity_at,0),started_at) * 1000 AS updated FROM sessions WHERE id > ? AND MAX(COALESCE(last_activity_at,0),started_at) * 1000 >= ? ORDER BY id LIMIT ?").all(e.cursor??"",n,e.limit+1),i=r.slice(0,e.limit).map(a=>({nativeSessionId:String(a.id),sourceInstanceId:s.instanceId,path:String(a.id),title:typeof a.title=="string"?a.title:String(a.id),cwd:typeof a.cwd=="string"?a.cwd:null,updatedAt:new Date(Number(a.updated)).toISOString(),storageRevision:s.source==="opencode"?String(a.revision):void 0}));return{items:i,nextCursor:r.length>e.limit?i.at(-1).nativeSessionId:null}}finally{t.close()}}p(Bt,"listDatabaseSessions");function Pt(s,e){if(s.source==="openclaw")return Ut(s,e);let t=qt(s);try{let n;if(s.source==="opencode"){let i=t.prepare("SELECT id,title,directory,parent_id,version,time_created,time_updated FROM session WHERE id = ?").get(e);if(!i)throw new Error("Native session is unavailable.");let a=t.prepare("SELECT (SELECT COALESCE(SUM(length(CAST(data AS BLOB))),0) FROM message WHERE session_id=?) + (SELECT COALESCE(SUM(length(CAST(data AS BLOB))),0) FROM part WHERE session_id=?) AS bytes").get(e,e);if(Number(a?.bytes)>L)throw new Error("Native session exceeds the retained byte limit.");let o=t.prepare("SELECT id,data FROM message WHERE session_id = ? ORDER BY time_created,id LIMIT 100001").all(e);if(o.length>1e5)throw new Error("Native session exceeds the event limit.");let l=0,c=o.map(f=>{if(l+=Buffer.byteLength(String(f.data)),l>L)throw new Error("Native session exceeds the retained byte limit.");let u=t.prepare("SELECT id,data FROM part WHERE session_id = ? AND message_id = ? ORDER BY time_created,id LIMIT 100001").all(e,String(f.id));if(u.length>1e5)throw new Error("Native parts exceed the event limit.");return{info:{...JSON.parse(String(f.data)),id:f.id,sessionID:e},parts:u.map(h=>{if(l+=Buffer.byteLength(String(h.data)),l>L)throw new Error("Native session exceeds the retained byte limit.");return{...JSON.parse(String(h.data)),id:h.id,sessionID:e,messageID:f.id}})}});n={info:{...i,parentID:i.parent_id,time:{created:i.time_created,updated:i.time_updated}},messages:c}}else{let i=t.prepare("SELECT id,title,parent_session_id,system_prompt FROM sessions WHERE id = ?").get(e);if(!i)throw new Error("Native session is unavailable.");let a=t.prepare("SELECT COALESCE(SUM(length(CAST(COALESCE(content,'') AS BLOB))+length(CAST(COALESCE(tool_calls,'') AS BLOB))),0) AS bytes FROM messages WHERE session_id=? AND active=1").get(e);if(Number(a?.bytes)>L)throw new Error("Native session exceeds the retained byte limit.");let o=t.prepare("SELECT id,role,content,tool_call_id,tool_calls,timestamp,finish_reason,compacted FROM messages WHERE session_id = ? AND active = 1 ORDER BY id LIMIT 100001").all(e);if(o.length>1e5)throw new Error("Native session exceeds the event limit.");let l=0;n={...i,messages:o.map(c=>{if(l+=Buffer.byteLength(JSON.stringify(c)),l>L)throw new Error("Native session exceeds the retained byte limit.");return{...c,tool_calls:typeof c.tool_calls=="string"?JSON.parse(c.tool_calls):null}}),message_count:o.length}}let r=JSON.stringify(n);if(Buffer.byteLength(r)>L)throw new Error("Native session exceeds the retained byte limit.");return{path:`${e}.json`,text:r}}finally{t.close()}}p(Pt,"readDatabaseSession");function Le(s){return typeof s!="string"?null:s.replace(/\s+/gu," ").trim().slice(0,160)||null}p(Le,"titleText");function jt(s,e,t=!1){let n=s.filter(r=>r.sessionId===void 0||r.sessionId===e);for(let r of[...n].reverse())if(r.type==="custom-title"){let i=Le(r.customTitle);if(i)return i}for(let r of[...n].reverse())if(r.type==="summary"){let i=Le(r.summary);if(i)return i}for(let r of n){if(r.type!=="user"||r.sessionId!==e||r.isMeta||r.isSidechain&&!t)continue;let i=_(r.message).content,a=Le(Array.isArray(i)?i.filter(o=>_(o).type==="text").map(o=>_(o).text).filter(o=>typeof o=="string").join(" "):i);if(a)return a}return e}p(jt,"claudeConversationTitle");function Wt(s,e){return Le(s)??e}p(Wt,"retainedConversationTitle");var le=class extends Error{static{p(this,"NativeSessionNotReadyError")}constructor(){super("This session has no retained user request yet.")}};import{createHash as Xs}from"node:crypto";import{open as Ks}from"node:fs/promises";async function zt(s){let e=await Ks(s.path,"r");try{let t=await e.stat();if(!t.isFile()||t.size>512*1024*1024)return null;let n=Xs("sha256"),r=new TextDecoder("utf-8",{fatal:!0}),i=s.since===null?-1/0:Date.parse(s.since),a=Date.parse(s.until),o=new de,l=0,c=0,f=[],u=0,h=p(w=>{if(++l>1e6||w.byteLength>$.lineBytes)return!1;let y;try{y=r.decode(w)}catch{return!1}if(!y.trim())return!0;let m;try{m=JSON.parse(y)}catch{return!1}if(!m||typeof m!="object"||Array.isArray(m))return!1;let d=m,E=d.payload&&typeof d.payload=="object"&&!Array.isArray(d.payload)?d.payload:{};if(!o.accept(d)||o.metadata&&o.metadata.id!==s.sessionId)return!1;if(d.type==="response_item"&&E.type==="message"&&E.role==="user"||d.type==="event_msg"&&E.type==="user_message"){let b=typeof d.timestamp=="string"?Date.parse(d.timestamp):NaN;if(!Number.isFinite(b)||b>=i&&b<a)return!1}return!0},"inspect");for await(let w of e.createReadStream({autoClose:!1,highWaterMark:256*1024})){await s.check();let y=Buffer.isBuffer(w)?w:Buffer.from(w);if(c+=y.byteLength,c>512*1024*1024)return null;n.update(y);let m=0,d;for(;(d=y.indexOf(10,m))!==-1;){let S=y.subarray(m,d);if(u+S.byteLength>$.lineBytes)return null;let b=f.length?Buffer.concat([...f,S],u+S.byteLength):S;if(!h(b))return null;f=[],u=0,m=d+1}let E=y.subarray(m);if(E.byteLength&&(f.push(E),u+=E.byteLength),u>$.lineBytes)return null}if(u&&!h(Buffer.concat(f,u)))return null;let g=await e.stat();if(t.dev!==g.dev||t.ino!==g.ino||t.size!==g.size||t.mtimeMs!==g.mtimeMs||t.ctimeMs!==g.ctimeMs||c!==g.size)throw new Error("Native source changed during window inventory.");return o.metadata?{sha256:n.digest("hex")}:null}finally{await e.close()}}p(zt,"inspectCodexWindow");async function Ve(s,e,t=!0){let n=await Jt(s.root),r=await Jt(tn(n,e)),i=en(n,r);if(i.startsWith(`..${sn}`)||i===".."||Ye(i))throw new Error("History path is outside the selected source.");if(t&&(await Xt(r)).size>L)throw new Error("Source file exceeds 32 MiB.");return r}p(Ve,"selectedPath");async function _e(s,e){let t=await Ve(s,e),n=await Qs(t);if(n.byteLength>L)throw new Error("Source changed beyond the retained limit.");let r=t.endsWith(".zst")?nn(n,{maxOutputLength:64*1024*1024}):n,i=new TextDecoder("utf-8",{fatal:!0}).decode(r);if(t.endsWith(".jsonl")&&i&&!i.endsWith(`
|
|
20
20
|
`)){let a=i.lastIndexOf(`
|
|
21
|
-
`);try{JSON.parse(i.slice(a+1))}catch{return i.slice(0,a+1)}}return i}p(
|
|
22
|
-
`);if(o=
|
|
23
|
-
`))try{JSON.parse(
|
|
24
|
-
`);if(
|
|
25
|
-
`)){let C=
|
|
26
|
-
`);try{JSON.parse(
|
|
27
|
-
${
|
|
21
|
+
`);try{JSON.parse(i.slice(a+1))}catch{return i.slice(0,a+1)}}return i}p(_e,"readSelectedFile");async function Kt(s,e,t){if(s.source!=="codex"||s.acquisition!=="files"||e.issue||!(e.path||s.root).endsWith(".jsonl"))return null;if(e.sourceInstanceId!==s.instanceId)throw new Error("Native session belongs to another selected source.");return zt({...t,path:await Ve(s,e.path,!1),sessionId:e.nativeSessionId})}p(Kt,"inspectSessionWindow");async function rn(s){if((await Vs(s.root)).isFile())return[""];let e=s.source==="codex"?["sessions","archived_sessions"]:s.source==="grok_build"?["sessions"]:s.source==="claude_code"?["projects"]:s.source==="pi"||s.source==="oh_my_pi"?["sessions"]:[""],t=[];async function n(r,i){if(i>12)throw new Error("Selected history exceeds directory depth limit.");let a;try{a=await Zs(ke(s.root,r),{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(let o of a){let l=ke(r,o.name);if(!o.isSymbolicLink()&&(o.isDirectory()?await n(l,i+1):o.isFile()&&(s.source==="openclaw"?o.name==="manifest.json":s.source==="grok_build"?o.name==="updates.jsonl":/\.jsonl(?:\.zst)?$/u.test(o.name))&&t.push(l),t.length>1e4))throw new Error("Select a narrower source directory (more than 10,000 history files).")}}p(n,"walk");for(let r of e)await n(r,0);return!t.length&&e[0]!==""&&await n("",0),t.sort()}p(rn,"pathsBelow");function Gt(s,e){return(e||s.root).endsWith(".json")}p(Gt,"sessionFileJson");async function pe(s,e={}){if(!s.available||!s.capabilities.history)throw new Error(s.reason??"Native history is unavailable.");let t=e.limit??50;if(!Number.isInteger(t)||t<1||t>100||e.since&&!Number.isFinite(Date.parse(e.since)))throw new Error("Invalid history page or date range.");if(s.acquisition==="sqlite")return Bt(s,{...e,limit:t});let n=await rn(s),r=[];for(let i of n)if(!(e.parentNativeSessionId&&s.source==="claude_code"&&!i.replaceAll("\\","/").includes(`/${e.parentNativeSessionId}/subagents/`))&&!(e.cursor&&i<=e.cursor)){try{let a=await Xt(ke(s.root,i));if(e.since&&a.mtimeMs<Date.parse(e.since))continue;let o;if(s.acquisition!=="bundle"&&!Gt(s,i)&&s.source!=="hermes"&&!(i||s.root).endsWith(".zst")){let m=await Ys(await Ve(s,i,!1),"r");try{let d=Buffer.alloc(262144),E=await m.read(d,0,d.length,0),S=d.subarray(0,E.bytesRead).toString("utf8"),b=S.lastIndexOf(`
|
|
22
|
+
`);if(o=S,!S.endsWith(`
|
|
23
|
+
`))try{JSON.parse(S.slice(b+1))}catch{o=S.slice(0,b+1)}let N=(await m.stat()).size;if(s.source==="claude_code"&&N>E.bytesRead){let v=Math.max(E.bytesRead,N-d.length),A=Buffer.alloc(d.length+1),M=await m.read(A,0,A.length,v-1),x=A.subarray(0,M.bytesRead).toString("utf8"),R=x.indexOf(`
|
|
24
|
+
`);if(x=R<0?"":x.slice(R+1),!x.endsWith(`
|
|
25
|
+
`)){let C=x.lastIndexOf(`
|
|
26
|
+
`);try{JSON.parse(x.slice(C+1))}catch{x=x.slice(0,C+1)}}o+=`
|
|
27
|
+
${x}`}}finally{await m.close()}}else o=await _e(s,i);let l=s.acquisition==="bundle"||Gt(s,i)?[_(JSON.parse(o))]:o.split(/\r?\n/u).filter(Boolean).slice(0,s.source==="claude_code"?void 0:12).map(m=>_(JSON.parse(m))),c=l.find(m=>m.type==="session"||m.type==="session_meta")??l[0]??{},f=c.type==="session_meta"?_(c.payload):s.source==="grok_build"?_(c.params):s.source==="opencode"?_(c.info):c,u=s.source==="claude_code"?ee(i||s.root).replace(/\.jsonl(?:\.zst)?$/u,""):typeof f.id=="string"?f.id:typeof f.sessionId=="string"?f.sessionId:ee(i).replace(/\.jsonl(?:\.zst)?$/u,""),h=s.source==="claude_code"&&/(?:^|[\/])subagents[\/]agent-[^\/]+\.jsonl$/u.test(i)?l.find(m=>m.isSidechain===!0&&typeof m.agentId=="string"&&`agent-${m.agentId}`===u&&typeof m.sessionId=="string"&&ee(Ke(Ke(i)))===m.sessionId):void 0,w=(s.source==="claude_code"?l.find(m=>m.sessionId===(h?.sessionId??u)&&m.type==="user"&&typeof m.cwd=="string"&&Ye(m.cwd)):void 0)?.cwd??f.cwd,y=s.source==="claude_code"?jt(l,h?String(h.sessionId):u,!!h):Wt(f.title,u);if(s.source==="grok_build"&&i.endsWith("updates.jsonl"))try{let m=_(JSON.parse(await _e(s,ke(Ke(i),"summary.json")))),d=_(m.info);d.id===u&&(w=d.cwd,typeof m.generated_title=="string"&&(y=m.generated_title.slice(0,500)))}catch{}r.push({nativeSessionId:u,...h?{parentNativeSessionId:String(h.sessionId)}:{},sourceInstanceId:s.instanceId,path:i,title:y,cwd:typeof w=="string"&&Ye(w)?w:null,updatedAt:a.mtime.toISOString(),storageRevision:[a.dev,a.ino,a.size,a.mtimeMs,a.ctimeMs].join(":")})}catch(a){if(a.code==="ENOENT")continue;r.push({nativeSessionId:ee(i||s.root),sourceInstanceId:s.instanceId,path:i,title:ee(i||s.root),cwd:null,updatedAt:new Date(0).toISOString(),issue:a instanceof Error?a.message:"Unable to inspect native session"})}if(r.length>t)break}return{items:r.slice(0,t),nextCursor:r.length>t?r[t-1].path:null}}p(pe,"listSessions");function Yt(s,e){let t=Ce(e);if(t.sessionId!==(s.parentNativeSessionId??s.nativeSessionId))throw new Error("Native session changed identity.");if(s.parentNativeSessionId&&e.filter(r=>r.type==="user"||r.type==="assistant").some(r=>r.isSidechain!==!0||`agent-${String(r.agentId)}`!==s.nativeSessionId))throw new Error("Native worker changed identity.");return t}p(Yt,"assertClaudeIdentity");async function Ze(s,e){if(s.source!=="claude_code")return{revision:"",branches:[]};if(e.issue)throw new Error(e.issue);if(e.sourceInstanceId!==s.instanceId)throw new Error("Native session belongs to another selected source.");let t=await _e(s,e.path),n=Yt(e,Q({path:ee(e.path),text:t}));return{revision:O(t),branches:n.branches()}}p(Ze,"inspectSessionBranches");async function De(s,e,t={}){if(e.issue)throw new Error(e.issue);if(e.sourceInstanceId!==s.instanceId)throw new Error("Native session belongs to another selected source.");let n;if(s.acquisition==="sqlite")n=[Pt(s,e.nativeSessionId)];else if(s.acquisition==="bundle"){let i=e.path.slice(0,-13);n=await Promise.all(["manifest.json","events.jsonl","session-branch.json"].map(async a=>({path:a,text:await _e(s,`${i}${a}`)})))}else n=[{path:ee(e.path||s.root).replace(/\.zst$/u,""),text:await _e(s,e.path)}];if(t.expectedBranchRevision&&!t.branchLeafId)throw new Error("Choose a branch before supplying its revision.");if(s.source==="claude_code"){let i=n[0],a=Yt(e,Q(i));if(t.latestBranch){if(t.branchLeafId||t.expectedBranchRevision||t.branchAnchor)throw new Error("Choose either the latest conversation or an explicit branch.");n=[{...i,text:a.select(a.latestLeafId()).chain.map(o=>JSON.stringify(o)).join(`
|
|
28
28
|
`)+`
|
|
29
29
|
`}]}if(t.branchAnchor){if(t.branchLeafId||t.expectedBranchRevision)throw new Error("Choose either a frozen branch snapshot or a followed branch anchor.");if(a.select(t.branchAnchor.leafId).chainHash!==t.branchAnchor.chainHash)throw new Error("The selected branch history changed. Review and select it again before syncing.");let l=a.leaves.filter(c=>a.select(c.uuid).chain.some(f=>f.uuid===t.branchAnchor.leafId));if(l.length!==1)throw new Error("The selected branch diverged. Pause this connection and choose its branch again.");t={...t,branchLeafId:l[0].uuid}}if(t.expectedBranchRevision&&O(i.text)!==t.expectedBranchRevision)throw new Error("This conversation changed. Refresh its branches and choose again.");if(t.branchLeafId){if(!a.leaves.some(o=>o.uuid===t.branchLeafId))throw new Error("The selected Claude branch is no longer a leaf. Refresh and choose again.");n=[{...i,text:a.select(t.branchLeafId).chain.map(o=>JSON.stringify(o)).join(`
|
|
30
30
|
`)+`
|
|
31
|
-
`}]}}else if(t.expectedBranchRevision||t.branchAnchor)throw new Error("Branch revision selection is only supported for Claude Code.");let r=
|
|
31
|
+
`}]}}else if(t.expectedBranchRevision||t.branchAnchor)throw new Error("Branch revision selection is only supported for Claude Code.");let r=Rt({source:s.source,files:n,acquisition:{machineId:s.machineId,sourceInstanceId:s.instanceId},...t});if(r.issues.length&&r.issues.every(i=>i.code==="no_user_request"))throw new le;if(r.issues.length)throw new Error(r.issues.map(i=>i.message).join("; "));if(s.acquisition==="sqlite"&&r.sessions.some(i=>i.sessionId!==e.nativeSessionId))throw new Error("Native session changed identity.");return{files:n,preview:r,branchLeafId:t.branchLeafId}}p(De,"readSession");var on=Y.object({sourceInstanceId:Y.string().min(1).max(500),sessionKeys:Y.array(Y.string().regex(/^[a-f0-9]{64}$/)).min(1).max(1e4)}).strict().refine(s=>new Set(s.sessionKeys).size===s.sessionKeys.length,"Conversation selection contains duplicates.");function ue(s){return O(JSON.stringify([s.path,s.nativeSessionId]))}p(ue,"nativeSessionSelectionKey");async function an(s){if(!s.available||!s.capabilities.history)throw new Error("The selected conversation source is unavailable.");let e=[],t,n=new Set;do{let r=await pe(s,{cursor:t,limit:100});if(e.push(...r.items),e.length>1e4)throw new Error("Choose a source with no more than 10,000 conversations.");if(t=r.nextCursor??void 0,t&&n.has(t))throw new Error("Conversation listing did not advance. Refresh the source.");t&&n.add(t)}while(t);return e}p(an,"nativeUploadInventory");async function pi(s,e){let t=on.parse(e);if(t.sourceInstanceId!==s.instanceId)throw new Error("Conversation selection belongs to another source installation.");let n=new Set((await an(s)).map(ue));if(t.sessionKeys.some(r=>!n.has(r)))throw new Error("A selected conversation is no longer available. Refresh and select it again.");return t}p(pi,"validateNativeUploadSelection");function ui(s,e,t){let n=(t.query??"").trim().toLocaleLowerCase(),r=t.range??"all",i=t.offset??0;if(n.length>500||!["day","week","all"].includes(r)||!Number.isInteger(i)||i<0||i>1e4)throw new Error("Invalid conversation search or page.");let a=r==="all"?0:Date.now()-(r==="day"?1:7)*864e5,o=e.filter(c=>Date.parse(c.updatedAt)>=a&&(!n||[c.title,c.cwd,c.nativeSessionId].some(f=>f?.toLocaleLowerCase().includes(n)))).sort((c,f)=>f.updatedAt.localeCompare(c.updatedAt)),l=s.selectedSessionKeys?new Set(s.selectedSessionKeys):null;return{total:o.length,nextOffset:i+50<o.length?i+50:null,items:o.slice(i,i+50).map(c=>({key:ue(c),title:c.title,cwd:c.cwd,nativeSessionId:c.nativeSessionId,updatedAt:c.updatedAt,issue:c.issue??null,approved:l===null||l.has(ue(c))}))}}p(ui,"nativeUploadConversationPage");var Vt=Ns(xs(),1);function fe(s,e=new Date){if(s.length>512)throw new Error("Cron expressions must be at most 512 characters.");let t=s.trim().split(/\s+/u);if(t.length!==5)throw new Error("Use five cron fields: minute hour day-of-month month day-of-week.");let n=[[],[],[],["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],["sun","mon","tue","wed","thu","fri","sat"]],r=t.map((c,f)=>c.replace(/[a-z]+/giu,u=>{let h=n[f].indexOf(u.toLowerCase());if(h<0)throw new Error("Cron supports standard month/weekday names, numbers, *, lists, ranges and steps.");return String(h+(f===3?1:0))}));if(r.some(c=>!/^[\d*,/\-]+$/u.test(c)))throw new Error("Cron supports numbers, *, lists, ranges and steps; second-level schedules are not supported.");let i=r.join(" "),a=Vt.CronExpressionParser.parse(i,{currentDate:e,tz:Intl.DateTimeFormat().resolvedOptions().timeZone}),o=a.fields;if(o.minute.values.length!==1)throw new Error("Imports support at most one scheduled run per hour. Choose a single cron minute, such as 0 or 30.");let l={minute:[...o.minute.values],hour:[...o.hour.values],month:[...o.month.values],dayOfMonth:o.dayOfMonth.values.map(Number),dayOfWeek:[...new Set(o.dayOfWeek.values.map(c=>Number(c)%7))],anyDayOfMonth:o.dayOfMonth.isWildcard,anyDayOfWeek:o.dayOfWeek.isWildcard};return{expression:i,calendar:l,interval:a}}p(fe,"parseImportCron");function be(s,e){let t=s.dayOfMonth.includes(e.getDate()),n=s.dayOfWeek.includes(e.getDay());return(!s.anyDayOfMonth&&!s.anyDayOfWeek&&(t||n)||t&&s.anyDayOfWeek||s.anyDayOfMonth&&!s.anyDayOfWeek&&n)&&s.month.includes(e.getMonth()+1)&&s.hour.includes(e.getHours())&&s.minute.includes(e.getMinutes())}p(be,"importCalendarMatches");var Qe=["sun","mon","tue","wed","thu","fri","sat"];function cn(s){if(!/^(?:[01]\d|2[0-3]):[0-5]\d$/u.test(s))throw new Error("Use a sync time in 24-hour HH:MM format, such as 00:00.");return s}p(cn,"syncTime");function he(s){if(s.frequency==="hourly")return{frequency:s.frequency};if(s.frequency==="cron"){let t=fe(s.expression);return t.interval.next(),{frequency:"cron",expression:t.expression}}let e=cn(s.time);if(s.frequency==="daily")return{frequency:"daily",time:e};if(s.frequency==="weekly"&&Number.isInteger(s.day)&&s.day>=0&&s.day<=6)return{frequency:"weekly",time:e,day:s.day};throw new Error("Choose a supported import frequency and, for weekly imports, a weekday from Sunday (0) to Saturday (6).")}p(he,"validateCollectorSchedule");function Me(s){if(s.frequency==="cron")return s.expression;if(s.frequency==="hourly")return"0 * * * *";let[e,t]=s.time.split(":").map(Number);return`${t} ${e} * * ${s.frequency==="weekly"?s.day:"*"}`}p(Me,"scheduleExpression");function Ei(s){return s.frequency==="cron"?`cron ${s.expression}`:s.frequency==="hourly"?"hourly at minute 00":s.frequency==="daily"?`daily at ${s.time}`:`weekly on ${Qe[s.day]} at ${s.time}`}p(Ei,"scheduleDescription");function dn(s){return`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`}p(dn,"localDay");function et(s){return`${dn(s)}T${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`}p(et,"scheduledMinute");function Zt(s,e=new Date){let{interval:t,calendar:n}=fe(Me(s),e);for(let r=0;r<10;r++){let i=t.next().toDate();if(be(n,i))return i.toISOString()}throw new Error("Unable to determine the next sync time.")}p(Zt,"nextScheduledSync");function Qt(s,e,t=new Date){return!s||e===et(t)?!1:be(fe(Me(s),t).calendar,t)}p(Qt,"scheduledSyncDue");import{DatabaseSync as pn}from"node:sqlite";import{mkdir as un,chmod as ts}from"node:fs/promises";import{join as fn}from"node:path";var P={heartbeatMs:1e4,staleMs:6e4,maxPending:1e4,maxBytes:134217728,batchCases:20,runMs:36e5,requestMs:6e4,attemptsPerRun:3};function bi(s,e){if(e.id!==s.id||e.teamId!==s.teamId||e.projectId!==s.projectId||e.machineId!==s.source.machineId||e.sourceInstanceId!==s.source.instanceId||e.sourceRoot!==s.source.root||e.source!==s.source.source)throw new Error("The hosted destination belongs to another source or workspace.");return{taskDatasetId:e.taskDatasetId,conversationDatasetId:e.conversationDatasetId}}p(bi,"collectorDestinations");function es(s){let e={tasks:null,conversations:null};if(!s.accountBaseUrl||!s.destinations)return e;let t;try{t=new URL(s.accountBaseUrl)}catch{return e}if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1"].includes(t.hostname))||t.username||t.password||t.search||t.hash||t.pathname!=="/")return e;let n=p(r=>r?`${t.origin}/console/datasets/${encodeURIComponent(r)}/tasks?project=${encodeURIComponent(s.projectId)}&connection=${encodeURIComponent(s.id)}`:null,"link");return{tasks:n(s.destinations.taskDatasetId),conversations:n(s.destinations.conversationDatasetId)}}p(es,"collectorDestinationLinks");var $e=class{static{p(this,"CollectorProgress")}database;constructor(e){this.database=e,e.exec(`
|
|
32
32
|
CREATE TABLE IF NOT EXISTS backfills(connection_id TEXT PRIMARY KEY,discovered INTEGER NOT NULL DEFAULT 0);
|
|
33
33
|
CREATE TABLE IF NOT EXISTS backfill_units(connection_id TEXT NOT NULL,session_key TEXT NOT NULL,state TEXT NOT NULL,error TEXT,PRIMARY KEY(connection_id,session_key));
|
|
34
34
|
CREATE TABLE IF NOT EXISTS backfill_operations(operation_id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,session_key TEXT NOT NULL,admitted INTEGER NOT NULL DEFAULT 0);
|
|
35
|
-
`)}reset(e){for(let t of["backfill_operations","backfill_units","backfills"])this.database.prepare(`DELETE FROM ${t} WHERE connection_id=?`).run(e)}select(e,t){this.database.prepare("INSERT OR IGNORE INTO backfills(connection_id) VALUES(?)").run(e),this.database.prepare("SELECT discovered FROM backfills WHERE connection_id=?").get(e)?.discovered||this.database.prepare("INSERT OR IGNORE INTO backfill_units VALUES(?,?,'reading',NULL)").run(e,t)}tracks(e,t){let n=this.database.prepare("SELECT state FROM backfill_units WHERE connection_id=? AND session_key=?").get(e,t);return n?.state==="reading"||n?.state==="error"}queued(e,t,n){this.tracks(t,n)&&this.database.prepare("INSERT OR IGNORE INTO backfill_operations VALUES(?,?,?,0)").run(e,t,n)}retained(e,t,n){if(!this.tracks(e,t))return;let r=this.database.prepare("SELECT id FROM pending WHERE connection_id=? AND json_extract(payload,'$.sessionKey')=?").all(e,n);for(let i of r)this.queued(String(i.id),e,t)}read(e,t,n){if(!this.tracks(e,t))return;let r=this.database.prepare("SELECT COUNT(*) AS n FROM backfill_operations WHERE connection_id=? AND session_key=? AND admitted=0").get(e,t);this.database.prepare("UPDATE backfill_units SET state=?,error=NULL WHERE connection_id=? AND session_key=?").run(Number(r?.n)?"queued":n?"complete":"skipped",e,t)}failed(e,t,n){this.tracks(e,t)&&this.database.prepare("UPDATE backfill_units SET state='error',error=? WHERE connection_id=? AND session_key=?").run(n.slice(0,500),e,t)}discovered(e){this.database.prepare("INSERT INTO backfills VALUES(?,1) ON CONFLICT(connection_id) DO UPDATE SET discovered=1").run(e)}acknowledge(e){let t=this.database.prepare("SELECT connection_id,session_key FROM backfill_operations WHERE operation_id=?").get(e);if(!t)return;this.database.prepare("UPDATE backfill_operations SET admitted=1 WHERE operation_id=?").run(e);let n=this.database.prepare("SELECT COUNT(*) AS n FROM backfill_operations WHERE connection_id=? AND session_key=? AND admitted=0").get(t.connection_id,t.session_key);Number(n?.n)||this.database.prepare("UPDATE backfill_units SET state='complete' WHERE connection_id=? AND session_key=? AND state='queued'").run(t.connection_id,t.session_key)}status(e){let t=this.database.prepare("SELECT discovered FROM backfills WHERE connection_id=?").get(e),n=this.database.prepare("SELECT state,COUNT(*) AS n FROM backfill_units WHERE connection_id=? GROUP BY state").all(e),r=p(a=>Number(n.find(o=>o.state===a)?.n??0),"count"),i=n.reduce((a,o)=>a+Number(o.n),0);return{stage:t?.discovered?r("error")?"attention":r("reading")?"reading":r("queued")?"uploading":"complete":"discovering",total:i,admitted:r("complete"),skipped:r("skipped"),failed:r("error")}}};var
|
|
35
|
+
`)}reset(e){for(let t of["backfill_operations","backfill_units","backfills"])this.database.prepare(`DELETE FROM ${t} WHERE connection_id=?`).run(e)}select(e,t){this.database.prepare("INSERT OR IGNORE INTO backfills(connection_id) VALUES(?)").run(e),this.database.prepare("SELECT discovered FROM backfills WHERE connection_id=?").get(e)?.discovered||this.database.prepare("INSERT OR IGNORE INTO backfill_units VALUES(?,?,'reading',NULL)").run(e,t)}tracks(e,t){let n=this.database.prepare("SELECT state FROM backfill_units WHERE connection_id=? AND session_key=?").get(e,t);return n?.state==="reading"||n?.state==="error"}queued(e,t,n){this.tracks(t,n)&&this.database.prepare("INSERT OR IGNORE INTO backfill_operations VALUES(?,?,?,0)").run(e,t,n)}retained(e,t,n){if(!this.tracks(e,t))return;let r=this.database.prepare("SELECT id FROM pending WHERE connection_id=? AND json_extract(payload,'$.sessionKey')=?").all(e,n);for(let i of r)this.queued(String(i.id),e,t)}read(e,t,n){if(!this.tracks(e,t))return;let r=this.database.prepare("SELECT COUNT(*) AS n FROM backfill_operations WHERE connection_id=? AND session_key=? AND admitted=0").get(e,t);this.database.prepare("UPDATE backfill_units SET state=?,error=NULL WHERE connection_id=? AND session_key=?").run(Number(r?.n)?"queued":n?"complete":"skipped",e,t)}failed(e,t,n){this.tracks(e,t)&&this.database.prepare("UPDATE backfill_units SET state='error',error=? WHERE connection_id=? AND session_key=?").run(n.slice(0,500),e,t)}discovered(e){this.database.prepare("INSERT INTO backfills VALUES(?,1) ON CONFLICT(connection_id) DO UPDATE SET discovered=1").run(e)}acknowledge(e){let t=this.database.prepare("SELECT connection_id,session_key FROM backfill_operations WHERE operation_id=?").get(e);if(!t)return;this.database.prepare("UPDATE backfill_operations SET admitted=1 WHERE operation_id=?").run(e);let n=this.database.prepare("SELECT COUNT(*) AS n FROM backfill_operations WHERE connection_id=? AND session_key=? AND admitted=0").get(t.connection_id,t.session_key);Number(n?.n)||this.database.prepare("UPDATE backfill_units SET state='complete' WHERE connection_id=? AND session_key=? AND state='queued'").run(t.connection_id,t.session_key)}status(e){let t=this.database.prepare("SELECT discovered FROM backfills WHERE connection_id=?").get(e),n=this.database.prepare("SELECT state,COUNT(*) AS n FROM backfill_units WHERE connection_id=? GROUP BY state").all(e),r=p(a=>Number(n.find(o=>o.state===a)?.n??0),"count"),i=n.reduce((a,o)=>a+Number(o.n),0);return{stage:t?.discovered?r("error")?"attention":r("reading")?"reading":r("queued")?"uploading":"complete":"discovering",total:i,admitted:r("complete"),skipped:r("skipped"),failed:r("error")}}};var te=class{static{p(this,"CollectorCoverage")}store;constructor(e){this.store=e,e.database.exec(`CREATE TABLE IF NOT EXISTS coverage_sessions(
|
|
36
36
|
connection_id TEXT NOT NULL,source_key_hash TEXT NOT NULL,value TEXT NOT NULL,
|
|
37
|
-
PRIMARY KEY(connection_id,source_key_hash));`)}begin(e,t,n,r){let i=
|
|
37
|
+
PRIMARY KEY(connection_id,source_key_hash));`)}begin(e,t,n,r){let i=Te.parse({schemaVersion:"openpond.collectorCoverageManifest.v1",jobId:t,connectionId:e.id,connectionRevision:e.revision,machineId:e.source.machineId,sourceInstanceId:e.source.instanceId,from:e.since,to:r,startedAt:n,finishedAt:null,listingComplete:!1,pendingOperations:this.store.queued(e.id),sessions:[]});this.store.database.exec("BEGIN IMMEDIATE");try{this.store.database.prepare("DELETE FROM coverage_sessions WHERE connection_id=?").run(e.id),this.store.set(`coverage:${e.id}`,JSON.stringify(i)),this.store.database.exec("COMMIT")}catch(a){throw this.store.database.exec("ROLLBACK"),a}}record(e,t){let n=ce.parse(t),r=JSON.stringify(n),i=this.store.database.prepare("SELECT COALESCE(SUM(length(value)),0) AS bytes FROM coverage_sessions WHERE connection_id=? AND source_key_hash!=?").get(e,n.sourceKeyHash),a=this.store.database.prepare("SELECT COALESCE(SUM(json_array_length(n.value,'$.boundaries')),0) AS n FROM coverage_sessions c,json_each(c.value,'$.normalized') n WHERE c.connection_id=? AND c.source_key_hash!=?").get(e,n.sourceKeyHash);if(Buffer.byteLength(r)+Number(i?.bytes??0)>8*1024*1024||n.normalized.reduce((c,f)=>c+f.boundaries.length,0)+Number(a?.n??0)>2e4)throw new Error("Source coverage exceeds its bounded inventory. Select a narrower import window.");let o=Number(this.store.database.prepare("SELECT COUNT(*) AS n FROM coverage_sessions WHERE connection_id=?").get(e)?.n??0);if(!this.store.database.prepare("SELECT 1 FROM coverage_sessions WHERE connection_id=? AND source_key_hash=?").get(e,n.sourceKeyHash)&&o>=1e4)throw new Error("Source inventory exceeds 10,000 sessions. Select a narrower import window.");this.store.database.prepare("INSERT INTO coverage_sessions VALUES(?,?,?) ON CONFLICT(connection_id,source_key_hash) DO UPDATE SET value=excluded.value").run(e,n.sourceKeyHash,r)}manifest(e){let t=this.store.setting(`coverage:${e}`);if(!t)return null;let n=this.store.database.prepare("SELECT value FROM coverage_sessions WHERE connection_id=? ORDER BY source_key_hash").all(e).map(r=>ce.parse(JSON.parse(String(r.value))));return Te.parse({...JSON.parse(t),pendingOperations:this.store.queued(e),sessions:n})}finish(e,t){let n=this.manifest(e);if(!n)throw new Error("Source coverage was not initialized.");n.listingComplete||=t,n.finishedAt??=new Date().toISOString();let{sessions:r,...i}=Te.parse(n);return this.store.set(`coverage:${e}`,JSON.stringify({...i,sessions:[]})),n}summary(e){let t=this.manifest(e);return t?ut(t):null}static sourceKey(e){return O(e)}};import{setImmediate as ln}from"node:timers/promises";var se=class extends Error{static{p(this,"CollectorQueueFullError")}constructor(){super("Import queue is full. Pending uploads must finish before more history can be read.")}},He=class{static{p(this,"CollectorSnapshots")}database;constructor(e){this.database=e,e.exec(`
|
|
38
38
|
CREATE TABLE IF NOT EXISTS collector_snapshots(hash TEXT PRIMARY KEY,payload TEXT NOT NULL,bytes INTEGER NOT NULL);
|
|
39
39
|
CREATE TABLE IF NOT EXISTS pending_snapshots(operation_id TEXT PRIMARY KEY,snapshot_hash TEXT NOT NULL);
|
|
40
40
|
CREATE INDEX IF NOT EXISTS pending_snapshots_hash ON pending_snapshots(snapshot_hash);
|
|
41
41
|
`)}prepare(e){let t=JSON.stringify(e);return{hash:O(e),payload:t,bytes:Buffer.byteLength(t)}}exists(e){return!!this.database.prepare("SELECT 1 FROM collector_snapshots WHERE hash=?").get(e)}retain(e,t){this.database.prepare("INSERT OR IGNORE INTO collector_snapshots VALUES(?,?,?)").run(t.hash,t.payload,t.bytes),this.database.prepare("INSERT OR REPLACE INTO pending_snapshots VALUES(?,?)").run(e,t.hash)}files(e){let t=this.database.prepare("SELECT payload FROM collector_snapshots JOIN pending_snapshots ON hash=snapshot_hash WHERE operation_id=?").get(e);if(!t)throw new Error("The pending import's source snapshot is missing.");return JSON.parse(String(t.payload))}bytes(e){return Number(e?this.database.prepare("SELECT COALESCE(SUM(bytes),0) AS n FROM collector_snapshots WHERE hash IN (SELECT snapshot_hash FROM pending_snapshots JOIN pending ON operation_id=pending.id WHERE connection_id=?)").get(e)?.n:this.database.prepare("SELECT COALESCE(SUM(bytes),0) AS n FROM collector_snapshots").get()?.n)}collect(){this.database.exec(`DELETE FROM pending_snapshots WHERE operation_id NOT IN (SELECT id FROM pending);
|
|
42
|
-
DELETE FROM collector_snapshots WHERE hash NOT IN (SELECT snapshot_hash FROM pending_snapshots);`)}async migrate(e){let t=this.database.prepare("SELECT id FROM pending WHERE id NOT IN (SELECT operation_id FROM pending_snapshots)").all();for(let n of t){if(await
|
|
42
|
+
DELETE FROM collector_snapshots WHERE hash NOT IN (SELECT snapshot_hash FROM pending_snapshots);`)}async migrate(e){let t=this.database.prepare("SELECT id FROM pending WHERE id NOT IN (SELECT operation_id FROM pending_snapshots)").all();for(let n of t){if(await ln(),e())return;let r=this.database.prepare("SELECT payload FROM pending WHERE id=?").get(n.id);if(!r)continue;let{files:i,...a}=JSON.parse(String(r.payload)),o=this.prepare(i),l=JSON.stringify(a);this.database.exec("BEGIN IMMEDIATE");try{this.retain(String(n.id),o),this.database.prepare("UPDATE pending SET payload=?,bytes=? WHERE id=?").run(l,Buffer.byteLength(l),n.id),this.database.exec("COMMIT")}catch(c){throw this.database.exec("ROLLBACK"),c}}this.collect()}};var j=class s{static{p(this,"CollectorStore")}database;progress;snapshots;coverage;constructor(e){this.database=e,this.progress=new $e(e),this.snapshots=new He(e),this.coverage=new te(this)}static async open(e){await un(e,{recursive:!0,mode:448}),await ts(e,448);let t=fn(e,"collector.sqlite"),n=new pn(t);return await ts(t,384),n.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000;
|
|
43
43
|
CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
|
44
44
|
CREATE TABLE IF NOT EXISTS connections(id TEXT PRIMARY KEY,config TEXT NOT NULL,admitted INTEGER NOT NULL DEFAULT 0,error TEXT);
|
|
45
45
|
CREATE TABLE IF NOT EXISTS admitted_boundaries(connection_id TEXT NOT NULL,boundary_id TEXT NOT NULL,PRIMARY KEY(connection_id,boundary_id));
|
|
@@ -50,8 +50,8 @@ ${A}`}}finally{await y.close()}}else o=await be(s,i);let l=s.acquisition==="bund
|
|
|
50
50
|
SELECT 1 FROM pending p, json_each(p.payload,'$.boundaryIds') b
|
|
51
51
|
WHERE p.connection_id=checkpoints.connection_id
|
|
52
52
|
AND json_extract(p.payload,'$.sessionKey')=checkpoints.session_key
|
|
53
|
-
AND b.value=checkpoints.boundary_id)`).run(e.id);for(let r of n||t.since!==e.since?["source_scans","checkpoints","pending"]:["source_scans","pending"])this.database.prepare(`DELETE FROM ${r} WHERE connection_id=?`).run(e.id);this.snapshots.collect(),n&&(this.database.prepare("DELETE FROM admitted_boundaries WHERE connection_id=?").run(e.id),this.database.prepare("UPDATE connections SET admitted=0 WHERE id=?").run(e.id),this.database.prepare("DELETE FROM settings WHERE key=?").run(`lastAdmission:${e.id}`))}else t&&(e={...e,requestedSyncRevision:Math.max(t.requestedSyncRevision??0,e.requestedSyncRevision??0),completedSyncRevision:Math.max(t.completedSyncRevision??0,e.completedSyncRevision??0)});this.database.prepare("INSERT INTO connections(id,config) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET config=excluded.config").run(e.id,JSON.stringify(e)),this.database.exec("COMMIT")}catch(t){throw this.database.exec("ROLLBACK"),t}}error(e,t){this.database.prepare("UPDATE connections SET error=? WHERE id=?").run(t?.slice(0,500)??null,e)}queued(e){return Number((e?this.database.prepare("SELECT COUNT(*) AS n FROM pending WHERE connection_id=?").get(e):this.database.prepare("SELECT COUNT(*) AS n FROM pending").get())?.n??0)}sourceChanged(e,t,n){return this.database.prepare("SELECT revision FROM source_scans WHERE connection_id=? AND session_key=?").get(e,t)?.revision!==n}scanned(e,t,n){this.database.prepare("INSERT INTO source_scans VALUES(?,?,?) ON CONFLICT(connection_id,session_key) DO UPDATE SET revision=excluded.revision").run(e,t,n)}changed(e,t,n,r){return this.database.prepare("SELECT revision FROM checkpoints WHERE connection_id=? AND session_key=? AND boundary_id=?").get(e,t,n)?.revision!==r}enqueue(e,t,n,r=this.snapshots.prepare(e.files)){let{files:i,...a}=e,o=JSON.stringify(a),l=Buffer.byteLength(o);this.database.exec("BEGIN IMMEDIATE");try{if(this.database.prepare("SELECT 1 FROM pending WHERE id=?").get(e.operationId)){this.database.exec("COMMIT");return}let c=this.database.prepare("SELECT COUNT(*) AS count,COALESCE(SUM(bytes),0) AS bytes FROM pending").get();if(Number(c.count)>=P.maxPending||Number(c.bytes)+this.snapshots.bytes()+l+(this.snapshots.exists(r.hash)?0:r.bytes)>P.maxBytes)throw new
|
|
54
|
-
const matches = ${
|
|
53
|
+
AND b.value=checkpoints.boundary_id)`).run(e.id);for(let r of n||t.since!==e.since?["source_scans","checkpoints","pending"]:["source_scans","pending"])this.database.prepare(`DELETE FROM ${r} WHERE connection_id=?`).run(e.id);this.snapshots.collect(),n&&(this.database.prepare("DELETE FROM admitted_boundaries WHERE connection_id=?").run(e.id),this.database.prepare("UPDATE connections SET admitted=0 WHERE id=?").run(e.id),this.database.prepare("DELETE FROM settings WHERE key=?").run(`lastAdmission:${e.id}`))}else t&&(e={...e,requestedSyncRevision:Math.max(t.requestedSyncRevision??0,e.requestedSyncRevision??0),completedSyncRevision:Math.max(t.completedSyncRevision??0,e.completedSyncRevision??0)});this.database.prepare("INSERT INTO connections(id,config) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET config=excluded.config").run(e.id,JSON.stringify(e)),this.database.exec("COMMIT")}catch(t){throw this.database.exec("ROLLBACK"),t}}error(e,t){this.database.prepare("UPDATE connections SET error=? WHERE id=?").run(t?.slice(0,500)??null,e)}queued(e){return Number((e?this.database.prepare("SELECT COUNT(*) AS n FROM pending WHERE connection_id=?").get(e):this.database.prepare("SELECT COUNT(*) AS n FROM pending").get())?.n??0)}sourceChanged(e,t,n){return this.database.prepare("SELECT revision FROM source_scans WHERE connection_id=? AND session_key=?").get(e,t)?.revision!==n}scanned(e,t,n){this.database.prepare("INSERT INTO source_scans VALUES(?,?,?) ON CONFLICT(connection_id,session_key) DO UPDATE SET revision=excluded.revision").run(e,t,n)}changed(e,t,n,r){return this.database.prepare("SELECT revision FROM checkpoints WHERE connection_id=? AND session_key=? AND boundary_id=?").get(e,t,n)?.revision!==r}enqueue(e,t,n,r=this.snapshots.prepare(e.files)){let{files:i,...a}=e,o=JSON.stringify(a),l=Buffer.byteLength(o);this.database.exec("BEGIN IMMEDIATE");try{if(this.database.prepare("SELECT 1 FROM pending WHERE id=?").get(e.operationId)){this.database.exec("COMMIT");return}let c=this.database.prepare("SELECT COUNT(*) AS count,COALESCE(SUM(bytes),0) AS bytes FROM pending").get();if(Number(c.count)>=P.maxPending||Number(c.bytes)+this.snapshots.bytes()+l+(this.snapshots.exists(r.hash)?0:r.bytes)>P.maxBytes)throw new se;this.snapshots.retain(e.operationId,r),this.database.prepare("INSERT OR IGNORE INTO pending(id,connection_id,payload,bytes,created_at) VALUES(?,?,?,?,?)").run(e.operationId,e.connectionId,o,l,Date.now());let f=this.database.prepare("INSERT INTO checkpoints VALUES(?,?,?,?) ON CONFLICT(connection_id,session_key,boundary_id) DO UPDATE SET revision=excluded.revision");for(let u of t)f.run(e.connectionId,e.sessionKey,u.id,u.revision);n&&this.progress.queued(e.operationId,e.connectionId,n),this.database.exec("COMMIT")}catch(c){throw this.database.exec("ROLLBACK"),c}}next(e){let t=this.database.prepare("SELECT id,payload,attempts FROM pending WHERE connection_id=? ORDER BY created_at,id LIMIT 1").get(e);return t?{entry:{...JSON.parse(String(t.payload)),files:this.snapshots.files(String(t.id))},attempts:Number(t.attempts)}:null}acknowledge(e){this.database.exec("BEGIN IMMEDIATE");try{let t=this.database.prepare("DELETE FROM pending WHERE id=?").run(e.operationId);if(Number(t.changes)>0){this.snapshots.collect(),this.progress.acknowledge(e.operationId),this.set(`lastAdmission:${e.connectionId}`,new Date().toISOString());let n=0,r=this.database.prepare("INSERT OR IGNORE INTO admitted_boundaries VALUES(?,?)");for(let i of e.boundaryIds)n+=Number(r.run(e.connectionId,i).changes);this.database.prepare("UPDATE connections SET admitted=admitted+? WHERE id=?").run(n,e.connectionId)}this.database.exec("COMMIT")}catch(t){throw this.database.exec("ROLLBACK"),t}}retry(e,t){let n=Math.min(6e4,1e3*2**Math.min(t,6));this.database.prepare("UPDATE pending SET attempts=?,retry_at=? WHERE id=?").run(t+1,Date.now()+n+Math.floor(Math.random()*Math.max(1,n/5)),e)}schedule(e){let t=this.setting(`schedule:${e}`);return t?he(JSON.parse(t)):null}status(){let e=this.setting("heartbeatAt"),t=Number(this.setting("pid"))||null,n=!1;try{t&&(process.kill(t,0),n=!0)}catch{}return{schemaVersion:1,running:n&&!!e&&Date.now()-Date.parse(e)<P.staleMs,desiredState:this.setting("desiredState")==="running"?"running":"stopped",pid:t,heartbeatAt:e,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,connections:this.database.prepare("SELECT id,config,admitted,error FROM connections ORDER BY id").all().map(r=>{let i=JSON.parse(String(r.config)),a=this.schedule(String(r.id)),o=this.setting(`run:${r.id}`),l=o?JSON.parse(o):null;return l?.state==="running"&&!n&&(l.state="failed",l.error="The import was interrupted before completion. Run Sync now to resume."),{id:String(r.id),state:i.state,projectId:i.projectId,teamId:i.teamId,accountBaseUrl:i.accountBaseUrl??null,sourceInstanceId:i.source.instanceId,sourceRoot:i.source.root,source:i.source.source,queued:this.queued(String(r.id)),admitted:Number(r.admitted),error:typeof r.error=="string"?r.error:null,backfill:this.progress.status(String(r.id)),pendingBytes:this.snapshots.bytes(String(r.id))+Number(this.database.prepare("SELECT COALESCE(SUM(bytes),0) AS bytes FROM pending WHERE connection_id=?").get(String(r.id))?.bytes??0),lastAdmissionAt:this.setting(`lastAdmission:${r.id}`),since:i.since,selectedConversations:i.selectedSessionKeys?.length??null,schedule:a,nextRunAt:a&&i.state==="active"?Zt(a):null,lastSuccessfulSyncAt:this.setting(`lastSuccess:${r.id}`),run:l,coverage:this.coverage.summary(String(r.id)),requestedSyncRevision:i.requestedSyncRevision??0,completedSyncRevision:i.completedSyncRevision??0,acknowledgedSyncRevision:Number(this.setting(`syncAcknowledged:${r.id}`))||0,destinationLinks:es(i)}})}}};import{randomUUID as hs}from"node:crypto";import{createHash as hn}from"node:crypto";import{constants as re}from"node:fs";import{chmod as rs,copyFile as mn,lstat as oe,mkdir as gn,mkdtemp as yn,open as rt,realpath as Fe,rename as En,rm as os}from"node:fs/promises";import{dirname as ss,isAbsolute as wn,join as ne,relative as Sn,resolve as _n,sep as bn}from"node:path";var is="appimage-runtime",vn='const p=require("node:path");const u=require("node:url");const entry=p.join(process.env.APPDIR,"resources","cli","cli.js");process.argv.splice(1,0,entry);import(u.pathToFileURL(entry).href);';async function st(s){let e=_n(s);for(let n=e;;n=ss(n)){let r=await oe(n).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(r&&(!r.isDirectory()||r.isSymbolicLink()))throw new Error("Collector runtime storage must use real directories.");if(ss(n)===n)break}await gn(e,{recursive:!0,mode:448});let t=await oe(e);if(!t.isDirectory()||t.isSymbolicLink()||t.uid!==process.getuid())throw new Error("Collector runtime storage must belong to the current user.");await rs(e,448)}p(st,"privateDirectory");async function nt(s){let e=hn("sha256"),t=await rt(s,re.O_RDONLY|re.O_NOFOLLOW);try{for await(let n of t.createReadStream({autoClose:!1}))e.update(n)}finally{await t.close()}return e.digest("hex")}p(nt,"digest");async function tt(s){let e=await rt(s,re.O_RDONLY|re.O_NOFOLLOW);try{await e.sync()}finally{await e.close()}}p(tt,"sync");async function ns(s,e){let t=await oe(s);if(!t.isFile()||t.isSymbolicLink()||t.uid!==process.getuid()||(t.mode&511)!==320||await nt(s)!==e)throw new Error("Retained AppImage runtime failed its ownership or integrity check.")}p(ns,"verify");async function as(s,e=process.env){if(process.platform!=="linux"||!e.APPIMAGE||!e.APPDIR)return null;let t=await Fe(e.APPDIR),n=await Fe(s.executable),r=Sn(t,n);if(wn(r)||r===".."||r.startsWith(`..${bn}`))return null;let i=s.args[0];if(!i||await Fe(i)!==ne(t,"resources","cli","cli.js"))throw new Error("AppImage collection requires its bundled CLI entrypoint.");let a=await Fe(e.APPIMAGE),o=await oe(a);if(!o.isFile()||o.size>1024*1024*1024)throw new Error("AppImage runtime is unavailable or exceeds the retained size limit.");let l=Buffer.alloc(11),c=await rt(a,re.O_RDONLY|re.O_NOFOLLOW);try{await c.read(l,0,l.length,0)}finally{await c.close()}if(!l.subarray(0,4).equals(Buffer.from([127,69,76,70]))||!l.subarray(8,11).equals(Buffer.from([65,73,2])))throw new Error("Collector runtime must be a type-2 AppImage.");let f=await nt(a);await st(s.directory);let u=ne(s.directory,is);await st(u);let h=ne(u,f),g=ne(h,"openpond.AppImage"),w=await oe(h).catch(y=>{if(y.code==="ENOENT")return null;throw y});if(w){if(!w.isDirectory()||w.isSymbolicLink()||w.uid!==process.getuid()||(w.mode&511)!==448)throw new Error("Retained runtime directory is not private.");await ns(g,f)}else{let y=await yn(ne(u,".stage-"));try{let m=ne(y,"openpond.AppImage");await mn(a,m,re.COPYFILE_EXCL),await rs(m,320);let d=await oe(a);if(o.dev!==d.dev||o.ino!==d.ino||o.size!==d.size||o.mtimeMs!==d.mtimeMs||await nt(m)!==f)throw new Error("AppImage changed while preparing the collector runtime; retry installation.");await tt(m),await tt(y);try{await En(y,h)}catch(E){if(!["EEXIST","ENOTEMPTY"].includes(E.code??""))throw E}await ns(g,f),await tt(u)}finally{await os(y,{recursive:!0,force:!0})}}return{executable:g,args:["-e",vn,"--",...s.args.slice(1)]}}p(as,"retainAppImageRuntime");async function cs(s){let e=ne(s,is),t=await oe(e).catch(n=>{if(n.code==="ENOENT")return null;throw n});if(t){if(await st(s),!t.isDirectory()||t.isSymbolicLink()||t.uid!==process.getuid())throw new Error("Refusing to remove unowned collector runtime storage.");await os(e,{recursive:!0})}}p(cs,"removeAppImageRuntimes");import{execFile as Tn}from"node:child_process";import{promisify as Nn}from"node:util";import{mkdir as ot,writeFile as xn,rm as Z,rename as Cn}from"node:fs/promises";import{homedir as ms}from"node:os";import{isAbsolute as us,join as q}from"node:path";function ds(s){let e=s.schedules.map(t=>fe(Me(t)).calendar);return`"use strict";
|
|
54
|
+
const matches = ${be.toString()};
|
|
55
55
|
const calendars = ${JSON.stringify(e)};
|
|
56
56
|
if (calendars.some(calendar => matches(calendar, new Date()))) {
|
|
57
57
|
const { spawn } = require("node:child_process");
|
|
@@ -61,14 +61,14 @@ if (calendars.some(calendar => matches(calendar, new Date()))) {
|
|
|
61
61
|
child.on("error", error => { console.error(error.message); process.exitCode = 1; });
|
|
62
62
|
child.on("exit", (code, signal) => { process.exitCode = code ?? (signal === "SIGINT" ? 130 : 143); });
|
|
63
63
|
}
|
|
64
|
-
`}p(
|
|
64
|
+
`}p(ds,"collectorCalendarGate");var In=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],ve=p(s=>s.replace(/&/gu,"&").replace(/</gu,"<").replace(/>/gu,">").replace(/"/gu,"""),"xml"),ls=p(s=>`"${s.replace(/\\/gu,"\\\\").replace(/"/gu,'\\"').replace(/%/gu,"%%").replace(/\$/gu,()=>"$$")}"`,"systemdQuote"),On=p(s=>`"${s.replace(/(\\*)"/gu,'$1$1\\"').replace(/(\\+)$/u,"$1$1")}"`,"windowsQuote");function ps(s){let e=[...new Map(s.schedules.map(o=>{let l=he(o);return[JSON.stringify(l),l]})).values()],t=[s.executable,s.gatePath],n=e.some(o=>o.frequency==="cron")?[{frequency:"calendar-tick"}]:e,r=p(o=>{if(o.frequency==="calendar-tick")return"*-*-* *:*:00";if(o.frequency==="hourly")return"*-*-* *:00:00";if(o.frequency==="cron")throw new Error("Cron needs the calendar gate.");return`${o.frequency==="weekly"?`${Qe[o.day]} `:""}*-*-* ${o.time}:00`},"cron"),i=p(o=>{if(o.frequency==="calendar-tick")return"<dict/>";if(o.frequency==="hourly")return"<dict><key>Minute</key><integer>0</integer></dict>";if(o.frequency==="cron")throw new Error("Cron needs the calendar gate.");let[l,c]=o.time.split(":").map(Number);return`<dict>${o.frequency==="weekly"?`<key>Weekday</key><integer>${o.day}</integer>`:""}<key>Hour</key><integer>${l}</integer><key>Minute</key><integer>${c}</integer></dict>`},"launchd"),a=p(o=>{if(o.frequency==="calendar-tick"||o.frequency==="hourly")return`<CalendarTrigger><Repetition><Interval>${o.frequency==="hourly"?"PT1H":"PT1M"}</Interval><Duration>P1D</Duration><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2020-01-01T00:00:00</StartBoundary><Enabled>true</Enabled><ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay></CalendarTrigger>`;if(o.frequency==="cron")throw new Error("Cron needs the calendar gate.");return`<CalendarTrigger><StartBoundary>2020-01-01T${o.time}:00</StartBoundary><Enabled>true</Enabled>${o.frequency==="daily"?"<ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay>":`<ScheduleByWeek><WeeksInterval>1</WeeksInterval><DaysOfWeek><${In[o.day]}/></DaysOfWeek></ScheduleByWeek>`}</CalendarTrigger>`},"windows");return{gate:ds({executable:s.executable,args:s.args,schedules:e}),service:`[Unit]
|
|
65
65
|
Description=OpenPond conversation import job
|
|
66
66
|
After=network-online.target
|
|
67
67
|
[Service]
|
|
68
68
|
Type=oneshot
|
|
69
|
-
${s.environment.map(([o,l])=>`Environment=${
|
|
69
|
+
${s.environment.map(([o,l])=>`Environment=${ls(`${o}=${l}`)}`).join(`
|
|
70
70
|
`)}
|
|
71
|
-
ExecStart=${t.map(
|
|
71
|
+
ExecStart=${t.map(ls).join(" ")}
|
|
72
72
|
TimeoutStartSec=65min
|
|
73
73
|
TimeoutStopSec=15s
|
|
74
74
|
Restart=no
|
|
@@ -87,10 +87,10 @@ WakeSystem=false
|
|
|
87
87
|
Unit=${s.name}.service
|
|
88
88
|
[Install]
|
|
89
89
|
WantedBy=timers.target
|
|
90
|
-
`,plist:`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>${s.name}</string><key>ProgramArguments</key><array>${t.map(o=>`<string>${
|
|
90
|
+
`,plist:`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>${s.name}</string><key>ProgramArguments</key><array>${t.map(o=>`<string>${ve(o)}</string>`).join("")}</array><key>EnvironmentVariables</key><dict>${s.environment.map(([o,l])=>`<key>${ve(o)}</key><string>${ve(l)}</string>`).join("")}</dict><key>StartCalendarInterval</key><array>${n.map(i).join("")}</array><key>RunAtLoad</key><false/><key>KeepAlive</key><false/><key>Nice</key><integer>10</integer></dict></plist>`,windowsTask(o,l){return`<?xml version="1.0"?><Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Triggers>${n.map(a).join("")}</Triggers><Principals><Principal id="Owner"><UserId>${ve(o)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><StartWhenAvailable>false</StartWhenAvailable><WakeToRun>false</WakeToRun><ExecutionTimeLimit>PT65M</ExecutionTimeLimit></Settings><Actions Context="Owner"><Exec><Command>powershell.exe</Command><Arguments>${ve(["-NoProfile","-NonInteractive","-File",l].map(On).join(" "))}</Arguments></Exec></Actions></Task>`},powershell:`${s.environment.map(([o,l])=>`$env:${o} = '${l.replace(/'/gu,"''")}'`).join(`
|
|
91
91
|
`)}
|
|
92
92
|
& ${t.map(o=>`'${o.replace(/'/gu,"''")}'`).join(" ")}
|
|
93
93
|
exit $LASTEXITCODE
|
|
94
|
-
`}}p(ds,"collectorServiceFiles");var hs=Tn(On),J=p(async(s,e)=>{await hs(s,e,{timeout:15e3,maxBuffer:16384,windowsHide:!0})},"command");function ms(s){return`openpond-import-${O(s).slice(0,16)}`}p(ms,"identity");async function ga(s,e){let t=await j.open(s);try{t.put(e)}finally{t.close()}}p(ga,"configureCollector");async function Ue(s){let e=await j.open(s);try{return e.status()}finally{e.close()}}p(Ue,"collectorStatus");async function Cn(s,e,t){let n=await j.open(s);try{if(e==="start"||e==="stop")n.set("desiredState",e==="start"?"running":"stopped");else if(e==="sync")n.set("syncNow","yes");else{let r=n.connections().find(i=>i.id===t);if(!r)throw new Error("Select a retained connection.");n.put({...r,state:e==="pause"?"paused":e==="resume"?"active":"disconnected"})}return n.status()}finally{n.close()}}p(Cn,"controlCollector");async function ps(s){if(process.platform==="darwin"&&(await Ue(s.directory)).running)throw new Error("Wait for the current import to finish, or cancel it, before changing its macOS schedule.");if(!ls(s.directory)||!ls(s.executable)||[s.directory,s.executable,...s.args].some(c=>/[\r\n\0]/u.test(c)))throw new Error("Collector jobs require absolute paths and single-line arguments.");let e=await os(s);e&&(s={...s,...e,environment:{...s.environment,ELECTRON_RUN_AS_NODE:"1",APPIMAGE_EXTRACT_AND_RUN:"1"}});let t=Object.entries(s.environment??{});if(t.some(([c,f])=>!["OPENPOND_HOME","ELECTRON_RUN_AS_NODE","APPIMAGE_EXTRACT_AND_RUN"].includes(c)||typeof f!="string"||/[\r\n\0]/u.test(f)))throw new Error("Unsupported service environment setting.");let n=s.home??fs(),r=ms(s.directory),i=await j.open(s.directory),a;try{a=i.connections().map(c=>i.schedule(c.id)).filter(c=>c!==null)}finally{i.close()}let o=q(s.directory,"calendar-gate.cjs"),l=ds({name:r,gatePath:o,executable:s.executable,args:[...s.args,"import","service","run","--scheduled","--collector-dir",s.directory],environment:t,schedules:a});if(await me(o,l.gate,{mode:384}),process.platform==="linux"){let c=q(n,".config/systemd/user");await rt(c,{recursive:!0,mode:448}),await Oe("systemctl",["--user","disable",`${r}.service`]),await me(q(c,`${r}.service`),l.service,{mode:384}),a.length?(await me(q(c,`${r}.timer`),l.timer,{mode:384}),await J("systemctl",["--user","daemon-reload"]),await J("systemctl",["--user","enable","--now",`${r}.timer`]),await J("systemctl",["--user","restart",`${r}.timer`])):(await Oe("systemctl",["--user","disable","--now",`${r}.timer`]),await Z(q(c,`${r}.timer`),{force:!0}),await J("systemctl",["--user","daemon-reload"]))}else if(process.platform==="darwin"){let c=q(n,"Library/LaunchAgents"),f=q(c,`${r}.plist`);await rt(c,{recursive:!0,mode:448}),await Oe("launchctl",["bootout",`gui/${process.getuid()}/${r}`]),a.length?(await me(f,l.plist,{mode:384}),await J("launchctl",["bootstrap",`gui/${process.getuid()}`,f])):await Z(f,{force:!0})}else if(process.platform==="win32")if(!a.length)await Oe("schtasks",["/Delete","/TN",r,"/F"]);else{let c=(await hs("whoami",[],{timeout:5e3,maxBuffer:1024})).stdout.trim(),f=q(s.directory,"scheduled-task.xml"),u=q(s.directory,"start-collector.ps1");await rt(s.directory,{recursive:!0,mode:448}),await me(u,l.powershell,{mode:384}),await me(f,l.windowsTask(c,u),{mode:384}),await J("schtasks",["/Create","/TN",r,"/XML",f,"/F"])}else throw new Error("Scheduled imports need a supported OS scheduler. Use import sync manually on this OS.");return{name:r,platform:process.platform,status:await Ue(s.directory)}}p(ps,"installCollectorService");async function Oe(s,e){try{await J(s,e)}catch(t){let n=t;if(n.code==="ENOENT"||!/not (?:loaded|found|exist)|does not exist|No such|could not be found|cannot find|not been loaded/iu.test(n.stderr??n.message))throw t}}p(Oe,"optionalCommand");async function ya(s,e,t){if(t!==null&&(t=he(t)),process.platform==="darwin"&&(await Ue(s.directory)).running)throw new Error("Wait for the current import to finish, or cancel it, before changing its macOS schedule.");let n=await j.open(s.directory),r=us(),i;n.database.exec("BEGIN IMMEDIATE");try{let a=n.connections().find(l=>l.id===e);if(!a||t&&a.state==="disconnected")throw new Error("Select a connected source before scheduling imports.");if(t&&a.selectedSessionKeys?.length===0)throw new Error("Choose conversations to upload before enabling continual imports.");let o=n.setting("scheduleOwner");if(o){let{pid:l}=JSON.parse(o),c=!0;try{process.kill(l,0)}catch(f){c=f.code!=="ESRCH"}if(c)throw new Error("Another schedule update is in progress. Try again shortly.")}i=n.setting(`schedule:${e}`),n.set("scheduleOwner",JSON.stringify({pid:process.pid,token:r})),n.set(`schedule:${e}`,t?JSON.stringify(t):""),n.database.exec("COMMIT")}catch(a){throw n.database.exec("ROLLBACK"),n.close(),a}try{return await ps(s),n.status()}catch(a){n.set(`schedule:${e}`,i??"");try{await ps(s)}catch{throw new Error(`Schedule installation failed and OS rollback could not be verified. Review the OS scheduler. ${a instanceof Error?a.message:""}`)}throw a}finally{n.set("scheduleOwner",""),n.close()}}p(ya,"setCollectorSchedule");async function Ea(s,e=fs()){await Cn(s,"stop");let t=ms(s);if(process.platform==="linux")await Oe("systemctl",["--user","disable","--now",`${t}.timer`]),await Z(q(e,".config/systemd/user",`${t}.timer`),{force:!0}),await J("systemctl",["--user","disable","--now",`${t}.service`]),await Z(q(e,".config/systemd/user",`${t}.service`),{force:!0}),await J("systemctl",["--user","daemon-reload"]);else if(process.platform==="darwin")await J("launchctl",["bootout",`gui/${process.getuid()}/${t}`]),await Z(q(e,"Library/LaunchAgents",`${t}.plist`),{force:!0});else if(process.platform==="win32")await J("schtasks",["/End","/TN",t]),await J("schtasks",["/Delete","/TN",t,"/F"]),await Z(q(s,"scheduled-task.xml"),{force:!0}),await Z(q(s,"start-collector.ps1"),{force:!0});else throw new Error("No per-user supervisor is available.");await Z(q(s,"calendar-gate.cjs"),{force:!0}),process.platform==="linux"&&await is(s);let n=await j.open(s);try{for(let r of n.connections())n.set(`schedule:${r.id}`,"")}finally{n.close()}return Ue(s)}p(Ea,"uninstallCollectorService");async function me(s,e,t){let n=`${s}.${us()}.tmp`;try{await Nn(n,e,{...t,flag:"wx"}),await xn(n,s)}finally{await Z(n,{force:!0})}}p(me,"atomicServiceFile");import{homedir as Rn}from"node:os";import{join as ys,resolve as gs}from"node:path";import{randomUUID as An}from"node:crypto";import{mkdir as Ln,open as kn,readFile as Dn}from"node:fs/promises";function Mn(s=ys(Rn(),".openpond")){return process.env.OPENPOND_COLLECTOR_DIR?gs(process.env.OPENPOND_COLLECTOR_DIR):gs(s,"conversation-importer")}p(Mn,"collectorDirectory");async function Oa(s=Mn()){await Ln(s,{recursive:!0,mode:448});let e=ys(s,"machine-id");try{let n=await kn(e,"wx",384);try{await n.writeFile(An()),await n.sync()}finally{await n.close()}}catch(n){if(n.code!=="EEXIST")throw n}let t=(await Dn(e,"utf8")).trim();if(!/^[a-f0-9-]{36}$/u.test(t))throw new Error("Collector machine identity is invalid; restore its retained state.");return t}p(Oa,"collectorMachineId");import{execFile as Hn}from"node:child_process";import{realpath as Fn}from"node:fs/promises";import{isAbsolute as Un}from"node:path";import{promisify as qn}from"node:util";import{createHash as Es}from"node:crypto";function ot(s,e){let t=Buffer.from(s,"base64");if(t.toString("base64")!==s||t.byteLength>e)throw new Error("connected_git_object_bytes_invalid");return t}p(ot,"bytes");function it(s,e,t){return Es(t===40?"sha1":"sha256").update(`${s} ${e.byteLength}\0`).update(e).digest("hex")}p(it,"objectHash");function $n(s,e,t){let n=0,r=new Set,i=null,a=new TextDecoder("utf-8",{fatal:!0});for(;n<s.byteLength;){let o=s.indexOf(32,n),l=s.indexOf(0,o+1),c=l+1+t/2;if(o<n||l<o||c>s.byteLength)throw new Error("connected_git_tree_invalid");let f=s.subarray(n,o).toString("ascii"),u=a.decode(s.subarray(o+1,l));if(!u||u.includes("/")||r.has(u))throw new Error("connected_git_tree_invalid");r.add(u),u===e&&(i={mode:f,hash:s.subarray(l+1,c).toString("hex")}),n=c}if(!i)throw new Error("connected_git_path_missing");return i}p($n,"treeEntry");function ws(s,e){let t=Te.parse(s),n=we.parse(e),r=t.commitHash.length,i=ot(n.commit.base64,256*1024);if(n.commit.hash!==t.commitHash||it("commit",i,r)!==t.commitHash)throw new Error("connected_git_commit_mismatch");let a=i.indexOf(10);if(a<0)throw new Error("connected_git_commit_invalid");let o=i.subarray(0,a).toString("ascii");if(!new RegExp(`^tree [a-f0-9]{${r}}$`).test(o))throw new Error("connected_git_commit_invalid");let l=new Map,c=i.byteLength;for(let y of n.trees){let m=ot(y.base64,2097152);if(c+=m.byteLength,c>8*1024*1024||l.has(y.hash)||y.hash.length!==r||it("tree",m,r)!==y.hash)throw new Error("connected_git_tree_mismatch");l.set(y.hash,m)}let f=n.path.split("/"),u=new Set,h=o.slice(5),g="";for(let[y,m]of f.entries()){let d=l.get(h);if(!d||u.has(h))throw new Error("connected_git_tree_missing");u.add(h);let E=$n(d,m,r);if(g=E.mode,y<f.length-1?g!=="40000":!["100644","100755"].includes(g))throw new Error("connected_git_file_mode_invalid");h=E.hash}if(u.size!==l.size)throw new Error("connected_git_unreferenced_tree");let w=ot(n.contentsBase64,2*1024*1024);if(it("blob",w,r)!==h)throw new Error("connected_git_blob_mismatch");return{path:n.path,commitHash:t.commitHash,gitObjectHash:h,mode:g,sizeBytes:w.byteLength,sha256:Es("sha256").update(w).digest("hex"),contentsBase64:w.toString("base64")}}p(ws,"verifyConnectedGitFileProof");var Bn=qn(Hn);async function Pn(s){let e=Te.parse(s.repositoryContext);if(!Un(s.repositoryPath)||!s.paths.length||s.paths.length>100||new Set(s.paths).size!==s.paths.length)throw new Error("native_git_asset_selection_invalid");for(let c of s.paths)we.shape.path.parse(c);let t=await Fn(s.repositoryPath),n=p(async(c,f=2*1024*1024)=>(s.signal?.throwIfAborted(),(await Bn("git",["-C",t,...c],{encoding:"buffer",timeout:15e3,maxBuffer:f,signal:s.signal})).stdout),"read"),r=p(async c=>{let f=(await n(["rev-parse","--verify",c],1024)).toString("ascii").trim();if(!new RegExp(`^[a-f0-9]{${e.commitHash.length}}$`).test(f))throw new Error("native_git_object_identity_invalid");return f},"objectId"),i=await n(["cat-file","commit",e.commitHash],256*1024),a=new Map,o=0,l=[];for(let c of s.paths){let f=["",...c.split("/").slice(0,-1).map((y,m,d)=>d.slice(0,m+1).join("/"))],u=[];for(let y of f){let m=y?`${e.commitHash}:${y}`:`${e.commitHash}^{tree}`,d=a.get(m);if(!d){let E=await r(m);d={hash:E,base64:(await n(["cat-file","tree",E])).toString("base64")},a.set(m,d)}u.push(d)}let h=await r(`${e.commitHash}:${c}`),g=we.parse({schemaVersion:"openpond.connectedGitFileProof.v1",path:c,commit:{hash:e.commitHash,base64:i.toString("base64")},trees:u,contentsBase64:(await n(["cat-file","blob",h])).toString("base64")}),w=ws(e,g);if(o+=Buffer.byteLength(JSON.stringify(g)),o>16*1024*1024)throw new Error("native_git_asset_capture_limit");l.push({proof:g,verified:w})}return l}p(Pn,"captureNativeGitAssetProofs");import{randomUUID as zn}from"node:crypto";import{setTimeout as Jn}from"node:timers/promises";var ge=class{static{p(this,"CollectorSourceCache")}store;constructor(e){this.store=e,e.database.exec(`CREATE TABLE IF NOT EXISTS source_read_cache(
|
|
94
|
+
`}}p(ps,"collectorServiceFiles");var gs=Nn(Tn),J=p(async(s,e)=>{await gs(s,e,{timeout:15e3,maxBuffer:16384,windowsHide:!0})},"command");function ys(s){return`openpond-import-${O(s).slice(0,16)}`}p(ys,"identity");async function ya(s,e){let t=await j.open(s);try{t.put(e)}finally{t.close()}}p(ya,"configureCollector");async function Ue(s){let e=await j.open(s);try{return e.status()}finally{e.close()}}p(Ue,"collectorStatus");async function Rn(s,e,t){let n=await j.open(s);try{if(e==="start"||e==="stop")n.set("desiredState",e==="start"?"running":"stopped");else if(e==="sync")n.set("syncNow","yes");else{let r=n.connections().find(i=>i.id===t);if(!r)throw new Error("Select a retained connection.");n.put({...r,state:e==="pause"?"paused":e==="resume"?"active":"disconnected"})}return n.status()}finally{n.close()}}p(Rn,"controlCollector");async function fs(s){if(process.platform==="darwin"&&(await Ue(s.directory)).running)throw new Error("Wait for the current import to finish, or cancel it, before changing its macOS schedule.");if(!us(s.directory)||!us(s.executable)||[s.directory,s.executable,...s.args].some(c=>/[\r\n\0]/u.test(c)))throw new Error("Collector jobs require absolute paths and single-line arguments.");let e=await as(s);e&&(s={...s,...e,environment:{...s.environment,ELECTRON_RUN_AS_NODE:"1",APPIMAGE_EXTRACT_AND_RUN:"1"}});let t=Object.entries(s.environment??{});if(t.some(([c,f])=>!["OPENPOND_HOME","ELECTRON_RUN_AS_NODE","APPIMAGE_EXTRACT_AND_RUN"].includes(c)||typeof f!="string"||/[\r\n\0]/u.test(f)))throw new Error("Unsupported service environment setting.");let n=s.home??ms(),r=ys(s.directory),i=await j.open(s.directory),a;try{a=i.connections().map(c=>i.schedule(c.id)).filter(c=>c!==null)}finally{i.close()}let o=q(s.directory,"calendar-gate.cjs"),l=ps({name:r,gatePath:o,executable:s.executable,args:[...s.args,"import","service","run","--scheduled","--collector-dir",s.directory],environment:t,schedules:a});if(await me(o,l.gate,{mode:384}),process.platform==="linux"){let c=q(n,".config/systemd/user");await ot(c,{recursive:!0,mode:448}),await Ie("systemctl",["--user","disable",`${r}.service`]),await me(q(c,`${r}.service`),l.service,{mode:384}),a.length?(await me(q(c,`${r}.timer`),l.timer,{mode:384}),await J("systemctl",["--user","daemon-reload"]),await J("systemctl",["--user","enable","--now",`${r}.timer`]),await J("systemctl",["--user","restart",`${r}.timer`])):(await Ie("systemctl",["--user","disable","--now",`${r}.timer`]),await Z(q(c,`${r}.timer`),{force:!0}),await J("systemctl",["--user","daemon-reload"]))}else if(process.platform==="darwin"){let c=q(n,"Library/LaunchAgents"),f=q(c,`${r}.plist`);await ot(c,{recursive:!0,mode:448}),await Ie("launchctl",["bootout",`gui/${process.getuid()}/${r}`]),a.length?(await me(f,l.plist,{mode:384}),await J("launchctl",["bootstrap",`gui/${process.getuid()}`,f])):await Z(f,{force:!0})}else if(process.platform==="win32")if(!a.length)await Ie("schtasks",["/Delete","/TN",r,"/F"]);else{let c=(await gs("whoami",[],{timeout:5e3,maxBuffer:1024})).stdout.trim(),f=q(s.directory,"scheduled-task.xml"),u=q(s.directory,"start-collector.ps1");await ot(s.directory,{recursive:!0,mode:448}),await me(u,l.powershell,{mode:384}),await me(f,l.windowsTask(c,u),{mode:384}),await J("schtasks",["/Create","/TN",r,"/XML",f,"/F"])}else throw new Error("Scheduled imports need a supported OS scheduler. Use import sync manually on this OS.");return{name:r,platform:process.platform,status:await Ue(s.directory)}}p(fs,"installCollectorService");async function Ie(s,e){try{await J(s,e)}catch(t){let n=t;if(n.code==="ENOENT"||!/not (?:loaded|found|exist)|does not exist|No such|could not be found|cannot find|not been loaded/iu.test(n.stderr??n.message))throw t}}p(Ie,"optionalCommand");async function Ea(s,e,t){if(t!==null&&(t=he(t)),process.platform==="darwin"&&(await Ue(s.directory)).running)throw new Error("Wait for the current import to finish, or cancel it, before changing its macOS schedule.");let n=await j.open(s.directory),r=hs(),i;n.database.exec("BEGIN IMMEDIATE");try{let a=n.connections().find(l=>l.id===e);if(!a||t&&a.state==="disconnected")throw new Error("Select a connected source before scheduling imports.");if(t&&a.selectedSessionKeys?.length===0)throw new Error("Choose conversations to upload before enabling continual imports.");let o=n.setting("scheduleOwner");if(o){let{pid:l}=JSON.parse(o),c=!0;try{process.kill(l,0)}catch(f){c=f.code!=="ESRCH"}if(c)throw new Error("Another schedule update is in progress. Try again shortly.")}i=n.setting(`schedule:${e}`),n.set("scheduleOwner",JSON.stringify({pid:process.pid,token:r})),n.set(`schedule:${e}`,t?JSON.stringify(t):""),n.database.exec("COMMIT")}catch(a){throw n.database.exec("ROLLBACK"),n.close(),a}try{return await fs(s),n.status()}catch(a){n.set(`schedule:${e}`,i??"");try{await fs(s)}catch{throw new Error(`Schedule installation failed and OS rollback could not be verified. Review the OS scheduler. ${a instanceof Error?a.message:""}`)}throw a}finally{n.set("scheduleOwner",""),n.close()}}p(Ea,"setCollectorSchedule");async function wa(s,e=ms()){await Rn(s,"stop");let t=ys(s);if(process.platform==="linux")await Ie("systemctl",["--user","disable","--now",`${t}.timer`]),await Z(q(e,".config/systemd/user",`${t}.timer`),{force:!0}),await J("systemctl",["--user","disable","--now",`${t}.service`]),await Z(q(e,".config/systemd/user",`${t}.service`),{force:!0}),await J("systemctl",["--user","daemon-reload"]);else if(process.platform==="darwin")await J("launchctl",["bootout",`gui/${process.getuid()}/${t}`]),await Z(q(e,"Library/LaunchAgents",`${t}.plist`),{force:!0});else if(process.platform==="win32")await J("schtasks",["/End","/TN",t]),await J("schtasks",["/Delete","/TN",t,"/F"]),await Z(q(s,"scheduled-task.xml"),{force:!0}),await Z(q(s,"start-collector.ps1"),{force:!0});else throw new Error("No per-user supervisor is available.");await Z(q(s,"calendar-gate.cjs"),{force:!0}),process.platform==="linux"&&await cs(s);let n=await j.open(s);try{for(let r of n.connections())n.set(`schedule:${r.id}`,"")}finally{n.close()}return Ue(s)}p(wa,"uninstallCollectorService");async function me(s,e,t){let n=`${s}.${hs()}.tmp`;try{await xn(n,e,{...t,flag:"wx"}),await Cn(n,s)}finally{await Z(n,{force:!0})}}p(me,"atomicServiceFile");import{homedir as An}from"node:os";import{join as ws,resolve as Es}from"node:path";import{randomUUID as Ln}from"node:crypto";import{mkdir as kn,open as Dn,readFile as Mn}from"node:fs/promises";function $n(s=ws(An(),".openpond")){return process.env.OPENPOND_COLLECTOR_DIR?Es(process.env.OPENPOND_COLLECTOR_DIR):Es(s,"conversation-importer")}p($n,"collectorDirectory");async function Ta(s=$n()){await kn(s,{recursive:!0,mode:448});let e=ws(s,"machine-id");try{let n=await Dn(e,"wx",384);try{await n.writeFile(Ln()),await n.sync()}finally{await n.close()}}catch(n){if(n.code!=="EEXIST")throw n}let t=(await Mn(e,"utf8")).trim();if(!/^[a-f0-9-]{36}$/u.test(t))throw new Error("Collector machine identity is invalid; restore its retained state.");return t}p(Ta,"collectorMachineId");import{execFile as Fn}from"node:child_process";import{realpath as Un}from"node:fs/promises";import{isAbsolute as qn}from"node:path";import{promisify as Bn}from"node:util";import{createHash as Ss}from"node:crypto";function it(s,e){let t=Buffer.from(s,"base64");if(t.toString("base64")!==s||t.byteLength>e)throw new Error("connected_git_object_bytes_invalid");return t}p(it,"bytes");function at(s,e,t){return Ss(t===40?"sha1":"sha256").update(`${s} ${e.byteLength}\0`).update(e).digest("hex")}p(at,"objectHash");function Hn(s,e,t){let n=0,r=new Set,i=null,a=new TextDecoder("utf-8",{fatal:!0});for(;n<s.byteLength;){let o=s.indexOf(32,n),l=s.indexOf(0,o+1),c=l+1+t/2;if(o<n||l<o||c>s.byteLength)throw new Error("connected_git_tree_invalid");let f=s.subarray(n,o).toString("ascii"),u=a.decode(s.subarray(o+1,l));if(!u||u.includes("/")||r.has(u))throw new Error("connected_git_tree_invalid");r.add(u),u===e&&(i={mode:f,hash:s.subarray(l+1,c).toString("hex")}),n=c}if(!i)throw new Error("connected_git_path_missing");return i}p(Hn,"treeEntry");function _s(s,e){let t=Oe.parse(s),n=we.parse(e),r=t.commitHash.length,i=it(n.commit.base64,256*1024);if(n.commit.hash!==t.commitHash||at("commit",i,r)!==t.commitHash)throw new Error("connected_git_commit_mismatch");let a=i.indexOf(10);if(a<0)throw new Error("connected_git_commit_invalid");let o=i.subarray(0,a).toString("ascii");if(!new RegExp(`^tree [a-f0-9]{${r}}$`).test(o))throw new Error("connected_git_commit_invalid");let l=new Map,c=i.byteLength;for(let y of n.trees){let m=it(y.base64,2097152);if(c+=m.byteLength,c>8*1024*1024||l.has(y.hash)||y.hash.length!==r||at("tree",m,r)!==y.hash)throw new Error("connected_git_tree_mismatch");l.set(y.hash,m)}let f=n.path.split("/"),u=new Set,h=o.slice(5),g="";for(let[y,m]of f.entries()){let d=l.get(h);if(!d||u.has(h))throw new Error("connected_git_tree_missing");u.add(h);let E=Hn(d,m,r);if(g=E.mode,y<f.length-1?g!=="40000":!["100644","100755"].includes(g))throw new Error("connected_git_file_mode_invalid");h=E.hash}if(u.size!==l.size)throw new Error("connected_git_unreferenced_tree");let w=it(n.contentsBase64,2*1024*1024);if(at("blob",w,r)!==h)throw new Error("connected_git_blob_mismatch");return{path:n.path,commitHash:t.commitHash,gitObjectHash:h,mode:g,sizeBytes:w.byteLength,sha256:Ss("sha256").update(w).digest("hex"),contentsBase64:w.toString("base64")}}p(_s,"verifyConnectedGitFileProof");var Pn=Bn(Fn);async function jn(s){let e=Oe.parse(s.repositoryContext);if(!qn(s.repositoryPath)||!s.paths.length||s.paths.length>100||new Set(s.paths).size!==s.paths.length)throw new Error("native_git_asset_selection_invalid");for(let c of s.paths)we.shape.path.parse(c);let t=await Un(s.repositoryPath),n=p(async(c,f=2*1024*1024)=>(s.signal?.throwIfAborted(),(await Pn("git",["-C",t,...c],{encoding:"buffer",timeout:15e3,maxBuffer:f,signal:s.signal})).stdout),"read"),r=p(async c=>{let f=(await n(["rev-parse","--verify",c],1024)).toString("ascii").trim();if(!new RegExp(`^[a-f0-9]{${e.commitHash.length}}$`).test(f))throw new Error("native_git_object_identity_invalid");return f},"objectId"),i=await n(["cat-file","commit",e.commitHash],256*1024),a=new Map,o=0,l=[];for(let c of s.paths){let f=["",...c.split("/").slice(0,-1).map((y,m,d)=>d.slice(0,m+1).join("/"))],u=[];for(let y of f){let m=y?`${e.commitHash}:${y}`:`${e.commitHash}^{tree}`,d=a.get(m);if(!d){let E=await r(m);d={hash:E,base64:(await n(["cat-file","tree",E])).toString("base64")},a.set(m,d)}u.push(d)}let h=await r(`${e.commitHash}:${c}`),g=we.parse({schemaVersion:"openpond.connectedGitFileProof.v1",path:c,commit:{hash:e.commitHash,base64:i.toString("base64")},trees:u,contentsBase64:(await n(["cat-file","blob",h])).toString("base64")}),w=_s(e,g);if(o+=Buffer.byteLength(JSON.stringify(g)),o>16*1024*1024)throw new Error("native_git_asset_capture_limit");l.push({proof:g,verified:w})}return l}p(jn,"captureNativeGitAssetProofs");import{randomUUID as Jn}from"node:crypto";import{setTimeout as Gn}from"node:timers/promises";var ge=class{static{p(this,"CollectorSourceCache")}store;constructor(e){this.store=e,e.database.exec(`CREATE TABLE IF NOT EXISTS source_read_cache(
|
|
95
95
|
connection_id TEXT NOT NULL,session_key TEXT NOT NULL,selection_hash TEXT NOT NULL,value TEXT NOT NULL,
|
|
96
|
-
PRIMARY KEY(connection_id,session_key));`)}selection(e,t,n){return O([e.source,e.projectId,e.teamId,e.apiBaseUrl,e.account??null,e.since,e.selectedSessionKeys??null,t,n])}read(e,t,n,r){let i=this.store.database.prepare("SELECT value FROM source_read_cache WHERE connection_id=? AND session_key=? AND selection_hash=?").get(e.id,n,this.selection(e,t,r));return i?ae.parse(JSON.parse(String(i.value))):null}retain(e,t,n,r,i){let a=ae.parse(i);a.nativeRevisionHash===null||a.state!=="admitted"&&!(a.state==="skipped"&&a.reason==="no_eligible_boundaries")||this.store.database.prepare("INSERT INTO source_read_cache VALUES(?,?,?,?) ON CONFLICT(connection_id,session_key) DO UPDATE SET selection_hash=excluded.selection_hash,value=excluded.value").run(e.id,n,this.selection(e,t,r),JSON.stringify(a))}seed(e,t,n){if(!n||n.connectionRevision!==e.revision||n.from!==e.since||n.to!==t||n.sourceInstanceId!==e.source.instanceId||n.machineId!==e.source.machineId)return;let r=new Map(n.sessions.map(i=>[i.sourceKeyHash,i]));for(let i of this.store.database.prepare("SELECT session_key,revision FROM source_scans WHERE connection_id=?").all(e.id)){let a=String(i.session_key),o=r.get(O(a));o&&this.retain(e,t,a,String(i.revision),o)}}};var jn=["source","admission","control","heartbeat"],ye=class{static{p(this,"CollectorErrors")}store;constructor(e){this.store=e}read(e){let t=this.store.setting(`errors:${e}`);if(t)return JSON.parse(t);let n=this.store.database.prepare("SELECT error FROM backfill_units WHERE connection_id=? AND state='error' AND error IS NOT NULL ORDER BY session_key LIMIT 1").get(e);return typeof n?.error=="string"?{source:n.error}:{}}message(e,t){let n=this.read(e);return jn.filter(r=>r!==t).map(r=>n[r]).find(Boolean)??null}source(e){return this.read(e).source??null}set(e,t,n){let r=this.read(e);n?r[t]=n.slice(0,500):delete r[t],this.store.set(`errors:${e}`,JSON.stringify(r)),this.store.error(e,this.message(e))}};var qe=class{static{p(this,"CollectorSyncRequests")}store;acquisitions=new Map;constructor(e){this.store=e}observe(e,t){let n=t.requestedSyncRevision??e.requestedSyncRevision??0,r=t.completedSyncRevision??0;if(!Number.isSafeInteger(n)||n<0||n>t.revision||!Number.isSafeInteger(r)||r<0||r>n)throw new Error("Invalid remote sync acknowledgement.");let i=this.confirmed(e.id);return r>i&&this.store.set(`syncAcknowledged:${e.id}`,String(r)),{requestedSyncRevision:Math.max(e.requestedSyncRevision??0,n),completedSyncRevision:Math.max(e.completedSyncRevision??0,r)}}needsAcquisition(e){let t=e.requestedSyncRevision??0;if(t<=(e.completedSyncRevision??0))return!1;let n=this.acquisitions.get(e.id);return n?.controlRevision!==e.revision||n.requestedSyncRevision!==t}acquired(e,t){this.acquisitions.set(e,t)}complete(e,t){let n=this.acquisitions.get(e.id),r=e.requestedSyncRevision??0;if(e.state!=="active"||this.store.setting("desiredState")!=="running"||this.store.queued(e.id)||t||!n?.succeeded||n.controlRevision!==e.revision||n.requestedSyncRevision!==r||r<=(e.completedSyncRevision??0))return e;let i={...e,completedSyncRevision:r};return this.store.put(i),i}confirmed(e){return Number(this.store.setting(`syncAcknowledged:${e}`))||0}needsAcknowledgement(e){return(e.completedSyncRevision??0)>this.confirmed(e.id)}};var Wn=Y.object({leafId:Y.string().min(1).max(200),chainHash:Y.string().regex(/^[a-f0-9]{64}$/),sourceInstanceId:Y.string().min(1)}).strict(),Ss=p((s,e)=>`branch:${JSON.stringify([s,e])}`,"key");function _s(s,e,t){let n=s.setting(Ss(e,t));if(!n)return;let r=Wn.parse(JSON.parse(n));return s.connections().find(a=>a.id===e)?.source.instanceId===r.sourceInstanceId?{leafId:r.leafId,chainHash:r.chainHash}:void 0}p(_s,"collectorBranchAnchor");async function bs(s,e){if(s.source!=="claude_code")throw new Error("Branch selection is currently supported for Claude Code.");let t,n=[];do{let r=await pe(s,{cursor:t,limit:100});n.push(...r.items.filter(i=>i.nativeSessionId===e)),t=r.nextCursor??void 0}while(t);if(n.length!==1)throw new Error("Select exactly one native session in this connection's source location.");return n[0]}p(bs,"findSession");async function ec(s,e,t){let n=await j.open(s);try{let r=n.connections().find(a=>a.id===e);if(!r)throw new Error("Select a connection from openpond import status.");let i=await bs(r.source,t);return{session:i,...await Ve(r.source,i)}}finally{n.close()}}p(ec,"inspectCollectorBranches");async function tc(s,e,t,n){let r=await j.open(s);try{let i=r.connections().find(c=>c.id===e);if(!i||i.state!=="paused")throw new Error(`Pause this connection first: openpond import pause ${e}`);let a=await bs(i.source,t),o=await Ve(i.source,a),l=o.branches.find(c=>c.leafId===n.leafId);if(o.revision!==n.revision||!l)throw new Error("This conversation changed. Refresh its branches and choose again.");await De(i.source,a,{branchLeafId:n.leafId,expectedBranchRevision:n.revision}),r.database.exec("BEGIN IMMEDIATE");try{let c=r.connections().find(u=>u.id===e);if(!c||c.state!=="paused"||c.revision!==i.revision||c.source.instanceId!==i.source.instanceId)throw new Error("Connection changed during branch selection. Refresh and try again.");r.set(Ss(e,t),JSON.stringify({leafId:l.leafId,chainHash:l.chainHash,sourceInstanceId:i.source.instanceId}));for(let u of["source_scans","checkpoints","pending"])r.database.prepare(`DELETE FROM ${u} WHERE connection_id=?`).run(e);r.snapshots.collect();let f=new ye(r);f.set(e,"source",f.source(e)),r.progress.reset(e),f.set(e,"admission",null),r.database.exec("COMMIT")}catch(c){throw r.database.exec("ROLLBACK"),c}return{connectionId:e,nativeSessionId:t,leafId:l.leafId,state:"paused"}}finally{r.close()}}p(tc,"selectCollectorBranch");async function vs(s){let{store:e,connection:t,check:n,drain:r,progress:i,until:a}=s,o=new ge(e),l,c=0,f=0,u=[],h=t.selectedSessionKeys?new Set(t.selectedSessionKeys):null,g=new Set,w=0;do{await n(),i({phase:"discovering"});let y=await pe(t.source,{cursor:l,limit:50});if(w+=y.items.length,w>1e4)throw new Error("Source inventory exceeds 10,000 sessions. Select a narrower source directory.");let m=y.items.filter(d=>!h||h.has(ue(d)));for(let d of m)g.add(ue(d));f+=m.length;for(let d of m){let E=JSON.stringify([d.path,d.nativeSessionId]);e.coverage.record(t.id,{sourceKeyHash:ee.sourceKey(E),nativeRevisionHash:d.storageRevision?O([d.storageRevision,Re(t.source.source)]):null,state:"reading",reason:null,unknownTimeBoundaries:0,normalized:[]})}i({discovered:f});for(let d of m){if(await n(),await r(),Number(e.database.prepare("SELECT COALESCE(SUM(bytes),0) AS n FROM pending").get()?.n)+e.snapshots.bytes()>=P.maxBytes)throw new te;i({phase:"reading"});let S=JSON.stringify([d.path,d.nativeSessionId]),b=d.storageRevision?O([d.storageRevision,Re(t.source.source)]):null;e.progress.select(t.id,S);let N=b?o.read(t,a,S,b):null;if(N){e.coverage.record(t.id,N),e.progress.read(t.id,S,N.state==="admitted"),i({processed:++c});continue}let v={sourceKeyHash:ee.sourceKey(S),nativeRevisionHash:b,state:"reading",reason:b?null:"source_revision_unavailable",unknownTimeBoundaries:0,normalized:[]};try{let L=await Xt(t.source,d,{since:t.since,until:a,check:n});if(L){v.nativeRevisionHash=O(["codex-window-inventory-v1",L.sha256]),v.state="skipped",v.reason="no_eligible_boundaries",e.coverage.record(t.id,v),e.progress.read(t.id,S,!1),b&&(e.scanned(t.id,S,b),o.retain(t,a,S,b,v));continue}let{files:A,preview:x,branchLeafId:C}=await De(t.source,d,{branchAnchor:_s(e,t.id,d.nativeSessionId)});v.nativeRevisionHash=O([A,Re(t.source.source)]),await n();let R=e.snapshots.prepare(A),B=!1;for(let H of x.sessions){let W=JSON.stringify([t.source.instanceId,H.sessionId,H.branchId]);e.progress.retained(t.id,S,W);let ie=H.boundaries.filter(M=>{if(M.projection!=="turn"||M.terminal==="unknown")return!1;let G=H.events[M.start]?.occurredAt;return!G||!Number.isFinite(Date.parse(G))?(v.unknownTimeBoundaries++,!1):Date.parse(G)<Date.parse(a)&&(!t.since||Date.parse(G)>=Date.parse(t.since))});v.normalized.push({sessionHash:H.contentHash,boundaries:ie.map(M=>({id:M.id,inputHash:M.inputHash,revisionHash:M.revisionHash,occurredAt:H.events[M.start].occurredAt})).sort((M,G)=>M.id<G.id?-1:M.id>G.id?1:0)}),e.coverage.record(t.id,v),B||=ie.length>0;let at=ie.filter(M=>e.changed(t.id,W,M.id,O([M.inputHash,M.revisionHash])));for(let M=0;M<at.length;M+=P.batchCases){await n();let G=at.slice(M,M+P.batchCases),Is=`sync-${O([t.id,W,G.map(V=>[V.id,V.inputHash,V.revisionHash])]).slice(0,48)}`;e.enqueue({operationId:Is,connectionId:t.id,sessionKey:W,contentHash:H.contentHash,files:A,boundaryIds:G.map(V=>V.id),...C?{branchLeafId:C}:{}},G.map(V=>({id:V.id,revision:O([V.inputHash,V.revisionHash])})),S,R)}}e.progress.read(t.id,S,B),b&&e.scanned(t.id,S,b),await r(),v.state=B?"admitted":"skipped",v.reason=B?null:"no_eligible_boundaries",v.normalized.sort((H,W)=>H.sessionHash<W.sessionHash?-1:H.sessionHash>W.sessionHash?1:0),e.coverage.record(t.id,v),b&&o.retain(t,a,S,b,v)}catch(L){if(L instanceof de){v.state="skipped",v.reason="native_session_not_ready",e.coverage.record(t.id,v),e.progress.read(t.id,S,!1),b&&e.scanned(t.id,S,b);continue}if(L instanceof te||L instanceof K||L instanceof oe)throw L;let A=L instanceof Error?L.message:"Unable to read session";v.state="failed",v.reason="source_read_failed",e.coverage.record(t.id,v),e.progress.failed(t.id,S,A),u.push(`${d.nativeSessionId}: ${A}`)}finally{i({processed:++c})}await r()}l=y.nextCursor??void 0}while(l);if(e.progress.discovered(t.id),e.coverage.finish(t.id,h===null),h&&[...h].some(y=>!g.has(y)))throw new Error("A selected conversation is no longer available. Review the upload selection.");if(u.length)throw new Error(`${u.length} session(s) need attention. ${u[0]}`)}p(vs,"acquireCollectorSource");var K=class extends Error{static{p(this,"CollectorInterruptedError")}},oe=class extends Error{static{p(this,"CollectorScopeChangedError")}};async function Oc(s){let e=s.until??new Date().toISOString();if(!Number.isFinite(Date.parse(e))||Date.parse(e)>Date.now())throw new Error("--until must be a valid timestamp no later than now.");let t=await j.open(s.directory),n=zn(),r=[];t.database.exec("BEGIN IMMEDIATE");try{let d=t.setting("owner");if(d){let S=JSON.parse(d),b=!0;try{process.kill(S.pid,0)}catch(N){b=N.code!=="ESRCH"}if(b){if(s.trigger==="scheduled"){t.database.exec("COMMIT"),t.close();return}throw new Error("An import is already running. Cancel it or wait for it to finish.")}}let E=new Date;if(r=t.connections().filter(S=>S.state!=="disconnected"&&S.selectedSessionKeys?.length!==0&&(!s.connectionIds||s.connectionIds.includes(S.id))&&(s.trigger!=="scheduled"||S.state==="active"&&Vt(t.schedule(S.id),t.setting(`scheduledMinute:${S.id}`),E))),s.trigger==="scheduled")for(let S of r)t.set(`scheduledMinute:${S.id}`,Qe(E));if(r.length&&s.trigger&&t.set("desiredState","running"),!r.length||t.setting("desiredState")!=="running"||s.signal.aborted){t.database.exec("COMMIT"),t.close();return}t.set("owner",JSON.stringify({pid:process.pid,nonce:n})),t.set("pid",String(process.pid)),t.set("heartbeatAt",E.toISOString()),t.database.exec("COMMIT")}catch(d){throw t.database.exec("ROLLBACK"),t.close(),d}let i=new AbortController,a=Date.now()+(s.maxDurationMs??P.runMs),o=AbortSignal.any([s.signal,i.signal]),l=setTimeout(()=>i.abort(new Error("Import exceeded its one-hour time budget. Remaining work is retained for the next run.")),s.maxDurationMs??P.runMs),c=setInterval(()=>{t.setting("desiredState")!=="running"?i.abort(new K("Import cancelled.")):t.set("heartbeatAt",new Date().toISOString())},250),f=new ye(t),u=new qe(t),h=p(d=>t.connections().find(E=>E.id===d.id)??d,"retained"),g=p(d=>{let E=t.queued(d.id),S=f.message(d.id,"heartbeat");return{pendingOperations:E,error:S,completedSyncRevision:!E&&!S?d.completedSyncRevision??0:0}},"heartbeatInput");function w(d,E){let S=h(d);if(S.state==="disconnected"||E.revision<S.revision)return S;let b=u.observe(S,E);E.revision>S.revision&&f.set(S.id,"control",null);let N={...S,...b,...E.revision>S.revision?{revision:E.revision,state:E.state}:{},...E.destinations?{destinations:E.destinations}:{}};return t.put(N),N}p(w,"applyRemote");function y(d,E,S){f.set(d.id,S,E instanceof Error?E.message:"Import failed.");let b=E&&typeof E=="object"&&"status"in E?Number(E.status):0,N=h(d);N.state!=="disconnected"&&[400,401,403].includes(b)&&t.put({...N,state:b===400?"paused":"disconnected"})}p(y,"recordFailure");function m(){if(Date.now()>=a&&!i.signal.aborted&&i.abort(new Error("Import time budget reached. Remaining work is retained for the next run.")),o.aborted)throw o.reason??new K("Import cancelled.");if(t.setting("desiredState")!=="running")throw new K("Import cancelled.")}p(m,"checkCancelled");try{await t.snapshots.migrate(()=>o.aborted||Date.now()>=a||t.setting("desiredState")!=="running");for(let d of r){let E="heartbeat",S=0,b={id:n,state:"running",phase:"discovering",startedAt:new Date().toISOString(),finishedAt:null,processed:0,discovered:0,uploaded:0,error:null},N=p(x=>{b={...b,...x},t.set(`run:${d.id}`,JSON.stringify(b))},"progress");N({});let v=p(async()=>{m(),E="heartbeat",d=h(d);let x=await s.transport.heartbeat(d,g(d),o);d=w(d,x),f.set(d.id,"heartbeat",null),S=Date.now()},"heartbeat"),L=p(async()=>{if(m(),Date.now()-S>=P.heartbeatMs&&await v(),d=h(d),d.state!=="active")throw new K(`Source ${d.state}.`)},"check"),A=p(async()=>{for(;t.queued(d.id);){await L();let x=t.next(d.id);if(!x)break;N({phase:"uploading"});let C=!1;for(let R=0;R<P.attemptsPerRun;R++){if(await L(),!t.database.prepare("SELECT 1 FROM pending WHERE id=? AND connection_id=?").get(x.entry.operationId,d.id)){C=!0;break}E="admission";try{await s.transport.admit(d,x.entry,o),t.acknowledge(x.entry),f.set(d.id,"admission",null),N({uploaded:b.uploaded+x.entry.boundaryIds.length}),C=!0;break}catch(B){t.retry(x.entry.operationId,x.attempts+R);let H=B&&typeof B=="object"&&"status"in B?Number(B.status):0;if(o.aborted||[400,401,403,409].includes(H)||R+1>=P.attemptsPerRun)throw B;await Jn(1e3*2**R,void 0,{signal:o})}}if(!C)throw new Error("Pending import was not acknowledged.")}},"drain");try{if(await v(),d.state!=="active")throw new K(`Source ${d.state}.`);await A();let x;for(let C=0;C<3;C++){await L();let R=d.revision,B=d.requestedSyncRevision??0,H=JSON.stringify(d.selectedSessionKeys);E="source",new ge(t).seed(d,e,t.coverage.manifest(d.id)),t.coverage.begin(d,`${n}-${C}`,b.startedAt,e);let W=p(async()=>{if(await L(),E="source",d.revision!==R||JSON.stringify(d.selectedSessionKeys)!==H)throw new oe("Source settings changed during acquisition.")},"checkAcquisition");try{await vs({store:t,connection:d,until:e,check:W,drain:p(async()=>{await A(),await W()},"drain"),progress:N})}catch(ie){if(ie instanceof oe&&C<2)continue;throw ie}if(f.set(d.id,"source",null),await A(),await s.transport.publishCoverage(d,t.coverage.finish(d.id,d.selectedSessionKeys===void 0),o),d=h(d),d.revision!==R){if(C===2)throw new Error("Source settings changed repeatedly during import. Run Sync now again.");continue}if(u.acquired(d.id,{controlRevision:R,requestedSyncRevision:B,succeeded:!0}),d=u.complete(d,f.message(d.id,"heartbeat")),await v(),d.revision!==R||u.needsAcquisition(d)){if(C===2)throw new Error("Source settings changed during completion. Run Sync now again.");continue}if(u.needsAcknowledgement(d))throw new Error("The server has not acknowledged sync completion. Retry with Sync now.");x=R;break}if(await L(),d.revision!==x)throw new oe("Source settings changed before completion. Run Sync now again.");N({state:"completed",finishedAt:new Date().toISOString()}),t.set(`lastSuccess:${d.id}`,b.finishedAt)}catch(x){let C=x instanceof K||s.signal.aborted||o.reason instanceof K,R=o.aborted?o.reason:x,B=R instanceof Error?R.message:"Import cancelled.";if(C||y(d,R,E),N({state:C?"cancelled":"failed",error:B,finishedAt:new Date().toISOString()}),t.coverage.manifest(d.id)?.jobId.startsWith(`${n}-`)){let H=t.coverage.finish(d.id,!1);if(!o.aborted&&d.state==="active")try{await s.transport.publishCoverage(d,H,o)}catch(W){y(d,W,"source")}}}if(o.aborted||t.setting("desiredState")!=="running")break}}finally{clearInterval(c),clearTimeout(l),JSON.parse(t.setting("owner")||"{}").nonce===n&&(t.set("pid",""),t.set("heartbeatAt",""),t.set("owner",""),t.set("desiredState","stopped")),t.close()}}p(Oc,"runCollector");export{ut as a,ar as b,Ct as c,pe as d,Ve as e,De as f,rn as g,on as h,li as i,pi as j,_i as k,Ze as l,an as m,he as n,yi as o,j as p,ec as q,tc as r,Oc as s,ga as t,Ue as u,Cn as v,ps as w,ya as x,Ea as y,Mn as z,Oa as A,ws as B,Pn as C};
|
|
96
|
+
PRIMARY KEY(connection_id,session_key));`)}selection(e,t,n){return O([e.source,e.projectId,e.teamId,e.apiBaseUrl,e.account??null,e.since,e.selectedSessionKeys??null,t,n])}read(e,t,n,r){let i=this.store.database.prepare("SELECT value FROM source_read_cache WHERE connection_id=? AND session_key=? AND selection_hash=?").get(e.id,n,this.selection(e,t,r));return i?ce.parse(JSON.parse(String(i.value))):null}retain(e,t,n,r,i){let a=ce.parse(i);a.nativeRevisionHash===null||a.state!=="admitted"&&!(a.state==="skipped"&&a.reason==="no_eligible_boundaries")||this.store.database.prepare("INSERT INTO source_read_cache VALUES(?,?,?,?) ON CONFLICT(connection_id,session_key) DO UPDATE SET selection_hash=excluded.selection_hash,value=excluded.value").run(e.id,n,this.selection(e,t,r),JSON.stringify(a))}seed(e,t,n){if(!n||n.connectionRevision!==e.revision||n.from!==e.since||n.to!==t||n.sourceInstanceId!==e.source.instanceId||n.machineId!==e.source.machineId)return;let r=new Map(n.sessions.map(i=>[i.sourceKeyHash,i]));for(let i of this.store.database.prepare("SELECT session_key,revision FROM source_scans WHERE connection_id=?").all(e.id)){let a=String(i.session_key),o=r.get(O(a));o&&this.retain(e,t,a,String(i.revision),o)}}};var Wn=["source","admission","control","heartbeat"],ye=class{static{p(this,"CollectorErrors")}store;constructor(e){this.store=e}read(e){let t=this.store.setting(`errors:${e}`);if(t)return JSON.parse(t);let n=this.store.database.prepare("SELECT error FROM backfill_units WHERE connection_id=? AND state='error' AND error IS NOT NULL ORDER BY session_key LIMIT 1").get(e);return typeof n?.error=="string"?{source:n.error}:{}}message(e,t){let n=this.read(e);return Wn.filter(r=>r!==t).map(r=>n[r]).find(Boolean)??null}source(e){return this.read(e).source??null}set(e,t,n){let r=this.read(e);n?r[t]=n.slice(0,500):delete r[t],this.store.set(`errors:${e}`,JSON.stringify(r)),this.store.error(e,this.message(e))}};var qe=class{static{p(this,"CollectorSyncRequests")}store;acquisitions=new Map;constructor(e){this.store=e}observe(e,t){let n=t.requestedSyncRevision??e.requestedSyncRevision??0,r=t.completedSyncRevision??0;if(!Number.isSafeInteger(n)||n<0||n>t.revision||!Number.isSafeInteger(r)||r<0||r>n)throw new Error("Invalid remote sync acknowledgement.");let i=this.confirmed(e.id);return r>i&&this.store.set(`syncAcknowledged:${e.id}`,String(r)),{requestedSyncRevision:Math.max(e.requestedSyncRevision??0,n),completedSyncRevision:Math.max(e.completedSyncRevision??0,r)}}needsAcquisition(e){let t=e.requestedSyncRevision??0;if(t<=(e.completedSyncRevision??0))return!1;let n=this.acquisitions.get(e.id);return n?.controlRevision!==e.revision||n.requestedSyncRevision!==t}acquired(e,t){this.acquisitions.set(e,t)}complete(e,t){let n=this.acquisitions.get(e.id),r=e.requestedSyncRevision??0;if(e.state!=="active"||this.store.setting("desiredState")!=="running"||this.store.queued(e.id)||t||!n?.succeeded||n.controlRevision!==e.revision||n.requestedSyncRevision!==r||r<=(e.completedSyncRevision??0))return e;let i={...e,completedSyncRevision:r};return this.store.put(i),i}confirmed(e){return Number(this.store.setting(`syncAcknowledged:${e}`))||0}needsAcknowledgement(e){return(e.completedSyncRevision??0)>this.confirmed(e.id)}};var zn=Y.object({leafId:Y.string().min(1).max(200),chainHash:Y.string().regex(/^[a-f0-9]{64}$/),sourceInstanceId:Y.string().min(1)}).strict(),bs=p((s,e)=>`branch:${JSON.stringify([s,e])}`,"key");function vs(s,e,t){let n=s.setting(bs(e,t));if(!n)return;let r=zn.parse(JSON.parse(n));return s.connections().find(a=>a.id===e)?.source.instanceId===r.sourceInstanceId?{leafId:r.leafId,chainHash:r.chainHash}:void 0}p(vs,"collectorBranchAnchor");async function Is(s,e){if(s.source!=="claude_code")throw new Error("Branch selection is currently supported for Claude Code.");let t,n=[];do{let r=await pe(s,{cursor:t,limit:100});n.push(...r.items.filter(i=>i.nativeSessionId===e)),t=r.nextCursor??void 0}while(t);if(n.length!==1)throw new Error("Select exactly one native session in this connection's source location.");return n[0]}p(Is,"findSession");async function tc(s,e,t){let n=await j.open(s);try{let r=n.connections().find(a=>a.id===e);if(!r)throw new Error("Select a connection from openpond import status.");let i=await Is(r.source,t);return{session:i,...await Ze(r.source,i)}}finally{n.close()}}p(tc,"inspectCollectorBranches");async function sc(s,e,t,n){let r=await j.open(s);try{let i=r.connections().find(c=>c.id===e);if(!i||i.state!=="paused")throw new Error(`Pause this connection first: openpond import pause ${e}`);let a=await Is(i.source,t),o=await Ze(i.source,a),l=o.branches.find(c=>c.leafId===n.leafId);if(o.revision!==n.revision||!l)throw new Error("This conversation changed. Refresh its branches and choose again.");await De(i.source,a,{branchLeafId:n.leafId,expectedBranchRevision:n.revision}),r.database.exec("BEGIN IMMEDIATE");try{let c=r.connections().find(u=>u.id===e);if(!c||c.state!=="paused"||c.revision!==i.revision||c.source.instanceId!==i.source.instanceId)throw new Error("Connection changed during branch selection. Refresh and try again.");r.set(bs(e,t),JSON.stringify({leafId:l.leafId,chainHash:l.chainHash,sourceInstanceId:i.source.instanceId}));for(let u of["source_scans","checkpoints","pending"])r.database.prepare(`DELETE FROM ${u} WHERE connection_id=?`).run(e);r.snapshots.collect();let f=new ye(r);f.set(e,"source",f.source(e)),r.progress.reset(e),f.set(e,"admission",null),r.database.exec("COMMIT")}catch(c){throw r.database.exec("ROLLBACK"),c}return{connectionId:e,nativeSessionId:t,leafId:l.leafId,state:"paused"}}finally{r.close()}}p(sc,"selectCollectorBranch");async function Os(s){let{store:e,connection:t,check:n,drain:r,progress:i,until:a}=s,o=new ge(e),l,c=0,f=0,u=[],h=t.selectedSessionKeys?new Set(t.selectedSessionKeys):null,g=new Set,w=0;do{await n(),i({phase:"discovering"});let y=await pe(t.source,{cursor:l,limit:50});if(w+=y.items.length,w>1e4)throw new Error("Source inventory exceeds 10,000 sessions. Select a narrower source directory.");let m=y.items.filter(d=>!h||h.has(ue(d)));for(let d of m)g.add(ue(d));f+=m.length;for(let d of m){let E=JSON.stringify([d.path,d.nativeSessionId]);e.coverage.record(t.id,{sourceKeyHash:te.sourceKey(E),nativeRevisionHash:d.storageRevision?O([d.storageRevision,Re(t.source.source)]):null,state:"reading",reason:null,unknownTimeBoundaries:0,normalized:[]})}i({discovered:f});for(let d of m){if(await n(),await r(),Number(e.database.prepare("SELECT COALESCE(SUM(bytes),0) AS n FROM pending").get()?.n)+e.snapshots.bytes()>=P.maxBytes)throw new se;i({phase:"reading"});let S=JSON.stringify([d.path,d.nativeSessionId]),b=d.storageRevision?O([d.storageRevision,Re(t.source.source)]):null;e.progress.select(t.id,S);let N=b?o.read(t,a,S,b):null;if(N){e.coverage.record(t.id,N),e.progress.read(t.id,S,N.state==="admitted"),i({processed:++c});continue}let v={sourceKeyHash:te.sourceKey(S),nativeRevisionHash:b,state:"reading",reason:b?null:"source_revision_unavailable",unknownTimeBoundaries:0,normalized:[]};try{let A=await Kt(t.source,d,{since:t.since,until:a,check:n});if(A){v.nativeRevisionHash=O(["codex-window-inventory-v1",A.sha256]),v.state="skipped",v.reason="no_eligible_boundaries",e.coverage.record(t.id,v),e.progress.read(t.id,S,!1),b&&(e.scanned(t.id,S,b),o.retain(t,a,S,b,v));continue}let{files:M,preview:x,branchLeafId:R}=await De(t.source,d,{branchAnchor:vs(e,t.id,d.nativeSessionId)});v.nativeRevisionHash=O([M,Re(t.source.source)]),await n();let C=e.snapshots.prepare(M),B=!1;for(let H of x.sessions){let W=JSON.stringify([t.source.instanceId,H.sessionId,H.branchId]);e.progress.retained(t.id,S,W);let ae=H.boundaries.filter(D=>{if(D.projection!=="turn"||D.terminal==="unknown")return!1;let G=H.events[D.start]?.occurredAt;return!G||!Number.isFinite(Date.parse(G))?(v.unknownTimeBoundaries++,!1):Date.parse(G)<Date.parse(a)&&(!t.since||Date.parse(G)>=Date.parse(t.since))});v.normalized.push({sessionHash:H.contentHash,boundaries:ae.map(D=>({id:D.id,inputHash:D.inputHash,revisionHash:D.revisionHash,occurredAt:H.events[D.start].occurredAt})).sort((D,G)=>D.id<G.id?-1:D.id>G.id?1:0)}),e.coverage.record(t.id,v),B||=ae.length>0;let ct=ae.filter(D=>e.changed(t.id,W,D.id,O([D.inputHash,D.revisionHash])));for(let D=0;D<ct.length;D+=P.batchCases){await n();let G=ct.slice(D,D+P.batchCases),Ts=`sync-${O([t.id,W,G.map(V=>[V.id,V.inputHash,V.revisionHash])]).slice(0,48)}`;e.enqueue({operationId:Ts,connectionId:t.id,sessionKey:W,contentHash:H.contentHash,files:M,boundaryIds:G.map(V=>V.id),...R?{branchLeafId:R}:{}},G.map(V=>({id:V.id,revision:O([V.inputHash,V.revisionHash])})),S,C)}}e.progress.read(t.id,S,B),b&&e.scanned(t.id,S,b),await r(),v.state=B?"admitted":"skipped",v.reason=B?null:"no_eligible_boundaries",v.normalized.sort((H,W)=>H.sessionHash<W.sessionHash?-1:H.sessionHash>W.sessionHash?1:0),e.coverage.record(t.id,v),b&&o.retain(t,a,S,b,v)}catch(A){if(A instanceof le){v.state="skipped",v.reason="native_session_not_ready",e.coverage.record(t.id,v),e.progress.read(t.id,S,!1),b&&e.scanned(t.id,S,b);continue}if(A instanceof se||A instanceof K||A instanceof ie)throw A;let M=A instanceof Error?A.message:"Unable to read session";v.state="failed",v.reason="source_read_failed",e.coverage.record(t.id,v),e.progress.failed(t.id,S,M),u.push(`${d.nativeSessionId}: ${M}`)}finally{i({processed:++c})}await r()}l=y.nextCursor??void 0}while(l);if(e.progress.discovered(t.id),e.coverage.finish(t.id,h===null),h&&[...h].some(y=>!g.has(y)))throw new Error("A selected conversation is no longer available. Review the upload selection.");if(u.length)throw new Error(`${u.length} session(s) need attention. ${u[0]}`)}p(Os,"acquireCollectorSource");var K=class extends Error{static{p(this,"CollectorInterruptedError")}},ie=class extends Error{static{p(this,"CollectorScopeChangedError")}};async function Tc(s){let e=s.until??new Date().toISOString();if(!Number.isFinite(Date.parse(e))||Date.parse(e)>Date.now())throw new Error("--until must be a valid timestamp no later than now.");let t=await j.open(s.directory),n=Jn(),r=[];t.database.exec("BEGIN IMMEDIATE");try{let d=t.setting("owner");if(d){let S=JSON.parse(d),b=!0;try{process.kill(S.pid,0)}catch(N){b=N.code!=="ESRCH"}if(b){if(s.trigger==="scheduled"){t.database.exec("COMMIT"),t.close();return}throw new Error("An import is already running. Cancel it or wait for it to finish.")}}let E=new Date;if(r=t.connections().filter(S=>S.state!=="disconnected"&&S.selectedSessionKeys?.length!==0&&(!s.connectionIds||s.connectionIds.includes(S.id))&&(s.trigger!=="scheduled"||S.state==="active"&&Qt(t.schedule(S.id),t.setting(`scheduledMinute:${S.id}`),E))),s.trigger==="scheduled")for(let S of r)t.set(`scheduledMinute:${S.id}`,et(E));if(r.length&&s.trigger&&t.set("desiredState","running"),!r.length||t.setting("desiredState")!=="running"||s.signal.aborted){t.database.exec("COMMIT"),t.close();return}t.set("owner",JSON.stringify({pid:process.pid,nonce:n})),t.set("pid",String(process.pid)),t.set("heartbeatAt",E.toISOString()),t.database.exec("COMMIT")}catch(d){throw t.database.exec("ROLLBACK"),t.close(),d}let i=new AbortController,a=Date.now()+(s.maxDurationMs??P.runMs),o=AbortSignal.any([s.signal,i.signal]),l=setTimeout(()=>i.abort(new Error("Import exceeded its one-hour time budget. Remaining work is retained for the next run.")),s.maxDurationMs??P.runMs),c=setInterval(()=>{t.setting("desiredState")!=="running"?i.abort(new K("Import cancelled.")):t.set("heartbeatAt",new Date().toISOString())},250),f=new ye(t),u=new qe(t),h=p(d=>t.connections().find(E=>E.id===d.id)??d,"retained"),g=p(d=>{let E=t.queued(d.id),S=f.message(d.id,"heartbeat");return{pendingOperations:E,error:S,completedSyncRevision:!E&&!S?d.completedSyncRevision??0:0}},"heartbeatInput");function w(d,E){let S=h(d);if(S.state==="disconnected"||E.revision<S.revision)return S;let b=u.observe(S,E);E.revision>S.revision&&f.set(S.id,"control",null);let N={...S,...b,...E.revision>S.revision?{revision:E.revision,state:E.state}:{},...E.destinations?{destinations:E.destinations}:{}};return t.put(N),N}p(w,"applyRemote");function y(d,E,S){f.set(d.id,S,E instanceof Error?E.message:"Import failed.");let b=E&&typeof E=="object"&&"status"in E?Number(E.status):0,N=h(d);N.state!=="disconnected"&&[400,401,403].includes(b)&&t.put({...N,state:b===400?"paused":"disconnected"})}p(y,"recordFailure");function m(){if(Date.now()>=a&&!i.signal.aborted&&i.abort(new Error("Import time budget reached. Remaining work is retained for the next run.")),o.aborted)throw o.reason??new K("Import cancelled.");if(t.setting("desiredState")!=="running")throw new K("Import cancelled.")}p(m,"checkCancelled");try{await t.snapshots.migrate(()=>o.aborted||Date.now()>=a||t.setting("desiredState")!=="running");for(let d of r){let E="heartbeat",S=0,b={id:n,state:"running",phase:"discovering",startedAt:new Date().toISOString(),finishedAt:null,processed:0,discovered:0,uploaded:0,error:null},N=p(x=>{b={...b,...x},t.set(`run:${d.id}`,JSON.stringify(b))},"progress");N({});let v=p(async()=>{m(),E="heartbeat",d=h(d);let x=await s.transport.heartbeat(d,g(d),o);d=w(d,x),f.set(d.id,"heartbeat",null),S=Date.now()},"heartbeat"),A=p(async()=>{if(m(),Date.now()-S>=P.heartbeatMs&&await v(),d=h(d),d.state!=="active")throw new K(`Source ${d.state}.`)},"check"),M=p(async()=>{for(;t.queued(d.id);){await A();let x=t.next(d.id);if(!x)break;N({phase:"uploading"});let R=!1;for(let C=0;C<P.attemptsPerRun;C++){if(await A(),!t.database.prepare("SELECT 1 FROM pending WHERE id=? AND connection_id=?").get(x.entry.operationId,d.id)){R=!0;break}E="admission";try{await s.transport.admit(d,x.entry,o),t.acknowledge(x.entry),f.set(d.id,"admission",null),N({uploaded:b.uploaded+x.entry.boundaryIds.length}),R=!0;break}catch(B){t.retry(x.entry.operationId,x.attempts+C);let H=B&&typeof B=="object"&&"status"in B?Number(B.status):0;if(o.aborted||[400,401,403,409].includes(H)||C+1>=P.attemptsPerRun)throw B;await Gn(1e3*2**C,void 0,{signal:o})}}if(!R)throw new Error("Pending import was not acknowledged.")}},"drain");try{if(await v(),d.state!=="active")throw new K(`Source ${d.state}.`);await M();let x;for(let R=0;R<3;R++){await A();let C=d.revision,B=d.requestedSyncRevision??0,H=JSON.stringify(d.selectedSessionKeys);E="source",new ge(t).seed(d,e,t.coverage.manifest(d.id)),t.coverage.begin(d,`${n}-${R}`,b.startedAt,e);let W=p(async()=>{if(await A(),E="source",d.revision!==C||JSON.stringify(d.selectedSessionKeys)!==H)throw new ie("Source settings changed during acquisition.")},"checkAcquisition");try{await Os({store:t,connection:d,until:e,check:W,drain:p(async()=>{await M(),await W()},"drain"),progress:N})}catch(ae){if(ae instanceof ie&&R<2)continue;throw ae}if(f.set(d.id,"source",null),await M(),await s.transport.publishCoverage(d,t.coverage.finish(d.id,d.selectedSessionKeys===void 0),o),d=h(d),d.revision!==C){if(R===2)throw new Error("Source settings changed repeatedly during import. Run Sync now again.");continue}if(u.acquired(d.id,{controlRevision:C,requestedSyncRevision:B,succeeded:!0}),d=u.complete(d,f.message(d.id,"heartbeat")),await v(),d.revision!==C||u.needsAcquisition(d)){if(R===2)throw new Error("Source settings changed during completion. Run Sync now again.");continue}if(u.needsAcknowledgement(d))throw new Error("The server has not acknowledged sync completion. Retry with Sync now.");x=C;break}if(await A(),d.revision!==x)throw new ie("Source settings changed before completion. Run Sync now again.");N({state:"completed",finishedAt:new Date().toISOString()}),t.set(`lastSuccess:${d.id}`,b.finishedAt)}catch(x){let R=x instanceof K||s.signal.aborted||o.reason instanceof K,C=o.aborted?o.reason:x,B=C instanceof Error?C.message:"Import cancelled.";if(R||y(d,C,E),N({state:R?"cancelled":"failed",error:B,finishedAt:new Date().toISOString()}),t.coverage.manifest(d.id)?.jobId.startsWith(`${n}-`)){let H=t.coverage.finish(d.id,!1);if(!o.aborted&&d.state==="active")try{await s.transport.publishCoverage(d,H,o)}catch(W){y(d,W,"source")}}}if(o.aborted||t.setting("desiredState")!=="running")break}}finally{clearInterval(c),clearTimeout(l),JSON.parse(t.setting("owner")||"{}").nonce===n&&(t.set("pid",""),t.set("heartbeatAt",""),t.set("owner",""),t.set("desiredState","stopped")),t.close()}}p(Tc,"runCollector");export{ft as a,cr as b,Rt as c,pe as d,Ze as e,De as f,on as g,an as h,pi as i,ui as j,bi as k,Qe as l,cn as m,he as n,Ei as o,j as p,tc as q,sc as r,Tc as s,ya as t,Ue as u,Rn as v,fs as w,Ea as x,wa as y,$n as z,Ta as A,_s as B,jn as C};
|