@testmuai/kane-cli 0.6.2 → 0.6.3

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 (106) hide show
  1. package/dist/ChatSurface-J777M5WC.js +8 -0
  2. package/dist/{ChromeProfilePicker-XXNZLSCC.js → ChromeProfilePicker-UUGUMJPI.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-FJF5INQO.js → CliFeedbackPrompt-JZWESL7Z.js} +1 -1
  4. package/dist/{CliUploadProgress-5E3CCYPZ.js → CliUploadProgress-62U3LAUU.js} +1 -1
  5. package/dist/{ConfigView-TGVOKOUZ.js → ConfigView-WHEFCVHR.js} +1 -1
  6. package/dist/{EvidenceViewOffer-7O3RNBEE.js → EvidenceViewOffer-JQDEAE2T.js} +1 -1
  7. package/dist/{FolderPicker-T4JB4NNW.js → FolderPicker-HJUUHQEI.js} +1 -1
  8. package/dist/{HelpView-PSHKI7DD.js → HelpView-EWHP7LSJ.js} +1 -1
  9. package/dist/{InfoBox-PXWJ6BIX.js → InfoBox-GQQJVTI5.js} +1 -1
  10. package/dist/{LinksBox-IUOYRXYO.js → LinksBox-EWCPAZFN.js} +1 -1
  11. package/dist/{ProfilesView-UK5XX5WP.js → ProfilesView-5FJNQMUW.js} +1 -1
  12. package/dist/{ProjectPicker-3FE7UFXL.js → ProjectPicker-IN7GFN7I.js} +1 -1
  13. package/dist/{SaveSessionPrompt-P7NF5FDA.js → SaveSessionPrompt-ISODGFP7.js} +1 -1
  14. package/dist/SingleShotApp-QANGFAPO.js +2 -0
  15. package/dist/{SummaryBox-WVR4U3NN.js → SummaryBox-R6WHU7VD.js} +1 -1
  16. package/dist/TestMdRunView-74A3LCNE.js +2 -0
  17. package/dist/{WhoamiView-QVXJAVTC.js → WhoamiView-YRQNOSOH.js} +1 -1
  18. package/dist/{bind-SRZYTS4Q.js → bind-FZ4X4SOK.js} +2 -2
  19. package/dist/{bridge-I6N3YPXI.js → bridge-7UMWMIJJ.js} +1 -1
  20. package/dist/{changelog-HPSX3L7T.js → changelog-YQC2QDCO.js} +1 -1
  21. package/dist/chat-controller-QXFAB2DK.js +3 -0
  22. package/dist/{chunk-HUD7SPUF.js → chunk-2S4S2XJC.js} +1 -1
  23. package/dist/{chunk-DEYHK6ZC.js → chunk-2TVRHXRK.js} +1 -1
  24. package/dist/{chunk-6XKJH5ZE.js → chunk-326XAPMW.js} +2 -2
  25. package/dist/{chunk-TJRBV2V2.js → chunk-53VDR5DN.js} +3 -3
  26. package/dist/{chunk-X4QL2DAD.js → chunk-6RQAUK5F.js} +1 -1
  27. package/dist/{chunk-5ON7QQZO.js → chunk-7LFCSSPX.js} +10 -10
  28. package/dist/{chunk-2U5DZUC7.js → chunk-7MV5UF6O.js} +1 -1
  29. package/dist/{chunk-VL2UA23Z.js → chunk-7YQW4TFI.js} +1 -1
  30. package/dist/{chunk-KGFISJFM.js → chunk-ARS72637.js} +1 -1
  31. package/dist/{chunk-KRFGAVYU.js → chunk-AV5SUGRY.js} +1 -1
  32. package/dist/{chunk-K2MKBBI4.js → chunk-B5LJCGAY.js} +1 -1
  33. package/dist/{chunk-Z4K4AYEI.js → chunk-BFFCGEUH.js} +1 -1
  34. package/dist/{chunk-FU3OQXFH.js → chunk-BGGNBWAJ.js} +1 -1
  35. package/dist/{chunk-4PIMEZJW.js → chunk-BO3JA2GS.js} +3 -3
  36. package/dist/{chunk-D5DEWIAU.js → chunk-C5POEXSX.js} +2 -2
  37. package/dist/{chunk-HR7AGYV2.js → chunk-CIW2KP4C.js} +1 -1
  38. package/dist/{chunk-XN7PPLFS.js → chunk-DEEBPSJN.js} +1 -1
  39. package/dist/{chunk-QIE62H3J.js → chunk-E4OYR32M.js} +1 -1
  40. package/dist/{chunk-Q6TVDG3X.js → chunk-EEO4XWY6.js} +1 -1
  41. package/dist/{chunk-PJSCM6JX.js → chunk-EWFFJBAM.js} +1 -1
  42. package/dist/{chunk-S6GRW5ZA.js → chunk-F2K3XFFH.js} +2 -2
  43. package/dist/{chunk-M6DX4ENH.js → chunk-F66SSA4C.js} +1 -1
  44. package/dist/{chunk-44QUA6GV.js → chunk-FFL2TQEJ.js} +1 -1
  45. package/dist/{chunk-FOZVXYVG.js → chunk-G6AF2JUA.js} +1 -1
  46. package/dist/{chunk-GN3SZXZ5.js → chunk-ME5QSYWX.js} +1 -1
  47. package/dist/{chunk-52VLJKIN.js → chunk-NFGG5DA2.js} +1 -1
  48. package/dist/{chunk-YSK535OI.js → chunk-OE7TVGNB.js} +2 -2
  49. package/dist/{chunk-6UNTIXFW.js → chunk-OGVIHL5G.js} +1 -1
  50. package/dist/{chunk-35SRW4KA.js → chunk-P46TIMGQ.js} +1 -1
  51. package/dist/{chunk-N62EM6JX.js → chunk-PJDOXRLB.js} +1 -1
  52. package/dist/{chunk-IDDVO4UV.js → chunk-Q4HLQOJI.js} +1 -1
  53. package/dist/chunk-RE3BZVGE.js +3 -0
  54. package/dist/{chunk-YIOWO6WS.js → chunk-RLG5NUTE.js} +1 -1
  55. package/dist/{chunk-ZGH7T32S.js → chunk-RZFINU7J.js} +1 -1
  56. package/dist/{chunk-WM5QHLAP.js → chunk-SGU72YLH.js} +4 -4
  57. package/dist/{chunk-OZM4UU5F.js → chunk-SHSV64GX.js} +1 -1
  58. package/dist/{chunk-4G4HPMR2.js → chunk-SL7AJ7JQ.js} +1 -1
  59. package/dist/{chunk-LZKUF23A.js → chunk-SQFNMZJ2.js} +1 -1
  60. package/dist/{chunk-B2CIHKXG.js → chunk-TTSYHJLX.js} +1 -1
  61. package/dist/chunk-TY5LWU6I.js +14 -0
  62. package/dist/{chunk-L4AUCQVO.js → chunk-TZZYRDCF.js} +1 -1
  63. package/dist/{chunk-DCYTRYR2.js → chunk-UXJPCWGW.js} +1 -1
  64. package/dist/{chunk-MHQ6A2QZ.js → chunk-VXGOWBET.js} +1 -1
  65. package/dist/{chunk-BKGJGPDN.js → chunk-WFRL54GK.js} +1 -1
  66. package/dist/{chunk-EK2B2LZK.js → chunk-XBE7PGVY.js} +1 -1
  67. package/dist/{chunk-OZODSY6H.js → chunk-Y6LMHBLE.js} +1 -1
  68. package/dist/{chunk-LV5VRSPI.js → chunk-Y7KW5AEN.js} +1 -1
  69. package/dist/{chunk-U3JB76QP.js → chunk-YZKPZXHY.js} +1 -1
  70. package/dist/{chunk-NEZ4G7XR.js → chunk-YZSYXNMB.js} +1 -1
  71. package/dist/{config-KD62VH3R.js → config-5OOP2BO3.js} +1 -1
  72. package/dist/{credentials-NQNJR4E4.js → credentials-XCP6DJZZ.js} +1 -1
  73. package/dist/{evidence-FFOI2H3N.js → evidence-AX67Q6RN.js} +1 -1
  74. package/dist/{evolve-cmd-PHQ6FHRI.js → evolve-cmd-HR25DRTC.js} +1 -1
  75. package/dist/{extract-bind-6UMILP4U.js → extract-bind-ZDAXRQUS.js} +2 -2
  76. package/dist/{extract-cmd-MZR7PHGA.js → extract-cmd-5GGI6LAM.js} +1 -1
  77. package/dist/{generate-headless-XOBQS6RU.js → generate-headless-DRDE46ON.js} +2 -2
  78. package/dist/index.js +12 -12
  79. package/dist/{interactive-bind-5FWW3S53.js → interactive-bind-T6OBLZCT.js} +2 -2
  80. package/dist/{list-commands-PDTISP6T.js → list-commands-UDAL3SBY.js} +1 -1
  81. package/dist/login-flow-LJ4BH3OS.js +2 -0
  82. package/dist/{persist-recorded-session-5UNUINWF.js → persist-recorded-session-BW3YSFMP.js} +1 -1
  83. package/dist/{pipeline-F4WTOZ3Y.js → pipeline-TZJ652NT.js} +1 -1
  84. package/dist/{reconcile-cmd-MNMWAZF3.js → reconcile-cmd-242S7XNO.js} +2 -2
  85. package/dist/{recording-banner-IWY3GS6N.js → recording-banner-6FVTCUWQ.js} +1 -1
  86. package/dist/{require-project-folder-PFIDA5ZH.js → require-project-folder-AQUVEEJB.js} +1 -1
  87. package/dist/run-UGAOGR3B.js +2 -0
  88. package/dist/{run-test-md-7GONSVAM.js → run-test-md-AUK7NGLL.js} +2 -2
  89. package/dist/{skill-installer-YZP5DWWZ.js → skill-installer-2MNPCPRD.js} +1 -1
  90. package/dist/{spawner-YDYCSTZD.js → spawner-XCOMTJJC.js} +1 -1
  91. package/dist/tcg-generate-E5X23RVP.js +2 -0
  92. package/dist/{testmd-actions-7RNW76DN.js → testmd-actions-TU4KTO32.js} +1 -1
  93. package/dist/token-refresh-GGLARJV4.js +2 -0
  94. package/dist/{validate-basic-IQY5CRLP.js → validate-basic-IYMPP7C7.js} +1 -1
  95. package/dist/{version-check-U5UBPVX4.js → version-check-MUPSKONS.js} +1 -1
  96. package/package.json +6 -6
  97. package/dist/ChatSurface-HGP5EHZM.js +0 -9
  98. package/dist/SingleShotApp-UIDA54GB.js +0 -2
  99. package/dist/TestMdRunView-OH4Y6YD6.js +0 -2
  100. package/dist/chat-controller-VKGECDTU.js +0 -3
  101. package/dist/chunk-DM2GL24Z.js +0 -3
  102. package/dist/chunk-HW7Z5S2M.js +0 -14
  103. package/dist/login-flow-IXPJHTL2.js +0 -2
  104. package/dist/run-V2WMNHFK.js +0 -2
  105. package/dist/tcg-generate-ZRKSX2KC.js +0 -2
  106. package/dist/token-refresh-DH2L2IPP.js +0 -2
