@runcofactor/cli 0.54.0 → 0.56.0
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 -1
- package/dist/{account-6YJAU53I.js → account-CZYZD2JS.js} +5 -5
- package/dist/{alert-Z7V2ZUEW.js → alert-JQ4SDEB7.js} +8 -8
- package/dist/{api-catalog-UEDTRM6E.js → api-catalog-IWQC35P2.js} +5 -5
- package/dist/{api-key-V5GEPRRG.js → api-key-GUDXIIEA.js} +5 -5
- package/dist/{attachment-M7VZ6GSE.js → attachment-CPZYOBUB.js} +5 -5
- package/dist/{auth-DVTMWJKF.js → auth-DS6MBVEI.js} +3 -3
- package/dist/{benchmark-KZJZYUTQ.js → benchmark-6HPCIQHD.js} +5 -5
- package/dist/{blackcat-QJXYDE66.js → blackcat-V3L63WFE.js} +3 -3
- package/dist/{chunk-FLDIN6VX.js → chunk-2E3STBHS.js} +2 -2
- package/dist/{chunk-KNWKOKM7.js → chunk-2OHYMT3A.js} +20 -11
- package/dist/chunk-2OHYMT3A.js.map +1 -0
- package/dist/{chunk-L4Y5PZUE.js → chunk-3LGCHNBC.js} +2 -2
- package/dist/{chunk-ZFN5FWN2.js → chunk-4MFMPC5P.js} +46 -2
- package/dist/chunk-4MFMPC5P.js.map +1 -0
- package/dist/{chunk-2M4PZK6Q.js → chunk-56HFZHQM.js} +8 -8
- package/dist/{chunk-AQOHNAEN.js → chunk-5OYWNS6D.js} +20 -9
- package/dist/chunk-5OYWNS6D.js.map +1 -0
- package/dist/{chunk-RA2NRAWU.js → chunk-62EXS76C.js} +6 -6
- package/dist/{chunk-HGEJHS45.js → chunk-6ILWJFKY.js} +368 -6
- package/dist/chunk-6ILWJFKY.js.map +1 -0
- package/dist/{chunk-4EWSONHO.js → chunk-BDOL622T.js} +4 -4
- package/dist/{chunk-T6EQFICG.js → chunk-C3CXVX2B.js} +4 -4
- package/dist/{chunk-33U56YGD.js → chunk-CWICLBLU.js} +2 -1
- package/dist/{chunk-33U56YGD.js.map → chunk-CWICLBLU.js.map} +1 -1
- package/dist/{chunk-MQQCUU5S.js → chunk-DEVD2WD2.js} +2 -2
- package/dist/{chunk-TRC63RSK.js → chunk-EWK44F6V.js} +3 -3
- package/dist/chunk-EWK44F6V.js.map +1 -0
- package/dist/{chunk-Q7UAEFW5.js → chunk-FNHPTTRF.js} +7 -5
- package/dist/chunk-FNHPTTRF.js.map +1 -0
- package/dist/{chunk-JAIMLQOU.js → chunk-GCD4EHCD.js} +6 -6
- package/dist/{chunk-7MRZWPVC.js → chunk-H6ZMKNP7.js} +3 -3
- package/dist/{chunk-ZOPVBINJ.js → chunk-IEWAH7W3.js} +5 -5
- package/dist/{chunk-74TU6PGO.js → chunk-IV4HRGKX.js} +77 -12
- package/dist/chunk-IV4HRGKX.js.map +1 -0
- package/dist/{chunk-ZO5MSM4Q.js → chunk-J2ZQULU3.js} +2 -2
- package/dist/{chunk-IVWWYKAM.js → chunk-K2IDR6FR.js} +3 -3
- package/dist/{chunk-QGP67JOK.js → chunk-KTZRI27M.js} +4 -4
- package/dist/{chunk-HESV3F6U.js → chunk-L644NMDI.js} +3 -3
- package/dist/{chunk-HESV3F6U.js.map → chunk-L644NMDI.js.map} +1 -1
- package/dist/{chunk-LPQTXBJF.js → chunk-LFT7GUWS.js} +63 -17
- package/dist/chunk-LFT7GUWS.js.map +1 -0
- package/dist/{chunk-O7MBDOMO.js → chunk-O7B2IYCZ.js} +30 -14
- package/dist/chunk-O7B2IYCZ.js.map +1 -0
- package/dist/{chunk-R2CVV7QT.js → chunk-RHWPZKRV.js} +28 -1
- package/dist/chunk-RHWPZKRV.js.map +1 -0
- package/dist/{chunk-3YNR6U6Q.js → chunk-UJSW72LG.js} +3 -3
- package/dist/{chunk-G2SCV2CY.js → chunk-VACACCD6.js} +3 -3
- package/dist/{chunk-CV22445U.js → chunk-VMAR67FF.js} +2 -2
- package/dist/{chunk-QYHJUHL7.js → chunk-VMJ7TBVM.js} +2 -2
- package/dist/chunk-WRRA4ATV.js +332 -0
- package/dist/chunk-WRRA4ATV.js.map +1 -0
- package/dist/{chunk-YACDH6MJ.js → chunk-XHEVDABB.js} +2 -2
- package/dist/{chunk-7VBX2M4F.js → chunk-XHGF6VC6.js} +4 -4
- package/dist/{credential-546ER7WQ.js → credential-GJW7LGYP.js} +5 -5
- package/dist/{credential-template-BWMEBGBN.js → credential-template-UWBYKKWD.js} +5 -5
- package/dist/dev-PBW7BSOD.js +605 -0
- package/dist/dev-PBW7BSOD.js.map +1 -0
- package/dist/{digest-NIVBDDI2.js → digest-XEHGCJM4.js} +8 -8
- package/dist/{docs-AK4MDP6K.js → docs-KH4BCEQF.js} +5 -5
- package/dist/{doctor-NCLA47EL.js → doctor-FOXXE5SK.js} +3 -3
- package/dist/{environment-X3PV5IN2.js → environment-EBDPQTIS.js} +7 -7
- package/dist/{eval-5FZKYZ6O.js → eval-QZSSEICV.js} +67 -27
- package/dist/eval-QZSSEICV.js.map +1 -0
- package/dist/{exploration-2RVGIUKT.js → exploration-LCGKRGOQ.js} +5 -5
- package/dist/{exploratory-test-SJ5HFI3L.js → exploratory-test-SGECQGIX.js} +13 -5
- package/dist/exploratory-test-SGECQGIX.js.map +1 -0
- package/dist/{external-run-4NDVAHQB.js → external-run-2AJAI5O7.js} +9 -9
- package/dist/{feature-flag-C4IRE724.js → feature-flag-P7N4WQIH.js} +5 -5
- package/dist/{feedback-337OZCKC.js → feedback-LAT7TQ2T.js} +6 -6
- package/dist/{flow-D7ZLBKCH.js → flow-NH2DC6AP.js} +5 -5
- package/dist/{github-LKXYIALH.js → github-FCEKBLXI.js} +6 -6
- package/dist/index.js +106 -408
- package/dist/index.js.map +1 -1
- package/dist/{init-GKEC6LPH.js → init-5U5EZOAW.js} +5 -5
- package/dist/{install-K45SAT2V.js → install-X3UNVXKY.js} +5 -5
- package/dist/{issues-2HMTQYWR.js → issues-4P6I3YQW.js} +8 -8
- package/dist/{knobs-KUCGLO5Z.js → knobs-JKTWJ6ZG.js} +5 -5
- package/dist/{landing-KAET2I73.js → landing-6AGLKI66.js} +7 -7
- package/dist/{list-GDV4UYWV.js → list-TWP2RP33.js} +5 -5
- package/dist/{local-NFOSJLLV.js → local-D75QE5TB.js} +7 -7
- package/dist/{login-Y77HWROY.js → login-RBET4TIP.js} +5 -5
- package/dist/{mcp-CPCFMU6B.js → mcp-562SUUMK.js} +11 -11
- package/dist/{metrics-Y245ST63.js → metrics-4WF2GEPA.js} +5 -5
- package/dist/{monitor-BUDWSC3S.js → monitor-WJXH54H2.js} +5 -5
- package/dist/{perf-3JOAXPHP.js → perf-C6N6P7YG.js} +12 -361
- package/dist/perf-C6N6P7YG.js.map +1 -0
- package/dist/{product-CXL3YTMD.js → product-CYEQ7HOB.js} +5 -5
- package/dist/{product-map-656BTU74.js → product-map-MSDLIFZY.js} +7 -7
- package/dist/{prompts-3SZ7O5E6.js → prompts-ME53WPN4.js} +5 -5
- package/dist/{proofs-4CSCCSNL.js → proofs-D3G6ZUFP.js} +11 -9
- package/dist/{property-IEKBXRVY.js → property-5GLJNAVB.js} +29 -10
- package/dist/property-5GLJNAVB.js.map +1 -0
- package/dist/{psql-M4CM6TSI.js → psql-EXAUDU3W.js} +5 -5
- package/dist/{record-QP4TYZBS.js → record-EE7NGNKY.js} +6 -6
- package/dist/{redis-KG47IGJV.js → redis-M4EYWKOJ.js} +5 -5
- package/dist/{release-QHPSQULK.js → release-4KUWVWWC.js} +5 -5
- package/dist/{runbook-YVBG2QK3.js → runbook-AHU77ANQ.js} +5 -5
- package/dist/{sandbox-ZXDZTCCN.js → sandbox-FBLJEYA2.js} +1917 -1633
- package/dist/sandbox-FBLJEYA2.js.map +1 -0
- package/dist/{scenarios-2SX2NUCD.js → scenarios-TU656T2B.js} +5 -5
- package/dist/{schedule-P6F7MLXX.js → schedule-DXJI6SYO.js} +8 -8
- package/dist/{session-SZMCZTPE.js → session-RUFTJHF4.js} +10 -10
- package/dist/{skill-D4XFW6QI.js → skill-ZK76GQ47.js} +111 -13
- package/dist/skill-ZK76GQ47.js.map +1 -0
- package/dist/skills/cofactor-debug-run/SKILL.md +6 -1
- package/dist/skills/cofactor-debug-run/history/2.0.10.md +320 -0
- package/dist/skills/cofactor-debug-run/history/2.0.9.md +319 -0
- package/dist/skills/cofactor-debug-run/version.json +1 -1
- package/dist/{slack-UDXTPOSW.js → slack-M3OKDVMY.js} +6 -6
- package/dist/{spec-YCBBIV27.js → spec-5MXEBLYR.js} +5 -5
- package/dist/{src-DY7GLRO2.js → src-2X5OQRPJ.js} +4 -4
- package/dist/{src-NG7DRE5A.js → src-72EFBA2R.js} +3 -3
- package/dist/{src-DEGBASCD.js → src-KH6WSBJV.js} +5 -5
- package/dist/{src-ZKVNVLXY.js → src-VLV36QYH.js} +127 -20
- package/dist/src-VLV36QYH.js.map +1 -0
- package/dist/{start-ZYZSORPY.js → start-PDYBRB5T.js} +5 -5
- package/dist/{status-ESIG6A7W.js → status-VMVPVCDA.js} +5 -5
- package/dist/{tag-3K5Y25AR.js → tag-7KTDLPVU.js} +6 -6
- package/dist/{task-JLNX7O3M.js → task-QLFYZNKR.js} +6 -6
- package/dist/{teams-F4IU3EXE.js → teams-Y7BXCY6P.js} +7 -7
- package/dist/{test-suite-QHDUW5W5.js → test-suite-6U22AYFG.js} +15 -14
- package/dist/test-suite-6U22AYFG.js.map +1 -0
- package/dist/{tickets-NBL5WACL.js → tickets-CQDJDNPY.js} +5 -5
- package/dist/{trace-ZKYAI5JF.js → trace-QDORWXYX.js} +8 -8
- package/dist/{triage-5NWCREUM.js → triage-GY7M3UGG.js} +6 -6
- package/dist/{trigger-KXYYY5IR.js → trigger-DLFAORX4.js} +9 -9
- package/dist/{update-check-Q2URVJLC.js → update-check-ES6XQ7OF.js} +4 -4
- package/dist/{upgrade-4XSASC7U.js → upgrade-WKEOW5GS.js} +5 -5
- package/dist/{usage-UY7VZYVY.js → usage-E6FDTR3W.js} +7 -7
- package/dist/{utilities-53NXNLA7.js → utilities-4Z6YX3L5.js} +6 -6
- package/dist/{visual-IJAT7X7D.js → visual-TA6LPVDJ.js} +5 -5
- package/dist/{workflow-OQNH2FIS.js → workflow-B5FXS2CJ.js} +92 -36
- package/dist/workflow-B5FXS2CJ.js.map +1 -0
- package/dist/{workflow-cache-FP6MKLVR.js → workflow-cache-MNLEMRMM.js} +16 -16
- package/dist/{workflow-cache-convergence-resolve-HS5KO7US.js → workflow-cache-convergence-resolve-G5HJM6MF.js} +5 -5
- package/dist/{workflow-debug-EM55H2QE.js → workflow-debug-TNBUGSBK.js} +11 -11
- package/dist/{workflow-feedback-GNWNWVHH.js → workflow-feedback-G2ZXAUGI.js} +5 -5
- package/dist/{workflow-fork-M5AQWST7.js → workflow-fork-6HHOMC2D.js} +5 -5
- package/dist/{workflow-promotion-HYULZDYL.js → workflow-promotion-RG7L6JZT.js} +5 -5
- package/dist/{workflow-proposals-EN327FSE.js → workflow-proposals-ZNF2F3UE.js} +5 -5
- package/dist/{workflow-revisions-ZMTVNWRW.js → workflow-revisions-TP64Z6FO.js} +5 -5
- package/dist/{workflow-status-FNAJG34W.js → workflow-status-5RG3JX56.js} +5 -5
- package/package.json +3 -2
- package/dist/chunk-74TU6PGO.js.map +0 -1
- package/dist/chunk-AQOHNAEN.js.map +0 -1
- package/dist/chunk-HGEJHS45.js.map +0 -1
- package/dist/chunk-KNWKOKM7.js.map +0 -1
- package/dist/chunk-LPQTXBJF.js.map +0 -1
- package/dist/chunk-O7MBDOMO.js.map +0 -1
- package/dist/chunk-Q7UAEFW5.js.map +0 -1
- package/dist/chunk-R2CVV7QT.js.map +0 -1
- package/dist/chunk-TRC63RSK.js.map +0 -1
- package/dist/chunk-ZFN5FWN2.js.map +0 -1
- package/dist/eval-5FZKYZ6O.js.map +0 -1
- package/dist/exploratory-test-SJ5HFI3L.js.map +0 -1
- package/dist/perf-3JOAXPHP.js.map +0 -1
- package/dist/property-IEKBXRVY.js.map +0 -1
- package/dist/sandbox-ZXDZTCCN.js.map +0 -1
- package/dist/skill-D4XFW6QI.js.map +0 -1
- package/dist/src-ZKVNVLXY.js.map +0 -1
- package/dist/test-suite-QHDUW5W5.js.map +0 -1
- package/dist/workflow-OQNH2FIS.js.map +0 -1
- /package/dist/{account-6YJAU53I.js.map → account-CZYZD2JS.js.map} +0 -0
- /package/dist/{alert-Z7V2ZUEW.js.map → alert-JQ4SDEB7.js.map} +0 -0
- /package/dist/{api-catalog-UEDTRM6E.js.map → api-catalog-IWQC35P2.js.map} +0 -0
- /package/dist/{api-key-V5GEPRRG.js.map → api-key-GUDXIIEA.js.map} +0 -0
- /package/dist/{attachment-M7VZ6GSE.js.map → attachment-CPZYOBUB.js.map} +0 -0
- /package/dist/{auth-DVTMWJKF.js.map → auth-DS6MBVEI.js.map} +0 -0
- /package/dist/{benchmark-KZJZYUTQ.js.map → benchmark-6HPCIQHD.js.map} +0 -0
- /package/dist/{blackcat-QJXYDE66.js.map → blackcat-V3L63WFE.js.map} +0 -0
- /package/dist/{chunk-FLDIN6VX.js.map → chunk-2E3STBHS.js.map} +0 -0
- /package/dist/{chunk-L4Y5PZUE.js.map → chunk-3LGCHNBC.js.map} +0 -0
- /package/dist/{chunk-2M4PZK6Q.js.map → chunk-56HFZHQM.js.map} +0 -0
- /package/dist/{chunk-RA2NRAWU.js.map → chunk-62EXS76C.js.map} +0 -0
- /package/dist/{chunk-4EWSONHO.js.map → chunk-BDOL622T.js.map} +0 -0
- /package/dist/{chunk-T6EQFICG.js.map → chunk-C3CXVX2B.js.map} +0 -0
- /package/dist/{chunk-MQQCUU5S.js.map → chunk-DEVD2WD2.js.map} +0 -0
- /package/dist/{chunk-JAIMLQOU.js.map → chunk-GCD4EHCD.js.map} +0 -0
- /package/dist/{chunk-7MRZWPVC.js.map → chunk-H6ZMKNP7.js.map} +0 -0
- /package/dist/{chunk-ZOPVBINJ.js.map → chunk-IEWAH7W3.js.map} +0 -0
- /package/dist/{chunk-ZO5MSM4Q.js.map → chunk-J2ZQULU3.js.map} +0 -0
- /package/dist/{chunk-IVWWYKAM.js.map → chunk-K2IDR6FR.js.map} +0 -0
- /package/dist/{chunk-QGP67JOK.js.map → chunk-KTZRI27M.js.map} +0 -0
- /package/dist/{chunk-3YNR6U6Q.js.map → chunk-UJSW72LG.js.map} +0 -0
- /package/dist/{chunk-G2SCV2CY.js.map → chunk-VACACCD6.js.map} +0 -0
- /package/dist/{chunk-CV22445U.js.map → chunk-VMAR67FF.js.map} +0 -0
- /package/dist/{chunk-QYHJUHL7.js.map → chunk-VMJ7TBVM.js.map} +0 -0
- /package/dist/{chunk-YACDH6MJ.js.map → chunk-XHEVDABB.js.map} +0 -0
- /package/dist/{chunk-7VBX2M4F.js.map → chunk-XHGF6VC6.js.map} +0 -0
- /package/dist/{credential-546ER7WQ.js.map → credential-GJW7LGYP.js.map} +0 -0
- /package/dist/{credential-template-BWMEBGBN.js.map → credential-template-UWBYKKWD.js.map} +0 -0
- /package/dist/{digest-NIVBDDI2.js.map → digest-XEHGCJM4.js.map} +0 -0
- /package/dist/{docs-AK4MDP6K.js.map → docs-KH4BCEQF.js.map} +0 -0
- /package/dist/{doctor-NCLA47EL.js.map → doctor-FOXXE5SK.js.map} +0 -0
- /package/dist/{environment-X3PV5IN2.js.map → environment-EBDPQTIS.js.map} +0 -0
- /package/dist/{exploration-2RVGIUKT.js.map → exploration-LCGKRGOQ.js.map} +0 -0
- /package/dist/{external-run-4NDVAHQB.js.map → external-run-2AJAI5O7.js.map} +0 -0
- /package/dist/{feature-flag-C4IRE724.js.map → feature-flag-P7N4WQIH.js.map} +0 -0
- /package/dist/{feedback-337OZCKC.js.map → feedback-LAT7TQ2T.js.map} +0 -0
- /package/dist/{flow-D7ZLBKCH.js.map → flow-NH2DC6AP.js.map} +0 -0
- /package/dist/{github-LKXYIALH.js.map → github-FCEKBLXI.js.map} +0 -0
- /package/dist/{init-GKEC6LPH.js.map → init-5U5EZOAW.js.map} +0 -0
- /package/dist/{install-K45SAT2V.js.map → install-X3UNVXKY.js.map} +0 -0
- /package/dist/{issues-2HMTQYWR.js.map → issues-4P6I3YQW.js.map} +0 -0
- /package/dist/{knobs-KUCGLO5Z.js.map → knobs-JKTWJ6ZG.js.map} +0 -0
- /package/dist/{landing-KAET2I73.js.map → landing-6AGLKI66.js.map} +0 -0
- /package/dist/{list-GDV4UYWV.js.map → list-TWP2RP33.js.map} +0 -0
- /package/dist/{local-NFOSJLLV.js.map → local-D75QE5TB.js.map} +0 -0
- /package/dist/{login-Y77HWROY.js.map → login-RBET4TIP.js.map} +0 -0
- /package/dist/{mcp-CPCFMU6B.js.map → mcp-562SUUMK.js.map} +0 -0
- /package/dist/{metrics-Y245ST63.js.map → metrics-4WF2GEPA.js.map} +0 -0
- /package/dist/{monitor-BUDWSC3S.js.map → monitor-WJXH54H2.js.map} +0 -0
- /package/dist/{product-CXL3YTMD.js.map → product-CYEQ7HOB.js.map} +0 -0
- /package/dist/{product-map-656BTU74.js.map → product-map-MSDLIFZY.js.map} +0 -0
- /package/dist/{prompts-3SZ7O5E6.js.map → prompts-ME53WPN4.js.map} +0 -0
- /package/dist/{proofs-4CSCCSNL.js.map → proofs-D3G6ZUFP.js.map} +0 -0
- /package/dist/{psql-M4CM6TSI.js.map → psql-EXAUDU3W.js.map} +0 -0
- /package/dist/{record-QP4TYZBS.js.map → record-EE7NGNKY.js.map} +0 -0
- /package/dist/{redis-KG47IGJV.js.map → redis-M4EYWKOJ.js.map} +0 -0
- /package/dist/{release-QHPSQULK.js.map → release-4KUWVWWC.js.map} +0 -0
- /package/dist/{runbook-YVBG2QK3.js.map → runbook-AHU77ANQ.js.map} +0 -0
- /package/dist/{scenarios-2SX2NUCD.js.map → scenarios-TU656T2B.js.map} +0 -0
- /package/dist/{schedule-P6F7MLXX.js.map → schedule-DXJI6SYO.js.map} +0 -0
- /package/dist/{session-SZMCZTPE.js.map → session-RUFTJHF4.js.map} +0 -0
- /package/dist/{slack-UDXTPOSW.js.map → slack-M3OKDVMY.js.map} +0 -0
- /package/dist/{spec-YCBBIV27.js.map → spec-5MXEBLYR.js.map} +0 -0
- /package/dist/{src-DEGBASCD.js.map → src-2X5OQRPJ.js.map} +0 -0
- /package/dist/{src-DY7GLRO2.js.map → src-72EFBA2R.js.map} +0 -0
- /package/dist/{src-NG7DRE5A.js.map → src-KH6WSBJV.js.map} +0 -0
- /package/dist/{start-ZYZSORPY.js.map → start-PDYBRB5T.js.map} +0 -0
- /package/dist/{status-ESIG6A7W.js.map → status-VMVPVCDA.js.map} +0 -0
- /package/dist/{tag-3K5Y25AR.js.map → tag-7KTDLPVU.js.map} +0 -0
- /package/dist/{task-JLNX7O3M.js.map → task-QLFYZNKR.js.map} +0 -0
- /package/dist/{teams-F4IU3EXE.js.map → teams-Y7BXCY6P.js.map} +0 -0
- /package/dist/{tickets-NBL5WACL.js.map → tickets-CQDJDNPY.js.map} +0 -0
- /package/dist/{trace-ZKYAI5JF.js.map → trace-QDORWXYX.js.map} +0 -0
- /package/dist/{triage-5NWCREUM.js.map → triage-GY7M3UGG.js.map} +0 -0
- /package/dist/{trigger-KXYYY5IR.js.map → trigger-DLFAORX4.js.map} +0 -0
- /package/dist/{update-check-Q2URVJLC.js.map → update-check-ES6XQ7OF.js.map} +0 -0
- /package/dist/{upgrade-4XSASC7U.js.map → upgrade-WKEOW5GS.js.map} +0 -0
- /package/dist/{usage-UY7VZYVY.js.map → usage-E6FDTR3W.js.map} +0 -0
- /package/dist/{utilities-53NXNLA7.js.map → utilities-4Z6YX3L5.js.map} +0 -0
- /package/dist/{visual-IJAT7X7D.js.map → visual-TA6LPVDJ.js.map} +0 -0
- /package/dist/{workflow-cache-FP6MKLVR.js.map → workflow-cache-MNLEMRMM.js.map} +0 -0
- /package/dist/{workflow-cache-convergence-resolve-HS5KO7US.js.map → workflow-cache-convergence-resolve-G5HJM6MF.js.map} +0 -0
- /package/dist/{workflow-debug-EM55H2QE.js.map → workflow-debug-TNBUGSBK.js.map} +0 -0
- /package/dist/{workflow-feedback-GNWNWVHH.js.map → workflow-feedback-G2ZXAUGI.js.map} +0 -0
- /package/dist/{workflow-fork-M5AQWST7.js.map → workflow-fork-6HHOMC2D.js.map} +0 -0
- /package/dist/{workflow-promotion-HYULZDYL.js.map → workflow-promotion-RG7L6JZT.js.map} +0 -0
- /package/dist/{workflow-proposals-EN327FSE.js.map → workflow-proposals-ZNF2F3UE.js.map} +0 -0
- /package/dist/{workflow-revisions-ZMTVNWRW.js.map → workflow-revisions-TP64Z6FO.js.map} +0 -0
- /package/dist/{workflow-status-FNAJG34W.js.map → workflow-status-5RG3JX56.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli-helpers.ts"],"sourcesContent":["/**\n * Shared CLI helpers for superadmin management commands (knobs, feature-flags).\n */\n\nimport { readFileSync } from 'node:fs';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { getCanaryTmpDir } from '@chatsdet/tmp';\nimport { VALID_MACRO_NAMES } from '@chatsdet/types';\nimport { getArgValue } from './auth.js';\nimport { apiFetch, exitOnFailure, isTerminalFailure } from './api-fetch.js';\nimport { decodeJwtPayload, isSuperadminToken } from './jwt.js';\n\n/**\n * Canonical hyphenated UUID, matching `isUuid` in `@chatsdet/ids`.\n * Kept as a RegExp for existing CLI callers using `UUID_RE.test()`.\n */\nexport const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport type LifecycleStage = 'active' | 'baking' | 'internal' | 'deprecated' | 'ready_for_cleanup';\n\n/** Stages knobs may use — `baking` (the oven) and `internal` are flag-only. */\nexport const KNOB_LIFECYCLE_STAGES: LifecycleStage[] = [\n 'active',\n 'deprecated',\n 'ready_for_cleanup',\n];\n\nexport function toLifecycleLabel(stage: LifecycleStage): string {\n switch (stage) {\n case 'baking':\n return 'baking';\n case 'internal':\n return 'internal';\n case 'deprecated':\n return 'deprecated';\n case 'ready_for_cleanup':\n return 'ready_for_cleanup';\n default:\n return 'active';\n }\n}\n\nexport function parseLifecycleStage(\n argv: string[],\n allowedStages: LifecycleStage[] = [\n 'active',\n 'baking',\n 'internal',\n 'deprecated',\n 'ready_for_cleanup',\n ]\n): LifecycleStage {\n const stage = getArgValue(argv, '--stage');\n if (!stage || !allowedStages.includes(stage as LifecycleStage)) {\n console.error(`Error: --stage is required and must be one of: ${allowedStages.join(', ')}`);\n process.exit(1);\n }\n return stage as LifecycleStage;\n}\n\n/**\n * Target-org id for superadmin cross-org commands (feature-flag, product,\n * account, task). `--org` is now the global identity selector — which of *your*\n * logged-in orgs to act as — so cross-org targeting uses `--target-org`.\n *\n * The two flags are mutually exclusive by design: a bare `--org` naming an org\n * you aren't logged into is already rejected by identity resolution (with a hint\n * to use `--target-org`); if it names one you ARE logged into, we stop here so a\n * superadmin action never silently runs under the wrong identity. Either way the\n * fix is the same — use `--target-org`.\n */\nexport function getTargetOrg(argv: string[]): string | undefined {\n const target = getArgValue(argv, '--target-org');\n if (target) return target;\n if (getArgValue(argv, '--org')) {\n console.error(\n 'Error: --org selects which of your logged-in orgs to act as. To target a ' +\n 'different org for this command, use --target-org.'\n );\n process.exit(1);\n }\n return undefined;\n}\n\n/** Drop exactly one trailing `\\n` or `\\r\\n`; any other trailing whitespace is part of the value. */\nexport function stripOneTrailingNewline(raw: string): string {\n if (raw.endsWith('\\r\\n')) return raw.slice(0, -2);\n if (raw.endsWith('\\n')) return raw.slice(0, -1);\n return raw;\n}\n\n/**\n * Resolve a `<text|@file>` flag value: `@path` reads that file, anything else\n * is the text itself. An unreadable file prints `Error reading <path>` and\n * exits 1 rather than surfacing a stack trace.\n */\nexport function readTextOrFile(value: string): string {\n if (!value.startsWith('@')) return value;\n const file = value.slice(1);\n try {\n return readFileSync(file, 'utf8');\n } catch (err) {\n console.error(`Error reading ${file}: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n}\n\n/**\n * Connecting an integration from the CLI is admin-only (the API answers\n * `ADMIN_REQUIRED` to anyone else), so a member is told before a browser opens\n * or a question is asked. The role is the one `GET /cli-login/orgs` reports for\n * the token's org (as `cofactor orgs list` shows it); a superadmin passes, as on\n * the API. `integration` is the `cofactor` subcommand (`slack`, `github`).\n */\nexport async function requireOrgAdmin(\n apiUrl: string,\n token: string,\n integration: string,\n action: string\n): Promise<void> {\n if (isSuperadminToken(token)) return;\n const orgId = decodeJwtPayload(token)?.org_id;\n const result = await apiRequest<{\n ok: boolean;\n error?: string;\n organizations?: Array<{ id: string; name: string; role: string }>;\n }>(apiUrl, token, 'GET', '/cli-login/orgs');\n const die = (message: string): never => {\n console.error(`Error: ${message}`);\n return process.exit(1);\n };\n if (!result.ok) die(result.error ?? 'failed to read your role in this organization');\n const org = result.organizations?.find((o) => o.id === orgId);\n if (org?.role !== 'admin') {\n const label = integration[0].toUpperCase() + integration.slice(1);\n die(\n `Only organization admins can ${action} ${label}. Ask an admin of ${org?.name ?? 'this organization'} to run \\`cofactor ${integration} ${action}\\`.`\n );\n }\n}\n\n/** All of stdin as UTF-8 text (Node and Bun alike). */\nexport async function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));\n return Buffer.concat(chunks).toString('utf-8');\n}\n\nexport async function apiRequest<T extends { ok: boolean; error?: string }>(\n apiUrl: string,\n token: string,\n method: string,\n path: string,\n body?: Record<string, unknown>,\n options?: { timeoutMs?: number }\n): Promise<T> {\n const result = await apiFetch(`${apiUrl}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n 'User-Agent': 'Cofactor-CLI',\n },\n token,\n ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n ...(body ? { body: JSON.stringify(body) } : {}),\n });\n\n if (!result.ok) {\n const { failure } = result;\n // Terminal kinds (auth/proxy/TLS) surface the full diagnostic and exit;\n // http-error falls through so the caller can pretty-print structured\n // user errors (unresolved vars, invalid macros, etc.).\n if (isTerminalFailure(failure)) exitOnFailure(failure);\n const text = failure.body ?? '';\n let errorMessage = failure.message;\n let parsed: Record<string, unknown> | null = null;\n try {\n const data = JSON.parse(text);\n if (data && typeof data === 'object') {\n parsed = data as Record<string, unknown>;\n if (typeof parsed.error === 'string') errorMessage = parsed.error;\n }\n } catch {\n /* keep failure.message */\n }\n return { ...parsed, ok: false, error: errorMessage } as T;\n }\n\n try {\n return (await result.response.json()) as T;\n } catch {\n return { ok: false, error: `Invalid JSON response (${result.response.status})` } as T;\n }\n}\n\n/** One environment option carried by the workflow-detail payload. */\nexport type WorkflowEnvOption = {\n id: string;\n name: string;\n type: string;\n isDefault: boolean;\n environmentKindId?: string | null;\n environmentKindName?: string | null;\n};\n\n/**\n * Fetch the environments available on a workflow's property (from the\n * workflow-detail payload). Shared by `workflow run --environment` and\n * `workflow patch --default-environment` so both resolve names identically.\n */\nexport async function fetchWorkflowEnvironments(\n apiUrl: string,\n token: string,\n workflowId: string\n): Promise<WorkflowEnvOption[]> {\n const res = await apiRequest<{\n ok: boolean;\n error?: string;\n workflow?: { environments?: WorkflowEnvOption[] };\n }>(apiUrl, token, 'GET', `/workflows/${workflowId}`);\n return res.workflow?.environments ?? [];\n}\n\n/**\n * Resolve a `--environment` argument (UUID or case-insensitive name) to an\n * environment id against the flow's property. Exits with an actionable error\n * listing the known environments when no match is found.\n */\nexport function resolveEnvironmentByNameOrId(envs: WorkflowEnvOption[], nameOrId: string): string {\n const match =\n envs.find((e) => e.id === nameOrId) ??\n envs.find((e) => e.name.toLowerCase() === nameOrId.toLowerCase()) ??\n envs.find((e) => e.environmentKindName?.toLowerCase() === nameOrId.toLowerCase());\n if (match) return match.id;\n // A bare UUID that isn't in the (possibly empty) known list may still be a\n // valid env the server will accept — e.g. a login-less flow with no resolved\n // property scope being pointed at a sandbox env. Pass it through and let the\n // server be the authority; only hard-fail on an unresolvable *name*.\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(nameOrId)) {\n return nameOrId;\n }\n console.error(\n `Error: environment \"${nameOrId}\" not found on this flow's property. Known: ${\n envs.map((e) => `${e.name} (${e.type})`).join(', ') || '(none)'\n }`\n );\n process.exit(1);\n}\n\ntype UnresolvedRef = {\n nodeId?: string;\n nodeType?: string;\n field?: string;\n variable: string;\n};\n\n/**\n * Render a structured `userError` response from the workflow API into a\n * multi-line, actionable message. Recognizes `WORKFLOW_UNRESOLVED_VARIABLES`\n * and falls back to `✖ {code}: {message}` for other codes. Returns `null` if\n * the response body isn't a recognized structured error.\n */\nexport function renderWorkflowUserError(result: Record<string, unknown>): string | null {\n const code = typeof result.code === 'string' ? result.code : null;\n const message = typeof result.error === 'string' ? result.error : null;\n if (!code) return null;\n\n if (code === 'WORKFLOW_VALIDATION_FAILED') {\n type ValidationIssue = {\n nodeId?: string | null;\n nodeType?: string | null;\n field?: string;\n message?: string;\n code?: string;\n severity?: 'error' | 'warning';\n };\n const issues = Array.isArray(result.issues) ? (result.issues as ValidationIssue[]) : [];\n const errors = issues.filter((i) => (i.severity ?? 'error') === 'error');\n const warnings = issues.filter((i) => i.severity === 'warning');\n\n const lines: string[] = [\n `✖ Validation failed (${errors.length} error${errors.length === 1 ? '' : 's'}` +\n (warnings.length > 0\n ? `, ${warnings.length} warning${warnings.length === 1 ? '' : 's'}`\n : '') +\n ')',\n ];\n if (message) lines.push(` ${message}`);\n\n // Group by nodeId (null = flow-level).\n const byNode = new Map<string, ValidationIssue[]>();\n for (const issue of issues) {\n const key = issue.nodeId ?? '__flow__';\n const arr = byNode.get(key) ?? [];\n arr.push(issue);\n byNode.set(key, arr);\n }\n for (const [nodeKey, nodeIssues] of byNode) {\n const heading =\n nodeKey === '__flow__'\n ? 'Flow'\n : `Node ${nodeKey}${nodeIssues[0]?.nodeType ? ` (${nodeIssues[0].nodeType})` : ''}`;\n lines.push(` ${heading}:`);\n for (const issue of nodeIssues) {\n const sev = issue.severity === 'warning' ? '⚠' : '•';\n const field = issue.field ? `${issue.field} — ` : '';\n lines.push(` ${sev} ${field}${issue.message ?? ''}`);\n }\n }\n return lines.join('\\n');\n }\n\n if (code === 'WORKFLOW_UNRESOLVED_VARIABLES') {\n const lines: string[] = [`✖ ${code}`];\n if (message) lines.push(` ${message}`);\n const refs = Array.isArray(result.refs) ? (result.refs as UnresolvedRef[]) : [];\n const variables = Array.isArray(result.variables)\n ? (result.variables as string[])\n : refs.map((r) => r.variable);\n\n if (refs.length > 0) {\n lines.push(' Unresolved references:');\n for (const ref of refs) {\n const loc = ref.field && ref.nodeId ? ` (node ${ref.nodeId}, ${ref.field})` : '';\n lines.push(` • $var.${ref.variable}${loc}`);\n }\n } else if (variables.length > 0) {\n lines.push(' Unresolved:');\n for (const v of variables) lines.push(` • $var.${v}`);\n }\n\n const macroHints = variables.filter((v) => VALID_MACRO_NAMES.has(v.toUpperCase()));\n if (macroHints.length > 0) {\n lines.push(' Hint: these look like macro names, not variables:');\n for (const v of macroHints) {\n lines.push(` $var.${v} → $${v.toUpperCase()}()`);\n }\n }\n return lines.join('\\n');\n }\n\n if (code === 'WORKFLOW_INVALID_INPUT_VALUES') {\n const lines: string[] = [`✖ ${code}`];\n if (message) lines.push(` ${message}`);\n const issues = Array.isArray(result.issues)\n ? (result.issues as Array<{\n key?: string;\n value?: string;\n reason?: string;\n variables?: string[];\n }>)\n : [];\n for (const issue of issues) {\n const key = issue.key ?? '?';\n const value = issue.value ?? '';\n if (issue.reason === 'self_referential') {\n lines.push(` • ${key}: self-referential → ${value}`);\n lines.push(` Use a literal or point at a different upstream variable.`);\n } else if (issue.reason === 'macro_name_used_as_var') {\n lines.push(` • ${key}: macro name used as $var → ${value}`);\n for (const v of issue.variables ?? []) {\n lines.push(` $var.${v} → $${v.toUpperCase()}()`);\n }\n } else {\n lines.push(` • ${key}: ${issue.reason ?? 'invalid'} → ${value}`);\n }\n }\n return lines.join('\\n');\n }\n\n if (code === 'WORKFLOW_INVALID_MACRO') {\n const lines: string[] = [`✖ ${code}`];\n if (message) lines.push(` ${message}`);\n const invalid = Array.isArray(result.invalid) ? (result.invalid as string[]) : [];\n const valid = Array.isArray(result.valid) ? (result.valid as string[]) : [];\n if (invalid.length > 0) {\n lines.push(` Invalid macro(s): ${invalid.map((n) => `$${n}()`).join(', ')}`);\n }\n if (valid.length > 0) {\n lines.push(` Valid macros: ${valid.map((n) => `$${n}()`).join(', ')}`);\n }\n return lines.join('\\n');\n }\n\n return `✖ ${code}${message ? `: ${message}` : ''}`;\n}\n\nexport async function downloadStorageState(opts: {\n apiUrl: string;\n token: string;\n propertyId: string;\n credentialId: string;\n prefix?: string;\n}): Promise<string | undefined> {\n const tmpFile = path.join(getCanaryTmpDir(), `${opts.prefix ?? 'canary-ss'}-${Date.now()}.json`);\n try {\n const res = await fetch(\n `${opts.apiUrl}/org/properties/${opts.propertyId}/credentials/${opts.credentialId}/storage-state/download`,\n {\n headers: { Authorization: `Bearer ${opts.token}` },\n redirect: 'follow',\n }\n );\n if (res.ok) {\n const body = await res.text();\n await fs.writeFile(tmpFile, body, 'utf-8');\n return tmpFile;\n }\n } catch {\n // Caller handles missing storage state\n }\n return undefined;\n}\n\n/* ── Credential selection ─────────────────────────────────────────────── */\n\nexport interface CredentialListItem {\n id: string;\n name: string;\n propertyId: string;\n propertyName?: string;\n propertyBaseUrl?: string;\n environmentId?: string | null;\n environmentName?: string | null;\n storageStateS3Key?: string | null;\n isDefault?: boolean;\n isEphemeral?: boolean;\n}\n\n/**\n * Fetch org credentials and let the user pick one interactively.\n *\n * @param credentialArg - Credential name or ID to auto-select, or undefined for interactive\n * @returns The selected credential, or null if none found / invalid selection\n */\nexport async function selectCredential(\n apiUrl: string,\n token: string,\n credentialArg?: string\n): Promise<CredentialListItem | null> {\n const credentials = await fetchList<CredentialListItem>(\n apiUrl,\n token,\n '/org/credentials',\n 'items'\n );\n\n if (credentials.length === 0) {\n console.error('No credentials found. Create one first in the web app.');\n return null;\n }\n\n if (credentialArg) {\n const match = credentials.find(\n (c) => c.id === credentialArg || c.name.toLowerCase() === credentialArg.toLowerCase()\n );\n if (!match) {\n console.error(`Credential \"${credentialArg}\" not found.`);\n console.error('Available credentials:');\n for (const c of credentials) {\n const env = c.environmentName ? ` — ${c.environmentName}` : '';\n const baseUrl = c.propertyBaseUrl ? ` — ${c.propertyBaseUrl}` : '';\n console.error(` - ${c.name} [${c.propertyName ?? c.propertyId}${env}${baseUrl}]`);\n }\n return null;\n }\n return match;\n }\n\n // Interactive selection\n console.log('\\nSelect a credential:\\n');\n const labels = credentials.map((c) => {\n const property = c.propertyName ?? c.propertyId;\n const env = c.environmentName ? ` — ${c.environmentName}` : '';\n const baseUrl = c.propertyBaseUrl ? ` — ${c.propertyBaseUrl}` : '';\n return `${c.name} [${property}${env}${baseUrl}]`;\n });\n\n const readline = await import('node:readline');\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const answer = await new Promise<string>((resolve) => {\n for (let i = 0; i < labels.length; i++) {\n console.log(` ${i + 1}. ${labels[i]}`);\n }\n rl.question('\\nEnter number: ', (ans) => {\n rl.close();\n resolve(ans.trim());\n });\n });\n\n const idx = parseInt(answer, 10) - 1;\n if (isNaN(idx) || idx < 0 || idx >= credentials.length) {\n console.error('Invalid selection.');\n return null;\n }\n\n return credentials[idx];\n}\n\nexport type CredentialDetail = {\n id: string;\n name: string;\n authProvider?: string;\n /** Resolved login start URL (environment URL + relative login path) */\n loginUrl?: string | null;\n loginInstructions?: string | null;\n sessionVerificationGuidance?: string | null;\n data?: {\n username?: string;\n password?: string;\n email?: string;\n user?: string;\n mfaSecret?: string;\n apiKey?: string;\n customHeaders?: Record<string, string>;\n [key: string]: unknown;\n } | null;\n};\n\nexport async function fetchCredentialDetail(\n apiUrl: string,\n token: string,\n propertyId: string,\n credId: string\n): Promise<CredentialDetail | null> {\n const result = await apiRequest<{ ok: boolean; credential?: CredentialDetail; error?: string }>(\n apiUrl,\n token,\n 'GET',\n `/org/properties/${propertyId}/credentials/${credId}`\n );\n if (!result.ok || !result.credential) return null;\n return result.credential;\n}\n\n/**\n * Non-interactive credential lookup by id or case-insensitive name, narrowed by\n * application (id or case-insensitive name) when several match. Throws on none or ambiguous.\n */\nexport function findCredential(\n list: CredentialListItem[],\n ref: string,\n application?: string\n): CredentialListItem {\n const lower = ref.toLowerCase();\n let matches = list.filter((c) => c.id === ref || c.name.toLowerCase() === lower);\n if (matches.length === 0) throw new Error(`Credential \"${ref}\" not found.`);\n if (matches.length === 1) return matches[0]!;\n if (!application) {\n const options = matches.map((c) => ` - ${c.id} (${c.propertyName ?? c.propertyId})`);\n throw new Error(\n [`Multiple credentials match \"${ref}\". Pass --application to disambiguate.`, ...options].join(\n '\\n'\n )\n );\n }\n const app = application.toLowerCase();\n matches = matches.filter((c) => c.propertyId === application || c.propertyName?.toLowerCase() === app);\n if (matches.length === 0) {\n throw new Error(`Credential \"${ref}\" found, but none match application \"${application}\".`);\n }\n if (matches.length > 1) {\n throw new Error(`Multiple credentials match \"${ref}\" on application \"${application}\".`);\n }\n return matches[0]!;\n}\n\n/** The login identifier of a credential: username, else email, else user. */\nexport function credentialUsername(data: NonNullable<CredentialDetail['data']>): string | undefined {\n return data.username ?? data.email ?? data.user;\n}\n\n/**\n * Resolve a credential name or id to its UUID.\n *\n * The server runs `extractUuid` on `credentialId`, so a bare name is rejected\n * with an opaque invalid-id error. Resolving here is what makes\n * `--credential \"Superadmin User\"` mean what it looks like it means.\n */\nexport async function resolveCredentialId(\n arg: string,\n propertyId: string | undefined,\n apiUrl: string,\n token: string\n): Promise<string> {\n const all = await fetchList<CredentialListItem>(apiUrl, token, '/org/credentials', 'items');\n\n const byId = all.find((c) => c.id === arg);\n if (byId) return byId.id;\n\n // Narrow to the target's application when one is known. The same credential\n // name routinely exists on several applications, so match within the\n // selected application.\n const credentials = propertyId ? all.filter((c) => c.propertyId === propertyId) : all;\n\n const byName = credentials.filter((c) => c.name.toLowerCase() === arg.toLowerCase());\n if (byName.length === 1) return byName[0]!.id;\n if (byName.length > 1) {\n console.error(\n `Error: Multiple credentials match \"${arg}\"` +\n (propertyId ? ' on this application.' : '. Pass --application to narrow, or use the id.')\n );\n for (const c of byName) console.error(` - ${c.name} (${c.id}) env=${c.environmentName ?? ''}`);\n process.exit(1);\n }\n\n console.error(`Error: Credential \"${arg}\" not found.`);\n if (credentials.length > 0) {\n console.error('Available credentials:');\n for (const c of credentials) console.error(` - ${c.name} (${c.id})`);\n }\n process.exit(1);\n}\n\n/* ── Property selection ──────────────────────────────────────────────── */\n\ninterface PropertyListItem {\n id: string;\n name: string;\n baseUrl: string;\n}\n\nexport async function fetchProperties(apiUrl: string, token: string): Promise<PropertyListItem[]> {\n return fetchList<PropertyListItem>(apiUrl, token, '/org/properties', 'items');\n}\n\n/**\n * Read the application/property selector flag. `--application` is the user-facing\n * name; `--property` is kept as a backwards-compat alias (read second). Internally\n * this is still a \"property\" — the rename is cosmetic.\n */\nexport function getApplicationArg(argv: string[]): string | undefined {\n return getArgValue(argv, '--application') ?? getArgValue(argv, '--property');\n}\n\n/**\n * Return the first positional argument, excluding values consumed by the given\n * `--flag value` pairs.\n *\n * The obvious `argv.find(a => !a.startsWith('-'))` returns the FIRST FLAG VALUE\n * whenever a flag precedes the positional (`--application Acme my-target`),\n * which is the normal shape for every application-scoped command.\n */\nexport function getPositionalArg(\n argv: string[],\n flagsWithValues: string[]\n): string | undefined {\n return getPositionalArgs(argv, flagsWithValues).find((a) => !a.startsWith('-'));\n}\n\n/**\n * Every word that is not a `--flag` or the value of one of the given\n * `--flag value` pairs, in order (a `--flag=value` is one `--` token, so it is\n * skipped whole). Single-dash words are kept, because they can be free text\n * (`-5% latency`). Use this, not `argv.filter(a => !a.startsWith('--'))`, which\n * drops each flag but keeps its value, wherever positional words are joined\n * into free text such as a comment.\n */\nexport function getPositionalArgs(argv: string[], flagsWithValues: string[]): string[] {\n const out: string[] = [];\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!;\n if (flagsWithValues.includes(a)) {\n i++;\n continue;\n }\n if (!a.startsWith('--')) out.push(a);\n }\n return out;\n}\n\n/** Global `--flag value` pairs a `guide` subcommand may be given (every command accepts them). */\nconst GUIDE_VALUE_FLAGS = ['--env', '--api-url', '--token', '--org'];\n\n/**\n * The section slug of a `<command> guide [section]` invocation. Skips global\n * flag values, so `guide --env production` prints the whole guide instead of\n * failing on an unknown section named \"production\".\n */\nexport function getGuideSectionArg(argv: string[]): string | undefined {\n return getPositionalArg(argv, GUIDE_VALUE_FLAGS);\n}\n\n/**\n * Read the application/property UUID flag. `--application-id` is the user-facing\n * name; `--property-id` is kept as a backwards-compat alias.\n */\nexport function getApplicationIdArg(argv: string[]): string | undefined {\n return getArgValue(argv, '--application-id') ?? getArgValue(argv, '--property-id');\n}\n\nexport async function selectProperty(\n apiUrl: string,\n token: string,\n hint?: string\n): Promise<PropertyListItem | null> {\n const properties = await fetchProperties(apiUrl, token);\n\n if (properties.length === 0) {\n console.error('No applications found. Create one first in the web app.');\n return null;\n }\n\n if (hint) {\n const match = properties.find(\n (p) => p.id === hint || p.name.toLowerCase() === hint.toLowerCase()\n );\n if (!match) {\n console.error(`Application \"${hint}\" not found.`);\n console.error('Available applications:');\n for (const p of properties) {\n console.error(` - ${p.name} (${p.baseUrl})`);\n }\n return null;\n }\n return match;\n }\n\n if (properties.length === 1) {\n // stderr: stdout may be carrying `--json` output.\n console.error(`Auto-selected application: ${properties[0].name}`);\n return properties[0];\n }\n\n if (!process.stdin.isTTY) {\n console.error('Multiple applications and no --application given. Pass one of:');\n for (const p of properties) {\n console.error(` --application \"${p.name}\" (${p.baseUrl})`);\n }\n return null;\n }\n\n return promptChoice(\n 'Select an application:',\n properties.map((p) => ({ label: `${p.name} — ${p.baseUrl}`, value: p }))\n );\n}\n\n/* ── Interactive prompt helpers ──────────────────────────────────────── */\n\n/**\n * Neither prompt waits on a stdin that is not a terminal: an agent or a script\n * piping the CLI would otherwise hang forever on a question nobody can answer.\n */\nfunction failNonInteractive(question: string): never {\n console.error(`Cannot prompt \"${question}\": stdin is not a terminal. Pass the value explicitly.`);\n process.exit(1);\n}\n\nexport async function promptInput(question: string, defaultValue?: string): Promise<string> {\n if (!process.stdin.isTTY) {\n if (defaultValue !== undefined) return defaultValue;\n failNonInteractive(question);\n }\n const readline = await import('node:readline');\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const prompt = defaultValue ? `${question} [${defaultValue}]: ` : `${question}: `;\n const answer = await new Promise<string>((resolve) => {\n rl.question(prompt, (ans) => {\n rl.close();\n resolve(ans.trim());\n });\n });\n return answer || defaultValue || '';\n}\n\nexport async function promptChoice<T>(\n question: string,\n options: Array<{ label: string; value: T }>\n): Promise<T | null> {\n if (!process.stdin.isTTY) {\n for (const option of options) console.error(` - ${option.label}`);\n failNonInteractive(question);\n }\n console.log(`\\n${question}\\n`);\n for (let i = 0; i < options.length; i++) {\n console.log(` ${i + 1}. ${options[i].label}`);\n }\n const readline = await import('node:readline');\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const answer = await new Promise<string>((resolve) => {\n rl.question('\\nEnter number: ', (ans) => {\n rl.close();\n resolve(ans.trim());\n });\n });\n\n const idx = parseInt(answer, 10) - 1;\n if (isNaN(idx) || idx < 0 || idx >= options.length) {\n console.error('Invalid selection.');\n return null;\n }\n return options[idx].value;\n}\n\nexport async function uploadStorageState(opts: {\n apiUrl: string;\n token: string;\n propertyId: string;\n credentialId: string;\n storageState: unknown;\n}): Promise<{ ok: boolean; s3Key?: string; error?: string }> {\n const result = await apiFetch(\n `${opts.apiUrl}/org/properties/${opts.propertyId}/credentials/${opts.credentialId}/storage-state/upload`,\n {\n method: 'PUT',\n headers: {\n Authorization: `Bearer ${opts.token}`,\n 'Content-Type': 'application/json',\n },\n token: opts.token,\n body: JSON.stringify({ storageState: opts.storageState }),\n }\n );\n\n if (!result.ok) exitOnFailure(result.failure);\n\n return (await result.response.json()) as { ok: boolean; s3Key?: string; error?: string };\n}\n\n/* ── Repeatable-flag collection ──────────────────────────────────────── */\n\n/**\n * Collect every value for a repeatable flag (`getArgValue` only returns the\n * first). Accepts both `--key value` and `--key=value` forms.\n *\n * A `--key` with no usable value — missing, looking like the next flag (a\n * bare `-`-leading token), or blank after trimming — exits 1 naming the flag\n * rather than being silently dropped: `--layer A --layer` must not quietly\n * become one layer instead of two, and `--layer \"\"` must not push an empty\n * layer. The single validating implementation for the whole CLI — previously\n * duplicated (leniently, with the dangling-value bug) in `issue-create.ts`,\n * `automation-shared.ts`, and `sandbox.ts`.\n */\nexport function getArgValues(argv: string[], key: string): string[] {\n const out: string[] = [];\n const eqPrefix = `${key}=`;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === key) {\n const value = argv[i + 1];\n if (value === undefined || value.startsWith('-') || value.trim().length === 0) {\n console.error(`Error: ${key} requires a value.`);\n process.exit(1);\n }\n out.push(value);\n } else if (arg?.startsWith(eqPrefix)) {\n const value = arg.slice(eqPrefix.length);\n if (value.trim().length === 0) {\n console.error(`Error: ${key} requires a value.`);\n process.exit(1);\n }\n out.push(value);\n }\n }\n return out;\n}\n\n/**\n * `getArgValue` (auth.ts) returns whatever token follows the flag, including\n * another flag — `--name --failure-mode continue` would create a suite\n * literally named \"--failure-mode\", and `!body.name.trim()` never catches it\n * because the string isn't blank. Same validation `getArgValues` applies to\n * repeatable flags, scoped to these three scalar write flags rather than\n * changing `getArgValue` itself, which the whole CLI depends on staying\n * permissive.\n *\n * Checks the `--key=value` form first, returning its suffix verbatim — like\n * the hoisted `getArgValues`, that branch skips the leading-`-` check, so\n * `--description=\"- covers the checkout path\"` is the escape hatch for a\n * value that legitimately starts with `-` (the bare `--key value` form\n * rejects a leading `-` to catch a swallowed flag, which otherwise makes such\n * a value unrepresentable).\n *\n * @param opts.allowEmpty Accept a blank value (after trimming) instead of\n * erroring. Use only when blank has domain meaning, such as clearing a\n * description or sending an empty directory-area list.\n */\nexport function getScalarArgValue(\n argv: string[],\n key: string,\n opts?: { allowEmpty: boolean }\n): string | undefined {\n const eqPrefix = `${key}=`;\n const eqToken = argv.find((a) => a.startsWith(eqPrefix));\n if (eqToken !== undefined) {\n const value = eqToken.slice(eqPrefix.length);\n if (value.trim().length === 0 && !opts?.allowEmpty) {\n console.error(`Error: ${key} requires a value.`);\n process.exit(1);\n }\n return value;\n }\n\n const value = getArgValue(argv, key);\n if (value === undefined) return undefined;\n const blank = value.trim().length === 0;\n if (value.startsWith('-') || (blank && !opts?.allowEmpty)) {\n console.error(`Error: ${key} requires a value.`);\n process.exit(1);\n }\n return value;\n}\n\n/* ── Test suite selection ────────────────────────────────────────────── */\n\n/** One suite as returned by `GET /test-suites` — enough to resolve `<name|id>`. */\nexport type SuiteRef = {\n id: string;\n name: string;\n};\n\n/**\n * Resolve a `--suite <name|id>` (or bare `<id|name>` positional) argument\n * against `GET /test-suites`. An exact id match wins; otherwise falls back to\n * a case-insensitive name match. Lists the available suites on a miss.\n *\n * Shared by `test-suite`'s create/update/delete/members/set-members verbs and\n * `remote-test`'s `--suite` run flag, so suite name resolution has exactly one\n * implementation.\n */\nexport async function resolveTestSuite(\n arg: string,\n apiUrl: string,\n token: string\n): Promise<SuiteRef> {\n const res = await apiRequest<{ ok: boolean; error?: string; data?: SuiteRef[] }>(\n apiUrl,\n token,\n 'GET',\n '/test-suites'\n );\n if (!res.ok) {\n console.error(`Error: ${res.error ?? 'Failed to list test suites'}`);\n process.exit(1);\n }\n const suites = res.data ?? [];\n const match =\n suites.find((s) => s.id === arg) ?? suites.find((s) => s.name.toLowerCase() === arg.toLowerCase());\n if (!match) {\n // `arg` echoes the user's own --suite entry and `s.name` is server data —\n // write straight to stderr rather than through console.error, which the\n // `cofactor` binary brand-rewrites (a suite named \"Canary Smoke\" would\n // print as \"Cofactor Smoke\").\n process.stderr.write(`Error: Test suite \"${arg}\" not found.\\n`);\n if (suites.length > 0) {\n console.error('Available suites:');\n for (const s of suites) process.stderr.write(` - ${s.name} (${s.id})\\n`);\n }\n process.exit(1);\n }\n return match;\n}\n\nexport async function fetchList<T>(\n apiUrl: string,\n token: string,\n path: string,\n listKey: string\n): Promise<T[]> {\n const result = await apiFetch(`${apiUrl}${path}`, {\n headers: { Authorization: `Bearer ${token}` },\n token,\n });\n\n if (!result.ok) exitOnFailure(result.failure);\n\n const json = (await result.response.json()) as Record<string, unknown>;\n\n if (!json.ok) {\n console.error(`Error: ${json.error}`);\n process.exit(1);\n }\n\n return (json[listKey] as T[]) ?? [];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAIA,SAAS,oBAAoB;AAC7B,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,aAAa;AAWb,IAAM,UAAU;AAKhB,IAAM,wBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,iBAAiB,OAA+B;AAC9D,UAAQ,OAAO;AAAA,IACb,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAEO,SAAS,oBACd,MACA,gBAAkC;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GACgB;AAChB,QAAM,QAAQ,YAAY,MAAM,SAAS;AACzC,MAAI,CAAC,SAAS,CAAC,cAAc,SAAS,KAAuB,GAAG;AAC9D,YAAQ,MAAM,kDAAkD,cAAc,KAAK,IAAI,CAAC,EAAE;AAC1F,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,SAAO;AACT;AAaO,SAAS,aAAa,MAAoC;AAC/D,QAAM,SAAS,YAAY,MAAM,cAAc;AAC/C,MAAI,OAAQ,QAAO;AACnB,MAAI,YAAY,MAAM,OAAO,GAAG;AAC9B,YAAQ;AAAA,MACN;AAAA,IAEF;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,SAAO;AACT;AAGO,SAAS,wBAAwB,KAAqB;AAC3D,MAAI,IAAI,SAAS,MAAM,EAAG,QAAO,IAAI,MAAM,GAAG,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AE,OAAO,GAAG,KAAK,OAAO,KAAK,CAAC,MAAM,EAAE,KAAK,YAAY,MAAM,IAAI,YAAY,CAAC;AACnG,MAAI,CAAC,OAAO;AAKV,YAAQ,OAAO,MAAM,sBAAsB,GAAG;AAAA,CAAgB;AAC9D,QAAI,OAAO,SAAS,GAAG;AACrB,cAAQ,MAAM,mBAAmB;AACjC,iBAAW,KAAK,OAAQ,SAAQ,OAAO,MAAM,OAAO,EAAE,IAAI,KAAK,EAAE,EAAE;AAAA,CAAK;AAAA,IAC1E;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,SAAO;AACT;AAEA,eAAsB,UACpB,QACA,OACAD,OACA,SACc;AACd,QAAM,SAAS,MAAM,SAAS,GAAG,MAAM,GAAGA,KAAI,IAAI;AAAA,IAChD,SAAS,EAAE,eAAe,UAAU,KAAK,GAAG;AAAA,IAC5C;AAAA,EACF,CAAC;AAED,MAAI,CAAC,OAAO,GAAI,eAAc,OAAO,OAAO;AAE5C,QAAM,OAAQ,MAAM,OAAO,SAAS,KAAK;AAEzC,MAAI,CAAC,KAAK,IAAI;AACZ,YAAQ,MAAM,UAAU,KAAK,KAAK,EAAE;AACpC,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,SAAQ,KAAK,OAAO,KAAa,CAAC;AACpC;","names":["path","value"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth.ts","../src/api-fetch.ts","../src/debug.ts","../src/argv.ts","../src/jwt.ts","../src/default-urls.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { readBrandEnv } from './brand.js';\nimport { setActingTarget } from './api-fetch.js';\nimport { DEFAULT_API_URL, DEFAULT_APP_URL } from './default-urls.js';\nimport { isFreeTextFlag, isFreeTextValue } from './argv.js';\n\nexport type StoredAuth = {\n token?: string;\n apiUrl?: string;\n orgId?: string;\n orgName?: string;\n /**\n * The org's vanity app subdomain at login time, when it has one. Cached so\n * printed links land on the org's own host without a lookup per command.\n *\n * May go stale if the org is later renamed; retired labels redirect to the\n * current host, so a stale value costs a redirect rather than a dead link.\n */\n appSubdomain?: string | null;\n /**\n * Which environment this session belongs to (`production` | `dev` | `local` |\n * custom). Purely for display/filtering — `apiUrl` already encodes the env —\n * so the same org can hold a session in more than one environment at once.\n */\n envLabel?: string;\n};\n\n/** Multi-profile auth file format */\ntype MultiProfileAuth = {\n profiles: Record<string, StoredAuth>;\n default: string;\n};\n\n/** Legacy flat format (single profile) */\ntype LegacyAuth = StoredAuth;\n\n/**\n * Resolve where the multi-profile auth file lives. Honors a\n * `CANARY_CONFIG_DIR` / `COFACTOR_CONFIG_DIR` override (for non-standard config\n * locations and tests), else the default `~/.config/canary-cli`.\n */\nfunction getAuthPaths(): { dir: string; file: string } {\n const dir = readBrandEnv('CANARY_CONFIG_DIR') ?? defaultConfigDir();\n return { dir, file: path.join(dir, 'auth.json') };\n}\n\n/** The standard config directory, ignoring any `CANARY_CONFIG_DIR` override. */\nexport function defaultConfigDir(): string {\n return path.join(os.homedir(), '.config', 'canary-cli');\n}\n\n/** The config directory this invocation reads and writes sessions in. */\nexport function activeConfigDir(): string {\n return getAuthPaths().dir;\n}\n\n/* ── Shared argv helpers ─────────────────────────────────────────────── */\n\nexport function getArgValue(argv: string[], key: string): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i];\n if (token === key) return i < argv.length - 1 ? argv[i + 1] : undefined;\n if (token.startsWith(`${key}=`)) return token.slice(key.length + 1);\n }\n return undefined;\n}\n\n/** The flag an argument starts with, without its value: errors must not echo a fused `--token`. */\nfunction flagName(token: string): string {\n return token.trim().split(/[\\s=]/)[0];\n}\n\n/** Global flags that always take a value; a missing value must never fall back to the default profile. */\nexport const GLOBAL_VALUE_FLAGS = ['--org', '--env', '--api-url', '--target-org', '--token'];\n\n/**\n * Reject argv that the flag parser would silently misread, before any command\n * resolves credentials. An ignored `--org` / `--env` quietly retargets the\n * default profile (often prod), so these are hard errors:\n * - one token holding several flags (`\"--org X --env dev\"`, from an unquoted\n * zsh variable, which zsh does not word-split);\n * - a global value flag with no value, or whose value holds another flag.\n * The free-text value of a flag such as `--description` is not checked, so\n * `--description \"--org Acme\"` passes, unless it starts with `--org=`, which\n * getArgValue would read as the selector. zsh drops an empty unquoted `$DESC`, so\n * `--description $DESC $SEL` also passes, with the selector as the description:\n * the argv is identical, and that case is accepted. Errors name the flag only:\n * a fused `--token` would otherwise print the credential.\n */\nexport function assertWellFormedGlobalFlags(argv: string[]): void {\n const refuse = (message: string): never => {\n console.error(`Error: ${message}`);\n process.exit(1);\n };\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i];\n if (isFreeTextValue(argv, i)) {\n // getArgValue reads any `--org=...` word as the selector, even as another flag's value.\n if (token.includes('=') && GLOBAL_VALUE_FLAGS.includes(token.split('=')[0])) {\n refuse(`the value of ${argv[i - 1]} starts with ${flagName(token)}=, which the CLI would read as ${flagName(token)}.`);\n }\n continue;\n }\n if (/^\\s+--/.test(token)) {\n refuse(\n `an argument starting \" ${flagName(token)}\" has leading whitespace, so its flag would be ignored. Remove the leading space.`\n );\n }\n if (!token.startsWith('--')) continue;\n const [name, ...inline] = token.split('=');\n // `--description=x --org A` is free text the user attached with `=`; `--limit=1 --org A` is fused.\n const freeTextInline = inline.length > 0 && isFreeTextFlag(name);\n if (/\\s/.test(name) || (!freeTextInline && /\\s--[\\w-]+/.test(token))) {\n refuse(\n `${flagName(token)} reached the CLI fused with what follows it, as ONE argument, so it would be ignored. ` +\n 'The shell did not split it (zsh does not word-split an unquoted $VAR). ' +\n 'Pass each flag and value as its own argument. If this is the value of another flag, attach it with = ' +\n '(--flag=--org ...) or pass it as its own argument after that flag.'\n );\n }\n if (!GLOBAL_VALUE_FLAGS.includes(name)) continue;\n const value = inline.length > 0 ? inline.join('=') : argv[i + 1];\n if (!value || (inline.length === 0 && value.startsWith('--'))) refuse(`${name} requires a value.`);\n if (/^\\s|\\s--[\\w-]+/.test(value)) {\n refuse(`the value of ${name} holds another flag or leading whitespace; pass each flag and value as its own argument.`);\n }\n }\n}\n\nexport function hasFlag(argv: string[], ...flags: string[]): boolean {\n return flags.some((flag) => argv.includes(flag));\n}\n\n/* ── Environment / profile mapping ───────────────────────────────────── */\n\n/** Map --env values to profile names for multi-profile auth storage */\nexport function envToProfile(env: string): string {\n if (env === 'prod' || env === 'production') return 'production';\n if (env === 'dev') return 'dev';\n if (env === 'local') return 'local';\n return env;\n}\n\nconst VALID_ENVS = ['prod', 'dev', 'local'];\n\n/** Environment URL mappings shared across CLI commands */\nexport const ENV_URLS: Record<string, { api: string; app: string }> = {\n prod: {\n api: DEFAULT_API_URL,\n app: DEFAULT_APP_URL,\n },\n production: {\n api: DEFAULT_API_URL,\n app: DEFAULT_APP_URL,\n },\n dev: {\n api: 'https://api.dev.runcofactor.com',\n app: 'https://app.dev.runcofactor.com',\n },\n local: {\n api: 'http://localhost:3000',\n app: 'http://localhost:5173',\n },\n};\n\n/** Reverse of `ENV_URLS`: the env label (`production`|`dev`|`local`) for an API\n * URL, or `undefined` for a custom URL. Used to tag stored sessions. */\nexport function envLabelForApiUrl(apiUrl: string): string | undefined {\n for (const [key, urls] of Object.entries(ENV_URLS)) {\n if (urls.api === apiUrl) return envToProfile(key);\n }\n return undefined;\n}\n\n/**\n * Storage key for an org's session, scoped by environment so the same org can\n * be logged into prod and dev at once without one clobbering the other\n * (`org-123@dev` vs `org-123@production`).\n */\nexport function orgProfileKey(orgId: string, envLabel?: string): string {\n return envLabel ? `${orgId}@${envLabel}` : orgId;\n}\n\n/**\n * Derive the web-app URL for a given API URL, always on the cofactor domain.\n *\n * Canary is retired as a brand, so anything we print should send people to\n * cofactor even when the session itself was established against a trycanary\n * host (those hosts stay live and keep working — only the printed link moves).\n * localhost is left alone: there is no cofactor equivalent of a dev server.\n */\nexport function resolveAppUrl(apiUrl: string): string {\n const derived = (() => {\n for (const env of Object.values(ENV_URLS)) {\n if (env.api === apiUrl) return env.app;\n }\n // Fallback for custom API URLs: replace \"api.\" at protocol boundary or \"/api\" path\n return apiUrl.replace(/(:\\/\\/)api\\./, '$1app.').replace(/:3000\\b/, ':5173');\n })();\n return derived.replace(/\\btrycanary\\.ai\\b/, 'runcofactor.com');\n}\n\n/**\n * A DNS label, matching the shape the API validates an `app_subdomain` against\n * (and the web app's `TENANT_LABEL_PATTERN`). Keep the two in sync.\n */\nconst TENANT_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n\n/**\n * The app URL to print for a session — the org's own host when it has a vanity\n * subdomain, otherwise the shared one.\n *\n * A link to the shared host is not wrong so much as unhelpful for an org with\n * its own host: the shared host resolves whichever org the browser session\n * happens to be on, which may not be the org the command was run against.\n *\n * A label that isn't a DNS label falls back to the shared host rather than\n * being spliced in. Today the only writer is our own API, which validates it —\n * but `hostname = \"cf/evil.\" + host` does not throw, it silently truncates the\n * host to `cf` and drops our domain entirely, so failing closed is cheap\n * insurance against a link that points somewhere unintended.\n */\nexport function resolveOrgAppUrl(apiUrl: string, appSubdomain?: string | null): string {\n const appUrl = resolveAppUrl(apiUrl);\n if (!appSubdomain || !TENANT_LABEL_PATTERN.test(appSubdomain)) return appUrl;\n\n const url = new URL(appUrl);\n // Only the cofactor app hosts carry per-org subdomains; a localhost or\n // custom host has nowhere to put the label.\n if (!url.hostname.startsWith('app.') || !url.hostname.endsWith('.runcofactor.com')) {\n return appUrl;\n }\n url.hostname = `${appSubdomain}.${url.hostname}`;\n return url.toString().replace(/\\/$/, '');\n}\n\nfunction isMultiProfile(data: unknown): data is MultiProfileAuth {\n return typeof data === 'object' && data !== null && 'profiles' in data;\n}\n\n/** Read the raw auth file and normalize to multi-profile format */\nasync function readAuthFile(configDir?: string): Promise<MultiProfileAuth | null> {\n try {\n const content = await fs.readFile(configDir ? path.join(configDir, 'auth.json') : getAuthPaths().file, 'utf8');\n const data = JSON.parse(content) as unknown;\n\n if (isMultiProfile(data)) {\n return data;\n }\n\n // Legacy flat format — treat as the \"default\" profile\n const legacy = data as LegacyAuth;\n return {\n profiles: { default: legacy },\n default: 'default',\n };\n } catch {\n return null;\n }\n}\n\nexport async function readStoredAuth(profile?: string): Promise<StoredAuth | null> {\n const auth = await readAuthFile();\n if (!auth) return null;\n\n const key = profile ?? auth.default;\n return auth.profiles[key] ?? null;\n}\n\nexport async function readStoredToken(profile?: string): Promise<string | null> {\n const auth = await readStoredAuth(profile);\n return auth?.token ?? null;\n}\n\nexport async function readStoredApiUrl(profile?: string): Promise<string | null> {\n const auth = await readStoredAuth(profile);\n return auth?.apiUrl ?? null;\n}\n\n/** Return all stored tokens across every profile */\nexport async function readAllStoredTokens(): Promise<string[]> {\n const auth = await readAuthFile();\n if (!auth) return [];\n return Object.values(auth.profiles)\n .map((p) => p.token)\n .filter((t): t is string => !!t);\n}\n\nexport async function saveAuth(auth: StoredAuth, profile?: string): Promise<string> {\n const { dir: AUTH_DIR, file: AUTH_FILE } = getAuthPaths();\n await fs.mkdir(AUTH_DIR, { recursive: true, mode: 0o700 });\n\n // Read existing file (may be legacy or multi-profile)\n let existing: MultiProfileAuth;\n try {\n const content = await fs.readFile(AUTH_FILE, 'utf8');\n const data = JSON.parse(content) as unknown;\n\n if (isMultiProfile(data)) {\n existing = data;\n } else {\n // Migrate legacy flat format into profiles.default\n existing = {\n profiles: { default: data as LegacyAuth },\n default: 'default',\n };\n }\n } catch {\n existing = { profiles: {}, default: 'default' };\n }\n\n const key = profile ?? 'default';\n existing.profiles[key] = auth;\n\n // Set default to this profile if no default exists yet\n if (!existing.profiles[existing.default]) {\n existing.default = key;\n }\n\n await fs.writeFile(AUTH_FILE, JSON.stringify(existing, null, 2), {\n encoding: 'utf8',\n mode: 0o600,\n });\n // writeFile's mode only applies on creation; enforce 0600 on overwrite too.\n await fs.chmod(AUTH_FILE, 0o600).catch(() => {});\n return AUTH_FILE;\n}\n\n/* ── Multi-org session lookup ────────────────────────────────────────── */\n\nexport type StoredProfile = { key: string; auth: StoredAuth };\n\n/** Enumerate every stored session (profile) plus the current default key. */\nexport async function readAllProfiles(): Promise<{\n profiles: StoredProfile[];\n default: string;\n}> {\n const auth = await readAuthFile();\n if (!auth) return { profiles: [], default: 'default' };\n return {\n profiles: Object.entries(auth.profiles).map(([key, a]) => ({ key, auth: a })),\n default: auth.default,\n };\n}\n\nexport type SessionMatch =\n | { kind: 'match'; key: string; auth: StoredAuth }\n | { kind: 'none' }\n | { kind: 'ambiguous'; candidates: StoredProfile[] };\n\n/**\n * Find the stored session for an org, selected by `orgId` (exact) or `orgName`\n * (case-insensitive). When `env` is given it narrows to sessions in that\n * environment, so the same org can be logged in across prod/dev without clashing.\n * Returns `ambiguous` when a bare name matches sessions in multiple envs.\n * `apiUrl` replaces the env filter: it selects a login made with a custom `--api-url`\n * (no env label) by exact API URL, so callers pass `env` or `apiUrl`, never both.\n */\nexport async function findSessionByOrg(\n selector: string,\n env?: string,\n configDir?: string,\n apiUrl?: string\n): Promise<SessionMatch> {\n const auth = await readAuthFile(configDir);\n if (!auth) return { kind: 'none' };\n\n const sel = selector.toLowerCase();\n const all = Object.entries(auth.profiles).map(([key, a]) => ({ key, auth: a }));\n\n // Exact orgId match is unambiguous — prefer it over name matches.\n const byId = all.filter(({ auth: a }) => a.orgId === selector);\n let candidates = byId.length > 0 ? byId : all.filter(({ auth: a }) => a.orgName?.toLowerCase() === sel);\n\n // When --env is given, restrict to sessions in that environment — ALWAYS, even\n // for a single candidate. Otherwise a lone prod session would resolve under\n // `--env dev` and its token would be sent to the dev host (fail-open). No\n // match in the requested env → fall through to `none` so the caller errors.\n if (apiUrl) {\n // A login made with a custom --api-url carries no env label; match its host exactly.\n candidates = candidates.filter(({ auth: a }) => a.apiUrl === apiUrl);\n } else if (env) {\n const wantEnv = envToProfile(env);\n const wantApi = ENV_URLS[env]?.api;\n candidates = candidates.filter(\n ({ auth: a }) => a.envLabel === wantEnv || (!!wantApi && a.apiUrl === wantApi)\n );\n }\n\n // Collapse duplicate profiles that point at the SAME session: login mirrors a\n // session under both an org-scoped key (`org@env`) and the env-name key (for\n // `--env` lookups), so identical entries must not read as an ambiguous\n // multi-env match. Comparison is by token — the JWT is the real identity — so a\n // future refactor must not \"fix\" this into trusting local orgName/orgId fields.\n // The org-scoped key sorts first (written first), so it survives as representative.\n if (candidates.length > 1) {\n const seen = new Map<string, StoredProfile>();\n for (const c of candidates) {\n const idKey = c.auth.token ?? c.key;\n if (!seen.has(idKey)) seen.set(idKey, c);\n }\n candidates = [...seen.values()];\n }\n\n // `login` writes the org-scoped key (`orgProfileKey`) on every login, but the\n // env-name mirror (`production`, `dev`, …) only on `login --env`. After\n // `login --org X --env prod` then a plain `login --org X`, the mirror holds an\n // older token for the same org and env, and `--org X --env prod` failed as\n // ambiguous. The org-scoped key is the latest login for that org and env, so\n // it wins over its own mirror — deliberately, even if that login was another\n // user. The mirror's orgId/envLabel only decide which entry is discarded; the\n // survivor already passed the selector and env filter above.\n if (candidates.length > 1) {\n const keys = new Set(candidates.map((c) => c.key));\n const isShadowedEnvMirror = ({ key, auth: a }: StoredProfile) =>\n !!a.orgId && !!a.envLabel && key === a.envLabel && keys.has(orgProfileKey(a.orgId, a.envLabel));\n candidates = candidates.filter((c) => !isShadowedEnvMirror(c));\n }\n\n if (candidates.length === 0) return { kind: 'none' };\n if (candidates.length === 1) return { kind: 'match', key: candidates[0].key, auth: candidates[0].auth };\n return { kind: 'ambiguous', candidates };\n}\n\n/** Point the persistent `default` at an existing profile key. */\nexport async function setDefaultProfile(key: string): Promise<void> {\n const auth = await readAuthFile();\n if (!auth || !auth.profiles[key]) {\n throw new Error(`No stored session for profile \"${key}\".`);\n }\n auth.default = key;\n const { dir: AUTH_DIR, file: AUTH_FILE } = getAuthPaths();\n await fs.mkdir(AUTH_DIR, { recursive: true, mode: 0o700 });\n await fs.writeFile(AUTH_FILE, JSON.stringify(auth, null, 2), {\n encoding: 'utf8',\n mode: 0o600,\n });\n // writeFile's mode only applies on creation; enforce 0600 on overwrite too.\n await fs.chmod(AUTH_FILE, 0o600).catch(() => {});\n}\n\n/* ── Shared config resolution ────────────────────────────────────────── */\n\ntype ResolvedConfig = {\n apiUrl: string;\n token: string;\n /**\n * The selected org's vanity app subdomain, when the invocation resolved to a\n * stored session that has one. Carried here so any command can print a link\n * on the org's own host via {@link resolveOrgAppUrl} without re-reading the\n * auth file or widening its own signature.\n *\n * Undefined for token-only auth (`--token`, `CANARY_API_TOKEN`), where there\n * is no stored profile to read it from — those callers get the shared host,\n * which is the same link they get today.\n */\n appSubdomain?: string | null;\n};\n\n/**\n * Which stored session an invocation targets, before falling back to `--env`\n * profile / default. Returns the org selector string when one is in play (from\n * `--org` or `CANARY_ORG`), else `null`. With `--env` the selector still applies:\n * the (org, env) pair must resolve to one session or the command fails, so\n * `CANARY_ORG` is never silently dropped.\n */\nexport function getOrgSelector(argv: string[]): string | null {\n return getArgValue(argv, '--org') || (readBrandEnv('CANARY_ORG') ?? null);\n}\n\n/**\n * The API URL for this invocation, with no token and no `--org` session: `--api-url`, then `--env`,\n * then the env var, then the stored login's URL, then production. An unknown `--env` falls through:\n * `resolveConfig` rejects it before getting here, but callers that skip it (guides, which need no\n * login) get no validation and no `--org` session lookup.\n */\nexport async function resolveApiUrl(argv: string[]): Promise<string> {\n const env = getArgValue(argv, '--env');\n const profile = env ? envToProfile(env) : undefined;\n return (\n getArgValue(argv, '--api-url') ??\n (env ? ENV_URLS[env]?.api : undefined) ??\n readBrandEnv('CANARY_API_URL') ??\n (await readStoredApiUrl(profile)) ??\n DEFAULT_API_URL\n );\n}\n\nasync function resolveConfigInternal(\n argv: string[],\n opts: { required: boolean }\n): Promise<ResolvedConfig | null> {\n const env = getArgValue(argv, '--env');\n const profile = env ? envToProfile(env) : undefined;\n\n if (env && !ENV_URLS[env]) {\n if (opts.required) {\n console.error(`Unknown environment: ${env}`);\n console.error(`Valid environments: ${VALID_ENVS.join(', ')}`);\n process.exit(1);\n }\n return null;\n }\n\n // `--org <name|id>` (or CANARY_ORG) picks one of your logged-in sessions to\n // act as. It's an opt-in selector layered on top of the existing --env /\n // default resolution — a bare command with no --org behaves exactly as before.\n const orgSelector = getOrgSelector(argv);\n let selectedAuth: StoredAuth | null = null;\n if (orgSelector) {\n const match = await findSessionByOrg(orgSelector, env);\n if (match.kind === 'none') {\n if (opts.required) {\n printNoSessionForOrg(orgSelector, await readAllProfiles());\n process.exit(1);\n }\n return null;\n }\n if (match.kind === 'ambiguous') {\n if (opts.required) {\n printAmbiguousOrg(orgSelector, match.candidates);\n process.exit(1);\n }\n return null;\n }\n selectedAuth = match.auth;\n }\n\n let apiUrl: string;\n if (selectedAuth) {\n // The selected session's host is authoritative: never silently repoint an\n // org's bearer token to a different host via --api-url / CANARY_API_URL.\n apiUrl = selectedAuth.apiUrl ?? DEFAULT_API_URL;\n const explicitApiUrl = getArgValue(argv, '--api-url');\n if (explicitApiUrl && explicitApiUrl !== apiUrl) {\n if (opts.required) {\n console.error(`Error: the \"${orgSelector}\" session uses ${apiUrl}, but --api-url is ${explicitApiUrl}.`);\n console.error('Omit --api-url, or log that org in against the other host.');\n process.exit(1);\n }\n return null;\n }\n } else {\n apiUrl = await resolveApiUrl(argv);\n }\n\n const explicitToken = getArgValue(argv, '--token');\n\n // The session the token actually came from, when it came from one at all.\n // Tracked rather than re-derived afterwards: a `??` chain over \"selected\n // session, else stored profile\" cannot tell \"this org has no subdomain\"\n // (a real `null`) from \"no session was selected\", and would graft an\n // unrelated org's vanity host onto the link — the wrong org entirely.\n let tokenSource: StoredAuth | null = null;\n\n let token: string | null;\n if (explicitToken) {\n token = explicitToken;\n } else if (selectedAuth) {\n // An --org / CANARY_ORG selection points at a specific stored session.\n token = selectedAuth.token ?? readBrandEnv('CANARY_API_TOKEN') ?? null;\n if (selectedAuth.token) tokenSource = selectedAuth;\n if (!token && opts.required) {\n console.error(`Error: No token stored for org \"${orgSelector}\".`);\n console.error(`Run: canary login --org \"${orgSelector}\"`);\n process.exit(1);\n }\n } else if (profile) {\n const storedAuth = await readStoredAuth(profile);\n token = storedAuth?.token ?? readBrandEnv('CANARY_API_TOKEN') ?? null;\n if (storedAuth?.token) tokenSource = storedAuth;\n if (!token && opts.required) {\n console.error(`Error: No token found for \"${env}\" profile.`);\n console.error(`Run: canary login --env ${env}`);\n process.exit(1);\n }\n } else {\n const envToken = readBrandEnv('CANARY_API_TOKEN');\n if (envToken) {\n token = envToken;\n } else {\n const storedAuth = await readStoredAuth();\n token = storedAuth?.token ?? null;\n if (storedAuth?.token) tokenSource = storedAuth;\n }\n if (!token && opts.required) {\n console.error('Error: No API token found.');\n console.error('Run: canary login');\n process.exit(1);\n }\n }\n\n // An explicit --org/CANARY_ORG selection names the org outright, so it wins\n // even when its stored session held no token and the credential came from the\n // environment — `apiUrl` above already treats the selection as authoritative\n // in exactly that case, and the two must not disagree about which org this\n // invocation is acting as. Otherwise only the session that supplied the\n // credential names a host; token-only auth names no org and keeps the shared\n // one, the same link it produced before.\n const appSubdomain = (selectedAuth ?? tokenSource)?.appSubdomain ?? null;\n\n const source = selectedAuth ?? tokenSource;\n setActingTarget({\n orgName: source?.orgName ?? null,\n orgId: source?.orgId ?? null,\n env: source?.envLabel ?? env ?? null,\n apiUrl,\n });\n\n return token ? { apiUrl, token, appSubdomain } : null;\n}\n\n/** Error output when `--org`/`CANARY_ORG` names an org with no stored session. */\nexport function printNoSessionForOrg(\n selector: string,\n all: { profiles: StoredProfile[] }\n): void {\n console.error(`Error: No logged-in session for org \"${selector}\".`);\n const withOrg = all.profiles.filter((p) => p.auth.orgName || p.auth.orgId);\n if (withOrg.length > 0) {\n console.error('\\nLogged-in orgs:');\n for (const { auth: a } of withOrg) {\n const envLabel = a.envLabel ? ` [${a.envLabel}]` : '';\n console.error(` - ${a.orgName ?? '(unnamed)'} (${a.orgId ?? '?'})${envLabel}`);\n }\n }\n console.error(`\\nTo add one: canary login --org \"${selector}\"`);\n console.error(\n 'Note: --org selects which of your orgs to act as. Superadmin commands that\\n' +\n 'target a different org use --target-org instead.'\n );\n}\n\n/** Error output when a selector matches more than one session. Distinguishes an\n * env split (same org in prod+dev → narrow with --env) from a genuine name clash\n * across distinct orgs (→ select by org ID, --env won't help). */\nexport function printAmbiguousOrg(selector: string, candidates: StoredProfile[]): void {\n const distinctOrgs = new Set(candidates.map((c) => c.auth.orgId ?? c.key));\n if (distinctOrgs.size <= 1) {\n console.error(`Error: Org \"${selector}\" is logged into multiple environments. Narrow with --env:`);\n } else {\n console.error(`Error: \"${selector}\" matches multiple orgs. Select by org ID:`);\n }\n for (const { auth: a } of candidates) {\n const envLabel = a.envLabel ?? '(unknown env)';\n console.error(` - ${a.orgName ?? '(unnamed)'} (${a.orgId ?? '?'}) [${envLabel}]`);\n }\n}\n\n/**\n * Resolve API URL and auth token from argv flags, env vars, and stored profiles.\n * Used by knobs, feature-flag, release, and debug-session commands.\n */\nexport async function resolveConfig(argv: string[]): Promise<ResolvedConfig> {\n return (await resolveConfigInternal(argv, { required: true }))!;\n}\n\nexport async function resolveOptionalConfig(argv: string[]): Promise<ResolvedConfig | null> {\n return resolveConfigInternal(argv, { required: false });\n}\n\n/**\n * Where the effective auth token would come from for this invocation:\n * - `flag` — explicit `--token`\n * - `env` — CANARY_API_TOKEN / COFACTOR_API_TOKEN\n * - `stored` — an interactive `canary login` session in auth.json\n * - `none` — no token resolvable\n *\n * Mirrors the precedence in `resolveConfigInternal` exactly (which differs by\n * whether a profile is selected). `stored` is the only \"logged in interactively\"\n * source; `flag`/`env` are API-key style auth used by CI/automation.\n */\nexport async function resolveAuthSource(\n argv: string[]\n): Promise<'flag' | 'env' | 'stored' | 'none'> {\n const env = getArgValue(argv, '--env');\n if (env && !ENV_URLS[env]) return 'none';\n const profile = env ? envToProfile(env) : undefined;\n\n if (getArgValue(argv, '--token')) return 'flag';\n\n const orgSelector = getOrgSelector(argv);\n if (orgSelector) {\n const match = await findSessionByOrg(orgSelector, env);\n if (match.kind === 'match' && match.auth.token) return 'stored';\n if (readBrandEnv('CANARY_API_TOKEN')) return 'env';\n return 'none';\n }\n\n if (profile) {\n // With a profile, stored auth wins over the env var.\n if (await readStoredToken(profile)) return 'stored';\n if (readBrandEnv('CANARY_API_TOKEN')) return 'env';\n return 'none';\n }\n\n // Without a profile, the env var wins over stored auth.\n if (readBrandEnv('CANARY_API_TOKEN')) return 'env';\n if (await readStoredToken()) return 'stored';\n return 'none';\n}\n","/**\n * Central fetch wrapper for the Canary CLI.\n *\n * Exists to classify failures so corporate-proxy interference (Zscaler,\n * Netskope, Cloudflare Access, etc.) is distinguishable from real auth\n * expiry. Every non-2xx or transport error gets a specific, actionable\n * message instead of the historical blanket \"session may have expired.\"\n *\n * Set CANARY_DEBUG=1 (or pass --debug to the CLI) to log every request\n * and its classification — this is what affected users should share\n * with us or their IT/Zscaler admin.\n */\n\nimport process from 'node:process';\nimport { debug, isDebug } from './debug.js';\nimport { decodeJwtPayload } from './jwt.js';\n\n/** Header every canary API response carries. Absence => response did not come from our API. */\nconst CANARY_REQUEST_ID_HEADER = 'x-canary-request-id';\n\n/** Default per-request timeout. Zscaler-half-opened sockets have been observed\n * hanging indefinitely; the CLI should give up and classify rather than hang. */\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/** Treat a JWT exp within this grace window as still valid — tolerates the\n * typical handful of seconds of client-clock skew so we don't mislabel a\n * 30-second-fast clock as `token-revoked`. */\nconst JWT_EXP_SKEW_SEC = 60;\n\n/**\n * Best-effort scrub of `Bearer <token>` and bare three-segment JWTs from\n * error text before we print it. Doctor output is explicitly coached to be\n * shared with IT — if a proxy block page reflects the Authorization header,\n * we do not want the token in that paste.\n */\nfunction redactSecrets(text: string): string {\n return text\n .replace(/Bearer\\s+[A-Za-z0-9._-]+/gi, 'Bearer [redacted]')\n .replace(/\\beyJ[A-Za-z0-9_-]{6,}\\.[A-Za-z0-9_-]{6,}\\.[A-Za-z0-9_-]{6,}\\b/g, '[redacted-jwt]');\n}\n\n/** Strip query string — query params sometimes carry one-time tokens. */\nfunction redactUrl(url: string): string {\n const q = url.indexOf('?');\n return q === -1 ? url : `${url.slice(0, q)}?[redacted]`;\n}\n\nexport type FailureKind =\n | 'tls'\n | 'network'\n | 'html-body'\n | 'proxy-injected-4xx'\n | 'token-revoked'\n | 'token-expired'\n | 'unauthorized'\n | 'http-error';\n\nexport interface ClassifiedFailure {\n kind: FailureKind;\n status: number | null;\n url: string;\n message: string;\n /**\n * Response body text. Full body for `http-error` (so callers can parse\n * structured error payloads); truncated snippet for proxy/TLS failures\n * where the body is likely an HTML block page.\n */\n body?: string;\n /** Best-effort content-type. */\n contentType?: string;\n /** Raw error object for transport failures. */\n cause?: unknown;\n /**\n * Value of `x-canary-request-id` on the response, if any. Present means\n * the response came from our API (even for `token-revoked` / `token-expired`\n * / `unauthorized`); absent means the response was injected or the request\n * never reached us.\n */\n requestId?: string | null;\n}\n\n/**\n * Node/undici TLS error codes that indicate a MITM proxy (Zscaler et al.)\n * is intercepting HTTPS without the user trusting the proxy's root CA.\n */\nconst TLS_CODES = new Set([\n 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n 'UNABLE_TO_GET_ISSUER_CERT',\n 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',\n 'SELF_SIGNED_CERT_IN_CHAIN',\n 'DEPTH_ZERO_SELF_SIGNED_CERT',\n 'CERT_HAS_EXPIRED',\n 'CERT_UNTRUSTED',\n 'ERR_TLS_CERT_ALTNAME_INVALID',\n 'CERT_SIGNATURE_FAILURE',\n]);\n\nfunction extractErrorCode(err: unknown): string | null {\n if (!err || typeof err !== 'object') return null;\n const withCode = err as { code?: unknown; cause?: unknown };\n if (typeof withCode.code === 'string') return withCode.code;\n if (withCode.cause) return extractErrorCode(withCode.cause);\n return null;\n}\n\nfunction looksLikeHtml(body: string, contentType: string | null): boolean {\n if (contentType && contentType.toLowerCase().includes('text/html')) return true;\n const trimmed = body.trimStart();\n return trimmed.startsWith('<!') || trimmed.startsWith('<html') || trimmed.startsWith('<HTML');\n}\n\n/** Decode JWT `exp` and compare to now (with a small skew grace); null if undecodable. */\nfunction jwtExpStatus(token: string | undefined): 'expired' | 'valid' | 'unknown' {\n if (!token) return 'unknown';\n const payload = decodeJwtPayload(token);\n const exp = payload && typeof payload.exp === 'number' ? (payload.exp as number) : null;\n if (exp === null) return 'unknown';\n const nowSec = Math.floor(Date.now() / 1000);\n return exp < nowSec - JWT_EXP_SKEW_SEC ? 'expired' : 'valid';\n}\n\n/** Warn once per process when sending Authorization to a non-local http:// URL. */\nlet warnedAboutPlaintext = false;\nfunction maybeWarnPlaintextAuth(url: string, hasAuthHeader: boolean): void {\n if (!hasAuthHeader || warnedAboutPlaintext) return;\n if (!url.startsWith('http://')) return;\n try {\n const host = new URL(url).hostname;\n if (host === 'localhost' || host === '127.0.0.1' || host === '::1') return;\n } catch {\n return;\n }\n warnedAboutPlaintext = true;\n process.stderr.write(\n `[canary] WARNING: sending Authorization over plaintext http:// (${url}). ` +\n 'Your API token may be exposed to the network. Use https:// in CANARY_API_URL.\\n'\n );\n}\n\nfunction hasAuthHeader(init: RequestInit): boolean {\n const h = init.headers;\n if (!h) return false;\n if (h instanceof Headers) return h.has('authorization');\n if (Array.isArray(h)) return h.some(([k]) => k.toLowerCase() === 'authorization');\n return Object.keys(h).some((k) => k.toLowerCase() === 'authorization');\n}\n\n/** Who the current invocation resolved to act as; set by config resolution. */\nlet actingTarget: { orgName: string | null; orgId: string | null; env: string | null; apiUrl: string } | null = null;\nlet announcedWrite = false;\n\nexport function setActingTarget(target: NonNullable<typeof actingTarget>): void {\n actingTarget = target;\n}\n\n/** Name the org and environment a write is aimed at, once per process, so a misdirected write is visible. */\nfunction announceWriteTarget(url: string, method: string): void {\n if (announcedWrite || method === 'GET') return;\n announcedWrite = true;\n const t = actingTarget;\n const target = t?.apiUrl ?? url;\n let origin = target;\n try {\n origin = new URL(target).origin;\n } catch {\n // Malformed --api-url: print it raw; the request below classifies the failure.\n }\n process.stderr.write(\n `acting as ${t?.orgName ?? 'unknown org'} (${t?.orgId ?? 'unknown id'}) on ${t?.env ?? 'unknown env'} ${origin}\\n`\n );\n}\n\n/**\n * Wrap global `fetch` with classification. Always resolves — never throws —\n * so callers can make a single uniform decision from the returned shape.\n */\nexport async function apiFetch(\n url: string,\n init: RequestInit & { token?: string; timeoutMs?: number } = {}\n): Promise<\n | { ok: true; response: Response; requestId: string | null }\n | { ok: false; failure: ClassifiedFailure }\n> {\n const { token, timeoutMs, ...fetchInit } = init;\n maybeWarnPlaintextAuth(url, hasAuthHeader(fetchInit));\n announceWriteTarget(url, (fetchInit.method ?? 'GET').toUpperCase());\n debug(`→ ${fetchInit.method ?? 'GET'} ${redactUrl(url)}`);\n\n // Merge caller-supplied signal with our timeout so both can abort.\n // timeoutMs <= 0 disables the timeout (use for long-lived SSE streams).\n const timeout = timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const timeoutSignal = timeout > 0 ? AbortSignal.timeout(timeout) : null;\n const effectiveSignal =\n fetchInit.signal && timeoutSignal\n ? AbortSignal.any([fetchInit.signal, timeoutSignal])\n : (fetchInit.signal ?? timeoutSignal ?? undefined);\n\n let response: Response;\n try {\n response = await fetch(url, { ...fetchInit, signal: effectiveSignal });\n } catch (err) {\n const isTimeout =\n (err as { name?: string })?.name === 'TimeoutError' ||\n Boolean(timeoutSignal?.aborted);\n if (isTimeout) {\n const msg = `Request to ${redactUrl(url)} timed out after ${timeout}ms.`;\n debug(`✖ network timeout`);\n return {\n ok: false,\n failure: { kind: 'network', status: null, url, message: msg, cause: err },\n };\n }\n const code = extractErrorCode(err);\n if (code && TLS_CODES.has(code)) {\n const msg = [\n `TLS verification failed talking to ${redactUrl(url)} (${code}).`,\n 'A corporate proxy (Zscaler, Netskope, ZPA, Cloudflare Access) is likely intercepting HTTPS.',\n 'Fixes: point Node at the proxy\\'s root CA with',\n ' NODE_EXTRA_CA_CERTS=/path/to/corporate-root.pem canary …',\n 'or on Node 20+ enable the system trust store with',\n ' NODE_OPTIONS=--use-system-ca canary …',\n ].join('\\n');\n debug(`✖ tls ${code}`);\n return { ok: false, failure: { kind: 'tls', status: null, url, message: msg, cause: err } };\n }\n const msg = `Network error reaching ${redactUrl(url)}: ${String((err as Error).message ?? err)}`;\n debug(`✖ network ${msg}`);\n return { ok: false, failure: { kind: 'network', status: null, url, message: msg, cause: err } };\n }\n\n const requestId = response.headers.get(CANARY_REQUEST_ID_HEADER);\n const contentType = response.headers.get('content-type');\n debug(`← ${response.status} ${redactUrl(url)} (ct=${contentType ?? 'n/a'} rid=${requestId ?? 'none'})`);\n\n if (response.ok) {\n return { ok: true, response, requestId };\n }\n\n // Read body once so we can classify and still return something useful.\n // Scrub secrets before constructing user-facing `snippet`; `bodyText` is\n // kept intact for callers that parse structured JSON error bodies.\n const bodyText = await response.clone().text().catch(() => '');\n const snippet = redactSecrets(bodyText.slice(0, 200));\n\n // HTML on a JSON endpoint => proxy block page or captive portal.\n if (looksLikeHtml(bodyText, contentType)) {\n return {\n ok: false,\n failure: {\n kind: 'html-body',\n status: response.status,\n url,\n contentType: contentType ?? undefined,\n requestId,\n body: snippet,\n message: [\n `Got an HTML response from ${url} (status ${response.status}).`,\n 'A corporate proxy block page or captive portal is intercepting this request — the',\n 'response did not come from the Canary API.',\n 'Check that your proxy (e.g. Zscaler) allowlists the API hostname, and that any',\n 'required sign-in to the proxy itself is current.',\n snippet ? `First bytes: ${snippet.replace(/\\s+/g, ' ')}` : '',\n ]\n .filter(Boolean)\n .join('\\n'),\n },\n };\n }\n\n // 401/403 without our header => not our response.\n if ((response.status === 401 || response.status === 403) && !requestId) {\n return {\n ok: false,\n failure: {\n kind: 'proxy-injected-4xx',\n status: response.status,\n url,\n contentType: contentType ?? undefined,\n requestId,\n body: snippet,\n message: [\n `Got ${response.status} from ${url} but the response is missing the \\`${CANARY_REQUEST_ID_HEADER}\\` header.`,\n 'This response was almost certainly injected by a corporate proxy (Zscaler, Netskope,',\n 'Cloudflare Access) rather than returned by our API — retrying \"canary login\" will not fix it.',\n 'Ask your IT team to allowlist the API host, or re-auth to the proxy and try again.',\n ].join('\\n'),\n },\n };\n }\n\n if (response.status === 401) {\n const jwtStatus = jwtExpStatus(token);\n if (jwtStatus === 'valid') {\n return {\n ok: false,\n failure: {\n kind: 'token-revoked',\n status: 401,\n url,\n requestId,\n body: snippet,\n message: [\n 'Server rejected a token that is still valid locally (unexpired JWT).',\n 'Likely causes: the token was revoked, the server\\'s signing key rotated, or the',\n 'user/org was deactivated. `canary login` will issue a fresh token.',\n ].join('\\n'),\n },\n };\n }\n if (jwtStatus === 'expired') {\n return {\n ok: false,\n failure: {\n kind: 'token-expired',\n status: 401,\n url,\n requestId,\n body: snippet,\n message: 'Your stored token has expired. Run: canary login',\n },\n };\n }\n return {\n ok: false,\n failure: {\n kind: 'unauthorized',\n status: 401,\n url,\n requestId,\n body: snippet,\n message: 'Unauthorized. Run: canary login',\n },\n };\n }\n\n return {\n ok: false,\n failure: {\n kind: 'http-error',\n status: response.status,\n url,\n contentType: contentType ?? undefined,\n requestId,\n body: bodyText,\n message: `${response.status} ${response.statusText}${snippet ? `: ${snippet}` : ''}`,\n },\n };\n}\n\n/**\n * Kinds of failure the user can't recover from by retrying the same call —\n * no token on disk, proxy interception, TLS mismatch, rejected JWT. Callers\n * should `exitOnFailure` immediately for these. `http-error` is excluded\n * because the caller often needs to pretty-print a structured error body.\n */\nexport function isTerminalFailure(failure: ClassifiedFailure): boolean {\n return failure.kind !== 'http-error';\n}\n\n/**\n * Print a classified failure and exit(1). Use from command handlers that\n * have no way to recover — matches the historical behavior of the various\n * `if (res.status === 401) { console.error(...); process.exit(1); }` blocks.\n */\nexport function exitOnFailure(failure: ClassifiedFailure): never {\n process.stderr.write(`Error: ${failure.message}\\n`);\n if (isDebug() && failure.body && failure.kind !== 'html-body') {\n process.stderr.write(`[canary-debug] body: ${failure.body}\\n`);\n }\n process.exit(1);\n}\n\n/**\n * Drop-in for `fetch()` in CLI call sites that parse the body themselves:\n * exits the process for terminal failures (TLS/proxy/unauthorized) so the\n * user sees a diagnostic, and returns a Response otherwise — whether 2xx\n * or an HTTP error (so the caller can still inspect .status / .json()).\n */\nexport async function fetchOrExit(\n url: string,\n init: RequestInit & { token?: string; timeoutMs?: number } = {}\n): Promise<Response> {\n const result = await apiFetch(url, init);\n if (result.ok) return result.response;\n if (isTerminalFailure(result.failure)) exitOnFailure(result.failure);\n // http-error: reconstruct a Response the caller can json() / read status on.\n return new Response(result.failure.body ?? '', {\n status: result.failure.status ?? 500,\n headers: result.failure.contentType\n ? { 'content-type': result.failure.contentType }\n : undefined,\n });\n}\n","import process from 'node:process';\nimport { splitAtSeparator } from './argv.js';\n\n/**\n * Whether verbose CLI diagnostics are enabled. Opt-in only, so normal runs stay\n * quiet — set CANARY_DEBUG=1 (or =true) or pass --debug. Diagnostics always go\n * to stderr so they never pollute stdout-piped (`--json`) output.\n */\nexport function isDebug(): boolean {\n return (\n process.env.CANARY_DEBUG === '1' ||\n process.env.CANARY_DEBUG === 'true' ||\n splitAtSeparator(process.argv.slice(2)).options.includes('--debug')\n );\n}\n\n/** Write a diagnostic line to stderr, but only when debug mode is enabled. */\nexport function debug(line: string): void {\n if (isDebug()) {\n process.stderr.write(`[canary-debug] ${line}\\n`);\n }\n}\n","/**\n * POSIX-style split at the first `--`: `options` are the CLI's own words,\n * `passthrough` is the command after the separator, which no flag scanning\n * (help, version, config, telemetry) may read.\n */\nexport function splitAtSeparator(argv: string[]): { options: string[]; passthrough: string[] } {\n const separator = argv.indexOf('--');\n return {\n options: separator === -1 ? argv : argv.slice(0, separator),\n passthrough: separator === -1 ? [] : argv.slice(separator + 1),\n };\n}\n\n/**\n * Flags whose value is free text, so it may legitimately start with a flag-like\n * word: `--description \"--org Acme\"`. Only the word after one of these is exempt\n * from the fused-flag check; after any other flag (a switch, a typo, a flag this\n * list does not name) a fused `\"--org X --env prod\"` is still refused, and the\n * error names the escape. Keep it to flags whose value is a name or\n * prose (`--application` is a name lookup that fails loudly on a bad name): a\n * fused selector after a listed flag becomes its value instead of being refused.\n */\nconst FREE_TEXT_FLAGS = new Set([\n '--application', '--body', '--cleanup', '--content', '--description', '--label', '--message', '--name',\n '--preflight', '--prompt', '--query', '--reason', '--search', '--summary', '--title',\n]);\n\n/**\n * Whether `argv[i]` is the free-text value of the flag just before it. A word\n * that is itself a well-formed flag (`--x` or `--x=y`, no whitespace) is never\n * a value, so a bare trailing `--org` after `--description` is still checked.\n */\nexport function isFreeTextValue(argv: string[], i: number): boolean {\n return isFreeTextFlag(argv[i - 1] ?? '') && !/^--[\\w-]+(=\\S*)?$/.test(argv[i]);\n}\n\nexport function isFreeTextFlag(flag: string): boolean {\n return FREE_TEXT_FLAGS.has(flag);\n}\n","/**\n * JWT payload decoder for CLI superadmin detection.\n *\n * Decodes the payload section of a JWT locally (no signature verification,\n * no network calls). Used to conditionally show superadmin CLI commands.\n *\n * @module\n */\n\n/**\n * Decode the payload (second segment) of a JWT without verifying the signature.\n * Returns the parsed JSON object, or `null` if the token is malformed.\n */\nexport function decodeJwtPayload(token: string): Record<string, unknown> | null {\n try {\n const parts = token.split(\".\");\n if (parts.length !== 3) return null;\n\n const base64 = parts[1]!.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const json = Buffer.from(base64, \"base64\").toString(\"utf8\");\n const payload: unknown = JSON.parse(json);\n\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n return null;\n }\n return payload as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/**\n * Returns `true` when the JWT's `is_superadmin` claim is exactly `true`.\n * Returns `false` for any invalid, missing, or non-superadmin token.\n */\nexport function isSuperadminToken(token: string | null | undefined): boolean {\n if (!token) return false;\n const payload = decodeJwtPayload(token);\n return payload?.is_superadmin === true;\n}\n","/**\n * Compiled-in default platform URLs for the CLI.\n *\n * Single source of truth — every command's final `??` fallback resolves here,\n * so the prod default lives in exactly one place. Runtime overrides still win\n * (`--api-url` / `--app-url` flags, `CANARY_API_URL` / `COFACTOR_API_URL` env,\n * `--env`, and stored profile). Both the `canary` and `cofactor` brands share\n * this default; `trycanary.ai` 301-redirects to `runcofactor.com`, so the old\n * host keeps working for anyone with it saved.\n */\nexport const DEFAULT_API_URL = 'https://api.runcofactor.com';\nexport const DEFAULT_APP_URL = 'https://app.runcofactor.com';\n"],"mappings":";;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAOA,cAAa;;;ACUpB,OAAOC,cAAa;;;ACbpB,OAAO,aAAa;;;ACKb,SAAS,iBAAiB,MAA8D;AAC7F,QAAM,YAAY,KAAK,QAAQ,IAAI;AACnC,SAAO;AAAA,IACL,SAAS,cAAc,KAAK,OAAO,KAAK,MAAM,GAAG,SAAS;AAAA,IAC1D,aAAa,cAAc,KAAK,CAAC,IAAI,KAAK,MAAM,YAAY,CAAC;AAAA,EAC/D;AACF;AAWA,IAAM,kBAAkB,oBAAI,IAAI;AAAA,EAC9B;AAAA,EAAiB;AAAA,EAAU;AAAA,EAAa;AAAA,EAAa;AAAA,EAAiB;AAAA,EAAW;AAAA,EAAa;AAAA,EAC9F;AAAA,EAAe;AAAA,EAAY;AAAA,EAAW;AAAA,EAAY;AAAA,EAAY;AAAA,EAAa;AAC7E,CAAC;AAOM,SAAS,gBAAgB,MAAgB,GAAoB;AAClE,SAAO,eAAe,KAAK,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,oBAAoB,KAAK,KAAK,CAAC,CAAC;AAC/E;AAEO,SAAS,eAAe,MAAuB;AACpD,SAAO,gBAAgB,IAAI,IAAI;AACjC;;;AD9BO,SAAS,UAAmB;AACjC,SACE,QAAQ,IAAI,iBAAiB,OAC7B,QAAQ,IAAI,iBAAiB,UAC7B,iBAAiB,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,QAAQ,SAAS,SAAS;AAEtE;AAGO,SAAS,MAAM,MAAoB;AACxC,MAAI,QAAQ,GAAG;AACb,YAAQ,OAAO,MAAM,kBAAkB,IAAI;AAAA,CAAI;AAAA,EACjD;AACF;;;AERO,SAAS,iBAAiB,OAA+C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EAAE,YAAY;AAC/B,YAAQ,MAAM,OAAO,EAAE,WAAW,WAAW,KAAK,EAAE,SAAS,GAAG,MAAM,QAAQ,GAAG;AAAA,EACnF;AACF;AAMA,eAAsB,cAAc,MAAyC;AAC3E,SAAQ,MAAM,sBAAsB,MAAM,EAAE,UAAU,KAAK,CAAC;AAC9D;AAEA,eAAsB,sBAAsB,MAAgD;AAC1F,SAAO,sBAAsB,MAAM,EAAE,UAAU,MAAM,CAAC;AACxD;AAaA,eAAsB,kBACpB,MAC6C;AAC7C,QAAM,MAAM,YAAY,MAAM,OAAO;AACrC,MAAI,OAAO,CAAC,SAAS,GAAG,EAAG,QAAO;AAClC,QAAM,UAAU,MAAM,aAAa,GAAG,IAAI;AAE1C,MAAI,YAAY,MAAM,SAAS,EAAG,QAAO;AAEzC,QAAM,cAAc,eAAe,IAAI;AACvC,MAAI,aAAa;AACf,UAAM,QAAQ,MAAM,iBAAiB,aAAa,GAAG;AACrD,QAAI,MAAM,SAAS,WAAW,MAAM,KAAK,MAAO,QAAO;AACvD,QAAI,aAAa,kBAAkB,EAAG,QAAO;AAC7C,WAAO;AAAA,EACT;AAEA,MAAI,SAAS;AAEX,QAAI,MAAM,gBAAgB,OAAO,EAAG,QAAO;AAC3C,QAAI,aAAa,kBAAkB,EAAG,QAAO;AAC7C,WAAO;AAAA,EACT;AAGA,MAAI,aAAa,kBAAkB,EAAG,QAAO;AAC7C,MAAI,MAAM,gBAAgB,EAAG,QAAO;AACpC,SAAO;AACT;","names":["process","process","hasAuthHeader","process","msg","process"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/eval.ts","../../types/src/agent-eval-template.ts","../src/eval-bundle.ts","../src/eval-run.ts","../../types/src/agent-eval-render.ts","../src/eval-template.ts"],"sourcesContent":["/** `cofactor eval`: author agent evals, add cases, run them against a commit and compare models. */\nimport { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';\nimport { gunzipSync } from 'node:zlib';\nimport { join } from 'node:path';\nimport { AGENT_EVAL_MAX_BUNDLE_BYTES, EvalConversationSchema } from '@chatsdet/types/agent-eval-template';\nimport { printServedGuide } from './guide.js';\nimport { GLOBAL_VALUE_FLAGS, hasFlag, resolveConfig } from './auth.js';\nimport { writeRawOutput } from './brand.js';\nimport {\n getPositionalArg,\n getPositionalArgs,\n getScalarArgValue,\n readStdin,\n} from './cli-helpers.js';\nimport { resolveApplicationId } from './environment.js';\nimport { EVALS, getEval, request, requestAll, requestText, type EvalDetail, type UploadReply } from './eval-api.js';\nimport { loadBundle, missingRequiredPaths } from './eval-bundle.js';\nimport { compareRuns, getRun, listRuns, runEval } from './eval-run.js';\nimport {\n EVAL_GITIGNORE,\n TemplateError,\n formatIssues,\n initRunbook,\n initTemplate,\n readPushPayload,\n} from './eval-template.js';\n\nconst USAGE = {\n guide: 'guide',\n init: 'init <name> [--application <app>] [--capability CAP-…]',\n push: 'push [<file>] --application <app>',\n show: 'show <name>',\n runbook: 'runbook <name>',\n list: 'list',\n cases: 'cases <name> [--download <dir>]',\n 'rm-case': 'rm-case <name> <key>',\n 'add-case':\n 'add-case <name> --key <k> --input <dir|file.tar.gz> --expected <file|-> --source \"<provenance>\" [--title <t>] [--conversation <file.json>]',\n run: 'run <name> [--model <alias>]... [--environment <env>] [--at <sha>] [--case <key>]... [--repeats N] [--parallel N] [--no-wait]',\n get: 'get <run-id> [--case <key>] [--transcript]',\n runs: 'runs <name> [--limit N]',\n compare: 'compare (<run-id>... | --batch <id>)',\n};\ntype Command = keyof typeof USAGE;\n\nconst VALUE_FLAGS = [\n ...GLOBAL_VALUE_FLAGS,\n '--application',\n '--capability',\n '--key',\n '--input',\n '--expected',\n '--source',\n '--title',\n '--conversation',\n '--model',\n '--environment',\n '--at',\n '--case',\n '--repeats',\n '--parallel',\n '--limit',\n '--batch',\n '--download',\n];\n/** How many positional arguments a sub-command needs (push, list and compare take none). */\nconst POSITIONALS: Partial<Record<Command, number>> = {\n show: 1, runbook: 1, cases: 1, 'rm-case': 2, 'add-case': 1, run: 1, get: 1, runs: 1,\n};\nconst WRITES: Command[] = ['push', 'add-case', 'rm-case', 'run'];\nconst DEFAULT_TEMPLATE_DIR = 'evals';\n\nfunction printHelp(command: string | undefined): void {\n const usage = Object.hasOwn(USAGE, command ?? '') ? USAGE[command as Command] : undefined;\n console.log(\n [\n `Usage: cofactor eval ${usage ?? '<sub-command>'} [--json]`,\n '',\n ...Object.values(USAGE).map((line) => ` cofactor eval ${line}`),\n '',\n 'guide: prints the agent-eval guide: the latest served copy, else the one bundled with this CLI (no login needed).',\n 'An eval runs an agent command against a set of cases at a commit, grades each attempt and reports',\n 'pass rate, cost and time per task. The template and runbook live in your repo under evals/.',\n '',\n 'init: writes evals/<name>.eval.yaml (a commented template with a script and an ai-judge grader),',\n ' evals/<name>.runbook.md and evals/.gitignore (*.tar.gz, _staging/). Refuses to overwrite.',\n 'push: validates the template locally, reads the runbook it names (relative to the YAML) and stores both;',\n ' re-pushing is idempotent. Defaults to evals/*.eval.yaml when exactly one exists. Needs --application.',\n ' Warns on a missing runbook heading; errors when \"## Finding real data\" or \"## Sanitizing\" is empty, or when',\n ' any section still has the \"<!-- cofactor:todo -->\" line that init writes (delete it once the section is written).',\n 'show/list/cases/runbook: read the stored eval, its cases (key, sha256, size, source) and runbook.',\n ' cases --download <dir> also writes each bundle as <dir>/<key>.tar (uncompressed, so its sha256 is the case\\'s sha256).',\n 'add-case: --input is a directory (tarred deterministically: sorted entries, fixed mtime, uid/gid 0) or a .tar.gz.',\n ' The sha256 shown is that of the uncompressed tar, so the same files give the same sha256 on any runtime',\n ' and dedup is by tar content; gzip is transport only.',\n ' The template\\'s input.require paths are checked first.',\n ' --expected is a JSON file, or - for stdin. --source says where the data came from and what corroborates the',\n ' label. Never include customer data in a case. --conversation <file.json> is required for a multi-turn eval.',\n 'rm-case: deletes a case that no run has used.',\n 'run: starts one run per --model (alias from the template; none means its default) and waits, printing one',\n ' section per model and then the comparison grid. --case and a --repeats that differs from the template make a partial run',\n ' that never counts for coverage or proofs. Polls every 5 seconds for at most 8.5 hours; a timeout leaves the',\n ' runs readable with get; the batch and run ids are printed to stderr before waiting. --no-wait prints the',\n ' ids and exits 0. --json prints an array with one entry per run, in order: the run\\'s result, or',\n ' {id, status, verdict, error} for a run with no result.',\n 'get: a run\\'s result. --case <key> narrows to one case; --case <key> --transcript adds a multi-turn attempt\\'s',\n ' conversation. runs: recent runs for an eval, newest first (--limit N).',\n 'compare: the grid for run ids or a --batch; --json prints the array of runs.',\n '',\n 'Common options:',\n ' --org <name|id> Logged-in organization; required explicitly for push, add-case, rm-case and run',\n ' --env <env> API environment (prod, dev, local)',\n ' --api-url <url> API URL override',\n ' --token <key> API token override',\n ' --json Raw JSON on every sub-command except init',\n ' --help, -h Show help without authentication',\n '',\n 'Requires the sandbox-v2 organization flag. API-key scopes:',\n ' run: sandbox:create + sandbox:exec, named explicitly (sandbox:* does not grant sandbox:exec).',\n ' push, add-case, rm-case: sandbox:edit. show, list, cases, runbook, get, runs, compare: sandbox:read.',\n '',\n 'Exit codes (run):',\n ' 0 every run\\'s verdict is pass',\n ' 3 at least one run\\'s verdict is fail (the agent missed the pass bar; perf also exits 3 for \"slower\")',\n ' 1 a failed or cancelled run, a polling timeout, or any error',\n 'Other sub-commands exit 0 on success, 1 on error.',\n ].join('\\n')\n );\n}\n\nfunction required(argv: string[], flag: string): string {\n const value = getScalarArgValue(argv, flag);\n if (!value) throw new Error(`${flag} is required.`);\n return value;\n}\n\n/** `--expected` alone may be `-` (stdin), which the generic value check reads as a missing value. */\nfunction expectedArg(argv: string[]): string {\n const i = argv.findIndex((arg) => arg === '--expected' || arg.startsWith('--expected='));\n const value = i < 0 ? undefined : argv[i]!.startsWith('--expected=') ? argv[i]!.slice('--expected='.length) : argv[i + 1];\n if (!value || value.startsWith('--')) throw new Error('--expected is required: a JSON file, or - for stdin.');\n return value;\n}\n\nasync function readJson(path: string, label: string): Promise<unknown> {\n let text: string;\n try {\n text = path === '-' ? await readStdin() : await readFile(path, 'utf8');\n } catch (error) {\n throw new Error(`Cannot read ${label}: ${error instanceof Error ? error.message : String(error)}`);\n }\n try {\n return JSON.parse(text);\n } catch (error) {\n throw new Error(`${label} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\ntype Context = { argv: string[]; positionals: string[]; apiUrl: string; token: string; json: boolean };\n\n/** The first positional (an eval name or run id), or the sub-command's usage as the error. */\nfunction target(ctx: Context, command: Command): string {\n const value = ctx.positionals[0];\n if (!value) throw new Error(`Usage: cofactor eval ${USAGE[command]}`);\n return value;\n}\n\nasync function init(argv: string[]): Promise<void> {\n const name = getPositionalArg(argv, VALUE_FLAGS);\n if (!name) throw new Error(`Usage: cofactor eval ${USAGE.init}`);\n if (!/^[a-z0-9-]{2,40}$/.test(name) || name === 'runs' || name === 'compare')\n throw new Error('The eval name must be 2 to 40 lowercase letters, digits or dashes (and not \"runs\" or \"compare\").');\n const capability = getScalarArgValue(argv, '--capability');\n if (capability !== undefined && !/^CAP-[A-Z0-9]+-\\d{3,}$/.test(capability))\n throw new Error('--capability must be a product-map code such as CAP-CMM-001.');\n const files = [\n { path: join(DEFAULT_TEMPLATE_DIR, `${name}.eval.yaml`), text: initTemplate({ name, application: getScalarArgValue(argv, '--application'), capability }) },\n { path: join(DEFAULT_TEMPLATE_DIR, `${name}.runbook.md`), text: initRunbook(name) },\n ];\n const gitignore = join(DEFAULT_TEMPLATE_DIR, '.gitignore');\n const exists = async (path: string) => readFile(path).then(() => true, () => false);\n for (const file of files) {\n if (await exists(file.path)) throw new Error(`${file.path} already exists; not overwriting it.`);\n }\n await mkdir(DEFAULT_TEMPLATE_DIR, { recursive: true });\n const written = files.map((file) => file.path);\n for (const file of files) await writeFile(file.path, file.text, { flag: 'wx' });\n if (!(await exists(gitignore))) {\n await writeFile(gitignore, EVAL_GITIGNORE, { flag: 'wx' });\n written.push(gitignore);\n }\n writeRawOutput(\n hasFlag(argv, '--json')\n ? JSON.stringify({ written }, null, 2)\n : `${written.map((path) => `Wrote ${path}`).join('\\n')}\\nEdit the run command and graders, write each runbook section and delete its <!-- cofactor:todo --> line, then: cofactor eval push ${files[0]!.path} --application <app> --org <org>`\n );\n}\n\nasync function defaultTemplateFile(): Promise<string> {\n const found = (await readdir(DEFAULT_TEMPLATE_DIR).catch(() => [])).filter((f) => f.endsWith('.eval.yaml'));\n if (found.length !== 1)\n throw new Error(\n found.length === 0\n ? `No ${DEFAULT_TEMPLATE_DIR}/*.eval.yaml found; pass the template file.`\n : `Several templates in ${DEFAULT_TEMPLATE_DIR}/ (${found.join(', ')}); pass the one to push.`\n );\n return join(DEFAULT_TEMPLATE_DIR, found[0]!);\n}\n\nasync function push({ argv, apiUrl, token, json }: Context): Promise<void> {\n const file = getPositionalArg(argv, VALUE_FLAGS) ?? (await defaultTemplateFile());\n const payload = await readPushPayload(file);\n for (const warning of payload.warnings) console.error(`Warning: ${warning}`);\n const applicationId = await resolveApplicationId(argv, apiUrl, token);\n const pushed = await request<{ id: string; name: string }>(apiUrl, token, 'PUT', EVALS, {\n applicationId,\n definition: payload.definition,\n runbook: payload.runbook,\n });\n const detail = await getEval(apiUrl, token, pushed.name);\n if (json) {\n writeRawOutput(JSON.stringify({ ...detail, warnings: payload.warnings }, null, 2));\n return;\n }\n writeRawOutput(\n [\n `Pushed ${detail.name} (${detail.id})`,\n `Cases: ${detail.cases.length}`,\n `Capabilities: ${detail.capabilities.map((c) => c.code).join(', ') || 'none'}`,\n ].join('\\n')\n );\n}\n\nfunction describeEval(detail: EvalDetail): string {\n const d = detail.definition;\n return [\n `${detail.name} ${detail.id}`,\n d.description,\n `Application: ${detail.applicationId}`,\n `Mode: ${d.mode}`,\n `Run: ${d.run.split('\\n')[0]}${d.run.includes('\\n') ? ' …' : ''}`,\n `Models: ${Object.entries(d.agent.models).map(([alias, m]) => `${alias}${alias === d.agent.default ? '*' : ''} (${m.model})`).join(', ')}`,\n `Graders: ${d.graders.map((g) => `${g.id} [${g.kind}]`).join(', ')}`,\n `Repeats: ${d.repeats}, pass at least ${d.passAtLeast}, bar ${Math.round(d.passBar * 100)}%, ${d.attemptSeconds}s per attempt`,\n `Capabilities: ${detail.capabilities.map((c) => `${c.code} ${c.title}`).join('; ') || 'none'}`,\n `Cases: ${detail.cases.length}`,\n ].join('\\n');\n}\n\nasync function listEvals({ apiUrl, token, json }: Context): Promise<void> {\n const evals = await requestAll<{ id: string; name: string; applicationId: string; description: string; caseCount: number; latestVerdict: 'pass' | 'fail' | null }>(apiUrl, token, EVALS);\n writeRawOutput(\n json\n ? JSON.stringify(evals, null, 2)\n : evals.map((e) => `${e.name} ${e.id} ${e.caseCount} cases ${e.latestVerdict ?? '-'} ${e.description}`).join('\\n') || 'No evals found.'\n );\n}\n\nasync function showEval(ctx: Context): Promise<void> {\n const detail = await getEval(ctx.apiUrl, ctx.token, target(ctx, 'show'));\n writeRawOutput(ctx.json ? JSON.stringify(detail, null, 2) : describeEval(detail));\n}\n\n// A tar may unpack to more than the gzip limit; the same bound the bundle reader uses for archives.\nconst DOWNLOAD_MAX_TAR_BYTES = 4 * AGENT_EVAL_MAX_BUNDLE_BYTES;\n\n/** Fetch every case bundle through its signed URL and write it, gunzipped, as `<dir>/<key>.tar` (the tar whose sha256 is the case's content address). */\nasync function downloadBundles(ctx: Context, evaluation: EvalDetail, dir: string): Promise<void> {\n await mkdir(dir, { recursive: true });\n for (const { key } of evaluation.cases) {\n // The key becomes a file name: never trust the server for that.\n if (!/^[a-z0-9][a-z0-9-]*$/.test(key)) throw new Error(`Refusing to download case \"${key}\": its key is not a plain file name.`);\n const { url } = await request<{ url: string }>(\n ctx.apiUrl,\n ctx.token,\n 'GET',\n `${EVALS}/${encodeURIComponent(evaluation.id)}/cases/${encodeURIComponent(key)}/bundle`\n );\n const target = new URL(url);\n if (target.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(target.hostname))\n throw new Error(`Refusing to download case ${key} over ${target.protocol}.`);\n const response = await fetch(target, { redirect: 'error' });\n if (!response.ok) throw new Error(`Downloading the bundle of case ${key} failed (${response.status}).`);\n await writeFile(join(dir, `${key}.tar`), gunzipSync(Buffer.from(await response.arrayBuffer()), { maxOutputLength: DOWNLOAD_MAX_TAR_BYTES }));\n }\n console.error(`Downloaded ${evaluation.cases.length} case bundle${evaluation.cases.length === 1 ? '' : 's'} to ${dir}`);\n}\n\nasync function listCases(ctx: Context): Promise<void> {\n const evaluation = await getEval(ctx.apiUrl, ctx.token, target(ctx, 'cases'));\n const { cases } = evaluation;\n const download = getScalarArgValue(ctx.argv, '--download');\n if (download) await downloadBundles(ctx, evaluation, download);\n writeRawOutput(\n ctx.json\n ? JSON.stringify(cases, null, 2)\n : cases.map((c) => `${c.key} ${c.bundleSha256.slice(0, 12)} ${c.bundleBytes} bytes ${c.title} [${c.source}]`).join('\\n') || 'No cases.'\n );\n}\n\nasync function showRunbook(ctx: Context): Promise<void> {\n const name = target(ctx, 'runbook');\n const text = await requestText(ctx.apiUrl, ctx.token, `${EVALS}/${encodeURIComponent(name)}/runbook`);\n writeRawOutput(ctx.json ? JSON.stringify({ name, runbook: text }, null, 2) : text.trimEnd());\n}\n\nasync function removeCase(ctx: Context): Promise<void> {\n const name = target(ctx, 'rm-case');\n const key = ctx.positionals[1];\n if (!key) throw new Error(`Usage: cofactor eval ${USAGE['rm-case']}`);\n const evaluation = await getEval(ctx.apiUrl, ctx.token, name);\n await request(ctx.apiUrl, ctx.token, 'DELETE', `${EVALS}/${encodeURIComponent(evaluation.id)}/cases/${encodeURIComponent(key)}`);\n writeRawOutput(ctx.json ? JSON.stringify({ eval: name, key, deleted: true }) : `Removed case ${key} from ${name}`);\n}\n\nasync function addCase(ctx: Context): Promise<void> {\n const { argv, apiUrl, token, json } = ctx;\n const name = target(ctx, 'add-case');\n const key = required(argv, '--key');\n const input = required(argv, '--input');\n const expectedSource = expectedArg(argv);\n const source = required(argv, '--source');\n const conversationFile = getScalarArgValue(argv, '--conversation');\n if (!/^[a-z0-9][a-z0-9-]{0,99}$/.test(key))\n throw new Error('--key must be lowercase letters, digits and dashes, starting with a letter or digit (at most 100 characters).');\n\n const expected = await readJson(expectedSource, expectedSource === '-' ? 'the expected value on stdin' : `--expected ${expectedSource}`);\n let conversation: unknown;\n if (conversationFile) {\n const parsed = EvalConversationSchema.safeParse(await readJson(conversationFile, `--conversation ${conversationFile}`));\n if (!parsed.success)\n throw new TemplateError(`${conversationFile} is not a valid conversation:`, formatIssues(parsed.error));\n conversation = parsed.data;\n }\n\n const evaluation = await getEval(apiUrl, token, name);\n const multiTurn = evaluation.definition.mode === 'multi-turn';\n if (multiTurn && !conversation) throw new Error(`${name} is multi-turn: pass --conversation <file.json>.`);\n if (!multiTurn && conversation) throw new Error(`${name} is single-turn: --conversation is only for multi-turn evals.`);\n\n const bundle = await loadBundle(input);\n const missing = missingRequiredPaths(bundle.entries, evaluation.definition.input.require);\n if (missing.length)\n throw new Error(`The bundle is missing required input path(s): ${missing.join(', ')} (the template's input.require).`);\n\n const evalPath = `${EVALS}/${encodeURIComponent(evaluation.id)}`;\n const upload = await request<UploadReply>(apiUrl, token, 'POST', `${evalPath}/uploads`, {\n sha256: bundle.sha256,\n gzipSha256: bundle.gzipSha256,\n bytes: bundle.bytes,\n });\n const deduplicated = upload.status === 'exists';\n if (upload.status === 'upload') {\n const response = await fetch(upload.url, { method: 'PUT', headers: upload.headers, body: new Uint8Array(bundle.archive) });\n if (!response.ok)\n throw new Error(`Uploading the bundle failed (${response.status}): ${(await response.text()).slice(0, 300)}`);\n }\n await request(apiUrl, token, 'POST', `${evalPath}/cases`, {\n key,\n title: getScalarArgValue(argv, '--title') ?? key,\n sha256: bundle.sha256,\n expected,\n source,\n ...(conversation ? { conversation } : {}),\n });\n const result = { eval: name, key, sha256: bundle.sha256, bytes: bundle.bytes, deduplicated };\n writeRawOutput(\n json\n ? JSON.stringify(result, null, 2)\n : `Added case ${key} to ${name}\\nsha256 ${bundle.sha256} (${bundle.bytes} bytes local gzip), ${deduplicated ? 'deduplicated: the bundle already existed' : 'uploaded'}`\n );\n}\n\n/** One handler per authenticated sub-command; a number is the process exit code. */\nconst HANDLERS: Record<Exclude<Command, 'init' | 'guide'>, (ctx: Context) => Promise<number | void>> = {\n push,\n show: showEval,\n runbook: showRunbook,\n list: listEvals,\n cases: listCases,\n 'rm-case': removeCase,\n 'add-case': addCase,\n run: (ctx) => runEval(ctx.argv, target(ctx, 'run'), ctx.apiUrl, ctx.token),\n get: (ctx) => getRun(ctx.argv, target(ctx, 'get'), ctx.apiUrl, ctx.token),\n runs: (ctx) => listRuns(ctx.argv, target(ctx, 'runs'), ctx.apiUrl, ctx.token),\n compare: (ctx) => compareRuns(ctx.argv, ctx.positionals, ctx.apiUrl, ctx.token),\n};\n\nexport async function runEvalCommand(argv: string[]): Promise<void> {\n const [command, ...rest] = argv;\n if (!command || command === 'help' || hasFlag(argv, '--help', '-h')) {\n printHelp(command === 'help' ? rest[0] : command);\n return;\n }\n if (command === 'guide') {\n await printServedGuide('eval', rest);\n return;\n }\n let code = 0;\n try {\n if (!Object.hasOwn(USAGE, command)) throw new Error(`Unknown eval command: ${command}`);\n const cmd = command as Exclude<Command, 'guide'>;\n // Require the identity selector before authentication or any mutating request.\n if (WRITES.includes(cmd)) required(rest, '--org');\n // --expected is checked by expectedArg: its value may be a bare \"-\".\n for (const flag of VALUE_FLAGS.filter((flag) => flag !== '--expected')) {\n if (rest.includes(flag) && getScalarArgValue(rest, flag) === undefined) throw new Error(`${flag} requires a value.`);\n }\n const positionals = getPositionalArgs(rest, VALUE_FLAGS);\n // Usage errors come before authentication.\n if (positionals.length < (POSITIONALS[cmd] ?? 0)) throw new Error(`Usage: cofactor eval ${USAGE[cmd]}`);\n if (cmd === 'init') {\n await init(rest);\n } else {\n const { apiUrl, token } = await resolveConfig(rest);\n const ctx = { argv: rest, positionals, apiUrl, token, json: hasFlag(rest, '--json') };\n code = (await HANDLERS[cmd](ctx)) ?? 0;\n }\n } catch (error) {\n console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);\n code = 1;\n }\n if (code !== 0) process.exit(code);\n}\n","/**\n * Agent evaluation shared contracts.\n * @module agent-eval-template\n * @see docs/project/conventions.md\n */\nimport { z } from 'zod';\n\nexport const AGENT_EVAL_MAX_BUNDLE_BYTES = 512 * 1024 ** 2;\nexport const AGENT_EVAL_MAX_TOTAL_BUNDLE_BYTES = 2 * 1024 ** 3;\n\nconst ModelSchema = z.strictObject({\n provider: z.enum(['anthropic', 'azure']),\n model: z.string().min(1),\n});\n\n// Upper case like sandbox secret names; EVAL_* is the attempt's own contract and would be overwritten.\nconst EnvName = z\n .string()\n .regex(/^[A-Z_][A-Z0-9_]*$/, 'Must be an upper-case environment variable name')\n .refine((name) => !name.startsWith('EVAL_'), 'EVAL_ names are reserved for the attempt environment');\n/**\n * Where an agent reads its model configuration: the env var names the attempt sets for one provider. An entry\n * replaces all of that provider's standard names (spec D8; azure's two key and two URL names become one each) and is\n * needed only when the agent reads other names.\n */\nconst ProviderEnvSchema = z.strictObject({\n env: z\n .strictObject({\n apiKey: EnvName, // gets the attempt's scoped proxy token\n baseUrl: EnvName, // gets the proxy URL for the provider's wire\n model: EnvName, // gets the model id\n })\n .refine((env) => new Set(Object.values(env)).size === 3, 'apiKey, baseUrl and model must be different names'),\n});\n\nconst ScriptGrader = z.strictObject({\n id: z.string().regex(/^[a-z0-9-]+$/),\n kind: z.literal('script'),\n command: z.string().min(1),\n});\nconst JudgeGrader = z.strictObject({\n id: z.string().regex(/^[a-z0-9-]+$/),\n kind: z.literal('ai-judge'),\n rubric: z.string().min(20),\n scale: z.enum(['binary', '1-5']),\n passAt: z.number().int().min(2).max(5).optional(), // required when scale is '1-5'\n judge: ModelSchema,\n});\n\nexport const AgentEvalTemplateSchema = z\n .strictObject({\n version: z.literal(1),\n name: z\n .string()\n .regex(/^[a-z0-9-]{2,40}$/)\n .refine((n) => n !== 'runs' && n !== 'compare'), // reserved route segments\n description: z.string().min(1).max(500),\n proves: z.strictObject({ capabilities: z.array(z.string().regex(/^CAP-/)).min(1) }), // resolved within the application given at push\n runbook: z.string().min(1), // path relative to this file\n mode: z.enum(['single-turn', 'multi-turn']).default('single-turn'),\n run: z.string().min(1), // shell command, cwd = repo root of the commit; multi-turn: the agent process, JSONL on stdin/stdout\n simulator: ModelSchema.optional(), // required when mode is multi-turn: pins the simulated-user model\n input: z.strictObject({\n description: z.string().min(1),\n require: z.array(z.string()).default([]),\n }),\n agent: z.strictObject({\n models: z\n .record(z.string().regex(/^[a-z0-9-]+$/), ModelSchema)\n .refine((m) => Object.keys(m).length >= 1),\n default: z.string(), // must be a key of models\n providers: z\n .strictObject({ anthropic: ProviderEnvSchema.optional(), azure: ProviderEnvSchema.optional() })\n .optional(), // absent, or an absent entry: the standard names; every entry's provider must be used by a model\n }),\n graders: z.array(z.discriminatedUnion('kind', [ScriptGrader, JudgeGrader])).min(1),\n repeats: z.number().int().min(1).max(7).default(3),\n passAtLeast: z.number().int().min(1).default(2), // <= repeats\n passBar: z.number().min(0.1).max(1), // minimum case pass rate for the eval to pass\n attemptSeconds: z.number().int().min(30).max(1700), // grader commands get a fixed 120 s\n })\n .superRefine((template, ctx) => {\n if (!Object.hasOwn(template.agent.models, template.agent.default)) {\n ctx.addIssue({\n code: 'custom',\n path: ['agent', 'default'],\n message: 'Default must name an agent model alias',\n });\n }\n const used = new Set<string>(Object.values(template.agent.models).map((m) => m.provider));\n for (const [provider, entry] of Object.entries(template.agent.providers ?? {})) {\n if (entry && !used.has(provider)) {\n ctx.addIssue({\n code: 'custom',\n path: ['agent', 'providers', provider],\n message: `No agent model uses provider ${provider}; remove this entry or add a model that uses it`,\n });\n }\n }\n if (template.passAtLeast > template.repeats) {\n ctx.addIssue({\n code: 'custom',\n path: ['passAtLeast'],\n message: 'passAtLeast must not exceed repeats',\n });\n }\n const ids = new Set<string>();\n template.graders.forEach((grader, index) => {\n if (ids.has(grader.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['graders', index, 'id'],\n message: 'Grader ids must be unique',\n });\n }\n ids.add(grader.id);\n if (grader.kind === 'ai-judge' && grader.scale === '1-5' && grader.passAt === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['graders', index, 'passAt'],\n message: 'A 1-5 judge requires passAt',\n });\n }\n });\n if ((template.mode === 'multi-turn') !== (template.simulator !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n path: ['simulator'],\n message: 'A simulator is required exactly when mode is multi-turn',\n });\n }\n });\nexport type AgentEvalTemplate = z.infer<typeof AgentEvalTemplateSchema>;\n\n/** A multi-turn case's conversation; null on a single-turn case. */\nexport const EvalConversationSchema = z.discriminatedUnion('kind', [\n z.strictObject({ kind: z.literal('scripted'), turns: z.array(z.string().min(1)).min(1) }),\n z.strictObject({\n kind: z.literal('simulated'),\n persona: z.string().min(1),\n goal: z.string().min(1),\n facts: z.array(z.string()),\n stopWhen: z.string().min(1),\n maxTurns: z.number().int().min(2).max(30),\n }),\n]);\nexport type EvalConversation = z.infer<typeof EvalConversationSchema>;\n","/**\n * Case bundles for `cofactor eval add-case`: a deterministic tar of a directory (gzipped for\n * upload), a reader for an existing .tar.gz, and the `input.require` check. The content address\n * `sha256` is the hash of the uncompressed tar, which this file fully specifies, so the same files\n * give the same sha256 on any runtime and identical bundles deduplicate across cases and evals\n * (spec D4, D11). Gzip is transport only: its bytes depend on the runtime's zlib, so they are\n * hashed separately as `gzipSha256` for the upload's integrity check.\n */\nimport { createHash } from 'node:crypto';\nimport { lstat, readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { gunzipSync, gzipSync } from 'node:zlib';\nimport { AGENT_EVAL_MAX_BUNDLE_BYTES } from '@chatsdet/types/agent-eval-template';\n\nconst BLOCK = 512;\n// Memory guards for this process, not the server's limit (which is on the archive's bytes and is\n// enforced by the API): a directory's raw size, and what an archive may unpack to.\nconst MAX_RAW_BYTES = AGENT_EVAL_MAX_BUNDLE_BYTES;\nconst MAX_UNPACKED_BYTES = 4 * AGENT_EVAL_MAX_BUNDLE_BYTES;\n\n/** `sha256` addresses the uncompressed tar; `archive` is the gzip that gets uploaded, with its own hash and size. */\nexport type BundleSource = {\n sha256: string;\n gzipSha256: string;\n bytes: number;\n archive: Buffer;\n entries: string[];\n};\n\nconst sha256Hex = (data: Buffer): string => createHash('sha256').update(data).digest('hex');\n\nfunction octal(value: number, width: number): string {\n return `${value.toString(8).padStart(width - 1, '0')}\\0`;\n}\n\n/** Split a path into the ustar `prefix` and `name` fields, which hold 155 and 100 bytes. */\nfunction splitName(path: string): { prefix: string; name: string } {\n if (Buffer.byteLength(path) <= 100) return { prefix: '', name: path };\n for (let i = path.indexOf('/'); i !== -1; i = path.indexOf('/', i + 1)) {\n const prefix = path.slice(0, i);\n const name = path.slice(i + 1);\n if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(name) <= 100) return { prefix, name };\n }\n throw new Error(`Path is too long for a bundle (limit 255 bytes): ${path}`);\n}\n\nfunction header(path: string, size: number, type: '0' | '5', mode: number): Buffer {\n const { prefix, name } = splitName(path);\n const block = Buffer.alloc(BLOCK);\n block.write(name, 0, 'utf8');\n block.write(octal(mode, 8), 100, 'ascii');\n block.write(octal(0, 8), 108, 'ascii'); // uid\n block.write(octal(0, 8), 116, 'ascii'); // gid\n block.write(octal(size, 12), 124, 'ascii');\n block.write(octal(0, 12), 136, 'ascii'); // fixed mtime\n block.fill(0x20, 148, 156); // checksum placeholder is spaces\n block.write(type, 156, 'ascii');\n block.write('ustar\\0', 257, 'ascii');\n block.write('00', 263, 'ascii');\n // uname and gname stay empty: no owner names in the archive.\n block.write(prefix, 345, 'utf8');\n const checksum = block.reduce((sum, byte) => sum + byte, 0);\n block.write(`${checksum.toString(8).padStart(6, '0')}\\0 `, 148, 'ascii');\n return block;\n}\n\ntype Entry = { path: string; absolute: string; directory: boolean; mode: number; size: number };\n\n/** Entries in byte order of their NFC-normalized names, so macOS (NFD) and Linux file systems agree. */\nasync function walk(root: string, real = '', archive = ''): Promise<Entry[]> {\n const names = (await readdir(real ? join(root, real) : root))\n .map((name) => ({ real: name, archive: name.normalize('NFC') }))\n .sort((a, b) => Buffer.compare(Buffer.from(a.archive), Buffer.from(b.archive)));\n const entries: Entry[] = [];\n for (const name of names) {\n const realPath = real ? `${real}/${name.real}` : name.real;\n const path = archive ? `${archive}/${name.archive}` : name.archive;\n const absolute = join(root, realPath);\n const stats = await lstat(absolute);\n if (stats.isDirectory()) {\n entries.push({ path, absolute, directory: true, mode: 0o755, size: 0 });\n entries.push(...(await walk(root, realPath, path)));\n } else if (stats.isFile()) {\n entries.push({\n path,\n absolute,\n directory: false,\n mode: stats.mode & 0o111 ? 0o755 : 0o644,\n size: stats.size,\n });\n } else {\n throw new Error(\n `Cannot bundle ${path}: only regular files and directories are supported (no symlinks or devices).`\n );\n }\n }\n return entries;\n}\n\n/** Tar a directory deterministically: sorted entries, mtime 0, uid and gid 0, no owner names. */\nexport async function tarDirectory(root: string): Promise<Buffer> {\n const entries = await walk(root);\n const total = entries.reduce((sum, entry) => sum + entry.size, 0);\n if (total > MAX_RAW_BYTES) {\n throw new Error(`The input directory holds ${total} bytes; the CLI bundles at most ${MAX_RAW_BYTES}. Prune it.`);\n }\n const parts: Buffer[] = [];\n for (const entry of entries) {\n if (entry.directory) {\n parts.push(header(`${entry.path}/`, 0, '5', entry.mode));\n continue;\n }\n const content = await readFile(entry.absolute);\n parts.push(header(entry.path, content.length, '0', entry.mode), content);\n const padding = (BLOCK - (content.length % BLOCK)) % BLOCK;\n if (padding) parts.push(Buffer.alloc(padding));\n }\n parts.push(Buffer.alloc(BLOCK * 2));\n return Buffer.concat(parts);\n}\n\nfunction readString(block: Buffer, start: number, length: number): string {\n const slice = block.subarray(start, start + length);\n const end = slice.indexOf(0);\n return slice.subarray(0, end === -1 ? length : end).toString('utf8');\n}\n\nfunction normalize(path: string): string {\n return path.replace(/^(\\.\\/)+/, '').replace(/\\/+$/, '');\n}\n\n/** Entry paths of an uncompressed tar (ustar, GNU long names and pax `path` records). */\nexport function listTarEntries(tar: Buffer): string[] {\n const entries: string[] = [];\n let longName: string | null = null;\n let offset = 0;\n while (offset + BLOCK <= tar.length) {\n const block = tar.subarray(offset, offset + BLOCK);\n if (block.every((byte) => byte === 0)) break;\n const stored = Number.parseInt(readString(block, 148, 8).trim(), 8);\n const actual = block.reduce((sum, byte, i) => sum + (i >= 148 && i < 156 ? 0x20 : byte), 0);\n if (stored !== actual) throw new Error('not a valid tar archive (bad header checksum)');\n const size = Number.parseInt(readString(block, 124, 12).trim() || '0', 8);\n const type = String.fromCharCode(block[156] || 0x30);\n const body = tar.subarray(offset + BLOCK, offset + BLOCK + size);\n offset += BLOCK + Math.ceil(size / BLOCK) * BLOCK;\n if (type === 'L') {\n longName = readString(body, 0, body.length);\n continue;\n }\n if (type === 'x') {\n const record = body.toString('utf8').match(/\\d+ path=([^\\n]*)\\n/);\n if (record?.[1]) longName = record[1];\n continue;\n }\n if (type === 'g') continue;\n const prefix = readString(block, 345, 155);\n if (['1', '2', '3', '4', '6'].includes(type))\n throw new Error(`the archive holds a link or device entry (${readString(block, 0, 100)}); only files and directories are supported`);\n const name = longName ?? (prefix ? `${prefix}/${readString(block, 0, 100)}` : readString(block, 0, 100));\n longName = null;\n entries.push(normalize(name));\n }\n return entries;\n}\n\n/** Load an input (a directory or a .tar.gz) as a bundle, with its entry list, the tar's sha256 and the gzip's size and hash. */\nexport async function loadBundle(input: string): Promise<BundleSource> {\n let stats;\n try {\n stats = await lstat(input);\n } catch {\n throw new Error(`--input ${input} does not exist.`);\n }\n let tar: Buffer;\n if (stats.isDirectory()) {\n tar = await tarDirectory(input);\n } else if (stats.isFile() && /\\.(tar\\.gz|tgz)$/.test(input)) {\n if (stats.size > AGENT_EVAL_MAX_BUNDLE_BYTES)\n throw new Error(`${input} is ${stats.size} bytes; a bundle is limited to ${AGENT_EVAL_MAX_BUNDLE_BYTES}. Prune it.`);\n const gzip = await readFile(input);\n try {\n tar = gunzipSync(gzip, { maxOutputLength: MAX_UNPACKED_BYTES });\n } catch {\n throw new Error(`--input ${input} is not a valid gzip file, or unpacks to more than ${MAX_UNPACKED_BYTES} bytes.`);\n }\n } else {\n throw new Error('--input must be a directory or a .tar.gz file.');\n }\n // Always re-gzipped here, even for a .tar.gz input: the upload is then a single-member gzip from\n // this CLI, whatever the input held. Gzip is transport only; the content address is the tar's hash.\n const archive = gzipSync(tar, { level: 9 });\n let entries: string[];\n try {\n entries = listTarEntries(tar);\n } catch (error) {\n throw new Error(`--input ${input}: ${error instanceof Error ? error.message : String(error)}.`);\n }\n return {\n sha256: sha256Hex(tar),\n gzipSha256: sha256Hex(archive),\n bytes: archive.length,\n archive,\n entries,\n };\n}\n\n/** The `input.require` paths the bundle does not contain (a path may name a file or a directory). */\nexport function missingRequiredPaths(entries: string[], required: string[]): string[] {\n return required.filter((path) => {\n const wanted = normalize(path);\n return !entries.some((entry) => entry === wanted || entry.startsWith(`${wanted}/`));\n });\n}\n","/** `cofactor eval run|get|runs|compare`: start runs, wait for them and print their results. */\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { renderAgentEvalCompare, renderAgentEvalRun } from '@chatsdet/types/agent-eval-render';\nimport type {\n AgentEvalCompareResult,\n AgentEvalRunResult,\n AgentEvalTranscriptEntry,\n} from '@chatsdet/types/agent-eval-result';\nimport { hasFlag } from './auth.js';\nimport { writeRawOutput } from './brand.js';\nimport { getArgValues, getScalarArgValue } from './cli-helpers.js';\nimport { EVALS, getEval, request, requestTolerant } from './eval-api.js';\n\ntype RunStatus = AgentEvalRunResult['status'];\ntype Verdict = 'pass' | 'fail' | null;\n/** `GET /org/agent-evals/runs/:id`: the run row, its stored result once finished, and its attempts. */\ntype RunDetail = {\n id: string;\n batchId: string;\n status: RunStatus;\n verdict: Verdict;\n error: string | null;\n modelAlias: string;\n result: AgentEvalRunResult | null;\n attempts: { attemptIndex: number; transcript: AgentEvalTranscriptEntry[] | null; case: { key: string } }[];\n};\n/** One item of `GET /org/agent-evals/:name/runs`. */\ntype RunSummary = {\n id: string;\n batchId: string;\n modelAlias: string;\n commitSha: string;\n status: RunStatus;\n verdict: Verdict;\n error: string | null;\n};\n\n/** Tests shorten the interval. */\nexport const pollSettings = { intervalMs: 5000 };\n// The run job has an eight-hour budget; wait a little past it before giving up.\nconst WAIT_MS = 8.5 * 60 * 60 * 1000;\nconst MAX_TRANSIENT_FAILURES = 5;\nconst FINISHED: RunStatus[] = ['completed', 'failed', 'cancelled'];\n\nfunction intFlag(argv: string[], flag: string): number | undefined {\n const value = getScalarArgValue(argv, flag);\n if (value === undefined) return undefined;\n if (!/^\\d+$/.test(value)) throw new Error(`${flag} must be a whole number.`);\n return Number(value);\n}\n\nconst runPath = (id: string, transcript = false) =>\n `${EVALS}/runs/${encodeURIComponent(id)}${transcript ? '?transcript=1' : ''}`;\n\nconst describeRun = (run: RunDetail) =>\n `${run.id} ${run.modelAlias} ${run.status}${run.verdict ? ` ${run.verdict}` : ''}${run.error ? ` ${run.error}` : ''}`;\n\nconst stub = (run: RunDetail) => ({ id: run.id, status: run.status, verdict: run.verdict, error: run.error });\n\n/** 0 when every run passed, 1 for a failed or cancelled run, 3 when a run's verdict is fail. */\nfunction exitCodeFor(runs: { status: RunStatus; verdict: Verdict }[]): number {\n if (runs.some((run) => run.status !== 'completed')) return 1;\n return runs.some((run) => run.verdict !== 'pass') ? 3 : 0;\n}\n\n/**\n * Wait for every run of a batch. One light list request per tick covers the batch; each run's full\n * detail is fetched once when all are finished. Network errors and 5xx replies are tolerated up to\n * five in a row; auth and 4xx errors end the wait at once.\n */\nasync function waitForRuns(\n apiUrl: string,\n token: string,\n evalName: string,\n started: { batchId: string; runIds: string[] }\n): Promise<RunDetail[]> {\n const ids = `batch ${started.batchId}; runs ${started.runIds.join(', ')}`;\n let transient = 0;\n const get = async <T>(path: string): Promise<T | null> => {\n const reply = await requestTolerant<T>(apiUrl, token, path);\n if ('data' in reply) {\n transient = 0;\n return reply.data;\n }\n if (++transient >= MAX_TRANSIENT_FAILURES)\n throw new Error(`Giving up after ${transient} failed polls (${reply.transient}). Still readable: ${ids}.`);\n return null;\n };\n const deadline = Date.now() + WAIT_MS;\n for (;;) {\n if (Date.now() >= deadline)\n throw new Error(`Timed out waiting for the runs. Inspect them with cofactor eval get <run-id>: ${ids}.`);\n const page = await get<{ items: RunSummary[] }>(`${EVALS}/${encodeURIComponent(evalName)}/runs?limit=100`);\n if (page) {\n const statuses = new Map(page.items.map((item) => [item.id, item.status]));\n // A run beyond the first page is looked up directly.\n const known = await Promise.all(\n started.runIds.map(async (id) => statuses.get(id) ?? (await get<RunDetail>(runPath(id)))?.status)\n );\n if (known.every((status) => status !== undefined && FINISHED.includes(status))) break;\n }\n await sleep(pollSettings.intervalMs);\n }\n const details: RunDetail[] = [];\n for (const id of started.runIds) {\n let detail: RunDetail | null = null;\n while (!(detail = await get<RunDetail>(runPath(id)))) await sleep(pollSettings.intervalMs);\n details.push(detail);\n }\n return details;\n}\n\nexport async function runEval(argv: string[], name: string, apiUrl: string, token: string): Promise<number> {\n const json = hasFlag(argv, '--json');\n const models = getArgValues(argv, '--model');\n const cases = getArgValues(argv, '--case');\n const at = getScalarArgValue(argv, '--at');\n const environment = getScalarArgValue(argv, '--environment');\n const repeats = intFlag(argv, '--repeats');\n const parallel = intFlag(argv, '--parallel');\n const evaluation = await getEval(apiUrl, token, name);\n const started = await request<{ batchId: string; runIds: string[] }>(\n apiUrl,\n token,\n 'POST',\n `${EVALS}/${encodeURIComponent(evaluation.id)}/runs`,\n {\n ...(models.length ? { models } : {}),\n ...(environment ? { environment } : {}),\n ...(at ? { at } : {}),\n ...(cases.length ? { cases } : {}),\n ...(repeats !== undefined ? { repeats } : {}),\n ...(parallel !== undefined ? { parallel } : {}),\n }\n );\n if (hasFlag(argv, '--no-wait')) {\n writeRawOutput(\n json\n ? JSON.stringify(started, null, 2)\n : `Started batch ${started.batchId}\\n${started.runIds.join('\\n')}\\nRead results with: cofactor eval get <run-id> | cofactor eval compare --batch ${started.batchId}`\n );\n return 0;\n }\n // Printed before waiting so an interrupted or failed wait still leaves the ids to read results with.\n console.error(\n `Started batch ${started.batchId}; runs ${started.runIds.join(', ')}. If this is interrupted, read results with cofactor eval get <run-id> or cofactor eval compare --batch ${started.batchId}.`\n );\n const details = await waitForRuns(apiUrl, token, name, started);\n const results = details.flatMap((run) => (run.result ? [run.result] : []));\n if (json) {\n writeRawOutput(JSON.stringify(details.map((run) => run.result ?? stub(run)), null, 2));\n } else {\n const compare =\n details.length > 1 && results.length === details.length\n ? await request<AgentEvalCompareResult>(apiUrl, token, 'GET', `${EVALS}/compare?batch=${encodeURIComponent(started.batchId)}`)\n : null;\n if (results.length)\n writeRawOutput(\n [...results.map(renderAgentEvalRun), ...(compare ? [renderAgentEvalCompare(compare)] : [])].join('\\n').trimEnd()\n );\n for (const run of details.filter((run) => !run.result || run.status !== 'completed')) console.error(describeRun(run));\n }\n return exitCodeFor(details);\n}\n\nexport async function getRun(argv: string[], target: string, apiUrl: string, token: string): Promise<void> {\n const json = hasFlag(argv, '--json');\n const caseKey = getScalarArgValue(argv, '--case');\n const transcript = hasFlag(argv, '--transcript');\n if (transcript && !caseKey) throw new Error('--transcript needs --case <key>: transcripts are large, so the CLI prints one case at a time.');\n const run = await request<RunDetail>(apiUrl, token, 'GET', runPath(target, transcript));\n if (!run.result) {\n writeRawOutput(json ? JSON.stringify(stub(run), null, 2) : describeRun(run));\n return;\n }\n const result: AgentEvalRunResult = {\n ...run.result,\n cases: run.result.cases\n .filter((c) => caseKey === undefined || c.key === caseKey)\n .map((c) => ({\n ...c,\n attempts: c.attempts.map((attempt) => ({\n ...attempt,\n transcript: transcript\n ? (run.attempts.find((a) => a.case.key === c.key && a.attemptIndex === attempt.index)?.transcript ?? attempt.transcript)\n : attempt.transcript,\n })),\n })),\n };\n if (caseKey && result.cases.length === 0) throw new Error(`Run ${target} has no case \"${caseKey}\".`);\n if (json) {\n writeRawOutput(JSON.stringify(result, null, 2));\n return;\n }\n const lines = [renderAgentEvalRun(result).trimEnd()];\n if (transcript) {\n for (const attempt of result.cases.flatMap((c) => c.attempts)) {\n lines.push('', `Transcript, attempt ${attempt.index}:`);\n lines.push(\n ...(attempt.transcript?.length\n ? attempt.transcript.map((entry) => `${entry.role}: ${entry.text}`)\n : ['(none: this eval is not multi-turn, or the attempt did not run)'])\n );\n }\n }\n writeRawOutput(lines.join('\\n'));\n}\n\nexport async function listRuns(argv: string[], name: string, apiUrl: string, token: string): Promise<void> {\n const limit = intFlag(argv, '--limit');\n const page = await request<{ items: RunSummary[]; nextCursor: string | null }>(\n apiUrl,\n token,\n 'GET',\n `${EVALS}/${encodeURIComponent(name)}/runs${limit !== undefined ? `?limit=${limit}` : ''}`\n );\n writeRawOutput(\n hasFlag(argv, '--json')\n ? JSON.stringify(page, null, 2)\n : page.items\n .map((run) => `${run.id} ${run.modelAlias} ${run.status} ${run.verdict ?? '-'} ${run.commitSha.slice(0, 7)} batch ${run.batchId}`)\n .join('\\n') || 'No runs found.'\n );\n}\n\nexport async function compareRuns(argv: string[], ids: string[], apiUrl: string, token: string): Promise<void> {\n const batch = getScalarArgValue(argv, '--batch');\n if (Boolean(batch) === (ids.length > 0)) throw new Error('Use either one or more run ids or --batch <id>.');\n const query = batch ? `batch=${encodeURIComponent(batch)}` : `runs=${ids.map(encodeURIComponent).join(',')}`;\n const comparison = await request<AgentEvalCompareResult>(apiUrl, token, 'GET', `${EVALS}/compare?${query}`);\n writeRawOutput(\n hasFlag(argv, '--json') ? JSON.stringify(comparison.runs, null, 2) : renderAgentEvalCompare(comparison).trimEnd()\n );\n}\n","/** Pure markdown rendering shared by CLI and tests. Tokens per task are averaged here from server-provided case means. */\nimport type {\n AgentEvalCaseResult,\n AgentEvalCompareResult,\n AgentEvalRunResult,\n AgentEvalTokens,\n} from './agent-eval-result.js';\n\nconst cell = (value: string) => value.replaceAll('|', '\\\\|').replace(/\\r?\\n/g, ' ');\nconst percent = (value: number) => `${Math.round(value * 100)}%`;\nconst money = (cents: number | null, incomplete = false) =>\n cents === null ? 'unpriced' : `$${(cents / 100).toFixed(2)}${incomplete ? '*' : ''}`;\nconst minutes = (ms: number) => (ms / 60_000).toFixed(1);\nconst tokenCount = (n: number) =>\n n >= 1000 ? `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k` : `${Math.round(n)}`;\nconst tokenPair = (tokens: AgentEvalTokens) =>\n `${tokenCount(tokens.input)} / ${tokenCount(tokens.output)}`;\n/** Mean tokens per task, averaged from the server's per-case means; shared by the CLI markdown and the run page. */\nexport const meanTaskTokens = (result: AgentEvalRunResult): AgentEvalTokens => {\n const cases = result.cases;\n const mean = (key: keyof AgentEvalTokens) =>\n cases.length ? cases.reduce((n, c) => n + c.tokensPerAttempt[key], 0) / cases.length : 0;\n return {\n input: mean('input'),\n output: mean('output'),\n cacheRead: mean('cacheRead'),\n cacheCreation: mean('cacheCreation'),\n };\n};\nconst verdict = (r: AgentEvalRunResult) => (r.verdict ?? r.status).toUpperCase();\n\nexport function renderAgentEvalRun(result: AgentEvalRunResult): string {\n const s = result.summary;\n const taskTokens = meanTaskTokens(result);\n const warning = result.warnings.length\n ? ` [WARNING: ${result.warnings.map(cell).join('; ')}]`\n : '';\n // userSim is non-null exactly for a multi-turn eval (D16); single-turn output stays unchanged.\n const multiTurn = s.userSim !== null;\n const turnsToSuccess = (c: AgentEvalCaseResult) => {\n const passing = c.attempts.flatMap((a) => (a.passed && a.turns !== null ? [a.turns] : []));\n return passing.length ? (passing.reduce((n, t) => n + t, 0) / passing.length).toFixed(1) : '-';\n };\n const lines = [\n `## Eval ${cell(result.eval)}: ${verdict(result)} (${s.casesPassed}/${s.cases} cases, bar ${percent(result.passBar)}) — ${cell(result.model.alias)} (${cell(result.model.id)}) @ ${result.commit.slice(0, 7)}, ${result.repeats} repeats${warning}`,\n '',\n `| Case | Result | Attempts | Score | ${multiTurn ? 'Turns | ' : ''}Cost/attempt | Time/attempt | Tokens in/out |`,\n `|---|---|---|---|${multiTurn ? '---|' : ''}---|---|---|`,\n ...result.cases.map(\n (c) =>\n `| ${cell(c.key)} | ${c.passed ? 'PASS' : 'FAIL'} | ${c.passedAttempts}/${c.attempts.length} | ${c.meanScore.toFixed(1)} | ${multiTurn ? `${turnsToSuccess(c)} | ` : ''}${money(\n c.costCentsPerAttempt,\n c.attempts.some((a) => !a.costComplete)\n )} | ${minutes(c.durationMsPerAttempt)} min | ${tokenPair(c.tokensPerAttempt)} |`\n ),\n '',\n `Per task: ${money(s.costCentsPerTask, s.incompleteCalls > 0)} | ${minutes(s.durationMsPerTask)} min | ${tokenCount(taskTokens.input)} in / ${tokenCount(taskTokens.output)} out. Total: ${money(s.costCents, s.incompleteCalls > 0)} for ${s.attempts} attempts, ${Math.round(result.cases.flatMap((c) => c.attempts).reduce((n, a) => n + a.durationMs, 0) / 60_000)} min of agent time.`,\n ];\n const judges = [\n ...new Set(\n result.cases\n .flatMap((c) => c.attempts.flatMap((a) => a.grades))\n .filter((g) => g.kind === 'ai-judge')\n .map((g) => g.judgeModel)\n ),\n ];\n lines.push(\n `Judge (${judges.length ? judges.map((m) => cell(m ?? 'unknown')).join(', ') : 'none'}, pinned): ${s.judge.calls} calls, ${money(s.judge.costCents)}, not included above.`\n );\n if (s.userSim) {\n const models = [\n ...new Set(\n result.cases.flatMap((c) =>\n c.attempts.flatMap((a) => a.calls.filter((call) => call.role === 'user-sim').map((call) => call.model))\n )\n ),\n ];\n lines.push(\n `User-sim (${models.length ? models.map(cell).join(', ') : 'none'}, pinned): ${s.userSim.calls} calls, ${money(s.userSim.costCents)}, not included above.`\n );\n }\n const failures = result.cases.flatMap((c) =>\n c.attempts.flatMap((a) => [\n ...a.grades\n .filter((g) => !g.pass)\n .map((g) => `${cell(c.key)} #${a.index}: ${cell(g.grader)}: ${cell(g.reason)}`),\n ...(a.error && !a.grades.some((g) => !g.pass && (g.reason === a.error || g.error === a.error))\n ? [`${cell(c.key)} #${a.index}: ${cell(a.error)}`]\n : []),\n ])\n );\n lines.push(`Failed grades: ${failures.length ? failures.join('; ') : 'none'}.`);\n if (result.error) lines.push(`Error: ${cell(result.error)}.`);\n if (s.incompleteCalls) lines.push('* Cost is a lower bound because agent calls were incomplete.');\n lines.push(\n `Warnings: ${result.warnings.length ? result.warnings.map(cell).join('; ') : 'none'}. Run: ${result.id}.`\n );\n return `${lines.join('\\n')}\\n`;\n}\n\nexport function renderAgentEvalCompare(result: AgentEvalCompareResult): string {\n const lines = [\n `## Eval compare: ${cell(result.eval)} @ ${result.commit.slice(0, 7)}${result.batchId ? ` (batch ${result.batchId})` : ''}`,\n '',\n '| Model | Verdict | Pass rate | Mean score | Cost/task | Time/task | Tokens/task in/out |',\n '|---|---|---|---|---|---|---|',\n ...result.runs.map(\n (r) =>\n `| ${cell(r.model.alias)} (${cell(r.model.id)}) | ${verdict(r)} | ${percent(r.summary.passRate)} | ${r.summary.meanScore.toFixed(1)} | ${money(r.summary.costCentsPerTask, r.summary.incompleteCalls > 0)} | ${minutes(r.summary.durationMsPerTask)} min | ${tokenPair(meanTaskTokens(r))} |`\n ),\n '',\n `| Case | ${result.runs.map((r) => cell(r.model.alias)).join(' | ')} |`,\n `|---|${result.runs.map(() => '---|').join('')}`,\n ...result.cases.map(\n (c) =>\n `| ${cell(c.key)} | ${c.models\n .map(\n ({ result: r }) =>\n `${r.passedAttempts}/${r.attempts.length} ${r.passed ? 'PASS' : 'FAIL'} ${money(\n r.costCentsPerAttempt,\n r.attempts.some((a) => !a.costComplete)\n )} ${minutes(r.durationMsPerAttempt)}m`\n )\n .join(' | ')} |`\n ),\n ];\n for (const r of result.runs)\n if (r.warnings.length)\n lines.push(`Warnings (${cell(r.model.alias)}): ${r.warnings.map(cell).join('; ')}.`);\n if (result.runs.some((r) => r.summary.incompleteCalls > 0))\n lines.push('* Cost is a lower bound because agent calls were incomplete.');\n return `${lines.join('\\n')}\\n`;\n}\n","/** Authoring side of `cofactor eval`: the `init` files and the local checks `push` runs. */\nimport { readFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, relative, resolve, sep } from 'node:path';\nimport { parse } from 'yaml';\nimport type { ZodError } from 'zod';\nimport {\n AgentEvalTemplateSchema,\n type AgentEvalTemplate,\n} from '@chatsdet/types/agent-eval-template';\n\n/** `eval init` writes this line first in every runbook section; `eval push` refuses a runbook that still has one. */\nexport const RUNBOOK_TODO_MARKER = '<!-- cofactor:todo -->';\n\n/** The fixed runbook headings, in order, each with the prompt `eval init` writes under it. */\nexport const RUNBOOK_SECTIONS: readonly { heading: string; prompt: string }[] = [\n {\n heading: 'What this eval proves',\n prompt: \"Describe the agent's job in one paragraph and the capabilities it backs.\",\n },\n {\n heading: 'Anatomy of a case',\n prompt:\n 'List the files in $EVAL_INPUT, what the expected value holds, and what a good case teaches.',\n },\n {\n heading: 'Finding real data',\n prompt:\n 'Say where in production the inputs live: exact cofactor commands, queries and ids, and how to pick varied cases.',\n },\n {\n heading: 'Labeling',\n prompt:\n 'Say how the expected value is decided and what must corroborate it; never the agent\\'s own output alone.',\n },\n {\n heading: 'Sanitizing',\n prompt:\n 'Say what to strip or replace before upload, the check to run, and the neutral names to use (Acme, example.com).',\n },\n {\n heading: 'Synthesizing scenarios',\n prompt:\n 'Say how to make a case when no real one exists (mutate a frozen input) and how to mark it synthetic in --source.',\n },\n {\n heading: 'Adding the case',\n prompt: 'Give the exact eval add-case command shape for this eval.',\n },\n { heading: 'Known traps', prompt: 'Record what has gone wrong before.' },\n];\n\n/** Headings whose section must not be empty: real data and sanitizing are what keep customer data out of cases. */\nconst REQUIRED_SECTIONS = ['Finding real data', 'Sanitizing'];\n\nexport const EVAL_GITIGNORE = '*.tar.gz\\n_staging/\\n';\n\nexport function initRunbook(name: string): string {\n return [\n `# ${name} runbook`,\n '',\n ...RUNBOOK_SECTIONS.flatMap(({ heading, prompt }) => [`## ${heading}`, '', RUNBOOK_TODO_MARKER, `<!-- ${prompt} -->`, '']),\n ].join('\\n');\n}\n\nexport function initTemplate(opts: {\n name: string;\n application?: string;\n capability?: string;\n}): string {\n const capability = opts.capability ?? 'CAP-REPLACE-ME';\n const application = opts.application ?? '<application>';\n return `# Agent eval: ${opts.name}\n# Push it with:\n# cofactor eval push evals/${opts.name}.eval.yaml --application ${application} --org <org>\n# Add cases with:\n# cofactor eval add-case ${opts.name} --key <key> --input <dir> --expected <file> --source \"<provenance>\" --org <org>\n# Run it with:\n# cofactor eval run ${opts.name} --org <org>\nversion: 1\nname: ${opts.name}\ndescription: Replace with one sentence on what this agent must get right.\n\n# Capabilities in the application's product map that this eval proves (CAP- codes).\nproves:\n capabilities:\n - ${capability}\n\n# Runbook for whoever adds cases; path relative to this file. Stored with the eval.\nrunbook: ${opts.name}.runbook.md\n\n# single-turn: \\`run\\` is executed once per attempt. multi-turn: \\`run\\` is the agent process,\n# speaking JSONL on stdin/stdout, and a \\`simulator\\` model is required (cases then need a conversation).\nmode: single-turn\n\n# Shell command run at the repository root of the evaluated commit. It reads its case from\n# $EVAL_INPUT and writes its answer to $EVAL_OUTPUT/answer.* (answer.json, answer.txt, ...).\n# Model calls go to the injected base URL (agent.providers below); never use a real key.\nrun: ./scripts/run-agent.sh\n\ninput:\n description: What the files in a case's input directory contain.\n # Paths every case bundle must contain (files or directories); checked before upload.\n require:\n - input.json\n\nagent:\n models:\n # alias: provider (anthropic | azure) and model id. Aliases are what --model takes.\n sonnet:\n provider: anthropic\n model: claude-sonnet-4-6\n default: sonnet\n # Each attempt sets the selected provider's key (a proxy token), base URL (the metering proxy) and\n # model id, under these standard names unless an entry below maps them:\n # anthropic: ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL, ANTHROPIC_MODEL\n # azure: OPENAI_API_KEY, AZURE_OPENAI_API_KEY, OPENAI_BASE_URL, AZURE_OPENAI_BASE_URL, OPENAI_MODEL\n # Only if the agent reads other names (upper case, never EVAL_*; an entry replaces all of that provider's\n # standard names), copy them from where its code builds the model client, e.g.\n # createAnthropic({ apiKey: process.env.AGENT_CLAUDE_KEY, baseURL: process.env.AGENT_CLAUDE_URL }):\n # providers:\n # anthropic:\n # env: { apiKey: AGENT_CLAUDE_KEY, baseUrl: AGENT_CLAUDE_URL, model: AGENT_CLAUDE_MODEL }\n\ngraders:\n # A script grader runs after the agent exits with EVAL_INPUT, EVAL_OUTPUT and EVAL_EXPECTED\n # (the case's expected value as a JSON file). Its last stdout line is\n # {\"pass\": true, \"score\": 1, \"reason\": \"why\"}. Anything else is a grader error.\n - id: answer-matches-expected\n kind: script\n command: ./scripts/grade-answer.sh\n\n # An ai-judge scores a rubric against the answer and the case's expected value.\n # The judge model is pinned. scale is binary or 1-5; a 1-5 scale requires passAt.\n - id: answer-quality\n kind: ai-judge\n rubric: The answer states the same root cause as the expected value and cites evidence from the input.\n scale: 1-5\n passAt: 4\n judge:\n provider: anthropic\n model: claude-opus-4-8\n\n# Each case runs \\`repeats\\` times and passes when at least \\`passAtLeast\\` attempts pass.\nrepeats: 3\npassAtLeast: 2\n\n# The eval passes when this share of cases pass.\npassBar: 0.5\n\n# Time limit per attempt, in seconds (30 to 1700).\nattemptSeconds: 600\n`;\n}\n\n/** Zod issues as one readable line each: `graders.1.passAt: A 1-5 judge requires passAt`. */\nexport function formatIssues(error: ZodError): string[] {\n return error.issues.map((issue) => {\n const path = issue.path.map(String).join('.');\n return `${path || '(template)'}: ${issue.message}`;\n });\n}\n\nexport class TemplateError extends Error {\n constructor(heading: string, lines: string[]) {\n super(`${heading}\\n${lines.map((line) => ` ${line}`).join('\\n')}`);\n }\n}\n\nexport type PushPayload = {\n definition: AgentEvalTemplate;\n runbook: string;\n warnings: string[];\n};\n\nfunction sectionBodies(runbook: string): Map<string, string> {\n const sections = new Map<string, string>();\n let current: string | null = null;\n for (const line of runbook.split(/\\r?\\n/)) {\n const heading = line.match(/^##\\s+(.+?)\\s*$/);\n if (heading) {\n current = heading[1]!;\n sections.set(current, '');\n } else if (current !== null) {\n sections.set(current, `${sections.get(current)}${line}\\n`);\n }\n }\n return sections;\n}\n\n/** Missing headings are warnings; an empty required section or a section still holding the todo marker is an error. */\nexport function checkRunbook(runbook: string): { errors: string[]; warnings: string[] } {\n const sections = sectionBodies(runbook);\n const errors: string[] = [];\n const warnings: string[] = [];\n const todo = [...sections].filter(([, body]) => body.split('\\n').some((line) => line.trim() === RUNBOOK_TODO_MARKER));\n if (todo.length) {\n errors.push(\n `Runbook still has ${RUNBOOK_TODO_MARKER} in: ${todo.map(([heading]) => `\"## ${heading}\"`).join(', ')}. Write each section, then delete its marker line.`\n );\n }\n for (const { heading } of RUNBOOK_SECTIONS) {\n const body = sections.get(heading);\n const empty = body === undefined || body.replace(/<!--[\\s\\S]*?-->/g, '').trim() === '';\n if (body === undefined) warnings.push(`Runbook has no \"## ${heading}\" section.`);\n if (REQUIRED_SECTIONS.includes(heading) && empty) {\n errors.push(`Runbook section \"## ${heading}\" is empty; write it before pushing.`);\n }\n }\n return { errors, warnings };\n}\n\n/** Parse and validate a template file and read its runbook, relative to the YAML. */\nexport async function readPushPayload(file: string): Promise<PushPayload> {\n let source: string;\n try {\n source = await readFile(file, 'utf8');\n } catch {\n throw new Error(`Cannot read ${file}.`);\n }\n let raw: unknown;\n try {\n raw = parse(source);\n } catch (error) {\n throw new Error(`${file} is not valid YAML: ${error instanceof Error ? error.message : String(error)}`);\n }\n const parsed = AgentEvalTemplateSchema.safeParse(raw);\n if (!parsed.success) throw new TemplateError(`${file} is not a valid eval template:`, formatIssues(parsed.error));\n const runbookPath = resolve(dirname(file), parsed.data.runbook);\n const inside = relative(dirname(resolve(file)), runbookPath);\n if (isAbsolute(parsed.data.runbook) || inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside))\n throw new Error(`The template's runbook (${parsed.data.runbook}) must be a path inside the template's directory.`);\n let runbook: string;\n try {\n runbook = await readFile(runbookPath, 'utf8');\n } catch {\n throw new Error(`Cannot read the runbook ${runbookPath} (the template's runbook: ${parsed.data.runbook}).`);\n }\n const { errors, warnings } = checkRunbook(runbook);\n if (errors.length) throw new TemplateError(`${runbookPath} cannot be pushed:`, errors);\n return { definition: parsed.data, runbook, warnings };\n}\n"],"mappings":";;;;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,IAAI,IAAI;AAC3B,MAAI,CAAC,WAAW,YAAY,UAAU,QAAQ,MAAM,UAAU,IAAI,GAAG;AACnE,cAAU,YAAY,SAAS,KAAK,CAAC,IAAI,OAAO;AAChD;AAAA,EACF;AACA,MAAI,YAAY,SAAS;AACvB,UAAM,iBAAiB,QAAQ,IAAI;AACnC;AAAA,EACF;AACA,MAAI,OAAO;AACX,MAAI;AACF,QAAI,CAAC,OAAO,OAAO,OAAO,OAAO,EAAG,OAAM,IAAI,MAAM,yBAAyB,OAAO,EAAE;AACtF,UAAM,MAAM;AAEZ,QAAI,OAAO,SAAS,GAAG,EAAG,UAAS,MAAM,OAAO;AAEhD,eAAW,QAAQ,YAAY,OAAO,CAACC,UAASA,UAAS,YAAY,GAAG;AACtE,UAAI,KAAK,SAAS,IAAI,KAAK,kBAAkB,MAAM,IAAI,MAAM,OAAW,OAAM,IAAI,MAAM,GAAG,IAAI,oBAAoB;AAAA,IACrH;AACA,UAAM,cAAc,kBAAkB,MAAM,WAAW;AAEvD,QAAI,YAAY,UAAU,YAAY,GAAG,KAAK,GAAI,OAAM,IAAI,MAAM,wBAAwB,MAAM,GAAG,CAAC,EAAE;AACtG,QAAI,QAAQ,QAAQ;AAClB,YAAM,KAAK,IAAI;AAAA,IACjB,OAAO;AACL,YAAM,EAAE,QAAQ,MAAM,IAAI,MAAM,cAAc,IAAI;AAClD,YAAM,MAAM,EAAE,MAAM,MAAM,aAAa,QAAQ,OAAO,MAAM,QAAQ,MAAM,QAAQ,EAAE;AACpF,aAAQ,MAAM,SAAS,GAAG,EAAE,GAAG,KAAM;AAAA,IACvC;AAAA,EACF,SAAS,OAAO;AACd,YAAQ,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAChF,WAAO;AAAA,EACT;AACA,MAAI,SAAS,EAAG,SAAQ,KAAK,IAAI;AACnC;","names":["readFile","readdir","gunzipSync","join","required","run","target","readFile","readFile","readFile","join","readdir","target","gunzipSync","flag"]}
|