@testmuai/kane-cli 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ChatSurface-R55VO3VW.js +9 -0
- package/dist/{ChromeProfilePicker-PIWZY4WH.js → ChromeProfilePicker-BZKLIO2T.js} +1 -1
- package/dist/{CliFeedbackPrompt-URXCHBZ5.js → CliFeedbackPrompt-3HYRBMXS.js} +1 -1
- package/dist/CliUploadProgress-OAPMO5I3.js +2 -0
- package/dist/{ConfigView-NWNDNTKW.js → ConfigView-YIAAISLE.js} +1 -1
- package/dist/EvidenceViewOffer-DBMZQ34Z.js +2 -0
- package/dist/FolderPicker-ILK4AIKL.js +2 -0
- package/dist/HelpView-HBQX64VR.js +2 -0
- package/dist/{InfoBox-FPAWQZGQ.js → InfoBox-DKJO73HM.js} +1 -1
- package/dist/{LinksBox-O5ZFYSK2.js → LinksBox-44WCVBT4.js} +1 -1
- package/dist/{ProfilesView-SPECXHZE.js → ProfilesView-NVEDYU3H.js} +1 -1
- package/dist/{ProjectPicker-ANJ6NGNY.js → ProjectPicker-COBY7TCY.js} +1 -1
- package/dist/{SaveSessionPrompt-W2GWELOP.js → SaveSessionPrompt-O4ENMYHP.js} +1 -1
- package/dist/ScrollbackTap-Q3IOKNMS.js +2 -0
- package/dist/SingleShotApp-NA6A2S6I.js +2 -0
- package/dist/{SummaryBox-DJUDYML7.js → SummaryBox-ROV7TNK4.js} +1 -1
- package/dist/TestMdRunView-U5YTNLY6.js +2 -0
- package/dist/{WhoamiView-DH25ZD4C.js → WhoamiView-4QV3DPN2.js} +1 -1
- package/dist/archive-committer-3NI773TP.js +2 -0
- package/dist/bind-RDTZZ6ZI.js +6 -0
- package/dist/bridge-VY2Q3HQU.js +2 -0
- package/dist/{changelog-RCKUVBFL.js → changelog-JMFGVNEU.js} +1 -1
- package/dist/chat-committer-RTJCKQMM.js +2 -0
- package/dist/chat-controller-OTBYHB4Y.js +3 -0
- package/dist/chunk-22A2ECA2.js +2 -0
- package/dist/{chunk-T4PKTWZ6.js → chunk-2PDWMY2B.js} +1 -1
- package/dist/{chunk-I4B2KY4X.js → chunk-2T4JPBB5.js} +1 -1
- package/dist/{chunk-AM5WZPPY.js → chunk-37CI4EJX.js} +1 -1
- package/dist/chunk-427OQS2N.js +2 -0
- package/dist/chunk-47RNFG2V.js +23 -0
- package/dist/{chunk-IECUFWIZ.js → chunk-4CRKK5WV.js} +1 -1
- package/dist/chunk-5446YVGQ.js +4 -0
- package/dist/{chunk-TJWU7DOO.js → chunk-5FD6ZXB5.js} +1 -1
- package/dist/chunk-5ILXUQIX.js +2 -0
- package/dist/chunk-5UXL6RNG.js +2 -0
- package/dist/chunk-5Y2G4NC7.js +2 -0
- package/dist/chunk-6PS65QFF.js +2 -0
- package/dist/chunk-7DBQEOFL.js +9 -0
- package/dist/{chunk-R5RHRG65.js → chunk-7SUKUJO2.js} +1 -1
- package/dist/{chunk-LOQV5GME.js → chunk-AAWRKFE4.js} +1 -1
- package/dist/chunk-AD46OCZ4.js +4 -0
- package/dist/chunk-AE6SS34N.js +4 -0
- package/dist/chunk-B2PZAB7J.js +4 -0
- package/dist/chunk-BC7UVJJB.js +2 -0
- package/dist/{chunk-DTM4ZMMJ.js → chunk-BMSWIYYK.js} +1 -1
- package/dist/{chunk-YSIYPC4R.js → chunk-CB3TEWZJ.js} +1 -1
- package/dist/chunk-CE664P73.js +2 -0
- package/dist/chunk-CP4XCWAJ.js +5 -0
- package/dist/chunk-D5T4ARTB.js +2 -0
- package/dist/chunk-DFS4RMVP.js +2 -0
- package/dist/chunk-DM2GL24Z.js +3 -0
- package/dist/{chunk-HZ46P2GR.js → chunk-FAIH2K2U.js} +1 -1
- package/dist/chunk-FS4YJM22.js +2 -0
- package/dist/chunk-FXPPQL4D.js +6 -0
- package/dist/chunk-FYOCF7DY.js +2 -0
- package/dist/chunk-GIGD4M7V.js +5 -0
- package/dist/chunk-GIRXJOJI.js +2 -0
- package/dist/chunk-HGL3RM7P.js +8 -0
- package/dist/{chunk-HFXQU7UZ.js → chunk-HMGNPFXP.js} +1 -1
- package/dist/chunk-I2S6KNZW.js +2 -0
- package/dist/chunk-IACKIGPX.js +2 -0
- package/dist/{chunk-C4LYBQT3.js → chunk-IRDMEYJB.js} +2 -2
- package/dist/{chunk-4IOOBSNB.js → chunk-ISAE457F.js} +1 -1
- package/dist/{chunk-AFCEFOIK.js → chunk-J5BUMF3G.js} +1 -1
- package/dist/chunk-JFAFKHDX.js +4 -0
- package/dist/{chunk-6E5UYAEB.js → chunk-KFAYCOTB.js} +1 -1
- package/dist/{chunk-UOGJUJCF.js → chunk-KGP7NSXH.js} +1 -1
- package/dist/chunk-KHDUQ33H.js +2 -0
- package/dist/chunk-KHU7C6EE.js +2 -0
- package/dist/chunk-LMJTY32X.js +6 -0
- package/dist/chunk-M5JQXOCE.js +12 -0
- package/dist/chunk-MJFYMMX2.js +2 -0
- package/dist/chunk-MMI3VSCA.js +6 -0
- package/dist/{chunk-NLIOFVMP.js → chunk-MZ2PXBKK.js} +1 -1
- package/dist/chunk-N2ZW5635.js +6 -0
- package/dist/chunk-NNZV5RCE.js +2 -0
- package/dist/{chunk-7IBNOVML.js → chunk-NSSKSXCT.js} +1 -1
- package/dist/{chunk-PISZLYS5.js → chunk-O4O4KL6Z.js} +1 -1
- package/dist/{chunk-QO6PAA7Q.js → chunk-OBBXDBEE.js} +2 -2
- package/dist/chunk-Q4P2L7DY.js +2 -0
- package/dist/chunk-Q4PUOA46.js +61 -0
- package/dist/chunk-QPZRHAYK.js +4 -0
- package/dist/chunk-QZWQCHXK.js +11 -0
- package/dist/{chunk-7AEC572G.js → chunk-R2K2SGGE.js} +1 -1
- package/dist/{chunk-3FN66LTP.js → chunk-RFHMDQXZ.js} +1 -1
- package/dist/chunk-RGEAEAZB.js +20 -0
- package/dist/{chunk-GEAWRRR7.js → chunk-RH2OAIJI.js} +1 -1
- package/dist/chunk-RKWJG3WW.js +19 -0
- package/dist/{chunk-IU53F4ZV.js → chunk-ROPXE7TF.js} +1 -1
- package/dist/chunk-RY4OOGSC.js +14 -0
- package/dist/chunk-S74MQRDN.js +2 -0
- package/dist/{chunk-ZWAZ4QU4.js → chunk-SB6MBQKR.js} +1 -1
- package/dist/{chunk-XDERMCAU.js → chunk-SQJWMOJQ.js} +1 -1
- package/dist/{chunk-ELBPBHTE.js → chunk-SUDAFBVD.js} +2 -2
- package/dist/chunk-VJUIW2ES.js +4 -0
- package/dist/chunk-VXD5667K.js +7 -0
- package/dist/chunk-WAGJLR5X.js +356 -0
- package/dist/chunk-WGG5XURS.js +13 -0
- package/dist/chunk-WRHZCHZY.js +2 -0
- package/dist/chunk-XDW2RGIL.js +7 -0
- package/dist/chunk-YANCBRER.js +3 -0
- package/dist/{chunk-THEZSXZM.js → chunk-YJ6AQ2KP.js} +1 -1
- package/dist/chunk-Z56AWGVY.js +2 -0
- package/dist/{chunk-PTP3WS3N.js → chunk-ZA67EBYF.js} +1 -1
- package/dist/chunk-ZKYYZ5NO.js +6 -0
- package/dist/{chunk-TPG2T5GH.js → chunk-ZNANAARA.js} +1 -1
- package/dist/cover-cmd-Y5L4O4Q3.js +2 -0
- package/dist/{credentials-52QRPGET.js → credentials-L63BBW2S.js} +1 -1
- package/dist/descriptor-SL5A7RQE.js +2 -0
- package/dist/distill-cmd-EYCCCFL3.js +2 -0
- package/dist/evidence-UAFPTHQX.js +2 -0
- package/dist/evolve-cmd-2SPNVTT4.js +2 -0
- package/dist/{exit-manager-IUHAXFJ6.js → exit-manager-VCSIUYBR.js} +1 -1
- package/dist/explain-JIXUWEFJ.js +2 -0
- package/dist/explain-cmd-55WRDIMW.js +9 -0
- package/dist/explain-cmd-RIDEMDMY.js +3 -0
- package/dist/extract-bind-DS4UP23P.js +5 -0
- package/dist/extract-cmd-PMZHMMU7.js +6 -0
- package/dist/gaps-cmd-P2DRK6FW.js +2 -0
- package/dist/gate-FACZRGOC.js +2 -0
- package/dist/{generate-headless-WG6ZPINI.js → generate-headless-C3UZKDS5.js} +2 -2
- package/dist/headless-io-GXHKDPHB.js +2 -0
- package/dist/index.js +55 -54
- package/dist/ingest-4CGBXC2L.js +2 -0
- package/dist/ingest-cmd-FJ3SLTT4.js +3 -0
- package/dist/interactive-bind-SJLDJULN.js +7 -0
- package/dist/interrupt-guard-UREUWNRL.js +2 -0
- package/dist/lifecycle-cmd-56OZT4LY.js +2 -0
- package/dist/list-cmd-JB2ABACD.js +3 -0
- package/dist/list-commands-PGAX5HRB.js +2 -0
- package/dist/logical-ids-QRRUXV5E.js +2 -0
- package/dist/login-flow-4OJ34VDP.js +2 -0
- package/dist/maintenance-cmd-E3HEEVQW.js +2 -0
- package/dist/open-MQLQKFAW.js +2 -0
- package/dist/{persist-recorded-session-XKPZX7HW.js → persist-recorded-session-WFU4M4SQ.js} +1 -1
- package/dist/pipeline-EYQUM27P.js +2 -0
- package/dist/readmodel-MPTENJ2R.js +2 -0
- package/dist/reconcile-cmd-TFFYCTCY.js +8 -0
- package/dist/{recording-banner-2TNKQHP2.js → recording-banner-PH2NND2X.js} +1 -1
- package/dist/{require-project-folder-SJG5FQY6.js → require-project-folder-RD2UAB7E.js} +1 -1
- package/dist/revert-3TKLOYQA.js +2 -0
- package/dist/review-cmd-SL52N4TM.js +4 -0
- package/dist/run-NODOSQUL.js +2 -0
- package/dist/run-test-md-I6O4H7B2.js +17 -0
- package/dist/{scrollback-6GINSTL2.js → scrollback-JLPJR25X.js} +1 -1
- package/dist/sessions-cmd-STHKGDX4.js +23 -0
- package/dist/signals-cmd-LXHZQLXZ.js +2 -0
- package/dist/{skill-installer-M6AREQQW.js → skill-installer-BJLHH3DW.js} +1 -1
- package/dist/spawner-UDCF35OA.js +2 -0
- package/dist/tcg-generate-E7H4LF7Y.js +2 -0
- package/dist/testmd-actions-FMVUXZGX.js +2 -0
- package/dist/token-refresh-OGBTJGZ2.js +2 -0
- package/dist/turn-preflight-I5SM4UIZ.js +2 -0
- package/dist/ui-JEJGTURD.js +4 -0
- package/dist/{validate-basic-FO7C2URG.js → validate-basic-WILRWRRP.js} +1 -1
- package/dist/{version-check-PHZX5WS7.js → version-check-TXTCVX2N.js} +1 -1
- package/dist/view-cmd-QE2FS3GB.js +436 -0
- package/package.json +6 -6
- package/dist/CliUploadProgress-DMH3C3UZ.js +0 -2
- package/dist/EvidenceViewOffer-HEBQ7C4H.js +0 -2
- package/dist/FolderPicker-5S23OTSY.js +0 -2
- package/dist/HelpView-YYKTP4JH.js +0 -2
- package/dist/SingleShotApp-5TYM356H.js +0 -2
- package/dist/TestMdRunView-BIVXQE54.js +0 -2
- package/dist/chunk-54TKNWXF.js +0 -5
- package/dist/chunk-5MTRNUAK.js +0 -2
- package/dist/chunk-7KDNH6JP.js +0 -10
- package/dist/chunk-7YRNLGUT.js +0 -11
- package/dist/chunk-C6S4IEBC.js +0 -2
- package/dist/chunk-DJL47DYJ.js +0 -8
- package/dist/chunk-H6QJ4YU7.js +0 -2
- package/dist/chunk-J75KVNX5.js +0 -18
- package/dist/chunk-MUPHP5W6.js +0 -27
- package/dist/chunk-NAYAVVTP.js +0 -6
- package/dist/chunk-P5XBCJYQ.js +0 -7
- package/dist/chunk-Q2I65L2W.js +0 -6
- package/dist/chunk-QCEWUUE6.js +0 -55
- package/dist/chunk-V2GYBVSM.js +0 -2
- package/dist/chunk-Y44AETOW.js +0 -2
- package/dist/chunk-YCNCW4O4.js +0 -8
- package/dist/evidence-O4AON5FU.js +0 -2
- package/dist/list-commands-VJAL4J3O.js +0 -2
- package/dist/login-flow-VZ2MITFA.js +0 -2
- package/dist/pipeline-CADTHPDV.js +0 -2
- package/dist/run-test-md-INJKPE2I.js +0 -13
- package/dist/tcg-generate-VKFXR5JT.js +0 -2
- package/dist/testmd-actions-4QLHD74A.js +0 -2
- package/dist/token-refresh-2HKIYD4Y.js +0 -2
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{c as Tt,d as Qr}from"./chunk-VXD5667K.js";import{a as Lt,b as Zr,c as et,d as tt,e as Xr,f as Dt,g as rn,h as nn}from"./chunk-LMJTY32X.js";import{a as Te,b as ne,e as _e,f as xt,k as Yr,p as he,q as Pt,t as Jr}from"./chunk-RKWJG3WW.js";import{b as Se}from"./chunk-2PDWMY2B.js";import{a as Ze,b as At}from"./chunk-O4O4KL6Z.js";import{a as Or,b as Et}from"./chunk-XDW2RGIL.js";import{a as Le,b as en}from"./chunk-C5UNZ6ZY.js";import{c as tn}from"./chunk-S3DAAAE5.js";import{c as sn}from"./chunk-GIGD4M7V.js";import{d as Wr}from"./chunk-2YQ6TW77.js";import{a as we}from"./chunk-WAOCHXJ5.js";import{B as jr,C as Fr,D as Nr,F as $r,G as Mr,I as Vr,J as Kr,K as Hr,X as qr,aa as Gr,ba as zr,j as Xe,x as Ur}from"./chunk-WGG5XURS.js";import{a as Br}from"./chunk-BC7UVJJB.js";import{a as xr,c as kt,d as Ct,e as Qe,f as Pr,g as Tr}from"./chunk-M5JQXOCE.js";import{g as Lr,h as Dr}from"./chunk-OBBXDBEE.js";import{a as Je}from"./chunk-2WVKOZ6W.js";import{a as We,b as Ar}from"./chunk-NLCCBXXV.js";import{a as re}from"./chunk-KGP7NSXH.js";import{a as M}from"./chunk-RZ4F3BHX.js";import{a as Cr}from"./chunk-E47GFYXA.js";import{a as ze,c as _t,i as Er,j as Ye,k as It,l as Rt}from"./chunk-HMGNPFXP.js";import{join as le,basename as as}from"path";import{existsSync as Ro,readFileSync as cs}from"fs";function on(e,t){if(process.env.KANE_REPLAY_TRACE==="1")for(let r=0;r<e.steps.length;r++){let n=e.steps[r],s=t[r],o=" ".repeat(n.trace.length-1),i=`step ${n.flatIndex}`;s.kind==="replay"?process.stderr.write(`[replay-trace] ${o}${i}: REPLAY (would skip; v1 always authors)
|
|
3
|
+
`):process.stderr.write(`[replay-trace] ${o}${i}: AUTHOR (${s.reason})
|
|
4
|
+
`)}}function Ie(e){process.env.KANE_REPLAY_TRACE==="1"&&process.stderr.write(e)}function an(e,t){let r=e===0?"(none)":`0..${e-1}`,n=e>=t?"(none)":`${e}..${t-1}`;Ie(`[replay-trace] phase: replay ${r}, author ${n}
|
|
5
|
+
`)}function ln(e,t){Ie(`[replay-trace] step ${e}: REPLAY ${t==="ok"?"OK":"FAILED"}
|
|
6
|
+
`)}function cn(e,t,r){Ie(`[replay-trace] shrink ${e}/${t} \u2192 new boundary ${r}
|
|
7
|
+
`)}function dn(e,t){Ie(`[replay-trace] complete-reauthor (${e} shrinks exhausted of ${t})
|
|
8
|
+
`)}function Ot(){Ie(`[replay-trace] force-author (--author) \u2014 walker bypassed
|
|
9
|
+
`)}function un(e){Ie(`[replay-trace] cancelled at step ${e}
|
|
10
|
+
`)}import{join as mn}from"path";function Ut(e){let t={objective:e.step.objective,model:"v16-alpha",width:e.windowSize.width,height:e.windowSize.height,session_id:e.sessionId,run_index:e.runIndex,stream:!0,mode:"replay",replay:{recording_path:Xr(e.decision),step_label:e.step.objective,...e.investigationAsync?{investigation:"async"}:{}},screenshot_dir:e.evidence?mn(e.sessionDir,"scratch",String(e.runIndex)):mn(e.sessionDir,"runs",String(e.runIndex)),run_id:"run",test_id:"test"};return e.forceNavigateUrl&&(t.url=e.forceNavigateUrl),e.chrome.wsEndpoint?t.ws_endpoint=e.chrome.wsEndpoint:e.chrome.cdpEndpoint&&(t.cdp_endpoint=e.chrome.cdpEndpoint),e.auth.basicAuth?(t.username=e.auth.basicAuth.username,t.access_key=e.auth.basicAuth.access_key):e.auth.token&&(t.auth={type:"bearer",token:e.auth.token}),e.variables&&Object.keys(e.variables).length>0&&(t.variables=e.variables),e.sessionContext&&(t.session_context=e.sessionContext),e.evidence&&(t.evidence=Xe(e.evidence.packTestDir,e.evidence.ordinalOffset)),t}async function fn(e){let t=e.forceAuthor?0:tt(e.decisions),r=0,n=!1;for(;;){let s=e.session.snapshot(),o=e.accumulator.snapshot(),i=await e.runReplayPhase(t);if(i.cancelled)return n=!0,un(i.failedAt??0),{authorBoundary:t,cancelledInPhase:n,shrinkCount:r};if(i.failedAt===null)return{authorBoundary:t,cancelledInPhase:n,shrinkCount:r};let f=en({failedAt:i.failedAt,shrinkCount:r,hasRetry:e.hasRetry,maxShrinks:e.maxShrinks});if(f.kind==="fail")return{authorBoundary:-1,cancelledInPhase:n,shrinkCount:r};if(e.acquireLockIfNeeded&&!await e.acquireLockIfNeeded())return{authorBoundary:-1,cancelledInPhase:n,shrinkCount:r};if(e.session.rollback(s),e.accumulator.rollback(o),f.kind==="complete-reauthor")return dn(r+1,e.maxShrinks),{authorBoundary:0,cancelledInPhase:n,shrinkCount:r};r++,cn(r,Le.maxShrinks,f.newAuthorBoundary),t=f.newAuthorBoundary}}var ks=15e3,jt=3,pn=[500,1e3];async function Ft(e){if(process.env.KANE_LOCK_CONFLICT_SIMULATE==="1")return{ok:!1,reason:"concurrent",httpStatus:409,message:"simulated contention (KANE_LOCK_CONFLICT_SIMULATE=1)"};let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/playground`,r=await rt(t,{from_commit_id:e.fromCommitId,new_commit_id:e.newCommitId},e.auth);return r.ok?{ok:!0,sessionExpiresAt:B(r.body,"session_expires_at")??""}:{ok:!1,...Cs(r)}}function Cs(e){let t=B(e.body,"error")??B(e.body,"code")??"",r=B(e.body,"message")??B(e.body,"detail")??e.text??`HTTP ${e.status}`,n;return e.status===0?n="network":e.status===401||e.status===403?n="auth":e.status===409&&t==="PlaygroundBaseCommitMismatch"?n="base_mismatch":e.status===409?n="concurrent":e.status===422?n="disabled":e.status===400&&/no committed/i.test(r)?n="no_commits":e.status===400?n="missing_field":e.status>=500||e.status===408||e.status===429?n="network":n="other",{reason:n,httpStatus:e.status,message:r}}async function hn(e){let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/playground/reserve`,r=await rt(t,void 0,e.auth);return r.ok?{ok:!0,sessionExpiresAt:B(r.body,"session_expires_at")??""}:{ok:!1,expired:r.status===404,httpStatus:r.status,message:B(r.body,"message")??B(r.body,"detail")??r.text??`HTTP ${r.status}`}}async function Nt(e){let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/commit`,r={commit_id:e.body.commitId,from_commit_id:e.body.fromCommitId,commit_message:e.body.commitMessage,total_steps:e.body.totalSteps};e.body.timeTaken!==void 0&&(r.time_taken=e.body.timeTaken),e.body.objectives!==void 0&&(r.objectives=e.body.objectives);let n=await rt(t,r,e.auth);return n.ok?{ok:!0,testId:B(n.body,"test_id")??e.testId,testcaseId:B(n.body,"testcase_id")??"",projectId:B(n.body,"project_id"),isTestCaseDeleted:typeof n.body?.is_test_case_deleted=="boolean"?n.body.is_test_case_deleted:void 0}:{ok:!1,...Es(n)}}function Es(e){let t=B(e.body,"error")??B(e.body,"code")??"",r=B(e.body,"message")??B(e.body,"detail")??e.text??`HTTP ${e.status}`,n;return e.status===0?n="network":e.status===401||e.status===403?n="auth":e.status===409&&t==="PlaygroundBaseCommitMismatch"?n="base_mismatch":e.status===409&&t==="PlaygroundCommitLockMismatch"?n="lock_mismatch":e.status===409?n="expired":e.status===422?n="not_found":e.status>=500||e.status===408||e.status===429?n="network":n="other",{reason:n,httpStatus:e.status,message:r}}async function De(e){let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/commit`,r={discard:!0,commit_id:e.body.commitId,from_commit_id:e.body.fromCommitId,commit_message:"(discarded)",total_steps:1},n=await rt(t,r,e.auth);return n.ok?{ok:!0}:{ok:!1,reason:B(n.body,"error")??"other",httpStatus:n.status,message:B(n.body,"message")??B(n.body,"detail")??n.text??`HTTP ${n.status}`}}async function rt(e,t,r){let n=null;for(let s=1;s<=jt;s++){let o=new AbortController,i=setTimeout(()=>o.abort(),ks);try{let f=await M(e,{method:"POST",headers:{Authorization:We(r.username,r.accessKey),"Content-Type":"application/json",Accept:"application/json"},...t!==void 0?{body:JSON.stringify(t)}:{},signal:o.signal});clearTimeout(i);let a=await f.text(),c=null;if(a)try{c=JSON.parse(a)}catch{}let y=f.status>=500||f.status===408||f.status===429;if(f.ok||!y)return{ok:f.ok,status:f.status,body:c,text:a};if(s<jt){await gn(pn[s-1]??1e3);continue}return{ok:!1,status:f.status,body:c,text:a}}catch(f){if(clearTimeout(i),n=f,s<jt){await gn(pn[s-1]??1e3);continue}}}return{ok:!1,status:0,body:null,text:n?.message??"exhausted retries"}}function gn(e){return new Promise(t=>setTimeout(t,e))}function B(e,t){if(typeof e!="object"||e===null)return;let r=e[t];return typeof r=="string"?r:void 0}var As=60*1e3,bn="lock-heartbeat",me=new Map,Oe=null,xs={register:(e,t)=>Qe(e,t),deregister:e=>Pr(e),cleanup:(e,t)=>Tr(e,t),remoteLogger:null};function yn(e){if(e!==void 0){let t=me.get(e);t!==void 0&&(clearInterval(t),me.delete(e));return}for(let t of me.values())clearInterval(t);me.clear()}function nt(e){if(me.has(e.testId))return;let t=e.lifecycle??xs,r=setInterval(async()=>{let n=await hn({baseUrl:e.baseUrl,testId:e.testId,auth:e.auth});if(!n.ok){let s=n.expired?"session expired":n.message;process.stderr.write(`[lock] heartbeat failed (${e.testId}): ${s}; continuing run
|
|
11
|
+
`)}},As);me.set(e.testId,r),Oe===null&&(Oe=t,t.register(bn,()=>yn()))}function be(e){me.size!==0&&(yn(e),me.size===0&&Oe!==null&&(Oe.deregister(bn),Oe=null))}import{readFileSync as vn,readdirSync as Sn,existsSync as ye,promises as wn}from"fs";import{join as se}from"path";async function Ps(e,t){let r=se(e,"steps",`${t.ordinal}-${t.id}`),n;try{n=await wn.readFile(se(r,"screenshot.png"))}catch{return null}let s=null;try{s=JSON.parse(await wn.readFile(se(r,"step.json"),"utf8")).action_id??null}catch{}return{png:n,actionId:s}}function Zo(){let e=[];return{track:t=>{e.push(t.catch(()=>{}))},settle:async()=>{await Promise.all(e)}}}async function _n(e,t,r,n){try{let s=await Ps(e,t);if(!s){n("warn","SCREENSHOT_SKIP","Pack step folder or screenshot not found",{ordinal:t.ordinal,id:t.id,reason:"pack_step_not_found"});return}if(!s.actionId){n("warn","SCREENSHOT_SKIP","No action_id in step.json",{ordinal:t.ordinal,id:t.id,reason:"no_action_id"});return}r.enqueue(s.actionId,s.png),n("info","SCREENSHOT_ENQUEUED","Screenshot enqueued",{ordinal:t.ordinal,id:t.id,action_id:s.actionId,size:s.png.length})}catch(s){n("error","SCREENSHOT_DISPATCH_ERROR","Screenshot dispatch error",{ordinal:t.ordinal,id:t.id,error:s instanceof Error?s.message:String(s)})}}function In(e,t,r,n,s,o){try{let i=se(e,"runs",String(t),"run-test");if(!ye(i)){s("warn","SCREENSHOT_SKIP","Runs dir not found",{step_index:r,reason:"runsDir_not_found",path:i});return}let f=i;if(o){let k=se(i,`child-${o}`);if(!ye(k)){s("warn","SCREENSHOT_SKIP","Child dir not found",{step_index:r,child_id:o,reason:"child_dir_not_found",path:k});return}let C=Sn(k).filter(l=>ye(se(k,l,"screenshots")));if(C.length===0){s("warn","SCREENSHOT_SKIP","No screenshots dir under child",{step_index:r,child_id:o,reason:"no_child_screenshots_dir"});return}f=se(k,C[0])}else if(!ye(se(i,"screenshots"))){let k=Sn(i).filter(C=>ye(se(i,C,"screenshots")));if(k.length===0){s("warn","SCREENSHOT_SKIP","No screenshots dir found",{step_index:r,reason:"no_screenshots_dir"});return}f=se(i,k[0])}let a=se(f,"screenshots",`step_${String(r).padStart(3,"0")}.png`);if(!ye(a)){s("warn","SCREENSHOT_SKIP","Screenshot not found",{step_index:r,child_id:o,reason:"screenshot_not_found",path:a});return}let c=se(i,"actions.ndjson");if(!ye(c)){s("warn","SCREENSHOT_SKIP","NDJSON not found",{step_index:r,reason:"ndjson_not_found"});return}let y=vn(c,"utf-8").trim().split(`
|
|
12
|
+
`),w=y[y.length-1];if(!w){s("warn","SCREENSHOT_SKIP","NDJSON empty",{step_index:r,reason:"ndjson_empty"});return}let R=JSON.parse(w).action_id;if(!R){s("warn","SCREENSHOT_SKIP","No action_id in NDJSON",{step_index:r,reason:"no_action_id"});return}let x=vn(a);n.enqueue(R,x),s("info","SCREENSHOT_ENQUEUED","Screenshot enqueued",{step_index:r,child_id:o,action_id:R,size:x.length})}catch(i){s("error","SCREENSHOT_DISPATCH_ERROR","Screenshot dispatch error",{step_index:r,error:i instanceof Error?i.message:String(i)})}}import{dirname as Ts,join as Ls}from"path";function Rn(e,t,r){let n=e.total_runs??1,s=e.run_dir,o,i;if(n>1&&s){let f=Ts(s);o=Array.from({length:n},(a,c)=>Ls(f,String(t+c))),r&&r.length===n&&(i=r)}return{allRunDirs:o,flowObjectives:i}}function kn(e,t,r,n){return{index:r,objective:t,summary:e.summary,oneLiner:e.one_liner,status:e.status,resultCode:e.result_code,reasonCode:e.reason_code,perFlowMetadata:e.per_flow_metadata,context:e.context??{memory:{},variables:{},pointer:""},run_dir:e.run_dir,run_dirs:n.allRunDirs,flow_objectives:n.flowObjectives}}var st=class{constructor(t){this.resolved=t;this.outcomes=t.rootSteps.map(r=>({rootStepIndex:r.index,status:"skipped"}))}outcomes;skipRoot=null;overallHalted=!1;shouldRunFlatStep(t){if(this.overallHalted)return!1;let r=t.trace[0].stepIndex;return!(this.skipRoot!==null&&r===this.skipRoot)}recordStep(t,r){let n=t.trace[0].stepIndex,s=this.outcomes.find(a=>a.rootStepIndex===n),o=this.resolved.rootSteps.find(a=>a.index===n),i=o.body.kind!=="objective";return i&&(s.refKind="import",s.refLabel=o.body.path,s.inlinedCount=(s.inlinedCount??0)+1,s.duration_s=(s.duration_s??0)+r.duration_s),r.status==="passed"?(i?s.status!=="failed"&&(s.status="passed"):(s.status="passed",s.duration_s=r.duration_s),{continueOverall:!0}):t.optional?(s.softFailures=s.softFailures??[],s.softFailures.push({subStepIndex:t.trace[t.trace.length-1].stepIndex,reason:r.reason}),{continueOverall:!0}):(s.status="failed",s.duration_s=i?s.duration_s:r.duration_s,s.failedSubStepIndex=i?t.trace.slice(1).map(a=>a.stepIndex):void 0,s.reason=r.reason,this.skipRoot=n,o.optional??!1?(s.softFailed=!0,{continueOverall:!0}):(this.overallHalted=!0,{continueOverall:!1}))}snapshotOutcomes(){return[...this.outcomes]}snapshot(){return{outcomes:this.outcomes.map(t=>({...t,softFailures:t.softFailures?[...t.softFailures]:void 0})),skipRoot:this.skipRoot,overallHalted:this.overallHalted}}rollback(t){this.outcomes=t.outcomes.map(r=>({...r,softFailures:r.softFailures?[...r.softFailures]:void 0})),this.skipRoot=t.skipRoot,this.overallHalted=t.overallHalted}finalize(){let t=this.outcomes.some(n=>n.status==="failed"&&!n.softFailed)?"failed":"passed",r=this.outcomes.reduce((n,s)=>n+(s.duration_s??0),0);return{overallStatus:t,outcomes:this.outcomes,totalDurationS:r}}};function $t(e){if(!e)return null;let t=e.trim();return t?/^https?:\/\//i.test(t)?t:`https://${t}`:null}function Cn(e){return $t(e.flag)??$t(e.frontmatter)??(e.configDefault&&e.configDefault!==Ye?$t(e.configDefault):null)}function En(e){return e.resolvedUrl!==null?!1:!((!!e.local||!!e.allowMissingUrl)&&!e.isTTY)}import{spawn as Ds}from"child_process";async function An(e,t,r=100){let n=`${e.replace(/\/+$/,"")}/json/version`,s=await M(n);if(!s.ok)throw new Error(`CDP /json/version returned ${s.status}`);let o=await s.json();if(!o.webSocketDebuggerUrl)throw new Error("CDP /json/version missing webSocketDebuggerUrl");let i=new Cr(o.webSocketDebuggerUrl);await new Promise((m,_)=>{i.once("open",m),i.once("error",_)});let f=1,a=new Map;i.on("message",m=>{let _;try{_=JSON.parse(m.toString())}catch{return}if(_.id==null)return;let D=a.get(_.id);D&&(a.delete(_.id),_.error?D.reject(new Error(_.error.message)):D.resolve(_.result))});function c(m,_){let D=f++;return new Promise((ce,J)=>{a.set(D,{resolve:N=>ce(N),reject:J});let X={id:D,method:m};_&&(X.params=_),i.send(JSON.stringify(X))})}let w=(await c("Target.getTargets")).targetInfos.find(m=>m.type==="page");if(!w)throw i.close(),new Error("CDP: no page target found");let R=(await c("Browser.getWindowForTarget",{targetId:w.targetId})).windowId,x="",k=!1,C=null,l=!1;i.on("close",()=>{l=!0}),i.on("error",()=>{l=!0});async function H(){if(!k){if(l){k=!0;return}try{let _=(await c("Browser.getWindowBounds",{windowId:R})).bounds,D=`${_.left}:${_.top}:${_.width}:${_.height}`;D!==x&&(x=D,t({left:_.left,top:_.top,width:_.width,height:_.height}))}catch{}k||(C=setTimeout(H,r))}}return H(),{stop(){if(!k){k=!0,C&&clearTimeout(C);try{i.close()}catch{}}}}}var Os=new Set(["1","true","yes"]);function xn(e){if(e?.headless)return null;let t=process.env.KANE_CLI_DISABLE_MARKER;if(t!=null&&Os.has(t.toLowerCase()))return null;let r=Or();if(!r)return null;let n=[...r.args,"overlay"];e?.text&&n.push(e.text);let s;try{s=Ds(r.cmd,n,{cwd:r.cwd,stdio:["pipe","ignore","ignore"],detached:!1,windowsHide:!0})}catch{return null}s.stdin?.on("error",()=>{});let o=!1;s.on("exit",()=>{o=!0}),s.on("error",()=>{o=!0});function i(c){if(!(o||!s.stdin||s.stdin.destroyed))try{s.stdin.write(JSON.stringify(c)+`
|
|
13
|
+
`)}catch{}}e?.chromePid&&e.chromePid>0&&i({type:"chrome_pid",pid:e.chromePid});let f=null;e?.cdpEndpoint&&An(e.cdpEndpoint,c=>i({type:"bounds",...c})).then(c=>{f=c.stop}).catch(()=>{});let a=!1;return{setRunActive(c){a||i({type:"run_active",active:c})},setStepText(c){if(a)return;let y=c.trim();y&&i({type:"step_text",text:y})},setStepComplete(){a||i({type:"step_complete"})},kill(){if(!a){a=!0,f?.();try{s.stdin?.end()}catch{}try{s.kill("SIGTERM")}catch{}}}}}function Pn(e,t,r){return`${e}/projects/${t}/test-cases/${r}`}function ot(e,t,r,n){return`${Pn(e,t,r)}/dashboard/share/${n}?type=summary&agentView=true&fqdn=summary-page`}function Tn(e,t,r,n){if(!(!t||!r||!n))return ot(e,t,r,n)}function Ln(e,t,r){return`${Pn(e,t,r)}/dashboard?type=summary&agentView=true&fqdn=summary-page`}import{mkdtempSync as Ys,rmSync as Ws}from"fs";import{join as Js}from"path";import{tmpdir as Qs}from"os";import{spawn as Un,spawnSync as Us}from"child_process";import{existsSync as Mt}from"fs";import{createConnection as js}from"net";import{homedir as Ue,platform as Ne}from"os";import{join as je}from"path";var Fs=new Set(["1","true","yes"]),it=class extends Error{constructor(t){super(t),this.name="ChromeNotFoundError"}};function wi(e){return e instanceof it?e.message:`Chrome failed: ${e instanceof Error?e.message:String(e)}`}var at={darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",je(Ue(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),"/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",je(Ue(),"Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"),"/Applications/Chromium.app/Contents/MacOS/Chromium"],linux:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/google-chrome-for-testing","/usr/local/bin/google-chrome-for-testing",je(Ue(),"chrome-for-testing/chrome-linux64/chrome"),"/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],win32:["C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",je(Ue(),"AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"),"C:\\chrome-for-testing\\chrome-win64\\chrome.exe",je(Ue(),"AppData\\Local\\chrome-for-testing\\chrome-win64\\chrome.exe")]};function Ns(){if(process.env.KANE_CLI_CHROME_PATH)return process.env.KANE_CLI_CHROME_PATH;let e=Ne(),t=at[e]??at.linux;for(let r of t)if(Mt(r))return r;return e==="win32"?"chrome.exe":"google-chrome"}function $s(){if(process.env.KANE_CLI_CHROME_PATH)return Mt(process.env.KANE_CLI_CHROME_PATH);let e=Ne();if((at[e]??at.linux).some(s=>Mt(s)))return!0;let r=e==="win32"?"chrome.exe":"google-chrome",n=e==="win32"?"where":"which";try{return Us(n,[r],{stdio:"ignore"}).status===0}catch{return!1}}function Ms(){let e=Ne();return e==="darwin"?["Google Chrome is required but was not found at any standard path.","","Install via Homebrew (recommended):"," brew install --cask google-chrome","","Or download:"," https://www.google.com/chrome/","","Then re-run your command. Set KANE_CLI_CHROME_PATH=/path/to/chrome","to point at a non-standard install."].join(`
|
|
14
|
+
`):e==="linux"?["Google Chrome is required but was not found at /usr/bin/google-chrome.","(amd64 / x86_64 only \u2014 Google does not ship Chrome for Linux ARM.)","","Debian / Ubuntu (any version):"," wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb"," sudo apt install -y ./google-chrome-stable_current_amd64.deb","","Fedora / RHEL / AlmaLinux / Rocky:"," sudo dnf install -y https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm","","Then re-run your command. Set KANE_CLI_CHROME_PATH=/path/to/chrome","to point at a non-standard install."].join(`
|
|
15
|
+
`):e==="win32"?["Google Chrome is required but was not found in Program Files or AppData.","","Install via winget (Windows 10 1809+):"," winget install --id Google.Chrome -e --silent","","Or download:"," https://www.google.com/chrome/","","Then re-run your command. Set KANE_CLI_CHROME_PATH=C:\\path\\to\\chrome.exe","to point at a non-standard install."].join(`
|
|
16
|
+
`):["Google Chrome is required.","Install from https://www.google.com/chrome/","(Note: no official Chrome builds for BSD or Alpine/musl Linux.)"].join(`
|
|
17
|
+
`)}function Bs(e){let t=Ne(),r=[`--remote-debugging-port=${e.port}`,`--user-data-dir=${e.userDataDir}`,`--window-size=${e.width},${e.height}`,"--no-first-run","--no-default-browser-check","--disable-blink-features=AutomationControlled","--disable-features=DownloadBubble,DownloadBubbleV2","--safebrowsing-disable-download-protection","--disable-popup-blocking","--disable-notifications","--disable-infobars","--disable-translate","--disable-prompt-on-repost","--disable-background-networking","--disable-client-side-phishing-detection","--disable-default-apps","--disable-hang-monitor","--disable-sync","--metrics-recording-only","--safebrowsing-disable-auto-update","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--test-type=webdriver","--allow-pre-commit-input","--enable-logging","--v=1"];return t==="linux"&&(r.push("--no-sandbox"),r.push("--disable-dev-shm-usage"),r.push("--password-store=basic")),t==="darwin"&&r.push("--use-mock-keychain"),e.headless&&r.push("--headless=new"),r}function Vs(e){return new Promise(t=>{let r=js({port:e,host:"127.0.0.1"});r.setTimeout(1e3),r.on("connect",()=>{r.destroy(),t(!0)}),r.on("timeout",()=>{r.destroy(),t(!1)}),r.on("error",()=>{r.destroy(),t(!1)})})}async function Ks(){for(let e=It;e<=Rt;e++)if(!await Vs(e))return e;throw new Error(`All CDP ports ${It}-${Rt} are in use. Close other Chrome instances.`)}var Fe=class extends Error{constructor(t){super(t),this.name="CdpReadinessError"}};async function Hs(e,t){let r=Date.now(),n=`http://127.0.0.1:${e}/json/version`;for(;Date.now()-r<t;){try{if((await M(n)).ok)return`http://127.0.0.1:${e}`}catch{}await new Promise(s=>setTimeout(s,200))}throw new Fe(`Chrome CDP not ready after ${t}ms on port ${e}`)}var qs=3e4,Gs=2;function Dn(e,t,r){let n=process.env[e];if(n==null||n.trim()==="")return t;let s=Number(n);return!Number.isInteger(s)||s<r?t:s}function zs(e){return Math.min(500*e,3e3)}function On(e,t){try{if(e.pid)if(t==="win32")Un("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-e.pid,"SIGKILL")}catch{e.kill("SIGKILL")}else e.kill("SIGKILL")}catch{}}async function jn(e){let t=process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD;if(!(t!=null&&Fs.has(t.toLowerCase()))&&!$s())throw kt()?.log("error","CHROME_NOT_FOUND","Startup gate: Chrome unavailable at standard system paths",{platform:process.platform,kane_cli_chrome_path:process.env.KANE_CLI_CHROME_PATH??null,skip_browser_download:process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD??null}),new it(Ms());let n=Ne(),s=Ns(),o=Dn("KANE_CLI_CDP_TIMEOUT_MS",qs,1),f=Dn("KANE_CLI_CDP_RETRIES",Gs,0)+1,a;for(let c=1;c<=f;c++){let y=await Ks(),w=Bs({port:y,...e});e.startUrl&&w.push(e.startUrl);let A=Un(s,w,{stdio:"ignore",detached:!0});A.unref();try{let R=await new Promise((x,k)=>{A.on("error",C=>{k(new Error(`Failed to launch Chrome: ${C.message}. Is Chrome installed at ${s}?`))}),A.on("close",C=>{C!==null&&C!==0&&k(new Fe(`Chrome exited during startup with code ${C}`))}),Hs(y,o).then(x,k)});return{process:A,port:y,cdpEndpoint:R,kill(){On(A,n)}}}catch(R){if(a=R,!(R instanceof Fe))throw R;On(A,n),kt()?.log("warn","CHROME_CDP_LAUNCH_RETRY",`Chrome CDP launch attempt ${c}/${f} failed`,{attempt:c,max_attempts:f,port:y,timeout_ms:o,headless:e.headless??!1,error:R.message}),c<f&&await new Promise(x=>setTimeout(x,zs(c)))}}throw a??new Error("Chrome launch failed after retries")}async function Fn(e){if(e.cft)return{instance:null,tempDir:null};if(e.wsEndpoint)return{wsEndpoint:e.wsEndpoint,instance:null,tempDir:null};if(e.cdpEndpoint){let s=await M(`${e.cdpEndpoint}/json/version`);if(!s.ok)throw new Error(`CDP endpoint not reachable: ${e.cdpEndpoint} (${s.status})`);return{cdpEndpoint:e.cdpEndpoint,instance:null,tempDir:null}}let t,r=null;if(e.config.chrome_profile_path)t=e.config.chrome_profile_path.replace("~",process.env.HOME??"~");else{r=Ys(Js(Qs(),"kane-clean-")),t=r;let s=r;Qe("tempDir",()=>{try{Ws(s,{recursive:!0,force:!0})}catch{}})}let n=await jn({userDataDir:t,width:e.config.window_size.width,height:e.config.window_size.height,startUrl:e.startUrl,headless:e.headless});return{cdpEndpoint:n.cdpEndpoint,instance:n,tempDir:r}}function Nn(e){let t={objective:e.objective,model:e.model,width:e.windowSize.width,height:e.windowSize.height,session_id:e.sessionId,run_index:e.runIndex,stream:!0,max_steps:e.maxSteps??30,headless:e.headless??!1};return e.url&&(t.url=e.url),e.requireStartUrl&&(t.require_start_url=!0),e.chrome.wsEndpoint?t.ws_endpoint=e.chrome.wsEndpoint:e.chrome.cdpEndpoint&&(t.cdp_endpoint=e.chrome.cdpEndpoint),e.auth.basicAuth?(t.username=e.auth.basicAuth.username,t.access_key=e.auth.basicAuth.access_key):e.auth.token&&(t.auth={type:"bearer",token:e.auth.token}),e.disableAskUser&&(t.disable_ask_user=!0),e.enableTaskSkills&&(t.enable_task_skills=!0),e.networkWs&&(t.network_ws=!0),e.networkSse&&(t.network_sse=!0),(e.bugDetection==="stop"||e.bugDetection==="continue")&&(t.bug_detection=e.bugDetection),e.variables&&Object.keys(e.variables).length>0&&(t.variables=e.variables),e.globalContext&&(t.global_context=e.globalContext),e.localContext&&(t.local_context=e.localContext),e.sessionContext&&(t.session_context=e.sessionContext),e.evidence&&(t.evidence=Xe(e.evidence.packTestDir,e.evidence.ordinalOffset)),t}import{readdirSync as Zs,readFileSync as Mn,existsSync as Bn}from"fs";import{join as Xs}from"path";function $n(e,t){if(!Bn(e))return{};let r={},n;try{n=Zs(e).filter(s=>s.endsWith(".json")).sort()}catch{return{}}for(let s of n)try{let o=Mn(Xs(e,s),"utf-8"),i=JSON.parse(o);if(i&&typeof i=="object"){for(let[f,a]of Object.entries(i))if(a&&typeof a=="object"&&"value"in a){let c=a;r[f]={value:c.value,secret:c.secret??!1,syntax:c.syntax??`{{${f}}}`}}}}catch{t?t("warn","VARIABLE_PARSE_FAILED","Skipping invalid variables file",{file:s}):process.stderr.write(`[variables] Warning: skipping invalid variables file: ${s}
|
|
18
|
+
`)}return r}function Vn(e){if(!Bn(e))throw new Error(`Variables file not found: ${e}`);let t=Mn(e,"utf-8"),r=JSON.parse(t),n={};if(r&&typeof r=="object"){for(let[s,o]of Object.entries(r))if(o&&typeof o=="object"&&"value"in o){let i=o;n[s]={value:i.value,secret:i.secret??!1,syntax:i.syntax??`{{${s}}}`}}}return n}function Kn(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Invalid --variables JSON")}let r={};if(t&&typeof t=="object"){for(let[n,s]of Object.entries(t))if(s&&typeof s=="object"&&"value"in s){let o=s;r[n]={value:o.value,secret:o.secret??!1,syntax:o.syntax??`{{${n}}}`}}}return r}function Hn(e,t,r){let n=$n(e,r),s=$n(t,r);return{...n,...s}}var Re=class{constructor(t){this.baseUrl=t}async pushSecret(t){let r=We(t.username,t.accessKey),n=await M(`${this.baseUrl}/logistics/v1.0/secrets/create`,{method:"PUT",headers:{Authorization:r,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({secretKey:t.secretKey,secretValue:t.secretValue,orgId:t.orgId,username:t.username,scope:"user",type:"user",accessKey:t.accessKey})});if(!n.ok)throw new Error(`Push secret failed: ${n.status} ${await n.text()}`)}static extractVariableKeys(t){let r=t.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g),n=new Set;for(let s of r)n.add(s[1]);return[...n]}};var ke=class extends Ar{constructor(t,r,n){super(t,{username:r,accessKey:n})}async upsertVariable(t){let r=t.environmentId??0,n=await M(`${this.baseUrl}/v1/variables`,{method:"POST",headers:this.headers(),body:JSON.stringify({name:t.name,value:String(t.value),type:"variable",value_type:"string",is_persist:t.isPersist??!1,environment_id:r})});if(n.ok)return{id:(await n.json()).id??0};if(n.status!==409&&n.status!==422)return{id:0};if(!(await M(`${this.baseUrl}/v1/variables/name/${encodeURIComponent(t.name)}`,{method:"PUT",headers:this.headers(),body:JSON.stringify({value:String(t.value),value_type:"string",type:"variable",environment_id:r})})).ok)return{id:0};let o=await M(`${this.baseUrl}/v1/variables/${encodeURIComponent(t.name)}?environment_id=${r}`,{method:"GET",headers:this.headers()});return o.ok?{id:(await o.json()).data?.id??0}:{id:0}}};function qn(e,t){if(Object.keys(e).length===0)return{};let r={};for(let[n,s]of Object.entries(e)){let o=s.syntax??`{{${n}}}`;t.includes(o)&&(r[n]=s)}return r}function Gn(e){let t=Hn(e.globalDir,e.localDir,e.onLoadError),r=e.file?Vn(e.file):{},n=e.inline?Kn(e.inline):{},s={...t,...r,...n},o=Object.keys(s).length>0,{variables:i,objective:f}=o?Se(s,e.objective):{variables:{},objective:e.objective},a=Object.entries(s).filter(([,y])=>y.secret),c=Object.entries(s).filter(([,y])=>!y.secret);return{raw:s,auteur:i,auteurObjective:f,secretEntries:a,nonSecretEntries:c}}async function zn(e){if(e.localMode)return{};let t=re(e.env);if(e.variables.secretEntries.length>0){let n=new Re(t.secretsBaseUrl);for(let[s,o]of e.variables.secretEntries)n.pushSecret({secretKey:s,secretValue:o.value,username:e.auth.username,accessKey:e.auth.access_key,orgId:e.orgId}).then(()=>e.log("info","SECRET_PUSH_OK","Secret pushed",{key:s})).catch(i=>e.log("error","SECRET_PUSH_FAILED","Secret push failed",{key:s,error:String(i)}))}let r={};if(e.variables.nonSecretEntries.length>0){let n=new ke(t.tmsBaseUrl,e.auth.username,e.auth.access_key);for(let[s,o]of e.variables.nonSecretEntries)try{let i=await n.upsertVariable({name:s,value:o.value});r[s]=i.id,e.log("info","VAR_PUSH_OK","Variable pushed",{name:s,id:i.id})}catch(i){e.log("error","VAR_PUSH_FAILED","Variable push failed",{name:s,error:String(i)})}}return r}import{readFileSync as eo,existsSync as to}from"fs";function Bt(e){if(!to(e))return null;try{return eo(e,"utf-8").trim()||null}catch{return null}}var ro=()=>{};async function Yn(e,t,r){let n=t.log??ro,s=e.session.testId??null,o=null,i=null,f=null;if(!r.localMode&&t.performUpload)try{o=await t.performUpload(),o?.success&&(o.testId&&(s=o.testId),o.testcaseId&&e.session.setTestcaseId(o.testcaseId))}catch(a){n("error","FINALIZE_UPLOAD_ERROR","Upload pipeline threw",{error:String(a)})}if(t.renderFeedbackPrompt)try{i=await t.renderFeedbackPrompt(),i&&s&&t.submitFeedback&&t.submitFeedback(s,i).catch(a=>{n("error","FINALIZE_FEEDBACK_SUBMIT_ERROR","Feedback submit failed",{error:String(a)})})}catch(a){n("error","FINALIZE_FEEDBACK_RENDER_ERROR","Feedback prompt threw",{error:String(a)})}if(e.session.flushRecorder(),r.skipLocalWrites)n("info","FINALIZE_SKIP_LOCAL_WRITES","Skipping local writes (testmd flow handles via staging)");else if(r.sourcePath&&r.rootSteps&&r.outcomes){try{f=Lt({sourcePath:r.sourcePath,title:r.title,rootSteps:r.rootSteps,outcomes:r.outcomes,overallStatus:r.overallStatus,startedISO:r.startedISO,durationS:r.durationS,sessionId:e.session.sessionId})}catch(a){n("error","FINALIZE_RESULT_MD_ERROR","_Result.md write failed",{error:String(a)})}try{Pt({sourcePath:r.sourcePath,commitId:e.session.sessionId,testId:s??void 0,testcaseId:e.session.testcaseId??void 0,projectId:e.tuiConfig.project_id??void 0,folderId:e.tuiConfig.folder_id??void 0,orgId:e.session.orgId??void 0,sessionName:e.session.sessionName??Te(r.sourcePath),plan:e.session.plan??void 0})}catch(a){n("error","FINALIZE_META_WRITE_ERROR","meta.json write failed",{error:String(a)})}if(o?.codeExportDir)try{let a=e.tuiConfig.code_export?.language??"python";Dt(o.codeExportDir,xt(r.sourcePath,"playwright",a))}catch(a){n("error","FINALIZE_CODE_COPY_ERROR","code-export copy failed",{error:String(a)})}}else if(e.session.recorder?.lastWrittenPath){let a=e.session.recorder.lastWrittenPath,c=e.session.getFlows(),y=c.map((R,x)=>({index:x+1,heading:`Step ${x+1}`,verifies:[],headingLine:0,body:{kind:"objective",text:R.objective}})),w=c.map((R,x)=>({rootStepIndex:x+1,status:R.status==="passed"?"passed":R.status==="failed"?"failed":"skipped",duration_s:R.duration,reason:R.reason})),A=w.some(R=>R.status==="failed")?"failed":"passed";try{f=Lt({sourcePath:a,title:e.session.sessionName??"Session",rootSteps:y,outcomes:w,overallStatus:A,startedISO:e.session.startedAt,durationS:w.reduce((R,x)=>R+(x.duration_s??0),0),sessionId:e.session.sessionId})}catch(R){n("error","FINALIZE_TUI_RESULT_MD_ERROR","TUI _Result.md write failed",{error:String(R)})}try{Pt({sourcePath:a,commitId:e.session.sessionId,testId:s??void 0,testcaseId:e.session.testcaseId??void 0,sessionName:e.session.sessionName??void 0,projectId:e.tuiConfig.project_id??void 0,folderId:e.tuiConfig.folder_id??void 0,plan:e.session.plan??void 0})}catch(R){n("error","FINALIZE_TUI_META_WRITE_ERROR","TUI meta.json write failed",{error:String(R)})}if(o?.codeExportDir)try{let R=e.tuiConfig.code_export?.language??"python";Dt(o.codeExportDir,xt(a,"playwright",R))}catch(R){n("error","FINALIZE_TUI_CODE_COPY_ERROR","TUI code-export copy failed",{error:String(R)})}e.session.recorder.lastCollisionSuffixed&&process.stderr.write(`Saved to ${a} (renamed: ${e.session.sessionName}_test.md already existed)
|
|
19
|
+
`)}try{t.runCleanup?.()}catch(a){n("error","FINALIZE_CLEANUP_ERROR","Cleanup hook threw",{error:String(a)})}try{await e.session.finish("complete")}catch(a){n("error","FINALIZE_SESSION_FINISH_ERROR","session.finish threw",{error:String(a)})}return{uploadResult:o,feedbackChoice:i,resultMdPath:f}}import{readFileSync as Vt,writeFileSync as Kt,existsSync as Jn}from"fs";function Wn(e,t,r){if(r.forceAuthor)return"re-recorded from scratch";if(r.retryTriggered)return"re-recorded after retry";if(t.length>0&&t.every(i=>i.kind==="author"&&i.reason==="no-result-md"))return"initial recording";if(t.length>0&&t.every(i=>i.kind==="replay"))return r.wantsPush?"re-recorded (no source changes)":"no changes";let n=[];for(let i=0;i<t.length;i++){let f=t[i];if(!f||f.kind!=="author"||f.reason==="downstream-of-divergence"||f.reason==="no-result-md")continue;let a=no(e,e.steps[i]);switch(f.reason){case"structure-mismatch":n.push(`added/removed: ${a}`);break;case"md5-mismatch":n.push(`modified: ${a}`);break;case"missing-recording":n.push(`re-recorded: ${a}`);break;case"recorded-failed":n.push(`re-authored after failure: ${a}`);break}}if(n.length===0)return"automated commit";let s=n.filter((i,f)=>f===0||n[f-1]!==i),o=s.slice(0,3).join("; ");return s.length>3?`${o}; +${s.length-3} more`:o}function no(e,t){if(!t)return"unknown step";let r=t.trace[0]?.stepIndex;if(r==null)return"unknown step";let s=e.rootSteps[r-1]?.heading?.trim()??"";return t.trace.length>1?s?`imported step in "${s}"`:`imported step ${r}`:s||`step ${r}`}function so(e,t){if(!(!e.shouldReplaceLocalOutput||!e.resolvedTest||!e.sourcePath||!e.stepRunRecords||!e.outcomes||!e.overallStatus))return async()=>{let{changedUnitFiles:r,legacySweep:n}=await rn({resolvedTest:e.resolvedTest,sessionDir:e.session.sessionDir,stepRunRecords:e.stepRunRecords,outcomes:e.outcomes,overallStatus:e.overallStatus,startedISO:e.startedISO??new Date().toISOString(),durationS:e.durationS??0,sessionId:e.session.sessionId,commitId:e.fromCommitId??"",tmsIds:e.tmsIds??{},codeExportDir:e.codeExportDir,packTestDir:e.evidence?.packTestDir??e.evidenceRead?.packTestDir,authoredFlatIdx:new Set(e.authoredFlatIdx??[])});t.files=r;for(let s of r){let o=ne(s);if(Jn(`${o}.staging`)){Yr(o);let i=n.find(f=>f.unitFile===s);i&&nn(i.dirs)}}}}function oo(e,t){if(!(!e.shouldCommit||e.isFirstRun||!e.tmsBaseUrl||!e.testId||!e.fromCommitId||!e.newCommitId||!e.basicAuth||!e.resolvedTest||!e.decisions))return async()=>{let r=Wn(e.resolvedTest,e.decisions,{wantsPush:e.wantsPush??!1,retryTriggered:e.retryTriggered??!1,forceAuthor:e.forceAuthor??!1}),n=e.resolvedTest.steps.map(o=>o.objective).filter(o=>typeof o=="string"&&o.length>0).slice(0,50),s=await Nt({baseUrl:`${e.tmsBaseUrl}/kane-cli/v1`,testId:e.testId,body:{commitId:e.newCommitId,fromCommitId:e.fromCommitId,commitMessage:r,totalSteps:e.resolvedTest.steps.length,timeTaken:Math.round(e.durationS??0),objectives:n},auth:{username:e.basicAuth.username,accessKey:e.basicAuth.access_key}});if(s.ok&&e.sourcePath){let o=_e(e.sourcePath);try{let i=JSON.parse(Vt(o,"utf8"));i.commit_id=e.newCommitId,Kt(o,JSON.stringify(i,null,2)+`
|
|
20
|
+
`,"utf8")}catch(i){process.stderr.write(`warn: failed to update meta.json commit_id: ${i.message}
|
|
21
|
+
`)}}if(s.ok)for(let o of e.unitLocks??[]){if(!t.files.includes(o.file)){await De({baseUrl:`${e.tmsBaseUrl}/kane-cli/v1`,testId:o.testId,body:{commitId:e.newCommitId,fromCommitId:o.fromCommitId},auth:{username:e.basicAuth.username,accessKey:e.basicAuth.access_key}}),be(o.testId);continue}let i=e.resolvedTest.steps.filter(c=>c.owningFile===o.file),f=i.map(c=>c.objective).filter(c=>typeof c=="string"&&c.length>0).slice(0,50),a=await Nt({baseUrl:`${e.tmsBaseUrl}/kane-cli/v1`,testId:o.testId,body:{commitId:e.newCommitId,fromCommitId:o.fromCommitId,commitMessage:`healed via importer ${e.sourcePath??""}`,totalSteps:i.length,timeTaken:0,objectives:f},auth:{username:e.basicAuth.username,accessKey:e.basicAuth.access_key}});if(a.ok){let c=_e(o.file);try{let y=JSON.parse(Vt(c,"utf8"));y.commit_id=e.newCommitId,Kt(c,JSON.stringify(y,null,2)+`
|
|
22
|
+
`,"utf8")}catch(y){process.stderr.write(`warn: failed to update unit meta commit_id (${o.file}): ${y.message}
|
|
23
|
+
`)}}else process.stderr.write(`warn: unit self-commit failed (${o.file}): ${a.reason??""} ${a.message??""}
|
|
24
|
+
`)}return s}}function io(e){if(!(!e.isFirstRun||!e.sourcePath))return async t=>{if(!e.sourcePath)return;let r=_e(e.sourcePath);try{let n=Jn(r)?JSON.parse(Vt(r,"utf8")):{};e.session.sessionId&&(n.commit_id=e.session.sessionId),t&&(n.testcase_id=t),e.tmsIds?.testId&&(n.test_id=e.tmsIds.testId),e.tmsIds?.projectId&&(n.project_id=e.tmsIds.projectId),e.tmsIds?.folderId&&(n.folder_id=e.tmsIds.folderId),e.tmsIds?.orgId&&(n.org_id=e.tmsIds.orgId),e.tmsIds?.sessionName&&(n.session_name=e.tmsIds.sessionName),Kt(r,JSON.stringify(n,null,2)+`
|
|
25
|
+
`,"utf8")}catch(n){process.stderr.write(`warn: failed to update meta.json after endTest: ${n.message}
|
|
26
|
+
`)}}}function Qn(e){let t=re(e.env),r={files:[]},{session:n,auth:s}=e,o=s.basicAuth?{username:s.basicAuth.username,accessKey:s.basicAuth.access_key}:s.token,i=s.resolvedCreds?.username??s.basicAuth?.username??"",f=s.resolvedCreds?.access_key??s.basicAuth?.access_key??"",a=s.resolvedCreds?.org_id??0,c=s.resolvedCreds?.user_id??0,y=[];for(let k of Object.keys(n.auteurVariables))k.startsWith("secrets.user.")&&y.push({key_name:k.replace("secrets.user.",""),scope:"user"});let A=n.getContext().prior_runs.map(k=>k.status),R=n.auteurVariables,x=Object.keys(R).length>0;return{controllerBaseUrl:t.controllerBaseUrl,tmsBaseUrl:t.tmsBaseUrl,auth:o,authResolver:s.resolver,sessionId:n.sessionId,sessionDir:n.sessionDir,testId:n.testId,commitId:n.sessionId,projectId:e.projectId,folderId:e.folderId,firstObjective:n.firstObjective??"KaneAI Test",firstUrl:n.firstUrl??"",runDirs:n.getRunDirs(),runObjectives:n.getRunObjectives(),runMetadata:n.getRunMetadata(),startedAt:n.startedAt,endedAt:new Date().toISOString(),totalSteps:e.totalSteps,totalDuration:e.totalDuration,runStatuses:A,orgId:a,userId:c,tmsUsername:i,tmsAccessKey:f,screenshotBaseUrl:n.screenshotBaseUrl,screenshotExtMap:e.screenshotExtMap,shareApiBaseUrl:t.shareApiBaseUrl,variables:x?R:void 0,variableIds:e.variableIds,secrets:y,codeExport:e.codeExport,onProgress:e.onProgress,log:e.log,shouldUploadArtifacts:e.shouldUploadArtifacts,shouldReplaceLocalOutput:e.shouldReplaceLocalOutput,shouldCommit:e.shouldCommit,isFirstRun:e.isFirstRun,onAtomicReplace:so(e,r),onCommitLock:oo(e,r),onFinalizeSuccess:io(e),evidence:e.evidence,evidenceRead:e.evidenceRead,authoredExecutionPath:e.authoredExecutionPath}}var Zn=["python","javascript"];function ao(e){if(e!==void 0){if(!Zn.includes(e))throw new Error(`--code-language must be one of: ${Zn.join(", ")} (got "${e}")`);return e}}function Xn(e,t){let r=ao(e.codeLanguage);return{enabled:e.codeExport??t.enabled,language:r??t.language,skipValidation:e.skipCodeValidation??t.skip_validation}}async function es(e){try{let r=await new Je(e.tmsBaseUrl,e.auth.username,e.auth.access_key).createAtmTest({objective:e.objective.slice(0,100),creation_mode:"KANECLI",playground_disabled:e.hasCustomProfile,testURL:e.url,project_id:e.projectId,folder_id:e.folderId,authoring_version:4});return e.log("info","ATM_CREATE_OK","Test created",{test_id:r}),r}catch(t){return e.log("error","ATM_CREATE_FAILED","Test creation failed",{error:t instanceof Error?t.message:String(t)}),null}}var lo=null,co=()=>lo??=import("sharp").then(e=>e.default??e).catch(()=>null),lt=class{maxWorkers;maxRetries=2;queue=[];activeCount=0;drainResolvers=[];sas;log;uploadedExt=new Map;constructor(t,r=3,n){this.sas=t,this.maxWorkers=r,this.log=n}updateSas(t){this.sas=t}enqueue(t,r){this.queue.push({operationId:t,buffer:r}),this.pump()}async drain(t=3e4){if(!(this.queue.length===0&&this.activeCount===0))return new Promise(r=>{this.drainResolvers.push(r),setTimeout(()=>{r()},t)})}pump(){for(;this.activeCount<this.maxWorkers&&this.queue.length>0;){let t=this.queue.shift();this.activeCount++,this.processJob(t).finally(()=>{if(this.activeCount--,this.pump(),this.queue.length===0&&this.activeCount===0){for(let r of this.drainResolvers)r();this.drainResolvers=[]}})}}async processJob(t){let r,n="image/webp",s=await co();if(s)try{let a=await s(t.buffer).webp({quality:80}).toBuffer();r=new Uint8Array(a)}catch(a){r=new Uint8Array(t.buffer),n="image/png",this.log?.("warn","SCREENSHOT_CONVERT_FAILED","WebP conversion failed, using PNG",{operation_id:t.operationId,error:a instanceof Error?a.message:String(a)})}else r=new Uint8Array(t.buffer),n="image/png";let o=n==="image/webp"?"webp":"png",i=`test_screenshots/untagged_screenshot/${t.operationId}.${o}`,f=`${this.sas.base_url}/${this.sas.container}/${i}?${this.sas.sas_token}`;for(let a=0;a<=this.maxRetries;a++)try{let c=await M(f,{method:"PUT",headers:{"Content-Type":n,"x-ms-blob-type":"BlockBlob"},body:r});if(c.ok){this.uploadedExt.set(t.operationId,o);return}if(a<this.maxRetries){await this.backoff(a);continue}this.log?.("warn","SCREENSHOT_UPLOAD_FAILED","Screenshot upload failed after retries",{operation_id:t.operationId,status:c.status,attempts:this.maxRetries+1})}catch{if(a<this.maxRetries){await this.backoff(a);continue}this.log?.("warn","SCREENSHOT_UPLOAD_FAILED","Screenshot upload failed (network error)",{operation_id:t.operationId,error:"network",attempts:this.maxRetries+1})}}backoff(t){let r=t===0?1e3:3e3;return new Promise(n=>setTimeout(n,r))}getExt(t){return this.uploadedExt.get(t)??"png"}getExtMap(){return this.uploadedExt}isNearExpiry(){if(!this.sas.expiry)return!1;let t=new Date(this.sas.expiry).getTime();return Date.now()>t-5*6e4}};var $e=class{config;buffer=[];stepBuffer=new Map;flushTimer=null;currentRunIndex=null;stopped=!1;_droppedBatches=0;_droppedEntries=0;constructor(t){this.config=t}start(){if(this.flushTimer)return;let t=this.config.flushIntervalMs??5e3;this.flushTimer=setInterval(()=>{this.flush().catch(()=>{})},t),this.flushTimer.unref&&this.flushTimer.unref()}setRunIndex(t){this.currentRunIndex=t}log(t,r,n,s={}){if(this.stopped)return;let o=this.buildEntry(t,r,n,s);this.buffer.push(o)}logStep(t,r,n,s={}){if(this.stopped)return;let o=this.buildEntry("debug",r,n,s);o.run_index=t,this.stepBuffer.has(t)||this.stepBuffer.set(t,[]),this.stepBuffer.get(t).push(o)}escalate(t){let r=this.stepBuffer.get(t);r&&r.length>0&&this.buffer.push(...r),this.stepBuffer.delete(t)}discardSteps(t){this.stepBuffer.delete(t)}async flush(){if(this.buffer.length===0)return;let t=this.buffer.splice(0),r=null;try{r=await this.config.getToken()}catch{this.buffer.unshift(...t);return}let n={"Content-Type":"application/json"};r&&(n.Authorization=`Bearer ${r}`);let s=JSON.stringify(t);for(let o=0;o<3;o++){try{let i=new AbortController,f=setTimeout(()=>i.abort(),1e4),a=await M(this.config.proxyUrl,{method:"POST",headers:n,body:s,signal:i.signal});if(clearTimeout(f),a.ok)return}catch{}o<2&&await new Promise(i=>setTimeout(i,1e3*Math.pow(2,o)))}this._droppedBatches++,this._droppedEntries+=t.length}get droppedBatches(){return this._droppedBatches}get droppedEntries(){return this._droppedEntries}async shutdown(){this._droppedBatches>0&&this.log("warn","LOG_DROPS",`Dropped ${this._droppedEntries} entries in ${this._droppedBatches} batches`,{dropped_batches:this._droppedBatches,dropped_entries:this._droppedEntries}),this.stopped=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush()}shutdownSync(){this.stopped=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}get bufferSize(){return this.buffer.length}stepBufferSize(t){return this.stepBuffer.get(t)?.length??0}buildEntry(t,r,n,s){return{hostname:"kane-cli",service:"kane-cli",ddsource:"kane-cli",ddtags:`version:${this.config.device.cli_version}`,level:t,event:r,message:n,session_id:this.config.sessionId,run_index:r.startsWith("tcg_")?null:this.currentRunIndex,identity:this.config.identity,device:this.config.device,context:s,timestamp:new Date().toISOString()}}};import{platform as mo,arch as fo}from"os";function Ht(e=process.env){try{let t=e.KANE_CLI_USER_AGENT;return t&&t.trim()?uo(t):e.CLAUDECODE==="1"||e.CLAUDE_CODE_ENTRYPOINT?"claude-code":e.CURSOR_TRACE_ID||e.TERM_PROGRAM==="cursor"?"cursor":e.TERM_PROGRAM==="vscode"||e.VSCODE_PID?"vscode":e.CI==="true"||e.GITHUB_ACTIONS==="true"||e.GITLAB_CI==="true"||e.CIRCLECI==="true"||e.BUILDKITE==="true"?"ci":"unknown"}catch{return"unknown"}}function uo(e){return e.toLowerCase().replace(/[^a-z0-9_-]/g,"-").slice(0,40)}function ts(e){let t={proxyUrl:Er,sessionId:e.sessionId,identity:e.identity,device:{cli_version:ze,platform:mo(),arch:fo(),host_agent:Ht(),invocation_mode:e.invocationMode},getToken:e.getToken};return new $e(t)}import{execSync as po}from"child_process";import{readFileSync as go}from"fs";import{createHash as ho}from"crypto";import{hostname as bo,platform as yo,arch as vo}from"os";var ct=null;function rs(){return ct||(ct=So(),ct)}function So(){let e=yo();if(e==="darwin")try{let n=po("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf-8",timeout:5e3}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(n?.[1])return n[1]}catch{}if(e==="linux")try{let r=go("/etc/machine-id","utf-8").trim();if(r)return r}catch{}let t=`${bo()}:${e}:${vo()}`;return ho("sha256").update(t).digest("hex").slice(0,32)}async function wo(e){try{let t=re(e.env),n=await new we(t.controllerBaseUrl,e.auth).getScreenshotSas();return e.session.setScreenshotSas(n),e.log("info","SCREENSHOT_SAS_OK","Screenshot SAS fetched",{base_url:n.base_url,container:n.container,expiry:n.expiry}),new lt(n,3,e.log)}catch(t){return e.log("warn","SCREENSHOT_SAS_FAIL","Screenshot SAS fetch failed",{error:t instanceof Error?t.message:String(t)}),null}}async function _o(e){if(e.session.hasRemoteLogger||!e.tmsCreds)return null;let t=e.tmsCreds,r=ts({sessionId:e.session.sessionId,identity:{org_id:String(t.org_id??""),user_id:String(t.user_id??""),machine_id:rs(),email:t.email??null,email_domain:t.email_domain??"unknown",user_type:t.user_type??"unknown",env:e.env,plan:t.plan??"unknown"},invocationMode:e.invocationMode,getToken:e.getToken});return e.session.setRemoteLogger(r),r.start(),r}async function Yt(e){let[t,r]=await Promise.allSettled([e.skipScreenshotQueue?Promise.resolve(null):wo({env:e.env,auth:e.auth,session:e.session,log:e.log}),_o({env:e.env,tmsCreds:e.tmsCreds,getToken:e.getToken,session:e.session,invocationMode:e.invocationMode})]);return{resolver:e.resolver,screenshotQueue:t.status==="fulfilled"?t.value:null,remoteLogger:r.status==="fulfilled"?r.value:null}}async function qt(e){await Promise.allSettled([e.screenshotQueue?.drain(),e.remoteLogger?.shutdown()])}async function Ua(e,t){switch(e.kind){case"boot":{if(t.state.identityServicesRef.current)return t.state.identityServicesRef.current;let r=t.auth.initResolver(e.env);r.prime(e.tmsCreds),t.state.setTmsCredsCache(e.tmsCreds);let n=await Gt(e.env,e.tmsCreds,r,t);return zt(n,t),n}case"login":case"switch":{let r=t.state.identityServicesRef.current;r&&(await qt(r),r.resolver.revoke()),t.state.identityServicesRef.current=null,t.state.screenshotQueueRef.current=null,t.state.setTmsCredsCache(null);let n=t.auth.initResolver(e.env),s=await n.resolve(!0).catch(()=>null);if(!s)return t.log("warn","IDENTITY_VALIDATE_FAILED","Identity validation failed",{kind:e.kind,env:e.env}),null;t.state.setTmsCredsCache(s);let o=await Gt(e.env,s,n,t);return zt(o,t),o}case"logout":{let r=t.state.identityServicesRef.current;return r&&(await qt(r),r.resolver.revoke()),t.state.identityServicesRef.current=null,t.state.screenshotQueueRef.current=null,t.state.setTmsCredsCache(null),null}case"resessionize":{let r=t.state.identityServicesRef.current;r&&await qt(r),t.state.identityServicesRef.current=null,t.state.screenshotQueueRef.current=null;let n=t.state.getTmsCredsCache(),s=t.auth.getResolver(),o=s??t.auth.initResolver(e.env);!s&&n&&o.prime(n);let i=await Gt(e.env,n,o,t);return zt(i,t),i}}}async function Gt(e,t,r,n){let s=n.auth.getBasicAuth(),o=s?null:await n.auth.getToken(),i=s?{username:s.username,accessKey:s.access_key}:o??null;return i===null?{resolver:r,screenshotQueue:null,remoteLogger:null}:Yt({env:e,tmsCreds:t,resolver:r,auth:i,getToken:()=>n.auth.getToken(),session:n.getSession(),log:n.log,skipScreenshotQueue:n.options?.skipScreenshotQueue,invocationMode:"tui"})}function zt(e,t){t.state.identityServicesRef.current=e,t.state.screenshotQueueRef.current=e.screenshotQueue,e.remoteLogger&&(t.exit.registerCleanup("remote-logger",()=>e.remoteLogger.shutdownSync()),t.exit.setExitRemoteLogger(e.remoteLogger))}import{relative as ko}from"path";import{readFile as Io}from"fs/promises";function ns(e){return e.shouldUploadArtifacts&&!e.lockHeld&&!e.isFirstRun&&e.sealed&&!!e.testId}var Wt=e=>e instanceof Error?e.message:String(e);async function ss(e){let{controller:t,tms:r,testId:n,sessionId:s,executionId:o,sealedPackPath:i,projectId:f}=e,a;try{let c={key:"evidence",content_type:"application/zip",filename:`${o}.evidence`},w=(await t.getPresignedUrls(n,s,[c])).urls?.evidence?.upload_url;if(!w)return{ok:!1,stage:"presign",error:"presign response missing evidence upload_url"};a=w}catch(c){return{ok:!1,stage:"presign",error:Wt(c)}}try{let c=await Io(i);await Wr(a,c,"application/zip")}catch(c){return{ok:!1,stage:"upload",error:Wt(c)}}try{await r.ingestEvidence(o,f)}catch(c){return{ok:!1,stage:"ingest",error:Wt(c)}}return{ok:!0}}function os(e){return e.isFirstRun||et(e.decisions)||e.push===!0||e.author===!0}function is(e,t){return{projectId:e?.project_id??t.project_id??null,folderId:e?.folder_id??t.folder_id??null}}function Jt(e){return e?"author":"replay"}function Co(e,t){return e?{session:e,ownsLifecycle:!1}:{session:t,ownsLifecycle:!0}}function Qt(e,t){return e?.total_runs??t?.length??1}function Eo(e){let t=(e?.per_flow_metadata??[]).map(r=>({resultCode:r?.result_code!=null?Number(r.result_code):null}));return{resultCode:e?.result_code!=null?Number(e.result_code):null,...t.length?{perFlow:t}:{}}}var dt=["target","chrome_profile","cdp_endpoint","ws_endpoint","headless"];async function $l(e,t,r){let{path:n,cwd:s,opts:o,isAgent:i,disableAskUser:f,resolved:a,resolvedAuth:c,cliOverrides:y,environment:w,envConfig:A,profile:R,model:x,creds:k,configStore:C,session:l}=e,H=!1,m=await To(n,a,o,{resolvedAuth:c,tmsBaseUrl:A.tmsBaseUrl},l.sessionId,r);if(m.abort)return{overallStatus:"failed",exitCode:m.abort.exitCode,outputDir:ne(n),durationS:0,uploadResult:null};let _=m.lockAcquired,D=!1,ce=new Set,J=!1,X=!1;_&&t.onLockState({phase:"acquired",scope:"preemptive"}),l.start({model:x,environment:w,profile:R}),l.setRecordingEnabled(!1);let N=0,er=c.basicAuth?{username:c.basicAuth.username,accessKey:c.basicAuth.access_key}:c.token??null,xe=null;if(er!==null){let d=await Yt({env:w,tmsCreds:c.resolvedCreds??null,resolver:c.resolver,auth:er,getToken:async()=>c.token??null,session:l,log:(u,g,b,h)=>l.log(u,g,b,h),skipScreenshotQueue:!!o.local||!c.basicAuth,invocationMode:i?"agent":"cli"});xe=d.screenshotQueue,d.remoteLogger&&(r.register("remote-logger",()=>d.remoteLogger.shutdownSync()),r.remoteLogger=d.remoteLogger,e.skipGlobalRemoteLogger||xr(d.remoteLogger))}if(o.name){try{tn(o.name)}catch(d){return process.stderr.write(`error: ${d.message}
|
|
27
|
+
`),{overallStatus:"failed",exitCode:2,outputDir:ne(n),durationS:0,uploadResult:null}}l.setSessionName(o.name)}let ut={};for(let[d,u]of Object.entries(a.rootGlobal))dt.includes(d)||(ut[d]=u);for(let[d,u]of Object.entries(y))dt.includes(d)||u!==void 0&&(ut[d]=u);let ee={...a.chrome};for(let d of dt){let u=y[d];u!==void 0&&(ee[d]=u)}let us={...ut,...ee};l.setResolvedGlobal(us);let tr=k.getActiveProfile()??"default",rr=k.getDefaultEnv(),{rehydrateIfStale:ms}=await import("./profile-sync-DTTRRIVP.js");ms(k,C,tr,rr);let j=C.load(),nr=(y.assertion_mode??j.assertion_mode)==="dom"?"dom":"visual",sr=y.final_validation,or=sr===void 0?void 0:sr==="on",F=j.project_id??null,de=j.folder_id??null,ir=os({isFirstRun:m.isFirstRun,decisions:m.decisions,push:o.push===!0,author:o.author===!0});if(ir){if(c.basicAuth){let d=await Dr({creds:k,config:C,profile:tr,env:rr,tmsCreds:c.basicAuth,isLocal:!!o.local,log:(u,g,b,h)=>l.log(u,g,b,h),onAnnounce:e.onAnnounce,onFatalExit:e.onFatalExit});if(d.status==="ok"){F=d.projectId,de=d.folderId,j=C.load();let u=he(n);u?.project_id&&(F=u.project_id,de=u.folder_id??de),i&&d.autoDefaulted&&t.onAgentEvent(Lr(d.autoDefaulted))}else if(d.status==="cancelled"){process.stderr.write(`error: project/folder configuration failed. See remediation above, or use --local.
|
|
28
|
+
`);let{shutdown:u}=await import("./exit-manager-VCSIUYBR.js");return u(2,"project/folder gate failed"),{}}}}else{let d=he(n);({projectId:F,folderId:de}=is(d,{project_id:j.project_id??null,folder_id:j.folder_id??null})),l.log("info","GATE_SKIP_REPLAY","Project/folder gate skipped (planned pure replay)",{meta_project:!!d?.project_id,config_project:!!j.project_id})}{let d=Jr(a),u=c.resolvedCreds?.org_id!=null?String(c.resolvedCreds.org_id):void 0,g=d.find(p=>p.project_id&&F&&p.project_id!==String(F)||p.org_id&&u&&p.org_id!==u),b=new Set(d.map(p=>p.project_id).filter(Boolean)),h=new Set(d.map(p=>p.org_id).filter(Boolean));if(g||b.size>1||h.size>1){let p=g??d[0];return process.stderr.write(`error: tenant mismatch \u2014 imported test '${p.file}' was authored under project ${p.project_id??"?"} / org ${p.org_id??"?"}, which differs from the run's project/org (or another imported test). Cross-tenant imports are not allowed.
|
|
29
|
+
`),await l.finish("complete"),{overallStatus:"failed",exitCode:2,outputDir:ne(n),durationS:0,uploadResult:null}}}let ie;try{ie=await Fn({config:{chrome_profile_path:ee.chrome_profile??null,window_size:{width:1920,height:1080}},startUrl:Ye,headless:ee.headless??!1,wsEndpoint:ee.ws_endpoint,cdpEndpoint:ee.cdp_endpoint})}catch(d){return process.stderr.write(`error: Chrome launch failed: ${d.message}
|
|
30
|
+
`),await l.finish("complete"),{overallStatus:"failed",exitCode:2,outputDir:ne(n),durationS:0,uploadResult:null}}let Me=ie.instance;Me&&r.register("chrome",()=>{try{Me.kill()}catch{}});let ar=$r(ie.cdpEndpoint),G=null,lr=ie.cdpEndpoint??ee.cdp_endpoint;if(lr&&!ee.ws_endpoint&&!ee.headless&&!e.isAgent)try{G=xn({headless:ee.headless??!1,cdpEndpoint:lr,chromePid:Me?.process.pid}),G&&r.register("marker-overlay",()=>G.kill())}catch(d){l.log("warn","OVERLAY_SPAWN_FAILED","Marker overlay spawn failed",{error:String(d)})}c.resolvedCreds?.org_id!==void 0&&l.setOrgId(String(c.resolvedCreds.org_id)),l.setUserIdentity(c.resolvedCreds?.username??null,c.resolvedCreds?.email??null);let fe=Gn({objective:"",globalDir:le(_t,"variables"),localDir:le(s,".testmuai","variables"),file:o.variablesFile,inline:o.variables}),fs=a.rootGlobal.variables??{},Q=Ao(fe.raw,fs);l.setAuteurVariables(Q.auteur);let cr=Bt(le(_t,"global-memory.md"))??void 0,dr=Bt(le(s,".testmuai","context.md"))??void 0;o.local?process.stderr.write(`info: --local \u2014 KaneAI upload skipped
|
|
31
|
+
`):c.basicAuth?F||(ir?process.stderr.write(`warn: KaneAI upload skipped \u2014 no project configured.
|
|
32
|
+
`):process.stderr.write(`warn: evidence publish will be skipped \u2014 no project_id in meta.json or config.
|
|
33
|
+
`)):process.stderr.write(`warn: KaneAI upload skipped \u2014 TMS credentials could not be resolved.
|
|
34
|
+
Run 'kane-cli login' (OAuth) or 'kane-cli config set-username/set-access-key' (basic auth).
|
|
35
|
+
`);let ve=!o.local&&!!c.basicAuth&&F!=null;if(l.log("info","PIPELINE_GATE_STATE","Initial gate state (run-start)",{phase:"run-start",shouldUploadArtifacts:ve,lockHeld:_,isFirstRun:m.isFirstRun,hasAuth:m.hasAuth}),ve&&m.testId==null&&!m.degradedReadonly){let d=re(w);try{let u=await es({tmsBaseUrl:d.tmsBaseUrl,auth:c.basicAuth,objective:a.steps[0].objective,url:"",projectId:F,folderId:de??"",hasCustomProfile:!!ee.chrome_profile,log:(g,b,h,p)=>l.log(g,b,h,p)});u&&l.setTestId(u)}catch(u){process.stderr.write(`warn: ATM test creation failed: ${u.message}
|
|
36
|
+
`)}}else m.testId&&l.setTestId(m.testId);let Be={};if(c.basicAuth&&!o.local&&(Q.secretEntries.length>0||Q.nonSecretEntries.length>0))try{Be=await zn({variables:Q,auth:c.basicAuth,orgId:String(c.resolvedCreds?.org_id??""),env:w,localMode:!!o.local,log:(d,u,g,b)=>l.log(d,u,g,b)})}catch(d){process.stderr.write(`warn: variable/secret push failed: ${d.message}
|
|
37
|
+
`)}let mt=new Map;for(let[d,u]of Q.nonSecretEntries)mt.set(d,u.value);let ft=new Map;for(let[d,u]of Q.secretEntries)ft.set(d,u.value);async function pt(d){if(!c.basicAuth||o.local)return;let u=[],g=[];for(let[h,p]of Object.entries(d))if(p.secret){if(ft.get(h)===p.value)continue;g.push([h,p])}else{if(mt.get(h)===p.value)continue;u.push([h,p])}if(u.length===0&&g.length===0)return;let b=re(w);if(u.length>0){let h=new ke(b.tmsBaseUrl,c.basicAuth.username,c.basicAuth.access_key);for(let[p,I]of u)try{let P=await h.upsertVariable({name:p,value:I.value});Be[p]=P.id,mt.set(p,I.value),l.log("info","VAR_PUSH_STEP","Variable updated mid-run",{name:p})}catch(P){l.log("warn","VAR_PUSH_STEP_FAILED","Mid-run variable push failed",{name:p,error:String(P)})}}if(g.length>0){let h=new Re(b.secretsBaseUrl);for(let[p,I]of g)try{await h.pushSecret({secretKey:p,secretValue:I.value,username:c.basicAuth.username,accessKey:c.basicAuth.access_key,orgId:String(c.resolvedCreds?.org_id??"")}),ft.set(p,I.value),l.log("info","SECRET_PUSH_STEP","Secret updated mid-run",{name:p})}catch(P){l.log("warn","SECRET_PUSH_STEP_FAILED","Mid-run secret push failed",{name:p,error:String(P)})}}}let Pe=xe?(d,u,g,b)=>{if(!(_||m.isFirstRun))return;if(L&&b){_n(L.packTestDir,b,xe,(p,I,P,q)=>l.log(p,I,P,q));return}let h=N+u;In(l.sessionDir,h,d,xe,(p,I,P,q)=>l.log(p,I,P,q),g)}:void 0,ur=a.rootTitle??a.rootSteps[0]?.heading??as(n),ps=Object.keys(Q.raw).length>0?Se(Q.raw,ur).objective:ur,pe=Cn({flag:o.url,frontmatter:a.rootGlobal?.url,configDefault:C.load().default_url}),gs=En({resolvedUrl:pe,local:!!o.local,allowMissingUrl:!!o.allowMissingUrl,isTTY:!!process.stdin.isTTY});l.setFirstRun(ps,pe??"");let ue=new st(a),Ve=new Date().toISOString(),mr=Date.now(),gt=e.evidenceAttach?null:new Mr({origin:"testmd",runKind:"author",pid:process.pid,title:a.rootTitle??as(n),started:Ve,producerVersion:ze,surfaces:pe?[pe]:void 0,testmdRelPath:ko(s,n),definition:{path:"test.md",content:cs(n,"utf8")},cwd:s,packRootDir:le(l.sessionDir,"evidence")}),ae=Co(e.evidenceAttach,gt),Z=ae.session,L=null;if(e.evidenceAttach)L={executionId:e.evidenceAttach.id,testId:e.evidenceAttach.test,packTestDir:e.evidenceAttach.packTestDir};else if(gt)try{L=await gt.start()}catch(d){l.log("warn","EVIDENCE_START_FAILED","Evidence pack creation failed",{error:String(d)})}let Ke=[],ht=[],fr,bt=(d,u,g,b,h)=>{if(!L)return;Z.noteSpawn(h?.length?{...d,steps:d.steps.map(I=>({...I,verifies:h}))}:d),d.resolution&&(fr=d.resolution),Ke.push(Eo(u));let p=Qt(u,b);for(let I=0;I<p;I++)ht.push(g+I)},yt=()=>L?{packTestDir:L.packTestDir,ordinalOffset:Z.nextOrdinalOffset()}:void 0,hs=typeof o.maxSteps=="string"&&o.maxSteps!==""?parseInt(o.maxSteps,10):void 0;function pr(d,u){let g=a.steps[d],b=ls(g.config,y),h=Ce(fe.raw,b.variables,g.objective);return Nn({objective:h.objective,url:d===0?pe??void 0:g.unitEntryUrl,requireStartUrl:d===0&&gs,model:x,chrome:ie,auth:c,sessionId:l.sessionId,runIndex:u,windowSize:{width:1920,height:1080},maxSteps:b.max_steps??hs??30,headless:ee.headless??!1,disableAskUser:!0,variables:Object.keys(h.variables).length>0?h.variables:void 0,globalContext:b.global_context??cr,localContext:b.local_context??dr,sessionContext:l.getContext(),bugDetection:o.bugDetection??j.bug_detection,evidence:yt()})}function gr(d){let g=a.steps[d].trace[0].stepIndex,b=a.rootSteps.find(p=>p.index===g);a.steps.slice(0,d).some(p=>p.trace[0].stepIndex===g)||t.onAgentEvent({type:"test_md_step_start",step_index:g,heading:b.heading,ref:b.body.kind==="import_ref"?{kind:"import",label:b.body.path,unit_kind:b.body.path.endsWith("_test.md")?"test":"helper"}:null})}function vt(d,u,g,b,h,p){let I=a.steps[d],P=I.trace[0].stepIndex,q=!a.steps.slice(d+1).some(T=>T.trace[0].stepIndex===P),V=g?.status==="passed"?"passed":"failed",O=g?.reason??h??void 0,U=g?.duration??p,S=g?.verdict;if(S&&typeof S=="object"){let T=typeof S.one_liner=="string"?S.one_liner:"",E=typeof S.bug_title=="string"&&S.bug_title?S.bug_title:T;if(E&&V==="failed"){let K=[S.family,S.category].filter(Boolean).join("/"),te=typeof S.confidence=="number"?`, confidence ${S.confidence.toFixed(2)}`:"";O=`${O??"failed"} \u2014 bug verdict: ${E}${K?` [${K}${te}]`:""}`}let v=typeof S.category_proposal=="string"?S.category_proposal:"";v&&V==="failed"&&(O=`${O??"failed"}; category proposal: ${v} \u2014 consider adding to taxonomy`),t.onAgentEvent({type:"test_md_bug_verdict",step_index:I.trace[0].stepIndex,confirmed:S.confirmed===!0,bug_title:E||null,family:S.family??null,category:S.category??null,category_proposal:v||null,severity:S.severity??null,confidence:typeof S.confidence=="number"?S.confidence:null,one_liner:T||null})}let{continueOverall:$}=ue.recordStep(I,{status:V,duration_s:U,reason:O}),Y=ls(I.config,y),W=Ce(fe.raw,Y.variables,I.objective).objective;if(g){let T=Rn(g,u,b);l.addRunResult(kn(g,W,u,T),g.total_runs)}else l.addRunResult({index:u,objective:W,status:V,summary:"",context:{memory:{},variables:{},pointer:""}},1);if(q||!$){let T=ue.snapshotOutcomes().find(E=>E.rootStepIndex===P);t.onAgentEvent({type:"test_md_step_end",step_index:P,status:T.status,duration_s:T.duration_s??0,ref_kind:T.refKind??null,unit_kind:T.refKind==="import"?(T.refLabel??"").endsWith("_test.md")?"test":"helper":null,inlined_count:T.inlinedCount??null,failed_sub_step_index:T.failedSubStepIndex??null})}return $}let St=[];async function bs(d){an(d,a.steps.length);for(let u=0;u<d;u++){if(H||e.signal?.aborted)return{failedAt:u,cancelled:!0};let g=a.steps[u],b=m.decisions[u];if(b.kind!=="replay")return process.stderr.write(`error: runReplayPhase invoked on a non-replay decision at step ${u}
|
|
38
|
+
`),{failedAt:u,cancelled:!1};let h=l.nextRunIndex();N=h;let p=u===0?pe??void 0:a.steps[u].unitEntryUrl,I={width:j.window_size.width,height:j.window_size.height},P=Ce(fe.raw,g.config.variables,g.objective),q=Ut({step:g,decision:b,chrome:ie,auth:c,sessionId:l.sessionId,runIndex:h,sessionDir:l.sessionDir,windowSize:I,forceNavigateUrl:p,sessionContext:l.getContext(),variables:Object.keys(P.variables).length>0?P.variables:void 0,evidence:yt(),investigationAsync:!ae.ownsLifecycle});await pt(P.raw),gr(u);let V=Date.now(),O=null,U=null,S=Ze();try{let T=Et(q,{environment:w});r.register("runner",()=>{(Ct()||e.signal?.aborted)&&(H=!0);try{T.cancel()}catch{}}),G?.setRunActive(!0);try{for await(let E of T.events){if(t.onAgentEvent(E),S=At(S,E),E.type==="step_event"&&E.event==="reasoning"?G?.setStepText(E.detail):E.type==="step_end"&&(E.status==="passed"&&G?.setStepComplete(),Pe&&Pe(E.index,0,E.child_id,typeof E.ordinal=="number"&&E.id?{ordinal:E.ordinal,id:E.id}:void 0)),E.type==="run_end"){O=E;break}if(E.type==="error"){U=E.message??"runner error";break}}if(!ae.ownsLifecycle&&O?.status==="failed")r.deregister("runner"),St.push({exited:T.exited.then(()=>{}).catch(()=>{}),cancel:()=>{try{T.cancel()}catch{}}});else try{T.cancel()}catch{}if(!O&&!U){let{code:E}=await T.exited;E!==0&&(U=`runner exited with code ${E}`)}}finally{G?.setRunActive(!1),r.cleanup("runner","Replay step complete")}}catch(T){U=T.message}if(H)return{failedAt:u,cancelled:!0};let $=Math.round((Date.now()-V)/1e3),Y=vt(u,h,O,null,U,$);l.recordStepRun({testmdStepIndex:a.steps[u].flatIndex,runIndex:h,totalRunDirs:1}),bt(S,O,h,null,a.steps[u].verifies);let W=!!U||O?.status==="failed";if(ln(u,W?"failed":"ok"),W||!Y)return{failedAt:u,cancelled:!1}}return{failedAt:null,cancelled:!1}}let hr=async()=>{if(_)return!0;let d=c.basicAuth;if(!d){let h=await c.resolver.resolve(!0);h?.username&&h?.access_key&&(d={username:h.username,access_key:h.access_key},c.basicAuth=d)}if(!m.testId||!m.fromCommitId||!d)return process.stderr.write(`error: cannot acquire lock \u2014 missing required state
|
|
39
|
+
`),!1;let u=l.sessionId,g=o.onLockConflict??a.rootGlobal.on_lock_conflict??"readonly",b=await Xt({tmsBaseUrl:A.tmsBaseUrl,testId:m.testId,fromCommitId:m.fromCommitId,newCommitId:u,basicAuth:d,onLockConflict:g});if(b==="ok"){_=!0,m.newCommitId=u,l.log("info","MID_RUN_LOCK_ACQUIRED","Mid-run lock acquired",{test_id:m.testId}),i&&t.onLockState({phase:"acquired",scope:"mid_run"}),nt({baseUrl:Ee(A.tmsBaseUrl),testId:m.testId,auth:Ae(d),lifecycle:r});let h=await ds({resolved:a,decisions:m.decisions,tmsBaseUrl:A.tmsBaseUrl,newCommitId:u,basicAuth:d,mode:g,lifecycle:r,alreadyLocked:m.unitLocks,allUnits:!0});return h.outcome==="ok"?m.unitLocks.push(...h.locks):process.stderr.write(`warn: mid-run unit lock acquisition degraded (${h.outcome}) \u2014 affected units will not self-commit
|
|
40
|
+
`),!0}return l.log("error","MID_RUN_LOCK_CONFLICT","Mid-run lock acquisition failed",{reason:b}),i&&t.onLockState({phase:"conflict",scope:"mid_run",reason:b}),process.stderr.write(`error: mid-run lock acquisition failed (${b})
|
|
41
|
+
`),!1};if(i){let d=o.author===!0;d&&(Ot(),l.log("info","FORCE_AUTHOR_RUN","--author flag set; walker bypassed"));let{authorBoundary:u,cancelledInPhase:g,shrinkCount:b}=await fn({decisions:m.decisions,forceAuthor:d,hasRetry:o.retry===!0||o.retryCount!==void 0,maxShrinks:o.retryCount!==void 0?parseInt(o.retryCount,10):Le.maxShrinks,runReplayPhase:bs,session:l,accumulator:ue,acquireLockIfNeeded:hr});if(X=b>0,b>0&&(l.log("info","RETRY_TRIGGERED","Retry loop triggered",{shrink_count:b,final_author_boundary:u}),t.onRetryAttempt({shrink_count:b,final_author_boundary:u,complete_reauthor:u===0})),u===0&&b>0&&l.log("info","COMPLETE_REAUTHOR_TRIGGERED","Complete reauthor fallback",{shrink_count:b}),!g&&u>=0)for(let h=u;h<a.steps.length&&!e.signal?.aborted;h++){let p=a.steps[h];if(!ue.shouldRunFlatStep(p))continue;gr(h),D=!0,ce.add(a.steps[h].flatIndex);let I=l.nextRunIndex();N=I,await pt(Ce(fe.raw,p.config.variables,p.objective).raw);let P=pr(h,I),q=Date.now(),V=null,O=null,U=null,S=!1,$=0,Y=Ze();try{let E=Et(P,{environment:w,assertionMode:nr,finalValidation:or});r.register("runner",()=>{(Ct()||e.signal?.aborted)&&(H=!0);try{E.cancel()}catch{}}),G?.setRunActive(!0);try{for await(let v of E.events){if(t.onAgentEvent(v),Y=At(Y,v),v.type==="bifurcation"){let K=v.count??v.flows?.length??0;(v.is_single_flow??K<=1)||(U=v.flows??null,S=!0,$=0)}else if(v.type==="run_start"&&S)$++;else if(v.type==="step_event"&&v.event==="reasoning")G?.setStepText(v.detail);else if(v.type==="step_end"&&(v.status==="passed"&&G?.setStepComplete(),Pe)){let K=S?Math.max(0,$-1):0;Pe(v.index,K,v.child_id,typeof v.ordinal=="number"&&v.id?{ordinal:v.ordinal,id:v.id}:void 0)}if(v.type==="run_end"){V=v;break}if(v.type==="error"){O=v.message??"runner error";break}}try{E.cancel()}catch{}}finally{G?.setRunActive(!1),r.cleanup("runner","Step complete")}}catch(E){O=E.message}let W=Math.round((Date.now()-q)/1e3),T=vt(h,I,V,U,O,W);if(l.recordStepRun({testmdStepIndex:a.steps[h].flatIndex,runIndex:I,totalRunDirs:Qt(V,U)}),bt(Y,V,I,U,a.steps[h].verifies),!T||H||e.signal?.aborted)break}}else{let{effectiveDecisions:d}=await import("./effective-decisions-DRM3JSR4.js"),{decideRetry:u}=await import("./replay-policy-6USQBT3E.js"),g=o.retry===!0||o.retryCount!==void 0,b=o.retryCount!==void 0?parseInt(o.retryCount,10):Le.maxShrinks,h=o.author===!0;h&&(Ot(),l.log("info","FORCE_AUTHOR_RUN","--author flag set; walker bypassed"));let p=h?0:tt(m.decisions),I=0,P=null,q=m.decisions.filter(S=>S.kind==="replay").length,V=m.decisions.length-q,O=[];o.push&&O.push("--push"),g&&O.push("--retry"),o.retryCount!==void 0&&O.push(`--retry-count=${o.retryCount}`),h&&O.push("--author");let U={source:n,steps:{total:m.decisions.length,replay:q,author:V},model:x,viewport:{width:j.window_size.width,height:j.window_size.height},chrome:ie.cdpEndpoint??ie.wsEndpoint??"managed",session:l.sessionName??"ephemeral",variables:{count:Object.keys(Q.raw).length,secrets:Object.values(Q.raw).filter(S=>S.secret).length,names:Object.keys(Q.raw)},flags:O,mode:y.mode??"testing"};for(;;){let S=l.snapshot(),$=ue.snapshot(),Y=d(m.decisions,p,h);if(I>=1){let v=p===0?`\u21BB Complete re-author \u2014 retry budget exhausted (${I}/${b})`:`\u21BB Retry ${I}/${b} \u2014 replay 0..${p-1}, author ${p}..${m.decisions.length-1}
|
|
42
|
+
reason: replay miss at step ${(P??0)+1}`;process.stderr.write(v+`
|
|
43
|
+
`)}let W=I>=1&&p>0&&P!==null?{startIdx:0,endIdx:P,count:P}:void 0;G?.setRunActive(!0);let T=await Do({decisions:Y,resolved:a,session:l,accumulator:ue,tuiConfig:j,globalConfig:U,buildStepConfigAt:pr,buildReplayConfig:v=>{let K=m.decisions[v];if(K.kind!=="replay")throw new Error("expected replay decision at index "+v);let te=a.steps[v];return Ut({step:te,decision:K,chrome:ie,auth:c,sessionId:l.sessionId,runIndex:l.nextRunIndex(),sessionDir:l.sessionDir,windowSize:{width:j.window_size.width,height:j.window_size.height},forceNavigateUrl:v===0?pe??void 0:te.unitEntryUrl,sessionContext:l.getContext(),variables:xo(fe.raw,te.config.variables,te.objective),evidence:yt()})},onAnyAuthorStep:v=>{D=!0,ce.add(a.steps[v].flatIndex)},onCancel:()=>{J=!0},topBannerModel:x,topBannerAuth:`${k.getActiveProfile()??"no profile"}/${w}`,spawnOpts:{environment:w,mode:y.mode??"testing",assertionMode:nr,finalValidation:or,log:(v,K,te,wt)=>l.log(v,K,te,wt)},priorAttemptRollup:W,pushStepLevelDelta:(v,K)=>pt(Ce(fe.raw,v,K).raw),onSequencerStepEnd:(v,K,te,wt)=>{let _s=Math.round((Date.now()-wt)/1e3),Is=v.hadError?v.reason??"runner error":null,Rs=vt(K,te,v.runEnd,v.bifurcationFlows??null,Is,_s);return l.recordStepRun({testmdStepIndex:a.steps[K].flatIndex,runIndex:te,totalRunDirs:Qt(v.runEnd,v.bifurcationFlows)}),bt(v.evidence??Ze(),v.runEnd,te,v.bifurcationFlows,a.steps[K].verifies),Rs},screenshotDispatcher:Pe,onReasoning:v=>G?.setStepText(v),onStepComplete:()=>G?.setStepComplete(),onSpawnStart:v=>{N=v},host:t});if(G?.setRunActive(!1),T.cancelled){r.cleanup("marker-overlay","user cancelled run"),r.cleanup("chrome","user cancelled run");break}if(T.failedAt===null)break;let E=u({failedAt:T.failedAt,shrinkCount:I,hasRetry:g,maxShrinks:b});if(E.kind==="fail"||!_&&!await hr())break;l.rollback(S),ue.rollback($),E.kind==="complete-reauthor"?p=0:p=E.newAuthorBoundary,I++,X=!0,l.log("info","RETRY_TRIGGERED","Retry loop triggered (TTY)",{shrink_count:I,failed_at:P}),p===0&&l.log("info","COMPLETE_REAUTHOR_TRIGGERED","Complete reauthor fallback (TTY)",{shrink_count:I}),P=T.failedAt}}let z=ue.finalize(),ge=Math.round((Date.now()-mr)/1e3),ys={session:l,resolvedAuth:c,chromeResult:ie,chromeInstance:Me??null,testId:l.testId??null,preparedVariables:Q,variableIds:Be,globalContext:cr,localContext:dr,tuiConfig:j,env:w,localMode:!!o.local},br=!1,yr=!1,vr=!1,Sr=async(d={})=>{if(!L)return!1;if(ae.ownsLifecycle?br:vr)return!0;try{let u=await ar(),g=Jt(D)==="replay",b=le(ne(n),".internal","execution.json"),h=le(l.sessionDir,"execution.json"),p=qr(L.packTestDir,g?[b,h]:[h,b],(S,$,Y,W)=>l.log(S,$,Y,W)),{ids:I,linear:P}=p?zr(L.packTestDir):{ids:[],linear:!0},{steps:q,tail:V,unjoined:O}=Gr(Z.steps,I,g,P);p?O?l.log("warn","SKIPPED_TAIL_UNJOINED","Executed records don't align with the authored blob \u2014 skipped tail withheld",{executed:Z.steps.length,leaves:I.length}):V.length>0&&l.log("info","SKIPPED_TAIL_APPENDED","Unexecuted authored actions recorded as skipped",{count:V.length}):l.log("warn","SKIPPED_TAIL_NO_BLOB","No auteur blob in pack \u2014 unexecuted actions cannot be recorded as skipped",{});let U=await Z.writeResult({steps:[...q,...V],spawns:Ke.length?Ke:[{resultCode:null}],tags:a.rootGlobal.tags,externalIdInput:{execution_id:L.executionId,session_id:l.sessionId,commit_id:l.sessionId,test_id:m.testId??l.testId??void 0,testcase_id:d.testcaseId??m.testcaseId??l.testcaseId??void 0,project_id:F??void 0,folder_id:de??void 0,org_id:l.orgId!=null?String(l.orgId):void 0,session_name:l.sessionName??Te(n),user_name:l.userName??void 0,user_email:l.userEmail??void 0,sharable_link:Tn(re(w).testManagerUiUrl,F,d.testcaseId??m.testcaseId??l.testcaseId,d.shareId)},runnerEnv:Nr({cdpBrowser:u,resolution:fr}),intentEnv:{model:x,platform:"Desktop",platform_type:"web",...ae.ownsLifecycle?{}:{run_kind:Jt(D)}},durationMs:Date.now()-mr,log:(S,$,Y,W)=>l.log(S,$,Y,W)});if(!ae.ownsLifecycle)return await jr(Z.pack,L.testId,le(l.sessionDir,"tui.log")),vr=!0,l.log("info","EVIDENCE_RESULT_WRITTEN","Member result.yaml written",{execution_id:L.executionId,verdict:U}),!0;if(!yr)try{let S=Kr({cwd:process.cwd(),members:[{path:n,verdict:U,executionId:L.executionId,startedAt:new Date().toISOString(),acs:Vr(Z.steps),mode:"testmd",local:!!o.local}]});yr=!0;for(let $ of S.warnings)l.log("warn","EXEC_SYNC",$,{});S.synced>0&&l.log("info","EXEC_SYNC",`context sync: ${S.synced} fact(s), ${S.superseded} supersession(s)`,{})}catch(S){l.log("warn","EXEC_SYNC",`exec-sync failed: ${S instanceof Error?S.message:String(S)}`,{})}try{let S=Hr(Z.pack,Br(process.cwd()));S.status==="skipped"&&l.log("warn","EVIDENCE_COVERAGE_SKIPPED",`coverage/usecases.yaml not written: ${S.reason}`,{})}catch(S){l.log("warn","EVIDENCE_COVERAGE_SKIPPED","coverage writer threw",{error:String(S)})}return await Fr({executionId:L.executionId,testId:L.testId,saved:!0,runKind:Jt(D),verdict:U,outputStemDir:ne(n),cwd:s,packDir:Z.pack,tuiLogPath:le(l.sessionDir,"tui.log"),expectStatusDisagrees:(o.bugDetection??j.bug_detection)==="continue",log:(S,$,Y,W)=>l.log(S,$,Y,W),surface:"testmd"}),br=!0,l.log("info","EVIDENCE_SEALED","Evidence pack sealed",{execution_id:L.executionId,verdict:U}),!0}catch(u){return l.log("warn","EVIDENCE_SEAL_FAILED","Evidence pack seal failed",{error:String(u)}),!1}},He=ve&&(_||m.isFirstRun)&&!m.degradedReadonly,vs=async()=>{if(!c.basicAuth)return null;let d=re(w),u=(D||o.push===!0)&&!J,g=(_||m.isFirstRun)&&!J&&z.overallStatus==="passed"&&!m.degradedReadonly;l.log("info","PIPELINE_GATE_STATE","Derived gate state (finalize)",{phase:"finalize",shouldUploadArtifacts:ve,shouldUploadPipeline:He,shouldReplaceLocalOutput:u,shouldCommit:g,lockHeld:_,anyAuthorStepRan:D,cancelled:J,overallStatus:z.overallStatus});let b=Qn({session:l,env:w,auth:c,variables:Q,variableIds:Be,projectId:F,folderId:de,totalSteps:z.outcomes.length,totalDuration:ge,screenshotExtMap:xe?.getExtMap(),codeExport:Xn({codeExport:o.codeExport,codeLanguage:o.codeLanguage,skipCodeValidation:o.skipCodeValidation},j.code_export),onProgress:()=>{},log:(p,I,P,q)=>l.log(p,I,P,q),shouldUploadArtifacts:He,shouldReplaceLocalOutput:u,shouldCommit:g,isFirstRun:m.isFirstRun,resolvedTest:a,sourcePath:n,stepRunRecords:l.getStepRunRecords(),authoredFlatIdx:[...ce],unitLocks:m.unitLocks,outcomes:z.outcomes,overallStatus:z.overallStatus,fromCommitId:m.fromCommitId,startedISO:Ve,durationS:ge,tmsIds:{testId:m.testId??l.testId??void 0,testcaseId:m.testcaseId??l.testcaseId??void 0,projectId:F??void 0,folderId:de??void 0,orgId:l.orgId??void 0,sessionName:l.sessionName??Te(n)},tmsBaseUrl:A.tmsBaseUrl,testId:m.testId??void 0,newCommitId:m.newCommitId??void 0,basicAuth:c.basicAuth??void 0,decisions:m.decisions,wantsPush:o.push===!0,retryTriggered:X,forceAuthor:o.author===!0,evidence:L&&ae.ownsLifecycle?{executionId:L.executionId,packTestDir:L.packTestDir,sealedPackPath:Z.pack,cwd:s,runIndices:ht,sealFn:Sr}:void 0,evidenceRead:L&&!ae.ownsLifecycle?{packTestDir:L.packTestDir,runIndices:ht}:void 0,authoredExecutionPath:D?void 0:le(ne(n),".internal","execution.json")});m.newCommitId!=null&&(b.skipTmsFinalize=!0);let h=new sn(b);return i?await h.execute():await t.runUpload(h,p=>{if(p.testcaseId&&p.shareId&&F)return ot(d.testManagerUiUrl,F,p.testcaseId,p.shareId)})};L&&await ar();let oe=await Yn(ys,{performUpload:vs,runCleanup:()=>{r.cleanup("chrome","test.md run complete")},log:(d,u,g,b)=>l.log(d,u,g,b)},{overallStatus:z.overallStatus,outcomes:z.outcomes,sourcePath:n,title:a.rootTitle,rootSteps:a.rootSteps,startedISO:Ve,durationS:ge,localMode:!!o.local,skipLocalWrites:!0}),wr=await Sr({testcaseId:oe.uploadResult?.testcaseId,shareId:oe.uploadResult?.shareId}),_r=o.evidencePublish===!1,Ir=ae.ownsLifecycle&&!!L&&!!c.basicAuth&&ns({shouldUploadArtifacts:ve,lockHeld:_,isFirstRun:m.isFirstRun,sealed:wr,testId:m.testId});if(Ir&&_r)l.log("info","EVIDENCE_PUBLISH_SKIPPED","Replay evidence publish skipped (--no-evidence-publish)",{execution_id:L.executionId}),process.stderr.write(`info: evidence publish skipped (--no-evidence-publish)
|
|
44
|
+
`);else if(_r&&(_||m.isFirstRun))process.stderr.write(`note: --no-evidence-publish has no effect on author/commit runs
|
|
45
|
+
`);else if(Ir){let d=c.basicAuth,u=L,g=F,b=await ss({controller:new we(A.controllerBaseUrl,{username:d.username,accessKey:d.access_key}),tms:new Je(A.tmsBaseUrl,c.resolvedCreds?.username??d.username,c.resolvedCreds?.access_key??d.access_key),testId:m.testId,sessionId:l.sessionId,executionId:u.executionId,sealedPackPath:Z.pack,projectId:g});b.ok?l.log("info","EVIDENCE_INGESTED","Replay evidence uploaded and ingested",{execution_id:u.executionId,project_id:g}):(l.log("warn","EVIDENCE_PUBLISH_FAILED","Replay evidence publish failed",{execution_id:u.executionId,stage:b.stage,error:b.error}),process.stderr.write(` \u26A0 evidence publish failed (${b.stage}): ${b.error}
|
|
46
|
+
`)),t.onAgentEvent({type:"test_md_evidence_ingest",status:b.ok?"ok":"failed",evidence_id:u.executionId,...b.ok?{}:{stage:b.stage}})}await Lo(n,m,l,z.outcomes,z.overallStatus,Ve,ge,oe.uploadResult,j,o,{resolvedAuth:c,tmsBaseUrl:A.tmsBaseUrl},_,J);try{let d=he(n);if(Qr({shouldUploadPipeline:He,uploadSucceeded:!!oe.uploadResult?.success,metaCommitId:d?.commit_id,metaTestId:d?.test_id})){let u=await Tt({sourcePath:n,testId:d.test_id,sessionId:l.sessionId,commitId:d.commit_id,controller:new we(A.controllerBaseUrl,{username:c.basicAuth.username,accessKey:c.basicAuth.access_key})});u.ok?l.log("info","BUNDLE_SYNC_OK","testmd bundle pushed",{commit_id:d.commit_id,bytes:u.bytes}):(l.log("warn","BUNDLE_SYNC_FAILED","testmd bundle sync failed",{commit_id:d.commit_id,stage:u.stage,error:u.error}),process.stderr.write(` \u26A0 bundle sync failed (${u.stage}): ${u.error}
|
|
47
|
+
`)),t.onAgentEvent({type:"test_md_bundle_sync",status:u.ok?"ok":"failed",commit_id:d.commit_id,path:n,...u.ok?{bytes:u.bytes}:{stage:u.stage}})}}catch(d){l.log("warn","BUNDLE_SYNC_FAILED","testmd bundle sync threw",{error:d instanceof Error?d.message:String(d)})}if(He&&oe.uploadResult?.success)for(let d of m.unitLocks)try{let u=he(d.file);if(u?.commit_id!==l.sessionId||!u?.test_id)continue;let g=await Tt({sourcePath:d.file,testId:String(u.test_id),sessionId:l.sessionId,commitId:String(u.commit_id),controller:new we(A.controllerBaseUrl,{username:c.basicAuth.username,accessKey:c.basicAuth.access_key})});g.ok?l.log("info","BUNDLE_SYNC_OK","unit bundle pushed",{commit_id:u.commit_id,path:d.file,bytes:g.bytes}):l.log("warn","BUNDLE_SYNC_FAILED","unit bundle sync failed",{commit_id:u.commit_id,path:d.file,stage:g.stage,error:g.error}),t.onAgentEvent({type:"test_md_bundle_sync",status:g.ok?"ok":"failed",commit_id:u.commit_id,path:d.file,...g.ok?{bytes:g.bytes}:{stage:g.stage}})}catch(u){l.log("warn","BUNDLE_SYNC_FAILED","unit bundle sync threw",{path:d.file,error:u instanceof Error?u.message:String(u)})}let Rr=re(w),qe=oe.uploadResult?.testcaseId,Ge=qe&&oe.uploadResult?.shareId&&F?ot(Rr.testManagerUiUrl,F,qe,oe.uploadResult.shareId):void 0,Ss=a.unitFiles.filter(d=>d.file!==a.rootPath).map(d=>{let u=a.steps.filter(p=>p.owningFile===d.file),g=u.filter(p=>ce.has(p.flatIndex)).length,h=(d.kind==="test"?he(d.file):null)?.commit_id===l.sessionId;return{path:d.file,kind:d.kind,replayed:u.length-g,authored:g,committed:h,...h?{commit_id:l.sessionId}:{}}}),kr={overallStatus:z.overallStatus,durationS:ge,decisions:m.decisions,outcomes:z.outcomes,cancelled:J,retryTriggered:X,lockHeld:_,anyAuthorStepRan:D,isFirstRun:m.isFirstRun,wantsPush:o.push===!0,uploadResult:oe.uploadResult,shouldUploadArtifacts:ve,shouldReplaceLocalOutput:D&&!J,shouldCommit:(_||m.isFirstRun)&&!J&&z.overallStatus==="passed"&&!m.degradedReadonly,shareUrl:Ge,imports:Ss},{buildSummaryEvent:ws}=await import("./SummaryBox-ROV7TNK4.js");if(i?t.onAgentEvent(ws(kr)):await t.onSummary(kr),!i){let d=qe&&F?Ln(Rr.testManagerUiUrl,F,qe):void 0;await t.onLinks({recordedTestPath:n,outputDir:ne(n),shareableLink:Ge,testCaseLink:d,codeExportDir:oe.uploadResult?.codeExportDir})}if(ae.ownsLifecycle&&Z&&wr){let{offerEvidenceView:d}=await import("./evidence-UAFPTHQX.js");await d({packPath:Z.pack,env:w,isTTY:!i&&!J&&!!process.stdin.isTTY&&!!process.stderr.isTTY,log:u=>process.stderr.write(u+`
|
|
48
|
+
`)})}return t.onAgentEvent({type:"test_md_done",overall_status:z.overallStatus,duration_s:ge,session_id:l.sessionId,...Ge?{share_url:Ge}:{}}),{overallStatus:z.overallStatus,exitCode:z.overallStatus==="passed"?0:1,outputDir:ne(n),durationS:ge,uploadResult:oe.uploadResult,anyAuthorStepRan:D,resultCode:Ur(Ke),...St.length?{pendingInvestigations:St}:{}}}function Ao(e,t){let r={...e,...t},n=Object.keys(r).length>0?Se(r,""):{variables:{},objective:"",keyMap:{}};return{raw:r,auteur:n.variables,auteurObjective:"",secretEntries:Object.entries(r).filter(([,s])=>s.secret),nonSecretEntries:Object.entries(r).filter(([,s])=>!s.secret)}}function Ce(e,t,r){let n={...e,...t??{}};if(Object.keys(n).length===0)return{raw:n,variables:{},objective:r};let s=Se(n,r);return{raw:n,variables:qn(s.variables,s.objective),objective:s.objective}}function xo(e,t,r){let n=Ce(e,t,r).variables;return Object.keys(n).length>0?n:void 0}function ls(e,t){let r=new Set(dt),n={...e};for(let[s,o]of Object.entries(t))r.has(s)||s!=="variables"&&o!==void 0&&e[s]===void 0&&(n[s]=o);return n}function Po(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}async function To(e,t,r,n,s,o){let i=Zr(t);on(t,i);let f=_e(e),a=Ro(f)?JSON.parse(cs(f,"utf8")):null,c=a?.testcase_id,y=a?.test_id,w=a?.commit_id,A=r.push===!0,R=r.retry===!0||r.retryCount!==void 0,x=r.author===!0;A&&!c&&process.stderr.write(`[--push] no meta.json yet \u2014 flag is a no-op on first run
|
|
49
|
+
`),x&&(c=void 0,y=void 0,w=void 0);let k=n.resolvedAuth.basicAuth;if(!k){let N=await n.resolvedAuth.resolver.resolve(!0);N?.username&&N?.access_key&&(k={username:N.username,access_key:N.access_key},n.resolvedAuth.basicAuth=k)}let C=!!k,l=!r.local&&C&&y!=null&&w!=null&&c!=null,H=l&&(et(i)||A);if(A&&!l)return process.stderr.write(`error: --push requires authenticated credentials for the lock API. Run 'kane-cli login' (OAuth) or pass --username/--access-key inline.
|
|
50
|
+
`),{resolved:t,decisions:i,testId:y,testcaseId:c,fromCommitId:w,newCommitId:null,isFirstRun:!1,hasAuth:C,canLock:l,lockAcquired:!1,unitLocks:[],degradedReadonly:!1,abort:{exitCode:2}};if(R&&!l)return process.stderr.write(`error: --retry requires authenticated credentials for the lock API. Run 'kane-cli login' (OAuth) or pass --username/--access-key inline.
|
|
51
|
+
`),{resolved:t,decisions:i,testId:y,testcaseId:c,fromCommitId:w,newCommitId:null,isFirstRun:!1,hasAuth:C,canLock:l,lockAcquired:!1,unitLocks:[],degradedReadonly:!1,abort:{exitCode:2}};if(x&&!C)return process.stderr.write(`error: --author requires authenticated credentials for the TMS API. Run 'kane-cli login' (OAuth) or pass --username/--access-key inline.
|
|
52
|
+
`),{resolved:t,decisions:i,testId:y,testcaseId:c,fromCommitId:w,newCommitId:null,isFirstRun:!1,hasAuth:C,canLock:l,lockAcquired:!1,unitLocks:[],degradedReadonly:!1,abort:{exitCode:2}};let m=null,_=!1,D=!1;if(H){m=s;let X=r.onLockConflict??t.rootGlobal.on_lock_conflict??"readonly",N=await Xt({tmsBaseUrl:n.tmsBaseUrl,testId:y,fromCommitId:w,newCommitId:m,basicAuth:k,onLockConflict:X});if(N==="ok")_=!0,nt({baseUrl:Ee(n.tmsBaseUrl),testId:y,auth:Ae(k),lifecycle:o});else{if(N==="abort")return{resolved:t,decisions:i,testId:y,testcaseId:c,fromCommitId:w,newCommitId:null,isFirstRun:!1,hasAuth:C,canLock:l,lockAcquired:!1,unitLocks:[],degradedReadonly:!1,abort:{exitCode:2}};m=null,D=!0}}let ce=[],J=H&&!_;if(!r.local&&C&&!J){let X=r.onLockConflict??t.rootGlobal.on_lock_conflict??"readonly",N=await ds({resolved:t,decisions:i,tmsBaseUrl:n.tmsBaseUrl,newCommitId:m??s,basicAuth:k,mode:X,lifecycle:o});if(N.outcome==="ok")ce=N.locks;else{if(_&&y&&w&&m&&await Zt(n,y,w,m),be(),N.outcome==="abort")return{resolved:t,decisions:i,testId:y,testcaseId:c,fromCommitId:w,newCommitId:null,isFirstRun:c==null,hasAuth:C,canLock:l,lockAcquired:!1,unitLocks:[],degradedReadonly:!1,abort:{exitCode:2}};process.stderr.write(`[lock] imported-unit conflict \u2014 whole run degrades to readonly (no commits, no uploads)
|
|
53
|
+
`),m=null,_=!1,D=!0}}return{resolved:t,decisions:i,testId:y,testcaseId:c,fromCommitId:w,newCommitId:m,isFirstRun:c==null,hasAuth:C,canLock:l,lockAcquired:_,unitLocks:ce,degradedReadonly:D}}async function ds(e){let t=new Set(e.resolved.steps.filter((n,s)=>e.decisions[s]?.kind==="author").map(n=>n.owningFile)),r=[];for(let n of e.resolved.unitFiles){if(n.kind!=="test"||n.file===e.resolved.rootPath||!e.allUnits&&!t.has(n.file)||e.alreadyLocked?.some(i=>i.file===n.file))continue;let s=he(n.file);if(!s?.test_id||!s?.commit_id)continue;let o=await Xt({tmsBaseUrl:e.tmsBaseUrl,testId:String(s.test_id),fromCommitId:String(s.commit_id),newCommitId:e.newCommitId,basicAuth:e.basicAuth,onLockConflict:e.mode});if(o==="ok"){r.push({file:n.file,testId:String(s.test_id),fromCommitId:String(s.commit_id)}),nt({baseUrl:Ee(e.tmsBaseUrl),testId:String(s.test_id),auth:Ae(e.basicAuth),lifecycle:e.lifecycle});continue}for(let i of r)await De({baseUrl:Ee(e.tmsBaseUrl),testId:i.testId,body:{commitId:e.newCommitId,fromCommitId:i.fromCommitId},auth:Ae(e.basicAuth)}),be(i.testId);return{outcome:o,locks:[]}}return{outcome:"ok",locks:r}}function Ee(e){return`${e}/kane-cli/v1`}function Ae(e){return{username:e.username,accessKey:e.access_key}}async function Xt(e){let t=Ee(e.tmsBaseUrl),r=Ae(e.basicAuth),n={baseUrl:t,testId:e.testId,fromCommitId:e.fromCommitId,newCommitId:e.newCommitId,auth:r},s=await Ft(n);if(s.ok)return"ok";if(!(s.reason==="concurrent"||s.reason==="base_mismatch"))return process.stderr.write(`[lock] acquire failed: ${s.reason} (HTTP ${s.httpStatus}): ${s.message}
|
|
54
|
+
`),"abort";let i=s.reason==="concurrent"?"concurrent session":"base commit mismatch (pull latest)";if(e.onLockConflict==="fail")return process.stderr.write(`[lock] ${i}; aborting (--on-lock-conflict fail)
|
|
55
|
+
`),"abort";if(e.onLockConflict==="wait"){if(s.reason==="base_mismatch")return process.stderr.write(`[lock] base commit mismatch \u2014 pull latest; aborting
|
|
56
|
+
`),"abort";for(;;){process.stderr.write(`[lock] waiting (concurrent session)...
|
|
57
|
+
`),await new Promise(a=>setTimeout(a,3e4));let f=await Ft(n);if(f.ok)return"ok";if(f.reason!=="concurrent")return process.stderr.write(`[lock] wait drifted to ${f.reason} (HTTP ${f.httpStatus}): ${f.message}; aborting
|
|
58
|
+
`),"abort"}}return process.stderr.write(`[lock] ${i} \u2014 running in readonly mode (no commit)
|
|
59
|
+
`),"readonly"}async function Lo(e,t,r,n,s,o,i,f,a,c,y,w,A){let{decisions:R,testId:x,testcaseId:k,fromCommitId:C,newCommitId:l}=t;if(!(s==="passed")||A){let m=A?"cancelled":s;w&&x&&C&&l&&(process.stderr.write(`[lock] run not committed (${m}); discarding playground lock
|
|
60
|
+
`),await Zt(y,x,C,l));for(let _ of t.unitLocks)await Zt(y,_.testId,_.fromCommitId,l??r.sessionId);be();return}be()}async function Zt(e,t,r,n){let s=e.resolvedAuth.basicAuth;if(!s){let i=await e.resolvedAuth.resolver.resolve(!0);i?.username&&i?.access_key&&(s={username:i.username,access_key:i.access_key},e.resolvedAuth.basicAuth=s)}if(!s)return;let o=await De({baseUrl:Ee(e.tmsBaseUrl),testId:t,body:{commitId:n,fromCommitId:r},auth:Ae(s)});o.ok||process.stderr.write(`warn: discardLock failed: ${o.reason} (HTTP ${o.httpStatus}): ${o.message}
|
|
61
|
+
`)}async function Do(e){let t=null,r=!1,n=0,s=-1,o=-1,i=0,f=async a=>{if(a&&a.status==="failed")return n>0&&e.decisions[n-1].kind==="replay"&&(t=n-1),null;for(;n<e.decisions.length&&!e.accumulator.shouldRunFlatStep(e.resolved.steps[n]);)n++;if(n>=e.decisions.length)return null;let c=e.decisions[n],y=e.resolved.steps[n],w=n;n++;let A=e.session.nextRunIndex();s=w,o=A,i=Date.now(),e.onSpawnStart?.(A),c.kind==="author"&&e.onAnyAuthorStep(w),await e.pushStepLevelDelta(y.config.variables,y.objective);let R=c.kind==="replay"?e.buildReplayConfig(w):e.buildStepConfigAt(w,A),x=c.kind==="replay"?"md5-match":c.reason,k=y.config??{},C={};for(let[l,H]of Object.entries(k))H!=null&&l!=="variables"&&l!=="assurance"&&(C[l]=H);return{config:R,banner:{stepLabel:`Step ${w+1}/${e.decisions.length}`,objective:Po(y.objective,100)},mode:c.kind,modeReason:x,perStepOverrides:Object.keys(C).length>0?C:void 0}};return await e.host.runSteps({topBanner:{model:e.topBannerModel,auth:e.topBannerAuth},globalConfig:e.globalConfig,getNextStep:f,onStepEnd:a=>(a.status==="failed"&&s>=0&&e.decisions[s]?.kind==="replay"&&(t=s),e.onSequencerStepEnd(a,s,o,i)),onAllComplete:()=>{},onCancel:()=>{r=!0,e.onCancel()},spawnOpts:e.spawnOpts,priorAttemptRollup:e.priorAttemptRollup,screenshotDispatcher:e.screenshotDispatcher,onReasoning:e.onReasoning,onStepComplete:e.onStepComplete}),{failedAt:t,cancelled:r}}export{Rn as a,kn as b,it as c,wi as d,jn as e,xn as f,Zo as g,_n as h,In as i,$t as j,Cn as k,En as l,ot as m,Tn as n,Ln as o,Fn as p,Nn as q,qn as r,Gn as s,zn as t,Bt as u,Qn as v,Xn as w,es as x,ts as y,rs as z,Yt as A,Ua as B,ss as C,Jt as D,$l as E,Ao as F,Ce as G,xo as H,ls as I};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
function l(e,n){let r=/^L(\d+)-L(\d+)$/.exec(n);if(!r)return null;let t=parseInt(r[1],10),o=parseInt(r[2],10),i=e.split(`
|
|
3
|
+
`);return t<1||o<t||o>i.length?null:i.slice(t-1,o).map(a=>a.replace(/^\d+\| /,"")).join(`
|
|
4
|
+
`)}function s(e,n,r){if(e.format==="image")return n.anchor==="img#whole"?[]:[{code:"CITE_ANCHOR_INVALID",detail:`image cites are anchor-only (img#whole), got ${n.anchor}`}];if(!n.anchor||n.quote===void 0||n.quote==="")return[{code:"MISSING_CITE",detail:"text-kind cites need anchor+quote"}];let t=r!==null?l(r,n.anchor):null;return t===null?[{code:"BAD_ANCHOR",detail:`anchor ${n.anchor} does not resolve in the source`}]:t.includes(n.quote)?[]:[{code:"QUOTE_MISMATCH",detail:`quote is not verbatim within ${n.anchor}`}]}export{l as a,s as b};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as ve}from"./chunk-CB3TEWZJ.js";import{c as we,x as d}from"./chunk-HMGNPFXP.js";import{a as V}from"./chunk-HCBYKLMW.js";import{a as v,b as u,h as Te,i as de,k as Ae}from"./chunk-C44QQJR4.js";import{a as ue}from"./chunk-6YGTRKDT.js";import{e as B}from"./chunk-UR6MHSHU.js";var Be=B(ue(),1);import{readFileSync as Ye,writeFileSync as Ve,mkdirSync as Xe}from"fs";import{dirname as Ge,join as Pe}from"path";var Je=Pe(we,"command-history.json"),gt=Pe(we,"generate-history.json"),ze=200,Ee=class{entries;filePath;max;constructor(o=Je,n=ze){this.filePath=o,this.max=n,this.entries=this._load()}push(o){this.entries.length>0&&this.entries[this.entries.length-1]===o||(this.entries.push(o),this.entries.length>this.max&&(this.entries=this.entries.slice(this.entries.length-this.max)),this._save())}getAll(){return[...this.entries]}search(o){let n=o.toLowerCase(),l=[];for(let s=this.entries.length-1;s>=0;s--)this.entries[s].toLowerCase().includes(n)&&l.push(this.entries[s]);return l}_load(){if(this.filePath===null)return[];try{let o=Ye(this.filePath,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?n:[]}catch{return[]}}_save(){if(this.filePath!==null)try{Xe(Ge(this.filePath),{recursive:!0}),Ve(this.filePath,JSON.stringify(this.entries)+`
|
|
3
|
+
`)}catch{}}};function pt(r){let o=(0,Be.useRef)(null);return o.current||(o.current=new Ee(r)),o.current}var C=B(ue(),1);var Se=B(ue(),1);var $=B(V(),1);function Le({history:r,onSelect:o,onClose:n}){let[l,s]=(0,Se.useState)(""),[c,m]=(0,Se.useState)(0),S=l?r.search(l).slice(0,8):[];return de((y,g)=>{if(g.escape){n();return}if(g.return){S.length>0&&S[c]?o(S[c]):n();return}if(g.upArrow){m(M=>Math.max(0,M-1));return}if(g.downArrow){m(M=>Math.min(S.length-1,M+1));return}if(g.backspace||g.delete){s(M=>M.slice(0,-1)),m(0);return}y&&!g.ctrl&&!g.meta&&(s(M=>M+y),m(0))}),(0,$.jsxs)(v,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,$.jsx)(u,{color:d.muted,bold:!0,children:"reverse search"}),(0,$.jsxs)(v,{gap:1,children:[(0,$.jsx)(u,{color:d.dim,children:"search:"}),(0,$.jsx)(u,{children:l}),(0,$.jsx)(u,{color:d.orange,children:"\u2588"})]}),S.length>0&&(0,$.jsx)(u,{children:" "}),S.map((y,g)=>(0,$.jsx)(v,{marginLeft:2,children:(0,$.jsxs)(u,{color:g===c?d.orange:d.dim,bold:g===c,children:[g===c?"\u25B8 ":" ",y]})},`${g}-${y}`))]})}var X=B(V(),1);function De({commands:r,selectedIndex:o}){return r.length===0?null:(0,X.jsx)(v,{flexDirection:"column",marginBottom:0,children:r.map((n,l)=>{let s=l===o;return(0,X.jsxs)(v,{children:[(0,X.jsx)(u,{color:s?d.orange:d.dim,children:s?"\u276F ":" "}),(0,X.jsxs)(u,{color:s?d.orange:void 0,bold:s,children:["/",n.name]}),n.args&&(0,X.jsxs)(u,{color:d.dim,children:[" ",n.args]}),(0,X.jsxs)(u,{color:d.dim,children:[" ",n.description]})]},n.name)})})}var _e=B(ue(),1);var P=B(V(),1),$e={scenario:"Scenarios",case:"Test Cases",file:"Files"};function Oe(r){let o={scenario:0,case:0,file:0};for(let n of r)o[n.kind]++;return["scenario","case","file"].filter(n=>o[n]>0).map(n=>`${o[n]} ${$e[n]}`).join(" \xB7 ")}var ge=7;function Ke({items:r,selectedIndex:o,accent:n=d.orange}){let l=r.length;if(l===0)return null;let s=Math.floor(ge/2),c=l<=ge?0:Math.max(0,Math.min(o-s,l-ge)),m=Math.min(l,c+ge),S=c,y=l-m;return(0,P.jsxs)(v,{flexDirection:"column",marginBottom:0,children:[S>0&&(0,P.jsx)(v,{children:(0,P.jsx)(u,{color:d.dim,children:` \u22EF ${S} above \u2014 ${Oe(r.slice(0,c))}`})}),r.slice(c,m).map((g,M)=>{let W=c+M,H=W===o,Q=M===0||r[W-1].kind!==g.kind;return(0,P.jsxs)(_e.default.Fragment,{children:[Q&&(0,P.jsx)(v,{children:(0,P.jsx)(u,{color:d.dim,children:$e[g.kind]})}),(0,P.jsxs)(v,{children:[(0,P.jsx)(u,{color:H?n:d.dim,children:H?"\u276F ":" "}),(0,P.jsx)(u,{color:H?n:void 0,bold:H,children:g.label})]})]},`${g.kind}:${g.value}:${W}`)}),y>0&&(0,P.jsx)(v,{children:(0,P.jsx)(u,{color:d.dim,children:` \u22EF ${y} more \u2014 ${Oe(r.slice(m))}`})})]})}var pe=B(ue(),1);var Qe=27,Ze=127,et=11;function tt(r){return r>=64&&r<=126}function nt(r,o){r===et&&o({killToEnd:!0,ctrl:!0,raw:String.fromCharCode(r)})}function rt(r,o){r===Ze&&o({backspace:!0,meta:!0,raw:"\x1B\x7F"})}function ot(r,o){let n=r.map(s=>String.fromCharCode(s)).join(""),l=/^\[1;([0-9]+)([A-D])$/.exec(n);if(l){let s=parseInt(l[1],10),c=l[2],m={raw:"\x1B"+n};if(s===2)m.shift=!0;else if(s===3)m.meta=!0;else if(s===5)m.ctrl=!0;else return;c==="A"?m.arrowUp=!0:c==="B"?m.arrowDown=!0:c==="C"?m.arrowRight=!0:c==="D"&&(m.arrowLeft=!0),o(m);return}if(n==="[H"||n==="[1~"||n==="[7~"){o({home:!0,raw:"\x1B"+n});return}if(n==="[F"||n==="[4~"||n==="[8~"){o({end:!0,raw:"\x1B"+n});return}if(n==="[3;5~"){o({delete:!0,ctrl:!0,raw:"\x1B"+n});return}if(n==="[3;3~"){o({delete:!0,meta:!0,raw:"\x1B"+n});return}}function it(r,o){r===72?o({home:!0,raw:"\x1BO"+String.fromCharCode(r)}):r===70&&o({end:!0,raw:"\x1BO"+String.fromCharCode(r)})}function st(){let r="IDLE",o=[];function n(){r="IDLE",o=[]}return{feed(l,s){for(let c of l)r==="IDLE"?c===Qe?(r="ESC",o=[]):nt(c,s):r==="ESC"?c===91?(r="CSI",o=[]):c===79?(r="SS3",o=[]):(rt(c,s),n()):r==="CSI"?(o.push(c),tt(c)&&(ot([91,...o],s),n())):r==="SS3"&&(it(c,s),n())},flushIdle(l){r==="ESC"&&o.length===0&&l({raw:"\x1B"}),n()}}}function He(r,o={}){let n=(0,pe.useRef)(r);n.current=r;let{stdin:l}=Te();(0,pe.useEffect)(()=>{if(o.isActive===!1||!l)return;let s=st(),c=null,m=S=>{c&&(clearTimeout(c),c=null);let y=Buffer.isBuffer(S)?S:Buffer.from(S,"binary");s.feed(y,g=>n.current(g)),c=setTimeout(()=>{s.flushIdle(g=>n.current(g)),c=null},50)};return l.on("data",m),()=>{l.removeListener("data",m),c&&clearTimeout(c)}},[o.isActive,l])}var x=B(V(),1);function lt(r,o){let n=o-1;for(;n>=0&&r[n]!=="@"&&r[n]!==" "&&r[n]!==`
|
|
4
|
+
`;)n--;return n<0||r[n]!=="@"||n>0&&r[n-1]!==" "&&r[n-1]!==`
|
|
5
|
+
`?null:{at:n,query:r.slice(n+1,o).join("")}}var ye=10;function at(r){return r.replace(/\x1b?\[200~/g,"").replace(/\x1b?\[201~/g,"").replace(/\r\n/g,`
|
|
6
|
+
`).replace(/\r/g,`
|
|
7
|
+
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,"")}function ct(r,o){let n=[],l=0;for(;l<=r.length;){let s=l;for(;s<r.length&&r[s]!==`
|
|
8
|
+
`;)s++;if(l===s)n.push({start:l,end:l});else{let c=l;for(;c<s;){let m=Math.min(c+o,s);n.push({start:c,end:m}),c=m}}if(s>=r.length)break;l=s+1}return n}function ut(r,o,n){if(r.length===0)return 0;if(o>=n.length)return r.length-1;if(n[o]===`
|
|
9
|
+
`){for(let l=r.length-1;l>=0;l--)if(r[l].end===o)return l;return r.length-1}for(let l=0;l<r.length;l++){let s=r[l];if(s.start<=o&&o<s.end)return l}return r.length-1}function Fe(r,o,n,l){let s=ct(r,n);if(s.length===0)return null;let c=ut(s,o,r),m=c+l;if(m<0||m>=s.length)return null;let S=o-s[c].start,y=s[m],g=y.end-y.start;return y.start+Math.min(S,g)}function Ht({onSubmit:r,onEscape:o,history:n,placeholder:l="Type an objective or /command...",commands:s,clearSeq:c,submitVerb:m,footerBindings:S,inert:y=!1,clearOnSubmit:g=!0,noHistory:M=!1,accent:W=d.orange,scenarios:H,mentionFiles:Q,submitEmpty:ke=!1}){let[a,E]=(0,C.useState)([]),[f,h]=(0,C.useState)(0),[N,U]=(0,C.useState)("none"),[Z,L]=(0,C.useState)(-1),ee=(0,C.useRef)(""),[Ie,se]=(0,C.useState)(!0),{stdout:We}=Ae(),le=We?.columns??80,[ae,j]=(0,C.useState)(0),[te,ne]=(0,C.useState)(0),[Ne,xe]=(0,C.useState)([]),[Ue,fe]=(0,C.useState)(null),Me=(0,C.useRef)(!1);(0,C.useEffect)(()=>{if(c!==void 0){if(!Me.current){Me.current=!0;return}E([]),h(0),L(-1),ee.current="",se(!0),U("none"),j(0)}},[c]);let I=a.join(""),ce=(()=>{if(N!=="none"||a.length===0)return"";if(I.startsWith("/")&&s&&I.length>=2){let e=I.slice(1).toLowerCase(),t=s.find(p=>p.name.startsWith(e)&&p.name!==e);return t?`/${t.name}`.slice(I.length):""}if(I.startsWith("/")||M)return"";let i=n.getAll();for(let e=i.length-1;e>=0;e--)if(i[e].startsWith(I)&&i[e]!==I)return i[e].slice(I.length);return""})(),G=(()=>{if(!s||!I.startsWith("/"))return[];let i=I.length>=2?I.slice(1).toLowerCase():"";return i&&s.some(e=>e.name===i)?[]:s.filter(e=>!i||e.name.startsWith(i))})(),re=G.length>0&&I.startsWith("/"),D=!!Q||!!(H&&H.length)?lt(a,f):null,be=D?D.query:null,F=(()=>{if(!D)return[];let i=D.query.toLowerCase(),e=[];(H??[]).forEach((t,p)=>{let b=`s${p+1}`;(!i||b.includes(i)||(t.title??"").toLowerCase().includes(i))&&e.push({kind:"scenario",value:b,label:`@${b} ${t.title??t.sid??""}`.trim()})}),(H??[]).forEach((t,p)=>{let w=p+1;(t.test_cases??[]).forEach((b,T)=>{let O=`s${w}.c${T+1}`;(!i||O.includes(i)||(b.title??"").toLowerCase().includes(i))&&e.push({kind:"case",value:O,label:`@${O} ${b.title??""}`.trim()})})});for(let t of Ne)e.push({kind:"file",value:t,label:t});return e})(),oe=D!==null&&D.at!==Ue&&!re&&N==="none"&&F.length>0;(0,C.useEffect)(()=>{if(!Q||be===null){xe([]);return}let i=!1;return Q(be).then(e=>{i||xe(e)}).catch(()=>{i||xe([])}),()=>{i=!0}},[be,Q]),(0,C.useEffect)(()=>{te>=F.length&&ne(0)},[F.length]);let Re=i=>{if(!D)return;let e=i.kind==="file"&&/\s/.test(i.value)?`@"${i.value}"`:`@${i.value}`,t=[...a.slice(0,D.at),...e,...a.slice(f)];E(t),h(D.at+e.length),ne(0),fe(D.at),se(!1)};if(de((i,e)=>{if(Ie&&i&&se(!1),e.return){if(oe&&F[te]){Re(F[te]);return}if(re&&G[ae]){let t=`/${G[ae].name}`;M||n.push(t),r(t),E([]),h(0),U("none"),L(-1),ee.current="",se(!0),j(0);return}I.trim()?(M||n.push(I.trim()),r(I.trim()),g&&(E([]),h(0),U("none"),L(-1),ee.current="",se(!0),j(0))):ke&&r("");return}if(e.escape){if(oe){fe(D.at);return}N!=="none"?U("none"):a.length>0?(E([]),h(0),L(-1),ee.current=""):o?.();return}if(e.tab&&!e.shift){if(oe&&F[te]){Re(F[te]);return}if(re&&G[ae]){let t=`/${G[ae].name}`;E([...t]),h(t.length),j(0);return}if(ce){let t=I+ce;E([...t]),h(t.length);return}return}if(e.ctrl&&i==="r"){if(M)return;U("search");return}if(e.ctrl&&i==="a"){h(0);return}if(e.ctrl&&i==="e"){h(a.length);return}if(e.ctrl&&i==="w"){if(f===0)return;let t=f-1;for(;t>0&&a[t]===" ";)t--;for(;t>0&&a[t-1]!==" ";)t--;let p=[...a.slice(0,t),...a.slice(f)];E(p),h(t);return}if(e.ctrl&&i==="u"){E([]),h(0),L(-1),U("none");return}if(e.meta&&i==="b"){let t=f-1;for(;t>0&&a[t]===" ";)t--;for(;t>0&&a[t-1]!==" ";)t--;h(Math.max(0,t));return}if(e.meta&&i==="f"){let t=f;for(;t<a.length&&a[t]!==" ";)t++;for(;t<a.length&&a[t]===" ";)t++;h(t);return}if(e.leftArrow){if(e.ctrl||e.shift)return;h(t=>Math.max(0,t-1));return}if(e.rightArrow){if(e.ctrl||e.shift)return;if(f>=a.length&&ce){let t=I+ce;E([...t]),h(t.length)}else h(t=>Math.min(a.length,t+1));return}if(e.upArrow){if(e.shift)return;if(oe){ne(t=>Math.max(0,t-1));return}if(re){j(t=>Math.max(0,t-1));return}if(N==="none"){let t=Math.max(1,le-2),p=Fe(a,f,t,-1);if(p!==null){h(p);return}if(M)return;let w=n.getAll();if(w.length===0)return;if(Z===-1){ee.current=I,L(w.length-1);let b=w[w.length-1];E([...b]),h(b.length)}else if(Z>0){let b=Z-1;L(b);let T=w[b];E([...T]),h(T.length)}}return}if(e.downArrow){if(e.shift)return;if(oe){ne(t=>Math.min(F.length-1,t+1));return}if(re){j(t=>Math.min(G.length-1,t+1));return}if(N==="none"){let t=Math.max(1,le-2),p=Fe(a,f,t,1);if(p!==null){h(p);return}if(M)return;let w=n.getAll();if(Z===-1)return;if(Z<w.length-1){let b=Z+1;L(b);let T=w[b];E([...T]),h(T.length)}else{L(-1);let b=ee.current;E([...b]),h(b.length)}}return}if(e.backspace||e.delete){if(e.meta||e.ctrl)return;if(f>0){let t=[...a.slice(0,f-1),...a.slice(f)];E(t),h(f-1),L(-1),j(0),fe(null),ne(0)}return}if(i&&!e.ctrl&&!e.meta){let t=at(i);if(!t)return;let p=[...a.slice(0,f),...t,...a.slice(f)];E(p),h(f+t.length),L(-1),j(0),fe(null),ne(0)}},{isActive:!y&&N!=="search"}),He(i=>{if(i.home){h(0);return}if(i.end){h(a.length);return}if(i.killToEnd){E(a.slice(0,f));return}if(i.arrowLeft&&(i.ctrl||i.meta)){let e=f-1;for(;e>0&&a[e]===" ";)e--;for(;e>0&&a[e-1]!==" ";)e--;h(Math.max(0,e));return}if(i.arrowRight&&(i.ctrl||i.meta)){let e=f;for(;e<a.length&&a[e]!==" ";)e++;for(;e<a.length&&a[e]===" ";)e++;h(e);return}if(i.backspace&&i.meta){if(f===0)return;let e=f-1;for(;e>0&&a[e]===" ";)e--;for(;e>0&&a[e-1]!==" ";)e--;let t=[...a.slice(0,e),...a.slice(f)];E(t),h(e);return}if(i.delete&&(i.ctrl||i.meta)){let e=f;for(;e<a.length&&a[e]===" ";)e++;for(;e<a.length&&a[e]!==" ";)e++;E([...a.slice(0,f),...a.slice(e)]);return}},{isActive:!y&&N!=="search"}),y)return(0,x.jsxs)(v,{flexDirection:"column",children:[(0,x.jsx)(u,{color:d.muted,children:"\u2500".repeat(le)}),(0,x.jsxs)(v,{children:[(0,x.jsx)(u,{color:d.muted,children:"\u276F "}),(0,x.jsx)(u,{color:d.dim,children:l})]}),(0,x.jsx)(ve,{bindings:S??[{keys:"ctrl+c",label:"cancel"},{keys:"/cancel",label:"stop turn"},{keys:"ctrl+t",label:"thinking"}],suppressEscBack:!0})]});let je=i=>{E([...i]),h(i.length),U("none")},qe=()=>{U("none")},he=(()=>{if(Ie&&a.length===0)return null;let i=f>=a.length,e=a.slice(0,f).join(""),t,p;i?(t=" ",p=""):a[f]===`
|
|
10
|
+
`?(t=" ",p=a.slice(f).join("")):(t=a[f],p=a.slice(f+1).join(""));let w=e+t+p+ce,b=e.length,T=b+1,O=T+p.length,me=Math.max(1,le-2),R=[],k=0;for(;k<=w.length;){let A=w.indexOf(`
|
|
11
|
+
`,k);if(A===-1&&(A=w.length),k===A)R.push({type:"content",start:k,end:k});else{let _=k;for(;_<A;){let q=Math.min(_+me,A);R.push({type:"content",start:_,end:q}),_=q}}if(A>=w.length)break;k=A+1}let K=Math.max(0,R.findIndex(A=>A.start<=b&&b<=A.end)),z;if(R.length<=ye)z=R;else{let _=ye-1-4;if(K<4||K>=R.length-_)z=[...R.slice(0,4),{type:"ellipsis",hidden:R.length-4-_},...R.slice(R.length-_)];else{let q=ye-2,Ce=Math.floor(q/2),Y=K-Ce,ie=K+(q-Ce)-1;Y<1&&(ie+=1-Y,Y=1),ie>R.length-2&&(Y-=ie-(R.length-2),ie=R.length-2),Y=Math.max(1,Y),z=[{type:"ellipsis",hidden:Y},...R.slice(Y,ie+1),{type:"ellipsis",hidden:R.length-ie-1}]}}return{full:w,b,c:T,a:O,rows:z}})();return(0,x.jsxs)(v,{flexDirection:"column",children:[N==="search"&&(0,x.jsx)(Le,{history:n,onSelect:je,onClose:qe}),re&&(0,x.jsx)(De,{commands:G,selectedIndex:ae}),oe&&(0,x.jsx)(Ke,{items:F,selectedIndex:te,accent:W}),(0,x.jsx)(u,{color:d.muted,children:"\u2500".repeat(le)}),he===null?(0,x.jsxs)(v,{children:[(0,x.jsx)(u,{color:W,children:"\u276F "}),(0,x.jsx)(u,{inverse:!0,children:" "}),(0,x.jsx)(u,{color:d.dim,children:l})]}):(()=>{let i=he.rows.findIndex(e=>e.type==="content");return(0,x.jsx)(v,{flexDirection:"column",children:he.rows.map((e,t)=>{if(e.type==="ellipsis")return(0,x.jsx)(v,{children:(0,x.jsxs)(u,{color:d.dim,children:[" \u22EF ","(",e.hidden," more line",e.hidden===1?"":"s",")"]})},t);let{full:p,b:w,c:b,a:T}=he,O=e.start,J=e.end,me=t===i,R=me?"\u276F ":" ",k=me?W:d.muted,K=[(0,x.jsx)(u,{color:k,children:R},"p")];O<Math.min(w,J)&&K.push((0,x.jsx)(u,{children:p.slice(O,Math.min(w,J))},"b"));let z=Math.max(w,O),A=Math.min(b,J);z<A&&K.push((0,x.jsx)(u,{color:W,inverse:!0,children:p.slice(z,A)},"c"));let _=Math.max(b,O),q=Math.min(T,J);return _<q&&K.push((0,x.jsx)(u,{children:p.slice(_,q)},"a")),J>T&&K.push((0,x.jsx)(u,{color:d.dim,children:p.slice(Math.max(T,O),J)},"g")),(0,x.jsx)(v,{children:K},t)})})})(),(0,x.jsx)(ve,{bindings:S??[{keys:"\u2191\u2193",label:"history"},{keys:"\u21B5",label:m??"submit"},{keys:"tab",label:"complete"},{keys:"ctrl+r",label:"search"}],escBackLabel:"clear"})]})}export{gt as a,Ee as b,pt as c,Ht as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{a as $}from"./chunk-
|
|
2
|
+
import{a as $}from"./chunk-2PDWMY2B.js";import{b as D}from"./chunk-XDW2RGIL.js";import{a as E}from"./chunk-NLCCBXXV.js";function U(e){return["completed","failed","ended","stopped"].includes(e.trim().toLowerCase())}function je(e){return["ended","stopped"].includes(e.trim().toLowerCase())}function q(e){return{requestId:e.requestId,objective:e.objective,status:"",turnActive:!1,scenarios:[],thinking:"",thinkingLog:[],chatLog:[],progress:0}}function Re(e){return e.pendingClarification===void 0?e:{...e,pendingClarification:void 0}}function Ce(e){return{...e,turnActive:!0,error:void 0,thinking:"",thinkingLog:[]}}function P(e,t){switch(t.type){case"thinking":return{...e,status:"thinking",thinking:e.thinking+t.delta};case"thinking_done":return{...e,thinkingLog:[...e.thinkingLog,{text:e.thinking,tookMs:t.tookMs}],thinking:""};case"progress":return{...e,progress:t.pct};case"snapshot":return{...e,scenarios:t.data.scenarios,status:t.data.status,headline:t.data.headline??e.headline};case"chat":return{...e,turnActive:!1,chatLog:[...e.chatLog,{role:"model",text:t.text}]};case"clarification":return{...e,turnActive:!1,chatLog:[...e.chatLog,{role:"model",text:t.text}],pendingClarification:t.text};case"limit":return{...e,limits:{scenarioLimit:t.scenarioLimit,perScenarioLimit:t.perScenarioLimit}};case"error":return{...e,error:t.message};case"done":return{...e,status:t.status,turnActive:!1,error:t.status==="failed"&&!e.error?"generation failed":e.error}}}function H(e,t){let n=[],i=e.type??"",l=e.status??"";if(i==="ping")return n;switch(i){case"thinking_token":typeof e.data=="string"&&n.push({type:"thinking",delta:e.data});break;case"thinking_stopped":{let r=e.data??{},o=se(r.time_taken);n.push({type:"thinking_done",text:typeof e.data=="string"?e.data:r.message??"",tookMs:o});break}case"progress":{let r=e.data??{};typeof r.progress=="number"&&n.push({type:"progress",pct:r.progress});break}case"clarification":{let r=e.data??{};typeof r.message=="string"&&n.push({type:"clarification",text:r.message});break}case"chatting_stopped":{let r=e.data??{};typeof r.message=="string"&&r.message.length>0&&n.push({type:"chat",text:r.message});break}case"limit_update":{let r=e.data??{},o=r.test_cases_limit??e.test_cases_limit,p=r.per_scenario_test_cases_limit??e.per_scenario_test_cases_limit;n.push({type:"limit",scenarioLimit:o,perScenarioLimit:p});break}case"error":{let r=typeof e.data=="string"?e.data:e.data?.message??"generation error";n.push({type:"error",message:r});break}case"request_cancelled":return n.push({type:"done",status:"stopped"}),n;case"session_ended":return n.push({type:"done",status:"ended"}),n;default:break}if(Array.isArray(e.scenarios)&&n.push({type:"snapshot",data:{requestId:t,status:l,headline:e.headline,scenarios:e.scenarios}}),l&&U(l)){let r=l.trim().toLowerCase();n.push({type:"done",status:r})}return n}function se(e){if(!e)return;let t=/^([\d.]+)(ms|s)?$/.exec(e.trim());if(!t)return;let n=Number(t[1]);if(Number.isFinite(n))return t[2]==="ms"?Math.round(n):Math.round(n*1e3)}var v=class extends Error{constructor(t){super(t),this.name="AuthError"}},M=class extends Error{constructor(t){super(t),this.name="ForbiddenError"}},I=class extends Error{constructor(t){super(t),this.name="InsufficientCreditsError"}},k=class extends Error{constructor(n,i){super(n);this.cause=i;this.name="TransportError"}};function x(e,t){let n=t?.message??t?.error??`HTTP ${e}`;return e===401?new v(n):e===403?t?.key==="insufficient_credits"?new I(n):new M(n):new k(n)}async function*J(e){let t=e.fetchImpl??fetch,n=e.maxRetries??5,i=e.maxBackoffMs??3e4,l=e.connectTimeoutMs??1e4,r=0,o=!1;for(;;){if(e.signal.aborted)return;let p=new AbortController,a=()=>p.abort();e.signal.addEventListener("abort",a,{once:!0});let c=setTimeout(()=>p.abort(),l),h;try{h=await t(e.url,{method:"GET",headers:{Authorization:await e.authHeader(),Accept:"text/event-stream"},signal:p.signal})}catch(w){if(clearTimeout(c),e.signal.removeEventListener("abort",a),e.signal.aborted)return;if(++r>n)throw new k("SSE connect failed",w);await O(F(r,i));continue}if(clearTimeout(c),!h.ok){e.signal.removeEventListener("abort",a);let w=await oe(h);if(h.status===401&&o){if(++r>n)throw x(401,w);await O(F(r,i));continue}throw x(h.status,w)}if(!h.body)throw e.signal.removeEventListener("abort",a),new k("SSE response had no body");o=!0,r=0;let g=h.body.getReader(),m=new TextDecoder("utf-8"),b="";try{for(;;){if(e.signal.aborted){await g.cancel().catch(()=>{});return}let{done:w,value:s}=await g.read();if(w)break;b+=m.decode(s,{stream:!0});let f;for(;(f=b.indexOf(`
|
|
3
3
|
|
|
4
4
|
`))>=0;){let u=b.slice(0,f);b=b.slice(f+2);let d=ie(u);d&&(yield d)}}}catch(w){if(e.signal.aborted)return;if(++r>n)throw new k("SSE stream dropped",w);await O(F(r,i));continue}finally{e.signal.removeEventListener("abort",a)}return}}function ie(e){let t="message",n="";for(let i of e.split(`
|
|
5
5
|
`))i.startsWith("event:")?t=i.slice(6).trim():i.startsWith("data:")&&(n+=i.slice(5).trim());if(t!=="message"||!n)return null;try{let i=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(i)}catch{return null}}function F(e,t){return Math.min(t,1e3*2**(e-1))}function O(e){return new Promise(t=>setTimeout(t,e))}async function oe(e){try{return await e.clone().json()}catch{return}}function W(e,t){t?.length&&(e.append("files",t.map(n=>n.fileKey).join(",")),e.append("gemini_metadata",JSON.stringify(t.map(n=>({fileData:{fileUri:n.geminiUri,mimeType:n.mimeType}})))))}function Ue(e,t={}){let n=t.fetchImpl??fetch,i=new Map,l=!0;async function r(){let s=await e.authResolver.resolve();if(!s)throw new v("unauthorized; run `kane-cli login`");return E(s.username,s.access_key)}function o(s){return`${e.baseUrl}${s}`}async function p(s){if(!s.ok){let f;try{f=await s.clone().json()}catch{f=void 0}throw x(s.status,f)}return s.json()}function a(s){let f=s?.data??s;return{request_id:f.request_id??f.id,status:f.status??""}}function c(s,f,u,d){let y=q({requestId:s,objective:f});d&&(y=P(y,{type:"snapshot",data:d}),d.status==="cleaned_up"&&(y={...y,error:"session was reaped (cleaned_up) \u2014 continuing will destructively regenerate"}));let S=new AbortController;u&&(u.aborted?S.abort():u.addEventListener("abort",()=>S.abort(),{once:!0})),i.set(s,S);let A={requestId:s,state:y,events:void 0};return A.events=(async function*(){try{let C=J({url:o(`/requests/${s}/sse`),authHeader:r,signal:S.signal,log:e.log,fetchImpl:n});for await(let L of C)for(let z of H(L,s))A.state=P(A.state,z),yield z}finally{i.delete(s)}})(),A}async function h(s,f){let u=new FormData;u.append("prompt",s.prompt),l=s.memoryEnhancement??!0,u.append("memory_enhancement",String(l)),s.scenarioLimit!==void 0&&u.append("test_scenario_limit",String(s.scenarioLimit)),s.perScenarioLimit!==void 0&&u.append("per_scenario_test_cases_limit",String(s.perScenarioLimit));let d=s.projectId??e.projectId,y=s.folderId??e.folderId;d&&u.append("project_id",d),y&&u.append("folder_id",y),W(u,s.attachments);let S=await n(o("/requests"),{method:"POST",headers:{Authorization:await r()},body:u}),A=await p(S),{request_id:C}=a(A),L=String(C);return c(L,s.prompt,f)}async function g(s,f){let u=await n(o(`/requests/${s}`),{method:"GET",headers:{Authorization:await r()}}),d=await p(u),y=d?.data??d,S={requestId:s,status:y.status??"",headline:y.headline,scenarios:Array.isArray(y.scenarios)?y.scenarios:[]};return c(s,"",f,S)}async function m(s,f,u){let d=new FormData;d.append("prompt",f),d.append("chat_enabled","true"),d.append("memory_enhancement",String(l)),u?.mappings&&d.append("mappings",JSON.stringify(u.mappings)),W(d,u?.attachments);let y=await n(o(`/requests/${s}`),{method:"PUT",headers:{Authorization:await r()},body:d});if(!y.ok){let S;try{S=await y.clone().json()}catch{}throw x(y.status,S)}}async function b(s){i.get(s)?.abort();let u=await n(o(`/requests/${s}/stop`),{method:"DELETE",headers:{Authorization:await r()}});if(!u.ok&&u.status!==404){let d;try{d=await u.clone().json()}catch{}throw x(u.status,d)}}async function w(s){i.get(s)?.abort();let u=await n(o(`/requests/${s}/end`),{method:"DELETE",headers:{Authorization:await r()}});if(!u.ok&&u.status!==404){let d;try{d=await u.clone().json()}catch{}throw x(u.status,d)}}return{start:h,attach:g,chat:m,cancel:b,end:w}}import{statSync as ae,realpathSync as G,existsSync as ce}from"fs";import{extname as ue,resolve as j,isAbsolute as pe}from"path";import{homedir as V}from"os";var le=new Set([".txt",".json",".xml",".jpg",".jpeg",".png",".gif",".bmp",".webp",".pdf",".docx",".csv",".xlsx",".mp3",".wav",".m4a",".webm",".mpeg",".mpga",".mp4",".mov"]),de=50*1024*1024,X=10;function fe(e){return e==="~"?V():e.startsWith("~/")?j(V(),e.slice(2)):e}function Ge(e,t){let n=[],i=[],l=new Set,r=[],o=(()=>{try{return G(j(t))}catch{return j(t)}})(),p=o.endsWith("/")?o:o+"/";for(let a of e){let c=fe(a),h=pe(c)?c:j(t,c);if(!ce(h)){n.push(`Not found: ${a}`);continue}let g;try{g=G(h)}catch{n.push(`Cannot resolve: ${a}`);continue}if(l.has(g))continue;let m;try{m=ae(g)}catch{n.push(`Cannot read: ${a}`);continue}if(!m.isFile()){n.push(`Not a file: ${a}`);continue}if(m.size===0){n.push(`Empty file: ${a}`);continue}let b=ue(g).toLowerCase();if(!le.has(b)){n.push(`Unsupported type ${b||"(none)"}: ${a}`);continue}if(m.size>de){n.push(`Too large (>50MB): ${a}`);continue}g!==o&&!g.startsWith(p)&&i.push(`Outside working dir: ${a}`),l.add(g),r.push(g)}return r.length>X&&n.push(`Too many files: ${r.length} (max ${X})`),{ok:n.length?[]:r,errors:n,warnings:i}}var B=class extends Error{constructor(n){super(n.join("; "));this.errors=n;this.name="AttachmentValidationError"}};async function Xe(e){let{promptText:t,filePaths:n,cwd:i,scenarios:l,isRefine:r,conn:o,deps:p}=e,{ok:a,errors:c,warnings:h}=p.validate(n,i);if(c.length)throw new B(c);e.onValidated?.();let g=a.length?await p.upload(o,a,p.onUpload):[],m=r?p.buildMappings(t,l):void 0;return{promptText:t,mappings:m,attachments:g,warnings:h}}import{readFile as me}from"fs/promises";import{basename as K}from"path";async function ge(e){let t=await e.authResolver.resolve();if(!t)throw new v("unauthorized; run `kane-cli login`");return E(t.username,t.access_key)}async function he(e,t,n={}){let i=n.fetchImpl??fetch,l=await me(t),r=K(t),o=new FormData;o.append("file",new Blob([l]),r),o.append("source","omniBox"),o.append("geminiFileUpload","true");let p=await i(`${e.tmsBaseUrl}/v1/attachment`,{method:"POST",headers:{Authorization:await ge(e)},body:o,signal:n.signal});if(!p.ok){let m;try{m=await p.clone().json()}catch{}throw x(p.status,m)}let a=await p.json(),c=a?.data??a,h=c?.gemini_response?.uri,g=c?.gemini_response?.mimeType;if(!c?.file_key||!h){let m=c&&typeof c=="object"?Object.keys(c).join(","):typeof c,b=(()=>{try{return JSON.stringify(c).slice(0,500)}catch{return"<unserializable>"}})();throw new Error(`attachment upload for ${r} returned no file_key/gemini uri \u2014 status ${p.status}, body keys: [${m}], raw: ${b}`)}return{fileName:c.file_name??r,fileKey:c.file_key,geminiUri:h,mimeType:g??"application/octet-stream"}}async function tt(e,t,n,i={}){let l=[];for(let r=0;r<t.length;r++){if(i.signal?.aborted)throw Object.assign(new Error("upload aborted"),{name:"AbortError"});let o=K(t[r]);n?.({file:o,index:r+1,total:t.length,status:"uploading"});try{l.push(await he(e,t[r],i)),n?.({file:o,index:r+1,total:t.length,status:"done"})}catch(p){throw n?.({file:o,index:r+1,total:t.length,status:"failed"}),p}}return l}var ye=/@([sS])(\d+)\.([cC])(\d+)/g,be=/@([sS])(\d+)(?!\d)(?!\.[cC]\d)/g;function rt(e,t){let n={},i={};for(let l of e.matchAll(ye)){let r=Number(l[2]),o=Number(l[4]),p=t[r-1];if(!p)continue;n[`s${r}`]=String(p.id);let a=p.test_cases??[];if(a[o-1])for(let c=0;c<o;c++){let h=a[c];h&&(i[`s${r}.c${c+1}`]=String(h.id))}}for(let l of e.matchAll(be)){let r=Number(l[2]),o=t[r-1];o&&(n[`s${r}`]=String(o.id))}if(!(Object.keys(n).length===0&&Object.keys(i).length===0))return{scenario:n,testcase:i}}function R(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(n==null||typeof n!="object")return[];let i=n;if(typeof i.step!="string")return[];let l=typeof i.expected_result=="string"?i.expected_result:typeof i.outcome=="string"?i.outcome:"";t.push({step:i.step,expected:l})}return t}var we=30,Se=300;function Z(){return{mode:"testing",max_steps:we,timeout:Se,variables:{}}}function Q(e){return e.title??`Test case ${e.id}`}function ct(e,t){return $({frontmatter:Z(),heading:Q(t),steps:e.sub_objectives.map(n=>n.objective)})}function Y(e){let t=R(e.manual_steps).map(n=>n.step);return $({frontmatter:Z(),heading:Q(e),steps:t})}import{mkdtempSync as xe,mkdirSync as N,writeFileSync as ee,rmSync as te,renameSync as _e,existsSync as ne,readFileSync as ve}from"fs";import{join as _,resolve as ke}from"path";async function ft(e,t,n,i=Y){(n.redirectBareCwd??!0)&&ke(t)===process.cwd()&&(t=_(t,".testmuai","tests"));let l=T(e.objective)??e.headline,r=T(n.suiteName)??`${T(re(l,4))??"tcg"}-${e.requestId}`,o=r,p=_(t,r);ne(p)&&!Te(p,e.requestId)&&(o=`${r}-${e.requestId}`);let a=_(t,o),c=[],h=new Map;for(let m of e.scenarios){let b=(m.test_cases??[]).filter(Ae);if(b.length===0)continue;let w=T(Ee(m.scode))??T(m.sid)??`s${m.id}`,s=h.get(w)??new Set;h.set(w,s);for(let f of b){let u=T(re(f.title,5))??"case",d=`${u}_test.md`;for(let y=2;s.has(d);y++)d=`${u}-${y}_test.md`;s.add(d),c.push({dir:w,file:d,tc:f})}}if(c.length===0)return{suiteDir:a,paths:[],warning:"no functional test cases generated"};N(t,{recursive:!0});let g=xe(_(t,".tcg-tmp-"));try{N(_(g,"helpers"),{recursive:!0}),ee(_(g,".tcg-suite.json"),JSON.stringify({requestId:e.requestId,suiteName:o}));let m=[],b=new Set;for(let s of c){let f=_(g,s.dir);b.has(f)||(N(f,{recursive:!0}),b.add(f));let u=_(f,s.file);ee(u,i(s.tc)),m.push(u)}ne(a)&&te(a,{recursive:!0,force:!0}),_e(g,a);let w=m.map(s=>s.replace(g,a));return{suiteDir:a,paths:w}}catch(m){try{te(g,{recursive:!0,force:!0})}catch{}throw m}}function Ae(e){return(e.category??"").trim().toLowerCase()==="functional"}function Te(e,t){try{return JSON.parse(ve(_(e,".tcg-suite.json"),"utf-8"))?.requestId===t}catch{return!1}}function T(e){return e&&e.length>0?e:void 0}function re(e,t){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(Boolean).slice(0,t).join("-"):""}function Ee(e){return e?e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,""):""}function ht(e){let t=[];e.title&&t.push(e.title),e.description&&t.push("",e.description);let n=R(e.manual_steps);return n.length>0&&(t.push("","Steps:"),n.forEach((i,l)=>{t.push(`${l+1}. ${i.step}`)})),t.join(`
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
2
|
import R from"process";import{Buffer as U}from"buffer";import z from"path";import{fileURLToPath as ue}from"url";import{promisify as we}from"util";import G from"child_process";import ge,{constants as he}from"fs/promises";import H from"process";import W,{constants as Y}from"fs/promises";import O from"process";import q from"os";import S from"fs";import V from"fs";import L from"fs";var x;function X(){try{return L.statSync("/.dockerenv"),!0}catch{return!1}}function K(){try{return L.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function y(){return x===void 0&&(x=X()||K()),x}var v,j=()=>{try{return V.statSync("/run/.containerenv"),!0}catch{return!1}};function p(){return v===void 0&&(v=j()||y()),v}var T=()=>{if(O.platform!=="linux")return!1;if(q.release().toLowerCase().includes("microsoft"))return!p();try{if(S.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!p()}catch{}return S.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||S.existsSync("/run/WSL")?!p():!1},c=O.env.__IS_WSL_TEST__?T:T();var J=(()=>{let e="/mnt/",r;return async function(){if(r)return r;let o="/etc/wsl.conf",n=!1;try{await W.access(o,Y.F_OK),n=!0}catch{}if(!n)return e;let t=await W.readFile(o,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(t);return s?(r=s.groups.mountPoint.trim(),r=r.endsWith("/")?r:`${r}/`,r):e}})(),Q=async()=>`${await J()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,b=async()=>c?Q():`${H.env.SYSTEMROOT||H.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function m(e,r,o){let n=t=>Object.defineProperty(e,r,{value:t,enumerable:!0,writable:!0});return Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){let t=o();return n(t),t},set(t){n(t)}}),e}import{promisify as fe}from"util";import C from"process";import{execFile as le}from"child_process";import{promisify as Z}from"util";import ee from"process";import{execFile as re}from"child_process";var oe=Z(re);async function P(){if(ee.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await oe("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),o=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return o==="com.apple.safari"?"com.apple.Safari":o}import te from"process";import{promisify as ne}from"util";import{execFile as ie,execFileSync as Ge}from"child_process";var se=ne(ie);async function _(e,{humanReadableOutput:r=!0,signal:o}={}){if(te.platform!=="darwin")throw new Error("macOS only");let n=r?[]:["-ss"],t={};o&&(t.signal=o);let{stdout:s}=await se("osascript",["-e",e,n],t);return s.trim()}async function B(e){return _(`tell application "Finder" to set app_path to application file id "${e}" as string
|
|
3
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as ae}from"util";import{execFile as ce}from"child_process";var me=ae(ce),
|
|
3
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as ae}from"util";import{execFile as ce}from"child_process";var me=ae(ce),g={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},Ye=new Map(Object.entries(g)),E=class extends Error{};async function A(e=me){let{stdout:r}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),o=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(r);if(!o)throw new E(`Cannot find Windows browser in stdout: ${JSON.stringify(r)}`);let{id:n}=o.groups,t=n.lastIndexOf("."),s=n.lastIndexOf("-"),f=t===-1?void 0:n.slice(0,t),i=s===-1?void 0:n.slice(0,s);return g[n]??g[f]??g[i]??{name:n,id:n}}var pe=fe(le),de=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,r=>r.toUpperCase());async function F(){if(C.platform==="darwin"){let e=await P();return{name:await B(e),id:e}}if(C.platform==="linux"){let{stdout:e}=await pe("xdg-mime",["query","default","x-scheme-handler/http"]),r=e.trim();return{name:de(r.replace(/.desktop$/,"").replace("-"," ")),id:r}}if(C.platform==="win32")return A();throw new Error("Only macOS, Linux, and Windows are supported")}var xe=we(G.execFile),M=z.dirname(ue(import.meta.url)),k=z.join(M,"xdg-open"),{platform:u,arch:D}=R;async function ye(){let e=await b(),r=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,o=U.from(r,"utf16le").toString("base64"),{stdout:n}=await xe(e,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",o],{encoding:"utf8"}),t=n.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[t]?{id:s[t]}:{}}var $=async(e,r)=>{let o;for(let n of e)try{return await r(n)}catch(t){o=t}throw o},w=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return $(e.app,i=>w({...e,app:i}));let{name:r,arguments:o=[]}=e.app??{};if(o=[...o],Array.isArray(r))return $(r,i=>w({...e,app:{name:i,arguments:o}}));if(r==="browser"||r==="browserPrivate"){let i={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},a={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},l=c?await ye():await F();if(l.id in i){let I=i[l.id];return r==="browserPrivate"&&o.push(a[I]),w({...e,app:{name:d[I],arguments:o}})}throw new Error(`${l.name} is not supported as a default browser`)}let n,t=[],s={};if(u==="darwin")n="open",e.wait&&t.push("--wait-apps"),e.background&&t.push("--background"),e.newInstance&&t.push("--new"),r&&t.push("-a",r);else if(u==="win32"||c&&!p()&&!r){n=await b(),t.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),c||(s.windowsVerbatimArguments=!0);let i=["Start"];e.wait&&i.push("-Wait"),r?(i.push(`"\`"${r}\`""`),e.target&&o.push(e.target)):e.target&&i.push(`"${e.target}"`),o.length>0&&(o=o.map(a=>`"\`"${a}\`""`),i.push("-ArgumentList",o.join(","))),e.target=U.from(i.join(" "),"utf16le").toString("base64")}else{if(r)n=r;else{let i=!M||M==="/",a=!1;try{await ge.access(k,he.X_OK),a=!0}catch{}n=R.versions.electron??(u==="android"||i||!a)?"xdg-open":k}o.length>0&&t.push(...o),e.wait||(s.stdio="ignore",s.detached=!0)}u==="darwin"&&o.length>0&&t.push("--args",...o),e.target&&t.push(e.target);let f=G.spawn(n,t,s);return e.wait?new Promise((i,a)=>{f.once("error",a),f.once("close",l=>{if(!e.allowNonzeroExitCode&&l>0){a(new Error(`Exited with code ${l}`));return}i(f)})}):(f.unref(),f)},ve=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return w({...r,target:e})},gr=(e,r)=>{if(typeof e!="string"&&!Array.isArray(e))throw new TypeError("Expected a valid `name`");let{arguments:o=[]}=r??{};if(o!=null&&!Array.isArray(o))throw new TypeError("Expected `appArguments` as Array type");return w({...r,app:{name:e,arguments:o}})};function N(e){if(typeof e=="string"||Array.isArray(e))return e;let{[D]:r}=e;if(!r)throw new Error(`${D} is not supported`);return r}function h({[u]:e},{wsl:r}){if(r&&c)return N(r);if(!e)throw new Error(`${u} is not supported`);return N(e)}var d={};m(d,"chrome",()=>h({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));m(d,"brave",()=>h({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));m(d,"firefox",()=>h({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));m(d,"edge",()=>h({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));m(d,"browser",()=>"browser");m(d,"browserPrivate",()=>"browserPrivate");var hr=ve;export{gr as a,d as b,hr as c};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as p,b as d}from"./chunk-L5LI2JF4.js";import{b as f}from"./chunk-B2PZAB7J.js";var m=new Set(["delta","state-transition"]),b=/^capture baseline:/i;function g(e){return typeof e=="string"?e:e.text}function h(e){return typeof e=="object"&&e.baseline===!0||b.test(g(e).trim())}function v(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&"derived"in e}function S(e,r){if(e.check_prose)return e.check_prose;let n=r.find(i=>i.ref===e.check.verified_against),t=n?.text?` \u2014 the stated promise: ${n.text}`:"",o=String(e.check.operand??e.check.within??e.check.metric??"");return e.check.kind==="forbidden-presence"?`Confirm '${o}' does NOT appear (forbidden-presence)${t}`:`Confirm ${e.check.kind} check: ${o} (${e.check.operator})${t}`}var y=/^## Step \d+ — assert\s*$/;function B(e,r){if(r.length===0)return e;let n=e.split(`
|
|
3
|
+
`);for(let t=n.length-1;t>=0;t--){if(/^## Step \d+ — assert @verifies /.test(n[t]))return e;if(y.test(n[t]))return n[t]=`${n[t].trimEnd()} @verifies ${r.join(", ")}`,n.join(`
|
|
4
|
+
`)}return e}function C(e,r){return r.size===0?e:e.split(`
|
|
5
|
+
`).map(n=>{let t=n.match(/^@import\s+(\S+)\s*$/);if(t&&r.has(t[1]))return`@import ${r.get(t[1])}`;let o=n.match(/^## Import: (\S+)\s*$/);return o&&r.has(o[1])?`## Import: ${r.get(o[1])}`:n}).join(`
|
|
6
|
+
`)}function D(e,r,n){if(m.has(e.check.kind)&&!e.steps.some(h))throw new Error(`emitTestMd: check kind '${e.check.kind}' needs a baseline-capture step before the action (a step starting 'capture baseline: <metric>' or { baseline: true }) \u2014 the validator should have caught this`);let t=[`# ${e.title}`,""];r.intent&&t.push(`> ${r.intent}`,"");for(let u of e.reuses??[])t.push(`## Import: ${u}`,"",`@import ${u}`,"");let o=[],i=0;for(let u of e.steps){i++;let a=g(u).trim();t.push(`## Step ${i}`,"",a,""),o.push({step:i,objective:a,...h(u)?{baseline:!0}:{}})}i++;let s=S(e,n),c=e.check.expected_mode??(v(e.check.operand)?"runtime-derived":"inferred");t.push(`## Step ${i} \u2014 assert`,"",s,""),o.push({step:i,objective:s,check:{kind:e.check.kind,operator:e.check.operator,...e.check.operand!==void 0?{operand:e.check.operand}:{},...m.has(e.check.kind)?{baseline:e.check.baseline??null}:{},...e.check.within!==void 0?{within:e.check.within}:{},...e.check.metric!==void 0?{metric:e.check.metric}:{},...e.check.threshold!==void 0?{threshold:e.check.threshold}:{},...e.check.unit!==void 0?{unit:e.check.unit}:{},verified_against:e.check.verified_against,expected_mode:c,review_required:e.check.review_required??c==="runtime-derived"}});let l=d({title:e.title,...r.title?{scenario:r.title}:{},objectives:o},{sortKeys:!0,lineWidth:-1});return{test_md:t.join(`
|
|
7
|
+
`),objectives_yaml:l}}function G(e){let n=e.replace(/\r\n/g,`
|
|
8
|
+
`).split(`
|
|
9
|
+
`).map(i=>i.replace(/[ \t]+$/,""));if(n[0]?.trim()==="---"){let i=n.slice(1).findIndex(s=>s.trim()==="---");if(i>=0){let s=p(n.slice(1,i+1).join(`
|
|
10
|
+
`))??{},c="assurance"in s;delete s.assurance,Object.keys(s).length===0&&c?n=n.slice(i+2):n=["---",...d(s,{sortKeys:!0,lineWidth:-1}).trimEnd().split(`
|
|
11
|
+
`),"---",...n.slice(i+2)]}}let t=[];for(let i of n)i===""&&t[t.length-1]===""||t.push(i);for(;t[0]==="";)t.shift();for(;t[t.length-1]==="";)t.pop();let o=t.join(`
|
|
12
|
+
`)+`
|
|
13
|
+
`;return"sha256:"+f(Buffer.from("assurance.testdef\0"+o,"utf8"))}import{existsSync as $,readFileSync as E}from"fs";import{dirname as w,isAbsolute as I,resolve as j}from"path";var k=/^@import\s+(\S+)\s*$/;function _(e){let r=new Set;for(let n=0;n<e.length;n++)if(k.test(e[n].trim()))for(let t=n-1;t>=0;t--){let o=e[t].trim();if(o!==""){o==="```"&&r.add(n);break}}return r}function R(e,r,n=new Set,t=0){if(t>10)return e;let o=e.split(`
|
|
14
|
+
`),i=_(o);return o.map((s,c)=>{let l=k.exec(s.trim());if(!l||i.has(c))return s;let u=r(l[1]);if(!u||n.has(u.cycleKey))return s;let a=new Set(n);return a.add(u.cycleKey),R(u.body.trimEnd(),u.next,a,t+1)}).join(`
|
|
15
|
+
`)}function A(e){return r=>{let n=e.resolve(r);if(!n)return null;let t=e.getNode(n.tip)?.content.test_md_blob;return t?{body:t,cycleKey:n.tip,next:A(e)}:null}}function K(e,r){return n=>{let t=I(n)?n:j(e,n);if(!$(t))return null;let o=E(t,"utf8"),i=T(o);return!i||!r.resolve(i)?null:{body:M(o),cycleKey:t,next:K(w(t),r)}}}function L(e){let r=x(e);if(!r)return null;let n=/^assurance:\s*$[\s\S]*?^\s+id:\s*(\S+)\s*$/m.exec(r.text);if(!n)return null;let t=/^assurance:\s*$[\s\S]*?^\s+base:\s*(\S+)\s*$/m.exec(r.text);return{id:n[1],...t?{base:t[1]}:{}}}function T(e){return L(e)?.id??null}function x(e){let r=e.split(`
|
|
16
|
+
`);if(r[0]?.trim()!=="---")return null;for(let n=1;n<r.length;n++)if(r[n].trim()==="---")return{text:r.slice(1,n).join(`
|
|
17
|
+
`),endLine:n};return null}function M(e){let r=x(e);if(!r)return e;let n=e.split(`
|
|
18
|
+
`),t=n.slice(1,r.endLine),o=[],i=!1;for(let c of t){if(/^assurance:\s*$/.test(c)||/^assurance:\s*\{/.test(c)){i=!0;continue}i&&/^\s+\S/.test(c)||(i=!1,o.push(c))}let s=n.slice(r.endLine+1).join(`
|
|
19
|
+
`);return o.every(c=>c.trim()==="")?s:["---",...o,"---",s].join(`
|
|
20
|
+
`)}export{v as a,B as b,C as c,D as d,G as e,R as f,A as g,K as h,L as i,M as j};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{a as c}from"./chunk-
|
|
2
|
+
import{a as c}from"./chunk-KGP7NSXH.js";import{a as n}from"./chunk-RZ4F3BHX.js";import{u as s,v as a}from"./chunk-HMGNPFXP.js";import{createHash as h,randomBytes as g}from"crypto";var l=class{authBaseUrl;consentUrl;constructor(t="prod"){let e=c(t);this.authBaseUrl=e.authBaseUrl,this.consentUrl=e.consentUrl}static generatePkce(){let t=g(96).toString("base64url").slice(0,128),e=h("sha256").update(t).digest("base64url");return[t,e]}buildAuthorizationUrl(t,e,r,o){let i=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:o,scope:a,code_challenge:e,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${i.toString()}`}async registerClient(t){let e=await n(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:s,redirect_uris:[t],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!e.ok)throw new Error(`DCR failed: ${e.status} ${await e.text()}`);return e.json()}async exchangeCode(t,e,r,o){let i=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t,redirect_uri:o,client_id:e,code_verifier:r})});if(!i.ok)throw new Error(`Token exchange failed: ${i.status}`);return i.json()}async refreshToken(t,e){let r=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(t,e,r="access_token"){await n(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,token_type_hint:r,client_id:e})})}async validateToken(t){let e=new AbortController,r=setTimeout(()=>e.abort(),1e4);try{let o=await n(`${this.authBaseUrl}/api/user`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},signal:e.signal});return clearTimeout(r),o.ok}catch{return clearTimeout(r),!1}}};export{l as a};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as $}from"./chunk-L5LI2JF4.js";import{dirname as H,basename as U,join as w}from"path";function z(e){let t=U(e);return t.endsWith("_test.md")?t.slice(0,-8):t.endsWith(".md")?t.slice(0,-3):t}function k(e){return w(H(e),`output-${z(e)}`)}function ve(e){return w(k(e),"Result.md")}function O(e){return w(k(e),".internal")}function M(e){return w(O(e),"meta.json")}function _e(e,t,n){return w(k(e),`${t}-${n}-code`)}function ke(e){return w(k(e),"generated-code")}function xe(e){return k(e)+".staging"}function q(e){return w(O(e),"steps")}function Se(e,t,n){return w(q(e),`${t}-${n}`)}import{existsSync as g,renameSync as x,rmSync as v}from"fs";function $e(e){let t=`${e}.staging`,n=`${e}.bak`;if(!g(t))throw new Error(`atomicReplaceDir: staging missing: ${t}`);if(process.platform==="win32"){g(e)&&v(e,{recursive:!0,force:!0}),x(t,e);return}g(e)&&(g(n)&&v(n,{recursive:!0,force:!0}),x(e,n)),x(t,e),g(n)&&v(n,{recursive:!0,force:!0})}function Me(e){let t=`${e}.staging`,n=`${e}.bak`;if(process.platform==="win32"){g(t)&&(g(e)?v(t,{recursive:!0,force:!0}):x(t,e));return}if(g(n)&&!g(e)){x(n,e),g(t)&&v(t,{recursive:!0,force:!0});return}g(n)&&g(e)&&v(n,{recursive:!0,force:!0}),g(t)&&g(e)&&v(t,{recursive:!0,force:!0})}import{readFileSync as ge,existsSync as pe}from"fs";import{basename as G,dirname as ue,isAbsolute as me,resolve as Y}from"path";var c=class extends Error{constructor(n,r,i){super(`[${r}${i!=null?`:${i}`:""}] ${n}`);this.file=r;this.line=i;this.name="TestMdParseError"}},Q=new Set(["username","access_key","oauth","profile","project_id","folder_id"]),I=new Set(["mode","max_steps","timeout","global_context","local_context","variables","session_context","code_export","code_language","url","target","chrome_profile","cdp_endpoint","ws_endpoint","headless","on_lock_conflict","tags","assurance"]),L=new Set(["optional"]),X=new Set(["optional","variables"]),Z=new Set(["target","chrome_profile","cdp_endpoint","ws_endpoint","headless"]),ee=new Set(["mode","on_lock_conflict","tags","assurance"]);function T(e,t){let n=t.split(`
|
|
3
|
+
`),{global:r,bodyStartLine:i}=te(e,n),{title:o,steps:s}=oe(e,n,i);return{path:e,title:o,global:r,steps:s}}function te(e,t){if(t[0]?.trim()!=="---")return{global:{},bodyStartLine:0};let n=-1;for(let o=1;o<t.length;o++)if(t[o].trim()==="---"){n=o;break}if(n===-1)throw new c("frontmatter is missing closing '---'",e,1);let r=t.slice(1,n).join(`
|
|
4
|
+
`),i;try{i=$(r)??{}}catch(o){throw new c(`invalid YAML in frontmatter: ${o.message}`,e,1)}if(F(e,i,"frontmatter",1),i.on_lock_conflict!==void 0){let o=i.on_lock_conflict;if(o!=="readonly"&&o!=="fail"&&o!=="wait")throw new c(`on_lock_conflict must be 'readonly' | 'fail' | 'wait', got: ${JSON.stringify(o)}`,e,1)}if(A(e,i,1),i.assurance!==void 0){let o=i.assurance;if(o===null||typeof o!="object"||Array.isArray(o))throw new c("assurance must be a mapping with sub-keys {id, base}",e,1);let s=o;for(let l of Object.keys(s))if(l!=="id"&&l!=="base")throw new c(`unknown assurance sub-key '${l}' \u2014 the engine block allows only {id, base}`,e,1);if(typeof s.id!="string"||s.id.length===0)throw new c("assurance.id must be a non-empty string (logical id)",e,1);if(s.base!==void 0&&!(typeof s.base=="string"&&/^sha256:[0-9a-f]+$/.test(s.base)))throw new c("assurance.base must be a 'sha256:<hex>' string",e,1)}if(i.tags!==void 0){let o=i.tags,s=Array.isArray(o)?o.map(l=>String(l)).join(","):String(o);i.tags=ne(s,e,1)}return{global:i,bodyStartLine:n+1}}function ne(e,t,n){let i=e.trim().replace(/^\[/,"").replace(/\]$/,"").split(",").map(o=>o.trim().toLowerCase());if(i.length===0||i.some(o=>o.length===0))throw new c("tags must be a non-empty list of non-empty strings",t,n);return[...new Set(i)]}var ie=/\s@verifies\s+(ac-[\w.:\/-]+(?:\s*,\s*ac-[\w.:\/-]+)*)\s*$/;function re(e,t,n){let r=ie.exec(t);if(r)return{label:t.slice(0,r.index).trim(),verifies:r[1].split(",").map(o=>o.trim())};let i=t.lastIndexOf("@verifies");if(i>0&&/\s/.test(t[i-1])){let o=t.slice(i+9).split(/[\s,]+/).filter(s=>s.length>0);if(o.length===0||o.every(s=>s.startsWith("ac-")))throw new c("malformed @verifies directive \u2014 expected '@verifies ac-<id>[, ac-<id>\u2026]' at the end of the heading",e,n)}return{label:t,verifies:[]}}function oe(e,t,n){let r,i=n;for(;i<t.length&&t[i].trim()==="";)i++;let o=i<t.length?/^#\s+(.+?)\s*$/.exec(t[i]):null;o&&(r=o[1],i++);let s=[];for(let f=i;f<t.length;f++)/^##\s/.test(t[f])&&s.push(f);let l=[];for(let f=0;f<s.length;f++){let p=s[f],u=s[f+1]??t.length,h=t[p].replace(/^##\s+/,"").trim(),{label:a,verifies:d}=re(e,h,p+1),m=t.slice(p+1,u),{config:b,body:y,optional:R}=se(e,p+1,m);l.push({index:f+1,heading:a,verifies:d,config:b,body:y,headingLine:p+1,optional:R})}return{title:r,steps:l}}function se(e,t,n){let r=0;for(;r<n.length&&n[r].trim()==="";)r++;let i,o=t;if(r<n.length&&/^```yaml\s*$/.test(n[r])){let d=r;o=t+d,r++;let m=-1;for(;r<n.length;){if(/^```\s*$/.test(n[r])){m=r;break}r++}if(m===-1)throw new c("step-config fenced ```yaml block is not closed",e,o);let b=n.slice(d+1,m).join(`
|
|
5
|
+
`);try{i=$(b)??{}}catch(y){throw new c(`invalid YAML in step config: ${y.message}`,e,o)}r=m+1}let s=ae(n.slice(r)),l=s.filter(d=>d.trim()!=="");if(l.length>0&&/^@session\s+/.test(l[0].trim()))throw new c("@session is no longer supported (iteration 3); use @import instead",e,t);let f=/^@import\s+(\S.*)$/,u=s.filter(d=>f.test(d.trim())).length>0;if(u&&l.length!==1)throw new c("step body must be exactly one of prose / @import",e,t);let h=!1,a;if(i){if(F(e,i,u?"step config (ref)":"step config (objective)",o),A(e,i,o),typeof i.optional=="boolean")h=i.optional;else if(i.optional!==void 0)throw new c(`step config 'optional' must be boolean: got ${typeof i.optional}`,e,o);let d={...i};delete d.optional,u&&delete d.variables,!u&&Object.keys(d).length>0&&(a=d)}if(u){let m=f.exec(l[0].trim())[1].trim(),b=i?.variables;return{body:{kind:"import_ref",path:m,...b&&Object.keys(b).length>0?{bindings:b}:{}},optional:h}}return{body:{kind:"objective",text:s.join(`
|
|
6
|
+
`).trim()},config:a,optional:h}}function ae(e){let t=0,n=e.length;for(;t<n&&e[t].trim()==="";)t++;for(;n>t&&e[n-1].trim()==="";)n--;return e.slice(t,n)}function A(e,t,n){let r=t.variables;if(r==null)return;if(typeof r!="object"||Array.isArray(r))throw new c("variables must be an object map",e,n);let i={};for(let[o,s]of Object.entries(r))if(typeof s=="string")i[o]={value:s};else if(s&&typeof s=="object"&&!Array.isArray(s)&&typeof s.value=="string")i[o]=s;else throw new c(`variable '${o}' must be a string or { value: ... } object`,e,n);t.variables=i}function F(e,t,n,r){for(let i of Object.keys(t)){if(Q.has(i))throw new c(`auth/identity keys are CLI-only: ${i}`,e,r);if(n==="frontmatter"){if(L.has(i))throw new c(`step-only key in frontmatter: ${i}`,e,r);if(!I.has(i))throw new c(`unknown config key: ${i}`,e,r)}else if(n==="step config (objective)"){if(!I.has(i)&&!L.has(i))throw new c(`unknown config key: ${i}`,e,r);if(Z.has(i))throw new c(`chrome config is global-only: ${i}`,e,r);if(ee.has(i))throw new c(`'${i}' is run-level and cannot be set per-step`,e,r)}else if(!X.has(i))throw new c(`step config on @import may only contain 'optional' / 'variables': got ${i}`,e,r)}}import{createHash as P}from"crypto";function S(e){if(e==null)return null;if(Array.isArray(e))return e.map(S);if(typeof e=="object"){let t={};for(let n of Object.keys(e).sort()){let r=e[n];r!==void 0&&(t[n]=S(r))}return t}return e}function ce(e){if(e.body.kind!=="objective")throw new Error("stepMd5: only objective steps have an md5; @import rows do not");let t={...e.config??{},optional:e.optional??!1},n=JSON.stringify(S(t));return P("md5").update(e.body.text).update(`
|
|
7
|
+
`).update(n).digest("hex")}function V(e){let t={};for(let[r,i]of Object.entries(e.bindings??{}))t[r]={value:i.value,...i.secret===!0?{secret:!0}:{},...i.syntax?{syntax:i.syntax}:{}};let n=JSON.stringify(S({bindings:t,optional:e.optional}));return P("md5").update(e.path).update(`
|
|
8
|
+
`).update(n).digest("hex")}function Le(e){return ce({index:e.trace[e.trace.length-1].stepIndex,heading:e.trace[e.trace.length-1].heading,verifies:[],body:{kind:"objective",text:e.objective},config:e.parsedConfig,headingLine:1,optional:e.optional})}import{writeFileSync as de,mkdirSync as le,readFileSync as fe}from"fs";import{dirname as K}from"path";function D(e){try{return JSON.parse(fe(M(e),"utf8"))}catch{return null}}function Ve(e){let t=M(e.sourcePath);try{le(K(t),{recursive:!0})}catch(r){return process.stderr.write(`
|
|
9
|
+
\u26A0 Failed to create output directory.
|
|
10
|
+
${r.message}
|
|
11
|
+
Path: ${K(t)}
|
|
12
|
+
|
|
13
|
+
`),t}let n={commit_id:e.commitId};e.testId!==void 0&&(n.test_id=e.testId),e.testcaseId!==void 0&&(n.testcase_id=e.testcaseId),e.projectId!==void 0&&(n.project_id=e.projectId),e.folderId!==void 0&&(n.folder_id=e.folderId),e.orgId!==void 0&&(n.org_id=e.orgId),e.sessionName!==void 0&&(n.session_name=e.sessionName),e.plan!==void 0&&(n.plan=e.plan);try{de(t,JSON.stringify(n,null,2)+`
|
|
14
|
+
`,"utf8")}catch(r){process.stderr.write(`
|
|
15
|
+
\u26A0 Failed to write meta.json.
|
|
16
|
+
${r.message}
|
|
17
|
+
Path: ${t}
|
|
18
|
+
|
|
19
|
+
`)}return t}var N=["target","chrome_profile","cdp_endpoint","ws_endpoint","headless"],be=["mode","on_lock_conflict","tags","target","chrome_profile","cdp_endpoint","ws_endpoint","headless"],_=class extends Error{constructor(t){super(t),this.name="TestMdResolveError"}};function E(e){return G(e).endsWith("_test.md")?"test":"helper"}function Je(e){let t=Y(e),n=W(t),r=he(n.global),i=[],o=[],s=[{file:t,kind:E(t)}],l=[];return J(n,o,i,[],t,{},s,l,{}),i.forEach((p,u)=>p.flatIndex=u+1),{rootPath:t,rootTitle:n.title,rootGlobal:n.global,rootSteps:n.steps,chrome:r,steps:i,unitFiles:s,warnings:l}}function Be(e){let t=[];for(let n of e.unitFiles){if(n.kind!=="test")continue;let r=D(n.file);r&&t.push({file:n.file,...r.project_id?{project_id:String(r.project_id)}:{},...r.org_id?{org_id:String(r.org_id)}:{}})}return t}function W(e){if(!pe(e))throw new _(`@import path not found: ${e}`);let t=ge(e,"utf8");return T(e,t)}function J(e,t,n,r,i,o,s,l,f){if(t.includes(e.path)){let a=[...t,e.path].map(d=>G(d)).join(" \u2192 ");throw new _(`cyclic reference: ${a}`)}t.push(e.path);let p=r.length===0,u=e.global.variables??{};for(let a of Object.keys(o))if(Object.hasOwn(u,a))throw new _(`callsite binding '${a}' collides with a declared variable in ${e.path} (frontmatter variables are pinned; parameters are its undeclared names)`);let h=e.global;if(!p){let a={...e.global};for(let d of be)a[d]!==void 0&&(l.push(`${e.path}: '${d}' is root-governed on imported units \u2014 ignored`),delete a[d]);a.url!==void 0&&(f.pending=String(a.url),delete a.url),h=a}for(let a of e.steps){let d=a.body.kind!=="objective";if(a.optional&&d&&!p)throw new _(`intermediate-ref 'optional' is not supported in v1: ${e.path}:${a.headingLine}`);if(a.body.kind==="objective"){let j={file:e.path,stepIndex:a.index,heading:a.heading,optional:a.optional??!1},B=ye(h,a.config,o),C={flatIndex:0,objective:a.body.text,sourceFile:e.path,trace:[...r,j],config:B,parsedConfig:a.config,optional:a.optional??!1,verifies:a.verifies,owningFile:e.path,unitKind:E(e.path)};f.pending&&(C.unitEntryUrl=f.pending,f.pending=void 0),n.push(C);continue}let m={file:e.path,stepIndex:a.index,heading:a.heading,optional:a.optional??!1,rowMd5:V({path:a.body.path,bindings:a.body.bindings,optional:a.optional??!1})},b=ue(e.path),y=me(a.body.path)?a.body.path:Y(b,a.body.path),R=W(y);s.some(j=>j.file===y)||s.push({file:y,kind:E(y)}),J(R,t,n,[...r,m],i,a.body.bindings??{},s,l,f)}p||(f.pending=void 0),t.pop()}function he(e){let t={};for(let n of N)e[n]!==void 0&&(t[n]=e[n]);return t}function ye(e,t,n){let r={};for(let[s,l]of Object.entries(e))N.includes(s)||(r[s]=l);let i={...r,...t??{}},o={...n,...e.variables??{},...t?.variables??{}};return Object.keys(o).length>0?i.variables=o:delete i.variables,i}export{z as a,k as b,ve as c,O as d,M as e,_e as f,ke as g,xe as h,q as i,Se as j,$e as k,Me as l,T as m,V as n,Le as o,D as p,Ve as q,_ as r,Je as s,Be as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{a as b}from"./chunk-
|
|
2
|
+
import{a as b}from"./chunk-CB3TEWZJ.js";import{m as d,x as o}from"./chunk-HMGNPFXP.js";import{a as L}from"./chunk-HCBYKLMW.js";import{a as u,b as c,i as A}from"./chunk-C44QQJR4.js";import{a as D}from"./chunk-6YGTRKDT.js";import{e as h}from"./chunk-UR6MHSHU.js";var x=h(D(),1);import{readdirSync as N,mkdirSync as B,statSync as k}from"fs";import{join as P}from"path";var r=h(L(),1);function O(n){try{return N(n).filter(l=>{try{return k(P(n,l)).isDirectory()}catch{return!1}})}catch{return[]}}function E(n,l,f,v){return{name:n,path:l,label:n,isActive:v}}function H({currentPath:n,onSelect:l,onCancel:f}){let s=O(d).map(i=>{let e=P(d,i);return E(i,e,n,e===n)}),p=!n,R=s.length+2,[a,C]=(0,x.useState)(()=>{if(p)return 0;let i=s.findIndex(e=>e.isActive);return i>=0?i+1:0}),[T,I]=(0,x.useState)(!1),[S,g]=(0,x.useState)("");return A((i,e)=>{if(T){if(e.escape){I(!1),g("");return}if(e.return){let t=S.trim();if(t){let m=P(d,t);B(m,{recursive:!0}),l(m),f()}return}if(e.backspace||e.delete){g(t=>t.slice(0,-1));return}i&&!e.ctrl&&!e.meta&&g(t=>t+i);return}if(e.escape){f();return}if(e.upArrow){C(t=>Math.max(0,t-1));return}if(e.downArrow){C(t=>Math.min(R-1,t+1));return}if(e.return){if(a===0){p||l(""),f();return}if(a===s.length+1){B(d,{recursive:!0}),I(!0),g("");return}let t=s[a-1];t&&!t.isActive&&l(t.path),f();return}}),T?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile \u203A New"}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(c,{color:o.secondary,children:"Name: "}),(0,r.jsx)(c,{children:S}),(0,r.jsx)(c,{color:o.dim,children:"\u2588"})]}),(0,r.jsx)(b,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:"back"})]}):(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile"}),(0,r.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,r.jsxs)(c,{color:p?o.green:a===0?o.orange:o.dim,children:[a===0?"\u276F ":" ","Use temporary (no profile)",p?" \u25CF active":""]}),s.map((i,e)=>{let m=e+1===a,w=m?"\u276F ":" ",y=i.isActive?o.green:m?o.orange:void 0;return(0,r.jsxs)(c,{color:y,children:[w,i.label,i.isActive?" \u25CF active":""]},i.name)}),(0,r.jsxs)(c,{color:a===s.length+1?o.orange:o.dim,children:[a===s.length+1?"\u276F ":" ","+ Create new"]})]}),(0,r.jsx)(b,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}export{O as a,E as b,H as c};
|