@@ -1,9 +1,9 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as z}from"./chunk-I2S6KNZW.js";import{b as H,d as Q}from"./chunk-DM2GL24Z.js";import{d as j}from"./chunk-JFAFKHDX.js";import{a as G}from"./chunk-YKTYVJBN.js";import{d as U}from"./chunk-KHDUQ33H.js";import{a as B}from"./chunk-D5T4ARTB.js";import{a as I,c as O}from"./chunk-QIE62H3J.js";import{randomBytes as Ze}from"crypto";function X(t,e){let n=Math.min(t.length,e.length),s=0,r=0,a=0;for(let o=0;o<n;o++)s+=t[o]*e[o],r+=t[o]*t[o],a+=e[o]*e[o];return r===0||a===0?0:s/(Math.sqrt(r)*Math.sqrt(a))}function K(t,e,n){return n*t+(1-n)*e}var J=.7;import{readFileSync as xe,writeFileSync as Ae,renameSync as ve,mkdirSync as ke}from"fs";import{dirname as Se,join as W}from"path";function Ee(t){return W(t,"embeddings")}function Re(t){let e=t.indexOf(":");return e>=0?t.slice(e+1):t}function Y(t,e,n){let s=Re(n);return W(Ee(t),e,s.slice(0,2),`${s.slice(2)}.f32`)}function Z(t,e,n){try{let s=xe(Y(t,e,n)),r=new Float32Array(Math.floor(s.length/4));for(let a=0;a<r.length;a++)r[a]=s.readFloatLE(a*4);return r}catch{return null}}function q(t,e,n,s){try{let r=Y(t,e,n);ke(Se(r),{recursive:!0});let a=Buffer.alloc(s.length*4);for(let d=0;d<s.length;d++)a.writeFloatLE(s[d],d*4);let o=`${r}.tmp`;Ae(o,a),ve(o,r)}catch(r){process.stderr.write(`[embed] Failed to cache vector: ${r instanceof Error?r.message:String(r)}
2
+ import{a as z}from"./chunk-I2S6KNZW.js";import{b as H,d as Q}from"./chunk-RE3BZVGE.js";import{d as j}from"./chunk-JFAFKHDX.js";import{a as G}from"./chunk-YKTYVJBN.js";import{d as U}from"./chunk-KHDUQ33H.js";import{a as B}from"./chunk-D5T4ARTB.js";import{a as I,c as O}from"./chunk-E4OYR32M.js";function rt(t){let e=process.env.HOME??"";return e&&t.startsWith(e)?`~${t.slice(e.length)}`:t}import{randomBytes as Ze}from"crypto";function X(t,e){let n=Math.min(t.length,e.length),s=0,r=0,a=0;for(let o=0;o<n;o++)s+=t[o]*e[o],r+=t[o]*t[o],a+=e[o]*e[o];return r===0||a===0?0:s/(Math.sqrt(r)*Math.sqrt(a))}function K(t,e,n){return n*t+(1-n)*e}var W=.7;import{readFileSync as xe,writeFileSync as Ae,renameSync as ve,mkdirSync as ke}from"fs";import{dirname as Se,join as J}from"path";function Ee(t){return J(t,"embeddings")}function Re(t){let e=t.indexOf(":");return e>=0?t.slice(e+1):t}function Y(t,e,n){let s=Re(n);return J(Ee(t),e,s.slice(0,2),`${s.slice(2)}.f32`)}function Z(t,e,n){try{let s=xe(Y(t,e,n)),r=new Float32Array(Math.floor(s.length/4));for(let a=0;a<r.length;a++)r[a]=s.readFloatLE(a*4);return r}catch{return null}}function q(t,e,n,s){try{let r=Y(t,e,n);ke(Se(r),{recursive:!0});let a=Buffer.alloc(s.length*4);for(let d=0;d<s.length;d++)a.writeFloatLE(s[d],d*4);let o=`${r}.tmp`;Ae(o,a),ve(o,r)}catch(r){process.stderr.write(`[embed] Failed to cache vector: ${r instanceof Error?r.message:String(r)}
3
3
  `)}}var $e=["get_node","get_edges","find_by_provenance","match_by_type","stale_nodes","search_similar"],Ce=["source_read","source_grep"],Me=[...$e,...Ce],re=50,N=200,se=10,ie=50,ee=20,Te=200,De=50;function D(t,e,n){let s=typeof t=="number"&&Number.isFinite(t)?Math.floor(t):e;return Math.max(1,Math.min(s,n))}function k(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new y(`param "${e}" must be a non-empty string`);return n}function v(t,e){let n=t[e];if(n==null)return null;if(typeof n!="string")throw new y(`param "${e}" must be a string when present`);return n}var y=class extends Error{};function P(t,e){let n=t.getNode(e);return n?{cid:e,label:n.label,content:n.content,trust:t.trust.get(e)??null,freshness:t.stale(e)}:null}function te(t){return new Set(t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").split(" ").filter(Boolean))}function oe(t,...e){let n=te(t);if(n.size===0)return 0;let s=t.trim().toLowerCase(),r=0;for(let a of e){let o=te(a);if(o.size===0)continue;let d=0;for(let c of n)o.has(c)&&d++;let u=n.size+o.size-d,m=u===0?0:d/u;s&&a.toLowerCase().includes(s)&&(m=Math.max(m,.9)),r=Math.max(r,m)}return r}function Fe(t,e){let n=k(e,"cid"),s=v(e,"type"),r=v(e,"direction")??"both";if(!["out","in","both"].includes(r))throw new y('param "direction" must be out|in|both');let a=D(e.limit,re,N),o=[];return(r==="out"||r==="both")&&o.push(...t.edgesFrom(n)),(r==="in"||r==="both")&&o.push(...t.edgesInto(n)),o.filter(d=>s==null||d.type===s).slice(0,a)}function Le(t,e){let n=k(e,"source_id"),s=t.heads.get(n)??null,r=[];for(let a of t.nodeLabel.keys()){let o=t.derivesInto(a).filter(u=>u.props.source_id===n).map(u=>({source_cid:u.props.source_cid,anchor:u.props.anchor??null}));if(o.length===0)continue;let d=P(t,a);if(d&&(r.push({...d,pins:o,pinned_to_head:s!=null&&o.some(u=>u.source_cid===s)}),r.length>=N))break}return r}function Ge(t,e){let n=k(e,"label"),s=v(e,"trust"),r=v(e,"freshness"),a=D(e.limit,re,N),o=[];for(let{cid:d}of t.byLabel(n)){let u=P(t,d);if(u&&!(s!=null&&u.trust!==s)&&!(r!=null&&u.freshness!==r)&&(o.push(u),o.length>=a))break}return o}function Ne(t){return t.staleList().map(({cid:e,state:n})=>{let s=t.getNode(e);return{cid:e,state:n,label:s?.label??null,title:s?.content.title??null}})}function Pe(t,e){let n=k(e,"text"),s=v(e,"label")??"usecase",r=D(e.k,se,ie),a=[];for(let{cid:o,content:d}of t.byLabel(s)){let u=String(d.title??""),m=String(d.summary??""),c=oe(n,u,m);c<=0||a.push({cid:o,title:u,summary:m,score:Math.round(c*1e3)/1e3,trust:t.trust.get(o)??null,freshness:t.stale(o)})}return a.sort((o,d)=>d.score-o.score||o.cid.localeCompare(d.cid)),a.slice(0,r)}function ae(t,e,n){let s=t.heads.get(n);if(typeof s!="string"){let o=[...t.heads.keys()].sort().join(", ");throw new y(`unknown source_id "${n}" \u2014 known: ${o||"(none)"}`)}if(t.mediaOf(s).format==="image")throw new y(`source "${n}" is an image \u2014 no line window (cite img#whole)`);let r=t.getNode(s)?.content?.blob,a=typeof r=="string"?U(e,r):null;if(a==null)throw new y(`source "${n}" blob is missing from the store`);return{head:s,lines:a.toString("utf8").replace(/\n$/,"").split(`
4
4
  `)}}function Ve(t,e,n){return t.slice(e-1,n).map((s,r)=>`${String(e+r).padStart(4,"0")}| ${s}`).join(`
5
5
  `)}function Ie(t,e,n){let s=k(e,"source_id"),r=v(e,"anchor"),a=e.line_range;if(r!=null&&a!=null)throw new y("give anchor OR line_range, not both");let{head:o,lines:d}=ae(t,n,s),u=d.length,m,c;if(r!=null){let f=/^L(\d+)-L(\d+)$/.exec(r);if(!f)throw new y(`anchor "${r}" is not L<a>-L<b>`);let h=Number(f[1]),b=Number(f[2]);if(h<1||b<h||b>u)throw new y(`anchor "${r}" does not resolve (source has ${u} lines)`);m=Math.max(1,h-ee),c=Math.min(u,b+ee)}else if(a!=null){if(!Array.isArray(a)||a.length!==2||!a.every(b=>Number.isInteger(b)))throw new y('param "line_range" must be [from_line, to_line]');let[f,h]=a;if(f<1||h<f)throw new y('param "line_range" must be 1-based with from \u2264 to');if(f>u)throw new y(`line_range starts past the end (source has ${u} lines)`);m=f,c=Math.min(h,u)}else m=1,c=u;return c=Math.min(c,m+Te-1),{window:Ve(d,m,c),from_line:m,to_line:c,source_cid:o}}function Oe(t,e,n){let s=k(e,"pattern"),r=v(e,"source_id"),a;try{a=new RegExp(s,"u")}catch(m){throw new y(`invalid pattern: ${m instanceof Error?m.message:String(m)}`)}let o=r!=null?[r]:[...t.heads.keys()].sort(),d=[],u=!1;e:for(let m of o){if(r==null){let f=t.heads.get(m);if(typeof f!="string"||t.mediaOf(f).format==="image")continue}let{lines:c}=ae(t,n,m);for(let f=0;f<c.length;f++)if(a.test(c[f])){if(d.length>=De){u=!0;break e}d.push({source_id:m,line:f+1,text:c[f]})}}return{matches:d,truncated:u}}function Be(t,e,n,s){try{switch(e){case"get_node":return{ok:!0,result:P(t,k(n,"cid"))};case"get_edges":return{ok:!0,result:Fe(t,n)};case"find_by_provenance":return{ok:!0,result:Le(t,n)};case"match_by_type":return{ok:!0,result:Ge(t,n)};case"stale_nodes":return{ok:!0,result:Ne(t)};case"search_similar":return{ok:!0,result:Pe(t,n)};case"source_read":case"source_grep":{if(s==null)throw new y("source text unavailable (no context store)");return{ok:!0,result:(e==="source_read"?Ie:Oe)(t,n,s)}}default:return{ok:!1,error:`unknown method: ${e} \u2014 available: ${Me.join(", ")}`}}}catch(r){return r instanceof y?{ok:!1,error:`${e}: ${r.message}`}:{ok:!1,error:`${e}: graph read failed: ${r instanceof Error?r.message:String(r)}`}}}var ne="assurance.sim";function Ue(t){return[t.title,t.summary,t.description].filter(Boolean).join(`
6
- `)}async function je(t,e,n){let s=k(e,"text"),r=v(e,"label")??"usecase",a=D(e.k,se,ie),o=[];for(let{cid:u,content:m}of t.byLabel(r)){if(t.superseded.has(u))continue;let c=String(m.title??""),f=String(m.summary??""),h=String(m.description??"");o.push({cid:u,title:c,summary:f,description:h,lex:oe(s,c,f,h)})}let d=u=>{let m=[];for(let c of o){let f=u(c);f.score<=0||m.push({cid:c.cid,title:c.title,summary:c.summary,score:Math.round(f.score*1e3)/1e3,trust:t.trust.get(c.cid)??null,freshness:t.stale(c.cid),...f.dense!==void 0?{dense_score:Math.round(f.dense*1e3)/1e3,lexical_score:Math.round(c.lex*1e3)/1e3}:{}})}return m.sort((c,f)=>f.score-c.score||c.cid.localeCompare(f.cid)),m.slice(0,a)};try{let u=n.readVector??Z,m=n.writeVector??q,c=n.alpha??J,{alias:f}=await n.resolveAlias(ne),h=new Map,b=[],R=[];for(let _ of o){let x=u(n.contextDir,f,_.cid);x?h.set(_.cid,x):(b.push(_.cid),R.push(Ue(_)))}let{vectors:S}=await n.embed(ne,[s,...R]),$=Float32Array.from(S[0]);for(let _=0;_<b.length;_++){let x=Float32Array.from(S[_+1]);h.set(b[_],x),m(n.contextDir,f,b[_],x)}return d(_=>{let x=h.get(_.cid),w=x?X($,x):0;return{score:K(w,_.lex,c),dense:w}})}catch{return d(u=>({score:u.lex}))}}async function ce(t,e,n,s){if(e==="search_similar"&&s)try{return{ok:!0,result:await je(t,n,s)}}catch(r){return r instanceof y?{ok:!1,error:`${e}: ${r.message}`}:{ok:!1,error:`${e}: graph read failed: ${r instanceof Error?r.message:String(r)}`}}return Be(t,e,n,s?.contextDir)}import{readFileSync as He,writeFileSync as Qe,renameSync as ze,mkdirSync as Xe}from"fs";import{dirname as Ke,join as Je}from"path";var V=1,We=720*60*1e3;function F(t){return Je(O,"embeddings",`alias-${t}.json`)}function le(t,e=Date.now()){return t!==null&&e-t.fetchedAt<We}function ue(t){try{let e=JSON.parse(He(t,"utf-8"));return e.wrapperVersion!==V||typeof e.purposes!="object"||e.purposes===null?null:{wrapperVersion:V,writtenByVersion:String(e.writtenByVersion??""),purposes:e.purposes}}catch{return null}}function de(t,e,n=F(t)){let r=ue(n)?.purposes?.[e];return!r||typeof r.alias!="string"||typeof r.dims!="number"||typeof r.fetchedAt!="number"?null:{alias:r.alias,dims:r.dims,fetchedAt:r.fetchedAt}}function me(t,e,n,s=F(t)){try{Xe(Ke(s),{recursive:!0});let a=ue(s)?.purposes??{};a[e]={alias:n.alias,dims:n.dims,fetchedAt:Date.now()};let o={wrapperVersion:V,writtenByVersion:I,purposes:a},d=`${s}.tmp`;Qe(d,JSON.stringify(o,null,2)+`
6
+ `)}async function je(t,e,n){let s=k(e,"text"),r=v(e,"label")??"usecase",a=D(e.k,se,ie),o=[];for(let{cid:u,content:m}of t.byLabel(r)){if(t.superseded.has(u))continue;let c=String(m.title??""),f=String(m.summary??""),h=String(m.description??"");o.push({cid:u,title:c,summary:f,description:h,lex:oe(s,c,f,h)})}let d=u=>{let m=[];for(let c of o){let f=u(c);f.score<=0||m.push({cid:c.cid,title:c.title,summary:c.summary,score:Math.round(f.score*1e3)/1e3,trust:t.trust.get(c.cid)??null,freshness:t.stale(c.cid),...f.dense!==void 0?{dense_score:Math.round(f.dense*1e3)/1e3,lexical_score:Math.round(c.lex*1e3)/1e3}:{}})}return m.sort((c,f)=>f.score-c.score||c.cid.localeCompare(f.cid)),m.slice(0,a)};try{let u=n.readVector??Z,m=n.writeVector??q,c=n.alpha??W,{alias:f}=await n.resolveAlias(ne),h=new Map,b=[],R=[];for(let _ of o){let x=u(n.contextDir,f,_.cid);x?h.set(_.cid,x):(b.push(_.cid),R.push(Ue(_)))}let{vectors:S}=await n.embed(ne,[s,...R]),$=Float32Array.from(S[0]);for(let _=0;_<b.length;_++){let x=Float32Array.from(S[_+1]);h.set(b[_],x),m(n.contextDir,f,b[_],x)}return d(_=>{let x=h.get(_.cid),w=x?X($,x):0;return{score:K(w,_.lex,c),dense:w}})}catch{return d(u=>({score:u.lex}))}}async function ce(t,e,n,s){if(e==="search_similar"&&s)try{return{ok:!0,result:await je(t,n,s)}}catch(r){return r instanceof y?{ok:!1,error:`${e}: ${r.message}`}:{ok:!1,error:`${e}: graph read failed: ${r instanceof Error?r.message:String(r)}`}}return Be(t,e,n,s?.contextDir)}import{readFileSync as He,writeFileSync as Qe,renameSync as ze,mkdirSync as Xe}from"fs";import{dirname as Ke,join as We}from"path";var V=1,Je=720*60*1e3;function F(t){return We(O,"embeddings",`alias-${t}.json`)}function le(t,e=Date.now()){return t!==null&&e-t.fetchedAt<Je}function ue(t){try{let e=JSON.parse(He(t,"utf-8"));return e.wrapperVersion!==V||typeof e.purposes!="object"||e.purposes===null?null:{wrapperVersion:V,writtenByVersion:String(e.writtenByVersion??""),purposes:e.purposes}}catch{return null}}function de(t,e,n=F(t)){let r=ue(n)?.purposes?.[e];return!r||typeof r.alias!="string"||typeof r.dims!="number"||typeof r.fetchedAt!="number"?null:{alias:r.alias,dims:r.dims,fetchedAt:r.fetchedAt}}function me(t,e,n,s=F(t)){try{Xe(Ke(s),{recursive:!0});let a=ue(s)?.purposes??{};a[e]={alias:n.alias,dims:n.dims,fetchedAt:Date.now()};let o={wrapperVersion:V,writtenByVersion:I,purposes:a},d=`${s}.tmp`;Qe(d,JSON.stringify(o,null,2)+`
7
7
  `),ze(d,s)}catch(r){process.stderr.write(`[embed] Failed to save alias cache: ${r instanceof Error?r.message:String(r)}
8
- `)}}function Ye(t){return t.TESTMUAI_ENV==="stage"?"stage":"prod"}function fe(t){let e=t.env??process.env,n=t.auth?.TESTMUAI_BASIC_AUTH||e.TESTMUAI_BASIC_AUTH;if(n)return{authorization:`Basic ${n}`};let s=t.auth?.TESTMUAI_API_KEY||e.TESTMUAI_API_KEY;return s?{authorization:`Bearer ${s}`}:{}}async function ge(t,e={}){let n=e.env??process.env,s=Ye(n),r=e.aliasCacheFile??F(s),a=e.now??Date.now,o=de(s,t,r);if(le(o,a()))return{alias:o.alias,dims:o.dims};let u=`${G(n)}/assurance/embed/alias?purpose=${encodeURIComponent(t)}`,m=await(e.fetchImpl??fetch)(u,{method:"GET",headers:fe(e)});if(!m.ok)throw new Error(`embed alias resolve failed: ${m.status}`);let c=await m.json();return me(s,t,{alias:c.alias,dims:c.dims},r),{alias:c.alias,dims:c.dims}}async function pe(t,e,n={}){let s=n.env??process.env,r=G(s),a=await(n.fetchImpl??fetch)(`${r}/assurance/embed`,{method:"POST",headers:{...fe(n),"content-type":"application/json"},body:JSON.stringify({purpose:t,input:e})});if(!a.ok)throw new Error(`embed failed: ${a.status}`);return await a.json()}var qe=2,he=10,et=2;function _e(t,e,n){return t.map(s=>{let r=e.find(a=>a.id===s.id);return r&&r.selected_index!=null&&r.selected_index>=0&&r.selected_index<s.options.length?{id:s.id,resolution:"answered",selected_index:r.selected_index,free_text:null}:r&&r.free_text!=null&&s.allow_free_text?{id:s.id,resolution:"answered",selected_index:-1,free_text:r.free_text}:n.explicitAcceptDefaults?{id:s.id,resolution:"assumed-default",selected_index:s.recommended_index,flagged:!0}:{id:s.id,resolution:"deferred",selected_index:null}})}async function At(t,e,n,s,r=()=>{},a){let o=(i,l)=>r(i,l,t.session_id),d=(process.env.ASSURANCE_LOG_LEVEL??"info").toLowerCase()==="debug",u={contextDir:e.contextDir,resolveAlias:i=>ge(i,{env:process.env,auth:e.auth}),embed:(i,l)=>pe(i,l,{env:process.env,auth:e.auth})},m=0,c=e.agent(t,{auth:e.auth,onWarn:i=>{o("warn",i),e.out(i)},onStderr:i=>o("agent_stderr",i)}),f=null,h=null,b;e.chat?.attachSender?.(i=>c.send(i)),e.initialMessage&&(c.send({type:"user_message",message_id:`msg-${t.session_id}-${Ze(3).toString("hex")}`,text:e.initialMessage}),o("user_message_sent",{chars:e.initialMessage.length,...d?{text:e.initialMessage}:{}}),e.emit?.({type:"message_sent",sid:t.session_id,chars:e.initialMessage.length}),e.chat?.note(`delivered your message to the agent: "${e.initialMessage}"`));let R,S=0,$=0,_=0,x,w=H(),C=e.progress??e.out;try{for await(let i of c.events){try{e.chat?.onAgentEvent(i)}catch(l){o("chat_mirror_error",{event_type:i.type,message:l instanceof Error?l.message:String(l)})}if(i.type==="reasoning_delta"?(m+=i.text.length,process.env.KANE_TRACE_REASONING&&o("reasoning_delta",i.text)):o(i.type,i),i.type==="reasoning_done"&&o("reasoning_chars",m),i.type==="progress")C(`\u2026 ${i.stage}${i.n?` #${i.n}`:""}`),e.emit?.({type:"agent_activity",kind:"progress",label:`${i.stage}${i.n?` #${i.n}`:""}`});else if(i.type==="reasoning_delta"||i.type==="reasoning_done"||i.type==="tool_activity"||i.type==="decision_activity"){e.onStreamEvent?.(i);let l=w;if(w=Q(w,i),w===l)continue;i.type==="reasoning_delta"?w.liveThinking===i.text&&C("\u2237 thinking\u2026"):i.type==="reasoning_done"?i.present&&(C(`thought for ${(i.took_ms/1e3).toFixed(1)}s`),e.emit?.({type:"agent_activity",kind:"thinking_done",label:`thought for ${(i.took_ms/1e3).toFixed(1)}s`})):i.type==="tool_activity"?i.status!=="done"&&(C(w.activity[w.activity.length-1].label),e.emit?.({type:"agent_activity",kind:"tool",label:w.activity[w.activity.length-1].label})):(C(`\xB7 ${w.activity[w.activity.length-1].label}`),e.emit?.({type:"agent_activity",kind:"decision",label:w.activity[w.activity.length-1].label}))}else if(i.type==="usage")x=i.total_credits,e.emit?.({type:"usage",credits:i.credits,total_credits:i.total_credits});else if(i.type==="graph_query"){let l=await ce(e.graphSlot?.current??s,i.method,i.params??{},u),A=l.ok?{type:"graph_result",id:i.id,ok:!0,result:l.result}:{type:"graph_result",id:i.id,ok:!1,error:l.error};o("graph_result",d?{id:i.id,method:i.method,ok:l.ok,result:l.ok?l.result:l.error}:{id:i.id,method:i.method,ok:l.ok}),c.send(A)}else if(i.type==="session_paused")b=i;else if(i.type==="ask_user"){i.text&&(e.chat?e.chat.ledger({kind:"agent",text:i.text}):e.out(i.text));let l=t.mode;if(l!=="interactive"){let g=i.questions.filter(p=>p.risk==="high");if(l==="ci"&&g.length>0){R=g,c.kill();break}if(l==="agent"&&g.length>0){o("pause_requested",{high:g.map(p=>p.id)}),c.send({type:"pause"});continue}let E=_e(i.questions,[],{explicitAcceptDefaults:!0});S+=E.length;for(let p of E)o("assumed_default",{id:p.id,resolution:p.resolution}),e.emit?.({type:"assumed_default",id:p.id,selected_index:p.selected_index,risk:i.questions.find(T=>T.id===p.id)?.risk});let M={type:"user_response",answers:E.map(p=>({id:p.id,selected_index:p.resolution==="deferred"?null:p.selected_index,free_text:null}))};c.send(M);continue}let A=await e.ask(i.questions),ye=_e(i.questions,A,{explicitAcceptDefaults:!1}),we={type:"user_response",answers:i.questions.map(g=>{let E=A.find(p=>p.id===g.id);if(E?.free_text!=null){let p=n.get(g.id)??0;if(!g.allow_free_text||p>=qe){let T=g.options[g.recommended_index]?.label??"recommended option";if(S+=1,e.emit?.({type:"assumed_default",id:g.id,selected_index:g.recommended_index,risk:g.risk}),e.chat?.noteCoercion)e.chat.noteCoercion(g,T);else{let L=g.text.replace(/\?+\s*$/,""),be=L.length<=36?L:`${L.slice(0,33)}\u2026`;e.out(`note: couldn't use a typed answer for "${be}" \u2014 kept the recommended option (${T})`)}return{id:g.id,selected_index:g.recommended_index,free_text:null}}return n.set(g.id,p+1),{id:g.id,selected_index:null,free_text:E.free_text}}let M=ye.find(p=>p.id===g.id);return M.resolution==="deferred"?{id:g.id,selected_index:null,free_text:null}:{id:g.id,selected_index:M.selected_index,free_text:null}})};c.send(we)}else if(i.type==="chat_ops"&&!e.chat){let l=i.chat_ops??i,A=Array.isArray(l.ops)?l.ops.length:0;if(A===0)l.text&&e.out(l.text),c.send({type:"session_complete"}),o("headless_zero_op_chat_turn_complete",{chars:l.text?.length??0});else if(_<et)_+=1,c.send({type:"user_message",message_id:`nochat-${t.session_id}-${_}`,text:"[auto-repair] chat ops are unavailable in this mode \u2014 commit through finalize_design, or finish if nothing remains."}),o("headless_chat_ops_nudge",{n:_,ops:A});else{h="agent kept sending chat ops in a mode with no chat plane",e.out("error: agent kept sending chat ops in a mode with no chat plane \u2014 closing the session"),o("headless_chat_ops_terminal",{ops:A}),c.kill();break}}else if(i.type===(a.terminalEventType??"proposal")){let l=await a.onProposalEvent(i[i.type]);if(f=l.proposal,l.error&&(h=l.error),l.receipt)e.emit?.(l.receipt.event),t.mode!=="interactive"?($+=1,l.sessionComplete||$>=he?(l.sessionComplete||(e.out(`warning: ${he} commits without completion \u2014 closing the session (runaway guard)`),o("receipt_runaway_cap",{commits:$})),c.send({type:"session_complete"}),o("session_complete_sent",{commit_n:l.receipt.event.commit_n,runaway:!l.sessionComplete})):(c.send({type:"user_message",message_id:`receipt-${t.session_id}-${String(l.receipt.event.commit_n??0)}`,text:l.receipt.text}),o("receipt_sent",{commit_n:l.receipt.event.commit_n,chars:l.receipt.text.length}))):e.chat?.holdReceipt&&(e.chat.holdReceipt(l.receipt.text),o("receipt_held",{commit_n:l.receipt.event.commit_n}));else if(l.error&&t.mode!=="interactive"){e.out("error: commit failed with no repair channel \u2014 closing the session"),o("headless_commit_error_terminal",{error:l.error}),c.kill();break}}else if(i.type==="error"){h=i.message;let l=i.failed_proposal;l&&o("failed_proposal",l)}}}finally{c.kill()}return{proposal:f,error:h,paused:b,highRisk:R,...S>0?{assumedDefaults:S}:{},...x!==void 0?{creditsTotal:x}:{}}}var tt={kind:"system",id:"distiller"};function Rt(t,e=n=>process.stderr.write(n+`
9
- `)){try{let n=B(t),{watermark:s}=j(t),r=z({contextDir:t,graph:n,watermark:s,by:tt});if(r.errors){let a=r.errors.map(o=>`${o.code}: ${o.detail}`).join("; ");return e(`warning: style-note distill skipped \u2014 ${a}`),{minted:0,error:a}}return{minted:r.minted,error:null}}catch(n){let s=n instanceof Error?n.message:String(n);return e(`warning: style-note distill skipped \u2014 ${s}`),{minted:0,error:s}}}export{ce as a,ge as b,pe as c,qe as d,_e as e,At as f,Rt as g};
8
+ `)}}function Ye(t){return t.TESTMUAI_ENV==="stage"?"stage":"prod"}function fe(t){let e=t.env??process.env,n=t.auth?.TESTMUAI_BASIC_AUTH||e.TESTMUAI_BASIC_AUTH;if(n)return{authorization:`Basic ${n}`};let s=t.auth?.TESTMUAI_API_KEY||e.TESTMUAI_API_KEY;return s?{authorization:`Bearer ${s}`}:{}}async function ge(t,e={}){let n=e.env??process.env,s=Ye(n),r=e.aliasCacheFile??F(s),a=e.now??Date.now,o=de(s,t,r);if(le(o,a()))return{alias:o.alias,dims:o.dims};let u=`${G(n)}/assurance/embed/alias?purpose=${encodeURIComponent(t)}`,m=await(e.fetchImpl??fetch)(u,{method:"GET",headers:fe(e)});if(!m.ok)throw new Error(`embed alias resolve failed: ${m.status}`);let c=await m.json();return me(s,t,{alias:c.alias,dims:c.dims},r),{alias:c.alias,dims:c.dims}}async function pe(t,e,n={}){let s=n.env??process.env,r=G(s),a=await(n.fetchImpl??fetch)(`${r}/assurance/embed`,{method:"POST",headers:{...fe(n),"content-type":"application/json"},body:JSON.stringify({purpose:t,input:e})});if(!a.ok)throw new Error(`embed failed: ${a.status}`);return await a.json()}var qe=2,he=10,et=2;function _e(t,e,n){return t.map(s=>{let r=e.find(a=>a.id===s.id);return r&&r.selected_index!=null&&r.selected_index>=0&&r.selected_index<s.options.length?{id:s.id,resolution:"answered",selected_index:r.selected_index,free_text:null}:r&&r.free_text!=null&&s.allow_free_text?{id:s.id,resolution:"answered",selected_index:-1,free_text:r.free_text}:n.explicitAcceptDefaults?{id:s.id,resolution:"assumed-default",selected_index:s.recommended_index,flagged:!0}:{id:s.id,resolution:"deferred",selected_index:null}})}async function kt(t,e,n,s,r=()=>{},a){let o=(i,l)=>r(i,l,t.session_id),d=(process.env.ASSURANCE_LOG_LEVEL??"info").toLowerCase()==="debug",u={contextDir:e.contextDir,resolveAlias:i=>ge(i,{env:process.env,auth:e.auth}),embed:(i,l)=>pe(i,l,{env:process.env,auth:e.auth})},m=0,c=e.agent(t,{auth:e.auth,onWarn:i=>{o("warn",i),e.out(i)},onStderr:i=>o("agent_stderr",i)}),f=null,h=null,b;e.chat?.attachSender?.(i=>c.send(i)),e.initialMessage&&(c.send({type:"user_message",message_id:`msg-${t.session_id}-${Ze(3).toString("hex")}`,text:e.initialMessage}),o("user_message_sent",{chars:e.initialMessage.length,...d?{text:e.initialMessage}:{}}),e.emit?.({type:"message_sent",sid:t.session_id,chars:e.initialMessage.length}),e.chat?.note(`delivered your message to the agent: "${e.initialMessage}"`));let R,S=0,$=0,_=0,x,w=H(),C=e.progress??e.out;try{for await(let i of c.events){try{e.chat?.onAgentEvent(i)}catch(l){o("chat_mirror_error",{event_type:i.type,message:l instanceof Error?l.message:String(l)})}if(i.type==="reasoning_delta"?(m+=i.text.length,process.env.KANE_TRACE_REASONING&&o("reasoning_delta",i.text)):o(i.type,i),i.type==="reasoning_done"&&o("reasoning_chars",m),i.type==="progress")C(`\u2026 ${i.stage}${i.n?` #${i.n}`:""}`),e.emit?.({type:"agent_activity",kind:"progress",label:`${i.stage}${i.n?` #${i.n}`:""}`});else if(i.type==="reasoning_delta"||i.type==="reasoning_done"||i.type==="tool_activity"||i.type==="decision_activity"){e.onStreamEvent?.(i);let l=w;if(w=Q(w,i),w===l)continue;i.type==="reasoning_delta"?w.liveThinking===i.text&&C("\u2237 thinking\u2026"):i.type==="reasoning_done"?i.present&&(C(`thought for ${(i.took_ms/1e3).toFixed(1)}s`),e.emit?.({type:"agent_activity",kind:"thinking_done",label:`thought for ${(i.took_ms/1e3).toFixed(1)}s`})):i.type==="tool_activity"?i.status!=="done"&&(C(w.activity[w.activity.length-1].label),e.emit?.({type:"agent_activity",kind:"tool",label:w.activity[w.activity.length-1].label})):(C(`\xB7 ${w.activity[w.activity.length-1].label}`),e.emit?.({type:"agent_activity",kind:"decision",label:w.activity[w.activity.length-1].label}))}else if(i.type==="usage")x=i.total_credits,e.emit?.({type:"usage",credits:i.credits,total_credits:i.total_credits});else if(i.type==="graph_query"){let l=await ce(e.graphSlot?.current??s,i.method,i.params??{},u),A=l.ok?{type:"graph_result",id:i.id,ok:!0,result:l.result}:{type:"graph_result",id:i.id,ok:!1,error:l.error};o("graph_result",d?{id:i.id,method:i.method,ok:l.ok,result:l.ok?l.result:l.error}:{id:i.id,method:i.method,ok:l.ok}),c.send(A)}else if(i.type==="session_paused")b=i;else if(i.type==="ask_user"){i.text&&(e.chat?e.chat.ledger({kind:"agent",text:i.text}):e.out(i.text));let l=t.mode;if(l!=="interactive"){let g=i.questions.filter(p=>p.risk==="high");if(l==="ci"&&g.length>0){R=g,c.kill();break}if(l==="agent"&&g.length>0){o("pause_requested",{high:g.map(p=>p.id)}),c.send({type:"pause"});continue}let E=_e(i.questions,[],{explicitAcceptDefaults:!0});S+=E.length;for(let p of E)o("assumed_default",{id:p.id,resolution:p.resolution}),e.emit?.({type:"assumed_default",id:p.id,selected_index:p.selected_index,risk:i.questions.find(T=>T.id===p.id)?.risk});let M={type:"user_response",answers:E.map(p=>({id:p.id,selected_index:p.resolution==="deferred"?null:p.selected_index,free_text:null}))};c.send(M);continue}let A=await e.ask(i.questions),ye=_e(i.questions,A,{explicitAcceptDefaults:!1}),we={type:"user_response",answers:i.questions.map(g=>{let E=A.find(p=>p.id===g.id);if(E?.free_text!=null){let p=n.get(g.id)??0;if(!g.allow_free_text||p>=qe){let T=g.options[g.recommended_index]?.label??"recommended option";if(S+=1,e.emit?.({type:"assumed_default",id:g.id,selected_index:g.recommended_index,risk:g.risk}),e.chat?.noteCoercion)e.chat.noteCoercion(g,T);else{let L=g.text.replace(/\?+\s*$/,""),be=L.length<=36?L:`${L.slice(0,33)}\u2026`;e.out(`note: couldn't use a typed answer for "${be}" \u2014 kept the recommended option (${T})`)}return{id:g.id,selected_index:g.recommended_index,free_text:null}}return n.set(g.id,p+1),{id:g.id,selected_index:null,free_text:E.free_text}}let M=ye.find(p=>p.id===g.id);return M.resolution==="deferred"?{id:g.id,selected_index:null,free_text:null}:{id:g.id,selected_index:M.selected_index,free_text:null}})};c.send(we)}else if(i.type==="chat_ops"&&!e.chat){let l=i.chat_ops??i,A=Array.isArray(l.ops)?l.ops.length:0;if(A===0)l.text&&e.out(l.text),c.send({type:"session_complete"}),o("headless_zero_op_chat_turn_complete",{chars:l.text?.length??0});else if(_<et)_+=1,c.send({type:"user_message",message_id:`nochat-${t.session_id}-${_}`,text:"[auto-repair] chat ops are unavailable in this mode \u2014 commit through finalize_design, or finish if nothing remains."}),o("headless_chat_ops_nudge",{n:_,ops:A});else{h="agent kept sending chat ops in a mode with no chat plane",e.out("error: agent kept sending chat ops in a mode with no chat plane \u2014 closing the session"),o("headless_chat_ops_terminal",{ops:A}),c.kill();break}}else if(i.type===(a.terminalEventType??"proposal")){let l=await a.onProposalEvent(i[i.type]);if(f=l.proposal,l.error&&(h=l.error),l.receipt)e.emit?.(l.receipt.event),t.mode!=="interactive"?($+=1,l.sessionComplete||$>=he?(l.sessionComplete||(e.out(`warning: ${he} commits without completion \u2014 closing the session (runaway guard)`),o("receipt_runaway_cap",{commits:$})),c.send({type:"session_complete"}),o("session_complete_sent",{commit_n:l.receipt.event.commit_n,runaway:!l.sessionComplete})):(c.send({type:"user_message",message_id:`receipt-${t.session_id}-${String(l.receipt.event.commit_n??0)}`,text:l.receipt.text}),o("receipt_sent",{commit_n:l.receipt.event.commit_n,chars:l.receipt.text.length}))):e.chat?.holdReceipt&&(e.chat.holdReceipt(l.receipt.text),o("receipt_held",{commit_n:l.receipt.event.commit_n}));else if(l.error&&t.mode!=="interactive"){e.out("error: commit failed with no repair channel \u2014 closing the session"),o("headless_commit_error_terminal",{error:l.error}),c.kill();break}}else if(i.type==="error"){h=i.message;let l=i.failed_proposal;l&&o("failed_proposal",l)}}}finally{c.kill()}return{proposal:f,error:h,paused:b,highRisk:R,...S>0?{assumedDefaults:S}:{},...x!==void 0?{creditsTotal:x}:{}}}var tt={kind:"system",id:"distiller"};function Ct(t,e=n=>process.stderr.write(n+`
9
+ `)){try{let n=B(t),{watermark:s}=j(t),r=z({contextDir:t,graph:n,watermark:s,by:tt});if(r.errors){let a=r.errors.map(o=>`${o.code}: ${o.detail}`).join("; ");return e(`warning: style-note distill skipped \u2014 ${a}`),{minted:0,error:a}}return{minted:r.minted,error:null}}catch(n){let s=n instanceof Error?n.message:String(n);return e(`warning: style-note distill skipped \u2014 ${s}`),{minted:0,error:s}}}export{rt as a,ce as b,ge as c,pe as d,qe as e,_e as f,kt as g,Ct as h};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{x as o}from"./chunk-QIE62H3J.js";import{a as m}from"./chunk-HCBYKLMW.js";import{a as e,b as i}from"./chunk-C44QQJR4.js";import{e as d}from"./chunk-UR6MHSHU.js";var r=d(m(),1),s={default:o.muted,error:o.red,success:o.green,info:o.orange,warning:o.orange};function h({title:t,titleColor:a,borderColor:l,variant:n="default",children:c,width:u,paddingX:x=2,paddingY:g=0,marginBottom:f=0}){let p=l??s[n],B=a??(n==="default"?o.orange:s[n]);return(0,r.jsxs)(e,{flexDirection:"column",marginBottom:f,children:[t&&(0,r.jsx)(e,{marginBottom:0,children:(0,r.jsxs)(i,{color:B,bold:!0,children:[" ",t]})}),(0,r.jsx)(e,{borderStyle:"round",borderColor:p,flexDirection:"column",paddingX:x,paddingY:g,width:u,children:c})]})}function k({label:t,value:a,labelColor:l=o.dim,valueColor:n,labelWidth:c=14}){return(0,r.jsxs)(e,{children:[(0,r.jsx)(e,{width:c,flexShrink:0,children:(0,r.jsx)(i,{color:l,children:t})}),(0,r.jsx)(e,{flexShrink:1,children:(0,r.jsx)(i,{color:n,wrap:"wrap",children:a})})]})}function I({label:t}){return(0,r.jsx)(e,{marginTop:1,marginBottom:0,children:(0,r.jsx)(i,{bold:!0,children:t})})}export{h as a,k as b,I as c};
2
+ import{x as o}from"./chunk-E4OYR32M.js";import{a as m}from"./chunk-HCBYKLMW.js";import{a as e,b as i}from"./chunk-C44QQJR4.js";import{e as d}from"./chunk-UR6MHSHU.js";var r=d(m(),1),s={default:o.muted,error:o.red,success:o.green,info:o.orange,warning:o.orange};function h({title:t,titleColor:a,borderColor:l,variant:n="default",children:c,width:u,paddingX:x=2,paddingY:g=0,marginBottom:f=0}){let p=l??s[n],B=a??(n==="default"?o.orange:s[n]);return(0,r.jsxs)(e,{flexDirection:"column",marginBottom:f,children:[t&&(0,r.jsx)(e,{marginBottom:0,children:(0,r.jsxs)(i,{color:B,bold:!0,children:[" ",t]})}),(0,r.jsx)(e,{borderStyle:"round",borderColor:p,flexDirection:"column",paddingX:x,paddingY:g,width:u,children:c})]})}function k({label:t,value:a,labelColor:l=o.dim,valueColor:n,labelWidth:c=14}){return(0,r.jsxs)(e,{children:[(0,r.jsx)(e,{width:c,flexShrink:0,children:(0,r.jsx)(i,{color:l,children:t})}),(0,r.jsx)(e,{flexShrink:1,children:(0,r.jsx)(i,{color:n,wrap:"wrap",children:a})})]})}function I({label:t}){return(0,r.jsx)(e,{marginTop:1,marginBottom:0,children:(0,r.jsx)(i,{bold:!0,children:t})})}export{h as a,k as b,I as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as n}from"./chunk-RZ4F3BHX.js";import{a as c}from"./chunk-YIOWO6WS.js";import{u as s,v as a}from"./chunk-QIE62H3J.js";import{createHash as h,randomBytes as g}from"crypto";var l=class{authBaseUrl;consentUrl;constructor(t="prod"){let e=c(t);this.authBaseUrl=e.authBaseUrl,this.consentUrl=e.consentUrl}static generatePkce(){let t=g(96).toString("base64url").slice(0,128),e=h("sha256").update(t).digest("base64url");return[t,e]}buildAuthorizationUrl(t,e,r,o){let i=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:o,scope:a,code_challenge:e,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${i.toString()}`}async registerClient(t){let e=await n(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:s,redirect_uris:[t],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!e.ok)throw new Error(`DCR failed: ${e.status} ${await e.text()}`);return e.json()}async exchangeCode(t,e,r,o){let i=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t,redirect_uri:o,client_id:e,code_verifier:r})});if(!i.ok)throw new Error(`Token exchange failed: ${i.status}`);return i.json()}async refreshToken(t,e){let r=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(t,e,r="access_token"){await n(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,token_type_hint:r,client_id:e})})}async validateToken(t){let e=new AbortController,r=setTimeout(()=>e.abort(),1e4);try{let o=await n(`${this.authBaseUrl}/api/user`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},signal:e.signal});return clearTimeout(r),o.ok}catch{return clearTimeout(r),!1}}};export{l as a};
2
+ import{a as n}from"./chunk-RZ4F3BHX.js";import{a as c}from"./chunk-RLG5NUTE.js";import{u as s,v as a}from"./chunk-E4OYR32M.js";import{createHash as h,randomBytes as g}from"crypto";var l=class{authBaseUrl;consentUrl;constructor(t="prod"){let e=c(t);this.authBaseUrl=e.authBaseUrl,this.consentUrl=e.consentUrl}static generatePkce(){let t=g(96).toString("base64url").slice(0,128),e=h("sha256").update(t).digest("base64url");return[t,e]}buildAuthorizationUrl(t,e,r,o){let i=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:o,scope:a,code_challenge:e,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${i.toString()}`}async registerClient(t){let e=await n(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:s,redirect_uris:[t],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!e.ok)throw new Error(`DCR failed: ${e.status} ${await e.text()}`);return e.json()}async exchangeCode(t,e,r,o){let i=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t,redirect_uri:o,client_id:e,code_verifier:r})});if(!i.ok)throw new Error(`Token exchange failed: ${i.status}`);return i.json()}async refreshToken(t,e){let r=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(t,e,r="access_token"){await n(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,token_type_hint:r,client_id:e})})}async validateToken(t){let e=new AbortController,r=setTimeout(()=>e.abort(),1e4);try{let o=await n(`${this.authBaseUrl}/api/user`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},signal:e.signal});return clearTimeout(r),o.ok}catch{return clearTimeout(r),!1}}};export{l as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as m}from"./chunk-KRFGAVYU.js";import{x as t}from"./chunk-QIE62H3J.js";import{a as p}from"./chunk-HCBYKLMW.js";import{a,b as r,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 R({onSubmit:l}){let[o,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(o===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)(r,{color:t.secondary,children:"Rate this session: "}),(0,e.jsx)(r,{color:o===0?t.orange:t.dim,children:o===0?"[ \u{1F44D} ]":" \u{1F44D} "}),(0,e.jsx)(r,{children:" "}),(0,e.jsx)(r,{color:o===1?t.orange:t.dim,children:o===1?"[ \u{1F44E} ]":" \u{1F44E} "})]}),(0,e.jsx)(m,{bindings:[{keys:"\u2190/\u2192",label:"select"},{keys:"\u21B5",label:"submit"}],escBackLabel:"skip"})]})}export{R as a};
2
+ import{a as m}from"./chunk-AV5SUGRY.js";import{x as t}from"./chunk-E4OYR32M.js";import{a as p}from"./chunk-HCBYKLMW.js";import{a,b as r,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 R({onSubmit:l}){let[o,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(o===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)(r,{color:t.secondary,children:"Rate this session: "}),(0,e.jsx)(r,{color:o===0?t.orange:t.dim,children:o===0?"[ \u{1F44D} ]":" \u{1F44D} "}),(0,e.jsx)(r,{children:" "}),(0,e.jsx)(r,{color:o===1?t.orange:t.dim,children:o===1?"[ \u{1F44E} ]":" \u{1F44E} "})]}),(0,e.jsx)(m,{bindings:[{keys:"\u2190/\u2192",label:"select"},{keys:"\u21B5",label:"submit"}],escBackLabel:"skip"})]})}export{R as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as l}from"./chunk-RZ4F3BHX.js";import{a,c,e as o}from"./chunk-QIE62H3J.js";import{readFileSync as f,writeFileSync as d,mkdirSync as h,realpathSync as g}from"fs";import{join as y}from"path";var C="npm install -g @testmuai/kane-cli@latest",b="brew upgrade lambdatest/kane/kane-cli";function w(){try{let t=process.argv[1];if(t&&g(t).includes("/Cellar/"))return b}catch{}return C}var m=y(c,"version-check.json"),S=1440*60*1e3;function k(){try{let t=JSON.parse(f(m,"utf-8"));if(Date.now()-t.checkedAt<S)return t}catch{}return null}function A(t){try{h(c,{recursive:!0}),d(m,JSON.stringify({latest:t,checkedAt:Date.now()}))}catch{}}function u(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);for(let s=0;s<3;s++){let e=(n[s]??0)-(i[s]??0);if(e!==0)return e}return 0}function p(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);return(n[0]??0)!==(i[0]??0)?"major":(n[1]??0)!==(i[1]??0)?"minor":"patch"}async function j(){try{let t=k();if(t)return u(a,t.latest)>0?{current:a,latest:t.latest,severity:p(a,t.latest)}:null;let r=new AbortController,i=setTimeout(()=>r.abort(),5e3),n=await l(o,{headers:{Accept:"application/json"},signal:r.signal});if(clearTimeout(i),!n.ok)return null;let e=(await n.json())["dist-tags"]?.latest;return e?(A(e),u(a,e)>0?{current:a,latest:e,severity:p(a,e)}:null):null}catch{return null}}export{w as a,u as b,p as c,j as d};
2
+ import{a as l}from"./chunk-RZ4F3BHX.js";import{a,c,e as o}from"./chunk-E4OYR32M.js";import{readFileSync as f,writeFileSync as d,mkdirSync as h,realpathSync as g}from"fs";import{join as y}from"path";var C="npm install -g @testmuai/kane-cli@latest",b="brew upgrade lambdatest/kane/kane-cli";function w(){try{let t=process.argv[1];if(t&&g(t).includes("/Cellar/"))return b}catch{}return C}var m=y(c,"version-check.json"),S=1440*60*1e3;function k(){try{let t=JSON.parse(f(m,"utf-8"));if(Date.now()-t.checkedAt<S)return t}catch{}return null}function A(t){try{h(c,{recursive:!0}),d(m,JSON.stringify({latest:t,checkedAt:Date.now()}))}catch{}}function u(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);for(let s=0;s<3;s++){let e=(n[s]??0)-(i[s]??0);if(e!==0)return e}return 0}function p(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);return(n[0]??0)!==(i[0]??0)?"major":(n[1]??0)!==(i[1]??0)?"minor":"patch"}async function j(){try{let t=k();if(t)return u(a,t.latest)>0?{current:a,latest:t.latest,severity:p(a,t.latest)}:null;let r=new AbortController,i=setTimeout(()=>r.abort(),5e3),n=await l(o,{headers:{Accept:"application/json"},signal:r.signal});if(clearTimeout(i),!n.ok)return null;let e=(await n.json())["dist-tags"]?.latest;return e?(A(e),u(a,e)>0?{current:a,latest:e,severity:p(a,e)}:null):null}catch{return null}}export{w as a,u as b,p as c,j as d};
@@ -0,0 +1,14 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as ge,e as Te,g as Me,h as Ge}from"./chunk-SGU72YLH.js";import{b as Ne,f as je,g as Be,h as Ue}from"./chunk-FXPPQL4D.js";import{a as Oe}from"./chunk-RE3BZVGE.js";import{a as Pe,b as Ae}from"./chunk-JFAFKHDX.js";import{e as z,f as re}from"./chunk-FTD3B7QA.js";import{c as Ce}from"./chunk-VJUIW2ES.js";import{b as Ie}from"./chunk-YKTYVJBN.js";import{a as Fe}from"./chunk-Z56AWGVY.js";import{a as ee,d as te}from"./chunk-KHDUQ33H.js";import{a as E}from"./chunk-D5T4ARTB.js";import{b as Ee}from"./chunk-B2PZAB7J.js";import{d as U}from"./chunk-IACKIGPX.js";import{appendFileSync as et,mkdirSync as pe,writeFileSync as he}from"fs";import{extname as tt,join as I}from"path";var O=class extends Error{code;constructor(e,c){super(`${e}: ${c}`),this.name="ProposalAdapterError",this.code=e}};function He(s){return s.version===2}function qe(s,e){if(s.read_basis.length!==1)throw new O("READ_BASIS_COUNT",`read_basis must have exactly 1 element, got ${s.read_basis.length}`);let c=s.read_basis[0],h=s.use_cases.map(i=>{if(i.cite.length!==1)throw new O("CITE_COUNT",`${i.temp_ref}: cite must have exactly 1 element, got ${i.cite.length}`);let l=i.cite[0];if(l.source_id!==c.source_id)throw new O("SOURCE_MISMATCH",`${i.temp_ref}: cite source ${l.source_id} != read_basis source ${c.source_id} (single-source)`);return{temp_ref:i.temp_ref,title:i.title,...i.description!==void 0?{description:i.description}:{},...i.summary!==void 0?{summary:i.summary}:{},...i.actors!==void 0?{actors:i.actors}:{},...i.value!==void 0?{value:i.value}:{},risk:i.risk,cite:{anchor:l.anchor,quote:l.quote},...i.criteria!=null&&i.criteria.length>0?{criteria:i.criteria.map((d,p)=>{if(d.cite.source_id!==c.source_id)throw new O("SOURCE_MISMATCH",`${i.temp_ref}.criteria[${p}]: cite source ${d.cite.source_id} != read_basis source ${c.source_id} (single-source)`);return{text:d.text,cite:{anchor:d.cite.anchor,quote:d.cite.quote}}})}:{},depends_on_hint:i.depends_on_hint,matches_existing:i.matches_existing,...i.conflicts_with!=null?{conflicts_with:i.conflicts_with}:{},...i.changed?{changed:!0}:{},...i.updated!=null?{updated:i.updated}:{}}});return{version:1,read_basis:e,source:{source_id:c.source_id,source_cid:c.source_cid},use_cases:h}}function Le(s){let{contextDir:e,graph:c}=s,h=s.maxDigestBytes??4096,i={},l=[];for(let[u,m]of c.heads){if(i[u]=m,typeof m!="string")continue;let _=c.mediaOf(m),w=c.getNode(m)?.content?.blob;if(typeof w=="string")if(_.format==="image")l.push({source_id:u,cid:m,format:"image",blobRef:{path:ee(e,w),cid:w}});else{let n=te(e,w)?.toString("utf8")??"";l.push({source_id:u,cid:m,format:_.format,text:n})}}l.sort((u,m)=>u.source_id<m.source_id?-1:1);let d=[];for(let u of c.byLabel(U.STYLENOTE).sort((m,_)=>m.cid<_.cid?-1:1))c.superseded.has(u.cid)||d.push(`\u2022 ${String(u.content.statement)} [${String(u.content.learned_from_kind)}]`);let p="";for(let u of d){if(Buffer.byteLength(p+u+`
3
+ `,"utf8")>h)break;p+=u+`
4
+ `}return{read_basis:i,sources:l,styleNoteDigest:p}}function We(s,e){let c=Le({contextDir:s,graph:e}).styleNoteDigest;return c.length>0?c:void 0}function rt(s){return s.length>8&&s[0]===137&&s[1]===80&&s[2]===78&&s[3]===71?"image/png":s.length>3&&s[0]===255&&s[1]===216&&s[2]===255?"image/jpeg":s.length>12&&s.toString("ascii",0,4)==="RIFF"&&s.toString("ascii",8,12)==="WEBP"?"image/webp":null}function st(s){return s.toString("utf8").replace(/\n$/,"").split(`
5
+ `).map((c,h)=>`${String(h+1).padStart(4,"0")}| ${c}`).join(`
6
+ `)}function ze(s){return s.toISOString().replace(/[-:]/g,"").slice(0,15)}function ot(s){return s.startsWith("su-conv-")?`conv-${Ee(Buffer.from(s,"utf8")).slice(0,8)}`:s}function Ye(s){return s.source_id.startsWith("su-conv-")?"the conversation":s.source_id}function it(s,e,c){return`reading ${Ye(s)}${c>1?` (source ${e} of ${c})`:""}`}function V(s){return s.toLowerCase().trim().replace(/\s+/g," ")}function Ve(s,e){let c=new Map,h=new Map,i=new Map;for(let{cid:d,content:p}of e.byLabel(U.USECASE)){if(e.superseded.has(d))continue;(e.trust.get(d)==="archived"?i:h).set(V(String(p.title??"")),d)}let l=d=>e.trust.get(d)==="archived"?{cid:d,archived:!0,reason:e.archivedReason.get(d)}:{cid:d};for(let d of s.use_cases){if(d.matches_existing){let m=d.matches_existing.cid;if(e.superseded.has(m)){let _=e.tipOf(m);m=e.superseded.has(_)?null:_}if(m!==null){c.set(d.temp_ref,l(m));continue}}let p=h.get(V(d.title));if(p){c.set(d.temp_ref,{cid:p});continue}let u=i.get(V(d.title));u&&c.set(d.temp_ref,l(u))}return c}var Je=/^(\S+)\.criteria\[(\d+)\]/;function nt(s,e,c){if(e.length===0||!e.every(i=>Je.test(i.detail)))return!1;let h=new Map;for(let i of e){let l=Je.exec(i.detail),d=h.get(l[1])??new Set;d.add(Number(l[2])),h.set(l[1],d)}for(let i of s.use_cases){let l=h.get(i.temp_ref);l?.size&&(i.criteria=(i.criteria??[]).filter((d,p)=>!l.has(p)),c(`${i.temp_ref}: dropped ${l.size} criteria with unverifiable cites \u2014 committed without them (criteria are hints, not oracles)`))}return!0}async function Xe(s,e,c,h,i=()=>{},l){let d=(p,u)=>i(p,u,s.session_id);return Me(s,e,c,h,i,{async onProposalEvent(p){let u=p,m=null,_=null;if(He(u))try{m=qe(u,s.read_basis),d("adapter",{ok:!0,use_cases:m.use_cases.length})}catch(w){_=w instanceof O?w.message:String(w),d("adapter",{ok:!1,error:_})}else m=u;return m&&m.use_cases.length===0&&e.out("warning: the agent proposed ZERO use-cases for this source"),m&&l&&await l(m),{proposal:m,error:_}}})}var at=new Set(["agent","ci","override"]);async function Ft(s,e){let c=s.mode??"interactive";if(c==="interactive"){if(!e.isTTY)return e.out("extract: --mode interactive needs a TTY (use --mode agent|ci|override headless)"),2}else if(!at.has(c))return e.out(`extract: unknown mode "${c}" \u2014 interactive | agent | ci | override`),2;let h=ze(e.now?.()??new Date),i=I(e.contextDir,"logs");pe(i,{recursive:!0});let l=I(i,`extract-${h}.log`),d=`run-${h}-${Math.random().toString(36).slice(2,8)}`,p=t=>t==="error"||t==="failed_proposal"?"error":t==="repair_respawn"?"warn":"info",u=(t,a,x)=>{try{et(l,JSON.stringify({ts:new Date().toISOString(),level:p(t),run_id:d,...x?{session_id:x}:{},kind:t,data:a})+`
7
+ `)}catch{}};e.out(`trace: ${ge(l)}`),e.emit?.({type:"run_start",mode:c,trace:l});let m=Ie();if(m&&e.out(m),e.preflightTurn){let t=await e.preflightTurn();if(u("preflight",t),!t.ok)return e.out(t.message??"error: turn-endpoint preflight failed"),e.emit?.({type:"error",message:t.message??"error: turn-endpoint preflight failed",code:"PREFLIGHT"}),2}let _=E(e.contextDir),w=We(e.contextDir,_);if(s.source){if(s.resume){let a="error: --source cannot be combined with --resume (the resumed session already has its scope)";return e.out(a),e.emit?.({type:"error",message:a,code:"SOURCE_WITH_RESUME"}),2}let t=_.heads.get(s.source);if(typeof t!="string"){let a=t===null?`error: --source ${s.source} was ingested but is retired \u2014 re-ingest it to extract again`:`error: --source ${s.source} is not an ingested source (kane-cli context list shows them)`;return e.out(a),e.emit?.({type:"error",message:a,code:"SOURCE_UNKNOWN"}),2}}let n=null;if(s.resume){try{n=Ue(e.contextDir,s.resume,_)}catch(a){return e.out(`error: ${a instanceof Error?a.message:String(a)}`),e.emit?.({type:"error",message:`error: ${a instanceof Error?a.message:String(a)}`}),1}n.staleBasis.length>0&&e.out(`note: changed since the pause: ${n.staleBasis.join(", ")} \u2014 re-presented items may be stale`);let t=n.handle.state.held_receipts??[];if(t.length>0)if(e.chat?.holdReceipt)for(let a of t)e.chat.holdReceipt(a);else e={...e,initialMessage:[t.join(`
8
+
9
+ `),e.initialMessage].filter(Boolean).join(`
10
+
11
+ `)};n.handle.state.assumed.length>0&&e.out(`note: ${n.handle.state.assumed.length} default(s) were assumed while you were away \u2014 kane-cli context sessions show ${s.resume} lists them`)}let _e=_.extractedSourceCids,J=!!(s.force||n?.handle.state.force),v=[],T=[];for(let[t,a]of _.heads.entries())if(a!=null&&!(s.source&&t!==s.source)){if(!s.source&&!n&&t.startsWith("su-conv-")){e.out(`skipped: ${t} \u2014 conversation source (extract it explicitly with --source ${t})`),T.push({source_id:t,reason:"conversation"});continue}if(n){let x=t in n.handle.state.read_basis,A=n.handle.state.corpus_cursor.remaining.includes(t);if(!x&&!A)continue;if(A&&!J&&_e.has(a)){e.out(`cached: ${t} @ ${a.slice(0,19)} already extracted \u2014 skipping`),T.push({source_id:t,reason:"cached"});continue}}else if(!J&&_e.has(a)){e.out(`cached: ${t} @ ${a.slice(0,19)} already extracted \u2014 skipping`),T.push({source_id:t,reason:"cached"});continue}v.push({source_id:t,cid:a})}if(e.emit?.({type:"corpus",sources:v,skipped:T}),v.length===0){if(n){let x=`error: resumed session's paused source (${Object.keys(n.handle.state.read_basis).join(", ")||"unknown"}) is no longer in the corpus \u2014 restore/re-ingest it and re-run --resume ${s.resume}, or discard with: kane-cli context sessions clean ${s.resume}`;return e.out(x),e.emit?.({type:"error",message:x,code:"SOURCE_MISSING"}),n.handle.release(),2}let t=T.length>0&&T.every(a=>a.reason==="conversation");return e.out(s.source?`extract: nothing to do \u2014 ${s.source} is already extracted at its current snapshot (--force to re-run)`:t?"extract: nothing to do \u2014 only conversation sources here (extract one explicitly with --source <id>)":"extract: nothing to do \u2014 every ingested source is already extracted"),0}let X=new Map;if(n&&n.questions.length>0&&!s.message){e.out(`re-presenting ${n.questions.length} unanswered question(s) from the paused session`);let t=await e.ask(n.questions.map(je));for(let a of t)X.set(a.id,a)}let G=e.by??{kind:"human",id:"owner"},P=c==="interactive"&&!s.plan&&!!e.chat,se=0,xe=0;try{for(let t of v){let a=E(e.contextDir),x={current:a};e.chat?.attachOnCommitted?.(r=>{x.current=r});let A=a.getNode(t.cid),H=String(A?.content.blob??""),oe=te(e.contextDir,H);if(!oe)return e.out(`error: ${t.source_id}: blob ${H} missing from .context/blobs`),e.emit?.({type:"error",source_id:t.source_id,message:`error: ${t.source_id}: blob ${H} missing from .context/blobs`,code:"BLOB_MISSING"}),1;let ve=a.mediaOf(t.cid),ie=ve.media_type.startsWith("image/");if(!ie){let r=rt(oe);if(r){e.out(`skipping ${t.source_id}: binary ${r} ingested before image support \u2014 re-ingest it (kane-cli context ingest) to extract from it`),e.emit?.({type:"source_skipped",source_id:t.source_id,reason:"binary_pre_media"});continue}}let q=ie?`0001| (image source ${t.source_id} \u2014 the content is attached as an image; cite it with anchor img#whole)`:st(oe),ye=ze(e.now?.()??new Date),M=`${ye}-${t.source_id}`,$e=!!(n&&t.source_id in n.handle.state.read_basis)?s.resume:`ext-${ye}-${ot(t.source_id)}`,N="";if(P){let r=Ce({contextDir:e.contextDir,graph:E(e.contextDir),sessionStamp:$e,by:G});r.errors===null||r.errors[0]?.code==="CONV_SOURCE_EXISTS"?(N=r.sourceId,e.chat.attachConversationSource?.(N),x.current=E(e.contextDir)):e.out(`warning: conversation source unavailable (${r.errors[0]?.detail}) \u2014 chat adds will not land this session`)}let b={type:"run_config",version:1,session_id:$e,mode:c,source:{source_id:t.source_id,source_cid:t.cid,kind:tt(t.source_id)||"md",numbered_text:q},existing_use_cases:a.byLabel(U.USECASE).filter(({cid:r})=>a.trust.get(r)!=="archived"&&!a.superseded.has(r)).map(({cid:r,content:o})=>({id:r,title:String(o.title??""),summary:String(o.summary??"")})),read_basis:x.current.latestHash,max_free_text_rounds:Te,graph_reads:!0,verb:"extract",...w!==void 0?{style_note_digest:w}:{},topology:Fe(),...P?{chat:!0}:{},...ie?{image_sources:[{source_id:t.source_id,source_cid:t.cid,media_type:ve.media_type,blob_ref:{path:ee(e.contextDir,H),cid:H}}]}:{},...n&&t.source_id in n.handle.state.read_basis?{resume:{agent_state:n.handle.state.agent_state}}:{}};P||e.out(n&&t.source_id in n.handle.state.read_basis?`resuming: ${t.source_id} (session ${s.resume})`:`extracting: ${t.source_id} @ ${t.cid.slice(0,19)}`),e.emit?.({type:"source_start",source_id:t.source_id,cid:t.cid,index:v.indexOf(t)+1,total:v.length,resumed:!!(n&&t.source_id in n.handle.state.read_basis)}),e.chat?.ledger?.({kind:"banner",text:it(t,v.indexOf(t)+1,v.length)}),e.chat?.setWorking?.(`Reading ${Ye(t)}\u2026`);let be=new Map;u("spawn",{source_id:t.source_id,source_cid:t.cid,resume:!!n,chat:P},b.session_id);let Se=!1,Ke=async r=>{let o=z(r,q,E(e.contextDir));if(u("kane_validate",{errors:o.map(g=>g.code)},b.session_id),o.length>0){e.chat.submit("[auto-repair] the proposal failed validation: "+o.map(g=>`${g.code}: ${g.detail}`).join("; ")+" \u2014 please re-finalize with these fixed.");return}let y=E(e.contextDir),k=Ve(r,y),Q=I(e.contextDir,"proposals",M);pe(Q,{recursive:!0}),he(I(Q,"proposal.json"),JSON.stringify(r,null,2)+`
12
+ `);let Ze=new Map(r.use_cases.map(g=>[g.temp_ref,{resolution:"skipped"}])),Z=re({contextDir:e.contextDir,graph:y,proposal:r,proposalId:M,verdicts:Ze,by:{kind:"ai",id:"extract-agent"},autoName:!0});if(Z.errors){e.chat.ledger?.({kind:"commit",ok:!1,line:"commit failed \u2014 nothing landed",warnings:Z.errors.map(g=>`${g.code}: ${g.detail}`)});return}Se=!0;let j=Z.record.nodes.length;se+=j;let B=r.use_cases.length-j;{let g=E(e.contextDir),De=new Map;for(let{cid:$,content:R}of g.byLabel(U.USECASE))g.superseded.has($)||De.set(V(String(R.title??"")),$);let fe=[];for(let $ of r.use_cases){let R=null;if($.matches_existing?.cid&&g.hasNode($.matches_existing.cid)){let W=g.tipOf($.matches_existing.cid);R=g.superseded.has(W)?null:W}R=R??De.get(V($.title))??null,R&&fe.push({ref:$.temp_ref,cid:R})}fe.length>0&&e.chat.registerAliases?.(fe),x.current=g;let ke=$=>{for(let[R,W]of g.names)if(W===$&&!g.superseded.has(W))return R},Re=Oe({verb:"extract",commitN:1,phase:"proposal",committed:Z.record.nodes.map($=>({cid:$.cid,...ke($.cid)?{logical_id:ke($.cid)}:{}})),reused:B},g);e.emit?.(Re.event),e.chat.holdReceipt?.(Re.text)}u("commit",{derived:j,evidence_matched:B,chat:!0},b.session_id),e.chat.ledger?.({kind:"commit",ok:!0,line:j===0&&B>0?`all ${B} matched existing \u2014 nothing new to save`:`saved ${j} use-case${j===1?"":"s"} as drafts`+(B>0?` \xB7 ${B} matched existing`:"")})},we=!!(n&&t.source_id in n.handle.state.read_basis),Y=we&&X.size>0?{...e,ask:async r=>r.every(o=>X.has(o.id))?(n.handle.markApplied(r.map(o=>`resolveq:${s.resume}:${o.id}`)),e.out(`answered ${r.length} re-asked question(s) from the held resume answers`),r.map(o=>X.get(o.id))):e.ask(r)}:e;we&&s.message&&(Y={...Y,initialMessage:s.message});let f=await Xe(b,{...Y,graphSlot:x},be,a,u,P?Ke:void 0);if(e.chat?.setWorking?.(null),f.error)return e.out(`error: agent failed for ${t.source_id}: ${f.error}`),e.emit?.({type:"error",source_id:t.source_id,message:`error: agent failed for ${t.source_id}: ${f.error}`}),1;if(f.highRisk)return e.out(`error: ${f.highRisk.length} high-risk decision${f.highRisk.length===1?"":"s"} need a human \u2014 ci mode won't guess. Re-run with --mode agent to pause for review.`),e.emit?.({type:"error",source_id:t.source_id,message:`error: high-risk question(s) in ci mode (fail-closed): ${f.highRisk.map(r=>r.id).join(", ")}`,code:"HIGH_RISK_CI"}),1;if(f.paused){let r=v.slice(v.indexOf(t)+1).map(Q=>Q.source_id),o=n?.handle??Ne(e.contextDir,{sid:b.session_id,mode:"agent",created_at:(e.now?.()??new Date).toISOString(),expires_at:new Date((e.now?.()??new Date).getTime()+1440*60*1e3).toISOString(),agent_state:f.paused.agent_state,pending:{questions:[],proposals:[]},assumed:[],read_basis:{[t.source_id]:t.cid},corpus_cursor:{remaining:r},conv_source:N,verb:"extract",...J?{force:!0}:{}});N&&o.state.conv_source!==N&&o.save({conv_source:N});let y=e.chat?.drainHeldReceipts?.()??[];(y.length>0||(o.state.held_receipts?.length??0)>0)&&o.save({held_receipts:y}),n?.handle&&o.save({read_basis:{[t.source_id]:t.cid},corpus_cursor:{remaining:r},...J&&!o.state.force?{force:!0}:{}}),Be(o,f.paused),u("session_paused",{sid:o.state.sid},b.session_id);let k=`kane-cli context extract --resume ${o.state.sid} --mode ${c}`;return e.out(`paused: session ${o.state.sid} saved \u2014 resume with: ${k}`),e.emit?.({type:"session_paused",sid:o.state.sid,source_id:t.source_id,mode:c,resume:k,expires_at:o.state.expires_at,pending_questions:f.paused.pending.questions}),e.chat?.ledger?.({kind:"pause",sid:o.state.sid,expires_at:o.state.expires_at,resume:k,messageForm:`${k} --message "<your words>"`}),3}if(P){if(xe+=f.assumedDefaults??0,f.error)return 1;if(!Se){let r=v.length-v.indexOf(t)-1;return e.out(`done \u2014 nothing committed for ${t.source_id} (no finalize before the session ended)`+(r>0?`; stopping here \u2014 ${r} remaining source(s) not extracted (re-run kane-cli context extract to continue)`:"")),n&&t.source_id in n.handle.state.read_basis&&(n.handle.complete(),n=null),0}n&&t.source_id in n.handle.state.read_basis&&(n.handle.complete(),n=null);continue}if(!f.proposal)return e.out(`error: agent ended without a proposal for ${t.source_id}`),e.emit?.({type:"error",source_id:t.source_id,message:`error: agent ended without a proposal for ${t.source_id}`}),1;let D=z(f.proposal,q,a);if(u("kane_validate",{errors:D.map(r=>r.code)},b.session_id),D.length>0&&nt(f.proposal,D,r=>e.out(r))&&(u("criteria_dropped",{source_id:t.source_id},b.session_id),D=z(f.proposal,q,a)),D.length>0){if(e.out("the agent's proposal didn't validate \u2014 retrying once"),e.emit?.({type:"validate_failed",source_id:t.source_id,codes:D.map(r=>r.code),repairing:!0}),u("repair_respawn",{source_id:t.source_id},b.session_id),f=await Xe(b,{...Y,graphSlot:x},be,a,u),f.error||!f.proposal)return e.out(`error: repair run failed for ${t.source_id}`),e.emit?.({type:"error",source_id:t.source_id,message:`error: repair run failed for ${t.source_id}`}),1;if(D=z(f.proposal,q,a),D.length>0){for(let r of D)e.out(` ${r.detail}`);return e.emit?.({type:"validate_failed",source_id:t.source_id,codes:D.map(r=>r.code),repairing:!1}),e.emit?.({type:"error",source_id:t.source_id,message:`error: proposal failed validation after repair (${D.map(r=>r.code).join(", ")})`}),1}}let S=f.proposal,K=Ve(S,a),ne=I(e.contextDir,"proposals",M);if(pe(ne,{recursive:!0}),he(I(ne,"proposal.json"),JSON.stringify(S,null,2)+`
13
+ `),s.plan){e.out(`plan: ${S.use_cases.length} use-case(s) proposed from ${t.source_id} (nothing committed)`);for(let r of S.use_cases){let o=K.get(r.temp_ref),y=o?o.archived?` \u2248 matches ARCHIVED ${o.cid.slice(0,19)}${o.reason?` \u2014 previously rejected: "${o.reason}"`:" \u2014 previously rejected"}`:` \u2248 matches ${o.cid.slice(0,19)}`:"";e.out(` [${r.risk}] ${r.title} \u2014 cite ${r.cite.anchor}${y}`)}e.emit?.({type:"plan",source_id:t.source_id,use_cases:S.use_cases.map(r=>{let o=K.get(r.temp_ref);return{risk:r.risk,title:r.title,anchor:r.cite.anchor,...o?{match:o.cid,match_archived:!!o.archived}:{}}})}),f.assumedDefaults&&e.out(`assumed: ${f.assumedDefaults} default(s) auto-taken (flagged)`);continue}for(let r of S.use_cases){if(!r.conflicts_with?.length)continue;let o=r.conflicts_with.filter(k=>a.resolve(k)!==null),y=r.conflicts_with.filter(k=>a.resolve(k)===null);y.length>0&&(e.out(`note: ${r.temp_ref}: dropped unresolvable conflict hint(s): ${y.join(", ")}`),r.conflicts_with=o.length>0?o:void 0)}u("review_start",{use_cases:S.use_cases.length,flags:K.size},b.session_id);let L=await e.review(S.use_cases,K);u("review_verdicts",[...L.entries()].map(([r,o])=>({ref:r,resolution:o.resolution})),b.session_id),he(I(ne,"review.json"),JSON.stringify(S.use_cases.map(r=>{let o=L.get(r.temp_ref)??{resolution:"skipped"};return{id:r.temp_ref,kind:"review-item",resolution:o.resolution,edit:o.edit??null,reason:o.reason??null,...o.supersedeTarget?{supersede_target:o.supersedeTarget}:{},by:G}}),null,2)+`
14
+ `);let ae=a,C=re({contextDir:e.contextDir,graph:ae,proposal:S,proposalId:M,verdicts:L,by:G,autoName:!0});if(C.errors&&C.errors[0]?.code==="STALE_BASIS"){if(!await e.confirmStale(`the context changed while you reviewed (${C.errors[0].detail}) \u2014 commit against the new head anyway?`))return e.out("aborted: proposal not committed"),e.emit?.({type:"error",source_id:t.source_id,message:"aborted: proposal not committed",code:"STALE_BASIS"}),e.emit?.({type:"done",status:"aborted",exit_code:1}),1;ae=E(e.contextDir),C=re({contextDir:e.contextDir,graph:ae,proposal:S,proposalId:M,verdicts:L,by:G,allowStaleBasis:!0,autoName:!0})}if(C.errors){for(let r of C.errors)e.out(` ${r.detail}`);return e.emit?.({type:"error",source_id:t.source_id,message:`error: commit failed: ${C.errors.map(r=>`${r.code}: ${r.detail}`).join("; ")}`}),1}let Qe=new Date().toISOString();for(let r of S.use_cases){let o=L.get(r.temp_ref)??{resolution:"skipped"};for(let y of Ae({ts:Qe,command:"context extract",id:r.temp_ref,by:G},o.resolution))Pe(e.contextDir,y)}let F=C.record,ce=new Map(F.review.map(r=>[r.id,r.resolution])),ue=[...ce.values()].filter(r=>r==="approved"||r==="edited").length,de=[...ce.values()].filter(r=>r==="rejected").length,le=F.nodes.filter(r=>!ce.has(r.cid)).length,me=F.supersessions.filter(r=>r.kind==="node"&&r.new!==r.old).length;u("commit",{trusted:ue,derived:le,archived:de},b.session_id),e.out(`committed: ${ue} trusted, ${le} derived (queued), ${de} archived`+(me>0?`, ${me} superseded`:"")),f.assumedDefaults&&e.out(`assumed: ${f.assumedDefaults} default(s) auto-taken (flagged)`),e.emit?.({type:"commit",source_id:t.source_id,proposal_id:M,trusted:ue,derived:le,archived:de,superseded:me,assumed:f.assumedDefaults??0,evidence_matched:Math.max(0,S.use_cases.length-F.nodes.length),minted:F.nodes.map(r=>{let o=F.names?.find(y=>y.cid===r.cid)?.slug;return{cid:r.cid,...o?{logical_id:o}:{}}})}),n&&t.source_id in n.handle.state.read_basis&&(n.handle.complete(),e.out(`session ${s.resume} complete`),e.emit?.({type:"session_complete",sid:s.resume,source_id:t.source_id}),n=null)}}finally{n?.handle.release()}if(P){let t=e.chat?.state.ledger.filter(A=>A.kind==="answer"&&A.receipt.form==="assumed").length??0,a=xe+t,x=e.chat?.state.credits?.total;e.chat?.ledger?.({kind:"summary",lines:[`saved ${se} use-case${se===1?"":"s"} across ${v.length} source${v.length===1?"":"s"}`,...a>0?[`${a} assumed default(s)`]:[],...x!==void 0?[`credits used: ${x.toFixed(1)}`]:[],`trace: ${ge(l)}`]})}return s.plan||Ge(e.contextDir),0}export{ot as a,Ye as b,it as c,Ve as d,Ft as e};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as g}from"./chunk-QIE62H3J.js";import{readFileSync as o,writeFileSync as h,mkdirSync as u,readdirSync as a,unlinkSync as s,existsSync as l,chmodSync as f}from"fs";import{join as n,dirname as P}from"path";var d=class{baseDir;profilesDir;configFile;constructor(t=g){this.baseDir=t,this.profilesDir=n(t,"profiles"),this.configFile=n(t,"config.json")}readConfig(){try{return JSON.parse(o(this.configFile,"utf-8"))}catch{return{}}}writeConfig(t){u(this.baseDir,{recursive:!0,mode:448}),h(this.configFile,JSON.stringify(t,null,2)+`
2
+ import{c as g}from"./chunk-E4OYR32M.js";import{readFileSync as o,writeFileSync as h,mkdirSync as u,readdirSync as a,unlinkSync as s,existsSync as l,chmodSync as f}from"fs";import{join as n,dirname as P}from"path";var d=class{baseDir;profilesDir;configFile;constructor(t=g){this.baseDir=t,this.profilesDir=n(t,"profiles"),this.configFile=n(t,"config.json")}readConfig(){try{return JSON.parse(o(this.configFile,"utf-8"))}catch{return{}}}writeConfig(t){u(this.baseDir,{recursive:!0,mode:448}),h(this.configFile,JSON.stringify(t,null,2)+`
3
3
  `),f(this.configFile,384)}getActiveProfile(){return this.readConfig().active_profile??null}setActiveProfile(t){let i=this.readConfig();i.active_profile=t,this.writeConfig(i)}getDefaultEnv(){return this.readConfig().default_env??"prod"}setDefaultEnv(t){let i=this.readConfig();i.default_env=t,this.writeConfig(i)}credentialsPath(t,i){return n(this.profilesDir,t,i,"credentials")}clientPath(t,i){return n(this.profilesDir,t,i,"client.json")}basicAuthPath(t,i){return n(this.profilesDir,t,i,"basic-auth")}profileConfigPath(t,i){return n(this.profilesDir,t,i,"profile-config.json")}saveProfileConfig(t,i,r){let e=this.loadProfileConfig(t,i)??{};this.writeSecure(this.profileConfigPath(t,i),{...e,...r})}loadProfileConfig(t,i){try{return JSON.parse(o(this.profileConfigPath(t,i),"utf-8"))}catch{return null}}writeSecure(t,i){try{u(P(t),{recursive:!0,mode:448}),h(t,JSON.stringify(i,null,2)+`
4
4
  `),f(t,384)}catch(r){let e=r instanceof Error?r.message:String(r);process.stderr.write(`[auth] Failed to save credentials: ${e}
5
5
  `)}}saveCredentials(t,i,r){this.writeSecure(this.credentialsPath(t,i),r)}loadCredentials(t,i){try{return JSON.parse(o(this.credentialsPath(t,i),"utf-8"))}catch{return null}}saveClient(t,i,r){this.writeSecure(this.clientPath(t,i),r)}loadClient(t,i){try{return JSON.parse(o(this.clientPath(t,i),"utf-8"))}catch{return null}}getActiveCredentials(){let t=this.getActiveProfile();if(!t)return{credentials:null,profile:null,env:null};let i=this.getDefaultEnv();return{credentials:this.loadCredentials(t,i),profile:t,env:i}}saveBasicAuth(t,i,r){this.writeSecure(this.basicAuthPath(t,i),r)}loadBasicAuth(t,i){try{return JSON.parse(o(this.basicAuthPath(t,i),"utf-8"))}catch{return null}}deleteBasicAuth(t,i){try{s(this.basicAuthPath(t,i))}catch{}}resolveAuth(){let t=this.getActiveProfile();if(!t)return null;let i=this.getDefaultEnv(),r=this.loadBasicAuth(t,i);return r?{method:"basic",...r,profile:t,env:i}:this.loadCredentials(t,i)?{method:"oauth",profile:t,env:i}:null}listProfiles(){let t=[];try{for(let i of a(this.profilesDir)){let r=n(this.profilesDir,i);try{for(let e of a(r)){let c=n(r,e),v=l(n(c,"credentials")),p=l(n(c,"client.json")),y=l(n(c,"basic-auth"));(v||p||y)&&t.push({profile:i,env:e})}}catch{}}}catch{}return t}deleteProfile(t,i){try{s(this.credentialsPath(t,i))}catch{}if(this.getActiveProfile()===t){let r=this.readConfig();delete r.active_profile,this.writeConfig(r)}}deleteProfileFull(t,i){if(i){try{s(this.credentialsPath(t,i))}catch{}try{s(this.clientPath(t,i))}catch{}try{s(this.basicAuthPath(t,i))}catch{}try{s(this.profileConfigPath(t,i))}catch{}}else try{let r=n(this.profilesDir,t);for(let e of a(r)){try{s(n(r,e,"credentials"))}catch{}try{s(n(r,e,"client.json"))}catch{}try{s(n(r,e,"basic-auth"))}catch{}try{s(n(r,e,"profile-config.json"))}catch{}}}catch{}}};export{d as a};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as $e}from"./chunk-44QUA6GV.js";import{a as te}from"./chunk-M6DX4ENH.js";import{a as K}from"./chunk-5Y2G4NC7.js";import{a as Be}from"./chunk-PJSCM6JX.js";import{a as ve}from"./chunk-OZM4UU5F.js";import{b as ye}from"./chunk-DFS4RMVP.js";import{x as i}from"./chunk-QIE62H3J.js";import{a as k}from"./chunk-HCBYKLMW.js";import{a as s,b as o,i as Se,j as Te,k as ee}from"./chunk-C44QQJR4.js";import{a as V}from"./chunk-6YGTRKDT.js";import{e as R}from"./chunk-UR6MHSHU.js";var A=R(V(),1);var C=R(V(),1);function de(e){let t=e.flatMap(u=>[u,...u.children??[]]),n=t.filter(u=>u.status==="passed").length,l=t.filter(u=>u.status==="failed").length,a=t.filter(u=>u.status==="passed"||u.status==="failed").length;return{passed:n,failed:l,total:a}}function we(e){let t=$e(e.screenshotDispatcher,e.stepLogger,e.onReasoning,e.onStepComplete),[n,l]=(0,C.useState)(0),[a,u]=(0,C.useState)("idle"),c=(0,C.useRef)("idle"),v=(0,C.useRef)(0),S=(0,C.useRef)(!1),T=(0,C.useRef)(null),d=(0,C.useRef)(null),L=(0,C.useCallback)(h=>{c.current=h,u(h)},[]),O=(0,C.useCallback)(async h=>{let b=await e.getNextConfig(h);if(!b){L("done"),e.onAllComplete?.();return}let B=h?v.current+1:0;v.current=B,l(B),e.onStepStart?.(b,B),T.current=null,d.current=null,L("running"),await t.startRun(b,e.spawnOpts)},[t,e,L]);(0,C.useEffect)(()=>{S.current||(S.current=!0,O(null))},[]),(0,C.useEffect)(()=>{if(!t.lastRunEnd||t.lastRunEnd===T.current||c.current!=="running")return;T.current=t.lastRunEnd,c.current="transitioning",u("transitioning");let h=t.lastRunEnd,b=de(t.steps),B=t.bifurcationInfo,F={status:h.status==="passed"?"passed":"failed",duration_s:h.duration??0,reason:h.reason,runEnd:h,hadError:!1,stepsPassed:b.passed,stepsFailed:b.failed,stepsTotal:b.total,bifurcationFlows:B&&!B.isSingleFlow?B.flows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(F,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(F)},[t.lastRunEnd]),(0,C.useEffect)(()=>{if(!t.runError||t.runError===d.current||t.lastRunEnd||c.current!=="running")return;d.current=t.runError,c.current="transitioning",u("transitioning");let h=de(t.steps),b={status:"failed",duration_s:0,reason:t.runError,runEnd:null,hadError:!0,stepsPassed:h.passed,stepsFailed:h.failed,stepsTotal:h.total,bifurcationFlows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(b,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(b)},[t.runError,t.lastRunEnd]);let y=(0,C.useCallback)(()=>{t.cancelRun()},[t]);return{runner:t,currentStepIndex:n,phase:a,cancel:y}}var pe=R(V(),1);var ne=R(k(),1),Ee=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function ke({label:e,hasBifurcation:t=!1}){let[n,l]=(0,pe.useState)(0),[a,u]=(0,pe.useState)(0);K(()=>{l(v=>(v+1)%Ee.length)},80),K(()=>{u(v=>(v+1)%4)},400);let c=e??(t?"Planning approach":"Analyzing objective");return(0,ne.jsxs)(s,{marginLeft:1,children:[(0,ne.jsxs)(o,{color:i.orange,children:[Ee[n]," "]}),(0,ne.jsxs)(o,{color:i.dim,children:[c,".".repeat(a+1)]})]})}function Ie(e){if(!e.isRunning||e.replayInfo)return null;let t=e.bifurcationInfo;if(t&&!t.isSingleFlow){let n=e.steps.findIndex(a=>a.status==="running");return(n===-1?e.cmInitCounts.length===0:n>=e.cmInitCounts.length)?{label:n>0?`Planning flow ${n+1}`:void 0,hasBifurcation:!0}:null}return e.cmInitCounts.length>0||e.steps.some(n=>n.children?.length)?null:{hasBifurcation:!!t}}var I=R(V(),1);var Ce=R(V(),1);var re=R(k(),1),He="#ffc580",Ue="#ffd9a8",Le="#ffffff";function oe({text:e,active:t=!0}){let[n,l]=(0,Ce.useState)(0),a=4;if(K(()=>{l(c=>(c+1)%(e.length+a*2))},t?80:null),!t)return(0,re.jsx)(o,{color:Le,children:e});let u=e.split("").map((c,v)=>{let S=n-a,T=Math.abs(v-S-a/2),d;return T<=a/2?d=He:T<=a?d=Ue:d=Le,(0,re.jsx)(o,{color:d,children:c},v)});return(0,re.jsx)(o,{children:u})}var _=R(k(),1),We={starting:i.orange,running:i.orange,passed:i.green,failed:i.red,cancelled:i.dim,timed_out:i.orange};function ie({currentStep:e,maxSteps:t,elapsed:n,status:l}){let a=We[l]??i.orange,u=n<60?`${n.toFixed(1)}s`:`${Math.floor(n/60)}m ${Math.round(n%60)}s`;return(0,_.jsxs)(s,{marginLeft:3,children:[(0,_.jsx)(o,{color:i.dim,children:"Steps "}),(0,_.jsx)(o,{bold:!0,children:e}),(0,_.jsxs)(o,{color:i.dim,children:["/",t]}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Elapsed "}),(0,_.jsx)(o,{bold:!0,children:u}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Status "}),(0,_.jsx)(o,{bold:!0,color:a,children:l})]})}var Ve={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 Oe(e){return Ve[e]??"\u25CF"}var q=R(k(),1);function fe({steps:e,flows:t,cmInitCounts:n,renderStep:l}){return(0,q.jsxs)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,q.jsxs)(o,{color:i.dim,children:["\u2501\u2501 Bifurcated into ",t?.length??e.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),e.map((a,u)=>(0,q.jsxs)(s,{flexDirection:"column",marginTop:u>0?1:0,children:[(0,q.jsxs)(o,{color:i.orange,children:["Flow ",u+1,": ",t?.[u]??a.objective]}),n&&n[u]!=null&&(0,q.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",n[u]," checkpoints"]}),a.children&&a.children.length>0?a.children.map(c=>{let v=!!c.branchObjective,S=`f${u}-${c.childId??"p"}-${c.index}`;return v?(0,q.jsxs)(s,{flexDirection:"column",children:[l({...c,children:void 0},S),(c.children??[]).map(T=>(0,q.jsx)(s,{marginLeft:2,children:l(T,`${S}-${T.childId??"p"}-${T.index}`)},`${S}-${T.childId??"p"}-${T.index}`))]},`${S}-host`):l(c,S)}):a.status==="pending"&&(0,q.jsx)(o,{color:i.dim,children:" \u25CB Waiting..."})]},u))]})}var H=R(k(),1);function Pe({label:e,shimmer:t=!1}){return(0,H.jsxs)(s,{marginLeft:6,children:[(0,H.jsx)(te,{}),(0,H.jsx)(o,{children:" "}),t?(0,H.jsx)(oe,{text:e,active:!0}):(0,H.jsx)(o,{color:i.dim,children:e})]})}var De=R(V(),1);var me=R(k(),1);function ze(e,t){let n=[];for(let l of e.split(`
2
+ import{c as $e}from"./chunk-FFL2TQEJ.js";import{a as te}from"./chunk-F66SSA4C.js";import{a as K}from"./chunk-5Y2G4NC7.js";import{a as Be}from"./chunk-EWFFJBAM.js";import{a as ve}from"./chunk-SHSV64GX.js";import{b as ye}from"./chunk-DFS4RMVP.js";import{x as i}from"./chunk-E4OYR32M.js";import{a as k}from"./chunk-HCBYKLMW.js";import{a as s,b as o,i as Se,j as Te,k as ee}from"./chunk-C44QQJR4.js";import{a as V}from"./chunk-6YGTRKDT.js";import{e as R}from"./chunk-UR6MHSHU.js";var A=R(V(),1);var C=R(V(),1);function de(e){let t=e.flatMap(u=>[u,...u.children??[]]),n=t.filter(u=>u.status==="passed").length,l=t.filter(u=>u.status==="failed").length,a=t.filter(u=>u.status==="passed"||u.status==="failed").length;return{passed:n,failed:l,total:a}}function we(e){let t=$e(e.screenshotDispatcher,e.stepLogger,e.onReasoning,e.onStepComplete),[n,l]=(0,C.useState)(0),[a,u]=(0,C.useState)("idle"),c=(0,C.useRef)("idle"),v=(0,C.useRef)(0),S=(0,C.useRef)(!1),T=(0,C.useRef)(null),d=(0,C.useRef)(null),L=(0,C.useCallback)(h=>{c.current=h,u(h)},[]),O=(0,C.useCallback)(async h=>{let b=await e.getNextConfig(h);if(!b){L("done"),e.onAllComplete?.();return}let B=h?v.current+1:0;v.current=B,l(B),e.onStepStart?.(b,B),T.current=null,d.current=null,L("running"),await t.startRun(b,e.spawnOpts)},[t,e,L]);(0,C.useEffect)(()=>{S.current||(S.current=!0,O(null))},[]),(0,C.useEffect)(()=>{if(!t.lastRunEnd||t.lastRunEnd===T.current||c.current!=="running")return;T.current=t.lastRunEnd,c.current="transitioning",u("transitioning");let h=t.lastRunEnd,b=de(t.steps),B=t.bifurcationInfo,F={status:h.status==="passed"?"passed":"failed",duration_s:h.duration??0,reason:h.reason,runEnd:h,hadError:!1,stepsPassed:b.passed,stepsFailed:b.failed,stepsTotal:b.total,bifurcationFlows:B&&!B.isSingleFlow?B.flows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(F,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(F)},[t.lastRunEnd]),(0,C.useEffect)(()=>{if(!t.runError||t.runError===d.current||t.lastRunEnd||c.current!=="running")return;d.current=t.runError,c.current="transitioning",u("transitioning");let h=de(t.steps),b={status:"failed",duration_s:0,reason:t.runError,runEnd:null,hadError:!0,stepsPassed:h.passed,stepsFailed:h.failed,stepsTotal:h.total,bifurcationFlows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(b,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(b)},[t.runError,t.lastRunEnd]);let y=(0,C.useCallback)(()=>{t.cancelRun()},[t]);return{runner:t,currentStepIndex:n,phase:a,cancel:y}}var pe=R(V(),1);var ne=R(k(),1),Ee=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function ke({label:e,hasBifurcation:t=!1}){let[n,l]=(0,pe.useState)(0),[a,u]=(0,pe.useState)(0);K(()=>{l(v=>(v+1)%Ee.length)},80),K(()=>{u(v=>(v+1)%4)},400);let c=e??(t?"Planning approach":"Analyzing objective");return(0,ne.jsxs)(s,{marginLeft:1,children:[(0,ne.jsxs)(o,{color:i.orange,children:[Ee[n]," "]}),(0,ne.jsxs)(o,{color:i.dim,children:[c,".".repeat(a+1)]})]})}function Ie(e){if(!e.isRunning||e.replayInfo)return null;let t=e.bifurcationInfo;if(t&&!t.isSingleFlow){let n=e.steps.findIndex(a=>a.status==="running");return(n===-1?e.cmInitCounts.length===0:n>=e.cmInitCounts.length)?{label:n>0?`Planning flow ${n+1}`:void 0,hasBifurcation:!0}:null}return e.cmInitCounts.length>0||e.steps.some(n=>n.children?.length)?null:{hasBifurcation:!!t}}var I=R(V(),1);var Ce=R(V(),1);var re=R(k(),1),He="#ffc580",Ue="#ffd9a8",Le="#ffffff";function oe({text:e,active:t=!0}){let[n,l]=(0,Ce.useState)(0),a=4;if(K(()=>{l(c=>(c+1)%(e.length+a*2))},t?80:null),!t)return(0,re.jsx)(o,{color:Le,children:e});let u=e.split("").map((c,v)=>{let S=n-a,T=Math.abs(v-S-a/2),d;return T<=a/2?d=He:T<=a?d=Ue:d=Le,(0,re.jsx)(o,{color:d,children:c},v)});return(0,re.jsx)(o,{children:u})}var _=R(k(),1),We={starting:i.orange,running:i.orange,passed:i.green,failed:i.red,cancelled:i.dim,timed_out:i.orange};function ie({currentStep:e,maxSteps:t,elapsed:n,status:l}){let a=We[l]??i.orange,u=n<60?`${n.toFixed(1)}s`:`${Math.floor(n/60)}m ${Math.round(n%60)}s`;return(0,_.jsxs)(s,{marginLeft:3,children:[(0,_.jsx)(o,{color:i.dim,children:"Steps "}),(0,_.jsx)(o,{bold:!0,children:e}),(0,_.jsxs)(o,{color:i.dim,children:["/",t]}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Elapsed "}),(0,_.jsx)(o,{bold:!0,children:u}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Status "}),(0,_.jsx)(o,{bold:!0,color:a,children:l})]})}var Ve={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 Oe(e){return Ve[e]??"\u25CF"}var q=R(k(),1);function fe({steps:e,flows:t,cmInitCounts:n,renderStep:l}){return(0,q.jsxs)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,q.jsxs)(o,{color:i.dim,children:["\u2501\u2501 Bifurcated into ",t?.length??e.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),e.map((a,u)=>(0,q.jsxs)(s,{flexDirection:"column",marginTop:u>0?1:0,children:[(0,q.jsxs)(o,{color:i.orange,children:["Flow ",u+1,": ",t?.[u]??a.objective]}),n&&n[u]!=null&&(0,q.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",n[u]," checkpoints"]}),a.children&&a.children.length>0?a.children.map(c=>{let v=!!c.branchObjective,S=`f${u}-${c.childId??"p"}-${c.index}`;return v?(0,q.jsxs)(s,{flexDirection:"column",children:[l({...c,children:void 0},S),(c.children??[]).map(T=>(0,q.jsx)(s,{marginLeft:2,children:l(T,`${S}-${T.childId??"p"}-${T.index}`)},`${S}-${T.childId??"p"}-${T.index}`))]},`${S}-host`):l(c,S)}):a.status==="pending"&&(0,q.jsx)(o,{color:i.dim,children:" \u25CB Waiting..."})]},u))]})}var H=R(k(),1);function Pe({label:e,shimmer:t=!1}){return(0,H.jsxs)(s,{marginLeft:6,children:[(0,H.jsx)(te,{}),(0,H.jsx)(o,{children:" "}),t?(0,H.jsx)(oe,{text:e,active:!0}):(0,H.jsx)(o,{color:i.dim,children:e})]})}var De=R(V(),1);var me=R(k(),1);function ze(e,t){let n=[];for(let l of e.split(`
3
3
  `)){if(l===""){n.push("");continue}let a="";for(let u of l.split(" ")){let c=u;for(;c.length>t;)a&&(n.push(a),a=""),n.push(c.slice(0,t)),c=c.slice(t);a===""?a=c:a.length+1+c.length<=t?a+=" "+c:(n.push(a),a=c)}n.push(a)}return n}function je({text:e,maxLines:t=3}){let{stdout:n}=ee(),l=Math.max(20,(n?.columns??80)-7),a=!e.trim(),[u,c]=(0,De.useState)(!0);K(()=>c(T=>!T),500);let v=(a?"Thinking\u2026":e)+(u?"\u258C":" "),S=ze(v,l).slice(-t);for(;S.length<t;)S.push("");return(0,me.jsx)(s,{borderStyle:"round",borderColor:i.muted,paddingX:1,marginLeft:3,flexDirection:"column",children:S.map((T,d)=>(0,me.jsx)(o,{color:a?i.dim:i.secondary,wrap:"truncate-end",children:T.length?T:" "},d))})}var U=R(k(),1);function se({activity:e,describe:t,describeVisible:n}){return(0,U.jsxs)(U.Fragment,{children:[e?(0,U.jsx)(Pe,{label:e.label,shimmer:e.shimmer}):null,n?(0,U.jsx)(je,{text:t??""}):null]})}var r=R(k(),1);function le(e){for(let t of e){if(t.children&&t.children.length>0){let n=le(t.children);if(n)return n}if(t.status==="running")return t}}function z(e){return e.status==="running"&&!e.branchObjective&&(!e.children||e.children.length===0)}function Fe(e){let t=[];for(let n of e)z(n)||(n.children&&n.children.length>0?t.push({...n,children:Fe(n.children)}):t.push(n));return t}function ge(e,t){if(!e)return null;let n=e.objective??"";return n.length>0&&!/^Step \d+$/.test(n)?{label:n+"\u2026",shimmer:!1}:{label:t?"Looking at the screen\u2026":"Deciding next action\u2026",shimmer:!0}}function P({step:e,indent:t=2}){let n=e.actionType?Oe(e.actionType):null,l=e.status==="running",a=e.status==="passed",u=e.status==="failed",c=e.status==="pending"||e.status==="stopped",{stdout:v}=ee(),S=v?.columns??80,T=Math.max(20,S-t-21),d=e.objective??"",L=d.length>T?d.slice(0,T-1)+"\u2026":d,O=(e.duration??0)*1e3,y=e.duration!=null?O<1e3?`${Math.round(O)}ms`:`${(O/1e3).toFixed(1)}s`:"";return(0,r.jsxs)(s,{flexDirection:"column",children:[(0,r.jsxs)(s,{marginLeft:t,children:[(0,r.jsx)(s,{width:4,children:(0,r.jsxs)(o,{color:i.muted,children:[String(e.index).padStart(2," ")," "]})}),(0,r.jsx)(s,{width:3,children:l?(0,r.jsx)(te,{}):a?(0,r.jsx)(o,{color:i.green,bold:!0,children:"\u2713"}):u?(0,r.jsx)(o,{color:i.red,bold:!0,children:"\u2717"}):(0,r.jsx)(o,{color:i.muted,children:"\u25CB"})}),(0,r.jsx)(s,{flexGrow:1,children:l?(0,r.jsx)(oe,{text:L,active:!0}):u?(0,r.jsx)(o,{color:i.red,children:L}):c?(0,r.jsx)(o,{color:i.dim,children:L}):(0,r.jsx)(o,{color:i.dim,children:L})}),(a||u)&&n?(0,r.jsx)(s,{width:3,marginLeft:1,children:(0,r.jsx)(o,{color:i.muted,children:n})}):(0,r.jsx)(s,{width:3,marginLeft:1}),(0,r.jsx)(s,{width:7,justifyContent:"flex-end",children:(0,r.jsx)(o,{color:i.dim,children:y})})]}),e.children&&e.children.length>0&&(0,r.jsx)(s,{flexDirection:"column",children:e.children.map((h,b)=>(0,r.jsx)(P,{step:h,indent:t+2},`child-${b}`))})]})}function Xe(e){return e.type==="cm_init"?(0,r.jsx)(s,{marginLeft:2,paddingLeft:1,children:(0,r.jsxs)(o,{color:i.dim,children:["\u25AA Generated task with ",e.count," checkpoints"]})}):(0,r.jsx)(s,{marginLeft:2,paddingLeft:1,children:(0,r.jsx)(P,{step:e.step})})}function _e({steps:e,bifurcated:t,flows:n,cmInitCounts:l,maxSteps:a=50,staticSteps:u=!1,onStepCommit:c,describe:v,describeVisible:S,describeRevealing:T}){let d=(0,I.useRef)(new Set),L=(0,I.useRef)(!1),O=(0,I.useRef)(new Set),y=(0,I.useRef)(!1),h=(0,I.useRef)(new Set),b=(0,I.useRef)(0);(0,I.useEffect)(()=>{e.length===0&&b.current>0&&(d.current.clear(),L.current=!1,O.current.clear(),y.current=!1,h.current.clear()),b.current=e.length},[e.length]);let B=e.flatMap(p=>[p,...p.children??[]]),F=B.some(p=>p.status==="running"),M=B.some(p=>p.status==="failed"),X=B.length===0||B.every(p=>p.status==="pending"),Y=B.filter(p=>p.status==="passed"||p.status==="failed").length,N;X?N="starting":F?N="running":M?N="failed":N="passed";let J=(0,I.useRef)(null),[ce,he]=(0,I.useState)(0);(0,I.useEffect)(()=>{B.length===0||X?(J.current=null,he(0)):F&&J.current==null&&(J.current=Date.now())},[F,X,B.length]),(0,I.useEffect)(()=>{if(!F)return;let p=setInterval(()=>{J.current!=null&&he((Date.now()-J.current)/1e3)},500);return()=>clearInterval(p)},[F]);let ae=(0,I.useRef)(new Set),[,xe]=(0,I.useState)(0),be=(0,I.useRef)(!1);(0,I.useEffect)(()=>{if(!c||!u||t)return;let p=[];!be.current&&l&&l[0]!=null&&(be.current=!0,l[0]>0&&p.push({key:"cm_init_0",type:"cm_init",count:l[0]}));for(let g of e)(g.status==="passed"||g.status==="failed")&&!ae.current.has(g.index)&&(ae.current.add(g.index),p.push({key:`step_${g.index}`,type:"step",step:{...g,children:g.children?[...g.children]:void 0}}));if(p.length>0){for(let g of p)c(Xe(g));xe(g=>g+1)}},[e,t,l,u,c]),(0,I.useEffect)(()=>{if(!c||u)return;let p=d.current.size;if(!t&&!y.current&&l&&l[0]!=null&&(y.current=!0,l[0]>0&&c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsxs)(o,{color:i.dim,children:["\u25A0 Generated task with ",l[0]," checkpoints"]})}))),t&&n&&!L.current&&(L.current=!0,c((0,r.jsx)(o,{color:i.purple,children:"\u2501\u2501 Bifurcated into "+n.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"}))),t){let g=e.flatMap((x,f)=>{let m=x.children??[];return!O.current.has(f)&&m.length>0&&(O.current.add(f),c((0,r.jsx)(o,{color:i.purple,children:" Flow "+(f+1)+": "+(n?.[f]??"")})),l?.[f]!=null&&l[f]>0&&!h.current.has(f)&&(h.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",l[f]," checkpoints"]})})))),l?.[f]!=null&&l[f]>0&&O.current.has(f)&&!h.current.has(f)&&(h.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",l[f]," checkpoints"]})}))),m});for(let x of g){let f=`${x.childId??"p"}-${x.index}-${x.objective}`;if(!!x.branchObjective){d.current.has(f)||(d.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:{...x,children:void 0}})})));for(let $ of x.children??[]){let w=`child-${x.childId??"p"}-${x.index}-${$.childId??"p"}-${$.index}-${$.objective}`;d.current.has(w)||($.status==="passed"||$.status==="failed"||$.status==="stopped")&&(d.current.add(w),c((0,r.jsx)(s,{marginLeft:4,children:(0,r.jsx)(P,{step:$})})))}continue}d.current.has(f)||(x.status==="passed"||x.status==="failed"||x.status==="stopped")&&(d.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:x})})))}}else for(let g of e){let x=`${g.index}-${g.objective}`,f=!!g.branchObjective;f&&!d.current.has(x)&&(d.current.add(x),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:{...g,children:void 0}})})));for(let m of g.children??[]){let $=`child-${g.index}-${m.childId??"p"}-${m.index}-${m.objective}`;d.current.has($)||(m.status==="passed"||m.status==="failed"||m.status==="stopped")&&(d.current.add($),c((0,r.jsx)(s,{marginLeft:4,children:(0,r.jsx)(P,{step:m})})))}!f&&!d.current.has(x)&&(g.status==="passed"||g.status==="failed"||g.status==="stopped")&&(d.current.add(x),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:{...g,children:void 0}})})))}d.current.size>p&&xe(g=>g+1)},[e,c,t,n,l]);let G=[];if(u&&!t)for(let p of e)ae.current.has(p.index)||G.push(p);else if(c&&!u)if(t)for(let p of e){let g=p.children??[],x=[];for(let f of g){let m=`${f.childId??"p"}-${f.index}-${f.objective}`,$=d.current.has(m);if(f.branchObjective){let w=(f.children??[]).filter(Q=>{let ue=`child-${f.childId??"p"}-${f.index}-${Q.childId??"p"}-${Q.index}-${Q.objective}`;return!d.current.has(ue)});(!$||w.length>0)&&x.push({...f,children:w})}else $||x.push(f)}x.length>0&&G.push({...p,children:x})}else for(let p of e){let g=`${p.index}-${p.objective}`,x=d.current.has(g),f=(p.children??[]).filter(m=>{let $=`child-${p.index}-${m.childId??"p"}-${m.index}-${m.objective}`;return!d.current.has($)});x?f.length>0&&G.push({...p,children:f}):G.push({...p,children:f})}if(!u){let p=c?G:e,g=le(p),x=ge(g,T);return(0,r.jsxs)(s,{flexDirection:"column",children:[t?c?p.length>0?(0,r.jsx)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:p.map((m,$)=>(0,r.jsx)(s,{flexDirection:"column",marginTop:$>0?1:0,children:m.children&&m.children.length>0?m.children.map(w=>{if(z(w))return null;let Q=!!w.branchObjective,ue=`${w.childId??"p"}-${w.index}-${w.objective}`,Ke=d.current.has(ue);return Q?(0,r.jsxs)(s,{flexDirection:"column",children:[!Ke&&(0,r.jsx)(P,{step:{...w,children:void 0}}),(w.children??[]).filter(Z=>!z(Z)).map(Z=>(0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:Z})},`f${$}-${w.index}-${Z.childId??"p"}-${Z.index}`))]},`f${$}-host-${w.childId??"p"}-${w.index}`):(0,r.jsx)(P,{step:w},`f${$}-${w.childId??"p"}-${w.index}`)}):m.status==="pending"&&(0,r.jsx)(o,{color:i.dim,children:" \u25CB Waiting..."})},$))}):null:(0,r.jsx)(fe,{steps:e,flows:n,cmInitCounts:l,renderStep:(m,$)=>z(m)?null:(0,r.jsx)(P,{step:m},$)}):(0,r.jsxs)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!c&&l&&l[0]!=null&&(0,r.jsxs)(o,{color:i.dim,children:["\u25AA Generated task with ",l[0]," checkpoints"]}),p.filter(m=>!(m.status==="running"&&(!m.children||m.children.length===0))).map(m=>{let $=`${m.index}-${m.objective}`;return c&&d.current.has($)?(0,r.jsx)(s,{flexDirection:"column",children:(m.children??[]).filter(w=>!z(w)).map(w=>(0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:w})},`${w.childId??"p"}-${w.index}`))},`branch-children-${m.index}`):(0,r.jsx)(P,{step:m},m.index)})]}),(0,r.jsx)(se,{activity:x,describe:v,describeVisible:S}),B.length>0&&(0,r.jsx)(ie,{currentStep:Y,maxSteps:a,elapsed:ce,status:N})]})}if(t){let p=le(e),g=ge(p,T);return(0,r.jsxs)(s,{flexDirection:"column",children:[(0,r.jsx)(fe,{steps:e,flows:n,cmInitCounts:l,renderStep:(x,f)=>z(x)?null:(0,r.jsx)(P,{step:x},f)}),(0,r.jsx)(se,{activity:g,describe:v,describeVisible:S}),B.length>0&&(0,r.jsx)(ie,{currentStep:Y,maxSteps:a,elapsed:ce,status:N})]})}let Ne=le(G),Ge=ge(Ne,T),Re=Fe(G);return(0,r.jsxs)(s,{flexDirection:"column",children:[Re.length>0&&(0,r.jsx)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:Re.map(p=>(0,r.jsx)(P,{step:p},p.index))}),(0,r.jsx)(se,{activity:Ge,describe:v,describeVisible:S}),B.length>0&&(0,r.jsx)(ie,{currentStep:Y,maxSteps:a,elapsed:ce,status:N})]})}var W=R(k(),1);function Ae({runner:e,runKey:t,onStepCommit:n}){let l=Ie({isRunning:e.isRunning,bifurcationInfo:e.bifurcationInfo,steps:e.steps,cmInitCounts:e.cmInitCounts,replayInfo:e.replayInfo});return(0,W.jsxs)(W.Fragment,{children:[l&&(0,W.jsx)(ke,{label:l.label,hasBifurcation:l.hasBifurcation}),e.isRunning&&e.steps.length>0&&(0,W.jsx)(_e,{steps:e.steps,bifurcated:!!e.bifurcationInfo&&!e.bifurcationInfo.isSingleFlow,flows:e.bifurcationInfo?.flows,cmInitCounts:e.cmInitCounts,maxSteps:e.maxSteps,onStepCommit:n},`run-${t}`)]})}var D=R(k(),1),Ye=64;function Je(e){return e.split(`
4
4
  `).map(t=>t.replace(/^[-–•]\s*/,"").trim()).filter(t=>t.length>0)}function qe({status:e,summary:t,duration:n,steps:l,stepsPassed:a,stepsFailed:u,reason:c,creditsConsumed:v}){let S=e==="passed",T=S?i.green:i.red,d=S?"\u2713":"\u2717",L=e.toUpperCase(),O=a??(S?l:Math.max(0,l-1)),y=u??(S?0:1),h=y>0?`${l} steps (${O} passed, ${y} failed)`:`${l} steps`,b=n<60?`${n.toFixed(1)}s`:`${Math.floor(n/60)}m ${Math.round(n%60)}s`,B=Je(t);return(0,D.jsx)(s,{flexDirection:"column",marginTop:1,children:(0,D.jsxs)(s,{borderStyle:"round",borderColor:T,flexDirection:"column",paddingX:2,paddingY:1,width:Ye+6,children:[(0,D.jsxs)(s,{flexDirection:"column",children:[(0,D.jsxs)(o,{bold:!0,color:T,children:[d," ",L]}),(0,D.jsxs)(o,{color:i.dim,wrap:"wrap",children:[h," \xB7 ",b,typeof v=="number"&&v>0?` \xB7 ${parseFloat(v.toFixed(4))} credits`:""]})]}),B.length>0&&(0,D.jsx)(s,{flexDirection:"column",marginTop:1,marginLeft:1,children:B.map((F,M)=>(0,D.jsxs)(s,{marginBottom:M<B.length-1?1:0,children:[(0,D.jsx)(o,{color:i.orange,children:"\u25CF "}),(0,D.jsx)(s,{flexShrink:1,children:(0,D.jsx)(o,{wrap:"wrap",children:F})})]},M))}),c&&!S&&(0,D.jsx)(s,{marginTop:1,children:(0,D.jsxs)(o,{color:i.red,wrap:"wrap",children:["Reason: ",c]})})]})})}var j=R(k(),1);function Me({message:e,code:t,remediation:n,docsUrl:l}){return(0,j.jsx)(ve,{title:"Error",variant:"error",children:(0,j.jsxs)(s,{flexDirection:"column",paddingY:1,children:[(0,j.jsxs)(o,{color:i.red,bold:!0,children:[" \u2717 ",e]}),t&&(0,j.jsxs)(s,{marginTop:0,marginLeft:5,children:[(0,j.jsx)(o,{color:i.muted,children:"Code: "}),(0,j.jsx)(o,{color:i.dim,children:t})]}),n&&(0,j.jsxs)(s,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,j.jsx)(o,{color:i.green,bold:!0,children:"Fix:"}),(0,j.jsxs)(o,{color:i.orange,children:["$ ",n]})]}),l&&(0,j.jsxs)(s,{marginTop:1,marginLeft:5,children:[(0,j.jsx)(o,{color:i.muted,children:"Docs: "}),(0,j.jsx)(o,{color:i.orange,underline:!0,children:l})]})]})})}var E=R(k(),1);function un(e){let{exit:t}=Te(),{append:n}=ye(),l=(0,A.useRef)(!1);(0,A.useEffect)(()=>{l.current||(l.current=!0,n((0,E.jsx)(s,{flexDirection:"column",marginBottom:1,children:(0,E.jsxs)(s,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,E.jsx)(o,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,E.jsx)(o,{color:i.dim,children:" \u2502 "}),(0,E.jsx)(o,{color:i.orange,children:e.topBanner.model}),(0,E.jsx)(o,{color:i.dim,children:" \u2502 "}),(0,E.jsx)(o,{color:i.dim,children:e.topBanner.auth})]})})),n((0,E.jsx)(Qe,{data:e.globalConfig})),e.priorAttemptRollup&&n((0,E.jsx)(o,{color:i.dim,children:` \u21B3 replayed ${e.priorAttemptRollup.startIdx}..${e.priorAttemptRollup.endIdx-1} (${e.priorAttemptRollup.count} steps, from prior attempt)`})))},[]);let a=(0,A.useRef)(null),u=(0,A.useCallback)(async y=>{let h=await e.getNextStep(y);return h?(a.current=h,h.config):(a.current=null,null)},[e]),c=(0,A.useCallback)((y,h)=>{let b=a.current;if(!b)return;let B=b.mode==="replay"?"cyan":"#dc4e08",F=b.modeReason?` (${b.modeReason})`:"",M=b.perStepOverrides?Object.entries(b.perStepOverrides):[];n((0,E.jsxs)(s,{flexDirection:"column",marginBottom:0,children:[(0,E.jsxs)(o,{children:[(0,E.jsxs)(o,{color:i.dim,children:[b.banner.stepLabel," "]}),(0,E.jsxs)(o,{color:B,children:["[",b.mode,"]"]}),(0,E.jsx)(o,{color:i.dim,children:F})]}),(0,E.jsx)(o,{color:i.dim,children:b.banner.objective}),M.length>0&&(0,E.jsxs)(o,{color:i.dim,children:["overrides: ",M.map(([X,Y])=>`${X}=${Y}`).join(", ")]})]}))},[n]),v=(0,A.useRef)(0),S=(0,A.useRef)(!1),T=(0,A.useCallback)((y,h)=>(y.hadError?n((0,E.jsx)(Me,{message:y.reason??"Runner error",code:"RUNNER_ERROR"})):n((0,E.jsx)(s,{flexDirection:"column",marginBottom:1,children:(0,E.jsx)(qe,{status:y.status,summary:y.runEnd?.summary??"",duration:y.runEnd?.duration??0,steps:y.stepsTotal,stepsPassed:y.stepsPassed,stepsFailed:y.stepsFailed,reason:y.runEnd?.reason,creditsConsumed:y.runEnd?.credits_consumed})})),e.onStepEnd?.(y,h)??!0),[n,e]),d=we({getNextConfig:u,onStepStart:c,onStepEnd:T,onAllComplete:()=>{e.onAllComplete(),e.exitOnComplete!==!1&&setImmediate(()=>t())},screenshotDispatcher:e.screenshotDispatcher,stepLogger:e.stepLogger,onReasoning:e.onReasoning,onStepComplete:e.onStepComplete,spawnOpts:e.spawnOpts}),L=250,O=5e3;return Se((y,h)=>{if(h.ctrl&&y==="c"){let b=Date.now(),B=b-v.current;if(B<L)return;S.current&&B<O?(d.cancel(),e.onCancel?.(),e.exitOnComplete!==!1&&setImmediate(()=>t())):(S.current=!0,n((0,E.jsx)(o,{color:"yellow",children:"press Ctrl+C again to cancel run"}))),v.current=b}}),(0,E.jsx)(s,{flexDirection:"column",children:d.phase!=="done"&&(0,E.jsx)(Ae,{runner:d.runner,runKey:d.currentStepIndex,onStepCommit:n})})}function Qe({data:e}){return(0,E.jsx)(Be,{title:"test.md run",titleColor:"#ff9500",borderColor:i.dim,rows:[{label:"source",value:e.source},{label:"steps",value:`${e.steps.total} (${e.steps.replay} replay, ${e.steps.author} author per walker)`},{label:"model",value:e.model},{label:"viewport",value:`${e.viewport.width} x ${e.viewport.height}`},{label:"chrome",value:e.chrome},{label:"session",value:e.session},{label:"variables",value:`${e.variables.count} (${e.variables.secrets} secret)`},{label:"flags",value:e.flags.length>0?e.flags.join(" "):"(none)"}]})}export{_e as a,ke as b,Ie as c,de as d,qe as e,Me as f,un as g};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as $}from"./chunk-YCCUBQY4.js";import{a as U}from"./chunk-U3JB76QP.js";import{a as T}from"./chunk-2WVKOZ6W.js";import{a as k}from"./chunk-YIOWO6WS.js";import{a as _}from"./chunk-KRFGAVYU.js";import{x as i}from"./chunk-QIE62H3J.js";import{a as O}from"./chunk-HCBYKLMW.js";import{a as u,b as s}from"./chunk-C44QQJR4.js";import{a as K}from"./chunk-6YGTRKDT.js";import{e as S}from"./chunk-UR6MHSHU.js";var e=S(K(),1);var r=S(O(),1);function V(n,x,c){return{id:n,label:`${x} (${n})`,isActive:n===c}}function se({resolver:n,currentProjectId:x,env:c,onSelect:w,onCancel:C}){let[q,B]=(0,e.useState)([]),[D,l]=(0,e.useState)(!0),[H,m]=(0,e.useState)(!1),[J,g]=(0,e.useState)(!1),[Q,P]=(0,e.useState)(null),[d,p]=(0,e.useState)("list"),[v,R]=(0,e.useState)(""),[E,h]=(0,e.useState)(null),[I,X]=(0,e.useState)(""),b=(0,e.useRef)(!1),A=(0,e.useRef)(!0);(0,e.useEffect)(()=>{if(!n){P("Login first to browse projects"),l(!1);return}let o=new AbortController,a=I.trim();return A.current?l(!0):a&&g(!0),m(!0),P(null),(async()=>{try{let t=n.cached??await n.resolve();if(!t){P("Login first to browse projects"),l(!1),m(!1),g(!1);return}let L=k(c),F=new T(L.tmsBaseUrl,t.username,t.access_key),f=!0,N=0,G=a?{signal:o.signal,name:a,perPage:10}:{signal:o.signal,perPage:10};for await(let y of F.listProjectsStream(G)){if(f&&(l(!1),g(!1),A.current=!1,f=!1),y.totalLoaded===0&&y.done&&N===0&&!a){b.current=!0,p("naming"),m(!1);return}let M=y.projects.map(j=>V(j.project_id,j.name,x));B(N===0?M:j=>[...j,...M]),N+=y.projects.length,y.done&&m(!1)}f&&(l(!1),m(!1),g(!1))}catch(t){if(t?.name==="AbortError")return;P(t instanceof Error?t.message:String(t)),l(!1),m(!1),g(!1)}})(),()=>o.abort()},[n,x,c,I]);let Y=(0,e.useCallback)(o=>{let a=o.trim();if(!a){h("Name cannot be empty");return}h(null),p("creating"),(async()=>{try{if(!n)throw new Error("Not authenticated");let t=n.cached??await n.resolve();if(!t)throw new Error("Not authenticated");let L=k(c),f=await new T(L.tmsBaseUrl,t.username,t.access_key).createProject(a);w(f.id,f.name)}catch(t){h(t instanceof Error?t.message:String(t)),p("naming")}})()},[n,c,w]),z=(0,e.useCallback)(()=>{R(""),h(null),b.current?C():p("list")},[C]);return d==="naming"||d==="creating"?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(s,{color:i.orange,bold:!0,children:"Create new project"}),b.current&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.dim,children:"No projects yet \u2014 let's create one."})}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(s,{color:i.dim,children:"Name: "}),d==="naming"?(0,r.jsx)($,{value:v,onChange:o=>{R(o),E&&h(null)},onSubmit:Y,onCancel:z}):(0,r.jsx)(s,{children:v})]}),E&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.red,children:E})}),d==="creating"&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.dim,children:"Creating..."})}),d==="naming"&&(0,r.jsx)(_,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:b.current?"cancel":"back"})]}):(0,r.jsx)(U,{title:"Projects",items:q,loading:D,loadingMore:H,searching:J,preserveSelectionById:!0,onSearch:X,error:Q,itemNoun:"projects",onTab:()=>{b.current=!1,p("naming")},extraHint:"tab to create new",onSelect:o=>{let a=o.label.replace(` (${o.id})`,"");w(o.id,a)},onCancel:C})}export{V as a,se as b};
2
+ import{a as $}from"./chunk-YCCUBQY4.js";import{a as U}from"./chunk-YZKPZXHY.js";import{a as T}from"./chunk-2WVKOZ6W.js";import{a as k}from"./chunk-RLG5NUTE.js";import{a as _}from"./chunk-AV5SUGRY.js";import{x as i}from"./chunk-E4OYR32M.js";import{a as O}from"./chunk-HCBYKLMW.js";import{a as u,b as s}from"./chunk-C44QQJR4.js";import{a as K}from"./chunk-6YGTRKDT.js";import{e as S}from"./chunk-UR6MHSHU.js";var e=S(K(),1);var r=S(O(),1);function V(n,x,c){return{id:n,label:`${x} (${n})`,isActive:n===c}}function se({resolver:n,currentProjectId:x,env:c,onSelect:w,onCancel:C}){let[q,B]=(0,e.useState)([]),[D,l]=(0,e.useState)(!0),[H,m]=(0,e.useState)(!1),[J,g]=(0,e.useState)(!1),[Q,P]=(0,e.useState)(null),[d,p]=(0,e.useState)("list"),[v,R]=(0,e.useState)(""),[E,h]=(0,e.useState)(null),[I,X]=(0,e.useState)(""),b=(0,e.useRef)(!1),A=(0,e.useRef)(!0);(0,e.useEffect)(()=>{if(!n){P("Login first to browse projects"),l(!1);return}let o=new AbortController,a=I.trim();return A.current?l(!0):a&&g(!0),m(!0),P(null),(async()=>{try{let t=n.cached??await n.resolve();if(!t){P("Login first to browse projects"),l(!1),m(!1),g(!1);return}let L=k(c),F=new T(L.tmsBaseUrl,t.username,t.access_key),f=!0,N=0,G=a?{signal:o.signal,name:a,perPage:10}:{signal:o.signal,perPage:10};for await(let y of F.listProjectsStream(G)){if(f&&(l(!1),g(!1),A.current=!1,f=!1),y.totalLoaded===0&&y.done&&N===0&&!a){b.current=!0,p("naming"),m(!1);return}let M=y.projects.map(j=>V(j.project_id,j.name,x));B(N===0?M:j=>[...j,...M]),N+=y.projects.length,y.done&&m(!1)}f&&(l(!1),m(!1),g(!1))}catch(t){if(t?.name==="AbortError")return;P(t instanceof Error?t.message:String(t)),l(!1),m(!1),g(!1)}})(),()=>o.abort()},[n,x,c,I]);let Y=(0,e.useCallback)(o=>{let a=o.trim();if(!a){h("Name cannot be empty");return}h(null),p("creating"),(async()=>{try{if(!n)throw new Error("Not authenticated");let t=n.cached??await n.resolve();if(!t)throw new Error("Not authenticated");let L=k(c),f=await new T(L.tmsBaseUrl,t.username,t.access_key).createProject(a);w(f.id,f.name)}catch(t){h(t instanceof Error?t.message:String(t)),p("naming")}})()},[n,c,w]),z=(0,e.useCallback)(()=>{R(""),h(null),b.current?C():p("list")},[C]);return d==="naming"||d==="creating"?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(s,{color:i.orange,bold:!0,children:"Create new project"}),b.current&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.dim,children:"No projects yet \u2014 let's create one."})}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(s,{color:i.dim,children:"Name: "}),d==="naming"?(0,r.jsx)($,{value:v,onChange:o=>{R(o),E&&h(null)},onSubmit:Y,onCancel:z}):(0,r.jsx)(s,{children:v})]}),E&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.red,children:E})}),d==="creating"&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.dim,children:"Creating..."})}),d==="naming"&&(0,r.jsx)(_,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:b.current?"cancel":"back"})]}):(0,r.jsx)(U,{title:"Projects",items:q,loading:D,loadingMore:H,searching:J,preserveSelectionById:!0,onSearch:X,error:Q,itemNoun:"projects",onTab:()=>{b.current=!1,p("naming")},extraHint:"tab to create new",onSelect:o=>{let a=o.label.replace(` (${o.id})`,"");w(o.id,a)},onCancel:C})}export{V as a,se as b};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as b}from"./chunk-KRFGAVYU.js";import{m as d,x as o}from"./chunk-QIE62H3J.js";import{a as L}from"./chunk-HCBYKLMW.js";import{a as u,b as c,i as A}from"./chunk-C44QQJR4.js";import{a as D}from"./chunk-6YGTRKDT.js";import{e as h}from"./chunk-UR6MHSHU.js";var x=h(D(),1);import{readdirSync as N,mkdirSync as B,statSync as k}from"fs";import{join as P}from"path";var r=h(L(),1);function O(n){try{return N(n).filter(l=>{try{return k(P(n,l)).isDirectory()}catch{return!1}})}catch{return[]}}function E(n,l,f,v){return{name:n,path:l,label:n,isActive:v}}function H({currentPath:n,onSelect:l,onCancel:f}){let s=O(d).map(i=>{let e=P(d,i);return E(i,e,n,e===n)}),p=!n,R=s.length+2,[a,C]=(0,x.useState)(()=>{if(p)return 0;let i=s.findIndex(e=>e.isActive);return i>=0?i+1:0}),[T,I]=(0,x.useState)(!1),[S,g]=(0,x.useState)("");return A((i,e)=>{if(T){if(e.escape){I(!1),g("");return}if(e.return){let t=S.trim();if(t){let m=P(d,t);B(m,{recursive:!0}),l(m),f()}return}if(e.backspace||e.delete){g(t=>t.slice(0,-1));return}i&&!e.ctrl&&!e.meta&&g(t=>t+i);return}if(e.escape){f();return}if(e.upArrow){C(t=>Math.max(0,t-1));return}if(e.downArrow){C(t=>Math.min(R-1,t+1));return}if(e.return){if(a===0){p||l(""),f();return}if(a===s.length+1){B(d,{recursive:!0}),I(!0),g("");return}let t=s[a-1];t&&!t.isActive&&l(t.path),f();return}}),T?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile \u203A New"}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(c,{color:o.secondary,children:"Name: "}),(0,r.jsx)(c,{children:S}),(0,r.jsx)(c,{color:o.dim,children:"\u2588"})]}),(0,r.jsx)(b,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:"back"})]}):(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile"}),(0,r.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,r.jsxs)(c,{color:p?o.green:a===0?o.orange:o.dim,children:[a===0?"\u276F ":" ","Use temporary (no profile)",p?" \u25CF active":""]}),s.map((i,e)=>{let m=e+1===a,w=m?"\u276F ":" ",y=i.isActive?o.green:m?o.orange:void 0;return(0,r.jsxs)(c,{color:y,children:[w,i.label,i.isActive?" \u25CF active":""]},i.name)}),(0,r.jsxs)(c,{color:a===s.length+1?o.orange:o.dim,children:[a===s.length+1?"\u276F ":" ","+ Create new"]})]}),(0,r.jsx)(b,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}export{O as a,E as b,H as c};
2
+ import{a as b}from"./chunk-AV5SUGRY.js";import{m as d,x as o}from"./chunk-E4OYR32M.js";import{a as L}from"./chunk-HCBYKLMW.js";import{a as u,b as c,i as A}from"./chunk-C44QQJR4.js";import{a as D}from"./chunk-6YGTRKDT.js";import{e as h}from"./chunk-UR6MHSHU.js";var x=h(D(),1);import{readdirSync as N,mkdirSync as B,statSync as k}from"fs";import{join as P}from"path";var r=h(L(),1);function O(n){try{return N(n).filter(l=>{try{return k(P(n,l)).isDirectory()}catch{return!1}})}catch{return[]}}function E(n,l,f,v){return{name:n,path:l,label:n,isActive:v}}function H({currentPath:n,onSelect:l,onCancel:f}){let s=O(d).map(i=>{let e=P(d,i);return E(i,e,n,e===n)}),p=!n,R=s.length+2,[a,C]=(0,x.useState)(()=>{if(p)return 0;let i=s.findIndex(e=>e.isActive);return i>=0?i+1:0}),[T,I]=(0,x.useState)(!1),[S,g]=(0,x.useState)("");return A((i,e)=>{if(T){if(e.escape){I(!1),g("");return}if(e.return){let t=S.trim();if(t){let m=P(d,t);B(m,{recursive:!0}),l(m),f()}return}if(e.backspace||e.delete){g(t=>t.slice(0,-1));return}i&&!e.ctrl&&!e.meta&&g(t=>t+i);return}if(e.escape){f();return}if(e.upArrow){C(t=>Math.max(0,t-1));return}if(e.downArrow){C(t=>Math.min(R-1,t+1));return}if(e.return){if(a===0){p||l(""),f();return}if(a===s.length+1){B(d,{recursive:!0}),I(!0),g("");return}let t=s[a-1];t&&!t.isActive&&l(t.path),f();return}}),T?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile \u203A New"}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(c,{color:o.secondary,children:"Name: "}),(0,r.jsx)(c,{children:S}),(0,r.jsx)(c,{color:o.dim,children:"\u2588"})]}),(0,r.jsx)(b,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:"back"})]}):(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile"}),(0,r.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,r.jsxs)(c,{color:p?o.green:a===0?o.orange:o.dim,children:[a===0?"\u276F ":" ","Use temporary (no profile)",p?" \u25CF active":""]}),s.map((i,e)=>{let m=e+1===a,w=m?"\u276F ":" ",y=i.isActive?o.green:m?o.orange:void 0;return(0,r.jsxs)(c,{color:y,children:[w,i.label,i.isActive?" \u25CF active":""]},i.name)}),(0,r.jsxs)(c,{color:a===s.length+1?o.orange:o.dim,children:[a===s.length+1?"\u276F ":" ","+ Create new"]})]}),(0,r.jsx)(b,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}export{O as a,E as b,H as c};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as s,j as l}from"./chunk-QIE62H3J.js";import{readFileSync as g,writeFileSync as o,mkdirSync as i,existsSync as p}from"fs";import{dirname as a}from"path";var n={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:l,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"testing",assertion_mode:"dom",network_ws:!1,network_sse:!1,bug_detection:"off",final_validation:!1,code_export:{enabled:!0,language:"python",skip_validation:!0},generate:{scenario_limit:2,per_scenario_limit:3,memory_enabled:!1},last_seen_version:"",hints_enabled:!0},c=class{constructor(r=s){this.path=r}exists(){return p(this.path)}load(){try{let r=g(this.path,"utf-8"),e=JSON.parse(r);return{...n,...e,code_export:{...n.code_export,...e.code_export??{}},generate:{...n.generate,...e.generate??{}}}}catch{return{...n,code_export:{...n.code_export},generate:{...n.generate}}}}set(r,e){try{let t=this.load();t[r]=e,i(a(this.path),{recursive:!0}),o(this.path,JSON.stringify(t,null,2)+`
2
+ import{d as s,j as l}from"./chunk-E4OYR32M.js";import{readFileSync as g,writeFileSync as o,mkdirSync as i,existsSync as p}from"fs";import{dirname as a}from"path";var n={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:l,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"testing",assertion_mode:"dom",network_ws:!1,network_sse:!1,bug_detection:"off",final_validation:!1,code_export:{enabled:!0,language:"python",skip_validation:!0},generate:{scenario_limit:2,per_scenario_limit:3,memory_enabled:!1},last_seen_version:"",hints_enabled:!0},c=class{constructor(r=s){this.path=r}exists(){return p(this.path)}load(){try{let r=g(this.path,"utf-8"),e=JSON.parse(r);return{...n,...e,code_export:{...n.code_export,...e.code_export??{}},generate:{...n.generate,...e.generate??{}}}}catch{return{...n,code_export:{...n.code_export},generate:{...n.generate}}}}set(r,e){try{let t=this.load();t[r]=e,i(a(this.path),{recursive:!0}),o(this.path,JSON.stringify(t,null,2)+`
3
3
  `)}catch(t){let d=t instanceof Error?t.message:String(t);process.stderr.write(`[config] Failed to save config: ${d}
4
4
  `)}}save(r){try{let t={...this.load(),...r};i(a(this.path),{recursive:!0}),o(this.path,JSON.stringify(t,null,2)+`
5
5
  `)}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`[config] Failed to save config: ${t}
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as f}from"./chunk-35SRW4KA.js";import{a as h}from"./chunk-FPFOW6BS.js";import{a as m}from"./chunk-YIOWO6WS.js";var o=class extends Error{constructor(a,l){super(a);this.code=l;this.name="AuthError"}};async function k(c){let{creds:i,env:a,usernameFlag:l,accessKeyFlag:p,log:t}=c,e=null,u=null;if(l&&p)e={username:l,access_key:p},t("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:l});else{let r=i.resolveAuth();r?.method==="basic"&&(e={username:r.username,access_key:r.access_key},t("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:r.username}))}if(!e){let{credentials:r,profile:E}=i.getActiveCredentials();if(!r)throw new o("Not authenticated \u2014 no credentials found","not_authenticated");if(u=r.access_token,r.expires_at-Date.now()/1e3<300)try{let n=await f({creds:i,profile:E,env:a,credentials:r});n&&(u=n.accessToken,t("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(n){let d=n instanceof Error?n.message:String(n);throw t("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:d}),new o(`Token refresh failed: ${d}`,"refresh_failed")}}let v=m(a),b=async()=>u,y=e?{username:e.username,access_key:e.access_key}:null,g=new h(v.controllerBaseUrl,b,y,t),s=await g.resolve();return s&&!e&&(e={username:s.username,access_key:s.access_key},t("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:s.username})),{basicAuth:e,token:u,resolver:g,resolvedCreds:s}}export{o as a,k as b};
2
+ import{a as f}from"./chunk-P46TIMGQ.js";import{a as h}from"./chunk-FPFOW6BS.js";import{a as m}from"./chunk-RLG5NUTE.js";var o=class extends Error{constructor(a,l){super(a);this.code=l;this.name="AuthError"}};async function k(c){let{creds:i,env:a,usernameFlag:l,accessKeyFlag:p,log:t}=c,e=null,u=null;if(l&&p)e={username:l,access_key:p},t("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:l});else{let r=i.resolveAuth();r?.method==="basic"&&(e={username:r.username,access_key:r.access_key},t("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:r.username}))}if(!e){let{credentials:r,profile:E}=i.getActiveCredentials();if(!r)throw new o("Not authenticated \u2014 no credentials found","not_authenticated");if(u=r.access_token,r.expires_at-Date.now()/1e3<300)try{let n=await f({creds:i,profile:E,env:a,credentials:r});n&&(u=n.accessToken,t("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(n){let d=n instanceof Error?n.message:String(n);throw t("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:d}),new o(`Token refresh failed: ${d}`,"refresh_failed")}}let v=m(a),b=async()=>u,y=e?{username:e.username,access_key:e.access_key}:null,g=new h(v.controllerBaseUrl,b,y,t),s=await g.resolve();return s&&!e&&(e={username:s.username,access_key:s.access_key},t("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:s.username})),{basicAuth:e,token:u,resolver:g,resolvedCreds:s}}export{o as a,k as b};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as ve}from"./chunk-KRFGAVYU.js";import{c as we,x as d}from"./chunk-QIE62H3J.js";import{a as V}from"./chunk-HCBYKLMW.js";import{a as v,b as u,h as Te,i as de,k as Ae}from"./chunk-C44QQJR4.js";import{a as ue}from"./chunk-6YGTRKDT.js";import{e as B}from"./chunk-UR6MHSHU.js";var Be=B(ue(),1);import{readFileSync as Ye,writeFileSync as Ve,mkdirSync as Xe}from"fs";import{dirname as Ge,join as Pe}from"path";var Je=Pe(we,"command-history.json"),gt=Pe(we,"generate-history.json"),ze=200,Ee=class{entries;filePath;max;constructor(o=Je,n=ze){this.filePath=o,this.max=n,this.entries=this._load()}push(o){this.entries.length>0&&this.entries[this.entries.length-1]===o||(this.entries.push(o),this.entries.length>this.max&&(this.entries=this.entries.slice(this.entries.length-this.max)),this._save())}getAll(){return[...this.entries]}search(o){let n=o.toLowerCase(),l=[];for(let s=this.entries.length-1;s>=0;s--)this.entries[s].toLowerCase().includes(n)&&l.push(this.entries[s]);return l}_load(){if(this.filePath===null)return[];try{let o=Ye(this.filePath,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?n:[]}catch{return[]}}_save(){if(this.filePath!==null)try{Xe(Ge(this.filePath),{recursive:!0}),Ve(this.filePath,JSON.stringify(this.entries)+`
2
+ import{a as ve}from"./chunk-AV5SUGRY.js";import{c as we,x as d}from"./chunk-E4OYR32M.js";import{a as V}from"./chunk-HCBYKLMW.js";import{a as v,b as u,h as Te,i as de,k as Ae}from"./chunk-C44QQJR4.js";import{a as ue}from"./chunk-6YGTRKDT.js";import{e as B}from"./chunk-UR6MHSHU.js";var Be=B(ue(),1);import{readFileSync as Ye,writeFileSync as Ve,mkdirSync as Xe}from"fs";import{dirname as Ge,join as Pe}from"path";var Je=Pe(we,"command-history.json"),gt=Pe(we,"generate-history.json"),ze=200,Ee=class{entries;filePath;max;constructor(o=Je,n=ze){this.filePath=o,this.max=n,this.entries=this._load()}push(o){this.entries.length>0&&this.entries[this.entries.length-1]===o||(this.entries.push(o),this.entries.length>this.max&&(this.entries=this.entries.slice(this.entries.length-this.max)),this._save())}getAll(){return[...this.entries]}search(o){let n=o.toLowerCase(),l=[];for(let s=this.entries.length-1;s>=0;s--)this.entries[s].toLowerCase().includes(n)&&l.push(this.entries[s]);return l}_load(){if(this.filePath===null)return[];try{let o=Ye(this.filePath,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?n:[]}catch{return[]}}_save(){if(this.filePath!==null)try{Xe(Ge(this.filePath),{recursive:!0}),Ve(this.filePath,JSON.stringify(this.entries)+`
3
3
  `)}catch{}}};function pt(r){let o=(0,Be.useRef)(null);return o.current||(o.current=new Ee(r)),o.current}var C=B(ue(),1);var Se=B(ue(),1);var $=B(V(),1);function Le({history:r,onSelect:o,onClose:n}){let[l,s]=(0,Se.useState)(""),[c,m]=(0,Se.useState)(0),S=l?r.search(l).slice(0,8):[];return de((y,g)=>{if(g.escape){n();return}if(g.return){S.length>0&&S[c]?o(S[c]):n();return}if(g.upArrow){m(M=>Math.max(0,M-1));return}if(g.downArrow){m(M=>Math.min(S.length-1,M+1));return}if(g.backspace||g.delete){s(M=>M.slice(0,-1)),m(0);return}y&&!g.ctrl&&!g.meta&&(s(M=>M+y),m(0))}),(0,$.jsxs)(v,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,$.jsx)(u,{color:d.muted,bold:!0,children:"reverse search"}),(0,$.jsxs)(v,{gap:1,children:[(0,$.jsx)(u,{color:d.dim,children:"search:"}),(0,$.jsx)(u,{children:l}),(0,$.jsx)(u,{color:d.orange,children:"\u2588"})]}),S.length>0&&(0,$.jsx)(u,{children:" "}),S.map((y,g)=>(0,$.jsx)(v,{marginLeft:2,children:(0,$.jsxs)(u,{color:g===c?d.orange:d.dim,bold:g===c,children:[g===c?"\u25B8 ":" ",y]})},`${g}-${y}`))]})}var X=B(V(),1);function De({commands:r,selectedIndex:o}){return r.length===0?null:(0,X.jsx)(v,{flexDirection:"column",marginBottom:0,children:r.map((n,l)=>{let s=l===o;return(0,X.jsxs)(v,{children:[(0,X.jsx)(u,{color:s?d.orange:d.dim,children:s?"\u276F ":" "}),(0,X.jsxs)(u,{color:s?d.orange:void 0,bold:s,children:["/",n.name]}),n.args&&(0,X.jsxs)(u,{color:d.dim,children:[" ",n.args]}),(0,X.jsxs)(u,{color:d.dim,children:[" ",n.description]})]},n.name)})})}var _e=B(ue(),1);var P=B(V(),1),$e={scenario:"Scenarios",case:"Test Cases",file:"Files"};function Oe(r){let o={scenario:0,case:0,file:0};for(let n of r)o[n.kind]++;return["scenario","case","file"].filter(n=>o[n]>0).map(n=>`${o[n]} ${$e[n]}`).join(" \xB7 ")}var ge=7;function Ke({items:r,selectedIndex:o,accent:n=d.orange}){let l=r.length;if(l===0)return null;let s=Math.floor(ge/2),c=l<=ge?0:Math.max(0,Math.min(o-s,l-ge)),m=Math.min(l,c+ge),S=c,y=l-m;return(0,P.jsxs)(v,{flexDirection:"column",marginBottom:0,children:[S>0&&(0,P.jsx)(v,{children:(0,P.jsx)(u,{color:d.dim,children:` \u22EF ${S} above \u2014 ${Oe(r.slice(0,c))}`})}),r.slice(c,m).map((g,M)=>{let W=c+M,H=W===o,Q=M===0||r[W-1].kind!==g.kind;return(0,P.jsxs)(_e.default.Fragment,{children:[Q&&(0,P.jsx)(v,{children:(0,P.jsx)(u,{color:d.dim,children:$e[g.kind]})}),(0,P.jsxs)(v,{children:[(0,P.jsx)(u,{color:H?n:d.dim,children:H?"\u276F ":" "}),(0,P.jsx)(u,{color:H?n:void 0,bold:H,children:g.label})]})]},`${g.kind}:${g.value}:${W}`)}),y>0&&(0,P.jsx)(v,{children:(0,P.jsx)(u,{color:d.dim,children:` \u22EF ${y} more \u2014 ${Oe(r.slice(m))}`})})]})}var pe=B(ue(),1);var Qe=27,Ze=127,et=11;function tt(r){return r>=64&&r<=126}function nt(r,o){r===et&&o({killToEnd:!0,ctrl:!0,raw:String.fromCharCode(r)})}function rt(r,o){r===Ze&&o({backspace:!0,meta:!0,raw:"\x1B\x7F"})}function ot(r,o){let n=r.map(s=>String.fromCharCode(s)).join(""),l=/^\[1;([0-9]+)([A-D])$/.exec(n);if(l){let s=parseInt(l[1],10),c=l[2],m={raw:"\x1B"+n};if(s===2)m.shift=!0;else if(s===3)m.meta=!0;else if(s===5)m.ctrl=!0;else return;c==="A"?m.arrowUp=!0:c==="B"?m.arrowDown=!0:c==="C"?m.arrowRight=!0:c==="D"&&(m.arrowLeft=!0),o(m);return}if(n==="[H"||n==="[1~"||n==="[7~"){o({home:!0,raw:"\x1B"+n});return}if(n==="[F"||n==="[4~"||n==="[8~"){o({end:!0,raw:"\x1B"+n});return}if(n==="[3;5~"){o({delete:!0,ctrl:!0,raw:"\x1B"+n});return}if(n==="[3;3~"){o({delete:!0,meta:!0,raw:"\x1B"+n});return}}function it(r,o){r===72?o({home:!0,raw:"\x1BO"+String.fromCharCode(r)}):r===70&&o({end:!0,raw:"\x1BO"+String.fromCharCode(r)})}function st(){let r="IDLE",o=[];function n(){r="IDLE",o=[]}return{feed(l,s){for(let c of l)r==="IDLE"?c===Qe?(r="ESC",o=[]):nt(c,s):r==="ESC"?c===91?(r="CSI",o=[]):c===79?(r="SS3",o=[]):(rt(c,s),n()):r==="CSI"?(o.push(c),tt(c)&&(ot([91,...o],s),n())):r==="SS3"&&(it(c,s),n())},flushIdle(l){r==="ESC"&&o.length===0&&l({raw:"\x1B"}),n()}}}function He(r,o={}){let n=(0,pe.useRef)(r);n.current=r;let{stdin:l}=Te();(0,pe.useEffect)(()=>{if(o.isActive===!1||!l)return;let s=st(),c=null,m=S=>{c&&(clearTimeout(c),c=null);let y=Buffer.isBuffer(S)?S:Buffer.from(S,"binary");s.feed(y,g=>n.current(g)),c=setTimeout(()=>{s.flushIdle(g=>n.current(g)),c=null},50)};return l.on("data",m),()=>{l.removeListener("data",m),c&&clearTimeout(c)}},[o.isActive,l])}var x=B(V(),1);function lt(r,o){let n=o-1;for(;n>=0&&r[n]!=="@"&&r[n]!==" "&&r[n]!==`
4
4
  `;)n--;return n<0||r[n]!=="@"||n>0&&r[n-1]!==" "&&r[n-1]!==`
5
5
  `?null:{at:n,query:r.slice(n+1,o).join("")}}var ye=10;function at(r){return r.replace(/\x1b?\[200~/g,"").replace(/\x1b?\[201~/g,"").replace(/\r\n/g,`
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as R}from"./chunk-KRFGAVYU.js";import{x as r}from"./chunk-QIE62H3J.js";import{a as Y}from"./chunk-HCBYKLMW.js";import{a,b as i,i as X}from"./chunk-C44QQJR4.js";import{a as G}from"./chunk-6YGTRKDT.js";import{e as P}from"./chunk-UR6MHSHU.js";var u=P(G(),1);var e=P(Y(),1),f=5;function K(t,I){if(!I)return t;let c=I.toLowerCase();return t.filter(B=>B.label.toLowerCase().includes(c))}function J(t){let{title:I,items:c,loading:B=!1,loadingText:F,error:L=null,itemNoun:T="items",onSelect:H,onCancel:E,defaultActiveId:w,onTab:y,extraHint:N}=t,[x,d]=(0,u.useState)(0),[S,g]=(0,u.useState)(0),[s,A]=(0,u.useState)(""),[C,h]=(0,u.useState)(null);(0,u.useEffect)(()=>{if(c.length===0)return;if(t.preserveSelectionById&&C!==null){let n=c.findIndex(o=>o.id===C);if(n>=0){g(Math.floor(n/f)),d(n%f);return}}let l=w?c.findIndex(n=>n.id===w):c.findIndex(n=>n.isActive);l>=0?(g(Math.floor(l/f)),d(l%f),t.preserveSelectionById&&h(c[l].id)):t.preserveSelectionById&&(g(0),d(0),h(c[0]?.id??null))},[c,w,t.preserveSelectionById,C]),(0,u.useEffect)(()=>{if(!t.onSearch)return;let l=setTimeout(()=>t.onSearch(s),t.searchDebounceMs??250);return()=>clearTimeout(l)},[s,t.onSearch,t.searchDebounceMs]);let m=t.onSearch?c:K(c,s),M=S*f,p=Math.min(M+f,m.length),D=Math.ceil(m.length/f),O=p-M,v=m.slice(M,p);return X((l,n)=>{if(L){n.escape&&E();return}if(n.escape){s?(A(""),d(0),g(0)):E();return}if(n.tab&&y){y();return}if(n.upArrow){if(x>0){let o=x-1;d(o),t.preserveSelectionById&&h(v[o]?.id??null)}else if(S>0){let o=S-1,b=f-1;g(o),d(b),t.preserveSelectionById&&h(m[o*f+b]?.id??null)}return}if(n.downArrow){if(x<O-1){let o=x+1;d(o),t.preserveSelectionById&&h(v[o]?.id??null)}else if(S<D-1){let o=S+1,b=0;g(o),d(b),t.preserveSelectionById&&h(m[o*f+b]?.id??null)}return}if(n.return&&v[x]){H(v[x]);return}if(n.backspace||n.delete){A(o=>o.slice(0,-1)),d(0),g(0);return}l&&!n.ctrl&&!n.meta&&(A(o=>o+l),d(0),g(0))},{isActive:!B}),B?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:r.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(i,{color:r.orange,bold:!0,children:I}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(i,{color:r.secondary,children:F??`Loading ${T}\u2026`})})]}):L?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:r.red,paddingX:2,paddingY:1,children:[(0,e.jsx)(i,{color:r.red,bold:!0,children:I}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(i,{color:r.red,children:L})}),(0,e.jsx)(R,{bindings:[]})]}):(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:r.orange,paddingX:2,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(i,{color:r.orange,bold:!0,children:I}),(0,e.jsxs)(i,{color:r.dim,children:[" (",m.length,!t.onSearch&&s?`/${c.length}`:""," ",T,t.loadingMore?" \xB7 loading more":"",")"]})]}),(0,e.jsxs)(a,{marginTop:1,children:[(0,e.jsx)(i,{color:r.secondary,children:s?"filter: ":""}),s?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(i,{children:s}),(0,e.jsx)(i,{inverse:!0,children:" "})]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(i,{color:r.dim,children:["Search ",T,"\u2026"]}),(0,e.jsx)(i,{inverse:!0,children:" "})]})]}),(0,e.jsx)(a,{flexDirection:"column",marginTop:1,children:t.searching?(0,e.jsxs)(i,{color:r.secondary,children:["Searching ",T,"\u2026"]}):m.length===0?(0,e.jsxs)(i,{color:r.dim,children:["No ",T,' match "',s,'"']}):v.map((l,n)=>{let o=n===x,b=o?"\u276F ":" ",$=l.isActive?r.green:o?r.orange:void 0;return(0,e.jsxs)(i,{color:$,children:[b,l.label,l.isActive?" \u25CF selected":""]},l.id)})}),!t.searching&&D>1&&(0,e.jsx)(a,{marginTop:1,children:(0,e.jsxs)(i,{color:r.dim,children:["Page ",S+1,"/",D]})}),t.footer&&(0,e.jsx)(a,{marginTop:1,flexDirection:"column",children:t.footer}),(0,e.jsx)(R,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"type",label:"to search"},{keys:"\u21B5",label:"select"},...y&&N?[{keys:"tab",label:N}]:[]],escBackLabel:s?"clear":"back to chat"})]})}export{J as a};
2
+ import{a as R}from"./chunk-AV5SUGRY.js";import{x as r}from"./chunk-E4OYR32M.js";import{a as Y}from"./chunk-HCBYKLMW.js";import{a,b as i,i as X}from"./chunk-C44QQJR4.js";import{a as G}from"./chunk-6YGTRKDT.js";import{e as P}from"./chunk-UR6MHSHU.js";var u=P(G(),1);var e=P(Y(),1),f=5;function K(t,I){if(!I)return t;let c=I.toLowerCase();return t.filter(B=>B.label.toLowerCase().includes(c))}function J(t){let{title:I,items:c,loading:B=!1,loadingText:F,error:L=null,itemNoun:T="items",onSelect:H,onCancel:E,defaultActiveId:w,onTab:y,extraHint:N}=t,[x,d]=(0,u.useState)(0),[S,g]=(0,u.useState)(0),[s,A]=(0,u.useState)(""),[C,h]=(0,u.useState)(null);(0,u.useEffect)(()=>{if(c.length===0)return;if(t.preserveSelectionById&&C!==null){let n=c.findIndex(o=>o.id===C);if(n>=0){g(Math.floor(n/f)),d(n%f);return}}let l=w?c.findIndex(n=>n.id===w):c.findIndex(n=>n.isActive);l>=0?(g(Math.floor(l/f)),d(l%f),t.preserveSelectionById&&h(c[l].id)):t.preserveSelectionById&&(g(0),d(0),h(c[0]?.id??null))},[c,w,t.preserveSelectionById,C]),(0,u.useEffect)(()=>{if(!t.onSearch)return;let l=setTimeout(()=>t.onSearch(s),t.searchDebounceMs??250);return()=>clearTimeout(l)},[s,t.onSearch,t.searchDebounceMs]);let m=t.onSearch?c:K(c,s),M=S*f,p=Math.min(M+f,m.length),D=Math.ceil(m.length/f),O=p-M,v=m.slice(M,p);return X((l,n)=>{if(L){n.escape&&E();return}if(n.escape){s?(A(""),d(0),g(0)):E();return}if(n.tab&&y){y();return}if(n.upArrow){if(x>0){let o=x-1;d(o),t.preserveSelectionById&&h(v[o]?.id??null)}else if(S>0){let o=S-1,b=f-1;g(o),d(b),t.preserveSelectionById&&h(m[o*f+b]?.id??null)}return}if(n.downArrow){if(x<O-1){let o=x+1;d(o),t.preserveSelectionById&&h(v[o]?.id??null)}else if(S<D-1){let o=S+1,b=0;g(o),d(b),t.preserveSelectionById&&h(m[o*f+b]?.id??null)}return}if(n.return&&v[x]){H(v[x]);return}if(n.backspace||n.delete){A(o=>o.slice(0,-1)),d(0),g(0);return}l&&!n.ctrl&&!n.meta&&(A(o=>o+l),d(0),g(0))},{isActive:!B}),B?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:r.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(i,{color:r.orange,bold:!0,children:I}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(i,{color:r.secondary,children:F??`Loading ${T}\u2026`})})]}):L?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:r.red,paddingX:2,paddingY:1,children:[(0,e.jsx)(i,{color:r.red,bold:!0,children:I}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(i,{color:r.red,children:L})}),(0,e.jsx)(R,{bindings:[]})]}):(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:r.orange,paddingX:2,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(i,{color:r.orange,bold:!0,children:I}),(0,e.jsxs)(i,{color:r.dim,children:[" (",m.length,!t.onSearch&&s?`/${c.length}`:""," ",T,t.loadingMore?" \xB7 loading more":"",")"]})]}),(0,e.jsxs)(a,{marginTop:1,children:[(0,e.jsx)(i,{color:r.secondary,children:s?"filter: ":""}),s?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(i,{children:s}),(0,e.jsx)(i,{inverse:!0,children:" "})]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(i,{color:r.dim,children:["Search ",T,"\u2026"]}),(0,e.jsx)(i,{inverse:!0,children:" "})]})]}),(0,e.jsx)(a,{flexDirection:"column",marginTop:1,children:t.searching?(0,e.jsxs)(i,{color:r.secondary,children:["Searching ",T,"\u2026"]}):m.length===0?(0,e.jsxs)(i,{color:r.dim,children:["No ",T,' match "',s,'"']}):v.map((l,n)=>{let o=n===x,b=o?"\u276F ":" ",$=l.isActive?r.green:o?r.orange:void 0;return(0,e.jsxs)(i,{color:$,children:[b,l.label,l.isActive?" \u25CF selected":""]},l.id)})}),!t.searching&&D>1&&(0,e.jsx)(a,{marginTop:1,children:(0,e.jsxs)(i,{color:r.dim,children:["Page ",S+1,"/",D]})}),t.footer&&(0,e.jsx)(a,{marginTop:1,flexDirection:"column",children:t.footer}),(0,e.jsx)(R,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"type",label:"to search"},{keys:"\u21B5",label:"select"},...y&&N?[{keys:"tab",label:N}]:[]],escBackLabel:s?"clear":"back to chat"})]})}export{J as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{existsSync as l}from"fs";import{dirname as f,resolve as i}from"path";import{fileURLToPath as d}from"url";var g=f(d(import.meta.url));function p(){return[i(g,".."),i(g,"../../..")]}function A(o){return{"darwin-arm64":"kane-cli-darwin-arm64","darwin-x64":"kane-cli-darwin-x64","linux-x64":"kane-cli-linux-x64","linux-arm64":"kane-cli-linux-arm64","win32-x64":"kane-cli-win-x64"}[o]??null}function h(){let o=A(`${process.platform}-${process.arch}`),n=process.platform==="win32"?"assurance-agent.exe":"assurance-agent";for(let r of p()){for(let s of o?["@testmuai","@lambdatestincprivate"]:[]){let e=i(r,"node_modules",s,o,"bin",n);if(l(e))return{cmd:e,args:[]}}let a=i(r,"../assurance-agent/dist",n);if(l(a))return{cmd:a,args:[]};let t=i(r,"../assurance-agent/main.py");if(l(t)){let s=i(r,"../assurance-agent/.venv/bin/python");return{cmd:l(s)?s:"python3",args:[t]}}}return null}function w(o,n={}){return{...process.env,...n,TESTMUAI_SOURCE:"kane-cli",TESTMUAI_SESSION_ID:o,ASSURANCE_LOG_LEVEL:process.env.ASSURANCE_LOG_LEVEL??"info"}}async function x(){if(process.env.TESTMUAI_API_KEY||process.env.TESTMUAI_BASIC_AUTH)return{};try{let{CredentialsManager:o}=await import("./credentials-NQNJR4E4.js"),n=process.env.TESTMUAI_ENV==="stage"?"stage":"prod",r=new o,a=r.getActiveProfile()??"default",t={TESTMUAI_ENV:n},s=r.loadBasicAuth(a,n);if(s)return t.TESTMUAI_BASIC_AUTH=Buffer.from(`${s.username}:${s.access_key}`,"utf8").toString("base64"),t;let e=r.loadCredentials(a,n);if(e){try{let{refreshOAuthToken:u}=await import("./token-refresh-DH2L2IPP.js");await u({creds:r,profile:a,env:n,credentials:e})}catch{}let c=r.loadCredentials(a,n)??e;if(typeof c.access_token=="string"){let u=await E(n,c.access_token);return u?(t.TESTMUAI_BASIC_AUTH=u,t):(t.TESTMUAI_API_KEY=c.access_token,t)}}return{}}catch{return{}}}var _=8e3;function m(){return process.stderr.write("warn: session auth may expire during long runs \u2014 if that happens, run `kane-cli login` and retry\n"),null}async function E(o,n){if(process.env.TESTMUAI_BASE_URL)return null;try{let[{getEnvironment:r},{ControllerClient:a}]=await Promise.all([import("./config-KD62VH3R.js"),import("./controller-client-RD2YEMAH.js")]),t=new a(r(o).controllerBaseUrl,n),s;try{let e=await Promise.race([t.getTmsCredentials().catch(()=>null),new Promise(c=>{s=setTimeout(()=>c(null),_)})]);return typeof e?.username!="string"||!e.username||typeof e.access_key!="string"||!e.access_key?m():Buffer.from(`${e.username}:${e.access_key}`,"utf8").toString("base64")}finally{clearTimeout(s)}}catch{return m()}}export{A as a,h as b,w as c,x as d};
2
+ import{existsSync as l}from"fs";import{dirname as f,resolve as i}from"path";import{fileURLToPath as d}from"url";var g=f(d(import.meta.url));function p(){return[i(g,".."),i(g,"../../..")]}function A(o){return{"darwin-arm64":"kane-cli-darwin-arm64","darwin-x64":"kane-cli-darwin-x64","linux-x64":"kane-cli-linux-x64","linux-arm64":"kane-cli-linux-arm64","win32-x64":"kane-cli-win-x64"}[o]??null}function h(){let o=A(`${process.platform}-${process.arch}`),n=process.platform==="win32"?"assurance-agent.exe":"assurance-agent";for(let r of p()){for(let s of o?["@testmuai","@lambdatestincprivate"]:[]){let e=i(r,"node_modules",s,o,"bin",n);if(l(e))return{cmd:e,args:[]}}let a=i(r,"../assurance-agent/dist",n);if(l(a))return{cmd:a,args:[]};let t=i(r,"../assurance-agent/main.py");if(l(t)){let s=i(r,"../assurance-agent/.venv/bin/python");return{cmd:l(s)?s:"python3",args:[t]}}}return null}function w(o,n={}){return{...process.env,...n,TESTMUAI_SOURCE:"kane-cli",TESTMUAI_SESSION_ID:o,ASSURANCE_LOG_LEVEL:process.env.ASSURANCE_LOG_LEVEL??"info"}}async function x(){if(process.env.TESTMUAI_API_KEY||process.env.TESTMUAI_BASIC_AUTH)return{};try{let{CredentialsManager:o}=await import("./credentials-XCP6DJZZ.js"),n=process.env.TESTMUAI_ENV==="stage"?"stage":"prod",r=new o,a=r.getActiveProfile()??"default",t={TESTMUAI_ENV:n},s=r.loadBasicAuth(a,n);if(s)return t.TESTMUAI_BASIC_AUTH=Buffer.from(`${s.username}:${s.access_key}`,"utf8").toString("base64"),t;let e=r.loadCredentials(a,n);if(e){try{let{refreshOAuthToken:u}=await import("./token-refresh-GGLARJV4.js");await u({creds:r,profile:a,env:n,credentials:e})}catch{}let c=r.loadCredentials(a,n)??e;if(typeof c.access_token=="string"){let u=await E(n,c.access_token);return u?(t.TESTMUAI_BASIC_AUTH=u,t):(t.TESTMUAI_API_KEY=c.access_token,t)}}return{}}catch{return{}}}var _=8e3;function m(){return process.stderr.write("warn: session auth may expire during long runs \u2014 if that happens, run `kane-cli login` and retry\n"),null}async function E(o,n){if(process.env.TESTMUAI_BASE_URL)return null;try{let[{getEnvironment:r},{ControllerClient:a}]=await Promise.all([import("./config-5OOP2BO3.js"),import("./controller-client-RD2YEMAH.js")]),t=new a(r(o).controllerBaseUrl,n),s;try{let e=await Promise.race([t.getTmsCredentials().catch(()=>null),new Promise(c=>{s=setTimeout(()=>c(null),_)})]);return typeof e?.username!="string"||!e.username||typeof e.access_key!="string"||!e.access_key?m():Buffer.from(`${e.username}:${e.access_key}`,"utf8").toString("base64")}finally{clearTimeout(s)}}catch{return m()}}export{A as a,h as b,w as c,x as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a}from"./chunk-YIOWO6WS.js";import"./chunk-QIE62H3J.js";import"./chunk-UR6MHSHU.js";export{a as getEnvironment};
2
+ import{a}from"./chunk-RLG5NUTE.js";import"./chunk-E4OYR32M.js";import"./chunk-UR6MHSHU.js";export{a as getEnvironment};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a}from"./chunk-L4AUCQVO.js";import"./chunk-QIE62H3J.js";import"./chunk-UR6MHSHU.js";export{a as CredentialsManager};
2
+ import{a}from"./chunk-TZZYRDCF.js";import"./chunk-E4OYR32M.js";import"./chunk-UR6MHSHU.js";export{a as CredentialsManager};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{$ as fa,A as J,B as K,C as L,D as M,E as N,F as O,G as P,H as Q,L as R,M as S,N as T,O as U,P as V,Q as W,R as X,S as Y,T as Z,U as _,V as $,W as aa,X as ba,Y as ca,Z as da,_ as ea,a,aa as ga,b,ba as ha,c,ca as ia,d,e,f,g,h,i,j,k as t,l as u,m as v,n as w,o as x,p as y,q as z,r as A,s as B,t as C,u as D,v as E,w as F,x as G,y as H,z as I}from"./chunk-YSK535OI.js";import{a as n,b as o,c as p,e as q,f as r,g as s}from"./chunk-FYOCF7DY.js";import"./chunk-RGEAEAZB.js";import"./chunk-BC7UVJJB.js";import"./chunk-KHDUQ33H.js";import{a as k,b as l,c as m}from"./chunk-NFOBDHZK.js";import"./chunk-L5LI2JF4.js";import"./chunk-D5T4ARTB.js";import"./chunk-AE6SS34N.js";import"./chunk-GIRXJOJI.js";import"./chunk-B2PZAB7J.js";import"./chunk-IACKIGPX.js";import"./chunk-YIOWO6WS.js";import"./chunk-QIE62H3J.js";import"./chunk-UR6MHSHU.js";export{P as EvidenceSession,C as appendExecutionPointer,M as assembleExecutionEnv,i as buildEnvironment,j as buildEvidenceRunConfig,g as buildExternalId,z as buildLogsMetaYaml,y as buildResultYaml,t as buildRunYaml,O as createCdpBrowserCapture,u as createRunningPack,v as createRunningPackRoot,H as declareLogsFromDir,J as diagnostics,x as discardPack,ba as ensureAuteurExecution,N as fetchCdpBrowserString,L as finalizeEvidencePack,U as finalizeInlineEvidence,K as finalizeMemberTestLogs,da as flattenAuteurLeafIds,ca as flattenAuteurLeaves,T as inlineEvidenceBlock,q as listPacks,p as newExecutionId,h as normalizeOs,S as noteInlineSpawn,$ as offerEvidenceView,o as packPath,I as packTestLogsDir,V as parseRange,D as readExecutionPointers,ia as readPackLeafIds,ha as readPackLeaves,s as recoverStore,fa as remapReplayActionIds,r as resolvePack,ga as resolveReplayResultSteps,F as rollupTestStatus,aa as runEvidenceMerge,_ as runEvidenceServe,E as runEvidenceValidate,Q as runStartupRecovery,l as sealPack,w as sealPackById,Z as serveHint,d as shortHash,c as slugify,W as startEvidenceLocalServer,R as startInlineEvidence,n as storeDir,m as sweepStore,ea as synthesizeSkippedTail,f as testIdForInline,e as testIdForTestmd,k as validatePack,a as verdictFromResultCode,X as viewerBaseFor,Y as viewerUrlFor,b as worstOf,G as worstResultCode,B as writeLogsMeta,A as writeResult};
2
+ import{$ as fa,A as J,B as K,C as L,D as M,E as N,F as O,G as P,H as Q,L as R,M as S,N as T,O as U,P as V,Q as W,R as X,S as Y,T as Z,U as _,V as $,W as aa,X as ba,Y as ca,Z as da,_ as ea,a,aa as ga,b,ba as ha,c,ca as ia,d,e,f,g,h,i,j,k as t,l as u,m as v,n as w,o as x,p as y,q as z,r as A,s as B,t as C,u as D,v as E,w as F,x as G,y as H,z as I}from"./chunk-OE7TVGNB.js";import{a as n,b as o,c as p,e as q,f as r,g as s}from"./chunk-FYOCF7DY.js";import"./chunk-RGEAEAZB.js";import"./chunk-BC7UVJJB.js";import"./chunk-KHDUQ33H.js";import{a as k,b as l,c as m}from"./chunk-NFOBDHZK.js";import"./chunk-L5LI2JF4.js";import"./chunk-D5T4ARTB.js";import"./chunk-AE6SS34N.js";import"./chunk-GIRXJOJI.js";import"./chunk-B2PZAB7J.js";import"./chunk-IACKIGPX.js";import"./chunk-RLG5NUTE.js";import"./chunk-E4OYR32M.js";import"./chunk-UR6MHSHU.js";export{P as EvidenceSession,C as appendExecutionPointer,M as assembleExecutionEnv,i as buildEnvironment,j as buildEvidenceRunConfig,g as buildExternalId,z as buildLogsMetaYaml,y as buildResultYaml,t as buildRunYaml,O as createCdpBrowserCapture,u as createRunningPack,v as createRunningPackRoot,H as declareLogsFromDir,J as diagnostics,x as discardPack,ba as ensureAuteurExecution,N as fetchCdpBrowserString,L as finalizeEvidencePack,U as finalizeInlineEvidence,K as finalizeMemberTestLogs,da as flattenAuteurLeafIds,ca as flattenAuteurLeaves,T as inlineEvidenceBlock,q as listPacks,p as newExecutionId,h as normalizeOs,S as noteInlineSpawn,$ as offerEvidenceView,o as packPath,I as packTestLogsDir,V as parseRange,D as readExecutionPointers,ia as readPackLeafIds,ha as readPackLeaves,s as recoverStore,fa as remapReplayActionIds,r as resolvePack,ga as resolveReplayResultSteps,F as rollupTestStatus,aa as runEvidenceMerge,_ as runEvidenceServe,E as runEvidenceValidate,Q as runStartupRecovery,l as sealPack,w as sealPackById,Z as serveHint,d as shortHash,c as slugify,W as startEvidenceLocalServer,R as startInlineEvidence,n as storeDir,m as sweepStore,ea as synthesizeSkippedTail,f as testIdForInline,e as testIdForTestmd,k as validatePack,a as verdictFromResultCode,X as viewerBaseFor,Y as viewerUrlFor,b as worstOf,G as worstResultCode,B as writeLogsMeta,A as writeResult};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a,b,c,d,e}from"./chunk-X4QL2DAD.js";import"./chunk-NNZV5RCE.js";import"./chunk-AD46OCZ4.js";import"./chunk-JFAFKHDX.js";import"./chunk-QPZRHAYK.js";import"./chunk-ZKYYZ5NO.js";import"./chunk-BC7UVJJB.js";import"./chunk-KHDUQ33H.js";import"./chunk-D5T4ARTB.js";import"./chunk-AE6SS34N.js";import"./chunk-GIRXJOJI.js";import"./chunk-B2PZAB7J.js";import"./chunk-IACKIGPX.js";import"./chunk-UR6MHSHU.js";export{e as evolveCommand,b as evolveOneUc,d as liveRunDesignForUc,a as resolveParentUc,c as runEvolveCommand};
2
+ import{a,b,c,d,e}from"./chunk-6RQAUK5F.js";import"./chunk-NNZV5RCE.js";import"./chunk-AD46OCZ4.js";import"./chunk-JFAFKHDX.js";import"./chunk-QPZRHAYK.js";import"./chunk-ZKYYZ5NO.js";import"./chunk-BC7UVJJB.js";import"./chunk-KHDUQ33H.js";import"./chunk-D5T4ARTB.js";import"./chunk-AE6SS34N.js";import"./chunk-GIRXJOJI.js";import"./chunk-B2PZAB7J.js";import"./chunk-IACKIGPX.js";import"./chunk-UR6MHSHU.js";export{e as evolveCommand,b as evolveOneUc,d as liveRunDesignForUc,a as resolveParentUc,c as runEvolveCommand};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as D,c as h}from"./chunk-HW7Z5S2M.js";import"./chunk-WM5QHLAP.js";import"./chunk-I2S6KNZW.js";import"./chunk-FXPPQL4D.js";import"./chunk-DM2GL24Z.js";import"./chunk-6PS65QFF.js";import"./chunk-JFAFKHDX.js";import"./chunk-FTD3B7QA.js";import"./chunk-QPZRHAYK.js";import"./chunk-VJUIW2ES.js";import{c as A}from"./chunk-YKTYVJBN.js";import"./chunk-Z56AWGVY.js";import"./chunk-427OQS2N.js";import{a as y}from"./chunk-HUD7SPUF.js";import{d as C}from"./chunk-NEZ4G7XR.js";import{c as E}from"./chunk-ZKYYZ5NO.js";import{a as P}from"./chunk-BC7UVJJB.js";import"./chunk-KHDUQ33H.js";import"./chunk-D5T4ARTB.js";import"./chunk-AE6SS34N.js";import"./chunk-GIRXJOJI.js";import"./chunk-B2PZAB7J.js";import"./chunk-IACKIGPX.js";import"./chunk-QIE62H3J.js";import"./chunk-UR6MHSHU.js";async function j(n){let[{render:o},e,{QuestionBatchPrompt:i}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./ui-JEJGTURD.js")]),c=e.default??e;return new Promise(t=>{let p=o(c.createElement(i,{questions:n,onSubmit:a=>{p.unmount(),t(a)}}))})}async function F(n,o){let[{render:e},i,{ReviewChecklist:c}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./ui-JEJGTURD.js")]),t=i.default??i;return new Promise(p=>{let a=e(t.createElement(c,{items:n.map(u=>{let s=o.get(u.temp_ref);return{uc:u,dedupWith:s&&!s.archived?s.cid:void 0,archivedMatch:s?.archived?{cid:s.cid,reason:s.reason}:void 0}}),onSubmit:u=>{a.unmount(),p(u)}}))})}async function G(n){let{createInterface:o}=await import("readline/promises"),e=o({input:process.stdin,output:process.stdout});try{let i=await e.question(`${n} [y/N] `);return/^y(es)?$/i.test(i.trim())}finally{e.close()}}async function O(n){let o=await C(),e=P(process.cwd()),i=await A(o);if(!i.ok)return process.stderr.write((i.message??"error: turn-endpoint preflight failed")+`
2
+ import{d as D,e as h}from"./chunk-TY5LWU6I.js";import"./chunk-SGU72YLH.js";import"./chunk-I2S6KNZW.js";import"./chunk-FXPPQL4D.js";import"./chunk-RE3BZVGE.js";import"./chunk-6PS65QFF.js";import"./chunk-JFAFKHDX.js";import"./chunk-FTD3B7QA.js";import"./chunk-QPZRHAYK.js";import"./chunk-VJUIW2ES.js";import{c as A}from"./chunk-YKTYVJBN.js";import"./chunk-Z56AWGVY.js";import"./chunk-427OQS2N.js";import{a as y}from"./chunk-2S4S2XJC.js";import{d as C}from"./chunk-YZSYXNMB.js";import{c as E}from"./chunk-ZKYYZ5NO.js";import{a as P}from"./chunk-BC7UVJJB.js";import"./chunk-KHDUQ33H.js";import"./chunk-D5T4ARTB.js";import"./chunk-AE6SS34N.js";import"./chunk-GIRXJOJI.js";import"./chunk-B2PZAB7J.js";import"./chunk-IACKIGPX.js";import"./chunk-E4OYR32M.js";import"./chunk-UR6MHSHU.js";async function j(n){let[{render:o},e,{QuestionBatchPrompt:i}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./ui-JEJGTURD.js")]),c=e.default??e;return new Promise(t=>{let p=o(c.createElement(i,{questions:n,onSubmit:a=>{p.unmount(),t(a)}}))})}async function F(n,o){let[{render:e},i,{ReviewChecklist:c}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./ui-JEJGTURD.js")]),t=i.default??i;return new Promise(p=>{let a=e(t.createElement(c,{items:n.map(u=>{let s=o.get(u.temp_ref);return{uc:u,dedupWith:s&&!s.archived?s.cid:void 0,archivedMatch:s?.archived?{cid:s.cid,reason:s.reason}:void 0}}),onSubmit:u=>{a.unmount(),p(u)}}))})}async function G(n){let{createInterface:o}=await import("readline/promises"),e=o({input:process.stdin,output:process.stdout});try{let i=await e.question(`${n} [y/N] `);return/^y(es)?$/i.test(i.trim())}finally{e.close()}}async function O(n){let o=await C(),e=P(process.cwd()),i=await A(o);if(!i.ok)return process.stderr.write((i.message??"error: turn-endpoint preflight failed")+`
3
3
  `),2;let c=async()=>i;if(n.plan)return h(n,{contextDir:e,agent:y,preflightTurn:c,ask:j,review:F,confirmStale:G,out:l=>process.stdout.write(l+`
4
4
  `),progress:l=>process.stderr.write(l+`
5
- `),isTTY:E(),auth:o});let[{render:t},p,{ScrollbackProvider:a},{ChatSurface:u},{ScrollbackTap:s},{makeChatController:r},{setInkExit:w},x]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./scrollback-JLPJR25X.js"),import("./ChatSurface-HGP5EHZM.js"),import("./ScrollbackTap-Q3IOKNMS.js"),import("./chat-controller-VKGECDTU.js"),import("./exit-manager-VCSIUYBR.js"),Promise.all([import("./chat-committer-GHDZY5XF.js"),import("./descriptor-SL5A7RQE.js"),import("./explain-JIXUWEFJ.js"),import("./readmodel-MPTENJ2R.js")])]),[{commitChatTurn:I},{topologyDescriptor:M},{explain:V},{openGraph:k}]=x,v=p.default??p,m=r({commitChatTurn:I,descriptor:M(),contextDir:e,refreshGraph:()=>k(e),graph:k(e),explain:V,by:{kind:"human",id:"owner"},dedupFlags:l=>D(l,k(e))}),T={current:null},S=0,b=null,f=!1,N=()=>{if(S+=1,S>=2){try{g.unmount()}catch{}process.exit(130)}m.requestPause(),b=setTimeout(()=>{f||(f=!0,(async()=>{m.ledger({kind:"interrupted",detail:"the agent did not confirm the pause within 5s"}),await T.current?.flush();try{g.unmount()}catch{}process.exit(130)})())},5e3)},g=t(v.createElement(a,null,v.createElement(s,{into:T}),v.createElement(u,{controller:m,verb:"extract",onCtrlC:N})),{exitOnCtrlC:!1});w(()=>g.unmount()),m.ledger({kind:"banner",text:"kane-cli context \xB7 extract \xB7 interactive"});try{let l=h(n,{contextDir:e,agent:y,preflightTurn:c,ask:d=>m.ask(d),review:async d=>new Map(d.map(R=>[R.temp_ref,{resolution:"skipped"}])),confirmStale:async()=>!0,out:d=>m.note(d),progress:()=>{},isTTY:E(),auth:o,chat:m});return l.finally(()=>{f=!0}),await l}finally{f=!0,b&&clearTimeout(b),await T.current?.flush();try{g.unmount()}catch{}}}async function U(n){let o=await C(),{makeHeadlessIO:e,resolveEncoding:i,guardedChannels:c}=await import("./headless-io-GXHKDPHB.js"),t=e(i(n.mode),"extract"),{makeInterruptGuard:p}=await import("./interrupt-guard-UREUWNRL.js"),a=p(y,r=>t.out(r)),s=c(t,()=>a.interrupted(),/^error: (agent failed|repair run failed|agent ended)/);try{let r=await h(n,{contextDir:P(process.cwd()),agent:a.agent,preflightTurn:()=>A(o),ask:async()=>[],review:async w=>new Map(w.map(x=>[x.temp_ref,{resolution:"skipped"}])),confirmStale:async()=>!1,out:s.out,emit:s.emit,progress:t.progress,isTTY:!1,auth:o});return a.interrupted()&&r!==3?(t.out("interrupted \u2014 no session saved"),t.done(130)):t.done(r)}catch(r){return t.event({type:"error",message:`error: extract failed: ${r instanceof Error?r.message:String(r)}`}),t.out(`error: extract failed: ${r instanceof Error?r.message:String(r)}`),t.out("hint: per-run trace logs live under .context/logs/ (extract-*.log)"),t.done(1)}finally{a.dispose()}}export{U as bindExtractHeadless,O as bindExtractInteractive};
5
+ `),isTTY:E(),auth:o});let[{render:t},p,{ScrollbackProvider:a},{ChatSurface:u},{ScrollbackTap:s},{makeChatController:r},{setInkExit:w},x]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./scrollback-JLPJR25X.js"),import("./ChatSurface-J777M5WC.js"),import("./ScrollbackTap-Q3IOKNMS.js"),import("./chat-controller-QXFAB2DK.js"),import("./exit-manager-VCSIUYBR.js"),Promise.all([import("./chat-committer-GHDZY5XF.js"),import("./descriptor-SL5A7RQE.js"),import("./explain-JIXUWEFJ.js"),import("./readmodel-MPTENJ2R.js")])]),[{commitChatTurn:I},{topologyDescriptor:M},{explain:V},{openGraph:k}]=x,v=p.default??p,m=r({commitChatTurn:I,descriptor:M(),contextDir:e,refreshGraph:()=>k(e),graph:k(e),explain:V,by:{kind:"human",id:"owner"},dedupFlags:l=>D(l,k(e))}),T={current:null},S=0,b=null,f=!1,N=()=>{if(S+=1,S>=2){try{g.unmount()}catch{}process.exit(130)}m.requestPause(),b=setTimeout(()=>{f||(f=!0,(async()=>{m.ledger({kind:"interrupted",detail:"the agent did not confirm the pause within 5s"}),await T.current?.flush();try{g.unmount()}catch{}process.exit(130)})())},5e3)},g=t(v.createElement(a,null,v.createElement(s,{into:T}),v.createElement(u,{controller:m,verb:"extract",onCtrlC:N})),{exitOnCtrlC:!1});w(()=>g.unmount()),m.ledger({kind:"banner",text:"kane-cli context \xB7 extract \xB7 interactive"});try{let l=h(n,{contextDir:e,agent:y,preflightTurn:c,ask:d=>m.ask(d),review:async d=>new Map(d.map(R=>[R.temp_ref,{resolution:"skipped"}])),confirmStale:async()=>!0,out:d=>m.note(d),progress:()=>{},isTTY:E(),auth:o,chat:m});return l.finally(()=>{f=!0}),await l}finally{f=!0,b&&clearTimeout(b),await T.current?.flush();try{g.unmount()}catch{}}}async function U(n){let o=await C(),{makeHeadlessIO:e,resolveEncoding:i,guardedChannels:c}=await import("./headless-io-GXHKDPHB.js"),t=e(i(n.mode),"extract"),{makeInterruptGuard:p}=await import("./interrupt-guard-UREUWNRL.js"),a=p(y,r=>t.out(r)),s=c(t,()=>a.interrupted(),/^error: (agent failed|repair run failed|agent ended)/);try{let r=await h(n,{contextDir:P(process.cwd()),agent:a.agent,preflightTurn:()=>A(o),ask:async()=>[],review:async w=>new Map(w.map(x=>[x.temp_ref,{resolution:"skipped"}])),confirmStale:async()=>!1,out:s.out,emit:s.emit,progress:t.progress,isTTY:!1,auth:o});return a.interrupted()&&r!==3?(t.out("interrupted \u2014 no session saved"),t.done(130)):t.done(r)}catch(r){return t.event({type:"error",message:`error: extract failed: ${r instanceof Error?r.message:String(r)}`}),t.out(`error: extract failed: ${r instanceof Error?r.message:String(r)}`),t.out("hint: per-run trace logs live under .context/logs/ (extract-*.log)"),t.done(1)}finally{a.dispose()}}export{U as bindExtractHeadless,O as bindExtractInteractive};
@@ -3,4 +3,4 @@ import{a as s}from"./chunk-BC7UVJJB.js";import"./chunk-UR6MHSHU.js";import{exist
3
3
  `),2;let n=async(r,t)=>{if(process.stderr.write(r+`
4
4
  `),e.mode!=="agent")return 2;let{makeHeadlessIO:a,agentRefusal:c}=await import("./headless-io-GXHKDPHB.js");return c(a("ndjson","extract"),r,t)};if(e.apply)return n("extract: --apply is not implemented yet \u2014 coming with the plan\u2192apply workflow (run without --apply, or use --plan to preview)");{let{validateResumeMessage:r}=await import("./headless-io-GXHKDPHB.js"),t=r(e,"extract");if(t)return n(t)}if(!d(s(process.cwd())))return n("error: no context store here (run `kane-cli context ingest <files>` first)","NO_STORE");if(!e.mode&&!process.stdin.isTTY)return process.stderr.write(`extract: no TTY \u2014 pass an explicit --mode agent|ci|override to run headless
5
5
  `),2;let i=e.mode??"interactive";if(i==="interactive"){if(!process.stdin.isTTY||!process.stdout.isTTY)return process.stderr.write(`extract: --mode interactive needs a TTY on stdin and stdout (use --mode agent|ci|override headless)
6
- `),2;let{bindExtractInteractive:r}=await import("./extract-bind-6UMILP4U.js");return r(e)}let{bindExtractHeadless:o}=await import("./extract-bind-6UMILP4U.js");return o({...e,mode:i})}export{l as extractCommand};
6
+ `),2;let{bindExtractInteractive:r}=await import("./extract-bind-ZDAXRQUS.js");return r(e)}let{bindExtractHeadless:o}=await import("./extract-bind-ZDAXRQUS.js");return o({...e,mode:i})}export{l as extractCommand};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as T,f as P,g as $,h as G,j as N,k as M,l as B,m as I,n as L,o as U,p as F,r as z,s as C,t as _,u as O,v as K}from"./chunk-XN7PPLFS.js";import{b as k}from"./chunk-OZODSY6H.js";import{d as J}from"./chunk-B2CIHKXG.js";import{c as E}from"./chunk-2U5DZUC7.js";import"./chunk-IDDVO4UV.js";import{a as q}from"./chunk-EK2B2LZK.js";import"./chunk-35SRW4KA.js";import"./chunk-4G4HPMR2.js";import"./chunk-FPFOW6BS.js";import"./chunk-WAOCHXJ5.js";import"./chunk-L5LI2JF4.js";import{e as x,f as A}from"./chunk-M5JQXOCE.js";import{h as H}from"./chunk-HR7AGYV2.js";import"./chunk-2WVKOZ6W.js";import"./chunk-NLCCBXXV.js";import"./chunk-RZ4F3BHX.js";import{a as R}from"./chunk-YIOWO6WS.js";import"./chunk-VE3SUJMA.js";import{a as j}from"./chunk-L4AUCQVO.js";import"./chunk-QIE62H3J.js";import"./chunk-UR6MHSHU.js";import{join as se}from"path";async function V(t){let e=t.projectId,n=t.folderId,r=null;if(!e&&t.autoResolve){let l=await t.resolver.resolve();if(!l)throw new $("unauthorized; run `kane-cli login`");let u=await H({creds:t.autoResolve.creds,config:t.autoResolve.config,profile:t.autoResolve.profile,env:t.autoResolve.envName,tmsCreds:{username:l.username,access_key:l.access_key},isLocal:!1,log:t.log});u.status==="ok"&&(e=u.projectId,n=n??u.folderId,u.autoDefaulted&&(r={projectId:u.autoDefaulted.projectId,projectName:u.autoDefaulted.projectName,folderId:u.autoDefaulted.folderId,folderName:u.autoDefaulted.folderName}))}return{baseUrl:`${t.env.testGeneratorBaseUrl}/test-generator/api/v2`,tmsBaseUrl:t.env.tmsBaseUrl,authResolver:t.resolver,projectId:e,folderId:n,suiteName:t.suiteName,autoDefaulted:r,log:t.log}}function Z(t){return t.reduce((e,n)=>e+(n.test_cases?.length??0),0)}var y=class{constructor(e=n=>process.stdout.write(n)){this.write=e}emit(e){this.write(JSON.stringify(e)+`
2
+ import{a as T,f as P,g as $,h as G,j as N,k as M,l as B,m as I,n as L,o as U,p as F,r as z,s as C,t as _,u as O,v as K}from"./chunk-DEEBPSJN.js";import{b as k}from"./chunk-Y6LMHBLE.js";import{d as J}from"./chunk-TTSYHJLX.js";import{c as E}from"./chunk-7MV5UF6O.js";import"./chunk-Q4HLQOJI.js";import{a as q}from"./chunk-XBE7PGVY.js";import"./chunk-P46TIMGQ.js";import"./chunk-SL7AJ7JQ.js";import"./chunk-FPFOW6BS.js";import"./chunk-WAOCHXJ5.js";import"./chunk-L5LI2JF4.js";import{e as x,f as A}from"./chunk-M5JQXOCE.js";import{h as H}from"./chunk-CIW2KP4C.js";import"./chunk-2WVKOZ6W.js";import"./chunk-NLCCBXXV.js";import"./chunk-RZ4F3BHX.js";import{a as R}from"./chunk-RLG5NUTE.js";import"./chunk-VE3SUJMA.js";import{a as j}from"./chunk-TZZYRDCF.js";import"./chunk-E4OYR32M.js";import"./chunk-UR6MHSHU.js";import{join as se}from"path";async function V(t){let e=t.projectId,n=t.folderId,r=null;if(!e&&t.autoResolve){let l=await t.resolver.resolve();if(!l)throw new $("unauthorized; run `kane-cli login`");let u=await H({creds:t.autoResolve.creds,config:t.autoResolve.config,profile:t.autoResolve.profile,env:t.autoResolve.envName,tmsCreds:{username:l.username,access_key:l.access_key},isLocal:!1,log:t.log});u.status==="ok"&&(e=u.projectId,n=n??u.folderId,u.autoDefaulted&&(r={projectId:u.autoDefaulted.projectId,projectName:u.autoDefaulted.projectName,folderId:u.autoDefaulted.folderId,folderName:u.autoDefaulted.folderName}))}return{baseUrl:`${t.env.testGeneratorBaseUrl}/test-generator/api/v2`,tmsBaseUrl:t.env.tmsBaseUrl,authResolver:t.resolver,projectId:e,folderId:n,suiteName:t.suiteName,autoDefaulted:r,log:t.log}}function Z(t){return t.reduce((e,n)=>e+(n.test_cases?.length??0),0)}var y=class{constructor(e=n=>process.stdout.write(n)){this.write=e}emit(e){this.write(JSON.stringify(e)+`
3
3
  `)}onStart(e){this.emit({type:"generate_start",request_id:e.requestId,objective_chars:e.objectiveChars,scenario_limit:e.scenarioLimit,per_scenario_limit:e.perScenarioLimit,is_refine:e.isRefine})}onUpload(e){this.emit({type:"generate_upload",file:e.file,index:e.index,total:e.total,status:e.status})}onThinking(e){this.emit({type:"generate_thinking",took_ms:e.tookMs})}onProgress(e){this.emit({type:"generate_progress",pct:e})}onSnapshot(e){this.emit({type:"generate_snapshot",scenario_count:e.scenarios.length,case_count:Z(e.scenarios),scenarios:e.scenarios})}onClarification(e){this.emit({type:"generate_clarification",text:e})}onChat(e){this.emit({type:"generate_chat",text:e})}onError(e){this.emit({type:"error",message:e})}onSaveResult(e){this.emit({type:"generate_save_result",suite_dir:e.suiteDir,saved:e.saved,fell_back:e.fellBack,...e.warning?{warning:e.warning}:{}})}onDone(e){this.emit({type:"generate_done",request_id:e.requestId,status:e.status,scenario_count:e.scenarioCount,case_count:e.caseCount,refine_hint:e.refineHint,save_hint:e.saveHint,...e.suiteDir?{suite_dir:e.suiteDir}:{}})}onUpdateAvailable(e){this.emit({type:"update_available",current:e.current,latest:e.latest,severity:e.severity})}},S=class{constructor(e=n=>process.stdout.write(n)){this.write=e}onStart(e){let n=e.isRefine?"Refining":"Generating";this.write(`${n} (request ${e.requestId})\u2026
4
4
  `)}onUpload(e){e.status==="uploading"&&this.write(` uploading ${e.file} (${e.index}/${e.total})
5
5
  `)}onThinking(e){let n=e.tookMs?` (${Math.round(e.tookMs/1e3)}s)`:"";this.write(` thinking${n}
@@ -16,6 +16,6 @@ import{a as T,f as P,g as $,h as G,j as N,k as M,l as B,m as I,n as L,o as U,p a
16
16
  `),this.write(` Save: ${e.saveHint}
17
17
  `),e.suiteDir&&this.write(` Saved: ${e.suiteDir}
18
18
  `)}onUpdateAvailable(e){this.write(`(update available: ${e.current} \u2192 ${e.latest})
19
- `)}};import{createHash as ee}from"crypto";function te(t){return ee("sha1").update(JSON.stringify({t:t.title,p:t.preconditions,m:t.manual_steps})).digest("hex")}function re(t){let e=[];for(let n of t.scenarios)for(let r of n.test_cases??[])I(r)&&r.manual_steps!=null&&e.push(r);return e}async function ne(t,e,n){let r=new Array(t.length),l=0,u=Array.from({length:Math.min(e,t.length)},async()=>{for(;;){let d=l++;if(d>=t.length)return;try{r[d]={ok:!0,value:await n(t[d])}}catch{r[d]={ok:!1}}}});return await Promise.all(u),r}async function Y(t,e,n){let r=re(t),l=n.run??(async(c,s)=>{let m=await n.resolveAuth(),o=U({objective:c,model:n.model,sessionId:n.sessionId,auth:m});return F(o,n.spawnOpts,s)}),u=r.map(te),d=[...new Set(u)],g=new Map;d.forEach(c=>{g.set(c,r[u.indexOf(c)])});let p=d.map(c=>g.get(c)),v=await ne(p,n.concurrency??3,c=>l(L(c))),i=new Map;d.forEach((c,s)=>{let m=v[s];m.ok&&i.set(c,m.value)});let f=new Map;r.forEach((c,s)=>{f.set(c.id,i.get(u[s]))});let a=0;for(let c of t.scenarios)for(let s of c.test_cases??[])I(s)&&!f.get(s.id)&&a++;let w=c=>{let s=f.get(c.id);return s?N(s,c):M(c)};return{...await B(t,e,{suiteName:n.suiteName,redirectBareCwd:!1},w),fellBack:a}}function Pe(t,e){let n=!!t.agent||!!t.refine||!!t.save||!e,r=t.agent?"agent":"plain";return{headless:n,mode:r}}function $e(t){return t.refine&&t.save?{error:"use --refine or --save, not both"}:t.save?t.objective?{error:"--save takes no objective; use --refine to add to a request"}:t.req?{op:"save"}:{error:"--save requires --req <id>"}:t.refine?t.req?t.objective?t.out?{error:"--out is only valid with --save"}:{op:"refine"}:{error:"--refine needs a refinement objective"}:{error:"--refine requires --req <id>"}:t.req?{error:"--req requires --refine or --save"}:t.out?{error:"--out is only valid with --save"}:t.objective?{op:"new"}:{error:"provide an objective, or use --refine/--save with --req"}}function ie(){return se(process.cwd(),".testmuai","tests")}function Ge(t){if(typeof t!="string")return;let e=t.split(",").map(n=>n.trim()).filter(Boolean);return e.length?e:void 0}var X="tcg-generate-headless";function Q(t){return{refineHint:`kane-cli generate "<refinement>" --refine --req ${t}`,saveHint:`kane-cli generate --save --req ${t}`}}function W(t){return t.scenarios.reduce((e,n)=>e+(n.test_cases?.length??0),0)}function oe(t){return t==="completed"?0:t==="stopped"?3:1}async function Ne(t,e){let n=e.write??(i=>process.stdout.write(i)),r=e.sink??(e.mode==="agent"?new y(n):new S(n)),l,u,d=null;try{let i=await e.makeClient();l=i.client,u=i.conn,d=i.autoDefaulted}catch(i){return r.onError(i.message),2}if(e.mode==="agent"&&d){let{buildAutoDefaultedNdjson:i}=await import("./require-project-folder-PFIDA5ZH.js");n(i(d))}try{let i=await(e.checkUpdate??J)();i&&r.onUpdateAvailable(i)}catch{}let g=t.reqId??null;x(X,()=>{g&&l.cancel(g).catch(()=>{})});let p=process.cwd(),v={validate:e.validate??z,upload:e.upload??O,buildMappings:K,onUpload:i=>r.onUpload(i)};try{if(t.op==="save"){let s;try{s=(await l.attach(t.reqId)).state}catch(D){return r.onError(D.message),2}g=s.requestId,r.onSnapshot(s);let m=t.outDir??ie(),o=await e.materialize(s,m,t.suiteName);r.onSaveResult({suiteDir:o.suiteDir,saved:o.paths.length,fellBack:o.fellBack,warning:o.warning});let h=Q(s.requestId);return r.onDone({requestId:s.requestId,status:"completed",scenarioCount:s.scenarios.length,caseCount:W(s),refineHint:h.refineHint,saveHint:h.saveHint,suiteDir:o.suiteDir}),0}let i=t.op==="refine",f,a;if(i){let s;try{s=await l.attach(t.reqId)}catch(o){return r.onError(o.message),2}if(a=s.state,g=a.requestId,a.error)return r.onError(a.error),2;let m;try{m=await _({promptText:t.objective,filePaths:t.files??[],cwd:p,scenarios:a.scenarios,isRefine:!0,conn:u,deps:v})}catch(o){if(o instanceof C){for(let h of o.errors)r.onError(h);return 2}return r.onError(o.message),2}for(let o of m.warnings)process.stderr.write(`warning: ${o}
19
+ `)}};import{createHash as ee}from"crypto";function te(t){return ee("sha1").update(JSON.stringify({t:t.title,p:t.preconditions,m:t.manual_steps})).digest("hex")}function re(t){let e=[];for(let n of t.scenarios)for(let r of n.test_cases??[])I(r)&&r.manual_steps!=null&&e.push(r);return e}async function ne(t,e,n){let r=new Array(t.length),l=0,u=Array.from({length:Math.min(e,t.length)},async()=>{for(;;){let d=l++;if(d>=t.length)return;try{r[d]={ok:!0,value:await n(t[d])}}catch{r[d]={ok:!1}}}});return await Promise.all(u),r}async function Y(t,e,n){let r=re(t),l=n.run??(async(c,s)=>{let m=await n.resolveAuth(),o=U({objective:c,model:n.model,sessionId:n.sessionId,auth:m});return F(o,n.spawnOpts,s)}),u=r.map(te),d=[...new Set(u)],g=new Map;d.forEach(c=>{g.set(c,r[u.indexOf(c)])});let p=d.map(c=>g.get(c)),v=await ne(p,n.concurrency??3,c=>l(L(c))),i=new Map;d.forEach((c,s)=>{let m=v[s];m.ok&&i.set(c,m.value)});let f=new Map;r.forEach((c,s)=>{f.set(c.id,i.get(u[s]))});let a=0;for(let c of t.scenarios)for(let s of c.test_cases??[])I(s)&&!f.get(s.id)&&a++;let w=c=>{let s=f.get(c.id);return s?N(s,c):M(c)};return{...await B(t,e,{suiteName:n.suiteName,redirectBareCwd:!1},w),fellBack:a}}function Pe(t,e){let n=!!t.agent||!!t.refine||!!t.save||!e,r=t.agent?"agent":"plain";return{headless:n,mode:r}}function $e(t){return t.refine&&t.save?{error:"use --refine or --save, not both"}:t.save?t.objective?{error:"--save takes no objective; use --refine to add to a request"}:t.req?{op:"save"}:{error:"--save requires --req <id>"}:t.refine?t.req?t.objective?t.out?{error:"--out is only valid with --save"}:{op:"refine"}:{error:"--refine needs a refinement objective"}:{error:"--refine requires --req <id>"}:t.req?{error:"--req requires --refine or --save"}:t.out?{error:"--out is only valid with --save"}:t.objective?{op:"new"}:{error:"provide an objective, or use --refine/--save with --req"}}function ie(){return se(process.cwd(),".testmuai","tests")}function Ge(t){if(typeof t!="string")return;let e=t.split(",").map(n=>n.trim()).filter(Boolean);return e.length?e:void 0}var X="tcg-generate-headless";function Q(t){return{refineHint:`kane-cli generate "<refinement>" --refine --req ${t}`,saveHint:`kane-cli generate --save --req ${t}`}}function W(t){return t.scenarios.reduce((e,n)=>e+(n.test_cases?.length??0),0)}function oe(t){return t==="completed"?0:t==="stopped"?3:1}async function Ne(t,e){let n=e.write??(i=>process.stdout.write(i)),r=e.sink??(e.mode==="agent"?new y(n):new S(n)),l,u,d=null;try{let i=await e.makeClient();l=i.client,u=i.conn,d=i.autoDefaulted}catch(i){return r.onError(i.message),2}if(e.mode==="agent"&&d){let{buildAutoDefaultedNdjson:i}=await import("./require-project-folder-AQUVEEJB.js");n(i(d))}try{let i=await(e.checkUpdate??J)();i&&r.onUpdateAvailable(i)}catch{}let g=t.reqId??null;x(X,()=>{g&&l.cancel(g).catch(()=>{})});let p=process.cwd(),v={validate:e.validate??z,upload:e.upload??O,buildMappings:K,onUpload:i=>r.onUpload(i)};try{if(t.op==="save"){let s;try{s=(await l.attach(t.reqId)).state}catch(D){return r.onError(D.message),2}g=s.requestId,r.onSnapshot(s);let m=t.outDir??ie(),o=await e.materialize(s,m,t.suiteName);r.onSaveResult({suiteDir:o.suiteDir,saved:o.paths.length,fellBack:o.fellBack,warning:o.warning});let h=Q(s.requestId);return r.onDone({requestId:s.requestId,status:"completed",scenarioCount:s.scenarios.length,caseCount:W(s),refineHint:h.refineHint,saveHint:h.saveHint,suiteDir:o.suiteDir}),0}let i=t.op==="refine",f,a;if(i){let s;try{s=await l.attach(t.reqId)}catch(o){return r.onError(o.message),2}if(a=s.state,g=a.requestId,a.error)return r.onError(a.error),2;let m;try{m=await _({promptText:t.objective,filePaths:t.files??[],cwd:p,scenarios:a.scenarios,isRefine:!0,conn:u,deps:v})}catch(o){if(o instanceof C){for(let h of o.errors)r.onError(h);return 2}return r.onError(o.message),2}for(let o of m.warnings)process.stderr.write(`warning: ${o}
20
20
  `);r.onStart({requestId:a.requestId,objectiveChars:m.promptText.length,scenarioLimit:t.scenarioLimit,perScenarioLimit:t.perScenarioLimit,isRefine:!0});try{await l.chat(t.reqId,m.promptText,{mappings:m.mappings,attachments:m.attachments})}catch(o){return r.onError(o.message),2}f=s.events}else{let s;try{s=await _({promptText:t.objective,filePaths:t.files??[],cwd:p,scenarios:[],isRefine:!1,conn:u,deps:v})}catch(o){if(o instanceof C){for(let h of o.errors)r.onError(h);return 2}return r.onError(o.message),2}for(let o of s.warnings)process.stderr.write(`warning: ${o}
21
21
  `);let m;try{m=await l.start({prompt:s.promptText,attachments:s.attachments,scenarioLimit:t.scenarioLimit,perScenarioLimit:t.perScenarioLimit,memoryEnhancement:t.memory})}catch(o){return r.onError(o.message),2}a=m.state,g=a.requestId,r.onStart({requestId:a.requestId,objectiveChars:s.promptText.length,scenarioLimit:t.scenarioLimit,perScenarioLimit:t.perScenarioLimit,isRefine:!1}),f=m.events}let w="";for await(let s of f){switch(a=P(a,s),s.type){case"thinking_done":r.onThinking({tookMs:s.tookMs});break;case"progress":r.onProgress(s.pct);break;case"clarification":r.onClarification(s.text);break;case"chat":r.onChat(s.text);break;case"error":r.onError(s.message);break;case"done":w=s.status;break;default:break}if(s.type==="done"||s.type!=="thinking"&&a.status&&T(a.status))break}r.onSnapshot(a);let b=w||a.status||"completed",c=Q(a.requestId);return r.onDone({requestId:a.requestId,status:b,scenarioCount:a.scenarios.length,caseCount:W(a),refineHint:c.refineHint,saveHint:c.saveHint,suiteDir:void 0}),oe(b)}finally{A(X)}}var ae=()=>{};async function Me(t){let e=new j,n=new q,r=e.getActiveProfile()??"default",l=t.env??e.getDefaultEnv()??"prod",u=R(l),d=new E;t.name&&d.setSessionName(t.name);let g=n.load().model,p=async()=>{let i=await k({creds:e,env:l,usernameFlag:t.username,accessKeyFlag:t.accessKey,log:()=>{}}),f=await V({resolver:i.resolver,env:u,log:ae,projectId:t.projectId,folderId:t.folderId,autoResolve:t.projectId?void 0:{creds:e,config:n,profile:r,envName:l}});return{client:G(f),conn:f,autoDefaulted:f.autoDefaulted??null}},v=async()=>{let i=await k({creds:e,env:l,usernameFlag:t.username,accessKeyFlag:t.accessKey,log:()=>{}});return i.basicAuth?{username:i.basicAuth.username,access_key:i.basicAuth.access_key}:i.token?{auth:{type:"bearer",token:i.token}}:{}};return{mode:t.mode,makeClient:p,materialize:(i,f,a)=>Y(i,f,{model:g,sessionId:d.sessionId,resolveAuth:v,spawnOpts:{environment:l},suiteName:a})}}export{Me as buildHeadlessDeps,Pe as decideGenerateMode,ie as defaultOutDir,Ge as parseFilesFlag,$e as resolveGenerateOp,Ne as runGenerateHeadless};