@testmuai/kane-cli 0.2.10 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/ChromeProfilePicker-U2SEKNEQ.js +2 -0
  2. package/dist/CliFeedbackPrompt-EADRWA76.js +2 -0
  3. package/dist/CliUploadProgress-DV34KLES.js +2 -0
  4. package/dist/ConfigView-32U22T7S.js +2 -0
  5. package/dist/FolderPicker-C4ANRIT7.js +2 -0
  6. package/dist/HelpView-PUE5XHCB.js +2 -0
  7. package/dist/InfoBox-QNOWEKMD.js +2 -0
  8. package/dist/{LinksBox-FR4WLNX4.js → LinksBox-UCNEPFJD.js} +1 -1
  9. package/dist/ProfilesView-P6JL2BTH.js +2 -0
  10. package/dist/ProjectPicker-XEZIFGJ6.js +2 -0
  11. package/dist/SaveSessionPrompt-DIZX3M6X.js +2 -0
  12. package/dist/SingleShotApp-RLZN2PVQ.js +2 -0
  13. package/dist/SummaryBox-72NGQYS7.js +2 -0
  14. package/dist/TestMdRunView-DD6YI7CY.js +2 -0
  15. package/dist/{WhoamiView-AP6NXPTL.js → WhoamiView-LSMM65UI.js} +1 -1
  16. package/dist/{changelog-DFV22SXX.js → changelog-P7XOVZ6M.js} +1 -1
  17. package/dist/chunk-3MSXQU2C.js +2 -0
  18. package/dist/chunk-445V6RTR.js +2 -0
  19. package/dist/chunk-4SNZTVJB.js +2 -0
  20. package/dist/chunk-5KH7U63E.js +6 -0
  21. package/dist/chunk-66CVM7JL.js +53 -0
  22. package/dist/chunk-75SVKFKD.js +2 -0
  23. package/dist/chunk-7VX5H5MK.js +5 -0
  24. package/dist/{chunk-43D3E7EA.js → chunk-BAKBO5YA.js} +1 -1
  25. package/dist/chunk-BSQVYLV7.js +2 -0
  26. package/dist/chunk-C5UNZ6ZY.js +2 -0
  27. package/dist/{chunk-FK2AWXZN.js → chunk-CFFWCE27.js} +1 -1
  28. package/dist/chunk-FFO5XXKV.js +4 -0
  29. package/dist/chunk-FJ6L63SP.js +8 -0
  30. package/dist/chunk-G7I7EAV6.js +2 -0
  31. package/dist/chunk-G7VF5SDK.js +10 -0
  32. package/dist/chunk-GTFULP6B.js +13 -0
  33. package/dist/chunk-I4AD2L5R.js +2 -0
  34. package/dist/chunk-JPKW7SRP.js +2 -0
  35. package/dist/chunk-JYQO6G7F.js +2 -0
  36. package/dist/{chunk-SOUKF5VL.js → chunk-L2HVRWIT.js} +8 -8
  37. package/dist/chunk-MBQIYYLD.js +2 -0
  38. package/dist/chunk-MDBXYXSC.js +2 -0
  39. package/dist/chunk-MH26PIS4.js +2 -0
  40. package/dist/chunk-MNAVXLW4.js +20 -0
  41. package/dist/{chunk-UNQM5247.js → chunk-NLYBR5FP.js} +1 -1
  42. package/dist/chunk-OMYNAZW4.js +2 -0
  43. package/dist/{chunk-5WXHT4JD.js → chunk-OU2XDMNW.js} +1 -1
  44. package/dist/chunk-PINXGH2T.js +3 -0
  45. package/dist/chunk-Q6INY5JA.js +2 -0
  46. package/dist/chunk-QV2VR72Q.js +5 -0
  47. package/dist/chunk-S3DAAAE5.js +2 -0
  48. package/dist/chunk-SLA75N5B.js +2 -0
  49. package/dist/chunk-VE3SUJMA.js +2 -0
  50. package/dist/chunk-XJ7OYQ7M.js +2 -0
  51. package/dist/chunk-XW32PCGX.js +5 -0
  52. package/dist/chunk-Y5RLPELZ.js +103 -0
  53. package/dist/chunk-YCCUBQY4.js +2 -0
  54. package/dist/chunk-YUUZDFT7.js +2 -0
  55. package/dist/chunk-YV5KDJLP.js +2 -0
  56. package/dist/effective-decisions-DRM3JSR4.js +2 -0
  57. package/dist/index.js +38 -58
  58. package/dist/{logging-WJPMWUL5.js → logging-NPMKABVV.js} +1 -1
  59. package/dist/login-flow-QCYF5347.js +2 -0
  60. package/dist/name-validator-5YGJXLZ7.js +2 -0
  61. package/dist/persist-recorded-session-53YCJK7U.js +5 -0
  62. package/dist/pipeline-BVH3R7YP.js +2 -0
  63. package/dist/profile-sync-DTTRRIVP.js +2 -0
  64. package/dist/recording-banner-ABFX6FI4.js +3 -0
  65. package/dist/replay-policy-6USQBT3E.js +2 -0
  66. package/dist/run-test-md-C63UB65T.js +54 -0
  67. package/dist/testmd-actions-GPYFEL7F.js +20 -0
  68. package/dist/{tms-client-VH42IFUF.js → tms-client-CTH4NVFM.js} +1 -1
  69. package/dist/validate-basic-TW5CQAL3.js +2 -0
  70. package/dist/{version-check-AGBPWJQA.js → version-check-6XDFGFCG.js} +1 -1
  71. package/package.json +5 -5
  72. package/dist/ChromeProfilePicker-VPCR7EPX.js +0 -2
  73. package/dist/CliFeedbackPrompt-CKWGADHU.js +0 -2
  74. package/dist/CliUploadProgress-ZVRZFMGT.js +0 -2
  75. package/dist/ConfigView-XCWDFTNS.js +0 -2
  76. package/dist/FolderPicker-DN4OV6BI.js +0 -2
  77. package/dist/HelpView-DOYUDPWZ.js +0 -2
  78. package/dist/LoginWizard-NJ22OXIH.js +0 -2
  79. package/dist/ProfilesView-ENBYW7PJ.js +0 -2
  80. package/dist/ProjectPicker-43LFS6S6.js +0 -2
  81. package/dist/chunk-5PATFYIN.js +0 -2
  82. package/dist/chunk-6REBTGNQ.js +0 -106
  83. package/dist/chunk-75XK2HKS.js +0 -2
  84. package/dist/chunk-7E2QYCMX.js +0 -2
  85. package/dist/chunk-7H6IY5KC.js +0 -2
  86. package/dist/chunk-FBK6UISI.js +0 -2
  87. package/dist/chunk-HFQ7T5KT.js +0 -2
  88. package/dist/chunk-KJAVR2NX.js +0 -2
  89. package/dist/chunk-OILYCYAD.js +0 -2
  90. package/dist/chunk-PXIG2FKV.js +0 -2
  91. package/dist/chunk-YSOCZU7T.js +0 -2
  92. package/dist/chunk-YTG6V347.js +0 -2
  93. package/dist/login-flow-5WUX5JKU.js +0 -2
  94. package/dist/pipeline-ZSNZGJIH.js +0 -2
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as m}from"./chunk-BSQVYLV7.js";import{a as p}from"./chunk-HCBYKLMW.js";import{t}from"./chunk-JYQO6G7F.js";import{a,b as o,i as u}from"./chunk-C44QQJR4.js";import{a as b}from"./chunk-6YGTRKDT.js";import{e as n}from"./chunk-UR6MHSHU.js";var c=n(b(),1);var e=n(p(),1);function T({onSubmit:l}){let[r,f]=(0,c.useState)(0),s=(0,c.useRef)(!1);return u((x,i)=>{s.current||(i.leftArrow||i.rightArrow?f(d=>d===0?1:0):i.return?(s.current=!0,l(r===0?"positive":"negative")):i.escape&&(s.current=!0,l(null)))}),(0,e.jsxs)(a,{flexDirection:"column",marginTop:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(o,{color:t.secondary,children:"Rate this session: "}),(0,e.jsx)(o,{color:r===0?t.primary:t.dim,children:r===0?"[ \u{1F44D} ]":" \u{1F44D} "}),(0,e.jsx)(o,{children:" "}),(0,e.jsx)(o,{color:r===1?t.primary:t.dim,children:r===1?"[ \u{1F44E} ]":" \u{1F44E} "})]}),(0,e.jsx)(m,{bindings:[{keys:"\u2190/\u2192",label:"select"},{keys:"\u21B5",label:"submit"}],escBackLabel:"skip"})]})}export{T as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ function r(e){return{url:`${e.tmsBaseUrl}/kane-cli/v1/test-case/${e.testcaseId}/code`,body:{code_name:"kane-cli-trigger",language:e.codeExport.language,framework:"playwright",folder_name:"",accessibility:"false",skipCodeValidation:e.codeExport.skipValidation}}}function o(e){return`${e.tmsBaseUrl}/kane-cli/v1/test-case/${e.testcaseId}/codes?page=1&per_page=10`}export{r as a,o as b};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as p}from"./chunk-HCBYKLMW.js";import{t as a}from"./chunk-JYQO6G7F.js";import{b as u}from"./chunk-C44QQJR4.js";import{a as l}from"./chunk-6YGTRKDT.js";import{e as n}from"./chunk-UR6MHSHU.js";var m=n(l(),1);var o=n(l(),1);function c(r,e){let t=(0,o.useRef)(r);t.current=r,(0,o.useEffect)(()=>{if(e===null)return;let i=setInterval(()=>t.current(),e);return()=>clearInterval(i)},[e])}var s=n(p(),1),f=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function I({active:r=!0}){let[e,t]=(0,m.useState)(0);return c(()=>{t(i=>(i+1)%f.length)},r?80:null),(0,s.jsx)(u,{color:a.purple,children:r?f[e]:"\u25CF"})}export{c as a,I as b};
@@ -0,0 +1,20 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as oe}from"./chunk-7VX5H5MK.js";import{b as q}from"./chunk-YV5KDJLP.js";import{a as L,c as ae}from"./chunk-FFO5XXKV.js";import{b as ne,e as J,h as ie}from"./chunk-SLA75N5B.js";import{a as K}from"./chunk-66CVM7JL.js";import{b as re,d as se}from"./chunk-G7VF5SDK.js";import{b as G}from"./chunk-VE3SUJMA.js";import{a as k}from"./chunk-NLYBR5FP.js";import{a as ee}from"./chunk-E47GFYXA.js";import{i as B,j as H}from"./chunk-JYQO6G7F.js";import{a as D}from"./chunk-YUUZDFT7.js";import{a as O,b as te}from"./chunk-DXKKUGFG.js";import{dirname as Be,join as He}from"path";function Kt(e,t,r){let s=e.total_runs??1,o=e.run_dir,n,i;if(s>1&&o){let a=Be(o);n=Array.from({length:s},(c,l)=>He(a,String(t+l))),r&&r.length===s&&(i=r)}return{allRunDirs:n,flowObjectives:i}}function Gt(e,t,r,s){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:s.allRunDirs,flow_objectives:s.flowObjectives}}import{spawn as Ke}from"child_process";async function ce(e,t,r=100){let s=`${e.replace(/\/+$/,"")}/json/version`,o=await fetch(s);if(!o.ok)throw new Error(`CDP /json/version returned ${o.status}`);let n=await o.json();if(!n.webSocketDebuggerUrl)throw new Error("CDP /json/version missing webSocketDebuggerUrl");let i=new ee(n.webSocketDebuggerUrl);await new Promise((S,h)=>{i.once("open",S),i.once("error",h)});let a=1,c=new Map;i.on("message",S=>{let h;try{h=JSON.parse(S.toString())}catch{return}if(h.id==null)return;let _=c.get(h.id);_&&(c.delete(h.id),h.error?_.reject(new Error(h.error.message)):_.resolve(h.result))});function l(S,h){let _=a++;return new Promise((Fe,Me)=>{c.set(_,{resolve:Ve=>Fe(Ve),reject:Me});let Z={id:_,method:S};h&&(Z.params=h),i.send(JSON.stringify(Z))})}let u=(await l("Target.getTargets")).targetInfos.find(S=>S.type==="page");if(!u)throw i.close(),new Error("CDP: no page target found");let m=(await l("Browser.getWindowForTarget",{targetId:u.targetId})).windowId,p="",g=!1,w=null,I=!1;i.on("close",()=>{I=!0}),i.on("error",()=>{I=!0});async function T(){if(!g){if(I){g=!0;return}try{let h=(await l("Browser.getWindowBounds",{windowId:m})).bounds,_=`${h.left}:${h.top}:${h.width}:${h.height}`;_!==p&&(p=_,t({left:h.left,top:h.top,width:h.width,height:h.height}))}catch{}g||(w=setTimeout(T,r))}}return T(),{stop(){if(!g){g=!0,w&&clearTimeout(w);try{i.close()}catch{}}}}}var Ge=new Set(["1","true","yes"]);function Xt(e){if(e?.headless)return null;let t=process.env.KANE_CLI_DISABLE_MARKER;if(t!=null&&Ge.has(t.toLowerCase()))return null;let r=oe();if(!r)return null;let s=[...r.args,"overlay"];e?.text&&s.push(e.text);let o;try{o=Ke(r.cmd,s,{cwd:r.cwd,stdio:["pipe","ignore","ignore"],detached:!1,windowsHide:!0})}catch{return null}function n(c){if(!(!o.stdin||o.stdin.destroyed))try{o.stdin.write(JSON.stringify(c)+`
3
+ `)}catch{}}e?.chromePid&&e.chromePid>0&&n({type:"chrome_pid",pid:e.chromePid});let i=null;e?.cdpEndpoint&&ce(e.cdpEndpoint,c=>n({type:"bounds",...c})).then(c=>{i=c.stop}).catch(()=>{});let a=!1;return{setRunActive(c){a||n({type:"run_active",active:c})},setStepText(c){if(a)return;let l=c.trim();l&&n({type:"step_text",text:l})},setStepComplete(){a||n({type:"step_complete"})},kill(){if(!a){a=!0,i?.();try{o.stdin?.end()}catch{}try{o.kill("SIGTERM")}catch{}}}}}import{readFileSync as Je,existsSync as qe}from"fs";function tr(e){if(!qe(e))return null;try{return Je(e,"utf-8").trim()||null}catch{return null}}function le(e,t,r){return`${e}/projects/${t}/test-cases/${r}`}function sr(e,t,r,s){return`${le(e,t,r)}/dashboard/share/${s}?type=summary&agentView=true&fqdn=summary-page`}function or(e,t,r){return`${le(e,t,r)}/dashboard?type=summary&agentView=true&fqdn=summary-page`}import{readFileSync as de,readdirSync as ue,existsSync as R}from"fs";import{join as v}from"path";function cr(e,t,r,s,o,n){try{let i=v(e,"runs",String(t),"run-test");if(!R(i)){o("warn","SCREENSHOT_SKIP","Runs dir not found",{step_index:r,reason:"runsDir_not_found",path:i});return}let a=i;if(n){let g=v(i,`child-${n}`);if(!R(g)){o("warn","SCREENSHOT_SKIP","Child dir not found",{step_index:r,child_id:n,reason:"child_dir_not_found",path:g});return}let w=ue(g).filter(I=>R(v(g,I,"screenshots")));if(w.length===0){o("warn","SCREENSHOT_SKIP","No screenshots dir under child",{step_index:r,child_id:n,reason:"no_child_screenshots_dir"});return}a=v(g,w[0])}else if(!R(v(i,"screenshots"))){let g=ue(i).filter(w=>R(v(i,w,"screenshots")));if(g.length===0){o("warn","SCREENSHOT_SKIP","No screenshots dir found",{step_index:r,reason:"no_screenshots_dir"});return}a=v(i,g[0])}let c=v(a,"screenshots",`step_${String(r).padStart(3,"0")}.png`);if(!R(c)){o("warn","SCREENSHOT_SKIP","Screenshot not found",{step_index:r,child_id:n,reason:"screenshot_not_found",path:c});return}let l=v(i,"actions.ndjson");if(!R(l)){o("warn","SCREENSHOT_SKIP","NDJSON not found",{step_index:r,reason:"ndjson_not_found"});return}let d=de(l,"utf-8").trim().split(`
4
+ `),u=d[d.length-1];if(!u){o("warn","SCREENSHOT_SKIP","NDJSON empty",{step_index:r,reason:"ndjson_empty"});return}let m=JSON.parse(u).action_id;if(!m){o("warn","SCREENSHOT_SKIP","No action_id in NDJSON",{step_index:r,reason:"no_action_id"});return}let p=de(c);s.enqueue(m,p),o("info","SCREENSHOT_ENQUEUED","Screenshot enqueued",{step_index:r,child_id:n,action_id:m,size:p.length})}catch(i){o("error","SCREENSHOT_DISPATCH_ERROR","Screenshot dispatch error",{step_index:r,error:i instanceof Error?i.message:String(i)})}}import We from"sharp";var me=class{maxWorkers;maxRetries=2;queue=[];activeCount=0;drainResolvers=[];sas;log;constructor(t,r=3,s){this.sas=t,this.maxWorkers=r,this.log=s}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,s="image/webp";try{let a=await We(t.buffer).webp({quality:80}).toBuffer();r=new Uint8Array(a)}catch(a){r=new Uint8Array(t.buffer),s="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)})}let o=s==="image/webp"?"webp":"png",n=`test_screenshots/untagged_screenshot/${t.operationId}.${o}`,i=`${this.sas.base_url}/${this.sas.container}/${n}?${this.sas.sas_token}`;for(let a=0;a<=this.maxRetries;a++)try{let c=await fetch(i,{method:"PUT",headers:{"Content-Type":s,"x-ms-blob-type":"BlockBlob"},body:r});if(c.ok)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(s=>setTimeout(s,r))}isNearExpiry(){if(!this.sas.expiry)return!1;let t=new Date(this.sas.expiry).getTime();return Date.now()>t-5*6e4}};function fe(e,t){let r={},s={},o=t;for(let[n,i]of Object.entries(e))if(i.secret){let a=`secrets.user.${n}`;r[a]={value:i.value,secret:!0,syntax:`{{secrets.user.${n}}}`,type:"secret"},s[n]=a,o=o.replaceAll(`{{${n}}}`,`{{secrets.user.${n}}}`)}else{let a=`global.${n}`;r[a]={value:i.value,secret:!1,syntax:`{{global.${n}}}`,type:"global"},s[n]=a,o=o.replaceAll(`{{${n}}}`,`{{global.${n}}}`)}return{variables:r,objective:o,keyMap:s}}var $=class{constructor(t){this.baseUrl=t}async pushSecret(t){let r=O(t.username,t.accessKey),s=await fetch(`${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(!s.ok)throw new Error(`Push secret failed: ${s.status} ${await s.text()}`)}static extractVariableKeys(t){let r=t.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g),s=new Set;for(let o of r)s.add(o[1]);return[...s]}};var N=class extends te{constructor(t,r,s){super(t,{username:r,accessKey:s})}async upsertVariable(t){let r=t.environmentId??0,s=await fetch(`${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(s.ok)return{id:(await s.json()).id??0};if(s.status!==409&&s.status!==422)return{id:0};if(!(await fetch(`${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 n=await fetch(`${this.baseUrl}/v1/variables/${encodeURIComponent(t.name)}?environment_id=${r}`,{method:"GET",headers:this.headers()});return n.ok?{id:(await n.json()).data?.id??0}:{id:0}}};import{readdirSync as ze,readFileSync as ge,existsSync as he}from"fs";import{join as Ye}from"path";function pe(e,t){if(!he(e))return{};let r={},s;try{s=ze(e).filter(o=>o.endsWith(".json")).sort()}catch{return{}}for(let o of s)try{let n=ge(Ye(e,o),"utf-8"),i=JSON.parse(n);if(i&&typeof i=="object"){for(let[a,c]of Object.entries(i))if(c&&typeof c=="object"&&"value"in c){let l=c;r[a]={value:l.value,secret:l.secret??!1,syntax:l.syntax??`{{${a}}}`}}}}catch{t?t("warn","VARIABLE_PARSE_FAILED","Skipping invalid variables file",{file:o}):process.stderr.write(`[variables] Warning: skipping invalid variables file: ${o}
5
+ `)}return r}function be(e){if(!he(e))throw new Error(`Variables file not found: ${e}`);let t=ge(e,"utf-8"),r=JSON.parse(t),s={};if(r&&typeof r=="object"){for(let[o,n]of Object.entries(r))if(n&&typeof n=="object"&&"value"in n){let i=n;s[o]={value:i.value,secret:i.secret??!1,syntax:i.syntax??`{{${o}}}`}}}return s}function ye(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Invalid --variables JSON")}let r={};if(t&&typeof t=="object"){for(let[s,o]of Object.entries(t))if(o&&typeof o=="object"&&"value"in o){let n=o;r[s]={value:n.value,secret:n.secret??!1,syntax:n.syntax??`{{${s}}}`}}}return r}function we(e,t,r){let s=pe(e,r),o=pe(t,r);return{...s,...o}}function Cr(e,t){if(Object.keys(e).length===0)return{};let r={};for(let[s,o]of Object.entries(e)){let n=o.syntax??`{{${s}}}`;t.includes(n)&&(r[s]=o)}return r}function xr(e){let t=we(e.globalDir,e.localDir,e.onLoadError),r=e.file?be(e.file):{},s=e.inline?ye(e.inline):{},o={...t,...r,...s},n=Object.keys(o).length>0,{variables:i,objective:a}=n?fe(o,e.objective):{variables:{},objective:e.objective},c=Object.entries(o).filter(([,d])=>d.secret),l=Object.entries(o).filter(([,d])=>!d.secret);return{raw:o,auteur:i,auteurObjective:a,secretEntries:c,nonSecretEntries:l}}async function kr(e){if(e.localMode)return{};let t=k(e.env);if(e.variables.secretEntries.length>0){let s=new $(t.secretsBaseUrl);for(let[o,n]of e.variables.secretEntries)s.pushSecret({secretKey:o,secretValue:n.value,username:e.auth.username,accessKey:e.auth.access_key,orgId:e.orgId}).then(()=>e.log("info","SECRET_PUSH_OK","Secret pushed",{key:o})).catch(i=>e.log("error","SECRET_PUSH_FAILED","Secret push failed",{key:o,error:String(i)}))}let r={};if(e.variables.nonSecretEntries.length>0){let s=new N(t.tmsBaseUrl,e.auth.username,e.auth.access_key);for(let[o,n]of e.variables.nonSecretEntries)try{let i=await s.upsertVariable({name:o,value:n.value});r[o]=i.id,e.log("info","VAR_PUSH_OK","Variable pushed",{name:o,id:i.id})}catch(i){e.log("error","VAR_PUSH_FAILED","Variable push failed",{name:o,error:String(i)})}}return r}function Pr(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.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.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),t}var Qe=15e3,W=3,Se=[500,1e3];async function Tr(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 U(t,{from_commit_id:e.fromCommitId,new_commit_id:e.newCommitId},e.auth);return r.ok?{ok:!0,sessionExpiresAt:y(r.body,"session_expires_at")??""}:{ok:!1,...Xe(r)}}function Xe(e){let t=y(e.body,"error")??y(e.body,"code")??"",r=y(e.body,"message")??y(e.body,"detail")??e.text??`HTTP ${e.status}`,s;return e.status===0?s="network":e.status===401||e.status===403?s="auth":e.status===409&&t==="PlaygroundBaseCommitMismatch"?s="base_mismatch":e.status===409?s="concurrent":e.status===422?s="disabled":e.status===400&&/no committed/i.test(r)?s="no_commits":e.status===400?s="missing_field":e.status>=500||e.status===408||e.status===429?s="network":s="other",{reason:s,httpStatus:e.status,message:r}}async function Or(e){let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/playground/reserve`,r=await U(t,void 0,e.auth);return r.ok?{ok:!0,sessionExpiresAt:y(r.body,"session_expires_at")??""}:{ok:!1,expired:r.status===404,httpStatus:r.status,message:y(r.body,"message")??y(r.body,"detail")??r.text??`HTTP ${r.status}`}}async function ve(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 s=await U(t,r,e.auth);return s.ok?{ok:!0,testId:y(s.body,"test_id")??e.testId,testcaseId:y(s.body,"testcase_id")??"",projectId:y(s.body,"project_id"),isTestCaseDeleted:typeof s.body?.is_test_case_deleted=="boolean"?s.body.is_test_case_deleted:void 0}:{ok:!1,...Ze(s)}}function Ze(e){let t=y(e.body,"error")??y(e.body,"code")??"",r=y(e.body,"message")??y(e.body,"detail")??e.text??`HTTP ${e.status}`,s;return e.status===0?s="network":e.status===401||e.status===403?s="auth":e.status===409&&t==="PlaygroundBaseCommitMismatch"?s="base_mismatch":e.status===409&&t==="PlaygroundCommitLockMismatch"?s="lock_mismatch":e.status===409?s="expired":e.status===422?s="not_found":e.status>=500||e.status===408||e.status===429?s="network":s="other",{reason:s,httpStatus:e.status,message:r}}async function Dr(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},s=await U(t,r,e.auth);return s.ok?{ok:!0}:{ok:!1,reason:y(s.body,"error")??"other",httpStatus:s.status,message:y(s.body,"message")??y(s.body,"detail")??s.text??`HTTP ${s.status}`}}async function U(e,t,r){let s=null;for(let o=1;o<=W;o++){let n=new AbortController,i=setTimeout(()=>n.abort(),Qe);try{let a=await fetch(e,{method:"POST",headers:{Authorization:O(r.username,r.accessKey),"Content-Type":"application/json",Accept:"application/json"},...t!==void 0?{body:JSON.stringify(t)}:{},signal:n.signal});clearTimeout(i);let c=await a.text(),l=null;if(c)try{l=JSON.parse(c)}catch{}let d=a.status>=500||a.status===408||a.status===429;if(a.ok||!d)return{ok:a.ok,status:a.status,body:l,text:c};if(o<W){await _e(Se[o-1]??1e3);continue}return{ok:!1,status:a.status,body:l,text:c}}catch(a){if(clearTimeout(i),s=a,o<W){await _e(Se[o-1]??1e3);continue}}}return{ok:!1,status:0,body:null,text:s?.message??"exhausted retries"}}function _e(e){return new Promise(t=>setTimeout(t,e))}function y(e,t){if(typeof e!="object"||e===null)return;let r=e[t];return typeof r=="string"?r:void 0}import{readFileSync as Oe,writeFileSync as De,existsSync as Le}from"fs";import{mkdirSync as Q,writeFileSync as _t}from"fs";import{join as x}from"path";import{createHash as et}from"crypto";function z(e){if(e==null)return null;if(Array.isArray(e))return e.map(z);if(typeof e=="object"){let t={};for(let r of Object.keys(e).sort()){let s=e[r];s!==void 0&&(t[r]=z(s))}return t}return e}function tt(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},r=JSON.stringify(z(t));return et("md5").update(e.body.text).update(`
6
+ `).update(r).digest("hex")}function F(e){return tt({index:e.trace[e.trace.length-1].stepIndex,heading:e.trace[e.trace.length-1].heading,body:{kind:"objective",text:e.objective},config:e.parsedConfig,headingLine:1,optional:e.optional})}import{copyFileSync as rt,existsSync as st,mkdirSync as ot,writeFileSync as nt}from"fs";import{join as E}from"path";function Ie(e){for(let t=0;t<e.totalRunDirs;t++){let r=e.runIndex+t,s=E(e.sessionDir,"runs",String(r)),o=E(e.stagingStepDir,"flows",String(t));ot(o,{recursive:!0});let n=[E(s,"run-test","actions.ndjson"),E(s,"actions.ndjson")],i=E(o,"actions.ndjson"),a=!1;for(let c of n)if(st(c)){rt(c,i),a=!0;break}a||nt(i,"")}}import{basename as it,dirname as at,join as ct}from"path";function Re(e){let t=it(e);return t.endsWith("_test.md")?t.slice(0,-8):t.endsWith(".md")?t.slice(0,-3):t}function lt(e){if(e.length<2)throw new Error("helperOutputDirName requires trace length >= 2 (root + at least one helper)");let t=Re(e[0].file),r=Re(e[e.length-1].file),s=e.slice(0,-1).map(o=>String(o.stepIndex));return`helper-output-${r}-${t}-${s.join("-")}`}function C(e){if(e.length<2)throw new Error("helperOutputDirPath requires trace length >= 2");let t=e[e.length-1].file;return ct(at(t),lt(e))}import{readFileSync as bt}from"fs";import{join as yt,relative as wt}from"path";var b=class extends Error{constructor(r,s,o){super(`[${s}${o!=null?`:${o}`:""}] ${r}`);this.file=s;this.line=o;this.name="TestMdParseError"}},dt=new Set(["username","access_key","oauth","profile","project_id","folder_id"]),Ce=new Set(["mode","max_steps","timeout","global_context","local_context","variables","session_context","code_export","code_language","target","chrome_profile","cdp_endpoint","ws_endpoint","headless","on_lock_conflict"]),Y=new Set(["optional"]),ut=new Set(["target","chrome_profile","cdp_endpoint","ws_endpoint","headless"]),mt=new Set(["mode","on_lock_conflict"]);function xe(e,t){let r=t.split(`
7
+ `),{global:s,bodyStartLine:o}=ft(e,r),{title:n,steps:i}=pt(e,r,o);return{path:e,title:n,global:s,steps:i}}function ft(e,t){if(t[0]?.trim()!=="---")return{global:{},bodyStartLine:0};let r=-1;for(let n=1;n<t.length;n++)if(t[n].trim()==="---"){r=n;break}if(r===-1)throw new b("frontmatter is missing closing '---'",e,1);let s=t.slice(1,r).join(`
8
+ `),o;try{o=K(s)??{}}catch(n){throw new b(`invalid YAML in frontmatter: ${n.message}`,e,1)}if(Ee(e,o,"frontmatter",1),o.on_lock_conflict!==void 0){let n=o.on_lock_conflict;if(n!=="readonly"&&n!=="fail"&&n!=="wait")throw new b(`on_lock_conflict must be 'readonly' | 'fail' | 'wait', got: ${JSON.stringify(n)}`,e,1)}return ke(e,o,1),{global:o,bodyStartLine:r+1}}function pt(e,t,r){let s,o=r;for(;o<t.length&&t[o].trim()==="";)o++;let n=o<t.length?/^#\s+(.+?)\s*$/.exec(t[o]):null;n&&(s=n[1],o++);let i=[];for(let c=o;c<t.length;c++)/^##\s/.test(t[c])&&i.push(c);let a=[];for(let c=0;c<i.length;c++){let l=i[c],d=i[c+1]??t.length,u=t[l].replace(/^##\s+/,"").trim(),f=t.slice(l+1,d),{config:m,body:p,optional:g}=gt(e,l+1,f);a.push({index:c+1,heading:u,config:m,body:p,headingLine:l+1,optional:g})}return{title:s,steps:a}}function gt(e,t,r){let s=0;for(;s<r.length&&r[s].trim()==="";)s++;let o,n=t;if(s<r.length&&/^```yaml\s*$/.test(r[s])){let m=s;n=t+m,s++;let p=-1;for(;s<r.length;){if(/^```\s*$/.test(r[s])){p=s;break}s++}if(p===-1)throw new b("step-config fenced ```yaml block is not closed",e,n);let g=r.slice(m+1,p).join(`
9
+ `);try{o=K(g)??{}}catch(w){throw new b(`invalid YAML in step config: ${w.message}`,e,n)}s=p+1}let i=ht(r.slice(s)),a=i.filter(m=>m.trim()!=="");if(a.length>0&&/^@session\s+/.test(a[0].trim()))throw new b("@session is no longer supported (iteration 3); use @import instead",e,t);let c=/^@import\s+(\S.*)$/,d=i.filter(m=>c.test(m.trim())).length>0;if(d&&a.length!==1)throw new b("step body must be exactly one of prose / @import",e,t);let u=!1,f;if(o){if(Ee(e,o,d?"step config (ref)":"step config (objective)",n),d||ke(e,o,n),typeof o.optional=="boolean")u=o.optional;else if(o.optional!==void 0)throw new b(`step config 'optional' must be boolean: got ${typeof o.optional}`,e,n);let m={...o};delete m.optional,Object.keys(m).length>0&&(f=m)}return d?{body:{kind:"import_ref",path:c.exec(a[0].trim())[1].trim()},optional:u}:{body:{kind:"objective",text:i.join(`
10
+ `).trim()},config:f,optional:u}}function ht(e){let t=0,r=e.length;for(;t<r&&e[t].trim()==="";)t++;for(;r>t&&e[r-1].trim()==="";)r--;return e.slice(t,r)}function ke(e,t,r){let s=t.variables;if(s==null)return;if(typeof s!="object"||Array.isArray(s))throw new b("variables must be an object map",e,r);let o={};for(let[n,i]of Object.entries(s))if(typeof i=="string")o[n]={value:i};else if(i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.value=="string")o[n]=i;else throw new b(`variable '${n}' must be a string or { value: ... } object`,e,r);t.variables=o}function Ee(e,t,r,s){for(let o of Object.keys(t)){if(dt.has(o))throw new b(`auth/identity keys are CLI-only: ${o}`,e,s);if(r==="frontmatter"){if(Y.has(o))throw new b(`step-only key in frontmatter: ${o}`,e,s);if(!Ce.has(o))throw new b(`unknown config key: ${o}`,e,s)}else if(r==="step config (objective)"){if(!Ce.has(o)&&!Y.has(o))throw new b(`unknown config key: ${o}`,e,s);if(ut.has(o))throw new b(`chrome config is global-only: ${o}`,e,s);if(mt.has(o))throw new b(`'${o}' is run-level and cannot be set per-step`,e,s)}else if(!Y.has(o))throw new b(`step config on @import may only contain 'optional': got ${o}`,e,s)}}function je(e){let t=St(e.resolvedTest,e.runByStep),r=new Map;for(let s of t.values()){let o=r.get(s.helperFile);o||(o=xe(s.helperFile,bt(s.helperFile,"utf8")),r.set(s.helperFile,o));let n=[],i=!1;for(let c of o.steps){let l=c.index,d=s.resolvedSteps.filter(m=>m.trace[s.helperDepth].stepIndex===l);if(d.length===0){n.push({rootStepIndex:l,status:"skipped"});continue}let u=d[0].trace[0].stepIndex,f=e.outcomes.find(m=>m.rootStepIndex===u);if(!f){n.push({rootStepIndex:l,status:"skipped"});continue}if(c.body.kind==="objective"){let m=d[0],p=Pe(m,f);p==="failed"&&(i=!0);let g={rootStepIndex:l,status:p};p==="passed"&&(g.stepMd5=F(m)),n.push(g)}else{let m=!1,p=!1;for(let T of d){let S=Pe(T,f);S!=="skipped"&&(p=!0),S==="failed"&&(m=!0)}let g=m?"failed":p?"passed":"skipped";g==="failed"&&(i=!0);let w=C(d[0].trace.slice(0,s.helperDepth+2)),I=wt(s.finalDir,w);n.push({rootStepIndex:l,status:g,refKind:"import",refLabel:c.body.path,inlinedCount:d.length,helperResultRelPath:`${I}/Result.md`})}}let a=i?"failed":"passed";L({sourcePath:s.helperFile,title:o.title,rootSteps:o.steps,outcomes:n,overallStatus:a,startedISO:e.startedISO,durationS:0,sessionId:e.sessionId,outPath:yt(s.stagingDir,"Result.md")})}}function St(e,t){let r=new Map;for(let s of e.steps)if(t.has(s.flatIndex))for(let o=1;o<s.trace.length;o++){let n=s.trace.slice(0,o+1),i=C(n),a=r.get(i);a||(a={stagingDir:`${i}.staging`,finalDir:i,helperFile:n[o].file,helperDepth:o,resolvedSteps:[]},r.set(i,a)),a.resolvedSteps.push(s)}return r}function Pe(e,t){if(t.status==="passed")return"passed";if(t.status==="skipped")return"skipped";let r=e.trace.slice(1).map(n=>n.stepIndex),s=t.failedSubStepIndex??[],o=Math.min(r.length,s.length);for(let n=0;n<o;n++)if(r[n]!==s[n])return r[n]<s[n]?"passed":"skipped";return r.length===s.length?"failed":r.length<s.length?"passed":"skipped"}function Ae(e){let t=ie(e.resolvedTest.rootPath);Q(x(t,".internal"),{recursive:!0});let r=new Map;for(let o of e.stepRunRecords)r.set(o.testmdStepIndex,o);for(let o of e.resolvedTest.steps){let n=r.get(o.flatIndex);if(!n)continue;let i=o.trace[o.trace.length-1].stepIndex,a=F(o),c=a.slice(0,8),l;if(o.trace.length===1)l=x(t,".internal","steps",`${i}-${c}`);else{let d=`${C(o.trace)}.staging`;Q(x(d,".internal"),{recursive:!0}),l=x(d,".internal","steps",`${i}-${c}`)}if(Q(l,{recursive:!0}),Ie({sessionDir:e.sessionDir,runIndex:n.runIndex,totalRunDirs:n.totalRunDirs,stagingStepDir:l}),o.trace.length===1){let d=o.trace[0].stepIndex,u=e.outcomes.find(f=>f.rootStepIndex===d);u&&u.stepMd5==null&&(u.stepMd5=a)}}je({resolvedTest:e.resolvedTest,outcomes:e.outcomes,startedISO:e.startedISO,sessionId:e.sessionId,runByStep:r}),L({sourcePath:e.resolvedTest.rootPath,title:e.resolvedTest.rootTitle,rootSteps:e.resolvedTest.rootSteps,outcomes:e.outcomes,overallStatus:e.overallStatus,startedISO:e.startedISO,durationS:e.durationS,sessionId:e.sessionId,outPath:x(t,"Result.md")});let s={};if(e.commitId&&(s.commit_id=e.commitId),e.tmsIds.testId&&(s.test_id=e.tmsIds.testId),e.tmsIds.testcaseId&&(s.testcase_id=e.tmsIds.testcaseId),e.tmsIds.projectId&&(s.project_id=e.tmsIds.projectId),e.tmsIds.folderId&&(s.folder_id=e.tmsIds.folderId),e.tmsIds.orgId&&(s.org_id=e.tmsIds.orgId),e.tmsIds.sessionName&&(s.session_name=e.tmsIds.sessionName),_t(x(t,".internal","meta.json"),JSON.stringify(s,null,2)+`
11
+ `,"utf8"),e.codeExportDir){let o=e.codeExportLanguage??"python",n=x(t,`playwright-${o}-code`);try{ae(e.codeExportDir,n)}catch(i){process.stderr.write(`warn: codegen copy failed: ${i.message}
12
+ `)}}}function Te(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 s=[];for(let i=0;i<t.length;i++){let a=t[i];if(!a||a.kind!=="author"||a.reason==="downstream-of-divergence"||a.reason==="no-result-md")continue;let c=vt(e,e.steps[i]);switch(a.reason){case"structure-mismatch":s.push(`added/removed: ${c}`);break;case"md5-mismatch":s.push(`modified: ${c}`);break;case"missing-recording":s.push(`re-recorded: ${c}`);break;case"recorded-failed":s.push(`re-authored after failure: ${c}`);break}}if(s.length===0)return"automated commit";let o=s.filter((i,a)=>a===0||s[a-1]!==i),n=o.slice(0,3).join("; ");return o.length>3?`${n}; +${o.length-3} more`:n}function vt(e,t){if(!t)return"unknown step";let r=t.trace[0]?.stepIndex;if(r==null)return"unknown step";let o=e.rootSteps[r-1]?.heading?.trim()??"";return t.trace.length>1?o?`imported step in "${o}"`:`imported step ${r}`:o||`step ${r}`}function It(e){if(!(!e.shouldReplaceLocalOutput||!e.resolvedTest||!e.sourcePath||!e.stepRunRecords||!e.outcomes||!e.overallStatus))return async()=>{Ae({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}),q(ne(e.sourcePath));let t=new Set;for(let r of e.resolvedTest.steps)if(r.trace.length>1){let s=C(r.trace);if(t.has(s))continue;t.add(s),Le(`${s}.staging`)&&q(s)}}}function Rt(e){if(!(!e.shouldCommit||e.isFirstRun||!e.tmsBaseUrl||!e.testId||!e.fromCommitId||!e.newCommitId||!e.basicAuth||!e.resolvedTest||!e.decisions))return async()=>{let t=Te(e.resolvedTest,e.decisions,{wantsPush:e.wantsPush??!1,retryTriggered:e.retryTriggered??!1,forceAuthor:e.forceAuthor??!1}),r=e.resolvedTest.steps.map(o=>o.objective).filter(o=>typeof o=="string"&&o.length>0).slice(0,50),s=await ve({baseUrl:`${e.tmsBaseUrl}/kane-cli/v1`,testId:e.testId,body:{commitId:e.newCommitId,fromCommitId:e.fromCommitId,commitMessage:t,totalSteps:e.resolvedTest.steps.length,timeTaken:Math.round(e.durationS??0),objectives:r},auth:{username:e.basicAuth.username,accessKey:e.basicAuth.access_key}});if(s.ok&&e.sourcePath){let o=J(e.sourcePath);try{let n=JSON.parse(Oe(o,"utf8"));n.commit_id=e.newCommitId,De(o,JSON.stringify(n,null,2)+`
13
+ `,"utf8")}catch(n){process.stderr.write(`warn: failed to update meta.json commit_id: ${n.message}
14
+ `)}}return s}}function Ct(e){if(!(!e.isFirstRun||!e.sourcePath))return async t=>{if(!e.sourcePath)return;let r=J(e.sourcePath);try{let s=Le(r)?JSON.parse(Oe(r,"utf8")):{};e.session.sessionId&&(s.commit_id=e.session.sessionId),t&&(s.testcase_id=t),e.tmsIds?.testId&&(s.test_id=e.tmsIds.testId),e.tmsIds?.projectId&&(s.project_id=e.tmsIds.projectId),e.tmsIds?.folderId&&(s.folder_id=e.tmsIds.folderId),e.tmsIds?.orgId&&(s.org_id=e.tmsIds.orgId),e.tmsIds?.sessionName&&(s.session_name=e.tmsIds.sessionName),De(r,JSON.stringify(s,null,2)+`
15
+ `,"utf8")}catch(s){process.stderr.write(`warn: failed to update meta.json after endTest: ${s.message}
16
+ `)}}}function bs(e){let t=k(e.env),{session:r,auth:s}=e,o=s.basicAuth?{username:s.basicAuth.username,accessKey:s.basicAuth.access_key}:s.token,n=s.resolvedCreds?.username??s.basicAuth?.username??"",i=s.resolvedCreds?.access_key??s.basicAuth?.access_key??"",a=s.resolvedCreds?.org_id??0,c=s.resolvedCreds?.user_id??0,l=[];for(let p of Object.keys(r.auteurVariables))p.startsWith("secrets.user.")&&l.push({key_name:p.replace("secrets.user.",""),scope:"user"});let u=r.getContext().prior_runs.map(p=>p.status),f=r.auteurVariables,m=Object.keys(f).length>0;return{controllerBaseUrl:t.controllerBaseUrl,tmsBaseUrl:t.tmsBaseUrl,auth:o,authResolver:s.resolver,sessionId:r.sessionId,sessionDir:r.sessionDir,testId:r.testId,commitId:r.sessionId,projectId:e.projectId,folderId:e.folderId,firstObjective:r.firstObjective??"KaneAI Test",firstUrl:r.firstUrl??"",runDirs:r.getRunDirs(),runObjectives:r.getRunObjectives(),runMetadata:r.getRunMetadata(),startedAt:r.startedAt,endedAt:new Date().toISOString(),totalSteps:e.totalSteps,totalDuration:e.totalDuration,runStatuses:u,orgId:a,userId:c,tmsUsername:n,tmsAccessKey:i,screenshotBaseUrl:r.screenshotBaseUrl,shareApiBaseUrl:t.shareApiBaseUrl,variables:m?f:void 0,variableIds:e.variableIds,secrets:l,codeExport:e.codeExport,onProgress:e.onProgress,log:e.log,shouldUploadArtifacts:e.shouldUploadArtifacts,shouldReplaceLocalOutput:e.shouldReplaceLocalOutput,shouldCommit:e.shouldCommit,isFirstRun:e.isFirstRun,onAtomicReplace:It(e),onCommitLock:Rt(e),onFinalizeSuccess:Ct(e)}}var $e=["python","javascript"];function xt(e){if(e!==void 0){if(!$e.includes(e))throw new Error(`--code-language must be one of: ${$e.join(", ")} (got "${e}")`);return e}}function ws(e,t){let r=xt(e.codeLanguage);return{enabled:e.codeExport??t.enabled,language:r??t.language,skipValidation:e.skipCodeValidation??t.skip_validation}}async function vs(e){try{let r=await new D(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}}import{mkdtempSync as Nt,rmSync as Ut}from"fs";import{join as Ft}from"path";import{tmpdir as Mt}from"os";import{spawn as Ne,spawnSync as kt}from"child_process";import{existsSync as X}from"fs";import{createConnection as Et}from"net";import{homedir as P,platform as A}from"os";import{join as j}from"path";var Pt=new Set(["1","true","yes"]),M=class extends Error{constructor(t){super(t),this.name="ChromeNotFoundError"}};function As(e){return e instanceof M?e.message:`Chrome failed: ${e instanceof Error?e.message:String(e)}`}var V={darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",j(P(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),"/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",j(P(),"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",j(P(),"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",j(P(),"AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"),"C:\\chrome-for-testing\\chrome-win64\\chrome.exe",j(P(),"AppData\\Local\\chrome-for-testing\\chrome-win64\\chrome.exe")]};function jt(){if(process.env.KANE_CLI_CHROME_PATH)return process.env.KANE_CLI_CHROME_PATH;let e=A(),t=V[e]??V.linux;for(let r of t)if(X(r))return r;return e==="win32"?"chrome.exe":"google-chrome"}function At(){if(process.env.KANE_CLI_CHROME_PATH)return X(process.env.KANE_CLI_CHROME_PATH);let e=A();if((V[e]??V.linux).some(o=>X(o)))return!0;let r=e==="win32"?"chrome.exe":"google-chrome",s=e==="win32"?"where":"which";try{return kt(s,[r],{stdio:"ignore"}).status===0}catch{return!1}}function Tt(){let e=A();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(`
17
+ `):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(`
18
+ `):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(`
19
+ `):["Google Chrome is required.","Install from https://www.google.com/chrome/","(Note: no official Chrome builds for BSD or Alpine/musl Linux.)"].join(`
20
+ `)}function Ot(e){let t=A(),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 Dt(e){return new Promise(t=>{let r=Et({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 Lt(){for(let e=B;e<=H;e++)if(!await Dt(e))return e;throw new Error(`All CDP ports ${B}-${H} are in use. Close other Chrome instances.`)}async function $t(e,t=15e3){let r=Date.now(),s=`http://127.0.0.1:${e}/json/version`;for(;Date.now()-r<t;){try{if((await fetch(s)).ok)return`http://127.0.0.1:${e}`}catch{}await new Promise(o=>setTimeout(o,200))}throw new Error(`Chrome CDP not ready after ${t}ms on port ${e}`)}async function Ue(e){let t=process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD;if(!(t!=null&&Pt.has(t.toLowerCase()))&&!At())throw re()?.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 M(Tt());let s=A(),o=await Lt(),n=jt(),i=Ot({port:o,...e});e.startUrl&&i.push(e.startUrl);let a=Ne(n,i,{stdio:"ignore",detached:!0,windowsHide:!0});a.unref();let c=await new Promise((l,d)=>{a.on("error",u=>{d(new Error(`Failed to launch Chrome: ${u.message}. Is Chrome installed at ${n}?`))}),a.on("close",u=>{u!==null&&u!==0&&d(new Error(`Chrome exited during startup with code ${u}`))}),$t(o).then(l,d)});return{process:a,port:o,cdpEndpoint:c,kill(){try{if(a.pid)if(s==="win32")Ne("taskkill",["/pid",String(a.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-a.pid,"SIGKILL")}catch{a.kill("SIGKILL")}else a.kill("SIGKILL")}catch{}}}}async function Us(e){if(e.cft)return{instance:null,tempDir:null};if(e.wsEndpoint)return{wsEndpoint:e.wsEndpoint,instance:null,tempDir:null};if(e.cdpEndpoint){let o=await fetch(`${e.cdpEndpoint}/json/version`);if(!o.ok)throw new Error(`CDP endpoint not reachable: ${e.cdpEndpoint} (${o.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=Nt(Ft(Mt(),"kane-clean-")),t=r;let o=r;se("tempDir",()=>{try{Ut(o,{recursive:!0,force:!0})}catch{}})}let s=await Ue({userDataDir:t,width:e.config.window_size.width,height:e.config.window_size.height,startUrl:e.startUrl,headless:e.headless});return{cdpEndpoint:s.cdpEndpoint,instance:s,tempDir:r}}var Vt="KaneAI Generated",Bt="Untitled";async function Hs(e){let t=e.config.load(),r=new D(k(e.env).tmsBaseUrl,e.tmsCreds.username,e.tmsCreds.access_key),s=e.projectName??Vt,o=e.folderName??Bt,n=t.project_id??null,i=t.project_name??null;if(!n){let u=(await r.listProjects()).find(f=>f.name===s);if(u)n=u.project_id,i=u.name,e.log("info","ENSURE_PROJECT_FOUND","Found default project",{project_id:n,name:i});else{let f=await r.createProject(s);n=f.id,i=f.name,e.log("info","ENSURE_PROJECT_CREATED","Created default project",{project_id:n,name:i})}G(e.creds,e.config,e.profile,e.env,{projectId:n,projectName:i})}let a=t.folder_id??null,c=t.folder_name??null,l=!t.project_id;if(!a||l){let u=(await r.listFolders(n)).find(f=>f.name===o);if(u)a=u.id,c=u.name,e.log("info","ENSURE_FOLDER_FOUND","Found default folder",{folder_id:a,name:c});else{let f=await r.createFolder(n,o);a=f.id,c=f.name,e.log("info","ENSURE_FOLDER_CREATED","Created default folder",{folder_id:a,name:c})}G(e.creds,e.config,e.profile,e.env,{folderId:a,folderName:c})}return{projectId:n,projectName:i??s,folderId:a,folderName:c??o}}export{Kt as a,Gt as b,M as c,As as d,Ue as e,Xt as f,tr as g,sr as h,or as i,cr as j,me as k,fe as l,$ as m,N as n,Cr as o,xr as p,kr as q,Pr as r,F as s,C as t,xe as u,Tr as v,Or as w,Dr as x,bs as y,ws as z,vs as A,Us as B,Hs as C};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{s}from"./chunk-75XK2HKS.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost}}export{n as a};
2
+ import{s}from"./chunk-JYQO6G7F.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost}}export{n as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as f}from"./chunk-MH26PIS4.js";import{a as x}from"./chunk-HCBYKLMW.js";import{t}from"./chunk-JYQO6G7F.js";import{a as r,b as n}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as c}from"./chunk-UR6MHSHU.js";var p=c(B(),1);var e=c(x(),1);function v(){return[{name:"convert",label:"Converting session data",status:"pending"},{name:"zip",label:"Compressing artifacts",status:"pending"},{name:"presign",label:"Requesting upload URLs",status:"pending"},{name:"upload",label:"Uploading to KaneAI",status:"pending"},{name:"atomic_replace",label:"Replacing local output",status:"pending"},{name:"commit_lock",label:"Committing to TMS",status:"pending"},{name:"finalize",label:"Finalizing test case",status:"pending"},{name:"code_export",label:"Downloading test code",status:"pending"}]}function U(s,o,d,a){return s.map(l=>l.name===o?{...l,status:d,detail:a}:l)}function R(s){let o=s/1e3;if(o<60)return`${o.toFixed(1)}s`;let d=Math.floor(o/60),a=Math.round(o%60);return`${d}m ${a}s`}function D(s){let[o,d]=(0,p.useState)(0),a=p.default.useRef(Date.now());return(0,p.useEffect)(()=>{if(!s)return;a.current=Date.now();let l=setInterval(()=>{d(Date.now()-a.current)},100);return()=>clearInterval(l)},[s]),o}function h({steps:s,status:o,testUrl:d,error:a}){let l=D(o==="uploading");return o==="uploading"?(0,e.jsxs)(r,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,e.jsxs)(r,{children:[(0,e.jsx)(n,{color:t.primary,children:"\u2601 "}),(0,e.jsx)(n,{color:t.primary,bold:!0,children:"Saving to KaneAI"}),(0,e.jsxs)(n,{color:t.dimmed,children:[" ",R(l)]})]}),(0,e.jsx)(r,{flexDirection:"column",marginTop:1,children:s.filter(i=>i.status!=="skipped").map((i,S,T)=>{let b=S===T.length-1?"\u2514\u2500":"\u251C\u2500",m=i.status==="done",u=i.status==="running",g=i.status==="failed";return(0,e.jsxs)(r,{children:[(0,e.jsxs)(n,{color:t.dimmed,children:[" ",b," "]}),(0,e.jsx)(r,{width:3,children:u?(0,e.jsx)(f,{}):m?(0,e.jsx)(n,{color:t.green,children:"\u2713"}):g?(0,e.jsx)(n,{color:t.red,children:"\u2717"}):(0,e.jsx)(n,{color:t.muted,children:"\u25CB"})}),(0,e.jsx)(n,{color:m?t.dim:u?t.base:g?t.red:t.muted,children:i.label}),i.detail&&(0,e.jsxs)(n,{color:t.dimmed,children:[" ",i.detail]})]},i.name)})}),(0,e.jsx)(r,{marginTop:1,children:(0,e.jsx)(n,{color:t.muted,children:" press Ctrl+C twice to force exit"})})]}):o==="success"?(0,e.jsx)(e.Fragment,{}):(0,e.jsxs)(r,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,e.jsxs)(r,{children:[(0,e.jsx)(n,{color:t.red,children:"\u2601 "}),(0,e.jsx)(n,{color:t.red,bold:!0,children:"Save failed"})]}),a&&(0,e.jsxs)(r,{marginTop:0,children:[(0,e.jsx)(n,{color:t.dimmed,children:" "}),(0,e.jsx)(n,{color:t.dim,children:a})]})]})}export{v as a,U as b,h as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as u,g as f}from"./chunk-75XK2HKS.js";var o=class{config;buffer=[];stepBuffer=new Map;flushTimer=null;currentRunIndex=null;stopped=!1;_droppedBatches=0;_droppedEntries=0;constructor(e){this.config=e}start(){if(this.flushTimer)return;let e=this.config.flushIntervalMs??5e3;this.flushTimer=setInterval(()=>{this.flush().catch(()=>{})},e),this.flushTimer.unref&&this.flushTimer.unref()}setRunIndex(e){this.currentRunIndex=e}log(e,t,i,n={}){if(this.stopped)return;let r=this.buildEntry(e,t,i,n);this.buffer.push(r)}logStep(e,t,i,n={}){if(this.stopped)return;let r=this.buildEntry("debug",t,i,n);r.run_index=e,this.stepBuffer.has(e)||this.stepBuffer.set(e,[]),this.stepBuffer.get(e).push(r)}escalate(e){let t=this.stepBuffer.get(e);t&&t.length>0&&this.buffer.push(...t),this.stepBuffer.delete(e)}discardSteps(e){this.stepBuffer.delete(e)}async flush(){if(this.buffer.length===0)return;let e=this.buffer.splice(0),t=null;try{t=await this.config.getToken()}catch{this.buffer.unshift(...e);return}let i={"Content-Type":"application/json"};t&&(i.Authorization=`Bearer ${t}`);let n=JSON.stringify(e);for(let r=0;r<3;r++){try{let h=new AbortController,p=setTimeout(()=>h.abort(),1e4),d=await fetch(this.config.proxyUrl,{method:"POST",headers:i,body:n,signal:h.signal});if(clearTimeout(p),d.ok)return}catch{}r<2&&await new Promise(h=>setTimeout(h,1e3*Math.pow(2,r)))}this._droppedBatches++,this._droppedEntries+=e.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(e){return this.stepBuffer.get(e)?.length??0}buildEntry(e,t,i,n){return{hostname:"kane-cli",service:"kane-cli",ddsource:"kane-cli",ddtags:`env:${this.config.environment},version:${this.config.device.cli_version}`,level:e,event:t,message:i,session_id:this.config.sessionId,run_index:this.currentRunIndex,identity:this.config.identity,device:this.config.device,context:n,timestamp:new Date().toISOString()}}};import{platform as l,arch as g}from"os";function y(s){let e={proxyUrl:f,sessionId:s.sessionId,identity:s.identity,device:{cli_version:u,platform:l(),arch:g()},environment:s.environment,getToken:s.getToken};return new o(e)}export{o as a,y as b};
2
+ import{a as u,g as f}from"./chunk-JYQO6G7F.js";var n=class{config;buffer=[];stepBuffer=new Map;flushTimer=null;currentRunIndex=null;stopped=!1;_droppedBatches=0;_droppedEntries=0;constructor(e){this.config=e}start(){if(this.flushTimer)return;let e=this.config.flushIntervalMs??5e3;this.flushTimer=setInterval(()=>{this.flush().catch(()=>{})},e),this.flushTimer.unref&&this.flushTimer.unref()}setRunIndex(e){this.currentRunIndex=e}log(e,t,i,s={}){if(this.stopped)return;let r=this.buildEntry(e,t,i,s);this.buffer.push(r)}logStep(e,t,i,s={}){if(this.stopped)return;let r=this.buildEntry("debug",t,i,s);r.run_index=e,this.stepBuffer.has(e)||this.stepBuffer.set(e,[]),this.stepBuffer.get(e).push(r)}escalate(e){let t=this.stepBuffer.get(e);t&&t.length>0&&this.buffer.push(...t),this.stepBuffer.delete(e)}discardSteps(e){this.stepBuffer.delete(e)}async flush(){if(this.buffer.length===0)return;let e=this.buffer.splice(0),t=null;try{t=await this.config.getToken()}catch{this.buffer.unshift(...e);return}let i={"Content-Type":"application/json"};t&&(i.Authorization=`Bearer ${t}`);let s=JSON.stringify(e);for(let r=0;r<3;r++){try{let h=new AbortController,p=setTimeout(()=>h.abort(),1e4),d=await fetch(this.config.proxyUrl,{method:"POST",headers:i,body:s,signal:h.signal});if(clearTimeout(p),d.ok)return}catch{}r<2&&await new Promise(h=>setTimeout(h,1e3*Math.pow(2,r)))}this._droppedBatches++,this._droppedEntries+=e.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(e){return this.stepBuffer.get(e)?.length??0}buildEntry(e,t,i,s){return{hostname:"kane-cli",service:"kane-cli",ddsource:"kane-cli",ddtags:`version:${this.config.device.cli_version}`,level:e,event:t,message:i,session_id:this.config.sessionId,run_index:this.currentRunIndex,identity:this.config.identity,device:this.config.device,context:s,timestamp:new Date().toISOString()}}};import{platform as l,arch as g}from"os";function v(o){let e={proxyUrl:f,sessionId:o.sessionId,identity:o.identity,device:{cli_version:u,platform:l(),arch:g()},getToken:o.getToken};return new n(e)}export{n as a,v as b};
@@ -0,0 +1,3 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as Se}from"./chunk-66CVM7JL.js";import{f as ie}from"./chunk-G7VF5SDK.js";import{a as ae}from"./chunk-FJ6L63SP.js";import{b as Te}from"./chunk-G7I7EAV6.js";import{b as be}from"./chunk-75SVKFKD.js";import{a as we}from"./chunk-YCCUBQY4.js";import{a as re,b as oe,d as Ae}from"./chunk-VE3SUJMA.js";import{a as ve,b as ye}from"./chunk-QV2VR72Q.js";import{a as te}from"./chunk-NLYBR5FP.js";import{a as le}from"./chunk-PWGEMRBD.js";import{a as ee}from"./chunk-BSQVYLV7.js";import{a as Y}from"./chunk-HCBYKLMW.js";import{c as xe,t as v}from"./chunk-JYQO6G7F.js";import{a as w,b as g,h as pe,i as z,j as ge,k as he}from"./chunk-C44QQJR4.js";import{a as Z}from"./chunk-6YGTRKDT.js";import{a as fe}from"./chunk-YUUZDFT7.js";import{e as F}from"./chunk-UR6MHSHU.js";var C=F(Z(),1);var q=F(Z(),1);var de=F(Z(),1);var X=F(Y(),1);function Ee({history:c,onSelect:n,onClose:o}){let[d,h]=(0,de.useState)(""),[t,m]=(0,de.useState)(0),e=d?c.search(d).slice(0,8):[];return z((a,x)=>{if(x.escape){o();return}if(x.return){e.length>0&&e[t]?n(e[t]):o();return}if(x.upArrow){m(y=>Math.max(0,y-1));return}if(x.downArrow){m(y=>Math.min(e.length-1,y+1));return}if(x.backspace||x.delete){h(y=>y.slice(0,-1)),m(0);return}a&&!x.ctrl&&!x.meta&&(h(y=>y+a),m(0))}),(0,X.jsxs)(w,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,X.jsx)(g,{color:v.muted,bold:!0,children:"reverse search"}),(0,X.jsxs)(w,{gap:1,children:[(0,X.jsx)(g,{color:v.dimmed,children:"search:"}),(0,X.jsx)(g,{children:d}),(0,X.jsx)(g,{color:v.purple,children:"\u2588"})]}),e.length>0&&(0,X.jsx)(g,{children:" "}),e.map((a,x)=>(0,X.jsx)(w,{marginLeft:2,children:(0,X.jsxs)(g,{color:x===t?v.purple:v.dimmed,bold:x===t,children:[x===t?"\u25B8 ":" ",a]})},`${x}-${a}`))]})}var J=F(Y(),1);function Pe({commands:c,selectedIndex:n}){return c.length===0?null:(0,J.jsx)(w,{flexDirection:"column",marginBottom:0,children:c.map((o,d)=>{let h=d===n;return(0,J.jsxs)(w,{children:[(0,J.jsx)(g,{color:h?v.primary:v.dimmed,children:h?"\u276F ":" "}),(0,J.jsxs)(g,{color:h?v.primary:void 0,bold:h,children:["/",o.name]}),o.args&&(0,J.jsxs)(g,{color:v.dimmed,children:[" ",o.args]}),(0,J.jsxs)(g,{color:v.dimmed,children:[" ",o.description]})]},o.name)})})}var ce=F(Z(),1);var Me=27,ke=127,Oe=11;function je(c){return c>=64&&c<=126}function Fe(c,n){c===Oe&&n({killToEnd:!0,ctrl:!0,raw:String.fromCharCode(c)})}function Ke(c,n){c===ke&&n({backspace:!0,meta:!0,raw:"\x1B\x7F"})}function Ue(c,n){let o=c.map(h=>String.fromCharCode(h)).join(""),d=/^\[1;([0-9]+)([A-D])$/.exec(o);if(d){let h=parseInt(d[1],10),t=d[2],m={raw:"\x1B"+o};if(h===2)m.shift=!0;else if(h===3)m.meta=!0;else if(h===5)m.ctrl=!0;else return;t==="A"?m.arrowUp=!0:t==="B"?m.arrowDown=!0:t==="C"?m.arrowRight=!0:t==="D"&&(m.arrowLeft=!0),n(m);return}if(o==="[H"||o==="[1~"||o==="[7~"){n({home:!0,raw:"\x1B"+o});return}if(o==="[F"||o==="[4~"||o==="[8~"){n({end:!0,raw:"\x1B"+o});return}if(o==="[3;5~"){n({delete:!0,ctrl:!0,raw:"\x1B"+o});return}if(o==="[3;3~"){n({delete:!0,meta:!0,raw:"\x1B"+o});return}}function Ne(c,n){c===72?n({home:!0,raw:"\x1BO"+String.fromCharCode(c)}):c===70&&n({end:!0,raw:"\x1BO"+String.fromCharCode(c)})}function $e(){let c="IDLE",n=[];function o(){c="IDLE",n=[]}return{feed(d,h){for(let t of d)c==="IDLE"?t===Me?(c="ESC",n=[]):Fe(t,h):c==="ESC"?t===91?(c="CSI",n=[]):t===79?(c="SS3",n=[]):(Ke(t,h),o()):c==="CSI"?(n.push(t),je(t)&&(Ue([91,...n],h),o())):c==="SS3"&&(Ne(t,h),o())},flushIdle(d){c==="ESC"&&n.length===0&&d({raw:"\x1B"}),o()}}}function Ce(c,n={}){let o=(0,ce.useRef)(c);o.current=c;let{stdin:d}=pe();(0,ce.useEffect)(()=>{if(n.isActive===!1||!d)return;let h=$e(),t=null,m=e=>{t&&(clearTimeout(t),t=null);let a=Buffer.isBuffer(e)?e:Buffer.from(e,"binary");h.feed(a,x=>o.current(x)),t=setTimeout(()=>{h.flushIdle(x=>o.current(x)),t=null},50)};return d.on("data",m),()=>{d.removeListener("data",m),t&&clearTimeout(t)}},[n.isActive,d])}var L=F(Y(),1);function _e({onSubmit:c,onEscape:n,history:o,placeholder:d="Type an objective or /command...",commands:h}){let[t,m]=(0,q.useState)([]),[e,a]=(0,q.useState)(0),[x,y]=(0,q.useState)("none"),[D,E]=(0,q.useState)(-1),_=(0,q.useRef)(""),[I,Q]=(0,q.useState)(!0),{stdout:j}=he(),M=j?.columns??80,[N,$]=(0,q.useState)(0),R=t.join(""),G=(()=>{if(x!=="none"||t.length===0)return"";if(R.startsWith("/")&&h&&R.length>=2){let r=R.slice(1).toLowerCase(),i=h.find(S=>S.name.startsWith(r)&&S.name!==r);return i?`/${i.name}`.slice(R.length):""}if(R.startsWith("/"))return"";let l=o.getAll();for(let r=l.length-1;r>=0;r--)if(l[r].startsWith(R)&&l[r]!==R)return l[r].slice(R.length);return""})(),k=(()=>{if(!h||!R.startsWith("/"))return[];let l=R.length>=2?R.slice(1).toLowerCase():"";return l&&h.some(r=>r.name===l)?[]:h.filter(r=>!l||r.name.startsWith(l))})(),W=k.length>0&&R.startsWith("/");z((l,r)=>{if(I&&l&&Q(!1),r.return){if(W&&k[N]){let i=`/${k[N].name}`;o.push(i),c(i),m([]),a(0),y("none"),E(-1),_.current="",Q(!0),$(0);return}R.trim()&&(o.push(R.trim()),c(R.trim()),m([]),a(0),y("none"),E(-1),_.current="",Q(!0),$(0));return}if(r.escape){x!=="none"?y("none"):t.length>0?(m([]),a(0),E(-1),_.current=""):n?.();return}if(r.tab){if(W&&k[N]){let i=`/${k[N].name}`;m([...i]),a(i.length),$(0);return}if(G){let i=R+G;m([...i]),a(i.length);return}return}if(r.ctrl&&l==="r"){y("search");return}if(r.ctrl&&l==="a"){a(0);return}if(r.ctrl&&l==="e"){a(t.length);return}if(r.ctrl&&l==="w"){if(e===0)return;let i=e-1;for(;i>0&&t[i]===" ";)i--;for(;i>0&&t[i-1]!==" ";)i--;let S=[...t.slice(0,i),...t.slice(e)];m(S),a(i);return}if(r.ctrl&&l==="u"){m([]),a(0),E(-1),y("none");return}if(r.meta&&l==="b"){let i=e-1;for(;i>0&&t[i]===" ";)i--;for(;i>0&&t[i-1]!==" ";)i--;a(Math.max(0,i));return}if(r.meta&&l==="f"){let i=e;for(;i<t.length&&t[i]!==" ";)i++;for(;i<t.length&&t[i]===" ";)i++;a(i);return}if(r.leftArrow){if(r.ctrl||r.shift)return;a(i=>Math.max(0,i-1));return}if(r.rightArrow){if(r.ctrl||r.shift)return;if(e>=t.length&&G){let i=R+G;m([...i]),a(i.length)}else a(i=>Math.min(t.length,i+1));return}if(r.upArrow){if(r.shift)return;if(W){$(i=>Math.max(0,i-1));return}if(x==="none"){let i=o.getAll();if(i.length===0)return;if(D===-1){_.current=R,E(i.length-1);let S=i[i.length-1];m([...S]),a(S.length)}else if(D>0){let S=D-1;E(S);let O=i[S];m([...O]),a(O.length)}}return}if(r.downArrow){if(r.shift)return;if(W){$(i=>Math.min(k.length-1,i+1));return}if(x==="none"){let i=o.getAll();if(D===-1)return;if(D<i.length-1){let S=D+1;E(S);let O=i[S];m([...O]),a(O.length)}else{E(-1);let S=_.current;m([...S]),a(S.length)}}return}if(r.backspace||r.delete){if(r.meta||r.ctrl)return;if(e>0){let i=[...t.slice(0,e-1),...t.slice(e)];m(i),a(e-1),E(-1),$(0)}return}if(l&&!r.ctrl&&!r.meta){let i=[...t.slice(0,e),...l,...t.slice(e)];m(i),a(e+l.length),E(-1),$(0)}},{isActive:x!=="search"}),Ce(l=>{if(l.home){a(0);return}if(l.end){a(t.length);return}if(l.killToEnd){m(t.slice(0,e));return}if(l.arrowLeft&&(l.ctrl||l.meta)){let r=e-1;for(;r>0&&t[r]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;a(Math.max(0,r));return}if(l.arrowRight&&(l.ctrl||l.meta)){let r=e;for(;r<t.length&&t[r]!==" ";)r++;for(;r<t.length&&t[r]===" ";)r++;a(r);return}if(l.backspace&&l.meta){if(e===0)return;let r=e-1;for(;r>0&&t[r]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let i=[...t.slice(0,r),...t.slice(e)];m(i),a(r);return}if(l.delete&&(l.ctrl||l.meta)){let r=e;for(;r<t.length&&t[r]===" ";)r++;for(;r<t.length&&t[r]!==" ";)r++;m([...t.slice(0,e),...t.slice(r)]);return}},{isActive:x!=="search"});let ne=l=>{m([...l]),a(l.length),y("none")},U=()=>{y("none")},H=(()=>{if(I&&t.length===0)return null;let l=e>=t.length,r=t.slice(0,e).join(""),i=l?" ":t[e],S=l?"":t.slice(e+1).join(""),O="\u276F "+r+i+S+G,V=2,s=V+r.length,u=s+1,p=u+S.length,f=O.length,T=Math.max(1,Math.ceil(f/M)),P=[];for(let B=0;B<T;B++)P.push({start:B*M,end:Math.min((B+1)*M,f)});return{full:O,p:V,b:s,c:u,a:p,lines:P}})();return(0,L.jsxs)(w,{flexDirection:"column",children:[x==="search"&&(0,L.jsx)(Ee,{history:o,onSelect:ne,onClose:U}),W&&(0,L.jsx)(Pe,{commands:k,selectedIndex:N}),(0,L.jsx)(g,{color:v.muted,children:"\u2500".repeat(M)}),H===null?(0,L.jsxs)(w,{children:[(0,L.jsx)(g,{color:v.purple,children:"\u276F "}),(0,L.jsx)(g,{inverse:!0,children:" "}),(0,L.jsx)(g,{color:v.dimmed,children:d})]}):(0,L.jsx)(w,{flexDirection:"column",children:H.lines.map(({start:l,end:r},i)=>{let{full:S,p:O,b:V,c:s,a:u}=H,p=[];return r>0&&l<O&&p.push((0,L.jsx)(g,{color:v.purple,children:S.slice(Math.max(l,0),Math.min(O,r))},"p")),r>O&&l<V&&p.push((0,L.jsx)(g,{children:S.slice(Math.max(O,l),Math.min(V,r))},"b")),r>V&&l<s&&p.push((0,L.jsx)(g,{color:v.purple,inverse:!0,children:S.slice(Math.max(V,l),Math.min(s,r))},"c")),r>s&&l<u&&p.push((0,L.jsx)(g,{children:S.slice(Math.max(s,l),Math.min(u,r))},"a")),r>u&&p.push((0,L.jsx)(g,{color:v.dimmed,children:S.slice(Math.max(u,l),r)},"g")),(0,L.jsx)(w,{children:p},i)})}),(0,L.jsx)(ee,{bindings:[{keys:"\u2191\u2193",label:"history"},{keys:"\u21B5",label:"submit"},{keys:"tab",label:"complete"},{keys:"ctrl+r",label:"search"}],escBackLabel:"clear"})]})}var K=F(Z(),1);var b=F(Y(),1);function Ge(c){let n=[{id:"method",label:"Auth method",options:[{label:"Basic Auth",value:"basic"},{label:"OAuth (browser)",value:"oauth"}]}];return c&&n.push({id:"env",label:"Environment",options:[{label:"prod",value:"prod"},{label:"stage",value:"stage"}]}),n.push({id:"profile",label:"Profile"}),n.push({id:"credentials",label:"Credentials"}),n}function Re({devMode:c,profiles:n,onBasicLogin:o,onOAuthLogin:d,onComplete:h,onCancel:t}){let m=Ge(c),[e,a]=(0,K.useState)(0),[x,y]=(0,K.useState)(0),[D,E]=(0,K.useState)({}),[_,I]=(0,K.useState)("select"),[Q,j]=(0,K.useState)(""),[M,N]=(0,K.useState)("username"),[$,R]=(0,K.useState)(""),[G,k]=(0,K.useState)(null),[W,ne]=(0,K.useState)(null),U=m[e],H=D.method??"basic",l=D.env??"prod",r=(0,K.useCallback)(()=>{let f=n.filter(T=>T.env===l).map(T=>({label:`${T.profile} [${T.env}]`,value:T.profile}));return f.push({label:"+ Create new",value:"__new__"}),f},[n,l]),i=(0,K.useCallback)(()=>{e===0?t():(a(p=>p-1),y(0),I("select"),j(""),k(null))},[e,t]),S=(0,K.useCallback)(p=>{H==="basic"?(I("text-input"),N("username"),j("")):(I("waiting"),d(p,l).then(()=>{ne(`Logged in via OAuth as ${p} [${l}]`),I("done")}).catch(f=>{k(f.message),I("error")}))},[H,l,d]),O=(0,K.useCallback)(p=>{let f=p.trim();if(f){if(M==="profileName"){let T=f;E(P=>({...P,profile:T})),S(T);return}if(M==="username"){R(f),j(""),N("accessKey"),I("text-input-masked");return}if(M==="accessKey"){let T=D.profile??"default";I("waiting"),(async()=>{try{await o(T,l,$,f),ne(`Logged in as ${T} [${l}] via basic auth`),I("done")}catch{k("Credentials not valid. Please use valid credentials."),R(""),j(""),N("username"),I("text-input")}})()}}},[M,D.profile,l,o,$,S]),V=(0,K.useCallback)(p=>{j(p),G&&k(null)},[G]);z((p,f)=>{if(_==="done"){let P=D.profile??"default";h(P,l);return}if(_==="error"){t();return}if(_==="waiting"){f.escape&&t();return}if(_==="text-input"||_==="text-input-masked")return;if(f.escape){i();return}let T=U?.id==="profile"?r():U?.options??[];if(f.upArrow){y(P=>Math.max(0,P-1));return}if(f.downArrow){y(P=>Math.min(T.length-1,P+1));return}if(f.return&&T[x]){let P=T[x];if(U.id==="profile"){if(P.value==="__new__"){I("text-input"),N("profileName"),j("");return}E(B=>({...B,profile:P.value})),a(B=>B+1),y(0),S(P.value);return}E(B=>({...B,[U.id]:P.value})),a(B=>B+1),y(0)}});let s="Login";if(_==="done")return(0,b.jsxs)(w,{flexDirection:"column",borderStyle:"round",borderColor:v.statusPass,paddingX:2,paddingY:1,children:[(0,b.jsxs)(g,{color:v.statusPass,bold:!0,children:["\u2713 ",W]}),(0,b.jsx)(w,{marginTop:1,children:(0,b.jsx)(g,{color:v.dim,children:"press any key"})})]});if(_==="error")return(0,b.jsxs)(w,{flexDirection:"column",borderStyle:"round",borderColor:v.statusFail,paddingX:2,paddingY:1,children:[(0,b.jsx)(g,{color:v.statusFail,bold:!0,children:"Login failed"}),(0,b.jsx)(w,{marginTop:1,children:(0,b.jsx)(g,{color:v.statusFail,children:G})}),(0,b.jsx)(w,{marginTop:1,children:(0,b.jsx)(g,{color:v.dim,children:"press any key"})})]});if(_==="waiting")return(0,b.jsxs)(w,{flexDirection:"column",borderStyle:"round",borderColor:v.primary,paddingX:2,paddingY:1,children:[(0,b.jsxs)(g,{color:v.primary,bold:!0,children:[s," \u203A OAuth"]}),(0,b.jsx)(w,{marginTop:1,children:(0,b.jsx)(g,{color:v.secondary,children:"Opening browser for login..."})}),(0,b.jsx)(w,{marginTop:1,children:(0,b.jsx)(g,{color:v.primary,children:"Waiting for callback \u27F3"})}),(0,b.jsx)(ee,{bindings:[],escBackLabel:"cancel"})]});if(_==="text-input"||_==="text-input-masked"){let p=M==="username"?"Username":M==="accessKey"?"Access Key":"Profile name",f=M==="username"||M==="accessKey"?`${s} \u203A Basic Auth`:`${s} \u203A New Profile`;return(0,b.jsxs)(w,{flexDirection:"column",borderStyle:"round",borderColor:v.primary,paddingX:2,paddingY:1,children:[G&&(M==="username"||M==="accessKey")&&(0,b.jsx)(w,{marginBottom:1,children:(0,b.jsxs)(g,{color:v.statusFail,children:["\u2717 ",G]})}),(0,b.jsx)(g,{color:v.primary,bold:!0,children:f}),M==="accessKey"&&(0,b.jsxs)(w,{marginTop:1,children:[(0,b.jsx)(g,{color:v.secondary,children:"Username: "}),(0,b.jsx)(g,{children:$})]}),(0,b.jsxs)(w,{marginTop:1,children:[(0,b.jsxs)(g,{color:v.secondary,children:[p,": "]}),(0,b.jsx)(we,{value:Q,onChange:V,onSubmit:O,onCancel:i,masked:_==="text-input-masked"})]}),(0,b.jsx)(ee,{bindings:[{keys:"\u21B5",label:"confirm"}],escBackLabel:"back"})]})}let u=U?.id==="profile"?r():U?.options??[];return(0,b.jsxs)(w,{flexDirection:"column",borderStyle:"round",borderColor:v.primary,paddingX:2,paddingY:1,children:[(0,b.jsx)(g,{color:v.primary,bold:!0,children:s}),(0,b.jsx)(w,{marginTop:1,children:(0,b.jsxs)(g,{color:v.secondary,children:[U?.label,":"]})}),(0,b.jsx)(w,{flexDirection:"column",marginTop:1,children:u.map((p,f)=>{let T=f===x,P=T?"\u276F ":" ",B=p.value==="__new__"?v.statusPass:T?v.primary:void 0;return(0,b.jsxs)(g,{color:B,children:[P,p.label]},p.value)})}),(0,b.jsx)(ee,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}var Be=F(Z(),1);import{readFileSync as We,writeFileSync as He,mkdirSync as Ve}from"fs";import{dirname as Xe,join as Ye}from"path";var ze=Ye(xe,"command-history.json"),qe=200,me=class{entries;filePath;max;constructor(n=ze,o=qe){this.filePath=n,this.max=o,this.entries=this._load()}push(n){this.entries.length>0&&this.entries[this.entries.length-1]===n||(this.entries.push(n),this.entries.length>this.max&&(this.entries=this.entries.slice(this.entries.length-this.max)),this._save())}getAll(){return[...this.entries]}search(n){let o=n.toLowerCase(),d=[];for(let h=this.entries.length-1;h>=0;h--)this.entries[h].toLowerCase().includes(o)&&d.push(this.entries[h]);return d}_load(){try{let n=We(this.filePath,"utf-8"),o=JSON.parse(n);return Array.isArray(o)?o:[]}catch{return[]}}_save(){try{Ve(Xe(this.filePath),{recursive:!0}),He(this.filePath,JSON.stringify(this.entries)+`
3
+ `)}catch{}}};function De(c){let n=(0,Be.useRef)(null);return n.current||(n.current=new me(c)),n.current}async function ue(c,n,o,d){let h=c.loadBasicAuth(n,o),t=c.loadCredentials(n,o);if(!h&&!t)return d("info","STARTUP_GATE_NO_CREDS","Profile has no credentials",{profile:n,env:o}),{status:"needs_login",profile:n,env:o};let m=te(o),e=async()=>c.loadCredentials(n,o)?.access_token??null,a=new le(m.controllerBaseUrl,e,h,d);d("info","STARTUP_GATE_VALIDATE","Validating credentials with controller",{profile:n,env:o,method:h?"basic":"oauth"});let x=await a.resolve(!0);if(x)return d("info","STARTUP_GATE_VALID","Credentials validated",{profile:n,env:o,username:x.username,org_id:x.org_id}),{status:"authenticated",result:{profile:n,env:o,credentials:t,basicAuth:h,tmsCreds:x,resolver:a}};if(!h&&t){let y=t.refresh_token,E=c.loadClient(n,o)?.client_id;if(y&&E){d("info","STARTUP_GATE_REFRESH","Attempting token refresh",{profile:n,env:o});try{let I=await new ye(o).refreshToken(y,E);if(I.access_token){c.saveCredentials(n,o,{...t,...I,expires_at:Date.now()/1e3+(I.expires_in??3600)});let j=await a.resolve(!0);if(j)return d("info","STARTUP_GATE_REFRESH_OK","Token refreshed and validated",{profile:n,env:o,username:j.username}),{status:"authenticated",result:{profile:n,env:o,credentials:{...t,...I},basicAuth:null,tmsCreds:j,resolver:a}}}d("warn","STARTUP_GATE_REFRESH_INVALID","Refreshed token still invalid",{profile:n,env:o})}catch(_){d("warn","STARTUP_GATE_REFRESH_FAILED","Token refresh failed",{profile:n,env:o,error:_ instanceof Error?_.message:String(_)})}}else d("info","STARTUP_GATE_NO_REFRESH","No refresh_token or client_id \u2014 login required",{profile:n,env:o})}return d("info","STARTUP_GATE_INVALID","Credentials invalid \u2014 login required",{profile:n,env:o}),{status:"needs_login",profile:n,env:o}}async function Ie(c,n,o=new ae){let d=c.listProfiles();if(n("info","STARTUP_GATE_START","Auth startup gate",{profile_count:d.length}),d.length===0)return n("info","STARTUP_GATE_NONE","No profiles found \u2014 login required"),{status:"needs_login"};if(d.length>1){let m=c.getActiveProfile(),e=c.getDefaultEnv();if(m&&d.some(x=>x.profile===m&&x.env===e)){n("info","STARTUP_GATE_TRY_ACTIVE","Multiple profiles \u2014 trying active first",{activeProfile:m,activeEnv:e});let x=await ue(c,m,e,n);if(x.status==="authenticated")return x;n("info","STARTUP_GATE_ACTIVE_FAILED","Active profile invalid \u2014 showing picker",{activeProfile:m,activeEnv:e})}return n("info","STARTUP_GATE_MULTI","Multiple profiles \u2014 picker required",{profiles:d.map(a=>`${a.profile}/${a.env}`)}),{status:"needs_pick",profiles:d}}let{profile:h,env:t}=d[0];return c.setActiveProfile(h),c.setDefaultEnv(t),re(c,o,h,t),ue(c,h,t,n)}var A=F(Y(),1);function Vt({resultRef:c,mode:n="singleshot",loginCompleteRef:o}){let{exit:d}=ge(),h=(0,C.useRef)(new ve),t=(0,C.useRef)(new ae),m=(0,C.useRef)(new Se),e=h.current,a=t.current,x=m.current,y=De(),[D,E]=(0,C.useState)(n==="login"?"login":"gate"),[_,I]=(0,C.useState)(null),[Q,j]=(0,C.useState)(null),[M,N]=(0,C.useState)(null),[$,R]=(0,C.useState)(null),[G,k]=(0,C.useState)([]),W=(0,C.useCallback)((s,u,p,f)=>x.log(s,u,p,f),[x]),ne=(0,C.useCallback)((s,u)=>{s?re(e,a,s,u):a.save({project_id:null,project_name:null,folder_id:null,folder_name:null})},[e,a]),U=(0,C.useCallback)(()=>{n==="login"?(o&&(o.current=!0),d()):E("input")},[n,d,o]),H=(0,C.useCallback)((s,u)=>{let p=re(e,a,s,u);if(n==="login"){E("ensure-project");return}Ae(p)?U():p.projectId?E("ensure-folder"):E("ensure-project")},[e,a,U,n]);z((s,u)=>{u.ctrl&&s==="c"&&ie(0,"Ctrl+C exit")});let l=(0,C.useRef)(!1);C.default.useEffect(()=>{l.current||(l.current=!0,n!=="login"&&Ie(e,W).then(s=>{I(s),s.status==="authenticated"?H(s.result.profile,s.result.env):s.status==="needs_pick"?E("pick"):(j(s.profile??null),N(s.env??null),E("login"))}).catch(s=>{R(`Auth check failed: ${s instanceof Error?s.message:String(s)}`)}))},[e,W]);let r=(0,C.useCallback)(s=>{c.current={objective:s},d()},[c,d]),i=(0,C.useCallback)(async(s,u)=>{e.setActiveProfile(s),e.setDefaultEnv(u),(await ue(e,s,u,W)).status==="authenticated"?H(s,u):(j(s),N(u),E("login"))},[e,W,H]),S=(0,C.useCallback)(()=>{let s=e.getActiveProfile(),u=e.getDefaultEnv();if(!s)return null;let p=te(u),f=e.loadBasicAuth(s,u);return new le(p.controllerBaseUrl,async()=>e.loadCredentials(s,u)?.access_token??null,f,W)},[e,W]),O=(0,C.useCallback)(async()=>{let s=S();if(!s)return null;let u=s.cached??await s.resolve();if(!u)return null;let p=te(e.getDefaultEnv()),f=new fe(p.tmsBaseUrl,u.username,u.access_key);try{let P=(await f.listProjects()).find(se=>se.name==="KaneAI Generated");if(P)return{id:P.project_id,name:P.name};let B=await f.createProject("KaneAI Generated");return{id:B.id,name:B.name}}catch{return null}},[S,e]),V=(0,C.useCallback)(async s=>{let u=S();if(!u)return null;let p=u.cached??await u.resolve();if(!p)return null;let f=te(e.getDefaultEnv()),T=new fe(f.tmsBaseUrl,p.username,p.access_key);try{let B=(await T.listFolders(s)).find(Le=>Le.name==="Untitled");if(B)return{id:B.id,name:B.name};let se=await T.createFolder(s,"Untitled");return{id:se.id,name:se.name}}catch{return null}},[S,e]);if(D==="gate")return(0,A.jsx)(w,{paddingX:1,children:(0,A.jsx)(g,{color:"yellow",children:"Checking authentication..."})});if($)return(0,A.jsxs)(w,{flexDirection:"column",paddingX:1,children:[(0,A.jsx)(g,{color:"red",children:$}),(0,A.jsx)(g,{color:"gray",children:"Press Ctrl+C to exit."})]});if(D==="pick"&&_?.status==="needs_pick")return(0,A.jsx)(Je,{profiles:_.profiles,onSelect:i});if(D==="login")return(0,A.jsx)(Re,{devMode:process.env.KANE_DEV_MODE==="1",profiles:e.listProfiles(),onBasicLogin:async(s,u,p,f)=>{let{validateBasicAuth:T}=await import("./validate-basic-TW5CQAL3.js");await T(u,p,f),e.saveBasicAuth(s,u,{username:p,access_key:f}),e.setActiveProfile(s),e.setDefaultEnv(u)},onOAuthLogin:async(s,u)=>{let{LoginFlow:p}=await import("./login-flow-QCYF5347.js");e.setDefaultEnv(u),e.setActiveProfile(s),await new p(s,u,e).login()},onComplete:(s,u)=>{j(s),N(u),e.setActiveProfile(s),e.setDefaultEnv(u),H(s,u)},onCancel:()=>{ie(0,"Login cancelled")}});if(D==="ensure-project"){let s=e.getActiveProfile()??"default",u=e.getDefaultEnv(),p=()=>{if(n==="login"){E("ensure-folder");return}re(e,a,s,u).folderId?U():E("ensure-folder")};return(0,A.jsxs)(w,{flexDirection:"column",children:[(0,A.jsx)(w,{paddingX:1,marginBottom:1,children:(0,A.jsx)(g,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,A.jsx)(Te,{resolver:S(),currentProjectId:a.load().project_id,env:u,onSelect:(f,T)=>{oe(e,a,s,u,{projectId:f,projectName:T}),k(P=>[...P,`\u2713 Project: ${T} (${f})`]),p()},onCancel:async()=>{let f=await O();f&&(oe(e,a,s,u,{projectId:f.id,projectName:f.name}),k(T=>[...T,`\u2713 Default project: ${f.name} (${f.id})`]),p())}})]})}if(D==="ensure-folder"){let s=e.getActiveProfile()??"default",u=e.getDefaultEnv(),p=e.loadProfileConfig(s,u);return(0,A.jsxs)(w,{flexDirection:"column",children:[(0,A.jsx)(w,{paddingX:1,marginBottom:1,children:(0,A.jsx)(g,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,A.jsx)(be,{resolver:S(),projectId:p?.project_id??"",currentFolderId:a.load().folder_id,env:u,onSelect:(f,T)=>{oe(e,a,s,u,{folderId:f,folderName:T}),k(P=>[...P,`\u2713 Folder: ${T} (${f})`]),U()},onCancel:async()=>{if(!p?.project_id)return;let f=await V(p.project_id);f&&(oe(e,a,s,u,{folderId:f.id,folderName:f.name}),k(T=>[...T,`\u2713 Default folder: ${f.name} (${f.id})`]),U())}})]})}return D==="input"?(0,A.jsxs)(w,{flexDirection:"column",children:[G.length>0&&(0,A.jsx)(w,{flexDirection:"column",paddingX:1,marginBottom:1,children:G.map((s,u)=>(0,A.jsx)(g,{color:"green",children:s},u))}),(0,A.jsx)(_e,{onSubmit:r,onEscape:()=>ie(0,"User pressed Escape"),history:y,placeholder:"Type an objective..."})]}):(0,A.jsx)(A.Fragment,{})}function Je({profiles:c,onSelect:n}){let[o,d]=(0,C.useState)(0),[h,t]=(0,C.useState)(!1);return z((m,e)=>{if(!h){if(e.escape){ie(0,"Profile picker cancelled");return}if(e.upArrow&&o>0&&d(a=>a-1),e.downArrow&&o<c.length-1&&d(a=>a+1),e.return){t(!0);let a=c[o];n(a.profile,a.env).catch(()=>t(!1))}}}),(0,A.jsxs)(w,{flexDirection:"column",paddingX:1,children:[(0,A.jsx)(g,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,A.jsx)(w,{marginTop:1,flexDirection:"column",children:c.map((m,e)=>(0,A.jsxs)(g,{children:[e===o?"\u276F ":" ",(0,A.jsx)(g,{color:e===o?"#ff9500":"white",bold:e===o,children:m.profile}),(0,A.jsxs)(g,{color:"gray",children:[" [",m.env,"]"]})]},`${m.profile}-${m.env}`))}),h&&(0,A.jsx)(w,{marginTop:1,children:(0,A.jsx)(g,{color:"yellow",children:"Validating credentials..."})})]})}export{De as a,_e as b,Re as c,ue as d,Ie as e,Vt as f};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as h}from"./chunk-BSQVYLV7.js";import{a as A}from"./chunk-HCBYKLMW.js";import{t as a}from"./chunk-JYQO6G7F.js";import{a as c,b as f,i as P}from"./chunk-C44QQJR4.js";import{a as y}from"./chunk-6YGTRKDT.js";import{e as x}from"./chunk-UR6MHSHU.js";var L=x(y(),1);var r=x(A(),1);function B(i,d,l,u,p){let g=l==="basic"&&u?`basic (${u})`:l,n=20,s=`${i} [${d}]`,m="\xB7".repeat(Math.max(2,n-s.length+3));return{label:`${s} ${m} ${g}`,profile:i,env:d,isActive:p}}function I({creds:i,onSwitch:d,onCancel:l}){let u=i.listProfiles(),p=i.getActiveProfile(),g=i.getDefaultEnv(),n=u.map(e=>{let t=i.loadBasicAuth(e.profile,e.env),o=i.loadCredentials(e.profile,e.env)!==null,v=t?"basic":o?"oauth":"none",b=t?t.username:null,w=e.profile===p&&e.env===g;return B(e.profile,e.env,v,b,w)}),[s,m]=(0,L.useState)(()=>{let e=n.findIndex(t=>t.isActive);return e>=0?e:0});return P((e,t)=>{if(t.escape){l();return}if(t.upArrow){m(o=>Math.max(0,o-1));return}if(t.downArrow){m(o=>Math.min(n.length-1,o+1));return}if(t.return&&n[s]){let o=n[s];o.isActive||d(o.profile,o.env),l();return}}),n.length===0?(0,r.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:a.primary,paddingX:2,paddingY:1,children:[(0,r.jsx)(f,{color:a.primary,bold:!0,children:"Profiles"}),(0,r.jsx)(c,{marginTop:1,children:(0,r.jsx)(f,{color:a.dim,children:"No profiles \u2014 use Login to create one"})}),(0,r.jsx)(h,{bindings:[],escBackLabel:"back"})]}):(0,r.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:a.primary,paddingX:2,paddingY:1,children:[(0,r.jsx)(f,{color:a.primary,bold:!0,children:"Profiles"}),(0,r.jsx)(c,{flexDirection:"column",marginTop:1,children:n.map((e,t)=>{let o=t===s,v=o?"\u276F ":" ",b=e.isActive?a.statusPass:o?a.primary:void 0;return(0,r.jsxs)(f,{color:b,children:[v,e.label,e.isActive?" \u25CF active":""]},`${e.profile}-${e.env}`)})}),(0,r.jsx)(h,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"switch"}],escBackLabel:"back"})]})}export{B as a,I as b};
@@ -0,0 +1,5 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as d}from"./chunk-NLYBR5FP.js";import{c as h,q as g,r as u}from"./chunk-JYQO6G7F.js";import{readFileSync as a,writeFileSync as f,mkdirSync as p,readdirSync as c,unlinkSync as s,existsSync as l,chmodSync as y}from"fs";import{join as n,dirname as C}from"path";var v=class{baseDir;profilesDir;configFile;constructor(t=h){this.baseDir=t,this.profilesDir=n(t,"profiles"),this.configFile=n(t,"config.json")}readConfig(){try{return JSON.parse(a(this.configFile,"utf-8"))}catch{return{}}}writeConfig(t){p(this.baseDir,{recursive:!0,mode:448}),f(this.configFile,JSON.stringify(t,null,2)+`
3
+ `),y(this.configFile,384)}getActiveProfile(){return this.readConfig().active_profile??null}setActiveProfile(t){let r=this.readConfig();r.active_profile=t,this.writeConfig(r)}getDefaultEnv(){return this.readConfig().default_env??"prod"}setDefaultEnv(t){let r=this.readConfig();r.default_env=t,this.writeConfig(r)}credentialsPath(t,r){return n(this.profilesDir,t,r,"credentials")}clientPath(t,r){return n(this.profilesDir,t,r,"client.json")}basicAuthPath(t,r){return n(this.profilesDir,t,r,"basic-auth")}profileConfigPath(t,r){return n(this.profilesDir,t,r,"profile-config.json")}saveProfileConfig(t,r,e){let i=this.loadProfileConfig(t,r)??{};this.writeSecure(this.profileConfigPath(t,r),{...i,...e})}loadProfileConfig(t,r){try{return JSON.parse(a(this.profileConfigPath(t,r),"utf-8"))}catch{return null}}writeSecure(t,r){try{p(C(t),{recursive:!0,mode:448}),f(t,JSON.stringify(r,null,2)+`
4
+ `),y(t,384)}catch(e){let i=e instanceof Error?e.message:String(e);process.stderr.write(`[auth] Failed to save credentials: ${i}
5
+ `)}}saveCredentials(t,r,e){this.writeSecure(this.credentialsPath(t,r),e)}loadCredentials(t,r){try{return JSON.parse(a(this.credentialsPath(t,r),"utf-8"))}catch{return null}}saveClient(t,r,e){this.writeSecure(this.clientPath(t,r),e)}loadClient(t,r){try{return JSON.parse(a(this.clientPath(t,r),"utf-8"))}catch{return null}}getActiveCredentials(){let t=this.getActiveProfile();if(!t)return{credentials:null,profile:null,env:null};let r=this.getDefaultEnv();return{credentials:this.loadCredentials(t,r),profile:t,env:r}}saveBasicAuth(t,r,e){this.writeSecure(this.basicAuthPath(t,r),e)}loadBasicAuth(t,r){try{return JSON.parse(a(this.basicAuthPath(t,r),"utf-8"))}catch{return null}}deleteBasicAuth(t,r){try{s(this.basicAuthPath(t,r))}catch{}}resolveAuth(){let t=this.getActiveProfile();if(!t)return null;let r=this.getDefaultEnv(),e=this.loadBasicAuth(t,r);return e?{method:"basic",...e,profile:t,env:r}:this.loadCredentials(t,r)?{method:"oauth",profile:t,env:r}:null}listProfiles(){let t=[];try{for(let r of c(this.profilesDir)){let e=n(this.profilesDir,r);try{for(let i of c(e)){let o=n(e,i),P=l(n(o,"credentials")),w=l(n(o,"client.json")),k=l(n(o,"basic-auth"));(P||w||k)&&t.push({profile:r,env:i})}}catch{}}}catch{}return t}deleteProfile(t,r){try{s(this.credentialsPath(t,r))}catch{}if(this.getActiveProfile()===t){let e=this.readConfig();delete e.active_profile,this.writeConfig(e)}}deleteProfileFull(t,r){if(r){try{s(this.credentialsPath(t,r))}catch{}try{s(this.clientPath(t,r))}catch{}try{s(this.basicAuthPath(t,r))}catch{}try{s(this.profileConfigPath(t,r))}catch{}}else try{let e=n(this.profilesDir,t);for(let i of c(e)){try{s(n(e,i,"credentials"))}catch{}try{s(n(e,i,"client.json"))}catch{}try{s(n(e,i,"basic-auth"))}catch{}try{s(n(e,i,"profile-config.json"))}catch{}}}catch{}}};import{createHash as S,randomBytes as A}from"crypto";var m=class{authBaseUrl;consentUrl;constructor(t="prod"){let r=d(t);this.authBaseUrl=r.authBaseUrl,this.consentUrl=r.consentUrl}static generatePkce(){let t=A(96).toString("base64url").slice(0,128),r=S("sha256").update(t).digest("base64url");return[t,r]}buildAuthorizationUrl(t,r,e,i){let o=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:i,scope:u,code_challenge:r,code_challenge_method:"S256",state:e});return`${this.consentUrl}/oauth2?${o.toString()}`}async registerClient(t){let r=await fetch(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:g,redirect_uris:[t],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!r.ok)throw new Error(`DCR failed: ${r.status} ${await r.text()}`);return r.json()}async exchangeCode(t,r,e,i){let o=await fetch(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t,redirect_uri:i,client_id:r,code_verifier:e})});if(!o.ok)throw new Error(`Token exchange failed: ${o.status}`);return o.json()}async refreshToken(t,r){let e=await fetch(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:r})});if(!e.ok)throw new Error(`Token refresh failed: ${e.status}`);return e.json()}async revokeToken(t,r,e="access_token"){await fetch(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,token_type_hint:e,client_id:r})})}async validateToken(t){let r=new AbortController,e=setTimeout(()=>r.abort(),1e4);try{let i=await fetch(`${this.authBaseUrl}/api/user`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},signal:r.signal});return clearTimeout(e),i.ok}catch{return clearTimeout(e),!1}}};export{v as a,m as b};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ var r=/^[a-zA-Z0-9_\-]+$/,e=class extends Error{constructor(n){super(`name "${n}" is invalid; allowed: letters, digits, underscore, hyphen`),this.name="InvalidNameError"}};function s(t){return r.test(t)}function i(t){if(!r.test(t))throw new e(t)}export{e as a,s as b,i as c};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{dirname as o,basename as s,join as n}from"path";function g(t){let r=s(t);return r.endsWith("_test.md")?r.slice(0,-8):r.endsWith(".md")?r.slice(0,-3):r}function e(t){return n(o(t),`output-${g(t)}`)}function m(t){return n(e(t),"Result.md")}function u(t){return n(e(t),".internal")}function f(t){return n(u(t),"meta.json")}function a(t,r,i){return n(e(t),`${r}-${i}-code`)}function d(t){return n(e(t),"generated-code")}function x(t){return e(t)+".staging"}function p(t){return n(u(t),"steps")}function l(t,r,i){return n(p(t),`${r}-${i}`)}export{g as a,e as b,m as c,u as d,f as e,a as f,d as g,x as h,l as i};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ function _(t,i,n,l){let r=t.loadProfileConfig(n,l)??{},e={projectId:r.project_id??null,projectName:r.project_name??null,folderId:r.folder_id??null,folderName:r.folder_name??null};return i.save({project_id:e.projectId,project_name:e.projectName,folder_id:e.folderId,folder_name:e.folderName}),e}function u(t,i,n,l,r){let e={};r.projectId!==void 0&&(e.project_id=r.projectId??void 0),r.projectName!==void 0&&(e.project_name=r.projectName??void 0),r.folderId!==void 0&&(e.folder_id=r.folderId??void 0),r.folderName!==void 0&&(e.folder_name=r.folderName??void 0),t.saveProfileConfig(n,l,e);let d=t.loadProfileConfig(n,l)??{};i.save({project_id:d.project_id??null,project_name:d.project_name??null,folder_id:d.folder_id??null,folder_name:d.folder_name??null})}function j(t,i,n,l,r){let e=t.loadProfileConfig(n,l)??{},d=i.load(),o={project_id:e.project_id??null,project_name:e.project_name??null,folder_id:e.folder_id??null,folder_name:e.folder_name??null},a={project_id:d.project_id??null,project_name:d.project_name??null,folder_id:d.folder_id??null,folder_name:d.folder_name??null},c=o.project_id===a.project_id&&o.project_name===a.project_name&&o.folder_id===a.folder_id&&o.folder_name===a.folder_name,f={projectId:o.project_id,projectName:o.project_name,folderId:o.folder_id,folderName:o.folder_name};return c?{rehydrated:!1,state:f}:(r?.("warn","STALE_TUI_CONFIG_REHYDRATED","tui-config divergent from profile-config \u2014 rewriting",{profile:n,env:l,profile_state:o,tui_state:a}),i.save(o),{rehydrated:!0,state:f})}function p(t){return t.projectId!==null&&t.folderId!==null}export{_ as a,u as b,j as c,p as d};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as R}from"./chunk-BSQVYLV7.js";import{a as X}from"./chunk-HCBYKLMW.js";import{t as n}from"./chunk-JYQO6G7F.js";import{a as c,b as r,i as N}from"./chunk-C44QQJR4.js";import{a as G}from"./chunk-6YGTRKDT.js";import{e as M}from"./chunk-UR6MHSHU.js";var b=M(G(),1);var e=M(X(),1),d=5;function K(i,I){if(!I)return i;let a=I.toLowerCase();return i.filter(v=>v.label.toLowerCase().includes(a))}function Q(i){let{title:I,items:a,loading:v=!1,loadingText:Y,error:h=null,itemNoun:B="items",onSelect:H,onCancel:D,defaultActiveId:y,onTab:L,extraHint:E}=i,[x,s]=(0,b.useState)(0),[p,f]=(0,b.useState)(0),[u,w]=(0,b.useState)(""),[A,S]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(a.length===0)return;if(i.preserveSelectionById&&A!==null){let t=a.findIndex(o=>o.id===A);if(t>=0){f(Math.floor(t/d)),s(t%d);return}}let l=y?a.findIndex(t=>t.id===y):a.findIndex(t=>t.isActive);l>=0?(f(Math.floor(l/d)),s(l%d),i.preserveSelectionById&&S(a[l].id)):i.preserveSelectionById&&(f(0),s(0),S(a[0]?.id??null))},[a,y,i.preserveSelectionById,A]);let g=K(a,u),C=p*d,F=Math.min(C+d,g.length),P=Math.ceil(g.length/d),O=F-C,T=g.slice(C,F);return N((l,t)=>{if(h){t.escape&&D();return}if(t.escape){u?(w(""),s(0),f(0)):D();return}if(t.tab&&L){L();return}if(t.upArrow){if(x>0){let o=x-1;s(o),i.preserveSelectionById&&S(T[o]?.id??null)}else if(p>0){let o=p-1,m=d-1;f(o),s(m),i.preserveSelectionById&&S(g[o*d+m]?.id??null)}return}if(t.downArrow){if(x<O-1){let o=x+1;s(o),i.preserveSelectionById&&S(T[o]?.id??null)}else if(p<P-1){let o=p+1,m=0;f(o),s(m),i.preserveSelectionById&&S(g[o*d+m]?.id??null)}return}if(t.return&&T[x]){H(T[x]);return}if(t.backspace||t.delete){w(o=>o.slice(0,-1)),s(0),f(0);return}l&&!t.ctrl&&!t.meta&&(w(o=>o+l),s(0),f(0))},{isActive:!v}),v?(0,e.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:n.primary,paddingX:2,paddingY:1,children:[(0,e.jsx)(r,{color:n.primary,bold:!0,children:I}),(0,e.jsx)(c,{marginTop:1,children:(0,e.jsx)(r,{color:n.secondary,children:Y??`Loading ${B}\u2026`})})]}):h?(0,e.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:n.statusFail,paddingX:2,paddingY:1,children:[(0,e.jsx)(r,{color:n.statusFail,bold:!0,children:I}),(0,e.jsx)(c,{marginTop:1,children:(0,e.jsx)(r,{color:n.statusFail,children:h})}),(0,e.jsx)(R,{bindings:[]})]}):(0,e.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:n.primary,paddingX:2,paddingY:1,children:[(0,e.jsxs)(c,{children:[(0,e.jsx)(r,{color:n.primary,bold:!0,children:I}),(0,e.jsxs)(r,{color:n.dim,children:[" (",g.length,u?`/${a.length}`:""," ",B,i.loadingMore?" \xB7 loading more":"",")"]})]}),(0,e.jsxs)(c,{marginTop:1,children:[(0,e.jsx)(r,{color:n.secondary,children:u?"filter: ":""}),u?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(r,{children:u}),(0,e.jsx)(r,{inverse:!0,children:" "})]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(r,{color:n.dim,children:["Search ",B,"\u2026"]}),(0,e.jsx)(r,{inverse:!0,children:" "})]})]}),(0,e.jsx)(c,{flexDirection:"column",marginTop:1,children:g.length===0?(0,e.jsxs)(r,{color:n.dim,children:["No ",B,' match "',u,'"']}):T.map((l,t)=>{let o=t===x,m=o?"\u276F ":" ",$=l.isActive?n.statusPass:o?n.primary:void 0;return(0,e.jsxs)(r,{color:$,children:[m,l.label,l.isActive?" \u25CF selected":""]},l.id)})}),P>1&&(0,e.jsx)(c,{marginTop:1,children:(0,e.jsxs)(r,{color:n.dim,children:["Page ",p+1,"/",P]})}),i.footer&&(0,e.jsx)(c,{marginTop:1,flexDirection:"column",children:i.footer}),(0,e.jsx)(R,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"type",label:"to search"},{keys:"\u21B5",label:"select"},...L&&E?[{keys:"tab",label:E}]:[]],escBackLabel:u?"clear":"back to chat"})]})}export{Q as a};
@@ -0,0 +1,5 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as se,b as Te}from"./chunk-MH26PIS4.js";import{b as ke}from"./chunk-7VX5H5MK.js";import{d as Be,e as ae}from"./chunk-G7VF5SDK.js";import{a as Re}from"./chunk-CFFWCE27.js";import{a as N}from"./chunk-HCBYKLMW.js";import{t as s}from"./chunk-JYQO6G7F.js";import{a as c,b as o,d as ye,k as ue}from"./chunk-C44QQJR4.js";import{a as le}from"./chunk-6YGTRKDT.js";import{e as j}from"./chunk-UR6MHSHU.js";var G=j(N(),1),Le=64;function Pe(t){return t.split(`
3
+ `).map(i=>i.replace(/^[-–•]\s*/,"").trim()).filter(i=>i.length>0)}function Ge({status:t,summary:i,duration:l,steps:u,stepsPassed:S,stepsFailed:f,reason:x,creditsConsumed:d}){let D=t==="passed",E=D?s.green:s.red,P=D?"\u2713":"\u2717",F=t.toUpperCase(),H=S??(D?u:Math.max(0,u-1)),I=f??(D?0:1),M=I>0?`${u} steps (${H} passed, ${I} failed)`:`${u} steps`,Q=l<60?`${l.toFixed(1)}s`:`${Math.floor(l/60)}m ${Math.round(l%60)}s`,V=Pe(i);return(0,G.jsx)(c,{flexDirection:"column",marginTop:1,children:(0,G.jsxs)(c,{borderStyle:"round",borderColor:E,flexDirection:"column",paddingX:2,paddingY:1,width:Le+6,children:[(0,G.jsxs)(c,{flexDirection:"column",children:[(0,G.jsxs)(o,{bold:!0,color:E,children:[P," ",F]}),(0,G.jsxs)(o,{color:s.dimmed,wrap:"wrap",children:[M," \xB7 ",Q,typeof d=="number"&&d>0?` \xB7 ${parseFloat(d.toFixed(4))} credits`:""]})]}),V.length>0&&(0,G.jsx)(c,{flexDirection:"column",marginTop:1,marginLeft:1,children:V.map((Z,W)=>(0,G.jsxs)(c,{marginBottom:W<V.length-1?1:0,children:[(0,G.jsx)(o,{color:s.primary,children:"\u25CF "}),(0,G.jsx)(c,{flexShrink:1,children:(0,G.jsx)(o,{wrap:"wrap",children:Z})})]},W))}),x&&!D&&(0,G.jsx)(c,{marginTop:1,children:(0,G.jsxs)(o,{color:s.red,wrap:"wrap",children:["Reason: ",x]})})]})})}var A=j(N(),1);function Ke({message:t,code:i,remediation:l,docsUrl:u}){return(0,A.jsx)(Re,{title:"Error",variant:"error",children:(0,A.jsxs)(c,{flexDirection:"column",paddingY:1,children:[(0,A.jsxs)(o,{color:s.red,bold:!0,children:[" \u2717 ",t]}),i&&(0,A.jsxs)(c,{marginTop:0,marginLeft:5,children:[(0,A.jsx)(o,{color:s.muted,children:"Code: "}),(0,A.jsx)(o,{color:s.dimmed,children:i})]}),l&&(0,A.jsxs)(c,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,A.jsx)(o,{color:s.green,bold:!0,children:"Fix:"}),(0,A.jsxs)(o,{color:s.cyan,children:["$ ",l]})]}),u&&(0,A.jsxs)(c,{marginTop:1,marginLeft:5,children:[(0,A.jsx)(o,{color:s.muted,children:"Docs: "}),(0,A.jsx)(o,{color:s.cyan,underline:!0,children:u})]})]})})}var $=j(le(),1);var we=j(le(),1);var de=j(N(),1),De="#ffc580",Fe="#ffd9a8",ve="#ffffff";function _e({text:t,active:i=!0}){let[l,u]=(0,we.useState)(0),S=4;if(se(()=>{u(x=>(x+1)%(t.length+S*2))},i?80:null),!i)return(0,de.jsx)(o,{color:ve,children:t});let f=t.split("").map((x,d)=>{let D=l-S,E=Math.abs(d-D-S/2),P;return E<=S/2?P=De:E<=S?P=Fe:P=ve,(0,de.jsx)(o,{color:P,children:x},d)});return(0,de.jsx)(o,{children:f})}var O=j(N(),1),Oe={starting:s.cyan,running:s.purple,passed:s.green,failed:s.red,cancelled:s.dimmed,timed_out:s.yellow};function fe({currentStep:t,maxSteps:i,elapsed:l,status:u}){let{stdout:S}=ue(),f=S?.columns??80,x=Oe[u]??s.purple,d=l<60?`${l.toFixed(1)}s`:`${Math.floor(l/60)}m ${Math.round(l%60)}s`;return(0,O.jsxs)(c,{flexDirection:"column",marginTop:1,children:[(0,O.jsx)(o,{color:s.muted,children:"\u2500".repeat(Math.min(f,60))}),(0,O.jsxs)(c,{children:[(0,O.jsx)(o,{children:" "}),(0,O.jsx)(o,{color:s.dimmed,children:"Steps "}),(0,O.jsx)(o,{bold:!0,children:t}),(0,O.jsxs)(o,{color:s.dimmed,children:["/",i]}),(0,O.jsx)(o,{children:" "}),(0,O.jsx)(o,{color:s.dimmed,children:"Elapsed "}),(0,O.jsx)(o,{bold:!0,children:d}),(0,O.jsx)(o,{children:" "}),(0,O.jsx)(o,{color:s.dimmed,children:"Status "}),(0,O.jsx)(o,{bold:!0,color:x,children:u})]})]})}var Me={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u2299"};function $e(t){return Me[t]??"\u25CF"}var ne=j(N(),1);function xe({steps:t,flows:i,cmInitCounts:l,renderStep:u}){return(0,ne.jsxs)(c,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,ne.jsxs)(o,{color:s.dimmed,children:["\u2501\u2501 Bifurcated into ",i?.length??t.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),t.map((S,f)=>(0,ne.jsxs)(c,{flexDirection:"column",marginTop:f>0?1:0,children:[(0,ne.jsxs)(o,{color:s.purple,children:["Flow ",f+1,": ",i?.[f]??S.objective]}),l&&l[f]!=null&&(0,ne.jsxs)(o,{color:s.dimmed,children:[" \u25AA Generated task with ",l[f]," checkpoints"]}),S.children&&S.children.length>0?S.children.map(x=>u(x,`f${f}-${x.index}`)):S.status==="pending"&&(0,ne.jsx)(o,{color:s.dimmed,children:" \u25CB Waiting..."})]},f))]})}var r=j(N(),1);function U({step:t,indent:i=2}){let l=t.actionType?$e(t.actionType):null,u=t.status==="running",S=t.status==="passed",f=t.status==="failed",x=t.status==="pending"||t.status==="stopped",{stdout:d}=ue(),D=d?.columns??80,E=Math.max(20,D-i-21),P=t.objective??"",F=P.length>E?P.slice(0,E-1)+"\u2026":P,H=(t.duration??0)*1e3,I=t.duration!=null?H<1e3?`${Math.round(H)}ms`:`${(H/1e3).toFixed(1)}s`:"";return(0,r.jsxs)(c,{flexDirection:"column",children:[(0,r.jsxs)(c,{marginLeft:i,children:[(0,r.jsx)(c,{width:4,children:(0,r.jsxs)(o,{color:s.muted,children:[String(t.index).padStart(2," ")," "]})}),(0,r.jsx)(c,{width:3,children:u?(0,r.jsx)(Te,{}):S?(0,r.jsx)(o,{color:s.green,bold:!0,children:"\u2713"}):f?(0,r.jsx)(o,{color:s.red,bold:!0,children:"\u2717"}):(0,r.jsx)(o,{color:s.muted,children:"\u25CB"})}),(0,r.jsx)(c,{flexGrow:1,children:u?(0,r.jsx)(_e,{text:F,active:!0}):f?(0,r.jsx)(o,{color:s.red,children:F}):x?(0,r.jsx)(o,{color:s.dimmed,children:F}):(0,r.jsx)(o,{color:s.greenDim,children:F})}),(S||f)&&l?(0,r.jsx)(c,{width:3,marginLeft:1,children:(0,r.jsx)(o,{color:s.muted,children:l})}):(0,r.jsx)(c,{width:3,marginLeft:1}),(0,r.jsx)(c,{width:7,justifyContent:"flex-end",children:(0,r.jsx)(o,{color:s.dimmed,children:I})})]}),t.children&&t.children.length>0&&(0,r.jsx)(c,{flexDirection:"column",children:t.children.map((M,Q)=>(0,r.jsx)(U,{step:M,indent:i+2},`child-${Q}`))})]})}function ft({steps:t,bifurcated:i,flows:l,cmInitCounts:u,maxSteps:S=50,staticSteps:f=!1,onStepCommit:x}){let d=(0,$.useRef)(new Set),D=(0,$.useRef)(!1),E=(0,$.useRef)(new Set),P=(0,$.useRef)(!1),F=(0,$.useRef)(new Set),H=(0,$.useRef)(0);(0,$.useEffect)(()=>{t.length===0&&H.current>0&&(d.current.clear(),D.current=!1,E.current.clear(),P.current=!1,F.current.clear()),H.current=t.length},[t.length]);let I=t.flatMap(n=>[n,...n.children??[]]),M=I.some(n=>n.status==="running"),Q=I.some(n=>n.status==="failed"),V=I.length===0||I.every(n=>n.status==="pending"),Z=I.filter(n=>n.status==="passed"||n.status==="failed").length,W;V?W="starting":M?W="running":Q?W="failed":W="passed";let ee=(0,$.useRef)(null),[ie,ce]=(0,$.useState)(0);(0,$.useEffect)(()=>{I.length===0||V?(ee.current=null,ce(0)):M&&ee.current==null&&(ee.current=Date.now())},[M,V,I.length]),(0,$.useEffect)(()=>{if(!M)return;let n=setInterval(()=>{ee.current!=null&&ce((Date.now()-ee.current)/1e3)},500);return()=>clearInterval(n)},[M]);let v=(0,$.useRef)(new Set),[C,K]=(0,$.useState)([]),re=(0,$.useRef)(!1);(0,$.useEffect)(()=>{if(!f||i)return;let n=[];if(!i&&!re.current&&u&&u[0]!=null&&(re.current=!0,u[0]>0&&n.push({key:"cm_init_0",type:"cm_init",count:u[0]})),i){!v.current.has(-1)&&t.length>0&&(v.current.add(-1),n.push({key:"bif_header",type:"bifurcation_header",flowCount:l?.length??t.length}));for(let p=0;p<t.length;p++){let a=t[p],y=-(p+10);v.current.has(y)||(v.current.add(y),n.push({key:`flow_header_${p}`,type:"flow_header",flowIdx:p,label:l?.[p]??a.objective,cmCount:u?.[p]}));for(let B of a.children??[])(B.status==="passed"||B.status==="failed")&&!v.current.has(B.index)&&(v.current.add(B.index),n.push({key:`step_f${p}_${B.index}`,type:"step",step:{...B}}))}}else for(let p of t)(p.status==="passed"||p.status==="failed")&&!v.current.has(p.index)&&(v.current.add(p.index),n.push({key:`step_${p.index}`,type:"step",step:{...p,children:p.children?[...p.children]:void 0}}));n.length>0&&K(p=>[...p,...n])},[t,i,l,u,f]),(0,$.useEffect)(()=>{if(x)if(!i&&!P.current&&u&&u[0]!=null&&(P.current=!0,u[0]>0&&x((0,r.jsx)(c,{marginLeft:2,children:(0,r.jsxs)(o,{color:s.dimmed,children:["\u25A0 Generated task with ",u[0]," checkpoints"]})}))),i&&l&&!D.current&&(D.current=!0,x((0,r.jsx)(o,{color:"#b388ff",children:"\u2501\u2501 Bifurcated into "+l.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"}))),i){let n=t.flatMap((p,a)=>{let y=p.children??[];return!E.current.has(a)&&y.length>0&&(E.current.add(a),x((0,r.jsx)(o,{color:"#b388ff",children:" Flow "+(a+1)+": "+(l?.[a]??"")})),u?.[a]!=null&&u[a]>0&&!F.current.has(a)&&(F.current.add(a),x((0,r.jsx)(c,{marginLeft:2,children:(0,r.jsxs)(o,{color:s.dimmed,children:[" \u25AA Generated task with ",u[a]," checkpoints"]})})))),u?.[a]!=null&&u[a]>0&&E.current.has(a)&&!F.current.has(a)&&(F.current.add(a),x((0,r.jsx)(c,{marginLeft:2,children:(0,r.jsxs)(o,{color:s.dimmed,children:[" \u25AA Generated task with ",u[a]," checkpoints"]})}))),y});for(let p of n){let a=`${p.index}-${p.objective}`;d.current.has(a)||(p.status==="passed"||p.status==="failed"||p.status==="stopped")&&(d.current.add(a),x((0,r.jsx)(c,{marginLeft:2,children:(0,r.jsx)(U,{step:p})})))}}else for(let n of t){let p=`${n.index}-${n.objective}`,a=!!n.branchObjective;a&&!d.current.has(p)&&(d.current.add(p),x((0,r.jsx)(c,{marginLeft:2,children:(0,r.jsx)(U,{step:{...n,children:void 0}})})));for(let y of n.children??[]){let B=`child-${n.index}-${y.index}-${y.objective}`;d.current.has(B)||(y.status==="passed"||y.status==="failed"||y.status==="stopped")&&(d.current.add(B),x((0,r.jsx)(c,{marginLeft:4,children:(0,r.jsx)(U,{step:y})})))}!a&&!d.current.has(p)&&(n.status==="passed"||n.status==="failed"||n.status==="stopped")&&(d.current.add(p),x((0,r.jsx)(c,{marginLeft:2,children:(0,r.jsx)(U,{step:{...n,children:void 0}})})))}},[t,x,i,l,u]);let Y=[];if(x)if(i)for(let n of t){let a=(n.children??[]).filter(y=>{let B=`${y.index}-${y.objective}`;return!d.current.has(B)});a.length>0&&Y.push({...n,children:a})}else for(let n of t){let p=`${n.index}-${n.objective}`,a=d.current.has(p),y=(n.children??[]).filter(B=>{let L=`child-${n.index}-${B.index}-${B.objective}`;return!d.current.has(L)});a?y.length>0&&Y.push({...n,children:y}):Y.push({...n,children:y})}else if(f){if(!i)for(let n of t)v.current.has(n.index)||Y.push(n)}if(!f){let n=x?Y:t;return(0,r.jsxs)(c,{flexDirection:"column",children:[i?x?n.length>0?(0,r.jsx)(c,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:n.map((a,y)=>(0,r.jsx)(c,{flexDirection:"column",marginTop:y>0?1:0,children:a.children&&a.children.length>0?a.children.map(B=>(0,r.jsx)(U,{step:B},`f${y}-${B.index}`)):a.status==="pending"&&(0,r.jsx)(o,{color:s.dimmed,children:" \u25CB Waiting..."})},y))}):null:(0,r.jsx)(xe,{steps:t,flows:l,cmInitCounts:u,renderStep:(a,y)=>(0,r.jsx)(U,{step:a},y)}):(0,r.jsxs)(c,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!x&&u&&u[0]!=null&&(0,r.jsxs)(o,{color:s.dimmed,children:["\u25AA Generated task with ",u[0]," checkpoints"]}),n.map(a=>{let y=`${a.index}-${a.objective}`;return x&&d.current.has(y)?(0,r.jsx)(c,{flexDirection:"column",children:(a.children??[]).map(B=>(0,r.jsx)(c,{marginLeft:2,children:(0,r.jsx)(U,{step:B})},B.index))},`branch-children-${a.index}`):(0,r.jsx)(U,{step:a},a.index)})]}),M&&(0,r.jsx)(fe,{currentStep:Z,maxSteps:S,elapsed:ie,status:W})]})}return i?(0,r.jsxs)(c,{flexDirection:"column",children:[(0,r.jsx)(xe,{steps:t,flows:l,cmInitCounts:u,renderStep:(n,p)=>(0,r.jsx)(U,{step:n},p)}),M&&(0,r.jsx)(fe,{currentStep:Z,maxSteps:S,elapsed:ie,status:W})]}):(0,r.jsxs)(c,{flexDirection:"column",children:[(0,r.jsx)(ye,{items:C,children:n=>n.type==="cm_init"?(0,r.jsx)(c,{marginLeft:2,paddingLeft:1,children:(0,r.jsxs)(o,{color:s.dimmed,children:["\u25AA Generated task with ",n.count," checkpoints"]})},n.key):n.type==="bifurcation_header"?(0,r.jsx)(c,{marginLeft:2,paddingLeft:1,children:(0,r.jsxs)(o,{color:s.dimmed,children:["\u2501\u2501 Bifurcated into ",n.flowCount," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]})},n.key):n.type==="flow_header"?(0,r.jsxs)(c,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,r.jsxs)(o,{color:s.purple,children:["Flow ",n.flowIdx+1,": ",n.label]}),n.cmCount!=null&&(0,r.jsxs)(o,{color:s.dimmed,children:[" \u25AA Generated task with ",n.cmCount," checkpoints"]})]},n.key):(0,r.jsx)(c,{marginLeft:2,paddingLeft:1,children:(0,r.jsx)(U,{step:n.step})},n.key)}),Y.length>0&&(0,r.jsx)(c,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:Y.map(n=>(0,r.jsx)(U,{step:n},n.index))}),M&&(0,r.jsx)(fe,{currentStep:Z,maxSteps:S,elapsed:ie,status:W})]})}var ge=j(le(),1);var pe=j(N(),1),Ee=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function bt({label:t,hasBifurcation:i=!1}){let[l,u]=(0,ge.useState)(0),[S,f]=(0,ge.useState)(0);se(()=>{u(d=>(d+1)%Ee.length)},80),se(()=>{f(d=>(d+1)%4)},400);let x=t??(i?"Planning approach":"Analyzing objective");return(0,pe.jsxs)(c,{marginLeft:1,children:[(0,pe.jsxs)(o,{color:s.primary,children:[Ee[l]," "]}),(0,pe.jsxs)(o,{color:s.dim,children:[x,".".repeat(S+1)]})]})}function yt(t){if(!t.isRunning||t.replayInfo)return null;let i=t.bifurcationInfo;if(i&&!i.isSingleFlow){let l=t.steps.findIndex(S=>S.status==="running");return(l===-1?t.cmInitCounts.length===0:l>=t.cmInitCounts.length)?{label:l>0?`Planning flow ${l+1}`:void 0,hasBifurcation:!0}:null}return t.cmInitCounts.length>0||t.steps.some(l=>l.children?.length)?null:{hasBifurcation:!!i}}var _=j(le(),1);function be(t){let i=t.indexOf(": ");return i>0&&i<15?t.slice(i+2):t}function Se(t){return t.map(i=>{let l=i.children?Se(i.children):i.children;return i.status==="running"?{...i,status:"stopped",phase:void 0,children:l}:l!==i.children?{...i,children:l}:i})}function kt(t,i,l,u){let[S,f]=(0,_.useState)(!1),[x,d]=(0,_.useState)([]),[D,E]=(0,_.useState)(null),[P,F]=(0,_.useState)(null),[H,I]=(0,_.useState)(null),[M,Q]=(0,_.useState)(null),[V,Z]=(0,_.useState)([]),[W,ee]=(0,_.useState)(null),[ie,ce]=(0,_.useState)(void 0),v=(0,_.useRef)(null),C=(0,_.useRef)(null),K=(0,_.useRef)(0),re=(0,_.useRef)(!1),Y=(0,_.useCallback)(async(a,y)=>{let B=v.current;if(B){try{await B.exited}catch{}v.current=null}d([]),E(null),F(null),I(null),Q(null),Z([]),ee(null),ce(a.max_steps),f(!0),C.current=null,K.current=0;let L;try{L=ke(a,y)}catch(te){I(te instanceof Error?te.message:String(te)),f(!1);return}v.current=L,Be("runner",()=>L.cancel()),(async()=>{re.current=!1;let te=!1;for await(let e of L.events){if(re.current)break;switch(e.type){case"run_start":if(C.current&&!C.current.isSingleFlow){let R=K.current;K.current++,d(T=>T.map((h,b)=>b===R?{...h,status:"running"}:h.status==="running"&&!h.children?.some(m=>m.status==="running")?{...h,status:h.children?.some(m=>m.status==="failed")?"failed":"passed"}:h))}break;case"bifurcation":{let R=e.flows??[],T=e.count??R.length,h={flows:R,isSingleFlow:e.is_single_flow??T<=1};Q(h),C.current=h,K.current=0,d(R.map((b,m)=>({index:m+1,objective:b??`Flow ${m+1}`,status:"pending"})));break}case"step_start":{i?.("STEP_START",`Step ${e.index} started`,{index:e.index,objective:e.objective,child_id:e.child_id});let R=e.index,T=e.objective??`Step ${R}`,h=e.child_id,b=C.current&&!C.current.isSingleFlow;if(h)d(m=>{let g=m.findIndex(z=>z.status==="running"||z.children?.some(je=>je.status==="running"));if(g===-1)return m;let k=[...m],w={...k[g]},J=[...w.children??[]].map(z=>z.status==="running"?{...z,status:"stopped",phase:void 0}:z);return J.push({index:R,objective:T,status:"running"}),w.children=J,k[g]=w,k});else if(b){let m=Math.max(0,K.current-1);d(g=>{let k=[...g];if(m>=k.length)return g;let w={...k[m]},J=[...w.children??[]].map(z=>z.status==="running"?{...z,status:"stopped",phase:void 0}:z);return J.push({index:R,objective:T,status:"running"}),w.children=J,w.status="running",k[m]=w,k})}else d(m=>{let g=Se(m);return g.some(w=>w.index===R)?g.map(w=>w.index===R?{...w,status:"running",objective:T}:w):[...g,{index:R,objective:T,status:"running"}]});break}case"step_event":{i?.("STEP_EVENT",`Step ${e.index} ${e.event}`,{index:e.index,phase:e.event,action_type:e.action_type,detail:e.detail,child_id:e.child_id});let R=e.child_id,T=C.current&&!C.current.isSingleFlow;if(e.event==="cm_init"&&e.checkpoint_count!=null){Z(h=>[...h,e.checkpoint_count]);break}if(e.event==="replay_started"){ee({recordingLength:e.recording_length??0});break}if(e.event==="reasoning"&&e.detail&&e.detail!=="reasoning"&&l?.(e.detail),R)d(h=>h.map(b=>{if(!b.children)return b;let m=b.children.map(g=>{if(g.index!==e.index)return g;let k={phase:e.event};return e.event==="reasoning"&&e.detail&&e.detail!=="reasoning"&&(k.objective=e.detail),e.action_type&&(k.actionType=e.action_type),{...g,...k}});return{...b,children:m}}));else if(T){let h=Math.max(0,K.current-1);d(b=>{let m=[...b];if(h>=m.length)return b;let g={...m[h]},k=[...g.children??[]];if(!k.some(X=>X.index===e.index))k.push({index:e.index,objective:`Step ${e.index}`,status:"running",phase:e.event,actionType:e.action_type});else for(let X=0;X<k.length;X++){if(k[X].index!==e.index)continue;let J={phase:e.event};e.event==="reasoning"&&e.detail&&e.detail!=="reasoning"&&(J.objective=e.detail),e.action_type&&(J.actionType=e.action_type),k[X]={...k[X],...J}}return g.children=k,m[h]=g,m})}else d(h=>h.some(m=>m.index===e.index)?h.map(m=>{if(m.index!==e.index)return m;let g={phase:e.event};return e.event==="reasoning"&&e.detail&&e.detail!=="reasoning"&&(g.objective=e.detail),e.action_type&&(g.actionType=e.action_type),{...m,...g}}):[...Se(h),{index:e.index,objective:`Step ${e.index}`,status:"running",phase:e.event,actionType:e.action_type}]);break}case"step_end":{i?.("STEP_END",`Step ${e.index} ${e.status}`,{index:e.index,status:e.status,duration:e.duration,summary:e.summary,child_id:e.child_id}),u?.();let R=e.child_id,T=C.current&&!C.current.isSingleFlow;if(R)d(h=>h.map(b=>{if(!b.children)return b;let m=b.children.map(g=>g.index===e.index?{...g,status:e.status,duration:e.duration,phase:void 0,objective:g.objective.startsWith("Step ")?be(e.summary||g.objective):g.objective}:g);return{...b,children:m}}));else if(T){let h=Math.max(0,K.current-1);d(b=>{let m=[...b];if(h>=m.length)return b;let g={...m[h]},k=(g.children??[]).map(w=>w.index===e.index?{...w,status:e.status,duration:e.duration,phase:void 0,objective:w.objective.startsWith("Step ")?be(e.summary||w.objective):w.objective}:w);return g.children=k,m[h]=g,m})}else d(h=>h.map(b=>b.index===e.index?{...b,status:e.status,duration:e.duration,phase:void 0,objective:b.objective.startsWith("Step ")?be(e.summary||b.objective):b.objective}:b));{let b=C.current&&!C.current.isSingleFlow?Math.max(0,K.current-1):0;t?.(e.index,b,e.child_id)}break}case"child_agent_start":{let R=e.objective??"";d(T=>T.map(h=>h.status==="running"?{...h,objective:`${R} (branch)`,phase:`child: ${R.slice(0,50)}`,branchObjective:R}:h));break}case"child_agent_end":d(R=>R.map(T=>T.phase?.startsWith("child:")?{...T,phase:`child ${e.success?"done":"failed"}`}:T));break;case"ask_user":E(e.question??"");break;case"run_end":d(R=>R.map(T=>T.status==="running"?{...T,status:e.status,phase:void 0}:T)),f(!1),F(e),te=!0;break;case"error":f(!1),I(e.message??"Runner error"),d(R=>R.map(T=>T.status==="running"?{...T,status:"failed",phase:void 0}:T));break}}let{code:q,signal:me}=await L.exited,he=L.stderr,Ie=q===0&&!me,oe=[];q!==null&&q!==0&&oe.push(`Runner exited with code ${q}`),me&&oe.push(`Runner killed by signal ${me}`),he&&(!Ie||!te?oe.push(he):y?.log?.("debug","RUNNER_STDERR_BENIGN","Runner stderr on clean exit",{stderr:he})),v.current===L&&(oe.length>0&&I(oe.join(`
4
+ `)),f(!1),ae("runner","Event stream ended"),v.current=null)})().catch(te=>{let q=[`Runner event loop error: ${te}`];L.exitCode!==null&&L.exitCode!==0&&q.push(`Exit code: ${L.exitCode}`),L.exitSignal&&q.push(`Signal: ${L.exitSignal}`),L.stderr&&q.push(L.stderr),v.current===L&&(I(q.join(`
5
+ `)),f(!1),ae("runner","Event loop error"),v.current=null)})},[t,i,l,u]),n=(0,_.useCallback)(a=>{v.current?.sendUserResponse(a),E(null)},[]),p=(0,_.useCallback)(()=>{let a=v.current;a&&(a.sendCancel("user"),f(!1),E(null),setTimeout(()=>{v.current===a&&(ae("runner","User cancelled run"),v.current=null)},5e3))},[]);return(0,_.useEffect)(()=>()=>{re.current=!0,ae("runner","Component unmounted"),v.current=null},[]),{isRunning:S,steps:x,askingUser:D,lastRunEnd:P,runError:H,bifurcationInfo:M,cmInitCounts:V,replayInfo:W,maxSteps:ie,startRun:Y,sendAnswer:n,cancelRun:p}}function wt(t){let i=t.flatMap(f=>[f,...f.children??[]]),l=i.filter(f=>f.status==="passed").length,u=i.filter(f=>f.status==="failed").length,S=i.filter(f=>f.status==="passed"||f.status==="failed").length;return{passed:l,failed:u,total:S}}export{ft as a,bt as b,yt as c,kt as d,wt as e,Ge as f,Ke as g};
@@ -0,0 +1,103 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as D,b as A}from"./chunk-QV2VR72Q.js";import{l as S,m as C,n as P,o as U,p as N}from"./chunk-JYQO6G7F.js";import{createServer as Oe}from"http";import{randomBytes as He}from"crypto";import{URL as $e}from"url";import Z from"process";import{Buffer as ee}from"buffer";import re from"path";import{fileURLToPath as ke}from"url";import{promisify as Le}from"util";import te from"child_process";import Me,{constants as Ie}from"fs/promises";import Y from"process";import G,{constants as me}from"fs/promises";import j from"process";import le from"os";import L from"fs";import se from"fs";import z from"fs";var E;function ie(){try{return z.statSync("/.dockerenv"),!0}catch{return!1}}function ae(){try{return z.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function B(){return E===void 0&&(E=ie()||ae()),E}var k,ce=()=>{try{return se.statSync("/run/.containerenv"),!0}catch{return!1}};function u(){return k===void 0&&(k=ce()||B()),k}var K=()=>{if(j.platform!=="linux")return!1;if(le.release().toLowerCase().includes("microsoft"))return!u();try{if(L.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!u()}catch{}return L.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||L.existsSync("/run/WSL")?!u():!1},d=j.env.__IS_WSL_TEST__?K:K();var de=(()=>{let e="/mnt/",r;return async function(){if(r)return r;let t="/etc/wsl.conf",n=!1;try{await G.access(t,me.F_OK),n=!0}catch{}if(!n)return e;let o=await G.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(o);return i?(r=i.groups.mountPoint.trim(),r=r.endsWith("/")?r:`${r}/`,r):e}})(),fe=async()=>`${await de()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,M=async()=>d?fe():`${Y.env.SYSTEMROOT||Y.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function f(e,r,t){let n=o=>Object.defineProperty(e,r,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){let o=t();return n(o),o},set(o){n(o)}}),e}import{promisify as Pe}from"util";import O from"process";import{execFile as Ae}from"child_process";import{promisify as pe}from"util";import ue from"process";import{execFile as ge}from"child_process";var he=pe(ge);async function I(){if(ue.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await he("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}import we from"process";import{promisify as xe}from"util";import{execFile as ye,execFileSync as cr}from"child_process";var ve=xe(ye);async function X(e,{humanReadableOutput:r=!0,signal:t}={}){if(we.platform!=="darwin")throw new Error("macOS only");let n=r?[]:["-ss"],o={};t&&(o.signal=t);let{stdout:i}=await ve("osascript",["-e",e,n],o);return i.trim()}async function T(e){return X(`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 be}from"util";import{execFile as Se}from"child_process";var Ce=be(Se),y={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"}},ur=new Map(Object.entries(y)),F=class extends Error{};async function _(e=Ce){let{stdout:r}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(r);if(!t)throw new F(`Cannot find Windows browser in stdout: ${JSON.stringify(r)}`);let{id:n}=t.groups,o=n.lastIndexOf("."),i=n.lastIndexOf("-"),c=o===-1?void 0:n.slice(0,o),a=i===-1?void 0:n.slice(0,i);return y[n]??y[c]??y[a]??{name:n,id:n}}var Ee=Pe(Ae),Be=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,r=>r.toUpperCase());async function H(){if(O.platform==="darwin"){let e=await I();return{name:await T(e),id:e}}if(O.platform==="linux"){let{stdout:e}=await Ee("xdg-mime",["query","default","x-scheme-handler/http"]),r=e.trim();return{name:Be(r.replace(/.desktop$/,"").replace("-"," ")),id:r}}if(O.platform==="win32")return _();throw new Error("Only macOS, Linux, and Windows are supported")}var Te=Le(te.execFile),$=re.dirname(ke(import.meta.url)),q=re.join($,"xdg-open"),{platform:w,arch:V}=Z;async function Fe(){let e=await M(),r=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=ee.from(r,"utf16le").toString("base64"),{stdout:n}=await Te(e,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),o=n.trim(),i={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return i[o]?{id:i[o]}:{}}var J=async(e,r)=>{let t;for(let n of e)try{return await r(n)}catch(o){t=o}throw t},v=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return J(e.app,a=>v({...e,app:a}));let{name:r,arguments:t=[]}=e.app??{};if(t=[...t],Array.isArray(r))return J(r,a=>v({...e,app:{name:a,arguments:t}}));if(r==="browser"||r==="browserPrivate"){let a={"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"},l={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},s=d?await Fe():await H();if(s.id in a){let m=a[s.id];return r==="browserPrivate"&&t.push(l[m]),v({...e,app:{name:g[m],arguments:t}})}throw new Error(`${s.name} is not supported as a default browser`)}let n,o=[],i={};if(w==="darwin")n="open",e.wait&&o.push("--wait-apps"),e.background&&o.push("--background"),e.newInstance&&o.push("--new"),r&&o.push("-a",r);else if(w==="win32"||d&&!u()&&!r){n=await M(),o.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),d||(i.windowsVerbatimArguments=!0);let a=["Start"];e.wait&&a.push("-Wait"),r?(a.push(`"\`"${r}\`""`),e.target&&t.push(e.target)):e.target&&a.push(`"${e.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),a.push("-ArgumentList",t.join(","))),e.target=ee.from(a.join(" "),"utf16le").toString("base64")}else{if(r)n=r;else{let a=!$||$==="/",l=!1;try{await Me.access(q,Ie.X_OK),l=!0}catch{}n=Z.versions.electron??(w==="android"||a||!l)?"xdg-open":q}t.length>0&&o.push(...t),e.wait||(i.stdio="ignore",i.detached=!0)}w==="darwin"&&t.length>0&&o.push("--args",...t),e.target&&o.push(e.target);let c=te.spawn(n,o,i);return e.wait?new Promise((a,l)=>{c.once("error",l),c.once("close",s=>{if(!e.allowNonzeroExitCode&&s>0){l(new Error(`Exited with code ${s}`));return}a(c)})}):(c.unref(),c)},_e=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return v({...r,target:e})};function Q(e){if(typeof e=="string"||Array.isArray(e))return e;let{[V]:r}=e;if(!r)throw new Error(`${V} is not supported`);return r}function b({[w]:e},{wsl:r}){if(r&&d)return Q(r);if(!e)throw new Error(`${w} is not supported`);return Q(e)}var g={};f(g,"chrome",()=>b({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"]}}));f(g,"brave",()=>b({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"]}}));f(g,"firefox",()=>b({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));f(g,"edge",()=>b({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));f(g,"browser",()=>"browser");f(g,"browserPrivate",()=>"browserPrivate");var oe=_e;var ne=class{profile;environment;creds;oauth;constructor(r="default",t="prod",n){this.profile=r,this.environment=t,this.creds=n??new D,this.oauth=new A(t)}async login(){let{server:r,port:t}=await this.startCallbackServer(),n=N(t);try{let o=this.creds.loadClient(this.profile,this.environment),i=o?.redirect_uris;(!o||!i?.includes(n))&&(o=await this.oauth.registerClient(n),this.creds.saveClient(this.profile,this.environment,o));let c=o.client_id,[a,l]=A.generatePkce(),s=He(32).toString("hex"),m=this.oauth.buildAuthorizationUrl(c,l,s,n),p=await this.waitForCallback(r,t,m,s);if(!p)throw new Error("Login cancelled or timed out");let h=await this.oauth.exchangeCode(p,c,a,n),x={access_token:h.access_token,refresh_token:h.refresh_token,expires_at:Math.floor(Date.now()/1e3)+h.expires_in,scope:h.scope??"*"};return this.creds.saveCredentials(this.profile,this.environment,x),this.creds.setActiveProfile(this.profile),x}catch(o){throw r.close(),o}}startCallbackServer(){return new Promise((r,t)=>{let n=C,o=()=>{let i=Oe();i.on("error",c=>{c.code==="EADDRINUSE"&&n<P?(n++,o()):t(new Error(`Failed to start callback server: ${c.message}. Ports ${C}-${P} are all in use.`))}),i.listen(n,S,()=>{r({server:i,port:n})})};o()})}waitForCallback(r,t,n,o){return new Promise(i=>{let c=!1,a=setTimeout(()=>l(null),12e4),l=s=>{c||(c=!0,clearTimeout(a),r.close(),i(s))};r.on("request",(s,m)=>{let p=new $e(s.url??"/",`http://${S}:${t}`);if(p.pathname!==U){m.writeHead(404),m.end();return}let h=p.searchParams.get("state"),x=p.searchParams.get("code");if(p.searchParams.get("error")){m.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),m.end(R({state:"error",title:"Login failed",message:"We couldn't complete the sign-in. You can close this tab and try again from your terminal."})),l(null);return}if(h!==o){m.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),m.end(R({state:"error",title:"Invalid state",message:"The sign-in response didn't match this session. Please return to your terminal and try again."})),l(null);return}m.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),m.end(R({state:"success",title:"You're signed in",message:"Head back to your terminal \u2014 KaneAI is ready when you are.",autoClose:!0})),l(x)}),oe(n).catch(s=>{let m=s instanceof Error?s.message:String(s);process.stderr.write(`[auth] Could not open browser: ${m}
4
+ Please open this URL manually: ${n}
5
+ `)})})}};function R(e){let r=e.state==="success",t=r?"#22c55e":"#ef4444",n=r?"rgba(34, 197, 94, 0.12)":"rgba(239, 68, 68, 0.12)",o=r?'<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7"/></svg>':'<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',i=e.autoClose?"<script>setTimeout(function(){try{window.close();}catch(e){}}, 1500);</script>":"";return`<!doctype html>
6
+ <html lang="en">
7
+ <head>
8
+ <meta charset="utf-8" />
9
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
10
+ <title>${W(e.title)} \xB7 KaneAI</title>
11
+ <style>
12
+ :root {
13
+ color-scheme: light dark;
14
+ --bg: #f7f7f8;
15
+ --card: #ffffff;
16
+ --fg: #0a0a0a;
17
+ --muted: #6b7280;
18
+ --border: rgba(0, 0, 0, 0.06);
19
+ --shadow: 0 10px 40px rgba(0, 0, 0, 0.08);
20
+ }
21
+ @media (prefers-color-scheme: dark) {
22
+ :root {
23
+ --bg: #0a0a0a;
24
+ --card: #141416;
25
+ --fg: #f5f5f7;
26
+ --muted: #9ca3af;
27
+ --border: rgba(255, 255, 255, 0.08);
28
+ --shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
29
+ }
30
+ }
31
+ * { box-sizing: border-box; }
32
+ html, body { height: 100%; }
33
+ body {
34
+ margin: 0;
35
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, "Helvetica Neue", Arial, sans-serif;
36
+ background: var(--bg);
37
+ color: var(--fg);
38
+ display: flex;
39
+ align-items: center;
40
+ justify-content: center;
41
+ padding: 24px;
42
+ -webkit-font-smoothing: antialiased;
43
+ }
44
+ .card {
45
+ width: 100%;
46
+ max-width: 420px;
47
+ background: var(--card);
48
+ border: 1px solid var(--border);
49
+ border-radius: 16px;
50
+ box-shadow: var(--shadow);
51
+ padding: 40px 32px 32px;
52
+ text-align: center;
53
+ animation: rise 280ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
54
+ }
55
+ @keyframes rise {
56
+ from { opacity: 0; transform: translateY(8px); }
57
+ to { opacity: 1; transform: translateY(0); }
58
+ }
59
+ .icon {
60
+ width: 64px;
61
+ height: 64px;
62
+ margin: 0 auto 20px;
63
+ border-radius: 999px;
64
+ display: flex;
65
+ align-items: center;
66
+ justify-content: center;
67
+ background: ${n};
68
+ color: ${t};
69
+ }
70
+ h1 {
71
+ font-size: 22px;
72
+ font-weight: 600;
73
+ letter-spacing: -0.01em;
74
+ margin: 0 0 8px;
75
+ }
76
+ p {
77
+ margin: 0;
78
+ color: var(--muted);
79
+ font-size: 14.5px;
80
+ line-height: 1.5;
81
+ }
82
+ .brand {
83
+ margin-top: 28px;
84
+ padding-top: 20px;
85
+ border-top: 1px solid var(--border);
86
+ font-size: 12px;
87
+ letter-spacing: 0.08em;
88
+ text-transform: uppercase;
89
+ color: var(--muted);
90
+ }
91
+ .brand strong { color: var(--fg); font-weight: 600; letter-spacing: 0.08em; }
92
+ </style>
93
+ </head>
94
+ <body>
95
+ <main class="card" role="status" aria-live="polite">
96
+ <div class="icon">${o}</div>
97
+ <h1>${W(e.title)}</h1>
98
+ <p>${W(e.message)}</p>
99
+ <div class="brand"><strong>KaneAI</strong> \xB7 CLI</div>
100
+ </main>
101
+ ${i}
102
+ </body>
103
+ </html>`}function W(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}export{ne as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as m}from"./chunk-HCBYKLMW.js";import{a as l,b as i,i as c}from"./chunk-C44QQJR4.js";import{e as p}from"./chunk-UR6MHSHU.js";var e=p(m(),1);function g({value:r,onChange:n,onSubmit:x,onCancel:d,placeholder:o,masked:a}){c((s,t)=>{if(t.return){x?.(r);return}if(t.escape){d?.();return}if(t.backspace||t.delete){n(r.slice(0,-1));return}t.tab||t.ctrl||t.meta||s&&n(r+s)});let f=a?"\u2022".repeat(r.length):r;return(0,e.jsx)(l,{children:r.length===0&&o?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(i,{inverse:!0,children:" "}),(0,e.jsx)(i,{dimColor:!0,children:o})]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(i,{children:f}),(0,e.jsx)(i,{inverse:!0,children:" "})]})})}export{g as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as h}from"./chunk-DXKKUGFG.js";var p=class extends h{constructor(e,t,s){super(e,{username:t,accessKey:s})}async listProjects(e){let t=[],s=!1;for await(let r of this.listProjectsStream({log:e})){if(e&&!s&&r.projects.length>0){let o=r.projects[0];e("info","PROJECT_SAMPLE","Project list sample",{project_id:o.project_id,name:o.name}),s=!0}t.push(...r.projects)}return t}async*listProjectsStream(e){let t=e?.perPage??200,s=e?.maxPages??100,r=e?.signal,o=e?.log,i=0;for(let a=1;a<=s;a++){if(r?.aborted)return;let d=`${this.baseUrl}/v1/projects?page=${a}&per_page=${t}&sort=created_at`,g=AbortSignal.timeout(15e3),u=r?AbortSignal.any([r,g]):g,n;try{n=await fetch(d,{method:"GET",headers:this.headers(),signal:u})}catch(c){if(r?.aborted)return;if(a===1)throw c;o?.("warn","PROJECTS_STREAM_PARTIAL","stream stopped mid-page",{page:a,total_loaded:i,error:c instanceof Error?c.message:String(c)}),yield{page:a,projects:[],totalLoaded:i,done:!0};return}if(!n.ok){if(a===1)throw new Error(`listProjects ${n.status}: ${await n.text()}`);o?.("warn","PROJECTS_STREAM_PARTIAL","stream stopped on non-OK response",{page:a,status:n.status,total_loaded:i}),yield{page:a,projects:[],totalLoaded:i,done:!0};return}let l=(await n.json()).data??[];i+=l.length;let m=l.length<t;if(yield{page:a,projects:l,totalLoaded:i,done:m},m)return}o?.("warn","PROJECTS_STREAM_MAXPAGES","max pages reached",{max_pages:s,total_loaded:i}),yield{page:s,projects:[],totalLoaded:i,done:!0}}async getDefaultFolder(e){let t=await fetch(`${this.baseUrl}/v1/projects/${e}/folder/default`,{method:"GET",headers:this.headers()});if(!t.ok)throw new Error(`Get default folder failed: ${t.status} ${await t.text()}`);return(await t.json()).id}async listFolders(e){let t=await fetch(`${this.baseUrl}/v1/folder/entity/${e}`,{method:"GET",headers:this.headers()});if(!t.ok)throw new Error(`List folders failed: ${t.status} ${await t.text()}`);return(await t.json()).data??[]}async createProject(e){let t=await fetch(`${this.baseUrl}/v1/projects`,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:JSON.stringify({name:e,description:"",tags:[],source:"KTM"})});if(!t.ok)throw new Error(`Create project failed: ${t.status} ${await t.text()}`);return{id:(await t.json()).id,name:e}}async createFolder(e,t){let s=await fetch(`${this.baseUrl}/v1/folder`,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:JSON.stringify({folders:[{name:t,description:"",entity_id:e,entity_type:"project"}]})});if(!s.ok)throw new Error(`Create folder failed: ${s.status} ${await s.text()}`);return{id:(await s.json()).id,name:t}}async createAtmTest(e,t){let s=t?`Bearer ${t}`:this.authHeader,r=await fetch(`${this.baseUrl}/kane-cli/v1/test`,{method:"POST",headers:{Authorization:s,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`Create ATM test failed: ${r.status} ${await r.text()}`);let o=await r.json();if(!o.test_id)throw new Error("Create ATM test returned no test_id");return o.test_id}async endTest(e,t,s){let r=s?`Bearer ${s}`:this.authHeader,o=new URLSearchParams({commit_id:t.commit_id,time_taken:String(t.time_taken),steps_count:String(t.steps_count),commit_message:t.commit_message}),i={};t.objectives&&t.objectives.length>0&&(i.objectives=t.objectives);let a=await fetch(`${this.baseUrl}/kane-cli/v1/test/${e}?${o.toString()}`,{method:"DELETE",headers:{Authorization:r,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new Error(`End test failed: ${a.status} ${await a.text()}`);let d=await a.json();return{testcase_id:d.data?.testcase_id??"",test_id:d.data?.test_id??e,project_id:d.data?.project_id??""}}async submitFeedback(e,t){let s=t?`Bearer ${t}`:this.authHeader,r={instruction_id:e.instruction_id,test_id:e.test_id,feedback_type:e.feedback_type,mode:e.mode??"human"};e.details&&(r.details=e.details);let o=await fetch(`${this.baseUrl}/atm/v1/generative-feedback`,{method:"POST",headers:{Authorization:s,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Submit feedback failed: ${o.status} ${await o.text()}`);return await o.json()}};export{p as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{f as R,g as x}from"./chunk-G7VF5SDK.js";import{b}from"./chunk-QV2VR72Q.js";import{a as v}from"./chunk-NLYBR5FP.js";import{a as y}from"./chunk-PWGEMRBD.js";var m=class extends Error{constructor(t,i){super(t);this.code=i;this.name="AuthError"}};async function k(e){let r=e.credentials.expires_at,t=e.thresholdSeconds??300;if(r-Date.now()/1e3>=t)return null;let i=e.creds.loadClient(e.profile,e.env);if(!i)return null;let n=await new b(e.env).refreshToken(e.credentials.refresh_token,i.client_id),s=Math.floor(Date.now()/1e3)+n.expires_in;return e.creds.saveCredentials(e.profile,e.env,{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:s,scope:n.scope}),{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:s,scope:n.scope}}async function P(e){let{creds:r,env:t,usernameFlag:i,accessKeyFlag:c,log:n}=e,s=null,u=null;if(i&&c)s={username:i,access_key:c},n("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:i});else{let a=r.resolveAuth();a?.method==="basic"&&(s={username:a.username,access_key:a.access_key},n("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:a.username}))}if(!s){let{credentials:a,profile:C}=r.getActiveCredentials();if(!a)throw new m("Not authenticated \u2014 no credentials found","not_authenticated");if(u=a.access_token,a.expires_at-Date.now()/1e3<300)try{let p=await k({creds:r,profile:C,env:t,credentials:a});p&&(u=p.accessToken,n("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(p){let h=p instanceof Error?p.message:String(p);throw n("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:h}),new m(`Token refresh failed: ${h}`,"refresh_failed")}}let A=v(t),E=async()=>u,S=s?{username:s.username,access_key:s.access_key}:null,g=new y(A.controllerBaseUrl,E,S,n),f=await g.resolve();return f&&!s&&(s={username:f.username,access_key:f.access_key},n("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:f.username})),{basicAuth:s,token:u,resolver:g,resolvedCreds:f}}async function U(e){if(!e.isInteractive)return{recovered:!1};if(_(e.creds,e.config))return{recovered:!1};let{SingleShotApp:r}=await import("./SingleShotApp-RLZN2PVQ.js"),{render:t}=await import("./build-JIKYOZUH.js"),i=await import("./react-QWOAB3TB.js"),c={current:null},n={current:!1},{waitUntilExit:s,unmount:u}=t(i.default.createElement(r,{resultRef:c,mode:"login",loginCompleteRef:n}),{exitOnCtrlC:!1});x(()=>u()),await s();try{process.stdin.setRawMode?.(!1)}catch{}return process.stdout.write("\x1B[?25h"),n.current?{recovered:!0}:(R(0,"Startup gate cancelled"),{recovered:!1})}function _(e,r){let t=e.getActiveProfile(),i=e.getDefaultEnv();if(!t||!!!(e.loadBasicAuth(t,i)||e.loadCredentials(t,i)))return!1;let n=r.load();return!!n.project_id&&!!n.folder_id}import{existsSync as o,renameSync as d,rmSync as l}from"fs";function H(e){let r=`${e}.staging`,t=`${e}.bak`;if(!o(r))throw new Error(`atomicReplaceDir: staging missing: ${r}`);if(process.platform==="win32"){o(e)&&l(e,{recursive:!0,force:!0}),d(r,e);return}o(e)&&(o(t)&&l(t,{recursive:!0,force:!0}),d(e,t)),d(r,e),o(t)&&l(t,{recursive:!0,force:!0})}function $(e){let r=`${e}.staging`,t=`${e}.bak`;if(process.platform==="win32"){o(r)&&(o(e)?l(r,{recursive:!0,force:!0}):d(r,e));return}if(o(t)&&!o(e)){d(t,e),o(r)&&l(r,{recursive:!0,force:!0});return}o(t)&&o(e)&&l(t,{recursive:!0,force:!0}),o(r)&&o(e)&&l(r,{recursive:!0,force:!0})}export{k as a,H as b,$ as c,m as d,P as e,U as f};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import"./chunk-UR6MHSHU.js";function s(e,t,r){return r?e.map(()=>({kind:"author",reason:"force-author"})):e.map((o,n)=>n<t?o:{kind:"author",reason:"retry-promoted"})}export{s as effectiveDecisions};