@kynver-app/runtime 0.2.122 → 0.2.129
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/cli.js +255 -188
- package/dist/daemon-tick-thread.js +114 -50
- package/dist/desktop-entry.js +208 -144
- package/dist/index.js +279 -212
- package/dist/local-run-store/index.js +73 -9
- package/dist/server/cleanup.js +78 -14
- package/dist/server/default-repo.js +65 -1
- package/dist/server/dispatch-routing.js +67 -3
- package/dist/server/memory-cost-enforce.js +2 -2
- package/dist/server/memory-cost.js +1 -1
- package/dist/server/model-routing.js +67 -3
- package/dist/server/monitor.js +71 -7
- package/dist/server/orchestration.js +65 -1
- package/dist/server/worker-policy.js +66 -2
- package/dist/worker-broker/index.js +4 -4
- package/package.json +1 -1
package/dist/desktop-entry.js
CHANGED
|
@@ -1,29 +1,93 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
1
|
+
var VU=Object.defineProperty;var p=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Lv=(e,t)=>{for(var r in t)VU(e,r,{get:t[r],enumerable:!0})};function Wv(){Co=!0}function Qe(){return Co}function Uv(e){if(!Co)throw new Error("installDesktopCredentialProvider requires desktop credential mode");if(e.kind!=="desktop")throw new Error("only a desktop credential provider may be installed");if(li)throw new Error("desktop credential provider is already installed");li=e}function Fv(){return li!==null}function Kv(e){if(!Co)return e;if(!li)throw new ai;return li}function Pe(e,t=process.env){if(Co)return;let r=t[e]?.trim();return r||void 0}function pf(){if(Co)throw new df}var Bv,ai,df,Co,li,St=p(()=>{"use strict";Bv=["KYNVER_API_KEY","KYNVER_RUNNER_TOKEN","KYNVER_CHAT_BOX_CREDENTIAL","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","OPENCLAW_RUNNER_TOKEN"],ai=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},df=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},Co=!1,li=null});import{homedir as ff}from"node:os";import yn from"node:path";function Tl(e){return e==="~"?ff():e.startsWith("~/")||e.startsWith("~\\")?yn.join(ff(),e.slice(2)):e}function Me(e){return yn.resolve(Tl(e))}function GU(e){let t=Tl(e),r=yn.resolve(t),n=yn.resolve(ff());return r===n?"~":r.startsWith(`${n}${yn.sep}`)?`~/${yn.relative(n,r).split(yn.sep).join("/")}`:r.replace(/\\/g,"/").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^[A-Za-z]:\/home\/[^/]+(?=\/|$)/i,"~").replace(/^[A-Za-z]:\/Users\/[^/]+(?=\/|$)/i,"~")}function He(e){return GU(e)}var at=p(()=>{"use strict"});import{spawnSync as JU}from"node:child_process";function zU(e){return["/PID",String(e),"/T","/F"]}function XU(e){return e.error?{method:"taskkill",outcome:"failed",detail:e.error.message}:e.status===0?{method:"taskkill",outcome:"signalled"}:e.status===qU||/not found/i.test(e.stderr)?{method:"taskkill",outcome:"not_found"}:{method:"taskkill",outcome:"failed",detail:`taskkill exit ${e.status??"null"}: ${e.stderr.trim().slice(0,300)}`}}function QU(e){let t=JU("taskkill",e,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","pipe"],timeout:YU});return{status:t.status,stderr:t.stderr??"",...t.error?{error:t.error}:{}}}function ZU(e){return Number.isInteger(e)&&e>0}function fe(e,t="SIGTERM",r={}){if(!ZU(e))return{method:"none",outcome:"not_found"};if((r.platform??process.platform)==="win32"){let s=r.runTaskkill??QU;return XU(s(zU(e)))}let o=r.kill??((s,i)=>{process.kill(s,i)});try{return o(-e,t),{method:"group",outcome:"signalled"}}catch{}try{return o(e,t),{method:"pid",outcome:"signalled"}}catch(s){let i=s.code;return i==="ESRCH"?{method:"pid",outcome:"not_found"}:{method:"pid",outcome:"failed",detail:i??s.message}}}function Re(e=process.platform){return e!=="win32"}function Ze(e,t="SIGTERM",r={}){if((r.platform??process.platform)==="win32"&&e.pid){fe(e.pid,t,r);return}try{e.kill(t)}catch{}}var qU,YU,ci=p(()=>{"use strict";qU=128,YU=15e3});import{existsSync as eF,mkdirSync as tF,readFileSync as jv,readdirSync as Noe,renameSync as rF,rmSync as nF,statSync as Vv,writeFileSync as oF}from"node:fs";import{randomBytes as sF}from"node:crypto";import iF from"node:path";function lt(e){console.error(e),process.exit(1)}function z(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function _t(e,t){return e||lt(`missing ${t}`),e}function ui(e){try{return JSON.parse(e)}catch{return null}}function F(e,t){try{return JSON.parse(jv(e,"utf8"))}catch(r){if(arguments.length>1)return t;lt(`failed to read ${e}: ${r.message}`)}}function be(e,t){tF(iF.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${sF(4).toString("hex")}.tmp`;try{oF(r,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`),rF(r,e)}catch(n){try{nF(r,{force:!0})}catch{}throw n}}function B(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function Nl(e){return B(`${new Date().toISOString().replace(/[-:]/g,"").replace(/\..+/,"Z")}-${e}`)}function kn(e){return String(e).replace(/\/+$/,"")}function Dl(e){try{return Vv(e).size}catch{return 0}}function Ml(e){try{return Vv(e).mtime.toISOString()}catch{return null}}function Eo(e,t){return eF(e)?jv(e,"utf8").split(`
|
|
3
3
|
`).slice(-t).join(`
|
|
4
|
-
`):""}function
|
|
5
|
-
`).map(t=>t.trim()).filter(Boolean)}function Q(e,t){try{let r=pv("git",t,X({cwd:e,encoding:"utf8"}));return{status:r.status,stdout:r.stdout||"",stderr:r.stderr||"",error:r.error?r.error.message:null}}catch(r){return{status:null,stdout:"",stderr:"",error:r.message}}}function dv(e,t,r){let n=Q(e,["merge-base","--is-ancestor",t,r]);return n.status===0?{isAncestor:!0,error:null}:n.status===1?{isAncestor:!1,error:null}:{isAncestor:null,error:n.error||n.stderr||n.stdout||`git exited ${n.status}`}}function El(e,t="origin/main"){let r=typeof t=="string"?{base:t}:t,n=r.baseCommit?.trim()||r.base?.trim()||"origin/main",o=r.baseCommit?.trim()||null;if(!e)return Ro(n,"missing worktree path");let s=Q(e,["rev-parse","HEAD"]);if(s.status!==0)return Ro(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let m=Q(e,["rev-parse",n]);if(m.status!==0)return Ro(n,m.error||m.stderr||m.stdout||`failed to resolve ${n}`,s.stdout.trim());i=m.stdout.trim()}let a=s.stdout.trim();if(a===i)return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let l=dv(e,i,a),c=dv(e,a,i),u=l.error||c.error||void 0;if(l.isAncestor==null||c.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:"unknown",...u?{error:u}:{}};let d=l.isAncestor?"ahead":c.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:d,...u?{error:u}:{}}}function Ro(e,t,r=null){return{checked:!1,base:e,head:r,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:t}}var ve=p(()=>{"use strict";nt();D();ri()});import{existsSync as XW,mkdirSync as mv}from"node:fs";import{homedir as Yp}from"node:os";import wo from"node:path";function hv(e=Yp()){return wo.join(e,".kynver",QW)}function yv(e,t=Yp()){return wo.resolve(e)===wo.resolve(hv(t))}function ZW(e){Q(e,["config","--get","user.email"]).status!==0&&Q(e,["config","user.email","kynver@local"]),Q(e,["config","--get","user.name"]).status!==0&&Q(e,["config","user.name","Kynver"])}function gv(e){Q(e,["rev-parse","--verify","HEAD^{commit}"]).status!==0&&(ZW(e),Q(e,["commit","--allow-empty","-m","kynver byoc workspace"]))}function kv(e=Yp()){let t=hv(e);mv(wo.dirname(t),{recursive:!0});let r=!1;XW(t)||(mv(t,{recursive:!0}),r=!0);let n=Q(t,["rev-parse","--show-toplevel"]);if(n.status!==0)return Q(t,["init","-b","main"]),gv(t),r=!0,{repo:wo.resolve(t),created:r};let o=wo.resolve(n.stdout.trim()||t);return gv(o),{repo:o,created:r}}var QW,zp=p(()=>{"use strict";ve();QW="workspace"});import{existsSync as Qp,readFileSync as vv}from"node:fs";import{homedir as Rv}from"node:os";import st from"node:path";import{fileURLToPath as eU}from"node:url";function rU(e){let t=st.join(e,"package.json");if(!Qp(t))return null;try{let r=JSON.parse(vv(t,"utf8"));return typeof r.name=="string"?r.name.trim():null}catch{return null}}function wv(e){return rU(e)==="kynver"}function bv(e){let t=st.resolve(e);if(!Qp(t))return null;let r=Q(t,["rev-parse","--show-toplevel"]);if(r.status!==0)return null;let n=r.stdout.trim();return n.length?st.resolve(n):null}function nU(e=import.meta.url){let t=st.dirname(eU(e));for(let r=0;r<8;r+=1){let n=st.join(t,"package.json");if(Qp(n))try{if(JSON.parse(vv(n,"utf8")).name==="@kynver-app/runtime")return t}catch{}let o=st.dirname(t);if(o===t)break;t=o}return null}function Xp(e,t,r,n,o){if(!r)return;let s=st.resolve(r);e.has(s)||(o?.requireMonorepo??!0)&&!wv(s)||(e.add(s),t.push({repo:s,source:n}))}function Sv(e){let t=e?.cwd??process.cwd(),r=new Set,n=[];Xp(r,n,bv(t),"cwd_git",{requireMonorepo:!1});let o=nU(e?.runtimeModuleUrl??import.meta.url);o&&Xp(r,n,bv(o),"runtime_checkout");let s=Rv();for(let a of tU)Xp(r,n,Ne(st.join(s,a)),"well_known_path");let i=st.resolve(e?.cwd??process.cwd());return n.filter(a=>{if(a.source!=="runtime_checkout"||!wv(a.repo))return!0;let l=st.resolve(a.repo);return i===l||i.startsWith(`${l}${st.sep}`)})}function Al(e){return Sv(e)[0]??null}function oU(e){let t=st.resolve(e).replace(/\\/g,"/");return t.includes("/.kynver/harness/worktrees/")||t.includes("/.openclaw/harness/worktrees/")||t.includes("/kynver-harness/")||t.includes("/openclaw/harness/worktrees/")}function Pl(e){let t=Sv(e),r=t.find(o=>!oU(o.repo));if(r)return r;if(t[0])return t[0];let{repo:n}=kv(e?.home??Rv());return{repo:n,source:"byoc_workspace"}}var tU,oi=p(()=>{"use strict";ve();nt();zp();tU=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});function si(e){let t=dn(e);try{let r=new URL(t);return r.hostname.toLowerCase()===_v?(r.hostname=`www.${_v}`,dn(r.toString())):t}catch{return t}}function rr(e){if(e?.trim())return si(dn(e.trim()))}async function it(e,t,r=fetch){let n=si(e),o=new Headers(t?.headers),s=0;for(;s<=xv;){let i=await r(n,{...t,headers:o,redirect:"manual"});if(![301,302,303,307,308].includes(i.status))return i;let a=i.headers.get("location");if(!a)return i;let l=new URL(a,n);if(l.origin!==new URL(n).origin||l.username||l.password)throw await i.body?.cancel(),new Error("kynver API fetch refused unsafe redirect (origin change or embedded credentials)");let c=(t?.method??"GET").toUpperCase();if(!["GET","HEAD"].includes(c)&&i.status!==307&&i.status!==308)return i;await i.body?.cancel(),n=l.toString(),s+=1}throw new Error(`kynver API fetch exceeded ${xv} redirects for ${e}`)}var _v,xv,nr=p(()=>{"use strict";D();_v="kynver.com";xv=10});function pn(e){let t=(e??"").trim().toLowerCase();return t==="ghost"||t==="forge"||t==="box"?t:t.includes("forge")?"forge":t.includes("ghost")||t.includes("openclaw")?"ghost":"box"}function Il(e,t){return e[t]?.trim()||null}function Cv(e){let t=e?.split(":")[0]?.trim();return t?pn(t):null}function Qe(e=process.env,t={}){let r=[],n=Cv(t.boxId),o=Cv(Il(e,"KYNVER_BOX_ID")),s=t.boxKind?.trim();if(s)return n&&n!==pn(s)&&r.push(`config.boxId=${t.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:pn(s),source:"config",slugInferenceBlocked:!1,warnings:r};let i=Il(e,"KYNVER_BOX_KIND");if(i)return o&&o!==pn(i)&&r.push(`KYNVER_BOX_ID=${Il(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:pn(i),source:"env",slugInferenceBlocked:!1,warnings:r};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:r};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:r};let a=Il(e,"KYNVER_AGENT_OS_SLUG");return a&&r.push(`KYNVER_AGENT_OS_SLUG=${a} is a workspace slug, not box identity \u2014 operators set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND; customers default to box`),{boxKind:"box",source:"default",slugInferenceBlocked:!!a,warnings:r}}function Rt(e={},t=process.env){return Qe(t,e).boxKind}var De=p(()=>{"use strict"});function Zp(e,t){return e==="forge"?4:Math.max(1,t)}function or(e,t){return e==="forge"?Math.min(Math.max(1,t),4):Math.max(1,t)}function ii(e,t){return e==="forge"&&t>4}var So=p(()=>{"use strict"});import{readFileSync as sU}from"node:fs";import Ev from"node:os";function Av(e){if(e!==void 0){let t=e.match(/^MemAvailable:\s+(\d+)\s*kB/m);return t?Number(t[1])*1024:Ev.freemem()}if(process.platform==="linux")try{let r=sU("/proc/meminfo","utf8").match(/^MemAvailable:\s+(\d+)\s*kB/m);if(r)return Number(r[1])*1024}catch{}return Ev.freemem()}var Pv=p(()=>{"use strict"});import{existsSync as iU,readFileSync as aU,statfsSync as lU}from"node:fs";function ef(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!iU(e))continue;let t=aU(e,"utf8");if(/microsoft|wsl/i.test(t))return!0}catch{}return!1}function Iv(e={}){if(!(e.forceWsl===void 0?ef():e.forceWsl))return null;let r=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||_o,n=e.wslHostFreeWarnBytes??cU,o=e.wslHostFreeCriticalBytes??uU,s=e.statfs??lU,i;try{i=s(r)}catch(h){return{ok:!1,path:r,freeBytes:0,totalBytes:0,usedPercent:100,warnBelowBytes:n,criticalBelowBytes:o,reason:`Windows host disk probe failed at ${r}: ${h.message}`,probeError:h.message}}let a=Number(i.bavail)*Number(i.bsize),l=Number(i.blocks)*Number(i.bsize),c=l>0?(l-a)/l*100:100,u=a<n,d=a<o,m=!u&&!d,f=(a/(1024*1024*1024)).toFixed(1),g=null;return m||(g=`Windows host disk ${r} at ${d?"critical":"warning"}: ${f} GiB free (<${(d?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${dU()}`),{ok:m,path:r,freeBytes:a,totalBytes:l,usedPercent:c,warnBelowBytes:n,criticalBelowBytes:o,reason:g,probeError:null}}function dU(){return"Recovery: 1) free Windows C: (empty Recycle Bin / Storage Sense / clear %TEMP% and %LOCALAPPDATA%\\Temp\\wsl-crashes); 2) shut down WSL (`wsl --shutdown`) then compact the VHDX (`Optimize-VHD` or `diskpart compact vdisk`); 3) clear local node_modules / .next / harness worktrees before restarting workers; 4) disable recurring dumps via `%USERPROFILE%/.wslconfig` (`maxCrashDumpCount=-1`) or `kynver wsl-crashes --execute`. More help: https://www.kynver.com/help."}var cU,uU,_o,tf=p(()=>{"use strict";cU=25*1024*1024*1024,uU=12*1024*1024*1024,_o="/mnt/c"});import{execFileSync as Ov}from"node:child_process";import{existsSync as Tl,readFileSync as Tv,readdirSync as pU,statSync as fU}from"node:fs";import rf from"node:path";function Ol(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function Nv(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=Ov("cmd.exe",["/c","echo","%USERNAME%"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(n&&n!=="%USERNAME%"&&!n.includes("%"))return n}catch{}let t=process.env.USER?.trim()||process.env.LOGNAME?.trim(),r=process.env.KYNVER_WSL_HOST_MOUNT?.trim()||_o;return t&&Tl(rf.join(r,"Users",t))?t:null}function kU(e={}){let t=e.crashDumpDir?.trim()||process.env.KYNVER_WSL_CRASH_DUMP_DIR?.trim();if(t)return t;let r=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||_o,n=e.windowsUser??Nv();return n?`${r.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function bU(e){let t=/^wsl-crash-\d+-(\d+)-(.+)-(\d+)\.dmp$/i.exec(e);if(!t)return{executableHint:null,signal:null,pid:null};let r=Number(t[1]),n=t[2]??"",o=Number(t[3]),s=n.split("_").filter(Boolean);return{executableHint:s.length>0?s[s.length-1]:null,signal:Number.isFinite(o)?o:null,pid:Number.isFinite(r)?r:null}}function vU(){try{if(Tl("/proc/sys/kernel/core_pattern"))return Tv("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return Ov("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function RU(e){return!!(e&&/wsl-capture-crash/i.test(e))}function wU(e,t=_o){let r=rf.join(t,"Users",e,".wslconfig");if(!Tl(r))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=Tv(r,"utf8")}catch{return null}let o=null,s=null;for(let i of n.split(/\r?\n/)){let a=i.replace(/#.*$/,"").trim();if(!a||a.startsWith("["))continue;let l=a.indexOf("=");if(l<0)continue;let c=a.slice(0,l).trim().toLowerCase(),u=a.slice(l+1).trim();if(c==="maxcrashdumpcount"){let d=Number(u);o=Number.isFinite(d)?d:null}else c==="crashdumpfolder"&&(s=u.replace(/^["']|["']$/g,"")||null)}return{maxCrashDumpCount:o,crashDumpFolder:s}}function SU(e){if(!Tl(e))return[];let t=pU(e,{withFileTypes:!0}),r=[];for(let n of t){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=rf.join(e,n.name);try{let s=fU(o),i=bU(n.name);r.push({name:n.name,path:o,bytes:s.size,mtimeMs:s.mtimeMs,executableHint:i.executableHint,signal:i.signal,pid:i.pid})}catch{}}return r.sort((n,o)=>o.mtimeMs-n.mtimeMs),r}function xo(e={}){if(!(e.forceWsl===void 0?ef():e.forceWsl))return null;let r=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||_o,n=e.windowsUser??Nv(),o=e.warnBelowBytes??Ol("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",mU),s=e.criticalBelowBytes??Ol("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",gU),i=e.warnCount??Ol("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",hU),a=e.criticalCount??Ol("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",yU),l=(e.readCorePattern??vU)(),c=RU(l),u=null;n&&(u=(e.readWslConfig??wU)(n,r));let d=u?.maxCrashDumpCount??null,m=d===-1,f=kU({hostMount:r,windowsUser:n,crashDumpDir:e.crashDumpDir});if(!f)return{ok:!0,path:null,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:l,wslCaptureEnabled:c,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:null,probeError:"windows_user_unresolved"};let g;try{g=(e.listDumps??SU)(f)}catch(O){return{ok:!1,path:f,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:l,wslCaptureEnabled:c,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:`WSL crash dump probe failed at ${f}: ${O.message}`,probeError:O.message}}let h=g.reduce((O,P)=>O+P.bytes,0),y=g.length,v=[...new Set(g.map(O=>O.executableHint).filter(O=>!!O))],k=h>=s,b=h>=o,_=y>=a,S=y>=i,w=!(k||_||b||S),W=null;if(!w){let O=k||_?"critical":"warning",P=(h/1024**3).toFixed(1),N=v.length>0?v.join(", "):"unknown";W=`WSL crash dumps ${O}: ${y} file(s), ${P} GiB at ${f} (executables: ${N}). `+_U({wslCaptureEnabled:c,dumpsDisabledInWslConfig:m})}return{ok:w,path:f,windowsUser:n,dumpCount:y,totalBytes:h,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:g,executables:v,corePattern:l,wslCaptureEnabled:c,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:W,probeError:null}}function _U(e={}){let t=["Recovery:","1) run `kynver wsl-crashes --execute` or scripts/cleanup-wsl-crashes.ps1 to prune old .dmp files;"];return e.dumpsDisabledInWslConfig||t.push("2) add `[wsl2]\\nmaxCrashDumpCount=-1` to %USERPROFILE%/.wslconfig then `wsl --shutdown` to disable future dumps;"),e.wslCaptureEnabled&&t.push("3) investigate crashing executables (node OOM/SIGBUS often follows Windows C: pressure);"),t.push("More help: https://www.kynver.com/help."),t.join(" ")}var mU,gU,hU,yU,Nl=p(()=>{"use strict";tf();mU=5*1024*1024*1024,gU=10*1024*1024*1024,hU=2,yU=4});import{statfsSync as xU}from"node:fs";function Dr(e={}){let t=e.diskPath?.trim()||"/",r=e.diskFreeWarnBytes??CU,n=e.diskFreeCriticalBytes??EU,o=e.diskMaxUsedPercent??AU,s=e.diskHardMaxUsedPercent??PU,i=xU(t),a=Number(i.bavail)*Number(i.bsize),l=Number(i.blocks)*Number(i.bsize),c=l>0?(l-a)/l*100:100,u=a<r,d=a<n,m=a<r*2,f=m&&c>o,g=m&&c>s,h=!u&&!d&&!f&&!g,y=e.skipWslHostCheck?null:Iv(e.wslHost),v=e.skipWslCrashDumpCheck?null:xo(e.wslCrashDumps),k=h&&(y?y.ok:!0)&&(v?v.ok:!0),b=null;return k||(b=[d?`free space below critical ${n} bytes`:null,u?`free space below warning ${r} bytes`:null,g?`used percent above hard cap ${s}%`:null,f?`used percent above cap ${o}%`:null,y&&!y.ok?y.reason:null,v&&!v.ok?v.reason:null].filter(Boolean).join("; ")),IU({ok:k,path:t,freeBytes:a,totalBytes:l,usedPercent:c,warnBelowBytes:r,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:b,wslHost:y,wslCrashDumps:v?{ok:v.ok,path:v.path,dumpCount:v.dumpCount,totalBytes:v.totalBytes,executables:v.executables,wslCaptureEnabled:v.wslCaptureEnabled,dumpsDisabledInWslConfig:v.dumpsDisabledInWslConfig,reason:v.reason,probeError:v.probeError}:null})}function IU(e){let t=process.env.KYNVER_DISPATCH_DISK_GATE_FORCE?.trim().toLowerCase();return t?t==="ok"||t==="open"||t==="none"?e.ok?e:{...e,ok:!0,reason:`disk gate forced open by KYNVER_DISPATCH_DISK_GATE_FORCE (suppressed: ${e.reason??"no reason"})`}:t==="block"||t==="pressured"?{...e,ok:!1,reason:`disk gate forced closed by KYNVER_DISPATCH_DISK_GATE_FORCE${e.reason?` (underlying: ${e.reason})`:""}`}:e:e}var CU,EU,AU,PU,ai=p(()=>{"use strict";Nl();tf();CU=30*1024*1024*1024,EU=15*1024*1024*1024,AU=80,PU=90});import{existsSync as OU,readdirSync as TU}from"node:fs";import NU from"node:path";function wt(e){let t=new Set;for(let n of Object.keys(e.workers||{}))t.add(B(n));let r=NU.join(G(e.id),"workers");if(!OU(r))return[...t];for(let n of TU(r,{withFileTypes:!0}))n.isDirectory()&&t.add(B(n.name));return[...t]}var Co=p(()=>{"use strict";z();D()});function nf(e){let t=e.trim();if(!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&!Array.isArray(r))return r}catch{return null}return null}function Dv(e){let t=e.trim();if(!t)return null;let r=nf(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let l=nf(s[1]??"");l&&n.push(l)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let l=nf(t.slice(i,a+1));l&&n.push(l)}return n.length>0?n[n.length-1]:null}function Mv(e){let t=e.finalResult??e.final_result;if(t!=null)return typeof t=="string"?Dv(t)??(t.trim()||null):t;let r=typeof e.summary=="string"?e.summary.trim():"";if(!r)return null;let n=Dv(r);return n||r}var Lv=p(()=>{"use strict"});import{existsSync as DU,readFileSync as MU}from"node:fs";function Bv(e){return e==="complete"}function sr(e){return Bv(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function Ee(e){let t={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!DU(e))return t;let r=Date.now()+LU,n=new Date(r).toISOString(),o=MU(e,"utf8").split(`
|
|
6
|
-
`).filter(Boolean);for(let s of o){let i=
|
|
7
|
-
`).find(Boolean)??o,160):"npm audit failed"}function
|
|
8
|
-
${e.stderr}`.trim(),r=
|
|
9
|
-
`).filter(Boolean),n=null,o=Yv();for(let s of r){let i=ei(s);if(!i||typeof i!="object"||Array.isArray(i))continue;if(i.type==="turn.started"&&(n=null,t.finalResult=null),i.type==="item.completed"){let m=i.item;if(m&&typeof m=="object"&&!Array.isArray(m)){let f=m;f.type==="agent_message"&&typeof f.text=="string"&&f.text.trim()&&(n=f.text)}}i.type==="turn.completed"&&n&&!t.providerTerminalError&&(t.finalResult=n,n=null);let a=fF(i);if(a&&(t.firstEventAt||=a,t.lastEventAt=a),i.type==="stream_event"&&i.event&&typeof i.event=="object"&&i.event.type==="content_block_start"){let m=i.event.content_block;m?.type==="tool_use"&&(t.currentTool=String(m.name||"tool"))}if(i.type==="assistant"&&i.message&&typeof i.message=="object"){let m=i.message.content;if(Array.isArray(m)){let f=m.find(g=>g?.type==="tool_use");f&&(t.currentTool=String(f.name||t.currentTool))}}if(i.type==="tool_call"&&i.subtype==="started"){let m=i.tool_call&&typeof i.tool_call=="object"&&!Array.isArray(i.tool_call)?i.tool_call:void 0,f=mF(m);f&&(t.currentTool=f)}let l=bF(i);l&&vF(t,Jv({command:l.command,exitCode:l.exitCode,stdout:l.stdout,stderr:l.stderr,interleavedOutput:l.interleaved}));let c=Wl(i),u=c?null:zv(i,o),d=c??u;if(d?.currentTool&&(t.currentTool=d.currentTool),d?.usage&&(t.usage={...t.usage??{},...d.usage}),d?.terminal?d.terminal.ok?t.finalResult=d.terminal.finalResult:(t.finalResult=null,t.providerTerminalError=!0,t.error=d.terminal.error):i.type==="result"&&gF(t,i),i.type==="turn.failed"){n=null,t.finalResult=null,t.providerTerminalError=!0;let m=i.error;t.error=typeof m?.message=="string"?m.message:"provider turn failed"}kF(t,i)}return t}var di=p(()=>{"use strict";qv();D();Bl();cf();Xv()});function Qv(e,t=240){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}function pi(e){let t=(e??"").trim();if(!t)return null;if(ui(t))return{blocked:!0,reason:`provider authentication failed: ${Qv(t)}`};for(let r of RF)if(r.test.test(t))return{blocked:!0,reason:`${r.label}: ${Qv(t)}`};return null}var RF,df=p(()=>{"use strict";Bl();RF=[{test:/(?:claude provider refuses to spawn: worker prompt is empty after argv assembly|Input must be provided (?:either )?through stdin or as a prompt argument)/i,label:"provider prompt delivery failed"},{test:/\b(?:invalid|unknown|unsupported|unrecognized)\b[^.\n]*\bmodel\b/i,label:"provider rejected the requested model"},{test:/\bmodel\b[^.\n]*\b(?:not\s+(?:found|supported|available|recognized|valid)|is\s+not\s+valid|does\s+not\s+exist)/i,label:"provider rejected the requested model"},{test:/\b(?:did you mean|available models|choose (?:a|one of)|supported models)\b/i,label:"provider rejected the requested model"},{test:/model preflight failed/i,label:"model/provider preflight failed"},{test:/\b(?:command not found|ENOENT|is the .*CLI on PATH|executable not found|no such file or directory)\b/i,label:"provider CLI is missing or not on PATH"},{test:/\bfailed to spawn\b/i,label:"provider failed to spawn the worker process"},{test:/\b(?:not logged in|unauthorized|authentication (?:failed|required)|invalid api key|missing api key|401)\b/i,label:"provider authentication failed"},{test:/\b(?:out of usage|increase limits?|switch to auto|ask your admin to increase your limit|usage limits?|quota exceeded|insufficient_quota|credits? exhausted|billing|payment required)\b/i,label:"provider quota exhausted"}]});function Zv(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function wF(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function SF(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:Zv(e.head)}function _F(e,t,r){let n=["exited_with_changes_salvage"];if((e==="uncommitted"||e==="both")&&n.push(`${t} uncommitted change${t===1?"":"s"} with no final result`),(e==="committed_ahead"||e==="both")&&r){let o=r.length>12?r.slice(0,12):r;n.push(`commit ${o} ahead of base with no final result`)}return n.push("review worktree \u2014 commit, open a PR, or run a salvage worker before discarding"),n.join(": ")}function Ao(e){if(e.alive||wF(e.finalResult))return null;let t=(e.changedFiles??[]).filter(i=>i.trim()).length,r=Zv(e.headCommit)??SF(e.gitAncestry),n=t>0,o=!!r;if(!n&&!o)return{kind:"none",salvageable:!1,uncommittedCount:0,headCommit:null,attentionReason:"process exited without a final result"};let s=n&&o?"both":n?"uncommitted":"committed_ahead";return{kind:s,salvageable:!0,uncommittedCount:t,headCommit:r,attentionReason:_F(s,t,r)}}var Ul=p(()=>{"use strict"});import{existsSync as xF,readFileSync as CF,statSync as rR}from"node:fs";import Fl from"node:path";function IF(e,t=process.env){let r=e?AF:EF,n=t.KYNVER_WORKER_GIT_PROBE_CACHE_TTL_MS?.trim();if(!n)return r;let o=Number(n);return Number.isFinite(o)&&o>=0?Math.floor(o):r}function OF(e){return e.baseCommit?.trim()||e.base?.trim()||"origin/main"}function pf(e){try{return rR(e).mtimeMs}catch{return-1}}function TF(e){let t=Fl.join(e,".git");try{if(rR(t).isDirectory())return t;let r=/^gitdir:\s*(.+)$/m.exec(CF(t,"utf8"));return r?Fl.resolve(e,r[1].trim()):null}catch{return null}}function eR(e){let t=TF(e);return[pf(e),t?pf(Fl.join(t,"HEAD")):-2,t?pf(Fl.join(t,"index")):-2].join(":")}function tR(e,t){return{changedFiles:ni(e),gitAncestry:El(e,{base:t.base,baseCommit:t.baseCommit})}}function NF(e,t){for(Mr.delete(e),Mr.set(e,t);Mr.size>PF;){let r=Mr.keys().next().value;if(r===void 0)break;Mr.delete(r)}}function nR(e,t,r){let n=OF(t);if(!e||!e.trim())return fi.missingWorktree++,{changedFiles:[],gitAncestry:Ro(n,"missing worktree path")};let o=`${e}\0${n}`;if(!xF(e))return Mr.delete(o),fi.missingWorktree++,{changedFiles:[],gitAncestry:Ro(n,`worktree no longer exists: ${e}`)};if(r.alive)return Mr.delete(o),fi.liveProbes++,tR(e,t);let s=r.ttlMs??IF(!!t.baseCommit?.trim()),i=r.now??Date.now(),a=eR(e),l=Mr.get(o);if(s>0&&l&&l.fingerprint===a&&i<l.expiresAt)return fi.hits++,l.probe;fi.misses++;let c=tR(e,t);if(s>0){let u=.8+.4*(r.random??Math.random)();NF(o,{fingerprint:eR(e),expiresAt:i+Math.round(s*u),probe:c})}return c}var EF,AF,PF,Mr,fi,oR=p(()=>{"use strict";ve();EF=10*6e4,AF=60*6e4,PF=2048,Mr=new Map,fi={hits:0,misses:0,liveProbes:0,missingWorktree:0}});function mi(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function DF(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function MF(e){if(mi(e.headCommit)||mi(e.prUrl)||mi(e.artifactBundlePath)||mi(e.patchPath))return!0;let t=e.gitAncestry;return!!(t?.checked&&t.headIsAncestorOfBase===!1&&mi(t.head))}function Po(e){return DF(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:MF(e)?{blocked:!0,detail:`Worktree has ${e.changedFiles.length} uncommitted change(s); commit or discard before landing`}:{blocked:!0,reason:"dirty_worktree_no_pr",detail:`Worktree has ${e.changedFiles.length} uncommitted change(s) with no commit or PR; commit, open a PR, or discard before landing`}:{blocked:!1}}function sR(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var $l=p(()=>{"use strict"});function ff(e){let t=e.trim();if(!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&!Array.isArray(r))return r}catch{return null}return null}function iR(e){let t=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(t)?t.length:0}function Io(e){let t=e.trim();if(!t)return null;let r=ff(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let u=ff(s[1]??"");u&&n.push(u)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let u=ff(t.slice(i,a+1));u&&n.push(u)}if(n.length===0)return null;let l=n[n.length-1],c=iR(l);for(let u of n){let d=iR(u);d>c&&(l=u,c=d)}return l}var Kl=p(()=>{"use strict"});function aR(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:e.trim()||null}function lR(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function LF(e){return new Set(e.map(t=>lR(aR(t)??t)).filter(Boolean))}function cR(e,t,r){let n=aR(e)??e;if(!n)return"unrelated";let o=lR(n);return LF(t).has(o)?"contract":r?(r.outcome==="skipped"||r.outcome==="blocked")&&r.reason?.trim()?"support":(r.outcome==="merged","unrelated"):"unrelated"}var uR=p(()=>{"use strict"});function Oo(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function BF(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function gn(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:Oo(e)}function Hl(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function dR(e){let t=null;if(typeof e=="string"){let o=Io(e);o&&(t=o)}else e&&typeof e=="object"&&!Array.isArray(e)&&(t=e);if(!t)return[];let r=t.targetPrReconciliation??t.target_pr_reconciliation;if(!Array.isArray(r))return[];let n=[];for(let o of r){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=gn(String(s.prUrl??s.pr_url??"")),a=Oo(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:Oo(s.mergeCommit??s.merge_commit),reason:Oo(s.reason)})}return n}function pR(e,t){let r=[],n=gn(Oo(e.prUrl)??"");if(n&&r.push(n),t&&typeof t=="object"&&!Array.isArray(t)){let o=t,s=gn(String(o.prUrl??o.pr_url??""));s&&r.push(s)}return[...new Set(r)]}function fR(e){let{contract:t,snapshot:r}=e,n=e.finalResult??r.finalResult;if(!t.landingOnly&&t.targetPrUrls.length===0&&!t.repairEnforceOriginalPr)return{blocked:!1};if(!BF(n))return(t.requiresTargetPrReconciliation??(t.landingOnly||!!t.repairEnforceOriginalPr||t.targetPrUrls.length>0))&&t.targetPrUrls.length>0?{blocked:!0,reason:"missing_target_pr_reconciliation",detail:`Final result required to reconcile target PR(s): ${t.targetPrUrls.join(", ")}`}:{blocked:!1};if(!(t.requiresTargetPrReconciliation??(t.landingOnly||!!t.repairEnforceOriginalPr||t.targetPrUrls.length>0))&&!t.repairEnforceOriginalPr)return{blocked:!1};let s=t.repairEnforceOriginalPr?gn(Oo(t.targetPrUrl)??"")??(t.targetPrUrls.length===1?gn(t.targetPrUrls[0]):null):null;if(s){let d=pR(r,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let h of d)if(h!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${h} instead of canonical target ${s}`}}let g=dR(n).find(h=>h.prUrl===s);if(!g||g.outcome!=="merged"&&!(g.reason?.trim()&&(g.outcome==="skipped"||g.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=dR(n),a=new Map(i.map(d=>[Hl(d.prUrl),d])),l=new Set(t.targetPrUrls.map(d=>Hl(gn(d)??d)).filter(Boolean)),c=pR(r,n);if(t.landingOnly)for(let d of c){let m=a.get(Hl(d)),f=cR(d,t.targetPrUrls,m);if(!(f==="contract"||f==="support"))return l.size>0?{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${d}`}:{blocked:!0,reason:"unrelated_implementation_pr",detail:"Landing-only worker must not open new implementation PRs"}}if(t.targetPrUrls.length===0)return{blocked:!1};let u=[];for(let d of t.targetPrUrls){let m=Hl(gn(d)??d),f=a.get(m);if(!f){u.push(m);continue}f.outcome!=="merged"&&!f.reason?.trim()&&u.push(m)}return u.length>0?{blocked:!0,reason:u.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${u.join(", ")}`}:{blocked:!1}}function mR(e){if(e.blocked)return e.detail??e.reason}var gR=p(()=>{"use strict";Kl();uR()});function UF(e){let t=Date.now();if(e.providerTerminalError||Ll(e.finalResult)||e.finalResult&&e.error?.trim()||ui(e.error)||ui(e.finalResult)){let o=e.error||(typeof e.finalResult=="string"?e.finalResult:"provider terminal error");return{state:"blocked",reason:pi(o)?.reason??`provider terminal error: ${o}`}}if(e.completionBlocker&&!hR(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&$F(e.finalResult))return{state:"done",reason:"local-only worker superseded by merged PR"};let o={finalResult:e.finalResult,changedFiles:e.changedFiles??[],gitAncestry:e.gitAncestry??null,prUrl:e.prUrl??null},s=Po(o);if(s.blocked){let i=sR(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=fR({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=mR(i);if(a)return{state:"needs_attention",reason:i.reason?`landing contract (${i.reason}): ${a}`:`landing contract: ${a}`}}return{state:"done",reason:"final result recorded"}}if(!e.alive){if(FF(e))return{state:"done",reason:"empty abandoned worker record"};let o=pi(e.error);if(o)return{state:"blocked",reason:o.reason};let s=Ao({alive:!1,finalResult:null,changedFiles:e.changedFiles,gitAncestry:e.gitAncestry});if(s?.salvageable){let a=e.error?.trim();return{state:"needs_attention",reason:a?`${s.attentionReason} (${a})`:s.attentionReason}}let i=e.error?.trim();return{state:"needs_attention",reason:i?`process exited without a final result: ${i}`:s?.attentionReason??"process exited without a final result"}}if(e.heartbeatBlocker)return{state:"blocked",reason:`worker heartbeat reported blocker: ${e.heartbeatBlocker}`};let r=e.startedAt?Date.parse(e.startedAt):NaN;if(!e.firstEventAt&&e.stdoutBytes===0&&e.heartbeatBytes===0&&Number.isFinite(r)&&t-r>WF)return{state:"needs_attention",reason:`no first stream event ${Vp(r)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&t-n>mf?{state:"stale",reason:`no log/event/heartbeat activity for ${Vp(n)}s`}:{state:"ok",reason:"recent activity"}}function hR(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function FF(e){return e.finalResult||e.taskId||e.agentOsId||e.stdoutBytes>0||(e.stderrBytes??0)>0||e.heartbeatBytes>0||e.error?.trim()||(e.changedFiles??[]).some(t=>t.trim())?!1:/empty worker dir|marked abandoned/i.test(e.reconcileReason??"")}function $F(e){let t=null;if(typeof e=="string"?t=Io(e):e&&typeof e=="object"&&!Array.isArray(e)&&(t=e),!t)return!1;let r=t.targetPrReconciliation??t.target_pr_reconciliation;return Array.isArray(r)?r.some(n=>!n||typeof n!="object"||Array.isArray(n)?!1:String(n.outcome??"").trim()==="merged"):!1}function yR(e,t,r){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:t||(n??sr(r))}function kR(e){let t=mn(e.stdoutPath),r=Ee(e.heartbeatPath);return yR(e,t.finalResult,r)}function oe(e,t={}){let r=mn(e.stdoutPath),n=Ee(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=yR(e,r.finalResult,n),i=o?!1:re(e.pid),a=_l(e.stdoutPath),l=_l(e.stderrPath),c=_l(e.heartbeatPath),{changedFiles:u,gitAncestry:d}=nR(e.worktreePath,{base:t.base,baseCommit:t.baseCommit},{alive:i}),m=uv([r.lastEventAt,n.lastHeartbeatAt,xl(e.stdoutPath),xl(e.stderrPath),xl(e.heartbeatPath)]),f=r.error||!i&&!s&&jp(e.stderrPath,10).trim()||void 0,g=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,h=hR(g)?null:g,y=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,v=UF({alive:i,finalResult:s,firstEventAt:r.firstEventAt,stdoutBytes:a,stderrBytes:l,heartbeatBytes:c,lastActivityAt:m,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:f,providerTerminalError:r.providerTerminalError,changedFiles:u,gitAncestry:d,completionBlocker:h,landingContract:y,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),k=h||v.state==="blocked"?"blocked":o||v.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:k,attention:v,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:l,heartbeatBytes:c,firstEventAt:r.firstEventAt,lastEventAt:r.lastEventAt,lastActivityAt:m,currentTool:o?null:r.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:s,error:f,providerTerminalError:r.providerTerminalError,changedFiles:u,gitAncestry:d,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.provider??e.orchestrationAudit?.provider??null,usage:r.usage??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function Me(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function gf(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}function jl(e,t){return t.length===0?e:t.some(r=>r.attention==="needs_attention"||r.attention==="stale"||r.attention==="blocked")?"needs_attention":t.every(r=>r.status==="done")?"done":t.some(r=>r.status==="running")?"running":e}var WF,mf,_e=p(()=>{"use strict";fn();di();Bl();df();Ul();oR();$l();gR();Kl();D();WF=18e4,mf=6e5});import{readFileSync as KF}from"node:fs";function HF(e){if(!e||process.platform!=="linux")return null;try{return KF(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ")}catch{return null}}function bR(e){if(!e.pid||process.platform!=="linux")return!0;let t=HF(e.pid);return t?[e.worktreePath,e.workerDir,e.heartbeatPath].filter(n=>typeof n=="string"&&n.trim().length>0).some(n=>t.includes(n)):!1}function Lr(e){return typeof e.completionBlocker=="string"&&e.completionBlocker.trim()||typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim()||!re(e.pid)||!bR(e)?!1:!kR(e)}var Vl=p(()=>{"use strict";_e();D()});import RR from"node:os";import wR from"node:path";function vR(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function jF(e=E(),t,r){let n=vR(e.perWorkerMemBytes,Gl),o=vR(e.memReserveBytes,Jl),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):ql)),i=Do({config:e,configuredMaxWorkersOverride:t,totalMemBytes:r??RR.totalmem()});return{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i.configuredMaxWorkers,autoCap:i.autoCap,workerCapSource:i.workerCapSource}}function SR(e,t={}){let r=t.perWorkerMemBytes??Gl,n=t.memReserveBytes??Jl,o=t.memUtilization??ql,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/r));return Math.min(i,Yl)}function VF(){return Av()}function GF(e){let t=0;for(let r of wt(e)){let n=$(wR.join(G(e.id),"workers",B(r),"worker.json"),void 0);!n||!Lr(n)||t++}return t}function hf(){let e=0;for(let t of Re())e+=GF(t);return e}function To(){let e=[];for(let t of Re())for(let r of wt(t)){let n=$(wR.join(G(t.id),"workers",B(r),"worker.json"),void 0);n&&Lr(n)&&e.push({runId:t.id,workerName:r})}return e}function gi(e){let t=e.config??E(),r=e.totalMemBytes??RR.totalmem(),{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i,autoCap:a,workerCapSource:l}=jF(t,e.configuredMaxWorkersOverride,r),c=Rt(t),u=e.freeMemBytes??VF(),d=e.activeWorkers??hf(),m=Math.max(0,Math.floor(r*s)-o),f=Math.max(0,Math.floor(m/n)),g=Math.max(0,Math.floor(Math.max(0,u-o)/n)),h=a,y=or(c,i??h),v=Math.max(0,Math.min(y,f)),k=Math.max(0,v-d),_=Math.min(k,g),R=e.skipDiskGate||process.env.KYNVER_RESOURCE_GATE_SKIP_DISK==="1"?void 0:Dr({diskPath:e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/"});R&&!R.ok&&(_=0);let w=null;return _<=0&&(R&&!R.ok?w=R.reason??"disk gate blocked worker admission":d>=v?w=`at worker limit (${d}/${v} running)`:g<=0?w="insufficient free memory \u2014 waiting for workers to finish":w="no worker slots available"),{ok:_>0,totalMemBytes:r,freeMemBytes:u,memReserveBytes:o,perWorkerMemBytes:n,configuredMaxWorkers:i,workerCapSource:l,boxKind:c,autoCap:h,capacityWorkers:f,maxConcurrentWorkers:v,activeWorkers:d,slotsAvailable:_,reason:w,...R?{diskGate:R}:{}}}var Gl,Jl,ql,Yl,No=p(()=>{"use strict";Pv();H();De();So();hi();ai();z();Co();Vl();D();Gl=500*1024*1024,Jl=4*1024*1024*1024,ql=.85,Yl=64});function yi(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function Do(e){let t=e.config??{},r=e.env??process.env,n=yi(t.perWorkerMemBytes,Gl),o=yi(t.memReserveBytes,Jl),s=Math.min(1,Math.max(.1,Number(t.memUtilization)>0?Number(t.memUtilization):ql)),i=SR(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:yi(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(t.maxConcurrentWorkers!==void 0&&t.maxConcurrentWorkers!==null){let c=yi(t.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,Yl),autoCap:i,workerCapSource:"config"}}let l=(r.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||r.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&r.KYNVER_MAX_WORKERS&&yi(r.KYNVER_MAX_WORKERS,0)||null;return l?{configuredMaxWorkers:Math.min(l,Yl),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var hi=p(()=>{"use strict";No()});import{existsSync as JF,mkdirSync as zne,readFileSync as qF,writeFileSync as Xne}from"node:fs";import{homedir as YF}from"node:os";import zF from"node:path";function XF(e){let t=new Map;for(let r of e.split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("=");if(o<=0)continue;let s=n.slice(0,o).trim(),i=n.slice(o+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t.set(s,i)}return t}function zl(e=Br){return JF(e)?XF(qF(e,"utf8")):new Map}function _R(e=Br,t={}){let r=zl(e),n=0,o=0;for(let[s,i]of r){if(!t.override&&process.env[s]!=null){o++;continue}process.env[s]=i,n++}return{path:e,loaded:n,skipped:o}}var Br,ir=p(()=>{"use strict";Br=zF.join(YF(),".kynver",".env")});var xR=p(()=>{"use strict"});var CR=p(()=>{"use strict";xR()});var Xl=p(()=>{"use strict"});import{existsSync as QF,readFileSync as ZF}from"node:fs";import{homedir as e$}from"node:os";import t$ from"node:path";function kf(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function yf(e){return typeof e=="string"&&e.trim()?e:null}function bf(e){let t=kf(e);if(!t)return null;let r=t.desiredState;if(r!=="running"&&r!=="paused"&&r!=="stopped")return null;let n=t.policyVersion;if(typeof n!="number"||!Number.isInteger(n)||n<0)return null;let o=yf(t.requestedAt);return o?{desiredState:r,policyVersion:n,requestedAt:o,requestedByLabel:yf(t.requestedByLabel),reason:yf(t.reason)}:null}function ER(e){let t=kf(kf(e)?.response);return!t||t.runtimeControl===void 0?null:bf(t.runtimeControl)}function AR(e,t=e$()){let r=e.replace(/[^A-Za-z0-9_-]/g,"_");return t$.join(t,".kynver",`runtime-control-${r}.json`)}function vf(e,t,r){try{let n=Wr(e,r);if(n&&n.policyVersion>t.policyVersion)return;ye(AR(e,r),{contractVersion:1,agentOsId:e,control:t,deliveredAt:new Date().toISOString()})}catch{}}function Wr(e,t){try{let r=AR(e,t);if(!QF(r))return null;let n=JSON.parse(ZF(r,"utf8"));return n.agentOsId!==e?null:bf(n.control)}catch{return null}}function Mo(e){return e?.desiredState??"running"}function r$(e){return e==="keeper"||e==="desktop"}function n$(e,t,r=!1){let n=Mo(e);return n==="paused"?"paused":n==="stopped"?r&&t===0?"stopped":"stopping":"running"}function Zl(e){return e.control?{policyVersion:e.control.policyVersion,state:n$(e.control,e.inFlightWorkers,e.exiting),supervised:r$(e.supervisor),inFlightWorkers:Math.max(0,Math.floor(e.inFlightWorkers))}:null}function PR(e){let t=Mo(e);return t==="paused"?"runtime_paused":t==="stopped"?"runtime_stopped":null}function IR(e,t){return Mo(e)==="stopped"&&t===0}function TR(e){OR=e}function NR(){return OR}var Ql,OR,Ur=p(()=>{"use strict";D();Ql=83;OR=null});var ki=p(()=>{"use strict";CR();Xl();Ur()});import{existsSync as o$,readFileSync as s$}from"node:fs";function Rf(){if(process.platform==="win32")return"win32";if(process.platform==="darwin")return"darwin";if(process.platform==="linux"){if(process.env.WSL_DISTRO_NAME?.trim())return"wsl";try{if(o$("/proc/version")){let e=s$("/proc/version","utf8");if(/microsoft/i.test(e))return"wsl"}}catch{}return"linux"}return"linux"}var ec=p(()=>{"use strict"});var wf=p(()=>{"use strict";ec()});var bi=p(()=>{"use strict";ir();nt();H();ki();wf()});import u$ from"node:os";function vi(e,t){let r=(t??u$.hostname()).trim().toLowerCase().replace(/\s+/g,"-")||"unknown-host";return`${e}:${r}`}function MR(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function tc(e,t){let r=e.trim();if(!r)return vi(t);let n=r.indexOf(":");if(n>=0){let o=r.slice(0,n).trim().toLowerCase()||t,s=MR(r.slice(n+1));return s?`${o}:${s}`:vi(o)}return`${t}:${MR(r)}`}function Lo(e){let t=e.explicitBoxId?.trim()||e.env?.KYNVER_BOX_ID?.trim()||e.config?.boxId?.trim();return t?tc(t,e.boxKind):vi(e.boxKind,e.hostLabel)}var Bo=p(()=>{"use strict";De();De()});var LR=p(()=>{"use strict";ir();ki();bi()});import{existsSync as ar,mkdirSync as d$,readdirSync as rc,renameSync as BR,statSync as p$}from"node:fs";import lr from"node:path";function UR(e){try{return p$(e).isDirectory()}catch{return!1}}function f$(e){if(!ar(e))return!0;for(let t of WR){let r=lr.join(e,t);if(ar(r)&&(!UR(r)||rc(r).length>0))return!1}return!0}function m$(e){let t=lr.join(e,"runs");if(!ar(t)||!UR(t))return!1;for(let r of rc(t,{withFileTypes:!0})){if(!r.isDirectory()||r.name==="runs")continue;let n=lr.join(t,r.name,"run.json");if($(n,void 0)?.id)return!0}return!1}function g$(e){let t=lr.join(e,"runs");if(!ar(t))return!1;for(let r of rc(t,{withFileTypes:!0})){if(!r.isDirectory())continue;if($(lr.join(t,r.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function h$(e){let t=lr.join(e,"ghost");return ar(t)?!ar(lr.join(t,"runs")):g$(e)}function FR(e){return m$(e.sharedRoot)?f$(e.forgeRoot)?h$(e.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function $R(e,t){d$(t,{recursive:!0});for(let r of WR){let n=lr.join(e,r),o=lr.join(t,r);if(ar(n)){if(ar(o)&&rc(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(ar(o)){BR(n,o);continue}BR(n,o)}}}var WR,KR=p(()=>{"use strict";D();WR=["runs","worktrees"]});import{existsSync as Be}from"node:fs";import{homedir as y$}from"node:os";import Ae from"node:path";function Sf(e=process.env){return e.HOME?.trim()||y$()}function _f(e=process.env){return Ae.join(Sf(e),".kynver","harness")}function nc(e){let t=Ae.resolve(Ne(e.trim()));for(;k$.has(Ae.basename(t));)t=Ae.dirname(t);return t}function b$(e,t=process.env){return Ae.join(_f(t),e)}function v$(e=process.env){let t=_f(e);if(Be(Ae.join(t,"runs")))return!0;if(Be(t)&&!Be(Ae.join(t,"ghost"))&&!Be(Ae.join(t,"forge")))return Be(t);let r=Ae.join(Sf(e),HR);return Be(r)}function oc(e){let t=e.env??process.env,r=t.KYNVER_HARNESS_ROOT?.trim()||t.OPUS_HARNESS_ROOT?.trim();if(r)return{harnessRoot:nc(r),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:nc(n),source:"config"};let o=b$(e.boxKind,t);if(Be(Ae.join(o,"runs"))||Be(o)&&!R$(o))return{harnessRoot:o,source:"box_scoped"};let i=_f(t);if(e.boxKind==="forge"){let a=FR({sharedRoot:i,forgeRoot:o});if(a.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:a.blocker};if(a.action==="migrate")return e.allowForgeLegacyMigration!==!1&&$R(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&v$(t)){if(Be(Ae.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(Be(i)&&!Be(Ae.join(i,"ghost"))&&!Be(Ae.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let l=Ae.join(Sf(t),HR);if(Be(l))return{harnessRoot:l,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function R$(e){if(!Be(e))return!0;for(let t of["runs","worktrees"]){let r=Ae.join(e,t);if(Be(r))return!1}return!0}var HR,k$,xf=p(()=>{"use strict";nt();KR();HR=Ae.join(".openclaw","harness");k$=new Set(["runs","worktrees"])});import jR from"node:os";function sc(e){return e?.trim()?e.trim():null}function w$(e,t){let r=t.trim().toLowerCase()||"host";return`${e}-${r}`.replace(/[^a-z0-9._-]+/g,"-")}function S$(e){return e.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||e.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||e.KYNVER_DAEMON_STRICT_IDENTITY==="1"||e.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function Nt(e=E(),t=process.env,r={}){let n=Qe(t,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||sc(t.KYNVER_BOX_KIND)),a=r.strict===!0||S$(t);if((r.requireExplicitBoxKind||a)&&!i&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup` (customers: boxKind=box) or `kynver setup --box-kind forge|ghost` for operator pools before dispatch"),n.slugInferenceBlocked&&!i){let h="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";a||r.requireExplicitBoxKind?s.push(h):o.push(`${h} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let l=sc(e.runnerId),c=sc(t.KYNVER_RUNTIME_ID)??sc(t.OPENCLAW_RUNTIME_ID),u=l??c??w$(n.boxKind,jR.hostname()),d=l?"config":c?"env":"derived";d==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${u}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let m=Do({config:e,env:t,totalMemBytes:jR.totalmem()}),f=or(n.boxKind,m.configuredMaxWorkers??Zp(n.boxKind,m.autoCap)),g=oc({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:t});return g.migrationBlocker&&s.push(g.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:u,runnerIdSource:d,maxConcurrentWorkers:f,workerCapSource:m.workerCapSource,harnessRoot:g.harnessRoot,harnessRootSource:g.source},errors:s,warnings:o}}var hn=p(()=>{"use strict";H();De();So();hi();xf()});var Cf=p(()=>{"use strict";oi();De();Bo();H();bi();LR();nr();bt();hn()});function Ke(e){let t=e.trim().toLowerCase();return x$[t]??t}var JR,_$,x$,Ri=p(()=>{"use strict";JR=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],_$=JR.join("|"),x$={anthropic:"claude",opus:"claude",openai:"openai-compatible",openai_compatible:"openai-compatible","openai-compat":"openai-compatible",chatgpt:"codex",gpt:"codex","openai-api":"openai-compatible",openai_api:"openai-compatible",google:"gemini",gemini_cli:"gemini",gemini_api:"gemini-api","google-api":"gemini-api",google_api:"gemini-api"}});import{mkdirSync as YR}from"node:fs";import{homedir as zR}from"node:os";import ic from"node:path";function Wo(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return XR.includes(t)?t:null}function yn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(typeof r!="string"||!r.trim()||r.includes("\0"))continue;let n=Ne(r.trim());if(t.includes(n)||t.push(n),t.length>=E$)break}return t}function ac(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e.others==="default"?"default":null,n=e.byBox;if(!n||typeof n!="object"||Array.isArray(n)||!Object.prototype.hasOwnProperty.call(n,t))return r;let o=n[t];if(!o||typeof o!="object")return null;let s=o,i=Wo(s.access);return i?{access:i,folders:yn(s.folders)}:null}function wi(e){return C$.has(e)?"folder":"off"}function qR(e=zR()){let t=ic.join(e,".kynver",QR);return YR(t,{recursive:!0}),t}function Uo(e){let t=e.home??zR(),r=Wo(e.local?.chatComputerAccess),n,o;r==="off"?(n={access:"off",folders:[]},o="local_off"):e.website==="default"?(n={access:wi(e.engine),folders:[]},o="default"):e.website?(n=e.website,o="website"):r?(n={access:r,folders:yn(e.local?.chatWorkFolders)},o="local"):(n={access:wi(e.engine),folders:[]},o="default");let{access:s}=n;if(s==="off")return{access:s,folders:[],workDir:qR(t),extraFolders:[],source:o};let i=n.folders;s==="folder"&&(i=i.slice(0,1)),i.length===0&&s!=="full"&&(i=[qR(t)]);for(let l of i)try{YR(l,{recursive:!0})}catch{}let a=i[0]??t;return{access:s,folders:i,workDir:a,extraFolders:s==="folders"?i.slice(1):[],source:o}}function lc(e,t){if(e.access==="off")return!1;if(e.access==="full")return!0;let r=ic.resolve(t);return e.folders.some(n=>{let o=ic.relative(n,r);return o===""||!o.startsWith("..")&&!ic.isAbsolute(o)})}var XR,C$,E$,QR,kn=p(()=>{"use strict";nt();XR=["off","folder","folders","full"],C$=new Set(["cursor","codex","antigravity"]),E$=16,QR="chat-workspace"});var ZR=p(()=>{"use strict";kn()});import{execFileSync as A$}from"node:child_process";function Pf(e=process.env){let t=e[P$]?.trim().toLowerCase();return t==="file"?"file":t==="keychain"?"keychain":"auto"}function I$(e,t,r){let n={encoding:"utf8",timeout:r.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...r.input!==void 0?{input:r.input}:{}};return A$(e,t,n)}function O$(e=process.platform){return e==="darwin"?"macos":e==="linux"?"libsecret":e==="win32"?"windows":null}function Ef(e,t){let r=JSON.stringify(bn),n=JSON.stringify(t),o="[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]; $v = New-Object Windows.Security.Credentials.PasswordVault;";return e==="get"?`${o} try { $c = $v.Retrieve(${r}, ${n}); $c.RetrievePassword(); [Console]::Out.Write($c.Password) } catch { exit 3 }`:e==="set"?`${o} $s = [Console]::In.ReadToEnd().TrimEnd("\`r","\`n"); try { $old = $v.Retrieve(${r}, ${n}); $v.Remove($old) } catch {}; $v.Add((New-Object Windows.Security.Credentials.PasswordCredential(${r}, ${n}, $s)))`:`${o} try { $old = $v.Retrieve(${r}, ${n}); $v.Remove($old) } catch {}`}function ew(e={}){if(Pf(e.env??process.env)==="file")return null;let r=O$(e.platform??process.platform);return r?new Af(r,e.exec):null}var bn,P$,cr,Af,tw=p(()=>{"use strict";bn="kynver",P$="KYNVER_CREDENTIAL_STORE";cr=5e3;Af=class{constructor(t,r=I$){this.backend=t;this.exec=r}backend;exec;get(t){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",bn,"-a",t,"-w"],{timeoutMs:cr}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",bn,"account",t],{timeoutMs:cr}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",Ef("get",t)],{timeoutMs:cr}).replace(/\r?\n$/,"");return n||null}catch{return null}}set(t,r){if(!r||/[\r\n]/.test(r))return!1;try{this.backend==="macos"?this.exec("security",["add-generic-password","-U","-s",bn,"-a",t,"-l",`Kynver (${t})`,"-w",r],{timeoutMs:cr}):this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${t})`,"service",bn,"account",t],{input:`${r}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
`,{mode:384})}function lw(e,t,r,n={}){let o=ur();if(Ko().write(e,r)){let i={...o,...n};delete i[t],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],e])).sort(),Si(i);return}Si({...o,...n,[t]:r})}function cw(e,t){let r=Ko().read(e);return r||ur()[t]}function uw(){if(ze())return{backend:null,moved:[],stillInFile:[]};let e=Ko(),t=ur(),r=[],n=[],o=[[Fo,"apiKey"],[$o,"chatBoxCredential"]];for(let[s,i]of o){let a=t[i];a&&(e.available&&e.write(s,a)?r.push(i):n.push(i))}if(r.length>0){let s={...ur()};for(let i of r)delete s[i];s.store="keychain",s.keychainAccounts=Array.from(new Set([...s.keychainAccounts??[],...r.map(i=>i==="apiKey"?Fo:$o)])).sort(),Si(s)}return{backend:e.backend,moved:r,stillInFile:n}}function Bf(){return sv(W$)}function Pe(){return Bf().getApiKey()}function He(e){return Bf().getRunnerToken(e)}function vn(e,t){Bf().persistRunnerToken(e,t)}function Wf(e){let t=Ce("KYNVER_CHAT_BOX_CREDENTIAL");if(t)return t;if(ze())return uc?.agentOsId===e?uc.credential:void 0;let r=ur();if(!(r.chatBoxCredentialAgentOsId&&r.chatBoxCredentialAgentOsId!==e))return cw($o,"chatBoxCredential")}function dw(e,t){if(ze()){uc={agentOsId:e,credential:t};return}lw($o,"chatBoxCredential",t,{chatBoxCredentialAgentOsId:e})}function pw(){if(ze()){uc=null;return}Ko().remove($o);let e={...ur()};delete e.chatBoxCredential,delete e.chatBoxCredentialAgentOsId,Si(e)}function fw(){let e=Ko();return process.env.KYNVER_API_KEY?{backend:e.backend,apiKey:"env"}:e.read(Fo)?{backend:e.backend,apiKey:"keychain"}:ur().apiKey?{backend:e.backend,apiKey:"file"}:{backend:e.backend,apiKey:"none"}}function pe(e){let t=_i(e);return t||hw("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),t}function Rn(e){return _i(e)}function _i(e){let t=e||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||E().apiBaseUrl;return rr(t)}function U$(e,t){let r=e||He(t)||(t?void 0:He(E().agentOsId));if(r)return String(r);let n=Ce("KYNVER_RUNTIME_SECRET")||Ce("KYNVER_CRON_SECRET")||Ce("OPENCLAW_CRON_SECRET");if(n)return console.warn("[kynver] using deployment-level callback secret; run `kynver runner credential --agent-os-id <id>` for a scoped token"),String(n)}async function pc(e,t,r){let n=U$(e,t);if(n)return{ok:!0,secret:n};let o=Pe(),s=_i(r?.baseUrl);if(o&&t&&s)try{let i=await wn(t,{baseUrl:s,apiKey:o});return vn(t,i),{ok:!0,secret:i}}catch(i){return{ok:!1,reason:`runner credential mint failed: ${i.message}`}}return{ok:!1,reason:"no runner credential: requires --secret, KYNVER_RUNNER_TOKEN, a scoped runner token (`kynver runner credential`), ~/.kynver/credentials runnerToken, or KYNVER_API_KEY + API base URL to mint one"}}async function fe(e,t,r){let n=await pc(e,t,r);if(n.ok)return n.secret;hw(n.reason)}async function mw(e,t){let r=Pe(),n=_i(t?.baseUrl);if(!r||!e||!n)return null;try{let o=await wn(e,{baseUrl:n,apiKey:r});return vn(e,o),o}catch{return null}}async function gw(e,t,r){let n=Pe(),o=_i(r?.baseUrl);if(!n)return{ok:!1,reason:"KYNVER_API_KEY is required to refresh a rejected runner token"};if(!t)return{ok:!1,reason:"agentOsId is required to refresh a rejected runner token"};if(!o)return{ok:!1,reason:"KYNVER_API_URL or --base-url is required to refresh a rejected runner token"};try{let s=await wn(t,{baseUrl:o,apiKey:n});return s&&s!==e?(vn(t,s),{ok:!0,token:s}):{ok:!1,reason:"runner credential refresh returned the rejected token"}}catch(s){return{ok:!1,reason:s.message}}}async function wn(e,t){let r=t?.apiKey||Pe();if(!r)throw new Error("API key required \u2014 run `kynver login` first");let o=`${pe(t?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(e)}/runner-credentials`,s=await it(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(t?.enableMcpUpdates?{enableMcpUpdates:!0}:{})}),i=await s.text(),a=null;try{a=JSON.parse(i)}catch{a=null}if(!s.ok||!a?.token)throw new Error(`runner credential mint failed (${s.status}): ${a?.error??i.slice(0,200)}`);return a.token}function hw(e){console.error(e),process.exit(1)}var dc,Tf,Nf,L$,B$,Hse,jse,W$,uc,H=p(()=>{"use strict";oi();nt();nr();De();So();hi();ai();bi();Cf();Ri();hn();ZR();bt();rw();dc=Df.join(M$(),".kynver"),Tf=Df.join(dc,"config.json"),Nf=Df.join(dc,"credentials"),L$=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,B$=new Set(["aos","aos-1","agent-os-id","agentosid","agent_os_id","<agent-os-id>","<agentosid>","todo","changeme","change-me","placeholder"]);Hse=500*1024*1024,jse=4*1024*1024*1024;W$={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:cw(Fo,"apiKey")},getRunnerToken(e){let t=ur();if(!!t.runnerToken&&!!e&&t.runnerTokenAgentOsId===e)return t.runnerToken;let n=process.env.KYNVER_RUNNER_TOKEN?.trim();if(n)return n;if(t.runnerToken&&!(e&&t.runnerTokenAgentOsId&&t.runnerTokenAgentOsId!==e))return t.runnerToken},persistApiKey(e){lw(Fo,"apiKey",e)},persistRunnerToken(e,t){Si({...ur(),runnerToken:t,runnerTokenAgentOsId:e})}};uc=null});import Uf from"node:path";function Ie(e){return nc(e)}function at(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return Ie(e);let t=E(),r=t.harnessRoot?.trim();if(r)return Ie(r);let n=Nt(t,process.env);return n.identity?n.identity.harnessRoot:oc({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function Ze(e){return Uf.join(Ie(e),"runs")}function jo(e){return Uf.join(Ie(e),"worktrees")}function yw(){let e=at();return{harnessRoot:e,runsDir:Ze(e),worktreesDir:jo(e)}}function dr(e,t){return Uf.join(e,B(t))}var St=p(()=>{"use strict";H();xf();hn();D()});import{existsSync as fc,readdirSync as F$,statSync as $$}from"node:fs";import Sn from"node:path";function me(){return yw()}function ae(e){let{runsDir:t}=me(),r=Sn.join(dr(t,B(e)),"run.json");return fc(r)||ot(`run '${e}' not found`),$(r)}function Re(){let{runsDir:e}=me();return kw(e)}function mc(e){return kw(Ze(e))}function K$(e){try{return $$(e).isDirectory()}catch{return!1}}function kw(e){if(!fc(e))return[];let t=[];for(let r of F$(e,{withFileTypes:!0})){if(r.name==="runs")continue;let n=Sn.join(e,r.name);if(!K$(n))continue;let o=$(Sn.join(n,"run.json"),void 0);o?.id&&t.push(o)}return t}function _n(e,t){let{runsDir:r}=me(),n=Sn.join(dr(r,B(e)),"run.json"),o=Sn.join(dr(r,B(e)),"workers",B(t),"worker.json");return fc(o)||(fc(n)||ot(`run '${e}' not found`),ot(`worker '${t}' not found in run '${e}'`)),$(o)}function je(e){let{runsDir:t}=me();ye(Sn.join(dr(t,e.id),"run.json"),e)}function ee(e,t){let{runsDir:r}=me();ye(Sn.join(dr(r,e),"workers",t.name,"worker.json"),t)}function G(e){let{harnessRoot:t}=me();return xi(t,e)}function xi(e,t){return dr(Ze(e),B(t))}var z=p(()=>{"use strict";St();D()});import H$ from"node:path";function j$(e){let t=Array.isArray(e.ownedPaths)?e.ownedPaths.filter(n=>typeof n=="string"):[],r=Array.isArray(e.writeSetPrefixes)?(e.writeSetPrefixes??[]).filter(n=>typeof n=="string"):[];return{...t.length?{ownedPaths:t}:{},...r.length?{writeSetPrefixes:r}:{},...e.allowConcurrentHotspot?{allowConcurrentHotspot:!0}:{}}}function Vo(e){let t=ae(e),r=[];for(let n of Object.keys(t.workers||{})){let o=$(H$.join(G(t.id),"workers",B(n),"worker.json"),void 0);!o?.taskId||!Lr(o)||r.push({runId:t.id,workerName:n,taskId:o.taskId,pid:o.pid,...j$(o)})}return r}var gc=p(()=>{"use strict";z();Vl();D()});function Ff(e){return typeof e=="object"&&e!==null&&e.type===hc}function bw(e,t=process){let r=!1,n=a=>{r||(r=!0,e(a))},s=["SIGINT","SIGTERM","SIGBREAK","SIGHUP"].map(a=>{let l=()=>n(a);return t.on(a,l),[a,l]}),i=a=>{Ff(a)&&n("ipc")};return t.on("message",i),t.channel?.unref?.(),()=>{for(let[a,l]of s)t.off(a,l);t.off("message",i)}}function vw(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return[];let n=t.collect??Vo,o=t.killTree??Se,s;try{s=n(e)}catch{return[]}let i=[];for(let a of s)a.pid&&i.push({workerName:a.workerName,pid:a.pid,result:o(a.pid,"SIGKILL")});return i}var hc,yc=p(()=>{"use strict";gc();Zs();hc="kynver:daemon-stop"});import{createHash as V$}from"node:crypto";function et(e){return JSON.stringify($f(e))}function $f(e){if(Array.isArray(e))return e.map($f);if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=$f(e[r]);return t}return e}function Rw(e){return`ib-${V$("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function Go(e){if(!e)return null;let t=e.trim();if(!t)return null;if(/^[0-9a-fA-F]{64}$/.test(t))return new Uint8Array(t.match(/.{2}/g).map(r=>parseInt(r,16)));try{let r=Buffer.from(t,"base64");if(r.length===32)return new Uint8Array(r)}catch{}return null}function Ci(e){if(!e||typeof e!="object")return!1;let t=e;if(typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let r=t.bundle;return!(!r||typeof r!="object"||typeof r.version!="string"||!r.version||typeof r.generatedAt!="string"||!Array.isArray(r.personas)||!r.instructions||typeof r.instructions!="object"||!r.policyThresholds||typeof r.policyThresholds!="object")}function kc(e=process.env){if(e.NODE_ENV==="production")return!1;let t=e.KYNVER_ALLOW_DEV_SIGNING_KEYS?.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"?!0:e.NODE_ENV==="test"||e.VITEST==="true"}var Fr=p(()=>{"use strict"});import{createHash as G$,createPublicKey as J$,verify as q$}from"node:crypto";function X$(e){return`ca-${G$("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function xn(e,t=process.env){let r=Go(t.KYNVER_COMMAND_AUTH_PUBLIC_KEY);if(r)return X$(r)!==e?null:r;let n=z$[e];return!n||e===ww&&!kc(t)?null:Go(n)}function Q$(e){return J$({key:Buffer.concat([Y$,Buffer.from(e)]),format:"der",type:"spki"})}function Z$(e,t){return!Array.isArray(e)||e.length!==t.length?!1:e.every((r,n)=>typeof r=="string"&&r===t[n])}function eK(e){if(!e||typeof e!="object")return!1;let t=e;if(typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let r=t.payload;return!(!r||typeof r!="object"||r.v!==1||typeof r.agentOsId!="string"||!r.agentOsId||!Array.isArray(r.argv)||r.argv.some(n=>typeof n!="string")||typeof r.userId!="string"||!r.userId||typeof r.exp!="number"||!Number.isFinite(r.exp)||typeof r.nonce!="string"||!r.nonce)}function Sw(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!eK(e))return{ok:!1,reason:"malformed command authorization proof"};if(e.payload.agentOsId!==t.agentOsId)return{ok:!1,reason:"agentOsId mismatch"};if(!Z$(e.payload.argv,t.argv))return{ok:!1,reason:"argv mismatch"};if(e.payload.exp<=n)return{ok:!1,reason:"proof expired"};let o=xn(e.publicKeyId,r);if(!o)return{ok:!1,reason:`no verification key for publicKeyId "${e.publicKeyId}"`};let s;try{s=Buffer.from(e.signature,"base64url")}catch{return{ok:!1,reason:"signature is not base64url"}}if(s.length!==64)return{ok:!1,reason:"signature is not a 64-byte Ed25519 signature"};try{let i=Buffer.from(et(e.payload),"utf8");return q$(null,i,Q$(o),s)?{ok:!0,payload:e.payload}:{ok:!1,reason:"Ed25519 signature mismatch"}}catch(i){return{ok:!1,reason:`signature verification failed: ${i.message}`}}}var Y$,ww,z$,Ei=p(()=>{"use strict";Fr();Y$=Buffer.from("302a300506032b6570032100","hex"),ww="ca-6297fb8e1773",z$={[ww]:"16ae5cb2a61f8c94cf1b86e8258f9c2f2ff6aba5e6136250a422209b6e866881","ca-456fd128f3b3":"f29cbd559410c2578d7f9732ccd86570073355ccdb36af0d1b7dff15908466e7"}});function bc(e){let t=typeof e.description=="string"?e.description:"",r=typeof e.executorRef=="string"?e.executorRef:"",o=[...t.matchAll(tK)].at(-1)?.[1]?.toLowerCase();if(o)return o==="write"?"write":"read_only";if(/(?:^|:)read[_-]?only(?:$|:)/i.test(r))return"read_only";for(let s of t.matchAll(rK))try{let i=JSON.parse(s[1]);if(i.readOnly===!0||i.executionMode==="read_only")return"read_only"}catch{}return"write"}var tK,rK,Kf=p(()=>{"use strict";tK=/\[execution-mode:\s*(write|read[_-]?only)\s*\]/gi,rK=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/gi});import{createPublicKey as nK,verify as oK}from"node:crypto";function Hf(e){let t=e.trim();if(!t||t.includes("\0")||/\s/.test(t))return null;let r,n,o=/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.+)$/.exec(t);if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)){let a;try{a=new URL(t)}catch{return null}if(!["https:","http:","ssh:","git:","git+ssh:","ssh+git:"].includes(a.protocol))return null;r=a.port?`${a.hostname}:${a.port}`:a.hostname,n=decodeURIComponent(a.pathname)}else if(o&&!/^[A-Za-z]$/.test(o[1]))r=o[1],n=o[2];else return null;r=r.toLowerCase().replace(/\.$/,"");let s=n.replace(/\/+$/,"").replace(/\.git$/i,"").split("/").filter(Boolean);if(s.length<2||s.some(a=>a==="."||a===".."))return null;let i=`${r}/${s.join("/")}`;return aK.test(i)&&i.length<=512?i:null}function _w(e){let t=e.task??{};return e.landPrDispatch===!0||t.executor==="land_pr"?"land_pr":t.executor==="verify_live"?"verify_live":bc(t)==="read_only"?"read_only":"write"}function lK(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(Object.keys(t).sort().join(",")!=="payload,publicKeyId,signature"||typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let r=t.payload;if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).sort().join(",")!==[...iK].join(",")||r.v!==1||r.kind!=="dispatch_claim")return!1;for(let n of["tenantId","agentOsId","taskId","leaseOwner","leaseToken","repoIdentity","requestNonce"])if(typeof r[n]!="string"||!r[n])return!1;return!(typeof r.attempt!="number"||!Number.isInteger(r.attempt)||r.attempt<0||typeof r.exp!="number"||!Number.isFinite(r.exp)||!vc.includes(r.operationClass))}function xw(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!lK(e))return{ok:!1,code:"malformed",reason:"malformed dispatch claim authorization"};let o=e.payload;for(let a of Object.keys(t))if(o[a]!==t[a])return{ok:!1,code:"binding_mismatch",reason:`${a} mismatch`};if(o.exp<=n)return{ok:!1,code:"expired",reason:"authorization expired"};if(o.exp>n+sK+60)return{ok:!1,code:"malformed",reason:"authorization lifetime exceeds the allowed window"};let s=xn(e.publicKeyId,r);if(!s)return{ok:!1,code:"unknown_key",reason:`no verification key for publicKeyId "${e.publicKeyId}"`};let i=Buffer.from(e.signature,"base64url");if(i.length!==64)return{ok:!1,code:"bad_signature",reason:"not a 64-byte Ed25519 signature"};try{let a=nK({key:Buffer.concat([cK,Buffer.from(s)]),format:"der",type:"spki"});return oK(null,Buffer.from(et(o),"utf8"),a,i)?{ok:!0,payload:o}:{ok:!1,code:"bad_signature",reason:"Ed25519 signature mismatch"}}catch(a){return{ok:!1,code:"bad_signature",reason:`signature verification failed: ${a.message}`}}}var sK,vc,iK,aK,cK,Cw=p(()=>{"use strict";Ei();Fr();Kf();sK=120,vc=["write","read_only","land_pr","verify_live"],iK=["agentOsId","attempt","exp","kind","leaseOwner","leaseToken","operationClass","repoIdentity","requestNonce","taskId","tenantId","v"],aK=/^[a-z0-9.-]+(?::\d+)?(?:\/[A-Za-z0-9._~-]+){2,}$/;cK=Buffer.from("302a300506032b6570032100","hex")});import{spawnSync as uK}from"node:child_process";import{randomBytes as dK}from"node:crypto";function Ew(e){if(!e||typeof e!="object"||Array.isArray(e))return"policy must be an object";let t=e;if(Object.keys(t).sort().join(",")!=="accountId,agentOsId,approvedOperationClasses,repoIdentity,revision,v")return"unexpected policy fields";if(t.v!==pK)return"unsupported policy version";if(typeof t.revision!="number"||!Number.isSafeInteger(t.revision)||t.revision<1)return"invalid revision";if(typeof t.accountId!="string"||!t.accountId||t.accountId.length>128)return"invalid accountId";if(typeof t.agentOsId!="string"||!fK.test(t.agentOsId))return"invalid agentOsId";if(typeof t.repoIdentity!="string"||Hf(`https://${t.repoIdentity}`)!==t.repoIdentity)return"invalid repoIdentity";let n=t.approvedOperationClasses;if(!Array.isArray(n)||n.length>vc.length)return"invalid approvedOperationClasses";let o=new Set;for(let s of n){if(typeof s!="string"||!vc.includes(s)||o.has(s))return"invalid approvedOperationClasses";o.add(s)}return{v:1,revision:t.revision,accountId:t.accountId,agentOsId:t.agentOsId,repoIdentity:t.repoIdentity,approvedOperationClasses:[...n]}}function mK(e){let t=(c,u)=>({allow:!1,code:c,reason:u}),{policy:r,identity:n}=e;if(!n)return t("no_identity","the desktop runtime has not been prepared");if(!r)return t("no_policy","no approved execution policy on this computer");if(r.accountId!==n.accountId||r.agentOsId!==n.agentOsId)return t("policy_mismatch","the approved policy is for another account or workspace");if(!e.repoIdentity)return t("repo_identity_unavailable","the repository has no canonical remote identity");if(r.repoIdentity!==e.repoIdentity)return t("policy_mismatch","the approved policy is for another repository");let o=e.decision.claimAuthorization;if(o==null||!e.requestNonce)return t("missing_authorization","the claim carries no server authorization; the Kynver server must sign Desktop claims (KYNVER_COMMAND_AUTH_KEY, dispatch-claim-authorization diagnostic) and this runtime must be 0.2.87 or newer");let s=e.decision.task??{},i=_w(e.decision),a=xw(o,{tenantId:n.accountId,agentOsId:n.agentOsId,taskId:typeof s.id=="string"?s.id:"",attempt:typeof s.attempt=="number"?s.attempt:-1,leaseOwner:e.leaseOwner,leaseToken:typeof s.leaseToken=="string"?s.leaseToken:"",operationClass:i,repoIdentity:e.repoIdentity,requestNonce:e.requestNonce},e.env??process.env,e.nowSec);if(!a.ok)return t(a.code,a.reason);let l=a.payload;return e.consumed.consume(`${l.taskId}\0${l.leaseToken}\0${l.requestNonce}`)?r.approvedOperationClasses.includes(i)?{allow:!0,operationClass:i}:{allow:!1,code:"operation_not_approved",reason:`${i} work in ${r.repoIdentity} has not been approved on this computer`,consentRequired:{repoIdentity:r.repoIdentity,operationClass:i}}:t("replayed","this claim authorization was already used")}function Pw(){return ze()}function Iw(e){return Ai&&e.revision<Ai.revision?!1:(Ai=e,!0)}function Gf(){return Ai}function Ow(e){Aw=e}function Tw(e){return Vf.add(e),()=>Vf.delete(e)}function Nw(e){return{v:1,repoIdentity:e,requestNonce:dK(16).toString("base64url")}}function Rc(e){let t=uK("git",["-C",e,"remote","get-url","origin"],X({encoding:"utf8",timeout:1e4}));return t.status!==0||typeof t.stdout!="string"?null:Hf(t.stdout.trim())}function Dw(e){let t=mK({...e,policy:Ai,identity:Aw,consumed:gK});if(!t.allow){let r=e.decision.task??{},n={taskId:typeof r.id=="string"?r.id:"",code:t.code,reason:t.reason,...t.consentRequired?{consentRequired:t.consentRequired}:{}};for(let o of Vf)try{o(n)}catch{}}return t}var pK,fK,jf,Ai,Aw,gK,Vf,wc=p(()=>{"use strict";bt();Cw();D();pK=1,fK=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;jf=class{constructor(t=4096){this.capacity=t}capacity;order=[];keys=new Set;consume(t){if(this.keys.has(t))return!1;for(this.keys.add(t),this.order.push(t);this.order.length>this.capacity;)this.keys.delete(this.order.shift());return!0}};Ai=null,Aw=null,gK=new jf,Vf=new Set});import{createCipheriv as hK,createDecipheriv as yK,randomBytes as qf,scrypt as kK,timingSafeEqual as bK}from"node:crypto";function Lw(){return qf(Yf)}function Bw(e=vK){return{name:"scrypt",N:e.N,r:e.r,p:e.p,salt:qf(16).toString("base64")}}function Xf(e,t,r=RK){if(t.name!=="scrypt"||!Number.isInteger(t.N)||t.N<r||t.r<8||t.p<1)return Promise.reject(new _t("the vault file asks for an unsafe key-derivation setting; refusing"));let n=Buffer.from(t.salt,"base64");return n.length<16?Promise.reject(new _t("the vault file's salt is invalid")):new Promise((o,s)=>{kK(e.normalize("NFKC"),n,Yf,{N:t.N,r:t.r,p:t.p,maxmem:128*t.N*t.r*2},(i,a)=>i?s(i):o(a))})}function Pi(e,t,r){if(e.length!==Yf)throw new _t("bad key length");let n=qf(Mw),o=hK("aes-256-gcm",e,n);o.setAAD(Buffer.from(r,"utf8"));let s=Buffer.concat([o.update(t),o.final(),o.getAuthTag()]);return{n:n.toString("base64"),c:s.toString("base64")}}function Sc(e,t,r){try{let n=Buffer.from(t.n,"base64"),o=Buffer.from(t.c,"base64");if(n.length!==Mw||o.length<Jf)throw new _t;let s=yK("aes-256-gcm",e,n);return s.setAAD(Buffer.from(r,"utf8")),s.setAuthTag(o.subarray(o.length-Jf)),Buffer.concat([s.update(o.subarray(0,o.length-Jf)),s.final()])}catch(n){throw n instanceof _t?n:new _t}}function Qf(e){for(let t of e)if(t.includes(`
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
4
|
+
`):""}function Ll(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Bl(e){return new Promise(t=>setTimeout(t,e))}function re(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Gv(e){let t=null,r=-1/0;for(let n of e){if(!n)continue;let o=Date.parse(n);Number.isFinite(o)&&o>r&&(r=o,t=n)}return t}function mf(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var M=p(()=>{"use strict";ci()});function dF(e){let t=e[yf];return t?new Set(t.split(/[\s,]+/).map(r=>r.trim()).filter(Boolean)):new Set}function pF(e,t={}){return aF.has(e)?!0:cF.has(e)||t.operatorAllow?.has(e)||uF.some(r=>e.endsWith(r))?!1:lF.some(r=>e.endsWith(r))}function di(e){let t=dF(e),r={...e};for(let n of Object.keys(r))pF(n,{operatorAllow:t})&&delete r[n];return r}var gf,aF,lF,hf,cF,uF,yf,pi=p(()=>{"use strict";gf=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],aF=new Set(gf),lF=["_SECRET","_API_KEY","_KEK","_KEY","_TOKEN","_PASSWORD","_PASSPHRASE","_SALT"],hf=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],cF=new Set(hf),uF=["_PUBLIC_KEY"],yf="KYNVER_WORKER_ENV_ALLOW"});import{existsSync as fF,statSync as mF}from"node:fs";import{spawnSync as qv}from"node:child_process";function ce(e,t,r={}){let n=qv("git",t,z({cwd:e,encoding:"utf8"}));if(n.status!==0&&!r.allowFailure){let o=gF(e,t,n);if(r.throwError)throw new Error(o);lt(o)}return n.stdout||""}function gF(e,t,r){let n=typeof r.stderr=="string"&&r.stderr.trim()||typeof r.stdout=="string"&&r.stdout.trim()||r.error?.message||`exit ${r.status??"unknown"}`;return`git ${t.join(" ")} failed in ${e}: ${n}`}function hF(e){let t=e.trim();if(!t)return"git repo path is empty";let r=Me(t);if(!fF(r))return r===t?`git repo path does not exist: ${r}`:`git repo path does not exist: ${r} (from ${t})`;try{if(!mF(r).isDirectory())return`git repo path is not a directory: ${r}`}catch(n){return`git repo path is not readable: ${r} (${n.message})`}return null}function Yv(e){let t=hF(e);t&<(t),ce(Me(e.trim()),["rev-parse","--show-toplevel"])}function fi(e){return ce(e,["status","--short"],{allowFailure:!0}).split(`
|
|
5
|
+
`).map(t=>t.trim()).filter(Boolean)}function ee(e,t){try{let r=qv("git",t,z({cwd:e,encoding:"utf8"}));return{status:r.status,stdout:r.stdout||"",stderr:r.stderr||"",error:r.error?r.error.message:null}}catch(r){return{status:null,stdout:"",stderr:"",error:r.message}}}function Jv(e,t,r){let n=ee(e,["merge-base","--is-ancestor",t,r]);return n.status===0?{isAncestor:!0,error:null}:n.status===1?{isAncestor:!1,error:null}:{isAncestor:null,error:n.error||n.stderr||n.stdout||`git exited ${n.status}`}}function Wl(e,t="origin/main"){let r=typeof t=="string"?{base:t}:t,n=r.baseCommit?.trim()||r.base?.trim()||"origin/main",o=r.baseCommit?.trim()||null;if(!e)return Ao(n,"missing worktree path");let s=ee(e,["rev-parse","HEAD"]);if(s.status!==0)return Ao(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let f=ee(e,["rev-parse",n]);if(f.status!==0)return Ao(n,f.error||f.stderr||f.stdout||`failed to resolve ${n}`,s.stdout.trim());i=f.stdout.trim()}let a=s.stdout.trim();if(a===i)return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let l=Jv(e,i,a),c=Jv(e,a,i),u=l.error||c.error||void 0;if(l.isAncestor==null||c.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:"unknown",...u?{error:u}:{}};let d=l.isAncestor?"ahead":c.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:d,...u?{error:u}:{}}}function Ao(e,t,r=null){return{checked:!1,base:e,head:r,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:t}}var we=p(()=>{"use strict";at();M();pi()});import{existsSync as yF,mkdirSync as zv}from"node:fs";import{homedir as kf}from"node:os";import Po from"node:path";function Qv(e=kf()){return Po.join(e,".kynver",kF)}function Zv(e,t=kf()){return Po.resolve(e)===Po.resolve(Qv(t))}function bF(e){ee(e,["config","--get","user.email"]).status!==0&&ee(e,["config","user.email","kynver@local"]),ee(e,["config","--get","user.name"]).status!==0&&ee(e,["config","user.name","Kynver"])}function Xv(e){ee(e,["rev-parse","--verify","HEAD^{commit}"]).status!==0&&(bF(e),ee(e,["commit","--allow-empty","-m","kynver byoc workspace"]))}function eR(e=kf()){let t=Qv(e);zv(Po.dirname(t),{recursive:!0});let r=!1;yF(t)||(zv(t,{recursive:!0}),r=!0);let n=ee(t,["rev-parse","--show-toplevel"]);if(n.status!==0)return ee(t,["init","-b","main"]),Xv(t),r=!0,{repo:Po.resolve(t),created:r};let o=Po.resolve(n.stdout.trim()||t);return Xv(o),{repo:o,created:r}}var kF,bf=p(()=>{"use strict";we();kF="workspace"});import{existsSync as Rf,readFileSync as rR}from"node:fs";import{homedir as nR}from"node:os";import ct from"node:path";import{fileURLToPath as vF}from"node:url";function wF(e){let t=ct.join(e,"package.json");if(!Rf(t))return null;try{let r=JSON.parse(rR(t,"utf8"));return typeof r.name=="string"?r.name.trim():null}catch{return null}}function oR(e){return wF(e)==="kynver"}function tR(e){let t=ct.resolve(e);if(!Rf(t))return null;let r=ee(t,["rev-parse","--show-toplevel"]);if(r.status!==0)return null;let n=r.stdout.trim();return n.length?ct.resolve(n):null}function SF(e=import.meta.url){let t=ct.dirname(vF(e));for(let r=0;r<8;r+=1){let n=ct.join(t,"package.json");if(Rf(n))try{if(JSON.parse(rR(n,"utf8")).name==="@kynver-app/runtime")return t}catch{}let o=ct.dirname(t);if(o===t)break;t=o}return null}function vf(e,t,r,n,o){if(!r)return;let s=ct.resolve(r);e.has(s)||(o?.requireMonorepo??!0)&&!oR(s)||(e.add(s),t.push({repo:s,source:n}))}function sR(e){let t=e?.cwd??process.cwd(),r=new Set,n=[];vf(r,n,tR(t),"cwd_git",{requireMonorepo:!1});let o=SF(e?.runtimeModuleUrl??import.meta.url);o&&vf(r,n,tR(o),"runtime_checkout");let s=nR();for(let a of RF)vf(r,n,Me(ct.join(s,a)),"well_known_path");let i=ct.resolve(e?.cwd??process.cwd());return n.filter(a=>{if(a.source!=="runtime_checkout"||!oR(a.repo))return!0;let l=ct.resolve(a.repo);return i===l||i.startsWith(`${l}${ct.sep}`)})}function Ul(e){return sR(e)[0]??null}function _F(e){let t=ct.resolve(e).replace(/\\/g,"/");return t.includes("/.kynver/harness/worktrees/")||t.includes("/.openclaw/harness/worktrees/")||t.includes("/kynver-harness/")||t.includes("/openclaw/harness/worktrees/")}function Fl(e){let t=sR(e),r=t.find(o=>!_F(o.repo));if(r)return r;if(t[0])return t[0];let{repo:n}=eR(e?.home??nR());return{repo:n,source:"byoc_workspace"}}var RF,mi=p(()=>{"use strict";we();at();bf();RF=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});function gi(e){let t=kn(e);try{let r=new URL(t);return r.hostname.toLowerCase()===iR?(r.hostname=`www.${iR}`,kn(r.toString())):t}catch{return t}}function or(e){if(e?.trim())return gi(kn(e.trim()))}async function ut(e,t,r=fetch){let n=gi(e),o=new Headers(t?.headers),s=0;for(;s<=aR;){let i=await r(n,{...t,headers:o,redirect:"manual"});if(![301,302,303,307,308].includes(i.status))return i;let a=i.headers.get("location");if(!a)return i;let l=new URL(a,n);if(l.origin!==new URL(n).origin||l.username||l.password)throw await i.body?.cancel(),new Error("kynver API fetch refused unsafe redirect (origin change or embedded credentials)");let c=(t?.method??"GET").toUpperCase();if(!["GET","HEAD"].includes(c)&&i.status!==307&&i.status!==308)return i;await i.body?.cancel(),n=l.toString(),s+=1}throw new Error(`kynver API fetch exceeded ${aR} redirects for ${e}`)}var iR,aR,sr=p(()=>{"use strict";M();iR="kynver.com";aR=10});function bn(e){let t=(e??"").trim().toLowerCase();return t==="ghost"||t==="forge"||t==="box"?t:t.includes("forge")?"forge":t.includes("ghost")||t.includes("openclaw")?"ghost":"box"}function Kl(e,t){return e[t]?.trim()||null}function lR(e){let t=e?.split(":")[0]?.trim();return t?bn(t):null}function et(e=process.env,t={}){let r=[],n=lR(t.boxId),o=lR(Kl(e,"KYNVER_BOX_ID")),s=t.boxKind?.trim();if(s)return n&&n!==bn(s)&&r.push(`config.boxId=${t.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:bn(s),source:"config",slugInferenceBlocked:!1,warnings:r};let i=Kl(e,"KYNVER_BOX_KIND");if(i)return o&&o!==bn(i)&&r.push(`KYNVER_BOX_ID=${Kl(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:bn(i),source:"env",slugInferenceBlocked:!1,warnings:r};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:r};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:r};let a=Kl(e,"KYNVER_AGENT_OS_SLUG");return a&&r.push(`KYNVER_AGENT_OS_SLUG=${a} is a workspace slug, not box identity \u2014 operators set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND; customers default to box`),{boxKind:"box",source:"default",slugInferenceBlocked:!!a,warnings:r}}function xt(e={},t=process.env){return et(t,e).boxKind}var Le=p(()=>{"use strict"});function wf(e,t){return e==="forge"?4:Math.max(1,t)}function ir(e,t){return e==="forge"?Math.min(Math.max(1,t),4):Math.max(1,t)}function hi(e,t){return e==="forge"&&t>4}var Io=p(()=>{"use strict"});import{readFileSync as xF}from"node:fs";import cR from"node:os";function uR(e){if(e!==void 0){let t=e.match(/^MemAvailable:\s+(\d+)\s*kB/m);return t?Number(t[1])*1024:cR.freemem()}if(process.platform==="linux")try{let r=xF("/proc/meminfo","utf8").match(/^MemAvailable:\s+(\d+)\s*kB/m);if(r)return Number(r[1])*1024}catch{}return cR.freemem()}var dR=p(()=>{"use strict"});import{existsSync as CF,readFileSync as EF,statfsSync as AF}from"node:fs";function Sf(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!CF(e))continue;let t=EF(e,"utf8");if(/microsoft|wsl/i.test(t))return!0}catch{}return!1}function pR(e={}){if(!(e.forceWsl===void 0?Sf():e.forceWsl))return null;let r=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Oo,n=e.wslHostFreeWarnBytes??PF,o=e.wslHostFreeCriticalBytes??IF,s=e.statfs??AF,i;try{i=s(r)}catch(h){return{ok:!1,path:r,freeBytes:0,totalBytes:0,usedPercent:100,warnBelowBytes:n,criticalBelowBytes:o,reason:`Windows host disk probe failed at ${r}: ${h.message}`,probeError:h.message}}let a=Number(i.bavail)*Number(i.bsize),l=Number(i.blocks)*Number(i.bsize),c=l>0?(l-a)/l*100:100,u=a<n,d=a<o,f=!u&&!d,m=(a/(1024*1024*1024)).toFixed(1),g=null;return f||(g=`Windows host disk ${r} at ${d?"critical":"warning"}: ${m} GiB free (<${(d?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${OF()}`),{ok:f,path:r,freeBytes:a,totalBytes:l,usedPercent:c,warnBelowBytes:n,criticalBelowBytes:o,reason:g,probeError:null}}function OF(){return"Recovery: 1) free Windows C: (empty Recycle Bin / Storage Sense / clear %TEMP% and %LOCALAPPDATA%\\Temp\\wsl-crashes); 2) shut down WSL (`wsl --shutdown`) then compact the VHDX (`Optimize-VHD` or `diskpart compact vdisk`); 3) clear local node_modules / .next / harness worktrees before restarting workers; 4) disable recurring dumps via `%USERPROFILE%/.wslconfig` (`maxCrashDumpCount=-1`) or `kynver wsl-crashes --execute`. More help: https://www.kynver.com/help."}var PF,IF,Oo,_f=p(()=>{"use strict";PF=25*1024*1024*1024,IF=12*1024*1024*1024,Oo="/mnt/c"});import{execFileSync as fR}from"node:child_process";import{existsSync as Hl,readFileSync as mR,readdirSync as TF,statSync as NF}from"node:fs";import xf from"node:path";function $l(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function gR(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=fR("cmd.exe",["/c","echo","%USERNAME%"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(n&&n!=="%USERNAME%"&&!n.includes("%"))return n}catch{}let t=process.env.USER?.trim()||process.env.LOGNAME?.trim(),r=process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Oo;return t&&Hl(xf.join(r,"Users",t))?t:null}function WF(e={}){let t=e.crashDumpDir?.trim()||process.env.KYNVER_WSL_CRASH_DUMP_DIR?.trim();if(t)return t;let r=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Oo,n=e.windowsUser??gR();return n?`${r.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function UF(e){let t=/^wsl-crash-\d+-(\d+)-(.+)-(\d+)\.dmp$/i.exec(e);if(!t)return{executableHint:null,signal:null,pid:null};let r=Number(t[1]),n=t[2]??"",o=Number(t[3]),s=n.split("_").filter(Boolean);return{executableHint:s.length>0?s[s.length-1]:null,signal:Number.isFinite(o)?o:null,pid:Number.isFinite(r)?r:null}}function FF(){try{if(Hl("/proc/sys/kernel/core_pattern"))return mR("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return fR("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function KF(e){return!!(e&&/wsl-capture-crash/i.test(e))}function $F(e,t=Oo){let r=xf.join(t,"Users",e,".wslconfig");if(!Hl(r))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=mR(r,"utf8")}catch{return null}let o=null,s=null;for(let i of n.split(/\r?\n/)){let a=i.replace(/#.*$/,"").trim();if(!a||a.startsWith("["))continue;let l=a.indexOf("=");if(l<0)continue;let c=a.slice(0,l).trim().toLowerCase(),u=a.slice(l+1).trim();if(c==="maxcrashdumpcount"){let d=Number(u);o=Number.isFinite(d)?d:null}else c==="crashdumpfolder"&&(s=u.replace(/^["']|["']$/g,"")||null)}return{maxCrashDumpCount:o,crashDumpFolder:s}}function HF(e){if(!Hl(e))return[];let t=TF(e,{withFileTypes:!0}),r=[];for(let n of t){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=xf.join(e,n.name);try{let s=NF(o),i=UF(n.name);r.push({name:n.name,path:o,bytes:s.size,mtimeMs:s.mtimeMs,executableHint:i.executableHint,signal:i.signal,pid:i.pid})}catch{}}return r.sort((n,o)=>o.mtimeMs-n.mtimeMs),r}function To(e={}){if(!(e.forceWsl===void 0?Sf():e.forceWsl))return null;let r=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Oo,n=e.windowsUser??gR(),o=e.warnBelowBytes??$l("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",DF),s=e.criticalBelowBytes??$l("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",MF),i=e.warnCount??$l("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",LF),a=e.criticalCount??$l("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",BF),l=(e.readCorePattern??FF)(),c=KF(l),u=null;n&&(u=(e.readWslConfig??$F)(n,r));let d=u?.maxCrashDumpCount??null,f=d===-1,m=WF({hostMount:r,windowsUser:n,crashDumpDir:e.crashDumpDir});if(!m)return{ok:!0,path:null,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:l,wslCaptureEnabled:c,maxCrashDumpCount:d,dumpsDisabledInWslConfig:f,reason:null,probeError:"windows_user_unresolved"};let g;try{g=(e.listDumps??HF)(m)}catch(N){return{ok:!1,path:m,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:l,wslCaptureEnabled:c,maxCrashDumpCount:d,dumpsDisabledInWslConfig:f,reason:`WSL crash dump probe failed at ${m}: ${N.message}`,probeError:N.message}}let h=g.reduce((N,A)=>N+A.bytes,0),y=g.length,v=[...new Set(g.map(N=>N.executableHint).filter(N=>!!N))],k=h>=s,b=h>=o,_=y>=a,S=y>=i,w=!(k||_||b||S),L=null;if(!w){let N=k||_?"critical":"warning",A=(h/1024**3).toFixed(1),O=v.length>0?v.join(", "):"unknown";L=`WSL crash dumps ${N}: ${y} file(s), ${A} GiB at ${m} (executables: ${O}). `+jF({wslCaptureEnabled:c,dumpsDisabledInWslConfig:f})}return{ok:w,path:m,windowsUser:n,dumpCount:y,totalBytes:h,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:g,executables:v,corePattern:l,wslCaptureEnabled:c,maxCrashDumpCount:d,dumpsDisabledInWslConfig:f,reason:L,probeError:null}}function jF(e={}){let t=["Recovery:","1) run `kynver wsl-crashes --execute` or scripts/cleanup-wsl-crashes.ps1 to prune old .dmp files;"];return e.dumpsDisabledInWslConfig||t.push("2) add `[wsl2]\\nmaxCrashDumpCount=-1` to %USERPROFILE%/.wslconfig then `wsl --shutdown` to disable future dumps;"),e.wslCaptureEnabled&&t.push("3) investigate crashing executables (node OOM/SIGBUS often follows Windows C: pressure);"),t.push("More help: https://www.kynver.com/help."),t.join(" ")}var DF,MF,LF,BF,jl=p(()=>{"use strict";_f();DF=5*1024*1024*1024,MF=10*1024*1024*1024,LF=2,BF=4});import{statfsSync as VF}from"node:fs";function Br(e={}){let t=e.diskPath?.trim()||"/",r=e.diskFreeWarnBytes??GF,n=e.diskFreeCriticalBytes??JF,o=e.diskMaxUsedPercent??qF,s=e.diskHardMaxUsedPercent??YF,i=VF(t),a=Number(i.bavail)*Number(i.bsize),l=Number(i.blocks)*Number(i.bsize),c=l>0?(l-a)/l*100:100,u=a<r,d=a<n,f=a<r*2,m=f&&c>o,g=f&&c>s,h=!u&&!d&&!m&&!g,y=e.skipWslHostCheck?null:pR(e.wslHost),v=e.skipWslCrashDumpCheck?null:To(e.wslCrashDumps),k=h&&(y?y.ok:!0)&&(v?v.ok:!0),b=null;return k||(b=[d?`free space below critical ${n} bytes`:null,u?`free space below warning ${r} bytes`:null,g?`used percent above hard cap ${s}%`:null,m?`used percent above cap ${o}%`:null,y&&!y.ok?y.reason:null,v&&!v.ok?v.reason:null].filter(Boolean).join("; ")),zF({ok:k,path:t,freeBytes:a,totalBytes:l,usedPercent:c,warnBelowBytes:r,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:b,wslHost:y,wslCrashDumps:v?{ok:v.ok,path:v.path,dumpCount:v.dumpCount,totalBytes:v.totalBytes,executables:v.executables,wslCaptureEnabled:v.wslCaptureEnabled,dumpsDisabledInWslConfig:v.dumpsDisabledInWslConfig,reason:v.reason,probeError:v.probeError}:null})}function zF(e){let t=process.env.KYNVER_DISPATCH_DISK_GATE_FORCE?.trim().toLowerCase();return t?t==="ok"||t==="open"||t==="none"?e.ok?e:{...e,ok:!0,reason:`disk gate forced open by KYNVER_DISPATCH_DISK_GATE_FORCE (suppressed: ${e.reason??"no reason"})`}:t==="block"||t==="pressured"?{...e,ok:!1,reason:`disk gate forced closed by KYNVER_DISPATCH_DISK_GATE_FORCE${e.reason?` (underlying: ${e.reason})`:""}`}:e:e}var GF,JF,qF,YF,yi=p(()=>{"use strict";jl();_f();GF=30*1024*1024*1024,JF=15*1024*1024*1024,qF=80,YF=90});import{existsSync as XF,readdirSync as QF}from"node:fs";import ZF from"node:path";function Ct(e){let t=new Set;for(let n of Object.keys(e.workers||{}))t.add(B(n));let r=ZF.join(j(e.id),"workers");if(!XF(r))return[...t];for(let n of QF(r,{withFileTypes:!0}))n.isDirectory()&&t.add(B(n.name));return[...t]}var No=p(()=>{"use strict";Y();M()});function Cf(e){let t=e.trim();if(!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&!Array.isArray(r))return r}catch{return null}return null}function hR(e){let t=e.trim();if(!t)return null;let r=Cf(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let l=Cf(s[1]??"");l&&n.push(l)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let l=Cf(t.slice(i,a+1));l&&n.push(l)}return n.length>0?n[n.length-1]:null}function yR(e){let t=e.finalResult??e.final_result;if(t!=null)return typeof t=="string"?hR(t)??(t.trim()||null):t;let r=typeof e.summary=="string"?e.summary.trim():"";if(!r)return null;let n=hR(r);return n||r}var kR=p(()=>{"use strict"});import{existsSync as eK,readFileSync as tK}from"node:fs";function bR(e){return e==="complete"}function ar(e){return bR(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function Ie(e){let t={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!eK(e))return t;let r=Date.now()+rK,n=new Date(r).toISOString(),o=tK(e,"utf8").split(`
|
|
6
|
+
`).filter(Boolean);for(let s of o){let i=ui(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(t.heartbeatCount++,a.ts){let l=String(a.ts),c=Date.parse(l);Number.isFinite(c)&&c>r?t.timestampAnomalies.push({kind:"future_heartbeat_timestamp",observedAt:l,clampedTo:n}):t.lastHeartbeatAt=l}a.phase!==void 0&&a.phase!==null&&(t.lastHeartbeatPhase=String(a.phase)),a.summary!==void 0&&a.summary!==null&&(t.lastHeartbeatSummary=String(a.summary)),bR(t.lastHeartbeatPhase)&&(t.terminalFinalResult=yR(a)),t.heartbeatBlocker=a.blocker?String(a.blocker):null,a.boxResourceSnapshot&&typeof a.boxResourceSnapshot=="object"&&!Array.isArray(a.boxResourceSnapshot)&&(t.lastBoxResourceSnapshot=a.boxResourceSnapshot),Array.isArray(a.prEvidence)&&(t.lastPrEvidence=a.prEvidence.filter(l=>!!l&&typeof l=="object"&&typeof l.prUrl=="string"))}return t}var rK,vn=p(()=>{"use strict";kR();M();rK=6e4});function RR(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function Vl(e){if(!e)return[];let t=[],r="",n,o=!1;for(let s of e){if(o){r+=s,o=!1;continue}if(s==="\\"){o=!0;continue}if(n){s===n?n=void 0:r+=s;continue}if(s==='"'||s==="'"){n=s;continue}if(/\s/.test(s)){r&&(t.push(r),r="");continue}r+=s}return r&&t.push(r),t}function wR(e){let t=RR(e[0]);return!!(t&&nK.has(t))}function sK(e){let t=e.trim();return t.includes("/")?t.split("/").pop()??t:t}function iK(e){if(!e||e.includes("*"))return null;let t=sK(e);return!t||t.includes("/")?null:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(t)?t:null}function SR(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function Ef(e){if(!e)return!1;let t=e.trim();return t.startsWith("!")&&!t.includes("/")&&!t.endsWith("/**")}function aK(e){if(!e.startsWith("--glob="))return e;let t=e.slice(7);return t.startsWith("!")&&!t.includes("/")&&!t.endsWith("/**")?`--glob=${t}/**`:e}function lK(e){let t=[];for(let r=1;r<e.length;r+=1){let n=e[r];if(n){if(n==="--"){t.push(...e.slice(r+1));break}if(n.startsWith("-")){if(n.includes("="))continue;vR.has(n)&&(r+=1);continue}t.push(n)}}return t}function cK(e){let t=!1,r=e.map((o,s)=>{let i=aK(o),a=e[s-1];return a&&vR.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(t=!0),i}),n=lK(r);if(n.length===2){let[o,s]=n;if(Ef(s))return{argv:[r[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};let i=iK(s);if(i)return{argv:[r[0]??"rg","-g",i,o,"."],changed:!0}}return t&&n.length===1?{argv:[...r,"."],changed:!0}:{argv:r,changed:t}}function _R(e){for(let t=1;t<e.length;t+=1){let r=e[t];if(r&&(r==="-c"||r==="-lc"||r==="-cl"||/^-[a-zA-Z]*c[a-zA-Z]*$/u.test(r)))return t+1}return-1}function Gl(e){let t=e.trim();if(!t)return{command:t,wrapped:!1};let r=Vl(t);if(!r.length)return{command:t,wrapped:!1};let n=RR(r[0]);if(!n||!oK.has(n))return{command:t,wrapped:!1};let o=_R(r);if(o<0||o>=r.length)return{command:t,wrapped:!1};let s=r.slice(o).join(" ").trim();return s?{command:s,wrapped:!0}:{command:t,wrapped:!1}}function uK(e,t){let r=e.trim(),n=Vl(r),o=_R(n);if(o<0)return t;let s=n.slice(0,o).join(" "),i=t.includes("'")?`"${t.replace(/"/g,'\\"')}"`:`'${t}'`;return`${s} ${i}`}function dK(e){let t=e.trim(),r=Gl(t),n=Vl(r.command);if(!n.length||!wR(n))return{segment:t,changed:!1};let o=cK(n);if(!o.changed)return{segment:t,changed:!1};let s=o.argv.join(" ");return r.wrapped?{segment:uK(t,s),changed:!0}:{segment:s,changed:!0}}function Af(e){let t=e.trim();if(!t)return{command:t,changed:!1};let r=t.includes("&&")?" && ":t.includes("||")?" || ":"; ",n=t.split(/\s*(?:&&|\|\||;)\s*/u),o=!1,s=n.map(i=>{let a=dK(i);return a.changed&&(o=!0),a.segment});return o?{command:s.join(r),changed:!0}:{command:t,changed:!1}}function xR(e){let t=Gl(e).command,r=Vl(t.trim());return r.length&&wR(r)?!0:/\b(rg|ripgrep)\b/i.test(t)}function CR(e){if(!e)return{};let t=e.match(/search\s+"(.+)"\s+in\s+([^()]+?)(?:\s*\(|$)/iu);if(t)return{pattern:t[1],target:t[2]?.trim()};let r=e.match(/^search\s+"(.+)"\s+in\s+(.+)$/iu);return r?{pattern:r[1],target:r[2]?.trim()}:{}}function pK(e){let{pattern:t,target:r}=CR(e);return t?Ef(r)?{kind:"rg_exclude_syntax",pattern:t,target:r}:SR(r)?{kind:"bad_scope",pattern:t,target:r}:{kind:"not_repo_search",pattern:t,target:r}:{kind:"not_repo_search"}}function fK(e){let{pattern:t,target:r}=CR(e);if(!t)return null;if(Ef(r)){let n=`${r.trim()}/**`;return{command:`rg "${t}" -g '${n}' .`,changed:!0}}return r&&SR(r)?{command:`rg -g ${r} "${t}" .`,changed:!0}:null}function mK(e){if(e.kind==="bad_scope"&&e.pattern&&e.target)return`Use \`rg -g '${e.target}' ${e.pattern} .\` from the repo root instead of treating ${e.target} as a folder.`;if(e.kind==="rg_exclude_syntax"&&e.pattern){let t=e.target?`${e.target.trim()}/**`:"!node_modules/**";return`Repo search scope \`${e.target??"!node_modules"}\` is not a valid ripgrep path. Use \`rg "${e.pattern}" -g '${t}' .\` from the repo root (exclude globs need a \`/**\` suffix).`}return e.kind==="no_matches"&&e.pattern?`No matches for "${e.pattern}". Try a broader pattern, drop overly short tokens, or search from the repo root with \`rg "${e.pattern}" .\`.`:null}function gK(e){let t=e.match(/search\s+"(.+)"\s+in\s+([^()]+?)(?:\s*\(agent\)|\s*failed|$)/iu);return t?`search "${t[1]}" in ${t[2]?.trim()}`:null}function Pf(e){let t=e.meta?.trim()||(e.command?gK(e.command):null)||null;if(t){let r=pK(t),n=mK(r);if(n)return n;let o=fK(t);if(o?.changed)return`Repo search used an invalid scope. Retry with: \`${o.command}\`.`}if(e.command&&/\b(rg|ripgrep)\b/i.test(e.command)){let r=Af(e.command);if(r.changed)return`Ripgrep scope may be invalid. Retry with: \`${r.command}\`.`;if(e.exitCode===1)return"Ripgrep returned no matches (exit 1). Try a broader pattern or search from the repo root."}return null}var nK,oK,vR,ER=p(()=>{"use strict";nK=new Set(["rg","ripgrep","grep"]),oK=new Set(["bash","sh","dash","zsh"]),vR=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function ki(e,t=200){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}function kK(e){let t=e.trim();if(!t)return null;if(t.startsWith("{"))try{return JSON.parse(t)}catch{}let r=t.indexOf("{"),n=t.lastIndexOf("}");if(r>=0&&n>r)try{return JSON.parse(t.slice(r,n+1))}catch{return null}return null}function bi(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function bK(e){let t=e.metadata;if(!bi(t))return null;let r=t.vulnerabilities;if(!bi(r))return null;let n=s=>typeof r[s]=="number"?r[s]:0,o={info:n("info"),low:n("low"),moderate:n("moderate"),high:n("high"),critical:n("critical"),total:n("total")};return typeof r.total!="number"&&!o.critical&&!o.high&&!o.moderate&&!o.low&&!o.info?null:o}function vK(e){let t=[];e.critical&&t.push(`${e.critical} critical`),e.high&&t.push(`${e.high} high`),e.moderate&&t.push(`${e.moderate} moderate`),e.low&&t.push(`${e.low} low`),e.info&&t.push(`${e.info} info`);let r=t.length?t.join(", "):"see report";return`npm audit: ${e.total} vulnerabilit${e.total===1?"y":"ies"} (${r}) \u2014 remediation required`}function RK(e,t){let r=e.error;if(bi(r)){let s=typeof r.summary=="string"?r.summary.trim():"",i=typeof r.code=="string"?r.code.trim():"";if(s)return i?`${i}: ${s}`:s;if(i)return i}let n=typeof e.message=="string"?e.message.trim():"";if(n)return n;let o=t.trim();return o?ki(o.split(`
|
|
7
|
+
`).find(Boolean)??o,160):"npm audit failed"}function wK(e){let t=`${e.stdout}
|
|
8
|
+
${e.stderr}`.trim(),r=kK(t);if(!r||!bi(r)){let o=ki(t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit failed (invalid or missing JSON): ${o}`,parseError:"invalid_json"}}if(bi(r.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${RK(r,e.stderr)}`};let n=bK(r);return n?e.exitCode===0&&n.total===0?{kind:"success",exitCode:0,summary:"npm audit: no vulnerabilities reported",audit:n}:{kind:"audit_findings",exitCode:e.exitCode,summary:vK(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function SK(e){return hK.test(e)}function _K(e){let t=Gl(e).command;return AR.test(e)||AR.test(t)||xR(e)}function xK(e){let t=Pf({command:e.command,exitCode:e.exitCode});if(e.exitCode===0)return{kind:"success",exitCode:0,summary:"ripgrep finished (exit 0)"};if(e.exitCode===1){let n=(e.stderr||e.interleaved).trim();if(n&&yK.test(n)){let i=ki(n,160);return{kind:"command_failure",exitCode:1,summary:t??`ripgrep failed (exit 1): ${i}`}}let o=Af(e.command),s=o.changed&&!t?` Retry with: \`${o.command}\`.`:"";return{kind:"search_no_matches",exitCode:1,summary:t??`ripgrep: no matches (exit 1).${s} Try a broader pattern or search from the repo root.`}}let r=ki(e.interleaved||e.stdout||e.stderr||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:t??`ripgrep failed (exit ${e.exitCode}): ${r}`}}function PR(e){let t=e.stdout??"",r=e.stderr??"",n=e.interleavedOutput??"";if(SK(e.command)){let i=t.trim()||n.trim()||r.trim();return wK({exitCode:e.exitCode,stdout:i,stderr:r})}if(_K(e.command))return xK({command:e.command,exitCode:e.exitCode,stdout:t,stderr:r,interleaved:n});let o=Pf({command:e.command,exitCode:e.exitCode});if(o&&e.exitCode!==0)return{kind:"command_failure",exitCode:e.exitCode,summary:o};if(e.exitCode===0)return{kind:"success",exitCode:0,summary:"command succeeded (exit 0)"};let s=ki(n||t||r||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var hK,AR,yK,IR=p(()=>{"use strict";ER();hK=/\bnpm\s+audit\b/i,AR=/\b(rg|ripgrep)\b/i,yK=/\b(error|invalid|unknown|panic|not found)\b/i});function vi(e){return typeof e=="string"&&CK.test(e.trim())}function Jl(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.is_error===!0||t.providerTerminalError===!0||typeof t.subtype=="string"&&/^error(?:_|$)/.test(t.subtype)}var CK,ql=p(()=>{"use strict";CK=/^(?:provider authentication failed:\s*)?(?:(?:Failed to authenticate|authentication (?:failed|error))(?::\s*[^\n.!?]+)?|OAuth session expired and could not be refreshed)[.!]?$/i});function If(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function EK(e){if(!e)return;let t=typeof e.input_tokens=="number"?e.input_tokens:void 0,r=typeof e.output_tokens=="number"?e.output_tokens:void 0;if(!((t===void 0||t<0)&&(r===void 0||r<0)))return{...t!==void 0&&t>=0?{inputTokens:t}:{},...r!==void 0&&r>=0?{outputTokens:r}:{}}}function Yl(e){if(e.event==="step_update"&&If(e.step_update)){let s=e.step_update,i=s.step_type==="tool"&&typeof s.tool_name=="string"&&s.tool_name.trim()?s.tool_name.trim():void 0,a=typeof s.text_delta=="string"?s.text_delta:void 0;return!i&&a===void 0?null:{...i?{currentTool:i}:{},...a!==void 0?{textDelta:a}:{}}}if(e.event!=="result"||!If(e.result))return null;let t=e.result,r=typeof t.status=="string"?t.status.toUpperCase():"";if(r!=="SUCCESS"&&r!=="ERROR")return null;let n=If(t.usage)?EK(t.usage):void 0;if(r==="ERROR"){let s=typeof t.error=="string"&&t.error.trim()?t.error.trim():"antigravity cli result error";return{...n?{usage:n}:{},terminal:{ok:!1,finalResult:null,error:s}}}let o=typeof t.response=="string"?t.response.trim():"";return{...n?{usage:n}:{},terminal:{ok:!0,finalResult:o||"completed",error:null}}}var Of=p(()=>{"use strict"});function Tf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function OR(){return{assistantText:""}}function AK(e,t){if(!(t.role!=="assistant"||typeof t.content!="string")){if(t.delta===!0){e.assistantText+=t.content;return}e.assistantText=t.content}}function PK(e){let t=typeof e.input_tokens=="number"?e.input_tokens:void 0,r=typeof e.output_tokens=="number"?e.output_tokens:void 0,o=(Tf(e.models)?Object.keys(e.models):[]).find(s=>s.trim())?.trim();if(!(t===void 0&&r===void 0&&!o))return{...t!==void 0&&t>=0?{inputTokens:t}:{},...r!==void 0&&r>=0?{outputTokens:r}:{},...o?{model:o}:{}}}function IK(e){return e.type!=="result"||e.status!=="success"&&e.status!=="error"?!1:typeof e.result!="string"}function TR(e,t){if(e.type==="message"&&(e.role==="assistant"||e.role==="user"))return AK(t,e),{};if(e.type==="tool_use"&&typeof e.tool_name=="string"&&e.tool_name.trim())return{currentTool:e.tool_name.trim()};if(!IK(e))return null;let r=Tf(e.stats)?PK(e.stats):void 0;if(e.status==="error"){let o=Tf(e.error)&&typeof e.error.message=="string"?e.error.message:"gemini cli result error";return{...r?{usage:r}:{},terminal:{ok:!1,finalResult:null,error:o}}}let n=t.assistantText.trim();return{...r?{usage:r}:{},terminal:{ok:!0,finalResult:n||"completed",error:null}}}var NR=p(()=>{"use strict"});import{existsSync as OK,readFileSync as TK}from"node:fs";function NK(e){let t=e.timestamp_ms;return e.timestamp||e.ts||(t?new Date(t).toISOString():void 0)}function DK(e){if(!e)return null;for(let t of Object.keys(e))if(t.endsWith("ToolCall")){let r=t.slice(0,-8);return r.length?r:t}return null}function MK(e,t){e.finalResult=t.result||t.subtype||t.terminal_reason||"completed",Jl(t)&&(e.providerTerminalError=!0,e.error=String(t.result||t.api_error_status||"stream result error"))}function Do(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function LK(e){let t=e.usage;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function BK(e){if(typeof e.model=="string"&&e.model.trim())return e.model.trim();let t=e.modelUsage;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=Object.keys(t)[0];if(r?.trim())return r.trim()}}function WK(e,t){let r=LK(t);if(!r)return;let n=Do(r.input_tokens)??Do(r.inputTokens)??Do(r.prompt_tokens),o=Do(r.output_tokens)??Do(r.outputTokens)??Do(r.completion_tokens);if(n===void 0&&o===void 0)return;let s=BK(t)??e.usage?.model;e.usage={...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...s?{model:s}:{}}}function UK(e){if(e.type!=="tool_call"||e.subtype!=="completed")return null;let r=(e.tool_call&&typeof e.tool_call=="object"&&!Array.isArray(e.tool_call)?e.tool_call:null)?.shellToolCall;if(!r||typeof r!="object"||Array.isArray(r))return null;let n=r,o=n.args,s=o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.command=="string"?String(o.command):"",i=n.result;if(!i||typeof i!="object"||Array.isArray(i))return null;let a=i.success??i.failure;if(!a||typeof a!="object"||Array.isArray(a))return null;let l=a,c=typeof l.exitCode=="number"?l.exitCode:0;return{command:s,exitCode:c,stdout:typeof l.stdout=="string"?l.stdout:"",stderr:typeof l.stderr=="string"?l.stderr:"",interleaved:typeof l.interleavedOutput=="string"?l.interleavedOutput:""}}function FK(e,t){t.kind==="success"||t.kind==="search_no_matches"||(e.lastShellOutcome=t)}function Rn(e){let t={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null,usage:null};if(!OK(e))return t;let r=TK(e,"utf8").split(`
|
|
9
|
+
`).filter(Boolean),n=null,o=OR();for(let s of r){let i=ui(s);if(!i||typeof i!="object"||Array.isArray(i))continue;if(i.type==="turn.started"&&(n=null,t.finalResult=null),i.type==="item.completed"){let f=i.item;if(f&&typeof f=="object"&&!Array.isArray(f)){let m=f;m.type==="agent_message"&&typeof m.text=="string"&&m.text.trim()&&(n=m.text)}}i.type==="turn.completed"&&n&&!t.providerTerminalError&&(t.finalResult=n,n=null);let a=NK(i);if(a&&(t.firstEventAt||=a,t.lastEventAt=a),i.type==="stream_event"&&i.event&&typeof i.event=="object"&&i.event.type==="content_block_start"){let f=i.event.content_block;f?.type==="tool_use"&&(t.currentTool=String(f.name||"tool"))}if(i.type==="assistant"&&i.message&&typeof i.message=="object"){let f=i.message.content;if(Array.isArray(f)){let m=f.find(g=>g?.type==="tool_use");m&&(t.currentTool=String(m.name||t.currentTool))}}if(i.type==="tool_call"&&i.subtype==="started"){let f=i.tool_call&&typeof i.tool_call=="object"&&!Array.isArray(i.tool_call)?i.tool_call:void 0,m=DK(f);m&&(t.currentTool=m)}let l=UK(i);l&&FK(t,PR({command:l.command,exitCode:l.exitCode,stdout:l.stdout,stderr:l.stderr,interleavedOutput:l.interleaved}));let c=Yl(i),u=c?null:TR(i,o),d=c??u;if(d?.currentTool&&(t.currentTool=d.currentTool),d?.usage&&(t.usage={...t.usage??{},...d.usage}),d?.terminal?d.terminal.ok?t.finalResult=d.terminal.finalResult:(t.finalResult=null,t.providerTerminalError=!0,t.error=d.terminal.error):i.type==="result"&&MK(t,i),i.type==="turn.failed"){n=null,t.finalResult=null,t.providerTerminalError=!0;let f=i.error;t.error=typeof f?.message=="string"?f.message:"provider turn failed"}WK(t,i)}return t}var Ri=p(()=>{"use strict";IR();M();ql();Of();NR()});import{accessSync as KK,constants as $K,existsSync as HK,readFileSync as jK}from"node:fs";import Nf from"node:path";function MR(e){return Nf.join(e,VK)}function GK(e=process.env,t=process.platform){if(t==="win32")return!1;let r=e.KYNVER_WORKER_EXIT_CAPTURE?.trim().toLowerCase();return!(r==="0"||r==="false"||r==="off")}function DR(e){try{return KK(e,$K.X_OK),!0}catch{return!1}}function JK(e,t=process.env){if(!e)return!1;if(e.includes("/"))return DR(e);for(let r of(t.PATH??"").split(Nf.delimiter))if(r&&DR(Nf.join(r,e)))return!0;return!1}function tt(e,t,r,n={}){let o=n.env??process.env;return!r||!GK(o,n.platform)?[e,t]:JK(e,o)?[n.nodeExecutable??process.execPath,["-e",qK,MR(r),e,...t]]:[e,t]}function YK(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function zl(e){if(!e)return null;let t=MR(e);if(!HK(t))return null;try{let r=JSON.parse(jK(t,"utf8")),n=r.oomEvidence;return{exitCode:YK(r.exitCode),signal:typeof r.signal=="string"&&r.signal?r.signal:null,...typeof r.startedAt=="string"?{startedAt:r.startedAt}:{},...typeof r.endedAt=="string"?{endedAt:r.endedAt}:{},...typeof r.childPid=="number"?{childPid:r.childPid}:{},...typeof r.spawnError=="string"?{spawnError:r.spawnError}:{},oomEvidence:n&&(n.source==="cgroup"||n.source==="kernel_log")?{source:n.source,detail:String(n.detail??"").slice(0,300)}:null}}catch{return null}}function LR(e){if(!e)return null;let t=e.oomEvidence?" (kernel out-of-memory kill)":"";return e.spawnError?`could not start: ${e.spawnError}`:e.signal?`killed by ${e.signal}${t}`:e.exitCode===null?null:`exited with code ${e.exitCode}${t}`}var VK,qK,lr=p(()=>{"use strict";VK="exit.json";qK=String.raw`"use strict";
|
|
10
|
+
const cp = require("child_process"), fs = require("fs");
|
|
11
|
+
const argv = process.argv.slice(1);
|
|
12
|
+
const exitFile = argv[0], cmd = argv[1], args = argv.slice(2);
|
|
13
|
+
const startedMs = Date.now();
|
|
14
|
+
function cgroupOomKills() {
|
|
15
|
+
try {
|
|
16
|
+
const line = fs.readFileSync("/proc/self/cgroup", "utf8").split("\n").find((l) => l.startsWith("0::"));
|
|
17
|
+
if (!line) return null;
|
|
18
|
+
const file = "/sys/fs/cgroup" + line.slice(3).trim().replace(/\/$/, "") + "/memory.events";
|
|
19
|
+
const m = /(?:^|\n)oom_kill (\d+)/.exec(fs.readFileSync(file, "utf8"));
|
|
20
|
+
return m ? Number(m[1]) : null;
|
|
21
|
+
} catch { return null; }
|
|
22
|
+
}
|
|
23
|
+
function kernelLog() {
|
|
24
|
+
const override = process.env.KYNVER_EXIT_CAPTURE_KERNEL_LOG_FILE;
|
|
25
|
+
if (override) { try { return fs.readFileSync(override, "utf8"); } catch { return ""; } }
|
|
26
|
+
const run = (bin, a) => {
|
|
27
|
+
try {
|
|
28
|
+
const r = cp.spawnSync(bin, a, { encoding: "utf8", timeout: 3000, maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] });
|
|
29
|
+
return r.status === 0 ? String(r.stdout || "") : "";
|
|
30
|
+
} catch { return ""; }
|
|
31
|
+
};
|
|
32
|
+
return run("journalctl", ["-k", "-q", "--no-pager", "--since", "@" + Math.floor(startedMs / 1000)]) || run("dmesg", []);
|
|
33
|
+
}
|
|
34
|
+
const oomBefore = cgroupOomKills();
|
|
35
|
+
let child, finished = false;
|
|
36
|
+
function write(rec) {
|
|
37
|
+
try { fs.writeFileSync(exitFile, JSON.stringify(rec, null, 2) + "\n"); } catch {}
|
|
38
|
+
}
|
|
39
|
+
function finish(code, signal, spawnError) {
|
|
40
|
+
if (finished) return;
|
|
41
|
+
finished = true;
|
|
42
|
+
const rec = { exitCode: code, signal: signal || null, startedAt: new Date(startedMs).toISOString(), endedAt: new Date().toISOString(), childPid: child && child.pid };
|
|
43
|
+
if (spawnError) rec.spawnError = spawnError;
|
|
44
|
+
if (signal === "SIGKILL" || code === 137 || (code !== 0 && code !== null)) {
|
|
45
|
+
const oomAfter = cgroupOomKills();
|
|
46
|
+
if (oomBefore !== null && oomAfter !== null && oomAfter > oomBefore) {
|
|
47
|
+
rec.oomEvidence = { source: "cgroup", detail: "memory.events oom_kill " + oomBefore + " -> " + oomAfter };
|
|
48
|
+
} else if (signal === "SIGKILL" || code === 137) {
|
|
49
|
+
const pid = child && child.pid;
|
|
50
|
+
const hit = kernelLog().split("\n").find((l) => pid && new RegExp("(?:Killed process|oom-kill:.*pid=|Memory cgroup out of memory: Killed process) ?" + pid + "\\b").test(l));
|
|
51
|
+
if (hit) rec.oomEvidence = { source: "kernel_log", detail: hit.trim().slice(0, 300) };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
write(rec);
|
|
55
|
+
if (signal) {
|
|
56
|
+
const n = (require("os").constants.signals || {})[signal];
|
|
57
|
+
process.exit(128 + (n || 9));
|
|
58
|
+
}
|
|
59
|
+
process.exit(code === null ? 1 : code);
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
child = cp.spawn(cmd, args, { stdio: "inherit" });
|
|
63
|
+
} catch (e) {
|
|
64
|
+
process.stderr.write("failed to spawn worker process: " + (e && e.message) + "\n");
|
|
65
|
+
finish(127, null, String(e && e.message));
|
|
66
|
+
}
|
|
67
|
+
for (const s of ["SIGTERM", "SIGINT", "SIGHUP"]) process.on(s, () => { try { child.kill(s); } catch {} });
|
|
68
|
+
child.on("error", (e) => {
|
|
69
|
+
process.stderr.write("failed to spawn worker process: " + (e && e.message) + "\n");
|
|
70
|
+
if (!child.pid) finish(127, null, String(e && e.message));
|
|
71
|
+
});
|
|
72
|
+
child.on("exit", (code, signal) => finish(code, signal));
|
|
73
|
+
`});import zK from"node:path";function Df(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.handoffState;return typeof t=="string"&&QK.has(t)}function Xl(e){return!!(e&&XK.test(e))}function UR(e){if(e.noRestartAt?.trim())return"stopped_by_hand";if(e.finalResult&&!Df(e.finalResult))return"finished";if(e.alive)return e.stale?"stuck":"running";let t=e.error?.trim()??"",r=e.exit??null;if(r?.oomEvidence||Xl(t))return"oom";let n=e.reconcileReason??"";return/reconciled stale worker/i.test(n)?"stuck":BR.test(t)||BR.test(n)?"timed_out":r&&r.exitCode===0&&!r.signal&&!r.spawnError?"no_report":r&&(r.signal||r.spawnError||r.exitCode!==null&&r.exitCode!==0)||t?"crashed":"no_report"}function FR(e){let t=[ZK(e.stopClass)],r=LR(e.exit);r&&t.push(r),e.exit?.oomEvidence&&t.push(`evidence: ${e.exit.oomEvidence.detail}`),e.stopClass==="no_report"&&e.exit?.exitCode===0&&t.push("it exited normally but never sent a final report");let n=e.error?.replace(/\s+/g," ").trim();return n?t.push(`last output: ${n.length>300?`${n.slice(-300)}`:n}`):e.stopClass==="stuck"&&e.reconcileReason&&t.push(e.reconcileReason),t.join(" \u2014 ").slice(0,600)}function ZK(e){switch(e){case"finished":return"finished";case"oom":return"ran out of memory";case"crashed":return"crashed";case"no_report":return"stopped without reporting";case"timed_out":return"timed out";case"stuck":return"stuck (no progress)";case"stopped_by_hand":return"stopped on purpose";default:return"running"}}function KR(e,t=process.env){if(e<=0)return null;let r=Number.parseInt(t.KYNVER_NODE_OLD_SPACE_SIZE_MB??"",10),n=Number.isFinite(r)&&r>0?Math.max(r,WR/2):WR/2;return Math.min(e$,n*2**e)}function $R(e,t,r){let n=0,o;try{o=ne(e)}catch{return 0}for(let s of Object.keys(o.workers||{})){if(r&&s===r)continue;let i=F(zK.join(j(o.id),"workers",B(s),"worker.json"),void 0);if(!(!i||i.taskId!==t)){if(i.stopClass==="oom"||i.oomEvidence){n+=1;continue}if(zl(i.workerDir)?.oomEvidence){n+=1;continue}!i.stopClass&&i.stderrPath&&Xl(Eo(i.stderrPath,20))&&(n+=1)}}return n}function HR(e,t){if(!e)return t();let r=process.env.KYNVER_NODE_OLD_SPACE_SIZE_MB,n=process.env.NODE_OPTIONS;process.env.KYNVER_NODE_OLD_SPACE_SIZE_MB=String(e);let o=`--max-old-space-size=${e}`,s=(n??"").replace(/--max-old-space-size=\d+/g,"").trim();process.env.NODE_OPTIONS=s?`${s} ${o}`:o;try{return t()}finally{r===void 0?delete process.env.KYNVER_NODE_OLD_SPACE_SIZE_MB:process.env.KYNVER_NODE_OLD_SPACE_SIZE_MB=r,n===void 0?delete process.env.NODE_OPTIONS:process.env.NODE_OPTIONS=n}}var XK,BR,QK,WR,e$,Mf=p(()=>{"use strict";Y();M();lr();XK=/javascript heap out of memory|reached heap limit|allocation failed - process out of memory|\bout of memory\b|\boom[- ]?kill(?:ed|er)?\b|std::bad_alloc|cannot allocate memory|\benomem\b|exit(?:ed)? (?:with )?(?:code|status) 137\b|killed process \d+/i,BR=/\btimed? ?out\b|\btimeout\b|deadline exceeded/i,QK=new Set(["exited_without_final_result","exited_without_complete_heartbeat","exit_failure"]);WR=2048,e$=8192});function jR(e,t=240){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}function wi(e){let t=(e??"").trim();if(!t)return null;if(vi(t))return{blocked:!0,reason:`provider authentication failed: ${jR(t)}`};for(let r of t$)if(r.test.test(t))return{blocked:!0,reason:`${r.label}: ${jR(t)}`};return null}var t$,Lf=p(()=>{"use strict";ql();t$=[{test:/(?:claude provider refuses to spawn: worker prompt is empty after argv assembly|Input must be provided (?:either )?through stdin or as a prompt argument)/i,label:"provider prompt delivery failed"},{test:/\b(?:invalid|unknown|unsupported|unrecognized)\b[^.\n]*\bmodel\b/i,label:"provider rejected the requested model"},{test:/\bmodel\b[^.\n]*\b(?:not\s+(?:found|supported|available|recognized|valid)|is\s+not\s+valid|does\s+not\s+exist)/i,label:"provider rejected the requested model"},{test:/\b(?:did you mean|available models|choose (?:a|one of)|supported models)\b/i,label:"provider rejected the requested model"},{test:/model preflight failed/i,label:"model/provider preflight failed"},{test:/\b(?:command not found|ENOENT|is the .*CLI on PATH|executable not found|no such file or directory)\b/i,label:"provider CLI is missing or not on PATH"},{test:/\bfailed to spawn\b/i,label:"provider failed to spawn the worker process"},{test:/\b(?:not logged in|unauthorized|authentication (?:failed|required)|invalid api key|missing api key|401)\b/i,label:"provider authentication failed"},{test:/\b(?:out of usage|increase limits?|switch to auto|ask your admin to increase your limit|usage limits?|quota exceeded|insufficient_quota|credits? exhausted|billing|payment required)\b/i,label:"provider quota exhausted"}]});function VR(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function r$(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function n$(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:VR(e.head)}function o$(e,t,r){let n=["exited_with_changes_salvage"];if((e==="uncommitted"||e==="both")&&n.push(`${t} uncommitted change${t===1?"":"s"} with no final result`),(e==="committed_ahead"||e==="both")&&r){let o=r.length>12?r.slice(0,12):r;n.push(`commit ${o} ahead of base with no final result`)}return n.push("review worktree \u2014 commit, open a PR, or run a salvage worker before discarding"),n.join(": ")}function Mo(e){if(e.alive||r$(e.finalResult))return null;let t=(e.changedFiles??[]).filter(i=>i.trim()).length,r=VR(e.headCommit)??n$(e.gitAncestry),n=t>0,o=!!r;if(!n&&!o)return{kind:"none",salvageable:!1,uncommittedCount:0,headCommit:null,attentionReason:"process exited without a final result"};let s=n&&o?"both":n?"uncommitted":"committed_ahead";return{kind:s,salvageable:!0,uncommittedCount:t,headCommit:r,attentionReason:o$(s,t,r)}}var Ql=p(()=>{"use strict"});import{existsSync as s$,readFileSync as i$,statSync as qR}from"node:fs";import Zl from"node:path";function u$(e,t=process.env){let r=e?l$:a$,n=t.KYNVER_WORKER_GIT_PROBE_CACHE_TTL_MS?.trim();if(!n)return r;let o=Number(n);return Number.isFinite(o)&&o>=0?Math.floor(o):r}function d$(e){return e.baseCommit?.trim()||e.base?.trim()||"origin/main"}function Bf(e){try{return qR(e).mtimeMs}catch{return-1}}function p$(e){let t=Zl.join(e,".git");try{if(qR(t).isDirectory())return t;let r=/^gitdir:\s*(.+)$/m.exec(i$(t,"utf8"));return r?Zl.resolve(e,r[1].trim()):null}catch{return null}}function GR(e){let t=p$(e);return[Bf(e),t?Bf(Zl.join(t,"HEAD")):-2,t?Bf(Zl.join(t,"index")):-2].join(":")}function JR(e,t){return{changedFiles:fi(e),gitAncestry:Wl(e,{base:t.base,baseCommit:t.baseCommit})}}function f$(e,t){for(Wr.delete(e),Wr.set(e,t);Wr.size>c$;){let r=Wr.keys().next().value;if(r===void 0)break;Wr.delete(r)}}function YR(e,t,r){let n=d$(t);if(!e||!e.trim())return Si.missingWorktree++,{changedFiles:[],gitAncestry:Ao(n,"missing worktree path")};let o=`${e}\0${n}`;if(!s$(e))return Wr.delete(o),Si.missingWorktree++,{changedFiles:[],gitAncestry:Ao(n,`worktree no longer exists: ${e}`)};if(r.alive)return Wr.delete(o),Si.liveProbes++,JR(e,t);let s=r.ttlMs??u$(!!t.baseCommit?.trim()),i=r.now??Date.now(),a=GR(e),l=Wr.get(o);if(s>0&&l&&l.fingerprint===a&&i<l.expiresAt)return Si.hits++,l.probe;Si.misses++;let c=JR(e,t);if(s>0){let u=.8+.4*(r.random??Math.random)();f$(o,{fingerprint:GR(e),expiresAt:i+Math.round(s*u),probe:c})}return c}var a$,l$,c$,Wr,Si,zR=p(()=>{"use strict";we();a$=10*6e4,l$=60*6e4,c$=2048,Wr=new Map,Si={hits:0,misses:0,liveProbes:0,missingWorktree:0}});function _i(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function m$(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function g$(e){if(_i(e.headCommit)||_i(e.prUrl)||_i(e.artifactBundlePath)||_i(e.patchPath))return!0;let t=e.gitAncestry;return!!(t?.checked&&t.headIsAncestorOfBase===!1&&_i(t.head))}function Lo(e){return m$(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:g$(e)?{blocked:!0,detail:`Worktree has ${e.changedFiles.length} uncommitted change(s); commit or discard before landing`}:{blocked:!0,reason:"dirty_worktree_no_pr",detail:`Worktree has ${e.changedFiles.length} uncommitted change(s) with no commit or PR; commit, open a PR, or discard before landing`}:{blocked:!1}}function XR(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var ec=p(()=>{"use strict"});function Wf(e){let t=e.trim();if(!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&!Array.isArray(r))return r}catch{return null}return null}function QR(e){let t=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(t)?t.length:0}function Bo(e){let t=e.trim();if(!t)return null;let r=Wf(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let u=Wf(s[1]??"");u&&n.push(u)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let u=Wf(t.slice(i,a+1));u&&n.push(u)}if(n.length===0)return null;let l=n[n.length-1],c=QR(l);for(let u of n){let d=QR(u);d>c&&(l=u,c=d)}return l}var tc=p(()=>{"use strict"});function ZR(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:e.trim()||null}function ew(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function h$(e){return new Set(e.map(t=>ew(ZR(t)??t)).filter(Boolean))}function tw(e,t,r){let n=ZR(e)??e;if(!n)return"unrelated";let o=ew(n);return h$(t).has(o)?"contract":r?(r.outcome==="skipped"||r.outcome==="blocked")&&r.reason?.trim()?"support":(r.outcome==="merged","unrelated"):"unrelated"}var rw=p(()=>{"use strict"});function Wo(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function y$(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function wn(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:Wo(e)}function rc(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function nw(e){let t=null;if(typeof e=="string"){let o=Bo(e);o&&(t=o)}else e&&typeof e=="object"&&!Array.isArray(e)&&(t=e);if(!t)return[];let r=t.targetPrReconciliation??t.target_pr_reconciliation;if(!Array.isArray(r))return[];let n=[];for(let o of r){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=wn(String(s.prUrl??s.pr_url??"")),a=Wo(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:Wo(s.mergeCommit??s.merge_commit),reason:Wo(s.reason)})}return n}function ow(e,t){let r=[],n=wn(Wo(e.prUrl)??"");if(n&&r.push(n),t&&typeof t=="object"&&!Array.isArray(t)){let o=t,s=wn(String(o.prUrl??o.pr_url??""));s&&r.push(s)}return[...new Set(r)]}function sw(e){let{contract:t,snapshot:r}=e,n=e.finalResult??r.finalResult;if(!t.landingOnly&&t.targetPrUrls.length===0&&!t.repairEnforceOriginalPr)return{blocked:!1};if(!y$(n))return(t.requiresTargetPrReconciliation??(t.landingOnly||!!t.repairEnforceOriginalPr||t.targetPrUrls.length>0))&&t.targetPrUrls.length>0?{blocked:!0,reason:"missing_target_pr_reconciliation",detail:`Final result required to reconcile target PR(s): ${t.targetPrUrls.join(", ")}`}:{blocked:!1};if(!(t.requiresTargetPrReconciliation??(t.landingOnly||!!t.repairEnforceOriginalPr||t.targetPrUrls.length>0))&&!t.repairEnforceOriginalPr)return{blocked:!1};let s=t.repairEnforceOriginalPr?wn(Wo(t.targetPrUrl)??"")??(t.targetPrUrls.length===1?wn(t.targetPrUrls[0]):null):null;if(s){let d=ow(r,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let h of d)if(h!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${h} instead of canonical target ${s}`}}let g=nw(n).find(h=>h.prUrl===s);if(!g||g.outcome!=="merged"&&!(g.reason?.trim()&&(g.outcome==="skipped"||g.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=nw(n),a=new Map(i.map(d=>[rc(d.prUrl),d])),l=new Set(t.targetPrUrls.map(d=>rc(wn(d)??d)).filter(Boolean)),c=ow(r,n);if(t.landingOnly)for(let d of c){let f=a.get(rc(d)),m=tw(d,t.targetPrUrls,f);if(!(m==="contract"||m==="support"))return l.size>0?{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${d}`}:{blocked:!0,reason:"unrelated_implementation_pr",detail:"Landing-only worker must not open new implementation PRs"}}if(t.targetPrUrls.length===0)return{blocked:!1};let u=[];for(let d of t.targetPrUrls){let f=rc(wn(d)??d),m=a.get(f);if(!m){u.push(f);continue}m.outcome!=="merged"&&!m.reason?.trim()&&u.push(f)}return u.length>0?{blocked:!0,reason:u.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${u.join(", ")}`}:{blocked:!1}}function iw(e){if(e.blocked)return e.detail??e.reason}var aw=p(()=>{"use strict";tc();rw()});function b$(e){let t=Date.now();if(e.providerTerminalError||Jl(e.finalResult)||e.finalResult&&e.error?.trim()||vi(e.error)||vi(e.finalResult)){let o=e.error||(typeof e.finalResult=="string"?e.finalResult:"provider terminal error");return{state:"blocked",reason:wi(o)?.reason??`provider terminal error: ${o}`}}if(e.completionBlocker&&!lw(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&R$(e.finalResult))return{state:"done",reason:"local-only worker superseded by merged PR"};let o={finalResult:e.finalResult,changedFiles:e.changedFiles??[],gitAncestry:e.gitAncestry??null,prUrl:e.prUrl??null},s=Lo(o);if(s.blocked){let i=XR(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=sw({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=iw(i);if(a)return{state:"needs_attention",reason:i.reason?`landing contract (${i.reason}): ${a}`:`landing contract: ${a}`}}return{state:"done",reason:"final result recorded"}}if(!e.alive){if(v$(e))return{state:"done",reason:"empty abandoned worker record"};let o=wi(e.error);if(o)return{state:"blocked",reason:o.reason};let s=Mo({alive:!1,finalResult:null,changedFiles:e.changedFiles,gitAncestry:e.gitAncestry});if(s?.salvageable){let l=e.error?.trim();return{state:"needs_attention",reason:l?`${s.attentionReason} (${l})`:s.attentionReason}}let i=e.error?.trim(),a=Xl(i);return{state:"needs_attention",reason:i?`process exited without a final result${a?" (ran out of memory)":""}: ${i}`:s?.attentionReason??"process exited without a final result"}}if(e.heartbeatBlocker)return{state:"blocked",reason:`worker heartbeat reported blocker: ${e.heartbeatBlocker}`};let r=e.startedAt?Date.parse(e.startedAt):NaN;if(!e.firstEventAt&&e.stdoutBytes===0&&e.heartbeatBytes===0&&Number.isFinite(r)&&t-r>k$)return{state:"needs_attention",reason:`no first stream event ${mf(r)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&t-n>Uf?{state:"stale",reason:`no log/event/heartbeat activity for ${mf(n)}s`}:{state:"ok",reason:"recent activity"}}function lw(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function v$(e){return e.finalResult||e.taskId||e.agentOsId||e.stdoutBytes>0||(e.stderrBytes??0)>0||e.heartbeatBytes>0||e.error?.trim()||(e.changedFiles??[]).some(t=>t.trim())?!1:/empty worker dir|marked abandoned/i.test(e.reconcileReason??"")}function R$(e){let t=null;if(typeof e=="string"?t=Bo(e):e&&typeof e=="object"&&!Array.isArray(e)&&(t=e),!t)return!1;let r=t.targetPrReconciliation??t.target_pr_reconciliation;return Array.isArray(r)?r.some(n=>!n||typeof n!="object"||Array.isArray(n)?!1:String(n.outcome??"").trim()==="merged"):!1}function cw(e,t,r){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:t||(n??ar(r))}function uw(e){let t=Rn(e.stdoutPath),r=Ie(e.heartbeatPath);return cw(e,t.finalResult,r)}function ie(e,t={}){let r=Rn(e.stdoutPath),n=Ie(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=cw(e,r.finalResult,n),i=o?!1:re(e.pid),a=Dl(e.stdoutPath),l=Dl(e.stderrPath),c=Dl(e.heartbeatPath),{changedFiles:u,gitAncestry:d}=YR(e.worktreePath,{base:t.base,baseCommit:t.baseCommit},{alive:i}),f=Gv([r.lastEventAt,n.lastHeartbeatAt,Ml(e.stdoutPath),Ml(e.stderrPath),Ml(e.heartbeatPath)]),m=i?null:zl(e.workerDir),g=s&&!Df(s)?s:null,h=r.error||!i&&!s&&Eo(e.stderrPath,10).trim()||void 0,y=h||!i&&s&&!g&&Eo(e.stderrPath,10).trim()||void 0,v=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,k=lw(v)?null:v,b=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,_=b$({alive:i,finalResult:s,firstEventAt:r.firstEventAt,stdoutBytes:a,stderrBytes:l,heartbeatBytes:c,lastActivityAt:f,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:h,providerTerminalError:r.providerTerminalError,changedFiles:u,gitAncestry:d,completionBlocker:k,landingContract:b,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),S=k||_.state==="blocked"?"blocked":o||_.state==="done"?"done":s?"exited":i?"running":"exited",R=e.stopClass&&e.stopClass!=="running"&&e.stopClass!=="finished"?e.stopClass:null,w=UR({alive:i,finalResult:s,error:y??null,stale:_.state==="stale",noRestartAt:e.noRestartAt??null,reconcileReason:e.reconcileReason??null,exit:m}),L=R&&!i&&!g?R:w,N=L==="running"||L==="finished"?null:(R===L?e.stopReason:void 0)??FR({stopClass:L,exit:m,error:y??null,reconcileReason:e.reconcileReason??null});return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:S,stopClass:L,stopReason:N,exit:m,attention:_,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:l,heartbeatBytes:c,firstEventAt:r.firstEventAt,lastEventAt:r.lastEventAt,lastActivityAt:f,currentTool:o?null:r.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:s,error:h,providerTerminalError:r.providerTerminalError,changedFiles:u,gitAncestry:d,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.provider??e.orchestrationAudit?.provider??null,usage:r.usage??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function Be(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Ff(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}function nc(e,t){return t.length===0?e:t.some(r=>r.attention==="needs_attention"||r.attention==="stale"||r.attention==="blocked")?"needs_attention":t.every(r=>r.status==="done")?"done":t.some(r=>r.status==="running")?"running":e}var k$,Uf,Ce=p(()=>{"use strict";vn();Ri();Mf();lr();ql();Lf();Ql();zR();ec();aw();tc();M();k$=18e4,Uf=6e5});import{readFileSync as w$}from"node:fs";function S$(e){if(!e||process.platform!=="linux")return null;try{return w$(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ")}catch{return null}}function dw(e){if(!e.pid||process.platform!=="linux")return!0;let t=S$(e.pid);return t?[e.worktreePath,e.workerDir,e.heartbeatPath].filter(n=>typeof n=="string"&&n.trim().length>0).some(n=>t.includes(n)):!1}function Ur(e){return typeof e.completionBlocker=="string"&&e.completionBlocker.trim()||typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim()||!re(e.pid)||!dw(e)?!1:!uw(e)}var oc=p(()=>{"use strict";Ce();M()});import fw from"node:os";import mw from"node:path";function pw(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function _$(e=P(),t,r){let n=pw(e.perWorkerMemBytes,sc),o=pw(e.memReserveBytes,ic),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):ac)),i=Ko({config:e,configuredMaxWorkersOverride:t,totalMemBytes:r??fw.totalmem()});return{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i.configuredMaxWorkers,autoCap:i.autoCap,workerCapSource:i.workerCapSource}}function gw(e,t={}){let r=t.perWorkerMemBytes??sc,n=t.memReserveBytes??ic,o=t.memUtilization??ac,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/r));return Math.min(i,lc)}function x$(){return uR()}function C$(e){let t=0;for(let r of Ct(e)){let n=F(mw.join(j(e.id),"workers",B(r),"worker.json"),void 0);!n||!Ur(n)||t++}return t}function Kf(){let e=0;for(let t of Se())e+=C$(t);return e}function Uo(){let e=[];for(let t of Se())for(let r of Ct(t)){let n=F(mw.join(j(t.id),"workers",B(r),"worker.json"),void 0);n&&Ur(n)&&e.push({runId:t.id,workerName:r})}return e}function xi(e){let t=e.config??P(),r=e.totalMemBytes??fw.totalmem(),{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i,autoCap:a,workerCapSource:l}=_$(t,e.configuredMaxWorkersOverride,r),c=xt(t),u=e.freeMemBytes??x$(),d=e.activeWorkers??Kf(),f=Math.max(0,Math.floor(r*s)-o),m=Math.max(0,Math.floor(f/n)),g=Math.max(0,Math.floor(Math.max(0,u-o)/n)),h=a,y=ir(c,i??h),v=Math.max(0,Math.min(y,m)),k=Math.max(0,v-d),_=Math.min(k,g),R=e.skipDiskGate||process.env.KYNVER_RESOURCE_GATE_SKIP_DISK==="1"?void 0:Br({diskPath:e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/"});R&&!R.ok&&(_=0);let w=null;return _<=0&&(R&&!R.ok?w=R.reason??"disk gate blocked worker admission":d>=v?w=`at worker limit (${d}/${v} running)`:g<=0?w="insufficient free memory \u2014 waiting for workers to finish":w="no worker slots available"),{ok:_>0,totalMemBytes:r,freeMemBytes:u,memReserveBytes:o,perWorkerMemBytes:n,configuredMaxWorkers:i,workerCapSource:l,boxKind:c,autoCap:h,capacityWorkers:m,maxConcurrentWorkers:v,activeWorkers:d,slotsAvailable:_,reason:w,...R?{diskGate:R}:{}}}var sc,ic,ac,lc,Fo=p(()=>{"use strict";dR();$();Le();Io();Ci();yi();Y();No();oc();M();sc=500*1024*1024,ic=4*1024*1024*1024,ac=.85,lc=64});function Ei(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function Ko(e){let t=e.config??{},r=e.env??process.env,n=Ei(t.perWorkerMemBytes,sc),o=Ei(t.memReserveBytes,ic),s=Math.min(1,Math.max(.1,Number(t.memUtilization)>0?Number(t.memUtilization):ac)),i=gw(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Ei(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(t.maxConcurrentWorkers!==void 0&&t.maxConcurrentWorkers!==null){let c=Ei(t.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,lc),autoCap:i,workerCapSource:"config"}}let l=(r.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||r.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&r.KYNVER_MAX_WORKERS&&Ei(r.KYNVER_MAX_WORKERS,0)||null;return l?{configuredMaxWorkers:Math.min(l,lc),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var Ci=p(()=>{"use strict";Fo()});import{existsSync as E$,mkdirSync as Yie,readFileSync as A$,writeFileSync as zie}from"node:fs";import{homedir as P$}from"node:os";import I$ from"node:path";function O$(e){let t=new Map;for(let r of e.split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("=");if(o<=0)continue;let s=n.slice(0,o).trim(),i=n.slice(o+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t.set(s,i)}return t}function cc(e=Fr){return E$(e)?O$(A$(e,"utf8")):new Map}function hw(e=Fr,t={}){let r=cc(e),n=0,o=0;for(let[s,i]of r){if(!t.override&&process.env[s]!=null){o++;continue}process.env[s]=i,n++}return{path:e,loaded:n,skipped:o}}var Fr,cr=p(()=>{"use strict";Fr=I$.join(P$(),".kynver",".env")});var yw=p(()=>{"use strict"});var kw=p(()=>{"use strict";yw()});var uc=p(()=>{"use strict"});import{existsSync as T$,readFileSync as N$}from"node:fs";import{homedir as D$}from"node:os";import M$ from"node:path";function Hf(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function $f(e){return typeof e=="string"&&e.trim()?e:null}function jf(e){let t=Hf(e);if(!t)return null;let r=t.desiredState;if(r!=="running"&&r!=="paused"&&r!=="stopped")return null;let n=t.policyVersion;if(typeof n!="number"||!Number.isInteger(n)||n<0)return null;let o=$f(t.requestedAt);return o?{desiredState:r,policyVersion:n,requestedAt:o,requestedByLabel:$f(t.requestedByLabel),reason:$f(t.reason)}:null}function bw(e){let t=Hf(Hf(e)?.response);return!t||t.runtimeControl===void 0?null:jf(t.runtimeControl)}function vw(e,t=D$()){let r=e.replace(/[^A-Za-z0-9_-]/g,"_");return M$.join(t,".kynver",`runtime-control-${r}.json`)}function Vf(e,t,r){try{let n=Kr(e,r);if(n&&n.policyVersion>t.policyVersion)return;be(vw(e,r),{contractVersion:1,agentOsId:e,control:t,deliveredAt:new Date().toISOString()})}catch{}}function Kr(e,t){try{let r=vw(e,t);if(!T$(r))return null;let n=JSON.parse(N$(r,"utf8"));return n.agentOsId!==e?null:jf(n.control)}catch{return null}}function $o(e){return e?.desiredState??"running"}function L$(e){return e==="keeper"||e==="desktop"}function B$(e,t,r=!1){let n=$o(e);return n==="paused"?"paused":n==="stopped"?r&&t===0?"stopped":"stopping":"running"}function pc(e){return e.control?{policyVersion:e.control.policyVersion,state:B$(e.control,e.inFlightWorkers,e.exiting),supervised:L$(e.supervisor),inFlightWorkers:Math.max(0,Math.floor(e.inFlightWorkers))}:null}function Rw(e){let t=$o(e);return t==="paused"?"runtime_paused":t==="stopped"?"runtime_stopped":null}function ww(e,t){return $o(e)==="stopped"&&t===0}function _w(e){Sw=e}function xw(){return Sw}var dc,Sw,$r=p(()=>{"use strict";M();dc=83;Sw=null});var Ai,Ho=p(()=>{"use strict";kw();uc();$r();Ai="kynver-cron-daemon.service"});import{existsSync as W$,readFileSync as U$}from"node:fs";function Gf(){if(process.platform==="win32")return"win32";if(process.platform==="darwin")return"darwin";if(process.platform==="linux"){if(process.env.WSL_DISTRO_NAME?.trim())return"wsl";try{if(W$("/proc/version")){let e=U$("/proc/version","utf8");if(/microsoft/i.test(e))return"wsl"}}catch{}return"linux"}return"linux"}var fc=p(()=>{"use strict"});var Jf=p(()=>{"use strict";fc()});var Pi=p(()=>{"use strict";cr();at();$();Ho();Jf()});import H$ from"node:os";function Ii(e,t){let r=(t??H$.hostname()).trim().toLowerCase().replace(/\s+/g,"-")||"unknown-host";return`${e}:${r}`}function Ew(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function mc(e,t){let r=e.trim();if(!r)return Ii(t);let n=r.indexOf(":");if(n>=0){let o=r.slice(0,n).trim().toLowerCase()||t,s=Ew(r.slice(n+1));return s?`${o}:${s}`:Ii(o)}return`${t}:${Ew(r)}`}function jo(e){let t=e.explicitBoxId?.trim()||e.env?.KYNVER_BOX_ID?.trim()||e.config?.boxId?.trim();return t?mc(t,e.boxKind):Ii(e.boxKind,e.hostLabel)}var Vo=p(()=>{"use strict";Le();Le()});var Aw=p(()=>{"use strict";cr();Ho();Pi()});import{existsSync as ur,mkdirSync as j$,readdirSync as gc,renameSync as Pw,statSync as V$}from"node:fs";import dr from"node:path";function Ow(e){try{return V$(e).isDirectory()}catch{return!1}}function G$(e){if(!ur(e))return!0;for(let t of Iw){let r=dr.join(e,t);if(ur(r)&&(!Ow(r)||gc(r).length>0))return!1}return!0}function J$(e){let t=dr.join(e,"runs");if(!ur(t)||!Ow(t))return!1;for(let r of gc(t,{withFileTypes:!0})){if(!r.isDirectory()||r.name==="runs")continue;let n=dr.join(t,r.name,"run.json");if(F(n,void 0)?.id)return!0}return!1}function q$(e){let t=dr.join(e,"runs");if(!ur(t))return!1;for(let r of gc(t,{withFileTypes:!0})){if(!r.isDirectory())continue;if(F(dr.join(t,r.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function Y$(e){let t=dr.join(e,"ghost");return ur(t)?!ur(dr.join(t,"runs")):q$(e)}function Tw(e){return J$(e.sharedRoot)?G$(e.forgeRoot)?Y$(e.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function Nw(e,t){j$(t,{recursive:!0});for(let r of Iw){let n=dr.join(e,r),o=dr.join(t,r);if(ur(n)){if(ur(o)&&gc(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(ur(o)){Pw(n,o);continue}Pw(n,o)}}}var Iw,Dw=p(()=>{"use strict";M();Iw=["runs","worktrees"]});import{existsSync as Ue}from"node:fs";import{homedir as z$}from"node:os";import Oe from"node:path";function qf(e=process.env){return e.HOME?.trim()||z$()}function Yf(e=process.env){return Oe.join(qf(e),".kynver","harness")}function hc(e){let t=Oe.resolve(Me(e.trim()));for(;X$.has(Oe.basename(t));)t=Oe.dirname(t);return t}function Q$(e,t=process.env){return Oe.join(Yf(t),e)}function Z$(e=process.env){let t=Yf(e);if(Ue(Oe.join(t,"runs")))return!0;if(Ue(t)&&!Ue(Oe.join(t,"ghost"))&&!Ue(Oe.join(t,"forge")))return Ue(t);let r=Oe.join(qf(e),Mw);return Ue(r)}function yc(e){let t=e.env??process.env,r=t.KYNVER_HARNESS_ROOT?.trim()||t.OPUS_HARNESS_ROOT?.trim();if(r)return{harnessRoot:hc(r),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:hc(n),source:"config"};let o=Q$(e.boxKind,t);if(Ue(Oe.join(o,"runs"))||Ue(o)&&!eH(o))return{harnessRoot:o,source:"box_scoped"};let i=Yf(t);if(e.boxKind==="forge"){let a=Tw({sharedRoot:i,forgeRoot:o});if(a.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:a.blocker};if(a.action==="migrate")return e.allowForgeLegacyMigration!==!1&&Nw(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&Z$(t)){if(Ue(Oe.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(Ue(i)&&!Ue(Oe.join(i,"ghost"))&&!Ue(Oe.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let l=Oe.join(qf(t),Mw);if(Ue(l))return{harnessRoot:l,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function eH(e){if(!Ue(e))return!0;for(let t of["runs","worktrees"]){let r=Oe.join(e,t);if(Ue(r))return!1}return!0}var Mw,X$,zf=p(()=>{"use strict";at();Dw();Mw=Oe.join(".openclaw","harness");X$=new Set(["runs","worktrees"])});import Lw from"node:os";function kc(e){return e?.trim()?e.trim():null}function tH(e,t){let r=t.trim().toLowerCase()||"host";return`${e}-${r}`.replace(/[^a-z0-9._-]+/g,"-")}function rH(e){return e.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||e.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||e.KYNVER_DAEMON_STRICT_IDENTITY==="1"||e.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function Wt(e=P(),t=process.env,r={}){let n=et(t,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||kc(t.KYNVER_BOX_KIND)),a=r.strict===!0||rH(t);if((r.requireExplicitBoxKind||a)&&!i&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup` (customers: boxKind=box) or `kynver setup --box-kind forge|ghost` for operator pools before dispatch"),n.slugInferenceBlocked&&!i){let h="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";a||r.requireExplicitBoxKind?s.push(h):o.push(`${h} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let l=kc(e.runnerId),c=kc(t.KYNVER_RUNTIME_ID)??kc(t.OPENCLAW_RUNTIME_ID),u=l??c??tH(n.boxKind,Lw.hostname()),d=l?"config":c?"env":"derived";d==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${u}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let f=Ko({config:e,env:t,totalMemBytes:Lw.totalmem()}),m=ir(n.boxKind,f.configuredMaxWorkers??wf(n.boxKind,f.autoCap)),g=yc({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:t});return g.migrationBlocker&&s.push(g.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:u,runnerIdSource:d,maxConcurrentWorkers:m,workerCapSource:f.workerCapSource,harnessRoot:g.harnessRoot,harnessRootSource:g.source},errors:s,warnings:o}}var Sn=p(()=>{"use strict";$();Le();Io();Ci();zf()});var Xf=p(()=>{"use strict";mi();Le();Vo();$();Pi();Aw();sr();St();Sn()});function je(e){let t=e.trim().toLowerCase();return oH[t]??t}var Uw,nH,oH,Oi=p(()=>{"use strict";Uw=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],nH=Uw.join("|"),oH={anthropic:"claude",opus:"claude",openai:"openai-compatible",openai_compatible:"openai-compatible","openai-compat":"openai-compatible",chatgpt:"codex",gpt:"codex","openai-api":"openai-compatible",openai_api:"openai-compatible",google:"gemini",gemini_cli:"gemini",gemini_api:"gemini-api","google-api":"gemini-api",google_api:"gemini-api"}});import{mkdirSync as Kw}from"node:fs";import{homedir as $w}from"node:os";import bc from"node:path";function Go(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Hw.includes(t)?t:null}function _n(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(typeof r!="string"||!r.trim()||r.includes("\0"))continue;let n=Me(r.trim());if(t.includes(n)||t.push(n),t.length>=iH)break}return t}function vc(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e.others==="default"?"default":null,n=e.byBox;if(!n||typeof n!="object"||Array.isArray(n)||!Object.prototype.hasOwnProperty.call(n,t))return r;let o=n[t];if(!o||typeof o!="object")return null;let s=o,i=Go(s.access);return i?{access:i,folders:_n(s.folders)}:null}function Rc(e){return sH.has(e)?"folder":"off"}function Fw(e=$w()){let t=bc.join(e,".kynver",jw);return Kw(t,{recursive:!0}),t}function Jo(e){let t=e.home??$w(),r=Go(e.local?.chatComputerAccess),n,o;r==="off"?(n={access:"off",folders:[]},o="local_off"):e.website==="default"?(n={access:"off",folders:[]},o="default"):e.website?(n=e.website,o="website"):r?(n={access:r,folders:_n(e.local?.chatWorkFolders)},o="local"):(n={access:Rc(e.engine),folders:[]},o="default");let{access:s}=n;if(s==="off")return{access:s,folders:[],workDir:Fw(t),extraFolders:[],source:o};let i=n.folders;s==="folder"&&(i=i.slice(0,1)),i.length===0&&s!=="full"&&(i=[Fw(t)]);for(let l of i)try{Kw(l,{recursive:!0})}catch{}let a=i[0]??t;return{access:s,folders:i,workDir:a,extraFolders:s==="folders"?i.slice(1):[],source:o}}function wc(e,t){if(e.access==="off")return!1;if(e.access==="full")return!0;let r=bc.resolve(t);return e.folders.some(n=>{let o=bc.relative(n,r);return o===""||!o.startsWith("..")&&!bc.isAbsolute(o)})}var Hw,sH,iH,jw,xn=p(()=>{"use strict";at();Hw=["off","folder","folders","full"],sH=new Set(["cursor","codex","antigravity"]),iH=16,jw="chat-workspace"});var Vw=p(()=>{"use strict";xn()});import{execFileSync as aH}from"node:child_process";function em(e=process.env){let t=e[lH]?.trim().toLowerCase();return t==="file"?"file":t==="keychain"?"keychain":"auto"}function cH(e,t,r){let n={encoding:"utf8",timeout:r.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...r.input!==void 0?{input:r.input}:{}};return aH(e,t,n)}function uH(e=process.platform){return e==="darwin"?"macos":e==="linux"?"libsecret":e==="win32"?"windows":null}function Qf(e,t){let r=JSON.stringify(Cn),n=JSON.stringify(t),o="[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]; $v = New-Object Windows.Security.Credentials.PasswordVault;";return e==="get"?`${o} try { $c = $v.Retrieve(${r}, ${n}); $c.RetrievePassword(); [Console]::Out.Write($c.Password) } catch { exit 3 }`:e==="set"?`${o} $s = [Console]::In.ReadToEnd().TrimEnd("\`r","\`n"); try { $old = $v.Retrieve(${r}, ${n}); $v.Remove($old) } catch {}; $v.Add((New-Object Windows.Security.Credentials.PasswordCredential(${r}, ${n}, $s)))`:`${o} try { $old = $v.Retrieve(${r}, ${n}); $v.Remove($old) } catch {}`}function Gw(e={}){if(em(e.env??process.env)==="file")return null;let r=uH(e.platform??process.platform);return r?new Zf(r,e.exec):null}var Cn,lH,pr,Zf,Jw=p(()=>{"use strict";Cn="kynver",lH="KYNVER_CREDENTIAL_STORE";pr=5e3;Zf=class{constructor(t,r=cH){this.backend=t;this.exec=r}backend;exec;get(t){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",Cn,"-a",t,"-w"],{timeoutMs:pr}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",Cn,"account",t],{timeoutMs:pr}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",Qf("get",t)],{timeoutMs:pr}).replace(/\r?\n$/,"");return n||null}catch{return null}}set(t,r){if(!r||/[\r\n]/.test(r))return!1;try{this.backend==="macos"?this.exec("security",["add-generic-password","-U","-s",Cn,"-a",t,"-l",`Kynver (${t})`,"-w",r],{timeoutMs:pr}):this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${t})`,"service",Cn,"account",t],{input:`${r}
|
|
74
|
+
`,timeoutMs:pr}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",Qf("set",t)],{input:`${r}
|
|
75
|
+
`,timeoutMs:pr})}catch{return!1}return this.get(t)===r}delete(t){try{this.backend==="macos"?this.exec("security",["delete-generic-password","-s",Cn,"-a",t],{timeoutMs:pr}):this.backend==="libsecret"?this.exec("secret-tool",["clear","service",Cn,"account",t],{timeoutMs:pr}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",Qf("delete",t)],{timeoutMs:pr})}catch{}}}});function zo(){return tm||(tm=new rm),tm}var qo,Yo,dH,Sc,rm,tm,qw=p(()=>{"use strict";Jw();qo="api-key",Yo="chat-box-credential",dH=6e4,Sc=class extends Error{constructor(t){super(`KYNVER_CREDENTIAL_STORE=keychain but the OS keychain could not store "${t}"; refusing to write the secret to disk`),this.name="KeychainUnavailableError"}},rm=class{cache=new Map;keychain;env;now;constructor(t={}){this.env=t.env??process.env,this.keychain=t.keychain===void 0?Gw({env:this.env}):t.keychain,this.now=t.now??Date.now}get available(){return this.keychain!==null}get backend(){return this.keychain?.backend??null}read(t){if(!this.keychain)return null;let r=this.cache.get(t);if(r&&this.now()-r.at<dH)return r.value;let n=this.keychain.get(t);return this.cache.set(t,{value:n,at:this.now()}),n}write(t,r){let n=em(this.env);if(!this.keychain){if(n==="keychain")throw new Sc(t);return!1}let o=this.keychain.set(t,r);if(o)this.cache.set(t,{value:r,at:this.now()});else if(this.cache.delete(t),n==="keychain")throw new Sc(t);return o}remove(t){this.cache.delete(t),this.keychain?.delete(t)}invalidate(t){t?this.cache.delete(t):this.cache.clear()}},tm=null});import{existsSync as Yw,mkdirSync as zw,readFileSync as Xw,writeFileSync as Qw}from"node:fs";import{homedir as mH,totalmem as Cle}from"node:os";import sm from"node:path";function Xo(e){let t=String(e??"").trim();if(!t)return{ok:!1,reason:"missing"};let r=t.toLowerCase();return hH.has(r)?{ok:!1,value:t,reason:"placeholder"}:gH.test(t)?{ok:!0,value:t}:{ok:!1,value:t,reason:"not a UUID"}}function im(e){let t=Xo(e),r=t.value??String(e??"").trim(),n=r?`"${r}"`:"<empty>",o=t.reason==="placeholder"?"looks like a placeholder":t.reason??"is invalid";return[`Invalid AgentOS id ${n}: ${o}.`,"AgentOS ids are UUIDs from the AgentOS registry, not slugs or examples (for example, not `aos`).","Fix: run `kynver bootstrap` to relink this runner, or run `kynver setup --agent-os-id <uuid>` / pass `--agent-os-id <uuid>` after copying the id from Command Center.","If this came from stale ~/.kynver/config.json, remove or replace the agentOsId value before starting the daemon."].join(" ")}function Zw(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:Me(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:Me(e.defaultRepo.trim())}:{}}}function P(){if(!Yw(nm))return{};try{return Zw(JSON.parse(Xw(nm,"utf8")))}catch{return{}}}function We(e){zw(xc,{recursive:!0}),Qw(nm,`${JSON.stringify(Ww(e),null,2)}
|
|
76
|
+
`,{mode:384})}function Ww(e){return Zw(e)}function am(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:He(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:He(e.defaultRepo.trim())}:{},...e.chatWorkFolders?.length?{chatWorkFolders:e.chatWorkFolders.map(He)}:{}}}function fr(){if(pf(),!Yw(om))return{};try{return JSON.parse(Xw(om,"utf8"))}catch{return{}}}function Ti(e){pf(),zw(xc,{recursive:!0}),Qw(om,`${JSON.stringify(e,null,2)}
|
|
77
|
+
`,{mode:384})}function eS(e,t,r,n={}){let o=fr();if(zo().write(e,r)){let i={...o,...n};delete i[t],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],e])).sort(),Ti(i);return}Ti({...o,...n,[t]:r})}function tS(e,t){let r=zo().read(e);return r||fr()[t]}function rS(){if(Qe())return{backend:null,moved:[],stillInFile:[]};let e=zo(),t=fr(),r=[],n=[],o=[[qo,"apiKey"],[Yo,"chatBoxCredential"]];for(let[s,i]of o){let a=t[i];a&&(e.available&&e.write(s,a)?r.push(i):n.push(i))}if(r.length>0){let s={...fr()};for(let i of r)delete s[i];s.store="keychain",s.keychainAccounts=Array.from(new Set([...s.keychainAccounts??[],...r.map(i=>i==="apiKey"?qo:Yo)])).sort(),Ti(s)}return{backend:e.backend,moved:r,stillInFile:n}}function lm(){return Kv(yH)}function _e(){return lm().getApiKey()}function Te(e){return lm().getRunnerToken(e)}function En(e,t){lm().persistRunnerToken(e,t)}function cm(e){let t=Pe("KYNVER_CHAT_BOX_CREDENTIAL");if(t)return t;if(Qe())return _c?.agentOsId===e?_c.credential:void 0;let r=fr();if(!(r.chatBoxCredentialAgentOsId&&r.chatBoxCredentialAgentOsId!==e))return tS(Yo,"chatBoxCredential")}function nS(e,t){if(Qe()){_c={agentOsId:e,credential:t};return}eS(Yo,"chatBoxCredential",t,{chatBoxCredentialAgentOsId:e})}function oS(){if(Qe()){_c=null;return}zo().remove(Yo);let e={...fr()};delete e.chatBoxCredential,delete e.chatBoxCredentialAgentOsId,Ti(e)}function sS(){let e=zo();return process.env.KYNVER_API_KEY?{backend:e.backend,apiKey:"env"}:e.read(qo)?{backend:e.backend,apiKey:"keychain"}:fr().apiKey?{backend:e.backend,apiKey:"file"}:{backend:e.backend,apiKey:"none"}}function pe(e){let t=Ni(e);return t||lS("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),t}function An(e){return Ni(e)}function Ni(e){let t=e||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||P().apiBaseUrl;return or(t)}function kH(e,t){let r=e||Te(t)||(t?void 0:Te(P().agentOsId));if(r)return String(r);let n=Pe("KYNVER_RUNTIME_SECRET")||Pe("KYNVER_CRON_SECRET")||Pe("OPENCLAW_CRON_SECRET");if(n)return console.warn("[kynver] using deployment-level callback secret; run `kynver runner credential --agent-os-id <id>` for a scoped token"),String(n)}async function Cc(e,t,r){let n=kH(e,t);if(n)return{ok:!0,secret:n};let o=_e(),s=Ni(r?.baseUrl);if(o&&t&&s)try{let i=await Pn(t,{baseUrl:s,apiKey:o});return En(t,i),{ok:!0,secret:i}}catch(i){return{ok:!1,reason:`runner credential mint failed: ${i.message}`}}return{ok:!1,reason:"no runner credential: requires --secret, KYNVER_RUNNER_TOKEN, a scoped runner token (`kynver runner credential`), ~/.kynver/credentials runnerToken, or KYNVER_API_KEY + API base URL to mint one"}}async function me(e,t,r){let n=await Cc(e,t,r);if(n.ok)return n.secret;lS(n.reason)}async function iS(e,t){let r=_e(),n=Ni(t?.baseUrl);if(!r||!e||!n)return null;try{let o=await Pn(e,{baseUrl:n,apiKey:r});return En(e,o),o}catch{return null}}async function aS(e,t,r){let n=_e(),o=Ni(r?.baseUrl);if(!n)return{ok:!1,reason:"KYNVER_API_KEY is required to refresh a rejected runner token"};if(!t)return{ok:!1,reason:"agentOsId is required to refresh a rejected runner token"};if(!o)return{ok:!1,reason:"KYNVER_API_URL or --base-url is required to refresh a rejected runner token"};try{let s=await Pn(t,{baseUrl:o,apiKey:n});return s&&s!==e?(En(t,s),{ok:!0,token:s}):{ok:!1,reason:"runner credential refresh returned the rejected token"}}catch(s){return{ok:!1,reason:s.message}}}async function Pn(e,t){let r=t?.apiKey||_e();if(!r)throw new Error("API key required \u2014 run `kynver login` first");let o=`${pe(t?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(e)}/runner-credentials`,s=await ut(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(t?.enableMcpUpdates?{enableMcpUpdates:!0}:{})}),i=await s.text(),a=null;try{a=JSON.parse(i)}catch{a=null}if(!s.ok||!a?.token)throw new Error(`runner credential mint failed (${s.status}): ${a?.error??i.slice(0,200)}`);return a.token}function lS(e){console.error(e),process.exit(1)}var xc,nm,om,gH,hH,$le,Hle,yH,_c,$=p(()=>{"use strict";mi();at();sr();Le();Io();Ci();yi();Pi();Xf();Oi();Sn();Vw();St();qw();xc=sm.join(mH(),".kynver"),nm=sm.join(xc,"config.json"),om=sm.join(xc,"credentials"),gH=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,hH=new Set(["aos","aos-1","agent-os-id","agentosid","agent_os_id","<agent-os-id>","<agentosid>","todo","changeme","change-me","placeholder"]);$le=500*1024*1024,Hle=4*1024*1024*1024;yH={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:tS(qo,"apiKey")},getRunnerToken(e){let t=fr();if(!!t.runnerToken&&!!e&&t.runnerTokenAgentOsId===e)return t.runnerToken;let n=process.env.KYNVER_RUNNER_TOKEN?.trim();if(n)return n;if(t.runnerToken&&!(e&&t.runnerTokenAgentOsId&&t.runnerTokenAgentOsId!==e))return t.runnerToken},persistApiKey(e){eS(qo,"apiKey",e)},persistRunnerToken(e,t){Ti({...fr(),runnerToken:t,runnerTokenAgentOsId:e})}};_c=null});import um from"node:path";function Ne(e){return hc(e)}function dt(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return Ne(e);let t=P(),r=t.harnessRoot?.trim();if(r)return Ne(r);let n=Wt(t,process.env);return n.identity?n.identity.harnessRoot:yc({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function rt(e){return um.join(Ne(e),"runs")}function Qo(e){return um.join(Ne(e),"worktrees")}function cS(){let e=dt();return{harnessRoot:e,runsDir:rt(e),worktreesDir:Qo(e)}}function mr(e,t){return um.join(e,B(t))}var Et=p(()=>{"use strict";$();zf();Sn();M()});import{existsSync as Ec,readdirSync as bH,statSync as vH}from"node:fs";import In from"node:path";function he(){return cS()}function ne(e){let{runsDir:t}=he(),r=In.join(mr(t,B(e)),"run.json");return Ec(r)||lt(`run '${e}' not found`),F(r)}function Se(){let{runsDir:e}=he();return uS(e)}function Ac(e){return uS(rt(e))}function RH(e){try{return vH(e).isDirectory()}catch{return!1}}function uS(e){if(!Ec(e))return[];let t=[];for(let r of bH(e,{withFileTypes:!0})){if(r.name==="runs")continue;let n=In.join(e,r.name);if(!RH(n))continue;let o=F(In.join(n,"run.json"),void 0);o?.id&&t.push(o)}return t}function On(e,t){let{runsDir:r}=he(),n=In.join(mr(r,B(e)),"run.json"),o=In.join(mr(r,B(e)),"workers",B(t),"worker.json");return Ec(o)||(Ec(n)||lt(`run '${e}' not found`),lt(`worker '${t}' not found in run '${e}'`)),F(o)}function Ve(e){let{runsDir:t}=he();be(In.join(mr(t,e.id),"run.json"),e)}function X(e,t){let{runsDir:r}=he();be(In.join(mr(r,e),"workers",t.name,"worker.json"),t)}function j(e){let{harnessRoot:t}=he();return Di(t,e)}function Di(e,t){return mr(rt(e),B(t))}var Y=p(()=>{"use strict";Et();M()});import wH from"node:path";function SH(e){let t=Array.isArray(e.ownedPaths)?e.ownedPaths.filter(n=>typeof n=="string"):[],r=Array.isArray(e.writeSetPrefixes)?(e.writeSetPrefixes??[]).filter(n=>typeof n=="string"):[];return{...t.length?{ownedPaths:t}:{},...r.length?{writeSetPrefixes:r}:{},...e.allowConcurrentHotspot?{allowConcurrentHotspot:!0}:{}}}function Zo(e){let t=ne(e),r=[];for(let n of Object.keys(t.workers||{})){let o=F(wH.join(j(t.id),"workers",B(n),"worker.json"),void 0);!o?.taskId||!Ur(o)||r.push({runId:t.id,workerName:n,taskId:o.taskId,pid:o.pid,...SH(o)})}return r}var Pc=p(()=>{"use strict";Y();oc();M()});function dm(e){return typeof e=="object"&&e!==null&&e.type===Ic}function dS(e,t=process){let r=!1,n=a=>{r||(r=!0,e(a))},s=["SIGINT","SIGTERM","SIGBREAK","SIGHUP"].map(a=>{let l=()=>n(a);return t.on(a,l),[a,l]}),i=a=>{dm(a)&&n("ipc")};return t.on("message",i),t.channel?.unref?.(),()=>{for(let[a,l]of s)t.off(a,l);t.off("message",i)}}function pS(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return[];let n=t.collect??Zo,o=t.killTree??fe,s;try{s=n(e)}catch{return[]}let i=[];for(let a of s)a.pid&&i.push({workerName:a.workerName,pid:a.pid,result:o(a.pid,"SIGKILL")});return i}var Ic,Oc=p(()=>{"use strict";Pc();ci();Ic="kynver:daemon-stop"});import{createHash as _H}from"node:crypto";function nt(e){return JSON.stringify(pm(e))}function pm(e){if(Array.isArray(e))return e.map(pm);if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=pm(e[r]);return t}return e}function fS(e){return`ib-${_H("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function es(e){if(!e)return null;let t=e.trim();if(!t)return null;if(/^[0-9a-fA-F]{64}$/.test(t))return new Uint8Array(t.match(/.{2}/g).map(r=>parseInt(r,16)));try{let r=Buffer.from(t,"base64");if(r.length===32)return new Uint8Array(r)}catch{}return null}function Mi(e){if(!e||typeof e!="object")return!1;let t=e;if(typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let r=t.bundle;return!(!r||typeof r!="object"||typeof r.version!="string"||!r.version||typeof r.generatedAt!="string"||!Array.isArray(r.personas)||!r.instructions||typeof r.instructions!="object"||!r.policyThresholds||typeof r.policyThresholds!="object")}function Tc(e=process.env){if(e.NODE_ENV==="production")return!1;let t=e.KYNVER_ALLOW_DEV_SIGNING_KEYS?.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"?!0:e.NODE_ENV==="test"||e.VITEST==="true"}var Hr=p(()=>{"use strict"});import{createHash as xH,createPublicKey as CH,verify as EH}from"node:crypto";function IH(e){return`ca-${xH("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function Tn(e,t=process.env){let r=es(t.KYNVER_COMMAND_AUTH_PUBLIC_KEY);if(r)return IH(r)!==e?null:r;let n=PH[e];return!n||e===mS&&!Tc(t)?null:es(n)}function OH(e){return CH({key:Buffer.concat([AH,Buffer.from(e)]),format:"der",type:"spki"})}function TH(e,t){return!Array.isArray(e)||e.length!==t.length?!1:e.every((r,n)=>typeof r=="string"&&r===t[n])}function NH(e){if(!e||typeof e!="object")return!1;let t=e;if(typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let r=t.payload;return!(!r||typeof r!="object"||r.v!==1||typeof r.agentOsId!="string"||!r.agentOsId||!Array.isArray(r.argv)||r.argv.some(n=>typeof n!="string")||typeof r.userId!="string"||!r.userId||typeof r.exp!="number"||!Number.isFinite(r.exp)||typeof r.nonce!="string"||!r.nonce)}function gS(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!NH(e))return{ok:!1,reason:"malformed command authorization proof"};if(e.payload.agentOsId!==t.agentOsId)return{ok:!1,reason:"agentOsId mismatch"};if(!TH(e.payload.argv,t.argv))return{ok:!1,reason:"argv mismatch"};if(e.payload.exp<=n)return{ok:!1,reason:"proof expired"};let o=Tn(e.publicKeyId,r);if(!o)return{ok:!1,reason:`no verification key for publicKeyId "${e.publicKeyId}"`};let s;try{s=Buffer.from(e.signature,"base64url")}catch{return{ok:!1,reason:"signature is not base64url"}}if(s.length!==64)return{ok:!1,reason:"signature is not a 64-byte Ed25519 signature"};try{let i=Buffer.from(nt(e.payload),"utf8");return EH(null,i,OH(o),s)?{ok:!0,payload:e.payload}:{ok:!1,reason:"Ed25519 signature mismatch"}}catch(i){return{ok:!1,reason:`signature verification failed: ${i.message}`}}}var AH,mS,PH,Li=p(()=>{"use strict";Hr();AH=Buffer.from("302a300506032b6570032100","hex"),mS="ca-6297fb8e1773",PH={[mS]:"16ae5cb2a61f8c94cf1b86e8258f9c2f2ff6aba5e6136250a422209b6e866881","ca-456fd128f3b3":"f29cbd559410c2578d7f9732ccd86570073355ccdb36af0d1b7dff15908466e7"}});function Nc(e){let t=typeof e.description=="string"?e.description:"",r=typeof e.executorRef=="string"?e.executorRef:"",o=[...t.matchAll(DH)].at(-1)?.[1]?.toLowerCase();if(o)return o==="write"?"write":"read_only";if(/(?:^|:)read[_-]?only(?:$|:)/i.test(r))return"read_only";for(let s of t.matchAll(MH))try{let i=JSON.parse(s[1]);if(i.readOnly===!0||i.executionMode==="read_only")return"read_only"}catch{}return"write"}var DH,MH,fm=p(()=>{"use strict";DH=/\[execution-mode:\s*(write|read[_-]?only)\s*\]/gi,MH=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/gi});import{createPublicKey as LH,verify as BH}from"node:crypto";function mm(e){let t=e.trim();if(!t||t.includes("\0")||/\s/.test(t))return null;let r,n,o=/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.+)$/.exec(t);if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)){let a;try{a=new URL(t)}catch{return null}if(!["https:","http:","ssh:","git:","git+ssh:","ssh+git:"].includes(a.protocol))return null;r=a.port?`${a.hostname}:${a.port}`:a.hostname,n=decodeURIComponent(a.pathname)}else if(o&&!/^[A-Za-z]$/.test(o[1]))r=o[1],n=o[2];else return null;r=r.toLowerCase().replace(/\.$/,"");let s=n.replace(/\/+$/,"").replace(/\.git$/i,"").split("/").filter(Boolean);if(s.length<2||s.some(a=>a==="."||a===".."))return null;let i=`${r}/${s.join("/")}`;return FH.test(i)&&i.length<=512?i:null}function hS(e){let t=e.task??{};return e.landPrDispatch===!0||t.executor==="land_pr"?"land_pr":t.executor==="verify_live"?"verify_live":Nc(t)==="read_only"?"read_only":"write"}function KH(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(Object.keys(t).sort().join(",")!=="payload,publicKeyId,signature"||typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let r=t.payload;if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).sort().join(",")!==[...UH].join(",")||r.v!==1||r.kind!=="dispatch_claim")return!1;for(let n of["tenantId","agentOsId","taskId","leaseOwner","leaseToken","repoIdentity","requestNonce"])if(typeof r[n]!="string"||!r[n])return!1;return!(typeof r.attempt!="number"||!Number.isInteger(r.attempt)||r.attempt<0||typeof r.exp!="number"||!Number.isFinite(r.exp)||!Dc.includes(r.operationClass))}function yS(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!KH(e))return{ok:!1,code:"malformed",reason:"malformed dispatch claim authorization"};let o=e.payload;for(let a of Object.keys(t))if(o[a]!==t[a])return{ok:!1,code:"binding_mismatch",reason:`${a} mismatch`};if(o.exp<=n)return{ok:!1,code:"expired",reason:"authorization expired"};if(o.exp>n+WH+60)return{ok:!1,code:"malformed",reason:"authorization lifetime exceeds the allowed window"};let s=Tn(e.publicKeyId,r);if(!s)return{ok:!1,code:"unknown_key",reason:`no verification key for publicKeyId "${e.publicKeyId}"`};let i=Buffer.from(e.signature,"base64url");if(i.length!==64)return{ok:!1,code:"bad_signature",reason:"not a 64-byte Ed25519 signature"};try{let a=LH({key:Buffer.concat([$H,Buffer.from(s)]),format:"der",type:"spki"});return BH(null,Buffer.from(nt(o),"utf8"),a,i)?{ok:!0,payload:o}:{ok:!1,code:"bad_signature",reason:"Ed25519 signature mismatch"}}catch(a){return{ok:!1,code:"bad_signature",reason:`signature verification failed: ${a.message}`}}}var WH,Dc,UH,FH,$H,kS=p(()=>{"use strict";Li();Hr();fm();WH=120,Dc=["write","read_only","land_pr","verify_live"],UH=["agentOsId","attempt","exp","kind","leaseOwner","leaseToken","operationClass","repoIdentity","requestNonce","taskId","tenantId","v"],FH=/^[a-z0-9.-]+(?::\d+)?(?:\/[A-Za-z0-9._~-]+){2,}$/;$H=Buffer.from("302a300506032b6570032100","hex")});import{spawnSync as HH}from"node:child_process";import{randomBytes as jH}from"node:crypto";function bS(e){if(!e||typeof e!="object"||Array.isArray(e))return"policy must be an object";let t=e;if(Object.keys(t).sort().join(",")!=="accountId,agentOsId,approvedOperationClasses,repoIdentity,revision,v")return"unexpected policy fields";if(t.v!==VH)return"unsupported policy version";if(typeof t.revision!="number"||!Number.isSafeInteger(t.revision)||t.revision<1)return"invalid revision";if(typeof t.accountId!="string"||!t.accountId||t.accountId.length>128)return"invalid accountId";if(typeof t.agentOsId!="string"||!GH.test(t.agentOsId))return"invalid agentOsId";if(typeof t.repoIdentity!="string"||mm(`https://${t.repoIdentity}`)!==t.repoIdentity)return"invalid repoIdentity";let n=t.approvedOperationClasses;if(!Array.isArray(n)||n.length>Dc.length)return"invalid approvedOperationClasses";let o=new Set;for(let s of n){if(typeof s!="string"||!Dc.includes(s)||o.has(s))return"invalid approvedOperationClasses";o.add(s)}return{v:1,revision:t.revision,accountId:t.accountId,agentOsId:t.agentOsId,repoIdentity:t.repoIdentity,approvedOperationClasses:[...n]}}function JH(e){let t=(c,u)=>({allow:!1,code:c,reason:u}),{policy:r,identity:n}=e;if(!n)return t("no_identity","the desktop runtime has not been prepared");if(!r)return t("no_policy","no approved execution policy on this computer");if(r.accountId!==n.accountId||r.agentOsId!==n.agentOsId)return t("policy_mismatch","the approved policy is for another account or workspace");if(!e.repoIdentity)return t("repo_identity_unavailable","the repository has no canonical remote identity");if(r.repoIdentity!==e.repoIdentity)return t("policy_mismatch","the approved policy is for another repository");let o=e.decision.claimAuthorization;if(o==null||!e.requestNonce)return t("missing_authorization","the claim carries no server authorization; the Kynver server must sign Desktop claims (KYNVER_COMMAND_AUTH_KEY, dispatch-claim-authorization diagnostic) and this runtime must be 0.2.87 or newer");let s=e.decision.task??{},i=hS(e.decision),a=yS(o,{tenantId:n.accountId,agentOsId:n.agentOsId,taskId:typeof s.id=="string"?s.id:"",attempt:typeof s.attempt=="number"?s.attempt:-1,leaseOwner:e.leaseOwner,leaseToken:typeof s.leaseToken=="string"?s.leaseToken:"",operationClass:i,repoIdentity:e.repoIdentity,requestNonce:e.requestNonce},e.env??process.env,e.nowSec);if(!a.ok)return t(a.code,a.reason);let l=a.payload;return e.consumed.consume(`${l.taskId}\0${l.leaseToken}\0${l.requestNonce}`)?r.approvedOperationClasses.includes(i)?{allow:!0,operationClass:i}:{allow:!1,code:"operation_not_approved",reason:`${i} work in ${r.repoIdentity} has not been approved on this computer`,consentRequired:{repoIdentity:r.repoIdentity,operationClass:i}}:t("replayed","this claim authorization was already used")}function RS(){return Qe()}function wS(e){return Bi&&e.revision<Bi.revision?!1:(Bi=e,!0)}function ym(){return Bi}function SS(e){vS=e}function _S(e){return hm.add(e),()=>hm.delete(e)}function xS(e){return{v:1,repoIdentity:e,requestNonce:jH(16).toString("base64url")}}function Mc(e){let t=HH("git",["-C",e,"remote","get-url","origin"],z({encoding:"utf8",timeout:1e4}));return t.status!==0||typeof t.stdout!="string"?null:mm(t.stdout.trim())}function CS(e){let t=JH({...e,policy:Bi,identity:vS,consumed:qH});if(!t.allow){let r=e.decision.task??{},n={taskId:typeof r.id=="string"?r.id:"",code:t.code,reason:t.reason,...t.consentRequired?{consentRequired:t.consentRequired}:{}};for(let o of hm)try{o(n)}catch{}}return t}var VH,GH,gm,Bi,vS,qH,hm,Lc=p(()=>{"use strict";St();kS();M();VH=1,GH=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;gm=class{constructor(t=4096){this.capacity=t}capacity;order=[];keys=new Set;consume(t){if(this.keys.has(t))return!1;for(this.keys.add(t),this.order.push(t);this.order.length>this.capacity;)this.keys.delete(this.order.shift());return!0}};Bi=null,vS=null,qH=new gm,hm=new Set});import{createCipheriv as YH,createDecipheriv as zH,randomBytes as bm,scrypt as XH,timingSafeEqual as QH}from"node:crypto";function AS(){return bm(vm)}function PS(e=ZH){return{name:"scrypt",N:e.N,r:e.r,p:e.p,salt:bm(16).toString("base64")}}function wm(e,t,r=ej){if(t.name!=="scrypt"||!Number.isInteger(t.N)||t.N<r||t.r<8||t.p<1)return Promise.reject(new At("the vault file asks for an unsafe key-derivation setting; refusing"));let n=Buffer.from(t.salt,"base64");return n.length<16?Promise.reject(new At("the vault file's salt is invalid")):new Promise((o,s)=>{XH(e.normalize("NFKC"),n,vm,{N:t.N,r:t.r,p:t.p,maxmem:128*t.N*t.r*2},(i,a)=>i?s(i):o(a))})}function Wi(e,t,r){if(e.length!==vm)throw new At("bad key length");let n=bm(ES),o=YH("aes-256-gcm",e,n);o.setAAD(Buffer.from(r,"utf8"));let s=Buffer.concat([o.update(t),o.final(),o.getAuthTag()]);return{n:n.toString("base64"),c:s.toString("base64")}}function Bc(e,t,r){try{let n=Buffer.from(t.n,"base64"),o=Buffer.from(t.c,"base64");if(n.length!==ES||o.length<km)throw new At;let s=zH("aes-256-gcm",e,n);return s.setAAD(Buffer.from(r,"utf8")),s.setAuthTag(o.subarray(o.length-km)),Buffer.concat([s.update(o.subarray(0,o.length-km)),s.final()])}catch(n){throw n instanceof At?n:new At}}function Sm(e){for(let t of e)if(t.includes(`
|
|
78
|
+
`))throw new At("invalid vault field");return e.join(`
|
|
79
|
+
`)}function xm(e){return Sm(["kynver-site-login/v1/record",e.agentOsId,e.handle,e.origin,e.label,e.username,e.hasTotp?"totp":"no-totp"])}function IS(e,t){return e.length===t.length&&QH(e,t)}var vm,ES,km,ZH,ej,Rm,At,_m,Wc,Uc,OS=p(()=>{"use strict";vm=32,ES=12,km=16,ZH={N:2**17,r:8,p:1},ej=2**14,Rm=10,At=class extends Error{constructor(t="the saved-login vault could not be decrypted"){super(t),this.name="VaultCryptoError"}};_m=e=>Sm(["kynver-site-login/v1/vault-key",e]),Wc=e=>Sm(["kynver-site-login/v1/key-check",e]),Uc=Buffer.from("kynver-site-login-key-check-v1","utf8")});function TS(e){if(typeof e!="string"||!e.trim())return{ok:!1,reason:"a site address is required"};let t=e.trim();/^[a-z][a-z0-9+.-]*:/i.test(t)||(t=`https://${t}`);let r;try{r=new URL(t)}catch{return{ok:!1,reason:"not a valid web address"}}return r.protocol!=="https:"?{ok:!1,reason:"saved logins are only used on https:// sites"}:r.username||r.password?{ok:!1,reason:"the address must not contain a username or password"}:!r.hostname.includes(".")||tj.test(r.hostname)?{ok:!1,reason:"use the site's public address (e.g. https://www.instagram.com)"}:{ok:!0,origin:r.origin,unicodeHost:r.hostname.split(".").some(n=>n.startsWith("xn--"))}}function Ui(e){if(typeof e!="string"||!e)return null;try{let t=new URL(e).origin;return t&&t!=="null"?t:null}catch{return null}}function Cm(e,t){let r=Ui(t);return r!==null&&r===e}var tj,Em=p(()=>{"use strict";tj=/^(localhost|.*\.localhost|.*\.local|.*\.internal|0\.0\.0\.0|\[.*\]|\d{1,3}(\.\d{1,3}){3})$/i});import{createHmac as rj}from"node:crypto";function NS(e){let t=e.replace(/[\s-]/g,"").replace(/=+$/,"").toUpperCase();if(!t||!/^[A-Z2-7]+$/.test(t))return null;let r=0,n=0,o=[];for(let s of t)n=n<<5|nj.indexOf(s),r+=5,r>=8&&(o.push(n>>>r-8&255),r-=8);return o.length?Buffer.from(o):null}function Fc(e){let t=e.trim();if(!t)return null;if(/^otpauth:\/\//i.test(t)){let n;try{n=new URL(t)}catch{return null}if(n.host.toLowerCase()!=="totp")return null;let o=NS(n.searchParams.get("secret")??"");if(!o)return null;let s=(n.searchParams.get("algorithm")??"SHA1").toUpperCase(),i=Number(n.searchParams.get("digits")??"6"),a=Number(n.searchParams.get("period")??"30");return s!=="SHA1"&&s!=="SHA256"&&s!=="SHA512"||i!==6&&i!==7&&i!==8||!Number.isInteger(a)||a<10||a>300?null:{key:o,algorithm:s,digits:i,period:a}}let r=NS(t);return r?{key:r,algorithm:"SHA1",digits:6,period:30}:null}function oj(e,t,r,n){let o=Buffer.alloc(8);o.writeBigUInt64BE(t);let s=rj(n.toLowerCase(),e).update(o).digest(),i=s[s.length-1]&15,a=(s[i]&127)<<24|s[i+1]<<16|s[i+2]<<8|s[i+3];return String(a%10**r).padStart(r,"0")}function DS(e,t=Date.now()){let r=BigInt(Math.floor(t/1e3/e.period));return oj(e.key,r,e.digits,e.algorithm)}function MS(e,t=Date.now()){let r=Math.floor(t/1e3)%e.period;return e.period-r}var nj,Am=p(()=>{"use strict";nj="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"});var pt,Pm=p(()=>{"use strict";pt={maxRecords:200,maxLabel:80,maxUsername:254,maxPassword:1024,maxTotp:512}});import{createHash as sj,randomBytes as WS}from"node:crypto";import{chmodSync as LS,existsSync as ij,mkdirSync as aj,readFileSync as lj,renameSync as cj,rmSync as uj,writeFileSync as dj}from"node:fs";import{homedir as pj}from"node:os";import US from"node:path";function Fi(){return US.join(pj(),".kynver","site-logins")}function Im(e){return`${sj("sha256").update(`kynver-site-login:${e}`).digest("hex").slice(0,32)}.vault.json`}function BS(e,t,r,n=!0){let o=typeof e=="string"?e.trim():"";if(!o&&n)throw new J(`${t} is required`,"invalid");if(o.length>r)throw new J(`${t} is too long (max ${r})`,"invalid");if(FS.test(o))throw new J(`${t} contains control characters`,"invalid");return o}function fj(){let e="abcdefghijkmnpqrstuvwxyz23456789",t=WS(10);return`lg_${Array.from(t,r=>e[r%e.length]).join("")}`}var J,FS,Kc,Nn=p(()=>{"use strict";OS();Em();Am();Pm();J=class extends Error{constructor(r,n){super(r);this.code=n;this.name="SiteLoginError"}code},FS=/[\u0000-\u001f\u007f]/;Kc=class{constructor(t){this.opts=t;let r=t.agentOsId.trim();if(!r||FS.test(r)||r.length>200)throw new J("invalid workspace id","invalid");this.agentOsId=r,this.rootDir=t.rootDir??Fi(),this.filePath=US.join(this.rootDir,Im(r)),this.now=t.now??Date.now}opts;agentOsId;filePath;rootDir;now;exists(){return ij(this.filePath)}keyMode(){return this.exists()?this.read().keyMode:null}async createWithPassphrase(t){if(this.exists())throw new J("a saved-login vault already exists on this computer","exists");if(t.length<Rm)throw new J(`the vault passphrase must be at least ${Rm} characters`,"invalid");let r=AS(),n=PS(this.opts.scryptCost),o=await wm(t,n,this.opts.minScryptN);return this.write({v:1,agentOsId:this.agentOsId,keyMode:"passphrase",kdf:n,wrappedKey:Wi(o,r,_m(this.agentOsId)),keyCheck:Wi(r,Uc,Wc(this.agentOsId)),records:[]}),o.fill(0),r}createWithKeychainKey(t){if(this.exists())throw new J("a saved-login vault already exists on this computer","exists");this.write({v:1,agentOsId:this.agentOsId,keyMode:"keychain",keyCheck:Wi(t,Uc,Wc(this.agentOsId)),records:[]})}async unlockWithPassphrase(t){let r=this.read();if(r.keyMode!=="passphrase"||!r.kdf||!r.wrappedKey)throw new J("this vault is unlocked by the Kynver desktop app, not a passphrase","invalid");let n=null;try{n=await wm(t,r.kdf,this.opts.minScryptN);let o=Bc(n,r.wrappedKey,_m(this.agentOsId));return this.verifyKey(r,o),o}catch(o){throw o instanceof J?o:o instanceof At&&/unsafe|salt/.test(o.message)?new J(o.message,"corrupt"):new J("wrong vault passphrase","bad_key")}finally{n?.fill(0)}}unlockWithKey(t){return this.verifyKey(this.read(),t),t}wipe(){return this.exists()?(uj(this.filePath,{force:!0}),!0):!1}list(){return this.exists()?this.read().records.map(({secret:t,...r})=>r):[]}get(t){return this.list().find(r=>r.handle===t)??null}add(t,r){let n=this.read();if(this.verifyKey(n,t),n.records.length>=pt.maxRecords)throw new J(`at most ${pt.maxRecords} saved logins per workspace`,"full");let o=this.buildRecord(t,r,fj(),new Date(this.now()).toISOString());n.records.push(o),this.write(n);let{secret:s,...i}=o;return i}replace(t,r,n){let o=this.read();this.verifyKey(o,t);let s=o.records.findIndex(c=>c.handle===r);if(s<0)throw new J("no saved login with that id","not_found");let i=this.buildRecord(t,n,r,o.records[s].createdAt);o.records[s]=i,this.write(o);let{secret:a,...l}=i;return l}remove(t){if(!this.exists())return!1;let r=this.read(),n=r.records.filter(o=>o.handle!==t);return n.length===r.records.length?!1:(r.records=n,this.write(r),!0)}readSecret(t,r){let n=this.read();this.verifyKey(n,t);let o=n.records.find(i=>i.handle===r);if(!o)throw new J("no saved login with that id","not_found");let s;try{s=Bc(t,o.secret,xm({agentOsId:this.agentOsId,...o}))}catch{throw new J("this saved login failed its integrity check and was not used","corrupt")}try{let i=JSON.parse(s.toString("utf8"));if(typeof i.p!="string")throw new Error("shape");let{secret:a,...l}=o;return{summary:l,secret:{password:i.p,...typeof i.t=="string"?{totp:i.t}:{}}}}catch{throw new J("this saved login failed its integrity check and was not used","corrupt")}finally{s.fill(0)}}touch(t){let r=this.read(),n=r.records.find(o=>o.handle===t);n&&(n.lastUsedAt=new Date(this.now()).toISOString(),this.write(r))}buildRecord(t,r,n,o){let s=TS(r.origin);if(!s.ok)throw new J(s.reason,"invalid");let i=BS(r.label,"label",pt.maxLabel),a=BS(r.username,"username",pt.maxUsername),l=typeof r.password=="string"?r.password:"";if(!l)throw new J("password is required","invalid");if(l.length>pt.maxPassword)throw new J("password is too long","invalid");let c=typeof r.totp=="string"&&r.totp.trim()?r.totp.trim():void 0;if(c&&(c.length>pt.maxTotp||!Fc(c)))throw new J("the authenticator key is not a valid base32 secret or otpauth://totp link","invalid");let u={handle:n,origin:s.origin,label:i,username:a,hasTotp:!!c,createdAt:o,lastUsedAt:null},d=Buffer.from(JSON.stringify(c?{p:l,t:c}:{p:l}),"utf8");try{return{...u,secret:Wi(t,d,xm({agentOsId:this.agentOsId,...u}))}}finally{d.fill(0)}}verifyKey(t,r){try{let n=Bc(r,t.keyCheck,Wc(this.agentOsId));if(!IS(n,Uc))throw new Error("mismatch")}catch{throw new J("the vault key does not open this vault","bad_key")}}read(){if(!this.exists())throw new J("no saved-login vault on this computer yet","missing");let t;try{t=JSON.parse(lj(this.filePath,"utf8"))}catch{throw new J("the saved-login vault file is unreadable","corrupt")}if(!t||t.v!==1||t.keyMode!=="passphrase"&&t.keyMode!=="keychain"||!t.keyCheck||!Array.isArray(t.records))throw new J("the saved-login vault file is not a vault Kynver understands","corrupt");if(t.agentOsId!==this.agentOsId)throw new J("this saved-login vault belongs to a different workspace","corrupt");return t.records=t.records.filter(r=>r&&typeof r.handle=="string"&&typeof r.origin=="string"&&typeof r.label=="string"&&typeof r.username=="string"&&r.secret&&typeof r.secret.n=="string"&&typeof r.secret.c=="string"),t}write(t){aj(this.rootDir,{recursive:!0,mode:448});try{LS(this.rootDir,448)}catch{}let r=`${this.filePath}.${WS(4).toString("hex")}.tmp`;dj(r,`${JSON.stringify(t)}
|
|
80
|
+
`,{mode:384}),cj(r,this.filePath);try{LS(this.filePath,384)}catch{}}}});import{appendFileSync as hj,chmodSync as yj,existsSync as jS,mkdirSync as kj,readFileSync as VS,renameSync as bj,statSync as vj,writeFileSync as Rj}from"node:fs";import wj from"node:path";var Sj,GS,_j,$c,JS=p(()=>{"use strict";Nn();Sj=512*1024,GS=1e3,_j=10080*60*1e3,$c=class{constructor(t,r=Fi(),n=Date.now){this.rootDir=r;this.now=n;this.filePath=wj.join(r,Im(t).replace(/\.vault\.json$/,".audit.jsonl"))}rootDir;now;filePath;record(t){let r={at:new Date(this.now()).toISOString(),...t};try{kj(this.rootDir,{recursive:!0,mode:448}),this.rotateIfLarge(),hj(this.filePath,`${JSON.stringify(r)}
|
|
81
|
+
`,{mode:384}),yj(this.filePath,384)}catch{}return r}entries(t=GS){if(!jS(this.filePath))return[];try{return VS(this.filePath,"utf8").split(`
|
|
82
|
+
`).filter(Boolean).slice(-t).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}lastFill(){let t=this.entries().filter(r=>r.event==="fill");return t[t.length-1]??null}originRefusalsSince(t=_j){let r=this.now()-t;return this.entries().filter(n=>n.event==="fill"&&n.code==="origin_mismatch"&&Date.parse(n.at)>=r).length}rotateIfLarge(){if(!jS(this.filePath)||vj(this.filePath).size<Sj)return;let t=VS(this.filePath,"utf8").split(`
|
|
83
|
+
`).filter(Boolean).slice(-GS/2),r=`${this.filePath}.tmp`;Rj(r,`${t.join(`
|
|
20
84
|
`)}
|
|
21
|
-
`,{mode:384}),FK(r,this.filePath)}}});import{randomBytes as GK}from"node:crypto";import{existsSync as JK,rmSync as qK}from"node:fs";function rS(e,t){return{id:e.id,origin:e.origin,prompt:e.prompt,conversationId:e.conversationId,expiresInSec:Math.max(0,Math.round((e.expiresAt-t)/1e3))}}function xt(){return nS??=new im,nS}var YK,zK,im,nS,Ti=p(()=>{"use strict";tS();Cn();YK=720*60*1e3,zK=300*1e3,im=class{rootDir;now;idleMs;keys=new Map;codes=new Map;codeListeners=new Set;constructor(t={}){this.rootDir=t.rootDir??Oi(),this.now=t.now??Date.now,this.idleMs=t.idleMs??YK}store(t){return new Ec({agentOsId:t,rootDir:this.rootDir,now:this.now})}audit(t){return new Ac(t,this.rootDir,this.now)}unlock(t,r,n={}){this.lock(t),this.keys.set(t,{key:Buffer.from(r),lastUsedAt:this.now(),keychain:n.keychain===!0})}lock(t){for(let[r,n]of this.keys)t&&r!==t||(n.key.fill(0),this.keys.delete(r))}key(t){let r=this.keys.get(t);return r?!r.keychain&&this.now()-r.lastUsedAt>this.idleMs?(this.lock(t),null):(r.lastUsedAt=this.now(),r.key):null}isUnlocked(t){return this.key(t)!==null}wipe(t){this.lock(t);for(let[s,i]of this.codes)i.agentOsId===t&&this.codes.delete(s);let n=this.store(t).wipe(),o=this.audit(t).filePath;return JK(o)&&qK(o,{force:!0}),n}addCodeRequest(t){this.pruneCodes();for(let[s,i]of this.codes)i.agentOsId===t.agentOsId&&i.conversationId===t.conversationId&&this.codes.delete(s);let r=this.now(),n={...t,id:`cr_${GK(6).toString("hex")}`,createdAt:r,expiresAt:r+zK};this.codes.set(n.id,n);let o=rS(n,r);for(let s of this.codeListeners)try{s({...o,agentOsId:n.agentOsId})}catch{}return o}onCodeRequest(t){return this.codeListeners.add(t),()=>this.codeListeners.delete(t)}listCodeRequests(t){this.pruneCodes();let r=this.now();return[...this.codes.values()].filter(n=>!t||n.agentOsId===t).sort((n,o)=>o.createdAt-n.createdAt).map(n=>rS(n,r))}async submitCode(t,r,n){this.pruneCodes();let o=t?this.codes.get(t):[...this.codes.values()].filter(a=>!n||a.agentOsId===n).sort((a,l)=>l.createdAt-a.createdAt)[0];if(!o||n&&o.agentOsId!==n)return{ok:!1,text:"No page is waiting for a code right now (requests expire after 5 minutes)."};let s=r.replace(/\s+/g,"");if(!/^[A-Za-z0-9-]{3,12}$/.test(s))return{ok:!1,text:"That doesn't look like a verification code."};this.codes.delete(o.id);let i=await o.fill(s);return this.audit(o.agentOsId).record({event:"code",ok:i.ok,code:i.ok?null:"fill_failed",origin:o.origin,conversationId:o.conversationId}),i}report(t){let r=this.store(t),n=0,o=null,s=!1;try{s=r.exists(),s&&(o=r.keyMode(),n=r.list().length)}catch{}let i=this.audit(t),a=i.lastFill();return{state:s?this.isUnlocked(t)?"unlocked":"locked":"none",keyMode:o,count:n,lastFill:a?{ok:a.ok,code:a.code??null,at:a.at}:null,originRefusals7d:i.originRefusalsSince()}}pruneCodes(){let t=this.now();for(let[r,n]of this.codes)n.expiresAt<=t&&this.codes.delete(r)}};nS=null});var oS=p(()=>{"use strict";D()});var sS=p(()=>{"use strict";H();oS();nr()});function QK(e){return(e.accessibleItems??[]).filter(t=>t.access?.isOwner).map(t=>({id:typeof t.agentOs?.id=="string"?t.agentOs.id:"",slug:typeof t.agentOs?.slug=="string"?t.agentOs.slug.trim():""})).filter(t=>t.slug)}function am(e){if(!e)return null;let t=QK(e),r=typeof e.primarySlug=="string"?e.primarySlug.trim():"",n=typeof e.primaryAgentOsId=="string"?e.primaryAgentOsId.trim():"";if(t.length>0){if(n){let s=t.find(i=>i.id===n);if(s)return s}if(r){let s=t.find(i=>i.slug===r);if(s)return s}return t[0]??null}if(Array.isArray(e.accessibleItems)&&e.accessibleItems.length>0)return null;if(n&&r)return{id:n,slug:r};if(!r)return null;let o=e.items?.find(s=>s.slug===r);return o?.id&&o.slug?{id:o.id,slug:o.slug}:{id:"",slug:r}}var lm=p(()=>{"use strict"});function iS(e){return/\((?:401|403)\)/.test(e)?"access_denied":"transient"}var cm=p(()=>{"use strict";H();nr();D();sS();lm()});import{existsSync as ZK}from"node:fs";import{homedir as eH}from"node:os";import tH from"node:path";function aS(e,t){let r=process.env[e]?.trim().toLowerCase();return r?r==="0"||r==="false"||r==="no"||r==="off"?!1:r==="1"||r==="true"||r==="yes"||r==="on"?!0:t:t}function Ni(e,t,r=1){let n=Number(process.env[e]);return!Number.isFinite(n)||n<r?t:Math.floor(n)}function $r(){let e=process.env.KYNVER_CRON_STORE_PATH?.trim()||process.env.OPENCLAW_CRON_STORE_PATH?.trim();return e||tH.join(eH(),".kynver","agent-os-cron.json")}function rH(e=$r()){let t=process.env.KYNVER_CRON_TICK_STATE_PATH?.trim();return t||`${e.replace(/\.json$/i,"")}.tick-state.json`}function nH(){let e=E();return process.env.KYNVER_API_URL?.trim()||e.apiBaseUrl?.trim()||process.env.KYNVER_CRON_FIRE_BASE_URL?.trim()||process.env.OPENCLAW_CRON_FIRE_BASE_URL?.trim()||null}function lS(){let e=E();return Ce("KYNVER_CRON_SECRET")||Ce("OPENCLAW_CRON_SECRET")||Ce("KYNVER_RUNTIME_SECRET")||He(e.agentOsId)?.trim()||He()?.trim()||null}function qo(){let e=$r(),t=rH(e),r=nH(),n=lS(),o=!!(r&&n),s=ZK(e),i=o&&(s||aS("KYNVER_CRON_TICK_FORCE",!1));return{storePath:e,statePath:t,lockPath:`${t}.lock`,fireBaseUrl:r,secret:n,tickEnabled:aS("KYNVER_CRON_TICK_ENABLED",i),tickIntervalMs:Ni("KYNVER_CRON_TICK_INTERVAL_MS",6e4,5e3),missedRunPolicy:process.env.KYNVER_CRON_MISSED_RUN_POLICY?.trim().toLowerCase()==="skip"?"skip":"catch_up",maxCatchUpPerTick:Ni("KYNVER_CRON_MAX_CATCH_UP_PER_TICK",3,0),maxRetries:Ni("KYNVER_CRON_MAX_RETRIES",3,0),retryBackoffMs:Ni("KYNVER_CRON_RETRY_BACKOFF_MS",6e4,1e3),inflightLeaseMs:Ni("KYNVER_CRON_INFLIGHT_LEASE_MS",12e4,5e3)}}var pr=p(()=>{"use strict";H();bt()});import{promises as oH}from"node:fs";async function cS(e){try{return await oH.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function sH(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t.entries)?t.entries:[]}catch{return[]}}async function Pc(e=$r()){let t=await cS(e);return sH(t)}async function iH(e,t){let{mkdir:r,writeFile:n,rename:o}=await import("node:fs/promises"),{randomBytes:s}=await import("node:crypto"),{dirname:i}=await import("node:path");await r(i(e),{recursive:!0});let a=`${e}.${s(4).toString("hex")}.tmp`,l=JSON.stringify({entries:t},null,2);await n(a,l,"utf8"),await o(a,e)}async function um(e=$r()){return await cS(e)!==null?{created:!1}:(await iH(e,[]),{created:!0})}var Yo=p(()=>{"use strict";pr()});import{existsSync as aH,readFileSync as lH}from"node:fs";import{dirname as dm,join as dS}from"node:path";import{fileURLToPath as uS}from"node:url";function cH(e){let t=dm(uS(e));for(let r=0;r<6;r+=1){if(aH(dS(t,"package.json")))return t;let n=dm(t);if(n===t)break;t=n}throw new Error(`package.json not found above ${dm(uS(e))}`)}function uH(e=import.meta.url){let t=dS(cH(e),"package.json"),r=JSON.parse(lH(t,"utf8"));if(typeof r.version!="string"||!r.version.trim())throw new Error(`Missing package.json version at ${t}`);return r.version}var Dt,zo=p(()=>{"use strict";Dt=uH()});import{spawnSync as dH}from"node:child_process";import{readFileSync as pH}from"node:fs";function fH(e,t){let r=dH(e,t,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:15e3});return{status:r.status,stdout:r.stdout??""}}function mH(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=e.slice(t+1).trim().split(/\s+/)[19];return n&&/^\d+$/.test(n)?n:null}function gH(e){return Number.isInteger(e)&&e>0}function pS(e,t={}){if(!gH(e))return null;let r=t.platform??process.platform,n=t.readText??(s=>pH(s,"utf8")),o=t.run??fH;try{if(r==="linux"){let s=mH(n(`/proc/${e}/stat`));if(!s)return null;let i="";try{i=n("/proc/sys/kernel/random/boot_id").trim()}catch{}return`linux:${i}:${s}`}if(r==="darwin"){let s=o("ps",["-o","lstart=","-p",String(e)]),i=s.stdout.trim();return s.status===0&&i?`darwin:${i}`:null}if(r==="win32"){let s=`$p = Get-CimInstance Win32_Process -Filter "ProcessId=${e}"; if ($p) { $p.CreationDate.ToUniversalTime().ToString('o') }`,i=o("powershell.exe",["-NoProfile","-NonInteractive","-Command",s]),a=i.stdout.trim();return i.status===0&&a?`win32:${a}`:null}}catch{return null}return null}var pm=p(()=>{"use strict"});import{createHash as yH,randomUUID as kS}from"node:crypto";import{closeSync as kH,constants as fm,existsSync as bH,mkdirSync as mm,openSync as vH,readFileSync as RH,renameSync as gm,rmSync as Ic,writeFileSync as wH}from"node:fs";import{createConnection as SH,createServer as fS}from"node:net";import{homedir as _H,tmpdir as xH}from"node:os";import Mt from"node:path";function CH(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function bS(e){let t=e.stateRoot??Mt.join(_H(),".kynver"),r=e.platform??process.platform,n=yH("sha256").update(`${Mt.resolve(t)}\0${e.agentOsId}`).digest("hex").slice(0,24),o=Mt.join(t,"locks"),s=Mt.join(o,`${n.slice(0,16)}.sock`);r==="linux"?s=`\0kynver-daemon-owner-${n}`:Buffer.byteLength(s)>100&&(s=Mt.join(xH(),`kynver-owner-${n.slice(0,16)}.sock`));let i=Mt.join(t,`daemon-owner-${CH(e.agentOsId)}.json`);return{lockKey:n,lockFile:Mt.join(o,`daemon-owner-${n}.lock`),metadataFile:i,quarantineFile:i.replace(/\.json$/,".stale.json"),socketAddress:s}}function AH(e){mm(Mt.dirname(e),{recursive:!0});let t;try{t=vH(e,fm.O_RDWR|fm.O_CREAT|EH)}catch(n){let o=n.code;if(o==="EBUSY"||o==="EACCES"||o==="EPERM")return{busy:!0};throw n}let r=!0;return{held:{isHeld:()=>r,release:()=>{if(r){r=!1;try{kH(t)}catch{}}}}}}function mS(e,t){return new Promise((r,n)=>{let o=i=>{e.off("listening",s),i.code==="EADDRINUSE"?r("in_use"):n(i)},s=()=>{e.off("error",o),r("listening")};e.once("error",o),e.once("listening",s),e.listen({path:t,exclusive:!0})})}function PH(e,t=2e3){return new Promise(r=>{let n=SH({path:e}),o=i=>{clearTimeout(s),n.removeAllListeners(),n.destroy(),r(i)},s=setTimeout(()=>o(!0),t);n.once("connect",()=>o(!0)),n.once("error",()=>o(!1))})}async function IH(e,t){e.startsWith("\0")||mm(Mt.dirname(e),{recursive:!0,mode:448});let r=fS(a=>a.destroy());if(await mS(r,e)==="listening")return{held:gS(r,e)};if(!t||e.startsWith("\0"))return{busy:!0};if(await PH(e))return{busy:!0};let o=`${e}.stale-${process.pid}-${kS().slice(0,8)}`;try{gm(e,o),Ic(o,{force:!0})}catch{}let s=fS(a=>a.destroy());return await mS(s,e).catch(()=>"in_use")==="listening"?{held:gS(s,e)}:{busy:!0}}function gS(e,t){e.unref();let r=!0;return{isHeld:()=>r&&e.listening,release:()=>{r&&(r=!1,e.close(),t.startsWith("\0")||Ic(t,{force:!0}))}}}async function OH(e,t){return t==="win32"?AH(e.lockFile):IH(e.socketAddress,t!=="linux")}function TH(e){let t=e;return!!t&&t.version===1&&typeof t.agentOsId=="string"&&typeof t.instanceId=="string"&&typeof t.pid=="number"&&typeof t.ownerKind=="string"}function hS(e){try{let t=JSON.parse(RH(bS(e).metadataFile,"utf8"));return TH(t)?t:null}catch{return null}}function yS(e,t){mm(Mt.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;wH(r,`${JSON.stringify(t,null,2)}
|
|
22
|
-
`,{mode:384}),
|
|
85
|
+
`,{mode:384}),bj(r,this.filePath)}}});import{randomBytes as xj}from"node:crypto";import{existsSync as Cj,rmSync as Ej}from"node:fs";function qS(e,t){return{id:e.id,origin:e.origin,prompt:e.prompt,conversationId:e.conversationId,expiresInSec:Math.max(0,Math.round((e.expiresAt-t)/1e3))}}function Pt(){return YS??=new Om,YS}var Aj,Pj,Om,YS,Ki=p(()=>{"use strict";JS();Nn();Aj=720*60*1e3,Pj=300*1e3,Om=class{rootDir;now;idleMs;keys=new Map;codes=new Map;codeListeners=new Set;constructor(t={}){this.rootDir=t.rootDir??Fi(),this.now=t.now??Date.now,this.idleMs=t.idleMs??Aj}store(t){return new Kc({agentOsId:t,rootDir:this.rootDir,now:this.now})}audit(t){return new $c(t,this.rootDir,this.now)}unlock(t,r,n={}){this.lock(t),this.keys.set(t,{key:Buffer.from(r),lastUsedAt:this.now(),keychain:n.keychain===!0})}lock(t){for(let[r,n]of this.keys)t&&r!==t||(n.key.fill(0),this.keys.delete(r))}key(t){let r=this.keys.get(t);return r?!r.keychain&&this.now()-r.lastUsedAt>this.idleMs?(this.lock(t),null):(r.lastUsedAt=this.now(),r.key):null}isUnlocked(t){return this.key(t)!==null}wipe(t){this.lock(t);for(let[s,i]of this.codes)i.agentOsId===t&&this.codes.delete(s);let n=this.store(t).wipe(),o=this.audit(t).filePath;return Cj(o)&&Ej(o,{force:!0}),n}addCodeRequest(t){this.pruneCodes();for(let[s,i]of this.codes)i.agentOsId===t.agentOsId&&i.conversationId===t.conversationId&&this.codes.delete(s);let r=this.now(),n={...t,id:`cr_${xj(6).toString("hex")}`,createdAt:r,expiresAt:r+Pj};this.codes.set(n.id,n);let o=qS(n,r);for(let s of this.codeListeners)try{s({...o,agentOsId:n.agentOsId})}catch{}return o}onCodeRequest(t){return this.codeListeners.add(t),()=>this.codeListeners.delete(t)}listCodeRequests(t){this.pruneCodes();let r=this.now();return[...this.codes.values()].filter(n=>!t||n.agentOsId===t).sort((n,o)=>o.createdAt-n.createdAt).map(n=>qS(n,r))}async submitCode(t,r,n){this.pruneCodes();let o=t?this.codes.get(t):[...this.codes.values()].filter(a=>!n||a.agentOsId===n).sort((a,l)=>l.createdAt-a.createdAt)[0];if(!o||n&&o.agentOsId!==n)return{ok:!1,text:"No page is waiting for a code right now (requests expire after 5 minutes)."};let s=r.replace(/\s+/g,"");if(!/^[A-Za-z0-9-]{3,12}$/.test(s))return{ok:!1,text:"That doesn't look like a verification code."};this.codes.delete(o.id);let i=await o.fill(s);return this.audit(o.agentOsId).record({event:"code",ok:i.ok,code:i.ok?null:"fill_failed",origin:o.origin,conversationId:o.conversationId}),i}report(t){let r=this.store(t),n=0,o=null,s=!1;try{s=r.exists(),s&&(o=r.keyMode(),n=r.list().length)}catch{}let i=this.audit(t),a=i.lastFill();return{state:s?this.isUnlocked(t)?"unlocked":"locked":"none",keyMode:o,count:n,lastFill:a?{ok:a.ok,code:a.code??null,at:a.at}:null,originRefusals7d:i.originRefusalsSince()}}pruneCodes(){let t=this.now();for(let[r,n]of this.codes)n.expiresAt<=t&&this.codes.delete(r)}};YS=null});var zS=p(()=>{"use strict";M()});var XS=p(()=>{"use strict";$();zS();sr()});function Oj(e){return(e.accessibleItems??[]).filter(t=>t.access?.isOwner).map(t=>({id:typeof t.agentOs?.id=="string"?t.agentOs.id:"",slug:typeof t.agentOs?.slug=="string"?t.agentOs.slug.trim():""})).filter(t=>t.slug)}function Tm(e){if(!e)return null;let t=Oj(e),r=typeof e.primarySlug=="string"?e.primarySlug.trim():"",n=typeof e.primaryAgentOsId=="string"?e.primaryAgentOsId.trim():"";if(t.length>0){if(n){let s=t.find(i=>i.id===n);if(s)return s}if(r){let s=t.find(i=>i.slug===r);if(s)return s}return t[0]??null}if(Array.isArray(e.accessibleItems)&&e.accessibleItems.length>0)return null;if(n&&r)return{id:n,slug:r};if(!r)return null;let o=e.items?.find(s=>s.slug===r);return o?.id&&o.slug?{id:o.id,slug:o.slug}:{id:"",slug:r}}var Nm=p(()=>{"use strict"});function QS(e){return/\((?:401|403)\)/.test(e)?"access_denied":"transient"}var Dm=p(()=>{"use strict";$();sr();M();XS();Nm()});import{existsSync as Tj}from"node:fs";import{homedir as Nj}from"node:os";import Dj from"node:path";function ZS(e,t){let r=process.env[e]?.trim().toLowerCase();return r?r==="0"||r==="false"||r==="no"||r==="off"?!1:r==="1"||r==="true"||r==="yes"||r==="on"?!0:t:t}function $i(e,t,r=1){let n=Number(process.env[e]);return!Number.isFinite(n)||n<r?t:Math.floor(n)}function jr(){let e=process.env.KYNVER_CRON_STORE_PATH?.trim()||process.env.OPENCLAW_CRON_STORE_PATH?.trim();return e||Dj.join(Nj(),".kynver","agent-os-cron.json")}function Mj(e=jr()){let t=process.env.KYNVER_CRON_TICK_STATE_PATH?.trim();return t||`${e.replace(/\.json$/i,"")}.tick-state.json`}function Lj(){let e=P();return process.env.KYNVER_API_URL?.trim()||e.apiBaseUrl?.trim()||process.env.KYNVER_CRON_FIRE_BASE_URL?.trim()||process.env.OPENCLAW_CRON_FIRE_BASE_URL?.trim()||null}function e_(){let e=P();return Pe("KYNVER_CRON_SECRET")||Pe("OPENCLAW_CRON_SECRET")||Pe("KYNVER_RUNTIME_SECRET")||Te(e.agentOsId)?.trim()||Te()?.trim()||null}function rs(){let e=jr(),t=Mj(e),r=Lj(),n=e_(),o=!!(r&&n),s=Tj(e),i=o&&(s||ZS("KYNVER_CRON_TICK_FORCE",!1));return{storePath:e,statePath:t,lockPath:`${t}.lock`,fireBaseUrl:r,secret:n,tickEnabled:ZS("KYNVER_CRON_TICK_ENABLED",i),tickIntervalMs:$i("KYNVER_CRON_TICK_INTERVAL_MS",6e4,5e3),missedRunPolicy:process.env.KYNVER_CRON_MISSED_RUN_POLICY?.trim().toLowerCase()==="skip"?"skip":"catch_up",maxCatchUpPerTick:$i("KYNVER_CRON_MAX_CATCH_UP_PER_TICK",3,0),maxRetries:$i("KYNVER_CRON_MAX_RETRIES",3,0),retryBackoffMs:$i("KYNVER_CRON_RETRY_BACKOFF_MS",6e4,1e3),inflightLeaseMs:$i("KYNVER_CRON_INFLIGHT_LEASE_MS",12e4,5e3)}}var gr=p(()=>{"use strict";$();St()});import{promises as Bj}from"node:fs";async function t_(e){try{return await Bj.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function Wj(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t.entries)?t.entries:[]}catch{return[]}}async function Hc(e=jr()){let t=await t_(e);return Wj(t)}async function Uj(e,t){let{mkdir:r,writeFile:n,rename:o}=await import("node:fs/promises"),{randomBytes:s}=await import("node:crypto"),{dirname:i}=await import("node:path");await r(i(e),{recursive:!0});let a=`${e}.${s(4).toString("hex")}.tmp`,l=JSON.stringify({entries:t},null,2);await n(a,l,"utf8"),await o(a,e)}async function Mm(e=jr()){return await t_(e)!==null?{created:!1}:(await Uj(e,[]),{created:!0})}var ns=p(()=>{"use strict";gr()});import{existsSync as Fj,readFileSync as Kj}from"node:fs";import{dirname as Lm,join as n_}from"node:path";import{fileURLToPath as r_}from"node:url";function $j(e){let t=Lm(r_(e));for(let r=0;r<6;r+=1){if(Fj(n_(t,"package.json")))return t;let n=Lm(t);if(n===t)break;t=n}throw new Error(`package.json not found above ${Lm(r_(e))}`)}function Hj(e=import.meta.url){let t=n_($j(e),"package.json"),r=JSON.parse(Kj(t,"utf8"));if(typeof r.version!="string"||!r.version.trim())throw new Error(`Missing package.json version at ${t}`);return r.version}var Ge,Vr=p(()=>{"use strict";Ge=Hj()});import{spawnSync as jj}from"node:child_process";import{readFileSync as Vj}from"node:fs";function Gj(e,t){let r=jj(e,t,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:15e3});return{status:r.status,stdout:r.stdout??""}}function Jj(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=e.slice(t+1).trim().split(/\s+/)[19];return n&&/^\d+$/.test(n)?n:null}function qj(e){return Number.isInteger(e)&&e>0}function o_(e,t={}){if(!qj(e))return null;let r=t.platform??process.platform,n=t.readText??(s=>Vj(s,"utf8")),o=t.run??Gj;try{if(r==="linux"){let s=Jj(n(`/proc/${e}/stat`));if(!s)return null;let i="";try{i=n("/proc/sys/kernel/random/boot_id").trim()}catch{}return`linux:${i}:${s}`}if(r==="darwin"){let s=o("ps",["-o","lstart=","-p",String(e)]),i=s.stdout.trim();return s.status===0&&i?`darwin:${i}`:null}if(r==="win32"){let s=`$p = Get-CimInstance Win32_Process -Filter "ProcessId=${e}"; if ($p) { $p.CreationDate.ToUniversalTime().ToString('o') }`,i=o("powershell.exe",["-NoProfile","-NonInteractive","-Command",s]),a=i.stdout.trim();return i.status===0&&a?`win32:${a}`:null}}catch{return null}return null}var Bm=p(()=>{"use strict"});import{createHash as zj,randomUUID as u_}from"node:crypto";import{closeSync as Xj,constants as Wm,existsSync as Qj,mkdirSync as Um,openSync as Zj,readFileSync as e1,renameSync as Fm,rmSync as jc,writeFileSync as t1}from"node:fs";import{createConnection as r1,createServer as s_}from"node:net";import{homedir as n1,tmpdir as o1}from"node:os";import Ut from"node:path";function s1(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function d_(e){let t=e.stateRoot??Ut.join(n1(),".kynver"),r=e.platform??process.platform,n=zj("sha256").update(`${Ut.resolve(t)}\0${e.agentOsId}`).digest("hex").slice(0,24),o=Ut.join(t,"locks"),s=Ut.join(o,`${n.slice(0,16)}.sock`);r==="linux"?s=`\0kynver-daemon-owner-${n}`:Buffer.byteLength(s)>100&&(s=Ut.join(o1(),`kynver-owner-${n.slice(0,16)}.sock`));let i=Ut.join(t,`daemon-owner-${s1(e.agentOsId)}.json`);return{lockKey:n,lockFile:Ut.join(o,`daemon-owner-${n}.lock`),metadataFile:i,quarantineFile:i.replace(/\.json$/,".stale.json"),socketAddress:s}}function a1(e){Um(Ut.dirname(e),{recursive:!0});let t;try{t=Zj(e,Wm.O_RDWR|Wm.O_CREAT|i1)}catch(n){let o=n.code;if(o==="EBUSY"||o==="EACCES"||o==="EPERM")return{busy:!0};throw n}let r=!0;return{held:{isHeld:()=>r,release:()=>{if(r){r=!1;try{Xj(t)}catch{}}}}}}function i_(e,t){return new Promise((r,n)=>{let o=i=>{e.off("listening",s),i.code==="EADDRINUSE"?r("in_use"):n(i)},s=()=>{e.off("error",o),r("listening")};e.once("error",o),e.once("listening",s),e.listen({path:t,exclusive:!0})})}function l1(e,t=2e3){return new Promise(r=>{let n=r1({path:e}),o=i=>{clearTimeout(s),n.removeAllListeners(),n.destroy(),r(i)},s=setTimeout(()=>o(!0),t);n.once("connect",()=>o(!0)),n.once("error",()=>o(!1))})}async function c1(e,t){e.startsWith("\0")||Um(Ut.dirname(e),{recursive:!0,mode:448});let r=s_(a=>a.destroy());if(await i_(r,e)==="listening")return{held:a_(r,e)};if(!t||e.startsWith("\0"))return{busy:!0};if(await l1(e))return{busy:!0};let o=`${e}.stale-${process.pid}-${u_().slice(0,8)}`;try{Fm(e,o),jc(o,{force:!0})}catch{}let s=s_(a=>a.destroy());return await i_(s,e).catch(()=>"in_use")==="listening"?{held:a_(s,e)}:{busy:!0}}function a_(e,t){e.unref();let r=!0;return{isHeld:()=>r&&e.listening,release:()=>{r&&(r=!1,e.close(),t.startsWith("\0")||jc(t,{force:!0}))}}}async function u1(e,t){return t==="win32"?a1(e.lockFile):c1(e.socketAddress,t!=="linux")}function d1(e){let t=e;return!!t&&t.version===1&&typeof t.agentOsId=="string"&&typeof t.instanceId=="string"&&typeof t.pid=="number"&&typeof t.ownerKind=="string"}function l_(e){try{let t=JSON.parse(e1(d_(e).metadataFile,"utf8"));return d1(t)?t:null}catch{return null}}function c_(e,t){Um(Ut.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;t1(r,`${JSON.stringify(t,null,2)}
|
|
86
|
+
`,{mode:384}),Fm(r,e)}function p1(e){if(!Qj(e.metadataFile))return null;try{return Fm(e.metadataFile,e.quarantineFile),e.quarantineFile}catch{return jc(e.metadataFile,{force:!0}),null}}function p_(e){return`This AgentOS already has a running daemon on this machine: ${e?`${e.ownerKind} daemon pid ${e.pid} (runtime ${e.runtimeVersion}, since ${e.acquiredAt})`:"another daemon"}. Stop it first (Ctrl-C in its window, \`systemctl --user stop kynver-cron-daemon\` for a systemd-owned one, or quit the Desktop app), then start again.`}async function Vc(e){let t=e.platform??process.platform,r=d_(e),n=await u1(r,t);if("busy"in n){let u=l_(e);return{ok:!1,reason:"owner_conflict",holder:u,remedy:p_(u)}}let o=p1(r),s=(e.now??new Date).toISOString(),i={version:1,agentOsId:e.agentOsId,ownerKind:e.ownerKind,instanceId:u_(),pid:process.pid,processStart:e.processStart!==void 0?e.processStart:o_(process.pid),runtimeVersion:Ge,platform:t,acquiredAt:s,lastRenewedAt:s};try{c_(r.metadataFile,i)}catch{}let a=n.held,l=!1;return{ok:!0,lease:{get metadata(){return i},get released(){return l},isHeld:()=>!l&&a.isHeld(),renew(u=new Date){if(!l){i.lastRenewedAt=u.toISOString();try{c_(r.metadataFile,i)}catch{}}},release(){if(l)return;l=!0,l_(e)?.instanceId===i.instanceId&&jc(r.metadataFile,{force:!0}),a.release()}},quarantinedMetadata:o}}var i1,Gc=p(()=>{"use strict";Vr();Bm();i1=Wm.UV_FS_O_EXLOCK??268435456});var f1,m1,g1,h1,os,Km=p(()=>{"use strict";f1="embedded-1",m1=[{slug:"ghost",displayName:"Ghost",description:"Orchestration persona.",dispatchLane:null,defaultRoleLane:"system"},{slug:"astra",displayName:"Astra",description:"Planning persona.",dispatchLane:"implementation",defaultRoleLane:"plan_author"},{slug:"rhea",displayName:"Rhea",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"mnemo",displayName:"Mnemo",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"sentinel",displayName:"Sentinel",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"deep_reviewer"},{slug:"pixel",displayName:"Pixel",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"schema",displayName:"Schema",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"atlas",displayName:"Atlas",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"runtime_verifier"},{slug:"bridge",displayName:"Bridge",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"catalyst",displayName:"Catalyst",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"lorentz",displayName:"Lorentz",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"report_reviewer"},{slug:"dalton",displayName:"Dalton",description:"Landing persona.",dispatchLane:"landing",defaultRoleLane:"implementer"}],g1={"worker.prompt.core_rules":["Structured final result (recommended): record completion as JSON with summary, files, PR URLs, verification, risks, and blockers.","Completion handoff (required): before you stop, summarize the outcome in your last message and append a heartbeat line with phase `complete` and a structured finalResult object. Commit your work cleanly and open a GitHub PR (draft OK) for substantial changes \u2014 never leave uncommitted changes behind without reporting them.","Review-only workers must not open new implementation PRs \u2014 review the existing PR and record a verdict in the final result. Prefer `gh pr view` / `gh pr diff`; if a local checkout is needed, use a disposable ref or detached worktree, not a checked-out `pr-*` branch.","Keep verification targeted to touched paths; avoid full-monorepo verification unless explicitly requested.","Do not run `npm publish`.","If verification fails, append a heartbeat line immediately with the failing command, reason, and next action."].join(`
|
|
23
87
|
`),"worker.prompt.progress.compact":"Plan progress: when planId is set, report progress with `kynver plan progress --plan <planId> --row <rowKey> --role implementer --status in_progress|running|partial|blocked`. Do not mark rows done from the worker CLI.","worker.prompt.progress.full":["Structured plan progress (required when planId is set):","- Report checkpoints with `kynver plan progress --plan <planId> --row <rowKey> --role implementer --status in_progress|running|partial|blocked`.","- When a slice is finished, emit `partial` with evidence (`--evidence pr:<url>`, `--evidence path:<file>`, or `--evidence command:<cmd>`).","- Do not propose or confirm row `done` from the worker CLI."].join(`
|
|
24
88
|
`),"worker.prompt.merge_gate.compact":"Verification cost control: prefer local verification before requesting CI runs; do not push empty commits to re-trigger CI; record verification evidence on the PR.","worker.prompt.merge_gate.full":["Verification cost control:","- Prefer local verification of touched paths before requesting any CI run.","- Do not push empty commits to re-trigger CI.","- Record verification evidence on the PR before requesting review."].join(`
|
|
25
89
|
`),"worker.prompt.plan_artifacts.compact":"Plan artifacts: when authoring or revising plan documents, open a GitHub PR early and iterate from that PR branch; do not leave the canonical plan only in a local worktree.","worker.prompt.plan_artifacts.full":["Plan artifacts (when authoring or revising plan documents):","- Create a feature branch and open a GitHub PR (draft OK) before substantial drafting; commit and push the plan file.","- Iterate on that PR branch and link the PR URL on the related task and progress evidence."].join(`
|
|
26
|
-
`)},
|
|
90
|
+
`)},h1={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},os={version:f1,generatedAt:"1970-01-01T00:00:00.000Z",personas:m1,instructions:g1,policyThresholds:h1}});function m_(){return ss}function Mn(){return ss.version}function Ft(){return f_}function g_(e,t){ss=e,f_=t}function Hi(e){let t=ss.instructions[e];if(typeof t=="string"&&t.trim())return t;let r=os.instructions[e];return typeof r=="string"?r:""}function is(e,t){let r=ss.policyThresholds[e];if(typeof r=="number"&&Number.isFinite(r))return r;let n=os.policyThresholds[e];return typeof n=="number"&&Number.isFinite(n)?n:t}function h_(e){if(!e)return null;let t=e.trim().toLowerCase();return ss.personas.find(r=>r.slug===t)??null}var ss,f_,Gr=p(()=>{"use strict";Km();ss=os,f_="embedded"});import y_ from"node:os";function hr(e){return e?.trim()?e.trim():null}function De(e={}){let t=e.env??process.env,r=P();return{runnerId:hr(r.runnerId)??hr(t.KYNVER_RUNTIME_ID)??hr(t.OPENCLAW_RUNTIME_ID)??hr(t.HOSTNAME)??y_.hostname(),hostname:hr(t.HOSTNAME)??y_.hostname(),profile:hr(t.KYNVER_RUNNER_PROFILE)??hr(t.OPENCLAW_RUNNER_PROFILE),harnessRepo:hr(t.KYNVER_HARNESS_REPO)??hr(t.KYNVER_DEFAULT_REPO),runId:e.runId??null,instructionBundleVersion:Mn()}}var yr=p(()=>{"use strict";$();Gr();Le()});import y1 from"node:os";function $m(e=P(),t=process.env){let r=et(t,e),n=[...r.warnings],o=e.maxConcurrentWorkers,s=!1,i={...e};e.boxKind?.trim()||(i.boxKind=r.boxKind,s=!0,n.push(`persisted boxKind=${r.boxKind} to ~/.kynver/config.json \u2014 customers use box; operators set \`kynver setup --box-kind forge|ghost\``));let a=Wt(i,t);a.identity&&(i.runnerId?.trim()||(i.runnerId=a.identity.runnerId,s=!0,n.push(`persisted runnerId=${a.identity.runnerId} to ~/.kynver/config.json`)),!i.harnessRoot?.trim()&&(a.identity.harnessRootSource==="box_scoped"||a.identity.harnessRootSource==="legacy_migrated")&&(i.harnessRoot=a.identity.harnessRoot,s=!0,n.push(`persisted harnessRoot=${a.identity.harnessRoot} for ${r.boxKind} pool isolation`)));let l=t.KYNVER_BOX_ID?.trim();if(!e.boxId?.trim()&&l?(i.boxId=mc(l,r.boxKind),s=!0,n.push(`persisted boxId=${i.boxId} to ~/.kynver/config.json \u2014 set explicitly via kynver setup --box-id`)):!e.boxId?.trim()&&!l&&(i.boxId=Ii(r.boxKind,y1.hostname()),s=!0,n.push(`persisted boxId=${i.boxId} to ~/.kynver/config.json`)),hi(r.boxKind,o??0))o=4,i.maxConcurrentWorkers=4,i.maxConcurrentWorkersSource="setup-auto",s=!0,n.push(`clamped Forge maxConcurrentWorkers to ${4} (was ${e.maxConcurrentWorkers}; workspace aggregate caps are Ghost-only)`);else if(o!=null){let c=ir(r.boxKind,o);c!==o&&(o=c,i.maxConcurrentWorkers=c,s=!0,n.push(`clamped maxConcurrentWorkers to ${c} for ${r.boxKind} pool`))}return s&&We(i),{repaired:s,boxKind:r.boxKind,maxConcurrentWorkers:o??4,warnings:n}}var Hm=p(()=>{"use strict";$();Le();Vo();Io();Sn()});function It(e){let t=String(e).trim();return t.startsWith("krc1.")?{"Content-Type":"application/json","X-Kynver-Runner-Token":t}:{"Content-Type":"application/json","X-Kynver-Cron-Secret":t,"X-OpenClaw-Cron-Secret":t,"X-Kynver-Runtime-Secret":t}}var as=p(()=>{"use strict"});function k1(e){let t=e.runnerId??De().runnerId;return`${e.baseUrl.replace(/\/+$/,"")}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/runtime-control/runner?runnerId=${encodeURIComponent(t)}`}async function k_(e,t){try{return(await(e.fetchImpl??fetch)(k1(e),{method:"POST",headers:It(e.secret),body:JSON.stringify({ack:t})})).ok}catch{return!1}}var jm=p(()=>{"use strict";as();yr();$r()});var b_=p(()=>{"use strict";$();M();jm();$r()});function v_(){let e=process.env.KYNVER_GIT_COMMIT_SHA?.trim();return{contractVersion:1,nodeVersion:process.versions.node,runtimePackageVersion:Ge,buildIdentity:e&&b1.test(e)?e.toLowerCase():null,platform:process.platform,arch:process.arch}}var b1,R_=p(()=>{"use strict";Vr();b1=/^[0-9a-f]{7,40}$/i});import{mkdirSync as v1,readFileSync as gde,renameSync as R1,writeFileSync as w1}from"node:fs";import{homedir as S1}from"node:os";import w_ from"node:path";function _1(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return w_.join(S1(),".kynver",`daemon-heartbeat-${t}.json`)}function S_(e){try{let t=_1(e.agentOsId);v1(w_.dirname(t),{recursive:!0});let r={observedAt:(e.now??new Date).toISOString(),pid:process.pid,runId:e.runId,agentOsId:e.agentOsId,...e.instructionBundleVersion?{instructionBundleVersion:e.instructionBundleVersion}:{},runtimeIdentity:v_(),...e.owner?{owner:e.owner}:{}},n=`${t}.tmp-${process.pid}`;w1(n,JSON.stringify(r),"utf8"),R1(n,t)}catch{}}var Vm=p(()=>{"use strict";R_();Bm()});function Gm(e,t,r=6e4){let n=t-e;return n>r?n:null}var Jm=p(()=>{"use strict"});function C1(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_meta'").get())return null;let r=e.prepare("SELECT value FROM local_meta WHERE key = 'schema_version'").get();if(!r?.value)return null;let n=Number.parseInt(r.value,10);return Number.isFinite(n)?n:null}function __(e,t){let r=C1(e);if(r!==null&&r>1)throw new qm(r,1);e.exec("BEGIN IMMEDIATE");try{for(let n of x1)e.exec(n);e.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(1)),e.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_applied_at', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),e.exec("COMMIT")}catch(n){throw e.exec("ROLLBACK"),n}}var qm,x1,x_=p(()=>{"use strict";qm=class extends Error{constructor(t,r){super(`local-run-store schema version ${t} is newer than this runtime supports (${r}); refusing to open. Upgrade the runtime or quarantine the database deliberately.`),this.name="SchemaDowngradeRefusedError"}},x1=[`CREATE TABLE IF NOT EXISTS local_meta (
|
|
27
91
|
key TEXT PRIMARY KEY,
|
|
28
92
|
value TEXT NOT NULL
|
|
29
93
|
) STRICT`,`CREATE TABLE IF NOT EXISTS process_identity (
|
|
@@ -49,8 +113,8 @@ ${e.stderr}`.trim(),r=QU(t);if(!r||!ci(r)){let o=li(t||`exit ${e.exitCode}`,180)
|
|
|
49
113
|
payload_json TEXT NOT NULL,
|
|
50
114
|
created_at TEXT NOT NULL,
|
|
51
115
|
PRIMARY KEY (scope, seq)
|
|
52
|
-
) STRICT`]});import{existsSync as
|
|
53
|
-
`)){let n=r.trim().split(/\s+/);n.length<3||t.push({mountPoint:
|
|
116
|
+
) STRICT`]});import{existsSync as E1,realpathSync as A1,readFileSync as P1}from"node:fs";import C_ from"node:path";function T1(){try{return P1("/proc/self/mounts","utf8")}catch{return null}}function N1(e){let t=C_.resolve(e);for(let r=0;r<64;r+=1){if(E1(t))try{return A1.native(t)}catch{return t}let n=C_.dirname(t);if(n===t)return t;t=n}return t}function D1(e){return e.replace(/\\(\d{3})/g,(t,r)=>String.fromCharCode(Number.parseInt(r,8)))}function M1(e){let t=[];for(let r of e.split(`
|
|
117
|
+
`)){let n=r.trim().split(/\s+/);n.length<3||t.push({mountPoint:D1(n[1]),fsType:n[2]})}return t}function E_(e,t=process.platform){return t==="win32"?e.replace(/\\/g,"/"):e}function L1(e,t){let r=null,n=E_(e);for(let o of t){let s=E_(o.mountPoint),i=s.endsWith("/")?s:`${s}/`;(n===s||`${n}/`.startsWith(i))&&(!r||o.mountPoint.length>r.mountPoint.length)&&(r=o)}return r}function A_(e,t){let n=(t?.resolveRealPath??N1)(e),o=(t?.mountsSource??T1)();if(o===null)return{verdict:"rejected",reason:"Mount information unavailable \u2014 the filesystem type cannot be established safely, so WAL mode is refused (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let s=L1(n,M1(o));if(!s)return{verdict:"rejected",reason:"No mount entry covers the resolved database path \u2014 refusing WAL mode (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let i=s.fsType.toLowerCase();return O1.has(i)||i.startsWith("fuse.")?{verdict:"rejected",reason:`Filesystem '${i}' is network-like or crosses an OS boundary; SQLite WAL locking is not safe there.`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}:I1.has(i)?{verdict:"accepted",reason:`Local filesystem '${i}' accepted for WAL mode.`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}:{verdict:"rejected",reason:`Filesystem '${i}' is unknown to the qualification policy; WAL mode is refused rather than guessed (fail closed).`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}}var I1,O1,P_=p(()=>{"use strict";I1=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),O1=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"])});import{mkdirSync as W1}from"node:fs";import U1 from"node:path";import{DatabaseSync as F1}from"node:sqlite";var qc,K1,$1,ji,I_=p(()=>{"use strict";x_();P_();qc=class extends Error{constructor(t){super(`local-run-store refused: ${t}`),this.name="FilesystemPolicyError"}},K1="local-run-store.sqlite",$1=5e3,ji=class e{db;now;databasePath;constructor(t,r,n){this.db=t,this.databasePath=r,this.now=n}static open(t){let r=A_(t.directory,t.classifyOptions);if(r.verdict!=="accepted")throw new qc(r.reason);W1(t.directory,{recursive:!0,mode:448});let n=U1.join(t.directory,t.filename??K1),o=new F1(n,{timeout:t.busyTimeoutMs??$1}),s=t.now??(()=>new Date);try{o.exec("PRAGMA journal_mode = WAL");let i=o.prepare("PRAGMA journal_mode").get();if(i?.journal_mode?.toLowerCase()!=="wal")throw new qc(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),__(o,s().toISOString())}catch(i){throw o.close(),i}return new e(o,n,s)}inImmediateTransaction(t){this.db.exec("BEGIN IMMEDIATE");try{let r=t();return this.db.exec("COMMIT"),r}catch(r){throw this.db.exec("ROLLBACK"),r}}registerProcessIdentity(t){let r=this.now().toISOString();return this.inImmediateTransaction(()=>{this.db.prepare(`INSERT INTO process_identity
|
|
54
118
|
(process_key, pid, runtime_version, node_version, started_at, registered_at)
|
|
55
119
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
56
120
|
ON CONFLICT(process_key) DO UPDATE SET
|
|
@@ -74,134 +138,134 @@ ${e.stderr}`.trim(),r=QU(t);if(!r||!ci(r)){let o=li(t||`exit ${e.exitCode}`,180)
|
|
|
74
138
|
LIMIT ?`).all(...s,n).map(l=>({idempotencyKey:l.idempotency_key,operation:l.operation,resultJson:l.result_json,recordedAt:l.recorded_at}))}deleteOperationReceiptsByKeys(t){return t.length===0?0:this.inImmediateTransaction(()=>{let r=this.db.prepare("DELETE FROM operation_receipts WHERE idempotency_key = ?"),n=0;for(let o of t)n+=Number(r.run(o).changes);return n})}getOperationReceipt(t){let r=this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
|
|
75
139
|
FROM operation_receipts WHERE idempotency_key = ?`).get(t);return r?{idempotencyKey:r.idempotency_key,operation:r.operation,resultJson:r.result_json,recordedAt:r.recorded_at}:null}saveRecoveryCheckpoint(t){return this.inImmediateTransaction(()=>{let r=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max_seq FROM recovery_checkpoints WHERE scope = ?").get(t.scope),n=Number(r.max_seq)+1;return this.db.prepare(`INSERT INTO recovery_checkpoints (scope, seq, payload_json, created_at)
|
|
76
140
|
VALUES (?, ?, ?, ?)`).run(t.scope,n,t.payloadJson,this.now().toISOString()),{seq:n}})}latestRecoveryCheckpoint(t){let r=this.db.prepare(`SELECT scope, seq, payload_json, created_at FROM recovery_checkpoints
|
|
77
|
-
WHERE scope = ? ORDER BY seq DESC LIMIT 1`).get(t);return r?{scope:r.scope,seq:r.seq,payloadJson:r.payload_json,createdAt:r.created_at}:null}localSchemaVersion(){return 1}checkpointTruncate(){this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)")}integrityCheck(){return this.db.prepare("PRAGMA integrity_check").get()?.integrity_check==="ok"}pragma(t){let r=this.db.prepare(`PRAGMA ${t}`).get();return String(Object.values(r)[0])}close(){this.db.close()}}});import{existsSync as
|
|
78
|
-
`)}var fce,mce,gce,hce,Am=p(()=>{"use strict";Ur();ES();H();vm();D();yc();wm();Bi();fce=15*6e4,mce=2*6e4,gce=5*6e4,hce=30*6e4});import Aj from"node:path";function Pj(e){return Aj.resolve(Ne(e.trim()))}function rs(e,t,r){let n=e?.trim();return n?{repo:Pj(n),source:t,persistedInConfig:r}:null}function ZS(e){return e?{repo:e.repo,source:e.source,persistedInConfig:!1}:null}function Wi(e={}){let t=e.env??process.env,r=e.config??E(),n=rs(r.defaultRepo,"config",!0);if(n)return n;let o=rs(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(o)return o;let s=rs(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return s||ZS(Al({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl}))}function e_(e={}){let t=e.env??process.env,r=e.config??E(),n=rs(r.defaultRepo,"config",!0);if(n)return n;let o=rs(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(o)return o;let s=rs(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return s||ZS(Pl({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl,home:e.home}))}function t_(e,t){let r={...t??E(),defaultRepo:Ne(e),...yv(e)&&!t?.defaultBase?.trim()?{defaultBase:"main"}:{}};return Le(r),r}function Pm(e){return{defaultRepo:$e(e.repo),source:e.source,persistedInConfig:e.persistedInConfig}}var ns=p(()=>{"use strict";H();oi();nt();zp()});import Ij from"node:path";import{homedir as Oj}from"node:os";function r_(e){let t=E(),r=e_({...e,config:t});if(!r)return{ok:!1,remediated:!1,alreadyPersisted:!1,configPath:$e(Im),resolved:null,reason:"No git checkout found. Run this command from inside the repo you want the daemon to work on, or pass `kynver setup --repo /path/to/repo` (or export KYNVER_DEFAULT_REPO). On a fresh BYOC machine, `kynver start` creates ~/.kynver/workspace automatically.",remediation:"Run `kynver start` (creates ~/.kynver/workspace), or `kynver config ensure-default-repo` from a checkout (or `kynver setup --repo /path/to/repo`)."};if(r.persistedInConfig)return{ok:!0,remediated:!1,alreadyPersisted:!0,configPath:$e(Im),resolved:Pm(r),config:Lf(t)};let n=t_(r.repo,t),o=Pm({...r,persistedInConfig:!0,source:"config"});return{ok:!0,remediated:!0,alreadyPersisted:!1,configPath:$e(Im),resolved:o,config:Lf(n),remediation:"defaultRepo persisted in ~/.kynver/config.json \u2014 `kynver run create` no longer requires --repo."}}var Im,n_=p(()=>{"use strict";nt();H();ns();Im=Ij.join(Oj(),".kynver","config.json")});import{mkdirSync as Tj,readFileSync as Nj,renameSync as Dj,writeFileSync as Mj}from"node:fs";import{homedir as Lj}from"node:os";import o_ from"node:path";function s_(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return o_.join(Lj(),".kynver",`instruction-bundle-${t}.json`)}function i_(e,t){try{let r=s_(e);Tj(o_.dirname(r),{recursive:!0});let n=`${r}.tmp-${process.pid}`;Mj(n,JSON.stringify(t),{encoding:"utf8",mode:384}),Dj(n,r)}catch{}}function a_(e){try{let t=Nj(s_(e),"utf8"),r=JSON.parse(t);return Ci(r)?r:null}catch{return null}}var l_=p(()=>{"use strict";Fr()});function c_(e,t=process.env){let r=Go(t.KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY);if(r&&Rw(r)===e)return r;if(e===Bj&&!kc(t))return null;let n=Wj[e];return n?Go(n):null}var Bj,Wj,u_=p(()=>{"use strict";Fr();Bj="ib-3bab6314f0ba",Wj={"ib-3bab6314f0ba":"53a2040646cd479e1f5f1aea9abf7848ce8b62e32001efb8044dfd90e8ab87ed","ib-26e6c695da06":"bb1700f25b2ee7d7cdcdb9f446f0f44ef2cc22a3096bc161232fb658e7cdaf38","ib-49e76cb8052c":"8fc646b5c4f8f402120477452608398f035c3cddd2e7aa8bb328e97b84dcf6d8"}});import{createPublicKey as Uj,verify as Fj}from"node:crypto";function Kj(e){return Uj({key:Buffer.concat([$j,Buffer.from(e)]),format:"der",type:"spki"})}function Hj(e,t){if(!Ci(e))return{ok:!1,reason:"malformed signed bundle payload"};let r;try{r=Buffer.from(e.signature,"base64url")}catch{return{ok:!1,reason:"signature is not base64url"}}if(r.length!==64)return{ok:!1,reason:"signature is not a 64-byte Ed25519 signature"};try{let n=Buffer.from(et(e.bundle),"utf8");return Fj(null,n,Kj(t),r)?{ok:!0,bundle:e.bundle}:{ok:!1,reason:"Ed25519 signature mismatch"}}catch(n){return{ok:!1,reason:`signature verification failed: ${n.message}`}}}function d_(e,t=process.env){if(!Ci(e))return{ok:!1,reason:"malformed signed bundle payload"};let r=c_(e.publicKeyId,t);return r?Hj(e,r):{ok:!1,reason:`no verification key for publicKeyId "${e.publicKeyId}" (not pinned; set KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY)`}}var $j,p_=p(()=>{"use strict";u_();Fr();$j=Buffer.from("302a300506032b6570032100","hex")});function Fi(e,t){console.error(JSON.stringify({event:e,...t}))}function f_(e,t,r){let n=d_(e);return n.ok?(SS(n.bundle,t),t==="server"&&i_(r,e),!0):(Fi("instruction_bundle_signature_invalid",{agentOsId:r,source:t,publicKeyId:e.publicKeyId,reason:n.reason}),!1)}function Ui(e){if(yr.diskCacheTried)return!1;yr.diskCacheTried=!0;let t=a_(e);return t?f_(t,"disk",e):!1}async function m_(e){let t=e.nowMs??Date.now(),r=()=>({source:Lt(),version:An(),updated:!1});if(!e.force&&t-yr.lastAttemptAtMs<jj)return r();yr.lastAttemptAtMs=t;let n=e.baseUrl?.trim().replace(/\/$/,""),o=e.secret?.trim();if(!n||!o)return Lt()==="embedded"&&Ui(e.agentOsId)?{...r(),updated:!0}:r();let s=e.fetchImpl??fetch,i=new AbortController,a=setTimeout(()=>i.abort(),Vj);try{let l=Ct(o);delete l["Content-Type"],yr.etag&&Lt()==="server"&&(l["If-None-Match"]=yr.etag);let c=await s(`${n}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/runtime/instruction-bundle`,{headers:l,signal:i.signal});if(c.status===304)return r();if(c.status===404)return yr.routeMissingLogged||(yr.routeMissingLogged=!0,Fi("instruction_bundle_route_missing",{agentOsId:e.agentOsId,baseUrl:n})),Lt()==="embedded"&&Ui(e.agentOsId)?{...r(),updated:!0}:r();if(!c.ok)return Fi("instruction_bundle_fetch_failed",{agentOsId:e.agentOsId,status:c.status}),Lt()==="embedded"&&Ui(e.agentOsId)?{...r(),updated:!0}:r();let u=await c.json().catch(()=>null);return!u||!f_(u,"server",e.agentOsId)?Lt()==="embedded"&&Ui(e.agentOsId)?{...r(),updated:!0}:r():(yr.etag=c.headers.get("etag"),Fi("instruction_bundle_loaded",{agentOsId:e.agentOsId,version:An(),publicKeyId:u.publicKeyId}),{...r(),updated:!0})}catch(l){return Fi("instruction_bundle_fetch_error",{agentOsId:e.agentOsId,error:l instanceof Error?l.message:String(l)}),Lt()==="embedded"&&Ui(e.agentOsId)?{...r(),updated:!0}:r()}finally{clearTimeout(a)}}var jj,Vj,yr,g_=p(()=>{"use strict";es();l_();Kr();p_();jj=15*6e4,Vj=1e4,yr={lastAttemptAtMs:0,etag:null,diskCacheTried:!1,routeMissingLogged:!1}});import Gj from"node:os";function h_(e,t){console.error(JSON.stringify({event:"daemon_identity",level:e,message:t}))}function y_(e=E(),t=process.env){let r=Qe(t,e),n=Do({config:e,totalMemBytes:Gj.totalmem(),env:t}),o=[...r.warnings],s=[];if(!e.boxKind?.trim()&&!t.KYNVER_BOX_KIND?.trim()&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup` (customers get boxKind=box) or `kynver setup --box-kind forge|ghost` for operator pools before starting the daemon"),r.slugInferenceBlocked){let c=t.KYNVER_DAEMON_STRICT_IDENTITY==="1"||t.KYNVER_DAEMON_STRICT_IDENTITY==="true",u="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind; treating this host as a customer box (boxKind=box), not forge/ghost";c?s.push(u):o.push(u)}let i=n.configuredMaxWorkers??n.autoCap,a=or(r.boxKind,i);ii(r.boxKind,i)&&o.push(`Forge box maxConcurrentWorkers=${i} exceeds pool cap \u2014 using ${a}; run kynver setup --box-kind forge --max-workers 4`);let l=s.length===0;for(let c of o)h_("warn",c);for(let c of s)h_("error",c);return{ok:l,box:r,workerCapSource:n.workerCapSource,maxConcurrentWorkers:a,autoCap:n.autoCap,warnings:o,errors:s}}var k_=p(()=>{"use strict";H();De();So();hi()});import{spawnSync as Jj}from"node:child_process";import{existsSync as qj,readFileSync as Yj}from"node:fs";import zj from"node:path";function Qj(e,t,r){let n=new Map(e.map(s=>[s.pid,s])),o=[];for(let s of t)if(!(r(s.pid)||n.has(s.pid)))for(let i of e)i.parentPid===s.pid&&(i.createdAtMs+Xj<s.startedAtMs||o.push({workerName:s.workerName,workerPid:s.pid,orphanPid:i.pid}));return o}function Zj(e){let t=e.trim();if(!t)return[];let r=JSON.parse(t),n=Array.isArray(r)?r:[r],o=[];for(let s of n){let i=Number(s.ProcessId),a=Number(s.ParentProcessId),l=Date.parse(String(s.Created??""));Number.isInteger(i)&&Number.isInteger(a)&&Number.isFinite(l)&&o.push({pid:i,parentPid:a,createdAtMs:l})}return o}function e1(e){let t=e.filter(s=>Number.isInteger(s)&&s>0);if(t.length===0)return[];let n=`Get-CimInstance Win32_Process -Filter "${t.map(s=>`ParentProcessId=${s}`).join(" OR ")}" | Select-Object ProcessId,ParentProcessId,@{n='Created';e={$_.CreationDate.ToUniversalTime().ToString('o')}} | ConvertTo-Json -Compress`,o=Jj("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:3e4});if(o.status!==0)return[];try{return Zj(o.stdout??"")}catch{return[]}}function t1(e,t=re){try{let r=Re().find(o=>o.id===e);if(!r)return[];let n=[];for(let o of Object.keys(r.workers||{})){let s=zj.join(G(r.id),"workers",B(o),"worker.json");if(!qj(s))continue;let i=JSON.parse(Yj(s,"utf8")),a=Date.parse(i.startedAt??"");!i.pid||!Number.isFinite(a)||t(i.pid)||n.push({workerName:o,pid:i.pid,startedAtMs:a})}return n}catch{return[]}}function b_(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return{checkedWorkers:0,killed:[]};let n=t.isAlive??re,o=(t.collect??(l=>t1(l,n)))(e);if(o.length===0)return{checkedWorkers:0,killed:[]};let s=(t.query??e1)(o.map(l=>l.pid)),i=t.killTree??Se,a=Qj(s,o,n).map(l=>({...l,result:i(l.orphanPid,"SIGKILL")}));return{checkedWorkers:o.length,killed:a}}var Xj,v_=p(()=>{"use strict";z();D();Zs();Xj=5e3});import{mkdirSync as r1,readFileSync as n1,renameSync as o1,writeFileSync as s1}from"node:fs";import{homedir as i1}from"node:os";import Bc from"node:path";function R_(){return Bc.join(i1(),".kynver")}function a1(e=R_()){return Bc.join(e,"doctor-native-windows.json")}function w_(e=R_()){return Bc.join(e,"native-windows-state.json")}function l1(e,t){r1(Bc.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;s1(r,`${JSON.stringify(t,null,2)}
|
|
79
|
-
`,{mode:384}),
|
|
80
|
-
`,"utf8");try{await Ki.rename(n,e)}catch(o){let s=o.code;if(s!=="EPERM"&&s!=="EEXIST"&&s!=="EACCES")throw o;await Ki.unlink(n).catch(()=>{})}}async function W_(e,t){await T1(e,t)}function U_(e,t){let r=e.jobs[t];if(r)return r;let n={providerScheduleId:t,nextFireAt:null,lastFiredAt:null,lastAttemptAt:null,consecutiveFailures:0,completedAt:null,inflightUntil:null};return e.jobs[t]=n,n}var Uc,Um=p(()=>{"use strict";Uc={version:1,jobs:{}}});function N1(e,t){if(!e.inflightUntil)return!1;let r=Date.parse(e.inflightUntil);return!Number.isNaN(r)&&r>t}function D1(e){return!!e.completedAt}function M1(e,t,r,n){if(t.consecutiveFailures===0)return!0;if(e.spec.scheduleKind!=="cron"&&t.consecutiveFailures>r.maxRetries)return!1;if(!t.lastAttemptAt)return!0;let o=Date.parse(t.lastAttemptAt);return Number.isNaN(o)?!0:n-o>=r.retryBackoffMs}function L1(e,t,r){if(t.nextFireAt)return t.nextFireAt;let n=L_(e.spec,r);return t.nextFireAt=n,n}function B1(e,t,r,n){if(e.paused||D1(t)||N1(t,r)||!M1(e,t,n,r))return!1;let o=t.nextFireAt?Date.parse(t.nextFireAt):NaN;return Number.isNaN(o)?!1:r>=o}function W1(e,t,r){e.spec.scheduleKind==="cron"&&(t.nextFireAt=Bm(e.spec,r))}async function Fm(e={}){let t=e.env??qo(),r=e.now??new Date,n=r.getTime(),o=e.agentOsIdFilter?He(e.agentOsIdFilter):He();if(!t.tickEnabled)return{enabled:!1,skipped:"tick_disabled",scanned:0,due:0,fired:0,skippedJobs:0,errors:0};if(!t.fireBaseUrl||!t.secret&&!o)return{enabled:!0,skipped:"missing_fire_credentials",scanned:0,due:0,fired:0,skippedJobs:0,errors:0};let s=T_(t.lockPath);if(!s.acquired)return{enabled:!0,skipped:s.reason??"lock_not_acquired",scanned:0,due:0,fired:0,skippedJobs:0,errors:0,lockHeld:!0};try{let i=await Pc(t.storePath),a=e.agentOsIdFilter?i.filter(h=>h.spec.target.agentOsId===e.agentOsIdFilter):i,l=await Wm(t.statePath),c=[];for(let h of a){let y=U_(l,h.providerScheduleId);L1(h,y,r),B1(h,y,n,t)&&c.push({entry:h,job:y})}c.sort((h,y)=>{let v=Date.parse(h.job.nextFireAt??"")||0,k=Date.parse(y.job.nextFireAt??"")||0;return v-k});let u=0,d=0,m=0,f=t.maxCatchUpPerTick,g=[];for(let{entry:h,job:y}of c){if(t.missedRunPolicy==="skip"&&h.spec.scheduleKind==="cron"){let v=Date.parse(y.nextFireAt??"");if(!Number.isNaN(v)&&v<n-t.tickIntervalMs*2){y.nextFireAt=Bm(h.spec,r),m++;continue}}if(f<=0){m++;continue}y.inflightUntil=new Date(n+t.inflightLeaseMs).toISOString(),y.lastAttemptAt=r.toISOString(),W1(h,y,r);try{let v=He(h.spec.target.agentOsId)||t.secret;if(!v){y.inflightUntil=null,y.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,error:"missing_fire_credentials"});continue}let k=await A_({entry:h,baseUrl:t.fireBaseUrl,secret:v,fetchFn:e.fetchFn});y.inflightUntil=null,k.ok?(y.lastFiredAt=r.toISOString(),y.consecutiveFailures=0,h.spec.scheduleKind==="runAt"&&(y.completedAt=r.toISOString(),y.nextFireAt=null),u++,f--):(y.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,url:k.url,status:k.status,body:k.body}))}catch(v){y.inflightUntil=null,y.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,error:v instanceof Error?v.message:String(v)})}}return await W_(t.statePath,l),{enabled:!0,scanned:a.length,due:c.length,fired:u,skippedJobs:m,errors:d,...g.length?{errorDetails:g}:{}}}finally{N_(t.lockPath)}}var $m=p(()=>{"use strict";pr();P_();D_();H();B_();Yo();Um()});import F_ from"node:path";function Fc(e){let t=$(F_.join(G(e),$_),null);return JS(e,t)??t}function K_(e,t){let r={...t,updatedAt:new Date().toISOString()};ye(F_.join(G(e),$_),r),GS(e,r)}function H_(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.response;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.meshLiveness;if(!r||typeof r!="object"||Array.isArray(r))return null;let n=r.cronLease;if(!n||typeof n!="object"||Array.isArray(n))return null;let o=n;return{leaseToken:typeof o.leaseToken=="string"?o.leaseToken:null,holderBoxId:typeof o.holderBoxId=="string"?o.holderBoxId:null,authorized:o.authorized===!0,updatedAt:new Date().toISOString()}}var $_,Km=p(()=>{"use strict";D();z();Bi();$_="mesh-cron-lease.json"});function G_(e){Hi=e}function J_(e=Date.now()){return!Hi||Hi.stallCount===j_&&e-V_<9e5?null:(j_=Hi.stallCount,V_=e,Hi)}var Hi,j_,V_,Hm=p(()=>{"use strict";Hi=null,j_=-1,V_=0});function Y_(e){if(e!==void 0&&Number.isFinite(e)&&e>0)return Math.floor(e);let t=Number(process.env.KYNVER_CALLBACK_TIMEOUT_MS);return Number.isFinite(t)&&t>0?Math.floor(t):3e4}function q_(e){return new Error(`callback timeout after ${e}ms`)}async function z_(e,t){let r=Y_(t),n=new AbortController,o,s=!1;try{return await Promise.race([e(n.signal),new Promise((i,a)=>{o=setTimeout(()=>{s=!0,n.abort(),a(q_(r))},r)})])}catch(i){throw s?q_(r):i}finally{o&&clearTimeout(o)}}function X_(e,t){let r=Y_(t);return{ok:!1,status:0,response:{error:e instanceof Error?e.message:String(e),timeoutMs:r}}}async function Pn(e,t,r,n){try{return await z_(async o=>{let s=await it(e,{method:"POST",headers:Ct(t),body:JSON.stringify(r),signal:o}),i=null;try{i=await s.json()}catch{i=null}return{ok:s.ok,status:s.status,response:i}},n?.timeoutMs)}catch(o){return X_(o,n?.timeoutMs)}}async function de(e,t,r,n){let o=await Pn(e,t,r,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await gw(t,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await Pn(e,s.token,r,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function jm(e,t,r){try{return await z_(async n=>{let o=await it(e,{method:"GET",headers:Ct(t),signal:n}),s=null;try{s=await o.json()}catch{s=null}return{ok:o.ok,status:o.status,response:s}},r?.timeoutMs)}catch(n){return X_(n,r?.timeoutMs)}}var We=p(()=>{"use strict";es();nr();H()});function Q_(){let e=Number(process.env.KYNVER_DISPATCH_CALLBACK_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):3e5}var Z_=p(()=>{"use strict"});function ji(e){console.error(JSON.stringify({event:"dispatch_progress",ts:new Date().toISOString(),...e}))}function ex(e){if(!e||typeof e!="object")return!1;let t=e;if(t.timeout===!0||t.timeoutMs!==void 0)return!0;let r=t.error;if(typeof r!="string"||!r.trim())return!1;let n=r.toLowerCase();return n.includes("abort")||n.includes("timeout")}function Vm(e){if(!e||typeof e!="object")return!1;let t=e;return t.timeout===!0?!0:(typeof t.error=="string"?t.error.toLowerCase():"").includes("timeout")}var tx=p(()=>{"use strict"});function $1(e){return U1.includes(e)}function K1(e){return F1.includes(e)}function rx(e){return{slug:e.slug,displayName:e.displayName,description:e.description,dispatchLane:e.dispatchLane===null||$1(e.dispatchLane)?e.dispatchLane:null,defaultRoleLane:K1(e.defaultRoleLane)?e.defaultRoleLane:"implementer"}}function j1(e){if(!e)return null;let t=e.trim().toLowerCase(),r=H1.get(t)??null,n=_S(t);if(!n)return r;let o=rx(n);return r?{...o,dispatchLane:r.dispatchLane,defaultRoleLane:r.defaultRoleLane}:o}function Gm(e){return j1(e)?.defaultRoleLane??null}function ox(){return nx.filter(e=>e.dispatchLane==="review").map(e=>e.slug)}var U1,F1,nx,H1,$c=p(()=>{"use strict";hm();Kr();U1=["implementation","review","landing"],F1=["plan_author","implementer","report_reviewer","deep_reviewer","runtime_verifier","system"];nx=Xo.personas.map(rx),H1=new Map(nx.map(e=>[e.slug,e]))});function sx(e){return(e??"").trim().toLowerCase()}function V1(e){switch(sx(e)){case"implementer":case"repair_implementer":case"plan_author":case"runtime_verifier":return"implementation";case"plan_reviewer":case"report_reviewer":case"deep_reviewer":return"review";default:return null}}function G1(e){let t=sx(e);if(!t)return;if(t==="implementation"||t==="review"||t==="landing"||t==="any")return t;let r=V1(t);if(r)return r;if(t==="implement"||t==="repair"||t==="coding")return"implementation";if(t==="land"||t==="merge")return"landing"}function ix(e){return G1(e)??"any"}var ax=p(()=>{"use strict";$c()});function J1(e=process.env){let t=E();return Rt(t,e)!=="forge"}function Kc(e,t=process.env){if(J1(t))return e?.maxConcurrentWorkers??void 0}async function Hc(e,t){let r=pe(t.baseUrl?String(t.baseUrl):void 0),n=await fe(t.secret?String(t.secret):void 0,e,{baseUrl:r}),o=`${r}/api/agent-os/by-id/${encodeURIComponent(e)}/runtime`;try{let s=await jm(o,n);if(!s.ok)return null;let a=s.response?.preferences?.maxConcurrentWorkers;if(a==null)return{maxConcurrentWorkers:null};let l=Number(a);return!Number.isFinite(l)||l<=0?{maxConcurrentWorkers:null}:{maxConcurrentWorkers:Math.floor(l)}}catch{return null}}var Jm=p(()=>{"use strict";We();H();De()});async function lx(e,t=q1){let r=await t.fetchPreferences(e.agentOsId,e.args),n=t.configuredOverride(r,e.env);return t.observe({runId:e.runId,configuredMaxWorkersOverride:n})}var q1,cx=p(()=>{"use strict";Jm();No();q1={fetchPreferences:Hc,configuredOverride:Kc,observe:gi}});function jc(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function qm(e){return e.toLowerCase()}function Y1(e){let t=jc(e,"roleLane");if(t)return t;let r=qm(jc(e,"executorRef")),n=qm(jc(e,"title")),o=qm(jc(e,"personaSlug")),s=`${r} ${n}`;if(s.includes("deep review")||s.includes("security review")||r.includes("deep-reviewer"))return"deep_reviewer";if(s.includes("plan author")||s.includes("plan-author")||n.includes("strategy plan"))return"plan_author";if(s.includes("plan review")||r.includes("plan-reviewer"))return"plan_reviewer";if(s.includes("report review")||s.includes("completion report"))return"report_reviewer";if(s.includes("repair")||n.startsWith("fix ")||r.includes("repair"))return"repair_implementer";if(r.includes("cursor")||r.includes("codex")||r.includes("composer")||n.includes("implement")||n.includes("land:"))return"implementer";let i=Gm(o);if(i)return o==="lorentz"&&(s.includes("deep")||s.includes("security"))?"deep_reviewer":i;if(s.includes("review"))return"report_reviewer"}function ux(e){let t=Y1(e);return t?{...e,roleLane:t}:e}var dx=p(()=>{"use strict";$c()});function px(e){let t=e.trim();return z1.test(t)||X1.test(t)}function fx(e){let t=e.trim().toLowerCase();return t.startsWith("gpt-")||t.startsWith("gpt5")||t.includes("codex")}function Ym(e){let t=e.trim().toLowerCase();return t.includes("composer")||t.includes("cursor")}function mx(e){return e.trim().toLowerCase().startsWith("gemini-")}function Q1(e){return fx(e)?"codex":px(e)?"claude":mx(e)?"gemini":(Ym(e),"cursor")}function Z1(e){if(!e.startsWith("provider:"))return null;let t=e.slice(9),r=t.indexOf(":"),n=(r>=0?t.slice(0,r):t).trim().toLowerCase(),o=r>=0&&t.slice(r+1).trim()||void 0;return n?n==="claude"||n==="opus"||n==="anthropic"?{provider:"claude",model:o,rule:o?"executor_ref:provider_claude_model":"executor_ref:provider_claude"}:n==="codex"?{provider:"codex",model:o,rule:"executor_ref:provider_codex"}:n==="openai-compatible"||n==="openai"||n==="openai_compatible"?{provider:"openai-compatible",model:o,rule:"executor_ref:provider_openai_compatible"}:n==="chatgpt"||n==="gpt"?{provider:"codex",model:o,rule:"executor_ref:provider_codex"}:n==="openai-api"||n==="openai_api"?{provider:"openai-compatible",model:o,rule:"executor_ref:provider_openai_compatible"}:n==="cursor"||n==="composer"?{provider:"cursor",model:o,rule:"executor_ref:provider_cursor"}:n==="gemini-api"||n==="gemini_api"||n==="google-api"?{provider:"gemini-api",model:o,rule:"executor_ref:provider_gemini_api"}:n==="gemini"||n==="google"||n==="gemini_cli"?{provider:"gemini",model:o,rule:o?"executor_ref:provider_gemini_model":"executor_ref:provider_gemini"}:null:null}function eV(e){if(!e.startsWith("harness-lane:"))return null;let t=e.split(":").map(o=>o.trim()).filter(Boolean);if(t.length<2)return null;let r=t[1],n=t.slice(2).join(":");return n?px(n)||fx(n)||Ym(n)||mx(n)?{lane:r,model:n,provider:Q1(n),rule:"executor_ref:harness_lane_model"}:{lane:r,rule:"executor_ref:harness_lane"}:{lane:r,rule:"executor_ref:harness_lane"}}function ct(e){let t=typeof e=="string"?e.trim():"";return t?Z1(t)??eV(t):null}function gx(e){let t=ct(e);return t?!!(t.provider&&t.provider!=="cursor"||t.model&&!Ym(t.model)):!1}var z1,X1,Vc=p(()=>{"use strict";z1=/^claude[-_]/i,X1=/^(?:opus|sonnet|haiku)\b/i});function Vi(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function kr(e){if(!e?.trim())return!1;let t=e.trim().toLowerCase();return tV.has(t)?!0:t.includes("claude")||t.includes("opus")}function Gc(e){if(!e)return!1;let t=e.workerProviderOverride;if(typeof t=="string"&&kr(t))return!0;let r=Vi(e,"executorRef").toLowerCase();if(r==="provider:claude"||r.startsWith("provider:claude:")||r.includes("claude-worker-override")||r.includes("operator-claude"))return!0;let n=ct(Vi(e,"executorRef"));if(n?.provider&&kr(n.provider)||n?.model&&kr(nV(n.model)))return!0;let o=Vi(e,"description");if(rV.some(i=>i.test(o)))return!0;let s=Vi(e,"title");return!!/\[use-claude-worker\]/i.test(s)}function nV(e){let t=e.trim().toLowerCase();return/^claude[-_]/.test(t)||/^(?:opus|sonnet|haiku)\b/.test(t)?"claude":t}function oV(e,t){return{provider:br,model:Jc,rule:`policy:cursor_default${t}`,requestedModel:e}}function iV(e){return sV.some(t=>e.startsWith(t))}function zm(e){if(!e)return!1;let t=e.workerProviderOverride;return typeof t=="string"&&t.trim()||ct(Vi(e,"executorRef"))?.provider?!0:Gc(e)}function hx(e){let{routing:t,task:r}=e,n=e.explicitProvider?.trim().toLowerCase();if(e.explicitProviderIsOperatorOverride&&kr(n))return{...t,provider:"claude",rule:t.rule.startsWith("explicit:")?t.rule:"explicit:operator_provider"};if(n||iV(t.rule)||zm(r)||!kr(t.provider))return t;let o=t.rule&&t.rule!=="default:global"?`:${t.rule.replace(/:/g,"_")}`:"";return oV(t.model,o)}function yx(e,t=br){let r=e?.trim();return r?Ke(r):t}var br,tV,rV,sV,In=p(()=>{"use strict";Vc();qc();Ri();Ri();br="cursor",tV=new Set(["claude","opus","anthropic"]),rV=[/\[worker-provider:\s*claude\]/i,/\[use-claude-worker\]/i,/\[operator-worker-provider:\s*claude\]/i];sV=["explicit:","executor_ref:","factory:","task:"]});function os(e){return kx[e]}function bx(){return Object.values(kx)}var kx,Xm=p(()=>{"use strict";kx={codex:{id:"codex",displayName:"Codex (BYO OAuth / Hermes openai-codex)",costTier:"low",authSources:["oauth_local","api_key_env","subscription_hermes"],supportsLowRiskOrchestration:!0,supportsPrivilegedPlatformActions:!1,workerMcpTools:"supported"},cursor:{id:"cursor",displayName:"Cursor / Composer",costTier:"medium",authSources:["oauth_local","api_key_env"],supportsLowRiskOrchestration:!0,supportsPrivilegedPlatformActions:!0,workerMcpTools:"supported"},claude:{id:"claude",displayName:"Claude Code",costTier:"high",authSources:["oauth_local"],supportsLowRiskOrchestration:!0,supportsPrivilegedPlatformActions:!0,workerMcpTools:"supported"}}});import{existsSync as wx,readFileSync as aV}from"node:fs";import On from"node:path";function cV(e){return e.includes("/")||e.includes("\\")}function uV(e){return(e.PATHEXT||lV).split(";").map(t=>t.trim().toLowerCase()).filter(t=>t.startsWith("."))}function dV(e){let t=Object.keys(e).find(r=>r.toUpperCase()==="PATH");return t?e[t]??"":""}function pV(e,t={}){let r=t.env??process.env,n=t.exists??wx,o=uV(r),s=On.win32.extname(e)!=="",i=a=>s?[a]:o.map(l=>`${a}${l}`);if(cV(e)||On.win32.isAbsolute(e))return i(e).find(a=>n(a))??null;for(let a of dV(r).split(";").map(l=>l.trim()).filter(Boolean)){let l=i(On.win32.join(a,e)).find(c=>n(c));if(l)return l}return null}function Rx(e){return e.replace(/^[\\/]+/,"")}function mV(e){let t=e.split(/\r?\n/),r=new Map;for(let s of t){let i=fV.exec(s);i&&r.set(i[1].toUpperCase(),i[2])}let n=t.filter(s=>s.includes("%*")).pop();if(!n)return null;let o=vx.exec(n);if(o)return Rx(o[1]);for(let s of n.matchAll(/%([A-Za-z_]\w*)%/g)){let i=r.get(s[1].toUpperCase()),a=i?vx.exec(i):null;if(a)return Rx(a[1])}return null}function gV(e,t={}){if((t.platform??process.platform)!=="win32")return{executable:e,prefixArgs:[],kind:"passthrough"};let n=pV(e,t);if(!n)return{executable:e,prefixArgs:[],kind:"passthrough"};let o=On.win32.extname(n).toLowerCase();if(o!==".cmd"&&o!==".bat")return{executable:n,prefixArgs:[],kind:"exe"};let s=t.readText??(f=>aV(f,"utf8")),i=t.exists??wx,a;try{a=s(n)}catch{throw new Gi(n)}let l=mV(a);if(!l)throw new Gi(n);let c=On.win32.dirname(n),u=On.win32.join(c,l);if(!i(u))throw new Gi(n);let d=On.win32.join(c,"node.exe");return{executable:i(d)?d:t.nodeExecutable??process.execPath,prefixArgs:[u],kind:"node-shim"}}function se(e,t,r={}){let n=gV(e,r);return[n.executable,[...n.prefixArgs,...t]]}var Gi,lV,vx,fV,Ge=p(()=>{"use strict";Gi=class extends Error{constructor(r){super(`${r} is a batch file that is not a Node CLI shim; it cannot be spawned without a shell. Point the matching KYNVER_*_BIN setting at the real .exe or the CLI's JS entry, or run the daemon inside WSL.`);this.shimPath=r;this.name="UnresolvableWindowsShimError"}shimPath},lV=".COM;.EXE;.BAT;.CMD";vx=/%~?dp0%?\\?([^"%\r\n]+?\.(?:c|m)?js)\b/i,fV=/^\s*SET\s+"?([A-Za-z_]\w*)=([^"\r\n]*)"?\s*$/i});import{createHash as Sx}from"node:crypto";import{statSync as hV}from"node:fs";import{spawnSync as _x}from"node:child_process";function Bt(e){try{let t=hV(e),r=`${e}|${t.size}|${t.mtimeMs}`;return Sx("sha256").update(r).digest("hex").slice(0,16)}catch{return}}function ss(e){return Sx("sha256").update(`env:${e}`).digest("hex").slice(0,16)}function ut(e,t){for(let r of t){let n=process.env[r]?.trim();if(n)return n}return e}function At(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=se(e,t),i=_x(o,s,{windowsHide:!0,encoding:"utf8",timeout:n,env:{...process.env,...r.env,CI:"1",NO_COLOR:"1"}});if(i.status===0)return{ok:!0,note:r.okNote??`${e} ${t.join(" ")}: ok`};let a=(i.stderr||i.stdout||"").trim(),l=r.failPrefix??`${e} ${t.join(" ")} failed`;return{ok:!1,note:a?`${l}: ${a.slice(0,200)}`:l}}catch(o){return{ok:!1,note:o instanceof Error?o.message:`${e} probe failed`}}}function Yc(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=se(e,t);return _x(o,s,{windowsHide:!0,stdio:"ignore",timeout:n,env:{...process.env,CI:"1",NO_COLOR:"1"}}).status===0?{ok:!0,note:r.okNote??`${e} authenticated`}:{ok:!1,note:r.failNote??`${e} not authenticated`}}catch(o){return{ok:!1,note:o instanceof Error?o.message:`${e} auth probe failed`}}}var Tn=p(()=>{"use strict";Ge()});import{existsSync as yV}from"node:fs";import{homedir as kV}from"node:os";import Ji from"node:path";function vV(){let e=kV();return[process.env.CODEX_HOME?.trim()?Ji.join(Ji.resolve(process.env.CODEX_HOME.trim()),"auth.json"):null,Ji.join(e,".codex","auth.json"),Ji.join(e,".config","codex","auth.json")].filter(r=>!!r)}function RV(e){return Ji.dirname(e)}function wV(e){let t,r;for(let n of vV()){if(!yV(n))continue;t??=n;let o=At(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status",env:{CODEX_HOME:RV(n)}});if(r??=o,o.ok)return{authPath:n,login:o}}return{authPath:t,login:r??At(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status"})}}function xx(e=new Date().toISOString()){let t=ut(bV,["KYNVER_CODEX_BIN","CODEX_BIN"]);if(process.env.CODEX_API_KEY?.trim())return{providerId:"codex",ready:!0,authSource:"api_key_env",sessionFingerprint:ss("CODEX_API_KEY"),checkedAt:e,note:"CODEX_API_KEY present (env binding \u2014 cloud credits path, no token stored in Kynver)"};let{authPath:r,login:n}=wV(t),o=!!r&&n.ok;return{providerId:"codex",ready:o,authSource:"oauth_local",sessionFingerprint:r?Bt(r):void 0,checkedAt:e,note:o?"Local Codex OAuth session bound on runner":[n.note,r?void 0:"no Codex auth store found"].filter(Boolean).join("; ")}}var bV,Cx=p(()=>{"use strict";Tn();bV="codex"});import{existsSync as SV}from"node:fs";import{homedir as _V}from"node:os";import Qm from"node:path";function xV(){let e=process.env.HERMES_HOME?.trim(),t=e?Qm.resolve(e):Qm.join(_V(),".hermes");return Qm.join(t,"auth.json")}function zc(e=new Date().toISOString()){let t=ut("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=At(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=xV(),o=SV(n),s=Yc(t,["auth","status","openai-codex"],{okNote:"hermes openai-codex: logged in",failNote:"hermes openai-codex: not logged in"}),i=r.ok&&s.ok;return{path:"hermes_openai_codex",ready:i,authSource:i?"subscription_hermes":"none",sessionFingerprint:o?Bt(n):void 0,checkedAt:e,note:i?"Hermes openai-codex subscription session bound (ChatGPT Codex OAuth)":[r.note,s.note,o?void 0:"no ~/.hermes/auth.json"].filter(Boolean).join("; ")}}var Zm=p(()=>{"use strict";Tn()});function is(e=new Date().toISOString()){let t=xx(e);if(t.ready)return{...t,path:"codex_cli"};let r=zc(e);return r.ready?{providerId:"codex",ready:!0,authSource:r.authSource,sessionFingerprint:r.sessionFingerprint,checkedAt:r.checkedAt,note:r.note,path:"hermes_openai_codex",hermesOpenAiCodex:r}:{providerId:"codex",ready:!1,authSource:"none",checkedAt:e,path:"none",hermesOpenAiCodex:r,note:[t.note,r.note].filter(Boolean).join("; ")||"Codex CLI and Hermes openai-codex unavailable"}}var Xc=p(()=>{"use strict";Cx();Zm()});function Px(e,t){let r=os(e);return t==="privileged"?r.supportsPrivilegedPlatformActions:t==="low"?r.supportsLowRiskOrchestration:!0}function CV(e,t){let r=os(e.providerId),n=os(t.providerId),o=Ex.indexOf(r.costTier)-Ex.indexOf(n.costTier);if(o!==0)return o;let s=Ax[e.binding.authSource]-Ax[t.binding.authSource];return s!==0?s:e.providerId.localeCompare(t.providerId)}function eg(e){let t=bx().map(a=>({providerId:a.id,binding:e.inventory.bindings[a.id]})).filter(a=>a.binding.ready&&Px(a.providerId,e.riskClass));if(t.length===0)return null;let n=[...t].sort(CV)[0],o="codex";if(n.providerId===o)return{providerId:n.providerId,binding:n.binding};let s=e.inventory.bindings[o],i;return Px(o,e.riskClass)?s.ready||(i=s.note??`${o} not bound`):i=`${e.riskClass} orchestration requires privileged-capable provider`,{providerId:n.providerId,binding:n.binding,escalatedFrom:o,escalatedReason:i}}var Ex,Ax,Ix=p(()=>{"use strict";Xm();Ex=["low","medium","high"],Ax={oauth_local:0,subscription_hermes:0,runner_token:1,api_key_env:2,none:3}});import{existsSync as EV}from"node:fs";import{homedir as AV}from"node:os";import PV from"node:path";function OV(){let e=AV();return[PV.join(e,".claude",".credentials.json")]}function Ox(e=new Date().toISOString()){let t=ut(IV,["KYNVER_CLAUDE_BIN","CLAUDE_BIN"]);if(process.env.ANTHROPIC_API_KEY?.trim())return{providerId:"claude",ready:!1,authSource:"api_key_env",sessionFingerprint:ss("ANTHROPIC_API_KEY"),checkedAt:e,note:"ANTHROPIC_API_KEY present but scrubbed from worker env (deployment secret) \u2014 use `claude` CLI login (OAuth) for harness workers"};let r=At(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=OV().find(i=>EV(i)),o=Yc(t,["auth","status"],{okNote:"claude auth status: authenticated",failNote:"claude auth status: not authenticated"}),s=r.ok&&(o.ok||!!n);return{providerId:"claude",ready:s,authSource:"oauth_local",sessionFingerprint:n?Bt(n):void 0,checkedAt:e,note:s?"Local Claude Code OAuth session bound on runner":[r.note,o.note,n?void 0:"no ~/.claude/.credentials.json"].filter(Boolean).join("; ")}}var IV,Tx=p(()=>{"use strict";Tn();IV="claude"});function dt(e,t={}){let r=ti(e);if(!t.reviewWorker)return r;let n={...r,[TV]:"1"};for(let o of NV)delete n[o];return n}var TV,NV,Nn=p(()=>{"use strict";ri();TV="KYNVER_NO_PROD_DB_CREDENTIALS",NV=["KYNVER_ENV_FILE"]});function Nx(e){return e.replace(DV,"")}function Qc(e){return/^claude[-_]/i.test(e)||/^(?:opus|sonnet|haiku)\b/i.test(e)}function MV(e){let t=e.trim().toLowerCase();return t.startsWith("gemini-")||t==="auto"||t==="pro"||t==="flash"||t==="flash-lite"}function BV(e){let t=e.trim().toLowerCase();return LV.has(t)?"auto":null}function tg(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=Nx(r).trim()||t;return Dx.test(o)||!Qc(o)&&o!==t?{ok:!1,model:r,normalized:!1,requested:r,note:`model "${r}" is not a Claude model \u2014 the "claude" provider drives the Claude CLI, which only accepts claude-* model ids (got "${o}"). Pick a Claude model or switch the worker provider.`}:o!==r?{ok:!0,model:o,normalized:!0,requested:r,note:`normalized model "${r}" \u2192 "${o}" (the Claude CLI rejects reasoning-effort suffixes)`}:{ok:!0,model:o,normalized:!1}}function as(e,t){let r=(e??"").trim();return r?Qc(r)?{ok:!1,model:r,normalized:!1,requested:r,note:`model "${r}" is a Claude model but the worker provider is "codex". Switch the provider or pick a Codex/OpenAI model.`}:{ok:!0,model:r,normalized:!1}:{ok:!0,model:t,normalized:!1}}function rg(e,t){let r=(e??"").trim();if(r)return{ok:!0,model:r,normalized:!1};let n=(t??"").trim();return n?{ok:!0,model:n,normalized:!1}:{ok:!1,model:"",normalized:!1,note:'the "openai-compatible" provider has no universal default model \u2014 pass --model (any id your endpoint serves, e.g. llama3.1, qwen2.5-coder, gpt-4o-mini) or set KYNVER_WORKER_MODEL on the daemon host.'}}function ls(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=Nx(r).trim()||t;return Qc(o)||!MV(o)&&Dx.test(o)?{ok:!1,model:r,normalized:!1,requested:r,note:`model "${r}" is not a Gemini model \u2014 the gemini / gemini-api providers drive Google Gemini (got "${o}"). Pick a gemini-* model or an alias (auto, pro, flash, flash-lite), or switch the worker provider.`}:o!==r?{ok:!0,model:o,normalized:!0,requested:r,note:`normalized model "${r}" \u2192 "${o}"`}:{ok:!0,model:o,normalized:!1}}function cs(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let n=BV(r);return n?{ok:!0,model:n,normalized:!0,requested:r,note:`normalized model "${r}" \u2192 "${n}" (Cursor provider alias \u2014 use "auto" or a composer id, not "cursor")`}:Qc(r)?{ok:!1,model:r,normalized:!1,requested:r,note:`model "${r}" is a Claude model but the worker provider is "cursor". Switch the provider to "claude" or pick a Cursor model.`}:{ok:!0,model:r,normalized:!1}}var DV,Dx,LV,Wt=p(()=>{"use strict";DV=/-(?:thinking(?:-(?:high|medium|low|minimal|max|none))?|high|medium|low|minimal)$/i;Dx=/^(?:gpt-|gpt5|o1|o3|o4|gemini-|grok-|composer|deepseek|llama|mistral|qwen|command-)/i;LV=new Set(["cursor"])});import{existsSync as qi,readdirSync as WV}from"node:fs";import Dn from"node:path";function FV(e){let r=e.split("-")[0].split(".");if(r.length!==3)return null;let[n,o,s]=r;return!n||!o||!s?null:+`${n}${o.padStart(2,"0")}${s.padStart(2,"0")}`}function $V(e){let t=Dn.join(e,"versions");if(!qi(t))return null;let r=null,n=-1;for(let o of WV(t,{withFileTypes:!0})){if(!o.isDirectory()||!UV.test(o.name))continue;let s=FV(o.name);s==null||s<=n||(n=s,r=Dn.join(t,o.name))}return r}function Zc(e){let t=e?.trim()||Dn.join(process.env.LOCALAPPDATA||"","cursor-agent"),r=Dn.join(t,"node.exe"),n=Dn.join(t,"index.js");if(qi(r)&&qi(n))return{nodeExe:r,indexJs:n,versionDir:t};let o=$V(t);if(!o)return null;let s=Dn.join(o,"node.exe"),i=Dn.join(o,"index.js");return!qi(s)||!qi(i)?null:{nodeExe:s,indexJs:i,versionDir:o}}var UV,Mx=p(()=>{"use strict";UV=/^\d{4}\.\d{1,2}\.\d{1,2}-[a-f0-9]+$/i});import{closeSync as og,existsSync as Bx,mkdirSync as KV,openSync as sg,statSync as HV,unlinkSync as Lx}from"node:fs";import{spawn as jV}from"node:child_process";import VV from"node:os";import Ut from"node:path";function YV(e,t,r){return{executable:e,prefixArgs:[t],shell:!1,detached:be(),bundledVersionDir:r}}function Yi(e){if(process.platform==="win32"){let t=/\.(cmd|bat)$/i.test(e),r=/node\.exe$/i.test(e)&&Bx(Ut.join(Ut.dirname(e),"index.js"));if(t||r||e==="agent"){let o=t?Zc(Ut.dirname(e)):r?{nodeExe:e,indexJs:Ut.join(Ut.dirname(e),"index.js"),versionDir:Ut.dirname(e)}:Zc();if(o)return YV(o.nodeExe,o.indexJs,o.versionDir);throw new Error("Cursor Agent on Windows has no headless bundled node.exe under %LOCALAPPDATA%\\cursor-agent\\versions\\\u2026. Run `agent login` / update Cursor Agent CLI, use `--provider claude`, or set KYNVER_CURSOR_AGENT_ROOT to the cursor-agent folder.")}}return{executable:e,prefixArgs:[],shell:!1,detached:be()}}function zV(e,t,r){return dt({...process.env,CI:"1",NO_COLOR:"1",...t.bundledVersionDir?{CURSOR_INVOKED_AS:Ut.basename(e)||"agent.cmd"}:{}},{reviewWorker:r})}function Wx(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function ig(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function XV(){let e=process.env.KYNVER_CURSOR_START_LOCK_DIR?.trim()||Ut.join(VV.homedir(),".kynver","locks");return KV(e,{recursive:!0}),Ut.join(e,"cursor-agent-start.lock")}function QV(){if(process.env.KYNVER_CURSOR_START_LOCK==="0")return()=>{};let e=XV(),t=ig("KYNVER_CURSOR_START_LOCK_TIMEOUT_MS",JV),r=ig("KYNVER_CURSOR_START_LOCK_STALE_MS",qV),n=Date.now();for(;;)try{let o=sg(e,"wx");return og(o),()=>{try{Lx(e)}catch{}}}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-HV(e).mtimeMs>r){Lx(e);continue}}catch{continue}if(Date.now()-n>t)throw new Error(`timed out waiting for Cursor agent start lock: ${e}`);Wx(250)}}function Mn(e=process.env){let t=e.KYNVER_CURSOR_AGENT_BIN?.trim()||e.CURSOR_AGENT_BIN?.trim();if(t)return t;if(process.platform==="win32"){let r=Zc(e.KYNVER_CURSOR_AGENT_ROOT?.trim()||void 0);if(r)return r.nodeExe;let n=Ut.join(e.LOCALAPPDATA||"","cursor-agent","agent.cmd");if(Bx(n))return n}return"agent"}function ZV(){return Mn(process.env)}function eG(e,t,r=[]){return[...r,"-p",...e.executionMode==="read_only"?["--mode","plan"]:["--force"],...e.mcpConfigPath?["--approve-mcps"]:[],"--trust","--workspace",e.worktreePath,"--output-format","stream-json","--stream-partial-output","--model",t,e.prompt]}var ng,GV,JV,qV,Ux,us=p(()=>{"use strict";D();Nn();Wt();Mx();ng="composer-2.5",GV=15e3,JV=6e4,qV=3e4;Ux={name:"cursor",defaultModel:ng,preflightModel(e){return cs(e,ng)},start(e){let t=cs(e.model,ng);if(!t.ok)throw new Error(`cursor provider model preflight failed: ${t.note}`);let r=t.model,n=sg(e.stdoutPath,"a"),o=sg(e.stderrPath,"a"),s=["ignore",n,o],i=ZV(),a=Yi(i),l=QV(),c;try{c=jV(a.executable,eG(e,r,a.prefixArgs),X({cwd:e.worktreePath,detached:a.detached,shell:a.shell,stdio:s,env:zV(i,a,e.reviewWorker)})),Wx(ig("KYNVER_CURSOR_START_LOCK_HOLD_MS",GV))}finally{l(),og(n),og(o)}if(!c.pid)throw new Error(`failed to spawn Cursor agent worker (is \`${i}\` on PATH? run \`agent login\` or set CURSOR_API_KEY)`);return c.unref(),{pid:c.pid,model:r}}}});import{spawnSync as tG}from"node:child_process";function eu(e,t=process.env){try{let r;try{r=Yi(e)}catch{r={executable:e,prefixArgs:[]}}let n=tG(r.executable,[...r.prefixArgs,"status","--format","json"],{encoding:"utf8",windowsHide:!0,timeout:8e3,env:{...t,CI:"1",NO_COLOR:"1"}});if(n.status!==0)return{ok:!1,note:"agent status: not authenticated"};let o=(n.stdout||"").trim();if(!o)return{ok:!1,note:"agent status: empty response"};let s;try{s=JSON.parse(o)}catch{return{ok:!1,note:"agent status: unparseable response"}}return typeof s=="object"&&s!==null&&s.isAuthenticated===!0?{ok:!0,note:"agent status: authenticated"}:{ok:!1,note:"agent status: not authenticated"}}catch(r){return{ok:!1,note:r instanceof Error?r.message:"agent status probe failed"}}}var ag=p(()=>{"use strict";ds();us()});import{existsSync as Fx}from"node:fs";import{homedir as rG}from"node:os";import Ln from"node:path";import{spawnSync as nG}from"node:child_process";function oG(e){if(Ln.isAbsolute(e)||e.includes("/")||e.includes("\\"))return Fx(e);try{let t=nG(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function tu(e=process.env){let t=[],r=e.KYNVER_CURSOR_AUTH_HOME?.trim();r&&(t.push(Ln.join(r,".config","cursor","auth.json")),t.push(Ln.join(r,".cursor-agent","auth.json")));let n=rG();if(t.push(Ln.join(n,".config","cursor","auth.json")),t.push(Ln.join(n,".cursor-agent","auth.json")),process.platform==="win32"){let o=e.LOCALAPPDATA?.trim(),s=e.APPDATA?.trim();o&&t.push(Ln.join(o,"cursor-agent","auth.json")),s&&t.push(Ln.join(s,"cursor","auth.json"))}return t}function $x(e){return`${e.error}: ${e.detail}`}function nu(e=process.env){let t=Mn(e);return oG(t)?e.CURSOR_API_KEY?.trim()?{ok:!0,creds:{agentBin:t,authSource:"api_key_env"}}:tu(e).find(n=>Fx(n))?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:eu(t,e).ok?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:{ok:!1,error:lg,detail:"Run `agent login` on this computer, or set CURSOR_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:ru,detail:"`agent` CLI not found. Install the Cursor Agent CLI (https://cursor.com/docs/cli/headless) and keep it on PATH."}}var ru,lg,ds=p(()=>{"use strict";us();ag();ru="cursor_cli_unavailable",lg="cursor_not_logged_in"});import{existsSync as sG}from"node:fs";function Kx(e=new Date().toISOString()){let t=ut(iG,["KYNVER_CURSOR_AGENT_BIN","CURSOR_AGENT_BIN"]);if(process.env.CURSOR_API_KEY?.trim())return{providerId:"cursor",ready:!1,authSource:"api_key_env",sessionFingerprint:ss("CURSOR_API_KEY"),checkedAt:e,note:"CURSOR_API_KEY present but scrubbed from worker env (deployment secret) \u2014 use `agent login` (OAuth) for harness workers"};let r=At(t,["-v"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=tu().find(a=>sG(a)),o=eu(t),s=!!n||o.ok,i=r.ok&&s;return{providerId:"cursor",ready:i,authSource:"oauth_local",sessionFingerprint:n?Bt(n):void 0,checkedAt:e,note:i?"Local Cursor/Composer OAuth session bound on runner":[r.note,s?void 0:o.note??"no ~/.config/cursor/auth.json or `agent login` session"].filter(Boolean).join("; ")}}var iG,Hx=p(()=>{"use strict";ds();ag();Tn();iG="agent"});import{existsSync as aG,readFileSync as lG}from"node:fs";import{homedir as cG}from"node:os";import cg from"node:path";function dG(){let e=process.env.HERMES_HOME?.trim(),t=e?cg.resolve(e):cg.join(cG(),".hermes");return cg.join(t,".env")}function pG(e){try{let t=lG(e,"utf8"),r=[];for(let n of uG)new RegExp(`^${n}=`,"m").test(t)&&r.push(n);return r}catch{return[]}}function jx(e=new Date().toISOString()){let t=ut("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=At(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=dG(),o=aG(n),s=o?pG(n):[],a=s.some(c=>c.endsWith("_API_KEY"))?"api_key_env":o?"oauth_local":"none",l=r.ok&&o;return{adapterId:"hermes",cliAvailable:r.ok,profileBound:o,authSource:a,sessionFingerprint:o?Bt(n):void 0,checkedAt:e,note:l?`Hermes profile bound (${s.length?`keys: ${s.join(", ")}`:"no API keys detected"})`:[r.note,o?void 0:"no ~/.hermes/.env"].filter(Boolean).join("; ")}}var uG,Vx=p(()=>{"use strict";Tn();uG=["OPENAI_API_KEY","ANTHROPIC_API_KEY","KYNVER_API_KEY","KYNVER_BASE_URL"]});function Gx(e={}){let t=e.nowIso?.()??new Date().toISOString(),r=is(t),n={codex:r,cursor:Kx(t),claude:Ox(t)},o=Object.values(n).filter(s=>s.ready).length;return{generatedAt:t,bindings:n,cloudApiCredits:{anthropicApiKey:!!process.env.ANTHROPIC_API_KEY?.trim(),openaiApiKey:!!process.env.OPENAI_API_KEY?.trim(),codexApiKey:!!process.env.CODEX_API_KEY?.trim()},workerEndpoint:{baseUrlConfigured:!!process.env.KYNVER_WORKER_BASE_URL?.trim(),apiKeyConfigured:!!process.env.KYNVER_WORKER_API_KEY?.trim()},hermes:jx(t),hermesOpenAiCodex:zc(t),codexAdapterPath:r.path,readyCount:o}}var Jx=p(()=>{"use strict";Tx();Xc();Hx();Vx();Zm()});function ug(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function gG(e){let t=ug(e,"executorRef").toLowerCase(),r=ug(e,"title").toLowerCase(),n=ug(e,"description").toLowerCase(),o=`${t}
|
|
141
|
+
WHERE scope = ? ORDER BY seq DESC LIMIT 1`).get(t);return r?{scope:r.scope,seq:r.seq,payloadJson:r.payload_json,createdAt:r.created_at}:null}localSchemaVersion(){return 1}checkpointTruncate(){this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)")}integrityCheck(){return this.db.prepare("PRAGMA integrity_check").get()?.integrity_check==="ok"}pragma(t){let r=this.db.prepare(`PRAGMA ${t}`).get();return String(Object.values(r)[0])}close(){this.db.close()}}});import{existsSync as H1,renameSync as j1}from"node:fs";function V1(e,t){let r=`${e}.quarantine-${t}`;for(let n of["","-wal","-shm"]){let o=`${e}${n}`;H1(o)&&j1(o,`${r}${n}`)}return r}function O_(e){let t=e.quarantineStamp??(e.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),r=null;try{let s=ji.open(e);if(s.integrityCheck())return{store:s,recovered:!1,quarantinedTo:null};s.close()}catch(s){if(s.name==="SchemaDowngradeRefusedError"||s.name==="FilesystemPolicyError")throw s;r=s}let n=`${e.directory}/${e.filename??"local-run-store.sqlite"}`,o=V1(n,t);try{return{store:ji.open(e),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([r,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}var T_=p(()=>{"use strict";I_()});function G1(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function J1(){return q1.classifyOptions??G1()}function z1(e){Yc+=1;try{let t=J1(),r=O_({directory:e,...t?{classifyOptions:t}:{}});return{store:r.store,status:{state:"open",harnessRoot:e,databasePath:r.store.databasePath,schemaVersion:r.store.localSchemaVersion(),recovered:r.recovered,quarantinedTo:r.quarantinedTo,reason:null,openAttempts:Yc},failedAtMs:null,permanentRefusal:!1}}catch(t){return{store:null,status:{state:"unavailable",harnessRoot:e,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${t.name}: ${t.message}`,openAttempts:Yc},failedAtMs:Date.now(),permanentRefusal:t.name==="FilesystemPolicyError"||t.name==="SchemaDowngradeRefusedError"}}}function X1(e,t){return e.store||e.permanentRefusal?!1:e.failedAtMs===null?!0:t-e.failedAtMs>=Y1}function ue(e=Date.now()){let t=dt();return(!kr||kr.status.harnessRoot!==t||X1(kr,e))&&(Z1(),kr=z1(t)),kr.store}function Q1(){return kr?kr.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:Yc}}function N_(){return ue(),Q1()}function Z1(){try{kr?.store?.close()}catch{}kr=null}var q1,Y1,kr,Yc,Jr=p(()=>{"use strict";Et();T_();q1={},Y1=300*1e3,kr=null,Yc=0});import{existsSync as eV,readFileSync as tV}from"node:fs";import{homedir as rV}from"node:os";import nV from"node:path";function D_(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return nV.join(rV(),".kynver",`local-run-store-flags-${t}.json`)}function Ym(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,r={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=t[o];(s==="off"||s==="shadow"||s==="enforce")&&(r[o]=s)}return r}function M_(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.response;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.localRunStoreFlags;return r===void 0?null:Ym(r)}function L_(e,t){try{let r=D_(e),n={contractVersion:1,agentOsId:e,flags:Ym(t),deliveredAt:new Date().toISOString()};be(r,n),Ot={flags:n.flags,loadedAtMs:Date.now(),file:r}}catch{}}function B_(e=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(Ot&&e-Ot.loadedAtMs<oV)return Ot.flags;try{let t=P().agentOsId?.trim();if(!t)return Ot={flags:{},loadedAtMs:e,file:null},Ot.flags;let r=D_(t);if(!eV(r))return Ot={flags:{},loadedAtMs:e,file:r},Ot.flags;let n=JSON.parse(tV(r,"utf8")),o=n?.contractVersion===1?Ym(n.flags):{};return Ot={flags:o,loadedAtMs:e,file:r},o}catch{return Ot={flags:{},loadedAtMs:e,file:null},Ot.flags}}var oV,Ot,zm=p(()=>{"use strict";$();M();oV=3e4,Ot=null});function iV(e){let t=e?.trim().toLowerCase()??"";return t===""?{mode:"off",unknown:!1}:t==="off"||t==="shadow"||t==="enforce"?{mode:t,unknown:!1}:{mode:"off",unknown:!0}}function br(e=process.env){let t={},r={},n=[],o=B_();for(let s of sV){let i=e[s.env];if(typeof i=="string"&&i.trim()!==""){let c=iV(i);t[s.key]=c.mode,r[s.key]="env",c.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let l=o[s.key];if(l){t[s.key]=l,r[s.key]="server";continue}t[s.key]="off",r[s.key]="default"}return{flags:t,sources:r,warnings:n}}var sV,ls=p(()=>{"use strict";zm();sV=[{key:"dispatchReceipts",env:"KYNVER_LRS_DISPATCH_RECEIPTS",milestone:"D1"},{key:"admission",env:"KYNVER_LRS_ADMISSION",milestone:"D2"},{key:"planOutbox",env:"KYNVER_LRS_PLAN_OUTBOX",milestone:"D3"},{key:"keeper",env:"KYNVER_LRS_KEEPER",milestone:"D4"},{key:"meshLease",env:"KYNVER_LRS_MESH_LEASE",milestone:"D4"},{key:"quota",env:"KYNVER_LRS_QUOTA",milestone:"D4"}]});function Vi(e){return br(process.env).flags[e]}function Xm(e){return`mesh-cron-lease:${e}`}function W_(e,t){if(Vi("meshLease")==="off")return;let r=ue();if(r)try{let n=r.latestRecoveryCheckpoint(Xm(e));if(n){let o=JSON.parse(n.payloadJson);if((o.leaseToken??null)===(t.leaseToken??null)&&(o.holderBoxId??null)===(t.holderBoxId??null)&&o.authorized===t.authorized)return}r.saveRecoveryCheckpoint({scope:Xm(e),payloadJson:JSON.stringify(t)})}catch{Je.meshStoreFailures+=1}}function U_(e,t){let r=Vi("meshLease");if(r==="off")return null;let n=ue();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(Xm(e)),s=o?JSON.parse(o.payloadJson):null,i=s!==null&&((s.leaseToken??null)!==(t?.leaseToken??null)||(s.holderBoxId??null)!==(t?.holderBoxId??null)||(s.authorized??null)!==(t?.authorized??null));return i&&(Je.meshLeaseDivergences+=1),r!=="enforce"?null:i&&t?.updatedAt&&s?.updatedAt&&Date.parse(t.updatedAt)>Date.parse(s.updatedAt)?(Je.meshEnforceStaleInversions+=1,null):s}catch{return Je.meshStoreFailures+=1,null}}function zc(e){return`quota-cooldown:${e}`}function K_(e,t){if(Vi("quota")==="off")return;let r=ue();if(r)try{r.tryReserveAdmission(zc(e),F_,t)}catch{Je.quotaStoreFailures+=1}}function $_(e){if(Vi("quota")==="off")return;let t=ue();if(t)try{t.releaseAdmission(zc(e),F_)}catch{Je.quotaStoreFailures+=1}}function H_(e,t){let r=Vi("quota");if(r==="off")return null;let n=ue();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:zc(e),limit:50}).find(i=>i.key===zc(e)),s=!!o;return s!==t&&(Je.quotaVerdictDivergences+=1),r==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return Je.quotaStoreFailures+=1,null}}function j_(){return{"keeper.storeFailures":Je.keeperStoreFailures,"meshLease.storeFailures":Je.meshStoreFailures,"meshLease.divergences":Je.meshLeaseDivergences,"meshLease.enforceStaleInversions":Je.meshEnforceStaleInversions,"quota.storeFailures":Je.quotaStoreFailures,"quota.verdictDivergences":Je.quotaVerdictDivergences}}var Je,qde,F_,Gi=p(()=>{"use strict";Jr();ls();Je={keeperStoreFailures:0,meshStoreFailures:0,quotaStoreFailures:0,meshLeaseDivergences:0,meshEnforceStaleInversions:0,quotaVerdictDivergences:0};qde=1800*1e3;F_="quota-preflight"});function Qm(e){let t=e==="--run"?"no harness run id was passed and none could be resolved":"no AgentOS workspace id was passed and none is configured",r=e==="--run"?"`kynver start` creates or reuses a run automatically and passes it to the daemon":"the daemon reads agentOsId from ~/.kynver/config.json when the flag is omitted";return[`missing ${e}: ${t}.`,`Config file: ~/.kynver/config.json (${r}).`,`Fix: run \`kynver start\` (or \`kynver bootstrap\` first on a fresh machine) to set this up automatically, or pass ${e} explicitly.`,"Diagnose: run `kynver doctor runner-install`."].join(`
|
|
142
|
+
`)}var ppe,fpe,mpe,gpe,Zm=p(()=>{"use strict";$r();b_();$();Vm();M();Oc();Jm();Gi();ppe=15*6e4,fpe=2*6e4,mpe=5*6e4,gpe=30*6e4});import aV from"node:path";function lV(e){return aV.resolve(Me(e.trim()))}function cs(e,t,r){let n=e?.trim();return n?{repo:lV(n),source:t,persistedInConfig:r}:null}function V_(e){return e?{repo:e.repo,source:e.source,persistedInConfig:!1}:null}function Ji(e={}){let t=e.env??process.env,r=e.config??P(),n=cs(r.defaultRepo,"config",!0);if(n)return n;let o=cs(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(o)return o;let s=cs(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return s||V_(Ul({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl}))}function G_(e={}){let t=e.env??process.env,r=e.config??P(),n=cs(r.defaultRepo,"config",!0);if(n)return n;let o=cs(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(o)return o;let s=cs(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return s||V_(Fl({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl,home:e.home}))}function J_(e,t){let r={...t??P(),defaultRepo:Me(e),...Zv(e)&&!t?.defaultBase?.trim()?{defaultBase:"main"}:{}};return We(r),r}function eg(e){return{defaultRepo:He(e.repo),source:e.source,persistedInConfig:e.persistedInConfig}}var us=p(()=>{"use strict";$();mi();at();bf()});import cV from"node:path";import{homedir as uV}from"node:os";function q_(e){let t=P(),r=G_({...e,config:t});if(!r)return{ok:!1,remediated:!1,alreadyPersisted:!1,configPath:He(tg),resolved:null,reason:"No git checkout found. Run this command from inside the repo you want the daemon to work on, or pass `kynver setup --repo /path/to/repo` (or export KYNVER_DEFAULT_REPO). On a fresh BYOC machine, `kynver start` creates ~/.kynver/workspace automatically.",remediation:"Run `kynver start` (creates ~/.kynver/workspace), or `kynver config ensure-default-repo` from a checkout (or `kynver setup --repo /path/to/repo`)."};if(r.persistedInConfig)return{ok:!0,remediated:!1,alreadyPersisted:!0,configPath:He(tg),resolved:eg(r),config:am(t)};let n=J_(r.repo,t),o=eg({...r,persistedInConfig:!0,source:"config"});return{ok:!0,remediated:!0,alreadyPersisted:!1,configPath:He(tg),resolved:o,config:am(n),remediation:"defaultRepo persisted in ~/.kynver/config.json \u2014 `kynver run create` no longer requires --repo."}}var tg,Y_=p(()=>{"use strict";at();$();us();tg=cV.join(uV(),".kynver","config.json")});import{mkdirSync as dV,readFileSync as pV,renameSync as fV,writeFileSync as mV}from"node:fs";import{homedir as gV}from"node:os";import z_ from"node:path";function X_(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return z_.join(gV(),".kynver",`instruction-bundle-${t}.json`)}function Q_(e,t){try{let r=X_(e);dV(z_.dirname(r),{recursive:!0});let n=`${r}.tmp-${process.pid}`;mV(n,JSON.stringify(t),{encoding:"utf8",mode:384}),fV(n,r)}catch{}}function Z_(e){try{let t=pV(X_(e),"utf8"),r=JSON.parse(t);return Mi(r)?r:null}catch{return null}}var ex=p(()=>{"use strict";Hr()});function tx(e,t=process.env){let r=es(t.KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY);if(r&&fS(r)===e)return r;if(e===hV&&!Tc(t))return null;let n=yV[e];return n?es(n):null}var hV,yV,rx=p(()=>{"use strict";Hr();hV="ib-3bab6314f0ba",yV={"ib-3bab6314f0ba":"53a2040646cd479e1f5f1aea9abf7848ce8b62e32001efb8044dfd90e8ab87ed","ib-26e6c695da06":"bb1700f25b2ee7d7cdcdb9f446f0f44ef2cc22a3096bc161232fb658e7cdaf38","ib-49e76cb8052c":"8fc646b5c4f8f402120477452608398f035c3cddd2e7aa8bb328e97b84dcf6d8"}});import{createPublicKey as kV,verify as bV}from"node:crypto";function RV(e){return kV({key:Buffer.concat([vV,Buffer.from(e)]),format:"der",type:"spki"})}function wV(e,t){if(!Mi(e))return{ok:!1,reason:"malformed signed bundle payload"};let r;try{r=Buffer.from(e.signature,"base64url")}catch{return{ok:!1,reason:"signature is not base64url"}}if(r.length!==64)return{ok:!1,reason:"signature is not a 64-byte Ed25519 signature"};try{let n=Buffer.from(nt(e.bundle),"utf8");return bV(null,n,RV(t),r)?{ok:!0,bundle:e.bundle}:{ok:!1,reason:"Ed25519 signature mismatch"}}catch(n){return{ok:!1,reason:`signature verification failed: ${n.message}`}}}function nx(e,t=process.env){if(!Mi(e))return{ok:!1,reason:"malformed signed bundle payload"};let r=tx(e.publicKeyId,t);return r?wV(e,r):{ok:!1,reason:`no verification key for publicKeyId "${e.publicKeyId}" (not pinned; set KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY)`}}var vV,ox=p(()=>{"use strict";rx();Hr();vV=Buffer.from("302a300506032b6570032100","hex")});function Yi(e,t){console.error(JSON.stringify({event:e,...t}))}function sx(e,t,r){let n=nx(e);return n.ok?(g_(n.bundle,t),t==="server"&&Q_(r,e),!0):(Yi("instruction_bundle_signature_invalid",{agentOsId:r,source:t,publicKeyId:e.publicKeyId,reason:n.reason}),!1)}function qi(e){if(vr.diskCacheTried)return!1;vr.diskCacheTried=!0;let t=Z_(e);return t?sx(t,"disk",e):!1}async function ix(e){let t=e.nowMs??Date.now(),r=()=>({source:Ft(),version:Mn(),updated:!1});if(!e.force&&t-vr.lastAttemptAtMs<SV)return r();vr.lastAttemptAtMs=t;let n=e.baseUrl?.trim().replace(/\/$/,""),o=e.secret?.trim();if(!n||!o)return Ft()==="embedded"&&qi(e.agentOsId)?{...r(),updated:!0}:r();let s=e.fetchImpl??fetch,i=new AbortController,a=setTimeout(()=>i.abort(),_V);try{let l=It(o);delete l["Content-Type"],vr.etag&&Ft()==="server"&&(l["If-None-Match"]=vr.etag);let c=await s(`${n}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/runtime/instruction-bundle`,{headers:l,signal:i.signal});if(c.status===304)return r();if(c.status===404)return vr.routeMissingLogged||(vr.routeMissingLogged=!0,Yi("instruction_bundle_route_missing",{agentOsId:e.agentOsId,baseUrl:n})),Ft()==="embedded"&&qi(e.agentOsId)?{...r(),updated:!0}:r();if(!c.ok)return Yi("instruction_bundle_fetch_failed",{agentOsId:e.agentOsId,status:c.status}),Ft()==="embedded"&&qi(e.agentOsId)?{...r(),updated:!0}:r();let u=await c.json().catch(()=>null);return!u||!sx(u,"server",e.agentOsId)?Ft()==="embedded"&&qi(e.agentOsId)?{...r(),updated:!0}:r():(vr.etag=c.headers.get("etag"),Yi("instruction_bundle_loaded",{agentOsId:e.agentOsId,version:Mn(),publicKeyId:u.publicKeyId}),{...r(),updated:!0})}catch(l){return Yi("instruction_bundle_fetch_error",{agentOsId:e.agentOsId,error:l instanceof Error?l.message:String(l)}),Ft()==="embedded"&&qi(e.agentOsId)?{...r(),updated:!0}:r()}finally{clearTimeout(a)}}var SV,_V,vr,ax=p(()=>{"use strict";as();ex();Gr();ox();SV=15*6e4,_V=1e4,vr={lastAttemptAtMs:0,etag:null,diskCacheTried:!1,routeMissingLogged:!1}});import xV from"node:os";function lx(e,t){console.error(JSON.stringify({event:"daemon_identity",level:e,message:t}))}function cx(e=P(),t=process.env){let r=et(t,e),n=Ko({config:e,totalMemBytes:xV.totalmem(),env:t}),o=[...r.warnings],s=[];if(!e.boxKind?.trim()&&!t.KYNVER_BOX_KIND?.trim()&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup` (customers get boxKind=box) or `kynver setup --box-kind forge|ghost` for operator pools before starting the daemon"),r.slugInferenceBlocked){let c=t.KYNVER_DAEMON_STRICT_IDENTITY==="1"||t.KYNVER_DAEMON_STRICT_IDENTITY==="true",u="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind; treating this host as a customer box (boxKind=box), not forge/ghost";c?s.push(u):o.push(u)}let i=n.configuredMaxWorkers??n.autoCap,a=ir(r.boxKind,i);hi(r.boxKind,i)&&o.push(`Forge box maxConcurrentWorkers=${i} exceeds pool cap \u2014 using ${a}; run kynver setup --box-kind forge --max-workers 4`);let l=s.length===0;for(let c of o)lx("warn",c);for(let c of s)lx("error",c);return{ok:l,box:r,workerCapSource:n.workerCapSource,maxConcurrentWorkers:a,autoCap:n.autoCap,warnings:o,errors:s}}var ux=p(()=>{"use strict";$();Le();Io();Ci()});import{spawnSync as CV}from"node:child_process";import{existsSync as EV,readFileSync as AV}from"node:fs";import PV from"node:path";function OV(e,t,r){let n=new Map(e.map(s=>[s.pid,s])),o=[];for(let s of t)if(!(r(s.pid)||n.has(s.pid)))for(let i of e)i.parentPid===s.pid&&(i.createdAtMs+IV<s.startedAtMs||o.push({workerName:s.workerName,workerPid:s.pid,orphanPid:i.pid}));return o}function TV(e){let t=e.trim();if(!t)return[];let r=JSON.parse(t),n=Array.isArray(r)?r:[r],o=[];for(let s of n){let i=Number(s.ProcessId),a=Number(s.ParentProcessId),l=Date.parse(String(s.Created??""));Number.isInteger(i)&&Number.isInteger(a)&&Number.isFinite(l)&&o.push({pid:i,parentPid:a,createdAtMs:l})}return o}function NV(e){let t=e.filter(s=>Number.isInteger(s)&&s>0);if(t.length===0)return[];let n=`Get-CimInstance Win32_Process -Filter "${t.map(s=>`ParentProcessId=${s}`).join(" OR ")}" | Select-Object ProcessId,ParentProcessId,@{n='Created';e={$_.CreationDate.ToUniversalTime().ToString('o')}} | ConvertTo-Json -Compress`,o=CV("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:3e4});if(o.status!==0)return[];try{return TV(o.stdout??"")}catch{return[]}}function DV(e,t=re){try{let r=Se().find(o=>o.id===e);if(!r)return[];let n=[];for(let o of Object.keys(r.workers||{})){let s=PV.join(j(r.id),"workers",B(o),"worker.json");if(!EV(s))continue;let i=JSON.parse(AV(s,"utf8")),a=Date.parse(i.startedAt??"");!i.pid||!Number.isFinite(a)||t(i.pid)||n.push({workerName:o,pid:i.pid,startedAtMs:a})}return n}catch{return[]}}function dx(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return{checkedWorkers:0,killed:[]};let n=t.isAlive??re,o=(t.collect??(l=>DV(l,n)))(e);if(o.length===0)return{checkedWorkers:0,killed:[]};let s=(t.query??NV)(o.map(l=>l.pid)),i=t.killTree??fe,a=OV(s,o,n).map(l=>({...l,result:i(l.orphanPid,"SIGKILL")}));return{checkedWorkers:o.length,killed:a}}var IV,px=p(()=>{"use strict";Y();M();ci();IV=5e3});import{mkdirSync as MV,readFileSync as LV,renameSync as BV,writeFileSync as WV}from"node:fs";import{homedir as UV}from"node:os";import Xc from"node:path";function fx(){return Xc.join(UV(),".kynver")}function FV(e=fx()){return Xc.join(e,"doctor-native-windows.json")}function mx(e=fx()){return Xc.join(e,"native-windows-state.json")}function KV(e,t){MV(Xc.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;WV(r,`${JSON.stringify(t,null,2)}
|
|
143
|
+
`,{mode:384}),BV(r,e)}function ng(e){try{return JSON.parse(LV(e,"utf8"))}catch{return null}}function $V(e){let t=ng(FV(e));return!t||typeof t.checkedAt!="string"||typeof t.verdict!="string"?null:{checkedAt:t.checkedAt,runtimeVersion:typeof t.runtimeVersion=="string"?t.runtimeVersion:"unknown",verdict:t.verdict,failing:Array.isArray(t.failing)?t.failing.filter(r=>typeof r=="string"):[],warnings:Array.isArray(t.warnings)?t.warnings.filter(r=>typeof r=="string"):[],providers:t.providers&&typeof t.providers=="object"?Object.fromEntries(Object.entries(t.providers).filter(r=>typeof r[1]=="string")):{},orphanedProcesses:typeof t.orphanedProcesses=="number"?t.orphanedProcesses:0}}function gx(e=new Date,t){try{let r=mx(t),n=ng(r)??{};KV(r,{...n,lastWorkerCompletedAt:e.toISOString()})}catch{}}function HV(e){let t=ng(mx(e));return typeof t?.lastWorkerCompletedAt=="string"?t.lastWorkerCompletedAt:null}function yx(e){rg=e.admission,hx=e.ownerKind}function kx(e={}){let t=e.platform??process.platform,r=e.hostKind??Gf(),n=r==="win32";return{hostKind:r,wsl:r==="wsl",platform:t,arch:process.arch,nodeVersion:process.versions.node,runtimeVersion:Ge,ownerKind:hx,nativeWindows:n?{admission:rg?.basis??null,hostCapability:rg?.hostCapability??null,lastDoctor:$V(e.root),lastWorkerCompletedAt:HV(e.root)}:null}}var rg,hx,Qc=p(()=>{"use strict";fc();Vr();rg=null,hx=null});function jV(e){return typeof e=="string"&&bx.includes(e)}function VV(e,t){let r=e[t]?.trim().toLowerCase();return r==="1"||r==="true"||r==="yes"||r==="on"}function JV(e={}){let t=e.platform??process.platform,r=e.env??process.env;return e.hostCapability!==void 0&&!jV(e.hostCapability)?{allowed:!1,reason:"invalid_host_capability",remedy:"hostCapability must be one of: "+bx.join(", ")}:t!=="win32"?{allowed:!0,basis:"not_native_windows",hostCapability:e.hostCapability??null}:e.hostCapability?{allowed:!0,basis:"host_capability",hostCapability:e.hostCapability}:VV(r,og)?{allowed:!0,basis:"experimental_env_override",hostCapability:null}:{allowed:!1,reason:"native_windows_unqualified",remedy:GV}}function sg(e={}){let t=JV(e);return t.allowed?(t.basis==="experimental_env_override"&&console.error(JSON.stringify({event:"daemon_native_windows_experimental",override:og,note:"Native Windows is not yet qualified for this runtime release; WSL remains the supported path."})),t):(console.error(JSON.stringify({event:"daemon_start_blocked",reason:t.reason,remedy:t.remedy})),process.exit(1),t)}var bx,og,GV,ig=p(()=>{"use strict";bx=["desktop-supervised","native-windows-qualified"],og="KYNVER_DAEMON_ALLOW_NATIVE_WINDOWS";GV=`Run the daemon inside WSL: .\\scripts\\start-tier2-wsl.ps1 \u2014 or set ${og}=1 for the experimental native path (not yet qualified; \`kynver doctor runner-install\` reports the host).`});function qV(e){return e.replace(/\/+$/,"")}async function vx(e){let t=e.fetchFn??fetch,r=e.entry.spec.callbackPath.startsWith("/")?e.entry.spec.callbackPath:`/${e.entry.spec.callbackPath}`,n=`${qV(e.baseUrl)}${r}`,s={source:"kynver-cron",jobId:e.jobId??e.entry.spec.dedupeKey??null,agentOsId:e.entry.spec.target.agentOsId,kind:e.entry.spec.kind,target:e.entry.spec.target,...e.entry.spec.payload!==void 0&&{payload:e.entry.spec.payload}},i=await t(n,{method:"POST",headers:It(e.secret),body:JSON.stringify(s)}),a=null;try{a=await i.json()}catch{a=null}return{ok:i.ok,status:i.status,body:a,url:n}}var Rx=p(()=>{"use strict";as()});import{closeSync as YV,existsSync as ag,openSync as zV,readFileSync as XV,unlinkSync as wx,writeFileSync as QV}from"node:fs";function Sx(e){if(!ag(e))return null;try{let t=JSON.parse(XV(e,"utf8"));if(typeof t.pid=="number"&&typeof t.at=="string")return t}catch{return null}return null}function eG(e){let t=Sx(e);if(!t||!re(t.pid))return!0;let r=Date.parse(t.at);return Number.isNaN(r)?!0:Date.now()-r>ZV}function _x(e){if(ag(e)&&!eG(e)){let t=Sx(e);return{acquired:!1,reason:t?`held by pid ${t.pid}`:"held by another process"}}if(ag(e))try{wx(e)}catch{}try{let t=zV(e,"wx");return QV(t,JSON.stringify({pid:process.pid,at:new Date().toISOString()}),"utf8"),YV(t),{acquired:!0}}catch(t){if(t.code==="EEXIST")return{acquired:!1,reason:"concurrent acquire"};throw t}}function xx(e){try{wx(e)}catch{}}var ZV,Cx=p(()=>{"use strict";M();ZV=10*6e4});function rG(e){return tG.test(e.trim())}function nG(e,t,r){let n=new Set;for(let o of e.split(",")){let s=o.trim();if(!s)continue;if(s==="*"){for(let d=t;d<=r;d++)n.add(d);continue}let i=/^(.+)\/(\d+)$/.exec(s),a=i?i[1]:s,l=i?Math.max(1,Number(i[2])):1;if(a==="*"){for(let d=t;d<=r;d+=l)n.add(d);continue}let c=/^(\d+)-(\d+)$/.exec(a);if(c){let d=Math.max(t,Number(c[1])),f=Math.min(r,Number(c[2]));for(let m=d;m<=f;m+=l)n.add(m);continue}let u=Number(a);Number.isInteger(u)&&u>=t&&u<=r&&n.add(u)}return n}function zi(e,t,r,n){let o=e.trim();return o==="*"?!0:nG(o,r,n).has(t)}function oG(e,t){let r=e.trim().split(/\s+/);if(r.length!==5)return!1;let[n,o,s,i,a]=r;return zi(n,t.getUTCMinutes(),0,59)&&zi(o,t.getUTCHours(),0,23)&&zi(s,t.getUTCDate(),1,31)&&zi(i,t.getUTCMonth()+1,1,12)&&zi(a,t.getUTCDay(),0,6)}function iG(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),0,0))}function Ex(e,t){if(!rG(e))return null;let r=iG(t);r=new Date(r.getTime()+6e4);for(let n=0;n<sG;n++){if(oG(e,r))return r;r=new Date(r.getTime()+6e4)}return null}function Ax(e,t){if(e.scheduleKind==="runAt"&&e.runAt){let r=Date.parse(e.runAt);return Number.isNaN(r)?null:new Date(r).toISOString()}if(e.scheduleKind==="cron"&&e.cron){let r=Ex(e.cron.trim(),t);return r?r.toISOString():null}return null}function lg(e,t){if(e.scheduleKind!=="cron"||!e.cron?.trim())return null;let r=Ex(e.cron.trim(),t);return r?r.toISOString():null}var tG,sG,Px=p(()=>{"use strict";tG=/^[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+$/;sG=366*24*60});import{randomBytes as aG}from"node:crypto";import{promises as Xi}from"node:fs";import lG from"node:path";async function cG(e){try{return await Xi.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function uG(e){if(!e)return{...Zc,jobs:{...Zc.jobs}};try{let t=JSON.parse(e);return t?.version!==1||typeof t.jobs!="object"||!t.jobs?{...Zc,jobs:{}}:t}catch{return{...Zc,jobs:{}}}}async function cg(e){let t=await cG(e);return uG(t)}async function dG(e,t){await Xi.mkdir(lG.dirname(e),{recursive:!0});let r=aG(6).toString("hex"),n=`${e}.tmp-${process.pid}-${Date.now()}-${r}`;await Xi.writeFile(n,`${JSON.stringify(t,null,2)}
|
|
144
|
+
`,"utf8");try{await Xi.rename(n,e)}catch(o){let s=o.code;if(s!=="EPERM"&&s!=="EEXIST"&&s!=="EACCES")throw o;await Xi.unlink(n).catch(()=>{})}}async function Ix(e,t){await dG(e,t)}function Ox(e,t){let r=e.jobs[t];if(r)return r;let n={providerScheduleId:t,nextFireAt:null,lastFiredAt:null,lastAttemptAt:null,consecutiveFailures:0,completedAt:null,inflightUntil:null};return e.jobs[t]=n,n}var Zc,ug=p(()=>{"use strict";Zc={version:1,jobs:{}}});function pG(e,t){if(!e.inflightUntil)return!1;let r=Date.parse(e.inflightUntil);return!Number.isNaN(r)&&r>t}function fG(e){return!!e.completedAt}function mG(e,t,r,n){if(t.consecutiveFailures===0)return!0;if(e.spec.scheduleKind!=="cron"&&t.consecutiveFailures>r.maxRetries)return!1;if(!t.lastAttemptAt)return!0;let o=Date.parse(t.lastAttemptAt);return Number.isNaN(o)?!0:n-o>=r.retryBackoffMs}function gG(e,t,r){if(t.nextFireAt)return t.nextFireAt;let n=Ax(e.spec,r);return t.nextFireAt=n,n}function hG(e,t,r,n){if(e.paused||fG(t)||pG(t,r)||!mG(e,t,n,r))return!1;let o=t.nextFireAt?Date.parse(t.nextFireAt):NaN;return Number.isNaN(o)?!1:r>=o}function yG(e,t,r){e.spec.scheduleKind==="cron"&&(t.nextFireAt=lg(e.spec,r))}async function dg(e={}){let t=e.env??rs(),r=e.now??new Date,n=r.getTime(),o=e.agentOsIdFilter?Te(e.agentOsIdFilter):Te();if(!t.tickEnabled)return{enabled:!1,skipped:"tick_disabled",scanned:0,due:0,fired:0,skippedJobs:0,errors:0};if(!t.fireBaseUrl||!t.secret&&!o)return{enabled:!0,skipped:"missing_fire_credentials",scanned:0,due:0,fired:0,skippedJobs:0,errors:0};let s=_x(t.lockPath);if(!s.acquired)return{enabled:!0,skipped:s.reason??"lock_not_acquired",scanned:0,due:0,fired:0,skippedJobs:0,errors:0,lockHeld:!0};try{let i=await Hc(t.storePath),a=e.agentOsIdFilter?i.filter(h=>h.spec.target.agentOsId===e.agentOsIdFilter):i,l=await cg(t.statePath),c=[];for(let h of a){let y=Ox(l,h.providerScheduleId);gG(h,y,r),hG(h,y,n,t)&&c.push({entry:h,job:y})}c.sort((h,y)=>{let v=Date.parse(h.job.nextFireAt??"")||0,k=Date.parse(y.job.nextFireAt??"")||0;return v-k});let u=0,d=0,f=0,m=t.maxCatchUpPerTick,g=[];for(let{entry:h,job:y}of c){if(t.missedRunPolicy==="skip"&&h.spec.scheduleKind==="cron"){let v=Date.parse(y.nextFireAt??"");if(!Number.isNaN(v)&&v<n-t.tickIntervalMs*2){y.nextFireAt=lg(h.spec,r),f++;continue}}if(m<=0){f++;continue}y.inflightUntil=new Date(n+t.inflightLeaseMs).toISOString(),y.lastAttemptAt=r.toISOString(),yG(h,y,r);try{let v=Te(h.spec.target.agentOsId)||t.secret;if(!v){y.inflightUntil=null,y.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,error:"missing_fire_credentials"});continue}let k=await vx({entry:h,baseUrl:t.fireBaseUrl,secret:v,fetchFn:e.fetchFn});y.inflightUntil=null,k.ok?(y.lastFiredAt=r.toISOString(),y.consecutiveFailures=0,h.spec.scheduleKind==="runAt"&&(y.completedAt=r.toISOString(),y.nextFireAt=null),u++,m--):(y.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,url:k.url,status:k.status,body:k.body}))}catch(v){y.inflightUntil=null,y.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,error:v instanceof Error?v.message:String(v)})}}return await Ix(t.statePath,l),{enabled:!0,scanned:a.length,due:c.length,fired:u,skippedJobs:f,errors:d,...g.length?{errorDetails:g}:{}}}finally{xx(t.lockPath)}}var pg=p(()=>{"use strict";gr();Rx();Cx();$();Px();ns();ug()});import Tx from"node:path";function eu(e){let t=F(Tx.join(j(e),Nx),null);return U_(e,t)??t}function Dx(e,t){let r={...t,updatedAt:new Date().toISOString()};be(Tx.join(j(e),Nx),r),W_(e,r)}function Mx(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.response;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.meshLiveness;if(!r||typeof r!="object"||Array.isArray(r))return null;let n=r.cronLease;if(!n||typeof n!="object"||Array.isArray(n))return null;let o=n;return{leaseToken:typeof o.leaseToken=="string"?o.leaseToken:null,holderBoxId:typeof o.holderBoxId=="string"?o.holderBoxId:null,authorized:o.authorized===!0,updatedAt:new Date().toISOString()}}var Nx,fg=p(()=>{"use strict";M();Y();Gi();Nx="mesh-cron-lease.json"});function Wx(e){Qi=e}function Ux(e=Date.now()){return!Qi||Qi.stallCount===Lx&&e-Bx<9e5?null:(Lx=Qi.stallCount,Bx=e,Qi)}var Qi,Lx,Bx,mg=p(()=>{"use strict";Qi=null,Lx=-1,Bx=0});function Kx(e){if(e!==void 0&&Number.isFinite(e)&&e>0)return Math.floor(e);let t=Number(process.env.KYNVER_CALLBACK_TIMEOUT_MS);return Number.isFinite(t)&&t>0?Math.floor(t):3e4}function Fx(e){return new Error(`callback timeout after ${e}ms`)}async function $x(e,t){let r=Kx(t),n=new AbortController,o,s=!1;try{return await Promise.race([e(n.signal),new Promise((i,a)=>{o=setTimeout(()=>{s=!0,n.abort(),a(Fx(r))},r)})])}catch(i){throw s?Fx(r):i}finally{o&&clearTimeout(o)}}function Hx(e,t){let r=Kx(t);return{ok:!1,status:0,response:{error:e instanceof Error?e.message:String(e),timeoutMs:r}}}async function Ln(e,t,r,n){try{return await $x(async o=>{let s=await ut(e,{method:"POST",headers:It(t),body:JSON.stringify(r),signal:o}),i=null;try{i=await s.json()}catch{i=null}return{ok:s.ok,status:s.status,response:i}},n?.timeoutMs)}catch(o){return Hx(o,n?.timeoutMs)}}async function de(e,t,r,n){let o=await Ln(e,t,r,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await aS(t,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await Ln(e,s.token,r,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function gg(e,t,r){try{return await $x(async n=>{let o=await ut(e,{method:"GET",headers:It(t),signal:n}),s=null;try{s=await o.json()}catch{s=null}return{ok:o.ok,status:o.status,response:s}},r?.timeoutMs)}catch(n){return Hx(n,r?.timeoutMs)}}var Fe=p(()=>{"use strict";as();sr();$()});function jx(){let e=Number(process.env.KYNVER_DISPATCH_CALLBACK_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):3e5}var Vx=p(()=>{"use strict"});function Zi(e){console.error(JSON.stringify({event:"dispatch_progress",ts:new Date().toISOString(),...e}))}function Gx(e){if(!e||typeof e!="object")return!1;let t=e;if(t.timeout===!0||t.timeoutMs!==void 0)return!0;let r=t.error;if(typeof r!="string"||!r.trim())return!1;let n=r.toLowerCase();return n.includes("abort")||n.includes("timeout")}function hg(e){if(!e||typeof e!="object")return!1;let t=e;return t.timeout===!0?!0:(typeof t.error=="string"?t.error.toLowerCase():"").includes("timeout")}var Jx=p(()=>{"use strict"});function vG(e){return kG.includes(e)}function RG(e){return bG.includes(e)}function qx(e){return{slug:e.slug,displayName:e.displayName,description:e.description,dispatchLane:e.dispatchLane===null||vG(e.dispatchLane)?e.dispatchLane:null,defaultRoleLane:RG(e.defaultRoleLane)?e.defaultRoleLane:"implementer"}}function SG(e){if(!e)return null;let t=e.trim().toLowerCase(),r=wG.get(t)??null,n=h_(t);if(!n)return r;let o=qx(n);return r?{...o,dispatchLane:r.dispatchLane,defaultRoleLane:r.defaultRoleLane}:o}function yg(e){return SG(e)?.defaultRoleLane??null}function zx(){return Yx.filter(e=>e.dispatchLane==="review").map(e=>e.slug)}var kG,bG,Yx,wG,tu=p(()=>{"use strict";Km();Gr();kG=["implementation","review","landing"],bG=["plan_author","implementer","report_reviewer","deep_reviewer","runtime_verifier","system"];Yx=os.personas.map(qx),wG=new Map(Yx.map(e=>[e.slug,e]))});function Xx(e){return(e??"").trim().toLowerCase()}function _G(e){switch(Xx(e)){case"implementer":case"repair_implementer":case"plan_author":case"runtime_verifier":return"implementation";case"plan_reviewer":case"report_reviewer":case"deep_reviewer":return"review";default:return null}}function xG(e){let t=Xx(e);if(!t)return;if(t==="implementation"||t==="review"||t==="landing"||t==="any")return t;let r=_G(t);if(r)return r;if(t==="implement"||t==="repair"||t==="coding")return"implementation";if(t==="land"||t==="merge")return"landing"}function Qx(e){return xG(e)??"any"}var Zx=p(()=>{"use strict";tu()});function CG(e=process.env){let t=P();return xt(t,e)!=="forge"}function ru(e,t=process.env){if(CG(t))return e?.maxConcurrentWorkers??void 0}async function nu(e,t){let r=pe(t.baseUrl?String(t.baseUrl):void 0),n=await me(t.secret?String(t.secret):void 0,e,{baseUrl:r}),o=`${r}/api/agent-os/by-id/${encodeURIComponent(e)}/runtime`;try{let s=await gg(o,n);if(!s.ok)return null;let a=s.response?.preferences?.maxConcurrentWorkers;if(a==null)return{maxConcurrentWorkers:null};let l=Number(a);return!Number.isFinite(l)||l<=0?{maxConcurrentWorkers:null}:{maxConcurrentWorkers:Math.floor(l)}}catch{return null}}var kg=p(()=>{"use strict";Fe();$();Le()});async function eC(e,t=EG){let r=await t.fetchPreferences(e.agentOsId,e.args),n=t.configuredOverride(r,e.env);return t.observe({runId:e.runId,configuredMaxWorkersOverride:n})}var EG,tC=p(()=>{"use strict";kg();Fo();EG={fetchPreferences:nu,configuredOverride:ru,observe:xi}});function ou(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function bg(e){return e.toLowerCase()}function AG(e){let t=ou(e,"roleLane");if(t)return t;let r=bg(ou(e,"executorRef")),n=bg(ou(e,"title")),o=bg(ou(e,"personaSlug")),s=`${r} ${n}`;if(s.includes("deep review")||s.includes("security review")||r.includes("deep-reviewer"))return"deep_reviewer";if(s.includes("plan author")||s.includes("plan-author")||n.includes("strategy plan"))return"plan_author";if(s.includes("plan review")||r.includes("plan-reviewer"))return"plan_reviewer";if(s.includes("report review")||s.includes("completion report"))return"report_reviewer";if(s.includes("repair")||n.startsWith("fix ")||r.includes("repair"))return"repair_implementer";if(r.includes("cursor")||r.includes("codex")||r.includes("composer")||n.includes("implement")||n.includes("land:"))return"implementer";let i=yg(o);if(i)return o==="lorentz"&&(s.includes("deep")||s.includes("security"))?"deep_reviewer":i;if(s.includes("review"))return"report_reviewer"}function rC(e){let t=AG(e);return t?{...e,roleLane:t}:e}var nC=p(()=>{"use strict";tu()});function oC(e){let t=e.trim();return PG.test(t)||IG.test(t)}function sC(e){let t=e.trim().toLowerCase();return t.startsWith("gpt-")||t.startsWith("gpt5")||t.includes("codex")}function vg(e){let t=e.trim().toLowerCase();return t.includes("composer")||t.includes("cursor")}function iC(e){return e.trim().toLowerCase().startsWith("gemini-")}function OG(e){return sC(e)?"codex":oC(e)?"claude":iC(e)?"gemini":(vg(e),"cursor")}function TG(e){if(!e.startsWith("provider:"))return null;let t=e.slice(9),r=t.indexOf(":"),n=(r>=0?t.slice(0,r):t).trim().toLowerCase(),o=r>=0&&t.slice(r+1).trim()||void 0;return n?n==="claude"||n==="opus"||n==="anthropic"?{provider:"claude",model:o,rule:o?"executor_ref:provider_claude_model":"executor_ref:provider_claude"}:n==="codex"?{provider:"codex",model:o,rule:"executor_ref:provider_codex"}:n==="openai-compatible"||n==="openai"||n==="openai_compatible"?{provider:"openai-compatible",model:o,rule:"executor_ref:provider_openai_compatible"}:n==="chatgpt"||n==="gpt"?{provider:"codex",model:o,rule:"executor_ref:provider_codex"}:n==="openai-api"||n==="openai_api"?{provider:"openai-compatible",model:o,rule:"executor_ref:provider_openai_compatible"}:n==="cursor"||n==="composer"?{provider:"cursor",model:o,rule:"executor_ref:provider_cursor"}:n==="gemini-api"||n==="gemini_api"||n==="google-api"?{provider:"gemini-api",model:o,rule:"executor_ref:provider_gemini_api"}:n==="gemini"||n==="google"||n==="gemini_cli"?{provider:"gemini",model:o,rule:o?"executor_ref:provider_gemini_model":"executor_ref:provider_gemini"}:null:null}function NG(e){if(!e.startsWith("harness-lane:"))return null;let t=e.split(":").map(o=>o.trim()).filter(Boolean);if(t.length<2)return null;let r=t[1],n=t.slice(2).join(":");return n?oC(n)||sC(n)||vg(n)||iC(n)?{lane:r,model:n,provider:OG(n),rule:"executor_ref:harness_lane_model"}:{lane:r,rule:"executor_ref:harness_lane"}:{lane:r,rule:"executor_ref:harness_lane"}}function ft(e){let t=typeof e=="string"?e.trim():"";return t?TG(t)??NG(t):null}function aC(e){let t=ft(e);return t?!!(t.provider&&t.provider!=="cursor"||t.model&&!vg(t.model)):!1}var PG,IG,su=p(()=>{"use strict";PG=/^claude[-_]/i,IG=/^(?:opus|sonnet|haiku)\b/i});function ea(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function Rr(e){if(!e?.trim())return!1;let t=e.trim().toLowerCase();return DG.has(t)?!0:t.includes("claude")||t.includes("opus")}function iu(e){if(!e)return!1;let t=e.workerProviderOverride;if(typeof t=="string"&&Rr(t))return!0;let r=ea(e,"executorRef").toLowerCase();if(r==="provider:claude"||r.startsWith("provider:claude:")||r.includes("claude-worker-override")||r.includes("operator-claude"))return!0;let n=ft(ea(e,"executorRef"));if(n?.provider&&Rr(n.provider)||n?.model&&Rr(LG(n.model)))return!0;let o=ea(e,"description");if(MG.some(i=>i.test(o)))return!0;let s=ea(e,"title");return!!/\[use-claude-worker\]/i.test(s)}function LG(e){let t=e.trim().toLowerCase();return/^claude[-_]/.test(t)||/^(?:opus|sonnet|haiku)\b/.test(t)?"claude":t}function BG(e,t){return{provider:wr,model:au,rule:`policy:cursor_default${t}`,requestedModel:e}}function UG(e){return WG.some(t=>e.startsWith(t))}function Rg(e){if(!e)return!1;let t=e.workerProviderOverride;return typeof t=="string"&&t.trim()||ft(ea(e,"executorRef"))?.provider?!0:iu(e)}function lC(e){let{routing:t,task:r}=e,n=e.explicitProvider?.trim().toLowerCase();if(e.explicitProviderIsOperatorOverride&&Rr(n))return{...t,provider:"claude",rule:t.rule.startsWith("explicit:")?t.rule:"explicit:operator_provider"};if(n||UG(t.rule)||Rg(r)||!Rr(t.provider))return t;let o=t.rule&&t.rule!=="default:global"?`:${t.rule.replace(/:/g,"_")}`:"";return BG(t.model,o)}function cC(e,t=wr){let r=e?.trim();return r?je(r):t}var wr,DG,MG,WG,Bn=p(()=>{"use strict";su();lu();Oi();Oi();wr="cursor",DG=new Set(["claude","opus","anthropic"]),MG=[/\[worker-provider:\s*claude\]/i,/\[use-claude-worker\]/i,/\[operator-worker-provider:\s*claude\]/i];WG=["explicit:","executor_ref:","factory:","task:"]});function ds(e){return uC[e]}function dC(){return Object.values(uC)}var uC,wg=p(()=>{"use strict";uC={codex:{id:"codex",displayName:"Codex (BYO OAuth / Hermes openai-codex)",costTier:"low",authSources:["oauth_local","api_key_env","subscription_hermes"],supportsLowRiskOrchestration:!0,supportsPrivilegedPlatformActions:!1,workerMcpTools:"supported"},cursor:{id:"cursor",displayName:"Cursor / Composer",costTier:"medium",authSources:["oauth_local","api_key_env"],supportsLowRiskOrchestration:!0,supportsPrivilegedPlatformActions:!0,workerMcpTools:"supported"},claude:{id:"claude",displayName:"Claude Code",costTier:"high",authSources:["oauth_local"],supportsLowRiskOrchestration:!0,supportsPrivilegedPlatformActions:!0,workerMcpTools:"supported"}}});import{existsSync as mC,readFileSync as FG}from"node:fs";import Wn from"node:path";function $G(e){return e.includes("/")||e.includes("\\")}function HG(e){return(e.PATHEXT||KG).split(";").map(t=>t.trim().toLowerCase()).filter(t=>t.startsWith("."))}function jG(e){let t=Object.keys(e).find(r=>r.toUpperCase()==="PATH");return t?e[t]??"":""}function VG(e,t={}){let r=t.env??process.env,n=t.exists??mC,o=HG(r),s=Wn.win32.extname(e)!=="",i=a=>s?[a]:o.map(l=>`${a}${l}`);if($G(e)||Wn.win32.isAbsolute(e))return i(e).find(a=>n(a))??null;for(let a of jG(r).split(";").map(l=>l.trim()).filter(Boolean)){let l=i(Wn.win32.join(a,e)).find(c=>n(c));if(l)return l}return null}function fC(e){return e.replace(/^[\\/]+/,"")}function JG(e){let t=e.split(/\r?\n/),r=new Map;for(let s of t){let i=GG.exec(s);i&&r.set(i[1].toUpperCase(),i[2])}let n=t.filter(s=>s.includes("%*")).pop();if(!n)return null;let o=pC.exec(n);if(o)return fC(o[1]);for(let s of n.matchAll(/%([A-Za-z_]\w*)%/g)){let i=r.get(s[1].toUpperCase()),a=i?pC.exec(i):null;if(a)return fC(a[1])}return null}function qG(e,t={}){if((t.platform??process.platform)!=="win32")return{executable:e,prefixArgs:[],kind:"passthrough"};let n=VG(e,t);if(!n)return{executable:e,prefixArgs:[],kind:"passthrough"};let o=Wn.win32.extname(n).toLowerCase();if(o!==".cmd"&&o!==".bat")return{executable:n,prefixArgs:[],kind:"exe"};let s=t.readText??(m=>FG(m,"utf8")),i=t.exists??mC,a;try{a=s(n)}catch{throw new ta(n)}let l=JG(a);if(!l)throw new ta(n);let c=Wn.win32.dirname(n),u=Wn.win32.join(c,l);if(!i(u))throw new ta(n);let d=Wn.win32.join(c,"node.exe");return{executable:i(d)?d:t.nodeExecutable??process.execPath,prefixArgs:[u],kind:"node-shim"}}function ae(e,t,r={}){let n=qG(e,r);return[n.executable,[...n.prefixArgs,...t]]}var ta,KG,pC,GG,qe=p(()=>{"use strict";ta=class extends Error{constructor(r){super(`${r} is a batch file that is not a Node CLI shim; it cannot be spawned without a shell. Point the matching KYNVER_*_BIN setting at the real .exe or the CLI's JS entry, or run the daemon inside WSL.`);this.shimPath=r;this.name="UnresolvableWindowsShimError"}shimPath},KG=".COM;.EXE;.BAT;.CMD";pC=/%~?dp0%?\\?([^"%\r\n]+?\.(?:c|m)?js)\b/i,GG=/^\s*SET\s+"?([A-Za-z_]\w*)=([^"\r\n]*)"?\s*$/i});import{createHash as gC}from"node:crypto";import{statSync as YG}from"node:fs";import{spawnSync as hC}from"node:child_process";function Kt(e){try{let t=YG(e),r=`${e}|${t.size}|${t.mtimeMs}`;return gC("sha256").update(r).digest("hex").slice(0,16)}catch{return}}function ps(e){return gC("sha256").update(`env:${e}`).digest("hex").slice(0,16)}function mt(e,t){for(let r of t){let n=process.env[r]?.trim();if(n)return n}return e}function Tt(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=ae(e,t),i=hC(o,s,{windowsHide:!0,encoding:"utf8",timeout:n,env:{...process.env,...r.env,CI:"1",NO_COLOR:"1"}});if(i.status===0)return{ok:!0,note:r.okNote??`${e} ${t.join(" ")}: ok`};let a=(i.stderr||i.stdout||"").trim(),l=r.failPrefix??`${e} ${t.join(" ")} failed`;return{ok:!1,note:a?`${l}: ${a.slice(0,200)}`:l}}catch(o){return{ok:!1,note:o instanceof Error?o.message:`${e} probe failed`}}}function cu(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=ae(e,t);return hC(o,s,{windowsHide:!0,stdio:"ignore",timeout:n,env:{...process.env,CI:"1",NO_COLOR:"1"}}).status===0?{ok:!0,note:r.okNote??`${e} authenticated`}:{ok:!1,note:r.failNote??`${e} not authenticated`}}catch(o){return{ok:!1,note:o instanceof Error?o.message:`${e} auth probe failed`}}}var Un=p(()=>{"use strict";qe()});import{existsSync as zG}from"node:fs";import{homedir as XG}from"node:os";import ra from"node:path";function ZG(){let e=XG();return[process.env.CODEX_HOME?.trim()?ra.join(ra.resolve(process.env.CODEX_HOME.trim()),"auth.json"):null,ra.join(e,".codex","auth.json"),ra.join(e,".config","codex","auth.json")].filter(r=>!!r)}function eJ(e){return ra.dirname(e)}function tJ(e){let t,r;for(let n of ZG()){if(!zG(n))continue;t??=n;let o=Tt(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status",env:{CODEX_HOME:eJ(n)}});if(r??=o,o.ok)return{authPath:n,login:o}}return{authPath:t,login:r??Tt(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status"})}}function yC(e=new Date().toISOString()){let t=mt(QG,["KYNVER_CODEX_BIN","CODEX_BIN"]);if(process.env.CODEX_API_KEY?.trim())return{providerId:"codex",ready:!0,authSource:"api_key_env",sessionFingerprint:ps("CODEX_API_KEY"),checkedAt:e,note:"CODEX_API_KEY present (env binding \u2014 cloud credits path, no token stored in Kynver)"};let{authPath:r,login:n}=tJ(t),o=!!r&&n.ok;return{providerId:"codex",ready:o,authSource:"oauth_local",sessionFingerprint:r?Kt(r):void 0,checkedAt:e,note:o?"Local Codex OAuth session bound on runner":[n.note,r?void 0:"no Codex auth store found"].filter(Boolean).join("; ")}}var QG,kC=p(()=>{"use strict";Un();QG="codex"});import{existsSync as rJ}from"node:fs";import{homedir as nJ}from"node:os";import Sg from"node:path";function oJ(){let e=process.env.HERMES_HOME?.trim(),t=e?Sg.resolve(e):Sg.join(nJ(),".hermes");return Sg.join(t,"auth.json")}function uu(e=new Date().toISOString()){let t=mt("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=Tt(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=oJ(),o=rJ(n),s=cu(t,["auth","status","openai-codex"],{okNote:"hermes openai-codex: logged in",failNote:"hermes openai-codex: not logged in"}),i=r.ok&&s.ok;return{path:"hermes_openai_codex",ready:i,authSource:i?"subscription_hermes":"none",sessionFingerprint:o?Kt(n):void 0,checkedAt:e,note:i?"Hermes openai-codex subscription session bound (ChatGPT Codex OAuth)":[r.note,s.note,o?void 0:"no ~/.hermes/auth.json"].filter(Boolean).join("; ")}}var _g=p(()=>{"use strict";Un()});function fs(e=new Date().toISOString()){let t=yC(e);if(t.ready)return{...t,path:"codex_cli"};let r=uu(e);return r.ready?{providerId:"codex",ready:!0,authSource:r.authSource,sessionFingerprint:r.sessionFingerprint,checkedAt:r.checkedAt,note:r.note,path:"hermes_openai_codex",hermesOpenAiCodex:r}:{providerId:"codex",ready:!1,authSource:"none",checkedAt:e,path:"none",hermesOpenAiCodex:r,note:[t.note,r.note].filter(Boolean).join("; ")||"Codex CLI and Hermes openai-codex unavailable"}}var du=p(()=>{"use strict";kC();_g()});function RC(e,t){let r=ds(e);return t==="privileged"?r.supportsPrivilegedPlatformActions:t==="low"?r.supportsLowRiskOrchestration:!0}function sJ(e,t){let r=ds(e.providerId),n=ds(t.providerId),o=bC.indexOf(r.costTier)-bC.indexOf(n.costTier);if(o!==0)return o;let s=vC[e.binding.authSource]-vC[t.binding.authSource];return s!==0?s:e.providerId.localeCompare(t.providerId)}function xg(e){let t=dC().map(a=>({providerId:a.id,binding:e.inventory.bindings[a.id]})).filter(a=>a.binding.ready&&RC(a.providerId,e.riskClass));if(t.length===0)return null;let n=[...t].sort(sJ)[0],o="codex";if(n.providerId===o)return{providerId:n.providerId,binding:n.binding};let s=e.inventory.bindings[o],i;return RC(o,e.riskClass)?s.ready||(i=s.note??`${o} not bound`):i=`${e.riskClass} orchestration requires privileged-capable provider`,{providerId:n.providerId,binding:n.binding,escalatedFrom:o,escalatedReason:i}}var bC,vC,wC=p(()=>{"use strict";wg();bC=["low","medium","high"],vC={oauth_local:0,subscription_hermes:0,runner_token:1,api_key_env:2,none:3}});import{existsSync as iJ}from"node:fs";import{homedir as aJ}from"node:os";import lJ from"node:path";function uJ(){let e=aJ();return[lJ.join(e,".claude",".credentials.json")]}function SC(e=new Date().toISOString()){let t=mt(cJ,["KYNVER_CLAUDE_BIN","CLAUDE_BIN"]);if(process.env.ANTHROPIC_API_KEY?.trim())return{providerId:"claude",ready:!1,authSource:"api_key_env",sessionFingerprint:ps("ANTHROPIC_API_KEY"),checkedAt:e,note:"ANTHROPIC_API_KEY present but scrubbed from worker env (deployment secret) \u2014 use `claude` CLI login (OAuth) for harness workers"};let r=Tt(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=uJ().find(i=>iJ(i)),o=cu(t,["auth","status"],{okNote:"claude auth status: authenticated",failNote:"claude auth status: not authenticated"}),s=r.ok&&(o.ok||!!n);return{providerId:"claude",ready:s,authSource:"oauth_local",sessionFingerprint:n?Kt(n):void 0,checkedAt:e,note:s?"Local Claude Code OAuth session bound on runner":[r.note,o.note,n?void 0:"no ~/.claude/.credentials.json"].filter(Boolean).join("; ")}}var cJ,_C=p(()=>{"use strict";Un();cJ="claude"});function gt(e,t={}){let r=di(e);if(!t.reviewWorker)return r;let n={...r,[dJ]:"1"};for(let o of pJ)delete n[o];return n}var dJ,pJ,Fn=p(()=>{"use strict";pi();dJ="KYNVER_NO_PROD_DB_CREDENTIALS",pJ=["KYNVER_ENV_FILE"]});function xC(e){return e.replace(fJ,"")}function pu(e){return/^claude[-_]/i.test(e)||/^(?:opus|sonnet|haiku)\b/i.test(e)}function mJ(e){let t=e.trim().toLowerCase();return t.startsWith("gemini-")||t==="auto"||t==="pro"||t==="flash"||t==="flash-lite"}function hJ(e){let t=e.trim().toLowerCase();return gJ.has(t)?"auto":null}function Cg(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=xC(r).trim()||t;return CC.test(o)||!pu(o)&&o!==t?{ok:!1,model:r,normalized:!1,requested:r,note:`model "${r}" is not a Claude model \u2014 the "claude" provider drives the Claude CLI, which only accepts claude-* model ids (got "${o}"). Pick a Claude model or switch the worker provider.`}:o!==r?{ok:!0,model:o,normalized:!0,requested:r,note:`normalized model "${r}" \u2192 "${o}" (the Claude CLI rejects reasoning-effort suffixes)`}:{ok:!0,model:o,normalized:!1}}function ms(e,t){let r=(e??"").trim();return r?pu(r)?{ok:!1,model:r,normalized:!1,requested:r,note:`model "${r}" is a Claude model but the worker provider is "codex". Switch the provider or pick a Codex/OpenAI model.`}:{ok:!0,model:r,normalized:!1}:{ok:!0,model:t,normalized:!1}}function Eg(e,t){let r=(e??"").trim();if(r)return{ok:!0,model:r,normalized:!1};let n=(t??"").trim();return n?{ok:!0,model:n,normalized:!1}:{ok:!1,model:"",normalized:!1,note:'the "openai-compatible" provider has no universal default model \u2014 pass --model (any id your endpoint serves, e.g. llama3.1, qwen2.5-coder, gpt-4o-mini) or set KYNVER_WORKER_MODEL on the daemon host.'}}function gs(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=xC(r).trim()||t;return pu(o)||!mJ(o)&&CC.test(o)?{ok:!1,model:r,normalized:!1,requested:r,note:`model "${r}" is not a Gemini model \u2014 the gemini / gemini-api providers drive Google Gemini (got "${o}"). Pick a gemini-* model or an alias (auto, pro, flash, flash-lite), or switch the worker provider.`}:o!==r?{ok:!0,model:o,normalized:!0,requested:r,note:`normalized model "${r}" \u2192 "${o}"`}:{ok:!0,model:o,normalized:!1}}function hs(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let n=hJ(r);return n?{ok:!0,model:n,normalized:!0,requested:r,note:`normalized model "${r}" \u2192 "${n}" (Cursor provider alias \u2014 use "auto" or a composer id, not "cursor")`}:pu(r)?{ok:!1,model:r,normalized:!1,requested:r,note:`model "${r}" is a Claude model but the worker provider is "cursor". Switch the provider to "claude" or pick a Cursor model.`}:{ok:!0,model:r,normalized:!1}}var fJ,CC,gJ,$t=p(()=>{"use strict";fJ=/-(?:thinking(?:-(?:high|medium|low|minimal|max|none))?|high|medium|low|minimal)$/i;CC=/^(?:gpt-|gpt5|o1|o3|o4|gemini-|grok-|composer|deepseek|llama|mistral|qwen|command-)/i;gJ=new Set(["cursor"])});import{existsSync as na,readdirSync as yJ}from"node:fs";import Kn from"node:path";function bJ(e){let r=e.split("-")[0].split(".");if(r.length!==3)return null;let[n,o,s]=r;return!n||!o||!s?null:+`${n}${o.padStart(2,"0")}${s.padStart(2,"0")}`}function vJ(e){let t=Kn.join(e,"versions");if(!na(t))return null;let r=null,n=-1;for(let o of yJ(t,{withFileTypes:!0})){if(!o.isDirectory()||!kJ.test(o.name))continue;let s=bJ(o.name);s==null||s<=n||(n=s,r=Kn.join(t,o.name))}return r}function fu(e){let t=e?.trim()||Kn.join(process.env.LOCALAPPDATA||"","cursor-agent"),r=Kn.join(t,"node.exe"),n=Kn.join(t,"index.js");if(na(r)&&na(n))return{nodeExe:r,indexJs:n,versionDir:t};let o=vJ(t);if(!o)return null;let s=Kn.join(o,"node.exe"),i=Kn.join(o,"index.js");return!na(s)||!na(i)?null:{nodeExe:s,indexJs:i,versionDir:o}}var kJ,EC=p(()=>{"use strict";kJ=/^\d{4}\.\d{1,2}\.\d{1,2}-[a-f0-9]+$/i});import{closeSync as Pg,existsSync as IC,mkdirSync as RJ,openSync as Ig,statSync as wJ,unlinkSync as AC}from"node:fs";import{spawn as SJ}from"node:child_process";import _J from"node:os";import Ht from"node:path";function AJ(e,t,r){return{executable:e,prefixArgs:[t],shell:!1,detached:Re(),bundledVersionDir:r}}function oa(e){if(process.platform==="win32"){let t=/\.(cmd|bat)$/i.test(e),r=/node\.exe$/i.test(e)&&IC(Ht.join(Ht.dirname(e),"index.js"));if(t||r||e==="agent"){let o=t?fu(Ht.dirname(e)):r?{nodeExe:e,indexJs:Ht.join(Ht.dirname(e),"index.js"),versionDir:Ht.dirname(e)}:fu();if(o)return AJ(o.nodeExe,o.indexJs,o.versionDir);throw new Error("Cursor Agent on Windows has no headless bundled node.exe under %LOCALAPPDATA%\\cursor-agent\\versions\\\u2026. Run `agent login` / update Cursor Agent CLI, use `--provider claude`, or set KYNVER_CURSOR_AGENT_ROOT to the cursor-agent folder.")}}return{executable:e,prefixArgs:[],shell:!1,detached:Re()}}function PJ(e,t,r){return gt({...process.env,CI:"1",NO_COLOR:"1",...t.bundledVersionDir?{CURSOR_INVOKED_AS:Ht.basename(e)||"agent.cmd"}:{}},{reviewWorker:r})}function OC(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Og(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function IJ(){let e=process.env.KYNVER_CURSOR_START_LOCK_DIR?.trim()||Ht.join(_J.homedir(),".kynver","locks");return RJ(e,{recursive:!0}),Ht.join(e,"cursor-agent-start.lock")}function OJ(){if(process.env.KYNVER_CURSOR_START_LOCK==="0")return()=>{};let e=IJ(),t=Og("KYNVER_CURSOR_START_LOCK_TIMEOUT_MS",CJ),r=Og("KYNVER_CURSOR_START_LOCK_STALE_MS",EJ),n=Date.now();for(;;)try{let o=Ig(e,"wx");return Pg(o),()=>{try{AC(e)}catch{}}}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-wJ(e).mtimeMs>r){AC(e);continue}}catch{continue}if(Date.now()-n>t)throw new Error(`timed out waiting for Cursor agent start lock: ${e}`);OC(250)}}function $n(e=process.env){let t=e.KYNVER_CURSOR_AGENT_BIN?.trim()||e.CURSOR_AGENT_BIN?.trim();if(t)return t;if(process.platform==="win32"){let r=fu(e.KYNVER_CURSOR_AGENT_ROOT?.trim()||void 0);if(r)return r.nodeExe;let n=Ht.join(e.LOCALAPPDATA||"","cursor-agent","agent.cmd");if(IC(n))return n}return"agent"}function TJ(){return $n(process.env)}function PC(e,t,r=[]){return[...r,"-p",...e.executionMode==="read_only"?["--mode","plan"]:["--force"],...e.mcpConfigPath?["--approve-mcps"]:[],"--trust","--workspace",e.worktreePath,"--output-format","stream-json","--stream-partial-output","--model",t,e.prompt]}var Ag,xJ,CJ,EJ,TC,ys=p(()=>{"use strict";lr();M();Fn();$t();EC();Ag="composer-2.5",xJ=15e3,CJ=6e4,EJ=3e4;TC={name:"cursor",defaultModel:Ag,preflightModel(e){return hs(e,Ag)},start(e){let t=hs(e.model,Ag);if(!t.ok)throw new Error(`cursor provider model preflight failed: ${t.note}`);let r=t.model,n=Ig(e.stdoutPath,"a"),o=Ig(e.stderrPath,"a"),s=["ignore",n,o],i=TJ(),a=oa(i),l=OJ(),c;try{let[u,d]=a.shell?[a.executable,PC(e,r,a.prefixArgs)]:tt(a.executable,PC(e,r,a.prefixArgs),e.workerDir);c=SJ(u,d,z({cwd:e.worktreePath,detached:a.detached,shell:a.shell,stdio:s,env:PJ(i,a,e.reviewWorker)})),OC(Og("KYNVER_CURSOR_START_LOCK_HOLD_MS",xJ))}finally{l(),Pg(n),Pg(o)}if(!c.pid)throw new Error(`failed to spawn Cursor agent worker (is \`${i}\` on PATH? run \`agent login\` or set CURSOR_API_KEY)`);return c.unref(),{pid:c.pid,model:r}}}});import{spawnSync as NJ}from"node:child_process";function mu(e,t=process.env){try{let r;try{r=oa(e)}catch{r={executable:e,prefixArgs:[]}}let n=NJ(r.executable,[...r.prefixArgs,"status","--format","json"],{encoding:"utf8",windowsHide:!0,timeout:8e3,env:{...t,CI:"1",NO_COLOR:"1"}});if(n.status!==0)return{ok:!1,note:"agent status: not authenticated"};let o=(n.stdout||"").trim();if(!o)return{ok:!1,note:"agent status: empty response"};let s;try{s=JSON.parse(o)}catch{return{ok:!1,note:"agent status: unparseable response"}}return typeof s=="object"&&s!==null&&s.isAuthenticated===!0?{ok:!0,note:"agent status: authenticated"}:{ok:!1,note:"agent status: not authenticated"}}catch(r){return{ok:!1,note:r instanceof Error?r.message:"agent status probe failed"}}}var Tg=p(()=>{"use strict";ks();ys()});import{existsSync as NC}from"node:fs";import{homedir as DJ}from"node:os";import Hn from"node:path";import{spawnSync as MJ}from"node:child_process";function LJ(e){if(Hn.isAbsolute(e)||e.includes("/")||e.includes("\\"))return NC(e);try{let t=MJ(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function gu(e=process.env){let t=[],r=e.KYNVER_CURSOR_AUTH_HOME?.trim();r&&(t.push(Hn.join(r,".config","cursor","auth.json")),t.push(Hn.join(r,".cursor-agent","auth.json")));let n=DJ();if(t.push(Hn.join(n,".config","cursor","auth.json")),t.push(Hn.join(n,".cursor-agent","auth.json")),process.platform==="win32"){let o=e.LOCALAPPDATA?.trim(),s=e.APPDATA?.trim();o&&t.push(Hn.join(o,"cursor-agent","auth.json")),s&&t.push(Hn.join(s,"cursor","auth.json"))}return t}function DC(e){return`${e.error}: ${e.detail}`}function yu(e=process.env){let t=$n(e);return LJ(t)?e.CURSOR_API_KEY?.trim()?{ok:!0,creds:{agentBin:t,authSource:"api_key_env"}}:gu(e).find(n=>NC(n))?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:mu(t,e).ok?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:{ok:!1,error:Ng,detail:"Run `agent login` on this computer, or set CURSOR_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:hu,detail:"`agent` CLI not found. Install the Cursor Agent CLI (https://cursor.com/docs/cli/headless) and keep it on PATH."}}var hu,Ng,ks=p(()=>{"use strict";ys();Tg();hu="cursor_cli_unavailable",Ng="cursor_not_logged_in"});import{existsSync as BJ}from"node:fs";function MC(e=new Date().toISOString()){let t=mt(WJ,["KYNVER_CURSOR_AGENT_BIN","CURSOR_AGENT_BIN"]);if(process.env.CURSOR_API_KEY?.trim())return{providerId:"cursor",ready:!1,authSource:"api_key_env",sessionFingerprint:ps("CURSOR_API_KEY"),checkedAt:e,note:"CURSOR_API_KEY present but scrubbed from worker env (deployment secret) \u2014 use `agent login` (OAuth) for harness workers"};let r=Tt(t,["-v"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=gu().find(a=>BJ(a)),o=mu(t),s=!!n||o.ok,i=r.ok&&s;return{providerId:"cursor",ready:i,authSource:"oauth_local",sessionFingerprint:n?Kt(n):void 0,checkedAt:e,note:i?"Local Cursor/Composer OAuth session bound on runner":[r.note,s?void 0:o.note??"no ~/.config/cursor/auth.json or `agent login` session"].filter(Boolean).join("; ")}}var WJ,LC=p(()=>{"use strict";ks();Tg();Un();WJ="agent"});import{existsSync as UJ,readFileSync as FJ}from"node:fs";import{homedir as KJ}from"node:os";import Dg from"node:path";function HJ(){let e=process.env.HERMES_HOME?.trim(),t=e?Dg.resolve(e):Dg.join(KJ(),".hermes");return Dg.join(t,".env")}function jJ(e){try{let t=FJ(e,"utf8"),r=[];for(let n of $J)new RegExp(`^${n}=`,"m").test(t)&&r.push(n);return r}catch{return[]}}function BC(e=new Date().toISOString()){let t=mt("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=Tt(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=HJ(),o=UJ(n),s=o?jJ(n):[],a=s.some(c=>c.endsWith("_API_KEY"))?"api_key_env":o?"oauth_local":"none",l=r.ok&&o;return{adapterId:"hermes",cliAvailable:r.ok,profileBound:o,authSource:a,sessionFingerprint:o?Kt(n):void 0,checkedAt:e,note:l?`Hermes profile bound (${s.length?`keys: ${s.join(", ")}`:"no API keys detected"})`:[r.note,o?void 0:"no ~/.hermes/.env"].filter(Boolean).join("; ")}}var $J,WC=p(()=>{"use strict";Un();$J=["OPENAI_API_KEY","ANTHROPIC_API_KEY","KYNVER_API_KEY","KYNVER_BASE_URL"]});function UC(e={}){let t=e.nowIso?.()??new Date().toISOString(),r=fs(t),n={codex:r,cursor:MC(t),claude:SC(t)},o=Object.values(n).filter(s=>s.ready).length;return{generatedAt:t,bindings:n,cloudApiCredits:{anthropicApiKey:!!process.env.ANTHROPIC_API_KEY?.trim(),openaiApiKey:!!process.env.OPENAI_API_KEY?.trim(),codexApiKey:!!process.env.CODEX_API_KEY?.trim()},workerEndpoint:{baseUrlConfigured:!!process.env.KYNVER_WORKER_BASE_URL?.trim(),apiKeyConfigured:!!process.env.KYNVER_WORKER_API_KEY?.trim()},hermes:BC(t),hermesOpenAiCodex:uu(t),codexAdapterPath:r.path,readyCount:o}}var FC=p(()=>{"use strict";_C();du();LC();WC();_g()});function Mg(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function JJ(e){let t=Mg(e,"executorRef").toLowerCase(),r=Mg(e,"title").toLowerCase(),n=Mg(e,"description").toLowerCase(),o=`${t}
|
|
81
145
|
${r}
|
|
82
|
-
${n}`;return
|
|
83
|
-
`}function
|
|
84
|
-
`,{mode:384}),t}function ou(e){try{return kG(Zx(e)),!0}catch{return!1}}var RG,wG,ge,zi,zx,SG,_G,xG,tt=p(()=>{"use strict";vr();RG="KYNVER_WORKER_MCP_TOOLS",wG="mcp-config.json",ge="kynver",zi=["agent_os_context_envelope","agent_os_search_memory","agent_os_search_skills","agent_os_get_skill","agent_os_progress_note"],zx=zi.map(e=>`mcp__${ge}__${e}`),SG={"worker.context":["agent_os_context_envelope"],"worker.memory.read":["agent_os_search_memory"],"worker.skills.read":["agent_os_search_skills","agent_os_get_skill"],"worker.progress.report":["agent_os_progress_note"]};_G=["claude","cursor","codex","openai-compatible","gemini","gemini-api"],xG=["openai-compatible","gemini-api"]});import{closeSync as tC,openSync as rC}from"node:fs";import{spawn as EG}from"node:child_process";function AG(e,t){let n=oC(e,t).at(-1);if(typeof n!="string"||!n.trim())throw new Error("claude provider refuses to spawn: worker prompt is empty after argv assembly (stdin is ignored \u2014 fix prompt delivery before retrying)")}function oC(e,t){return["--model",t,"-p","--verbose","--permission-mode",e.executionMode==="read_only"?"plan":"bypassPermissions","--output-format","stream-json","--include-partial-messages",...e.mcpConfigPath?["--mcp-config",e.mcpConfigPath,`--allowedTools=${(e.mcpAllowedTools?.length?e.mcpAllowedTools:zx).join(",")}`]:[],"--",e.prompt]}var jr,Zi,nC,mg=p(()=>{"use strict";Nn();D();Ge();Wt();tt();jr="claude-sonnet-4-6",Zi="claude-opus-4-8";nC={name:"claude",defaultModel:jr,preflightModel(e){return tg(e,jr)},start(e){let t=tg(e.model,jr);if(!t.ok)throw new Error(`claude provider model preflight failed: ${t.note}`);let r=t.model;AG(e,r);let[n,o]=se("claude",oC(e,r)),s=rC(e.stdoutPath,"a"),i=rC(e.stderrPath,"a"),a=["ignore",s,i],l=EG(n,o,X({cwd:e.worktreePath,detached:be(),stdio:a,env:dt(process.env,{reviewWorker:e.reviewWorker})}));if(tC(s),tC(i),!l.pid)throw new Error("failed to spawn claude worker process (is the `claude` CLI on PATH?)");return l.unref(),{pid:l.pid,model:r}}}});import{closeSync as sC,openSync as iC}from"node:fs";import{spawn as PG}from"node:child_process";function IG(e,t){return dt({...process.env,CI:"1",NO_COLOR:"1",HERMES_ACCEPT_HOOKS:process.env.HERMES_ACCEPT_HOOKS??"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function OG(e,t){let r=process.env.KYNVER_HERMES_CODEX_MAX_TURNS?.trim()||"40";return["chat","-q",t,"--provider","openai-codex","-m",e,"-Q","--accept-hooks","--max-turns",r,"--toolsets","hermes-cli"]}var gg,aC,lC=p(()=>{"use strict";Nn();D();Ge();Tn();Wt();gg=process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||"gpt-5.5";aC={name:"hermes-codex",defaultModel:gg,preflightModel(e){return as(e,gg)},start(e){if(e.executionMode==="read_only")throw new Error("hermes-codex provider cannot enforce read_only execution mode (no sandbox flag); route read_only tasks to the direct codex exec path or another provider");let t=as(e.model,gg);if(!t.ok)throw new Error(`hermes-codex provider model preflight failed: ${t.note}`);let r=t.model,n=ut("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),[o,s]=se(n,OG(r,e.prompt)),i=iC(e.stdoutPath,"a"),a=iC(e.stderrPath,"a"),l=["ignore",i,a],c=PG(o,s,X({cwd:e.worktreePath,detached:be(),shell:!1,stdio:l,env:IG(e.reviewWorker,e.codexHome)}));if(sC(i),sC(a),!c.pid)throw new Error(`failed to spawn Hermes openai-codex worker (is \`${n}\` on PATH? run \`hermes auth status openai-codex\`)`);return c.unref(),{pid:c.pid,model:r}}}});function DG(e=process.env){return e[TG]?.trim().toLowerCase()==="elevated"?"elevated":NG}function su(e=process.platform,t=process.env){return e!=="win32"?[]:["-c",`windows.sandbox="${DG(t)}"`]}var TG,NG,hg=p(()=>{"use strict";TG="KYNVER_CODEX_WINDOWS_SANDBOX",NG="unelevated"});import{closeSync as cC,existsSync as MG,openSync as uC}from"node:fs";import{spawn as yg}from"node:child_process";function LG(){return process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||"gpt-5.5"}function wr(){return process.env.KYNVER_CODEX_BIN?.trim()||process.env.CODEX_BIN?.trim()||"codex"}function BG(e,t){return dt({...process.env,CI:"1",NO_COLOR:"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function WG(e,t,r,n=process.platform,o=process.env){return["--ask-for-approval","never","exec",...su(n,o),"--json","--sandbox",r==="read_only"?"read-only":"workspace-write","--model",e,t]}function UG(e,t,r){if(process.platform==="win32"){let[s,i]=se(e,t);return yg(s,i,r)}if(!MG("/usr/bin/script"))return yg(e,t,r);let o=[e,...t].map(s=>`'${s.replace(/'/g,"'\\''")}'`).join(" ");return yg("script",["-qfc",o,"/dev/null"],r)}var Rr,dC,Wn=p(()=>{"use strict";Nn();D();Ge();Xc();Wt();lC();hg();Rr=LG();dC={name:"codex",defaultModel:Rr,preflightModel(e){return as(e,Rr)},start(e){if(is().path==="hermes_openai_codex"&&e.executionMode!=="read_only")return aC.start(e);let r=as(e.model,Rr);if(!r.ok)throw new Error(`codex provider model preflight failed: ${r.note}`);let n=r.model,o=uC(e.stdoutPath,"a"),s=uC(e.stderrPath,"a"),i=["ignore",o,s],a=wr(),l=WG(n,e.prompt,e.executionMode),c;try{c=UG(a,l,X({cwd:e.worktreePath,detached:be(),shell:!1,stdio:i,env:BG(e.reviewWorker,e.codexHome)}))}finally{cC(o),cC(s)}if(!c.pid)throw new Error(`failed to spawn Codex worker (is \`${a}\` on PATH? run \`codex login\` or set CODEX_API_KEY)`);return c.unref(),{pid:c.pid,model:n}}}});import{existsSync as iu}from"node:fs";import Un from"node:path";import{fileURLToPath as FG}from"node:url";function $G(e,t){let r=Un.resolve(e);for(;;){let n=Un.join(r,t);if(iu(n))return n;let o=Un.dirname(r);if(o===r)return null;r=o}}function KG(e){return $G(e,Un.join("node_modules",".bin","tsx"))??"npx"}function kg(e,t){if(e.endsWith(".ts")){let r=KG(Un.dirname(e));return{command:r,argsPrefix:r==="npx"?["tsx",e]:[e],cliPath:e}}return{command:t,argsPrefix:[e],cliPath:e}}function au(e){if(e.explicitCliPath)return iu(e.explicitCliPath)?kg(e.explicitCliPath,e.nodeExecutable):null;let t=FG(new URL(".",e.importMetaUrl)),r=Un.join(t,"cli.js");if(iu(r))return kg(r,e.nodeExecutable);let n=Un.join(t,"cli.ts");return iu(n)?kg(n,e.nodeExecutable):null}var bg=p(()=>{"use strict"});function jG(e){return`/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/worker`}async function ea(e,t,r){let n=await e.fetchImpl(`${e.apiBaseUrl}${t}`,{method:r?.method??"GET",headers:{[HG]:e.token,...r?{"Content-Type":"application/json"}:{}},...r?{body:JSON.stringify(r.body)}:{}});if(!n.ok)throw new Error(`request failed (${n.status})`);return n.json()}function ta(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function lu(e,t,r){let n=jG(e);switch(t){case"agent_os_context_envelope":{let o=new URLSearchParams({task:e.taskId}),s=ta(r.memoryQuery);s&&o.set("memoryQuery",s);let i=ta(r.mode);return i&&o.set("mode",i),ea(e,`${n}/context-envelope?${o.toString()}`)}case"agent_os_search_memory":{let o=new URLSearchParams({q:String(r.query??"")});return typeof r.k=="number"&&o.set("k",String(r.k)),ea(e,`${n}/memory-search?${o.toString()}`)}case"agent_os_search_skills":{let o=new URLSearchParams,s=ta(r.query);s&&o.set("q",s),typeof r.limit=="number"&&o.set("limit",String(r.limit));let i=o.toString();return ea(e,`${n}/skills${i?`?${i}`:""}`)}case"agent_os_get_skill":return ea(e,`${n}/skills/${encodeURIComponent(String(r.slug??""))}`);case"agent_os_progress_note":return ea(e,`${n}/progress-note`,{method:"POST",body:{note:String(r.note??""),...r.kind==="blocked"?{kind:"blocked"}:{},...ta(r.eventKey)?{eventKey:ta(r.eventKey)}:{}}})}}function ps(e){return zi.includes(e)}var HG,ra,cu=p(()=>{"use strict";tt();HG="X-Kynver-Job-Token",ra={agent_os_context_envelope:{name:"agent_os_context_envelope",description:"Fetch the context envelope for YOUR OWN task: goal/plan/task summaries, relevant memory, and recent session context. Optional memoryQuery focuses the memory portion.",inputSchema:{type:"object",properties:{memoryQuery:{type:"string",description:"Focus the memory portion of the envelope."},mode:{type:"string",description:"Envelope mode hint."}},additionalProperties:!1}},agent_os_search_memory:{name:"agent_os_search_memory",description:"Semantic search over the workspace's long-term memory. Returns a bounded top-N of relevant entries.",inputSchema:{type:"object",properties:{query:{type:"string",description:"What to search for."},k:{type:"integer",minimum:1,maximum:20,description:"How many entries to return."}},required:["query"],additionalProperties:!1}},agent_os_search_skills:{name:"agent_os_search_skills",description:"Search the workspace's skill library (bounded, metadata-only index). Use agent_os_get_skill to fetch one full skill by slug.",inputSchema:{type:"object",properties:{query:{type:"string"},limit:{type:"integer",minimum:1,maximum:25}},additionalProperties:!1}},agent_os_get_skill:{name:"agent_os_get_skill",description:"Fetch ONE full skill (including instructions) by slug.",inputSchema:{type:"object",properties:{slug:{type:"string"}},required:["slug"],additionalProperties:!1}},agent_os_progress_note:{name:"agent_os_progress_note",description:"Append a progress or blocker note to YOUR OWN task's journal. kind: 'progress' (default) or 'blocked'.",inputSchema:{type:"object",properties:{note:{type:"string"},kind:{type:"string",enum:["progress","blocked"]},eventKey:{type:"string"}},required:["note"],additionalProperties:!1}}}});function na(e){return Xi(e).filter(ps).map(t=>{let r=ra[t];return{type:"function",function:{name:r.name,description:r.description,parameters:r.inputSchema}}})}var uu=p(()=>{"use strict";cu();tt()});import{closeSync as pC,openSync as fC}from"node:fs";import VG from"node:path";import{fileURLToPath as GG}from"node:url";import{spawn as JG}from"node:child_process";function vg(e=process.env){return e.KYNVER_WORKER_MODEL?.trim()||void 0}function YG(e=process.env){let t=e.KYNVER_WORKER_BASE_URL?.trim();if(!t)throw new oa(`the "openai-compatible" worker provider requires KYNVER_WORKER_BASE_URL on the daemon host \u2014 point it at any OpenAI-compatible chat-completions endpoint (e.g. http://localhost:11434/v1 for Ollama, http://localhost:8000/v1 for vLLM, or your gateway's /v1 URL). Set KYNVER_WORKER_API_KEY too when the endpoint requires auth.`);let r;try{r=new URL(t)}catch{throw new oa(`KYNVER_WORKER_BASE_URL is not a valid URL: "${t}" \u2014 expected e.g. http://localhost:11434/v1`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new oa(`KYNVER_WORKER_BASE_URL must be http(s), got "${r.protocol}//" \u2014 e.g. http://localhost:11434/v1`);let n=Number(e.KYNVER_WORKER_TIMEOUT_MS??""),o=Number.isFinite(n)&&n>0?Math.floor(n):qG;return{baseUrl:t.replace(/\/+$/,""),...e.KYNVER_WORKER_API_KEY?.trim()?{apiKey:e.KYNVER_WORKER_API_KEY.trim()}:{},timeoutMs:o}}function du(e,t,r,n){return{url:`${e.baseUrl}/chat/completions`,headers:{"content-type":"application/json",...e.apiKey?{authorization:`Bearer ${e.apiKey}`}:{}},body:{model:t,temperature:0,stream:!1,messages:[{role:"system",content:zG},{role:"user",content:r}],...n&&n.length?{tools:n,tool_choice:"auto"}:{}}}}function XG(){let e=GG(new URL(".",import.meta.url)),t=import.meta.url.endsWith(".ts"),r=VG.join(e,t?"openai-compatible-runner.ts":"openai-compatible-runner.js"),n=au({importMetaUrl:import.meta.url,explicitCliPath:r,nodeExecutable:process.execPath});if(!n)throw new Error(`openai-compatible runner script not found at ${r} \u2014 is the @kynver-app/runtime install complete?`);return{command:n.command,argsPrefix:n.argsPrefix}}function QG(e,t,r){let n=e.workerToolGrant,o=n?na(n.capabilities):void 0;return{provider:Fn,model:r,request:du(t,r,e.prompt,o),timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}function pu(e,t,r){let n=XG(),o=fC(e.stdoutPath,"a"),s=fC(e.stderrPath,"a"),i=["pipe",o,s],a=JG(n.command,n.argsPrefix,X({cwd:e.worktreePath,detached:be(),shell:!1,stdio:i,env:dt(process.env,{reviewWorker:e.reviewWorker})}));if(pC(o),pC(s),!a.pid)throw new Error(`failed to spawn ${t.provider} worker runner (node executable unavailable?)`);try{a.stdin?.on("error",()=>{}),a.stdin?.write(JSON.stringify(t)),a.stdin?.end()}catch(l){throw new Error(`failed to hand request config to ${t.provider} runner: ${l.message}`)}return a.unref(),{pid:a.pid,model:r}}var Fn,qG,oa,zG,mC,sa=p(()=>{"use strict";Nn();D();bg();Wt();uu();Fn="openai-compatible",qG=600*1e3;oa=class extends Error{};zG="You are a Kynver harness worker executing one work unit end to end. Follow the task instructions exactly and produce the complete deliverable (analysis, answer, or unified diff as the task requires) in a single response. Be precise and complete \u2014 your response is recorded verbatim as the work unit's final result.";mC={name:Fn,get defaultModel(){return vg()},preflightModel(e){return rg(e,vg())},start(e){let t=rg(e.model,vg());if(!t.ok)throw new Error(`openai-compatible provider model preflight failed: ${t.note}`);let r=t.model,n=YG(process.env),o=QG(e,n,r);return pu(e,o,r)}}});import ZG from"node:path";function pt(e=process.env){return e.KYNVER_GEMINI_BIN?.trim()||e.GEMINI_BIN?.trim()||"agy"}function fs(e){let t=ZG.basename(e).toLowerCase().replace(/\.cmd$/i,"").replace(/\.exe$/i,"");return t==="agy"||t==="antigravity"?"antigravity":"gemini"}function gC(e){return e.requested&&/-(?:high|medium|low)$/i.test(e.requested)?e.requested:e.model}function hC(e){let t=e.trim().toLowerCase();return!t||eJ.has(t)?[]:["--model",e.trim()]}function fu(e,t){return[...hC(t),"--output-format","stream-json",...e.executionMode==="read_only"?[]:["--dangerously-skip-permissions"],"--prompt",e.prompt]}function yC(e,t){return["--model",t,"--approval-mode",e.executionMode==="read_only"?"plan":"yolo","--output-format","stream-json","--skip-trust",...e.mcpConfigPath?["--allowed-mcp-server-names",ge]:[],"--prompt",e.prompt]}var eJ,$n=p(()=>{"use strict";tt();eJ=new Set(["gemini-2.5-pro","gemini-2.5-flash","auto","pro","flash","flash-lite"])});import{closeSync as kC,openSync as bC}from"node:fs";import{spawn as tJ}from"node:child_process";function Ue(e=process.env){return e.KYNVER_GEMINI_DEFAULT_MODEL?.trim()||"gemini-2.5-pro"}function rJ(e,t){return dt({...process.env,CI:"1",NO_COLOR:"1",GEMINI_CLI_TRUST_WORKSPACE:"true",...t?{GEMINI_CLI_HOME:t}:{}},{reviewWorker:e})}var Ft,vC,ia=p(()=>{"use strict";Nn();D();Ge();$n();Wt();Ft="gemini";vC={name:Ft,get defaultModel(){return Ue()},preflightModel(e){return ls(e,Ue())},start(e){let t=ls(e.model,Ue());if(!t.ok)throw new Error(`gemini provider model preflight failed: ${t.note}`);let r=pt(),n=fs(r),o=n==="antigravity"?gC(t):t.model,s=n==="antigravity"?fu(e,o):yC(e,o),[i,a]=se(r,s),l=bC(e.stdoutPath,"a"),c=bC(e.stderrPath,"a"),u=["ignore",l,c],d=tJ(i,a,X({cwd:e.worktreePath,detached:be(),shell:!1,stdio:u,env:rJ(e.reviewWorker,n==="gemini"?e.geminiCliHome:void 0)}));if(kC(l),kC(c),!d.pid)throw new Error(`failed to spawn Google Antigravity worker (is \`${r}\` on PATH? install Google Antigravity and run \`agy\` once to sign in`+(n==="antigravity"?'; GEMINI_API_KEY is used only when ~/.gemini/antigravity-cli/settings.json sets "modelProvider": "gemini")':", or set GEMINI_API_KEY)"));return d.unref(),{pid:d.pid,model:o}}}});function oJ(e=process.env){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()||void 0}function sJ(e=process.env){let t=oJ(e);if(!t)throw new aa('the "gemini-api" worker provider requires KYNVER_GEMINI_API_KEY or GEMINI_API_KEY on the daemon host \u2014 create a key at https://aistudio.google.com/apikey. To use Google Antigravity instead, set workerProvider / --provider gemini and run `agy` once to sign in.');let r=e.KYNVER_GEMINI_BASE_URL?.trim()||RC,n;try{n=new URL(r)}catch{throw new aa(`KYNVER_GEMINI_BASE_URL is not a valid URL: "${r}" \u2014 expected e.g. ${RC}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new aa(`KYNVER_GEMINI_BASE_URL must be http(s), got "${n.protocol}//"`);let o=Number(e.KYNVER_WORKER_TIMEOUT_MS??""),s=Number.isFinite(o)&&o>0?Math.floor(o):nJ;return{baseUrl:r.replace(/\/+$/,""),apiKey:t,timeoutMs:s}}function iJ(e,t,r){let n=e.workerToolGrant,o=n?na(n.capabilities):void 0,s=du(t,r,e.prompt,o);return{provider:$t,model:r,request:s,timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}var $t,RC,nJ,aa,wC,Rg=p(()=>{"use strict";sa();uu();Wt();ia();$t="gemini-api",RC="https://generativelanguage.googleapis.com/v1beta/openai",nJ=600*1e3,aa=class extends Error{};wC={name:$t,get defaultModel(){return Ue()},preflightModel(e){return ls(e,Ue())},start(e){let t=ls(e.model,Ue());if(!t.ok)throw new Error(`gemini-api provider model preflight failed: ${t.note}`);let r=t.model,n=sJ(process.env),o=iJ(e,n,r);return pu(e,o,r)}}});function Je(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function lJ(e){if(!e)return;let t=Je(e,"workerModelOverride")||Je(e,"modelOverride");return t||`${Je(e,"title")}
|
|
85
|
-
${
|
|
86
|
-
${Je(e,"executorRef")}`.match(/\[(?:worker-)?model:\s*([^\]\n]+)\]/i)?.[1]?.trim()||void 0}function SC(e){return e.toLowerCase()}function Sg(e=E()){let t=e.defaultModel?.trim();if(t)return t;let r=process.env.KYNVER_DEFAULT_MODEL?.trim();return r||aJ}function mu(e){let t=(e??"").toLowerCase();return!t||t.includes("composer")||t.includes("cursor")||t.includes("codex")||t.startsWith("gpt-")||t.startsWith("gpt5")?"cursor":/^claude[-_]/i.test(t)||/^(?:opus|sonnet|haiku)\b/i.test(t)?"claude":t.startsWith("gemini-")?Ft:"cursor"}function cJ(e,t){let r=e.trim().toLowerCase(),n=t?.trim();return r==="cursor"?{model:Jc,provider:"cursor",rule:n&&n!=="cursor"?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="claude"||r==="anthropic"?{model:jr,provider:"claude",rule:n&&n!=="claude"?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini"||r==="google"?{model:Ue(),provider:Ft,rule:n&&n!==Ft?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini-api"||r==="gemini_api"||r==="google-api"?{model:Ue(),provider:$t,rule:n&&n!==$t?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:null}function _C(e,t){return!!(e.includes("deep")&&e.includes("review")||e.includes("security")||e.includes("plan_author")||e.includes("plan-author")||t.includes("deep review")||t.includes("security review")||e.includes("plan")&&!e.includes("review")&&(e.includes("author")||e.includes("strategy")))}function xC(e,t,r){return uJ.has(e)?Zi:t.includes("review")||/^review[\s:]/.test(r)||r.includes("critique")?Zi:jr}function dJ(e){let t=SC(Je(e,"executorRef")),r=Je(e,"title").toLowerCase(),n=Je(e,"priority")||"normal",o=SC(Je(e,"roleLane"));if(t.includes("provider:claude")||t.startsWith("claude:")){let i=xC(o,t,r);return{provider:"claude",model:i,rule:i===Zi?"factory:claude_review":"factory:claude_implementation"}}if(t.includes("provider:codex")||t.startsWith("codex:"))return{provider:"codex",model:Rr,rule:"lane:codex_orchestration"};if(t.includes("provider:chatgpt")||t.startsWith("chatgpt:")||t.includes("provider:gpt")||t.startsWith("gpt:")){let i=ct(Je(e,"executorRef"));return{provider:"codex",...i?.model?{model:i.model}:{model:Rr},rule:"lane:codex_orchestration"}}if(t.includes("provider:openai")||t.startsWith("openai-compatible:")){let i=ct(Je(e,"executorRef"));return{provider:Fn,...i?.model?{model:i.model}:{},rule:"lane:openai_compatible"}}if(t.includes("provider:gemini-api")||t.startsWith("gemini-api:")){let i=ct(Je(e,"executorRef"));return{provider:$t,...i?.model?{model:i.model}:{model:Ue()},rule:"lane:gemini_api"}}if(t.includes("provider:gemini")||t.startsWith("gemini:")){let i=ct(Je(e,"executorRef"));return{provider:Ft,...i?.model?{model:i.model}:{model:Ue()},rule:"lane:gemini"}}if(t.includes("cursor")||t.includes("composer")||t.includes("copilot")||o==="implementer"||o==="repair_implementer")return{provider:"cursor",rule:"lane:implementation"};if(t.includes("codex"))return{provider:"codex",model:Rr,rule:"lane:codex_orchestration"};if(t.includes("landing")||r.startsWith("land:")||r.includes(" merge"))return{provider:"cursor",rule:"lane:landing"};if(t.includes("review")||/^review[\s:]/.test(r)||o.includes("review"))return _C(t,r)||o==="deep_reviewer"?{provider:"cursor",rule:"lane:deep_review"}:{provider:"cursor",rule:"lane:review"};if(_C(t,r)||o==="plan_author")return{provider:"cursor",rule:"lane:planning"};if(n==="critical")return{provider:"cursor",rule:"priority:critical"};if(n==="high")return{provider:"cursor",rule:"priority:high"};if(n==="low")return{provider:"cursor",rule:"priority:low"};let s=Sg();return{model:s,provider:mu(s),rule:"default:global"}}function pJ(e){return e?ct(Je(e,"executorRef")):null}function fJ(e){switch(Ke(e)){case Ft:case $t:return Ue();case"claude":return jr;case"codex":return Rr;case"cursor":return Jc;default:return}}function EC(e,t,r){let n=Ke(t);return n===e.provider&&e.rule===r?e:{...e,provider:n,model:fJ(n)??e.model,rule:r}}function mJ(e,t){let r=t?.trim();return!r||e.rule.startsWith("explicit:")&&e.rule!==wg?e:EC(e,r,wg)}function gJ(e,t){if(t.explicitProvider?.trim()||zm(t.task))return e;let r=t.configuredProvider?.trim();if(!r)return e;let n=Ke(r);return n===br||n===e.provider?e:EC(e,n,CC)}function gu(e){let t,r=pJ(e.task),n=e.explicitModel?.trim()?void 0:r?.model?.trim(),o=!e.explicitProvider?.trim()&&r?.provider?.trim()?r.provider.trim():void 0;if(e.explicitModel?.trim()){let l=e.explicitModel.trim(),c=cJ(l,e.explicitProvider);c?t=c:t={model:l,provider:e.explicitProvider?.trim()||mu(l),rule:"explicit:cli",requestedModel:l}}else if(n)t={model:n,provider:o||mu(n),rule:r?.rule??"executor_ref:model",requestedModel:n};else if(e.task&&Gc(e.task)){let l=lJ(e.task),c,u;if(l)c=l,u="task:provider_override";else{let d=typeof e.task.roleLane=="string"?e.task.roleLane.toLowerCase():"",m=typeof e.task.executorRef=="string"?e.task.executorRef.toLowerCase():"",f=typeof e.task.title=="string"?e.task.title.toLowerCase():"";c=xC(d,m,f),u=c===Zi?"factory:claude_review":"factory:claude_implementation"}t={model:c,provider:"claude",rule:u,requestedModel:c}}else if(e.task&&Object.keys(e.task).length>0){let l=dJ(e.task);t={...l,requestedModel:l.model}}else{let l=Sg();t={model:l,provider:e.explicitProvider?.trim()||mu(l),rule:"default:global",requestedModel:l}}t=mJ(t,e.explicitProvider),t=gJ(t,{explicitProvider:e.explicitProvider,task:e.task,configuredProvider:e.configuredProvider});let s=!!e.configuredProvider?.trim()&&Ke(e.configuredProvider)!==br&&t.rule==="config:worker_provider",i=hx({routing:t,task:e.task,explicitProvider:e.explicitProvider??(s?t.provider:void 0),explicitProviderIsOperatorOverride:!!e.explicitProviderIsOperatorOverride||s});if(!e.task||Object.keys(e.task).length===0||i.rule==="explicit:model_provider_alias"||i.rule==="explicit:model_provider_alias_overrode_provider"||i.rule==="explicit:cli"||i.rule===wg||i.rule===CC||kr(i.provider)&&(e.explicitProviderIsOperatorOverride||Gc(e.task))||i.provider===Fn||i.provider===Ft||i.provider===$t||i.provider==="codex")return i;let a=qx({task:e.task,explicitProvider:e.explicitProvider??i.provider,explicitModel:i.model,inventory:e.orchestrationInventory??void 0});return{provider:a.provider,model:a.provider==="codex"?a.model??i.model??Rr:i.model,rule:a.rule,requestedModel:i.requestedModel,orchestrationAudit:a.audit}}function AC(e,t,r){return e||t||r||Sg()||jr}var aJ,Jc,uJ,wg,CC,qc=p(()=>{"use strict";H();Vc();Yx();mg();Wn();sa();ia();Rg();In();aJ="claude-sonnet-4-6",Jc="composer-2.5";uJ=new Set(["report_reviewer","deep_reviewer","plan_reviewer"]);wg="explicit:cli_provider",CC="config:worker_provider"});function hJ(e){let t=e?.executorRef;return typeof t=="string"?t.trim():""}function PC(e){return e?.trim()||void 0}function IC(e){let t=hJ(e.task),r=ct(t),n=e.explicitProvider?.trim().toLowerCase(),o=PC(e.explicitModel??void 0),s=n||r?.provider,i=o||r?.model,a=n||o?"cli":r?.rule??"none";if(!s&&!i)return{ok:!0};!s&&i&&(/^claude[-_]/i.test(i)||/^(?:opus|sonnet|haiku)\b/i.test(i))&&(s="claude");let l=e.routing.provider,c=PC(e.routing.model),u={provider:l,model:c,rule:e.routing.rule};return s&&s!=="cursor"||t&&gx(t)||n&&n!=="cursor"?l==="cursor"?{ok:!1,error:`model_routing_mismatch: requested ${s??"non-cursor"}${i?` model=${i}`:""} (${a}) but routing resolved to cursor (${e.routing.rule})`,requested:{provider:s,model:i,source:a},resolved:u}:i&&c&&i!==c&&!kr(l)?{ok:!1,error:`model_routing_mismatch: requested model=${i} (${a}) but routing resolved model=${c} (${e.routing.rule})`,requested:{provider:s,model:i,source:a},resolved:u}:{ok:!0,requested:{provider:s,model:i,source:a},resolved:u}:{ok:!0,resolved:u}}var OC=p(()=>{"use strict";Vc();In()});function TC(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function NC(){return{maxTaskAttempts:TC(process.env.KYNVER_MAX_TASK_ATTEMPTS,Math.floor(Zo("harness.maxTaskAttempts",4))),dispatchCooldownMs:TC(process.env.KYNVER_DISPATCH_COOLDOWN_MS,Math.floor(Zo("harness.dispatchCooldownMs",5e3)))}}var DC=p(()=>{"use strict";Kr()});function xg(e){return e?.trim()?e.trim():null}function yJ(e){let t=xg(e);if(!t?.startsWith(_g))return null;let r=t.slice(_g.length),n=r.indexOf(MC);return n>=0?r.slice(0,n).trim()||null:r.trim()||null}function la(e,t){let r=e.trim(),n=t.trim();return`${_g}${r}${MC}${n}`}function kJ(e,t){let r=xg(t);return r?yJ(e)===r:!1}function hu(e){let t=xg(e.workerLeaseOwner);return t&&kJ(t,e.runId)?t:la(e.runId,e.runnerId)}var _g,MC,ca=p(()=>{"use strict";_g="kynver-harness:",MC="@runner:"});async function yu(e){let t=new Map,r=e.agentOsId?.trim();if(!r||e.taskIds.length===0)return t;let n=pe(e.baseUrl);try{let o=await fe(e.secret,r,{baseUrl:n}),s=`${n}/api/agent-os/by-id/${encodeURIComponent(r)}/harness/monitor/task-leases`,i=await de(s,o,{taskIds:[...new Set(e.taskIds)]},{agentOsId:r,baseUrl:n});if(!i.ok||!i.response||typeof i.response!="object")return t;let a=i.response.tasks;if(!Array.isArray(a))return t;for(let l of a)l?.taskId&&t.set(l.taskId,l)}catch{}return t}var Cg=p(()=>{"use strict";H();We()});async function ku(e){let t=e.worker.leaseOwner?.trim()??null,r=e.worker.leaseToken?.trim()??null;if(r)return{leaseOwner:t,leaseToken:r};let n=e.worker.taskId?.trim();if(!n)return{leaseOwner:t,leaseToken:null};let s=(await yu({agentOsId:e.agentOsId,taskIds:[n],baseUrl:e.baseUrl,secret:e.secret})).get(n),i=s?.leaseOwner?.trim()??null,a=s?.leaseToken?.trim()??null;if(!a)return{leaseOwner:t??i,leaseToken:null};let l=t??i;return(!e.worker.leaseToken||e.worker.leaseToken!==a)&&ee(e.worker.runId,{...e.worker,...l?{leaseOwner:l}:{},leaseToken:a}),{leaseOwner:l,leaseToken:a}}var Eg=p(()=>{"use strict";Cg();z()});import bJ from"node:path";function LC(e,t){return $(bJ.join(G(e),"workers",B(t),"worker.json"),void 0)}async function BC(e,t){let r=ae(e),n=String(t.agentOsId||"");if(!n)return{renewed:[],failed:[],skipped:[]};let o=pe(t.baseUrl?String(t.baseUrl):void 0),s=await fe(t.secret?String(t.secret):void 0,n,{baseUrl:o}),i=Number(t.leaseMs)>0?Math.floor(Number(t.leaseMs)):Pg,a=Oe({runId:e}).runnerId,l=[],c=[],u=[];for(let d of Object.keys(r.workers||{})){let m=LC(e,d);if(!m?.taskId||!m.agentOsId){u.push(d);continue}if(!re(m.pid)){u.push(d);continue}if(oe(m).status==="done"){u.push(d);continue}let g=hu({runId:e,workerLeaseOwner:m.leaseOwner??null,runnerId:a}),h=await ku({worker:m,agentOsId:n,baseUrl:o,secret:s}),y=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/${encodeURIComponent(m.taskId)}/renew-lease`,v=await de(y,s,{leaseOwner:h.leaseOwner??g,leaseDurationMs:i,...h.leaseToken?{leaseToken:h.leaseToken}:{}},{agentOsId:n,baseUrl:o});if(v.ok){l.push(d);continue}let k=v.response&&typeof v.response=="object"&&"reason"in v.response?String(v.response.reason??`http ${v.status}`):`http ${v.status}`;c.push({worker:d,reason:k})}return{renewed:l,failed:c,skipped:u}}function WC(e,t){let r=ae(e);for(let n of Object.keys(r.workers||{})){let o=LC(e,n);if(!(!o||o.taskId!==t||!re(o.pid)||oe(o).status==="done"))return!0}return!1}var Ag=p(()=>{"use strict";H();We();z();_e();D();bu();ca();mr();Eg()});function FC(e){let t=e.baseCommit?.trim()??"",r=[];t&&t!==UC&&r.push({ref:t,source:"baseCommit"});let n=e.base?.trim()??"";n&&n!==UC&&r.push({ref:n,source:"base"}),r.push({ref:"origin/main",source:"origin/main"}),r.push({ref:"origin/HEAD",source:"origin/HEAD"});let o=new Set;for(let s of r)if(!o.has(s.ref)&&(o.add(s.ref),e.verifyRef(s.ref)))return{ref:s.ref,repaired:s.source!=="baseCommit",source:s.source};throw new Error(`worktree base ref unresolvable: baseCommit=${t||"<empty>"} base=${n||"<empty>"} \u2014 origin/main and origin/HEAD also failed verification`)}var UC,$C=p(()=>{"use strict";UC="unknown"});function vu(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function KC(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:vu(e)}function wJ(e){let t=(e.title??"").trim().toLowerCase();if(t.startsWith("fix:")||t.startsWith("repair:"))return!0;let r=(e.executorRef??"").toLowerCase();return!!(r.startsWith(RJ)||r.includes("repair")||r.includes("unblock"))}function SJ(e){let t={repairEnforceOriginalPr:!1,targetPrUrl:null,targetPrBranch:null};if(!e)return t;let r=e.match(vJ);if(!r?.[1])return t;try{let n=JSON.parse(r[1]),o=vu(String(n.targetPrUrl??n.target_pr_url??"")),s=vu(String(n.targetPrBranch??n.target_pr_branch??""));return{repairEnforceOriginalPr:n.repairEnforceOriginalPr===!0||n.repair_enforce_original_pr===!0||!!o,targetPrUrl:o?KC(o):null,targetPrBranch:s}}catch{return t}}function HC(e){if(!wJ(e))return null;let t=SJ(e.description),r=e.prUrl?KC(e.prUrl):null,n=t.targetPrUrl??r;return n?{targetPrUrl:n,targetPrBranch:t.targetPrBranch??vu(e.branch)}:null}function jC(e){return["Repair target PR policy:","- Work on the existing target PR branch \u2014 do not open a duplicate repair PR by default.",`- Canonical target PR: ${e.targetPrUrl}`,...e.targetPrBranch?[`- Canonical target branch: \`${e.targetPrBranch}\` (checkout is already on this branch).`]:[],`- Reconcile ${e.targetPrUrl} in structured finalResult.targetPrReconciliation.`,"- Only supersede the original when the branch is inaccessible: set supersedesOriginalTargetPr: true with reason and close/comment on the original PR."]}var vJ,RJ,Ig=p(()=>{"use strict";vJ=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/i,RJ="next-action-fix:"});var VC=p(()=>{"use strict"});function GC(e){let t=e.ownedPaths.length?`Owned paths: ${e.ownedPaths.join(", ")}. Do not edit outside these paths without stopping and reporting why.`:"Owned paths: unrestricted for this worker, but keep edits tightly scoped.",r=!!e.model?.toLowerCase().includes("haiku"),n=r?"compact":"full",o=r?e.planId?`Active planId: ${e.planId}`:"No planId on this worker.":e.planId?`Active planId: ${e.planId}${e.taskId?` \xB7 taskId: ${e.taskId}`:""}`:"No planId on this worker \u2014 still emit progress when you touch plan-scoped work.",s=[...Di(`worker.prompt.progress.${n}`).split(`
|
|
87
|
-
`),o],i=
|
|
88
|
-
`),a=
|
|
89
|
-
`);return["You are running under the Kynver AgentOS runtime.","Immediately state your plan before editing.",t,`Worktree: ${e.worktreePath}`,`Progress heartbeat file: ${e.heartbeatPath}`,"After each major step, append one JSON line to the heartbeat file with fields: ts, phase, summary, changedFiles, blocker.","Before exiting, append a terminal heartbeat with phase `complete` and a structured finalResult object; if you cannot complete, append blocker plus the recovery next action instead of exiting silently.","Final response must include files changed, verification commands, and unresolved risks.","Also include a JSON code block containing the structured finalResult object itself (not a wrapper): summary, verification (actual commands and observed results), scope, risks, and changedFiles. This is required even if the heartbeat path is read-only or a terminal heartbeat cannot be written. Never invent verification evidence; disclose unverified surfaces and blockers.",...
|
|
90
|
-
`),"",...s,"",...i,"",...a,"",...e.runtimeEnvelopeMarkdown?.trim()?[e.runtimeEnvelopeMarkdown.trim(),""]:[],...e.contextEnvelopeMarkdown?.trim()?[e.contextEnvelopeMarkdown.trim(),""]:[],...e.personaMarkdown?.trim()?[e.personaMarkdown.trim(),""]:[],...e.instructionPolicyMarkdown?.trim()?["Operating rules (from AgentOS memory policy):",e.instructionPolicyMarkdown.trim(),""]:[],...e.memoryQualityMarkdown?.trim()?[e.memoryQualityMarkdown.trim(),""]:[],...e.repairTargetPrUrl?[...
|
|
91
|
-
`)}var
|
|
92
|
-
${n}`,s=
|
|
93
|
-
`).map(t=>t.trim()).find(Boolean)??""}function
|
|
94
|
-
`)}function
|
|
146
|
+
${n}`;return VJ.some(s=>s.test(o))?"privileged":t.includes("provider:claude")||t.includes("deep_review")||t.includes("security")||t.includes("landing")||t.includes("review")||r.startsWith("land:")||t.includes("implementer")||t.includes("repair")||r.includes("implement")?"elevated":GJ.some(s=>s.test(o))?"low":"elevated"}function qJ(e){let t=ds(e.provider),r=e.escalatedFrom&&e.escalatedReason?`Escalated from ${e.escalatedFrom} (${e.escalatedReason}); using ${t.displayName} (${t.costTier} tier)`:`${t.displayName} selected for ${e.riskClass} orchestration (${t.costTier} tier, auth=${e.authSource})`;return{provider:e.provider,model:e.model,authSource:e.authSource,costTier:t.costTier,riskClass:e.riskClass,costRationale:r,routingRule:e.routingRule,escalatedFrom:e.escalatedFrom,escalatedReason:e.escalatedReason}}function YJ(e){let t=e.inventory??UC();return e.codexBinding?{...t,bindings:{...t.bindings,codex:e.codexBinding}}:t}function jn(e){let t=qJ({provider:e.providerId,model:e.model,authSource:e.binding.authSource,riskClass:e.riskClass,routingRule:e.routingRule,escalatedFrom:e.escalatedFrom,escalatedReason:e.escalatedReason});return{provider:e.providerId,model:e.model,rule:t.routingRule,audit:t}}function KC(e){let t=e.task??{},r=JJ(t),n=YJ({inventory:e.inventory,codexBinding:e.codexBinding??(e.inventory?null:fs())}),o=e.preferLowCost===!1?null:e.explicitProvider?.trim().toLowerCase(),s=e.explicitModel?.trim()||void 0,i=wr;if(o==="codex"||o==="provider:codex"){let c=n.bindings.codex;if(!c.ready){let u=xg({inventory:n,riskClass:r});return jn(u?{providerId:u.providerId,binding:u.binding,riskClass:r,routingRule:"orchestration:explicit_codex_unavailable_cost_aware",model:s,escalatedFrom:"codex",escalatedReason:c.note??"codex oauth not bound"}:{providerId:i,binding:n.bindings[i],riskClass:r,routingRule:"orchestration:codex_unavailable_escalate_cursor",model:s,escalatedFrom:"codex",escalatedReason:c.note??"codex oauth not bound"})}return jn({providerId:"codex",binding:c,riskClass:r,routingRule:"orchestration:explicit_codex",model:s})}if(o==="cursor"||o==="provider:cursor"){let c=n.bindings.cursor;if(c.ready)return jn({providerId:"cursor",binding:c,riskClass:r,routingRule:"orchestration:explicit_cursor",model:s})}if(o==="claude"||o==="provider:claude"){let c=n.bindings.claude;if(c.ready)return jn({providerId:"claude",binding:c,riskClass:r,routingRule:"orchestration:explicit_claude",model:s})}let a=xg({inventory:n,riskClass:r});if(a)return jn({providerId:a.providerId,binding:a.binding,riskClass:r,routingRule:`orchestration:cost_aware_${a.providerId}`,model:s,escalatedFrom:a.escalatedFrom,escalatedReason:a.escalatedReason});let l=n.bindings.codex;return jn({providerId:i,binding:n.bindings[i],riskClass:r,routingRule:l.ready?"orchestration:inventory_empty_default_cursor":"orchestration:codex_unavailable_default_cursor",model:s,...l.ready?{}:{escalatedFrom:"codex",escalatedReason:l.note??"codex oauth not bound"}})}var VJ,GJ,$C=p(()=>{"use strict";Bn();wg();du();wC();FC();VJ=[/\bprivileged\b/i,/\bproduction\s+db\b/i,/\bdb:push\b/i,/\bmigration\b/i,/\bdeploy\b/i,/\bsecrets?\b/i,/\bstripe\b/i,/\[require-approval\]/i,/\[operator-only\]/i],GJ=[/\borchestration\b/i,/\bplan[- ]?progress\b/i,/\bstatus\s+sync\b/i,/\bheartbeat\b/i,/\bboard[- ]?drain\b/i,/\bmaintenance\b/i,/\[orchestration:\s*low-risk\]/i]});function Lg(e){return`${JSON.stringify(e)}
|
|
147
|
+
`}function Bg(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,reason:"malformed_request",error:"request was not valid JSON",id:""}}if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,reason:"malformed_request",error:"request must be a JSON object",id:""};let r=t,n=typeof r.id=="string"?r.id:"";if(r.v!==1)return{ok:!1,reason:"unsupported_protocol",error:"unsupported protocol version (expected 1)",id:n};if(!n)return{ok:!1,reason:"malformed_request",error:"request id must be a non-empty string",id:""};if(r.op==="list_tools")return{ok:!0,request:{v:1,id:n,op:"list_tools"}};if(r.op==="call_tool"){if(typeof r.name!="string"||!r.name)return{ok:!1,reason:"malformed_request",error:"call_tool requires a tool name",id:n};let o=r.args&&typeof r.args=="object"&&!Array.isArray(r.args)?r.args:{};return{ok:!0,request:{v:1,id:n,op:"call_tool",name:r.name,args:o}}}return{ok:!1,reason:"malformed_request",error:"unknown op",id:n}}var Nt,Sr=p(()=>{"use strict";Nt="KYNVER_WORKER_BROKER_SOCKET"});import{unlinkSync as zJ,writeFileSync as XJ}from"node:fs";import QJ from"node:path";function ia(e){if(!e||e.length===0)return[...sa];let t=new Set;for(let r of e)for(let n of t2[r]??[])t.add(n);return sa.filter(r=>t.has(r))}function jC(e){return ia(e).map(t=>`mcp__${ye}__${t}`)}function o2(e){return r2.includes(e)}function Wg(e){return n2.includes(e)}function VC(e){return o2(e)&&!Wg(e)}function aa(e=process.env){let t=e[ZJ]?.trim().toLowerCase();return t?t==="1"||t==="true"||t==="yes"||t==="on":!0}function GC(e){return QJ.join(e,e2)}function JC(e){let t=GC(e.workerDir),r={mcpServers:{[ye]:{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Nt]:e.brokerSocketPath}}}};return XJ(t,`${JSON.stringify(r,null,2)}
|
|
148
|
+
`,{mode:384}),t}function ku(e){try{return zJ(GC(e)),!0}catch{return!1}}var ZJ,e2,ye,sa,HC,t2,r2,n2,ot=p(()=>{"use strict";Sr();ZJ="KYNVER_WORKER_MCP_TOOLS",e2="mcp-config.json",ye="kynver",sa=["agent_os_context_envelope","agent_os_search_memory","agent_os_search_skills","agent_os_get_skill","agent_os_progress_note"],HC=sa.map(e=>`mcp__${ye}__${e}`),t2={"worker.context":["agent_os_context_envelope"],"worker.memory.read":["agent_os_search_memory"],"worker.skills.read":["agent_os_search_skills","agent_os_get_skill"],"worker.progress.report":["agent_os_progress_note"]};r2=["claude","cursor","codex","openai-compatible","gemini","gemini-api"],n2=["openai-compatible","gemini-api"]});import{closeSync as qC,openSync as YC}from"node:fs";import{spawn as s2}from"node:child_process";function i2(e,t){let n=XC(e,t).at(-1);if(typeof n!="string"||!n.trim())throw new Error("claude provider refuses to spawn: worker prompt is empty after argv assembly (stdin is ignored \u2014 fix prompt delivery before retrying)")}function XC(e,t){return["--model",t,"-p","--verbose","--permission-mode",e.executionMode==="read_only"?"plan":"bypassPermissions","--output-format","stream-json","--include-partial-messages",...e.mcpConfigPath?["--mcp-config",e.mcpConfigPath,`--allowedTools=${(e.mcpAllowedTools?.length?e.mcpAllowedTools:HC).join(",")}`]:[],"--",e.prompt]}var qr,la,zC,Ug=p(()=>{"use strict";lr();Fn();M();qe();$t();ot();qr="claude-sonnet-4-6",la="claude-opus-4-8";zC={name:"claude",defaultModel:qr,preflightModel(e){return Cg(e,qr)},start(e){let t=Cg(e.model,qr);if(!t.ok)throw new Error(`claude provider model preflight failed: ${t.note}`);let r=t.model;i2(e,r);let[n,o]=ae("claude",XC(e,r)),s=YC(e.stdoutPath,"a"),i=YC(e.stderrPath,"a"),a=["ignore",s,i],[l,c]=tt(n,o,e.workerDir),u=s2(l,c,z({cwd:e.worktreePath,detached:Re(),stdio:a,env:gt(process.env,{reviewWorker:e.reviewWorker})}));if(qC(s),qC(i),!u.pid)throw new Error("failed to spawn claude worker process (is the `claude` CLI on PATH?)");return u.unref(),{pid:u.pid,model:r}}}});import{closeSync as QC,openSync as ZC}from"node:fs";import{spawn as a2}from"node:child_process";function l2(e,t){return gt({...process.env,CI:"1",NO_COLOR:"1",HERMES_ACCEPT_HOOKS:process.env.HERMES_ACCEPT_HOOKS??"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function c2(e,t){let r=process.env.KYNVER_HERMES_CODEX_MAX_TURNS?.trim()||"40";return["chat","-q",t,"--provider","openai-codex","-m",e,"-Q","--accept-hooks","--max-turns",r,"--toolsets","hermes-cli"]}var Fg,eE,tE=p(()=>{"use strict";lr();Fn();M();qe();Un();$t();Fg=process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||"gpt-5.5";eE={name:"hermes-codex",defaultModel:Fg,preflightModel(e){return ms(e,Fg)},start(e){if(e.executionMode==="read_only")throw new Error("hermes-codex provider cannot enforce read_only execution mode (no sandbox flag); route read_only tasks to the direct codex exec path or another provider");let t=ms(e.model,Fg);if(!t.ok)throw new Error(`hermes-codex provider model preflight failed: ${t.note}`);let r=t.model,n=mt("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),[o,s]=ae(n,c2(r,e.prompt)),i=ZC(e.stdoutPath,"a"),a=ZC(e.stderrPath,"a"),l=["ignore",i,a],[c,u]=tt(o,s,e.workerDir),d=a2(c,u,z({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:l,env:l2(e.reviewWorker,e.codexHome)}));if(QC(i),QC(a),!d.pid)throw new Error(`failed to spawn Hermes openai-codex worker (is \`${n}\` on PATH? run \`hermes auth status openai-codex\`)`);return d.unref(),{pid:d.pid,model:r}}}});function p2(e=process.env){return e[u2]?.trim().toLowerCase()==="elevated"?"elevated":d2}function bu(e=process.platform,t=process.env){return e!=="win32"?[]:["-c",`windows.sandbox="${p2(t)}"`]}var u2,d2,Kg=p(()=>{"use strict";u2="KYNVER_CODEX_WINDOWS_SANDBOX",d2="unelevated"});import{closeSync as rE,existsSync as f2,openSync as nE}from"node:fs";import{spawn as $g}from"node:child_process";function m2(){return process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||"gpt-5.5"}function xr(){return process.env.KYNVER_CODEX_BIN?.trim()||process.env.CODEX_BIN?.trim()||"codex"}function g2(e,t){return gt({...process.env,CI:"1",NO_COLOR:"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function h2(e,t,r,n=process.platform,o=process.env){return["--ask-for-approval","never","exec",...bu(n,o),"--json","--sandbox",r==="read_only"?"read-only":"workspace-write","--model",e,t]}function y2(e,t,r,n){if(process.platform==="win32"){let[l,c]=ae(e,t);return $g(l,c,r)}if(!f2("/usr/bin/script")){let[l,c]=tt(e,t,n);return $g(l,c,r)}let s=[e,...t].map(l=>`'${l.replace(/'/g,"'\\''")}'`).join(" "),[i,a]=tt("script",["-qfc",s,"/dev/null"],n);return $g(i,a,r)}var _r,oE,Vn=p(()=>{"use strict";lr();Fn();M();qe();du();$t();tE();Kg();_r=m2();oE={name:"codex",defaultModel:_r,preflightModel(e){return ms(e,_r)},start(e){if(fs().path==="hermes_openai_codex"&&e.executionMode!=="read_only")return eE.start(e);let r=ms(e.model,_r);if(!r.ok)throw new Error(`codex provider model preflight failed: ${r.note}`);let n=r.model,o=nE(e.stdoutPath,"a"),s=nE(e.stderrPath,"a"),i=["ignore",o,s],a=xr(),l=h2(n,e.prompt,e.executionMode),c;try{c=y2(a,l,z({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:i,env:g2(e.reviewWorker,e.codexHome)}),e.workerDir)}finally{rE(o),rE(s)}if(!c.pid)throw new Error(`failed to spawn Codex worker (is \`${a}\` on PATH? run \`codex login\` or set CODEX_API_KEY)`);return c.unref(),{pid:c.pid,model:n}}}});import{existsSync as vu}from"node:fs";import Gn from"node:path";import{fileURLToPath as k2}from"node:url";function b2(e,t){let r=Gn.resolve(e);for(;;){let n=Gn.join(r,t);if(vu(n))return n;let o=Gn.dirname(r);if(o===r)return null;r=o}}function v2(e){return b2(e,Gn.join("node_modules",".bin","tsx"))??"npx"}function Hg(e,t){if(e.endsWith(".ts")){let r=v2(Gn.dirname(e));return{command:r,argsPrefix:r==="npx"?["tsx",e]:[e],cliPath:e}}return{command:t,argsPrefix:[e],cliPath:e}}function Ru(e){if(e.explicitCliPath)return vu(e.explicitCliPath)?Hg(e.explicitCliPath,e.nodeExecutable):null;let t=k2(new URL(".",e.importMetaUrl)),r=Gn.join(t,"cli.js");if(vu(r))return Hg(r,e.nodeExecutable);let n=Gn.join(t,"cli.ts");return vu(n)?Hg(n,e.nodeExecutable):null}var jg=p(()=>{"use strict"});function w2(e){return`/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/worker`}async function ca(e,t,r){let n=await e.fetchImpl(`${e.apiBaseUrl}${t}`,{method:r?.method??"GET",headers:{[R2]:e.token,...r?{"Content-Type":"application/json"}:{}},...r?{body:JSON.stringify(r.body)}:{}});if(!n.ok)throw new Error(`request failed (${n.status})`);return n.json()}function ua(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function wu(e,t,r){let n=w2(e);switch(t){case"agent_os_context_envelope":{let o=new URLSearchParams({task:e.taskId}),s=ua(r.memoryQuery);s&&o.set("memoryQuery",s);let i=ua(r.mode);return i&&o.set("mode",i),ca(e,`${n}/context-envelope?${o.toString()}`)}case"agent_os_search_memory":{let o=new URLSearchParams({q:String(r.query??"")});return typeof r.k=="number"&&o.set("k",String(r.k)),ca(e,`${n}/memory-search?${o.toString()}`)}case"agent_os_search_skills":{let o=new URLSearchParams,s=ua(r.query);s&&o.set("q",s),typeof r.limit=="number"&&o.set("limit",String(r.limit));let i=o.toString();return ca(e,`${n}/skills${i?`?${i}`:""}`)}case"agent_os_get_skill":return ca(e,`${n}/skills/${encodeURIComponent(String(r.slug??""))}`);case"agent_os_progress_note":return ca(e,`${n}/progress-note`,{method:"POST",body:{note:String(r.note??""),...r.kind==="blocked"?{kind:"blocked"}:{},...ua(r.eventKey)?{eventKey:ua(r.eventKey)}:{}}})}}function bs(e){return sa.includes(e)}var R2,da,Su=p(()=>{"use strict";ot();R2="X-Kynver-Job-Token",da={agent_os_context_envelope:{name:"agent_os_context_envelope",description:"Fetch the context envelope for YOUR OWN task: goal/plan/task summaries, relevant memory, and recent session context. Optional memoryQuery focuses the memory portion.",inputSchema:{type:"object",properties:{memoryQuery:{type:"string",description:"Focus the memory portion of the envelope."},mode:{type:"string",description:"Envelope mode hint."}},additionalProperties:!1}},agent_os_search_memory:{name:"agent_os_search_memory",description:"Semantic search over the workspace's long-term memory. Returns a bounded top-N of relevant entries.",inputSchema:{type:"object",properties:{query:{type:"string",description:"What to search for."},k:{type:"integer",minimum:1,maximum:20,description:"How many entries to return."}},required:["query"],additionalProperties:!1}},agent_os_search_skills:{name:"agent_os_search_skills",description:"Search the workspace's skill library (bounded, metadata-only index). Use agent_os_get_skill to fetch one full skill by slug.",inputSchema:{type:"object",properties:{query:{type:"string"},limit:{type:"integer",minimum:1,maximum:25}},additionalProperties:!1}},agent_os_get_skill:{name:"agent_os_get_skill",description:"Fetch ONE full skill (including instructions) by slug.",inputSchema:{type:"object",properties:{slug:{type:"string"}},required:["slug"],additionalProperties:!1}},agent_os_progress_note:{name:"agent_os_progress_note",description:"Append a progress or blocker note to YOUR OWN task's journal. kind: 'progress' (default) or 'blocked'.",inputSchema:{type:"object",properties:{note:{type:"string"},kind:{type:"string",enum:["progress","blocked"]},eventKey:{type:"string"}},required:["note"],additionalProperties:!1}}}});function pa(e){return ia(e).filter(bs).map(t=>{let r=da[t];return{type:"function",function:{name:r.name,description:r.description,parameters:r.inputSchema}}})}var _u=p(()=>{"use strict";Su();ot()});import{closeSync as sE,openSync as iE}from"node:fs";import S2 from"node:path";import{fileURLToPath as _2}from"node:url";import{spawn as x2}from"node:child_process";function Vg(e=process.env){return e.KYNVER_WORKER_MODEL?.trim()||void 0}function E2(e=process.env){let t=e.KYNVER_WORKER_BASE_URL?.trim();if(!t)throw new fa(`the "openai-compatible" worker provider requires KYNVER_WORKER_BASE_URL on the daemon host \u2014 point it at any OpenAI-compatible chat-completions endpoint (e.g. http://localhost:11434/v1 for Ollama, http://localhost:8000/v1 for vLLM, or your gateway's /v1 URL). Set KYNVER_WORKER_API_KEY too when the endpoint requires auth.`);let r;try{r=new URL(t)}catch{throw new fa(`KYNVER_WORKER_BASE_URL is not a valid URL: "${t}" \u2014 expected e.g. http://localhost:11434/v1`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new fa(`KYNVER_WORKER_BASE_URL must be http(s), got "${r.protocol}//" \u2014 e.g. http://localhost:11434/v1`);let n=Number(e.KYNVER_WORKER_TIMEOUT_MS??""),o=Number.isFinite(n)&&n>0?Math.floor(n):C2;return{baseUrl:t.replace(/\/+$/,""),...e.KYNVER_WORKER_API_KEY?.trim()?{apiKey:e.KYNVER_WORKER_API_KEY.trim()}:{},timeoutMs:o}}function xu(e,t,r,n){return{url:`${e.baseUrl}/chat/completions`,headers:{"content-type":"application/json",...e.apiKey?{authorization:`Bearer ${e.apiKey}`}:{}},body:{model:t,temperature:0,stream:!1,messages:[{role:"system",content:A2},{role:"user",content:r}],...n&&n.length?{tools:n,tool_choice:"auto"}:{}}}}function P2(){let e=_2(new URL(".",import.meta.url)),t=import.meta.url.endsWith(".ts"),r=S2.join(e,t?"openai-compatible-runner.ts":"openai-compatible-runner.js"),n=Ru({importMetaUrl:import.meta.url,explicitCliPath:r,nodeExecutable:process.execPath});if(!n)throw new Error(`openai-compatible runner script not found at ${r} \u2014 is the @kynver-app/runtime install complete?`);return{command:n.command,argsPrefix:n.argsPrefix}}function I2(e,t,r){let n=e.workerToolGrant,o=n?pa(n.capabilities):void 0;return{provider:Jn,model:r,request:xu(t,r,e.prompt,o),timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}function Cu(e,t,r){let n=P2(),o=iE(e.stdoutPath,"a"),s=iE(e.stderrPath,"a"),i=["pipe",o,s],[a,l]=tt(n.command,n.argsPrefix,e.workerDir),c=x2(a,l,z({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:i,env:gt(process.env,{reviewWorker:e.reviewWorker})}));if(sE(o),sE(s),!c.pid)throw new Error(`failed to spawn ${t.provider} worker runner (node executable unavailable?)`);try{c.stdin?.on("error",()=>{}),c.stdin?.write(JSON.stringify(t)),c.stdin?.end()}catch(u){throw new Error(`failed to hand request config to ${t.provider} runner: ${u.message}`)}return c.unref(),{pid:c.pid,model:r}}var Jn,C2,fa,A2,aE,ma=p(()=>{"use strict";lr();Fn();M();jg();$t();_u();Jn="openai-compatible",C2=600*1e3;fa=class extends Error{};A2="You are a Kynver harness worker executing one work unit end to end. Follow the task instructions exactly and produce the complete deliverable (analysis, answer, or unified diff as the task requires) in a single response. Be precise and complete \u2014 your response is recorded verbatim as the work unit's final result.";aE={name:Jn,get defaultModel(){return Vg()},preflightModel(e){return Eg(e,Vg())},start(e){let t=Eg(e.model,Vg());if(!t.ok)throw new Error(`openai-compatible provider model preflight failed: ${t.note}`);let r=t.model,n=E2(process.env),o=I2(e,n,r);return Cu(e,o,r)}}});import O2 from"node:path";function ht(e=process.env){return e.KYNVER_GEMINI_BIN?.trim()||e.GEMINI_BIN?.trim()||"agy"}function vs(e){let t=O2.basename(e).toLowerCase().replace(/\.cmd$/i,"").replace(/\.exe$/i,"");return t==="agy"||t==="antigravity"?"antigravity":"gemini"}function lE(e){return e.requested&&/-(?:high|medium|low)$/i.test(e.requested)?e.requested:e.model}function cE(e){let t=e.trim().toLowerCase();return!t||T2.has(t)?[]:["--model",e.trim()]}function Eu(e,t){return[...cE(t),"--output-format","stream-json",...e.executionMode==="read_only"?[]:["--dangerously-skip-permissions"],"--prompt",e.prompt]}function uE(e,t){return["--model",t,"--approval-mode",e.executionMode==="read_only"?"plan":"yolo","--output-format","stream-json","--skip-trust",...e.mcpConfigPath?["--allowed-mcp-server-names",ye]:[],"--prompt",e.prompt]}var T2,qn=p(()=>{"use strict";ot();T2=new Set(["gemini-2.5-pro","gemini-2.5-flash","auto","pro","flash","flash-lite"])});import{closeSync as dE,openSync as pE}from"node:fs";import{spawn as N2}from"node:child_process";function Ke(e=process.env){return e.KYNVER_GEMINI_DEFAULT_MODEL?.trim()||"gemini-2.5-pro"}function D2(e,t){return gt({...process.env,CI:"1",NO_COLOR:"1",GEMINI_CLI_TRUST_WORKSPACE:"true",...t?{GEMINI_CLI_HOME:t}:{}},{reviewWorker:e})}var jt,fE,ga=p(()=>{"use strict";lr();Fn();M();qe();qn();$t();jt="gemini";fE={name:jt,get defaultModel(){return Ke()},preflightModel(e){return gs(e,Ke())},start(e){let t=gs(e.model,Ke());if(!t.ok)throw new Error(`gemini provider model preflight failed: ${t.note}`);let r=ht(),n=vs(r),o=n==="antigravity"?lE(t):t.model,s=n==="antigravity"?Eu(e,o):uE(e,o),[i,a]=ae(r,s),l=pE(e.stdoutPath,"a"),c=pE(e.stderrPath,"a"),u=["ignore",l,c],[d,f]=tt(i,a,e.workerDir),m=N2(d,f,z({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:u,env:D2(e.reviewWorker,n==="gemini"?e.geminiCliHome:void 0)}));if(dE(l),dE(c),!m.pid)throw new Error(`failed to spawn Google Antigravity worker (is \`${r}\` on PATH? install Google Antigravity and run \`agy\` once to sign in`+(n==="antigravity"?'; GEMINI_API_KEY is used only when ~/.gemini/antigravity-cli/settings.json sets "modelProvider": "gemini")':", or set GEMINI_API_KEY)"));return m.unref(),{pid:m.pid,model:o}}}});function L2(e=process.env){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()||void 0}function B2(e=process.env){let t=L2(e);if(!t)throw new ha('the "gemini-api" worker provider requires KYNVER_GEMINI_API_KEY or GEMINI_API_KEY on the daemon host \u2014 create a key at https://aistudio.google.com/apikey. To use Google Antigravity instead, set workerProvider / --provider gemini and run `agy` once to sign in.');let r=e.KYNVER_GEMINI_BASE_URL?.trim()||mE,n;try{n=new URL(r)}catch{throw new ha(`KYNVER_GEMINI_BASE_URL is not a valid URL: "${r}" \u2014 expected e.g. ${mE}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new ha(`KYNVER_GEMINI_BASE_URL must be http(s), got "${n.protocol}//"`);let o=Number(e.KYNVER_WORKER_TIMEOUT_MS??""),s=Number.isFinite(o)&&o>0?Math.floor(o):M2;return{baseUrl:r.replace(/\/+$/,""),apiKey:t,timeoutMs:s}}function W2(e,t,r){let n=e.workerToolGrant,o=n?pa(n.capabilities):void 0,s=xu(t,r,e.prompt,o);return{provider:Vt,model:r,request:s,timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}var Vt,mE,M2,ha,gE,Gg=p(()=>{"use strict";ma();_u();$t();ga();Vt="gemini-api",mE="https://generativelanguage.googleapis.com/v1beta/openai",M2=600*1e3,ha=class extends Error{};gE={name:Vt,get defaultModel(){return Ke()},preflightModel(e){return gs(e,Ke())},start(e){let t=gs(e.model,Ke());if(!t.ok)throw new Error(`gemini-api provider model preflight failed: ${t.note}`);let r=t.model,n=B2(process.env),o=W2(e,n,r);return Cu(e,o,r)}}});function Ye(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function F2(e){if(!e)return;let t=Ye(e,"workerModelOverride")||Ye(e,"modelOverride");return t||`${Ye(e,"title")}
|
|
149
|
+
${Ye(e,"description")}
|
|
150
|
+
${Ye(e,"executorRef")}`.match(/\[(?:worker-)?model:\s*([^\]\n]+)\]/i)?.[1]?.trim()||void 0}function hE(e){return e.toLowerCase()}function qg(e=P()){let t=e.defaultModel?.trim();if(t)return t;let r=process.env.KYNVER_DEFAULT_MODEL?.trim();return r||U2}function Au(e){let t=(e??"").toLowerCase();return!t||t.includes("composer")||t.includes("cursor")||t.includes("codex")||t.startsWith("gpt-")||t.startsWith("gpt5")?"cursor":/^claude[-_]/i.test(t)||/^(?:opus|sonnet|haiku)\b/i.test(t)?"claude":t.startsWith("gemini-")?jt:"cursor"}function K2(e,t){let r=e.trim().toLowerCase(),n=t?.trim();return r==="cursor"?{model:au,provider:"cursor",rule:n&&n!=="cursor"?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="claude"||r==="anthropic"?{model:qr,provider:"claude",rule:n&&n!=="claude"?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini"||r==="google"?{model:Ke(),provider:jt,rule:n&&n!==jt?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini-api"||r==="gemini_api"||r==="google-api"?{model:Ke(),provider:Vt,rule:n&&n!==Vt?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:null}function yE(e,t){return!!(e.includes("deep")&&e.includes("review")||e.includes("security")||e.includes("plan_author")||e.includes("plan-author")||t.includes("deep review")||t.includes("security review")||e.includes("plan")&&!e.includes("review")&&(e.includes("author")||e.includes("strategy")))}function kE(e,t,r){return $2.has(e)?la:t.includes("review")||/^review[\s:]/.test(r)||r.includes("critique")?la:qr}function H2(e){let t=hE(Ye(e,"executorRef")),r=Ye(e,"title").toLowerCase(),n=Ye(e,"priority")||"normal",o=hE(Ye(e,"roleLane"));if(t.includes("provider:claude")||t.startsWith("claude:")){let i=kE(o,t,r);return{provider:"claude",model:i,rule:i===la?"factory:claude_review":"factory:claude_implementation"}}if(t.includes("provider:codex")||t.startsWith("codex:"))return{provider:"codex",model:_r,rule:"lane:codex_orchestration"};if(t.includes("provider:chatgpt")||t.startsWith("chatgpt:")||t.includes("provider:gpt")||t.startsWith("gpt:")){let i=ft(Ye(e,"executorRef"));return{provider:"codex",...i?.model?{model:i.model}:{model:_r},rule:"lane:codex_orchestration"}}if(t.includes("provider:openai")||t.startsWith("openai-compatible:")){let i=ft(Ye(e,"executorRef"));return{provider:Jn,...i?.model?{model:i.model}:{},rule:"lane:openai_compatible"}}if(t.includes("provider:gemini-api")||t.startsWith("gemini-api:")){let i=ft(Ye(e,"executorRef"));return{provider:Vt,...i?.model?{model:i.model}:{model:Ke()},rule:"lane:gemini_api"}}if(t.includes("provider:gemini")||t.startsWith("gemini:")){let i=ft(Ye(e,"executorRef"));return{provider:jt,...i?.model?{model:i.model}:{model:Ke()},rule:"lane:gemini"}}if(t.includes("cursor")||t.includes("composer")||t.includes("copilot")||o==="implementer"||o==="repair_implementer")return{provider:"cursor",rule:"lane:implementation"};if(t.includes("codex"))return{provider:"codex",model:_r,rule:"lane:codex_orchestration"};if(t.includes("landing")||r.startsWith("land:")||r.includes(" merge"))return{provider:"cursor",rule:"lane:landing"};if(t.includes("review")||/^review[\s:]/.test(r)||o.includes("review"))return yE(t,r)||o==="deep_reviewer"?{provider:"cursor",rule:"lane:deep_review"}:{provider:"cursor",rule:"lane:review"};if(yE(t,r)||o==="plan_author")return{provider:"cursor",rule:"lane:planning"};if(n==="critical")return{provider:"cursor",rule:"priority:critical"};if(n==="high")return{provider:"cursor",rule:"priority:high"};if(n==="low")return{provider:"cursor",rule:"priority:low"};let s=qg();return{model:s,provider:Au(s),rule:"default:global"}}function j2(e){return e?ft(Ye(e,"executorRef")):null}function V2(e){switch(je(e)){case jt:case Vt:return Ke();case"claude":return qr;case"codex":return _r;case"cursor":return au;default:return}}function vE(e,t,r){let n=je(t);return n===e.provider&&e.rule===r?e:{...e,provider:n,model:V2(n)??e.model,rule:r}}function G2(e,t){let r=t?.trim();return!r||e.rule.startsWith("explicit:")&&e.rule!==Jg?e:vE(e,r,Jg)}function J2(e,t){if(t.explicitProvider?.trim()||Rg(t.task))return e;let r=t.configuredProvider?.trim();if(!r)return e;let n=je(r);return n===wr||n===e.provider?e:vE(e,n,bE)}function Pu(e){let t,r=j2(e.task),n=e.explicitModel?.trim()?void 0:r?.model?.trim(),o=!e.explicitProvider?.trim()&&r?.provider?.trim()?r.provider.trim():void 0;if(e.explicitModel?.trim()){let l=e.explicitModel.trim(),c=K2(l,e.explicitProvider);c?t=c:t={model:l,provider:e.explicitProvider?.trim()||Au(l),rule:"explicit:cli",requestedModel:l}}else if(n)t={model:n,provider:o||Au(n),rule:r?.rule??"executor_ref:model",requestedModel:n};else if(e.task&&iu(e.task)){let l=F2(e.task),c,u;if(l)c=l,u="task:provider_override";else{let d=typeof e.task.roleLane=="string"?e.task.roleLane.toLowerCase():"",f=typeof e.task.executorRef=="string"?e.task.executorRef.toLowerCase():"",m=typeof e.task.title=="string"?e.task.title.toLowerCase():"";c=kE(d,f,m),u=c===la?"factory:claude_review":"factory:claude_implementation"}t={model:c,provider:"claude",rule:u,requestedModel:c}}else if(e.task&&Object.keys(e.task).length>0){let l=H2(e.task);t={...l,requestedModel:l.model}}else{let l=qg();t={model:l,provider:e.explicitProvider?.trim()||Au(l),rule:"default:global",requestedModel:l}}t=G2(t,e.explicitProvider),t=J2(t,{explicitProvider:e.explicitProvider,task:e.task,configuredProvider:e.configuredProvider});let s=!!e.configuredProvider?.trim()&&je(e.configuredProvider)!==wr&&t.rule==="config:worker_provider",i=lC({routing:t,task:e.task,explicitProvider:e.explicitProvider??(s?t.provider:void 0),explicitProviderIsOperatorOverride:!!e.explicitProviderIsOperatorOverride||s});if(!e.task||Object.keys(e.task).length===0||i.rule==="explicit:model_provider_alias"||i.rule==="explicit:model_provider_alias_overrode_provider"||i.rule==="explicit:cli"||i.rule===Jg||i.rule===bE||Rr(i.provider)&&(e.explicitProviderIsOperatorOverride||iu(e.task))||i.provider===Jn||i.provider===jt||i.provider===Vt||i.provider==="codex")return i;let a=KC({task:e.task,explicitProvider:e.explicitProvider??i.provider,explicitModel:i.model,inventory:e.orchestrationInventory??void 0});return{provider:a.provider,model:a.provider==="codex"?a.model??i.model??_r:i.model,rule:a.rule,requestedModel:i.requestedModel,orchestrationAudit:a.audit}}function RE(e,t,r){return e||t||r||qg()||qr}var U2,au,$2,Jg,bE,lu=p(()=>{"use strict";$();su();$C();Ug();Vn();ma();ga();Gg();Bn();U2="claude-sonnet-4-6",au="composer-2.5";$2=new Set(["report_reviewer","deep_reviewer","plan_reviewer"]);Jg="explicit:cli_provider",bE="config:worker_provider"});function q2(e){let t=e?.executorRef;return typeof t=="string"?t.trim():""}function wE(e){return e?.trim()||void 0}function SE(e){let t=q2(e.task),r=ft(t),n=e.explicitProvider?.trim().toLowerCase(),o=wE(e.explicitModel??void 0),s=n||r?.provider,i=o||r?.model,a=n||o?"cli":r?.rule??"none";if(!s&&!i)return{ok:!0};!s&&i&&(/^claude[-_]/i.test(i)||/^(?:opus|sonnet|haiku)\b/i.test(i))&&(s="claude");let l=e.routing.provider,c=wE(e.routing.model),u={provider:l,model:c,rule:e.routing.rule};return s&&s!=="cursor"||t&&aC(t)||n&&n!=="cursor"?l==="cursor"?{ok:!1,error:`model_routing_mismatch: requested ${s??"non-cursor"}${i?` model=${i}`:""} (${a}) but routing resolved to cursor (${e.routing.rule})`,requested:{provider:s,model:i,source:a},resolved:u}:i&&c&&i!==c&&!Rr(l)?{ok:!1,error:`model_routing_mismatch: requested model=${i} (${a}) but routing resolved model=${c} (${e.routing.rule})`,requested:{provider:s,model:i,source:a},resolved:u}:{ok:!0,requested:{provider:s,model:i,source:a},resolved:u}:{ok:!0,resolved:u}}var _E=p(()=>{"use strict";su();Bn()});function xE(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function CE(){return{maxTaskAttempts:xE(process.env.KYNVER_MAX_TASK_ATTEMPTS,Math.floor(is("harness.maxTaskAttempts",4))),dispatchCooldownMs:xE(process.env.KYNVER_DISPATCH_COOLDOWN_MS,Math.floor(is("harness.dispatchCooldownMs",5e3)))}}var EE=p(()=>{"use strict";Gr()});function zg(e){return e?.trim()?e.trim():null}function Y2(e){let t=zg(e);if(!t?.startsWith(Yg))return null;let r=t.slice(Yg.length),n=r.indexOf(AE);return n>=0?r.slice(0,n).trim()||null:r.trim()||null}function ya(e,t){let r=e.trim(),n=t.trim();return`${Yg}${r}${AE}${n}`}function z2(e,t){let r=zg(t);return r?Y2(e)===r:!1}function Iu(e){let t=zg(e.workerLeaseOwner);return t&&z2(t,e.runId)?t:ya(e.runId,e.runnerId)}var Yg,AE,ka=p(()=>{"use strict";Yg="kynver-harness:",AE="@runner:"});async function Ou(e){let t=new Map,r=e.agentOsId?.trim();if(!r||e.taskIds.length===0)return t;let n=pe(e.baseUrl);try{let o=await me(e.secret,r,{baseUrl:n}),s=`${n}/api/agent-os/by-id/${encodeURIComponent(r)}/harness/monitor/task-leases`,i=await de(s,o,{taskIds:[...new Set(e.taskIds)]},{agentOsId:r,baseUrl:n});if(!i.ok||!i.response||typeof i.response!="object")return t;let a=i.response.tasks;if(!Array.isArray(a))return t;for(let l of a)l?.taskId&&t.set(l.taskId,l)}catch{}return t}var Xg=p(()=>{"use strict";$();Fe()});async function Tu(e){let t=e.worker.leaseOwner?.trim()??null,r=e.worker.leaseToken?.trim()??null;if(r)return{leaseOwner:t,leaseToken:r};let n=e.worker.taskId?.trim();if(!n)return{leaseOwner:t,leaseToken:null};let s=(await Ou({agentOsId:e.agentOsId,taskIds:[n],baseUrl:e.baseUrl,secret:e.secret})).get(n),i=s?.leaseOwner?.trim()??null,a=s?.leaseToken?.trim()??null;if(!a)return{leaseOwner:t??i,leaseToken:null};let l=t??i;return(!e.worker.leaseToken||e.worker.leaseToken!==a)&&X(e.worker.runId,{...e.worker,...l?{leaseOwner:l}:{},leaseToken:a}),{leaseOwner:l,leaseToken:a}}var Qg=p(()=>{"use strict";Xg();Y()});import X2 from"node:path";function PE(e,t){return F(X2.join(j(e),"workers",B(t),"worker.json"),void 0)}async function IE(e,t){let r=ne(e),n=String(t.agentOsId||"");if(!n)return{renewed:[],failed:[],skipped:[]};let o=pe(t.baseUrl?String(t.baseUrl):void 0),s=await me(t.secret?String(t.secret):void 0,n,{baseUrl:o}),i=Number(t.leaseMs)>0?Math.floor(Number(t.leaseMs)):eh,a=De({runId:e}).runnerId,l=[],c=[],u=[];for(let d of Object.keys(r.workers||{})){let f=PE(e,d);if(!f?.taskId||!f.agentOsId){u.push(d);continue}if(!re(f.pid)){u.push(d);continue}if(ie(f).status==="done"){u.push(d);continue}let g=Iu({runId:e,workerLeaseOwner:f.leaseOwner??null,runnerId:a}),h=await Tu({worker:f,agentOsId:n,baseUrl:o,secret:s}),y=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/${encodeURIComponent(f.taskId)}/renew-lease`,v=await de(y,s,{leaseOwner:h.leaseOwner??g,leaseDurationMs:i,...h.leaseToken?{leaseToken:h.leaseToken}:{}},{agentOsId:n,baseUrl:o});if(v.ok){l.push(d);continue}let k=v.response&&typeof v.response=="object"&&"reason"in v.response?String(v.response.reason??`http ${v.status}`):`http ${v.status}`;c.push({worker:d,reason:k})}return{renewed:l,failed:c,skipped:u}}function OE(e,t){let r=ne(e);for(let n of Object.keys(r.workers||{})){let o=PE(e,n);if(!(!o||o.taskId!==t||!re(o.pid)||ie(o).status==="done"))return!0}return!1}var Zg=p(()=>{"use strict";$();Fe();Y();Ce();M();Nu();ka();yr();Qg()});import Q2 from"node:path";function TE(e){return typeof e?.noRestartAt=="string"&&e.noRestartAt.trim().length>0}function NE(e,t,r,n){return TE(t)||(t.noRestartAt=new Date().toISOString(),t.noRestartSource=r,n&&(t.noRestartReason=n),t.steerRestartRequired=!1,X(e,t)),t}function Du(e,t={}){let r=t.isAlive??re,n=t.kill??fe,o=t.sleep??Ll;return!e||!r(e)?null:(n(e,"SIGTERM"),o(1e3),r(e)?(n(e,"SIGKILL"),"SIGKILL"):"SIGTERM")}function th(e,t,r,n,o={}){NE(e,t,r,n);let s=Du(t.pid,o),i=Du(t.completionSidecarPid,o);return{workerSignal:s,sidecarSignal:i}}function DE(e,t,r={}){let n=r.isAlive??re,o=ne(e),s=[];for(let i of Object.keys(o.workers||{})){if(r.except&&i===r.except)continue;let a=F(Q2.join(j(o.id),"workers",B(i),"worker.json"),void 0);!a||a.taskId!==t||n(a.pid)||!a.completionSidecarPid||!n(a.completionSidecarPid)||(Du(a.completionSidecarPid,r),a.completionSidecarPid=void 0,a.watcherClearedForRelaunchAt=new Date().toISOString(),X(o.id,a),s.push(i))}return s}function Z2(e=process.env){let t=String(e.KYNVER_ALLOW_UNWATCHED_WORKER??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function ME(e,t,r,n={}){if(!Z2(n.env))throw th(e,t,"watcher_attach_failed",r,n.deps),t.status="failed",X(e,t),new Error(`watcher_attach_failed: ${r}; worker stopped instead of running unwatched`)}var Rs=p(()=>{"use strict";Y();M()});function BE(e){let t=e.baseCommit?.trim()??"",r=[];t&&t!==LE&&r.push({ref:t,source:"baseCommit"});let n=e.base?.trim()??"";n&&n!==LE&&r.push({ref:n,source:"base"}),r.push({ref:"origin/main",source:"origin/main"}),r.push({ref:"origin/HEAD",source:"origin/HEAD"});let o=new Set;for(let s of r)if(!o.has(s.ref)&&(o.add(s.ref),e.verifyRef(s.ref)))return{ref:s.ref,repaired:s.source!=="baseCommit",source:s.source};throw new Error(`worktree base ref unresolvable: baseCommit=${t||"<empty>"} base=${n||"<empty>"} \u2014 origin/main and origin/HEAD also failed verification`)}var LE,WE=p(()=>{"use strict";LE="unknown"});function Mu(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function UE(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:Mu(e)}function rq(e){let t=(e.title??"").trim().toLowerCase();if(t.startsWith("fix:")||t.startsWith("repair:"))return!0;let r=(e.executorRef??"").toLowerCase();return!!(r.startsWith(tq)||r.includes("repair")||r.includes("unblock"))}function nq(e){let t={repairEnforceOriginalPr:!1,targetPrUrl:null,targetPrBranch:null};if(!e)return t;let r=e.match(eq);if(!r?.[1])return t;try{let n=JSON.parse(r[1]),o=Mu(String(n.targetPrUrl??n.target_pr_url??"")),s=Mu(String(n.targetPrBranch??n.target_pr_branch??""));return{repairEnforceOriginalPr:n.repairEnforceOriginalPr===!0||n.repair_enforce_original_pr===!0||!!o,targetPrUrl:o?UE(o):null,targetPrBranch:s}}catch{return t}}function FE(e){if(!rq(e))return null;let t=nq(e.description),r=e.prUrl?UE(e.prUrl):null,n=t.targetPrUrl??r;return n?{targetPrUrl:n,targetPrBranch:t.targetPrBranch??Mu(e.branch)}:null}function KE(e){return["Repair target PR policy:","- Work on the existing target PR branch \u2014 do not open a duplicate repair PR by default.",`- Canonical target PR: ${e.targetPrUrl}`,...e.targetPrBranch?[`- Canonical target branch: \`${e.targetPrBranch}\` (checkout is already on this branch).`]:[],`- Reconcile ${e.targetPrUrl} in structured finalResult.targetPrReconciliation.`,"- Only supersede the original when the branch is inaccessible: set supersedesOriginalTargetPr: true with reason and close/comment on the original PR."]}var eq,tq,rh=p(()=>{"use strict";eq=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/i,tq="next-action-fix:"});var $E=p(()=>{"use strict"});function HE(e){let t=e.ownedPaths.length?`Owned paths: ${e.ownedPaths.join(", ")}. Do not edit outside these paths without stopping and reporting why.`:"Owned paths: unrestricted for this worker, but keep edits tightly scoped.",r=!!e.model?.toLowerCase().includes("haiku"),n=r?"compact":"full",o=r?e.planId?`Active planId: ${e.planId}`:"No planId on this worker.":e.planId?`Active planId: ${e.planId}${e.taskId?` \xB7 taskId: ${e.taskId}`:""}`:"No planId on this worker \u2014 still emit progress when you touch plan-scoped work.",s=[...Hi(`worker.prompt.progress.${n}`).split(`
|
|
151
|
+
`),o],i=Hi(`worker.prompt.merge_gate.${n}`).split(`
|
|
152
|
+
`),a=Hi(`worker.prompt.plan_artifacts.${n}`).split(`
|
|
153
|
+
`);return["You are running under the Kynver AgentOS runtime.","Immediately state your plan before editing.",t,`Worktree: ${e.worktreePath}`,`Progress heartbeat file: ${e.heartbeatPath}`,"After each major step, append one JSON line to the heartbeat file with fields: ts, phase, summary, changedFiles, blocker.","Before exiting, append a terminal heartbeat with phase `complete` and a structured finalResult object; if you cannot complete, append blocker plus the recovery next action instead of exiting silently.","Final response must include files changed, verification commands, and unresolved risks.","Also include a JSON code block containing the structured finalResult object itself (not a wrapper): summary, verification (actual commands and observed results), scope, risks, and changedFiles. This is required even if the heartbeat path is read-only or a terminal heartbeat cannot be written. Never invent verification evidence; disclose unverified surfaces and blockers.",...Hi("worker.prompt.core_rules").split(`
|
|
154
|
+
`),"",...s,"",...i,"",...a,"",...e.runtimeEnvelopeMarkdown?.trim()?[e.runtimeEnvelopeMarkdown.trim(),""]:[],...e.contextEnvelopeMarkdown?.trim()?[e.contextEnvelopeMarkdown.trim(),""]:[],...e.personaMarkdown?.trim()?[e.personaMarkdown.trim(),""]:[],...e.instructionPolicyMarkdown?.trim()?["Operating rules (from AgentOS memory policy):",e.instructionPolicyMarkdown.trim(),""]:[],...e.memoryQualityMarkdown?.trim()?[e.memoryQualityMarkdown.trim(),""]:[],...e.repairTargetPrUrl?[...KE({targetPrUrl:e.repairTargetPrUrl,targetPrBranch:e.repairTargetBranch??null}),""]:[],"Task:",e.task].join(`
|
|
155
|
+
`)}var jE=p(()=>{"use strict";rh();Gr();$E()});function GE(e){if(VE)return VE;let t=e?.trim();if(t){let o=Lu[je(t)];if(!o)throw new Error(`unknown worker provider "${t}" \u2014 supported: ${Object.keys(Lu).join(", ")}`);return o}let r=cC(P().workerProvider),n=Lu[r];if(!n)throw new Error(`unknown worker provider "${r}" \u2014 supported: ${Object.keys(Lu).join(", ")}`);return n}var Lu,VE,JE=p(()=>{"use strict";$();Bn();Ug();Vn();ys();ga();Gg();ma();Lu={claude:zC,codex:oE,cursor:TC,[jt]:fE,[Vt]:gE,[Jn]:aE},VE=null});function qE(e){return!!e.completionReportedAt?.trim()}function Bu(e,t,r){e.completionReportedAt=r.completionReportedAt,e.completionOutcome=r.completionOutcome,r.completionResponse!==void 0&&(e.completionResponse=r.completionResponse),X(t,e)}var nh=p(()=>{"use strict";Y()});function oq(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function oh(e){return!!(oq(e.completionBlocker)||e.completionOutcome==="rejected")}function ba(e){return qE(e)&&!oh(e)}var Wu=p(()=>{"use strict";nh()});function sh(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function va(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function zE(e){let t=sh(e);if(!t)return{routeOutcome:null,taskAdvanced:!1,detail:null};let r=va(t.outcome),n=va(t.detail)??va(t.error),o=sh(t.task),s=sh(t.closedTask),i=o?va(o.status):null,a=s?va(s.status):null,c=r==="skipped_terminal_task"&&(i!==null&&YE.has(i)||a!==null&&YE.has(a))||r!==null&&sq.has(r)||i==="awaiting_review"||i==="done"||a==="done";return{routeOutcome:r,taskAdvanced:c,detail:n}}function XE(e){return e.taskAdvanced}var sq,YE,QE=p(()=>{"use strict";sq=new Set(["review_scheduled","review_already_scheduled","closed","dispatched","dispatch_already_done","steer_restart_required"]),YE=new Set(["done","failed","cancelled"])});var ZE=p(()=>{"use strict"});function cq(e){if(!e)return null;let t=e.trim().toLowerCase();return t.length?t:null}function ih(e){return/\b(deep[- ]?review|plan review|review .*plan|security review|red[- ]team|lb\d+|runtime verification)\b/.test(e)}function uq(e,t){return e.startsWith("factory:")?e.includes("lb")||ih(t):!1}function Fu(e){let t=(e.executorRef??"").toLowerCase(),r=(e.title??"").toLowerCase(),n=(e.description??"").toLowerCase(),o=`${r}
|
|
156
|
+
${n}`,s=cq(e.personaSlug);return t.startsWith("harness-lane:blocked-lane-unblock:")||t==="lane:over_attempt_recovery"||t.startsWith("next-action-fix:")||t.startsWith("next-action-landing:")||t.startsWith("code-work-lane-chain:release:")?!1:!!(t.startsWith(iq)||t===aq||t.startsWith("daemon-review:")||s&&Uu.has(s)&&(t.includes("evidence")||t.includes("validate")||t.includes("review")||uq(t,o)||ih(o))||t.startsWith(lq)&&e.parentTaskId&&s&&Uu.has(s)||e.planId&&!e.parentTaskId&&s&&Uu.has(s)&&ih(o)||r.includes("expert pr review")||e.parentTaskId&&(r.startsWith("review:")||r.includes("review required")||r.includes("runtime review"))&&s&&Uu.has(s))}var iq,aq,lq,Uu,ah=p(()=>{"use strict";iq="expert-lane-pr-review:",aq="plan-review-task",lq="scheduledjob:",Uu=new Set(["lorentz","dalton","rhea","sentinel"])});function tA(e){return!!(e&&pq.test(e))}function $e(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function rA(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:$e(e.head)}function nA(e){if(e==null)return null;let r=(typeof e=="string"?e:typeof e=="object"&&e!==null&&"summary"in e?String(e.summary??""):JSON.stringify(e)).match(/https?:\/\/[^\s)>"]+\/(?:pull|pulls|merge_requests|pull-requests)\/\d+/i);return r?$e(r[0]):null}function fq(e,t,r){let n=t.trim();if(!n)return null;let o=r.git(e,["rev-list","--count",`${n}..HEAD`]);if(o.status!==0)return null;let s=Number.parseInt(o.stdout.trim(),10);return Number.isFinite(s)?s:null}function mq(e,t){if(t.changedFiles.length>0)return!1;let r=$e(e.personaSlug)?.toLowerCase();if(r&&dq.has(r))return!0;let n=$e(e.routingRule)??"";return!!(n&&eA.test(n))}function gq(e,t){if(e.changedFiles.length>0)return!0;let r=$e(t?.baseRef);if(r&&t?.exec&&t.worktreePath){let n=fq(t.worktreePath,r,t.exec);if(n===0)return!1;if(n!==null&&n>0)return!0}return!!($e(e.headCommit)||rA(e.gitAncestry))}function oA(e){if(!e.dispatched)return{required:!1,reason:"not_dispatched"};if(Fu({title:e.taskTitle??void 0,personaSlug:e.personaSlug,parentTaskId:e.parentTaskId,executorRef:e.executorRef}))return{required:!1,reason:"expert_review_task"};let t=$e(e.routingRule)??"";if(t&&eA.test(t))return{required:!1,reason:"review_lane"};let r=e.worker??{personaSlug:e.personaSlug,routingRule:e.routingRule};if(mq(r,e.snapshot))return{required:!1,reason:"review_artifact"};if($e(e.patchPath)||$e(e.artifactBundlePath))return{required:!1,reason:"patch_or_bundle"};if($e(e.repairTargetPrUrl))return{required:!1,reason:"repair_target_pr"};if($e(e.prUrl)??$e(e.taskPrUrl)??$e(e.snapshot.prUrl))return{required:!1,reason:"already_has_pr"};let s=e.exec&&e.baseRef?{baseRef:e.baseRef,exec:e.exec,worktreePath:e.snapshot.worktreePath}:void 0;return gq(e.snapshot,s)?{required:!0,snapshot:e.snapshot}:{required:!1,reason:"no_work_product"}}function sA(e,t){return{changedFiles:e.changedFiles,branch:e.branch,worktreePath:e.worktreePath,gitAncestry:e.gitAncestry,finalResult:e.finalResult,headCommit:$e(t?.headCommit)??rA(e.gitAncestry),prUrl:$e(t?.prUrl)??null}}var eA,dq,pq,lh=p(()=>{"use strict";ah();tu();eA=/^(lane:)?(review|deep_review|planning|landing)(:|$)/i,dq=new Set(zx()),pq=/no commits between/i});function aA(e){let t=e.trim();if(!t)return null;let r=t.match(/^git@github\.com:([^/]+\/[^/\s]+?)(?:\.git)?$/i);if(r)return iA(r[1]);let n=t.match(/^ssh:\/\/git@github\.com\/([^/]+\/[^/\s]+?)(?:\.git)?$/i);if(n)return iA(n[1]);try{let o=new URL(t.includes("://")?t:`https://${t}`);if(o.hostname.toLowerCase()!=="github.com")return null;let s=o.pathname.replace(/^\/+|\/+$/g,"").split("/");if(s.length<2)return null;let[i,a]=s;return!i||!a?null:`${i}/${a.replace(/\.git$/i,"")}`}catch{return null}}function iA(e){let t=e.split("/").filter(Boolean);if(t.length<2)return null;let r=t[0],n=t[1].replace(/\.git$/i,"");return r&&n?`${r}/${n}`:null}var lA=p(()=>{"use strict"});import{spawnSync as hq}from"node:child_process";function yq(e,t,r){try{let n=hq(e,r,{windowsHide:!0,cwd:t,encoding:"utf8"});return{status:n.status,stdout:(n.stdout||"").trim(),stderr:(n.stderr||"").trim(),error:n.error?n.error.message:null}}catch(n){return{status:null,stdout:"",stderr:"",error:n.message}}}function kq(e){return e.split(`
|
|
157
|
+
`).map(t=>t.trim()).find(Boolean)??""}function cA(e,t){let r=t.git(e,["remote","get-url","origin"]);return r.status!==0?null:aA(r.stdout)}function Yn(e,t){let r=t.git(e,["rev-parse","HEAD"]);return r.status!==0?null:r.stdout.trim()||null}function Ku(e,t,r,n){let o=n.gh(e,["pr","list","--repo",t,"--head",r,"--state","open","--json","url","--limit","1"]);if(o.status!==0)return null;try{return JSON.parse(o.stdout)[0]?.url?.trim()||null}catch{return null}}function Ra(e){let{worktreePath:t,branch:r,commitMessage:n,hasDirtyFiles:o,exec:s}=e;if(o){let l=s.git(t,["add","-A"]);if(l.status!==0)return{ok:!1,committed:!1,pushed:!1,detail:l.stderr||l.stdout||l.error||"git add failed"};let c=s.git(t,["commit","-m",n]);if(c.status!==0)return{ok:!1,committed:!1,pushed:!1,detail:c.stderr||c.stdout||c.error||"git commit failed"}}let i=s.git(t,["push","-u","origin",r]);if(i.status!==0)return{ok:!1,committed:o,pushed:!1,detail:i.stderr||i.stdout||i.error||"git push failed"};let a=Yn(t,s)??void 0;return{ok:!0,committed:o,pushed:!0,headCommit:a}}function uA(e){let t=e.remoteBranch.trim();if(!t)return{ok:!1,detail:"missing remote branch"};let r=e.exec.git(e.worktreePath,["push","-u","origin",`HEAD:refs/heads/${t}`]);return r.status!==0&&!/already up to date/i.test(r.stderr||r.stdout)?{ok:!1,detail:r.stderr||r.stdout||r.error||"git push to PR branch failed"}:{ok:!0}}function dA(e){let t=Ku(e.worktreePath,e.repo,e.branch,e.exec);if(t)return{ok:!0,prUrl:t,created:!1};let r=e.exec.gh(e.worktreePath,["pr","create","--repo",e.repo,"--base",e.base,"--head",e.branch,"--title",e.title,"--body",e.body,"--draft"]);if(r.status!==0)return{ok:!1,detail:r.stderr||r.stdout||r.error||"gh pr create failed"};let n=bq(r.stdout)??Ku(e.worktreePath,e.repo,e.branch,e.exec);return n?{ok:!0,prUrl:n,created:!0}:{ok:!1,detail:"gh pr create succeeded but no PR URL was parsed"}}function bq(e){let r=kq(e).match(/https?:\/\/[^\s]+\/pull\/\d+/i);return r?r[0]:null}var $u,Hu=p(()=>{"use strict";lA();we();$u={git:(e,t)=>ee(e,t),gh:(e,t)=>yq("gh",e,t)}});function pA(e){return`t-${B(e)}-a`}function fA(e,t){let r=pA(t);if(e.headRefName.toLowerCase().includes(r))return!0;let n=t.trim();if(!n)return!1;let o=e.body??"",s=e.title??"";return o.includes(n)||o.includes(`\`${n}\``)||s.includes(n)}function wa(e){return e.trim().toLowerCase()}function mA(e,t){if(!e.length)return null;if(t){let r=wa(t),n=e.find(o=>wa(o.url)===r);if(n)return n}return[...e].sort((r,n)=>n.number-r.number)[0]??null}function gA(e,t){let r=wa(t);return e.filter(n=>wa(n.url)!==r).map(n=>n.url)}function hA(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.map(r=>({url:r.url?.trim()??"",number:Number(r.number)||0,headRefName:r.headRefName?.trim()??"",createdAt:r.createdAt?.trim()??"",body:r.body,title:r.title})).filter(r=>r.url&&r.number>0&&r.headRefName):[]}catch{return[]}}function vq(e){let t=new Set,r=[];for(let n of e){let o=wa(n.url);t.has(o)||(t.add(o),r.push(n))}return r}function Rq(e,t,r,n){let o=n.gh(e,["search","prs",r,"--repo",t,"--state","open","--json","url,number,headRefName,createdAt,body,title","--limit","20"]);return o.status!==0?[]:hA(o.stdout).filter(s=>fA(s,r))}function wq(e,t,r,n){let o=n.gh(e,["pr","list","--repo",t,"--state","open","--json","url,number,headRefName,createdAt,body,title","--limit","100"]);if(o.status!==0)return[];let s=pA(r);return hA(o.stdout).filter(i=>i.headRefName.toLowerCase().includes(s)||fA(i,r))}function ch(e,t,r,n){let o=r.trim();if(!o)return[];let s=Rq(e,t,o,n),i=wq(e,t,o,n);return vq([...s,...i])}var ju=p(()=>{"use strict";M()});function Sq(e){let t=e.trim().match(/\/pull\/(\d+)(?:$|[?#])/i);if(!t)return null;let r=Number.parseInt(t[1],10);return Number.isFinite(r)?r:null}function uh(e){let t=gA(e.rows,e.canonicalPrUrl),r=[],n=[];for(let o of t){let s=Sq(o);if(!s){n.push({prUrl:o,detail:"could not parse PR number from URL"});continue}let i=`Superseded by ${e.canonicalPrUrl} (harness task retry dedupe).`,a=e.exec.gh(e.worktreePath,["pr","close",String(s),"--repo",e.repo,"--comment",i]);a.status===0?r.push(o):n.push({prUrl:o,detail:a.stderr||a.stdout||a.error||"gh pr close failed"})}return{closed:r,failed:n}}var dh=p(()=>{"use strict";ju()});function yA(e,t,r,n){let o=r.trim();if(!o||!t.trim())return null;let s=n.gh(e,["api",`repos/${t}/commits/${o}/pulls`]);if(s.status!==0||!s.stdout)return null;try{let l=JSON.parse(s.stdout).filter(c=>c.merged_at&&c.html_url?.trim()).sort((c,u)=>(typeof c.number=="number"?c.number:Number.MAX_SAFE_INTEGER)-(typeof u.number=="number"?u.number:Number.MAX_SAFE_INTEGER))[0];return l?.html_url?.trim()?{prUrl:l.html_url.trim(),number:typeof l.number=="number"?l.number:null}:null}catch{return null}}var kA=p(()=>{"use strict"});function _q(e){return e.gh(process.cwd(),["--version"]).status===0}function xq(e,t){return`AgentOS harness: ${e} (${t})`}function Cq(e,t,r){return["Automated PR-ready handoff from the Kynver harness runtime.","",e?`AgentOS task: \`${e}\``:"",`Harness worker: \`${t}\` \xB7 run \`${r}\``,"","Opened by orchestrator completion enforcement so production review receives a reviewable artifact."].filter(Boolean).join(`
|
|
158
|
+
`)}function fh(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function Eq(e){return fh(e.prUrlHint)??nA(e.status.finalResult)??fh(e.worker.taskPrUrl)??null}function Aq(e){let{snapshot:t,canonical:r,workerName:n,exec:o}=e,s=!1,i=!1,a=t.headCommit??Yn(t.worktreePath,o)??void 0;if(t.changedFiles.length>0){let l=Ra({worktreePath:t.worktreePath,branch:t.branch,commitMessage:`chore(harness): update PR handoff for ${n}`,hasDirtyFiles:!0,exec:o});if(!l.ok)return{ok:!1,reason:`PR-ready handoff blocked: ${l.detail??"git commit/push failed"}`,nextAction:"Commit and push the dirty worker changes to the existing PR branch, then rerun `kynver worker complete`."};s=l.committed,i=l.pushed,a=l.headCommit??a}if(r.headRefName!==t.branch){let l=uA({worktreePath:t.worktreePath,remoteBranch:r.headRefName,exec:o});if(!l.ok)return{ok:!1,reason:`PR-ready handoff blocked: ${l.detail??"git push to canonical PR branch failed"}`,nextAction:"Push worker commits to the canonical PR branch, then rerun `kynver worker complete`."};i=!0,a=Yn(t.worktreePath,o)??a}return{ok:!0,prUrl:r.url,headCommit:a,committed:s,pushed:i}}function ph(e){if(e.snapshot.changedFiles.length===0)return{ok:!0,prUrl:e.prUrl,headCommit:e.snapshot.headCommit??Yn(e.snapshot.worktreePath,e.exec)??void 0};let t=Ra({worktreePath:e.snapshot.worktreePath,branch:e.snapshot.branch,commitMessage:e.commitMessage,hasDirtyFiles:!0,exec:e.exec});return t.ok?{ok:!0,prUrl:e.prUrl,headCommit:t.headCommit??e.snapshot.headCommit??void 0,committed:t.committed,pushed:t.pushed}:{ok:!1,reason:`PR-ready handoff blocked: ${t.detail??"git commit/push failed"}`,nextAction:"Commit and push the dirty worker changes to the existing PR branch, then rerun `kynver worker complete`."}}function mh(e,t=$u){let r=Eq(e),n=sA(e.status,{prUrl:r,headCommit:null}),o=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main";if(!oA({dispatched:e.worker.dispatched,routingRule:e.worker.routingRule,personaSlug:e.worker.personaSlug,prUrl:r,taskTitle:e.worker.taskTitle,executorRef:e.worker.executorRef,parentTaskId:e.worker.parentTaskId,taskPrUrl:e.worker.taskPrUrl,repairTargetPrUrl:e.worker.repairTargetPrUrl,baseRef:o,exec:t,worker:e.worker,snapshot:n}).required)return r?ph({snapshot:n,prUrl:r,commitMessage:`chore(harness): update PR handoff for ${e.worker.name}`,exec:t}):{ok:!0};if(r)return ph({snapshot:n,prUrl:r,commitMessage:`chore(harness): update PR handoff for ${e.worker.name}`,exec:t});if(!_q(t)){let b=n.changedFiles.length;return{ok:!1,reason:`PR-ready handoff blocked: ${b?`${b} uncommitted change(s) with no PR URL`:"committed branch with no PR URL"}`,nextAction:"Install and authenticate GitHub CLI (`gh auth login`), then commit, push, and run `gh pr create` (or rerun `kynver worker complete` after the PR exists)."}}let i=cA(n.worktreePath,t);if(!i)return{ok:!1,reason:"PR-ready handoff blocked: could not resolve github.com origin for the worktree",nextAction:"Ensure `origin` points at GitHub, push the branch, open a PR, and rerun `kynver worker complete`."};let a=e.worker.repairTargetPrUrl?.trim();if(a){let b=!1,_=!1,S=n.headCommit??Yn(n.worktreePath,t)??void 0;if(n.changedFiles.length>0){let R=Ra({worktreePath:n.worktreePath,branch:n.branch,commitMessage:`fix(harness): repair target PR ${a}`,hasDirtyFiles:!0,exec:t});if(!R.ok)return{ok:!1,reason:`PR-ready handoff blocked: ${R.detail??"git commit/push failed"}`,nextAction:"Commit and push to the target PR branch, then rerun `kynver worker complete`."};b=R.committed,_=R.pushed,S=R.headCommit??S}else{let R=t.git(n.worktreePath,["push","-u","origin",n.branch]);if(R.status!==0&&!/already up to date/i.test(R.stderr||R.stdout))return{ok:!1,reason:`PR-ready handoff blocked: ${R.stderr||R.stdout||"git push failed"}`,nextAction:"Push the target branch to origin, then rerun `kynver worker complete`."};_=R.status===0}return{ok:!0,prUrl:a,headCommit:S,committed:b,pushed:_}}let l=fh(e.worker.taskId),c=[];if(l){c=ch(n.worktreePath,i,l,t);let b=mA(c);if(b){let _=Aq({snapshot:n,canonical:b,workerName:e.worker.name,exec:t});return _.ok&&_.prUrl&&uh({worktreePath:n.worktreePath,repo:i,rows:c,canonicalPrUrl:_.prUrl,exec:t}),_}}let u=Ku(n.worktreePath,i,n.branch,t);if(u)return ph({snapshot:n,prUrl:u,commitMessage:`chore(harness): update PR handoff for ${e.worker.name}`,exec:t});let d=n.changedFiles.length>0,f=!1,m=!1,g=n.headCommit??void 0,h=Ra({worktreePath:n.worktreePath,branch:n.branch,commitMessage:`chore(harness): PR-ready handoff for ${e.worker.name}`,hasDirtyFiles:d,exec:t});if(d&&!h.ok)return{ok:!1,reason:`PR-ready handoff blocked: ${h.detail??"git commit/push failed"}`,nextAction:"Commit and push the branch, run `gh pr create`, then rerun `kynver worker complete`."};if(d){if(f=h.committed,m=h.pushed,!h.ok)return{ok:!1,reason:`PR-ready handoff blocked: ${h.detail??"git push failed"}`,nextAction:"Fix git auth or merge conflicts, push the branch, run `gh pr create`, then rerun `kynver worker complete`."}}else{let b=t.git(n.worktreePath,["push","-u","origin",n.branch]);if(b.status!==0&&!/already up to date/i.test(b.stderr||b.stdout))return{ok:!1,reason:`PR-ready handoff blocked: ${b.stderr||b.stdout||b.error||"git push failed"}`,nextAction:"Push the branch to origin, run `gh pr create`, then rerun `kynver worker complete`."};m=b.status===0}g=h.headCommit??g??Yn(n.worktreePath,t)??void 0;let y=g?yA(n.worktreePath,i,g,t):null;if(y)return{ok:!0,prUrl:y.prUrl,headCommit:g,committed:f,pushed:m,created:!1};let v=e.run.base?.trim()||"main",k=dA({worktreePath:n.worktreePath,repo:i,branch:n.branch,base:v.replace(/^origin\//,""),title:xq(e.worker.name,e.worker.runId),body:Cq(e.worker.taskId,e.worker.name,e.worker.runId),exec:t});if(!k.ok||!k.prUrl){if(tA(k.detail))return{ok:!0,headCommit:g??void 0,committed:f,pushed:m};let b=n.changedFiles.length;return{ok:!1,reason:`PR-ready handoff blocked: ${b?`${b} uncommitted change(s) and no PR URL after handoff attempt`:"no PR URL after handoff attempt"}${k.detail?` (${k.detail})`:""}`,nextAction:"Run `gh pr create` on the worker branch (or fix `gh` auth), attach the PR URL to the task, then rerun `kynver worker complete`."}}if(l&&k.prUrl){let _=[...c.length>0?c:ch(n.worktreePath,i,l,t),{url:k.prUrl,number:Number.parseInt(k.prUrl.match(/\/pull\/(\d+)/)?.[1]??"",10)||0,headRefName:n.branch,createdAt:""}];uh({worktreePath:n.worktreePath,repo:i,rows:_,canonicalPrUrl:k.prUrl,exec:t})}return{ok:!0,prUrl:k.prUrl,headCommit:g??void 0,committed:f,pushed:m,created:k.created}}var bA=p(()=>{"use strict";lh();ju();dh();Hu();kA()});var vA=p(()=>{"use strict";ZE();lh();Hu();ju();dh();bA()});import Pq from"node:path";function hh(e){clearInterval(gh.get(e)),gh.delete(e)}function yh(e,t){if(hh(e),!Sa.has(e))return;let r=setInterval(()=>{(F(Pq.join(e,"worker.json"),null)?.completionReportedAt||!re(t))&&ws(e)},1e3);r.unref(),gh.set(e,r)}function kh(e,t){hh(e);let r=Sa.get(e);r&&r.close(),Sa.set(e,t)}async function Yr(e){hh(e);let t=Sa.get(e);return t?(Sa.delete(e),await t.close(),!0):!1}function ws(e){Yr(e).catch(()=>{})}var Sa,gh,bh=p(()=>{"use strict";M();Sa=new Map,gh=new Map});import{appendFileSync as Iq,existsSync as wA,mkdirSync as SA,readFileSync as Oq,rmSync as RA,writeFileSync as Tq}from"node:fs";import Cr from"node:path";function xA(e){return Cr.join(e,_A)}function Nq(e){return ce(e,["ls-files","--error-unmatch",_A.split(Cr.sep).join("/")],{allowFailure:!0}).trim().length>0}function Dq(e){let t=ce(e,["rev-parse","--git-common-dir"],{allowFailure:!0}).trim();if(!t)return;let r=Cr.isAbsolute(t)?t:Cr.join(e,t),n=Cr.join(r,"info","exclude"),o=".cursor/mcp.json";try{SA(Cr.dirname(n),{recursive:!0});let s=wA(n)?Oq(n,"utf8"):"";if(s.split(/\r?\n/).some(i=>i.trim()===o))return;Iq(n,`${s.endsWith(`
|
|
95
159
|
`)||!s?"":`
|
|
96
160
|
`}${o}
|
|
97
|
-
`)}catch{}}function
|
|
98
|
-
`,{mode:384}),
|
|
99
|
-
`)}function
|
|
161
|
+
`)}catch{}}function CA(e){if(Nq(e.worktreePath))return{ok:!1,reason:"repo_owns_config",detail:"the repository tracks .cursor/mcp.json \u2014 refusing to modify a tracked file in the worker's worktree"};let t=xA(e.worktreePath);SA(Cr.dirname(t),{recursive:!0});let r={mcpServers:{[ye]:{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Nt]:e.brokerSocketPath}}}};return Tq(t,`${JSON.stringify(r,null,2)}
|
|
162
|
+
`,{mode:384}),Dq(e.worktreePath),{ok:!0,configPath:t}}function Vu(e){let t=xA(e);if(!wA(t))return!1;try{RA(t,{force:!0});let r=Cr.dirname(t);return RA(r,{recursive:!1}),!0}catch{return!0}}var _A,vh=p(()=>{"use strict";we();Sr();ot();_A=Cr.join(".cursor","mcp.json")});import{copyFileSync as Mq,existsSync as Gu,mkdirSync as Lq,readFileSync as Bq,rmSync as Wq,symlinkSync as Uq,writeFileSync as Fq}from"node:fs";import{spawnSync as Kq}from"node:child_process";import{homedir as $q}from"node:os";import zr from"node:path";function EA(e){return zr.join(e,Hq)}function jq(e=process.env){let t=e.CODEX_HOME?.trim();if(t)return zr.resolve(t);let r=$q();for(let n of[zr.join(r,".codex"),zr.join(r,".config","codex")])if(Gu(n))return n;return null}function Vq(e){return["","# Added per task by the Kynver harness. Carries a broker socket path, never a credential.",`[mcp_servers.${ye}]`,'command = "npx"','args = ["-y", "-p", "@kynver-app/mcp-agent-os", "kynver-worker-mcp"]',"",`[mcp_servers.${ye}.env]`,`${Nt} = ${JSON.stringify(e)}`,""].join(`
|
|
163
|
+
`)}function Gq(e){return new RegExp(String.raw`^\s*\[\s*mcp_servers\s*\.\s*"?${ye}"?\s*[\].]`,"m").test(e)}function AA(e){let t=jq(e.env??process.env),r=t?zr.join(t,"config.toml"):null,n=r&&Gu(r)?Bq(r,"utf8"):"";if(n&&Gq(n))return{ok:!1,reason:"user_config_owns_server",detail:`the Codex config already declares an "${ye}" MCP server \u2014 refusing to write a duplicate stanza`};let o=EA(e.workerDir);Lq(o,{recursive:!0,mode:448});let s=!n||n.endsWith(`
|
|
100
164
|
`)?"":`
|
|
101
|
-
`;return
|
|
165
|
+
`;return Fq(zr.join(o,"config.toml"),`${n}${s}${Vq(e.brokerSocketPath)}`,{mode:384}),{ok:!0,codexHome:o,authMode:Jq(t,o)}}function Jq(e,t){let r=e?zr.join(e,"auth.json"):null;if(!r||!Gu(r))return"none";let n=zr.join(t,"auth.json");try{return Uq(r,n,"file"),"symlink"}catch{try{return Mq(r,n),"copy"}catch{return"none"}}}function _a(e){let t=EA(e);if(!Gu(t))return!1;try{return Wq(t,{recursive:!0,force:!0}),!0}catch{return!1}}function PA(e,t,r=1e4){try{let[n,o]=ae(t,["--version"]),s=Kq(n,o,{env:{...process.env,CODEX_HOME:e},encoding:"utf8",timeout:r,windowsHide:!0});return s.error&&s.error.code==="ENOENT"?{ok:!0}:s.status===0?{ok:!0}:{ok:!1,detail:(s.stderr||s.stdout||`exit ${s.status??"unknown"}`).toString().replace(/\s+/g," ").trim().slice(0,200)}}catch{return{ok:!0}}}var Hq,Rh=p(()=>{"use strict";qe();Sr();ot();Hq="codex-home"});import{appendFileSync as qq,existsSync as wh,mkdirSync as OA,readFileSync as TA,rmSync as IA,writeFileSync as Yq}from"node:fs";import Er from"node:path";function DA(e){return Er.join(e,NA)}function zq(e){return ce(e,["ls-files","--error-unmatch",NA.split(Er.sep).join("/")],{allowFailure:!0}).trim().length>0}function Xq(e){if(!wh(e))return{};try{let t=JSON.parse(TA(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))return{};let r=t.mcpServers;return!r||typeof r!="object"||Array.isArray(r)?{}:r}catch{return{}}}function Qq(e){let t=ce(e,["rev-parse","--git-common-dir"],{allowFailure:!0}).trim();if(!t)return;let r=Er.isAbsolute(t)?t:Er.join(e,t),n=Er.join(r,"info","exclude"),o=".agents/mcp_config.json";try{OA(Er.dirname(n),{recursive:!0});let s=wh(n)?TA(n,"utf8"):"";if(s.split(/\r?\n/).some(i=>i.trim()===o))return;qq(n,`${s.endsWith(`
|
|
102
166
|
`)||!s?"":`
|
|
103
167
|
`}${o}
|
|
104
|
-
`)}catch{}}function
|
|
105
|
-
`,{mode:384}),
|
|
106
|
-
`,{mode:384}),{ok:!0,geminiCliHome:o,authMode:Nq(r,s)}}function Nq(e,t){let r=["oauth_creds.json","google_accounts.json"],n="none";for(let o of r){let s=xr.join(e,o);if(!Qg(s))continue;let i=xr.join(t,o);try{Sq(s,i,"file"),n==="none"&&(n="symlink")}catch{try{bq(s,i),n="copy"}catch{}}}return n}function Nu(e){let t=UE(e);if(!Qg(t))return!1;try{return wq(t,{recursive:!0,force:!0}),!0}catch{return!1}}var Cq,Zg=p(()=>{"use strict";vr();tt();Cq="gemini-home"});import Dq from"node:path";function $E(e){return!!(typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim())}function Lq(e){if(typeof e=="string"){let t=e.trim();return t.length?t:null}if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e,r=t.summary??t.finalSummary??t.message;if(typeof r=="string"&&r.trim())return r.trim();try{return JSON.stringify(e)}catch{return null}}return null}function Jr(e){let t=e.finalResult??null,r=typeof e.lastHeartbeatSummary=="string"?e.lastHeartbeatSummary:Lq(t);return{finalResult:t??r??"completed",summary:r}}function Du(e,t,r){if($E(e)&&e.status==="done"&&e.completionSnapshot!=null)return;let n=new Date().toISOString(),o=Jr(t),s=r?.source?.trim();e.completionReportedAt=n,e.completionSnapshot=o,e.status="done",s&&(e.completionAckSource=s),ee(e.runId,e),e.workerDir&&(ms(e.workerDir),ou(e.workerDir),ga(e.workerDir),Nu(e.workerDir)),e.worktreePath&&(Iu(e.worktreePath),Tu(e.worktreePath))}function Bq(e){let t=new Map,n=e.response?.tick?.filteredItems;if(!Array.isArray(n))return t;for(let o of n){if(o.kind!=="task"||typeof o.id!="string")continue;let s=typeof o.taskStatus=="string"?o.taskStatus.trim():"";s&&t.set(o.id,s)}return t}function KE(e,t){let r=Bq(t);if(r.size===0)return[];let n=ae(e),o=[];for(let s of Object.keys(n.workers||{})){let i=$(Dq.join(G(n.id),"workers",B(s),"worker.json"),void 0);if(!i?.taskId||$E(i))continue;let a=r.get(i.taskId);if(!a||a==="running"||!Mq.has(a))continue;let l=oe(i,{base:n.base,baseCommit:n.baseCommit});Du(i,l,{source:`board-task-${a}`}),o.push({worker:s,taskId:i.taskId,taskStatus:a})}return o}var Mq,Mu=p(()=>{"use strict";z();_e();D();tt();Jg();qg();Yg();Xg();Zg();Mq=new Set(["awaiting_review","blocked","done","needs_input","waiting","scheduled","ready","cancelled","failed"])});function Lu(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"&&!Array.isArray(e)?Object.keys(e).length>0:!0}function Wq(e){let t=e.lastHeartbeatPhase?.trim();if(!t||t==="complete")return null;let r=e.lastHeartbeatSummary?.trim();return r?{summary:r,handoffState:"exited_without_complete_heartbeat",lastHeartbeatPhase:t,...e.heartbeatBlocker?{blocker:e.heartbeatBlocker}:{}}:null}function Uq(e){let t=pi(e);return t?{summary:t.reason,handoffState:"exit_failure",blocked:t.blocked}:null}function Fq(e){let t=e.status.attention.reason?.trim()||e.status.error?.trim()||"process exited without a final result";return{summary:`Worker exited with an error: ${t}`,handoffState:"exited_without_final_result",blocked:!0,attentionState:e.status.attention.state,attentionReason:t,...e.heartbeat.lastHeartbeatPhase?{lastHeartbeatPhase:e.heartbeat.lastHeartbeatPhase}:{},...e.heartbeat.lastHeartbeatSummary?{lastHeartbeatSummary:e.heartbeat.lastHeartbeatSummary}:{},...e.heartbeat.heartbeatBlocker?{blocker:e.heartbeat.heartbeatBlocker}:{}}}function Bu(e){let{worker:t,status:r}=e;if(Lu(r.finalResult)){let u=Ee(t.heartbeatPath),d=sr(u),m=Lu(d)&&JSON.stringify(d)===JSON.stringify(r.finalResult)?"heartbeat_complete":"stdout_stream";return{finalResult:r.finalResult,source:m,snapshot:Jr(r)}}if(r.alive)return null;let n=mn(t.stdoutPath);if(Lu(n.finalResult)){let u={...r,finalResult:n.finalResult};return{finalResult:n.finalResult,source:"stdout_stream",snapshot:Jr(u)}}let o=Ee(t.heartbeatPath),s=sr(o);if(Lu(s)){let u={...r,finalResult:s,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:s,source:"heartbeat_complete",snapshot:Jr(u)}}let i=Uq(r.error??n.error);if(i){let u={...r,finalResult:i};return{finalResult:i,source:"exit_failure",snapshot:Jr(u)}}let a=Wq(o);if(a){let u={...r,finalResult:a,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:a,source:"heartbeat_summary",snapshot:Jr(u)}}let l=Fq({status:r,heartbeat:o}),c={...r,finalResult:l,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:l,source:"exit_no_final_result",snapshot:Jr(c)}}function Wu(e,t){return e.completionSnapshot?.finalResult!=null?!1:(e.completionSnapshot=t.snapshot,e.completionHandoffSource=t.source,!0)}var eh=p(()=>{"use strict";fn();df();Mu();di()});function Uu(e){return e.filter(t=>{let r=t.trim(),n=r.startsWith("??")?r.slice(2).trim():r.length>3?r.slice(3).trim():r;return n!=="node_modules"&&!n.startsWith("node_modules/")})}function HE(e){let t=e.trim();return t.startsWith("??")?t.slice(2).trim():t.length>3&&/^[ MADRCU?!]{2} /.test(t.slice(0,3))?t.slice(3).trim():t}var th=p(()=>{"use strict"});function jE(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function VE(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function JE(e){let t=VE(e);if(!t)return[];let r=VE(t.worktreeHandoff),n=jE(r?.disposableArtifactsRemoved);return n.length?n:jE(t.disposableArtifactsRemoved)}function GE(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function qE(e,t){let r=Uu(e);if(r.length===0)return!0;if(t.length===0)return!1;let n=new Set(t.map(o=>GE(o)));return r.every(o=>{let s=GE(HE(o));return n.has(s)})}var YE=p(()=>{"use strict";th()});function Fu(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function zE(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function $q(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function Kq(e){let t=zE(e.disposableArtifactsRemoved),r=JE(e.finalResult);return[...new Set([...t,...r])]}function XE(e){let t=zE(e.changedFiles),r=Uu(t),n=Kq(e),o=r.length===0||qE(t,n);return Fu(e.prUrl)?o?{allowed:!0,state:"pr_handoff",materialDirtyCount:0}:{allowed:!1,state:"dirty_worktree",materialDirtyCount:r.length,detail:`Worktree has ${r.length} uncommitted change(s) with a PR attached; commit or discard before completing`}:Fu(e.headCommit)?o?{allowed:!0,state:"commit_handoff",materialDirtyCount:0}:{allowed:!1,state:"dirty_worktree",materialDirtyCount:r.length,detail:`Worktree has ${r.length} uncommitted change(s) on top of a commit; commit or discard before completing`}:Fu(e.artifactBundlePath)||Fu(e.patchPath)?o?{allowed:!0,state:"commit_handoff",materialDirtyCount:0}:{allowed:!1,state:"dirty_worktree",materialDirtyCount:r.length,detail:`Worktree has ${r.length} uncommitted change(s) with a patch/bundle handoff; clean the tree before completing`}:o?{allowed:!0,state:"clean",materialDirtyCount:0}:$q(e.finalResult)?{allowed:!1,state:"dirty_worktree_no_pr",materialDirtyCount:r.length,detail:`Worktree has ${r.length} uncommitted change(s) with no commit or PR; commit, open a PR, discard, or remove one-off files via \`kynver worker discard-disposable\` before completing`}:{allowed:!1,state:"dirty_worktree",materialDirtyCount:r.length,detail:`Worktree has ${r.length} uncommitted change(s) with no final result`}}var QE=p(()=>{"use strict";YE();th()});function Cr(e=process.env){return hr(e).flags.dispatchReceipts}function rh(e){return Cr(e)!=="off"}function nh(e,t){return`dispatch:${e}:${t.taskId}:${t.leaseToken}`}function ya(e,t,r){if(!rh())return;let n=ce();if(n)try{n.recordOperationReceipt({idempotencyKey:nh(e,t),operation:`dispatch-${e}`,resultJson:r===void 0?null:JSON.stringify(r)})}catch{rt.storeFailures+=1}}function eA(e){ya("claim",e,{runId:e.runId,workerName:e.workerName,provider:e.provider})}function $u(e){ya("spawned",e)}function gs(e,t){ya("released",e,{reasonClass:t})}function tA(e){ya("completion-sent",e)}function oh(e,t){ya("completion-acked",e,{outcome:t})}function rA(e){if(!rh())return!1;let t=ce();if(!t)return!1;try{let r=t.getOperationReceipt(nh("completion-acked",e));if(r){let n=null;try{n=r.resultJson?JSON.parse(r.resultJson).outcome??null:null}catch{n=null}if(n==="acknowledged")return rt.completionReplaysObserved+=1,!0}}catch{rt.storeFailures+=1}return!1}function sh(e){let t=String(e??"").split(":")[0]?.trim()??"";return t.length>0?t.slice(0,64):"unknown"}function nA(e){if(Cr()!=="enforce")return!1;let t=ce();if(!t)return!1;try{let r=t.getOperationReceipt(nh("completion-acked",e));if(!r)return!1;let n=null;try{n=r.resultJson?JSON.parse(r.resultJson).outcome??null:null}catch{n=null}return n==="acknowledged"?(rt.completionReplaysShortCircuited+=1,!0):!1}catch{return rt.storeFailures+=1,!1}}function oA(e,t){if(Cr()!=="enforce")return;let r=ce();if(r)try{r.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${e}:${t}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:t})})}catch{rt.storeFailures+=1}}function sA(e,t){if(Cr()!=="enforce")return[];let r=ce();if(!r)return[];let n=t?.nowMs??Date.now(),o=t?.windowMs??Hq;try{return r.listOperationReceipts({operation:"dispatch-start-failed",recordedAfter:new Date(n-o).toISOString(),limit:200}).filter(s=>{try{return s.resultJson?JSON.parse(s.resultJson).runId===e:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(e.length+1))}).filter(s=>s.length>0)}catch{return rt.storeFailures+=1,[]}}function ha(e){let t=e.split(":")[0]??"",r=Number(t);return Number.isInteger(r)&&r>=0?r:null}function iA(e){let t={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!rh())return t;let r=ce();if(!r)return t;let n=e?.nowMs??Date.now(),o=e?.strandedAfterMs??jq;try{let s=r.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-ZE).toISOString(),limit:Gq}),i=0,a=[];for(let c of s){let u=c.idempotencyKey.slice(15),d=Date.parse(c.recordedAt);if(!Number.isFinite(d)||n-d<o)continue;let m=r.getOperationReceipt(`dispatch:spawned:${u}`),f=r.getOperationReceipt(`dispatch:released:${u}`);if(m||f){n-d>=Vq&&a.length+5<=Jq&&a.push(c.idempotencyKey,`dispatch:spawned:${u}`,`dispatch:released:${u}`,`dispatch:completion-sent:${u}`,`dispatch:completion-acked:${u}`);continue}let g=u.split(":")[0]??"",h=ha(u.slice(g.length+1));if((g?r.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${g}:`,limit:10}):[]).some(b=>{if(h===null)return!0;let _=b.idempotencyKey.slice(`dispatch:completion-acked:${g}:`.length),S=ha(_);return S===null||S>=h}))continue;let k=!1;if(e?.hasLiveWorker&&c.resultJson)try{let b=JSON.parse(c.resultJson);b.runId&&b.workerName&&(k=e.hasLiveWorker({runId:b.runId,workerName:b.workerName}))}catch{k=!1}k||(i+=1)}let l=a.length>0?r.deleteOperationReceiptsByKeys(a):0;if(Cr()==="enforce"){let c=r.listOperationReceipts({limit:100}).filter(u=>{let d=Date.parse(u.recordedAt);return Number.isFinite(d)&&n-d>=ZE}).map(u=>u.idempotencyKey);if(c.length>0){let u=r.deleteOperationReceiptsByKeys(c);l+=u,rt.agedReceiptsPruned+=u}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:l}}catch{return rt.storeFailures+=1,t}}function aA(){return{"dispatchReceipts.storeFailures":rt.storeFailures,"dispatchReceipts.completionReplaysObserved":rt.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":rt.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":rt.agedReceiptsPruned}}var rt,Hq,jq,ZE,Vq,Gq,Jq,hs=p(()=>{"use strict";Hr();ts();rt={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};Hq=600*1e3;jq=900*1e3,ZE=10080*60*1e3,Vq=1440*60*1e3,Gq=500,Jq=300});function lA(){ah=!1}function Er(e=process.env){return hr(e).flags.admission}function Ku(e,t){return`${ih}${e}:${t}`}function cA(e,t){if(Er()==="off")return;let r=ce();if(r)try{r.tryReserveAdmission(Ku(e,t),lh,ys)}catch{qr.storeFailures+=1}}function ka(e,t){if(Er()==="off")return;let r=ce();if(r)try{r.releaseAdmission(Ku(e,t),lh)}catch{qr.storeFailures+=1}}function uA(e){let t={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(Er()==="off")return t;let r=ce();if(!r)return t;try{let n=new Set(e.liveWorkers.map(m=>Ku(m.runId,m.workerName))),o=r.listAdmissionReservations({keyPrefix:ih,limit:500}),s=new Set(o.map(m=>m.key)),i=[...n].filter(m=>!s.has(m)).length,a=o.filter(m=>!n.has(m.key)).length,l=!ah;ah=!0,!l&&i>0&&(qr.missingForLive+=i);let c=0;for(let m of e.liveWorkers)r.tryReserveAdmission(Ku(m.runId,m.workerName),lh,ys),c+=1;let u=0;for(let m of o)n.has(m.key)||r.releaseAdmission(m.key,m.owner)&&(u+=1,qr.deadSlotsReleased+=1);return{liveReservations:r.listAdmissionReservations({keyPrefix:ih,limit:500}).length,refreshed:c,deadReleased:u,missingForLive:i,orphaned:a,adoptionPass:l}}catch{return qr.storeFailures+=1,t}}function dA(){return{"admission.storeFailures":qr.storeFailures,"admission.missingForLive":qr.missingForLive,"admission.deadSlotsReleased":qr.deadSlotsReleased}}var ys,lh,ih,qr,ah,Hn=p(()=>{"use strict";Hr();ts();ys=900*1e3,lh="admission-shadow",ih="worker-slot:",qr={storeFailures:0,missingForLive:0,deadSlotsReleased:0},ah=!1});function pA(e){return`${ch}${e}`}function ju(e,t){return`${e}:${t}`}function fA(e){if(Er()!=="enforce")return{admitted:!0};let t=ce();if(!t)return{admitted:!0};let r=Math.max(0,Math.min(Hu,Math.floor(e.maxSlots)));if(e.diskActiveWorkers>=r)return Yr.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=ju(e.runId,e.workerName);for(let o=0;o<r;o+=1)if(t.tryReserveAdmission(pA(o),n,ys).acquired)return{admitted:!0,slot:o};return Yr.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return Yr.enforceStoreFailures+=1,{admitted:!0}}}function zr(e,t){if(Er()==="off")return;let r=ce();if(r)try{let n=ju(e,t),o=r.listAdmissionReservations({keyPrefix:ch,limit:Hu});for(let s of o)s.owner===n&&r.releaseAdmission(s.key,n)}catch{Yr.enforceStoreFailures+=1}}function mA(e){let t={refreshed:0,deadReleased:0,adopted:0};if(Er()!=="enforce")return t;let r=ce();if(!r)return t;try{let n=new Set(e.liveWorkers.map(c=>ju(c.runId,c.workerName))),o=r.listAdmissionReservations({keyPrefix:ch,limit:Hu}),s=0,i=0,a=new Set;for(let c of o)n.has(c.owner)?(r.tryReserveAdmission(c.key,c.owner,ys),a.add(c.owner),s+=1):r.releaseAdmission(c.key,c.owner)&&(i+=1);let l=0;for(let c of e.liveWorkers){let u=ju(c.runId,c.workerName);if(!a.has(u)){for(let d=0;d<Hu;d+=1)if(r.tryReserveAdmission(pA(d),u,ys).acquired){l+=1;break}}}return{refreshed:s,deadReleased:i,adopted:l}}catch{return Yr.enforceStoreFailures+=1,t}}function gA(){return{"admission.enforceStoreFailures":Yr.enforceStoreFailures,"admission.refusedSlotsExhausted":Yr.admissionsRefusedSlots,"admission.refusedDiskBackstop":Yr.admissionsRefusedDiskBackstop}}var ch,Hu,Yr,ks=p(()=>{"use strict";Hr();Hn();ch="worker-slot-n:",Hu=64;Yr={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0}});import qq from"node:path";function uh(e){let t=e.trim();if(!Yq.test(t))throw new Error(`invalid run id: ${e}`);return t}function Xq(e){let t=e.trim();if(!zq.test(t))throw new Error(`invalid worker name: ${e}`);return t}function kA(e){return typeof e=="string"?e.trim():""}function Vu(e){let t=kA(e.run),r=kA(e.name);return(!t||hA.has(t))&&ot(`missing --run RUN_ID (${yA})`),(!r||hA.has(r))&&ot(`missing --name WORKER_NAME (${yA})`),{runId:uh(t),workerName:Xq(r)}}function bA(e){let t=qq.resolve(e);if(t.includes(".."))throw new Error("repo path must not contain .. segments");return t}var Yq,zq,hA,yA,Gu=p(()=>{"use strict";D();Yq=/^[a-z0-9][a-z0-9._-]{0,127}$/i,zq=/^[a-z0-9][a-z0-9._-]{0,63}$/i,hA=new Set(["undefined","null"]),yA="usage: kynver worker <action> --run RUN_ID --name WORKER_NAME"});import{existsSync as Qq,mkdirSync as Zq,readFileSync as e2,writeFileSync as t2}from"node:fs";import{homedir as r2}from"node:os";import vA from"node:path";function a2(e){let t=e?.trim();return!!(t&&n2.test(t))}function l2(){let e=(process.env.KYNVER_PROVIDER_QUOTA_PREFLIGHT??"on").trim().toLowerCase();return e!=="off"&&e!=="0"&&e!=="false"&&e!=="no"}function dh(){let e=Number.parseInt(process.env.KYNVER_PROVIDER_QUOTA_COOLDOWN_MINUTES??"",10);return Number.isFinite(e)?Math.min(i2,Math.max(s2,e)):o2}function RA(){let e=process.env.KYNVER_PROVIDER_QUOTA_STORE_PATH?.trim();return e||vA.join(r2(),".kynver","provider-quota-cooldowns.json")}function ba(e){return(e??"").trim().toLowerCase()}function ph(){let e=RA();if(!Qq(e))return{};try{let t=JSON.parse(e2(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))return{};let r={};for(let[n,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let{lastExhaustedAt:s,reason:i}=o;typeof s!="string"||!Number.isFinite(Date.parse(s))||(r[ba(n)]={lastExhaustedAt:s,reason:typeof i=="string"?i.slice(0,500):""})}return r}catch{return{}}}function fh(e){let t=RA();try{Zq(vA.dirname(t),{recursive:!0}),t2(t,`${JSON.stringify(e,null,2)}
|
|
107
|
-
`,"utf8")}catch{}}function c2(e,t,r=Date.now()){let n=ba(e);if(!n)return;let o=ph();o[n]={lastExhaustedAt:new Date(r).toISOString(),reason:t.trim().slice(0,500)},fh(o),YS(n,dh()*6e4)}function u2(e){let t=ba(e);if(!t)return!1;zS(t);let r=ph();return t in r?(delete r[t],fh(r),!0):!1}function wA(e,t=Date.now()){if(!l2())return{ok:!0};let r=ba(e);if(!r)return{ok:!0};let n=ph(),o=n[r],s=!!(o&&Number.isFinite(Date.parse(o.lastExhaustedAt))&&Date.parse(o.lastExhaustedAt)+dh()*6e4>t),i=XS(r,s);if(i)return i.blocked?{ok:!1,provider:r,reason:`provider "${r}" is inside its local quota cooldown`+(i.retryAtIso?` \u2014 preflight declines spawn until ${i.retryAtIso}`:""),retryAtIso:i.retryAtIso??new Date(t).toISOString()}:{ok:!0};if(!o)return{ok:!0};let a=Date.parse(o.lastExhaustedAt),l=a+dh()*6e4;if(!Number.isFinite(a)||l<=t)return delete n[r],fh(n),{ok:!0};let c=new Date(l).toISOString();return{ok:!1,provider:r,reason:`provider "${r}" reported quota exhaustion at ${o.lastExhaustedAt} \u2014 local preflight declines spawn until ${c}`+(o.reason?` (${o.reason.slice(0,160)})`:""),retryAtIso:c}}function d2(e){if(typeof e=="string"){let t=e.trim();return t.length?t:null}if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;for(let r of["result","summary","error"]){let n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}return null}function SA(e){let t=ba(e.provider);if(!t)return"none";let r=d2(e.finalResult)??(typeof e.error=="string"&&e.error.trim()?e.error.trim():null);return r?a2(r)?(c2(t,r,e.nowMs??Date.now()),"recorded"):u2(t)?"cleared":"none":"none"}var n2,o2,s2,i2,mh=p(()=>{"use strict";Bi();n2=/\b(out of usage|increase limits?|switch to auto|ask your admin to increase your limit|(?:hit|reached|exceeded|over) (?:your |the )?usage limits?|usage limits? (?:hit|reached|exceeded)|exceeded your (?:current )?quota|quota (?:exceeded|exhausted)|insufficient_quota|insufficient (?:credits?|quota)|credits? exhausted|credit balance is too low|billing hard limit|check your plan and billing|402 payment required|provider quota exhausted|provider_quota_exhausted)\b/i,o2=30,s2=5,i2=240});function _A(e){let t=e.usage;return!t||t.inputTokens===void 0&&t.outputTokens===void 0?null:{provider:e.provider?.trim()||"unknown",model:t.model?.trim()||e.model?.trim()||null,inputTokens:t.inputTokens??null,outputTokens:t.outputTokens??null}}var xA=p(()=>{"use strict"});import qu from"node:path";async function CA(e,t,r){let n=await fetch(e,{method:"POST",headers:Ct(t),body:JSON.stringify(r)}),o=null;try{o=await n.json()}catch{o=null}return{ok:n.ok,status:n.status,parsed:o}}function f2(e){if(e&&typeof e=="object"){let t=e.error;if(typeof t=="string"&&t.trim())return t.trim()}}function EA(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function va(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function m2(e){return e.completionBlocker?`blocked:${e.completionBlocker}`:e.completionOutcome?e.completionOutcome:e.completionReportedAt?"completion_acknowledged":e.finished?"worker_finished":"in_progress"}function g2(e){return e.completionBlocker?"Resolve completion blocker, then rerun `kynver worker complete`.":e.completionOutcome==="review_scheduled"||e.completionOutcome==="review_already_scheduled"?"Await review lane and landing decision in Command Center.":e.completionOutcome==="needs_attention"?"Inspect blocker/attention reason in Command Center and dispatch a repair task.":e.finished&&!e.completionReportedAt?"Post completion acknowledgement to AgentOS (`kynver worker complete`).":null}function PA(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function h2(e){return e.prUrl?"pr_handoff":e.headCommit?"commit_handoff":e.changedFiles.length>0?"dirty_worktree":"none"}function bs(e,t){(e.completionBlocker??void 0)!==(t??void 0)&&(t?e.completionBlocker=t:delete e.completionBlocker,ee(e.runId,e))}function y2(e){e.completionBlocker&&(delete e.completionBlocker,ee(e.runId,e))}function Ju(e){return e?{base:e.base,baseCommit:e.baseCommit}:{}}function k2(e,t){return{...e,...t.prUrl?{prUrl:t.prUrl}:{},...t.headCommit?{headCommit:t.headCommit}:{}}}async function Yu(e){let{runId:t,workerName:r}=Vu(e),n=_n(t,r),o=ae(n.runId),s=oe(n,Ju(o)),i=(e.agentOsId?String(e.agentOsId):n.agentOsId)||"",a=(e.taskId?String(e.taskId):n.taskId)||null;if(!Me(s))return{ok:!0,skipped:!0,reason:"worker-not-finished"};if(n.localOnly)return{ok:!0,skipped:!0,reason:"local-only-worker"};if(!i)return{ok:!1,reason:"missing agentOsId"};let l=e.force===!0||e.force==="true";if(!l&&ua(n))return{ok:!0,skipped:!0,reason:"completion-already-acknowledged",httpStatus:200};if(!l&&Tg(n)&&y2(n),!s.finalResult&&s.alive===!1){let w=Bu({worker:n,status:s});w&&Wu(n,w)&&(ee(n.runId,n),n=_n(t,r),s=oe(n,Ju(o)))}if(!(e.skipPrHandoff===!0||e.skipPrHandoff==="true")&&!n.steerRestartRequired&&n.dispatched&&a){let w=Kg({worker:n,run:o,status:s});if(!w.ok)return bs(n,w.reason),{ok:!1,reason:w.reason,nextAction:w.nextAction,completionBlocked:!0};(w.prUrl||w.headCommit)&&(s=oe(n,Ju(o)),s=k2(s,w))}let u=s.gitAncestry.headIsAncestorOfBase===!1&&s.gitAncestry.head?s.gitAncestry.head:s.headCommit;if(n.dispatched&&!n.steerRestartRequired){let w=XE({changedFiles:s.changedFiles,finalResult:s.finalResult,prUrl:s.prUrl,headCommit:u,disposableArtifactsRemoved:n.disposableArtifactsRemoved});if(!w.allowed){let W=w.detail??`worktree completion blocked (${w.state})`;return bs(n,W),{ok:!1,reason:W,nextAction:"Clean the worktree (commit, open a PR, or `kynver worker discard-disposable --path <file>`), then rerun `kynver worker complete`.",completionBlocked:!0}}}try{SA({provider:n.provider??s.provider??null,finalResult:s.finalResult})}catch{}let d=pe(e.baseUrl?String(e.baseUrl):void 0),m=e.secret?String(e.secret):void 0,f=await fe(m,i,{baseUrl:d});a&&(await ku({worker:n,agentOsId:i,baseUrl:d,secret:f}),n=_n(t,r));let g=`${d}/api/agent-os/by-id/${encodeURIComponent(i)}/harness/completion`,h={...s};n.disposableArtifactsRemoved?.length&&(h.disposableArtifactsRemoved=n.disposableArtifactsRemoved),n.steerRestartRequired&&(h.steerRestartRequired=!0,h.pendingSteerEventIds=n.pendingSteerEventIds??[],n.dispatchSteerFenceEventId!=null&&(h.dispatchSteerFenceEventId=n.dispatchSteerFenceEventId));let y=_A({usage:s.usage,provider:n.provider??s.provider??null,model:typeof n.model=="string"?n.model:s.model??null}),v={source:"kynver-harness",agentOsId:i,runId:n.runId,workerName:n.name,taskId:a,leaseToken:n.leaseToken??null,startedAt:n.startedAt,finishedAt:s.lastActivityAt||new Date().toISOString(),...y?{workerUsage:y}:{},status:n.leaseToken?{...h,leaseToken:n.leaseToken}:h,workerInjection:{instructionPolicyFingerprint:n.instructionPolicyFingerprint??null,instructionPolicyEvidence:n.instructionPolicyEvidence??null,memoryQualityCapture:n.memoryQualityCapture??null,policyAt:n.instructionPolicyEvidence&&typeof n.instructionPolicyEvidence=="object"&&"policyAt"in n.instructionPolicyEvidence&&typeof n.instructionPolicyEvidence.policyAt=="string"?n.instructionPolicyEvidence.policyAt:null,personaSlug:n.personaSlug??null,personaEvidence:n.personaEvidence??null,contextEnvelopeEvidence:n.contextEnvelopeEvidence??null}},k=a&&n.leaseToken?{taskId:a,leaseToken:n.leaseToken}:null;if(k){if(rA(k),nA(k)){let w={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:{replayShortCircuited:!0}};return wu(n,n.runId,w),Du(n,s,{source:"harness-completion"}),bs(n,void 0),ka(n.runId,n.name),zr(n.runId,n.name),{ok:!0,httpStatus:200,response:{ok:!0,replayShortCircuited:!0},reason:"completion_replay_short_circuited",...s.prUrl?{prHandoff:{prUrl:s.prUrl}}:{}}}tA(k)}let b=await CA(g,f,v);if((b.status===401||b.status===403)&&!m){let w=await mw(i,{baseUrl:d});w&&w!==f&&(f=w,b=await CA(g,f,v))}if(b.ok){let w=ZC(b.parsed);if(!eE(w)){let L=`completion acknowledged but board not advanced: ${w.detail??(w.routeOutcome?`harness completion returned ${w.routeOutcome}`:"harness completion did not advance the linked task")}`;bs(n,L);let M={completionReportedAt:new Date().toISOString(),completionOutcome:"rejected",completionResponse:b.parsed};return wu(n,n.runId,M),k&&oh(k,"rejected"),{ok:!1,httpStatus:b.status,response:b.parsed,reason:L,completionBlocked:!0}}bs(n,void 0);let W=w.routeOutcome??"acknowledged",O={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:b.parsed};wu(n,n.runId,O),Du(n,s,{source:"harness-completion"}),k&&oh(k,"acknowledged"),ka(n.runId,n.name),zr(n.runId,n.name);let P=s.prUrl;return{ok:!0,httpStatus:b.status,response:b.parsed,reason:W,...P?{prHandoff:{prUrl:P}}:{}}}let _=b.status===401||b.status===403,S=f2(b.parsed)??(_?"runner token unauthorized":"non-2xx response"),R=_?`completion replay rejected (${b.status}): ${S}`:`completion replay failed (${b.status}): ${S}`;return bs(n,R),{ok:!1,httpStatus:b.status,response:b.parsed,completionBlocked:!0}}async function IA(e){try{let{runId:t,workerName:r}=Vu(e),n=_n(t,r),o=ae(n.runId),s=oe(n,Ju(o)),i=(e.agentOsId?String(e.agentOsId):n.agentOsId)||"",a=(e.taskId?String(e.taskId):n.taskId)||null;if(!Me(s)){console.log(JSON.stringify({worker:n.name,runId:n.runId,status:"skipped",reason:"worker-not-finished",workerStatus:s.status,alive:s.alive},null,2));return}if(n.localOnly){console.log(JSON.stringify({worker:n.name,runId:n.runId,status:"skipped",reason:"local-only-worker"},null,2));return}i||(console.error("worker complete requires --agent-os-id (or an agentOsId persisted at worker start)"),process.exit(1));let l=await Yu(e);console.log(JSON.stringify({worker:n.name,runId:n.runId,...l.skipped?{status:"skipped"}:{},...l.reason?{reason:l.reason}:{},...l.nextAction?{nextAction:l.nextAction}:{},...l.completionBlocked?{completionBlocked:l.completionBlocked}:{},agentOsId:i,taskId:a,httpStatus:l.httpStatus,response:l.response},null,2)),l.ok||process.exit(1)}catch(t){console.error(`worker complete failed: ${t.message}`),process.exit(1)}}function OA(e){let{run:t,workerName:r,worker:n}=e,o=oe(n,{base:t.base,baseCommit:t.baseCommit}),s=o.gitAncestry.headIsAncestorOfBase===!1&&o.gitAncestry.head?o.gitAncestry.head:void 0,i=Ao({alive:o.alive,finalResult:o.finalResult,changedFiles:o.changedFiles,gitAncestry:o.gitAncestry,headCommit:s}),a=n.completionBlocker,l=typeof a=="string"&&a?a:void 0,c=PA(l)?void 0:l,u=c?"blocked":o.status,d=c?"blocked":o.attention.state,m=EA(n.completionResponse),f=EA(m?.task),g=va(m?.outcome),h=va(m?.status),y=Array.isArray(m?.warnings)?m.warnings.filter(R=>typeof R=="string"&&R.trim().length>0):[],v=va(f?.prUrl)??va(m?.prUrl),k=va(n.completionReportedAt),b=m2({finished:Me(o),completionBlocker:c,completionOutcome:g,completionReportedAt:k}),_=g2({completionBlocker:c,completionOutcome:g,completionReportedAt:k,finished:Me(o)}),S=h2({changedFiles:o.changedFiles,headCommit:s,prUrl:v??void 0});return{worker:o.worker,status:u,attention:d,attentionReason:c??o.attention.reason,landingBlocked:o.finalResult?d==="needs_attention"||d==="blocked":!1,exitedWithoutFinalResult:!o.finalResult&&!o.alive,salvageState:i?.salvageable?"review_needed":"none",salvageReason:i?.salvageable?i.attentionReason:void 0,pid:o.pid,alive:o.alive,currentTool:o.currentTool,lastActivityAt:o.lastActivityAt,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary,heartbeatBlocker:o.heartbeatBlocker,changedFileCount:o.changedFiles.length,changedFiles:o.changedFiles,branch:o.branch,taskId:n.taskId??null,planId:n.planId??null,instructionPolicyFingerprint:typeof n.instructionPolicyFingerprint=="string"?n.instructionPolicyFingerprint:null,instructionPolicyRuleCount:(()=>{let R=n.instructionPolicyEvidence;if(!R||typeof R!="object")return null;let w=R.ruleSlugs;return Array.isArray(w)?w.length:null})(),leaseOwner:n.leaseOwner??null,model:typeof n.model=="string"?n.model:void 0,routingRule:typeof n.routingRule=="string"?n.routingRule:void 0,requestedModel:typeof n.requestedModel=="string"?n.requestedModel:void 0,headCommit:s,prUrl:v,handoffState:S,gitAncestry:o.gitAncestry,finalResult:o.finalResult,lifecycleStage:b,completionReportedAt:k,completionOutcome:n.completionOutcome??null,completionRouteStatus:h,completionRouteOutcome:g,completionWarnings:y,completionBlocker:c??null,checkpoint:{phase:o.lastHeartbeatPhase,summary:o.lastHeartbeatSummary,blocker:o.heartbeatBlocker},lastCommandHint:o.currentTool??o.lastHeartbeatSummary,failureReason:c??o.error??null,nextAction:_,ancestry:o.gitAncestry.relation,ancestryChecked:o.gitAncestry.checked}}function b2(e){let t=typeof e.status=="string"?e.status:"",r=typeof e.completionBlocker=="string"&&e.completionBlocker.trim().length>0?e.completionBlocker:void 0;return r&&!PA(r)?!1:typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim()||e.completionOutcome==="acknowledged"?!0:t==="done"}function v2(e,t){return{worker:e,status:"done",attention:"done",attentionReason:"metadata terminal worker; full status skipped in compact snapshot",alive:!1,pid:typeof t.pid=="number"?t.pid:void 0,branch:typeof t.branch=="string"?t.branch:void 0,taskId:t.taskId??null,planId:t.planId??null,model:typeof t.model=="string"?t.model:void 0,routingRule:typeof t.routingRule=="string"?t.routingRule:void 0,requestedModel:typeof t.requestedModel=="string"?t.requestedModel:void 0,lifecycleStage:t.completionReportedAt?"completion_acknowledged":"worker_finished",completionReportedAt:typeof t.completionReportedAt=="string"?t.completionReportedAt:null,completionOutcome:t.completionOutcome??null,localOnly:t.localOnly===!0,compactStatus:!0}}function Ra(e,t){let r={};for(let n of e){let o=n[t],s=typeof o=="string"&&o.trim()?o:"unknown";r[s]=(r[s]??0)+1}return r}function AA(e){if(e.attention!=="blocked")return!1;let t=typeof e.attentionReason=="string"?e.attentionReason:"";return t.includes("cli-config.json.tmp")||t.includes("Invalid authentication credentials")||t.includes("provider CLI is missing or not on PATH")||t.includes("unknown command:")}function R2(e){let t=e.filter(AA),r=e.filter(n=>{if(AA(n))return!1;let o=n.attention;return o==="needs_attention"||o==="blocked"||o==="stale"||n.status==="running"});return{actionableCount:r.length,runningCount:e.filter(n=>n.status==="running").length,blockedCount:e.filter(n=>n.attention==="blocked").length,staleCount:e.filter(n=>n.attention==="stale").length,needsAttentionCount:e.filter(n=>n.attention==="needs_attention").length,doneCount:e.filter(n=>n.status==="done").length,systemHealthBlockerCount:t.length,systemHealthBlockers:t.slice(0,10).map(n=>({worker:n.worker,status:n.status,attention:n.attention,attentionReason:n.attentionReason,model:n.model,routingRule:n.routingRule,lastActivityAt:n.lastActivityAt})),actionableWorkers:r.slice(0,25).map(n=>({worker:n.worker,status:n.status,attention:n.attention,attentionReason:n.attentionReason,taskId:n.taskId,planId:n.planId,model:n.model,routingRule:n.routingRule,lastActivityAt:n.lastActivityAt,nextAction:n.nextAction}))}}function TA(e,t,r){let n={runId:e.id,name:e.name,status:jl(e.status,t),repo:e.repo,workerCount:t.length,needsAttention:t.filter(o=>o.attention&&o.attention!=="ok"&&o.attention!=="done").map(o=>o.worker),workers:t};return r&&(n.summary={statusCounts:Ra(t,"status"),attentionCounts:Ra(t,"attention"),lifecycleCounts:Ra(t,"lifecycleStage")},n.controller=R2(t)),n}function w2(e){return e.status==="done"&&e.attention==="done"}function gh(e){let t=ae(e),n=Object.keys(t.workers||{}).map(s=>{let i=$(qu.join(G(t.id),"workers",B(s),"worker.json"),void 0);return i?OA({run:t,workerName:s,worker:i}):{worker:s,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=TA(t,n,!1);return ye(qu.join(G(t.id),"last-board.json"),o),o}function hh(e){let t=ae(e),n=Object.keys(t.workers||{}).map(i=>{let a=$(qu.join(G(t.id),"workers",B(i),"worker.json"),void 0);return a?b2(a)?v2(i,a):OA({run:t,workerName:i,worker:a}):{worker:i,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=n.filter(i=>!w2(i)),s=TA(t,o,!0);return s.status=jl(t.status,n),s.summary={...s.summary??{},totalWorkerCount:n.length,shownWorkerCount:o.length,omittedTerminalDoneWorkerCount:n.length-o.length,allStatusCounts:Ra(n,"status"),allAttentionCounts:Ra(n,"attention")},ye(qu.join(G(t.id),"last-board-compact.json"),s),s}async function NA(e,t){let r=String(e.run||""),n=String(e.agentOsId||"");if(!r||!n)return null;let o=gh(r),s=pe(e.baseUrl?String(e.baseUrl):void 0),i=await fe(e.secret?String(e.secret):void 0,n,{baseUrl:s}),a=`${s}/api/agent-os/by-id/${encodeURIComponent(n)}/harness/snapshot`,l=await de(a,i,{agentOsId:n,runId:r,source:t,snapshot:o},{agentOsId:n,baseUrl:s});return{ok:l.ok,httpStatus:l.status,response:l.response,authRefreshed:l.refreshedAuth,authRefreshFailure:l.authRefreshFailure}}var vs=p(()=>{"use strict";H();es();tE();We();z();Ul();SE();_e();eh();di();QE();Og();Su();hs();Hn();ks();Mu();D();Gu();Eg();mh();xA()});var DA=p(()=>{"use strict";We();z();D()});import{spawn as S2}from"node:child_process";import{existsSync as _2,openSync as x2,closeSync as MA}from"node:fs";import C2 from"node:path";function LA(e){let t=e.nodeExecutable??process.execPath,r=au({importMetaUrl:import.meta.url,explicitCliPath:e.cliPath,nodeExecutable:t});if(!r)return;let n=r.cliPath;if(!_2(n))return;let o=C2.join(e.workerDir,"auto-complete.log"),s;try{s=x2(o,"a")}catch{s=void 0}let i=["ignore",s??"ignore",s??"ignore"],a=[...r.argsPrefix,"worker","auto-complete","--run",e.runId,"--name",e.workerName];e.agentOsId&&a.push("--agent-os-id",e.agentOsId),e.baseUrl&&a.push("--base-url",e.baseUrl),e.secret&&a.push("--secret",e.secret);try{let l=S2(r.command,a,X({detached:be(),stdio:i,env:process.env}));return s!==void 0&&MA(s),l.unref(),{pid:l.pid,logPath:o,cliPath:n}}catch{if(s!==void 0)try{MA(s)}catch{}return}}var xye,BA=p(()=>{"use strict";D();Su();z();_e();vs();D();Gu();bg();H();DA();xye=360*60*1e3});var WA=p(()=>{"use strict"});function UA(e,t,r){le(e,["fetch","origin",r,"--prune"],{allowFailure:!0});let n=`origin/${r}`,o=Q(e,["worktree","add","-B",r,t,n]);if(o.status===0)return;let s=Q(e,["worktree","add","-b",r,t,"HEAD"]);if(s.status!==0){let i=o.stderr||o.stdout||s.stderr||s.stdout||"git worktree add failed for repair target branch";throw new Error(i)}}var FA=p(()=>{"use strict";ve()});import{createHash as E2}from"node:crypto";import{chmodSync as A2,mkdirSync as P2}from"node:fs";import $A from"node:os";import I2 from"node:path";function KA(e,t){return E2("sha256").update(e).digest("hex").slice(0,t)}function yh(e){let t=e.platform??process.platform,r=KA(e.agentOsId,12),n=KA(e.workerKey,16);if(t==="win32")return{socketPath:`${T2}kynver-worker-${r}-${n}`,socketDir:null,isNamedPipe:!0,relocated:!1};let o=I2.posix,s=e.homeDir??$A.homedir(),i=o.join(s,".kynver","brokers",r),a=o.join(i,`${n}.sock`);if(Buffer.byteLength(a,"utf8")<=O2)return{socketPath:a,socketDir:i,isNamedPipe:!1,relocated:!1};let l=o.join(e.tmpDir??$A.tmpdir(),`kynver-brokers-${r}`);return{socketPath:o.join(l,`${n}.sock`),socketDir:l,isNamedPipe:!1,relocated:!0}}function kh(e){e.socketDir&&(P2(e.socketDir,{recursive:!0,mode:448}),A2(e.socketDir,448))}var O2,T2,bh=p(()=>{"use strict";O2=100,T2="\\\\.\\pipe\\"});import N2 from"node:net";import{chmodSync as D2,unlinkSync as M2}from"node:fs";var wa,GA=p(()=>{"use strict";vr();cu();bh();tt();wa=class e{server;opts;now;fetchImpl;grantedTools;connections=new Set;sockets=new Set;revoked=!1;closed=!1;constructor(t){if(typeof t.identity?.verify!="function")throw new Error("WorkerBroker requires an explicit identity posture (S11) \u2014 see worker-broker/identity.ts");this.opts=t,this.now=t.now??Date.now,this.fetchImpl=t.fetchImpl??fetch,this.grantedTools=Xi(t.capabilities),this.server=N2.createServer(r=>{this.handleConnection(r)}),this.server.on("error",()=>{})}static async start(t){let r=new e(t);if(kh(t.address),await new Promise((n,o)=>{r.server.once("error",o),r.server.listen(t.address.socketPath,()=>{r.server.removeListener("error",o),n()})}),!t.address.isNamedPipe)try{D2(t.address.socketPath,384)}catch{}return r}get identitySummary(){return this.opts.identity.summary}get toolDescriptors(){return this.grantedTools.filter(ps).map(t=>ra[t])}async revoke(){this.revoked=!0,await this.close()}async close(){if(!this.closed){this.closed=!0;for(let t of this.sockets)t.destroy();if(this.sockets.clear(),this.connections.clear(),await new Promise(t=>this.server.close(()=>t())),!this.opts.address.isNamedPipe)try{M2(this.opts.address.socketPath)}catch{}}}refuse(t,r){this.opts.onRefusal?.(t,r)}async handleConnection(t){this.sockets.add(t),t.on("close",()=>{this.sockets.delete(t),this.connections.delete(t)});for(let o of this.connections)(o.destroyed||o.readableEnded)&&this.connections.delete(o);if(this.connections.size>=1){this.refuse("concurrent_connection","a second concurrent connection was attempted while the worker's own connection was open"),this.write(t,{id:"",ok:!1,reason:"concurrent_connection",error:"worker tools are already in use for this task"}),t.end();return}this.connections.add(t);let r=await this.opts.identity.verify({socket:t,workerPid:this.opts.workerPid});if(!r.ok){this.refuse("identity_refused",r.detail),this.write(t,{id:"",ok:!1,reason:"identity_refused",error:"caller could not be identified as this worker"}),t.end();return}let n="";t.setEncoding("utf8"),t.on("data",o=>{if(n+=o,Buffer.byteLength(n,"utf8")>1048576){this.refuse("request_too_large","request exceeded the line cap"),this.write(t,{id:"",ok:!1,reason:"request_too_large",error:"request exceeded the maximum size"}),t.end();return}let s=n.indexOf(`
|
|
168
|
+
`)}catch{}}function MA(e){if(zq(e.worktreePath))return{ok:!1,reason:"repo_owns_config",detail:"the repository tracks .agents/mcp_config.json \u2014 refusing to modify a tracked file in the worker's worktree"};let t=DA(e.worktreePath),r=Xq(t);if(ye in r)return{ok:!1,reason:"user_config_owns_server",detail:`the workspace MCP config already declares an "${ye}" server \u2014 refusing to overwrite it`};OA(Er.dirname(t),{recursive:!0});let n={mcpServers:{...r,[ye]:{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Nt]:e.brokerSocketPath}}}};return Yq(t,`${JSON.stringify(n,null,2)}
|
|
169
|
+
`,{mode:384}),Qq(e.worktreePath),{ok:!0,configPath:t}}function Ju(e){let t=DA(e);if(!wh(t))return!1;try{return IA(t,{force:!0}),IA(Er.dirname(t),{recursive:!1}),!0}catch{return!0}}var NA,Sh=p(()=>{"use strict";we();Sr();ot();NA=Er.join(".agents","mcp_config.json")});import{copyFileSync as Zq,existsSync as _h,mkdirSync as eY,readFileSync as tY,rmSync as rY,symlinkSync as nY,writeFileSync as oY}from"node:fs";import{homedir as sY}from"node:os";import Ar from"node:path";function LA(e){return Ar.join(e,iY)}function aY(e){return e.HOME?.trim()||e.USERPROFILE?.trim()||sY()}function lY(e=process.env){let t=e.GEMINI_CLI_HOME?.trim();return t?Ar.join(Ar.resolve(t),".gemini"):Ar.join(aY(e),".gemini")}function cY(e){if(!_h(e))return{};try{let t=JSON.parse(tY(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function uY(e){let t=e.mcpServers;return!t||typeof t!="object"||Array.isArray(t)?!1:ye in t}function dY(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function pY(e){return{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Nt]:e},trust:!0}}function BA(e){let t=e.env??process.env,r=lY(t),n=cY(Ar.join(r,"settings.json"));if(uY(n))return{ok:!1,reason:"user_config_owns_server",detail:`the Gemini CLI settings already declare an "${ye}" MCP server \u2014 refusing to write a duplicate stanza`};let o=LA(e.workerDir),s=Ar.join(o,".gemini");eY(s,{recursive:!0,mode:448});let i=n.mcpServers&&typeof n.mcpServers=="object"&&!Array.isArray(n.mcpServers)?n.mcpServers:{},a={...n,mcp:{...dY(n.mcp),autoAllowInHeadless:!0},mcpServers:{...i,[ye]:pY(e.brokerSocketPath)}};return oY(Ar.join(s,"settings.json"),`${JSON.stringify(a,null,2)}
|
|
170
|
+
`,{mode:384}),{ok:!0,geminiCliHome:o,authMode:fY(r,s)}}function fY(e,t){let r=["oauth_creds.json","google_accounts.json"],n="none";for(let o of r){let s=Ar.join(e,o);if(!_h(s))continue;let i=Ar.join(t,o);try{nY(s,i,"file"),n==="none"&&(n="symlink")}catch{try{Zq(s,i),n="copy"}catch{}}}return n}function qu(e){let t=LA(e);if(!_h(t))return!1;try{return rY(t,{recursive:!0,force:!0}),!0}catch{return!1}}var iY,xh=p(()=>{"use strict";Sr();ot();iY="gemini-home"});import mY from"node:path";function WA(e){return!!(typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim())}function hY(e){if(typeof e=="string"){let t=e.trim();return t.length?t:null}if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e,r=t.summary??t.finalSummary??t.message;if(typeof r=="string"&&r.trim())return r.trim();try{return JSON.stringify(e)}catch{return null}}return null}function Xr(e){let t=e.finalResult??null,r=typeof e.lastHeartbeatSummary=="string"?e.lastHeartbeatSummary:hY(t);return{finalResult:t??r??"completed",summary:r}}function Yu(e,t,r){if(WA(e)&&e.status==="done"&&e.completionSnapshot!=null)return;let n=new Date().toISOString(),o=Xr(t),s=r?.source?.trim();e.completionReportedAt=n,e.completionSnapshot=o,e.status="done",s&&(e.completionAckSource=s),X(e.runId,e),e.workerDir&&(ws(e.workerDir),ku(e.workerDir),_a(e.workerDir),qu(e.workerDir)),e.worktreePath&&(Vu(e.worktreePath),Ju(e.worktreePath))}function yY(e){let t=new Map,n=e.response?.tick?.filteredItems;if(!Array.isArray(n))return t;for(let o of n){if(o.kind!=="task"||typeof o.id!="string")continue;let s=typeof o.taskStatus=="string"?o.taskStatus.trim():"";s&&t.set(o.id,s)}return t}function UA(e,t,r={}){let n=yY(t);if(n.size===0)return[];let o=ne(e),s=[];for(let i of Object.keys(o.workers||{})){let a=F(mY.join(j(o.id),"workers",B(i),"worker.json"),void 0);if(!a?.taskId||WA(a))continue;let l=n.get(a.taskId);if(!l||l==="running"||!gY.has(l))continue;let c=ie(a,{base:o.base,baseCommit:o.baseCommit}),u;if(l==="cancelled"){let d=th(o.id,a,"board_task_cancelled","board task cancelled",r);u=!!(d.workerSignal||d.sidecarSignal)}Yu(a,c,{source:`board-task-${l}`}),s.push({worker:i,taskId:a.taskId,taskStatus:l,...u?{stopped:u}:{}})}return s}var gY,zu=p(()=>{"use strict";Y();Ce();M();ot();bh();vh();Rh();Sh();xh();Rs();gY=new Set(["awaiting_review","blocked","done","needs_input","waiting","scheduled","ready","cancelled","failed"])});function Xu(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"&&!Array.isArray(e)?Object.keys(e).length>0:!0}function kY(e){let t=e.lastHeartbeatPhase?.trim();if(!t||t==="complete")return null;let r=e.lastHeartbeatSummary?.trim();return r?{summary:r,handoffState:"exited_without_complete_heartbeat",lastHeartbeatPhase:t,...e.heartbeatBlocker?{blocker:e.heartbeatBlocker}:{}}:null}function bY(e){let t=wi(e);return t?{summary:t.reason,handoffState:"exit_failure",blocked:t.blocked}:null}function vY(e){let t=e.status.attention.reason?.trim()||e.status.error?.trim()||"process exited without a final result";return{summary:`Worker exited with an error: ${t}`,handoffState:"exited_without_final_result",blocked:!0,attentionState:e.status.attention.state,attentionReason:t,...e.heartbeat.lastHeartbeatPhase?{lastHeartbeatPhase:e.heartbeat.lastHeartbeatPhase}:{},...e.heartbeat.lastHeartbeatSummary?{lastHeartbeatSummary:e.heartbeat.lastHeartbeatSummary}:{},...e.heartbeat.heartbeatBlocker?{blocker:e.heartbeat.heartbeatBlocker}:{}}}function Qu(e){let{worker:t,status:r}=e;if(Xu(r.finalResult)){let u=Ie(t.heartbeatPath),d=ar(u),f=Xu(d)&&JSON.stringify(d)===JSON.stringify(r.finalResult)?"heartbeat_complete":"stdout_stream";return{finalResult:r.finalResult,source:f,snapshot:Xr(r)}}if(r.alive)return null;let n=Rn(t.stdoutPath);if(Xu(n.finalResult)){let u={...r,finalResult:n.finalResult};return{finalResult:n.finalResult,source:"stdout_stream",snapshot:Xr(u)}}let o=Ie(t.heartbeatPath),s=ar(o);if(Xu(s)){let u={...r,finalResult:s,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:s,source:"heartbeat_complete",snapshot:Xr(u)}}let i=bY(r.error??n.error);if(i){let u={...r,finalResult:i};return{finalResult:i,source:"exit_failure",snapshot:Xr(u)}}let a=kY(o);if(a){let u={...r,finalResult:a,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:a,source:"heartbeat_summary",snapshot:Xr(u)}}let l=vY({status:r,heartbeat:o}),c={...r,finalResult:l,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:l,source:"exit_no_final_result",snapshot:Xr(c)}}function Zu(e,t){return e.completionSnapshot?.finalResult!=null?!1:(e.completionSnapshot=t.snapshot,e.completionHandoffSource=t.source,!0)}var Ch=p(()=>{"use strict";vn();Lf();zu();Ri()});function ed(e){return e.filter(t=>{let r=t.trim(),n=r.startsWith("??")?r.slice(2).trim():r.length>3?r.slice(3).trim():r;return n!=="node_modules"&&!n.startsWith("node_modules/")})}function FA(e){let t=e.trim();return t.startsWith("??")?t.slice(2).trim():t.length>3&&/^[ MADRCU?!]{2} /.test(t.slice(0,3))?t.slice(3).trim():t}var Eh=p(()=>{"use strict"});function KA(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function $A(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function jA(e){let t=$A(e);if(!t)return[];let r=$A(t.worktreeHandoff),n=KA(r?.disposableArtifactsRemoved);return n.length?n:KA(t.disposableArtifactsRemoved)}function HA(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function VA(e,t){let r=ed(e);if(r.length===0)return!0;if(t.length===0)return!1;let n=new Set(t.map(o=>HA(o)));return r.every(o=>{let s=HA(FA(o));return n.has(s)})}var GA=p(()=>{"use strict";Eh()});function td(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function JA(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function RY(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function wY(e){let t=JA(e.disposableArtifactsRemoved),r=jA(e.finalResult);return[...new Set([...t,...r])]}function qA(e){let t=JA(e.changedFiles),r=ed(t),n=wY(e),o=r.length===0||VA(t,n);return td(e.prUrl)?o?{allowed:!0,state:"pr_handoff",materialDirtyCount:0}:{allowed:!1,state:"dirty_worktree",materialDirtyCount:r.length,detail:`Worktree has ${r.length} uncommitted change(s) with a PR attached; commit or discard before completing`}:td(e.headCommit)?o?{allowed:!0,state:"commit_handoff",materialDirtyCount:0}:{allowed:!1,state:"dirty_worktree",materialDirtyCount:r.length,detail:`Worktree has ${r.length} uncommitted change(s) on top of a commit; commit or discard before completing`}:td(e.artifactBundlePath)||td(e.patchPath)?o?{allowed:!0,state:"commit_handoff",materialDirtyCount:0}:{allowed:!1,state:"dirty_worktree",materialDirtyCount:r.length,detail:`Worktree has ${r.length} uncommitted change(s) with a patch/bundle handoff; clean the tree before completing`}:o?{allowed:!0,state:"clean",materialDirtyCount:0}:RY(e.finalResult)?{allowed:!1,state:"dirty_worktree_no_pr",materialDirtyCount:r.length,detail:`Worktree has ${r.length} uncommitted change(s) with no commit or PR; commit, open a PR, discard, or remove one-off files via \`kynver worker discard-disposable\` before completing`}:{allowed:!1,state:"dirty_worktree",materialDirtyCount:r.length,detail:`Worktree has ${r.length} uncommitted change(s) with no final result`}}var YA=p(()=>{"use strict";GA();Eh()});function Pr(e=process.env){return br(e).flags.dispatchReceipts}function Ah(e){return Pr(e)!=="off"}function Ph(e,t){return`dispatch:${e}:${t.taskId}:${t.leaseToken}`}function Ca(e,t,r){if(!Ah())return;let n=ue();if(n)try{n.recordOperationReceipt({idempotencyKey:Ph(e,t),operation:`dispatch-${e}`,resultJson:r===void 0?null:JSON.stringify(r)})}catch{st.storeFailures+=1}}function XA(e){Ca("claim",e,{runId:e.runId,workerName:e.workerName,provider:e.provider})}function rd(e){Ca("spawned",e)}function Ss(e,t){Ca("released",e,{reasonClass:t})}function QA(e){Ca("completion-sent",e)}function Ih(e,t){Ca("completion-acked",e,{outcome:t})}function ZA(e){if(!Ah())return!1;let t=ue();if(!t)return!1;try{let r=t.getOperationReceipt(Ph("completion-acked",e));if(r){let n=null;try{n=r.resultJson?JSON.parse(r.resultJson).outcome??null:null}catch{n=null}if(n==="acknowledged")return st.completionReplaysObserved+=1,!0}}catch{st.storeFailures+=1}return!1}function Oh(e){let t=String(e??"").split(":")[0]?.trim()??"";return t.length>0?t.slice(0,64):"unknown"}function eP(e){if(Pr()!=="enforce")return!1;let t=ue();if(!t)return!1;try{let r=t.getOperationReceipt(Ph("completion-acked",e));if(!r)return!1;let n=null;try{n=r.resultJson?JSON.parse(r.resultJson).outcome??null:null}catch{n=null}return n==="acknowledged"?(st.completionReplaysShortCircuited+=1,!0):!1}catch{return st.storeFailures+=1,!1}}function tP(e,t){if(Pr()!=="enforce")return;let r=ue();if(r)try{r.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${e}:${t}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:t})})}catch{st.storeFailures+=1}}function rP(e,t){if(Pr()!=="enforce")return[];let r=ue();if(!r)return[];let n=t?.nowMs??Date.now(),o=t?.windowMs??SY;try{return r.listOperationReceipts({operation:"dispatch-start-failed",recordedAfter:new Date(n-o).toISOString(),limit:200}).filter(s=>{try{return s.resultJson?JSON.parse(s.resultJson).runId===e:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(e.length+1))}).filter(s=>s.length>0)}catch{return st.storeFailures+=1,[]}}function xa(e){let t=e.split(":")[0]??"",r=Number(t);return Number.isInteger(r)&&r>=0?r:null}function nP(e){let t={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!Ah())return t;let r=ue();if(!r)return t;let n=e?.nowMs??Date.now(),o=e?.strandedAfterMs??_Y;try{let s=r.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-zA).toISOString(),limit:CY}),i=0,a=[];for(let c of s){let u=c.idempotencyKey.slice(15),d=Date.parse(c.recordedAt);if(!Number.isFinite(d)||n-d<o)continue;let f=r.getOperationReceipt(`dispatch:spawned:${u}`),m=r.getOperationReceipt(`dispatch:released:${u}`);if(f||m){n-d>=xY&&a.length+5<=EY&&a.push(c.idempotencyKey,`dispatch:spawned:${u}`,`dispatch:released:${u}`,`dispatch:completion-sent:${u}`,`dispatch:completion-acked:${u}`);continue}let g=u.split(":")[0]??"",h=xa(u.slice(g.length+1));if((g?r.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${g}:`,limit:10}):[]).some(b=>{if(h===null)return!0;let _=b.idempotencyKey.slice(`dispatch:completion-acked:${g}:`.length),S=xa(_);return S===null||S>=h}))continue;let k=!1;if(e?.hasLiveWorker&&c.resultJson)try{let b=JSON.parse(c.resultJson);b.runId&&b.workerName&&(k=e.hasLiveWorker({runId:b.runId,workerName:b.workerName}))}catch{k=!1}k||(i+=1)}let l=a.length>0?r.deleteOperationReceiptsByKeys(a):0;if(Pr()==="enforce"){let c=r.listOperationReceipts({limit:100}).filter(u=>{let d=Date.parse(u.recordedAt);return Number.isFinite(d)&&n-d>=zA}).map(u=>u.idempotencyKey);if(c.length>0){let u=r.deleteOperationReceiptsByKeys(c);l+=u,st.agedReceiptsPruned+=u}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:l}}catch{return st.storeFailures+=1,t}}function oP(){return{"dispatchReceipts.storeFailures":st.storeFailures,"dispatchReceipts.completionReplaysObserved":st.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":st.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":st.agedReceiptsPruned}}var st,SY,_Y,zA,xY,CY,EY,_s=p(()=>{"use strict";Jr();ls();st={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};SY=600*1e3;_Y=900*1e3,zA=10080*60*1e3,xY=1440*60*1e3,CY=500,EY=300});function sP(){Nh=!1}function Ir(e=process.env){return br(e).flags.admission}function nd(e,t){return`${Th}${e}:${t}`}function iP(e,t){if(Ir()==="off")return;let r=ue();if(r)try{r.tryReserveAdmission(nd(e,t),Dh,xs)}catch{Qr.storeFailures+=1}}function Ea(e,t){if(Ir()==="off")return;let r=ue();if(r)try{r.releaseAdmission(nd(e,t),Dh)}catch{Qr.storeFailures+=1}}function aP(e){let t={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(Ir()==="off")return t;let r=ue();if(!r)return t;try{let n=new Set(e.liveWorkers.map(f=>nd(f.runId,f.workerName))),o=r.listAdmissionReservations({keyPrefix:Th,limit:500}),s=new Set(o.map(f=>f.key)),i=[...n].filter(f=>!s.has(f)).length,a=o.filter(f=>!n.has(f.key)).length,l=!Nh;Nh=!0,!l&&i>0&&(Qr.missingForLive+=i);let c=0;for(let f of e.liveWorkers)r.tryReserveAdmission(nd(f.runId,f.workerName),Dh,xs),c+=1;let u=0;for(let f of o)n.has(f.key)||r.releaseAdmission(f.key,f.owner)&&(u+=1,Qr.deadSlotsReleased+=1);return{liveReservations:r.listAdmissionReservations({keyPrefix:Th,limit:500}).length,refreshed:c,deadReleased:u,missingForLive:i,orphaned:a,adoptionPass:l}}catch{return Qr.storeFailures+=1,t}}function lP(){return{"admission.storeFailures":Qr.storeFailures,"admission.missingForLive":Qr.missingForLive,"admission.deadSlotsReleased":Qr.deadSlotsReleased}}var xs,Dh,Th,Qr,Nh,zn=p(()=>{"use strict";Jr();ls();xs=900*1e3,Dh="admission-shadow",Th="worker-slot:",Qr={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Nh=!1});function cP(e){return`${Mh}${e}`}function sd(e,t){return`${e}:${t}`}function uP(e){if(Ir()!=="enforce")return{admitted:!0};let t=ue();if(!t)return{admitted:!0};let r=Math.max(0,Math.min(od,Math.floor(e.maxSlots)));if(e.diskActiveWorkers>=r)return Zr.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=sd(e.runId,e.workerName);for(let o=0;o<r;o+=1)if(t.tryReserveAdmission(cP(o),n,xs).acquired)return{admitted:!0,slot:o};return Zr.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return Zr.enforceStoreFailures+=1,{admitted:!0}}}function en(e,t){if(Ir()==="off")return;let r=ue();if(r)try{let n=sd(e,t),o=r.listAdmissionReservations({keyPrefix:Mh,limit:od});for(let s of o)s.owner===n&&r.releaseAdmission(s.key,n)}catch{Zr.enforceStoreFailures+=1}}function dP(e){let t={refreshed:0,deadReleased:0,adopted:0};if(Ir()!=="enforce")return t;let r=ue();if(!r)return t;try{let n=new Set(e.liveWorkers.map(c=>sd(c.runId,c.workerName))),o=r.listAdmissionReservations({keyPrefix:Mh,limit:od}),s=0,i=0,a=new Set;for(let c of o)n.has(c.owner)?(r.tryReserveAdmission(c.key,c.owner,xs),a.add(c.owner),s+=1):r.releaseAdmission(c.key,c.owner)&&(i+=1);let l=0;for(let c of e.liveWorkers){let u=sd(c.runId,c.workerName);if(!a.has(u)){for(let d=0;d<od;d+=1)if(r.tryReserveAdmission(cP(d),u,xs).acquired){l+=1;break}}}return{refreshed:s,deadReleased:i,adopted:l}}catch{return Zr.enforceStoreFailures+=1,t}}function pP(){return{"admission.enforceStoreFailures":Zr.enforceStoreFailures,"admission.refusedSlotsExhausted":Zr.admissionsRefusedSlots,"admission.refusedDiskBackstop":Zr.admissionsRefusedDiskBackstop}}var Mh,od,Zr,Cs=p(()=>{"use strict";Jr();zn();Mh="worker-slot-n:",od=64;Zr={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0}});import AY from"node:path";function Lh(e){let t=e.trim();if(!PY.test(t))throw new Error(`invalid run id: ${e}`);return t}function OY(e){let t=e.trim();if(!IY.test(t))throw new Error(`invalid worker name: ${e}`);return t}function gP(e){return typeof e=="string"?e.trim():""}function id(e){let t=gP(e.run),r=gP(e.name);return(!t||fP.has(t))&<(`missing --run RUN_ID (${mP})`),(!r||fP.has(r))&<(`missing --name WORKER_NAME (${mP})`),{runId:Lh(t),workerName:OY(r)}}function hP(e){let t=AY.resolve(e);if(t.includes(".."))throw new Error("repo path must not contain .. segments");return t}var PY,IY,fP,mP,ad=p(()=>{"use strict";M();PY=/^[a-z0-9][a-z0-9._-]{0,127}$/i,IY=/^[a-z0-9][a-z0-9._-]{0,63}$/i,fP=new Set(["undefined","null"]),mP="usage: kynver worker <action> --run RUN_ID --name WORKER_NAME"});import{existsSync as TY,mkdirSync as NY,readFileSync as DY,writeFileSync as MY}from"node:fs";import{homedir as LY}from"node:os";import yP from"node:path";function KY(e){let t=e?.trim();return!!(t&&BY.test(t))}function $Y(){let e=(process.env.KYNVER_PROVIDER_QUOTA_PREFLIGHT??"on").trim().toLowerCase();return e!=="off"&&e!=="0"&&e!=="false"&&e!=="no"}function Bh(){let e=Number.parseInt(process.env.KYNVER_PROVIDER_QUOTA_COOLDOWN_MINUTES??"",10);return Number.isFinite(e)?Math.min(FY,Math.max(UY,e)):WY}function kP(){let e=process.env.KYNVER_PROVIDER_QUOTA_STORE_PATH?.trim();return e||yP.join(LY(),".kynver","provider-quota-cooldowns.json")}function Aa(e){return(e??"").trim().toLowerCase()}function Wh(){let e=kP();if(!TY(e))return{};try{let t=JSON.parse(DY(e,"utf8"));if(!t||typeof t!="object"||Array.isArray(t))return{};let r={};for(let[n,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let{lastExhaustedAt:s,reason:i}=o;typeof s!="string"||!Number.isFinite(Date.parse(s))||(r[Aa(n)]={lastExhaustedAt:s,reason:typeof i=="string"?i.slice(0,500):""})}return r}catch{return{}}}function Uh(e){let t=kP();try{NY(yP.dirname(t),{recursive:!0}),MY(t,`${JSON.stringify(e,null,2)}
|
|
171
|
+
`,"utf8")}catch{}}function HY(e,t,r=Date.now()){let n=Aa(e);if(!n)return;let o=Wh();o[n]={lastExhaustedAt:new Date(r).toISOString(),reason:t.trim().slice(0,500)},Uh(o),K_(n,Bh()*6e4)}function jY(e){let t=Aa(e);if(!t)return!1;$_(t);let r=Wh();return t in r?(delete r[t],Uh(r),!0):!1}function bP(e,t=Date.now()){if(!$Y())return{ok:!0};let r=Aa(e);if(!r)return{ok:!0};let n=Wh(),o=n[r],s=!!(o&&Number.isFinite(Date.parse(o.lastExhaustedAt))&&Date.parse(o.lastExhaustedAt)+Bh()*6e4>t),i=H_(r,s);if(i)return i.blocked?{ok:!1,provider:r,reason:`provider "${r}" is inside its local quota cooldown`+(i.retryAtIso?` \u2014 preflight declines spawn until ${i.retryAtIso}`:""),retryAtIso:i.retryAtIso??new Date(t).toISOString()}:{ok:!0};if(!o)return{ok:!0};let a=Date.parse(o.lastExhaustedAt),l=a+Bh()*6e4;if(!Number.isFinite(a)||l<=t)return delete n[r],Uh(n),{ok:!0};let c=new Date(l).toISOString();return{ok:!1,provider:r,reason:`provider "${r}" reported quota exhaustion at ${o.lastExhaustedAt} \u2014 local preflight declines spawn until ${c}`+(o.reason?` (${o.reason.slice(0,160)})`:""),retryAtIso:c}}function VY(e){if(typeof e=="string"){let t=e.trim();return t.length?t:null}if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;for(let r of["result","summary","error"]){let n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}return null}function vP(e){let t=Aa(e.provider);if(!t)return"none";let r=VY(e.finalResult)??(typeof e.error=="string"&&e.error.trim()?e.error.trim():null);return r?KY(r)?(HY(t,r,e.nowMs??Date.now()),"recorded"):jY(t)?"cleared":"none":"none"}var BY,WY,UY,FY,Fh=p(()=>{"use strict";Gi();BY=/\b(out of usage|increase limits?|switch to auto|ask your admin to increase your limit|(?:hit|reached|exceeded|over) (?:your |the )?usage limits?|usage limits? (?:hit|reached|exceeded)|exceeded your (?:current )?quota|quota (?:exceeded|exhausted)|insufficient_quota|insufficient (?:credits?|quota)|credits? exhausted|credit balance is too low|billing hard limit|check your plan and billing|402 payment required|provider quota exhausted|provider_quota_exhausted)\b/i,WY=30,UY=5,FY=240});function RP(e){let t=e.usage;return!t||t.inputTokens===void 0&&t.outputTokens===void 0?null:{provider:e.provider?.trim()||"unknown",model:t.model?.trim()||e.model?.trim()||null,inputTokens:t.inputTokens??null,outputTokens:t.outputTokens??null}}var wP=p(()=>{"use strict"});import cd from"node:path";async function SP(e,t,r){let n=await fetch(e,{method:"POST",headers:It(t),body:JSON.stringify(r)}),o=null;try{o=await n.json()}catch{o=null}return{ok:n.ok,status:n.status,parsed:o}}function GY(e){if(e&&typeof e=="object"){let t=e.error;if(typeof t=="string"&&t.trim())return t.trim()}}function _P(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Pa(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function JY(e){return e.completionBlocker?`blocked:${e.completionBlocker}`:e.completionOutcome?e.completionOutcome:e.completionReportedAt?"completion_acknowledged":e.finished?"worker_finished":"in_progress"}function qY(e){return e.completionBlocker?"Resolve completion blocker, then rerun `kynver worker complete`.":e.completionOutcome==="review_scheduled"||e.completionOutcome==="review_already_scheduled"?"Await review lane and landing decision in Command Center.":e.completionOutcome==="needs_attention"?"Inspect blocker/attention reason in Command Center and dispatch a repair task.":e.finished&&!e.completionReportedAt?"Post completion acknowledgement to AgentOS (`kynver worker complete`).":null}function CP(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function YY(e){return e.prUrl?"pr_handoff":e.headCommit?"commit_handoff":e.changedFiles.length>0?"dirty_worktree":"none"}function Es(e,t){(e.completionBlocker??void 0)!==(t??void 0)&&(t?e.completionBlocker=t:delete e.completionBlocker,X(e.runId,e))}function zY(e){e.completionBlocker&&(delete e.completionBlocker,X(e.runId,e))}function ld(e){return e?{base:e.base,baseCommit:e.baseCommit}:{}}function XY(e,t){return{...e,...t.prUrl?{prUrl:t.prUrl}:{},...t.headCommit?{headCommit:t.headCommit}:{}}}async function As(e){let{runId:t,workerName:r}=id(e),n=On(t,r),o=ne(n.runId),s=ie(n,ld(o)),i=(e.agentOsId?String(e.agentOsId):n.agentOsId)||"",a=(e.taskId?String(e.taskId):n.taskId)||null;if(!Be(s))return{ok:!0,skipped:!0,reason:"worker-not-finished"};if(n.localOnly)return{ok:!0,skipped:!0,reason:"local-only-worker"};if(!i)return{ok:!1,reason:"missing agentOsId"};let l=e.force===!0||e.force==="true";if(!l&&ba(n))return{ok:!0,skipped:!0,reason:"completion-already-acknowledged",httpStatus:200};if(!l&&oh(n)&&zY(n),!s.finalResult&&s.alive===!1){let w=Qu({worker:n,status:s});w&&Zu(n,w)&&(X(n.runId,n),n=On(t,r),s=ie(n,ld(o)))}if(!(e.skipPrHandoff===!0||e.skipPrHandoff==="true")&&!n.steerRestartRequired&&n.dispatched&&a){let w=mh({worker:n,run:o,status:s});if(!w.ok)return Es(n,w.reason),{ok:!1,reason:w.reason,nextAction:w.nextAction,completionBlocked:!0};(w.prUrl||w.headCommit)&&(s=ie(n,ld(o)),s=XY(s,w))}let u=s.gitAncestry.headIsAncestorOfBase===!1&&s.gitAncestry.head?s.gitAncestry.head:s.headCommit;if(n.dispatched&&!n.steerRestartRequired){let w=qA({changedFiles:s.changedFiles,finalResult:s.finalResult,prUrl:s.prUrl,headCommit:u,disposableArtifactsRemoved:n.disposableArtifactsRemoved});if(!w.allowed){let L=w.detail??`worktree completion blocked (${w.state})`;return Es(n,L),{ok:!1,reason:L,nextAction:"Clean the worktree (commit, open a PR, or `kynver worker discard-disposable --path <file>`), then rerun `kynver worker complete`.",completionBlocked:!0}}}try{vP({provider:n.provider??s.provider??null,finalResult:s.finalResult})}catch{}let d=pe(e.baseUrl?String(e.baseUrl):void 0),f=e.secret?String(e.secret):void 0,m=await me(f,i,{baseUrl:d});a&&(await Tu({worker:n,agentOsId:i,baseUrl:d,secret:m}),n=On(t,r));let g=`${d}/api/agent-os/by-id/${encodeURIComponent(i)}/harness/completion`,h={...s};n.disposableArtifactsRemoved?.length&&(h.disposableArtifactsRemoved=n.disposableArtifactsRemoved),n.steerRestartRequired&&(h.steerRestartRequired=!0,h.pendingSteerEventIds=n.pendingSteerEventIds??[],n.dispatchSteerFenceEventId!=null&&(h.dispatchSteerFenceEventId=n.dispatchSteerFenceEventId));let y=RP({usage:s.usage,provider:n.provider??s.provider??null,model:typeof n.model=="string"?n.model:s.model??null}),v={source:"kynver-harness",agentOsId:i,runId:n.runId,workerName:n.name,taskId:a,leaseToken:n.leaseToken??null,startedAt:n.startedAt,finishedAt:s.lastActivityAt||new Date().toISOString(),...y?{workerUsage:y}:{},status:n.leaseToken?{...h,leaseToken:n.leaseToken}:h,workerInjection:{instructionPolicyFingerprint:n.instructionPolicyFingerprint??null,instructionPolicyEvidence:n.instructionPolicyEvidence??null,memoryQualityCapture:n.memoryQualityCapture??null,policyAt:n.instructionPolicyEvidence&&typeof n.instructionPolicyEvidence=="object"&&"policyAt"in n.instructionPolicyEvidence&&typeof n.instructionPolicyEvidence.policyAt=="string"?n.instructionPolicyEvidence.policyAt:null,personaSlug:n.personaSlug??null,personaEvidence:n.personaEvidence??null,contextEnvelopeEvidence:n.contextEnvelopeEvidence??null}},k=a&&n.leaseToken?{taskId:a,leaseToken:n.leaseToken}:null;if(k){if(ZA(k),eP(k)){let w={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:{replayShortCircuited:!0}};return Bu(n,n.runId,w),Yu(n,s,{source:"harness-completion"}),Es(n,void 0),Ea(n.runId,n.name),en(n.runId,n.name),{ok:!0,httpStatus:200,response:{ok:!0,replayShortCircuited:!0},reason:"completion_replay_short_circuited",...s.prUrl?{prHandoff:{prUrl:s.prUrl}}:{}}}QA(k)}let b=await SP(g,m,v);if((b.status===401||b.status===403)&&!f){let w=await iS(i,{baseUrl:d});w&&w!==m&&(m=w,b=await SP(g,m,v))}if(b.ok){let w=zE(b.parsed);if(!XE(w)){let W=`completion acknowledged but board not advanced: ${w.detail??(w.routeOutcome?`harness completion returned ${w.routeOutcome}`:"harness completion did not advance the linked task")}`;Es(n,W);let D={completionReportedAt:new Date().toISOString(),completionOutcome:"rejected",completionResponse:b.parsed};return Bu(n,n.runId,D),k&&Ih(k,"rejected"),{ok:!1,httpStatus:b.status,response:b.parsed,reason:W,completionBlocked:!0}}Es(n,void 0);let L=w.routeOutcome??"acknowledged",N={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:b.parsed};Bu(n,n.runId,N),Yu(n,s,{source:"harness-completion"}),k&&Ih(k,"acknowledged"),Ea(n.runId,n.name),en(n.runId,n.name);let A=s.prUrl;return{ok:!0,httpStatus:b.status,response:b.parsed,reason:L,...A?{prHandoff:{prUrl:A}}:{}}}let _=b.status===401||b.status===403,S=GY(b.parsed)??(_?"runner token unauthorized":"non-2xx response"),R=_?`completion replay rejected (${b.status}): ${S}`:`completion replay failed (${b.status}): ${S}`;return Es(n,R),{ok:!1,httpStatus:b.status,response:b.parsed,completionBlocked:!0}}async function EP(e){try{let{runId:t,workerName:r}=id(e),n=On(t,r),o=ne(n.runId),s=ie(n,ld(o)),i=(e.agentOsId?String(e.agentOsId):n.agentOsId)||"",a=(e.taskId?String(e.taskId):n.taskId)||null;if(!Be(s)){console.log(JSON.stringify({worker:n.name,runId:n.runId,status:"skipped",reason:"worker-not-finished",workerStatus:s.status,alive:s.alive},null,2));return}if(n.localOnly){console.log(JSON.stringify({worker:n.name,runId:n.runId,status:"skipped",reason:"local-only-worker"},null,2));return}i||(console.error("worker complete requires --agent-os-id (or an agentOsId persisted at worker start)"),process.exit(1));let l=await As(e);console.log(JSON.stringify({worker:n.name,runId:n.runId,...l.skipped?{status:"skipped"}:{},...l.reason?{reason:l.reason}:{},...l.nextAction?{nextAction:l.nextAction}:{},...l.completionBlocked?{completionBlocked:l.completionBlocked}:{},agentOsId:i,taskId:a,httpStatus:l.httpStatus,response:l.response},null,2)),l.ok||process.exit(1)}catch(t){console.error(`worker complete failed: ${t.message}`),process.exit(1)}}function AP(e){let{run:t,workerName:r,worker:n}=e,o=ie(n,{base:t.base,baseCommit:t.baseCommit}),s=o.gitAncestry.headIsAncestorOfBase===!1&&o.gitAncestry.head?o.gitAncestry.head:void 0,i=Mo({alive:o.alive,finalResult:o.finalResult,changedFiles:o.changedFiles,gitAncestry:o.gitAncestry,headCommit:s}),a=n.completionBlocker,l=typeof a=="string"&&a?a:void 0,c=CP(l)?void 0:l,u=c?"blocked":o.status,d=c?"blocked":o.attention.state,f=_P(n.completionResponse),m=_P(f?.task),g=Pa(f?.outcome),h=Pa(f?.status),y=Array.isArray(f?.warnings)?f.warnings.filter(R=>typeof R=="string"&&R.trim().length>0):[],v=Pa(m?.prUrl)??Pa(f?.prUrl),k=Pa(n.completionReportedAt),b=JY({finished:Be(o),completionBlocker:c,completionOutcome:g,completionReportedAt:k}),_=qY({completionBlocker:c,completionOutcome:g,completionReportedAt:k,finished:Be(o)}),S=YY({changedFiles:o.changedFiles,headCommit:s,prUrl:v??void 0});return{worker:o.worker,status:u,attention:d,attentionReason:c??o.attention.reason,landingBlocked:o.finalResult?d==="needs_attention"||d==="blocked":!1,exitedWithoutFinalResult:!o.finalResult&&!o.alive,salvageState:i?.salvageable?"review_needed":"none",salvageReason:i?.salvageable?i.attentionReason:void 0,pid:o.pid,alive:o.alive,currentTool:o.currentTool,lastActivityAt:o.lastActivityAt,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary,heartbeatBlocker:o.heartbeatBlocker,changedFileCount:o.changedFiles.length,changedFiles:o.changedFiles,branch:o.branch,taskId:n.taskId??null,planId:n.planId??null,instructionPolicyFingerprint:typeof n.instructionPolicyFingerprint=="string"?n.instructionPolicyFingerprint:null,instructionPolicyRuleCount:(()=>{let R=n.instructionPolicyEvidence;if(!R||typeof R!="object")return null;let w=R.ruleSlugs;return Array.isArray(w)?w.length:null})(),leaseOwner:n.leaseOwner??null,model:typeof n.model=="string"?n.model:void 0,routingRule:typeof n.routingRule=="string"?n.routingRule:void 0,requestedModel:typeof n.requestedModel=="string"?n.requestedModel:void 0,headCommit:s,prUrl:v,handoffState:S,gitAncestry:o.gitAncestry,finalResult:o.finalResult,lifecycleStage:b,completionReportedAt:k,completionOutcome:n.completionOutcome??null,completionRouteStatus:h,completionRouteOutcome:g,completionWarnings:y,completionBlocker:c??null,checkpoint:{phase:o.lastHeartbeatPhase,summary:o.lastHeartbeatSummary,blocker:o.heartbeatBlocker},lastCommandHint:o.currentTool??o.lastHeartbeatSummary,failureReason:c??o.error??null,nextAction:_,ancestry:o.gitAncestry.relation,ancestryChecked:o.gitAncestry.checked}}function QY(e){let t=typeof e.status=="string"?e.status:"",r=typeof e.completionBlocker=="string"&&e.completionBlocker.trim().length>0?e.completionBlocker:void 0;return r&&!CP(r)?!1:typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim()||e.completionOutcome==="acknowledged"?!0:t==="done"}function ZY(e,t){return{worker:e,status:"done",attention:"done",attentionReason:"metadata terminal worker; full status skipped in compact snapshot",alive:!1,pid:typeof t.pid=="number"?t.pid:void 0,branch:typeof t.branch=="string"?t.branch:void 0,taskId:t.taskId??null,planId:t.planId??null,model:typeof t.model=="string"?t.model:void 0,routingRule:typeof t.routingRule=="string"?t.routingRule:void 0,requestedModel:typeof t.requestedModel=="string"?t.requestedModel:void 0,lifecycleStage:t.completionReportedAt?"completion_acknowledged":"worker_finished",completionReportedAt:typeof t.completionReportedAt=="string"?t.completionReportedAt:null,completionOutcome:t.completionOutcome??null,localOnly:t.localOnly===!0,compactStatus:!0}}function Ia(e,t){let r={};for(let n of e){let o=n[t],s=typeof o=="string"&&o.trim()?o:"unknown";r[s]=(r[s]??0)+1}return r}function xP(e){if(e.attention!=="blocked")return!1;let t=typeof e.attentionReason=="string"?e.attentionReason:"";return t.includes("cli-config.json.tmp")||t.includes("Invalid authentication credentials")||t.includes("provider CLI is missing or not on PATH")||t.includes("unknown command:")}function ez(e){let t=e.filter(xP),r=e.filter(n=>{if(xP(n))return!1;let o=n.attention;return o==="needs_attention"||o==="blocked"||o==="stale"||n.status==="running"});return{actionableCount:r.length,runningCount:e.filter(n=>n.status==="running").length,blockedCount:e.filter(n=>n.attention==="blocked").length,staleCount:e.filter(n=>n.attention==="stale").length,needsAttentionCount:e.filter(n=>n.attention==="needs_attention").length,doneCount:e.filter(n=>n.status==="done").length,systemHealthBlockerCount:t.length,systemHealthBlockers:t.slice(0,10).map(n=>({worker:n.worker,status:n.status,attention:n.attention,attentionReason:n.attentionReason,model:n.model,routingRule:n.routingRule,lastActivityAt:n.lastActivityAt})),actionableWorkers:r.slice(0,25).map(n=>({worker:n.worker,status:n.status,attention:n.attention,attentionReason:n.attentionReason,taskId:n.taskId,planId:n.planId,model:n.model,routingRule:n.routingRule,lastActivityAt:n.lastActivityAt,nextAction:n.nextAction}))}}function PP(e,t,r){let n={runId:e.id,name:e.name,status:nc(e.status,t),repo:e.repo,workerCount:t.length,needsAttention:t.filter(o=>o.attention&&o.attention!=="ok"&&o.attention!=="done").map(o=>o.worker),workers:t};return r&&(n.summary={statusCounts:Ia(t,"status"),attentionCounts:Ia(t,"attention"),lifecycleCounts:Ia(t,"lifecycleStage")},n.controller=ez(t)),n}function tz(e){return e.status==="done"&&e.attention==="done"}function Kh(e){let t=ne(e),n=Object.keys(t.workers||{}).map(s=>{let i=F(cd.join(j(t.id),"workers",B(s),"worker.json"),void 0);return i?AP({run:t,workerName:s,worker:i}):{worker:s,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=PP(t,n,!1);return be(cd.join(j(t.id),"last-board.json"),o),o}function $h(e){let t=ne(e),n=Object.keys(t.workers||{}).map(i=>{let a=F(cd.join(j(t.id),"workers",B(i),"worker.json"),void 0);return a?QY(a)?ZY(i,a):AP({run:t,workerName:i,worker:a}):{worker:i,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=n.filter(i=>!tz(i)),s=PP(t,o,!0);return s.status=nc(t.status,n),s.summary={...s.summary??{},totalWorkerCount:n.length,shownWorkerCount:o.length,omittedTerminalDoneWorkerCount:n.length-o.length,allStatusCounts:Ia(n,"status"),allAttentionCounts:Ia(n,"attention")},be(cd.join(j(t.id),"last-board-compact.json"),s),s}async function IP(e,t){let r=String(e.run||""),n=String(e.agentOsId||"");if(!r||!n)return null;let o=Kh(r),s=pe(e.baseUrl?String(e.baseUrl):void 0),i=await me(e.secret?String(e.secret):void 0,n,{baseUrl:s}),a=`${s}/api/agent-os/by-id/${encodeURIComponent(n)}/harness/snapshot`,l=await de(a,i,{agentOsId:n,runId:r,source:t,snapshot:o},{agentOsId:n,baseUrl:s});return{ok:l.ok,httpStatus:l.status,response:l.response,authRefreshed:l.refreshedAuth,authRefreshFailure:l.authRefreshFailure}}var Ps=p(()=>{"use strict";$();Rs();as();QE();Fe();Y();Ql();vA();Ce();Ch();Ri();YA();nh();Wu();_s();zn();Cs();zu();M();ad();Qg();Fh();wP()});var OP=p(()=>{"use strict";Fe();Y();Rs();M()});import{spawn as rz}from"node:child_process";import{existsSync as nz,openSync as oz,closeSync as TP}from"node:fs";import sz from"node:path";function NP(e){let t=e.nodeExecutable??process.execPath,r=Ru({importMetaUrl:import.meta.url,explicitCliPath:e.cliPath,nodeExecutable:t});if(!r)return;let n=r.cliPath;if(!nz(n))return;let o=sz.join(e.workerDir,"auto-complete.log"),s;try{s=oz(o,"a")}catch{s=void 0}let i=["ignore",s??"ignore",s??"ignore"],a=[...r.argsPrefix,"worker","auto-complete","--run",e.runId,"--name",e.workerName];e.agentOsId&&a.push("--agent-os-id",e.agentOsId),e.baseUrl&&a.push("--base-url",e.baseUrl),e.secret&&a.push("--secret",e.secret);try{let l=rz(r.command,a,z({detached:Re(),stdio:i,env:process.env}));return s!==void 0&&TP(s),l.unref(),{pid:l.pid,logPath:o,cliPath:n}}catch{if(s!==void 0)try{TP(s)}catch{}return}}var Bve,DP=p(()=>{"use strict";M();Wu();Y();Ce();Ps();M();ad();jg();$();OP();Bve=360*60*1e3});var MP=p(()=>{"use strict"});function LP(e,t,r){ce(e,["fetch","origin",r,"--prune"],{allowFailure:!0});let n=`origin/${r}`,o=ee(e,["worktree","add","-B",r,t,n]);if(o.status===0)return;let s=ee(e,["worktree","add","-b",r,t,"HEAD"]);if(s.status!==0){let i=o.stderr||o.stdout||s.stderr||s.stdout||"git worktree add failed for repair target branch";throw new Error(i)}}var BP=p(()=>{"use strict";we()});import{createHash as iz}from"node:crypto";import{chmodSync as az,mkdirSync as lz}from"node:fs";import WP from"node:os";import cz from"node:path";function UP(e,t){return iz("sha256").update(e).digest("hex").slice(0,t)}function Hh(e){let t=e.platform??process.platform,r=UP(e.agentOsId,12),n=UP(e.workerKey,16);if(t==="win32")return{socketPath:`${dz}kynver-worker-${r}-${n}`,socketDir:null,isNamedPipe:!0,relocated:!1};let o=cz.posix,s=e.homeDir??WP.homedir(),i=o.join(s,".kynver","brokers",r),a=o.join(i,`${n}.sock`);if(Buffer.byteLength(a,"utf8")<=uz)return{socketPath:a,socketDir:i,isNamedPipe:!1,relocated:!1};let l=o.join(e.tmpDir??WP.tmpdir(),`kynver-brokers-${r}`);return{socketPath:o.join(l,`${n}.sock`),socketDir:l,isNamedPipe:!1,relocated:!0}}function jh(e){e.socketDir&&(lz(e.socketDir,{recursive:!0,mode:448}),az(e.socketDir,448))}var uz,dz,Vh=p(()=>{"use strict";uz=100,dz="\\\\.\\pipe\\"});import pz from"node:net";import{chmodSync as fz,unlinkSync as mz}from"node:fs";var Oa,HP=p(()=>{"use strict";Sr();Su();Vh();ot();Oa=class e{server;opts;now;fetchImpl;grantedTools;connections=new Set;sockets=new Set;revoked=!1;closed=!1;constructor(t){if(typeof t.identity?.verify!="function")throw new Error("WorkerBroker requires an explicit identity posture (S11) \u2014 see worker-broker/identity.ts");this.opts=t,this.now=t.now??Date.now,this.fetchImpl=t.fetchImpl??fetch,this.grantedTools=ia(t.capabilities),this.server=pz.createServer(r=>{this.handleConnection(r)}),this.server.on("error",()=>{})}static async start(t){let r=new e(t);if(jh(t.address),await new Promise((n,o)=>{r.server.once("error",o),r.server.listen(t.address.socketPath,()=>{r.server.removeListener("error",o),n()})}),!t.address.isNamedPipe)try{fz(t.address.socketPath,384)}catch{}return r}get identitySummary(){return this.opts.identity.summary}get toolDescriptors(){return this.grantedTools.filter(bs).map(t=>da[t])}async revoke(){this.revoked=!0,await this.close()}async close(){if(!this.closed){this.closed=!0;for(let t of this.sockets)t.destroy();if(this.sockets.clear(),this.connections.clear(),await new Promise(t=>this.server.close(()=>t())),!this.opts.address.isNamedPipe)try{mz(this.opts.address.socketPath)}catch{}}}refuse(t,r){this.opts.onRefusal?.(t,r)}async handleConnection(t){this.sockets.add(t),t.on("close",()=>{this.sockets.delete(t),this.connections.delete(t)});for(let o of this.connections)(o.destroyed||o.readableEnded)&&this.connections.delete(o);if(this.connections.size>=1){this.refuse("concurrent_connection","a second concurrent connection was attempted while the worker's own connection was open"),this.write(t,{id:"",ok:!1,reason:"concurrent_connection",error:"worker tools are already in use for this task"}),t.end();return}this.connections.add(t);let r=await this.opts.identity.verify({socket:t,workerPid:this.opts.workerPid});if(!r.ok){this.refuse("identity_refused",r.detail),this.write(t,{id:"",ok:!1,reason:"identity_refused",error:"caller could not be identified as this worker"}),t.end();return}let n="";t.setEncoding("utf8"),t.on("data",o=>{if(n+=o,Buffer.byteLength(n,"utf8")>1048576){this.refuse("request_too_large","request exceeded the line cap"),this.write(t,{id:"",ok:!1,reason:"request_too_large",error:"request exceeded the maximum size"}),t.end();return}let s=n.indexOf(`
|
|
108
172
|
`);for(;s>=0;){let i=n.slice(0,s);n=n.slice(s+1),i.trim()&&this.handleLine(t,i),s=n.indexOf(`
|
|
109
|
-
`)}})}write(t,r){if(!t.destroyed)try{t.write(dg(r))}catch{}}async handleLine(t,r){let n=pg(r);if(!n.ok){this.refuse(n.reason,n.error),this.write(t,{id:n.id,ok:!1,reason:n.reason,error:n.error});return}let{request:o}=n;if(this.revoked||this.closed){this.refuse("revoked","grant revoked"),this.write(t,{id:o.id,ok:!1,reason:"revoked",error:"worker tools are no longer available for this task"});return}if(this.now()>=this.opts.expiresAt){this.refuse("grant_expired","grant expired"),this.write(t,{id:o.id,ok:!1,reason:"grant_expired",error:"worker tools are no longer available for this task"});return}if(o.op==="list_tools"){this.write(t,{id:o.id,ok:!0,tools:this.toolDescriptors});return}if(!ps(o.name)){this.refuse("unknown_tool",o.name),this.write(t,{id:o.id,ok:!1,reason:"unknown_tool",error:`unknown tool: ${o.name}`});return}if(!this.grantedTools.includes(o.name)){this.refuse("capability_not_granted",o.name),this.write(t,{id:o.id,ok:!1,reason:"capability_not_granted",error:`tool not granted for this task: ${o.name}`});return}try{let s=await lu({apiBaseUrl:this.opts.apiBaseUrl,agentOsId:this.opts.agentOsId,taskId:this.opts.taskId,token:this.opts.token,fetchImpl:this.fetchImpl},o.name,o.args??{});this.write(t,{id:o.id,ok:!0,result:s})}catch(s){let i=s instanceof Error?s.message:"request failed";this.refuse("upstream_error",i),this.write(t,{id:o.id,ok:!1,reason:"upstream_error",error:i})}}}});function vh(){return JA}var JA,qA=p(()=>{"use strict";JA={posture:"scoped",summary:"scoped: per-worker endpoint in an owner-only (0700) directory, one connection at a time. Peer identity is not observed \u2014 another process of the same OS user is not excluded.",verify:async()=>({ok:!0})}});var YA=p(()=>{"use strict";vr()});var zA=p(()=>{"use strict";GA();qA();vr();cu();YA();Jg();bh()});import{existsSync as L2,mkdirSync as B2}from"node:fs";import Rs from"node:path";async function XA(e,t){let r=typeof t.name=="string"?t.name.trim():"";if(!r||r==="undefined"||r==="null")throw new Error(`worker name is required and must be a real identifier (got: ${JSON.stringify(t.name)})`);let n=B(r);if(e.workers?.[n])throw new Error(`worker already exists in run ${e.id}: ${n}`);if(!t.task)throw new Error(`missing task text for worker ${n}`);let o=t.routingRule||t.requestedModel?{provider:t.provider||br,model:t.model,rule:t.routingRule||"explicit:spawn",requestedModel:t.requestedModel??t.model}:gu({explicitModel:t.model,explicitProvider:t.provider,explicitProviderIsOperatorOverride:!!t.provider?.trim(),configuredProvider:E().workerProvider}),s=YC(o.provider),i=o.model;if(s.preflightModel){let T=s.preflightModel(t.model);if(!T.ok)throw new Error(`model preflight failed for provider "${s.name}": ${T.note??"invalid model/provider combination"}`);T.normalized&&console.error(`[supervisor] ${n}: ${T.note}`),i=T.model}let{worktreesDir:a}=me(),l=Rs.join(G(e.id),"workers",n);B2(l,{recursive:!0});let c=Rs.join(a,e.id,n),u=t.repairTargetBranch?.trim()||void 0,d=u||t.branch||`agent/${e.id}/${n}`;if(L2(c))throw new Error(`worktree path already exists: ${c}`);if(le(e.repo,["fetch","origin","--prune"],{allowFailure:!0}),u)UA(e.repo,c,u);else{let T=FC({baseCommit:e.baseCommit,base:e.base,verifyRef:x=>le(e.repo,["rev-parse","--verify","--quiet",`${x}^{commit}`],{allowFailure:!0}).trim().length>0});T.repaired&&(console.error(`[supervisor] ${n}: run baseCommit ${e.baseCommit||"<empty>"} invalid \u2014 repaired to ${T.ref} (${T.source})`),e.baseCommit=le(e.repo,["rev-parse",T.ref],{allowFailure:!0}).trim()||T.ref,je(e)),le(e.repo,["worktree","add","-b",d,c,e.baseCommit],{throwError:!0})}let m=Rs.join(l,"stdout.jsonl"),f=Rs.join(l,"stderr.log"),g=Rs.join(l,"heartbeat.jsonl"),h=GC({task:t.task,ownedPaths:t.ownedPaths||[],worktreePath:c,heartbeatPath:g,planId:t.planId,taskId:t.taskId,instructionPolicyMarkdown:t.instructionPolicyMarkdown,memoryQualityMarkdown:t.memoryQualityPromptMarkdown??t.memoryQualityCapture?.promptMarkdown??null,personaMarkdown:t.personaMarkdown,contextEnvelopeMarkdown:t.contextEnvelopeMarkdown,runtimeEnvelopeMarkdown:t.runtimeEnvelopeMarkdown,model:i,repairTargetPrUrl:t.repairTargetPrUrl,repairTargetBranch:t.repairTargetBranch??(u||void 0)}),y=process.env.KYNVER_HARNESS_TASK_ID,v=process.env.KYNVER_HARNESS_AGENT_OS_ID;t.taskId&&(process.env.KYNVER_HARNESS_TASK_ID=String(t.taskId)),t.agentOsId&&(process.env.KYNVER_HARNESS_AGENT_OS_ID=String(t.agentOsId));let k=xu({title:t.taskTitle,personaSlug:t.personaSlug,parentTaskId:t.parentTaskId,executorRef:t.executorRef}),b,_,S,R,w=t.workerMcpToken?.trim();if(w&&fg(s.name)&&Qi()){let T=Rn();T&&t.agentOsId&&t.taskId?(_={apiBaseUrl:T,agentOsId:String(t.agentOsId),taskId:String(t.taskId),token:w,capabilities:t.workerMcpCapabilities??null},console.error(`[supervisor] ${n}: worker tools enabled (in-process, no config on disk)`)):console.error(`[supervisor] ${n}: worker tools skipped (missing API base URL or task identity) \u2014 spawning without tools`)}let W=Qx(s.name);if(w&&W&&Qi()){let T=Rn();if(T&&t.agentOsId&&t.taskId){let x=yh({agentOsId:String(t.agentOsId),workerKey:l}),j=await wa.start({address:x,apiBaseUrl:T,agentOsId:String(t.agentOsId),taskId:String(t.taskId),token:w,capabilities:t.workerMcpCapabilities??null,expiresAt:t.workerMcpExpiresAt??Date.now()+W2,workerPid:process.pid,identity:vh(),onRefusal:I=>console.error(`[supervisor] ${n}: worker tools refused a call (${I})`)});if(Gg(l,j),s.name==="codex"){let I=OE({workerDir:l,brokerSocketPath:x.socketPath});if(I.ok){let K=TE(I.codexHome,wr());K.ok?(S=I.codexHome,b=S):(ga(l),await Vr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 codex rejected the generated config (${K.detail}); spawning with the normal environment`))}else await Vr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${I.detail}`)}else if(s.name==="cursor"){let I=PE({worktreePath:c,brokerSocketPath:x.socketPath});I.ok?b=I.configPath:(await Vr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${I.detail}`))}else if(s.name==="gemini"&&fs(pt())==="antigravity"){let I=WE({worktreePath:c,brokerSocketPath:x.socketPath});I.ok?b=I.configPath:(await Vr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${I.detail}`))}else if(s.name==="gemini"){let I=FE({workerDir:l,brokerSocketPath:x.socketPath});I.ok?(R=I.geminiCliHome,b=R):(await Vr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${I.detail}`))}else b=eC({workerDir:l,brokerSocketPath:x.socketPath});b&&console.error(`[supervisor] ${n}: worker tools enabled via broker (${j.identitySummary})`)}else console.error(`[supervisor] ${n}: worker MCP tools skipped (missing API base URL or task identity) \u2014 spawning without tools`)}let O;try{O=s.start({name:n,task:t.task,ownedPaths:t.ownedPaths,model:i,branch:d,worktreePath:c,workerDir:l,stdoutPath:m,stderrPath:f,heartbeatPath:g,prompt:h,reviewWorker:k,executionMode:t.executionMode??"write",..._?{workerToolGrant:_}:{},...S?{codexHome:S}:{},...R?{geminiCliHome:R}:{},...b?{mcpConfigPath:b,mcpAllowedTools:Xx(t.workerMcpCapabilities)}:{}})}catch(T){throw b&&(ou(l),Iu(c),ga(l),Nu(l),Tu(c),ms(l)),le(e.repo,["worktree","remove","--force",c],{allowFailure:!0}),le(e.repo,["branch","-D",d],{allowFailure:!0}),T}finally{y===void 0?delete process.env.KYNVER_HARNESS_TASK_ID:process.env.KYNVER_HARNESS_TASK_ID=y,v===void 0?delete process.env.KYNVER_HARNESS_AGENT_OS_ID:process.env.KYNVER_HARNESS_AGENT_OS_ID=v}let P=AC(O.model,i,s.defaultModel),N=E(),L=Qe(process.env,N),M=Oe().runnerId,V=Lo({boxKind:L.boxKind,config:N,env:process.env}),J={name:n,runId:e.id,status:"running",pid:O.pid,model:P,provider:o.provider,branch:d,worktreePath:c,workerDir:l,stdoutPath:m,stderrPath:f,heartbeatPath:g,ownedPaths:t.ownedPaths,...t.agentOsId?{agentOsId:String(t.agentOsId)}:{},...t.taskId?{taskId:String(t.taskId)}:{},...t.planId?{planId:String(t.planId)}:{},...t.instructionPolicyFingerprint?{instructionPolicyFingerprint:String(t.instructionPolicyFingerprint)}:{},...t.instructionPolicyEvidence?{instructionPolicyEvidence:t.instructionPolicyEvidence}:{},...t.memoryQualityCapture?{memoryQualityCapture:t.memoryQualityCapture}:{},...t.personaSlug?{personaSlug:String(t.personaSlug)}:{},...t.personaEvidence?{personaEvidence:t.personaEvidence}:{},...t.contextEnvelopeEvidence?{contextEnvelopeEvidence:t.contextEnvelopeEvidence}:{},...t.runtimeEnvelopeEvidence?{runtimeEnvelopeEvidence:t.runtimeEnvelopeEvidence}:{},...t.leaseOwner?{leaseOwner:String(t.leaseOwner)}:{},...t.leaseToken?{leaseToken:String(t.leaseToken)}:{},...t.dispatched?{dispatched:!0}:{},...!t.agentOsId||!t.taskId?{localOnly:!0}:{},routingRule:o.rule,...o.requestedModel?{requestedModel:o.requestedModel}:{},...o.orchestrationAudit?{orchestrationAudit:o.orchestrationAudit}:{},...t.executorRef?{executorRef:String(t.executorRef)}:{},...t.parentTaskId?{parentTaskId:String(t.parentTaskId)}:{},...t.taskTitle?{taskTitle:String(t.taskTitle)}:{},...t.taskPrUrl?{taskPrUrl:String(t.taskPrUrl)}:{},...t.repairTargetPrUrl?{repairTargetPrUrl:String(t.repairTargetPrUrl)}:{},...t.repairTargetBranch?{repairTargetBranch:String(t.repairTargetBranch)}:{},executionMode:t.executionMode??"write",boxKind:L.boxKind,boxId:V,runtimeId:M,startedAt:new Date().toISOString()};if(ee(e.id,J),Vg(l,O.pid),e.workers={...e.workers||{},[n]:{workerDir:l,statusPath:Rs.join(l,"worker.json")}},e.status="running",je(e),J.agentOsId&&J.taskId){let T;try{T=LA({runId:e.id,workerName:n,workerDir:l,agentOsId:J.agentOsId})}catch(x){let j=`completion sidecar failed to spawn: ${x.message}`;J.completionBlocker=j,ee(e.id,J)}if(T)T.pid&&(J.completionSidecarPid=T.pid,ee(e.id,J));else{let x="completion sidecar failed to spawn (CLI not found or spawn error)";J.completionBlocker=x,J.completionSidecarSpawnFailedAt=new Date().toISOString(),ee(e.id,J)}}return J}var W2,QA=p(()=>{"use strict";ve();z();z();$C();JC();D();qc();In();zC();BA();WA();FA();De();Bo();H();tt();qg();Yg();Wn();Zg();$n();Xg();zA();mr();Mg();W2=7200*1e3});function U2(e,t){let r=He(t)?.trim();return r||Ce("KYNVER_RUNNER_TOKEN",e)||Ce("OPENCLAW_RUNNER_TOKEN",e)||null}function F2(e){let t=Pe()?.trim();return t||Ce("KYNVER_API_KEY",e)||Ce("KYNVER_RUNTIME_SECRET",e)||Ce("KYNVER_CRON_SECRET",e)||Ce("OPENCLAW_CRON_SECRET",e)||null}async function ZA(e,t={}){let r=t.env??process.env,n=t.nowMs??Date.now(),o=t.timeoutMs??8e3,s=new Date(n).toISOString(),i=t.fetcher??fetch,a=U2(r,e.agentOsId),l=F2(r),c="none",u={};if(a)c="runner_token",u["X-Kynver-Runner-Token"]=a;else if(l)c="api_key",u["X-Kynver-Service-Secret"]=l;else return{reachable:!1,authSource:"none",endpoint:null,httpStatus:null,responseMs:null,probedAt:s,error:"No runner token or API key found \u2014 set KYNVER_RUNNER_TOKEN, store runnerToken in ~/.kynver/credentials, or complete M0.3 install"};let d=`${e.apiBaseUrl}/api/agent-os/runner-token/verify`,m=Date.now();try{let f=AbortSignal.timeout(o),g=await i(d,{method:"GET",headers:{...u,Accept:"application/json","X-Kynver-Agent-Os-Id":e.agentOsId},signal:f}),h=Date.now()-m,y=g.status<500;return{reachable:y,authSource:c,endpoint:d,httpStatus:g.status,responseMs:h,probedAt:s,error:y?null:`MCP endpoint returned HTTP ${g.status} \u2014 server error or misconfigured KYNVER_API_URL`}}catch(f){let g=Date.now()-m,h=f instanceof Error?f.message:String(f);return{reachable:!1,authSource:c,endpoint:d,httpStatus:null,responseMs:g,probedAt:s,error:`MCP endpoint unreachable: ${h}`}}}var eP=p(()=>{"use strict";H();bt()});function $2(e,t){let r=e.KYNVER_API_URL?.trim()||e.KYNVER_CRON_FIRE_BASE_URL?.trim()||t.apiBaseUrl?.trim()||null;return r?rr(r)??null:null}function K2(e,t){return(e.KYNVER_DEFAULT_REPO?.trim()||e.KYNVER_HARNESS_REPO?.trim()||t.defaultRepo?.trim()||null)??null}function H2(e,t,r){let n=e.KYNVER_HARNESS_ROOT?.trim()||t.harnessRoot?.trim()||null;return n||r||null}function tP(e,t={}){let r=t.env??process.env,n=t.nowMs??Date.now(),o=t.config??{},s=$2(r,o);if(!s)return{ok:!1,code:"missing_api_base_url",detail:"No API base URL found. Set KYNVER_API_URL, or run `kynver setup --api-base-url <url>`."};let i=(r.KYNVER_AGENT_OS_ID??r.OPENCLAW_AGENT_OS_ID??o.agentOsId??"").trim();if(i&&i!==e.agentOsId)return{ok:!1,code:"workspace_mismatch",detail:`envelope workspace "${e.agentOsId}" does not match local config "${i}"`};let a=K2(r,o),l=H2(r,o,a);return{ok:!0,context:{jobId:e.jobId,agentOsId:e.agentOsId,taskId:e.taskId,repoPath:a,worktreeBase:l,apiBaseUrl:s,hydratedAt:new Date(n).toISOString()}}}var rP=p(()=>{"use strict";nr()});var Sa=p(()=>{"use strict"});var _a=p(()=>{"use strict"});var wh=p(()=>{"use strict";H();_a()});var _h=p(()=>{"use strict";Sa()});import{mkdirSync as oP}from"node:fs";import{homedir as j2,tmpdir as Zke}from"node:os";import zu from"node:path";function sP(){let e=process.env.KYNVER_STATE_ROOT;return e?zu.resolve(e):zu.join(j2(),".kynver","state")}function Xu(){return zu.join(sP(),"plan-outbox")}function V2(){return zu.join(sP(),"plan-outbox-archive")}function iP(){let e=Xu(),t=V2();return oP(e,{recursive:!0}),oP(t,{recursive:!0}),{outboxDir:e,archiveDir:t}}var xa=p(()=>{"use strict"});function aP(){return{"planOutbox.storeFailures":Ca.storeFailures,"planOutbox.corruptItemsSeen":Ca.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":Ca.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":Ca.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":Ca.halfArchivesCompleted}}var obe,Ca,Ea=p(()=>{"use strict";Hr();ts();obe=600*1e3,Ca={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0}});import{existsSync as q2,readFileSync as Y2,renameSync as lbe,readdirSync as cbe,rmSync as ube,writeFileSync as dbe,unlinkSync as pbe}from"node:fs";import lP from"node:path";function cP(e){if(!q2(e))return null;try{return JSON.parse(Y2(e,"utf8"))}catch{return null}}function Qu(e){let{outboxDir:t}=iP();return{jsonPath:lP.join(t,`${e.id}.json`),bodyPath:lP.join(t,e.bodyPath)}}var Aa=p(()=>{"use strict";Ea();Sa();_h();xa()});var uP=p(()=>{"use strict";Sa();_a();wh()});var xh=p(()=>{"use strict";wh();_a();_h();xa();Ea();Aa();uP()});import tY from"node:path";function Ch(e){let t=tY.join(Xu(),`${e}.json`);return cP(t)}var dP=p(()=>{"use strict";Aa();Ea();xh();xa()});function Eh(e){let t=Qu(e);return["## Plan persistence risk","",`AgentOS plan write is **not** confirmed (${e.userStatus}).`,`- outboxId: \`${e.id}\``,e.planId?`- planId: \`${e.planId}\``:"- planId: (pending \u2014 create not yet applied)",`- outbox: \`${t.jsonPath}\``,`- body: \`${t.bodyPath}\``,"","Drain when approval/connectivity returns: `kynver plan outbox drain`"].join(`
|
|
110
|
-
`)}function
|
|
111
|
-
`),
|
|
112
|
-
`)}var
|
|
113
|
-
`)}function IY(e){let t=new Set;if(e.targetTaskId)return t.add(String(e.targetTaskId)),t;if(e.targetTaskIds)for(let r of String(e.targetTaskIds).split(",")){let n=r.trim();n&&t.add(n)}return t}async function Ss(e){let t=e.pipeline===!0||e.pipeline==="true";try{let ue=function(){return I.filter(A=>A.started).length},Te=function(A,C){ji({runId:l.id,agentOsId:u,phase:A,startedCount:ue(),outcomeCount:I.length,cappedStarts:P,...C})},er=function(){return I.some(A=>(typeof A.error=="string"?A.error:"").startsWith("dispatch_start_readback_failed:"))},Gb=function(A){return A.landPrDispatch===!0?!0:A.task?.executor==="land_pr"};var r=ue,n=Te,o=er,s=Gb;let i=hP();if(!i.ok||!i.identity){let A=yP(i);if(t)return{ok:!1,error:A,boundary:i};console.error(`run dispatch failed: ${A}`),process.exit(1)}let a=i.identity;for(let A of i.warnings)console.error(`[dispatch] runner-boundary warning: ${A}`);let l=ae(String(vt(String(e.run||""),"--run"))),c=mP(l,a);if(!c.ok){let A=c.reason??"run does not belong to this runner boundary";if(t)return{ok:!1,error:A,runId:l.id,runnerBoundary:a};console.error(`run dispatch failed: ${A}`),process.exit(1)}c.stamped&&console.error(`[dispatch] stamped run ${l.id} with boxKind=${a.boxKind} runnerId=${a.runnerId}`);let u=String(vt(String(e.agentOsId||""),"--agent-os-id")),d=pe(e.baseUrl?String(e.baseUrl):void 0),m=await fe(e.secret?String(e.secret):void 0,u,{baseUrl:d}),f=e.execute===!0||e.execute==="true",g=!f,h=Oe({runId:l.id}),y=la(l.id,h.runnerId),v=Pw(),k=v?Rc(l.repo):null,b=new WeakMap;if(v&&f&&!k){let A="desktop_execution_policy_denied:repo_identity_unavailable: the repository has no origin remote";if(t)return{ok:!1,error:A,runId:l.id};console.error(`run dispatch failed: ${A}`),process.exit(1)}let _=e.diskPath?Dr({diskPath:String(e.diskPath)}):Dr({diskPath:l.repo}),S=await lx({runId:l.id,agentOsId:u,args:e}),R=IY(e),w=R.size>0,W=Number(e.maxStarts)>0?Math.floor(Number(e.maxStarts)):1,O=w?Math.min(W,R.size):W;if(e.reconcileStaleBlockers===!0||e.reconcileStaleBlockers==="true"){let A=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/lane-hygiene`;try{await de(A,m,{agentOsId:u,dryRun:!1,includeBoardReconcile:!0},{agentOsId:u,baseUrl:d})}catch(C){console.error(`[dispatch] reconcile-stale-blockers lane-hygiene call failed: ${C.message}`)}}let P=g?O:Math.min(O,S.slotsAvailable);if(!g&&P<=0){let A={runId:l.id,agentOsId:u,dryRun:!1,skipped:!0,reason:S.reason??"no resource slots",resourceGate:S};if(t)return{ok:!0,...A};console.log(JSON.stringify(A,null,2));return}let N=Vo(l.id),L=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/tasks/dispatch-next`,M=(A,C)=>({agentOsId:u,...C?{claimAuthorization:C}:{},dryRun:g,maxStarts:A,leaseOwner:y,leaseDurationMs:Number(e.leaseMs)>0?Math.floor(Number(e.leaseMs)):Pg,runnerDiskGate:_,runnerResourceGate:S,activeHarnessWorkers:N,runnerPresence:h,harnessBoardSnapshot:gh(l.id),...e.lane?{lane:ix(String(e.lane))}:{},...e.executor?{executor:String(e.executor)}:{},...e.diskPath?{diskPath:String(e.diskPath)}:{},...e.targetTaskId?{targetTaskId:String(e.targetTaskId)}:{},...!e.targetTaskId&&e.targetTaskIds?{targetTaskIds:String(e.targetTaskIds).split(",").map(U=>U.trim()).filter(Boolean)}:{}}),V=Q_(),J=async A=>{let C=v&&k?Nw(k):void 0,U=await de(L,m,M(A,C),{agentOsId:u,baseUrl:d,timeoutMs:V})??{ok:!1,status:0,response:null},Y=U.response;if(C&&Array.isArray(Y?.result?.started))for(let ne of Y.result.started)ne&&typeof ne=="object"&&b.set(ne,C.requestNonce);return{dispatch:U,result:Y?.result}};g||ji({runId:l.id,agentOsId:u,phase:"awaiting_dispatch_next",timeoutMs:V});let T=await J(w||g?P:1);if(!T.dispatch.ok||!T.result){let A=Vm(T.dispatch.response),C={runId:l.id,agentOsId:u,action:"dispatch",httpStatus:T.dispatch.status,response:T.dispatch.response,authRefreshed:T.dispatch.refreshedAuth===!0,authRefreshFailure:T.dispatch.authRefreshFailure,...A?{timeout:!0}:{}};if(A&&ji({runId:l.id,agentOsId:u,phase:"timeout",timeout:!0,httpStatus:T.dispatch.status}),t)return{ok:!1,...C};console.log(JSON.stringify(C,null,2)),process.exit(1)}let x=T.result;if(g){let A=eI(x),C=tI(x),U={runId:l.id,agentOsId:u,dryRun:!0,wouldStart:x.started.map(Y=>({taskId:Y.task.id,title:Y.task.title,reason:Y.reason})),skipped:x.skipped.map(Y=>({taskId:Y.task.id,skipReason:Y.skipReason,reason:Y.reason})),diskGate:x.diskGate,resourceGate:x.resourceGate,inspected:x.inspected,pagesScanned:x.pagesScanned??null,candidatesExhausted:x.candidatesExhausted??null,capacityIdle:A?.capacityIdle===!0,admissionExhaustion:A,dispatchSkipDrain:C};if(t)return{ok:!0,...U};console.log(JSON.stringify(U,null,2));return}let j=NC(),I=[],K=[],F=Number(x.inspected)||0,Z=!1;async function te(A,C,U){let Y=await Pa({baseUrl:d,secret:m,agentOsId:u,taskId:String(A.id),leaseOwner:y,leaseToken:A.leaseToken?String(A.leaseToken):null,failureDetail:C});A.leaseToken&&gs({taskId:String(A.id),leaseToken:String(A.leaseToken).trim()},sh(C));let ne={taskId:A.id,started:!1,error:C,released:Y.released,releaseResponse:Y.releaseResponse,...U};return I.push(ne),Te("outcome",{lastOutcome:ne}),!1}async function RW(A){let C=A.task,U=String(C.id);if(w&&!R.has(U))return te(C,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[...R]});if(!(C.prUrl?String(C.prUrl):""))return te(C,"land_pr task missing prUrl");try{let ne=await $P({decision:A,baseUrl:d,secret:m,agentOsId:u,cwd:l.repo,operation:{agentOsId:u,taskId:U,runId:l.id,workerName:`land-pr-${U}`,leaseOwner:y,leaseToken:typeof C.leaseToken=="string"?C.leaseToken:"",receiptDir:`${G(l.id)}/land-pr-operations`}}),kt=await HP({baseUrl:d,secret:m,agentOsId:u,runId:l.id,task:C,report:ne});return kt.ok?(I.push({taskId:U,started:!0,landPr:!0,outcome:ne.outcome,completionStatus:kt.status}),!0):te(C,`land_pr completion POST failed (HTTP ${kt.status})`,{landPr:!0,outcome:ne.outcome})}catch(ne){return te(C,ne.message)}}async function wW(A){let C="duplicate_dispatch_prevented: live local worker already owns this task",U=await Pa({baseUrl:d,secret:m,agentOsId:u,taskId:String(A.id),leaseOwner:y,leaseToken:A.leaseToken?String(A.leaseToken):null,failureDetail:C});A.leaseToken&&gs({taskId:String(A.id),leaseToken:String(A.leaseToken).trim()},sh(C));let Y={taskId:A.id,started:!1,error:C,alreadyRunning:!0,nonFatal:!0,released:U.released,releaseResponse:U.releaseResponse};return I.push(Y),Te("outcome",{lastOutcome:Y}),!1}async function SW(A){let C=A.task,U=CY(A),Y=String(C.id);if(w&&!R.has(Y))return te(C,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[...R]});let ne=EY(C.personaSlug);if(ne&&(!U?.personaInjectionReady||!U.personaMarkdown))return te(C,`persona_injection_required: missing anchored context-envelope persona block for "${ne}"`);if(ne&&!U?.runtimeEnvelopeReady)return te(C,`runtime_envelope_required: missing AgentRuntimeEnvelope launch receipt for persona "${ne}"`);if(WC(l.id,Y))return wW(C);let kt=Number(C.attempt)||1;if(kt>j.maxTaskAttempts)return te(C,`task attempt ${kt} exceeds KYNVER_MAX_TASK_ATTEMPTS (${j.maxTaskAttempts})`);let cn=C.leaseToken?String(C.leaseToken).trim():"";if(!cn)return te(C,"dispatch_start_failed: claimed task missing leaseToken \u2014 refusing local spawn");let ko=B(`t-${C.id}-a${C.attempt}`),tr=gu({explicitModel:e.model?String(e.model):void 0,explicitProvider:e.provider?String(e.provider):void 0,explicitProviderIsOperatorOverride:!!e.provider,configuredProvider:E().workerProvider,task:ux(C)});eA({taskId:Y,leaseToken:cn,runId:l.id,workerName:ko,provider:tr.provider??null});let Up=IC({task:C,routing:tr,explicitProvider:e.provider?String(e.provider):void 0,explicitModel:e.model?String(e.model):void 0});if(!Up.ok)return te(C,Up.error??"model_routing_mismatch",{modelRoutingGuard:Up});if(XP(C)){let Ye=await QP({agentOsId:u,taskId:Y,baseUrl:d,secret:m});if(Ye&&Ye.dispatchable===!1)return te(C,`pr_review_head_reconcile_blocked: ${Ye.reason??Ye.outcome??"stale PR head"}`,{headReconcile:Ye});if(Ye?.activeReviewTaskId&&Ye.activeReviewTaskId!==Y)return te(C,`pr_review_head_reconcile_retargeted: active review is ${Ye.activeReviewTaskId}`,{headReconcile:Ye})}let kl=wA(tr.provider);if(!kl.ok)return te(C,`provider_quota_exhausted: ${kl.reason}`,{nonFatal:!0,providerQuotaPreflight:{provider:kl.provider,retryAt:kl.retryAtIso}});try{let Ye=C.planId?String(C.planId):void 0,bl=HC({title:C.title?String(C.title):void 0,description:C.description?String(C.description):null,executorRef:C.executorRef?String(C.executorRef):null,prUrl:C.prUrl?String(C.prUrl):null,branch:C.branch?String(C.branch):null}),Qb=fA({runId:l.id,workerName:ko,maxSlots:S.maxConcurrentWorkers,diskActiveWorkers:hf()});if(!Qb.admitted)return te(C,`admission_refused: ${Qb.reason}`,{nonFatal:!0});let vl=U?.workerMcpToken??null;if(vl&&Qi()){let bo=tP({jobId:`dispatch:${String(C.id)}`,agentOsId:u,taskId:String(C.id)},{config:{agentOsId:u,apiBaseUrl:d}});if(!bo.ok)console.error(`[dispatch] worker tools skipped for task ${String(C.id)}: context hydration failed (${bo.code}: ${bo.detail}) \u2014 spawning without tools`),vl=null;else{let Fp=await ZA(bo.context);Fp.reachable||(console.error(`[dispatch] worker tools skipped for task ${String(C.id)}: tool endpoint probe failed (${Fp.error??`HTTP ${Fp.httpStatus}`}) \u2014 spawning without tools`),vl=null)}}let Tt=await XA(l,{name:ko,task:PY(C,u),ownedPaths:e.owned?String(e.owned).split(",").map(bo=>bo.trim()).filter(Boolean):[],model:tr.model,provider:tr.provider,routingRule:tr.rule,requestedModel:tr.requestedModel,agentOsId:u,taskId:String(C.id),planId:Ye,branch:bl?.targetPrBranch??void 0,executorRef:C.executorRef?String(C.executorRef):void 0,parentTaskId:C.parentTaskId?String(C.parentTaskId):void 0,taskTitle:C.title?String(C.title):void 0,taskPrUrl:bl?.targetPrUrl??(C.prUrl?String(C.prUrl):void 0),repairTargetPrUrl:bl?.targetPrUrl,repairTargetBranch:bl?.targetPrBranch??void 0,instructionPolicyMarkdown:U?.instructionPolicyMarkdown??null,instructionPolicyFingerprint:U?.instructionPolicyFingerprint??null,instructionPolicyEvidence:U?.instructionPolicyEvidence??null,memoryQualityCapture:U?.memoryQualityCapture??null,memoryQualityPromptMarkdown:U?.memoryQualityPromptMarkdown??null,personaMarkdown:U?.personaMarkdown??null,personaSlug:U?.personaSlug??ne,personaEvidence:U?.personaEvidence??null,contextEnvelopeMarkdown:U?.contextEnvelopeMarkdown??null,contextEnvelopeEvidence:U?.contextEnvelopeEvidence??null,runtimeEnvelopeMarkdown:U?.runtimeEnvelopeMarkdown??null,runtimeEnvelopeEvidence:U?.runtimeEnvelopeEvidence??null,workerMcpToken:vl,workerMcpCapabilities:U?.workerMcpCapabilities??null,workerMcpExpiresAt:U?.workerMcpExpiresAt??null,leaseOwner:y,leaseToken:cn,dispatched:!0,executionMode:bc(C)}),Rl=await JP({agentOsId:u,taskId:String(C.id),leaseOwner:y,expectedLeaseToken:cn,worker:Tt,baseUrl:d,secret:m});if(!Rl.ok)return YP(l.id,Tt,Rl.error??"dispatch_start_readback_failed"),zr(l.id,ko),te(C,Rl.error??"dispatch_start_readback_failed",{readback:Rl.detail??null});Tt.leaseToken!==cn&&(Tt.leaseToken=cn,Tt.leaseOwner=y,ee(l.id,Tt)),$u({taskId:Y,leaseToken:cn}),cA(l.id,ko);let Zb={taskId:C.id,started:!0,worker:Tt.name,pid:Tt.pid,branch:Tt.branch,model:Tt.model,provider:tr.provider,routingRule:tr.rule,instructionPolicyFingerprint:U?.instructionPolicyFingerprint??null,instructionPolicyRuleCount:Array.isArray(U?.instructionPolicyEvidence?.ruleSlugs)?U.instructionPolicyEvidence.ruleSlugs.length:null,personaSlug:U?.personaSlug??ne,personaOperatingRuleCount:U?.personaEvidence?.operatingRuleCount??null};return I.push(Zb),Te("worker_started",{lastOutcome:Zb}),U?.instructionPolicyFingerprint&&console.error(`[dispatch] task ${Y}: instruction policy injected fingerprint=${U.instructionPolicyFingerprint}`),U?.personaSlug&&console.error(`[dispatch] task ${Y}: persona context injected slug=${U.personaSlug}`),U?.contextEnvelopeReady&&console.error(`[dispatch] task ${Y}: context envelope injected anchor=${U.contextEnvelopeEvidence?.anchorTaskId??Y}`),U?.runtimeEnvelopeReady&&console.error(`[dispatch] task ${Y}: runtime envelope injected id=${U.runtimeEnvelopeEvidence?.envelopeId??"unknown"}`),!0}catch(Ye){return zr(l.id,ko),te(C,Ye.message)}}let Wp=new Set;for(let A of sA(l.id))Wp.add(A);async function Jb(A){let C=A.task,U=String(C.id);if(Wp.has(U))return te(C,"dispatch_retry_loop_prevented: task already failed to start this tick");let Y=v?Dw({decision:A,leaseOwner:y,repoIdentity:k,requestNonce:b.get(A)??null}):null,ne=Y&&!Y.allow?await te(C,`desktop_execution_policy_denied:${Y.code}: ${Y.reason}`,{desktopPolicyDenied:Y.code,...Y.code==="operation_not_approved"?{nonFatal:!0}:{}}):Gb(A)?await RW(A):await SW(A);return ne||(Wp.add(U),oA(U,l.id)),ne}for(let A of x.started)await Jb(A);if(K.push(...x.skipped??[]),w)for(let A of K){let C=String(A.task.id);R.has(C)&&I.push({taskId:C,started:!1,error:`exact_target_not_started:${A.skipReason}`,skipReason:A.skipReason,detail:A.reason??null,requestedTargetTaskIds:[...R]})}for(;!w&&I.length<P;){if(er()){let U={started:!1,error:"dispatch_circuit_breaker: start readback failed; stopping top-up for this tick",nonFatal:!0};I.push(U),Te("circuit_breaker",{lastOutcome:U});break}let A=await J(1);if(!A.dispatch.ok||!A.result){let U=ex(A.dispatch.response),Y=ue();Z=U&&Y>0;let ne=Vm(A.dispatch.response),kt={started:!1,error:ne?"dispatch_next timed out during top-up":"dispatch_next request failed during top-up",httpStatus:A.dispatch.status,response:A.dispatch.response,...ne?{timeout:!0}:{},...Z?{nonFatal:!0,partialTopUp:!0}:{}};I.push(kt),Te("top_up_failed",{partialTopUpInterrupted:Z,lastOutcome:kt});break}F+=Number(A.result.inspected)||0,K.push(...A.result.skipped??[]);let C=A.result.started??[];if(C.length===0)break;for(let U of C){if(I.length>=P)break;await Jb(U)}}let yl=I.filter(A=>A.started).length,Nr=eI(x),yo=tI(x),qb=yl===0&&(Nr?.capacityIdle===!0||Number(x.resourceGate?.slotsAvailable)>0);if(qb&&Nr?.summary){let A=Nr.skipReasonCounts?.retry_ceiling_exceeded??0,C=x.overAttemptIdleRecovery??Nr.overAttemptIdleRecovery,U=C?.attempted===!0?`; over_attempt_recovery minted=${C.minted??0} started=${C.started??0}`:A>0?"; over_attempt_recovery not attempted":"",Y=yo?`; dispatch_skip_drain scanned=${yo.scanned??0} advanced=${yo.advanced??0}`:"",ne=Nr.progressionReport?.summary?`; ${Nr.progressionReport.summary}`:"",kt=yo?.prLifecycleAttempt?.summary?`; ${yo.prLifecycleAttempt.summary}`:"";console.error(`[dispatch] ${Nr.summary}${A>0?`; retry_ceiling_exceeded=${A}`:""}${U}${Y}${ne}${kt}`)}let Yb={runId:l.id,agentOsId:u,dryRun:!1,leaseOwner:y,startedCount:yl,capacityIdle:qb,admissionExhaustion:Nr,dispatchSkipDrain:yo,outcomes:I,skipped:K.map(A=>({taskId:A.task.id,skipReason:A.skipReason})),inspected:F,pagesScanned:x.pagesScanned??null,candidatesExhausted:x.candidatesExhausted??null,diskGate:x.diskGate,resourceGate:x.resourceGate,...Z?{partialTopUpInterrupted:!0}:{},dispatchCallbackTimeoutMs:V},zb=A=>!A.started&&A.nonFatal!==!0,_W=I.some(zb),Xb=Z&&yl>0?!0:!_W;if(ji({runId:l.id,agentOsId:u,phase:"complete",partial:Z,startedCount:yl,ok:Xb}),t)return{ok:Xb,...Yb};console.log(JSON.stringify(Yb,null,2)),I.some(zb)&&process.exit(1)}catch(i){if(t)return{ok:!1,error:i.message};console.error(`run dispatch failed: ${i.message}`),process.exit(1)}}var Pg,bu=p(()=>{"use strict";H();wc();We();Z_();tx();ax();ai();cx();No();z();z();dx();qc();OC();DC();Ag();QA();eP();rP();tt();gc();vs();D();fP();Ig();ca();mr();gP();kP();Ih();mh();KP();jP();GP();qP();zP();z();ZP();Kf();hs();Hn();ks();Pg=3600*1e3});function _s(e){if(!e||typeof e!="object")return 0;let t=e.startedCount;if(typeof t=="number")return t;let r=e.outcomes;return Array.isArray(r)?r.filter(n=>n.started).length:0}function TY(e){let{maxStarts:t,...r}=e;return r}async function Mh(e,t){if(t<=0)return{ok:!0,skipped:!0,reason:"no slots",maxStarts:0,startedCount:0};let r=TY(e);if(r.targetTaskId||r.targetTaskIds){let u=await Ss({...r,execute:!0,pipeline:!0,maxStarts:String(t)});return{...typeof u=="object"&&u!==null?u:{},passes:{target:u},startedCount:_s(u)}}let n=Math.min(t,OY),o=Math.max(0,t-n),s=await Ss({...r,execute:!0,pipeline:!0,lane:"review",maxStarts:String(n)}),i=_s(s),a=o+(n-i);if(a<=0)return{...typeof s=="object"&&s!==null?s:{},passes:{review:s},startedCount:i};let l=await Ss({...r,execute:!0,pipeline:!0,maxStarts:String(a)}),c=_s(l);return{passes:{review:s,work:l},startedCount:i+c,ok:!0}}var OY,rI=p(()=>{"use strict";bu();OY=1});function nI(e){if(!e||typeof e!="object")return[];let r=e.response?.dispatch?.exactTargetTaskIds;if(!Array.isArray(r))return[];let n=new Set,o=[];for(let s of r){if(typeof s!="string")continue;let i=s.trim();!i||n.has(i)||(n.add(i),o.push(i))}return o}var oI=p(()=>{"use strict"});function NY(e){let r=e.response?.dispatch;return r&&typeof r=="object"?r:null}function Ia(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function DY(e){let t=Number(process.env[e]);return!Number.isFinite(t)||t<=0?null:Math.floor(t)}function sI(e,t){let r=NY(t),n=Ia(r?.recommendedMaxStarts),o=Ia(r?.actionableReady),s=Ia(r?.queuedTasks),i=Ia(r?.boardAdvancedThisTick)??0,a=Ia(r?.leaseReapedThisTick)??0,l=i+a,c=o??s,u=e.slotsAvailable;c!==null?u=Math.min(u,c):n!==null&&(u=Math.min(u,n)),c===null&&n!==null&&(u=Math.max(u,Math.min(e.slotsAvailable,n)));let d=r?.underutilized===!0||(c??0)>0&&e.slotsAvailable>0&&e.maxConcurrentWorkers>0&&e.activeWorkers<e.maxConcurrentWorkers;if(e.slotsAvailable>0&&u===0&&(d||l>0)){let g=c??(l>0?l:1);u=Math.min(e.slotsAvailable,Math.max(1,g))}let m=DY("KYNVER_DAEMON_MAX_DISPATCH_STARTS");m!==null&&(u=Math.min(u,m));let f=s!==null&&o!==null?Math.max(0,s-o):null;return{maxStarts:Math.max(0,u),underutilized:d,advisedStarts:n,actionableReady:o,queuedTasks:s,nonDispatchableReady:f,boardAdvancedThisTick:i,leaseReapedThisTick:a}}var iI=p(()=>{"use strict"});import MY from"node:path";function Vn(e){let t=wt(e);if(t.length===0)return"failed";let r=!1,n=!1,o=!1,s=!1;for(let i of t){let a=$(MY.join(G(e.id),"workers",B(i),"worker.json"),void 0);if(!a)continue;let l=oe(a,{base:e.base,baseCommit:e.baseCommit});if(l.alive&&!l.finalResult){r=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),gf(l)&&(s=!0),l.finalResult&&l.attention.state==="done"&&(n=!0)}return r||o||s?null:n?"completed":"failed"}function Oa(){let e=[];for(let t of Re()){if(!LY.has(t.status))continue;let r=Vn(t);if(!r||r===t.status)continue;let n=t.status;t.status=r,je(t),e.push({runId:t.id,from:n,to:r})}return e}var LY,Ar,Qr=p(()=>{"use strict";z();Co();_e();D();LY=new Set(["running","dispatching","pending","queued","needs_attention"]),Ar=new Set(["completed","failed","cancelled","done"])});import It from"node:path";function Zu(e){return e.includes(BY)}function Lh(e,t){return It.join(Ze(Ie(e)),B(t))}function Zr(e,t,r){return It.join(Lh(e,t),"workers",B(r))}function aI(e,t,r){let n=Ie(e);return It.join(n,"runs","runs",B(t),"workers",B(r))}function Bh(){return["stdout.jsonl","stderr.log","heartbeat.jsonl","last-status.json","auto-complete.log","worker.json"]}function Gn(e){return{workerJsonPath:It.join(e,"worker.json"),stdoutPath:It.join(e,"stdout.jsonl"),stderrPath:It.join(e,"stderr.log"),heartbeatPath:It.join(e,"heartbeat.jsonl"),lastStatusPath:It.join(e,"last-status.json")}}function lI(e){let t=Gn(Zr(e.harnessRoot,e.runId,e.workerName)).workerJsonPath;return e.statusPath&&!Zu(e.statusPath)?e.statusPath:t}var BY,Wh=p(()=>{"use strict";St();D();BY=`${It.sep}runs${It.sep}runs${It.sep}`});import{existsSync as en,mkdirSync as WY,readdirSync as uI,renameSync as UY,statSync as Uh}from"node:fs";import he from"node:path";function dI(e,t){let r=he.resolve(e),n=he.resolve(Ze(t)),o=he.relative(n,r);return o!==".."&&!o.startsWith("..")&&!he.isAbsolute(o)}function Fh(e){if(!en(e))return[];try{return uI(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&t.name!=="runs").map(t=>t.name)}catch{return[]}}function $h(e){let t=he.join(e,"workers");if(!en(t))return[];try{return uI(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}function pI(e){return he.join(e,"archived-workers")}function $Y(e,t){let r=he.join(pI(e),B(t));return en(r)?`${r}-${Date.now()}`:r}function cI(e,t,r){if(!en(e))return!1;try{let n=t-Uh(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<r}catch{return!1}}function fI(e,t=Date.now(),r=Ta){if(!en(e))return!1;let n=Gn(e),o=$(n.workerJsonPath,void 0);if(o?.status==="running"&&re(o.pid))return!0;let s=Ee(n.heartbeatPath);if(s.lastHeartbeatAt){let i=t-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<r)return!0}return!!(cI(n.stdoutPath,t,r)||cI(n.heartbeatPath,t,r))}function KY(e,t,r){let n=typeof t.completionReportedAt=="string"?Date.parse(t.completionReportedAt):NaN;if(Number.isFinite(n))return r-n;let o=(()=>{let s=t.completionResponse;if(!s||typeof s!="object")return NaN;let i=s.task;if(!i||typeof i!="object")return NaN;let a=i.updatedAt;return typeof a=="string"?Date.parse(a):NaN})();if(Number.isFinite(o))return r-o;try{return r-Uh(he.join(e,"worker.json")).mtimeMs}catch{return 0}}function HY(e,t,r,n){if(fI(e,r))return{eligible:!1,reason:"worker has active/recent retention signals"};let o=typeof t.status=="string"?t.status:"";if(typeof t.completionBlocker=="string"&&t.completionBlocker.trim().length>0)return{eligible:!1,reason:"worker has completion blocker"};let i=typeof t.completionReportedAt=="string"||t.completionOutcome==="acknowledged";if(o!=="done"&&!i)return{eligible:!1,reason:`worker status is ${o||"unknown"}`};let a=KY(e,t,r);return!Number.isFinite(a)||a<n?{eligible:!1,reason:"terminal worker is still within archive grace window"}:{eligible:!0,reason:"terminal worker metadata archived"}}function xs(e,t=Date.now(),r=Ta){for(let n of $h(e))if(fI(he.join(e,"workers",n),t,r))return!0;return!1}function jY(){let t=Wi()?.repo??"",r="unknown";if(t)try{let n=le(t,["rev-parse","origin/main"],{allowFailure:!0}).trim();n&&(r=n)}catch{}return{repo:t,base:"origin/main",baseCommit:r}}function VY(e,t){let r=he.join(Ze(e),B(t));if(!en(r))return null;let n=$h(r);if(n.length===0)return null;let o;try{o=Uh(r).birthtime.toISOString()}catch{o=new Date().toISOString()}let s={};for(let a of n){let l=Zr(e,t,a);s[a]={workerDir:l,statusPath:he.join(l,"worker.json")}}let i=xs(r);return{id:t,name:t,...jY(),status:i?"running":"needs_attention",createdAt:o,workers:s}}function Kh(e){let t=Ie(e??at()),r=Ze(t),n=[];for(let o of Fh(r)){let s=he.join(r,o,"run.json");if(en(s)){n.push({runId:o,action:"skipped",reason:"run.json present"});continue}let i=VY(t,o);if(!i){n.push({runId:o,action:"skipped",reason:"no worker dirs on disk"});continue}je(i),n.push({runId:o,action:"repaired_run_json",reason:xs(he.join(r,o))?"synthesized run.json while worker artifacts still active":"synthesized run.json from orphan worker metadata dirs"})}return{runs:n}}function Hh(e,t={}){let r=Ie(e??at()),n=Ze(r),o=t.now??Date.now(),s=t.archiveAgeMs??FY,i=[];Kh(r);for(let a of Fh(n)){let l=he.join(n,a),c=he.join(l,"run.json"),u=$(c,void 0);if(!u?.id)continue;let d=new Set([...Object.keys(u.workers||{}),...$h(l)]),m=!1;for(let f of d){let g=he.join(l,"workers",B(f)),h=he.join(g,"worker.json"),y=$(h,void 0);if(!y){let b=he.join(pI(l),B(f));if(en(b)&&(u.workers[B(f)]||u.workers[f])){delete u.workers[B(f)],delete u.workers[f],m=!0,i.push({runId:u.id,worker:f,action:"archived",reason:"removed stale live index entry for archived worker metadata",archivePath:b});continue}i.push({runId:u.id,worker:f,action:"skipped",reason:"worker.json missing"});continue}let v=HY(g,y,o,s);if(!v.eligible){i.push({runId:u.id,worker:f,action:"skipped",reason:v.reason});continue}let k=$Y(l,f);WY(he.dirname(k),{recursive:!0}),UY(g,k),delete u.workers[B(f)],delete u.workers[f],m=!0,i.push({runId:u.id,worker:f,action:"archived",reason:v.reason,archivePath:k})}m&&je(u)}return{workers:i}}function mI(e,t=Date.now()){let r=new Set,n=Ze(e);for(let o of Fh(n)){let s=he.join(n,o);xs(s,t)&&r.add(`${e}\0${o}`)}return r}var Ta,FY,Cs=p(()=>{"use strict";ns();ve();fn();St();z();Wh();D();Ta=900*1e3,FY=3600*1e3});import{existsSync as tn,lstatSync as GY,readdirSync as JY,readlinkSync as qY,renameSync as jh,unlinkSync as YY}from"node:fs";import Kt from"node:path";function zY(e,t){let r=Lh(e,t),n;try{n=GY(r)}catch{return null}if(!n.isSymbolicLink())return null;let o=Kt.resolve(Kt.dirname(r),qY(r));if(xs(o)||xs(r))return null;let s=`${r}.materialize-${Date.now()}`;return jh(o,s),YY(r),jh(s,r),o}function XY(e){let t=[];for(let r of Bh()){let n=Kt.join(e.fromDir,r),o=Kt.join(e.toDir,r);!tn(n)||tn(o)||(jh(n,o),t.push(r))}return t}function gI(e,t){let r=Gn(t),n=!1;return e.workerDir!==t&&(e.workerDir=t,n=!0),e.stdoutPath!==r.stdoutPath&&(e.stdoutPath=r.stdoutPath,n=!0),e.stderrPath!==r.stderrPath&&(e.stderrPath=r.stderrPath,n=!0),e.heartbeatPath!==r.heartbeatPath&&(e.heartbeatPath=r.heartbeatPath,n=!0),n}function QY(e){let t=typeof e.lastStatus?.status=="string"?e.lastStatus.status:void 0,r=e.lastStatus?.attention&&typeof e.lastStatus.attention=="object"?e.lastStatus.attention.state:void 0;return t==="done"||r==="done"||e.stdoutFinalResult||e.heartbeatFinalResult?"done":t==="blocked"?"blocked":t==="running"?"exited":t??"exited"}function ZY(e){let t=Gn(e.canonicalDir),r=$(t.lastStatusPath,void 0),n=tn(t.stdoutPath),o=tn(t.heartbeatPath);if(!(n||o||r!=null))return null;let i=n?mn(t.stdoutPath):{finalResult:null},a=o?Ee(t.heartbeatPath):Ee(""),l=sr(a),c=QY({lastStatus:r,stdoutFinalResult:i.finalResult,heartbeatFinalResult:l}),u={name:e.workerName,runId:e.run.id,status:c,branch:typeof r?.branch=="string"?r.branch:`agent/${e.run.id}/${e.workerName}`,worktreePath:typeof r?.worktreePath=="string"?r.worktreePath:Kt.join(me().worktreesDir,e.run.id,e.workerName),workerDir:e.canonicalDir,stdoutPath:t.stdoutPath,stderrPath:t.stderrPath,heartbeatPath:t.heartbeatPath,startedAt:typeof r?.startedAt=="string"?r.startedAt:e.run.createdAt,reconciledAt:new Date().toISOString(),reconcileReason:"synthesized worker.json from on-disk artifacts after metadata repair"};return typeof r?.taskId=="string"&&(u.taskId=r.taskId),typeof r?.agentOsId=="string"&&(u.agentOsId=r.agentOsId),typeof r?.planId=="string"&&(u.planId=r.planId),typeof r?.pid=="number"&&(u.pid=r.pid),(i.finalResult||l)&&(u.completionSnapshot={finalResult:i.finalResult??l??"completed",summary:a.lastHeartbeatSummary}),gI(u,e.canonicalDir),u}function ez(e,t){let r=!1,n={...e.workers||{}};for(let[o,s]of Object.entries(n)){let i=Zr(t,e.id,o),a=Kt.join(i,"worker.json");(Zu(s.workerDir)||Zu(s.statusPath)||s.workerDir!==i||s.statusPath!==a)&&(n[o]={workerDir:i,statusPath:a},r=!0)}return r&&(e.workers=n,je(e)),r}function tz(e){let t=[],r=Zr(e.harnessRoot,e.run.id,e.workerName),n=aI(e.harnessRoot,e.run.id,e.workerName),o=Gn(r),s=XY({fromDir:n,toDir:r});s.length>0&&t.push({runId:e.run.id,worker:e.workerName,action:"relocated_artifacts",reason:`moved ${s.join(", ")} from nested runs/runs layout`});let i=lI({harnessRoot:e.harnessRoot,runId:e.run.id,workerName:e.workerName,statusPath:e.statusPath}),a=$(i,void 0);if(!a&&tn(o.workerJsonPath)&&(a=$(o.workerJsonPath,void 0)),!a){let l=ZY({run:e.run,workerName:e.workerName,canonicalDir:r,harnessRoot:e.harnessRoot});if(l)return ee(e.run.id,l),t.push({runId:e.run.id,worker:e.workerName,action:"synthesized_worker_json",reason:l.reconcileReason??"synthesized from artifacts"}),t;let c=tn(r),u=Bh().some(d=>tn(Kt.join(r,d)));if(c&&!u){let d={name:e.workerName,runId:e.run.id,status:"exited",branch:`agent/${e.run.id}/${e.workerName}`,worktreePath:Kt.join(me().worktreesDir,e.run.id,e.workerName),workerDir:r,stdoutPath:o.stdoutPath,stderrPath:o.stderrPath,heartbeatPath:o.heartbeatPath,startedAt:e.run.createdAt,reconciledAt:new Date().toISOString(),reconcileReason:"empty worker dir \u2014 marked abandoned during metadata reconcile"};return ee(e.run.id,d),t.push({runId:e.run.id,worker:e.workerName,action:"marked_abandoned",reason:d.reconcileReason??"empty worker dir"}),t}return t.push({runId:e.run.id,worker:e.workerName,action:"skipped",reason:"worker.json missing and no recoverable artifacts"}),t}return gI(a,r)?(a.reconciledAt=new Date().toISOString(),a.reconcileReason=a.reconcileReason??"repaired nested runs/runs path fields",ee(e.run.id,a),t.push({runId:e.run.id,worker:e.workerName,action:"repaired_worker_paths",reason:a.reconcileReason})):t.push({runId:e.run.id,worker:e.workerName,action:"skipped",reason:"worker metadata already canonical"}),t}function rz(e,t){let r=Kt.join(G(e.id),"workers");if(!tn(r))return[];let n=new Set(Object.keys(e.workers||{})),o=[];for(let s of JY(r,{withFileTypes:!0}))s.isDirectory()&&(n.has(s.name)||o.push(s.name));return o}function hI(){let{harnessRoot:e}=me(),t=Kh(e),r=[];for(let n of Re()){let o=zY(e,n.id);o&&r.push({runId:n.id,worker:"*",action:"materialized_run_symlink",reason:`replaced symlink with real run dir (was ${o})`}),ez(n,e)&&r.push({runId:n.id,worker:"*",action:"repaired_run_index",reason:"repaired nested runs/runs workerDir/statusPath entries in run.json"});let s=new Set(Object.keys(n.workers||{}));for(let i of rz(n,e))s.add(i),n.workers={...n.workers||{},[i]:{workerDir:Zr(e,n.id,i),statusPath:Kt.join(Zr(e,n.id,i),"worker.json")}},je(n),r.push({runId:n.id,worker:i,action:"repaired_run_index",reason:"indexed orphan worker dir into run.json"});for(let i of s){let a=n.workers?.[i];r.push(...tz({run:n,workerName:i,harnessRoot:e,statusPath:a?.statusPath}))}}return{workers:r,runMetadataRetention:t}}var yI=p(()=>{"use strict";fn();di();Wh();Cs();z();D()});import{execFileSync as kI}from"node:child_process";import bI from"node:path";function Vh(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:null}function nz(e){let t=Vh(e)?.match(/\/pull\/(\d+)$/);if(!t)return null;let r=Number.parseInt(t[1],10);return Number.isFinite(r)?r:null}function oz(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function sz(e){let t=new Set;for(let r of e.matchAll(/github\.com\/[^/\s)>"']+\/[^/\s)>"']+\/(?:pull|pulls)\/(\d+)/gi)){let n=Number.parseInt(r[1],10);Number.isFinite(n)&&t.add(n)}for(let r of e.matchAll(/\bPR\s*#?\s*(\d{2,})\b/gi)){let n=Number.parseInt(r[1],10);Number.isFinite(n)&&t.add(n)}for(let r of e.matchAll(/\bpr[-_]?(\d{2,})\b/gi)){let n=Number.parseInt(r[1],10);Number.isFinite(n)&&t.add(n)}return[...t]}function iz(e){let t=null;if(typeof e=="string"?t=Io(e):e&&typeof e=="object"&&!Array.isArray(e)&&(t=e),!t)return[];let r=t.targetPrReconciliation??t.target_pr_reconciliation;if(!Array.isArray(r))return[];let n=[];for(let o of r){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=Vh(String(s.prUrl??s.pr_url??"")),a=String(s.outcome??"").trim();!i||a!=="merged"||n.push({prUrl:i,mergeCommit:typeof s.mergeCommit=="string"?s.mergeCommit:typeof s.merge_commit=="string"?s.merge_commit:null,reason:typeof s.reason=="string"?s.reason:null})}return n}function az(e){try{let n=kI("git",["config","--get","remote.origin.url"],{windowsHide:!0,cwd:e.repoDir,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim().match(/github\.com[:/]([^/]+\/[^/.]+)(?:\.git)?$/i)?.[1];if(!n)return null;let o=kI("gh",["pr","view",String(e.prNumber),"--repo",n,"--json","state,mergedAt,mergeCommit,url"],{windowsHide:!0,cwd:e.repoDir,encoding:"utf8",stdio:["ignore","pipe","ignore"]}),s=JSON.parse(o);return{prUrl:Vh(s.url??`https://github.com/${n}/pull/${e.prNumber}`)??`https://github.com/${n}/pull/${e.prNumber}`,state:s.state??"",mergedAt:s.mergedAt??null,mergeCommit:s.mergeCommit?.oid??null}}catch{return null}}function lz(e){let t=Ee(e.heartbeatPath);return e.completionSnapshot?.finalResult??sr(t)}function cz(e){let t=new Map,r=G(e.id);for(let n of wt(e)){let o=$(bI.join(r,"workers",B(n),"worker.json"),void 0);if(o)for(let s of iz(lz(o))){let i=nz(s.prUrl);i!=null&&!t.has(i)&&t.set(i,s)}}return t}function uz(e,t){let r=Ee(e.heartbeatPath),n=[e.name,e.repairTargetPrUrl,e.taskPrUrl,e.branch,r.lastHeartbeatSummary,oz(t)].filter(Boolean).join(`
|
|
114
|
-
`);return sz(n)}function dz(e){return e.localOnly===!0&&!e.taskId&&!e.agentOsId}function Gh(e={}){let t=e.lookupPr??az,r=[],n=new Map;for(let o of Re()){let s=cz(o),i=G(o.id);for(let a of wt(o)){let l=bI.join(i,"workers",B(a),"worker.json"),c=$(l,void 0);if(!c||!dz(c))continue;let u=oe(c,{base:o.base,baseCommit:o.baseCommit});if(u.attention.state!=="needs_attention")continue;let d=null;for(let f of uz(c,u.finalResult)){if(d=s.get(f)??null,!d){let g=o.repo||c.worktreePath,h=`${g}#${f}`,y=n.has(h)?n.get(h)??null:t({repoDir:g,prNumber:f});n.has(h)||n.set(h,y),y&&(y.state==="MERGED"||y.mergedAt)&&(d={prUrl:y.prUrl,mergeCommit:y.mergeCommit??null,reason:"GitHub reports PR merged"})}if(d)break}if(!d){r.push({runId:o.id,worker:a,action:"skipped",reason:"no merged PR evidence"});continue}let m=new Date().toISOString();c.status="done",c.completionSnapshot={prUrl:d.prUrl,summary:`Local-only worker superseded by merged PR ${d.prUrl}`,finalResult:{summary:`Local-only repair/salvage worker superseded by merged PR ${d.prUrl}`,targetPrReconciliation:[{prUrl:d.prUrl,outcome:"merged",mergeCommit:d.mergeCommit??null,reason:d.reason??"PR already merged; local-only worker no longer requires attention"}]}},c.completionAckSource="local-pr-merged-reconcile",c.reconciledAt=m,c.reconcileReason="local-only needs_attention superseded by merged PR",ee(o.id,c),r.push({runId:o.id,worker:a,action:"marked_done",reason:c.reconcileReason,prUrl:d.prUrl,mergeCommit:d.mergeCommit??null})}}return{workers:r}}var vI=p(()=>{"use strict";fn();Kl();_e();z();Co();D()});import pz from"node:path";function mz(){return process.env.KYNVER_NO_STALE_CLEANUP==="1"}function RI(e,t){let r=Bu({worker:e,status:t}),n=r?Wu(e,r):!1,o=t.attention.state==="blocked"?"blocked":t.attention.state==="done"||t.status==="done"||r?"done":"exited",s=r&&n?`captured exited-worker handoff (${r.source})`:r?"synced finished worker record after terminal stdout/heartbeat":t.attention.reason;return{nextStatus:o,reason:s,handoffCaptured:n}}function Jh(){let e=hI();if(mz()){let s=Gh(),i=Hh();return{workers:[],finalizedRuns:Oa(),metadataReconcile:e,localPrAttentionReconcile:s,terminalWorkerArchive:i}}let t=[],r=Date.now();for(let s of Re())for(let i of wt(s)){let a=pz.join(G(s.id),"workers",B(i),"worker.json"),l=$(a,void 0);if(!l||l.status!=="running"){t.push({runId:s.id,worker:i,action:"skipped",reason:l?`worker status is ${l.status}`:"worker.json missing"});continue}let c=oe(l,{base:s.base,baseCommit:s.baseCommit});if(c.finalResult){if(l.status==="running"){let u=RI(l,c);l.status=u.nextStatus,l.reconciledAt=new Date().toISOString(),l.reconcileReason=u.reason,ee(s.id,l),t.push({runId:s.id,worker:i,action:"marked_exited",reason:l.reconcileReason})}else t.push({runId:s.id,worker:i,action:"skipped",reason:"final result present"});continue}if(!c.alive){let u=RI(l,c);l.status=u.nextStatus,l.reconciledAt=new Date().toISOString(),l.reconcileReason=u.reason,ee(s.id,l),t.push({runId:s.id,worker:i,action:"marked_exited",reason:c.attention.reason});continue}if(c.attention.state==="stale"&&l.pid&&re(l.pid)){let u=c.lastHeartbeatAt?Date.parse(c.lastHeartbeatAt):NaN,d=c.lastActivityAt?Date.parse(c.lastActivityAt):NaN,m=!Number.isFinite(u)||r-u>fz,f=Number.isFinite(d)&&r-d>mf;if(m&&f){Se(l.pid,"SIGTERM"),l.status="exited",l.reconciledAt=new Date().toISOString(),l.reconcileReason=`reconciled stale worker: ${c.attention.reason}`,ee(s.id,l),t.push({runId:s.id,worker:i,action:"killed_stale",reason:c.attention.reason});continue}}t.push({runId:s.id,worker:i,action:"skipped",reason:c.attention.reason})}let n=Gh(),o=Hh();return{workers:t,finalizedRuns:Oa(),metadataReconcile:e,localPrAttentionReconcile:n,terminalWorkerArchive:o}}var fz,qh=p(()=>{"use strict";Qr();z();Co();eh();_e();D();yI();vI();Cs();fz=900*1e3});import{readdirSync as gz,readFileSync as hz}from"node:fs";function Rz(e){if(process.platform!=="linux"||!e.trim())return null;let t=[];try{t=gz("/proc")}catch{return null}for(let r of t)if(/^\d+$/.test(r)&&Number(r)!==process.pid)try{if(hz(`/proc/${r}/cmdline`,"utf8").replace(/\0/g," ").includes(e))return Number(r)}catch{}return null}async function wI(e){let t=Cr(),r={mode:t,scanned:0,outcomes:[]};if(t!=="enforce")return r;let n=ce();if(!n)return r;let o=e.nowMs??Date.now(),s=e.strandedAfterMs??kz,i=e.findOrphanPid??Rz,a=[],l;try{l=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-bz).toISOString(),limit:vz})}catch{return Jn.recoveryStoreFailures+=1,r}for(let c of l){let u=c.idempotencyKey.slice(yz.length),d=u.split(":")[0]??"",m=u.slice(d.length+1);if(!(!d||!m))try{let f=Date.parse(c.recordedAt);if(!Number.isFinite(f)||o-f<s||n.getOperationReceipt(`dispatch:spawned:${u}`)||n.getOperationReceipt(`dispatch:released:${u}`))continue;let g=ha(m);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${d}:`,limit:10}).some(S=>{if(g===null)return!0;let R=ha(S.idempotencyKey.slice(`dispatch:completion-acked:${d}:`.length));return R===null||R>=g}))continue;let v={};try{v=c.resultJson?JSON.parse(c.resultJson):{}}catch{v={}}let k=v.runId??null,b=v.workerName??null;if(k&&b&&e.hasLiveWorker({runId:k,workerName:b})){$u({taskId:d,leaseToken:m}),a.push({taskId:d,leaseToken:m,runId:k,workerName:b,action:"finalized_late"});continue}if(k&&b){let S=e.worktreePathFor({runId:k,workerName:b}),R=S?i(S):null;if(R!==null){Jn.recoveryDeferredOrphans+=1,a.push({taskId:d,leaseToken:m,runId:k,workerName:b,action:"deferred_orphan",detail:`live pid ${R} references ${S}`});continue}}if(!k){a.push({taskId:d,leaseToken:m,runId:k,workerName:b,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let _=await e.releaseClaim({taskId:d,leaseToken:m,runId:k});_.released?(gs({taskId:d,leaseToken:m},"restart_recovery"),b&&(ka(k,b),zr(k,b)),Jn.recoveredStrandedClaims+=1,a.push({taskId:d,leaseToken:m,runId:k,workerName:b,action:"released"})):_.transportError?a.push({taskId:d,leaseToken:m,runId:k,workerName:b,action:"deferred_transport",detail:_.detail}):(gs({taskId:d,leaseToken:m},"restart_recovery_refused"),a.push({taskId:d,leaseToken:m,runId:k,workerName:b,action:"release_refused",detail:_.detail}))}catch{Jn.recoveryStoreFailures+=1}}return{mode:t,scanned:l.length,outcomes:a}}function SI(){return{"dispatchReceipts.recoveredStrandedClaims":Jn.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":Jn.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":Jn.recoveryStoreFailures}}var yz,kz,bz,vz,Jn,Yh=p(()=>{"use strict";Hr();hs();Hn();ks();yz="dispatch:claim:",kz=900*1e3,bz=10080*60*1e3,vz=200,Jn={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0}});import wz from"node:path";async function xI(e){if(_I||Cr()!=="enforce")return null;_I=!0;try{let t=Oe().runnerId,r=await wI({hasLiveWorker:e.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>wz.join(me().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await Pa({baseUrl:e.baseUrl,secret:e.secret,agentOsId:e.agentOsId,taskId:n,leaseOwner:la(s,t),leaseToken:o});return{released:i.released,transportError:i.transportError,detail:i.httpOk?void 0:JSON.stringify(i.releaseResponse).slice(0,200)}}});return r.outcomes.length>0&&console.error(`[daemon] D1b claim recovery: ${r.outcomes.map(n=>`${n.taskId}:${n.action}`).join(", ")}`),r}catch{return null}}var _I,CI=p(()=>{"use strict";z();ca();mr();Ih();Yh();hs();_I=!1});import Sz from"node:os";function EI(e,t={}){let r=E(),n=(t.boxKind??Rt(r)).trim().toLowerCase()||"forge",o=t.hostLabel??Sz.hostname();return{boxId:Lo({boxKind:n,hostLabel:o,explicitBoxId:t.boxId,config:r,env:process.env}),boxKind:n,displayName:t.displayName??null,hostLabel:o,observedAt:t.observedAt??new Date().toISOString(),totalMemBytes:e.totalMemBytes,freeMemBytes:e.freeMemBytes,activeWorkers:e.activeWorkers,maxConcurrentWorkers:e.maxConcurrentWorkers,autoCap:e.autoCap,slotsAvailable:e.slotsAvailable,harnessRunId:t.harnessRunId??null,queuedTasks:t.queuedTasks??null,reason:e.reason,...t.prEvidence?.length?{prEvidence:t.prEvidence}:{},host:C_()}}var AI=p(()=>{"use strict";H();De();Bo();Wc()});import _z from"node:path";async function ed(e){let t=e.pipeline===!0||e.pipeline==="true";try{let r=ae(String(vt(String(e.run||""),"--run"))),n=String(vt(String(e.agentOsId||""),"--agent-os-id")),o=pe(e.baseUrl?String(e.baseUrl):void 0),s=await fe(e.secret?String(e.secret):void 0,n,{baseUrl:o}),i=Oe({runId:r.id}).runnerId,a=await NA({run:r.id,agentOsId:n,...e},"run_sweep"),l=[];for(let m of Object.keys(r.workers||{})){let f=$(_z.join(G(r.id),"workers",B(m),"worker.json"),void 0);if(!f||!f.dispatched||!f.taskId)continue;let g=oe(f);if(g.alive||g.finalResult||f.completionReportedAt)continue;let h=hu({runId:r.id,workerLeaseOwner:f.leaseOwner??null,runnerId:i}),y=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/${encodeURIComponent(String(f.taskId))}/release`,v;try{v=await de(y,s,{agentOsId:n,leaseOwner:h,...f.leaseToken?.trim()?{leaseToken:f.leaseToken.trim()}:{}},{agentOsId:n,baseUrl:o})}catch(k){v={ok:!1,error:k.message}}l.push({worker:m,taskId:f.taskId,pid:f.pid,released:v.ok===!0||v.response?.ok===!0,response:v.response??v})}let c=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/reap`,u;try{u=await de(c,s,{agentOsId:n,...Number(e.graceMs)>=0&&e.graceMs!==void 0&&e.graceMs!==!0?{graceMs:Math.floor(Number(e.graceMs))}:{}},{agentOsId:n,baseUrl:o})}catch(m){u={ok:!1,error:m.message}}let d={runId:r.id,agentOsId:n,snapshotPublished:a,releasedLocalOrphans:l,reap:u.response??u};if(t)return{ok:!0,...d};console.log(JSON.stringify(d,null,2))}catch(r){if(t)return{ok:!1,error:r.message};console.error(`run sweep failed: ${r.message}`),process.exit(1)}}var zh=p(()=>{"use strict";H();We();z();_e();D();ca();mr();vs()});async function PI(e){let t=pe(e.baseUrl),r=await fe(e.secret,e.agentOsId,{baseUrl:t}),n=`${t}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/tasks/${encodeURIComponent(e.taskId)}/plan-progress-sync`,o=await de(n,r,{phase:e.phase,taskId:e.taskId,blocker:e.blocker,artifact:e.artifact},{agentOsId:e.agentOsId,baseUrl:t});return{ok:o.ok,status:o.status,response:o.response}}var II=p(()=>{"use strict";H();We()});import xz from"node:path";async function OI(e,t){let r=ae(e),n=String(t.agentOsId||"");if(!n)return[];let o=[];for(let s of Object.keys(r.workers||{})){let i=$(xz.join(G(r.id),"workers",B(s),"worker.json"),void 0);if(!i?.dispatched||!i.taskId)continue;let a=oe(i);if(!a.heartbeatBlocker)continue;if(i.lastSyncedHeartbeatBlocker===a.heartbeatBlocker){o.push({worker:s,phase:"heartbeat_blocker",ok:!0,skipped:!0});continue}let l=await PI({agentOsId:n,taskId:i.taskId,phase:"heartbeat_blocker",blocker:a.heartbeatBlocker,baseUrl:t.baseUrl?String(t.baseUrl):void 0,secret:t.secret?String(t.secret):void 0});l.ok&&(i.lastSyncedHeartbeatBlocker=a.heartbeatBlocker,ee(r.id,i)),o.push({worker:s,phase:"heartbeat_blocker",ok:l.ok})}return o}var TI=p(()=>{"use strict";_e();z();D();II()});function NI(e){let t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(t==="node_modules"||t.startsWith("node_modules/"))return!0;for(let r of Xh)if(t===r||t.startsWith(`${r}/`))return!0;return!1}var Xh,Qh=p(()=>{"use strict";Xh=[".next",".turbo","dist","build",".cache","node_modules/.cache"]});function ft(e){return e.filter(t=>{let r=t.trim(),n=r.startsWith("??")?r.slice(2).trim():r.length>3?r.slice(3).trim():r;return!NI(n)})}var qn=p(()=>{"use strict";Qh()});function Yn(e){if(typeof e=="string")return e.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/i)?.[0]??null;if(e&&typeof e=="object"){let t=e;for(let r of["prUrl","pr_url","pullRequestUrl"]){let n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}return null}function Na(e){let t=e.gitAncestry?.relation;return t==="merged"||t==="synced"?ft(e.changedFiles).length>0:!!(Yn(e.finalResult)||t==="ahead"||t==="diverged"||e.changedFiles.length>0&&e.finalResult)}var Da=p(()=>{"use strict";qn()});function Ma(e){return e.status||(e.status=oe(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function Zh(e,t){if(e.status)return ft(e.status.changedFiles).length>0;let r=t?t.porcelain(e.worktreePath):ni(e.worktreePath);return ft(r).length>0}function Cz(e){let t=e.worker.completionSnapshot?.finalResult;return t??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function ey(e,t){if(e.status)return e.status;let r=e.worker,n=typeof r.completionReportedAt=="string"&&r.completionReportedAt.trim().length>0,o=!!(r.status&&["done","exited","blocked","failed","abandoned"].includes(r.status))||n,s=Cz(e);if(o&&!re(r.pid)){let i=t?.gitStatusCache?t.gitStatusCache.porcelain(e.worktreePath):ni(e.worktreePath),a=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main",c=t?.gitRevCache?.countAheadOfMain(e.worktreePath,a)===0?{checked:!0,base:a,relation:"synced"}:El(e.worktreePath,{base:e.run.base,baseCommit:e.run.baseCommit}),u={runId:e.runId,worker:e.workerName,pid:r.pid,alive:!1,status:r.status??(n?"done":"exited"),attention:{state:n?"done":"stale"},branch:r.branch,worktreePath:e.worktreePath,ownedPaths:r.ownedPaths,stdoutBytes:0,stderrBytes:0,heartbeatBytes:0,firstEventAt:null,lastEventAt:null,lastActivityAt:r.completionReportedAt??null,currentTool:null,heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,heartbeatBlocker:null,changedFiles:i,gitAncestry:c,finalResult:s,completionBlocker:typeof r.completionBlocker=="string"&&r.completionBlocker.trim()||null,prUrl:r.repairTargetPrUrl??r.taskPrUrl??Yn(s)};return e.status=u,u}return Ma(e)}var td=p(()=>{"use strict";ve();_e();qn();Da();D()});function Ez(e,t=Date.now(),r=Ta){let n=Ee(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=t-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<r}function Es(e,t=Date.now(),r=Ta){return re(e.pid)?!0:Ez(e,t,r)}var rd=p(()=>{"use strict";fn();Cs();D()});function Az(e,t){return t?t.runTerminalCache.derive(e.run):Vn(e.run)}function Pr(e,t=Date.now()){return Es(e.worker,t)}function ty(e,t){return Ar.has(e.run.status)?!1:Az(e,t)!==null}function DI(e,t,r=Date.now()){if(Pr(e,r))return!0;if(Ar.has(e.run.status)||ty(e,t))return!1;let n=Ma(e);return Me(n)?!1:!!Pr(e,r)}var ry=p(()=>{"use strict";Qr();_e();td();rd()});function MI(e,t){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(Pr(e))return!0;let n=t??Ma(e);return!!(!Me(n)||Na(n)||ft(n.changedFiles).length>0||Po({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:Yn(n.finalResult)}).blocked)}var LI=p(()=>{"use strict";$l();td();qn();ry();_e();Da()});import{existsSync as WI,mkdirSync as Pz,writeFileSync as BI}from"node:fs";import nd from"node:path";function UI(e,t,r){return nd.join(e,"salvage",B(t),B(r))}function FI(e){return WI(nd.join(UI(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function $I(e){let t=UI(e.harnessRoot,e.indexed.runId,e.indexed.workerName);Pz(t,{recursive:!0});let r=nd.join(t,"salvage.patch"),n=!1;if(WI(e.indexed.worktreePath)){let s=Q(e.indexed.worktreePath,["diff","HEAD"]),i=Q(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(l=>l.trim()).join(`
|
|
115
|
-
`);a.trim()&&(
|
|
173
|
+
`)}})}write(t,r){if(!t.destroyed)try{t.write(Lg(r))}catch{}}async handleLine(t,r){let n=Bg(r);if(!n.ok){this.refuse(n.reason,n.error),this.write(t,{id:n.id,ok:!1,reason:n.reason,error:n.error});return}let{request:o}=n;if(this.revoked||this.closed){this.refuse("revoked","grant revoked"),this.write(t,{id:o.id,ok:!1,reason:"revoked",error:"worker tools are no longer available for this task"});return}if(this.now()>=this.opts.expiresAt){this.refuse("grant_expired","grant expired"),this.write(t,{id:o.id,ok:!1,reason:"grant_expired",error:"worker tools are no longer available for this task"});return}if(o.op==="list_tools"){this.write(t,{id:o.id,ok:!0,tools:this.toolDescriptors});return}if(!bs(o.name)){this.refuse("unknown_tool",o.name),this.write(t,{id:o.id,ok:!1,reason:"unknown_tool",error:`unknown tool: ${o.name}`});return}if(!this.grantedTools.includes(o.name)){this.refuse("capability_not_granted",o.name),this.write(t,{id:o.id,ok:!1,reason:"capability_not_granted",error:`tool not granted for this task: ${o.name}`});return}try{let s=await wu({apiBaseUrl:this.opts.apiBaseUrl,agentOsId:this.opts.agentOsId,taskId:this.opts.taskId,token:this.opts.token,fetchImpl:this.fetchImpl},o.name,o.args??{});this.write(t,{id:o.id,ok:!0,result:s})}catch(s){let i=s instanceof Error?s.message:"request failed";this.refuse("upstream_error",i),this.write(t,{id:o.id,ok:!1,reason:"upstream_error",error:i})}}}});function Gh(){return jP}var jP,VP=p(()=>{"use strict";jP={posture:"scoped",summary:"scoped: per-worker endpoint in an owner-only (0700) directory, one connection at a time. Peer identity is not observed \u2014 another process of the same OS user is not excluded.",verify:async()=>({ok:!0})}});var GP=p(()=>{"use strict";Sr()});var JP=p(()=>{"use strict";HP();VP();Sr();Su();GP();bh();Vh()});import{existsSync as gz,mkdirSync as hz}from"node:fs";import Is from"node:path";async function qP(e,t){let r=typeof t.name=="string"?t.name.trim():"";if(!r||r==="undefined"||r==="null")throw new Error(`worker name is required and must be a real identifier (got: ${JSON.stringify(t.name)})`);let n=B(r);if(e.workers?.[n])throw new Error(`worker already exists in run ${e.id}: ${n}`);if(!t.task)throw new Error(`missing task text for worker ${n}`);let o=t.routingRule||t.requestedModel?{provider:t.provider||wr,model:t.model,rule:t.routingRule||"explicit:spawn",requestedModel:t.requestedModel??t.model}:Pu({explicitModel:t.model,explicitProvider:t.provider,explicitProviderIsOperatorOverride:!!t.provider?.trim(),configuredProvider:P().workerProvider}),s=GE(o.provider),i=o.model;if(s.preflightModel){let E=s.preflightModel(t.model);if(!E.ok)throw new Error(`model preflight failed for provider "${s.name}": ${E.note??"invalid model/provider combination"}`);E.normalized&&console.error(`[supervisor] ${n}: ${E.note}`),i=E.model}let{worktreesDir:a}=he(),l=Is.join(j(e.id),"workers",n);hz(l,{recursive:!0});let c=Is.join(a,e.id,n),u=t.repairTargetBranch?.trim()||void 0,d=u||t.branch||`agent/${e.id}/${n}`;if(gz(c))throw new Error(`worktree path already exists: ${c}`);if(ce(e.repo,["fetch","origin","--prune"],{allowFailure:!0}),u)LP(e.repo,c,u);else{let E=BE({baseCommit:e.baseCommit,base:e.base,verifyRef:V=>ce(e.repo,["rev-parse","--verify","--quiet",`${V}^{commit}`],{allowFailure:!0}).trim().length>0});E.repaired&&(console.error(`[supervisor] ${n}: run baseCommit ${e.baseCommit||"<empty>"} invalid \u2014 repaired to ${E.ref} (${E.source})`),e.baseCommit=ce(e.repo,["rev-parse",E.ref],{allowFailure:!0}).trim()||E.ref,Ve(e)),ce(e.repo,["worktree","add","-b",d,c,e.baseCommit],{throwError:!0})}let f=Is.join(l,"stdout.jsonl"),m=Is.join(l,"stderr.log"),g=Is.join(l,"heartbeat.jsonl"),h=HE({task:t.task,ownedPaths:t.ownedPaths||[],worktreePath:c,heartbeatPath:g,planId:t.planId,taskId:t.taskId,instructionPolicyMarkdown:t.instructionPolicyMarkdown,memoryQualityMarkdown:t.memoryQualityPromptMarkdown??t.memoryQualityCapture?.promptMarkdown??null,personaMarkdown:t.personaMarkdown,contextEnvelopeMarkdown:t.contextEnvelopeMarkdown,runtimeEnvelopeMarkdown:t.runtimeEnvelopeMarkdown,model:i,repairTargetPrUrl:t.repairTargetPrUrl,repairTargetBranch:t.repairTargetBranch??(u||void 0)}),y=process.env.KYNVER_HARNESS_TASK_ID,v=process.env.KYNVER_HARNESS_AGENT_OS_ID;t.taskId&&(process.env.KYNVER_HARNESS_TASK_ID=String(t.taskId)),t.agentOsId&&(process.env.KYNVER_HARNESS_AGENT_OS_ID=String(t.agentOsId));let k=Fu({title:t.taskTitle,personaSlug:t.personaSlug,parentTaskId:t.parentTaskId,executorRef:t.executorRef}),b,_,S,R,w=t.workerMcpToken?.trim();if(w&&Wg(s.name)&&aa()){let E=An();E&&t.agentOsId&&t.taskId?(_={apiBaseUrl:E,agentOsId:String(t.agentOsId),taskId:String(t.taskId),token:w,capabilities:t.workerMcpCapabilities??null},console.error(`[supervisor] ${n}: worker tools enabled (in-process, no config on disk)`)):console.error(`[supervisor] ${n}: worker tools skipped (missing API base URL or task identity) \u2014 spawning without tools`)}let L=VC(s.name);if(w&&L&&aa()){let E=An();if(E&&t.agentOsId&&t.taskId){let V=Hh({agentOsId:String(t.agentOsId),workerKey:l}),x=await Oa.start({address:V,apiBaseUrl:E,agentOsId:String(t.agentOsId),taskId:String(t.taskId),token:w,capabilities:t.workerMcpCapabilities??null,expiresAt:t.workerMcpExpiresAt??Date.now()+yz,workerPid:process.pid,identity:Gh(),onRefusal:T=>console.error(`[supervisor] ${n}: worker tools refused a call (${T})`)});if(kh(l,x),s.name==="codex"){let T=AA({workerDir:l,brokerSocketPath:V.socketPath});if(T.ok){let U=PA(T.codexHome,xr());U.ok?(S=T.codexHome,b=S):(_a(l),await Yr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 codex rejected the generated config (${U.detail}); spawning with the normal environment`))}else await Yr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${T.detail}`)}else if(s.name==="cursor"){let T=CA({worktreePath:c,brokerSocketPath:V.socketPath});T.ok?b=T.configPath:(await Yr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${T.detail}`))}else if(s.name==="gemini"&&vs(ht())==="antigravity"){let T=MA({worktreePath:c,brokerSocketPath:V.socketPath});T.ok?b=T.configPath:(await Yr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${T.detail}`))}else if(s.name==="gemini"){let T=BA({workerDir:l,brokerSocketPath:V.socketPath});T.ok?(R=T.geminiCliHome,b=R):(await Yr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${T.detail}`))}else b=JC({workerDir:l,brokerSocketPath:V.socketPath});b&&console.error(`[supervisor] ${n}: worker tools enabled via broker (${x.identitySummary})`)}else console.error(`[supervisor] ${n}: worker MCP tools skipped (missing API base URL or task identity) \u2014 spawning without tools`)}let N=t.taskId?KR($R(e.id,String(t.taskId),n)):null,A;try{A=HR(N,()=>s.start({name:n,task:t.task,ownedPaths:t.ownedPaths,model:i,branch:d,worktreePath:c,workerDir:l,stdoutPath:f,stderrPath:m,heartbeatPath:g,prompt:h,reviewWorker:k,executionMode:t.executionMode??"write",..._?{workerToolGrant:_}:{},...S?{codexHome:S}:{},...R?{geminiCliHome:R}:{},...b?{mcpConfigPath:b,mcpAllowedTools:jC(t.workerMcpCapabilities)}:{}}))}catch(E){throw b&&(ku(l),Vu(c),_a(l),qu(l),Ju(c),ws(l)),ce(e.repo,["worktree","remove","--force",c],{allowFailure:!0}),ce(e.repo,["branch","-D",d],{allowFailure:!0}),E}finally{y===void 0?delete process.env.KYNVER_HARNESS_TASK_ID:process.env.KYNVER_HARNESS_TASK_ID=y,v===void 0?delete process.env.KYNVER_HARNESS_AGENT_OS_ID:process.env.KYNVER_HARNESS_AGENT_OS_ID=v}let O=RE(A.model,i,s.defaultModel),W=P(),D=et(process.env,W),G=De().runnerId,Q=jo({boxKind:D.boxKind,config:W,env:process.env}),H={name:n,runId:e.id,status:"running",pid:A.pid,model:O,provider:o.provider,branch:d,worktreePath:c,workerDir:l,stdoutPath:f,stderrPath:m,heartbeatPath:g,ownedPaths:t.ownedPaths,...t.agentOsId?{agentOsId:String(t.agentOsId)}:{},...t.taskId?{taskId:String(t.taskId)}:{},...t.planId?{planId:String(t.planId)}:{},...t.instructionPolicyFingerprint?{instructionPolicyFingerprint:String(t.instructionPolicyFingerprint)}:{},...t.instructionPolicyEvidence?{instructionPolicyEvidence:t.instructionPolicyEvidence}:{},...t.memoryQualityCapture?{memoryQualityCapture:t.memoryQualityCapture}:{},...t.personaSlug?{personaSlug:String(t.personaSlug)}:{},...t.personaEvidence?{personaEvidence:t.personaEvidence}:{},...t.contextEnvelopeEvidence?{contextEnvelopeEvidence:t.contextEnvelopeEvidence}:{},...t.runtimeEnvelopeEvidence?{runtimeEnvelopeEvidence:t.runtimeEnvelopeEvidence}:{},...t.leaseOwner?{leaseOwner:String(t.leaseOwner)}:{},...t.leaseToken?{leaseToken:String(t.leaseToken)}:{},...t.dispatched?{dispatched:!0}:{},...!t.agentOsId||!t.taskId?{localOnly:!0}:{},routingRule:o.rule,...o.requestedModel?{requestedModel:o.requestedModel}:{},...o.orchestrationAudit?{orchestrationAudit:o.orchestrationAudit}:{},...t.executorRef?{executorRef:String(t.executorRef)}:{},...t.parentTaskId?{parentTaskId:String(t.parentTaskId)}:{},...t.taskTitle?{taskTitle:String(t.taskTitle)}:{},...t.taskPrUrl?{taskPrUrl:String(t.taskPrUrl)}:{},...t.repairTargetPrUrl?{repairTargetPrUrl:String(t.repairTargetPrUrl)}:{},...t.repairTargetBranch?{repairTargetBranch:String(t.repairTargetBranch)}:{},executionMode:t.executionMode??"write",boxKind:D.boxKind,boxId:Q,runtimeId:G,startedAt:new Date().toISOString(),...N?{oomRetryHeapMb:N}:{}};if(X(e.id,H),yh(l,A.pid),e.workers={...e.workers||{},[n]:{workerDir:l,statusPath:Is.join(l,"worker.json")}},e.status="running",Ve(e),H.agentOsId&&H.taskId){let E;try{E=NP({runId:e.id,workerName:n,workerDir:l,agentOsId:H.agentOsId})}catch(V){let x=`completion sidecar failed to spawn: ${V.message}`;H.completionBlocker=x,X(e.id,H)}if(E)E.pid&&(H.completionSidecarPid=E.pid,X(e.id,H));else{let V=H.completionBlocker??"completion sidecar failed to spawn (CLI not found or spawn error)";H.completionBlocker=V,H.completionSidecarSpawnFailedAt=new Date().toISOString(),X(e.id,H),ME(e.id,H,V)}}return H}var yz,YP=p(()=>{"use strict";Rs();Mf();we();Y();Y();WE();jE();M();lu();Bn();JE();DP();MP();BP();Le();Vo();$();ot();vh();Rh();Vn();xh();qn();Sh();JP();yr();ah();yz=7200*1e3});function kz(e,t){let r=Te(t)?.trim();return r||Pe("KYNVER_RUNNER_TOKEN",e)||Pe("OPENCLAW_RUNNER_TOKEN",e)||null}function bz(e){let t=_e()?.trim();return t||Pe("KYNVER_API_KEY",e)||Pe("KYNVER_RUNTIME_SECRET",e)||Pe("KYNVER_CRON_SECRET",e)||Pe("OPENCLAW_CRON_SECRET",e)||null}async function zP(e,t={}){let r=t.env??process.env,n=t.nowMs??Date.now(),o=t.timeoutMs??8e3,s=new Date(n).toISOString(),i=t.fetcher??fetch,a=kz(r,e.agentOsId),l=bz(r),c="none",u={};if(a)c="runner_token",u["X-Kynver-Runner-Token"]=a;else if(l)c="api_key",u["X-Kynver-Service-Secret"]=l;else return{reachable:!1,authSource:"none",endpoint:null,httpStatus:null,responseMs:null,probedAt:s,error:"No runner token or API key found \u2014 set KYNVER_RUNNER_TOKEN, store runnerToken in ~/.kynver/credentials, or complete M0.3 install"};let d=`${e.apiBaseUrl}/api/agent-os/runner-token/verify`,f=Date.now();try{let m=AbortSignal.timeout(o),g=await i(d,{method:"GET",headers:{...u,Accept:"application/json","X-Kynver-Agent-Os-Id":e.agentOsId},signal:m}),h=Date.now()-f,y=g.status<500;return{reachable:y,authSource:c,endpoint:d,httpStatus:g.status,responseMs:h,probedAt:s,error:y?null:`MCP endpoint returned HTTP ${g.status} \u2014 server error or misconfigured KYNVER_API_URL`}}catch(m){let g=Date.now()-f,h=m instanceof Error?m.message:String(m);return{reachable:!1,authSource:c,endpoint:d,httpStatus:null,responseMs:g,probedAt:s,error:`MCP endpoint unreachable: ${h}`}}}var XP=p(()=>{"use strict";$();St()});function vz(e,t){let r=e.KYNVER_API_URL?.trim()||e.KYNVER_CRON_FIRE_BASE_URL?.trim()||t.apiBaseUrl?.trim()||null;return r?or(r)??null:null}function Rz(e,t){return(e.KYNVER_DEFAULT_REPO?.trim()||e.KYNVER_HARNESS_REPO?.trim()||t.defaultRepo?.trim()||null)??null}function wz(e,t,r){let n=e.KYNVER_HARNESS_ROOT?.trim()||t.harnessRoot?.trim()||null;return n||r||null}function QP(e,t={}){let r=t.env??process.env,n=t.nowMs??Date.now(),o=t.config??{},s=vz(r,o);if(!s)return{ok:!1,code:"missing_api_base_url",detail:"No API base URL found. Set KYNVER_API_URL, or run `kynver setup --api-base-url <url>`."};let i=(r.KYNVER_AGENT_OS_ID??r.OPENCLAW_AGENT_OS_ID??o.agentOsId??"").trim();if(i&&i!==e.agentOsId)return{ok:!1,code:"workspace_mismatch",detail:`envelope workspace "${e.agentOsId}" does not match local config "${i}"`};let a=Rz(r,o),l=wz(r,o,a);return{ok:!0,context:{jobId:e.jobId,agentOsId:e.agentOsId,taskId:e.taskId,repoPath:a,worktreeBase:l,apiBaseUrl:s,hydratedAt:new Date(n).toISOString()}}}var ZP=p(()=>{"use strict";sr()});var Ta=p(()=>{"use strict"});var Na=p(()=>{"use strict"});var qh=p(()=>{"use strict";$();Na()});var zh=p(()=>{"use strict";Ta()});import{mkdirSync as tI}from"node:fs";import{homedir as Sz,tmpdir as fwe}from"node:os";import ud from"node:path";function rI(){let e=process.env.KYNVER_STATE_ROOT;return e?ud.resolve(e):ud.join(Sz(),".kynver","state")}function dd(){return ud.join(rI(),"plan-outbox")}function _z(){return ud.join(rI(),"plan-outbox-archive")}function nI(){let e=dd(),t=_z();return tI(e,{recursive:!0}),tI(t,{recursive:!0}),{outboxDir:e,archiveDir:t}}var Da=p(()=>{"use strict"});function oI(){return{"planOutbox.storeFailures":Ma.storeFailures,"planOutbox.corruptItemsSeen":Ma.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":Ma.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":Ma.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":Ma.halfArchivesCompleted}}var kwe,Ma,La=p(()=>{"use strict";Jr();ls();kwe=600*1e3,Ma={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0}});import{existsSync as Ez,readFileSync as Az,renameSync as wwe,readdirSync as Swe,rmSync as _we,writeFileSync as xwe,unlinkSync as Cwe}from"node:fs";import sI from"node:path";function iI(e){if(!Ez(e))return null;try{return JSON.parse(Az(e,"utf8"))}catch{return null}}function pd(e){let{outboxDir:t}=nI();return{jsonPath:sI.join(t,`${e.id}.json`),bodyPath:sI.join(t,e.bodyPath)}}var Ba=p(()=>{"use strict";La();Ta();zh();Da()});var aI=p(()=>{"use strict";Ta();Na();qh()});var Xh=p(()=>{"use strict";qh();Na();zh();Da();La();Ba();aI()});import Dz from"node:path";function Qh(e){let t=Dz.join(dd(),`${e}.json`);return iI(t)}var lI=p(()=>{"use strict";Ba();La();Xh();Da()});function Zh(e){let t=pd(e);return["## Plan persistence risk","",`AgentOS plan write is **not** confirmed (${e.userStatus}).`,`- outboxId: \`${e.id}\``,e.planId?`- planId: \`${e.planId}\``:"- planId: (pending \u2014 create not yet applied)",`- outbox: \`${t.jsonPath}\``,`- body: \`${t.bodyPath}\``,"","Drain when approval/connectivity returns: `kynver plan outbox drain`"].join(`
|
|
174
|
+
`)}function ey(e){let t=e.metadata&&typeof e.metadata=="object"?e.metadata:null,r=typeof e.planPersistenceOutboxId=="string"&&e.planPersistenceOutboxId||(t&&typeof t.planPersistenceOutboxId=="string"?t.planPersistenceOutboxId:void 0);return r?{outboxId:r,jsonPath:typeof e.planPersistenceOutboxPath=="string"?e.planPersistenceOutboxPath:t&&typeof t.planPersistenceOutboxPath=="string"?t.planPersistenceOutboxPath:void 0,bodyPath:typeof e.planPersistenceBodyPath=="string"?e.planPersistenceBodyPath:t&&typeof t.planPersistenceBodyPath=="string"?t.planPersistenceBodyPath:void 0}:null}var cI=p(()=>{"use strict";Ba()});var uI=p(()=>{"use strict";Ta();Xh();lI();Ba();cI();Da();Na()});function ty(e){return e?.trim()?e.trim():null}function dI(e,t){let r=ty(e.boxKind),n=ty(e.runnerId),o=ty(e.harnessRoot);return r&&r!==t.boxKind?{ok:!1,reason:`run ${e.id} belongs to box "${r}" but this host is "${t.boxKind}" \u2014 use a run under ${t.harnessRoot}`}:n&&n!==t.runnerId?{ok:!1,reason:`run ${e.id} is bound to runner "${n}" but this host is "${t.runnerId}"`}:o&&o!==t.harnessRoot?{ok:!1,reason:`run ${e.id} harness root "${o}" does not match this host "${t.harnessRoot}"`}:!r||!n||!o?(e.boxKind=t.boxKind,e.runnerId=t.runnerId,e.harnessRoot=t.harnessRoot,Ve(e),{ok:!0,stamped:!0}):{ok:!0}}var pI=p(()=>{"use strict";Y()});function fI(e=process.env){return Wt(P(),e,{requireExplicitBoxKind:!0})}function mI(e){return[...e.errors,...e.warnings].join("; ")}var gI=p(()=>{"use strict";$();Sn()});async function Wa(e){let t=`${e.baseUrl}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/tasks/${encodeURIComponent(e.taskId)}/release`,r;try{r=await de(t,e.secret,{agentOsId:e.agentOsId,leaseOwner:e.leaseOwner,...e.leaseToken?.trim()?{leaseToken:e.leaseToken.trim()}:{},...e.failureDetail?{failureDetail:e.failureDetail}:{}},{agentOsId:e.agentOsId,baseUrl:e.baseUrl})}catch(s){return{released:!1,httpOk:!1,transportError:!0,releaseResponse:{ok:!1,error:s.message}}}let n=r.response;return{released:r.ok===!0||n?.ok===!0,httpOk:r.ok===!0,transportError:!1,releaseResponse:r.response??r}}var ry=p(()=>{"use strict";Fe()});function Os(e){if(!e||typeof e!="object")return!1;let t=e;return[t.agentOsId,t.subjectTaskId,t.reviewTaskId,t.signature].every(r=>typeof r=="string"&&!!r)&&/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/[1-9]\d*$/.test(t.prUrl)&&/^[a-f0-9]{40}$/.test(t.headSha)&&/^[a-f0-9]{64}$/.test(t.reviewGenerationSha256)&&Number.isSafeInteger(t.reviewAttempt)&&t.reviewAttempt>0&&typeof t.acceptedAt=="string"&&Number.isFinite(Date.parse(t.acceptedAt))}function hI(e,t){return e.signature===t.signature&&e.agentOsId===t.agentOsId&&e.subjectTaskId===t.subjectTaskId&&e.prUrl===t.prUrl&&e.reviewTaskId===t.reviewTaskId&&e.reviewAttempt===t.reviewAttempt&&e.reviewGenerationSha256===t.reviewGenerationSha256&&e.headSha===t.headSha&&e.acceptedAt===t.acceptedAt}var ny=p(()=>{"use strict"});function tn(e){return typeof e.name=="string"&&e.name||typeof e.context=="string"&&e.context||typeof e.workflowName=="string"&&e.workflowName||"unknown check"}function kI(e){let t=typeof e.completedAt=="string"&&e.completedAt||typeof e.startedAt=="string"&&e.startedAt;if(!t)return 0;let r=Date.parse(t);return Number.isFinite(r)?r:0}function bI(e){let t=Array.isArray(e)?e:[],r=new Map;for(let n of t){let o=n&&typeof n=="object"?n:{},s=tn(o),i=r.get(s);(!i||kI(o)>=kI(i))&&r.set(s,o)}return[...r.values()]}function Mz(e){let t=typeof e.detailsUrl=="string"&&e.detailsUrl||typeof e.details_url=="string"&&e.details_url||typeof e.html_url=="string"&&e.html_url||"",r=typeof e.workflowName=="string"?e.workflowName.trim():"",n=e.app&&typeof e.app=="object"?e.app:null,o=typeof n?.slug=="string"?n.slug:"";return r.length>0||o==="github-actions"||/^https:\/\/github\.com\/[^/]+\/[^/]+\/actions\//i.test(t)}function vI(e){let t=bI(e),r=[],n=[],o=[];for(let s of t){if(Mz(s)){o.push(tn(s));continue}let i=typeof s.conclusion=="string"?s.conclusion.toUpperCase():"",a=typeof s.status=="string"?s.status.toUpperCase():"",l=typeof s.state=="string"?s.state.toUpperCase():"";if(!(i&&yI.has(i))){if(i){n.push(`${tn(s)}=${i}`);continue}if(!(l&&yI.has(l))){if(l&&l!=="PENDING"&&l!=="EXPECTED"){n.push(`${tn(s)}=${l}`);continue}if(l==="PENDING"||l==="EXPECTED"){r.push(`${tn(s)}=${l}`);continue}if(a&&a!=="COMPLETED"){r.push(`${tn(s)}=${a}`);continue}r.push(`${tn(s)}=PENDING`)}}}return{pending:r,failed:n,ignoredActions:o}}function RI(e){return bI(e).some(r=>{let n=tn(r),o=typeof r.conclusion=="string"?r.conclusion.toUpperCase():"",s=typeof r.state=="string"?r.state.toUpperCase():"";return/^vercel/i.test(n)&&(o==="SUCCESS"||s==="SUCCESS")})}function wI(e,t){let r=e==="UNSTABLE"&&t.ignoredActions.length>0;return!Lz.has(e)&&!r?`mergeStateStatus is ${e}`:null}var yI,Lz,SI=p(()=>{"use strict";yI=new Set(["SUCCESS","SKIPPED","NEUTRAL"]);Lz=new Set(["CLEAN","HAS_HOOKS"])});import{spawnSync as Bz}from"node:child_process";function _I(){if(process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim())return{source:"env",configured:!0,reason:"GitHub token already configured in environment"};let e=Bz("gh",["auth","token"],{windowsHide:!0,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(e.status!==0)return{source:"missing",configured:!1,reason:typeof e.stderr=="string"&&e.stderr.trim()?e.stderr.trim():"gh auth token failed; run `gh auth login` on this machine"};let t=typeof e.stdout=="string"?e.stdout.trim():"";return t?(process.env.GH_TOKEN=t,{source:"gh-cli",configured:!0,reason:"Using local GitHub CLI auth for daemon land_pr merge"}):{source:"missing",configured:!1,reason:"gh auth token returned an empty token; run `gh auth login` on this machine"}}var xI=p(()=>{"use strict"});import{createHash as Wz,randomUUID as Uz}from"node:crypto";import{closeSync as CI,fsyncSync as EI,mkdirSync as Fz,openSync as AI,realpathSync as Kz,writeFileSync as $z}from"node:fs";import oy from"node:path";function II(e){return!!e&&[e.agentOsId,e.taskId,e.runId,e.workerName,e.leaseOwner,e.leaseToken,e.receiptDir].every(t=>typeof t=="string"&&!!t.trim())}function PI(e,t,r,n){Fz(e,{recursive:!0,mode:448});let o=Kz(e),s=AI(oy.join(o,`${t}.${r}.json`),"wx",384);try{$z(s,JSON.stringify({...n,phase:r},null,2)+`
|
|
175
|
+
`),EI(s)}finally{CI(s)}for(let i=o;;i=oy.dirname(i)){let a=AI(i,"r");try{EI(a)}catch(l){if(!Hz(l))throw l}finally{CI(a)}if(i===oy.dirname(i))break}}function Hz(e,t=process.platform){return t==="win32"&&e?.code==="EPERM"}function OI(e,t,r,n){let o={acceptedReview:n,agentOsId:e.agentOsId,taskId:e.taskId,runId:e.runId,workerName:e.workerName,leaseOwner:e.leaseOwner,leaseTokenSha256:Wz("sha256").update(e.leaseToken).digest("hex")},s={...o,prUrl:t,invocationId:Uz(),startedAt:new Date().toISOString(),finishedAt:null,headSha:r,mergedAt:null,mergeCommit:null,source:"daemon_land_pr",mergeInvoked:!1};return PI(e.receiptDir,s.invocationId,"pending",s),{finish(i){let a={...o,...i,invocationId:s.invocationId,startedAt:s.startedAt,finishedAt:new Date().toISOString()};return PI(e.receiptDir,s.invocationId,"finished",{...s,...a}),a}}}var TI=p(()=>{"use strict"});import{spawnSync as NI}from"node:child_process";function iy(e){return e?.trim()?["--repo",e.trim()]:[]}function DI(e){let t=/github\.com\/([^/]+)\/([^/]+)\/pull\/\d+/i.exec(e.trim());return t?`${t[1]}/${t[2]}`:null}function MI(e,t,r){let n=e.gh(t,r);if(n.status!==0)throw new Error(n.stderr||n.stdout||`gh ${r.join(" ")} failed`);return JSON.parse(n.stdout||"{}")}function qz(e){let t=typeof e.title=="string"?e.title.trim():"",r=typeof e.body=="string"?e.body.trim():"",n=Gz.test(t)||Jz.test(r),o=jz.test(r),s=Vz.test(r);return n||o||s||e.vercelCheckSuccess===!0}function Yz(e){if(!qz({title:e.title,body:e.body,vercelCheckSuccess:RI(e.statusCheckRollup)}))throw new Error(`PR #${e.number} lacks landing verification evidence \u2014 add ## Test plan / ## Verification with local commands, Vercel preview, or docs/no-code rationale`)}function zz(e){if(e.state!=="OPEN")throw new Error(`PR #${e.number} is ${e.state}, not OPEN`);if(e.isDraft)throw new Error(`PR #${e.number} is still a draft`);let t=vI(e.statusCheckRollup);if(t.failed.length>0)throw new Error(`PR #${e.number} has failing checks: ${t.failed.join(", ")}`);if(t.pending.length>0)throw new Error(`PR #${e.number} has pending checks: ${t.pending.join(", ")}`);let r=wI(e.mergeStateStatus,t);if(r)throw new Error(`PR #${e.number} ${r}`)}function Xz(e){zz(e),Yz(e)}function Qz(e){try{return Xz(e),null}catch(t){return t instanceof Error?t.message:String(t)}}function Zz(e,t,r,n){if(!n?.trim())return;let o=encodeURI(`heads/${n}`);e.gh(t,["api","-X","DELETE",`repos/${r}/git/refs/${o}`])}function e6(e,t,r){if(r?.trim())return r.trim();let n=e.gh(t,["repo","view","--json","nameWithOwner"]);if(n.status!==0)throw new Error(n.stderr||"Could not resolve GitHub repo");let o=JSON.parse(n.stdout||"{}");if(!o.nameWithOwner)throw new Error("Could not resolve GitHub repo");return o.nameWithOwner}function t6(e,t){if(!t?.trim())return;let r=NI("git",["worktree","list","--porcelain"],{windowsHide:!0,cwd:e,encoding:"utf8"});if(r.status!==0)return;let n=String(r.stdout||"").split(/\r?\n/),o=null,s=null;for(let i of n){if(i.startsWith("worktree ")){o=i.slice(9).trim(),s=null;continue}i.startsWith("branch ")&&o&&(s=i.slice(7).trim(),s.endsWith(`/${t}`)&&NI("git",["worktree","remove","--force",o],{windowsHide:!0,cwd:e,encoding:"utf8"}))}}async function LI(e){let t=e.cwd??process.cwd(),r=e.exec??$u,n=e.prUrl.trim();if(!n)throw new Error("prUrl is required");let o=e.acceptedReview,s=()=>({prUrl:n,outcome:"blocked",reason:"accepted_review_required: missing, stale or changed head; fresh independent review required"});if(!Os(o)||o.prUrl!==n||o.agentOsId!==e.operation?.agentOsId||!e.revalidateAcceptedReview)return s();let i=_I();if(!i.configured)return{prUrl:n,outcome:"blocked",reason:i.reason};let a=MI(r,t,["pr","view",n,...iy(e.repo),"--json",["number","url","title","body","state","isDraft","mergeStateStatus","statusCheckRollup","headRefName","headRefOid","mergedAt","mergeCommit"].join(",")]);if(a.state==="MERGED")return{prUrl:a.url||n,outcome:"skipped",mergeCommit:a.mergeCommit?.oid??null,provenance:{attribution:"preexisting_merge",mergeInvoked:!1,headSha:a.headRefOid??null,mergedAt:a.mergedAt??null,mergeCommit:a.mergeCommit?.oid??null},reason:`PR #${a.number} is already merged \u2014 land_pr no-op (redelivery)`};if(a.headRefOid?.toLowerCase()!==o.headSha)return s();let l=Qz(a);if(l)return e.skipNotReady?{prUrl:a.url||n,outcome:"skipped",reason:l}:{prUrl:a.url||n,outcome:"blocked",reason:l};if(e.dryRun)return{prUrl:a.url||n,outcome:"skipped",reason:"dry-run: PR is ready to merge"};if(!a.headRefOid||!/^[a-f0-9]{40}$/i.test(a.headRefOid)||!II(e.operation))return{prUrl:n,outcome:"blocked",reason:"land_pr requires observed headRefOid and claimed dispatch operation identity"};let c=String(a.number),u=await e.revalidateAcceptedReview().catch(()=>null);if(!Os(u)||!hI(o,u))return s();let d=OI(e.operation,n,o.headSha,o),f;try{f=r.gh(t,["pr","merge",c,...iy(e.repo),"--squash","--match-head-commit",o.headSha])}catch{let y=d.finish({attribution:"unconfirmed",mergeInvoked:!0,headSha:a.headRefOid,mergedAt:null,mergeCommit:null,mergeExitCode:null});return{prUrl:n,outcome:"blocked",reason:"merge invocation threw; outcome unconfirmed",provenance:y}}let m=(y,v)=>d.finish({attribution:v,mergeInvoked:!0,headSha:a.headRefOid,mergedAt:y?.mergedAt??null,mergeCommit:y?.mergeCommit?.oid??null,mergeExitCode:f.status});if(f.status!==0){let y=sy(r,t,c,e.repo);return y?{prUrl:y.url||a.url||n,outcome:"skipped",mergeCommit:y.mergeCommit?.oid??null,provenance:m(y,"external_merge_observed"),reason:`PR #${a.number} is already merged \u2014 merged by another lane during land_pr (race)`}:{prUrl:a.url||n,outcome:"blocked",reason:f.stderr||f.stdout||"gh pr merge failed",provenance:m(null,"unconfirmed")}}let g=sy(r,t,c,e.repo);if(g||(g=sy(r,t,c,e.repo)),!g)return{prUrl:n,outcome:"blocked",reason:"merge command completed but merged state is unconfirmed",provenance:m(null,"unconfirmed")};let h=m(g,"invoked_merge_observed");try{let y=e6(r,t,e.repo);Zz(r,t,y,a.headRefName),t6(t,a.headRefName)}catch{}return{prUrl:g?.url||a.url||n,outcome:"merged",provenance:h,mergeCommit:g?.mergeCommit?.oid??null,reason:`Daemon land_pr invoked merge; PR #${a.number} read back merged`}}function sy(e,t,r,n){try{let o=MI(e,t,["pr","view",r,...iy(n),"--json","number,url,mergedAt,mergeCommit,state"]);return o.state==="MERGED"?o:null}catch{return null}}var jz,Vz,Gz,Jz,BI=p(()=>{"use strict";ny();Hu();SI();xI();TI();jz=/^##\s*(test\s*plan|verification|test\s*evidence|verify)\b/im,Vz=/typecheck|npm run (test|build|typecheck)|vitest|tsc\b|verify-pr-local|local verify|local-verify|tests? (pass|green)|build green|node --test/i,Gz=/^docs[(:]/i,Jz=/docs[- ]only|documentation only|no[- ]code change|no code changes|low[- ]risk|plan tracker only|markdown only/i});async function WI(e){let t=e.decision.task,r=e.decision.acceptedReview,n=String(t.prUrl??"");return LI({prUrl:n,cwd:e.cwd,repo:DI(n),exec:e.exec,operation:e.operation,acceptedReview:Os(r)?r:void 0,revalidateAcceptedReview:async()=>{let o=await de(`${e.baseUrl}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/tasks/${encodeURIComponent(String(t.id))}/landing-review`,e.secret,{leaseToken:t.leaseToken,leaseOwner:t.leaseOwner,attempt:t.attempt},{agentOsId:e.agentOsId,baseUrl:e.baseUrl}),s=o.response;return o.ok&&s?.ok===!0&&Os(s.acceptedReview)?s.acceptedReview:null}})}var UI=p(()=>{"use strict";Fe();ny();BI()});async function FI(e){let t=await me(e.secret,e.agentOsId,{baseUrl:e.baseUrl}),r=String(e.task.id),n=`${e.baseUrl}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/harness/completion`,o=e.report.provenance?.finishedAt??new Date().toISOString(),s={source:"kynver-harness",agentOsId:e.agentOsId,runId:e.runId,workerName:`land-pr-${r}`,taskId:r,leaseToken:e.task.leaseToken??null,startedAt:e.report.provenance?.startedAt??o,finishedAt:o,status:{finalResult:e.report,prUrl:e.report.prUrl,summary:e.report.reason,leaseToken:e.task.leaseToken??null},workerInjection:null},i=await de(n,t,s,{agentOsId:e.agentOsId,baseUrl:e.baseUrl});return{ok:i.ok,status:i.status}}var KI=p(()=>{"use strict";$();Fe()});function $I(){return["## verify_live completion contract","Finish with a JSON finalResult object:","{",' "prUrl": "<landed pr>",',' "outcome": "passed" | "failed" | "skipped" | "no_mcp_surface",',' "reason": "<human summary>",',' "mergeCommit": "<sha optional>",',' "liveReadback": "<prod readback string from acceptance.liveReadbackQuery>",',' "mcpCalls": [{ "tool": "<name>", "ok": true, "summary": "..." }]',"}","","Drive the feature MCP tools against live production. Do not mark passed without exercising the MCP surface.","When the subject carries an acceptance snapshot, include liveReadback \u2014 the server oracle rejects passed if the original symptom still appears."].join(`
|
|
176
|
+
`)}var HI=p(()=>{"use strict"});function Xn(e){return`${r6} ${e.trim()}`}function n6(e){return e.branch?.trim()?e.worktreePath?.trim()?e.heartbeatPath?.trim()?e.startedAt?.trim()?null:"missing local worker startedAt":"missing local worker heartbeatPath":"missing local worker worktreePath":"missing local worker branch"}function o6(e){let{snapshot:t,leaseOwner:r,expectedLeaseToken:n,worker:o}=e;if(!t)return{ok:!1,error:Xn("task lease snapshot missing after spawn"),detail:{taskId:o.taskId,leaseOwner:r,expectedLeaseToken:n}};if(t.status!=="running")return{ok:!1,error:Xn(`AgentOS task status=${t.status} (expected running)`),detail:{taskId:t.taskId,status:t.status,leaseOwner:t.leaseOwner,blocker:t.blocker},snapshot:t};let s=t.leaseOwner?.trim()??"";if(!s||s!==r.trim())return{ok:!1,error:Xn(`leaseOwner mismatch (board=${s||"null"}, expected=${r})`),detail:{taskId:t.taskId,boardLeaseOwner:s||null,expectedLeaseOwner:r},snapshot:t};let i=t.leaseToken?.trim()??"";if(!i||i!==n.trim())return{ok:!1,error:Xn(`leaseToken mismatch (board=${i||"null"}, expected=${n})`),detail:{taskId:t.taskId,boardLeaseToken:i||null,expectedLeaseToken:n},snapshot:t};let a=n6(o);return a?{ok:!1,error:Xn(a),detail:{taskId:o.taskId,worker:o.name},snapshot:t}:t.heartbeatAt?.trim()?o.executorRef?.trim()&&t.executorRef?.trim()&&o.executorRef.trim()!==t.executorRef.trim()?{ok:!1,error:Xn(`executorRef mismatch (board=${t.executorRef}, worker=${o.executorRef})`),detail:{taskId:t.taskId,boardExecutorRef:t.executorRef,workerExecutorRef:o.executorRef},snapshot:t}:{ok:!0,snapshot:t}:{ok:!1,error:Xn("AgentOS heartbeatAt missing after claim"),detail:{taskId:t.taskId},snapshot:t}}async function jI(e){let t=await Ou({agentOsId:e.agentOsId,taskIds:[e.taskId],baseUrl:e.baseUrl,secret:e.secret});return o6({snapshot:t.get(e.taskId)??null,leaseOwner:e.leaseOwner,expectedLeaseToken:e.expectedLeaseToken,worker:e.worker})}var r6,VI=p(()=>{"use strict";Xg();r6="dispatch_start_readback_failed:"});function GI(e,t,r){t.pid&&re(t.pid)&&(fe(t.pid,"SIGTERM"),re(t.pid)&&fe(t.pid,"SIGKILL"));let n={...t,status:"failed",pid:void 0,completionBlocker:r,dispatchStartReadbackFailed:!0};return X(e,n),n}var JI=p(()=>{"use strict";M();Y()});function qI(e){let t=typeof e.personaSlug=="string"?e.personaSlug.trim().toLowerCase():"";if(t==="dalton"||t==="lorentz")return!0;let r=typeof e.executorRef=="string"?e.executorRef.trim().toLowerCase():"";if(r.startsWith("expert-lane-pr-review:")||r.startsWith("scheduledjob:")&&e.parentTaskId)return!0;let n=typeof e.title=="string"?e.title.toLowerCase():"";return n.includes("expert pr review")||n.startsWith("[dalton] review")||n.startsWith("[lorentz] review")}async function YI(e){let t=`${e.baseUrl}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/tasks/${encodeURIComponent(e.taskId)}/review-head-reconcile`,r=await de(t,e.secret,{phase:"worker_start"},{agentOsId:e.agentOsId,baseUrl:e.baseUrl});if(!r.ok)return null;let n=r.response;return n&&typeof n=="object"?n:null}var zI=p(()=>{"use strict";Fe()});function XI(e){let t=e.admissionExhaustion;return!t||typeof t!="object"?null:t}function QI(e){let t=e.dispatchSkipDrain;return!t||typeof t!="object"?null:t}function s6(e){let t=e.harnessWorkerContext;if(!t||typeof t!="object")return null;let r=t,n=typeof r.instructionPolicyMarkdown=="string"?r.instructionPolicyMarkdown:null,o=typeof r.instructionPolicyFingerprint=="string"?r.instructionPolicyFingerprint:null,s=r.instructionPolicyEvidence&&typeof r.instructionPolicyEvidence=="object"?r.instructionPolicyEvidence:null,i=typeof r.personaMarkdown=="string"?r.personaMarkdown:null,a=typeof r.personaEvidence=="object"&&r.personaEvidence&&typeof r.personaEvidence.injectedPersonaSlug=="string"?r.personaEvidence.injectedPersonaSlug:null,l=r.personaEvidence&&typeof r.personaEvidence=="object"?r.personaEvidence:null,c=r.personaInjectionReady===!0,u=typeof r.contextEnvelopeMarkdown=="string"?r.contextEnvelopeMarkdown:null,d=r.contextEnvelopeEvidence&&typeof r.contextEnvelopeEvidence=="object"?r.contextEnvelopeEvidence:null,f=r.contextEnvelopeReady===!0,m=typeof r.runtimeEnvelopeMarkdown=="string"?r.runtimeEnvelopeMarkdown:null,g=a6(r.runtimeEnvelopeReceipt),h=r.runtimeEnvelopeReady===!0,y=r.memoryQualityCapture&&typeof r.memoryQualityCapture=="object"?r.memoryQualityCapture:null,v=typeof r.memoryQualityPromptMarkdown=="string"?r.memoryQualityPromptMarkdown:typeof y?.promptMarkdown=="string"?y.promptMarkdown:null,k=r.workerMcpToolGrant&&typeof r.workerMcpToolGrant=="object"?r.workerMcpToolGrant:null,b=k&&typeof k.token=="string"&&k.token.trim()?k.token.trim():null,_=b&&Array.isArray(k?.capabilities)?k.capabilities.filter(R=>typeof R=="string"&&R.trim().length>0):null,S=b&&typeof k?.exp=="number"&&Number.isFinite(k.exp)?k.exp*1e3:null;return{instructionPolicyMarkdown:n,instructionPolicyFingerprint:o,instructionPolicyEvidence:s,memoryQualityCapture:y,memoryQualityPromptMarkdown:v,personaMarkdown:i,personaSlug:a,personaEvidence:l,personaInjectionReady:c,contextEnvelopeMarkdown:u,contextEnvelopeEvidence:d,contextEnvelopeReady:f,runtimeEnvelopeMarkdown:m,runtimeEnvelopeEvidence:g,runtimeEnvelopeReady:h,workerMcpToken:b,workerMcpCapabilities:_,workerMcpExpiresAt:S}}function i6(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length?t:null}function a6(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.envelopeId!="string"||!t.envelopeId.trim()?null:{envelopeId:t.envelopeId,envelopeSchemaVersion:typeof t.envelopeSchemaVersion=="string"?t.envelopeSchemaVersion:void 0,generatedAt:typeof t.generatedAt=="string"?t.generatedAt:void 0,injectedAt:typeof t.injectedAt=="string"?t.injectedAt:void 0,mode:typeof t.mode=="string"?t.mode:void 0,memoryIncludedCount:typeof t.memoryIncludedCount=="number"?t.memoryIncludedCount:void 0,memoryOmittedCount:typeof t.memoryOmittedCount=="number"?t.memoryOmittedCount:void 0,degraded:typeof t.degraded=="boolean"?t.degraded:void 0,degradedReason:typeof t.degradedReason=="string"?t.degradedReason:t.degradedReason===null?null:void 0,auditFingerprint:typeof t.auditFingerprint=="string"?t.auditFingerprint:void 0,promptMarkdownChars:typeof t.promptMarkdownChars=="number"?t.promptMarkdownChars:void 0}}function l6(e,t){let r=[`[AgentOS task ${e.id}] ${e.title}`,"",e.description?String(e.description):"(no description on the board task)","",`Board linkage: agentOsId=${t}, taskId=${e.id}, attempt=${e.attempt}, executor=${e.executor}${e.executorRef?`, executorRef=${e.executorRef}`:""}.`,"This worker was dispatched from the AgentOS board. The harness reports your completion back to the board when you finish."];e.executor==="verify_live"&&r.push("",$I());let n=ey(e);if(n?.outboxId){let o=Qh(n.outboxId);o?r.push("",Zh(o)):r.push("","## Plan persistence risk","",`Unconfirmed AgentOS plan write (outboxId=${n.outboxId}).`)}return r.join(`
|
|
177
|
+
`)}function c6(e){let t=new Set;if(e.targetTaskId)return t.add(String(e.targetTaskId)),t;if(e.targetTaskIds)for(let r of String(e.targetTaskIds).split(",")){let n=r.trim();n&&t.add(n)}return t}async function Ts(e){let t=e.pipeline===!0||e.pipeline==="true";try{let oe=function(){return x.filter(I=>I.started).length},ge=function(I,C){Zi({runId:l.id,agentOsId:u,phase:I,startedCount:oe(),outcomeCount:x.length,cappedStarts:A,...C})},Ae=function(){return x.some(I=>(typeof I.error=="string"?I.error:"").startsWith("dispatch_start_readback_failed:"))},Av=function(I){return I.landPrDispatch===!0?!0:I.task?.executor==="land_pr"};var r=oe,n=ge,o=Ae,s=Av;let i=fI();if(!i.ok||!i.identity){let I=mI(i);if(t)return{ok:!1,error:I,boundary:i};console.error(`run dispatch failed: ${I}`),process.exit(1)}let a=i.identity;for(let I of i.warnings)console.error(`[dispatch] runner-boundary warning: ${I}`);let l=ne(String(_t(String(e.run||""),"--run"))),c=dI(l,a);if(!c.ok){let I=c.reason??"run does not belong to this runner boundary";if(t)return{ok:!1,error:I,runId:l.id,runnerBoundary:a};console.error(`run dispatch failed: ${I}`),process.exit(1)}c.stamped&&console.error(`[dispatch] stamped run ${l.id} with boxKind=${a.boxKind} runnerId=${a.runnerId}`);let u=String(_t(String(e.agentOsId||""),"--agent-os-id")),d=pe(e.baseUrl?String(e.baseUrl):void 0),f=await me(e.secret?String(e.secret):void 0,u,{baseUrl:d}),m=e.execute===!0||e.execute==="true",g=!m,h=De({runId:l.id}),y=ya(l.id,h.runnerId),v=RS(),k=v?Mc(l.repo):null,b=new WeakMap;if(v&&m&&!k){let I="desktop_execution_policy_denied:repo_identity_unavailable: the repository has no origin remote";if(t)return{ok:!1,error:I,runId:l.id};console.error(`run dispatch failed: ${I}`),process.exit(1)}let _=e.diskPath?Br({diskPath:String(e.diskPath)}):Br({diskPath:l.repo}),S=await eC({runId:l.id,agentOsId:u,args:e}),R=c6(e),w=R.size>0,L=Number(e.maxStarts)>0?Math.floor(Number(e.maxStarts)):1,N=w?Math.min(L,R.size):L;if(e.reconcileStaleBlockers===!0||e.reconcileStaleBlockers==="true"){let I=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/lane-hygiene`;try{await de(I,f,{agentOsId:u,dryRun:!1,includeBoardReconcile:!0},{agentOsId:u,baseUrl:d})}catch(C){console.error(`[dispatch] reconcile-stale-blockers lane-hygiene call failed: ${C.message}`)}}let A=g?N:Math.min(N,S.slotsAvailable);if(!g&&A<=0){let I={runId:l.id,agentOsId:u,dryRun:!1,skipped:!0,reason:S.reason??"no resource slots",resourceGate:S};if(t)return{ok:!0,...I};console.log(JSON.stringify(I,null,2));return}let O=Zo(l.id),W=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/tasks/dispatch-next`,D=(I,C)=>({agentOsId:u,...C?{claimAuthorization:C}:{},dryRun:g,maxStarts:I,leaseOwner:y,leaseDurationMs:Number(e.leaseMs)>0?Math.floor(Number(e.leaseMs)):eh,runnerDiskGate:_,runnerResourceGate:S,activeHarnessWorkers:O,runnerPresence:h,harnessBoardSnapshot:Kh(l.id),...e.lane?{lane:Qx(String(e.lane))}:{},...e.executor?{executor:String(e.executor)}:{},...e.diskPath?{diskPath:String(e.diskPath)}:{},...e.targetTaskId?{targetTaskId:String(e.targetTaskId)}:{},...!e.targetTaskId&&e.targetTaskIds?{targetTaskIds:String(e.targetTaskIds).split(",").map(K=>K.trim()).filter(Boolean)}:{}}),G=jx(),Q=async I=>{let C=v&&k?xS(k):void 0,K=await de(W,f,D(I,C),{agentOsId:u,baseUrl:d,timeoutMs:G})??{ok:!1,status:0,response:null},q=K.response;if(C&&Array.isArray(q?.result?.started))for(let se of q.result.started)se&&typeof se=="object"&&b.set(se,C.requestNonce);return{dispatch:K,result:q?.result}};g||Zi({runId:l.id,agentOsId:u,phase:"awaiting_dispatch_next",timeoutMs:G});let H=await Q(w||g?A:1);if(!H.dispatch.ok||!H.result){let I=hg(H.dispatch.response),C={runId:l.id,agentOsId:u,action:"dispatch",httpStatus:H.dispatch.status,response:H.dispatch.response,authRefreshed:H.dispatch.refreshedAuth===!0,authRefreshFailure:H.dispatch.authRefreshFailure,...I?{timeout:!0}:{}};if(I&&Zi({runId:l.id,agentOsId:u,phase:"timeout",timeout:!0,httpStatus:H.dispatch.status}),t)return{ok:!1,...C};console.log(JSON.stringify(C,null,2)),process.exit(1)}let E=H.result;if(g){let I=XI(E),C=QI(E),K={runId:l.id,agentOsId:u,dryRun:!0,wouldStart:E.started.map(q=>({taskId:q.task.id,title:q.task.title,reason:q.reason})),skipped:E.skipped.map(q=>({taskId:q.task.id,skipReason:q.skipReason,reason:q.reason})),diskGate:E.diskGate,resourceGate:E.resourceGate,inspected:E.inspected,pagesScanned:E.pagesScanned??null,candidatesExhausted:E.candidatesExhausted??null,capacityIdle:I?.capacityIdle===!0,admissionExhaustion:I,dispatchSkipDrain:C};if(t)return{ok:!0,...K};console.log(JSON.stringify(K,null,2));return}let V=CE(),x=[],T=[],U=Number(E.inspected)||0,te=!1;async function Z(I,C,K){let q=await Wa({baseUrl:d,secret:f,agentOsId:u,taskId:String(I.id),leaseOwner:y,leaseToken:I.leaseToken?String(I.leaseToken):null,failureDetail:C});I.leaseToken&&Ss({taskId:String(I.id),leaseToken:String(I.leaseToken).trim()},Oh(C));let se={taskId:I.id,started:!1,error:C,released:q.released,releaseResponse:q.releaseResponse,...K};return x.push(se),ge("outcome",{lastOutcome:se}),!1}async function KU(I){let C=I.task,K=String(C.id);if(w&&!R.has(K))return Z(C,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[...R]});if(!(C.prUrl?String(C.prUrl):""))return Z(C,"land_pr task missing prUrl");try{let se=await WI({decision:I,baseUrl:d,secret:f,agentOsId:u,cwd:l.repo,operation:{agentOsId:u,taskId:K,runId:l.id,workerName:`land-pr-${K}`,leaseOwner:y,leaseToken:typeof C.leaseToken=="string"?C.leaseToken:"",receiptDir:`${j(l.id)}/land-pr-operations`}}),wt=await FI({baseUrl:d,secret:f,agentOsId:u,runId:l.id,task:C,report:se});return wt.ok?(x.push({taskId:K,started:!0,landPr:!0,outcome:se.outcome,completionStatus:wt.status}),!0):Z(C,`land_pr completion POST failed (HTTP ${wt.status})`,{landPr:!0,outcome:se.outcome})}catch(se){return Z(C,se.message)}}async function $U(I){let C="duplicate_dispatch_prevented: live local worker already owns this task",K=await Wa({baseUrl:d,secret:f,agentOsId:u,taskId:String(I.id),leaseOwner:y,leaseToken:I.leaseToken?String(I.leaseToken):null,failureDetail:C});I.leaseToken&&Ss({taskId:String(I.id),leaseToken:String(I.leaseToken).trim()},Oh(C));let q={taskId:I.id,started:!1,error:C,alreadyRunning:!0,nonFatal:!0,released:K.released,releaseResponse:K.releaseResponse};return x.push(q),ge("outcome",{lastOutcome:q}),!1}async function HU(I){let C=I.task,K=s6(I),q=String(C.id);if(w&&!R.has(q))return Z(C,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[...R]});let se=i6(C.personaSlug);if(se&&(!K?.personaInjectionReady||!K.personaMarkdown))return Z(C,`persona_injection_required: missing anchored context-envelope persona block for "${se}"`);if(se&&!K?.runtimeEnvelopeReady)return Z(C,`runtime_envelope_required: missing AgentRuntimeEnvelope launch receipt for persona "${se}"`);if(OE(l.id,q))return $U(C);let wt=Number(C.attempt)||1;if(wt>V.maxTaskAttempts)return Z(C,`task attempt ${wt} exceeds KYNVER_MAX_TASK_ATTEMPTS (${V.maxTaskAttempts})`);let gn=C.leaseToken?String(C.leaseToken).trim():"";if(!gn)return Z(C,"dispatch_start_failed: claimed task missing leaseToken \u2014 refusing local spawn");let hn=B(`t-${C.id}-a${C.attempt}`),nr=Pu({explicitModel:e.model?String(e.model):void 0,explicitProvider:e.provider?String(e.provider):void 0,explicitProviderIsOperatorOverride:!!e.provider,configuredProvider:P().workerProvider,task:rC(C)});XA({taskId:q,leaseToken:gn,runId:l.id,workerName:hn,provider:nr.provider??null});let cf=SE({task:C,routing:nr,explicitProvider:e.provider?String(e.provider):void 0,explicitModel:e.model?String(e.model):void 0});if(!cf.ok)return Z(C,cf.error??"model_routing_mismatch",{modelRoutingGuard:cf});if(qI(C)){let Xe=await YI({agentOsId:u,taskId:q,baseUrl:d,secret:f});if(Xe&&Xe.dispatchable===!1)return Z(C,`pr_review_head_reconcile_blocked: ${Xe.reason??Xe.outcome??"stale PR head"}`,{headReconcile:Xe});if(Xe?.activeReviewTaskId&&Xe.activeReviewTaskId!==q)return Z(C,`pr_review_head_reconcile_retargeted: active review is ${Xe.activeReviewTaskId}`,{headReconcile:Xe})}let Al=bP(nr.provider);if(!Al.ok)return Z(C,`provider_quota_exhausted: ${Al.reason}`,{nonFatal:!0,providerQuotaPreflight:{provider:Al.provider,retryAt:Al.retryAtIso}});try{let Xe=C.planId?String(C.planId):void 0,Pl=FE({title:C.title?String(C.title):void 0,description:C.description?String(C.description):null,executorRef:C.executorRef?String(C.executorRef):null,prUrl:C.prUrl?String(C.prUrl):null,branch:C.branch?String(C.branch):null}),Dv=uP({runId:l.id,workerName:hn,maxSlots:S.maxConcurrentWorkers,diskActiveWorkers:Kf()});if(!Dv.admitted)return Z(C,`admission_refused: ${Dv.reason}`,{nonFatal:!0});let Il=K?.workerMcpToken??null;if(Il&&aa()){let xo=QP({jobId:`dispatch:${String(C.id)}`,agentOsId:u,taskId:String(C.id)},{config:{agentOsId:u,apiBaseUrl:d}});if(!xo.ok)console.error(`[dispatch] worker tools skipped for task ${String(C.id)}: context hydration failed (${xo.code}: ${xo.detail}) \u2014 spawning without tools`),Il=null;else{let uf=await zP(xo.context);uf.reachable||(console.error(`[dispatch] worker tools skipped for task ${String(C.id)}: tool endpoint probe failed (${uf.error??`HTTP ${uf.httpStatus}`}) \u2014 spawning without tools`),Il=null)}}DE(l.id,String(C.id),{except:hn});let Bt=await qP(l,{name:hn,task:l6(C,u),ownedPaths:e.owned?String(e.owned).split(",").map(xo=>xo.trim()).filter(Boolean):[],model:nr.model,provider:nr.provider,routingRule:nr.rule,requestedModel:nr.requestedModel,agentOsId:u,taskId:String(C.id),planId:Xe,branch:Pl?.targetPrBranch??void 0,executorRef:C.executorRef?String(C.executorRef):void 0,parentTaskId:C.parentTaskId?String(C.parentTaskId):void 0,taskTitle:C.title?String(C.title):void 0,taskPrUrl:Pl?.targetPrUrl??(C.prUrl?String(C.prUrl):void 0),repairTargetPrUrl:Pl?.targetPrUrl,repairTargetBranch:Pl?.targetPrBranch??void 0,instructionPolicyMarkdown:K?.instructionPolicyMarkdown??null,instructionPolicyFingerprint:K?.instructionPolicyFingerprint??null,instructionPolicyEvidence:K?.instructionPolicyEvidence??null,memoryQualityCapture:K?.memoryQualityCapture??null,memoryQualityPromptMarkdown:K?.memoryQualityPromptMarkdown??null,personaMarkdown:K?.personaMarkdown??null,personaSlug:K?.personaSlug??se,personaEvidence:K?.personaEvidence??null,contextEnvelopeMarkdown:K?.contextEnvelopeMarkdown??null,contextEnvelopeEvidence:K?.contextEnvelopeEvidence??null,runtimeEnvelopeMarkdown:K?.runtimeEnvelopeMarkdown??null,runtimeEnvelopeEvidence:K?.runtimeEnvelopeEvidence??null,workerMcpToken:Il,workerMcpCapabilities:K?.workerMcpCapabilities??null,workerMcpExpiresAt:K?.workerMcpExpiresAt??null,leaseOwner:y,leaseToken:gn,dispatched:!0,executionMode:Nc(C)}),Ol=await jI({agentOsId:u,taskId:String(C.id),leaseOwner:y,expectedLeaseToken:gn,worker:Bt,baseUrl:d,secret:f});if(!Ol.ok)return GI(l.id,Bt,Ol.error??"dispatch_start_readback_failed"),en(l.id,hn),Z(C,Ol.error??"dispatch_start_readback_failed",{readback:Ol.detail??null});Bt.leaseToken!==gn&&(Bt.leaseToken=gn,Bt.leaseOwner=y,X(l.id,Bt)),rd({taskId:q,leaseToken:gn}),iP(l.id,hn);let Mv={taskId:C.id,started:!0,worker:Bt.name,pid:Bt.pid,branch:Bt.branch,model:Bt.model,provider:nr.provider,routingRule:nr.rule,instructionPolicyFingerprint:K?.instructionPolicyFingerprint??null,instructionPolicyRuleCount:Array.isArray(K?.instructionPolicyEvidence?.ruleSlugs)?K.instructionPolicyEvidence.ruleSlugs.length:null,personaSlug:K?.personaSlug??se,personaOperatingRuleCount:K?.personaEvidence?.operatingRuleCount??null};return x.push(Mv),ge("worker_started",{lastOutcome:Mv}),K?.instructionPolicyFingerprint&&console.error(`[dispatch] task ${q}: instruction policy injected fingerprint=${K.instructionPolicyFingerprint}`),K?.personaSlug&&console.error(`[dispatch] task ${q}: persona context injected slug=${K.personaSlug}`),K?.contextEnvelopeReady&&console.error(`[dispatch] task ${q}: context envelope injected anchor=${K.contextEnvelopeEvidence?.anchorTaskId??q}`),K?.runtimeEnvelopeReady&&console.error(`[dispatch] task ${q}: runtime envelope injected id=${K.runtimeEnvelopeEvidence?.envelopeId??"unknown"}`),!0}catch(Xe){return en(l.id,hn),Z(C,Xe.message)}}let lf=new Set;for(let I of rP(l.id))lf.add(I);async function Pv(I){let C=I.task,K=String(C.id);if(lf.has(K))return Z(C,"dispatch_retry_loop_prevented: task already failed to start this tick");let q=v?CS({decision:I,leaseOwner:y,repoIdentity:k,requestNonce:b.get(I)??null}):null,se=q&&!q.allow?await Z(C,`desktop_execution_policy_denied:${q.code}: ${q.reason}`,{desktopPolicyDenied:q.code,...q.code==="operation_not_approved"?{nonFatal:!0}:{}}):Av(I)?await KU(I):await HU(I);return se||(lf.add(K),tP(K,l.id)),se}for(let I of E.started)await Pv(I);if(T.push(...E.skipped??[]),w)for(let I of T){let C=String(I.task.id);R.has(C)&&x.push({taskId:C,started:!1,error:`exact_target_not_started:${I.skipReason}`,skipReason:I.skipReason,detail:I.reason??null,requestedTargetTaskIds:[...R]})}for(;!w&&x.length<A;){if(Ae()){let K={started:!1,error:"dispatch_circuit_breaker: start readback failed; stopping top-up for this tick",nonFatal:!0};x.push(K),ge("circuit_breaker",{lastOutcome:K});break}let I=await Q(1);if(!I.dispatch.ok||!I.result){let K=Gx(I.dispatch.response),q=oe();te=K&&q>0;let se=hg(I.dispatch.response),wt={started:!1,error:se?"dispatch_next timed out during top-up":"dispatch_next request failed during top-up",httpStatus:I.dispatch.status,response:I.dispatch.response,...se?{timeout:!0}:{},...te?{nonFatal:!0,partialTopUp:!0}:{}};x.push(wt),ge("top_up_failed",{partialTopUpInterrupted:te,lastOutcome:wt});break}U+=Number(I.result.inspected)||0,T.push(...I.result.skipped??[]);let C=I.result.started??[];if(C.length===0)break;for(let K of C){if(x.length>=A)break;await Pv(K)}}let El=x.filter(I=>I.started).length,Lr=XI(E),_o=QI(E),Iv=El===0&&(Lr?.capacityIdle===!0||Number(E.resourceGate?.slotsAvailable)>0);if(Iv&&Lr?.summary){let I=Lr.skipReasonCounts?.retry_ceiling_exceeded??0,C=E.overAttemptIdleRecovery??Lr.overAttemptIdleRecovery,K=C?.attempted===!0?`; over_attempt_recovery minted=${C.minted??0} started=${C.started??0}`:I>0?"; over_attempt_recovery not attempted":"",q=_o?`; dispatch_skip_drain scanned=${_o.scanned??0} advanced=${_o.advanced??0}`:"",se=Lr.progressionReport?.summary?`; ${Lr.progressionReport.summary}`:"",wt=_o?.prLifecycleAttempt?.summary?`; ${_o.prLifecycleAttempt.summary}`:"";console.error(`[dispatch] ${Lr.summary}${I>0?`; retry_ceiling_exceeded=${I}`:""}${K}${q}${se}${wt}`)}let Ov={runId:l.id,agentOsId:u,dryRun:!1,leaseOwner:y,startedCount:El,capacityIdle:Iv,admissionExhaustion:Lr,dispatchSkipDrain:_o,outcomes:x,skipped:T.map(I=>({taskId:I.task.id,skipReason:I.skipReason})),inspected:U,pagesScanned:E.pagesScanned??null,candidatesExhausted:E.candidatesExhausted??null,diskGate:E.diskGate,resourceGate:E.resourceGate,...te?{partialTopUpInterrupted:!0}:{},dispatchCallbackTimeoutMs:G},Tv=I=>!I.started&&I.nonFatal!==!0,jU=x.some(Tv),Nv=te&&El>0?!0:!jU;if(Zi({runId:l.id,agentOsId:u,phase:"complete",partial:te,startedCount:El,ok:Nv}),t)return{ok:Nv,...Ov};console.log(JSON.stringify(Ov,null,2)),x.some(Tv)&&process.exit(1)}catch(i){if(t)return{ok:!1,error:i.message};console.error(`run dispatch failed: ${i.message}`),process.exit(1)}}var eh,Nu=p(()=>{"use strict";$();Lc();Fe();Vx();Jx();Zx();yi();tC();Fo();Y();Y();nC();lu();_E();EE();Zg();YP();Rs();XP();ZP();ot();Pc();Ps();M();uI();rh();ka();yr();pI();gI();ry();Fh();UI();KI();HI();VI();JI();Y();zI();fm();_s();zn();Cs();eh=3600*1e3});function Ns(e){if(!e||typeof e!="object")return 0;let t=e.startedCount;if(typeof t=="number")return t;let r=e.outcomes;return Array.isArray(r)?r.filter(n=>n.started).length:0}function d6(e){let{maxStarts:t,...r}=e;return r}async function ay(e,t){if(t<=0)return{ok:!0,skipped:!0,reason:"no slots",maxStarts:0,startedCount:0};let r=d6(e);if(r.targetTaskId||r.targetTaskIds){let u=await Ts({...r,execute:!0,pipeline:!0,maxStarts:String(t)});return{...typeof u=="object"&&u!==null?u:{},passes:{target:u},startedCount:Ns(u)}}let n=Math.min(t,u6),o=Math.max(0,t-n),s=await Ts({...r,execute:!0,pipeline:!0,lane:"review",maxStarts:String(n)}),i=Ns(s),a=o+(n-i);if(a<=0)return{...typeof s=="object"&&s!==null?s:{},passes:{review:s},startedCount:i};let l=await Ts({...r,execute:!0,pipeline:!0,maxStarts:String(a)}),c=Ns(l);return{passes:{review:s,work:l},startedCount:i+c,ok:!0}}var u6,ZI=p(()=>{"use strict";Nu();u6=1});function eO(e){if(!e||typeof e!="object")return[];let r=e.response?.dispatch?.exactTargetTaskIds;if(!Array.isArray(r))return[];let n=new Set,o=[];for(let s of r){if(typeof s!="string")continue;let i=s.trim();!i||n.has(i)||(n.add(i),o.push(i))}return o}var tO=p(()=>{"use strict"});function p6(e){let r=e.response?.dispatch;return r&&typeof r=="object"?r:null}function Ua(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function f6(e){let t=Number(process.env[e]);return!Number.isFinite(t)||t<=0?null:Math.floor(t)}function rO(e,t){let r=p6(t),n=Ua(r?.recommendedMaxStarts),o=Ua(r?.actionableReady),s=Ua(r?.queuedTasks),i=Ua(r?.boardAdvancedThisTick)??0,a=Ua(r?.leaseReapedThisTick)??0,l=i+a,c=o??s,u=e.slotsAvailable;c!==null?u=Math.min(u,c):n!==null&&(u=Math.min(u,n)),c===null&&n!==null&&(u=Math.max(u,Math.min(e.slotsAvailable,n)));let d=r?.underutilized===!0||(c??0)>0&&e.slotsAvailable>0&&e.maxConcurrentWorkers>0&&e.activeWorkers<e.maxConcurrentWorkers;if(e.slotsAvailable>0&&u===0&&(d||l>0)){let g=c??(l>0?l:1);u=Math.min(e.slotsAvailable,Math.max(1,g))}let f=f6("KYNVER_DAEMON_MAX_DISPATCH_STARTS");f!==null&&(u=Math.min(u,f));let m=s!==null&&o!==null?Math.max(0,s-o):null;return{maxStarts:Math.max(0,u),underutilized:d,advisedStarts:n,actionableReady:o,queuedTasks:s,nonDispatchableReady:m,boardAdvancedThisTick:i,leaseReapedThisTick:a}}var nO=p(()=>{"use strict"});import m6 from"node:path";function Qn(e){let t=Ct(e);if(t.length===0)return"failed";let r=!1,n=!1,o=!1,s=!1;for(let i of t){let a=F(m6.join(j(e.id),"workers",B(i),"worker.json"),void 0);if(!a)continue;let l=ie(a,{base:e.base,baseCommit:e.baseCommit});if(l.alive&&!l.finalResult){r=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Ff(l)&&(s=!0),l.finalResult&&l.attention.state==="done"&&(n=!0)}return r||o||s?null:n?"completed":"failed"}function Fa(){let e=[];for(let t of Se()){if(!g6.has(t.status))continue;let r=Qn(t);if(!r||r===t.status)continue;let n=t.status;t.status=r,Ve(t),e.push({runId:t.id,from:n,to:r})}return e}var g6,Or,rn=p(()=>{"use strict";Y();No();Ce();M();g6=new Set(["running","dispatching","pending","queued","needs_attention"]),Or=new Set(["completed","failed","cancelled","done"])});import Dt from"node:path";function fd(e){return e.includes(h6)}function ly(e,t){return Dt.join(rt(Ne(e)),B(t))}function nn(e,t,r){return Dt.join(ly(e,t),"workers",B(r))}function oO(e,t,r){let n=Ne(e);return Dt.join(n,"runs","runs",B(t),"workers",B(r))}function cy(){return["stdout.jsonl","stderr.log","heartbeat.jsonl","last-status.json","auto-complete.log","worker.json"]}function Zn(e){return{workerJsonPath:Dt.join(e,"worker.json"),stdoutPath:Dt.join(e,"stdout.jsonl"),stderrPath:Dt.join(e,"stderr.log"),heartbeatPath:Dt.join(e,"heartbeat.jsonl"),lastStatusPath:Dt.join(e,"last-status.json")}}function sO(e){let t=Zn(nn(e.harnessRoot,e.runId,e.workerName)).workerJsonPath;return e.statusPath&&!fd(e.statusPath)?e.statusPath:t}var h6,uy=p(()=>{"use strict";Et();M();h6=`${Dt.sep}runs${Dt.sep}runs${Dt.sep}`});import{existsSync as y6,readFileSync as k6,readdirSync as b6,statSync as v6,writeFileSync as R6}from"node:fs";import w6 from"node:path";function A6(e,t=[]){if(!e)return e;let r=e,n=[...new Set(t.map(o=>o?.trim()).filter(o=>!!o&&o.length>=_6))].sort((o,s)=>s.length-o.length);for(let o of n){r.includes(o)&&(r=r.split(o).join(it));let s=JSON.stringify(o).slice(1,-1);s!==o&&r.includes(s)&&(r=r.split(s).join(it))}for(let[o,s]of S6)r=r.replace(o,s);return r}function iO(e=process.env,t=[]){let r=[];for(let[n,o]of Object.entries(e))o&&x6.test(n)&&r.push(o);for(let n of t)try{let o=n();o&&r.push(o)}catch{}return r}function aO(e,t=0){if(t>3||!y6(e))return[];let r=[];for(let n of b6(e,{withFileTypes:!0})){let o=w6.join(e,n.name);n.isDirectory()?r.push(...aO(o,t+1)):n.isFile()&&C6.test(n.name)&&r.push(o)}return r}function lO(e,t=[]){let r={masked:[],clean:0,failed:[]},n;try{n=aO(e)}catch{return r}for(let o of n)try{if(v6(o).size>E6){r.failed.push(o);continue}let s=k6(o,"utf8"),i=A6(s,t);if(i===s){r.clean+=1;continue}R6(o,i,"utf8"),r.masked.push(o)}catch{r.failed.push(o)}return r}var it,dy,S6,_6,x6,C6,E6,cO=p(()=>{"use strict";it="<redacted>",dy=`[^\\s"'\\\\,}\\]]`,S6=[[new RegExp(`\\b(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|rediss):\\/\\/${dy}+`,"gi"),it],[new RegExp(`\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s/@:"']+:[^\\s/@"']+@${dy}+`,"gi"),it],[/\bkynver_u_[A-Za-z0-9_-]+/g,it],[/\bkyn_[A-Za-z0-9]{12,}/g,it],[/\bsk-ant-[A-Za-z0-9_-]+/g,it],[/\bsk-[A-Za-z0-9_-]{8,}/g,it],[/\bkr[a-z]1\.[A-Za-z0-9._~+/=-]{8,}/g,it],[/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}/g,it],[/\bgithub_pat_[A-Za-z0-9_]{16,}/g,it],[/\b(Bearer|Basic)\s+(?!<redacted>)[A-Za-z0-9._~+/=-]{8,}/gi,`$1 ${it}`],[new RegExp(`(\\b(?:[A-Z0-9_]*(?:API_KEY|APIKEY|TOKEN|SECRET|PASSWORD)|DATABASE_URL|KYNVER_DATABASE_URL)\\s*=\\s*)(?!<redacted>)${dy}+`,"g"),`$1${it}`]],_6=12,x6=/(?:API_KEY|APIKEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)$/i,C6=/(?:\.jsonl|\.log|\.txt|^stdout.*|^stderr.*)$/i,E6=256*1024*1024});import{existsSync as on,mkdirSync as P6,readdirSync as dO,renameSync as I6,statSync as py}from"node:fs";import ke from"node:path";function pO(e,t){let r=ke.resolve(e),n=ke.resolve(rt(t)),o=ke.relative(n,r);return o!==".."&&!o.startsWith("..")&&!ke.isAbsolute(o)}function fy(e){if(!on(e))return[];try{return dO(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&t.name!=="runs").map(t=>t.name)}catch{return[]}}function my(e){let t=ke.join(e,"workers");if(!on(t))return[];try{return dO(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}function fO(e){return ke.join(e,"archived-workers")}function T6(e,t){let r=ke.join(fO(e),B(t));return on(r)?`${r}-${Date.now()}`:r}function uO(e,t,r){if(!on(e))return!1;try{let n=t-py(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<r}catch{return!1}}function mO(e,t=Date.now(),r=Ka){if(!on(e))return!1;let n=Zn(e),o=F(n.workerJsonPath,void 0);if(o?.status==="running"&&re(o.pid))return!0;let s=Ie(n.heartbeatPath);if(s.lastHeartbeatAt){let i=t-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<r)return!0}return!!(uO(n.stdoutPath,t,r)||uO(n.heartbeatPath,t,r))}function N6(e,t,r){let n=typeof t.completionReportedAt=="string"?Date.parse(t.completionReportedAt):NaN;if(Number.isFinite(n))return r-n;let o=(()=>{let s=t.completionResponse;if(!s||typeof s!="object")return NaN;let i=s.task;if(!i||typeof i!="object")return NaN;let a=i.updatedAt;return typeof a=="string"?Date.parse(a):NaN})();if(Number.isFinite(o))return r-o;try{return r-py(ke.join(e,"worker.json")).mtimeMs}catch{return 0}}function D6(e,t,r,n){if(mO(e,r))return{eligible:!1,reason:"worker has active/recent retention signals"};let o=typeof t.status=="string"?t.status:"";if(typeof t.completionBlocker=="string"&&t.completionBlocker.trim().length>0)return{eligible:!1,reason:"worker has completion blocker"};let i=typeof t.completionReportedAt=="string"||t.completionOutcome==="acknowledged";if(o!=="done"&&!i)return{eligible:!1,reason:`worker status is ${o||"unknown"}`};let a=N6(e,t,r);return!Number.isFinite(a)||a<n?{eligible:!1,reason:"terminal worker is still within archive grace window"}:{eligible:!0,reason:"terminal worker metadata archived"}}function Ds(e,t=Date.now(),r=Ka){for(let n of my(e))if(mO(ke.join(e,"workers",n),t,r))return!0;return!1}function M6(){let t=Ji()?.repo??"",r="unknown";if(t)try{let n=ce(t,["rev-parse","origin/main"],{allowFailure:!0}).trim();n&&(r=n)}catch{}return{repo:t,base:"origin/main",baseCommit:r}}function L6(e,t){let r=ke.join(rt(e),B(t));if(!on(r))return null;let n=my(r);if(n.length===0)return null;let o;try{o=py(r).birthtime.toISOString()}catch{o=new Date().toISOString()}let s={};for(let a of n){let l=nn(e,t,a);s[a]={workerDir:l,statusPath:ke.join(l,"worker.json")}}let i=Ds(r);return{id:t,name:t,...M6(),status:i?"running":"needs_attention",createdAt:o,workers:s}}function gy(e){let t=Ne(e??dt()),r=rt(t),n=[];for(let o of fy(r)){let s=ke.join(r,o,"run.json");if(on(s)){n.push({runId:o,action:"skipped",reason:"run.json present"});continue}let i=L6(t,o);if(!i){n.push({runId:o,action:"skipped",reason:"no worker dirs on disk"});continue}Ve(i),n.push({runId:o,action:"repaired_run_json",reason:Ds(ke.join(r,o))?"synthesized run.json while worker artifacts still active":"synthesized run.json from orphan worker metadata dirs"})}return{runs:n}}function hy(e,t={}){let r=Ne(e??dt()),n=rt(r),o=t.now??Date.now(),s=t.archiveAgeMs??O6,i=[],a=null,l=()=>a??=(t.knownSecrets??(()=>iO(process.env,[_e,()=>Te()])))();gy(r);for(let c of fy(n)){let u=ke.join(n,c),d=ke.join(u,"run.json"),f=F(d,void 0);if(!f?.id)continue;let m=new Set([...Object.keys(f.workers||{}),...my(u)]),g=!1;for(let h of m){let y=ke.join(u,"workers",B(h)),v=ke.join(y,"worker.json"),k=F(v,void 0);if(!k){let S=ke.join(fO(u),B(h));if(on(S)&&(f.workers[B(h)]||f.workers[h])){delete f.workers[B(h)],delete f.workers[h],g=!0,i.push({runId:f.id,worker:h,action:"archived",reason:"removed stale live index entry for archived worker metadata",archivePath:S});continue}i.push({runId:f.id,worker:h,action:"skipped",reason:"worker.json missing"});continue}let b=D6(y,k,o,s);if(!b.eligible){i.push({runId:f.id,worker:h,action:"skipped",reason:b.reason});continue}let _=T6(u,h);P6(ke.dirname(_),{recursive:!0}),I6(y,_),lO(_,l()),delete f.workers[B(h)],delete f.workers[h],g=!0,i.push({runId:f.id,worker:h,action:"archived",reason:b.reason,archivePath:_})}g&&Ve(f)}return{workers:i}}function gO(e,t=Date.now()){let r=new Set,n=rt(e);for(let o of fy(n)){let s=ke.join(n,o);Ds(s,t)&&r.add(`${e}\0${o}`)}return r}var Ka,O6,Ms=p(()=>{"use strict";us();we();vn();Et();Y();uy();M();$();cO();Ka=900*1e3,O6=3600*1e3});import{existsSync as sn,lstatSync as B6,readdirSync as W6,readlinkSync as U6,renameSync as yy,unlinkSync as F6}from"node:fs";import Gt from"node:path";function K6(e,t){let r=ly(e,t),n;try{n=B6(r)}catch{return null}if(!n.isSymbolicLink())return null;let o=Gt.resolve(Gt.dirname(r),U6(r));if(Ds(o)||Ds(r))return null;let s=`${r}.materialize-${Date.now()}`;return yy(o,s),F6(r),yy(s,r),o}function $6(e){let t=[];for(let r of cy()){let n=Gt.join(e.fromDir,r),o=Gt.join(e.toDir,r);!sn(n)||sn(o)||(yy(n,o),t.push(r))}return t}function hO(e,t){let r=Zn(t),n=!1;return e.workerDir!==t&&(e.workerDir=t,n=!0),e.stdoutPath!==r.stdoutPath&&(e.stdoutPath=r.stdoutPath,n=!0),e.stderrPath!==r.stderrPath&&(e.stderrPath=r.stderrPath,n=!0),e.heartbeatPath!==r.heartbeatPath&&(e.heartbeatPath=r.heartbeatPath,n=!0),n}function H6(e){let t=typeof e.lastStatus?.status=="string"?e.lastStatus.status:void 0,r=e.lastStatus?.attention&&typeof e.lastStatus.attention=="object"?e.lastStatus.attention.state:void 0;return t==="done"||r==="done"||e.stdoutFinalResult||e.heartbeatFinalResult?"done":t==="blocked"?"blocked":t==="running"?"exited":t??"exited"}function j6(e){let t=Zn(e.canonicalDir),r=F(t.lastStatusPath,void 0),n=sn(t.stdoutPath),o=sn(t.heartbeatPath);if(!(n||o||r!=null))return null;let i=n?Rn(t.stdoutPath):{finalResult:null},a=o?Ie(t.heartbeatPath):Ie(""),l=ar(a),c=H6({lastStatus:r,stdoutFinalResult:i.finalResult,heartbeatFinalResult:l}),u={name:e.workerName,runId:e.run.id,status:c,branch:typeof r?.branch=="string"?r.branch:`agent/${e.run.id}/${e.workerName}`,worktreePath:typeof r?.worktreePath=="string"?r.worktreePath:Gt.join(he().worktreesDir,e.run.id,e.workerName),workerDir:e.canonicalDir,stdoutPath:t.stdoutPath,stderrPath:t.stderrPath,heartbeatPath:t.heartbeatPath,startedAt:typeof r?.startedAt=="string"?r.startedAt:e.run.createdAt,reconciledAt:new Date().toISOString(),reconcileReason:"synthesized worker.json from on-disk artifacts after metadata repair"};return typeof r?.taskId=="string"&&(u.taskId=r.taskId),typeof r?.agentOsId=="string"&&(u.agentOsId=r.agentOsId),typeof r?.planId=="string"&&(u.planId=r.planId),typeof r?.pid=="number"&&(u.pid=r.pid),(i.finalResult||l)&&(u.completionSnapshot={finalResult:i.finalResult??l??"completed",summary:a.lastHeartbeatSummary}),hO(u,e.canonicalDir),u}function V6(e,t){let r=!1,n={...e.workers||{}};for(let[o,s]of Object.entries(n)){let i=nn(t,e.id,o),a=Gt.join(i,"worker.json");(fd(s.workerDir)||fd(s.statusPath)||s.workerDir!==i||s.statusPath!==a)&&(n[o]={workerDir:i,statusPath:a},r=!0)}return r&&(e.workers=n,Ve(e)),r}function G6(e){let t=[],r=nn(e.harnessRoot,e.run.id,e.workerName),n=oO(e.harnessRoot,e.run.id,e.workerName),o=Zn(r),s=$6({fromDir:n,toDir:r});s.length>0&&t.push({runId:e.run.id,worker:e.workerName,action:"relocated_artifacts",reason:`moved ${s.join(", ")} from nested runs/runs layout`});let i=sO({harnessRoot:e.harnessRoot,runId:e.run.id,workerName:e.workerName,statusPath:e.statusPath}),a=F(i,void 0);if(!a&&sn(o.workerJsonPath)&&(a=F(o.workerJsonPath,void 0)),!a){let l=j6({run:e.run,workerName:e.workerName,canonicalDir:r,harnessRoot:e.harnessRoot});if(l)return X(e.run.id,l),t.push({runId:e.run.id,worker:e.workerName,action:"synthesized_worker_json",reason:l.reconcileReason??"synthesized from artifacts"}),t;let c=sn(r),u=cy().some(d=>sn(Gt.join(r,d)));if(c&&!u){let d={name:e.workerName,runId:e.run.id,status:"exited",branch:`agent/${e.run.id}/${e.workerName}`,worktreePath:Gt.join(he().worktreesDir,e.run.id,e.workerName),workerDir:r,stdoutPath:o.stdoutPath,stderrPath:o.stderrPath,heartbeatPath:o.heartbeatPath,startedAt:e.run.createdAt,reconciledAt:new Date().toISOString(),reconcileReason:"empty worker dir \u2014 marked abandoned during metadata reconcile"};return X(e.run.id,d),t.push({runId:e.run.id,worker:e.workerName,action:"marked_abandoned",reason:d.reconcileReason??"empty worker dir"}),t}return t.push({runId:e.run.id,worker:e.workerName,action:"skipped",reason:"worker.json missing and no recoverable artifacts"}),t}return hO(a,r)?(a.reconciledAt=new Date().toISOString(),a.reconcileReason=a.reconcileReason??"repaired nested runs/runs path fields",X(e.run.id,a),t.push({runId:e.run.id,worker:e.workerName,action:"repaired_worker_paths",reason:a.reconcileReason})):t.push({runId:e.run.id,worker:e.workerName,action:"skipped",reason:"worker metadata already canonical"}),t}function J6(e,t){let r=Gt.join(j(e.id),"workers");if(!sn(r))return[];let n=new Set(Object.keys(e.workers||{})),o=[];for(let s of W6(r,{withFileTypes:!0}))s.isDirectory()&&(n.has(s.name)||o.push(s.name));return o}function yO(){let{harnessRoot:e}=he(),t=gy(e),r=[];for(let n of Se()){let o=K6(e,n.id);o&&r.push({runId:n.id,worker:"*",action:"materialized_run_symlink",reason:`replaced symlink with real run dir (was ${o})`}),V6(n,e)&&r.push({runId:n.id,worker:"*",action:"repaired_run_index",reason:"repaired nested runs/runs workerDir/statusPath entries in run.json"});let s=new Set(Object.keys(n.workers||{}));for(let i of J6(n,e))s.add(i),n.workers={...n.workers||{},[i]:{workerDir:nn(e,n.id,i),statusPath:Gt.join(nn(e,n.id,i),"worker.json")}},Ve(n),r.push({runId:n.id,worker:i,action:"repaired_run_index",reason:"indexed orphan worker dir into run.json"});for(let i of s){let a=n.workers?.[i];r.push(...G6({run:n,workerName:i,harnessRoot:e,statusPath:a?.statusPath}))}}return{workers:r,runMetadataRetention:t}}var kO=p(()=>{"use strict";vn();Ri();uy();Ms();Y();M()});import{execFileSync as bO}from"node:child_process";import vO from"node:path";function ky(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:null}function q6(e){let t=ky(e)?.match(/\/pull\/(\d+)$/);if(!t)return null;let r=Number.parseInt(t[1],10);return Number.isFinite(r)?r:null}function Y6(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function z6(e){let t=new Set;for(let r of e.matchAll(/github\.com\/[^/\s)>"']+\/[^/\s)>"']+\/(?:pull|pulls)\/(\d+)/gi)){let n=Number.parseInt(r[1],10);Number.isFinite(n)&&t.add(n)}for(let r of e.matchAll(/\bPR\s*#?\s*(\d{2,})\b/gi)){let n=Number.parseInt(r[1],10);Number.isFinite(n)&&t.add(n)}for(let r of e.matchAll(/\bpr[-_]?(\d{2,})\b/gi)){let n=Number.parseInt(r[1],10);Number.isFinite(n)&&t.add(n)}return[...t]}function X6(e){let t=null;if(typeof e=="string"?t=Bo(e):e&&typeof e=="object"&&!Array.isArray(e)&&(t=e),!t)return[];let r=t.targetPrReconciliation??t.target_pr_reconciliation;if(!Array.isArray(r))return[];let n=[];for(let o of r){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=ky(String(s.prUrl??s.pr_url??"")),a=String(s.outcome??"").trim();!i||a!=="merged"||n.push({prUrl:i,mergeCommit:typeof s.mergeCommit=="string"?s.mergeCommit:typeof s.merge_commit=="string"?s.merge_commit:null,reason:typeof s.reason=="string"?s.reason:null})}return n}function Q6(e){try{let n=bO("git",["config","--get","remote.origin.url"],{windowsHide:!0,cwd:e.repoDir,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim().match(/github\.com[:/]([^/]+\/[^/.]+)(?:\.git)?$/i)?.[1];if(!n)return null;let o=bO("gh",["pr","view",String(e.prNumber),"--repo",n,"--json","state,mergedAt,mergeCommit,url"],{windowsHide:!0,cwd:e.repoDir,encoding:"utf8",stdio:["ignore","pipe","ignore"]}),s=JSON.parse(o);return{prUrl:ky(s.url??`https://github.com/${n}/pull/${e.prNumber}`)??`https://github.com/${n}/pull/${e.prNumber}`,state:s.state??"",mergedAt:s.mergedAt??null,mergeCommit:s.mergeCommit?.oid??null}}catch{return null}}function Z6(e){let t=Ie(e.heartbeatPath);return e.completionSnapshot?.finalResult??ar(t)}function e4(e){let t=new Map,r=j(e.id);for(let n of Ct(e)){let o=F(vO.join(r,"workers",B(n),"worker.json"),void 0);if(o)for(let s of X6(Z6(o))){let i=q6(s.prUrl);i!=null&&!t.has(i)&&t.set(i,s)}}return t}function t4(e,t){let r=Ie(e.heartbeatPath),n=[e.name,e.repairTargetPrUrl,e.taskPrUrl,e.branch,r.lastHeartbeatSummary,Y6(t)].filter(Boolean).join(`
|
|
178
|
+
`);return z6(n)}function r4(e){return e.localOnly===!0&&!e.taskId&&!e.agentOsId}function by(e={}){let t=e.lookupPr??Q6,r=[],n=new Map;for(let o of Se()){let s=e4(o),i=j(o.id);for(let a of Ct(o)){let l=vO.join(i,"workers",B(a),"worker.json"),c=F(l,void 0);if(!c||!r4(c))continue;let u=ie(c,{base:o.base,baseCommit:o.baseCommit});if(u.attention.state!=="needs_attention")continue;let d=null;for(let m of t4(c,u.finalResult)){if(d=s.get(m)??null,!d){let g=o.repo||c.worktreePath,h=`${g}#${m}`,y=n.has(h)?n.get(h)??null:t({repoDir:g,prNumber:m});n.has(h)||n.set(h,y),y&&(y.state==="MERGED"||y.mergedAt)&&(d={prUrl:y.prUrl,mergeCommit:y.mergeCommit??null,reason:"GitHub reports PR merged"})}if(d)break}if(!d){r.push({runId:o.id,worker:a,action:"skipped",reason:"no merged PR evidence"});continue}let f=new Date().toISOString();c.status="done",c.completionSnapshot={prUrl:d.prUrl,summary:`Local-only worker superseded by merged PR ${d.prUrl}`,finalResult:{summary:`Local-only repair/salvage worker superseded by merged PR ${d.prUrl}`,targetPrReconciliation:[{prUrl:d.prUrl,outcome:"merged",mergeCommit:d.mergeCommit??null,reason:d.reason??"PR already merged; local-only worker no longer requires attention"}]}},c.completionAckSource="local-pr-merged-reconcile",c.reconciledAt=f,c.reconcileReason="local-only needs_attention superseded by merged PR",X(o.id,c),r.push({runId:o.id,worker:a,action:"marked_done",reason:c.reconcileReason,prUrl:d.prUrl,mergeCommit:d.mergeCommit??null})}}return{workers:r}}var RO=p(()=>{"use strict";vn();tc();Ce();Y();No();M()});import n4 from"node:path";function s4(){return process.env.KYNVER_NO_STALE_CLEANUP==="1"}function wO(e,t){let r=Qu({worker:e,status:t}),n=r?Zu(e,r):!1,o=t.attention.state==="blocked"?"blocked":t.attention.state==="done"||t.status==="done"||r?"done":"exited",s=r&&n?`captured exited-worker handoff (${r.source})`:r?"synced finished worker record after terminal stdout/heartbeat":t.attention.reason;return{nextStatus:o,reason:s,handoffCaptured:n}}function i4(e,t){t.stopClass&&(e.stopClass=t.stopClass),t.stopReason&&(e.stopReason=t.stopReason),t.exit&&(e.exitCode=t.exit.exitCode,e.exitSignal=t.exit.signal,e.oomEvidence=t.exit.oomEvidence??null);let r=t.error?.trim();r&&(e.exitStderrTail=r.slice(-1e3))}function vy(){let e=yO();if(s4()){let s=by(),i=hy();return{workers:[],finalizedRuns:Fa(),metadataReconcile:e,localPrAttentionReconcile:s,terminalWorkerArchive:i}}let t=[],r=Date.now();for(let s of Se())for(let i of Ct(s)){let a=n4.join(j(s.id),"workers",B(i),"worker.json"),l=F(a,void 0);if(!l||l.status!=="running"){t.push({runId:s.id,worker:i,action:"skipped",reason:l?`worker status is ${l.status}`:"worker.json missing"});continue}let c=ie(l,{base:s.base,baseCommit:s.baseCommit});if(c.finalResult){if(l.status==="running"){let u=wO(l,c);l.status=u.nextStatus,l.reconciledAt=new Date().toISOString(),l.reconcileReason=u.reason,l.stopClass="finished",X(s.id,l),t.push({runId:s.id,worker:i,action:"marked_exited",reason:l.reconcileReason})}else t.push({runId:s.id,worker:i,action:"skipped",reason:"final result present"});continue}if(!c.alive){let u=wO(l,c);l.status=u.nextStatus,l.reconciledAt=new Date().toISOString(),l.reconcileReason=u.reason,i4(l,c),X(s.id,l),t.push({runId:s.id,worker:i,action:"marked_exited",reason:c.attention.reason});continue}if(c.attention.state==="stale"&&l.pid&&re(l.pid)){let u=c.lastHeartbeatAt?Date.parse(c.lastHeartbeatAt):NaN,d=c.lastActivityAt?Date.parse(c.lastActivityAt):NaN,f=!Number.isFinite(u)||r-u>o4,m=Number.isFinite(d)&&r-d>Uf;if(f&&m){fe(l.pid,"SIGTERM"),l.status="exited",l.reconciledAt=new Date().toISOString(),l.reconcileReason=`reconciled stale worker: ${c.attention.reason}`,l.stopClass="stuck",l.stopReason=`stuck (no progress) \u2014 ${c.attention.reason}`,X(s.id,l),t.push({runId:s.id,worker:i,action:"killed_stale",reason:c.attention.reason});continue}}t.push({runId:s.id,worker:i,action:"skipped",reason:c.attention.reason})}let n=by(),o=hy();return{workers:t,finalizedRuns:Fa(),metadataReconcile:e,localPrAttentionReconcile:n,terminalWorkerArchive:o}}var o4,Ry=p(()=>{"use strict";rn();Y();No();Ch();Ce();M();kO();RO();Ms();o4=900*1e3});import{readdirSync as a4,readFileSync as l4}from"node:fs";function f4(e){if(process.platform!=="linux"||!e.trim())return null;let t=[];try{t=a4("/proc")}catch{return null}for(let r of t)if(/^\d+$/.test(r)&&Number(r)!==process.pid)try{if(l4(`/proc/${r}/cmdline`,"utf8").replace(/\0/g," ").includes(e))return Number(r)}catch{}return null}async function SO(e){let t=Pr(),r={mode:t,scanned:0,outcomes:[]};if(t!=="enforce")return r;let n=ue();if(!n)return r;let o=e.nowMs??Date.now(),s=e.strandedAfterMs??u4,i=e.findOrphanPid??f4,a=[],l;try{l=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-d4).toISOString(),limit:p4})}catch{return eo.recoveryStoreFailures+=1,r}for(let c of l){let u=c.idempotencyKey.slice(c4.length),d=u.split(":")[0]??"",f=u.slice(d.length+1);if(!(!d||!f))try{let m=Date.parse(c.recordedAt);if(!Number.isFinite(m)||o-m<s||n.getOperationReceipt(`dispatch:spawned:${u}`)||n.getOperationReceipt(`dispatch:released:${u}`))continue;let g=xa(f);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${d}:`,limit:10}).some(S=>{if(g===null)return!0;let R=xa(S.idempotencyKey.slice(`dispatch:completion-acked:${d}:`.length));return R===null||R>=g}))continue;let v={};try{v=c.resultJson?JSON.parse(c.resultJson):{}}catch{v={}}let k=v.runId??null,b=v.workerName??null;if(k&&b&&e.hasLiveWorker({runId:k,workerName:b})){rd({taskId:d,leaseToken:f}),a.push({taskId:d,leaseToken:f,runId:k,workerName:b,action:"finalized_late"});continue}if(k&&b){let S=e.worktreePathFor({runId:k,workerName:b}),R=S?i(S):null;if(R!==null){eo.recoveryDeferredOrphans+=1,a.push({taskId:d,leaseToken:f,runId:k,workerName:b,action:"deferred_orphan",detail:`live pid ${R} references ${S}`});continue}}if(!k){a.push({taskId:d,leaseToken:f,runId:k,workerName:b,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let _=await e.releaseClaim({taskId:d,leaseToken:f,runId:k});_.released?(Ss({taskId:d,leaseToken:f},"restart_recovery"),b&&(Ea(k,b),en(k,b)),eo.recoveredStrandedClaims+=1,a.push({taskId:d,leaseToken:f,runId:k,workerName:b,action:"released"})):_.transportError?a.push({taskId:d,leaseToken:f,runId:k,workerName:b,action:"deferred_transport",detail:_.detail}):(Ss({taskId:d,leaseToken:f},"restart_recovery_refused"),a.push({taskId:d,leaseToken:f,runId:k,workerName:b,action:"release_refused",detail:_.detail}))}catch{eo.recoveryStoreFailures+=1}}return{mode:t,scanned:l.length,outcomes:a}}function _O(){return{"dispatchReceipts.recoveredStrandedClaims":eo.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":eo.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":eo.recoveryStoreFailures}}var c4,u4,d4,p4,eo,wy=p(()=>{"use strict";Jr();_s();zn();Cs();c4="dispatch:claim:",u4=900*1e3,d4=10080*60*1e3,p4=200,eo={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0}});import m4 from"node:path";async function CO(e){if(xO||Pr()!=="enforce")return null;xO=!0;try{let t=De().runnerId,r=await SO({hasLiveWorker:e.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>m4.join(he().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await Wa({baseUrl:e.baseUrl,secret:e.secret,agentOsId:e.agentOsId,taskId:n,leaseOwner:ya(s,t),leaseToken:o});return{released:i.released,transportError:i.transportError,detail:i.httpOk?void 0:JSON.stringify(i.releaseResponse).slice(0,200)}}});return r.outcomes.length>0&&console.error(`[daemon] D1b claim recovery: ${r.outcomes.map(n=>`${n.taskId}:${n.action}`).join(", ")}`),r}catch{return null}}var xO,EO=p(()=>{"use strict";Y();ka();yr();ry();wy();_s();xO=!1});import g4 from"node:os";function AO(e,t={}){let r=P(),n=(t.boxKind??xt(r)).trim().toLowerCase()||"forge",o=t.hostLabel??g4.hostname();return{boxId:jo({boxKind:n,hostLabel:o,explicitBoxId:t.boxId,config:r,env:process.env}),boxKind:n,displayName:t.displayName??null,hostLabel:o,observedAt:t.observedAt??new Date().toISOString(),totalMemBytes:e.totalMemBytes,freeMemBytes:e.freeMemBytes,activeWorkers:e.activeWorkers,maxConcurrentWorkers:e.maxConcurrentWorkers,autoCap:e.autoCap,slotsAvailable:e.slotsAvailable,harnessRunId:t.harnessRunId??null,queuedTasks:t.queuedTasks??null,reason:e.reason,...t.prEvidence?.length?{prEvidence:t.prEvidence}:{},host:kx()}}var PO=p(()=>{"use strict";$();Le();Vo();Qc()});import h4 from"node:path";async function md(e){let t=e.pipeline===!0||e.pipeline==="true";try{let r=ne(String(_t(String(e.run||""),"--run"))),n=String(_t(String(e.agentOsId||""),"--agent-os-id")),o=pe(e.baseUrl?String(e.baseUrl):void 0),s=await me(e.secret?String(e.secret):void 0,n,{baseUrl:o}),i=De({runId:r.id}).runnerId,a=await IP({run:r.id,agentOsId:n,...e},"run_sweep"),l=[];for(let f of Object.keys(r.workers||{})){let m=F(h4.join(j(r.id),"workers",B(f),"worker.json"),void 0);if(!m||!m.dispatched||!m.taskId)continue;let g=ie(m);if(g.alive||g.finalResult||m.completionReportedAt)continue;try{let k=await As({run:r.id,name:f,agentOsId:n,...e.baseUrl?{baseUrl:String(e.baseUrl)}:{},...e.secret?{secret:String(e.secret)}:{}});if(k.ok&&!k.skipped){l.push({worker:f,taskId:m.taskId,pid:m.pid,released:!1,deathReported:!0,stopClass:g.stopClass??null});continue}}catch{}let h=Iu({runId:r.id,workerLeaseOwner:m.leaseOwner??null,runnerId:i}),y=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/${encodeURIComponent(String(m.taskId))}/release`,v;try{v=await de(y,s,{agentOsId:n,leaseOwner:h,...m.leaseToken?.trim()?{leaseToken:m.leaseToken.trim()}:{}},{agentOsId:n,baseUrl:o})}catch(k){v={ok:!1,error:k.message}}l.push({worker:f,taskId:m.taskId,pid:m.pid,released:v.ok===!0||v.response?.ok===!0,response:v.response??v})}let c=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/reap`,u;try{u=await de(c,s,{agentOsId:n,...Number(e.graceMs)>=0&&e.graceMs!==void 0&&e.graceMs!==!0?{graceMs:Math.floor(Number(e.graceMs))}:{}},{agentOsId:n,baseUrl:o})}catch(f){u={ok:!1,error:f.message}}let d={runId:r.id,agentOsId:n,snapshotPublished:a,releasedLocalOrphans:l,reap:u.response??u};if(t)return{ok:!0,...d};console.log(JSON.stringify(d,null,2))}catch(r){if(t)return{ok:!1,error:r.message};console.error(`run sweep failed: ${r.message}`),process.exit(1)}}var Sy=p(()=>{"use strict";$();Fe();Y();Ce();M();ka();yr();Ps()});async function IO(e){let t=pe(e.baseUrl),r=await me(e.secret,e.agentOsId,{baseUrl:t}),n=`${t}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/tasks/${encodeURIComponent(e.taskId)}/plan-progress-sync`,o=await de(n,r,{phase:e.phase,taskId:e.taskId,blocker:e.blocker,artifact:e.artifact},{agentOsId:e.agentOsId,baseUrl:t});return{ok:o.ok,status:o.status,response:o.response}}var OO=p(()=>{"use strict";$();Fe()});import y4 from"node:path";async function TO(e,t){let r=ne(e),n=String(t.agentOsId||"");if(!n)return[];let o=[];for(let s of Object.keys(r.workers||{})){let i=F(y4.join(j(r.id),"workers",B(s),"worker.json"),void 0);if(!i?.dispatched||!i.taskId)continue;let a=ie(i);if(!a.heartbeatBlocker)continue;if(i.lastSyncedHeartbeatBlocker===a.heartbeatBlocker){o.push({worker:s,phase:"heartbeat_blocker",ok:!0,skipped:!0});continue}let l=await IO({agentOsId:n,taskId:i.taskId,phase:"heartbeat_blocker",blocker:a.heartbeatBlocker,baseUrl:t.baseUrl?String(t.baseUrl):void 0,secret:t.secret?String(t.secret):void 0});l.ok&&(i.lastSyncedHeartbeatBlocker=a.heartbeatBlocker,X(r.id,i)),o.push({worker:s,phase:"heartbeat_blocker",ok:l.ok})}return o}var NO=p(()=>{"use strict";Ce();Y();M();OO()});function DO(e){let t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(t==="node_modules"||t.startsWith("node_modules/"))return!0;for(let r of _y)if(t===r||t.startsWith(`${r}/`))return!0;return!1}var _y,xy=p(()=>{"use strict";_y=[".next",".turbo","dist","build",".cache","node_modules/.cache"]});function yt(e){return e.filter(t=>{let r=t.trim(),n=r.startsWith("??")?r.slice(2).trim():r.length>3?r.slice(3).trim():r;return!DO(n)})}var to=p(()=>{"use strict";xy()});function ro(e){if(typeof e=="string")return e.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/i)?.[0]??null;if(e&&typeof e=="object"){let t=e;for(let r of["prUrl","pr_url","pullRequestUrl"]){let n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}return null}function $a(e){let t=e.gitAncestry?.relation;return t==="merged"||t==="synced"?yt(e.changedFiles).length>0:!!(ro(e.finalResult)||t==="ahead"||t==="diverged"||e.changedFiles.length>0&&e.finalResult)}var Ha=p(()=>{"use strict";to()});function ja(e){return e.status||(e.status=ie(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function Cy(e,t){if(e.status)return yt(e.status.changedFiles).length>0;let r=t?t.porcelain(e.worktreePath):fi(e.worktreePath);return yt(r).length>0}function k4(e){let t=e.worker.completionSnapshot?.finalResult;return t??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Ey(e,t){if(e.status)return e.status;let r=e.worker,n=typeof r.completionReportedAt=="string"&&r.completionReportedAt.trim().length>0,o=!!(r.status&&["done","exited","blocked","failed","abandoned"].includes(r.status))||n,s=k4(e);if(o&&!re(r.pid)){let i=t?.gitStatusCache?t.gitStatusCache.porcelain(e.worktreePath):fi(e.worktreePath),a=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main",c=t?.gitRevCache?.countAheadOfMain(e.worktreePath,a)===0?{checked:!0,base:a,relation:"synced"}:Wl(e.worktreePath,{base:e.run.base,baseCommit:e.run.baseCommit}),u={runId:e.runId,worker:e.workerName,pid:r.pid,alive:!1,status:r.status??(n?"done":"exited"),attention:{state:n?"done":"stale"},branch:r.branch,worktreePath:e.worktreePath,ownedPaths:r.ownedPaths,stdoutBytes:0,stderrBytes:0,heartbeatBytes:0,firstEventAt:null,lastEventAt:null,lastActivityAt:r.completionReportedAt??null,currentTool:null,heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,heartbeatBlocker:null,changedFiles:i,gitAncestry:c,finalResult:s,completionBlocker:typeof r.completionBlocker=="string"&&r.completionBlocker.trim()||null,prUrl:r.repairTargetPrUrl??r.taskPrUrl??ro(s)};return e.status=u,u}return ja(e)}var gd=p(()=>{"use strict";we();Ce();to();Ha();M()});function b4(e,t=Date.now(),r=Ka){let n=Ie(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=t-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<r}function Ls(e,t=Date.now(),r=Ka){return re(e.pid)?!0:b4(e,t,r)}var hd=p(()=>{"use strict";vn();Ms();M()});function v4(e,t){return t?t.runTerminalCache.derive(e.run):Qn(e.run)}function Tr(e,t=Date.now()){return Ls(e.worker,t)}function Ay(e,t){return Or.has(e.run.status)?!1:v4(e,t)!==null}function MO(e,t,r=Date.now()){if(Tr(e,r))return!0;if(Or.has(e.run.status)||Ay(e,t))return!1;let n=ja(e);return Be(n)?!1:!!Tr(e,r)}var Py=p(()=>{"use strict";rn();Ce();gd();hd()});function LO(e,t){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(Tr(e))return!0;let n=t??ja(e);return!!(!Be(n)||$a(n)||yt(n.changedFiles).length>0||Lo({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:ro(n.finalResult)}).blocked)}var BO=p(()=>{"use strict";ec();gd();to();Py();Ce();Ha()});import{existsSync as UO,mkdirSync as R4,writeFileSync as WO}from"node:fs";import yd from"node:path";function FO(e,t,r){return yd.join(e,"salvage",B(t),B(r))}function KO(e){return UO(yd.join(FO(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function $O(e){let t=FO(e.harnessRoot,e.indexed.runId,e.indexed.workerName);R4(t,{recursive:!0});let r=yd.join(t,"salvage.patch"),n=!1;if(UO(e.indexed.worktreePath)){let s=ee(e.indexed.worktreePath,["diff","HEAD"]),i=ee(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(l=>l.trim()).join(`
|
|
179
|
+
`);a.trim()&&(WO(r,a.endsWith(`
|
|
116
180
|
`)?a:`${a}
|
|
117
|
-
`),n=!0)}let o={capturedAt:new Date(e.now??Date.now()).toISOString(),skipReason:e.skipReason,runId:e.indexed.runId,workerName:e.indexed.workerName,worktreePath:e.indexed.worktreePath,taskId:e.indexed.worker.taskId,agentOsId:e.indexed.worker.agentOsId,branch:e.indexed.worker.branch,completionBlocker:e.indexed.worker.completionBlocker,finalResult:e.status.finalResult,changedFiles:e.status.changedFiles,gitAncestry:e.status.gitAncestry,prUrl:e.status.prUrl??null,...n?{patchPath:r}:{}};return
|
|
118
|
-
`),o}var KI=p(()=>{"use strict";ve();D()});import od from"node:path";function Oz(e){e.writeSalvageEvidence&&Iz.has(e.skipReason)&&(Pr(e.indexed,e.now)||FI({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})||$I({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}))}function Tz(e){let{indexed:t,worktreesAgeMs:r,terminalWorktreesAgeMs:n}=e;return t&&(Ar.has(t.run.status)||e.liveness&&ty(t,e.liveness)||e.liveness&&Me(ey(t,e.liveness))&&!Pr(t))?n:r}function Nz(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:Tz(e)}function Dz(e,t){if(e.harnessRoot?.trim())return od.resolve(e.harnessRoot);let r=t.worker.workerDir;if(!r)return null;let n=`${od.sep}runs${od.sep}`,o=r.indexOf(n);return o<0?null:r.slice(0,o+n.length-1)}function HI(e){let{indexed:t,includeOrphans:r,worktreesAgeMs:n,ageMs:o,orphanSafety:s,worktreeRemovalGuard:i}=e,a=e.now??Date.now();if(!t)return r?s??null:"orphan_without_flag";let l=Nz(e);if(n<=0&&!r&&l<=0)return"worktrees_disabled";if(l>0&&o<l)return"below_age_threshold";if(Pr(t,a))return"active_worker";let c=ey(t,e.liveness),u=Dz(e,t),d=g=>{if(u)try{Oz({indexed:t,harnessRoot:u,skipReason:g,status:c,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})}catch{}return g};if(MI(t,c)){let g=d("completion_blocked");if(g)return g}if(Zh(t,e.liveness?.gitStatusCache)){let g=d("dirty_worktree");if(g)return g}let m=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(m!=null&&m>0){let g=d("pr_or_unmerged_commits");if(g)return g}if(DI(t,e.liveness,a)||!Me(c))return"run_still_active";if(Na(c)){let g=d("pr_or_unmerged_commits");if(g)return g}if(ft(c.changedFiles).length>0){let g=d("dirty_worktree");if(g)return g}if(Po({finalResult:c.finalResult,changedFiles:c.changedFiles,gitAncestry:c.gitAncestry,prUrl:Yn(c.finalResult)}).blocked){let g=d("landing_blocked");if(g)return g}if(i&&e.worktreePath){let g=i({worktreePath:e.worktreePath,indexed:!!t,runId:t?.runId,worker:t?.workerName});if(g)return g.detail?{reason:g.reason,detail:g.detail}:g.reason}return null}function ny(e){let{indexed:t,nodeModulesAgeMs:r,ageMs:n,worktreePath:o,activeWorktreePaths:s,workerFilesystemLive:i,diskPressure:a}=e;return!a&&n<r?"below_age_threshold":i||s.has(od.resolve(o))||t&&Pr(t)?"active_worker":t&&Zh(t,e.gitStatusCache)?"dirty_worktree":null}function jI(e){return ny(e)}var Iz,VI=p(()=>{"use strict";$l();td();_e();Qr();ry();LI();KI();qn();Da();qn();Da();Iz=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"])});var sd=p(()=>{"use strict"});function JI(e,t){let r=[],n=new Set,o=(s,i,a)=>{let l=`${s}\0${i}`;n.has(l)||r.length>=24||(n.add(l),r.push({path:s,reason:i,...a?{detail:a}:{}}))};for(let s of t)GI.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||GI.has(s.skipReason)&&o(s.path,s.skipReason);return r}var GI,qI=p(()=>{"use strict";sd();GI=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"])});import YI from"node:path";function Lz(e,t){return Es(e,t)}function zI(e,t=Date.now()){let r=new Set,n=new Set;for(let o of e){for(let s of mc(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let l=$(YI.join(xi(o,s.id),"workers",B(a),"worker.json"),void 0);if(!l?.worktreePath)continue;let c=YI.resolve(l.worktreePath);Lz(l,t)&&(i=!0,r.add(c))}i&&n.add(`${o}\0${s.id}`)}for(let s of mI(o))n.add(s)}return{activeWorktreePaths:r,liveRunKeys:n}}function XI(e,t,r,n){return r?n.has(`${t}\0${r}`):!1}var oy=p(()=>{"use strict";z();St();Cs();rd();D()});import{existsSync as QI,readdirSync as ZI,statSync as Bz}from"node:fs";import eO from"node:path";function Wz(e,t){try{let r=Bz(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function Uz(e,t){let r=eO.join(e,"runs",t,"run.json");return QI(r)?$(r,null):null}function tO(e){try{return ZI(e).length===0}catch{return!1}}function rO(e){let{harnessRoot:t,runId:r,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(XI(n,t,r,i.liveRunKeys)||!tO(n))return"run_still_active";let a=Uz(t,r);return a&&!Ar.has(a.status)&&!Vn(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function nO(e){if(!QI(e.worktreesDir))return[];let t=[],r;try{r=ZI(e.worktreesDir,{withFileTypes:!0})}catch{return[]}for(let n of r){if(!n.isDirectory())continue;let o=n.name;if(e.runIdFilter&&o!==e.runIdFilter)continue;let s=eO.join(e.worktreesDir,o);tO(s)&&t.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:Wz(s,e.now)})}return t}var oO=p(()=>{"use strict";oy();Qr();D()});import{execFileSync as Fz}from"node:child_process";import{existsSync as sO,readdirSync as $z,statSync as Kz}from"node:fs";import Hz from"node:path";function Vz(e,t=jz){if(!sO(e))return 0;try{let n=Fz("du",["-sb",e],{encoding:"utf8",timeout:t,stdio:["ignore","pipe","ignore"]}).trim().split(/\s+/)[0],o=Number(n);return Number.isFinite(o)&&o>=0?o:null}catch{return null}}function Ir(e,t=5e4){if(!sO(e))return 0;let r=Vz(e);if(r!==null)return r;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=$z(i)}catch{continue}for(let l of a){if(o++>t)return null;let c=Hz.join(i,l),u;try{u=Kz(c)}catch{continue}u.isDirectory()?s.push(c):n+=u.size}}return n}var jz,La=p(()=>{"use strict";jz=2500});import{lstatSync as Gz,readdirSync as Jz}from"node:fs";function iO(e){try{let t=Gz(e),r=typeof process.getuid=="function"?process.getuid():null,n=typeof process.getgid=="function"?process.getgid():null,o=r!==null&&(t.uid!==r||n!==null&&t.gid!==n);return{uid:t.uid,gid:t.gid,foreign:o}}catch{return null}}function aO(e,t=32){let r=iO(e);if(!r)return!1;if(r.foreign)return!0;try{let n=Jz(e),o=0;for(let s of n){if(o>=t)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=iO(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}var lO=p(()=>{"use strict"});import mt from"node:path";function cO(e,t,r,n){let o=mt.resolve(e),s=`${mt.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=mt.relative(r,i);if(a.startsWith("..")||mt.isAbsolute(a))return"path_outside_harness";let l=a.split(mt.sep);return l.length<3||l[l.length-1]!==n||!o.startsWith(mt.resolve(t))?"path_outside_harness":null}function id(e,t,r){return cO(e,t,r,"node_modules")}function ad(e,t,r){return cO(e,t,r,".next")}function ld(e,t,r){let n=mt.resolve(e),o=mt.relative(r,n);return o.startsWith("..")||mt.isAbsolute(o)||o.split(mt.sep).length<3||!n.startsWith(mt.resolve(t))?"path_outside_harness":null}function uO(e,t,r){let n=mt.resolve(e);return id(n,t,r)===null||ad(n,t,r)===null||ld(n,t,r)===null}var sy=p(()=>{"use strict"});import{spawnSync as qz}from"node:child_process";import dO from"node:path";function fO(){let e=(process.env.KYNVER_CLEANUP_PRIVILEGED??"auto").trim().toLowerCase();return e==="0"||e==="false"||e==="off"||e==="no"?"off":e==="1"||e==="true"||e==="force"||e==="yes"?"force":"auto"}function pO(e){let t=qz("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:t.status===0,stderr:`${t.stderr??""}${t.stdout??""}`.trim()}}function mO(e,t,r){if(!uO(e,t,r))return{ok:!1,error:"path is not an allowed harness generated cache"};let n=typeof process.getuid=="function"?process.getuid():null,o=typeof process.getgid=="function"?process.getgid():null;if(n===null||o===null)return{ok:!1,error:"privileged reclaim requires POSIX uid/gid"};let s=pO(["chown","-R",`${n}:${o}`,dO.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=pO(["rm","-rf",dO.resolve(e)]);return i.ok?{ok:!0,method:"sudo_rm"}:{ok:!1,error:s.stderr||i.stderr||"sudo -n failed (password required or not permitted)"}}var iy,gO=p(()=>{"use strict";sy();iy="Root-owned harness caches require operator reclaim: configure passwordless sudo for chown/rm under ~/.kynver/harness/worktrees, or remove them as the harness owner with sudo available. More help: https://www.kynver.com/help."});import{existsSync as Yz,rmSync as zz}from"node:fs";function Xz(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function hO(e,t,r={}){if(!Yz(e.path))return{executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!t)return{executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.harnessRoot,o=n?jo(n):null,i=e.bytes??Ir(e.path)??void 0,a=r.removePath??zz,l=r.hasForeignOwnedEntry??aO;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(c){if(!Xz(c)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let u=l(e.path),d=fO();if(!(d==="force"||d==="auto"&&u))return u?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; ${iy}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let f=mO(e.path,n,o);if(f.ok&&f.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(f.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(g){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${g.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; privileged reclaim failed: ${f.error}; ${iy}`}}}var yO=p(()=>{"use strict";La();St();lO();gO()});import{existsSync as ay,rmSync as kO}from"node:fs";function ly(e){let t=e.harnessRoot;return!t||!dI(e.path,t)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function cy(e,t){let r=ly(e);if(r)return r;let n=hO(e,t);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function bO(e,t){return cy(e,t)}function vO(e,t){return cy(e,t)}function RO(e,t){return cy(e,t)}function wO(e,t){let r=ly(e);if(r)return r;if(!ay(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!t)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};try{let n=e.bytes??Ir(e.path);return kO(e.path,{recursive:!0,force:!0}),{...e,bytes:n,executed:!0,skipped:!1}}catch(n){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:n.message}}}function SO(e,t){let r=ly(e);if(r)return r;if(!ay(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!t)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.repo;try{let o=e.bytes??Ir(e.path);return n&&le(n,["worktree","remove","--force",e.path],{allowFailure:!0}),ay(e.path)&&kO(e.path,{recursive:!0,force:!0}),{...e,bytes:o,executed:!0,skipped:!1}}catch(o){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:o.message}}}var _O=p(()=>{"use strict";ve();La();yO();Cs();sy()});import{existsSync as cd,readdirSync as ud,statSync as Qz}from"node:fs";import Ht from"node:path";function uy(e,t){try{let r=Qz(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function CO(e,t){let r=Ht.relative(t,e);return r===""||!r.startsWith("..")&&!Ht.isAbsolute(r)}function xO(e,t,r,n){let o=[];for(let s of Xh){if(s===".next")continue;let i=Ht.join(e,s);if(!cd(i))continue;let a=Ht.resolve(i);r.has(a)||CO(a,t.harnessRoot)&&(r.add(a),o.push({kind:"remove_build_cache",path:a,bytes:null,runId:n.runId,worker:n.worker,repo:n.repo,ageMs:uy(a,t.now)}))}return o}function EO(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||t.push(...xO(n.worktreePath,e,r,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!cd(e.worktreesDir))return t;for(let n of ud(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Ht.join(e.worktreesDir,n.name);for(let s of ud(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=Ht.join(o,s.name);t.push(...xO(i,e,r,{runId:n.name,worker:s.name}))}}return t}function AO(e){let t=e.worktreesAgeMs>0||e.includeOrphans,r=e.includeOrphans;if(!t&&!r)return[];let n=[],o=new Set;if(t)for(let i of e.index.values()){if(e.runIdFilter&&i.runId!==e.runIdFilter)continue;let a=i.worktreePath;cd(a)&&(o.has(a)||(o.add(a),n.push({kind:"remove_worktree",path:a,bytes:null,runId:i.runId,worker:i.workerName,repo:i.run.repo,ageMs:uy(a,e.now)})))}if(!r||!cd(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(Ht.resolve(i.worktreePath));for(let i of ud(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=Ht.join(e.worktreesDir,i.name),l;try{l=ud(a,{withFileTypes:!0})}catch{continue}for(let c of l){if(!c.isDirectory())continue;let u=Ht.resolve(Ht.join(a,c.name));o.has(u)||s.has(u)||CO(u,e.harnessRoot)&&(o.add(u),n.push({kind:"remove_worktree",path:u,bytes:null,runId:i.name,worker:c.name,ageMs:uy(u,e.now)}))}}return n}var PO=p(()=>{"use strict";Qh()});import{existsSync as TO,readdirSync as IO,statSync as Zz}from"node:fs";import As from"node:path";function t6(e,t){try{let r=Zz(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function r6(e,t){let r=As.relative(t,e);return r===""||!r.startsWith("..")&&!As.isAbsolute(r)}function n6(e,t,r,n,o,s){if(!TO(n))return;let i=As.resolve(n);t.has(i)||r6(i,r.harnessRoot)&&(t.add(i),e.push({kind:o,path:i,bytes:null,harnessRoot:r.harnessRoot,runId:s.runId,worker:s.worker,repo:s.repo,ageMs:t6(i,r.now)}))}function OO(e,t,r,n,o){for(let s of e6)n6(e,t,r,As.join(n,s.dirName),s.kind,o)}function NO(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||OO(t,r,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!TO(e.worktreesDir))return t;for(let n of IO(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=As.join(e.worktreesDir,n.name),s;try{s=IO(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=As.join(o,i.name);OO(t,r,e,a,{runId:n.name,worker:i.name})}}return t}var e6,DO=p(()=>{"use strict";e6=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}]});import{existsSync as MO,statSync as o6}from"node:fs";import jt from"node:path";function s6(e,t){try{let r=o6(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function i6(e){let t=[],r=null;for(let n of e.split(`
|
|
119
|
-
`)){if(!n.trim())continue;let[o,...s]=n.split(" "),i=s.join(" ");if(o==="worktree"){r&&t.push(r),r={path:i};continue}r&&(o==="branch"&&(r.branch=i),o==="HEAD"&&(r.head=i),o==="bare"&&(r.bare=!0))}return r&&t.push(r),t}function
|
|
120
|
-
`).map(c=>c.trim()).filter(c=>c.length>0);if(
|
|
121
|
-
`).map(r=>r.trim()).filter(Boolean)}var E6,dT=p(()=>{"use strict";E6=5e3});var fd,pT=p(()=>{"use strict";dT();fd=class{cache=new Map;porcelain(t){let r=t,n=this.cache.get(r);if(n!==void 0)return n;let o=uT(r)??[];return this.cache.set(r,o),o}}});var md,fT=p(()=>{"use strict";Qr();md=class{cache=new Map;derive(t){let r=this.cache.get(t.id);if(r!==void 0)return r;let n=Vn(t);return this.cache.set(t.id,n),n}}});function P6(e){let t={};for(let r of e)t[r.kind]=(t[r.kind]??0)+1;return t}function mT(e,t={}){let r=t.maxSampleActions??12,n=t.maxSampleSkips??8;return{harnessRoot:e.harnessRoot,scanRoots:e.scanRoots,dryRun:e.dryRun,execute:e.execute,scannedAt:e.scannedAt,finalizedRuns:e.finalizedRuns.length,actionCount:e.actions.length,actionKinds:P6(e.actions),totals:e.totals,...e.storage?{storage:e.storage}:{},...e.preservedLivePaths?.length?{preservedLivePaths:e.preservedLivePaths}:{},...e.removedRunDirectories!=null?{removedRunDirectories:e.removedRunDirectories}:{},sampleActions:e.actions.slice(0,r).map(o=>({kind:o.kind,path:o.path,...o.skipReason?{skipReason:o.skipReason}:{},...o.bytes!=null?{bytes:o.bytes}:{},...o.runId?{runId:o.runId}:{},...o.worker?{worker:o.worker}:{}})),sampleSkips:e.skips.slice(0,n)}}var gT=p(()=>{"use strict"});import ht from"node:path";function I6(e={}){let t=e.harnessRoot?Ie(e.harnessRoot):at(),r=ZO({harnessRoot:t}),n=e.now??Date.now();return{harnessRoot:t,scanRoots:r,now:n}}function O6(e){return typeof e=="string"?{reason:e}:e}function Ps(e,t,r,n){e.push({path:t,reason:r,...n?{detail:n}:{}})}function gd(e,t,r){return!t||e.bytes!=null?e:{...e,bytes:Ir(e.path,r)}}function hT(e,t){let r={};for(let n of t)r[n.reason]=(r[n.reason]??0)+1;for(let n of e)n.skipReason&&(r[n.skipReason]=(r[n.skipReason]??0)+1);return r}function T6(e,t){return e.kind==="remove_next_cache"?vO(e,t):bO(e,t)}function N6(e,t,r){return e.kind==="remove_next_cache"?ad(e.path,t,r):id(e.path,t,r)}function D6(e){let t=new Map;for(let r of e)for(let[n,o]of UO(r))t.set(n,o);return t}function yT(e,t){return e.runId&&e.worker?ht.join(t,e.runId,e.worker):ht.resolve(e.path,"..")}function kT(e){return e.indexed?!1:my({harnessRoot:e.harnessRoot,runId:e.candidate.runId,workerName:e.candidate.worker,now:e.now})}function M6(e={}){let t=py(e),r=tT();t=rT(t,r);let n=I6(e);gt("scan",`${n.scanRoots.length} harness root(s)`);let o=zI(n.scanRoots,n.now),s=t.finalizeStaleRuns?Oa().map(P=>({runId:P.runId,from:P.from,to:P.to})):[];s.length>0&>("finalize",`${s.length} stale run(s) marked terminal`),gt("index","building worktree index");let i=D6(n.scanRoots);gt("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new md,gitStatusCache:new fd,gitRevCache:new pd},l=[],c=[],u=new Set,d=t.maxActionsPerSweep,m=()=>c.length>=d;for(let P of n.scanRoots){if(m())break;gt("root",P);let N=ht.join(P,"worktrees"),L=WO(i,P),M={harnessRoot:P,worktreesDir:N,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter,index:L,now:n.now},V=t.scanDependencyCaches?NO(M):[];gt("dependency",t.scanDependencyCaches?`${V.length} cache candidate(s) at ${P}`:"skipped (worktree-only sweep)");let J=0;for(let I of V){if(m())break;J+=1,J%50===0&>("dependency",`${J}/${V.length} evaluated`);let K=ht.resolve(I.path);if(u.has(K))continue;u.add(K);let F={...I,path:K},Z=N6(F,P,N);if(Z){Ps(l,F.path,Z),c.push({...F,executed:!1,skipped:!0,skipReason:Z});continue}let ue=yT(F,N),Te=L.get(ht.resolve(ue))??null,er=kT({candidate:F,indexed:Te,harnessRoot:P,now:n.now}),te=ny({indexed:Te,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:F.ageMs,worktreePath:ue,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:er,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(te){Ps(l,F.path,te),c.push({...F,executed:!1,skipped:!0,skipReason:te});continue}c.push(T6(gd(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(t.scanDependencyCaches)for(let I of EO(M)){if(m())break;let K=ht.resolve(I.path);if(u.has(K))continue;u.add(K);let F={...I,path:K},Z=ld(F.path,P,N);if(Z){Ps(l,F.path,Z),c.push({...F,executed:!1,skipped:!0,skipReason:Z});continue}let ue=yT(F,N),Te=L.get(ht.resolve(ue))??null,er=kT({candidate:F,indexed:Te,harnessRoot:P,now:n.now}),te=jI({indexed:Te,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:F.ageMs,worktreePath:ue,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:er,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(te){Ps(l,F.path,te),c.push({...F,executed:!1,skipped:!0,skipReason:te});continue}c.push(RO(gd(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}let T=[...AO(M),...LO(M)];gt("worktrees",`${T.length} candidate(s) at ${P}`);let x=new Set,j=0;for(let I of T){if(m())break;j+=1,j%50===0&>("worktrees",`${j}/${T.length} evaluated`);let K=ht.resolve(I.path);if(x.has(K))continue;x.add(K);let F={...I,path:K},Z=L.get(ht.resolve(F.path))??null,ue=Z?null:JO({worktreePath:F.path,harnessRoot:P,runId:F.runId,workerName:F.worker,now:n.now}),Te=HI({indexed:Z,worktreePath:ht.resolve(F.path),includeOrphans:t.includeOrphans,worktreesAgeMs:t.worktreesAgeMs,terminalWorktreesAgeMs:t.terminalWorktreesAgeMs,ageMs:F.ageMs,orphanSafety:ue,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:P,writeSalvageEvidence:t.execute});if(Te){let{reason:er,detail:te}=O6(Te);Ps(l,F.path,er,te),c.push({...F,executed:!1,skipped:!0,skipReason:er});continue}c.push(SO(gd(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(!m()&&t.runDirectoriesAgeMs>=0)for(let I of nO({harnessRoot:P,worktreesDir:N,runDirectoriesAgeMs:t.runDirectoriesAgeMs,runIdFilter:t.runIdFilter,activeGuards:o,now:n.now})){if(m())break;let K=ht.resolve(I.path);if(u.has(K))continue;u.add(K);let F={...I,path:K},Z=F.runId??ht.basename(K),ue=rO({harnessRoot:P,runId:Z,runPath:K,ageMs:F.ageMs,runDirectoriesAgeMs:t.runDirectoriesAgeMs,activeGuards:o});if(ue){Ps(l,F.path,ue),c.push({...F,executed:!1,skipped:!0,skipReason:ue});continue}c.push(wO(gd(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}}let f=0,g=0,h=0,y=0,v=0,k=0;for(let P of c)P.bytes&&(f+=P.bytes),!P.skipped&&!P.executed&&P.bytes&&(h+=P.bytes),P.executed?(v+=1,y+=P.bytes??0,P.kind==="remove_run_directory"&&(g+=1)):P.skipped&&(k+=1,P.skipReason==="dry_run"&&P.bytes&&(h+=P.bytes));let b=t.accountBytes?zO({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:t.storagePerRunEntryCap}):void 0,_=xo(),S=t.execute&&iT(_),R=S?sT({execute:!0}):null,w=_?{observed:!0,execute:S,dumpCount:_.dumpCount,totalBytes:_.totalBytes,removedCount:R?.removed.length??0,removedBytes:R?.removedBytes??0,executables:_.executables,path:_.path,reason:_.reason}:void 0;R&&R.removed.length>0&&(y+=R.removedBytes,v+=R.removed.length,gt("wsl-crashes",`removed ${R.removed.length} dump(s), ${R.removedBytes} bytes`)),gt("complete",`${c.length} action(s), ${k} skipped, ${v} removed`);let W=JI(c,l),O=mT({harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!t.execute,execute:t.execute,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,diskPressure:t.diskPressure,diskGate:t.diskGate?{ok:t.diskGate.ok,path:t.diskGate.path,freeBytes:t.diskGate.freeBytes,usedPercent:t.diskGate.usedPercent,reason:t.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:c,skips:l,totals:{candidateBytes:f,reclaimableBytes:h,removedBytes:y,removedPaths:v,skippedPaths:k,skipReasons:hT(c,l)},...b?{storage:b}:{},...W.length>0?{preservedLivePaths:W}:{},...g>0?{removedRunDirectories:g}:{},...w?{wslCrashDumps:w}:{}});return{harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!t.execute,execute:t.execute,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,diskPressure:t.diskPressure,diskGate:t.diskGate?{ok:t.diskGate.ok,path:t.diskGate.path,freeBytes:t.diskGate.freeBytes,usedPercent:t.diskGate.usedPercent,reason:t.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:c,skips:l,totals:{candidateBytes:f,reclaimableBytes:h,removedBytes:y,removedPaths:v,skippedPaths:k,skipReasons:hT(c,l)},...b?{storage:b}:{},...W.length>0?{preservedLivePaths:W}:{},...g>0?{removedRunDirectories:g}:{},...w?{wslCrashDumps:w}:{},compactSummary:O}}function bT(e){let t=jO(e);return M6({execute:t.execute,finalizeStaleRuns:t.finalizeStaleRuns,accountBytes:t.accountBytes,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter})}function vT(){return process.env.KYNVER_PIPELINE_CLEANUP!=="0"}var RT=p(()=>{"use strict";St();VI();qI();oO();_O();PO();DO();BO();FO();Qr();La();VO();qO();XO();eT();oy();nT();aT();Nl();lT();cT();pT();fT();gT()});function wT(e){let t=e.trim().split("-")[0]?.split("+")[0];if(!t)return null;let r=t.split(".");if(r.length<1||r.length>3)return null;let n=r.map(o=>Number.parseInt(o,10));if(n.some(o=>!Number.isFinite(o)||o<0))return null;for(;n.length<3;)n.push(0);return[n[0],n[1],n[2]]}function ST(e,t){let r=wT(e),n=wT(t);if(!r||!n)return 0;for(let o=0;o<3;o+=1){if(r[o]>n[o])return 1;if(r[o]<n[o])return-1}return 0}var L6,ECe,_T=p(()=>{"use strict";oi();L6={"@kynver-app/runtime":"0.1.83","@kynver-app/openclaw-agent-os":"0.1.43","@kynver-app/mcp-agent-os":"0.3.34"},ECe=Object.keys(L6)});import{readFile as B6}from"node:fs/promises";import{homedir as W6}from"node:os";import Qn from"node:path";function Is(e){let t=e?.trim();return t||null}function F6(e){return[...new Set(e.filter(t=>!!t))]}function $6(){let e=W6(),t=Is(process.env.KYNVER_OPENCLAW_NPM_ROOT)??Is(process.env.OPENCLAW_NPM_ROOT)??Qn.join(e,".openclaw","npm"),r=Is(process.env.KYNVER_NPM_GLOBAL_ROOT)??Is(process.env.KYNVER_NPM_GLOBAL_MODULES_ROOT)??(Is(process.env.NPM_CONFIG_PREFIX)?Qn.join(Is(process.env.NPM_CONFIG_PREFIX),"lib","node_modules"):Qn.join(e,".npm-global","lib","node_modules"));return F6([Qn.join(t,"lib","node_modules"),Qn.join(t,"node_modules"),r.endsWith("node_modules")?r:Qn.join(r,"lib","node_modules")])}async function K6(e){try{let t=JSON.parse(await B6(e,"utf8"));return typeof t.version=="string"&&t.version.trim()?t.version.trim():null}catch{return null}}function H6(e){let t=$6(),r=new Set,n=[];for(let o of t){let s=Qn.join(o,e,"package.json");r.has(s)||(r.add(s),n.push(s))}return n}async function xT(e=new Date().toISOString()){let t={};for(let r of U6){let n=null;for(let o of H6(r)){let s=await K6(o);s&&(!n||ST(s,n.version)>0)&&(n={version:s,path:o})}n&&(t[r]={version:n.version,observedAt:e,path:n.path})}return t}var U6,CT=p(()=>{"use strict";_T();U6=["@kynver-app/runtime","@kynver-app/openclaw-agent-os","@kynver-app/mcp-agent-os"]});import{spawnSync as j6}from"node:child_process";var V6,G6,ET,AT=p(()=>{"use strict";V6=1e4,G6=4*1024*1024,ET=(e,t,r)=>{try{let n=j6(e,t,{windowsHide:!0,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r?.timeoutMs??V6,maxBuffer:G6});return{ok:n.status===0,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:""}}catch(n){return{ok:!1,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}});function hd(e,t,r){return`${e} ${t} ${r}`}function hy(e){let t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return null;let r=e.slice(0,t),n=e.slice(t+1);return!/^[^/\s]+\/[^/\s]+$/.test(r)||!/^[0-9a-f]{7,40}$/i.test(n)?null:{repo:r,sha:n}}function PT(e){let t=e.trim().match(/[/:]([^/]+\/[^/]+)\/(?:pull|pulls|merge_requests|pull-requests)\/(\d+)/i);if(!t)return null;let r=Number(t[2]);return!Number.isFinite(r)||r<=0?null:{repo:t[1],number:r}}var yd=p(()=>{"use strict"});function by(){return Date.now()<yy}function Q6(e){let t=`${e.stdout}
|
|
122
|
-
${e.stderr}`.toLowerCase();return t.includes("api rate limit exceeded")||t.includes("rate limit exceeded")||t.includes("secondary rate limit")}function IT(e){Q6(e)&&(yy=Math.max(yy,Date.now()+X6))}function ky(e,t){if(by())return null;let r=e("gh",["api",...t]);if(!r.ok||!r.stdout.trim())return IT(r),null;try{return JSON.parse(r.stdout)}catch{return null}}function Z6(e,t,r,n){if(by())return null;let o=e("gh",["pr","view",String(r),"--repo",t,"--json",n.join(",")]);if(!o.ok||!o.stdout.trim())return IT(o),null;try{return JSON.parse(o.stdout)}catch{return null}}function vy(e){return by()?!1:process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()?!0:e("gh",["auth","token"]).ok}function Os(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function e4(e){return Array.isArray(e)?e.map(t=>Os(t)).filter(t=>t!==null).slice(0,q6).map(t=>({context:t.context??null,state:t.state??null,target_url:t.target_url??null,description:t.description??null})):[]}function t4(e,t,r){let n=ky(e,[`repos/${t}/commits/${r}/status`]);return n?{state:n.state??null,statuses:e4(n.statuses)}:null}var J6,q6,Y6,z6,X6,yy,OT,TT,NT,DT=p(()=>{"use strict";yd();J6=8e3,q6=30,Y6=100,z6=400,X6=3600*1e3,yy=0;OT={provider:"github",kind:"pr_snapshot",version:"2",isAvailable:vy,collect(e,t){let r=PT(e);if(!r)return null;let n=Z6(t,r.repo,r.number,["url","title","body","author","state","isDraft","mergedAt","mergeCommit","mergeable","headRefName","headRefOid","headRepositoryOwner","statusCheckRollup","files"]);if(!n)return null;let o=Os(n.author),s=Os(n.mergeCommit),i=Os(n.headRepositoryOwner),a=typeof n.body=="string"?n.body.slice(0,J6):null,l=Array.isArray(n.statusCheckRollup)?n.statusCheckRollup.map(u=>Os(u)).filter(u=>u!==null).slice(0,Y6).map(u=>({name:u.name??u.context??null,status:u.status??u.state??null,conclusion:u.conclusion??null,workflowName:u.workflowName??null,detailsUrl:u.detailsUrl??null})):[],c=Array.isArray(n.files)?n.files.map(u=>Os(u)).map(u=>typeof u?.path=="string"?u.path.trim():"").filter(Boolean).slice(0,z6):[];return{pull:{html_url:n.url??null,title:n.title??null,body:a,user:{login:o?.login??null},state:typeof n.state=="string"?n.state.toLowerCase():null,draft:n.isDraft??null,merged:!!n.mergedAt,merged_at:n.mergedAt??null,merge_commit_sha:s?.oid??null,mergeable:null,mergeable_state:n.mergeable??null,head:{sha:n.headRefOid??null,ref:n.headRefName??null,repo:{owner:{login:i?.login??null}}}},checkRuns:l,combinedStatus:{state:null,statuses:[]},changedFiles:c}}},TT={provider:"github",kind:"commit_status",version:"1",isAvailable:vy,collect(e,t){let r=hy(e);return r?t4(t,r.repo,r.sha):null}},NT={provider:"github",kind:"branch_reachability",version:"1",isAvailable:vy,collect(e,t){let r=hy(e);if(!r)return null;let n=ky(t,[`repos/${r.repo}`]),o=typeof n?.default_branch=="string"&&n.default_branch.trim()?n.default_branch.trim():null;if(!o)return null;let s=ky(t,[`repos/${r.repo}/compare/${encodeURIComponent(o)}...${r.sha}`]);if(!s)return null;let i=typeof s.status=="string"?s.status:null;return{defaultBranch:o,compareStatus:i,reachable:i==="identical"||i==="behind"}}}});function Ry(e){wy.some(t=>t.provider===e.provider&&t.kind===e.kind)||wy.push(e)}function MT(e,t){return wy.find(r=>r.provider===e&&r.kind===t)??null}function LT(){Ry(OT),Ry(TT),Ry(NT)}var wy,BT=p(()=>{"use strict";DT();wy=[]});function WT(e,t={}){LT();let r=t.run??ET,n=t.now??(()=>new Date),o=t.maxSubjects??r4,s=Date.now()+(t.deadlineMs??n4),i=new Set,a=e.filter(f=>{let g=hd(f.provider,f.kind,f.subject);return i.has(g)?!1:(i.add(g),!0)}),l=a.length>0?Math.floor(n().getTime()/6e4)%a.length:0,u=a.map((f,g)=>a[(l+g)%a.length]).slice(0,o),d={attempted:0,collected:0,cached:0,items:[],skipped:[]},m=new Map;for(let f of u){let g=hd(f.provider,f.kind,f.subject),h=n(),y=t.cache?.get(g,h)??null;if(y){d.cached+=1,d.collected+=1,d.items.push(y);continue}if(Date.now()>s){d.skipped.push({...f,reason:"budget_exhausted"});continue}let v=MT(f.provider,f.kind);if(!v){d.skipped.push({...f,reason:"no_recipe"});continue}let k=`${v.provider} ${v.kind}`,b=m.get(k);if(b===void 0&&(b=v.isAvailable(r),m.set(k,b)),!b){d.skipped.push({...f,reason:"provider_unavailable"});continue}if(t.cache?.reserve?.(f,g,n())===!1){d.skipped.push({...f,reason:"budget_exhausted"});continue}d.attempted+=1;let _=v.collect(f.subject,r);if(_==null){d.skipped.push({...f,reason:"collect_failed"});continue}d.collected+=1;let S={provider:f.provider,kind:f.kind,subject:f.subject,payload:_,observedAt:n().toISOString(),collectorVersion:v.version};d.items.push(S),t.cache?.set(g,S,n())}return d}var r4,n4,UT=p(()=>{"use strict";AT();BT();yd();r4=1,n4=25e3});import FT from"node:path";function $T(e){return FT.join(G(e),o4)}function a4(e){return FT.join(G(e),s4)}function KT(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object"||Array.isArray(r))continue;let n=r,o=typeof n.provider=="string"?n.provider.trim():"",s=typeof n.kind=="string"?n.kind.trim():"",i=typeof n.subject=="string"?n.subject.trim():"";!o||!s||!i||t.push({provider:o,kind:s,subject:i})}return t}function HT(e){let t=$($T(e),null);return KT(t?.wanted)}function jT(e,t){ye($T(e),{savedAt:new Date().toISOString(),wanted:t})}function VT(e,t={}){let r=t.ttlMs??i4,n=a4(e),s={...$(n,null)?.items??{}},i=!1;return{get(l,c){let u=s[l];if(!u)return null;let d=Date.parse(u.observedAt);return!Number.isFinite(d)||c.getTime()-d>r?(delete s[l],i=!0,null):u},set(l,c){s[l]=c,i=!0},flush(){i&&(ye(n,{savedAt:new Date().toISOString(),items:s}),i=!1)}}}function GT(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.providerEvidenceWanted;return Array.isArray(t)?KT(t):null}var o4,s4,i4,Sy=p(()=>{"use strict";z();D();yd();o4="provider-evidence-wanted.json",s4="provider-evidence-cache.json",i4=600*1e3});import l4 from"node:path";function _y(e,t){let r=process.env[e];if(!r)return t;let n=Number.parseInt(r,10);return Number.isFinite(n)&&n>=0?n:t}function f4(){return l4.join(me().harnessRoot,c4)}function m4(e){let t=e.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),r=e==="github"?d4:p4;return _y(`KYNVER_PROVIDER_EVIDENCE_${t}_PER_MINUTE`,_y("KYNVER_PROVIDER_EVIDENCE_LIVE_COLLECTS_PER_MINUTE",r))}function JT(){return _y("KYNVER_PROVIDER_EVIDENCE_SHARED_CACHE_TTL_MS",u4)}function g4(e){return Math.floor(e.getTime()/6e4)*6e4}function h4(e){return`${e.provider}:${e.kind}`}function qT(e,t={}){let r=VT(e,{ttlMs:t.ttlMs??JT()}),n=t.file??f4(),o=$(n,null),s={...o?.items??{}},i={...o?.budget??{}},a=t.ttlMs??JT(),l=!1;return{get(u,d){let m=r.get(u,d);if(m)return m;let f=s[u];if(!f)return null;let g=Date.parse(f.observedAt);return!Number.isFinite(g)||d.getTime()-g>a?(delete s[u],l=!0,null):(r.set(u,f,d),f)},set(u,d,m){r.set(u,d,m),s[u]=d,l=!0},reserve(u,d,m){let f=m4(u.provider);if(f===0)return!0;let g=h4(u),h=g4(m),y=i[g];return!y||y.windowStartMs!==h?(i[g]={windowStartMs:h,used:1},l=!0,!0):y.used>=f?!1:(y.used+=1,l=!0,!0)},flush(){r.flush(),l&&(ye(n,{savedAt:new Date().toISOString(),items:s,budget:i}),l=!1)}}}var c4,u4,d4,p4,YT=p(()=>{"use strict";z();D();Sy();c4="provider-evidence-shared-cache.json",u4=6e4,d4=1,p4=1});function zT(e){let t=$S(),r=hr(e?.env??process.env),n=(e?.now??(()=>new Date))().getTime(),o={};if(r.flags.dispatchReceipts!=="off"){Object.assign(o,aA());let s=iA({nowMs:n,hasLiveWorker:e?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,r.flags.dispatchReceipts==="enforce"&&Object.assign(o,SI())}return r.flags.planOutbox!=="off"&&Object.assign(o,aP()),r.flags.admission!=="off"&&(Object.assign(o,dA()),r.flags.admission==="enforce"&&Object.assign(o,gA())),(r.flags.keeper!=="off"||r.flags.meshLease!=="off"||r.flags.quota!=="off")&&Object.assign(o,QS()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:t.state,schemaVersion:t.schemaVersion,recovered:t.recovered,unavailableClass:t.reason?t.reason.split(":")[0]??null:null,flags:r.flags,flagSources:r.sources,flagWarningCount:r.warnings.length,divergenceCounters:o}}var XT=p(()=>{"use strict";Hr();ts();hs();Yh();Ea();Hn();ks();Bi()});import{createHash as QT}from"node:crypto";import{access as y4,mkdir as pEe,readFile as ZT,rename as fEe,writeFile as mEe}from"node:fs/promises";import{constants as k4}from"node:fs";import{homedir as xy}from"node:os";import qe from"node:path";function R4(){return process.env.KYNVER_MCP_UPDATE_INVENTORY_FILE?.trim()||qe.join(xy(),".kynver","mcp-installations.json")}function w4(e){return e==="openclaw"?process.env.KYNVER_OPENCLAW_NPM_ROOT?.trim()||qe.join(xy(),".openclaw","npm"):process.env.KYNVER_NPM_GLOBAL_ROOT?.trim()||process.env.NPM_CONFIG_PREFIX?.trim()||qe.join(xy(),".npm-global")}function S4(e){let t=qe.resolve(e);if(qe.basename(t)!=="node_modules")return t;let r=qe.dirname(t);return qe.basename(r)==="lib"?qe.dirname(r):r}function _4(e,t){return[qe.join(e,"lib","node_modules",t,"package.json"),qe.join(e,"node_modules",t,"package.json")]}async function x4(e){try{return await y4(e,k4.R_OK),!0}catch{return!1}}async function C4(e=R4()){let t;try{t=JSON.parse(await ZT(e,"utf8"))}catch{return[]}if(t.version!==1||!Array.isArray(t.installations)||t.installations.length>100)throw new Error("invalid MCP installation inventory");return t.installations.map(r=>{if(!r||!v4.test(r.inventoryKey)||!b4.test(r.packageName)||!["kynver","openclaw"].includes(r.prefix))throw new Error("invalid adopted MCP installation");if(r.packageName.includes("..")||r.packageName.includes("%"))throw new Error("invalid adopted MCP package identity");if(r.connectionId&&r.connectionId.length>128)throw new Error("invalid connection identity");if(r.binName&&!/^[A-Za-z0-9._-]{1,80}$/.test(r.binName))throw new Error("invalid MCP bin name");let n=r.envAllowlist??[];if(!Array.isArray(n)||n.length>32||n.some(o=>!/^[A-Z][A-Z0-9_]{1,80}$/.test(o)))throw new Error("invalid MCP environment allow-list");return{...r,envAllowlist:[...new Set(n)],lifecycle:r.lifecycle??"runtime_stdio"}})}function E4(e,t,r){if(typeof e.bin=="string")return qe.join(r,e.bin);if(!e.bin||typeof e.bin!="object"||Array.isArray(e.bin))return null;let n=e.bin,o=t.binName??(Object.keys(n).length===1?Object.keys(n)[0]:void 0),s=o?n[o]:null;return typeof s=="string"&&!qe.isAbsolute(s)&&!s.split(/[\\/]/).includes("..")?qe.join(r,s):null}function A4(e){return QT("sha256").update(JSON.stringify({inventoryKey:e.inventoryKey,connectionId:e.connectionId,packageName:e.packageName,managerKind:e.managerKind,sourceKind:e.sourceKind,installedVersion:e.installedVersion,nodeVersion:e.nodeVersion,policyChannel:e.policyChannel,executionConfigDigest:e.executionConfigDigest,capabilities:[...e.capabilities].sort()})).digest("hex")}async function P4(e){let t=[];for(let r of e){let n=S4(w4(r.prefix)),o=(await Promise.all(_4(n,r.packageName).map(async f=>({candidate:f,ok:await x4(f)})))).find(f=>f.ok)?.candidate;if(!o)continue;let s=JSON.parse(await ZT(o,"utf8"));if(s.name!==r.packageName||typeof s.version!="string"||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(s.version))continue;let i=qe.dirname(o),a=E4(s,r,i),l=r.packageName==="@kynver-app/runtime",c=r.lifecycle??"runtime_stdio",u=QT("sha256").update(JSON.stringify({prefix:n,binName:r.binName??null,envAllowlist:[...r.envAllowlist??[]].sort(),lifecycle:c})).digest("hex"),d=l?[]:c==="runtime_stdio"&&a?["update","restart","rollback","verify_mcp"]:["update","rollback"],m={inventoryKey:r.inventoryKey,connectionId:r.connectionId??null,packageName:r.packageName,managerKind:"npm_global",sourceKind:"configured_stdio",installedVersion:s.version,nodeVersion:process.versions.node,policyChannel:"latest",executionConfigDigest:u,capabilities:d};t.push({report:{...m,displayName:r.displayName?.trim()||r.packageName,inventoryFingerprint:A4(m),capabilityExplanation:l?"Runtime self-update requires a supervisor-owned durable handoff and is not enabled by this adapter.":c==="runtime_stdio"&&a?"The authorized runtime can install, start, and verify this configured stdio package.":"The package can be installed, but its external supervisor must restart and verify it."},local:{prefix:n,packageJsonPath:o,packageDir:i,binPath:a,envAllowlist:r.envAllowlist??[],lifecycle:c}})}return t}async function eN(){return P4(await C4())}var b4,v4,tN=p(()=>{"use strict";b4=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/i,v4=/^[A-Za-z0-9._:-]{8,128}$/});import{createHash as I4,createHmac as O4,timingSafeEqual as T4}from"node:crypto";function Cy(e){let t=e.trim().split(".");return t.length!==3||t[0]!=="krc1"||!t[1]||!t[2]?null:{tokenId:t[1],tokenHash:I4("sha256").update(`krc1.${t[1]}.${t[2]}`,"utf8").digest("hex")}}function rN(e,t,r){let n=Cy(t);if(!n||e.algorithm!=="hmac-sha256-runner-v1"||e.keyId!==n.tokenId)return!1;let o=Date.parse(e.claims.expiresAt);if(e.claims.version!==1||e.claims.agentOsId!==r||!Number.isFinite(o)||o<=Date.now()||o>Date.now()+10*6e4||![null,"installing","restarting","verifying"].includes(e.claims.resumePhase))return!1;let s=O4("sha256",Buffer.from(n.tokenHash,"hex")).update(JSON.stringify(e.claims),"utf8").digest(),i=Buffer.from(e.signature,"base64url");return i.length===s.length&&T4(i,s)}var Ey=p(()=>{"use strict"});import{createHash as N4}from"node:crypto";import{access as Ay,mkdtemp as D4,readFile as aN,rm as M4}from"node:fs/promises";import{constants as Py}from"node:fs";import{tmpdir as L4}from"node:os";import Ts from"node:path";import{spawn as B4}from"node:child_process";import{Client as W4}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as U4}from"@modelcontextprotocol/sdk/client/stdio.js";function lN(){return"npm"}function oN(e,t){return Buffer.byteLength(e)>=nN?e:(e+t.toString("utf8")).slice(0,nN)}function $4(e){let t=process.env.KYNVER_MCP_UPDATE_NPM_CACHE?.trim(),r=t&&Ts.isAbsolute(t)?t:e,n={PATH:process.env.PATH,SystemRoot:process.env.SystemRoot,TEMP:process.env.TEMP,TMP:process.env.TMP,npm_config_registry:Iy,npm_config_audit:"false",npm_config_fund:"false",npm_config_update_notifier:"false",npm_config_cache:r};return Object.fromEntries(Object.entries(n).filter(o=>typeof o[1]=="string"))}async function cN(e,t,r=Oy,n){return new Promise((o,s)=>{let i,a;try{[i,a]=se(e,t)}catch(f){s(f);return}let l=B4(i,a,{shell:!1,windowsHide:!0,detached:be(),env:$4(n),stdio:["ignore","pipe","pipe"]}),c="",u="",d=!1;l.stdout.on("data",f=>{c=oN(c,f)}),l.stderr.on("data",f=>{u=oN(u,f)});let m=setTimeout(()=>{d=!0,l.pid&&Se(l.pid,"SIGKILL")},r);l.once("error",f=>{clearTimeout(m),s(f)}),l.once("close",f=>{clearTimeout(m),d?s(new Error("process_timeout")):o({code:f,stdout:c,stderr:u})})})}function K4(e,t){let[r,n]=t.split("-",2);return!n||!["sha256","sha384","sha512"].includes(r)?!1:N4(r).update(e).digest("base64")===n}async function H4(e,t,r,n){let o=await cN(lN(),["pack",`${e}@${t}`,"--json","--pack-destination",n,`--registry=${Iy}`,"--ignore-scripts"],Oy,Ts.join(n,"npm-cache"));if(o.code!==0)throw new Error("artifact_download_failed");let s;try{s=JSON.parse(o.stdout)}catch{throw new Error("artifact_receipt_invalid")}let i=s[0]?.filename;if(typeof i!="string"||Ts.basename(i)!==i)throw new Error("artifact_receipt_invalid");let a=Ts.join(n,i);if(!K4(await aN(a),r))throw new Error("artifact_integrity_mismatch");return a}async function j4(e,t,r){if((await cN(lN(),["install","--global","--prefix",e,t,`--registry=${Iy}`,"--no-audit","--fund=false"],Oy,r)).code!==0)throw new Error("package_install_failed")}async function uN(e){let t=JSON.parse(await aN(e.local.packageJsonPath,"utf8"));if(t.name!==e.report.packageName||typeof t.version!="string")throw new Error("installed_identity_mismatch");return t.version}function V4(e){let t={};for(let r of["PATH","SystemRoot","TEMP","TMP",...e]){let n=process.env[r];n!==void 0&&(t[r]=n)}return t}async function sN(e){if(!e.local.binPath)throw new Error("mcp_binary_missing");await Ay(e.local.binPath,Py.X_OK).catch(async()=>Ay(e.local.binPath,Py.R_OK));let t=new U4({command:e.local.binPath,args:[],env:V4(e.local.envAllowlist),stderr:"pipe"}),r=new W4({name:"kynver-managed-update-verifier",version:"1.0.0"}),n;try{await Promise.race([r.connect(t),new Promise((s,i)=>{n=setTimeout(()=>i(new Error("mcp_handshake_timeout")),F4)})]);let o=await r.listTools();return{toolCount:Array.isArray(o.tools)?o.tools.length:0}}finally{n&&clearTimeout(n),await r.close().catch(()=>{})}}async function iN(e,t,r,n,o){let s=await D4(Ts.join(L4(),"kynver-mcp-update-"));try{let i=await H4(t,r,n,s);if(await o(),await j4(e.local.prefix,i,Ts.join(s,"npm-cache")),await uN(e)!==r)throw new Error("installed_version_mismatch")}finally{await M4(s,{recursive:!0,force:!0})}}async function dN(e,t,r,n={}){if(typeof process.getuid=="function"&&process.getuid()===0)throw new Error("root_execution_refused");if(e.report.inventoryKey!==t.inventoryKey||e.report.inventoryFingerprint!==t.inventoryFingerprint||e.report.packageName!==t.packageName)throw new Error("local_inventory_mismatch");if(t.packageName==="@kynver-app/runtime")throw new Error("runtime_self_update_requires_supervisor");await r("preflight"),await Ay(e.local.prefix,Py.W_OK).catch(()=>{throw new Error("npm_prefix_not_writable")});let o=await uN(e),s=t.resumePhase!==null&&o===t.targetVersion,i=s&&n.recoveryVerifiedTargetInstalled===!0;if(!i&&o!==t.installedVersion&&!s)throw new Error("installed_version_changed");try{if(i?await r("installing"):(await iN(e,t.packageName,t.targetVersion,t.targetIntegrity,async()=>{await r("installing"),await n.beforePackageMutation?.()}),await n.onTargetInstalled?.()),e.local.lifecycle!=="runtime_stdio")return{outcome:"manual_restart_required",observedVersion:t.targetVersion,handshakeVerified:!1,toolCount:null,failureCode:"external_supervisor_restart_required"};await r("restarting"),await r("verifying");let a=await sN(e);return{outcome:"succeeded",observedVersion:t.targetVersion,handshakeVerified:!0,toolCount:a.toolCount}}catch(a){let l=a instanceof Error?a.message:"update_failed";if(l==="progress_rejected")throw a;if(!t.rollbackIntegrity)return{outcome:"failed",observedVersion:null,handshakeVerified:!1,toolCount:null,failureCode:l};await n.beforePackageMutation?.();try{if(await iN(e,t.packageName,t.installedVersion,t.rollbackIntegrity,async()=>{await n.beforePackageMutation?.()}),e.local.lifecycle==="runtime_stdio"){let c=await sN(e);return{outcome:"rollback_succeeded",observedVersion:t.installedVersion,handshakeVerified:!0,toolCount:c.toolCount,failureCode:l}}return{outcome:"manual_restart_required",observedVersion:t.installedVersion,handshakeVerified:!1,toolCount:null,failureCode:l}}catch(c){if(c instanceof Error&&c.message==="progress_rejected")throw c;return{outcome:"rollback_failed",observedVersion:null,handshakeVerified:!1,toolCount:null,failureCode:l}}}}var Iy,nN,Oy,F4,pN=p(()=>{"use strict";Zs();Ge();Iy="https://registry.npmjs.org",nN=512*1024,Oy=2*6e4,F4=2e4});import{createHmac as G4,timingSafeEqual as J4}from"node:crypto";import{mkdir as q4,readFile as Y4,rename as z4,writeFile as X4}from"node:fs/promises";import{homedir as Q4}from"node:os";import Ty from"node:path";function Ny(){return process.env.KYNVER_MCP_UPDATE_STATE_ROOT?.trim()||Ty.join(Q4(),".kynver","state","mcp-updates")}function fN(e){if(!/^[A-Za-z0-9_-]{8,128}$/.test(e))throw new Error("invalid update operation identity");return Ty.join(Ny(),`${e}.json`)}function mN(e,t){let r=Cy(t);return r?G4("sha256",Buffer.from(r.tokenHash,"hex")).update(JSON.stringify(e),"utf8").digest("base64url"):null}async function gN(e,t){try{let r=JSON.parse(await Y4(fN(e),"utf8"));if(r.version!==2||r.operationId!==e||typeof r.integrityMac!="string")return null;let{integrityMac:n,...o}=r,s=mN(o,t);if(!s)return null;let i=Buffer.from(n,"utf8"),a=Buffer.from(s,"utf8");return i.length!==a.length||!J4(i,a)?null:r}catch{return null}}async function hN(e,t){let r=mN(e,t);if(!r)throw new Error("invalid_runner_credential_for_receipt");let n=fN(e.operationId);await q4(Ty.dirname(n),{recursive:!0,mode:448});let o=`${n}.${process.pid}.tmp`;await X4(o,`${JSON.stringify({...e,integrityMac:r},null,2)}
|
|
123
|
-
`,{mode:384}),await z4(o,n)}var Dy=p(()=>{"use strict";Ey()});import{randomBytes as My}from"node:crypto";import{mkdir as Ly,readFile as By,rename as Z4,rm as kd,stat as eX,writeFile as yN}from"node:fs/promises";import Zn from"node:path";function kN(){return Zn.join(Ny(),tX)}async function bN(){try{let e=JSON.parse(await By(Zn.join(kN(),"owner.json"),"utf8"));return!Number.isSafeInteger(e.pid)||typeof e.acquiredAt!="string"?null:{holder:e.holder==="desktop_update"?"desktop_update":"mcp_update",pid:e.pid,acquiredAt:e.acquiredAt,alive:vN(e.pid)}}catch{return null}}function vN(e){if(!Number.isSafeInteger(e)||e<=0)return!0;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function rX(e){try{return await eX(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function RN(){return nX("mcp_update")}async function nX(e){let t=kN(),r=`${t}.reclaiming`;await Ly(Zn.dirname(t),{recursive:!0,mode:448});let n=!1;try{if(await rX(r))return null;for(let o=0;o<2;o+=1)try{await Ly(t,{mode:448});let s={pid:process.pid,nonce:My(18).toString("base64url"),acquiredAt:new Date().toISOString(),holder:e};return await yN(Zn.join(t,"owner.json"),JSON.stringify(s),{mode:384}),n&&(await kd(r,{recursive:!0,force:!0}),n=!1),{release:async()=>{try{let i=JSON.parse(await By(Zn.join(t,"owner.json"),"utf8"));i.pid===s.pid&&i.nonce===s.nonce&&await kd(t,{recursive:!0,force:!0})}catch{}}}}catch(s){if(s.code!=="EEXIST")throw s;if(!n)try{await Ly(r,{mode:448}),n=!0,await yN(Zn.join(r,"owner.json"),JSON.stringify({pid:process.pid,nonce:My(18).toString("base64url"),acquiredAt:new Date().toISOString()}),{mode:384})}catch(l){if(l.code==="EEXIST")return null;throw l}let i=null;try{i=JSON.parse(await By(Zn.join(t,"owner.json"),"utf8"))}catch{return null}if(vN(i.pid))return null;let a=`${t}.stale-${process.pid}-${My(8).toString("hex")}`;await Z4(t,a),await kd(a,{recursive:!0,force:!0})}return null}finally{n&&await kd(r,{recursive:!0,force:!0})}}var tX,wN=p(()=>{"use strict";Dy();tX="host-mutation.lock"});function bd(e,t,r){return`${e}/api/agent-os/by-id/${encodeURIComponent(t)}/mcp-updates/${r}`}function oX(e){if(!e||typeof e!="object")return null;let t=e.claim;if(!t||typeof t!="object"||t.waitingForIdle!==!1)return null;let r=t.command;return r&&typeof r=="object"?r:null}function SN(e,t){let r=t.claims;return e.inventoryKey===r.inventoryKey&&e.packageName===r.packageName&&e.installedVersion===r.installedVersion&&e.targetVersion===r.targetVersion&&e.targetIntegrity===r.targetIntegrity&&e.rollbackIntegrity===r.rollbackIntegrity&&e.item.report.inventoryKey===r.inventoryKey&&e.item.report.packageName===r.packageName}function sX(e,t){return{inventoryKey:t.claims.inventoryKey,packageName:t.claims.packageName,installedVersion:t.claims.installedVersion,targetVersion:t.claims.targetVersion,targetIntegrity:t.claims.targetIntegrity,rollbackIntegrity:t.claims.rollbackIntegrity,verifiedTargetInstalled:!1,item:e}}async function _N(e){let t=pe(e.baseUrl),r=await eN();if(r.length===0)return{ok:!0,stage:"not_configured"};let n=await Pn(bd(t,e.agentOsId,"inventory"),e.secret,{items:r.map(s=>s.report)});if(!n.ok)return{ok:!1,stage:"inventory",status:n.status};let o=await RN();if(!o){let s=await bN();return{ok:!0,stage:"host_mutation_busy",...s?{heldBy:s.holder}:{}}}try{let s=await Pn(bd(t,e.agentOsId,"claim"),e.secret,{activeOwnedSessions:e.activeOwnedSessions});if(!s.ok)return{ok:!1,stage:"claim",status:s.status};let i=oX(s.response);if(!i)return{ok:!0,stage:"idle"};if(!rN(i,e.secret,e.agentOsId))return{ok:!1,stage:"command_auth"};let a=await gN(i.claims.operationId,e.secret);if(a?.terminal&&a.attempt===i.claims.attempt&&a.nonce===i.claims.nonce)return{ok:!0,stage:"already_completed",outcome:a.outcome};let l,c;if(i.claims.resumePhase!==null){if(!a||!SN(a.recovery,i))return{ok:!1,stage:"recovery_receipt_invalid"};c=a.recovery,l={...c.item,report:{...c.item.report,inventoryFingerprint:i.claims.inventoryFingerprint}}}else{let k=r.find(b=>b.report.inventoryKey===i.claims.inventoryKey);if(!k||k.report.inventoryFingerprint!==i.claims.inventoryFingerprint)return{ok:!1,stage:"inventory_changed"};l=k,c=a&&SN(a.recovery,i)?a.recovery:sX(k,i)}let u=a?.acceptedAt??new Date().toISOString(),d=async(k,b,_)=>{await hN({version:2,operationId:i.claims.operationId,attempt:i.claims.attempt,nonce:i.claims.nonce,acceptedAt:u,phase:k,terminal:b,..._?{outcome:_}:{},recovery:c},e.secret)};await d(a?.attempt===i.claims.attempt?a.phase:"claimed",!1);let m="claimed",f=async k=>{if(!(await Pn(bd(t,e.agentOsId,`operations/${encodeURIComponent(i.claims.operationId)}/events`),e.secret,{attempt:i.claims.attempt,fenceToken:i.claims.fenceToken,phase:k})).ok)throw new Error("progress_rejected");m=k,await d(k,!1)},g=k=>f(k),h=()=>f(m),y;try{y=await dN(l,i.claims,g,{recoveryVerifiedTargetInstalled:c.verifiedTargetInstalled,beforePackageMutation:h,onTargetInstalled:async()=>{c={...c,verifiedTargetInstalled:!0},await d("target_installed",!1)}})}catch(k){y={outcome:"failed",observedVersion:null,handshakeVerified:!1,toolCount:null,failureCode:k instanceof Error?k.message:"update_failed"}}let v=await Pn(bd(t,e.agentOsId,`operations/${encodeURIComponent(i.claims.operationId)}/complete`),e.secret,{attempt:i.claims.attempt,fenceToken:i.claims.fenceToken,...y});return v.ok?(await d(y.outcome,!0,y.outcome),{ok:y.outcome==="succeeded",stage:"complete",outcome:y.outcome}):{ok:!1,stage:"complete",status:v.status,outcome:y.outcome}}finally{await o.release()}}var xN=p(()=>{"use strict";H();We();tN();Ey();pN();wN();Dy()});import CN from"node:path";function iX(){let e=process.env.KYNVER_PIPELINE_SWEEP_ENABLED;return e?e==="1"||e.toLowerCase()==="true":!1}async function aX(e,t){let r=ae(e),n=[],o=Math.max(0,Number.parseInt(process.env.KYNVER_PIPELINE_COMPLETION_REPLAY_MAX_DEEP_CHECKS_PER_TICK??"0",10)||0),s=0;for(let i of Object.keys(r.workers||{})){let a=$(CN.join(G(r.id),"workers",B(i),"worker.json"),void 0);if(!a?.taskId||a.localOnly||Lr(a))continue;if(ua(a)){n.push({worker:i,ok:!0,taskId:a.taskId??null,skipped:!0});continue}if(s>=o)break;s++;let l=oe(a);if(!Me(l))continue;let c=Ao({alive:l.alive,finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry});if(!a.dispatched&&!l.finalResult&&!c?.salvageable)continue;let u=await Yu({run:e,name:i,agentOsId:String(t.agentOsId||a.agentOsId||""),...t});n.push({worker:i,ok:u.ok,taskId:a.taskId??null})}return n}async function lX(e,t,r,n,o){let s=pe(n.baseUrl?String(n.baseUrl):void 0),i=await fe(n.secret?String(n.secret):void 0,e,{baseUrl:s}),a=`${s}/api/agent-os/by-id/${encodeURIComponent(e)}/operator/tick`,l=await xT(),c=Vo(t),u=null;try{let S=HT(t);if(S.length>0){let R=qT(t);u=WT(S,{cache:R}),R.flush?.()}else u=null}catch{u=null}try{if(Er()!=="off"){let S=To();uA({liveWorkers:S}),mA({liveWorkers:S})}else lA()}catch{}let d=({runId:S,workerName:R})=>{try{let{runsDir:w}=me(),W=CN.join(dr(w,B(S)),"workers",B(R),"worker.json"),O=$(W,null);return O?Lr(O):!1}catch{return!1}};await xI({agentOsId:e,baseUrl:s,secret:i,hasLiveWorker:d});let m=null;try{m=zT({hasLiveWorker:d})}catch{m=null}let f=null;try{f=Zl({control:Wr(e),supervisor:NR(),inFlightWorkers:To().length})}catch{f=null}let g=Fc(t),h=J_(),y=await de(a,i,{agentOsId:e,runId:t,ingestHarness:!0,harnessBoardSnapshot:hh(t),resourceGate:r,boxResourceSnapshot:EI(r,{harnessRunId:t,boxKind:Rt(E())}),packageVersions:l,...o?{harnessCleanup:o}:{},runnerPresence:Oe({runId:t}),activeHarnessWorkers:c,...g?.leaseToken?{meshCronLeaseToken:g.leaseToken}:{},...m?{localRunStore:m}:{},...f?{runtimeControlAck:f}:{},...h?{daemonEventLoop:h}:{},...u&&u.items.length>0?{providerEvidence:u.items}:{}},{agentOsId:e,baseUrl:s}),v=GT(y.response);if(v)try{jT(t,v)}catch{}let k=H_(y);if(k)try{K_(t,k)}catch{}let b=HS(y);b&&jS(e,b);let _=ER(y);return _&&vf(e,_),{ok:y.ok,httpStatus:y.status,response:y.response,...u?{providerEvidence:{attempted:u.attempted,collected:u.collected,skipped:u.skipped.length}}:{}}}async function vd(e){let t=String(vt(String(e.run||""),"--run")),r=String(vt(String(e.agentOsId||""),"--agent-os-id")),n=e.execute!==!1&&e.execute!=="false";hh(t);let o=await Hc(r,e),s=Kc(o),i=gi({runId:t,configuredMaxWorkersOverride:s}),a=vT()?bT(t):void 0,l=await lX(r,t,i,e,a),c;if(n)try{let P=pe(e.baseUrl?String(e.baseUrl):void 0),N=await fe(e.secret?String(e.secret):void 0,r,{baseUrl:P});c=await _N({agentOsId:r,secret:N,baseUrl:P,activeOwnedSessions:To().length})}catch(P){c={ok:!1,stage:"cycle",error:P instanceof Error?P.message:"update cycle failed"}}let u=KE(t,l),d=await BC(t,e),m=await aX(t,e);m.some(P=>P.ok&&!P.skipped)&&S_();let f=gi({runId:t,configuredMaxWorkersOverride:s}),g=Jh(),h=await OI(t,e),y=sI(f,l),v=y.maxStarts,k=Wr(r),b=PR(k);b&&(v=0);let _=iX()?await ed({run:t,agentOsId:r,pipeline:!0,...e}):{ok:!0,skipped:!0,reason:"pipeline_sweep_disabled"},S=null,R=0,w=nI(l),W=v;if(n&&W>0&&w.length>0){let P=Math.min(W,w.length),N=await Mh({...e,run:t,agentOsId:r,targetTaskIds:w.join(",")},P),L=_s(N);R+=L,W=Math.max(0,W-L),S={exactTargetTaskIds:w,exact:N,startedCount:R}}if(n&&W>0){let P=await Mh({...e,run:t,agentOsId:r},W),N=_s(P);R+=N,S=S&&typeof S=="object"?{...S,broad:P,startedCount:R}:P}else!n||v<=0?S||(S={ok:!0,skipped:!0,reason:b??(n?f.reason??"no slots or queued work":"execute disabled"),maxStarts:0,dispatchAdvice:y,...w.length?{exactTargetTaskIds:w,exactOnly:!0}:{}}):S&&typeof S=="object"&&(S={...S,broadSkipped:!0,startedCount:R});let O=!y.underutilized&&v===0&&m.length===0&&R===0;return{runId:t,agentOsId:r,execute:n,resourceGate:i,dispatchResourceGate:f,leaseRenewal:d,completedWorkers:m,staleReconcile:g,harnessCleanup:a,planProgressSync:h,completionAckSync:u,operatorTick:l,mcpUpdates:c,sweep:_,dispatchAdvice:y,dispatch:S,idle:O,runtimeControl:k?{desiredState:k.desiredState,policyVersion:k.policyVersion}:null}}var Wy=p(()=>{"use strict";Ur();gc();H();We();rI();oI();iI();qh();No();Hn();CI();ks();AI();Wc();z();St();Ul();_e();zh();D();TI();Ag();vs();Su();Vl();Jm();H();De();RT();Mu();CT();mr();UT();YT();Sy();Km();XT();xm();xN();Hm()});function Rd(e){return Mo(Wr(e))!=="stopped"?null:To().length}var Uy=p(()=>{"use strict";No();Ur()});function EN(e){if(!e||typeof e!="object")return!1;let t=e;return t.type==="result"&&typeof t.id=="number"&&typeof t.ok=="boolean"}var AN=p(()=>{"use strict"});import{existsSync as cX}from"node:fs";import{fileURLToPath as uX}from"node:url";import{SHARE_ENV as dX,Worker as pX}from"node:worker_threads";function mX(e=import.meta.url){for(let t of[`./${PN}`,`../${PN}`]){let r=new URL(t,e);try{if(cX(uX(r)))return r}catch{}}return null}function gX(e){let t=(e.env??process.env).KYNVER_DAEMON_TICK_THREAD?.trim().toLowerCase();return t==="0"||t==="false"||t==="off"?{mode:"inline",reason:"disabled_by_env"}:e.desktopMode??ze()?{mode:"inline",reason:"desktop_sidecar"}:e.script?{mode:"thread",reason:"default"}:{mode:"inline",reason:"thread_entry_not_built"}}var PN,fX,hX,wd,IN=p(()=>{"use strict";bt();Hm();Kr();Wy();Uy();AN();PN="daemon-tick-thread.js",fX=3;hX=(e,t)=>new pX(e,{workerData:t,env:dX,name:"kynver-pipeline-tick"}),wd=class{constructor(t){this.options=t;this.script=t.script===void 0?mX():t.script;let r=gX({env:t.env,desktopMode:t.desktopMode,script:this.script});this.modeValue=r.mode,this.reason=r.reason,this.createWorker=t.createWorker??hX,this.log=t.log??(n=>console.error(n))}options;modeValue;reason;script;createWorker;log;worker=null;online=!1;pending=null;nextId=1;startFailures=0;sentBundleKey=null;get mode(){return this.modeValue}async runTick(t,r){if(this.modeValue==="inline")return this.runInline(t,r);let n=await this.request(()=>({type:"tick",id:this.nextId++,args:t,agentOsId:this.options.agentOsId,...this.bundleIfChanged(),eventLoopReport:r}));if(!n.ok)throw new Error(n.error);return{tick:n.tick,inFlightWorkers:n.inFlightWorkers,isolation:"thread"}}async close(){let t=this.worker;this.worker=null,t&&await t.terminate().catch(()=>{})}async runInline(t,r){return G_(r),{tick:await vd(t),inFlightWorkers:Rd(this.options.agentOsId),isolation:"inline"}}bundleIfChanged(){let t=wS(),r=Lt(),n=`${t.version}\0${r}`;return n===this.sentBundleKey?{}:(this.sentBundleKey=n,{instructionBundle:{bundle:t,source:r}})}ensureWorker(){if(this.worker)return this.worker;if(!this.script)throw new Error("tick thread entry not found");let t=this.createWorker(this.script,this.options.init);return this.worker=t,this.online=!1,this.sentBundleKey=null,t.on("online",()=>{this.online=!0,this.startFailures=0}),t.on("message",r=>{if(!EN(r)||!this.pending||r.id!==this.pending.id)return;let n=this.pending;this.pending=null,n.resolve(r)}),t.on("error",r=>this.onWorkerGone(t,r)),t.on("exit",r=>this.onWorkerGone(t,new Error(`tick thread exited with code ${r}`))),t}onWorkerGone(t,r){if(this.worker!==t)return;this.worker=null,this.online||(this.startFailures+=1,this.startFailures>=fX&&(this.modeValue="inline",this.log(JSON.stringify({event:"daemon_tick_thread_fallback",level:"error",reason:"thread_failed_to_start",attempts:this.startFailures,error:r.message})))),this.log(JSON.stringify({event:"daemon_tick_thread_exit",level:"warn",error:r.message}));let n=this.pending;this.pending=null,n?.reject(r)}request(t){if(this.pending)return Promise.reject(new Error("a pipeline tick is already running"));let r;try{r=this.ensureWorker()}catch(o){return Promise.reject(o instanceof Error?o:new Error(String(o)))}let n=t();return new Promise((o,s)=>{this.pending={id:n.id,resolve:o,reject:s};try{r.postMessage(n)}catch(i){this.pending=null,s(i instanceof Error?i:new Error(String(i)))}})}}});import{monitorEventLoopDelay as yX,performance as kX}from"node:perf_hooks";var bX,vX,RX,wX,ON,Sd,TN=p(()=>{"use strict";bX=1e3,vX=250,RX=5,wX=5e3,ON=e=>Number.isFinite(e)?Math.round(e/1e6):0,Sd=class{thresholdMs;sampleIntervalMs;now;monotonicNow;log;histogram;timer=null;lastSampleAt=0;lastSampleWallAt=0;startedAt=0;phase="starting";phasesInWindow=new Set(["starting"]);stallCount=0;maxLagMs=0;recent=[];tickIsolation="inline";constructor(t={}){this.thresholdMs=t.thresholdMs??bX,this.sampleIntervalMs=t.sampleIntervalMs??vX,this.now=t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??(()=>kX.now()),this.log=t.log??(r=>console.error(r)),this.histogram=t.histogram??yX({resolution:20})}setPhase(t){this.phase=t,this.phasesInWindow.add(t)}setTickIsolation(t){this.tickIsolation=t}start(){this.timer||(this.startedAt=this.now(),this.lastSampleWallAt=this.startedAt,this.lastSampleAt=this.monotonicNow(),this.histogram.enable(),this.timer=setInterval(()=>this.sample(),this.sampleIntervalMs),this.timer.unref?.())}stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.histogram.disable()}sample(){let t=this.now(),r=this.monotonicNow(),n=r-this.lastSampleAt,o=t-this.lastSampleWallAt;if(this.lastSampleAt=r,this.lastSampleWallAt=t,o-n>wX)return this.histogram.reset(),this.phasesInWindow=new Set([this.phase]),null;let s=Math.max(0,Math.round(n-this.sampleIntervalMs)),i=ON(this.histogram.max),a=ON(this.histogram.percentile(99)),l=Math.max(s,i),c=null;return(l>=this.thresholdMs||a>=this.thresholdMs)&&(c={at:new Date(t).toISOString(),lagMs:l,p99Ms:a,phase:this.phase,phasesInWindow:[...this.phasesInWindow]},this.stallCount+=1,this.maxLagMs=Math.max(this.maxLagMs,l),this.recent=[...this.recent,c].slice(-RX),this.log(JSON.stringify({event:"daemon_event_loop_stall",level:"warn",lagMs:l,p99Ms:a,maxMs:i,thresholdMs:this.thresholdMs,phase:c.phase,phasesInWindow:c.phasesInWindow,tickIsolation:this.tickIsolation}))),this.histogram.reset(),this.phasesInWindow=new Set([this.phase]),c}report(){return{contractVersion:1,observedAt:new Date(this.now()).toISOString(),monitorStartedAt:new Date(this.startedAt||this.now()).toISOString(),thresholdMs:this.thresholdMs,tickIsolation:this.tickIsolation,stallCount:this.stallCount,maxLagMs:this.maxLagMs,lastStall:this.recent.length?this.recent[this.recent.length-1]:null,recentStalls:[...this.recent]}}}});var SX,_X,xX,_d,NN=p(()=>{"use strict";nr();SX=5*6e4,_X=5*6e4,xX=2160*60*60,_d=class{constructor(t){this.deps=t;this.now=t.now??Date.now,this.fetchImpl=t.fetchImpl??fetch,this.log=t.log??(r=>console.error(JSON.stringify(r)))}deps;token=null;lastMintFailureAt=0;minting=null;refreshing=null;lastRefreshFailureAt=0;now;fetchImpl;log;async authorization(){let t=this.token&&this.token.expiresAtMs-this.now()>SX?this.token:null;if(t)return{kind:"box_token",bearer:t.token,boxId:t.boxId};let r=this.deps.loadBoxCredential();if(r||(r=await this.mintOnce()),r){let o=await this.refreshOnce(r);if(o)return{kind:"box_token",bearer:o.token,boxId:o.boxId};if(this.token&&this.token.expiresAtMs>this.now())return{kind:"box_token",bearer:this.token.token,boxId:this.token.boxId}}let n=this.deps.loadApiKey();return n?{kind:"api_key",bearer:n,boxId:null}:null}invalidateToken(){this.token=null}describe(){return{kind:this.token?"box_token":this.deps.loadApiKey()?"api_key":"none",boxId:this.token?.boxId??null,tokenExpiresAt:this.token?new Date(this.token.expiresAtMs).toISOString():null,hasBoxCredential:!!this.deps.loadBoxCredential()}}mintOnce(){return this.minting||(this.minting=this.mintBoxCredential().finally(()=>{this.minting=null})),this.minting}async mintBoxCredential(){let t=this.deps.loadApiKey();if(!t||this.now()-this.lastMintFailureAt<_X)return;let r=`${this.deps.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(this.deps.agentOsId)}/runner-credentials`;try{let n=await it(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({capabilities:["chat.relay"],ttlSeconds:xX,name:`chat-box:${this.deps.boxLabel()}`}),signal:AbortSignal.timeout(1e4)},this.fetchImpl),o=await n.json().catch(()=>null);if(!n.ok||typeof o?.token!="string"||!o.token){this.lastMintFailureAt=this.now(),this.log({event:"chat_box_credential_mint_failed",status:n.status,detail:typeof o?.error=="string"?o.error.slice(0,200):null});return}return this.deps.saveBoxCredential(o.token),this.log({event:"chat_box_credential_minted",agentOsId:this.deps.agentOsId}),o.token}catch(n){this.lastMintFailureAt=this.now(),this.log({event:"chat_box_credential_mint_failed",error:n instanceof Error?n.message:String(n)});return}}refreshOnce(t){return this.refreshing||(this.refreshing=this.refreshToken(t).finally(()=>{this.refreshing=null})),this.refreshing}async refreshToken(t){if(this.now()-this.lastRefreshFailureAt<15e3&&this.token===null)return null;let r=`${this.deps.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(this.deps.agentOsId)}/chat-box-token`;try{let n=await it(r,{method:"POST",headers:{"Content-Type":"application/json","X-Kynver-Runner-Token":t},body:JSON.stringify({boxLabel:this.deps.boxLabel()}),signal:AbortSignal.timeout(1e4)},this.fetchImpl);if(n.status===401||n.status===403)return this.log({event:"chat_box_credential_rejected",status:n.status}),this.deps.clearBoxCredential(),this.token=null,null;let o=await n.json().catch(()=>null);if(!n.ok||typeof o?.token!="string"||typeof o.boxId!="string")return this.lastRefreshFailureAt=this.now(),this.log({event:"chat_box_token_refresh_failed",status:n.status,detail:typeof o?.error=="string"?o.error.slice(0,200):null}),null;let s=typeof o.expiresAt=="string"&&!Number.isNaN(Date.parse(o.expiresAt))?Date.parse(o.expiresAt):this.now()+10*6e4;return this.token={token:o.token,expiresAtMs:s,boxId:o.boxId},this.token}catch(n){return this.lastRefreshFailureAt=this.now(),this.log({event:"chat_box_token_refresh_failed",error:n instanceof Error?n.message:String(n)}),null}}}});async function Ns(e){if(e.auth){let t=await e.auth.authorization();if(t)return{bearer:t.bearer,kind:t.kind,boxId:t.boxId??e.boxId}}return{bearer:e.apiKey,kind:"api_key",boxId:e.boxId}}function eo(e,t,r){r===401&&t.kind==="box_token"&&e.auth?.invalidateToken()}var xd=p(()=>{"use strict"});import{createHash as CX,verify as EX,createPublicKey as AX}from"node:crypto";function $y(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};return delete t[DN],t}function IX(e){return CX("sha256").update(et($y(e)),"utf8").digest("hex")}function Ky(e){return!e||typeof e!="object"||Array.isArray(e)?null:e[DN]??null}function OX(e){if(!e||typeof e!="object")return!1;let t=e;if(typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let r=t.payload;return!(!r||typeof r!="object"||r.v!==1||r.kind!=="chat-turn"||typeof r.turnId!="string"||!r.turnId||typeof r.agentOsId!="string"||!r.agentOsId||r.userId!==null&&(typeof r.userId!="string"||!r.userId)||r.boxId!==null&&typeof r.boxId!="string"||r.access!==null&&(!r.access||typeof r.access!="object"||Array.isArray(r.access))||typeof r.payloadHash!="string"||!/^[0-9a-f]{64}$/.test(r.payloadHash)||typeof r.exp!="number"||!Number.isFinite(r.exp)||typeof r.nonce!="string"||!r.nonce)}function TX(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)?e.computerAccess??null:null;return r===null&&t===null?!0:r===null||t===null?!1:et(r)===et(t)}function Fy(e,t){return{state:t,firstSeenAt:new Date(e.firstSeenSec*1e3).toISOString(),turnId:e.turnId}}function NX(e){return AX({key:Buffer.concat([PX,Buffer.from(e)]),format:"der",type:"spki"})}function MN(e,t,r={}){let n=r.env??process.env,o=r.nowSec??Math.floor(Date.now()/1e3),s=Ky(e);if(s===null)return{ok:!1,code:"unsigned",reason:"turn carries no signed envelope"};if(!OX(s))return{ok:!1,code:"malformed",reason:"malformed chat-turn envelope"};let i=s;if(i.payload.agentOsId!==t.agentOsId)return{ok:!1,code:"agent_os_mismatch",reason:"envelope is for another workspace"};if(i.payload.turnId!==t.turnId)return{ok:!1,code:"turn_id_mismatch",reason:"envelope is for another turn"};if(i.payload.exp<=o)return{ok:!1,code:"expired",reason:"envelope expired"};let a=xn(i.publicKeyId,n);if(!a)return{ok:!1,code:"no_verification_key",reason:`no verification key for publicKeyId "${i.publicKeyId}"`};let l;try{l=Buffer.from(i.signature,"base64url")}catch{return{ok:!1,code:"bad_signature",reason:"signature is not base64url"}}if(l.length!==64)return{ok:!1,code:"bad_signature",reason:"signature is not a 64-byte Ed25519 signature"};let c=!1;try{let d=Buffer.from(et(i.payload),"utf8");c=EX(null,d,NX(a),l)}catch(d){return{ok:!1,code:"bad_signature",reason:`signature verification failed: ${d.message}`}}if(!c)return{ok:!1,code:"bad_signature",reason:"Ed25519 signature mismatch"};if(IX(e)!==i.payload.payloadHash)return{ok:!1,code:"payload_tampered",reason:"turn payload does not match its signed hash"};if(!TX(e,i.payload.access))return{ok:!1,code:"access_mismatch",reason:"computer access on the turn differs from the signed setting"};if(!r.nonces)return{ok:!0,payload:i.payload,redelivered:!1};let u=r.nonces.consume({nonce:i.payload.nonce,turnId:i.payload.turnId,expSec:i.payload.exp,nowSec:o});return u.ok?{ok:!0,payload:i.payload,redelivered:u.redelivered}:{ok:!1,code:"replayed",reason:`envelope nonce already used on this computer (${DX(u.replay)})`,replay:u.replay}}function DX(e){return`${e.state==="in_flight"?"this computer is running that turn now":e.state==="already_ran"?"that turn already ran here":`the nonce belongs to turn ${e.turnId}`}; first seen ${e.firstSeenAt}`}var DN,PX,Cd,Hy=p(()=>{"use strict";Fr();Ei();DN="turnEnvelope",PX=Buffer.from("302a300506032b6570032100","hex");Cd=class{constructor(t=1e4){this.maxEntries=t}maxEntries;byNonce=new Map;byTurn=new Map;consume(t){let r=t.nowSec??Math.floor(Date.now()/1e3);this.purge(r);let n=this.byNonce.get(t.nonce);if(n)return n.turnId!==t.turnId?{ok:!1,replay:Fy(n,"turn_mismatch")}:n.state==="verified"?{ok:!0,redelivered:!0}:{ok:!1,replay:Fy(n,n.state==="started"?"in_flight":"already_ran")};let o=this.byTurn.get(t.turnId);if(o){if(o.state!=="verified")return{ok:!1,replay:Fy(o,o.state==="started"?"in_flight":"already_ran")};this.byNonce.delete(o.nonce);let i={...o,nonce:t.nonce,untilSec:Math.max(o.untilSec,t.expSec+60)};return this.byNonce.set(t.nonce,i),this.byTurn.set(t.turnId,i),{ok:!0,redelivered:!0}}if(this.byNonce.size>=this.maxEntries){let i=this.byNonce.values().next().value;i&&this.forget(i)}let s={nonce:t.nonce,turnId:t.turnId,firstSeenSec:r,state:"verified",untilSec:t.expSec+60};return this.byNonce.set(t.nonce,s),this.byTurn.set(t.turnId,s),{ok:!0,redelivered:!1}}markStarted(t){let r=this.byTurn.get(t);return r?(r.state==="verified"&&(r.state="started"),!0):!1}markFinished(t){let r=this.byTurn.get(t);return r?(r.state="finished",!0):!1}stateOf(t){return this.byTurn.get(t)?.state??null}purge(t=Math.floor(Date.now()/1e3)){for(let r of[...this.byNonce.values()])r.untilSec<=t&&this.forget(r)}forget(t){this.byNonce.delete(t.nonce),this.byTurn.get(t.turnId)===t&&this.byTurn.delete(t.turnId)}get size(){return this.byNonce.size}}});function LN(e=process.env,t={}){let r=(e[MX]??t.chatTurnSignature??"").toString().trim().toLowerCase();return r==="optional"||r==="off"||r==="0"||r==="false"?"optional":"required"}function BN(e,t){return t?`turn_rejected_${e}: ${t}`:`turn_rejected_${e}`}function WN(e,t){if(!(Ky(e.payload)!==null)&&t.policy==="optional"){let o=e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload.computerAccess??null:null;return{ok:!0,access:LX(o)?o:null,signed:!1,userId:null,redelivered:!1}}let n=MN(e.payload,{agentOsId:t.agentOsId,turnId:e.turnId},{env:t.env,nowSec:t.nowSec,nonces:t.nonces});return n.ok?{ok:!0,access:n.payload.access,signed:!0,userId:n.payload.userId,redelivered:n.redelivered}:{ok:!1,code:n.code,reason:n.reason,...n.replay?{replay:n.replay}:{}}}function LX(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.byBox;return!!t&&typeof t=="object"&&!Array.isArray(t)}var MX,UN=p(()=>{"use strict";Hy();MX="KYNVER_CHAT_TURN_SIGNATURE"});var Ed,FN=p(()=>{"use strict";Ed=class{rejects=new Map;duplicateOffers=0;childEnv=null;noteRejected(t){this.rejects.set(t,(this.rejects.get(t)??0)+1)}noteDuplicateOffer(){this.duplicateOffers+=1}report(t){return{signedTurns:!0,signaturePolicy:t.policy,accessRaiseGuard:!0,auth:t.auth,credentialStore:t.credentialStore,childEnvSafe:this.childEnv?this.childEnv.ok:null,...this.childEnv&&this.childEnv.leaked.length?{childEnvLeaked:this.childEnv.leaked}:{},rejectedTurns:Object.fromEntries(this.rejects),...this.duplicateOffers>0?{duplicateOffers:this.duplicateOffers}:{},...t.folderSandbox?{folderSandbox:t.folderSandbox}:{}}}}});import{lookup as BX}from"node:dns/promises";import{createServer as WX,request as UX}from"node:http";import{connect as FX,isIP as HN,isIPv4 as $X}from"node:net";function jN(e){let t=e.split(".");if(t.length!==4)return null;let r=t.map(n=>Number(n));return r.every(n=>Number.isInteger(n)&&n>=0&&n<=255)?r:null}function Ua(e){let t=jN(e);if(!t)return!0;let[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168||r===100&&n>=64&&n<=127||r===192&&n===0&&t[2]===0||r>=224}function HX(e){let t=e,r=t.indexOf("%");r!==-1&&(t=t.slice(0,r));let n=t.lastIndexOf(":"),o=t.slice(n+1);if(o.includes(".")){let u=jN(o);if(!u)return null;t=`${t.slice(0,n+1)}${(u[0]<<8|u[1]).toString(16)}:${(u[2]<<8|u[3]).toString(16)}`}let s=t.split("::");if(s.length>2)return null;let i=u=>u===""?[]:u.split(":").map(d=>/^[0-9a-f]{1,4}$/i.test(d)?parseInt(d,16):NaN),a=i(s[0]),l=s.length===2?i(s[1]):[];if([...a,...l].some(u=>Number.isNaN(u)))return null;let c=8-a.length-l.length;return(s.length===2?c<0:c!==0)?null:[...a,...new Array(Math.max(0,c)).fill(0),...l]}function jX(e){let t=HX(e);if(!t||t.every(s=>s===0)||t.slice(0,7).every(s=>s===0)&&t[7]===1)return!0;let n=(s,i)=>`${s>>8}.${s&255}.${i>>8}.${i&255}`;if(t.slice(0,5).every(s=>s===0)&&t[5]===65535||t.slice(0,6).every(s=>s===0)||t[0]===100&&t[1]===65435&&t.slice(2,6).every(s=>s===0))return Ua(n(t[6],t[7]));if(t[0]===8194)return Ua(n(t[1],t[2]));let o=t[0];return(o&65024)===64512||(o&65472)===65152||(o&65472)===65216||(o&65280)===65280||o===8193&&t[1]===3512}function $N(e){let t=HN(e);return t===4?Ua(e):t===6?jX(e):!0}function VX(e){return e==="localhost"||e.endsWith(".localhost")||e==="localhost6"||e==="ip6-localhost"}function GX(e){let t=e.trim().toLowerCase();for(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));t.endsWith(".");)t=t.slice(0,-1);return t}async function VN(e){return(await BX(e,{all:!0})).map(r=>r.address)}async function KN(e,t=VN){let r=GX(e);if(!r||r.length>KX)return{allowed:!1,host:r,reason:"invalid host"};if(VX(r))return{allowed:!1,host:r,reason:`${r} is this computer (loopback): local services are not reachable from a folder step`};if(HN(r))return $N(r)?{allowed:!1,host:r,reason:`${r} is a private, loopback, link-local or metadata address: not reachable from a folder step`}:{allowed:!0,host:r,address:r};let n;try{n=await t(r)}catch(s){return{allowed:!1,host:r,reason:`${r} could not be resolved (${s?.message??String(s)})`}}if(!n.length)return{allowed:!1,host:r,reason:`${r} could not be resolved`};let o=n.find(s=>$N(s));return o?{allowed:!1,host:r,reason:`${r} resolves to ${o}, a private, loopback, link-local or metadata address: not reachable from a folder step`}:{allowed:!0,host:r,address:n.find(s=>$X(s))??n[0]}}function jy(e,t,r){let n=`Kynver folder sandbox: ${r}
|
|
124
|
-
`;e.write(`HTTP/1.1 ${t} ${t===
|
|
181
|
+
`),n=!0)}let o={capturedAt:new Date(e.now??Date.now()).toISOString(),skipReason:e.skipReason,runId:e.indexed.runId,workerName:e.indexed.workerName,worktreePath:e.indexed.worktreePath,taskId:e.indexed.worker.taskId,agentOsId:e.indexed.worker.agentOsId,branch:e.indexed.worker.branch,completionBlocker:e.indexed.worker.completionBlocker,finalResult:e.status.finalResult,changedFiles:e.status.changedFiles,gitAncestry:e.status.gitAncestry,prUrl:e.status.prUrl??null,...n?{patchPath:r}:{}};return WO(yd.join(t,"evidence.json"),`${JSON.stringify(o,null,2)}
|
|
182
|
+
`),o}var HO=p(()=>{"use strict";we();M()});import kd from"node:path";function S4(e){e.writeSalvageEvidence&&w4.has(e.skipReason)&&(Tr(e.indexed,e.now)||KO({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})||$O({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}))}function _4(e){let{indexed:t,worktreesAgeMs:r,terminalWorktreesAgeMs:n}=e;return t&&(Or.has(t.run.status)||e.liveness&&Ay(t,e.liveness)||e.liveness&&Be(Ey(t,e.liveness))&&!Tr(t))?n:r}function x4(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:_4(e)}function C4(e,t){if(e.harnessRoot?.trim())return kd.resolve(e.harnessRoot);let r=t.worker.workerDir;if(!r)return null;let n=`${kd.sep}runs${kd.sep}`,o=r.indexOf(n);return o<0?null:r.slice(0,o+n.length-1)}function jO(e){let{indexed:t,includeOrphans:r,worktreesAgeMs:n,ageMs:o,orphanSafety:s,worktreeRemovalGuard:i}=e,a=e.now??Date.now();if(!t)return r?s??null:"orphan_without_flag";let l=x4(e);if(n<=0&&!r&&l<=0)return"worktrees_disabled";if(l>0&&o<l)return"below_age_threshold";if(Tr(t,a))return"active_worker";let c=Ey(t,e.liveness),u=C4(e,t),d=g=>{if(u)try{S4({indexed:t,harnessRoot:u,skipReason:g,status:c,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})}catch{}return g};if(LO(t,c)){let g=d("completion_blocked");if(g)return g}if(Cy(t,e.liveness?.gitStatusCache)){let g=d("dirty_worktree");if(g)return g}let f=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(f!=null&&f>0){let g=d("pr_or_unmerged_commits");if(g)return g}if(MO(t,e.liveness,a)||!Be(c))return"run_still_active";if($a(c)){let g=d("pr_or_unmerged_commits");if(g)return g}if(yt(c.changedFiles).length>0){let g=d("dirty_worktree");if(g)return g}if(Lo({finalResult:c.finalResult,changedFiles:c.changedFiles,gitAncestry:c.gitAncestry,prUrl:ro(c.finalResult)}).blocked){let g=d("landing_blocked");if(g)return g}if(i&&e.worktreePath){let g=i({worktreePath:e.worktreePath,indexed:!!t,runId:t?.runId,worker:t?.workerName});if(g)return g.detail?{reason:g.reason,detail:g.detail}:g.reason}return null}function Iy(e){let{indexed:t,nodeModulesAgeMs:r,ageMs:n,worktreePath:o,activeWorktreePaths:s,workerFilesystemLive:i,diskPressure:a}=e;return!a&&n<r?"below_age_threshold":i||s.has(kd.resolve(o))||t&&Tr(t)?"active_worker":t&&Cy(t,e.gitStatusCache)?"dirty_worktree":null}function VO(e){return Iy(e)}var w4,GO=p(()=>{"use strict";ec();gd();Ce();rn();Py();BO();HO();to();Ha();to();Ha();w4=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"])});var bd=p(()=>{"use strict"});function qO(e,t){let r=[],n=new Set,o=(s,i,a)=>{let l=`${s}\0${i}`;n.has(l)||r.length>=24||(n.add(l),r.push({path:s,reason:i,...a?{detail:a}:{}}))};for(let s of t)JO.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||JO.has(s.skipReason)&&o(s.path,s.skipReason);return r}var JO,YO=p(()=>{"use strict";bd();JO=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"])});import zO from"node:path";function A4(e,t){return Ls(e,t)}function XO(e,t=Date.now()){let r=new Set,n=new Set;for(let o of e){for(let s of Ac(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let l=F(zO.join(Di(o,s.id),"workers",B(a),"worker.json"),void 0);if(!l?.worktreePath)continue;let c=zO.resolve(l.worktreePath);A4(l,t)&&(i=!0,r.add(c))}i&&n.add(`${o}\0${s.id}`)}for(let s of gO(o))n.add(s)}return{activeWorktreePaths:r,liveRunKeys:n}}function QO(e,t,r,n){return r?n.has(`${t}\0${r}`):!1}var Oy=p(()=>{"use strict";Y();Et();Ms();hd();M()});import{existsSync as ZO,readdirSync as eT,statSync as P4}from"node:fs";import tT from"node:path";function I4(e,t){try{let r=P4(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function O4(e,t){let r=tT.join(e,"runs",t,"run.json");return ZO(r)?F(r,null):null}function rT(e){try{return eT(e).length===0}catch{return!1}}function nT(e){let{harnessRoot:t,runId:r,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(QO(n,t,r,i.liveRunKeys)||!rT(n))return"run_still_active";let a=O4(t,r);return a&&!Or.has(a.status)&&!Qn(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function oT(e){if(!ZO(e.worktreesDir))return[];let t=[],r;try{r=eT(e.worktreesDir,{withFileTypes:!0})}catch{return[]}for(let n of r){if(!n.isDirectory())continue;let o=n.name;if(e.runIdFilter&&o!==e.runIdFilter)continue;let s=tT.join(e.worktreesDir,o);rT(s)&&t.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:I4(s,e.now)})}return t}var sT=p(()=>{"use strict";Oy();rn();M()});import{execFileSync as T4}from"node:child_process";import{existsSync as iT,readdirSync as N4,statSync as D4}from"node:fs";import M4 from"node:path";function B4(e,t=L4){if(!iT(e))return 0;try{let n=T4("du",["-sb",e],{encoding:"utf8",timeout:t,stdio:["ignore","pipe","ignore"]}).trim().split(/\s+/)[0],o=Number(n);return Number.isFinite(o)&&o>=0?o:null}catch{return null}}function Nr(e,t=5e4){if(!iT(e))return 0;let r=B4(e);if(r!==null)return r;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=N4(i)}catch{continue}for(let l of a){if(o++>t)return null;let c=M4.join(i,l),u;try{u=D4(c)}catch{continue}u.isDirectory()?s.push(c):n+=u.size}}return n}var L4,Va=p(()=>{"use strict";L4=2500});import{lstatSync as W4,readdirSync as U4}from"node:fs";function aT(e){try{let t=W4(e),r=typeof process.getuid=="function"?process.getuid():null,n=typeof process.getgid=="function"?process.getgid():null,o=r!==null&&(t.uid!==r||n!==null&&t.gid!==n);return{uid:t.uid,gid:t.gid,foreign:o}}catch{return null}}function lT(e,t=32){let r=aT(e);if(!r)return!1;if(r.foreign)return!0;try{let n=U4(e),o=0;for(let s of n){if(o>=t)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=aT(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}var cT=p(()=>{"use strict"});import kt from"node:path";function uT(e,t,r,n){let o=kt.resolve(e),s=`${kt.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=kt.relative(r,i);if(a.startsWith("..")||kt.isAbsolute(a))return"path_outside_harness";let l=a.split(kt.sep);return l.length<3||l[l.length-1]!==n||!o.startsWith(kt.resolve(t))?"path_outside_harness":null}function vd(e,t,r){return uT(e,t,r,"node_modules")}function Rd(e,t,r){return uT(e,t,r,".next")}function wd(e,t,r){let n=kt.resolve(e),o=kt.relative(r,n);return o.startsWith("..")||kt.isAbsolute(o)||o.split(kt.sep).length<3||!n.startsWith(kt.resolve(t))?"path_outside_harness":null}function dT(e,t,r){let n=kt.resolve(e);return vd(n,t,r)===null||Rd(n,t,r)===null||wd(n,t,r)===null}var Ty=p(()=>{"use strict"});import{spawnSync as F4}from"node:child_process";import pT from"node:path";function mT(){let e=(process.env.KYNVER_CLEANUP_PRIVILEGED??"auto").trim().toLowerCase();return e==="0"||e==="false"||e==="off"||e==="no"?"off":e==="1"||e==="true"||e==="force"||e==="yes"?"force":"auto"}function fT(e){let t=F4("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:t.status===0,stderr:`${t.stderr??""}${t.stdout??""}`.trim()}}function gT(e,t,r){if(!dT(e,t,r))return{ok:!1,error:"path is not an allowed harness generated cache"};let n=typeof process.getuid=="function"?process.getuid():null,o=typeof process.getgid=="function"?process.getgid():null;if(n===null||o===null)return{ok:!1,error:"privileged reclaim requires POSIX uid/gid"};let s=fT(["chown","-R",`${n}:${o}`,pT.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=fT(["rm","-rf",pT.resolve(e)]);return i.ok?{ok:!0,method:"sudo_rm"}:{ok:!1,error:s.stderr||i.stderr||"sudo -n failed (password required or not permitted)"}}var Ny,hT=p(()=>{"use strict";Ty();Ny="Root-owned harness caches require operator reclaim: configure passwordless sudo for chown/rm under ~/.kynver/harness/worktrees, or remove them as the harness owner with sudo available. More help: https://www.kynver.com/help."});import{existsSync as K4,rmSync as $4}from"node:fs";function H4(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function yT(e,t,r={}){if(!K4(e.path))return{executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!t)return{executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.harnessRoot,o=n?Qo(n):null,i=e.bytes??Nr(e.path)??void 0,a=r.removePath??$4,l=r.hasForeignOwnedEntry??lT;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(c){if(!H4(c)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let u=l(e.path),d=mT();if(!(d==="force"||d==="auto"&&u))return u?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; ${Ny}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let m=gT(e.path,n,o);if(m.ok&&m.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(m.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(g){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${g.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; privileged reclaim failed: ${m.error}; ${Ny}`}}}var kT=p(()=>{"use strict";Va();Et();cT();hT()});import{existsSync as Dy,rmSync as bT}from"node:fs";function My(e){let t=e.harnessRoot;return!t||!pO(e.path,t)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function Ly(e,t){let r=My(e);if(r)return r;let n=yT(e,t);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function vT(e,t){return Ly(e,t)}function RT(e,t){return Ly(e,t)}function wT(e,t){return Ly(e,t)}function ST(e,t){let r=My(e);if(r)return r;if(!Dy(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!t)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};try{let n=e.bytes??Nr(e.path);return bT(e.path,{recursive:!0,force:!0}),{...e,bytes:n,executed:!0,skipped:!1}}catch(n){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:n.message}}}function _T(e,t){let r=My(e);if(r)return r;if(!Dy(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!t)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.repo;try{let o=e.bytes??Nr(e.path);return n&&ce(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Dy(e.path)&&bT(e.path,{recursive:!0,force:!0}),{...e,bytes:o,executed:!0,skipped:!1}}catch(o){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:o.message}}}var xT=p(()=>{"use strict";we();Va();kT();Ms();Ty()});import{existsSync as Sd,readdirSync as _d,statSync as j4}from"node:fs";import Jt from"node:path";function By(e,t){try{let r=j4(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function ET(e,t){let r=Jt.relative(t,e);return r===""||!r.startsWith("..")&&!Jt.isAbsolute(r)}function CT(e,t,r,n){let o=[];for(let s of _y){if(s===".next")continue;let i=Jt.join(e,s);if(!Sd(i))continue;let a=Jt.resolve(i);r.has(a)||ET(a,t.harnessRoot)&&(r.add(a),o.push({kind:"remove_build_cache",path:a,bytes:null,runId:n.runId,worker:n.worker,repo:n.repo,ageMs:By(a,t.now)}))}return o}function AT(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||t.push(...CT(n.worktreePath,e,r,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!Sd(e.worktreesDir))return t;for(let n of _d(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Jt.join(e.worktreesDir,n.name);for(let s of _d(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=Jt.join(o,s.name);t.push(...CT(i,e,r,{runId:n.name,worker:s.name}))}}return t}function PT(e){let t=e.worktreesAgeMs>0||e.includeOrphans,r=e.includeOrphans;if(!t&&!r)return[];let n=[],o=new Set;if(t)for(let i of e.index.values()){if(e.runIdFilter&&i.runId!==e.runIdFilter)continue;let a=i.worktreePath;Sd(a)&&(o.has(a)||(o.add(a),n.push({kind:"remove_worktree",path:a,bytes:null,runId:i.runId,worker:i.workerName,repo:i.run.repo,ageMs:By(a,e.now)})))}if(!r||!Sd(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(Jt.resolve(i.worktreePath));for(let i of _d(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=Jt.join(e.worktreesDir,i.name),l;try{l=_d(a,{withFileTypes:!0})}catch{continue}for(let c of l){if(!c.isDirectory())continue;let u=Jt.resolve(Jt.join(a,c.name));o.has(u)||s.has(u)||ET(u,e.harnessRoot)&&(o.add(u),n.push({kind:"remove_worktree",path:u,bytes:null,runId:i.name,worker:c.name,ageMs:By(u,e.now)}))}}return n}var IT=p(()=>{"use strict";xy()});import{existsSync as NT,readdirSync as OT,statSync as V4}from"node:fs";import Bs from"node:path";function J4(e,t){try{let r=V4(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function q4(e,t){let r=Bs.relative(t,e);return r===""||!r.startsWith("..")&&!Bs.isAbsolute(r)}function Y4(e,t,r,n,o,s){if(!NT(n))return;let i=Bs.resolve(n);t.has(i)||q4(i,r.harnessRoot)&&(t.add(i),e.push({kind:o,path:i,bytes:null,harnessRoot:r.harnessRoot,runId:s.runId,worker:s.worker,repo:s.repo,ageMs:J4(i,r.now)}))}function TT(e,t,r,n,o){for(let s of G4)Y4(e,t,r,Bs.join(n,s.dirName),s.kind,o)}function DT(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||TT(t,r,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!NT(e.worktreesDir))return t;for(let n of OT(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=Bs.join(e.worktreesDir,n.name),s;try{s=OT(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=Bs.join(o,i.name);TT(t,r,e,a,{runId:n.name,worker:i.name})}}return t}var G4,MT=p(()=>{"use strict";G4=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}]});import{existsSync as LT,statSync as z4}from"node:fs";import qt from"node:path";function X4(e,t){try{let r=z4(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function Q4(e){let t=[],r=null;for(let n of e.split(`
|
|
183
|
+
`)){if(!n.trim())continue;let[o,...s]=n.split(" "),i=s.join(" ");if(o==="worktree"){r&&t.push(r),r={path:i};continue}r&&(o==="branch"&&(r.branch=i),o==="HEAD"&&(r.head=i),o==="bare"&&(r.bare=!0))}return r&&t.push(r),t}function Z4(e,t){let r=qt.relative(qt.resolve(t),qt.resolve(e));return r!==""&&!r.startsWith("..")&&!qt.isAbsolute(r)}function BT(e){if(!e.includeOrphans||!LT(e.worktreesDir))return[];let t=new Set;for(let s of e.index.values())s.run.repo&&t.add(qt.resolve(s.run.repo));let r=new Set;for(let s of e.index.values())r.add(qt.resolve(s.worktreePath));let n=[],o=new Set;for(let s of t){let i=0,a;try{a=ce(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let l=Q4(a);for(let c of l){if(i>=eX)break;let u=qt.resolve(c.path);if(u===qt.resolve(s)||!Z4(u,e.worktreesDir)||r.has(u)||o.has(u)||!LT(u))continue;let f=qt.relative(e.worktreesDir,u).split(qt.sep),m=f[0],g=f[1]??"unknown";o.add(u),i+=1,n.push({kind:"remove_worktree",path:u,bytes:null,runId:m,worker:g,repo:s,ageMs:X4(u,e.now)})}}return n}var eX,WT=p(()=>{"use strict";we();eX=200});import Ga from"node:path";function UT(e,t){let r=Ga.resolve(t),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?Ga.resolve(s.harnessRoot):null;i&&i!==r||n.set(o,s)}return n}function FT(e){let t=new Map;for(let r of Ac(e))for(let n of Object.keys(r.workers||{})){let o=Ga.join(Di(e,r.id),"workers",B(n),"worker.json"),s=F(o,void 0);s?.worktreePath&&t.set(Ga.resolve(s.worktreePath),{harnessRoot:e,worktreePath:Ga.resolve(s.worktreePath),runId:r.id,workerName:n,run:r,worker:s})}return t}var KT=p(()=>{"use strict";Y();M()});function Ja(e){let t=process.env[e];return t==="1"||t==="true"||t==="yes"}function no(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)&&n>=0?n:t}function Uy(e={}){let t=e.execute===!0||e.execute!==!1&&Ja("KYNVER_CLEANUP_EXECUTE"),r=e.finalizeStaleRuns!==!1&&!Ja("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??no("KYNVER_CLEANUP_NODE_MODULES_AGE_MS",216e5),o=e.scanDependencyCaches??(e.nodeModulesAgeMs!==void 0||process.env.KYNVER_CLEANUP_NODE_MODULES_AGE_MS!=null),s=e.worktreesAgeMs??no("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??no("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??no("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),l=e.maxActionsPerSweep??no("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),c=e.includeOrphans===!0||Ja("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=Ja("KYNVER_CLEANUP_SCOPE_ALL")||process.env.KYNVER_CLEANUP_SCOPE==="all"?e.runIdFilter:e.runIdFilter??(process.env.KYNVER_CLEANUP_RUN_ID||void 0),f=e.accountBytes!==!1&&!Ja("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),m=no("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),g=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:f&&m>0?m:null,h=no("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),y=e.byteAccountingEntryCap??(Number.isFinite(h)&&h>0?Math.floor(h):2e3);return{execute:t,finalizeStaleRuns:r,scanDependencyCaches:o,nodeModulesAgeMs:n,worktreesAgeMs:s>0?s:0,terminalWorktreesAgeMs:i>=0?i:0,runDirectoriesAgeMs:a>=0?a:0,maxActionsPerSweep:Number.isFinite(l)&&l>0?Math.floor(l):120,includeOrphans:c,runIdFilter:d?String(d):void 0,accountBytes:f,storagePerRunEntryCap:g,byteAccountingEntryCap:y}}function VT(e){let t=process.env.KYNVER_CLEANUP_SCOPE==="all",r=Number(process.env.KYNVER_CLEANUP_WORKTREES_AGE_MS),n=t?Number.isFinite(r)&&r>0?r:6048e5:Number.isFinite(r)&&r>0?r:0;return Uy({runIdFilter:t?void 0:e,worktreesAgeMs:n,terminalWorktreesAgeMs:t?216e5:void 0,runDirectoriesAgeMs:t?36e5:void 0,includeOrphans:t?!0:void 0,finalizeStaleRuns:!0,accountBytes:!0,scanDependencyCaches:!0})}var GT=p(()=>{"use strict";bd()});import{existsSync as Fy,statSync as rX}from"node:fs";import oo from"node:path";function nX(e,t){let r=oo.relative(t,e);return r===""||!r.startsWith("..")&&!oo.isAbsolute(r)}function oX(e,t,r){if(!Fy(e))return!1;try{let n=t-rX(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<r}catch{return!1}}function Ky(e){if(!e.runId||!e.workerName)return!1;let t=e.now??Date.now(),r=e.heartbeatFreshMs??JT,n=oo.resolve(e.harnessRoot,"runs"),o=oo.resolve(n,e.runId,"workers",e.workerName);if(!nX(o,n))return!1;let s=F(oo.join(o,"worker.json"),void 0);return s&&Ls(s,t,r)?!0:s?!1:oX(oo.join(o,"heartbeat.jsonl"),t,r)}function qT(e){let t=e.now??Date.now(),r=e.heartbeatFreshMs??JT;if(!Fy(e.worktreePath))return null;if(e.runId&&e.workerName&&Ky(e))return"active_worker";let n=oo.join(e.worktreePath,".git");if(!Fy(n))return null;let o=ee(e.worktreePath,["status","--porcelain"]);if(o.status!==0)return"pr_or_unmerged_commits";let s=o.stdout.split(`
|
|
184
|
+
`).map(c=>c.trim()).filter(c=>c.length>0);if(yt(s).length>0)return"dirty_worktree";let i=ee(e.worktreePath,["rev-list","--count","@{u}..HEAD"]);if(i.status===0){let c=Number(i.stdout.trim());if(Number.isFinite(c)&&c>0)return"pr_or_unmerged_commits"}let a=ee(e.worktreePath,["rev-list","--count","origin/main..HEAD"]);if(a.status!==0)return i.status!==0?"pr_or_unmerged_commits":null;let l=Number(a.stdout.trim());return Number.isFinite(l)&&l>0?"pr_or_unmerged_commits":null}var JT,YT=p(()=>{"use strict";we();to();hd();M();JT=1800*1e3});import{existsSync as sX,readdirSync as zT,statSync as iX}from"node:fs";import aX from"node:path";function XT(e={}){let t=Ne(e.harnessRoot??dt()),r=Qo(t),n=e.now??Date.now(),o=new Date(n).toISOString();if(!sX(r))return{harnessRoot:t,worktreesDir:r,worktreesBytes:0,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o};let s=0,i=0,a=0,l=null,c;try{c=zT(r,{withFileTypes:!0})}catch{return{harnessRoot:t,worktreesDir:r,worktreesBytes:null,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o}}for(let u of c){if(!u.isDirectory())continue;i+=1;let d=aX.join(r,u.name);try{let f=iX(d);l=l===null?f.mtimeMs:Math.min(l,f.mtimeMs)}catch{}try{for(let f of zT(d,{withFileTypes:!0}))f.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let f=e.perRunEntryCap??5e4;if(f<=0)s=null;else{let m=Nr(d,f);m===null?s=null:s+=m}}}return{harnessRoot:t,worktreesDir:r,worktreesBytes:s,runCount:i,workerCount:a,oldestRunAt:l===null?null:new Date(l).toISOString(),scannedAt:o}}var QT=p(()=>{"use strict";Et();Va()});import{existsSync as lX}from"node:fs";import{homedir as cX}from"node:os";import ZT from"node:path";function $y(e,t,r){if(!r?.trim())return;let n=Ne(r.trim());e.has(n)||(e.add(n),t.push(n))}function dX(e){return e.scanWellKnown!=null?e.scanWellKnown:process.env.VITEST==="true"?!1:process.env.KYNVER_CLEANUP_SCAN_WELL_KNOWN!=="0"&&!["0","false","no"].includes((process.env.KYNVER_CLEANUP_SCAN_WELL_KNOWN??"").toLowerCase())}function eN(e={}){let t=new Set,r=[];$y(t,r,e.harnessRoot??dt());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])$y(t,r,o);if(dX(e))for(let o of uX){let s=ZT.resolve(o);!t.has(s)&&lX(s)&&$y(t,r,s)}return r}var uX,tN=p(()=>{"use strict";Et();uX=["/var/tmp/kynver-harness",ZT.join(cX(),".openclaw","harness")]});function pX(e){let t=process.env[e];return t==="1"||t==="true"||t==="yes"}function fX(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function rN(e={}){let t=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",r=fX("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=Br({...e,diskPath:t,diskMaxUsedPercent:e.diskMaxUsedPercent??r}),o=!n.ok||n.usedPercent>=r,s=process.env.KYNVER_CLEANUP_DISK_PRESSURE_FORCE?.trim().toLowerCase();return s==="none"||s==="off"||s==="0"?o=!1:(s==="pressured"||s==="on"||s==="1")&&(o=!0),{diskGate:n,pressured:o,maxUsedPercent:r}}function nN(e,t){if(!t.pressured)return e;let r=e.execute||!pX("KYNVER_CLEANUP_DRY_RUN_ON_PRESSURE");return{...e,execute:r,nodeModulesAgeMs:0,runIdFilter:void 0,includeOrphans:!0,terminalWorktreesAgeMs:0,runDirectoriesAgeMs:0,worktreesAgeMs:e.worktreesAgeMs>0?e.worktreesAgeMs:6048e5,diskPressure:!0,diskGate:t.diskGate}}var oN=p(()=>{"use strict";yi();bd()});import{unlinkSync as mX}from"node:fs";function xd(e){let t=process.env[e];return t==="1"||t==="true"||t==="yes"}function sN(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function gX(e,t,r){return e.length===0?[]:r?[...e]:e.length<=t?[]:e.slice(t)}function iN(e={}){let t=e.execute===!0||xd("KYNVER_WSL_CRASH_DUMP_EXECUTE")||xd("KYNVER_CLEANUP_EXECUTE"),r=e.purgeAll===!0||xd("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),n=Math.max(0,e.keepNewest??sN("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",r?0:1)),o=To({forceWsl:e.forceWsl});if(!o?.path)return{observation:o,execute:t,keepNewest:n,removed:[],removedBytes:0,skipped:o?.probeError?[{path:o.path??"(unresolved)",reason:o.probeError}]:[]};let s=gX(o.dumps,n,r),i=[],a=[],l=0;for(let c of s){if(!t){a.push({path:c.path,reason:"dry_run"});continue}try{mX(c.path),i.push({path:c.path,bytes:c.bytes,name:c.name}),l+=c.bytes}catch(u){a.push({path:c.path,reason:u.message})}}return{observation:o,execute:t,keepNewest:n,removed:i,removedBytes:l,skipped:a}}function aN(e){return e?xd("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>sN("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}var lN=p(()=>{"use strict";jl()});function bt(e,t){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let r=t?`: ${t}`:"";console.error(`[kynver cleanup] ${e}${r}`)}var cN=p(()=>{"use strict"});var Cd,uN=p(()=>{"use strict";we();Cd=class{aheadOfMain=new Map;countAheadOfMain(t,r="origin/main"){let n=`${t}\0${r}`;if(this.aheadOfMain.has(n))return this.aheadOfMain.get(n)??null;let o=ee(t,["rev-list","--count",`${r}..HEAD`]);if(o.status!==0)return this.aheadOfMain.set(n,null),null;let s=Number(o.stdout.trim()),i=Number.isFinite(s)?s:null;return this.aheadOfMain.set(n,i),i}}});import{spawnSync as hX}from"node:child_process";import{existsSync as yX}from"node:fs";import kX from"node:path";function vX(e,t){if(!yX(kX.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let r=hX("git",t,{windowsHide:!0,cwd:e,encoding:"utf8",timeout:bX}),n=r.error?.message?.includes("ETIMEDOUT")===!0;return{status:n?null:r.status,stdout:r.stdout||"",stderr:r.stderr||"",error:n?"git_timeout":r.error?r.error.message:null}}catch(r){return{status:null,stdout:"",stderr:"",error:r.message}}}function dN(e){let t=vX(e,["status","--short"]);return t.error==="not_a_git_repo"?[]:t.error==="git_timeout"||t.status!==0?null:t.stdout.split(`
|
|
185
|
+
`).map(r=>r.trim()).filter(Boolean)}var bX,pN=p(()=>{"use strict";bX=5e3});var Ed,fN=p(()=>{"use strict";pN();Ed=class{cache=new Map;porcelain(t){let r=t,n=this.cache.get(r);if(n!==void 0)return n;let o=dN(r)??[];return this.cache.set(r,o),o}}});var Ad,mN=p(()=>{"use strict";rn();Ad=class{cache=new Map;derive(t){let r=this.cache.get(t.id);if(r!==void 0)return r;let n=Qn(t);return this.cache.set(t.id,n),n}}});function RX(e){let t={};for(let r of e)t[r.kind]=(t[r.kind]??0)+1;return t}function gN(e,t={}){let r=t.maxSampleActions??12,n=t.maxSampleSkips??8;return{harnessRoot:e.harnessRoot,scanRoots:e.scanRoots,dryRun:e.dryRun,execute:e.execute,scannedAt:e.scannedAt,finalizedRuns:e.finalizedRuns.length,actionCount:e.actions.length,actionKinds:RX(e.actions),totals:e.totals,...e.storage?{storage:e.storage}:{},...e.preservedLivePaths?.length?{preservedLivePaths:e.preservedLivePaths}:{},...e.removedRunDirectories!=null?{removedRunDirectories:e.removedRunDirectories}:{},sampleActions:e.actions.slice(0,r).map(o=>({kind:o.kind,path:o.path,...o.skipReason?{skipReason:o.skipReason}:{},...o.bytes!=null?{bytes:o.bytes}:{},...o.runId?{runId:o.runId}:{},...o.worker?{worker:o.worker}:{}})),sampleSkips:e.skips.slice(0,n)}}var hN=p(()=>{"use strict"});import vt from"node:path";function wX(e={}){let t=e.harnessRoot?Ne(e.harnessRoot):dt(),r=eN({harnessRoot:t}),n=e.now??Date.now();return{harnessRoot:t,scanRoots:r,now:n}}function SX(e){return typeof e=="string"?{reason:e}:e}function Ws(e,t,r,n){e.push({path:t,reason:r,...n?{detail:n}:{}})}function Pd(e,t,r){return!t||e.bytes!=null?e:{...e,bytes:Nr(e.path,r)}}function yN(e,t){let r={};for(let n of t)r[n.reason]=(r[n.reason]??0)+1;for(let n of e)n.skipReason&&(r[n.skipReason]=(r[n.skipReason]??0)+1);return r}function _X(e,t){return e.kind==="remove_next_cache"?RT(e,t):vT(e,t)}function xX(e,t,r){return e.kind==="remove_next_cache"?Rd(e.path,t,r):vd(e.path,t,r)}function CX(e){let t=new Map;for(let r of e)for(let[n,o]of FT(r))t.set(n,o);return t}function kN(e,t){return e.runId&&e.worker?vt.join(t,e.runId,e.worker):vt.resolve(e.path,"..")}function bN(e){return e.indexed?!1:Ky({harnessRoot:e.harnessRoot,runId:e.candidate.runId,workerName:e.candidate.worker,now:e.now})}function EX(e={}){let t=Uy(e),r=rN();t=nN(t,r);let n=wX(e);bt("scan",`${n.scanRoots.length} harness root(s)`);let o=XO(n.scanRoots,n.now),s=t.finalizeStaleRuns?Fa().map(A=>({runId:A.runId,from:A.from,to:A.to})):[];s.length>0&&bt("finalize",`${s.length} stale run(s) marked terminal`),bt("index","building worktree index");let i=CX(n.scanRoots);bt("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new Ad,gitStatusCache:new Ed,gitRevCache:new Cd},l=[],c=[],u=new Set,d=t.maxActionsPerSweep,f=()=>c.length>=d;for(let A of n.scanRoots){if(f())break;bt("root",A);let O=vt.join(A,"worktrees"),W=UT(i,A),D={harnessRoot:A,worktreesDir:O,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter,index:W,now:n.now},G=t.scanDependencyCaches?DT(D):[];bt("dependency",t.scanDependencyCaches?`${G.length} cache candidate(s) at ${A}`:"skipped (worktree-only sweep)");let Q=0;for(let x of G){if(f())break;Q+=1,Q%50===0&&bt("dependency",`${Q}/${G.length} evaluated`);let T=vt.resolve(x.path);if(u.has(T))continue;u.add(T);let U={...x,path:T},te=xX(U,A,O);if(te){Ws(l,U.path,te),c.push({...U,executed:!1,skipped:!0,skipReason:te});continue}let oe=kN(U,O),ge=W.get(vt.resolve(oe))??null,Ae=bN({candidate:U,indexed:ge,harnessRoot:A,now:n.now}),Z=Iy({indexed:ge,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:U.ageMs,worktreePath:oe,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:Ae,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(Z){Ws(l,U.path,Z),c.push({...U,executed:!1,skipped:!0,skipReason:Z});continue}c.push(_X(Pd(U,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(t.scanDependencyCaches)for(let x of AT(D)){if(f())break;let T=vt.resolve(x.path);if(u.has(T))continue;u.add(T);let U={...x,path:T},te=wd(U.path,A,O);if(te){Ws(l,U.path,te),c.push({...U,executed:!1,skipped:!0,skipReason:te});continue}let oe=kN(U,O),ge=W.get(vt.resolve(oe))??null,Ae=bN({candidate:U,indexed:ge,harnessRoot:A,now:n.now}),Z=VO({indexed:ge,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:U.ageMs,worktreePath:oe,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:Ae,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(Z){Ws(l,U.path,Z),c.push({...U,executed:!1,skipped:!0,skipReason:Z});continue}c.push(wT(Pd(U,t.accountBytes,t.byteAccountingEntryCap),t.execute))}let H=[...PT(D),...BT(D)];bt("worktrees",`${H.length} candidate(s) at ${A}`);let E=new Set,V=0;for(let x of H){if(f())break;V+=1,V%50===0&&bt("worktrees",`${V}/${H.length} evaluated`);let T=vt.resolve(x.path);if(E.has(T))continue;E.add(T);let U={...x,path:T},te=W.get(vt.resolve(U.path))??null,oe=te?null:qT({worktreePath:U.path,harnessRoot:A,runId:U.runId,workerName:U.worker,now:n.now}),ge=jO({indexed:te,worktreePath:vt.resolve(U.path),includeOrphans:t.includeOrphans,worktreesAgeMs:t.worktreesAgeMs,terminalWorktreesAgeMs:t.terminalWorktreesAgeMs,ageMs:U.ageMs,orphanSafety:oe,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:A,writeSalvageEvidence:t.execute});if(ge){let{reason:Ae,detail:Z}=SX(ge);Ws(l,U.path,Ae,Z),c.push({...U,executed:!1,skipped:!0,skipReason:Ae});continue}c.push(_T(Pd(U,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(!f()&&t.runDirectoriesAgeMs>=0)for(let x of oT({harnessRoot:A,worktreesDir:O,runDirectoriesAgeMs:t.runDirectoriesAgeMs,runIdFilter:t.runIdFilter,activeGuards:o,now:n.now})){if(f())break;let T=vt.resolve(x.path);if(u.has(T))continue;u.add(T);let U={...x,path:T},te=U.runId??vt.basename(T),oe=nT({harnessRoot:A,runId:te,runPath:T,ageMs:U.ageMs,runDirectoriesAgeMs:t.runDirectoriesAgeMs,activeGuards:o});if(oe){Ws(l,U.path,oe),c.push({...U,executed:!1,skipped:!0,skipReason:oe});continue}c.push(ST(Pd(U,t.accountBytes,t.byteAccountingEntryCap),t.execute))}}let m=0,g=0,h=0,y=0,v=0,k=0;for(let A of c)A.bytes&&(m+=A.bytes),!A.skipped&&!A.executed&&A.bytes&&(h+=A.bytes),A.executed?(v+=1,y+=A.bytes??0,A.kind==="remove_run_directory"&&(g+=1)):A.skipped&&(k+=1,A.skipReason==="dry_run"&&A.bytes&&(h+=A.bytes));let b=t.accountBytes?XT({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:t.storagePerRunEntryCap}):void 0,_=To(),S=t.execute&&aN(_),R=S?iN({execute:!0}):null,w=_?{observed:!0,execute:S,dumpCount:_.dumpCount,totalBytes:_.totalBytes,removedCount:R?.removed.length??0,removedBytes:R?.removedBytes??0,executables:_.executables,path:_.path,reason:_.reason}:void 0;R&&R.removed.length>0&&(y+=R.removedBytes,v+=R.removed.length,bt("wsl-crashes",`removed ${R.removed.length} dump(s), ${R.removedBytes} bytes`)),bt("complete",`${c.length} action(s), ${k} skipped, ${v} removed`);let L=qO(c,l),N=gN({harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!t.execute,execute:t.execute,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,diskPressure:t.diskPressure,diskGate:t.diskGate?{ok:t.diskGate.ok,path:t.diskGate.path,freeBytes:t.diskGate.freeBytes,usedPercent:t.diskGate.usedPercent,reason:t.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:c,skips:l,totals:{candidateBytes:m,reclaimableBytes:h,removedBytes:y,removedPaths:v,skippedPaths:k,skipReasons:yN(c,l)},...b?{storage:b}:{},...L.length>0?{preservedLivePaths:L}:{},...g>0?{removedRunDirectories:g}:{},...w?{wslCrashDumps:w}:{}});return{harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!t.execute,execute:t.execute,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,diskPressure:t.diskPressure,diskGate:t.diskGate?{ok:t.diskGate.ok,path:t.diskGate.path,freeBytes:t.diskGate.freeBytes,usedPercent:t.diskGate.usedPercent,reason:t.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:c,skips:l,totals:{candidateBytes:m,reclaimableBytes:h,removedBytes:y,removedPaths:v,skippedPaths:k,skipReasons:yN(c,l)},...b?{storage:b}:{},...L.length>0?{preservedLivePaths:L}:{},...g>0?{removedRunDirectories:g}:{},...w?{wslCrashDumps:w}:{},compactSummary:N}}function vN(e){let t=VT(e);return EX({execute:t.execute,finalizeStaleRuns:t.finalizeStaleRuns,accountBytes:t.accountBytes,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter})}function RN(){return process.env.KYNVER_PIPELINE_CLEANUP!=="0"}var wN=p(()=>{"use strict";Et();GO();YO();sT();xT();IT();MT();WT();KT();rn();Va();GT();YT();QT();tN();Oy();oN();lN();jl();cN();uN();fN();mN();hN()});function SN(e){let t=e.trim().split("-")[0]?.split("+")[0];if(!t)return null;let r=t.split(".");if(r.length<1||r.length>3)return null;let n=r.map(o=>Number.parseInt(o,10));if(n.some(o=>!Number.isFinite(o)||o<0))return null;for(;n.length<3;)n.push(0);return[n[0],n[1],n[2]]}function Id(e,t){let r=SN(e),n=SN(t);if(!r||!n)return 0;for(let o=0;o<3;o+=1){if(r[o]>n[o])return 1;if(r[o]<n[o])return-1}return 0}var AX,JPe,Hy=p(()=>{"use strict";mi();AX={"@kynver-app/runtime":"0.1.83","@kynver-app/openclaw-agent-os":"0.1.43","@kynver-app/mcp-agent-os":"0.3.34"},JPe=Object.keys(AX)});import{readFile as PX}from"node:fs/promises";import{homedir as IX}from"node:os";import an from"node:path";function Us(e){let t=e?.trim();return t||null}function TX(e){return[...new Set(e.filter(t=>!!t))]}function _N(){let e=IX(),t=Us(process.env.KYNVER_OPENCLAW_NPM_ROOT)??Us(process.env.OPENCLAW_NPM_ROOT)??an.join(e,".openclaw","npm"),r=Us(process.env.KYNVER_NPM_GLOBAL_ROOT)??Us(process.env.KYNVER_NPM_GLOBAL_MODULES_ROOT)??(Us(process.env.NPM_CONFIG_PREFIX)?an.join(Us(process.env.NPM_CONFIG_PREFIX),"lib","node_modules"):an.join(e,".npm-global","lib","node_modules"));return TX([an.join(t,"lib","node_modules"),an.join(t,"node_modules"),r.endsWith("node_modules")?r:an.join(r,"lib","node_modules")])}async function NX(e){try{let t=JSON.parse(await PX(e,"utf8"));return typeof t.version=="string"&&t.version.trim()?t.version.trim():null}catch{return null}}function xN(){return _N().map(e=>an.join(e,"@kynver-app"))}function jy(e){let t=_N(),r=new Set,n=[];for(let o of t){let s=an.join(o,e,"package.json");r.has(s)||(r.add(s),n.push(s))}return n}async function CN(e=new Date().toISOString()){let t={};for(let r of OX){let n=null;for(let o of jy(r)){let s=await NX(o);s&&(!n||Id(s,n.version)>0)&&(n={version:s,path:o})}n&&(t[r]={version:n.version,observedAt:e,path:n.path})}return t}var OX,Vy=p(()=>{"use strict";Hy();OX=["@kynver-app/runtime","@kynver-app/openclaw-agent-os","@kynver-app/mcp-agent-os"]});import{spawnSync as DX}from"node:child_process";var MX,LX,EN,AN=p(()=>{"use strict";MX=1e4,LX=4*1024*1024,EN=(e,t,r)=>{try{let n=DX(e,t,{windowsHide:!0,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r?.timeoutMs??MX,maxBuffer:LX});return{ok:n.status===0,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:""}}catch(n){return{ok:!1,stdout:"",stderr:n instanceof Error?n.message:String(n)}}}});function Od(e,t,r){return`${e} ${t} ${r}`}function Gy(e){let t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return null;let r=e.slice(0,t),n=e.slice(t+1);return!/^[^/\s]+\/[^/\s]+$/.test(r)||!/^[0-9a-f]{7,40}$/i.test(n)?null:{repo:r,sha:n}}function PN(e){let t=e.trim().match(/[/:]([^/]+\/[^/]+)\/(?:pull|pulls|merge_requests|pull-requests)\/(\d+)/i);if(!t)return null;let r=Number(t[2]);return!Number.isFinite(r)||r<=0?null:{repo:t[1],number:r}}var Td=p(()=>{"use strict"});function Yy(){return Date.now()<Jy}function $X(e){let t=`${e.stdout}
|
|
186
|
+
${e.stderr}`.toLowerCase();return t.includes("api rate limit exceeded")||t.includes("rate limit exceeded")||t.includes("secondary rate limit")}function IN(e){$X(e)&&(Jy=Math.max(Jy,Date.now()+KX))}function qy(e,t){if(Yy())return null;let r=e("gh",["api",...t]);if(!r.ok||!r.stdout.trim())return IN(r),null;try{return JSON.parse(r.stdout)}catch{return null}}function HX(e,t,r,n){if(Yy())return null;let o=e("gh",["pr","view",String(r),"--repo",t,"--json",n.join(",")]);if(!o.ok||!o.stdout.trim())return IN(o),null;try{return JSON.parse(o.stdout)}catch{return null}}function zy(e){return Yy()?!1:process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()?!0:e("gh",["auth","token"]).ok}function Fs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function jX(e){return Array.isArray(e)?e.map(t=>Fs(t)).filter(t=>t!==null).slice(0,WX).map(t=>({context:t.context??null,state:t.state??null,target_url:t.target_url??null,description:t.description??null})):[]}function VX(e,t,r){let n=qy(e,[`repos/${t}/commits/${r}/status`]);return n?{state:n.state??null,statuses:jX(n.statuses)}:null}var BX,WX,UX,FX,KX,Jy,ON,TN,NN,DN=p(()=>{"use strict";Td();BX=8e3,WX=30,UX=100,FX=400,KX=3600*1e3,Jy=0;ON={provider:"github",kind:"pr_snapshot",version:"2",isAvailable:zy,collect(e,t){let r=PN(e);if(!r)return null;let n=HX(t,r.repo,r.number,["url","title","body","author","state","isDraft","mergedAt","mergeCommit","mergeable","headRefName","headRefOid","headRepositoryOwner","statusCheckRollup","files"]);if(!n)return null;let o=Fs(n.author),s=Fs(n.mergeCommit),i=Fs(n.headRepositoryOwner),a=typeof n.body=="string"?n.body.slice(0,BX):null,l=Array.isArray(n.statusCheckRollup)?n.statusCheckRollup.map(u=>Fs(u)).filter(u=>u!==null).slice(0,UX).map(u=>({name:u.name??u.context??null,status:u.status??u.state??null,conclusion:u.conclusion??null,workflowName:u.workflowName??null,detailsUrl:u.detailsUrl??null})):[],c=Array.isArray(n.files)?n.files.map(u=>Fs(u)).map(u=>typeof u?.path=="string"?u.path.trim():"").filter(Boolean).slice(0,FX):[];return{pull:{html_url:n.url??null,title:n.title??null,body:a,user:{login:o?.login??null},state:typeof n.state=="string"?n.state.toLowerCase():null,draft:n.isDraft??null,merged:!!n.mergedAt,merged_at:n.mergedAt??null,merge_commit_sha:s?.oid??null,mergeable:null,mergeable_state:n.mergeable??null,head:{sha:n.headRefOid??null,ref:n.headRefName??null,repo:{owner:{login:i?.login??null}}}},checkRuns:l,combinedStatus:{state:null,statuses:[]},changedFiles:c}}},TN={provider:"github",kind:"commit_status",version:"1",isAvailable:zy,collect(e,t){let r=Gy(e);return r?VX(t,r.repo,r.sha):null}},NN={provider:"github",kind:"branch_reachability",version:"1",isAvailable:zy,collect(e,t){let r=Gy(e);if(!r)return null;let n=qy(t,[`repos/${r.repo}`]),o=typeof n?.default_branch=="string"&&n.default_branch.trim()?n.default_branch.trim():null;if(!o)return null;let s=qy(t,[`repos/${r.repo}/compare/${encodeURIComponent(o)}...${r.sha}`]);if(!s)return null;let i=typeof s.status=="string"?s.status:null;return{defaultBranch:o,compareStatus:i,reachable:i==="identical"||i==="behind"}}}});function Xy(e){Qy.some(t=>t.provider===e.provider&&t.kind===e.kind)||Qy.push(e)}function MN(e,t){return Qy.find(r=>r.provider===e&&r.kind===t)??null}function LN(){Xy(ON),Xy(TN),Xy(NN)}var Qy,BN=p(()=>{"use strict";DN();Qy=[]});function WN(e,t={}){LN();let r=t.run??EN,n=t.now??(()=>new Date),o=t.maxSubjects??GX,s=Date.now()+(t.deadlineMs??JX),i=new Set,a=e.filter(m=>{let g=Od(m.provider,m.kind,m.subject);return i.has(g)?!1:(i.add(g),!0)}),l=a.length>0?Math.floor(n().getTime()/6e4)%a.length:0,u=a.map((m,g)=>a[(l+g)%a.length]).slice(0,o),d={attempted:0,collected:0,cached:0,items:[],skipped:[]},f=new Map;for(let m of u){let g=Od(m.provider,m.kind,m.subject),h=n(),y=t.cache?.get(g,h)??null;if(y){d.cached+=1,d.collected+=1,d.items.push(y);continue}if(Date.now()>s){d.skipped.push({...m,reason:"budget_exhausted"});continue}let v=MN(m.provider,m.kind);if(!v){d.skipped.push({...m,reason:"no_recipe"});continue}let k=`${v.provider} ${v.kind}`,b=f.get(k);if(b===void 0&&(b=v.isAvailable(r),f.set(k,b)),!b){d.skipped.push({...m,reason:"provider_unavailable"});continue}if(t.cache?.reserve?.(m,g,n())===!1){d.skipped.push({...m,reason:"budget_exhausted"});continue}d.attempted+=1;let _=v.collect(m.subject,r);if(_==null){d.skipped.push({...m,reason:"collect_failed"});continue}d.collected+=1;let S={provider:m.provider,kind:m.kind,subject:m.subject,payload:_,observedAt:n().toISOString(),collectorVersion:v.version};d.items.push(S),t.cache?.set(g,S,n())}return d}var GX,JX,UN=p(()=>{"use strict";AN();BN();Td();GX=1,JX=25e3});import FN from"node:path";function KN(e){return FN.join(j(e),qX)}function XX(e){return FN.join(j(e),YX)}function $N(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object"||Array.isArray(r))continue;let n=r,o=typeof n.provider=="string"?n.provider.trim():"",s=typeof n.kind=="string"?n.kind.trim():"",i=typeof n.subject=="string"?n.subject.trim():"";!o||!s||!i||t.push({provider:o,kind:s,subject:i})}return t}function HN(e){let t=F(KN(e),null);return $N(t?.wanted)}function jN(e,t){be(KN(e),{savedAt:new Date().toISOString(),wanted:t})}function VN(e,t={}){let r=t.ttlMs??zX,n=XX(e),s={...F(n,null)?.items??{}},i=!1;return{get(l,c){let u=s[l];if(!u)return null;let d=Date.parse(u.observedAt);return!Number.isFinite(d)||c.getTime()-d>r?(delete s[l],i=!0,null):u},set(l,c){s[l]=c,i=!0},flush(){i&&(be(n,{savedAt:new Date().toISOString(),items:s}),i=!1)}}}function GN(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.providerEvidenceWanted;return Array.isArray(t)?$N(t):null}var qX,YX,zX,Zy=p(()=>{"use strict";Y();M();Td();qX="provider-evidence-wanted.json",YX="provider-evidence-cache.json",zX=600*1e3});import QX from"node:path";function ek(e,t){let r=process.env[e];if(!r)return t;let n=Number.parseInt(r,10);return Number.isFinite(n)&&n>=0?n:t}function n3(){return QX.join(he().harnessRoot,ZX)}function o3(e){let t=e.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),r=e==="github"?t3:r3;return ek(`KYNVER_PROVIDER_EVIDENCE_${t}_PER_MINUTE`,ek("KYNVER_PROVIDER_EVIDENCE_LIVE_COLLECTS_PER_MINUTE",r))}function JN(){return ek("KYNVER_PROVIDER_EVIDENCE_SHARED_CACHE_TTL_MS",e3)}function s3(e){return Math.floor(e.getTime()/6e4)*6e4}function i3(e){return`${e.provider}:${e.kind}`}function qN(e,t={}){let r=VN(e,{ttlMs:t.ttlMs??JN()}),n=t.file??n3(),o=F(n,null),s={...o?.items??{}},i={...o?.budget??{}},a=t.ttlMs??JN(),l=!1;return{get(u,d){let f=r.get(u,d);if(f)return f;let m=s[u];if(!m)return null;let g=Date.parse(m.observedAt);return!Number.isFinite(g)||d.getTime()-g>a?(delete s[u],l=!0,null):(r.set(u,m,d),m)},set(u,d,f){r.set(u,d,f),s[u]=d,l=!0},reserve(u,d,f){let m=o3(u.provider);if(m===0)return!0;let g=i3(u),h=s3(f),y=i[g];return!y||y.windowStartMs!==h?(i[g]={windowStartMs:h,used:1},l=!0,!0):y.used>=m?!1:(y.used+=1,l=!0,!0)},flush(){r.flush(),l&&(be(n,{savedAt:new Date().toISOString(),items:s,budget:i}),l=!1)}}}var ZX,e3,t3,r3,YN=p(()=>{"use strict";Y();M();Zy();ZX="provider-evidence-shared-cache.json",e3=6e4,t3=1,r3=1});function zN(e){let t=N_(),r=br(e?.env??process.env),n=(e?.now??(()=>new Date))().getTime(),o={};if(r.flags.dispatchReceipts!=="off"){Object.assign(o,oP());let s=nP({nowMs:n,hasLiveWorker:e?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,r.flags.dispatchReceipts==="enforce"&&Object.assign(o,_O())}return r.flags.planOutbox!=="off"&&Object.assign(o,oI()),r.flags.admission!=="off"&&(Object.assign(o,lP()),r.flags.admission==="enforce"&&Object.assign(o,pP())),(r.flags.keeper!=="off"||r.flags.meshLease!=="off"||r.flags.quota!=="off")&&Object.assign(o,j_()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:t.state,schemaVersion:t.schemaVersion,recovered:t.recovered,unavailableClass:t.reason?t.reason.split(":")[0]??null:null,flags:r.flags,flagSources:r.sources,flagWarningCount:r.warnings.length,divergenceCounters:o}}var XN=p(()=>{"use strict";Jr();ls();_s();wy();La();zn();Cs();Gi()});import{createHash as QN}from"node:crypto";import{access as a3,mkdir as TIe,readFile as ZN,rename as NIe,writeFile as DIe}from"node:fs/promises";import{constants as l3}from"node:fs";import{homedir as tk}from"node:os";import ze from"node:path";function d3(){return process.env.KYNVER_MCP_UPDATE_INVENTORY_FILE?.trim()||ze.join(tk(),".kynver","mcp-installations.json")}function p3(e){return e==="openclaw"?process.env.KYNVER_OPENCLAW_NPM_ROOT?.trim()||ze.join(tk(),".openclaw","npm"):process.env.KYNVER_NPM_GLOBAL_ROOT?.trim()||process.env.NPM_CONFIG_PREFIX?.trim()||ze.join(tk(),".npm-global")}function f3(e){let t=ze.resolve(e);if(ze.basename(t)!=="node_modules")return t;let r=ze.dirname(t);return ze.basename(r)==="lib"?ze.dirname(r):r}function m3(e,t){return[ze.join(e,"lib","node_modules",t,"package.json"),ze.join(e,"node_modules",t,"package.json")]}async function g3(e){try{return await a3(e,l3.R_OK),!0}catch{return!1}}async function rk(e=d3()){let t;try{t=JSON.parse(await ZN(e,"utf8"))}catch{return[]}if(t.version!==1||!Array.isArray(t.installations)||t.installations.length>100)throw new Error("invalid MCP installation inventory");return t.installations.map(r=>{if(!r||!u3.test(r.inventoryKey)||!c3.test(r.packageName)||!["kynver","openclaw"].includes(r.prefix))throw new Error("invalid adopted MCP installation");if(r.packageName.includes("..")||r.packageName.includes("%"))throw new Error("invalid adopted MCP package identity");if(r.connectionId&&r.connectionId.length>128)throw new Error("invalid connection identity");if(r.binName&&!/^[A-Za-z0-9._-]{1,80}$/.test(r.binName))throw new Error("invalid MCP bin name");let n=r.envAllowlist??[];if(!Array.isArray(n)||n.length>32||n.some(o=>!/^[A-Z][A-Z0-9_]{1,80}$/.test(o)))throw new Error("invalid MCP environment allow-list");return{...r,envAllowlist:[...new Set(n)],lifecycle:r.lifecycle??"runtime_stdio"}})}function h3(e,t,r){if(typeof e.bin=="string")return ze.join(r,e.bin);if(!e.bin||typeof e.bin!="object"||Array.isArray(e.bin))return null;let n=e.bin,o=t.binName??(Object.keys(n).length===1?Object.keys(n)[0]:void 0),s=o?n[o]:null;return typeof s=="string"&&!ze.isAbsolute(s)&&!s.split(/[\\/]/).includes("..")?ze.join(r,s):null}function y3(e){return QN("sha256").update(JSON.stringify({inventoryKey:e.inventoryKey,connectionId:e.connectionId,packageName:e.packageName,managerKind:e.managerKind,sourceKind:e.sourceKind,installedVersion:e.installedVersion,nodeVersion:e.nodeVersion,policyChannel:e.policyChannel,executionConfigDigest:e.executionConfigDigest,capabilities:[...e.capabilities].sort()})).digest("hex")}async function k3(e){let t=[];for(let r of e){let n=f3(p3(r.prefix)),o=(await Promise.all(m3(n,r.packageName).map(async m=>({candidate:m,ok:await g3(m)})))).find(m=>m.ok)?.candidate;if(!o)continue;let s=JSON.parse(await ZN(o,"utf8"));if(s.name!==r.packageName||typeof s.version!="string"||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(s.version))continue;let i=ze.dirname(o),a=h3(s,r,i),l=r.packageName==="@kynver-app/runtime",c=r.lifecycle??"runtime_stdio",u=QN("sha256").update(JSON.stringify({prefix:n,binName:r.binName??null,envAllowlist:[...r.envAllowlist??[]].sort(),lifecycle:c})).digest("hex"),d=l?[]:c==="runtime_stdio"&&a?["update","restart","rollback","verify_mcp"]:["update","rollback"],f={inventoryKey:r.inventoryKey,connectionId:r.connectionId??null,packageName:r.packageName,managerKind:"npm_global",sourceKind:"configured_stdio",installedVersion:s.version,nodeVersion:process.versions.node,policyChannel:"latest",executionConfigDigest:u,capabilities:d};t.push({report:{...f,displayName:r.displayName?.trim()||r.packageName,inventoryFingerprint:y3(f),capabilityExplanation:l?"Runtime self-update requires a supervisor-owned durable handoff and is not enabled by this adapter.":c==="runtime_stdio"&&a?"The authorized runtime can install, start, and verify this configured stdio package.":"The package can be installed, but its external supervisor must restart and verify it."},local:{prefix:n,packageJsonPath:o,packageDir:i,binPath:a,envAllowlist:r.envAllowlist??[],lifecycle:c}})}return t}async function e0(){return k3(await rk())}var c3,u3,nk=p(()=>{"use strict";c3=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/i,u3=/^[A-Za-z0-9._:-]{8,128}$/});import{createHash as b3,createHmac as v3,timingSafeEqual as R3}from"node:crypto";function ok(e){let t=e.trim().split(".");return t.length!==3||t[0]!=="krc1"||!t[1]||!t[2]?null:{tokenId:t[1],tokenHash:b3("sha256").update(`krc1.${t[1]}.${t[2]}`,"utf8").digest("hex")}}function t0(e,t,r){let n=ok(t);if(!n||e.algorithm!=="hmac-sha256-runner-v1"||e.keyId!==n.tokenId)return!1;let o=Date.parse(e.claims.expiresAt);if(e.claims.version!==1||e.claims.agentOsId!==r||!Number.isFinite(o)||o<=Date.now()||o>Date.now()+10*6e4||![null,"installing","restarting","verifying"].includes(e.claims.resumePhase))return!1;let s=v3("sha256",Buffer.from(n.tokenHash,"hex")).update(JSON.stringify(e.claims),"utf8").digest(),i=Buffer.from(e.signature,"base64url");return i.length===s.length&&R3(i,s)}var sk=p(()=>{"use strict"});import{createHash as w3}from"node:crypto";import{access as ik,mkdtemp as S3,readFile as i0,rm as _3}from"node:fs/promises";import{constants as ak}from"node:fs";import{tmpdir as x3}from"node:os";import Ks from"node:path";import{spawn as C3}from"node:child_process";import{Client as E3}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as A3}from"@modelcontextprotocol/sdk/client/stdio.js";function a0(){return"npm"}function n0(e,t){return Buffer.byteLength(e)>=r0?e:(e+t.toString("utf8")).slice(0,r0)}function I3(e){let t=process.env.KYNVER_MCP_UPDATE_NPM_CACHE?.trim(),r=t&&Ks.isAbsolute(t)?t:e,n={PATH:process.env.PATH,SystemRoot:process.env.SystemRoot,TEMP:process.env.TEMP,TMP:process.env.TMP,npm_config_registry:lk,npm_config_audit:"false",npm_config_fund:"false",npm_config_update_notifier:"false",npm_config_cache:r};return Object.fromEntries(Object.entries(n).filter(o=>typeof o[1]=="string"))}async function l0(e,t,r=ck,n){return new Promise((o,s)=>{let i,a;try{[i,a]=ae(e,t)}catch(m){s(m);return}let l=C3(i,a,{shell:!1,windowsHide:!0,detached:Re(),env:I3(n),stdio:["ignore","pipe","pipe"]}),c="",u="",d=!1;l.stdout.on("data",m=>{c=n0(c,m)}),l.stderr.on("data",m=>{u=n0(u,m)});let f=setTimeout(()=>{d=!0,l.pid&&fe(l.pid,"SIGKILL")},r);l.once("error",m=>{clearTimeout(f),s(m)}),l.once("close",m=>{clearTimeout(f),d?s(new Error("process_timeout")):o({code:m,stdout:c,stderr:u})})})}function O3(e,t){let[r,n]=t.split("-",2);return!n||!["sha256","sha384","sha512"].includes(r)?!1:w3(r).update(e).digest("base64")===n}async function T3(e,t,r,n){let o=await l0(a0(),["pack",`${e}@${t}`,"--json","--pack-destination",n,`--registry=${lk}`,"--ignore-scripts"],ck,Ks.join(n,"npm-cache"));if(o.code!==0)throw new Error("artifact_download_failed");let s;try{s=JSON.parse(o.stdout)}catch{throw new Error("artifact_receipt_invalid")}let i=s[0]?.filename;if(typeof i!="string"||Ks.basename(i)!==i)throw new Error("artifact_receipt_invalid");let a=Ks.join(n,i);if(!O3(await i0(a),r))throw new Error("artifact_integrity_mismatch");return a}async function N3(e,t,r){if((await l0(a0(),["install","--global","--prefix",e,t,`--registry=${lk}`,"--no-audit","--fund=false"],ck,r)).code!==0)throw new Error("package_install_failed")}async function c0(e){let t=JSON.parse(await i0(e.local.packageJsonPath,"utf8"));if(t.name!==e.report.packageName||typeof t.version!="string")throw new Error("installed_identity_mismatch");return t.version}function D3(e){let t={};for(let r of["PATH","SystemRoot","TEMP","TMP",...e]){let n=process.env[r];n!==void 0&&(t[r]=n)}return t}async function o0(e){if(!e.local.binPath)throw new Error("mcp_binary_missing");await ik(e.local.binPath,ak.X_OK).catch(async()=>ik(e.local.binPath,ak.R_OK));let t=new A3({command:e.local.binPath,args:[],env:D3(e.local.envAllowlist),stderr:"pipe"}),r=new E3({name:"kynver-managed-update-verifier",version:"1.0.0"}),n;try{await Promise.race([r.connect(t),new Promise((s,i)=>{n=setTimeout(()=>i(new Error("mcp_handshake_timeout")),P3)})]);let o=await r.listTools();return{toolCount:Array.isArray(o.tools)?o.tools.length:0}}finally{n&&clearTimeout(n),await r.close().catch(()=>{})}}async function s0(e,t,r,n,o){let s=await S3(Ks.join(x3(),"kynver-mcp-update-"));try{let i=await T3(t,r,n,s);if(await o(),await N3(e.local.prefix,i,Ks.join(s,"npm-cache")),await c0(e)!==r)throw new Error("installed_version_mismatch")}finally{await _3(s,{recursive:!0,force:!0})}}async function u0(e,t,r,n={}){if(typeof process.getuid=="function"&&process.getuid()===0)throw new Error("root_execution_refused");if(e.report.inventoryKey!==t.inventoryKey||e.report.inventoryFingerprint!==t.inventoryFingerprint||e.report.packageName!==t.packageName)throw new Error("local_inventory_mismatch");if(t.packageName==="@kynver-app/runtime")throw new Error("runtime_self_update_requires_supervisor");await r("preflight"),await ik(e.local.prefix,ak.W_OK).catch(()=>{throw new Error("npm_prefix_not_writable")});let o=await c0(e),s=t.resumePhase!==null&&o===t.targetVersion,i=s&&n.recoveryVerifiedTargetInstalled===!0;if(!i&&o!==t.installedVersion&&!s)throw new Error("installed_version_changed");try{if(i?await r("installing"):(await s0(e,t.packageName,t.targetVersion,t.targetIntegrity,async()=>{await r("installing"),await n.beforePackageMutation?.()}),await n.onTargetInstalled?.()),e.local.lifecycle!=="runtime_stdio")return{outcome:"manual_restart_required",observedVersion:t.targetVersion,handshakeVerified:!1,toolCount:null,failureCode:"external_supervisor_restart_required"};await r("restarting"),await r("verifying");let a=await o0(e);return{outcome:"succeeded",observedVersion:t.targetVersion,handshakeVerified:!0,toolCount:a.toolCount}}catch(a){let l=a instanceof Error?a.message:"update_failed";if(l==="progress_rejected")throw a;if(!t.rollbackIntegrity)return{outcome:"failed",observedVersion:null,handshakeVerified:!1,toolCount:null,failureCode:l};await n.beforePackageMutation?.();try{if(await s0(e,t.packageName,t.installedVersion,t.rollbackIntegrity,async()=>{await n.beforePackageMutation?.()}),e.local.lifecycle==="runtime_stdio"){let c=await o0(e);return{outcome:"rollback_succeeded",observedVersion:t.installedVersion,handshakeVerified:!0,toolCount:c.toolCount,failureCode:l}}return{outcome:"manual_restart_required",observedVersion:t.installedVersion,handshakeVerified:!1,toolCount:null,failureCode:l}}catch(c){if(c instanceof Error&&c.message==="progress_rejected")throw c;return{outcome:"rollback_failed",observedVersion:null,handshakeVerified:!1,toolCount:null,failureCode:l}}}}var lk,r0,ck,P3,d0=p(()=>{"use strict";ci();qe();lk="https://registry.npmjs.org",r0=512*1024,ck=2*6e4,P3=2e4});import{createHmac as M3,timingSafeEqual as L3}from"node:crypto";import{mkdir as B3,readFile as W3,rename as U3,writeFile as F3}from"node:fs/promises";import{homedir as K3}from"node:os";import uk from"node:path";function qa(){return process.env.KYNVER_MCP_UPDATE_STATE_ROOT?.trim()||uk.join(K3(),".kynver","state","mcp-updates")}function p0(e){if(!/^[A-Za-z0-9_-]{8,128}$/.test(e))throw new Error("invalid update operation identity");return uk.join(qa(),`${e}.json`)}function f0(e,t){let r=ok(t);return r?M3("sha256",Buffer.from(r.tokenHash,"hex")).update(JSON.stringify(e),"utf8").digest("base64url"):null}async function m0(e,t){try{let r=JSON.parse(await W3(p0(e),"utf8"));if(r.version!==2||r.operationId!==e||typeof r.integrityMac!="string")return null;let{integrityMac:n,...o}=r,s=f0(o,t);if(!s)return null;let i=Buffer.from(n,"utf8"),a=Buffer.from(s,"utf8");return i.length!==a.length||!L3(i,a)?null:r}catch{return null}}async function g0(e,t){let r=f0(e,t);if(!r)throw new Error("invalid_runner_credential_for_receipt");let n=p0(e.operationId);await B3(uk.dirname(n),{recursive:!0,mode:448});let o=`${n}.${process.pid}.tmp`;await F3(o,`${JSON.stringify({...e,integrityMac:r},null,2)}
|
|
187
|
+
`,{mode:384}),await U3(o,n)}var Nd=p(()=>{"use strict";sk()});import{randomBytes as dk}from"node:crypto";import{mkdir as pk,readFile as fk,rename as $3,rm as Dd,stat as H3,writeFile as h0}from"node:fs/promises";import so from"node:path";function y0(){return so.join(qa(),j3)}async function k0(){try{let e=JSON.parse(await fk(so.join(y0(),"owner.json"),"utf8"));return!Number.isSafeInteger(e.pid)||typeof e.acquiredAt!="string"?null:{holder:e.holder==="desktop_update"?"desktop_update":"mcp_update",pid:e.pid,acquiredAt:e.acquiredAt,alive:b0(e.pid)}}catch{return null}}function b0(e){if(!Number.isSafeInteger(e)||e<=0)return!0;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function V3(e){try{return await H3(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function v0(){return G3("mcp_update")}async function G3(e){let t=y0(),r=`${t}.reclaiming`;await pk(so.dirname(t),{recursive:!0,mode:448});let n=!1;try{if(await V3(r))return null;for(let o=0;o<2;o+=1)try{await pk(t,{mode:448});let s={pid:process.pid,nonce:dk(18).toString("base64url"),acquiredAt:new Date().toISOString(),holder:e};return await h0(so.join(t,"owner.json"),JSON.stringify(s),{mode:384}),n&&(await Dd(r,{recursive:!0,force:!0}),n=!1),{release:async()=>{try{let i=JSON.parse(await fk(so.join(t,"owner.json"),"utf8"));i.pid===s.pid&&i.nonce===s.nonce&&await Dd(t,{recursive:!0,force:!0})}catch{}}}}catch(s){if(s.code!=="EEXIST")throw s;if(!n)try{await pk(r,{mode:448}),n=!0,await h0(so.join(r,"owner.json"),JSON.stringify({pid:process.pid,nonce:dk(18).toString("base64url"),acquiredAt:new Date().toISOString()}),{mode:384})}catch(l){if(l.code==="EEXIST")return null;throw l}let i=null;try{i=JSON.parse(await fk(so.join(t,"owner.json"),"utf8"))}catch{return null}if(b0(i.pid))return null;let a=`${t}.stale-${process.pid}-${dk(8).toString("hex")}`;await $3(t,a),await Dd(a,{recursive:!0,force:!0})}return null}finally{n&&await Dd(r,{recursive:!0,force:!0})}}var j3,R0=p(()=>{"use strict";Nd();j3="host-mutation.lock"});function Md(e,t,r){return`${e}/api/agent-os/by-id/${encodeURIComponent(t)}/mcp-updates/${r}`}function J3(e){if(!e||typeof e!="object")return null;let t=e.claim;if(!t||typeof t!="object"||t.waitingForIdle!==!1)return null;let r=t.command;return r&&typeof r=="object"?r:null}function w0(e,t){let r=t.claims;return e.inventoryKey===r.inventoryKey&&e.packageName===r.packageName&&e.installedVersion===r.installedVersion&&e.targetVersion===r.targetVersion&&e.targetIntegrity===r.targetIntegrity&&e.rollbackIntegrity===r.rollbackIntegrity&&e.item.report.inventoryKey===r.inventoryKey&&e.item.report.packageName===r.packageName}function q3(e,t){return{inventoryKey:t.claims.inventoryKey,packageName:t.claims.packageName,installedVersion:t.claims.installedVersion,targetVersion:t.claims.targetVersion,targetIntegrity:t.claims.targetIntegrity,rollbackIntegrity:t.claims.rollbackIntegrity,verifiedTargetInstalled:!1,item:e}}async function S0(e){let t=pe(e.baseUrl),r=await e0();if(r.length===0)return{ok:!0,stage:"not_configured"};let n=await Ln(Md(t,e.agentOsId,"inventory"),e.secret,{items:r.map(s=>s.report)});if(!n.ok)return{ok:!1,stage:"inventory",status:n.status};let o=await v0();if(!o){let s=await k0();return{ok:!0,stage:"host_mutation_busy",...s?{heldBy:s.holder}:{}}}try{let s=await Ln(Md(t,e.agentOsId,"claim"),e.secret,{activeOwnedSessions:e.activeOwnedSessions});if(!s.ok)return{ok:!1,stage:"claim",status:s.status};let i=J3(s.response);if(!i)return{ok:!0,stage:"idle"};if(!t0(i,e.secret,e.agentOsId))return{ok:!1,stage:"command_auth"};let a=await m0(i.claims.operationId,e.secret);if(a?.terminal&&a.attempt===i.claims.attempt&&a.nonce===i.claims.nonce)return{ok:!0,stage:"already_completed",outcome:a.outcome};let l,c;if(i.claims.resumePhase!==null){if(!a||!w0(a.recovery,i))return{ok:!1,stage:"recovery_receipt_invalid"};c=a.recovery,l={...c.item,report:{...c.item.report,inventoryFingerprint:i.claims.inventoryFingerprint}}}else{let k=r.find(b=>b.report.inventoryKey===i.claims.inventoryKey);if(!k||k.report.inventoryFingerprint!==i.claims.inventoryFingerprint)return{ok:!1,stage:"inventory_changed"};l=k,c=a&&w0(a.recovery,i)?a.recovery:q3(k,i)}let u=a?.acceptedAt??new Date().toISOString(),d=async(k,b,_)=>{await g0({version:2,operationId:i.claims.operationId,attempt:i.claims.attempt,nonce:i.claims.nonce,acceptedAt:u,phase:k,terminal:b,..._?{outcome:_}:{},recovery:c},e.secret)};await d(a?.attempt===i.claims.attempt?a.phase:"claimed",!1);let f="claimed",m=async k=>{if(!(await Ln(Md(t,e.agentOsId,`operations/${encodeURIComponent(i.claims.operationId)}/events`),e.secret,{attempt:i.claims.attempt,fenceToken:i.claims.fenceToken,phase:k})).ok)throw new Error("progress_rejected");f=k,await d(k,!1)},g=k=>m(k),h=()=>m(f),y;try{y=await u0(l,i.claims,g,{recoveryVerifiedTargetInstalled:c.verifiedTargetInstalled,beforePackageMutation:h,onTargetInstalled:async()=>{c={...c,verifiedTargetInstalled:!0},await d("target_installed",!1)}})}catch(k){y={outcome:"failed",observedVersion:null,handshakeVerified:!1,toolCount:null,failureCode:k instanceof Error?k.message:"update_failed"}}let v=await Ln(Md(t,e.agentOsId,`operations/${encodeURIComponent(i.claims.operationId)}/complete`),e.secret,{attempt:i.claims.attempt,fenceToken:i.claims.fenceToken,...y});return v.ok?(await d(y.outcome,!0,y.outcome),{ok:y.outcome==="succeeded",stage:"complete",outcome:y.outcome}):{ok:!1,stage:"complete",status:v.status,outcome:y.outcome}}finally{await o.release()}}var _0=p(()=>{"use strict";$();Fe();nk();sk();d0();R0();Nd()});import x0 from"node:path";function Y3(){let e=process.env.KYNVER_PIPELINE_SWEEP_ENABLED;return e?e==="1"||e.toLowerCase()==="true":!1}async function z3(e,t){let r=ne(e),n=[],o=Math.max(0,Number.parseInt(process.env.KYNVER_PIPELINE_COMPLETION_REPLAY_MAX_DEEP_CHECKS_PER_TICK??"0",10)||0),s=0;for(let i of Object.keys(r.workers||{})){let a=F(x0.join(j(r.id),"workers",B(i),"worker.json"),void 0);if(!a?.taskId||a.localOnly||Ur(a))continue;if(ba(a)){n.push({worker:i,ok:!0,taskId:a.taskId??null,skipped:!0});continue}if(s>=o)break;s++;let l=ie(a);if(!Be(l))continue;let c=Mo({alive:l.alive,finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry});if(!a.dispatched&&!l.finalResult&&!c?.salvageable)continue;let u=await As({run:e,name:i,agentOsId:String(t.agentOsId||a.agentOsId||""),...t});n.push({worker:i,ok:u.ok,taskId:a.taskId??null})}return n}async function X3(e,t,r,n,o){let s=pe(n.baseUrl?String(n.baseUrl):void 0),i=await me(n.secret?String(n.secret):void 0,e,{baseUrl:s}),a=`${s}/api/agent-os/by-id/${encodeURIComponent(e)}/operator/tick`,l=await CN(),c=Zo(t),u=null;try{let S=HN(t);if(S.length>0){let R=qN(t);u=WN(S,{cache:R}),R.flush?.()}else u=null}catch{u=null}try{if(Ir()!=="off"){let S=Uo();aP({liveWorkers:S}),dP({liveWorkers:S})}else sP()}catch{}let d=({runId:S,workerName:R})=>{try{let{runsDir:w}=he(),L=x0.join(mr(w,B(S)),"workers",B(R),"worker.json"),N=F(L,null);return N?Ur(N):!1}catch{return!1}};await CO({agentOsId:e,baseUrl:s,secret:i,hasLiveWorker:d});let f=null;try{f=zN({hasLiveWorker:d})}catch{f=null}let m=null;try{m=pc({control:Kr(e),supervisor:xw(),inFlightWorkers:Uo().length})}catch{m=null}let g=eu(t),h=Ux(),y=await de(a,i,{agentOsId:e,runId:t,ingestHarness:!0,harnessBoardSnapshot:$h(t),resourceGate:r,boxResourceSnapshot:AO(r,{harnessRunId:t,boxKind:xt(P())}),packageVersions:l,...o?{harnessCleanup:o}:{},runnerPresence:De({runId:t}),activeHarnessWorkers:c,...g?.leaseToken?{meshCronLeaseToken:g.leaseToken}:{},...f?{localRunStore:f}:{},...m?{runtimeControlAck:m}:{},...h?{daemonEventLoop:h}:{},...u&&u.items.length>0?{providerEvidence:u.items}:{}},{agentOsId:e,baseUrl:s}),v=GN(y.response);if(v)try{jN(t,v)}catch{}let k=Mx(y);if(k)try{Dx(t,k)}catch{}let b=M_(y);b&&L_(e,b);let _=bw(y);return _&&Vf(e,_),{ok:y.ok,httpStatus:y.status,response:y.response,...u?{providerEvidence:{attempted:u.attempted,collected:u.collected,skipped:u.skipped.length}}:{}}}async function Ld(e){let t=String(_t(String(e.run||""),"--run")),r=String(_t(String(e.agentOsId||""),"--agent-os-id")),n=e.execute!==!1&&e.execute!=="false";$h(t);let o=await nu(r,e),s=ru(o),i=xi({runId:t,configuredMaxWorkersOverride:s}),a=RN()?vN(t):void 0,l=await X3(r,t,i,e,a),c;if(n)try{let A=pe(e.baseUrl?String(e.baseUrl):void 0),O=await me(e.secret?String(e.secret):void 0,r,{baseUrl:A});c=await S0({agentOsId:r,secret:O,baseUrl:A,activeOwnedSessions:Uo().length})}catch(A){c={ok:!1,stage:"cycle",error:A instanceof Error?A.message:"update cycle failed"}}let u=UA(t,l),d=await IE(t,e),f=await z3(t,e);f.some(A=>A.ok&&!A.skipped)&&gx();let m=xi({runId:t,configuredMaxWorkersOverride:s}),g=vy(),h=await TO(t,e),y=rO(m,l),v=y.maxStarts,k=Kr(r),b=Rw(k);b&&(v=0);let _=Y3()?await md({run:t,agentOsId:r,pipeline:!0,...e}):{ok:!0,skipped:!0,reason:"pipeline_sweep_disabled"},S=null,R=0,w=eO(l),L=v;if(n&&L>0&&w.length>0){let A=Math.min(L,w.length),O=await ay({...e,run:t,agentOsId:r,targetTaskIds:w.join(",")},A),W=Ns(O);R+=W,L=Math.max(0,L-W),S={exactTargetTaskIds:w,exact:O,startedCount:R}}if(n&&L>0){let A=await ay({...e,run:t,agentOsId:r},L),O=Ns(A);R+=O,S=S&&typeof S=="object"?{...S,broad:A,startedCount:R}:A}else!n||v<=0?S||(S={ok:!0,skipped:!0,reason:b??(n?m.reason??"no slots or queued work":"execute disabled"),maxStarts:0,dispatchAdvice:y,...w.length?{exactTargetTaskIds:w,exactOnly:!0}:{}}):S&&typeof S=="object"&&(S={...S,broadSkipped:!0,startedCount:R});let N=!y.underutilized&&v===0&&f.length===0&&R===0;return{runId:t,agentOsId:r,execute:n,resourceGate:i,dispatchResourceGate:m,leaseRenewal:d,completedWorkers:f,staleReconcile:g,harnessCleanup:a,planProgressSync:h,completionAckSync:u,operatorTick:l,mcpUpdates:c,sweep:_,dispatchAdvice:y,dispatch:S,idle:N,runtimeControl:k?{desiredState:k.desiredState,policyVersion:k.policyVersion}:null}}var mk=p(()=>{"use strict";$r();Pc();$();Fe();ZI();tO();nO();Ry();Fo();zn();EO();Cs();PO();Qc();Y();Et();Ql();Ce();Sy();M();NO();Zg();Ps();Wu();oc();kg();$();Le();wN();zu();Vy();yr();UN();YN();Zy();fg();XN();zm();_0();mg()});function Bd(e){return $o(Kr(e))!=="stopped"?null:Uo().length}var gk=p(()=>{"use strict";Fo();$r()});function C0(e){if(!e||typeof e!="object")return!1;let t=e;return t.type==="result"&&typeof t.id=="number"&&typeof t.ok=="boolean"}var E0=p(()=>{"use strict"});import{existsSync as Q3}from"node:fs";import{fileURLToPath as Z3}from"node:url";import{SHARE_ENV as e8,Worker as t8}from"node:worker_threads";function n8(e=import.meta.url){for(let t of[`./${A0}`,`../${A0}`]){let r=new URL(t,e);try{if(Q3(Z3(r)))return r}catch{}}return null}function o8(e){let t=(e.env??process.env).KYNVER_DAEMON_TICK_THREAD?.trim().toLowerCase();return t==="0"||t==="false"||t==="off"?{mode:"inline",reason:"disabled_by_env"}:e.desktopMode??Qe()?{mode:"inline",reason:"desktop_sidecar"}:e.script?{mode:"thread",reason:"default"}:{mode:"inline",reason:"thread_entry_not_built"}}var A0,r8,s8,Wd,P0=p(()=>{"use strict";St();mg();Gr();mk();gk();E0();A0="daemon-tick-thread.js",r8=3;s8=(e,t)=>new t8(e,{workerData:t,env:e8,name:"kynver-pipeline-tick"}),Wd=class{constructor(t){this.options=t;this.script=t.script===void 0?n8():t.script;let r=o8({env:t.env,desktopMode:t.desktopMode,script:this.script});this.modeValue=r.mode,this.reason=r.reason,this.createWorker=t.createWorker??s8,this.log=t.log??(n=>console.error(n))}options;modeValue;reason;script;createWorker;log;worker=null;online=!1;pending=null;nextId=1;startFailures=0;sentBundleKey=null;get mode(){return this.modeValue}async runTick(t,r){if(this.modeValue==="inline")return this.runInline(t,r);let n=await this.request(()=>({type:"tick",id:this.nextId++,args:t,agentOsId:this.options.agentOsId,...this.bundleIfChanged(),eventLoopReport:r}));if(!n.ok)throw new Error(n.error);return{tick:n.tick,inFlightWorkers:n.inFlightWorkers,isolation:"thread"}}async close(){let t=this.worker;this.worker=null,t&&await t.terminate().catch(()=>{})}async runInline(t,r){return Wx(r),{tick:await Ld(t),inFlightWorkers:Bd(this.options.agentOsId),isolation:"inline"}}bundleIfChanged(){let t=m_(),r=Ft(),n=`${t.version}\0${r}`;return n===this.sentBundleKey?{}:(this.sentBundleKey=n,{instructionBundle:{bundle:t,source:r}})}ensureWorker(){if(this.worker)return this.worker;if(!this.script)throw new Error("tick thread entry not found");let t=this.createWorker(this.script,this.options.init);return this.worker=t,this.online=!1,this.sentBundleKey=null,t.on("online",()=>{this.online=!0,this.startFailures=0}),t.on("message",r=>{if(!C0(r)||!this.pending||r.id!==this.pending.id)return;let n=this.pending;this.pending=null,n.resolve(r)}),t.on("error",r=>this.onWorkerGone(t,r)),t.on("exit",r=>this.onWorkerGone(t,new Error(`tick thread exited with code ${r}`))),t}onWorkerGone(t,r){if(this.worker!==t)return;this.worker=null,this.online||(this.startFailures+=1,this.startFailures>=r8&&(this.modeValue="inline",this.log(JSON.stringify({event:"daemon_tick_thread_fallback",level:"error",reason:"thread_failed_to_start",attempts:this.startFailures,error:r.message})))),this.log(JSON.stringify({event:"daemon_tick_thread_exit",level:"warn",error:r.message}));let n=this.pending;this.pending=null,n?.reject(r)}request(t){if(this.pending)return Promise.reject(new Error("a pipeline tick is already running"));let r;try{r=this.ensureWorker()}catch(o){return Promise.reject(o instanceof Error?o:new Error(String(o)))}let n=t();return new Promise((o,s)=>{this.pending={id:n.id,resolve:o,reject:s};try{r.postMessage(n)}catch(i){this.pending=null,s(i instanceof Error?i:new Error(String(i)))}})}}});import{monitorEventLoopDelay as i8,performance as a8}from"node:perf_hooks";var l8,c8,u8,d8,I0,Ud,O0=p(()=>{"use strict";l8=1e3,c8=250,u8=5,d8=5e3,I0=e=>Number.isFinite(e)?Math.round(e/1e6):0,Ud=class{thresholdMs;sampleIntervalMs;now;monotonicNow;log;histogram;timer=null;lastSampleAt=0;lastSampleWallAt=0;startedAt=0;phase="starting";phasesInWindow=new Set(["starting"]);stallCount=0;maxLagMs=0;recent=[];tickIsolation="inline";constructor(t={}){this.thresholdMs=t.thresholdMs??l8,this.sampleIntervalMs=t.sampleIntervalMs??c8,this.now=t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??(()=>a8.now()),this.log=t.log??(r=>console.error(r)),this.histogram=t.histogram??i8({resolution:20})}setPhase(t){this.phase=t,this.phasesInWindow.add(t)}setTickIsolation(t){this.tickIsolation=t}start(){this.timer||(this.startedAt=this.now(),this.lastSampleWallAt=this.startedAt,this.lastSampleAt=this.monotonicNow(),this.histogram.enable(),this.timer=setInterval(()=>this.sample(),this.sampleIntervalMs),this.timer.unref?.())}stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.histogram.disable()}sample(){let t=this.now(),r=this.monotonicNow(),n=r-this.lastSampleAt,o=t-this.lastSampleWallAt;if(this.lastSampleAt=r,this.lastSampleWallAt=t,o-n>d8)return this.histogram.reset(),this.phasesInWindow=new Set([this.phase]),null;let s=Math.max(0,Math.round(n-this.sampleIntervalMs)),i=I0(this.histogram.max),a=I0(this.histogram.percentile(99)),l=Math.max(s,i),c=null;return(l>=this.thresholdMs||a>=this.thresholdMs)&&(c={at:new Date(t).toISOString(),lagMs:l,p99Ms:a,phase:this.phase,phasesInWindow:[...this.phasesInWindow]},this.stallCount+=1,this.maxLagMs=Math.max(this.maxLagMs,l),this.recent=[...this.recent,c].slice(-u8),this.log(JSON.stringify({event:"daemon_event_loop_stall",level:"warn",lagMs:l,p99Ms:a,maxMs:i,thresholdMs:this.thresholdMs,phase:c.phase,phasesInWindow:c.phasesInWindow,tickIsolation:this.tickIsolation}))),this.histogram.reset(),this.phasesInWindow=new Set([this.phase]),c}report(){return{contractVersion:1,observedAt:new Date(this.now()).toISOString(),monitorStartedAt:new Date(this.startedAt||this.now()).toISOString(),thresholdMs:this.thresholdMs,tickIsolation:this.tickIsolation,stallCount:this.stallCount,maxLagMs:this.maxLagMs,lastStall:this.recent.length?this.recent[this.recent.length-1]:null,recentStalls:[...this.recent]}}}});var p8,f8,m8,Fd,T0=p(()=>{"use strict";sr();p8=5*6e4,f8=5*6e4,m8=2160*60*60,Fd=class{constructor(t){this.deps=t;this.now=t.now??Date.now,this.fetchImpl=t.fetchImpl??fetch,this.log=t.log??(r=>console.error(JSON.stringify(r)))}deps;token=null;lastMintFailureAt=0;minting=null;refreshing=null;lastRefreshFailureAt=0;now;fetchImpl;log;async authorization(){let t=this.token&&this.token.expiresAtMs-this.now()>p8?this.token:null;if(t)return{kind:"box_token",bearer:t.token,boxId:t.boxId};let r=this.deps.loadBoxCredential();if(r||(r=await this.mintOnce()),r){let o=await this.refreshOnce(r);if(o)return{kind:"box_token",bearer:o.token,boxId:o.boxId};if(this.token&&this.token.expiresAtMs>this.now())return{kind:"box_token",bearer:this.token.token,boxId:this.token.boxId}}let n=this.deps.loadApiKey();return n?{kind:"api_key",bearer:n,boxId:null}:null}invalidateToken(){this.token=null}describe(){return{kind:this.token?"box_token":this.deps.loadApiKey()?"api_key":"none",boxId:this.token?.boxId??null,tokenExpiresAt:this.token?new Date(this.token.expiresAtMs).toISOString():null,hasBoxCredential:!!this.deps.loadBoxCredential()}}mintOnce(){return this.minting||(this.minting=this.mintBoxCredential().finally(()=>{this.minting=null})),this.minting}async mintBoxCredential(){let t=this.deps.loadApiKey();if(!t||this.now()-this.lastMintFailureAt<f8)return;let r=`${this.deps.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(this.deps.agentOsId)}/runner-credentials`;try{let n=await ut(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({capabilities:["chat.relay"],ttlSeconds:m8,name:`chat-box:${this.deps.boxLabel()}`}),signal:AbortSignal.timeout(1e4)},this.fetchImpl),o=await n.json().catch(()=>null);if(!n.ok||typeof o?.token!="string"||!o.token){this.lastMintFailureAt=this.now(),this.log({event:"chat_box_credential_mint_failed",status:n.status,detail:typeof o?.error=="string"?o.error.slice(0,200):null});return}return this.deps.saveBoxCredential(o.token),this.log({event:"chat_box_credential_minted",agentOsId:this.deps.agentOsId}),o.token}catch(n){this.lastMintFailureAt=this.now(),this.log({event:"chat_box_credential_mint_failed",error:n instanceof Error?n.message:String(n)});return}}refreshOnce(t){return this.refreshing||(this.refreshing=this.refreshToken(t).finally(()=>{this.refreshing=null})),this.refreshing}async refreshToken(t){if(this.now()-this.lastRefreshFailureAt<15e3&&this.token===null)return null;let r=`${this.deps.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(this.deps.agentOsId)}/chat-box-token`;try{let n=await ut(r,{method:"POST",headers:{"Content-Type":"application/json","X-Kynver-Runner-Token":t},body:JSON.stringify({boxLabel:this.deps.boxLabel()}),signal:AbortSignal.timeout(1e4)},this.fetchImpl);if(n.status===401||n.status===403)return this.log({event:"chat_box_credential_rejected",status:n.status}),this.deps.clearBoxCredential(),this.token=null,null;let o=await n.json().catch(()=>null);if(!n.ok||typeof o?.token!="string"||typeof o.boxId!="string")return this.lastRefreshFailureAt=this.now(),this.log({event:"chat_box_token_refresh_failed",status:n.status,detail:typeof o?.error=="string"?o.error.slice(0,200):null}),null;let s=typeof o.expiresAt=="string"&&!Number.isNaN(Date.parse(o.expiresAt))?Date.parse(o.expiresAt):this.now()+10*6e4;return this.token={token:o.token,expiresAtMs:s,boxId:o.boxId},this.token}catch(n){return this.lastRefreshFailureAt=this.now(),this.log({event:"chat_box_token_refresh_failed",error:n instanceof Error?n.message:String(n)}),null}}}});async function $s(e){if(e.auth){let t=await e.auth.authorization();if(t)return{bearer:t.bearer,kind:t.kind,boxId:t.boxId??e.boxId}}return{bearer:e.apiKey,kind:"api_key",boxId:e.boxId}}function io(e,t,r){r===401&&t.kind==="box_token"&&e.auth?.invalidateToken()}var Kd=p(()=>{"use strict"});import{createHash as g8,verify as h8,createPublicKey as y8}from"node:crypto";function yk(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};return delete t[N0],t}function b8(e){return g8("sha256").update(nt(yk(e)),"utf8").digest("hex")}function kk(e){return!e||typeof e!="object"||Array.isArray(e)?null:e[N0]??null}function v8(e){if(!e||typeof e!="object")return!1;let t=e;if(typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let r=t.payload;return!(!r||typeof r!="object"||r.v!==1||r.kind!=="chat-turn"||typeof r.turnId!="string"||!r.turnId||typeof r.agentOsId!="string"||!r.agentOsId||r.userId!==null&&(typeof r.userId!="string"||!r.userId)||r.boxId!==null&&typeof r.boxId!="string"||r.access!==null&&(!r.access||typeof r.access!="object"||Array.isArray(r.access))||typeof r.payloadHash!="string"||!/^[0-9a-f]{64}$/.test(r.payloadHash)||typeof r.exp!="number"||!Number.isFinite(r.exp)||typeof r.nonce!="string"||!r.nonce)}function R8(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)?e.computerAccess??null:null;return r===null&&t===null?!0:r===null||t===null?!1:nt(r)===nt(t)}function hk(e,t){return{state:t,firstSeenAt:new Date(e.firstSeenSec*1e3).toISOString(),turnId:e.turnId}}function w8(e){return y8({key:Buffer.concat([k8,Buffer.from(e)]),format:"der",type:"spki"})}function D0(e,t,r={}){let n=r.env??process.env,o=r.nowSec??Math.floor(Date.now()/1e3),s=kk(e);if(s===null)return{ok:!1,code:"unsigned",reason:"turn carries no signed envelope"};if(!v8(s))return{ok:!1,code:"malformed",reason:"malformed chat-turn envelope"};let i=s;if(i.payload.agentOsId!==t.agentOsId)return{ok:!1,code:"agent_os_mismatch",reason:"envelope is for another workspace"};if(i.payload.turnId!==t.turnId)return{ok:!1,code:"turn_id_mismatch",reason:"envelope is for another turn"};if(i.payload.exp<=o)return{ok:!1,code:"expired",reason:"envelope expired"};let a=Tn(i.publicKeyId,n);if(!a)return{ok:!1,code:"no_verification_key",reason:`no verification key for publicKeyId "${i.publicKeyId}"`};let l;try{l=Buffer.from(i.signature,"base64url")}catch{return{ok:!1,code:"bad_signature",reason:"signature is not base64url"}}if(l.length!==64)return{ok:!1,code:"bad_signature",reason:"signature is not a 64-byte Ed25519 signature"};let c=!1;try{let d=Buffer.from(nt(i.payload),"utf8");c=h8(null,d,w8(a),l)}catch(d){return{ok:!1,code:"bad_signature",reason:`signature verification failed: ${d.message}`}}if(!c)return{ok:!1,code:"bad_signature",reason:"Ed25519 signature mismatch"};if(b8(e)!==i.payload.payloadHash)return{ok:!1,code:"payload_tampered",reason:"turn payload does not match its signed hash"};if(!R8(e,i.payload.access))return{ok:!1,code:"access_mismatch",reason:"computer access on the turn differs from the signed setting"};if(!r.nonces)return{ok:!0,payload:i.payload,redelivered:!1};let u=r.nonces.consume({nonce:i.payload.nonce,turnId:i.payload.turnId,expSec:i.payload.exp,nowSec:o});return u.ok?{ok:!0,payload:i.payload,redelivered:u.redelivered}:{ok:!1,code:"replayed",reason:`envelope nonce already used on this computer (${S8(u.replay)})`,replay:u.replay}}function S8(e){return`${e.state==="in_flight"?"this computer is running that turn now":e.state==="already_ran"?"that turn already ran here":`the nonce belongs to turn ${e.turnId}`}; first seen ${e.firstSeenAt}`}var N0,k8,$d,bk=p(()=>{"use strict";Hr();Li();N0="turnEnvelope",k8=Buffer.from("302a300506032b6570032100","hex");$d=class{constructor(t=1e4){this.maxEntries=t}maxEntries;byNonce=new Map;byTurn=new Map;consume(t){let r=t.nowSec??Math.floor(Date.now()/1e3);this.purge(r);let n=this.byNonce.get(t.nonce);if(n)return n.turnId!==t.turnId?{ok:!1,replay:hk(n,"turn_mismatch")}:n.state==="verified"?{ok:!0,redelivered:!0}:{ok:!1,replay:hk(n,n.state==="started"?"in_flight":"already_ran")};let o=this.byTurn.get(t.turnId);if(o){if(o.state!=="verified")return{ok:!1,replay:hk(o,o.state==="started"?"in_flight":"already_ran")};this.byNonce.delete(o.nonce);let i={...o,nonce:t.nonce,untilSec:Math.max(o.untilSec,t.expSec+60)};return this.byNonce.set(t.nonce,i),this.byTurn.set(t.turnId,i),{ok:!0,redelivered:!0}}if(this.byNonce.size>=this.maxEntries){let i=this.byNonce.values().next().value;i&&this.forget(i)}let s={nonce:t.nonce,turnId:t.turnId,firstSeenSec:r,state:"verified",untilSec:t.expSec+60};return this.byNonce.set(t.nonce,s),this.byTurn.set(t.turnId,s),{ok:!0,redelivered:!1}}markStarted(t){let r=this.byTurn.get(t);return r?(r.state==="verified"&&(r.state="started"),!0):!1}markFinished(t){let r=this.byTurn.get(t);return r?(r.state="finished",!0):!1}stateOf(t){return this.byTurn.get(t)?.state??null}purge(t=Math.floor(Date.now()/1e3)){for(let r of[...this.byNonce.values()])r.untilSec<=t&&this.forget(r)}forget(t){this.byNonce.delete(t.nonce),this.byTurn.get(t.turnId)===t&&this.byTurn.delete(t.turnId)}get size(){return this.byNonce.size}}});function M0(e=process.env,t={}){let r=(e[_8]??t.chatTurnSignature??"").toString().trim().toLowerCase();return r==="optional"||r==="off"||r==="0"||r==="false"?"optional":"required"}function L0(e,t){return t?`turn_rejected_${e}: ${t}`:`turn_rejected_${e}`}function B0(e,t){if(!(kk(e.payload)!==null)&&t.policy==="optional"){let o=e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload.computerAccess??null:null;return{ok:!0,access:x8(o)?o:null,signed:!1,userId:null,redelivered:!1}}let n=D0(e.payload,{agentOsId:t.agentOsId,turnId:e.turnId},{env:t.env,nowSec:t.nowSec,nonces:t.nonces});return n.ok?{ok:!0,access:n.payload.access,signed:!0,userId:n.payload.userId,redelivered:n.redelivered}:{ok:!1,code:n.code,reason:n.reason,...n.replay?{replay:n.replay}:{}}}function x8(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.byBox;return!!t&&typeof t=="object"&&!Array.isArray(t)}var _8,W0=p(()=>{"use strict";bk();_8="KYNVER_CHAT_TURN_SIGNATURE"});var Hd,U0=p(()=>{"use strict";Hd=class{rejects=new Map;duplicateOffers=0;childEnv=null;noteRejected(t){this.rejects.set(t,(this.rejects.get(t)??0)+1)}noteDuplicateOffer(){this.duplicateOffers+=1}report(t){return{signedTurns:!0,signaturePolicy:t.policy,accessRaiseGuard:!0,auth:t.auth,credentialStore:t.credentialStore,childEnvSafe:this.childEnv?this.childEnv.ok:null,...this.childEnv&&this.childEnv.leaked.length?{childEnvLeaked:this.childEnv.leaked}:{},rejectedTurns:Object.fromEntries(this.rejects),...this.duplicateOffers>0?{duplicateOffers:this.duplicateOffers}:{},...t.folderSandbox?{folderSandbox:t.folderSandbox}:{}}}}});import{lookup as C8}from"node:dns/promises";import{createServer as E8,request as A8}from"node:http";import{connect as P8,isIP as $0,isIPv4 as I8}from"node:net";function H0(e){let t=e.split(".");if(t.length!==4)return null;let r=t.map(n=>Number(n));return r.every(n=>Number.isInteger(n)&&n>=0&&n<=255)?r:null}function Ya(e){let t=H0(e);if(!t)return!0;let[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168||r===100&&n>=64&&n<=127||r===192&&n===0&&t[2]===0||r>=224}function T8(e){let t=e,r=t.indexOf("%");r!==-1&&(t=t.slice(0,r));let n=t.lastIndexOf(":"),o=t.slice(n+1);if(o.includes(".")){let u=H0(o);if(!u)return null;t=`${t.slice(0,n+1)}${(u[0]<<8|u[1]).toString(16)}:${(u[2]<<8|u[3]).toString(16)}`}let s=t.split("::");if(s.length>2)return null;let i=u=>u===""?[]:u.split(":").map(d=>/^[0-9a-f]{1,4}$/i.test(d)?parseInt(d,16):NaN),a=i(s[0]),l=s.length===2?i(s[1]):[];if([...a,...l].some(u=>Number.isNaN(u)))return null;let c=8-a.length-l.length;return(s.length===2?c<0:c!==0)?null:[...a,...new Array(Math.max(0,c)).fill(0),...l]}function N8(e){let t=T8(e);if(!t||t.every(s=>s===0)||t.slice(0,7).every(s=>s===0)&&t[7]===1)return!0;let n=(s,i)=>`${s>>8}.${s&255}.${i>>8}.${i&255}`;if(t.slice(0,5).every(s=>s===0)&&t[5]===65535||t.slice(0,6).every(s=>s===0)||t[0]===100&&t[1]===65435&&t.slice(2,6).every(s=>s===0))return Ya(n(t[6],t[7]));if(t[0]===8194)return Ya(n(t[1],t[2]));let o=t[0];return(o&65024)===64512||(o&65472)===65152||(o&65472)===65216||(o&65280)===65280||o===8193&&t[1]===3512}function F0(e){let t=$0(e);return t===4?Ya(e):t===6?N8(e):!0}function D8(e){return e==="localhost"||e.endsWith(".localhost")||e==="localhost6"||e==="ip6-localhost"}function M8(e){let t=e.trim().toLowerCase();for(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));t.endsWith(".");)t=t.slice(0,-1);return t}async function j0(e){return(await C8(e,{all:!0})).map(r=>r.address)}async function K0(e,t=j0){let r=M8(e);if(!r||r.length>O8)return{allowed:!1,host:r,reason:"invalid host"};if(D8(r))return{allowed:!1,host:r,reason:`${r} is this computer (loopback): local services are not reachable from a folder step`};if($0(r))return F0(r)?{allowed:!1,host:r,reason:`${r} is a private, loopback, link-local or metadata address: not reachable from a folder step`}:{allowed:!0,host:r,address:r};let n;try{n=await t(r)}catch(s){return{allowed:!1,host:r,reason:`${r} could not be resolved (${s?.message??String(s)})`}}if(!n.length)return{allowed:!1,host:r,reason:`${r} could not be resolved`};let o=n.find(s=>F0(s));return o?{allowed:!1,host:r,reason:`${r} resolves to ${o}, a private, loopback, link-local or metadata address: not reachable from a folder step`}:{allowed:!0,host:r,address:n.find(s=>I8(s))??n[0]}}function vk(e,t,r){let n=`Kynver folder sandbox: ${r}
|
|
188
|
+
`;e.write(`HTTP/1.1 ${t} ${t===Rk?"Forbidden":"Bad Gateway"}\r
|
|
125
189
|
Content-Type: text/plain\r
|
|
126
190
|
Content-Length: ${Buffer.byteLength(n)}\r
|
|
127
191
|
Connection: close\r
|
|
128
192
|
\r
|
|
129
|
-
${n}`),e.end()}function
|
|
193
|
+
${n}`),e.end()}function B8(e){if(!e)return null;let t=e.lastIndexOf(":");if(t<=0)return null;let r=e.slice(0,t),n=Number(e.slice(t+1));return!Number.isInteger(n)||n<1||n>65535?null:{host:r,port:n}}async function W8(e={}){let t=e.lookup??j0,r=e.dial??((m,g)=>P8({host:m,port:g})),n=e.idleMs??L8,o={allowed:0,denied:0},s=(m,g,h)=>{let y=B8(m.url);if(g.on("error",()=>g.destroy()),!y){o.denied+=1,vk(g,400,"CONNECT needs host:port");return}K0(y.host,t).then(v=>{if(!v.allowed){o.denied+=1,vk(g,Rk,v.reason);return}o.allowed+=1;let k=r(v.address,y.port,v.host),b=!1;k.setTimeout(n,()=>k.destroy()),k.once("connect",()=>{b=!0,g.write(`HTTP/1.1 200 Connection Established\r
|
|
130
194
|
\r
|
|
131
|
-
`),h.length&&k.write(h),k.pipe(g),g.pipe(k)}),k.on("error",_=>{if(b){g.destroy();return}
|
|
195
|
+
`),h.length&&k.write(h),k.pipe(g),g.pipe(k)}),k.on("error",_=>{if(b){g.destroy();return}vk(g,502,`could not connect to ${v.host}:${y.port} (${_.code??_.message})`)}),k.on("close",()=>g.end()),g.on("close",()=>k.destroy())})},i=(m,g)=>{let h;try{h=new URL(m.url??"")}catch{g.writeHead(400,{"Content-Type":"text/plain"}).end(`Kynver folder sandbox: this is an HTTP proxy; send an absolute URL or CONNECT
|
|
132
196
|
`);return}if(h.protocol!=="http:"){g.writeHead(400,{"Content-Type":"text/plain"}).end(`Kynver folder sandbox: only http:// requests are forwarded here; https goes through CONNECT
|
|
133
|
-
`);return}let y=h.port?Number(h.port):80;
|
|
134
|
-
`);return}o.allowed+=1;let k={...
|
|
135
|
-
`)}),f.pipe(b)})},a=()=>{let f=WX(i);return f.on("connect",s),f.on("clientError",(g,h)=>h.destroy()),f.unref(),f},l=a(),c=await new Promise((f,g)=>{l.once("error",g),l.listen(0,"127.0.0.1",()=>{let h=l.address();if(!h||typeof h!="object"){g(new Error("egress proxy bound no port"));return}f(h.port)})}),u=a(),m=await new Promise(f=>{u.once("error",()=>f(!1)),u.listen(c,"::1",()=>f(!0))})?[l,u]:[l];return{port:c,listening:()=>l.listening,counts:()=>({...o}),close:()=>Promise.all(m.map(f=>new Promise(g=>f.close(()=>g())))).then(()=>{})}}async function GN(e={}){return Ds?.listening()?Ds:(Ad||(Ad=YX(e).then(t=>(Ds=t,Fa=null,t)).catch(t=>{throw Ds=null,Fa=`egress proxy could not start: ${t?.message??String(t)}`.slice(0,240),new Error(Fa)}).finally(()=>{Ad=null})),Ad)}function JN(){return Ds?.listening()?{status:"running",port:Ds.port}:Fa?{status:"failed",reason:Fa}:{status:"not_started"}}var KX,JX,Vy,Ds,Ad,Fa,Gy=p(()=>{"use strict";KX=253;JX=10*6e4,Vy=403;Ds=null,Ad=null,Fa=null});import{existsSync as zX}from"node:fs";import Id from"node:path";function qy(e=process.env,t={}){let r=(e[XX]??t.chatFolderSandbox??"").toString().trim().toLowerCase();return r==="best-effort"||r==="best_effort"||r==="optional"?"best_effort":"required"}function XN(e=process.env,t={}){let r=[],n=e[QX];n&&r.push(...n.split(/[\s,]+/)),Array.isArray(t.chatFolderSandboxDomains)&&r.push(...t.chatFolderSandboxDomains.filter(s=>typeof s=="string"));let o=[...ZX];for(let s of r){let i=s.trim().toLowerCase();i&&/^[a-z0-9*][a-z0-9.*-]*$/.test(i)&&!o.includes(i)&&o.push(i)}return o}function Pd(e){return`~/${e}`}function r3(){let e=[];for(let t of Od)e.push(`Read(${Pd(t)}/**)`,`Edit(${Pd(t)}/**)`);for(let t of Td)e.push(`Read(${Pd(t)})`,`Edit(${Pd(t)})`);for(let t of Ms)e.push(`Read(//**/${t})`,`Edit(//**/${t})`);return e}function n3(e,t=[],r={}){let n=["~/",...t3];for(let o of Od)n.push(`~/${o}`);for(let o of Td)n.push(`~/${o}`);for(let o of t)n.push(Jy(o));if(r.scanComplete!==!0)for(let o of e)for(let s of Ms)n.push(Id.posix.join(Jy(o),"**",s));return n}function o3(e){return[...e.map(Jy),...e3.map(t=>`~/${t}`)]}function Jy(e){return e.split(Id.sep).join("/")}function qN(e){let t={deny:r3(),blockReadsOutsideWorkingDirectories:!0};if(!e.sandbox)return{permissions:t,sandbox:{enabled:!1}};let r=e.egressProxyPort;return{permissions:t,sandbox:{enabled:!0,autoAllowBashIfSandboxed:!0,allowUnsandboxedCommands:!1,failIfUnavailable:!0,filesystem:{denyRead:n3(e.folders,e.sensitiveFiles,{scanComplete:e.sensitiveScanComplete}),allowRead:o3(e.folders)},network:{allowedDomains:e.domains,allowLocalBinding:!0,...typeof r=="number"&&r>0?{httpProxyPort:r}:{}}}}}function QN(e){return!!e&&s3.test(e)}function i3(e,t,r){return(t.PATH??"").split(Id.delimiter).filter(Boolean).some(o=>r(Id.join(o,e)))}function a3(e={}){let t=e.platform??process.platform,r=e.env??process.env,n=e.exists??zX;if(t==="darwin")return{kind:"seatbelt",available:!0,missing:[]};if(t==="linux"){let o=["bwrap","socat"].filter(s=>!i3(s,r,n));return o.length?{kind:"bubblewrap",available:!1,missing:o,reason:`Linux needs bubblewrap and socat on PATH to confine shell commands (missing: ${o.join(", ")})`}:{kind:"bubblewrap",available:!0,missing:[]}}return{kind:"none",available:!1,missing:[],reason:t==="win32"?"native Windows cannot confine shell commands (use WSL2 with bubblewrap and socat)":`no command sandbox on ${t}`}}function Yy(){return YN??=a3(),YN}function e0(e){ZN=e.trim().slice(0,240)||"sandbox failed to start"}function zy(){return ZN}function t0(e){return e.streamed.trim()||e.exitCode===0||e.numTurns!==null&&e.numTurns>0?!1:l3.test(e.detail)&&c3.test(e.detail)}function r0(e){if(e.access.access!=="folder"&&e.access.access!=="folders")throw new Error(`folder_sandbox_not_applicable: ${e.access.access}`);let t=e.access.folders.length?e.access.folders:[],r=e.runtime.available?e.startupFailure??null:e.runtime.reason??"no command sandbox";if(!r){let o=e.egress&&typeof e.egress.port=="number"&&e.egress.port>0?e.egress.port:null,s=o?void 0:e.egress&&"reason"in e.egress&&e.egress.reason||"egress proxy not started";return{shell:"sandboxed",policy:e.policy,runtime:e.runtime,network:o?"public":"domain-list",...s?{networkReason:s}:{},settings:qN({folders:t,sandbox:!0,domains:e.domains,egressProxyPort:o,sensitiveFiles:e.sensitiveFiles,sensitiveScanComplete:e.sensitiveScanComplete}),note:o?`${zN} ${u3}`:`${zN} ${d3}`}}let n=qN({folders:t,sandbox:!1,domains:e.domains});return e.policy==="best_effort"?{shell:"unconfined",policy:e.policy,runtime:e.runtime,reason:r,settings:n,note:f3}:{shell:"disabled",policy:e.policy,runtime:e.runtime,reason:r,settings:n,note:p3}}function Xy(e=process.env,t={},r={}){let n=r.runtime??Yy(),o=r.startupFailure===void 0?zy():r.startupFailure,s=qy(e,t),i=n.available?o??void 0:n.reason,a=i?s==="best_effort"?"unconfined":"disabled":"sandboxed",l=r.egress??JN(),c=a!=="sandboxed"?{}:l.status==="failed"?{network:"domain-list",networkReason:l.reason}:{network:"public"};return{policy:s,runtime:n.kind,available:n.available&&!o,shell:a,...i?{reason:i}:{},...c}}var XX,QX,ZX,Od,Td,Ms,e3,t3,to,s3,YN,ZN,l3,c3,zN,u3,d3,p3,f3,Nd=p(()=>{"use strict";Gy();XX="KYNVER_CHAT_FOLDER_SANDBOX",QX="KYNVER_CHAT_FOLDER_SANDBOX_DOMAINS";ZX=["registry.npmjs.org","*.npmjs.org","registry.yarnpkg.com","*.pnpm.io","pypi.org","*.pypi.org","files.pythonhosted.org","github.com","*.github.com","*.githubusercontent.com","gitlab.com","*.gitlab.com","bitbucket.org","crates.io","*.crates.io","static.crates.io","index.crates.io","proxy.golang.org","sum.golang.org","storage.googleapis.com","rubygems.org","*.rubygems.org","repo1.maven.org","*.maven.org","*.gradle.org","api.nuget.org","*.nuget.org","registry-1.docker.io","*.docker.io","*.docker.com","ghcr.io","deb.debian.org","*.debian.org","*.ubuntu.com","*.alpinelinux.org","*.fedoraproject.org","huggingface.co","*.huggingface.co","*.hf.co","nodejs.org","*.nodejs.org","deno.land","bun.sh","*.rustup.rs","sh.rustup.rs","go.dev","*.golang.org"];Od=[".ssh","private",".private",".config",".aws",".railway",".gnupg",".kube",".docker",".azure",".terraform.d",".1password",".password-store",".local/share/keyrings",".claude",".codex",".cursor",".gemini",".antigravity",".kynver/credentials.d",".kynver/site-logins","Library/Keychains","Library/Application Support","Library/Cookies",".mozilla"],Td=[".netrc",".npmrc",".pypirc",".git-credentials",".bash_history",".zsh_history",".python_history",".bashrc",".bash_profile",".profile",".zshrc",".zshenv",".zprofile",".claude.json",".vault-token",".m2/settings.xml",".gradle/gradle.properties",".cache/huggingface/token",".kynver/credentials",".kynver/credentials.json",".kynver/chat-box-credential",".kynver/config.json"],Ms=[".env",".env.*","*.env",".envrc","credentials","credentials.json","*credentials*.json","*service-account*.json","*service_account*.json","*.pem","*.p12","*.pfx","id_rsa","id_rsa.*","id_ed25519","id_ed25519.*","id_ecdsa","id_ecdsa.*"],e3=[".nvm",".npm",".cache",".local/bin",".local/lib",".local/share",".local/state",".cargo",".rustup",".pyenv",".rbenv",".bun",".deno",".volta",".fnm",".sdkman",".yarn",".pnpm-store",".conda","miniconda3","anaconda3",".gem",".m2",".gradle",".nuget",".dotnet",".go","go",".gitconfig"],t3=["/home","/root","/Users","/mnt","/media","/Volumes"];to=3128,s3=new RegExp([`failed to connect to (?:localhost|127\\.0\\.0\\.1|::1|\\[::1\\]) port ${to}\\b`,`(?:localhost|127\\.0\\.0\\.1|\\[::1\\]|::1):${to}\\b[^\\n]{0,80}?(?:connection refused|econnrefused)`,`(?:connection refused|econnrefused)[^\\n]{0,80}?(?:localhost|127\\.0\\.0\\.1|::1):${to}\\b`,`(?:cannot|could not|unable to) connect to proxy[^\\n]{0,80}?${to}\\b`,`proxyerror[^\\n]{0,120}?${to}\\b`].join("|"),"i");YN=null;ZN=null;l3=/sandbox/i,c3=/unavailable|not available|not supported|unsupported|bubblewrap|bwrap|socat|failIfUnavailable|seccomp|could not (?:be )?(?:start|initiali[sz]e)|failed to (?:start|initiali[sz]e)/i;zN="Your shell and file tools are confined to the chosen folder(s) this turn: other folders, dotfiles, ~/.ssh, ~/private, ~/.config, credential and .env files are not readable, writes stay in the folder, and the environment carries no secrets. Work inside the folder; if something is refused, say so.",u3="The folder limits files, not the internet: shell downloads (curl, wget, pip, npm, git \u2026) reach any public website through the sandbox's HTTP proxy. Only private, loopback, link-local and cloud-metadata addresses are refused (a 403 'Kynver folder sandbox' from the proxy says so). The sandbox's proxy bridge takes a moment to start in each new shell command: curl and wget here already retry a refused connection; in Python or other clients, retry a connection refused on localhost:3128 a few times (or `sleep 1` first). If a command still fails with 'Failed to connect to localhost port 3128', retry the command once; if it fails the same way again, the sandbox network proxy is not running on this computer: say exactly that. Never report such a failure as a blocked website or ask the user to allow a host.",d3="Shell network this turn is limited to package registries and code hosts (the computer's sandbox egress proxy is not running); fetch other websites with WebFetch, and say so when a shell download is refused.",p3="Shell commands are OFF this turn: this computer cannot confine them to the chosen folder, so only the file tools are available (reads and edits inside the folder). If the job needs commands, tell the user: on Linux/WSL2 install bubblewrap and socat, or choose full computer access in Kynver's Computers settings. Never claim to have run a command.",f3="Shell commands are NOT confined to the chosen folder on this computer (folder sandbox set to best-effort). Treat the folder boundary as a rule you follow yourself: do not read or change anything outside the chosen folder(s), and never look for credentials elsewhere on the computer."});function h3(e){let t=e[qp];return new Set(t?t.split(/[\s,]+/).map(r=>r.trim()).filter(Boolean):[])}function Qy(e,t={}){return g3.has(e)||t.operatorAllow?.has(e)||e===ek?!1:m3.some(r=>r.test(e))}function Vt(e=process.env){let t=ti(e);for(let n of Zy)delete t[n];let r=h3(e);for(let n of Object.keys(t))Qy(n,{operatorAllow:r})&&delete t[n];return t[ek]="1",t}function n0(e){let t=e.toUpperCase();return v3.has(t)||t===ek?!0:k3.has(t)?!Qy(t):b3.some(r=>t.startsWith(r))?!Qy(t)&&!/(_KEY|_TOKEN|_SECRET|_PASSWORD)$/i.test(t):!1}function R3(e=process.env){let t={};for(let[n,o]of Object.entries(e))typeof o=="string"&&n0(n)&&(t[n]=o);let r=Vt(t);for(let n of Object.keys(r))n0(n)||delete r[n];return r}function o0(e,t){return t==="folder"||t==="folders"?R3(e):Vt(e)}function tk(){return[`--disallowedTools=${w3.join(",")}`]}var Zy,ek,m3,g3,y3,k3,b3,v3,w3,ro=p(()=>{"use strict";ri();Zy=["KYNVER_API_KEY","KYNVER_RUNNER_TOKEN","KYNVER_CHAT_BOX_CREDENTIAL","KYNVER_CHAT_BOX_TOKEN","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","OPENCLAW_RUNNER_TOKEN","KYNVER_WORKER_API_KEY","KYNVER_GEMINI_API_KEY","KYNVER_OPENAI_API_KEY"],ek="KYNVER_CHAT_CHILD",m3=[/_URL$/i,/SECRET/i,/CREDENTIAL/i,/DATABASE/i,/ACCESS_KEY/i,/PASSWORD|PASSWD|_PWD$|^PGPASS/i,/_DSN$/i,/CONNECTION_STRING|CONN_STR/i,/PRIVATE_KEY/i,/SERVICE_ACCOUNT/i,/AUTHTOKEN|_AUTH$/i,/_API_KEY_|APIKEY/i],g3=new Set(Jp);y3=["PATH","HOME","USER","LOGNAME","SHELL","PWD","TMPDIR","TMP","TEMP","TZ","LANG","LANGUAGE","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","SSL_CERT_FILE","SSL_CERT_DIR","NODE_EXTRA_CA_CERTS","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","XDG_CACHE_HOME","XDG_DATA_HOME","NVM_DIR","NVM_BIN","NVM_INC","VOLTA_HOME","FNM_DIR","N_PREFIX","PNPM_HOME","BUN_INSTALL","DENO_INSTALL","PYENV_ROOT","VIRTUAL_ENV","CONDA_PREFIX","PYTHONIOENCODING","GOPATH","GOROOT","CARGO_HOME","RUSTUP_HOME","JAVA_HOME","DOTNET_ROOT","HOMEBREW_PREFIX","HOMEBREW_CELLAR","HOMEBREW_REPOSITORY","AWS_REGION","AWS_DEFAULT_REGION","AWS_PROFILE","GOOGLE_CLOUD_PROJECT","CLOUD_ML_REGION","SYSTEMROOT","WINDIR","SYSTEMDRIVE","COMSPEC","PATHEXT","USERPROFILE","HOMEDRIVE","HOMEPATH","USERNAME","APPDATA","LOCALAPPDATA","PROGRAMDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMW6432","COMMONPROGRAMFILES","COMMONPROGRAMFILES(X86)","ALLUSERSPROFILE","PUBLIC","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"],k3=new Set(y3.map(e=>e.toUpperCase())),b3=["LC_","CLAUDE_CODE_","CLAUDE_","ANTHROPIC_","DISABLE_","MAX_THINKING_","BASH_DEFAULT_","BASH_MAX_"],v3=new Set(["CLAUDE_CODE_OAUTH_TOKEN"]);w3=["Read(~/.kynver/credentials)","Read(~/.kynver/credentials.*)","Read(~/.kynver/chat-box-credential)","Read(~/.kynver/site-logins/**)"]});import{spawn as S3}from"node:child_process";async function s0(e=process.env,t={}){let r=t.now??(()=>new Date),n="KYNVER_API_KEY",o={...e,[n]:e[n]??"canary-not-a-real-key"},s=Vt(o),i=new Set([...Zy,...Gp]);return new Promise(a=>{let l="",c=!1,u=f=>{c||(c=!0,clearTimeout(m),a({...f,at:r().toISOString()}))},d;try{d=S3(t.execPath??process.execPath,["-e",_3],X({env:s,stdio:["ignore","pipe","ignore"]}))}catch(f){u({ok:!1,leaked:[],error:f instanceof Error?f.message:String(f)});return}let m=setTimeout(()=>{d.kill("SIGKILL"),u({ok:!1,leaked:[],error:"self-test timed out"})},t.timeoutMs??1e4);d.stdout?.on("data",f=>{l+=f.toString("utf8")}),d.on("error",f=>u({ok:!1,leaked:[],error:f.message})),d.on("close",()=>{let f;try{f=JSON.parse(l)}catch{u({ok:!1,leaked:[],error:"self-test child printed no env listing"});return}let g=Array.isArray(f)?f.filter(h=>typeof h=="string"&&i.has(h)).sort():[];u({ok:g.length===0,leaked:g})})})}var _3,i0=p(()=>{"use strict";D();ro();ri();_3="process.stdout.write(JSON.stringify(Object.keys(process.env)))"});import{existsSync as x3,mkdirSync as C3,readFileSync as E3,writeFileSync as A3}from"node:fs";import{homedir as P3}from"node:os";import rk from"node:path";function nk(e=P3()){return rk.join(e,I3)}function a0(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function O3(e){return typeof e.access!="string"?null:{access:e.access,folders:a0(e.folders),source:e.source??"default",signed:e.signed===!0,at:typeof e.at=="string"?e.at:""}}function T3(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(typeof r.access=="string")return{access:r.access,folders:a0(r.folders),changedAt:typeof r.changedAt=="string"?r.changedAt:"",nonce:typeof r.nonce=="string"?r.nonce:"",at:typeof r.at=="string"?r.at:""}}return t&&t.source==="website"?{access:t.access,folders:[...t.folders],changedAt:t.at,nonce:"",at:t.at}:null}function Dd(e=nk()){try{if(!x3(e))return{applied:null,website:null};let t=JSON.parse(E3(e,"utf8"));if(!t||typeof t!="object")return{applied:null,website:null};let r=O3(t);return{applied:r,website:T3(t.website,r)}}catch{return{applied:null,website:null}}}function l0(e,t){try{C3(rk.dirname(e),{recursive:!0});let r={...t.applied??{},...t.website?{website:t.website}:{}};A3(e,`${JSON.stringify(r,null,2)}
|
|
136
|
-
`,{mode:384})}catch{}}function
|
|
137
|
-
`,{encoding:"utf8",mode:384}),!0}catch(r){return console.error(JSON.stringify({event:"chat_command_log_write_failed",error:r instanceof Error?r.message:String(r)})),!1}}var
|
|
138
|
-
`)||n.includes("\0"))return{ok:!1,mutating:!1,reason:"control characters refused"}}let t=e[0],r=e.length>1&&!e[1].startsWith("--")?`${t} ${e[1]}`:t;if(t==="doctor"){let n=e[1]&&!e[1].startsWith("--")?e[1]:void 0;return n&&!
|
|
197
|
+
`);return}let y=h.port?Number(h.port):80;K0(h.hostname,t).then(v=>{if(!v.allowed){o.denied+=1,g.writeHead(Rk,{"Content-Type":"text/plain",Connection:"close"}).end(`Kynver folder sandbox: ${v.reason}
|
|
198
|
+
`);return}o.allowed+=1;let k={...m.headers};delete k["proxy-connection"],delete k["proxy-authorization"];let b=A8({host:v.address,port:y,method:m.method,path:`${h.pathname}${h.search}`,headers:k,setHost:!1,createConnection:()=>r(v.address,y,v.host)},_=>{g.writeHead(_.statusCode??502,_.headers),_.pipe(g)});b.setTimeout(n,()=>b.destroy(new Error("idle"))),b.on("error",_=>{g.headersSent||g.writeHead(502,{"Content-Type":"text/plain"}),g.end(`Kynver folder sandbox: could not reach ${v.host}:${y} (${_.code??_.message})
|
|
199
|
+
`)}),m.pipe(b)})},a=()=>{let m=E8(i);return m.on("connect",s),m.on("clientError",(g,h)=>h.destroy()),m.unref(),m},l=a(),c=await new Promise((m,g)=>{l.once("error",g),l.listen(0,"127.0.0.1",()=>{let h=l.address();if(!h||typeof h!="object"){g(new Error("egress proxy bound no port"));return}m(h.port)})}),u=a(),f=await new Promise(m=>{u.once("error",()=>m(!1)),u.listen(c,"::1",()=>m(!0))})?[l,u]:[l];return{port:c,listening:()=>l.listening,counts:()=>({...o}),close:()=>Promise.all(f.map(m=>new Promise(g=>m.close(()=>g())))).then(()=>{})}}async function V0(e={}){return Hs?.listening()?Hs:(jd||(jd=W8(e).then(t=>(Hs=t,za=null,t)).catch(t=>{throw Hs=null,za=`egress proxy could not start: ${t?.message??String(t)}`.slice(0,240),new Error(za)}).finally(()=>{jd=null})),jd)}function G0(){return Hs?.listening()?{status:"running",port:Hs.port}:za?{status:"failed",reason:za}:{status:"not_started"}}var O8,L8,Rk,Hs,jd,za,wk=p(()=>{"use strict";O8=253;L8=10*6e4,Rk=403;Hs=null,jd=null,za=null});import{existsSync as U8}from"node:fs";import Gd from"node:path";function _k(e=process.env,t={}){let r=(e[F8]??t.chatFolderSandbox??"").toString().trim().toLowerCase();return r==="best-effort"||r==="best_effort"||r==="optional"?"best_effort":"required"}function z0(e=process.env,t={}){let r=[],n=e[K8];n&&r.push(...n.split(/[\s,]+/)),Array.isArray(t.chatFolderSandboxDomains)&&r.push(...t.chatFolderSandboxDomains.filter(s=>typeof s=="string"));let o=[...$8];for(let s of r){let i=s.trim().toLowerCase();i&&/^[a-z0-9*][a-z0-9.*-]*$/.test(i)&&!o.includes(i)&&o.push(i)}return o}function Vd(e){return`~/${e}`}function V8(){let e=[];for(let t of Jd)e.push(`Read(${Vd(t)}/**)`,`Edit(${Vd(t)}/**)`);for(let t of qd)e.push(`Read(${Vd(t)})`,`Edit(${Vd(t)})`);for(let t of js)e.push(`Read(//**/${t})`,`Edit(//**/${t})`);return e}function G8(e,t=[],r={}){let n=["~/",...j8];for(let o of Jd)n.push(`~/${o}`);for(let o of qd)n.push(`~/${o}`);for(let o of t)n.push(Sk(o));if(r.scanComplete!==!0)for(let o of e)for(let s of js)n.push(Gd.posix.join(Sk(o),"**",s));return n}function J8(e){return[...e.map(Sk),...H8.map(t=>`~/${t}`)]}function Sk(e){return e.split(Gd.sep).join("/")}function J0(e){let t={deny:V8(),blockReadsOutsideWorkingDirectories:!0};if(!e.sandbox)return{permissions:t,sandbox:{enabled:!1}};let r=e.egressProxyPort;return{permissions:t,sandbox:{enabled:!0,autoAllowBashIfSandboxed:!0,allowUnsandboxedCommands:!1,failIfUnavailable:!0,filesystem:{denyRead:G8(e.folders,e.sensitiveFiles,{scanComplete:e.sensitiveScanComplete}),allowRead:J8(e.folders)},network:{allowedDomains:e.domains,allowLocalBinding:!0,...typeof r=="number"&&r>0?{httpProxyPort:r}:{}}}}}function X0(e){return!!e&&q8.test(e)}function Y8(e,t,r){return(t.PATH??"").split(Gd.delimiter).filter(Boolean).some(o=>r(Gd.join(o,e)))}function z8(e={}){let t=e.platform??process.platform,r=e.env??process.env,n=e.exists??U8;if(t==="darwin")return{kind:"seatbelt",available:!0,missing:[]};if(t==="linux"){let o=["bwrap","socat"].filter(s=>!Y8(s,r,n));return o.length?{kind:"bubblewrap",available:!1,missing:o,reason:`Linux needs bubblewrap and socat on PATH to confine shell commands (missing: ${o.join(", ")})`}:{kind:"bubblewrap",available:!0,missing:[]}}return{kind:"none",available:!1,missing:[],reason:t==="win32"?"native Windows cannot confine shell commands (use WSL2 with bubblewrap and socat)":`no command sandbox on ${t}`}}function xk(){return q0??=z8(),q0}function Z0(e){Q0=e.trim().slice(0,240)||"sandbox failed to start"}function Ck(){return Q0}function eD(e){return e.streamed.trim()||e.exitCode===0||e.numTurns!==null&&e.numTurns>0?!1:X8.test(e.detail)&&Q8.test(e.detail)}function tD(e){if(e.access.access!=="folder"&&e.access.access!=="folders")throw new Error(`folder_sandbox_not_applicable: ${e.access.access}`);let t=e.access.folders.length?e.access.folders:[],r=e.runtime.available?e.startupFailure??null:e.runtime.reason??"no command sandbox";if(!r){let o=e.egress&&typeof e.egress.port=="number"&&e.egress.port>0?e.egress.port:null,s=o?void 0:e.egress&&"reason"in e.egress&&e.egress.reason||"egress proxy not started";return{shell:"sandboxed",policy:e.policy,runtime:e.runtime,network:o?"public":"domain-list",...s?{networkReason:s}:{},settings:J0({folders:t,sandbox:!0,domains:e.domains,egressProxyPort:o,sensitiveFiles:e.sensitiveFiles,sensitiveScanComplete:e.sensitiveScanComplete}),note:o?`${Y0} ${Z8}`:`${Y0} ${e5}`}}let n=J0({folders:t,sandbox:!1,domains:e.domains});return e.policy==="best_effort"?{shell:"unconfined",policy:e.policy,runtime:e.runtime,reason:r,settings:n,note:r5}:{shell:"disabled",policy:e.policy,runtime:e.runtime,reason:r,settings:n,note:t5}}function Ek(e=process.env,t={},r={}){let n=r.runtime??xk(),o=r.startupFailure===void 0?Ck():r.startupFailure,s=_k(e,t),i=n.available?o??void 0:n.reason,a=i?s==="best_effort"?"unconfined":"disabled":"sandboxed",l=r.egress??G0(),c=a!=="sandboxed"?{}:l.status==="failed"?{network:"domain-list",networkReason:l.reason}:{network:"public"};return{policy:s,runtime:n.kind,available:n.available&&!o,shell:a,...i?{reason:i}:{},...c}}var F8,K8,$8,Jd,qd,js,H8,j8,ao,q8,q0,Q0,X8,Q8,Y0,Z8,e5,t5,r5,Yd=p(()=>{"use strict";wk();F8="KYNVER_CHAT_FOLDER_SANDBOX",K8="KYNVER_CHAT_FOLDER_SANDBOX_DOMAINS";$8=["registry.npmjs.org","*.npmjs.org","registry.yarnpkg.com","*.pnpm.io","pypi.org","*.pypi.org","files.pythonhosted.org","github.com","*.github.com","*.githubusercontent.com","gitlab.com","*.gitlab.com","bitbucket.org","crates.io","*.crates.io","static.crates.io","index.crates.io","proxy.golang.org","sum.golang.org","storage.googleapis.com","rubygems.org","*.rubygems.org","repo1.maven.org","*.maven.org","*.gradle.org","api.nuget.org","*.nuget.org","registry-1.docker.io","*.docker.io","*.docker.com","ghcr.io","deb.debian.org","*.debian.org","*.ubuntu.com","*.alpinelinux.org","*.fedoraproject.org","huggingface.co","*.huggingface.co","*.hf.co","nodejs.org","*.nodejs.org","deno.land","bun.sh","*.rustup.rs","sh.rustup.rs","go.dev","*.golang.org"];Jd=[".ssh","private",".private",".config",".aws",".railway",".gnupg",".kube",".docker",".azure",".terraform.d",".1password",".password-store",".local/share/keyrings",".claude",".codex",".cursor",".gemini",".antigravity",".kynver/credentials.d",".kynver/site-logins","Library/Keychains","Library/Application Support","Library/Cookies",".mozilla"],qd=[".netrc",".npmrc",".pypirc",".git-credentials",".bash_history",".zsh_history",".python_history",".bashrc",".bash_profile",".profile",".zshrc",".zshenv",".zprofile",".claude.json",".vault-token",".m2/settings.xml",".gradle/gradle.properties",".cache/huggingface/token",".kynver/credentials",".kynver/credentials.json",".kynver/chat-box-credential",".kynver/config.json"],js=[".env",".env.*","*.env",".envrc","credentials","credentials.json","*credentials*.json","*service-account*.json","*service_account*.json","*.pem","*.p12","*.pfx","id_rsa","id_rsa.*","id_ed25519","id_ed25519.*","id_ecdsa","id_ecdsa.*"],H8=[".nvm",".npm",".cache",".local/bin",".local/lib",".local/share",".local/state",".cargo",".rustup",".pyenv",".rbenv",".bun",".deno",".volta",".fnm",".sdkman",".yarn",".pnpm-store",".conda","miniconda3","anaconda3",".gem",".m2",".gradle",".nuget",".dotnet",".go","go",".gitconfig"],j8=["/home","/root","/Users","/mnt","/media","/Volumes"];ao=3128,q8=new RegExp([`failed to connect to (?:localhost|127\\.0\\.0\\.1|::1|\\[::1\\]) port ${ao}\\b`,`(?:localhost|127\\.0\\.0\\.1|\\[::1\\]|::1):${ao}\\b[^\\n]{0,80}?(?:connection refused|econnrefused)`,`(?:connection refused|econnrefused)[^\\n]{0,80}?(?:localhost|127\\.0\\.0\\.1|::1):${ao}\\b`,`(?:cannot|could not|unable to) connect to proxy[^\\n]{0,80}?${ao}\\b`,`proxyerror[^\\n]{0,120}?${ao}\\b`].join("|"),"i");q0=null;Q0=null;X8=/sandbox/i,Q8=/unavailable|not available|not supported|unsupported|bubblewrap|bwrap|socat|failIfUnavailable|seccomp|could not (?:be )?(?:start|initiali[sz]e)|failed to (?:start|initiali[sz]e)/i;Y0="Your shell and file tools are confined to the chosen folder(s) this turn: other folders, dotfiles, ~/.ssh, ~/private, ~/.config, credential and .env files are not readable, writes stay in the folder, and the environment carries no secrets. Work inside the folder; if something is refused, say so.",Z8="The folder limits files, not the internet: shell downloads (curl, wget, pip, npm, git \u2026) reach any public website through the sandbox's HTTP proxy. Only private, loopback, link-local and cloud-metadata addresses are refused (a 403 'Kynver folder sandbox' from the proxy says so). The sandbox's proxy bridge takes a moment to start in each new shell command: curl and wget here already retry a refused connection; in Python or other clients, retry a connection refused on localhost:3128 a few times (or `sleep 1` first). If a command still fails with 'Failed to connect to localhost port 3128', retry the command once; if it fails the same way again, the sandbox network proxy is not running on this computer: say exactly that. Never report such a failure as a blocked website or ask the user to allow a host.",e5="Shell network this turn is limited to package registries and code hosts (the computer's sandbox egress proxy is not running); fetch other websites with WebFetch, and say so when a shell download is refused.",t5="Shell commands are OFF this turn: this computer cannot confine them to the chosen folder, so only the file tools are available (reads and edits inside the folder). If the job needs commands, tell the user: on Linux/WSL2 install bubblewrap and socat, or choose full computer access in Kynver's Computers settings. Never claim to have run a command.",r5="Shell commands are NOT confined to the chosen folder on this computer (folder sandbox set to best-effort). Treat the folder boundary as a rule you follow yourself: do not read or change anything outside the chosen folder(s), and never look for credentials elsewhere on the computer."});function s5(e){let t=e[yf];return new Set(t?t.split(/[\s,]+/).map(r=>r.trim()).filter(Boolean):[])}function Ak(e,t={}){return o5.has(e)||t.operatorAllow?.has(e)||e===Ik?!1:n5.some(r=>r.test(e))}function Yt(e=process.env){let t=di(e);for(let n of Pk)delete t[n];let r=s5(e);for(let n of Object.keys(t))Ak(n,{operatorAllow:r})&&delete t[n];return t[Ik]="1",t}function rD(e){let t=e.toUpperCase();return c5.has(t)||t===Ik?!0:a5.has(t)?!Ak(t):l5.some(r=>t.startsWith(r))?!Ak(t)&&!/(_KEY|_TOKEN|_SECRET|_PASSWORD)$/i.test(t):!1}function u5(e=process.env){let t={};for(let[n,o]of Object.entries(e))typeof o=="string"&&rD(n)&&(t[n]=o);let r=Yt(t);for(let n of Object.keys(r))rD(n)||delete r[n];return r}function nD(e,t){return t==="folder"||t==="folders"?u5(e):Yt(e)}function Ok(){return[`--disallowedTools=${d5.join(",")}`]}var Pk,Ik,n5,o5,i5,a5,l5,c5,d5,lo=p(()=>{"use strict";pi();Pk=["KYNVER_API_KEY","KYNVER_RUNNER_TOKEN","KYNVER_CHAT_BOX_CREDENTIAL","KYNVER_CHAT_BOX_TOKEN","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","OPENCLAW_RUNNER_TOKEN","KYNVER_WORKER_API_KEY","KYNVER_GEMINI_API_KEY","KYNVER_OPENAI_API_KEY"],Ik="KYNVER_CHAT_CHILD",n5=[/_URL$/i,/SECRET/i,/CREDENTIAL/i,/DATABASE/i,/ACCESS_KEY/i,/PASSWORD|PASSWD|_PWD$|^PGPASS/i,/_DSN$/i,/CONNECTION_STRING|CONN_STR/i,/PRIVATE_KEY/i,/SERVICE_ACCOUNT/i,/AUTHTOKEN|_AUTH$/i,/_API_KEY_|APIKEY/i],o5=new Set(hf);i5=["PATH","HOME","USER","LOGNAME","SHELL","PWD","TMPDIR","TMP","TEMP","TZ","LANG","LANGUAGE","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","SSL_CERT_FILE","SSL_CERT_DIR","NODE_EXTRA_CA_CERTS","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","XDG_CACHE_HOME","XDG_DATA_HOME","NVM_DIR","NVM_BIN","NVM_INC","VOLTA_HOME","FNM_DIR","N_PREFIX","PNPM_HOME","BUN_INSTALL","DENO_INSTALL","PYENV_ROOT","VIRTUAL_ENV","CONDA_PREFIX","PYTHONIOENCODING","GOPATH","GOROOT","CARGO_HOME","RUSTUP_HOME","JAVA_HOME","DOTNET_ROOT","HOMEBREW_PREFIX","HOMEBREW_CELLAR","HOMEBREW_REPOSITORY","AWS_REGION","AWS_DEFAULT_REGION","AWS_PROFILE","GOOGLE_CLOUD_PROJECT","CLOUD_ML_REGION","SYSTEMROOT","WINDIR","SYSTEMDRIVE","COMSPEC","PATHEXT","USERPROFILE","HOMEDRIVE","HOMEPATH","USERNAME","APPDATA","LOCALAPPDATA","PROGRAMDATA","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMW6432","COMMONPROGRAMFILES","COMMONPROGRAMFILES(X86)","ALLUSERSPROFILE","PUBLIC","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"],a5=new Set(i5.map(e=>e.toUpperCase())),l5=["LC_","CLAUDE_CODE_","CLAUDE_","ANTHROPIC_","DISABLE_","MAX_THINKING_","BASH_DEFAULT_","BASH_MAX_"],c5=new Set(["CLAUDE_CODE_OAUTH_TOKEN"]);d5=["Read(~/.kynver/credentials)","Read(~/.kynver/credentials.*)","Read(~/.kynver/chat-box-credential)","Read(~/.kynver/site-logins/**)"]});import{spawn as p5}from"node:child_process";async function oD(e=process.env,t={}){let r=t.now??(()=>new Date),n="KYNVER_API_KEY",o={...e,[n]:e[n]??"canary-not-a-real-key"},s=Yt(o),i=new Set([...Pk,...gf]);return new Promise(a=>{let l="",c=!1,u=m=>{c||(c=!0,clearTimeout(f),a({...m,at:r().toISOString()}))},d;try{d=p5(t.execPath??process.execPath,["-e",f5],z({env:s,stdio:["ignore","pipe","ignore"]}))}catch(m){u({ok:!1,leaked:[],error:m instanceof Error?m.message:String(m)});return}let f=setTimeout(()=>{d.kill("SIGKILL"),u({ok:!1,leaked:[],error:"self-test timed out"})},t.timeoutMs??1e4);d.stdout?.on("data",m=>{l+=m.toString("utf8")}),d.on("error",m=>u({ok:!1,leaked:[],error:m.message})),d.on("close",()=>{let m;try{m=JSON.parse(l)}catch{u({ok:!1,leaked:[],error:"self-test child printed no env listing"});return}let g=Array.isArray(m)?m.filter(h=>typeof h=="string"&&i.has(h)).sort():[];u({ok:g.length===0,leaked:g})})})}var f5,sD=p(()=>{"use strict";M();lo();pi();f5="process.stdout.write(JSON.stringify(Object.keys(process.env)))"});import{existsSync as m5,mkdirSync as g5,readFileSync as h5,writeFileSync as y5}from"node:fs";import{homedir as k5}from"node:os";import Tk from"node:path";function Nk(e=k5()){return Tk.join(e,b5)}function iD(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function v5(e){return typeof e.access!="string"?null:{access:e.access,folders:iD(e.folders),source:e.source??"default",signed:e.signed===!0,at:typeof e.at=="string"?e.at:""}}function R5(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(typeof r.access=="string")return{access:r.access,folders:iD(r.folders),changedAt:typeof r.changedAt=="string"?r.changedAt:"",nonce:typeof r.nonce=="string"?r.nonce:"",at:typeof r.at=="string"?r.at:""}}return t&&t.source==="website"?{access:t.access,folders:[...t.folders],changedAt:t.at,nonce:"",at:t.at}:null}function zd(e=Nk()){try{if(!m5(e))return{applied:null,website:null};let t=JSON.parse(h5(e,"utf8"));if(!t||typeof t!="object")return{applied:null,website:null};let r=v5(t);return{applied:r,website:R5(t.website,r)}}catch{return{applied:null,website:null}}}function aD(e,t){try{g5(Tk.dirname(e),{recursive:!0});let r={...t.applied??{},...t.website?{website:t.website}:{}};y5(e,`${JSON.stringify(r,null,2)}
|
|
200
|
+
`,{mode:384})}catch{}}function w5(e,t){return e?e.access===t.access&&e.source===t.source&&e.folders.length===t.folders.length&&e.folders.every((r,n)=>r===t.folders[n]):!1}function lD(e,t={signed:!1}){let r=t.file??Nk(),n=t.now??(()=>new Date),o={access:e.access,folders:[...e.folders],source:e.source,signed:t.signed,at:n().toISOString()},s=zd(r);return w5(s.applied,o)?null:(aD(r,{applied:o,website:s.website}),{from:s.applied,to:o})}function cD(e,t={}){let r=t.file??Nk(),n=t.now??(()=>new Date),o=zd(r),s={access:e.access,folders:[...e.folders],changedAt:e.changedAt,nonce:e.nonce,at:n().toISOString()},i=o.website;return i&&i.access===s.access&&i.changedAt===s.changedAt&&i.nonce===s.nonce&&i.folders.length===s.folders.length&&i.folders.every((l,c)=>l===s.folders[c])?i:(aD(r,{applied:o.applied,website:s}),s)}function Xa(e){switch(e){case"off":return"off";case"folder":return"one folder";case"folders":return"chosen folders";case"full":return"full computer";default:return String(e)}}var b5,uD=p(()=>{"use strict";b5=Tk.join(".kynver","chat-access-state.json")});import{verify as S5,createPublicKey as _5}from"node:crypto";function E5(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let r=t.payload;return!(!r||typeof r!="object"||r.v!==1||r.kind!=="chat-access-change"||typeof r.agentOsId!="string"||!r.agentOsId||typeof r.boxId!="string"||!r.boxId||typeof r.access!="string"||!r.access||!Array.isArray(r.folders)||!r.folders.every(n=>typeof n=="string")||typeof r.changedAt!="string"||Number.isNaN(Date.parse(r.changedAt))||typeof r.exp!="number"||!Number.isFinite(r.exp)||typeof r.nonce!="string"||!r.nonce)}function dD(e){return!e||typeof e!="object"||Array.isArray(e)?null:e[x5]??null}function A5(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function P5(e,t){let r=Date.parse(e),n=Date.parse(t);return Number.isNaN(r)?!1:Number.isNaN(n)?!0:r>n}function Dk(e,t,r={}){let n=r.env??process.env,o=r.nowSec??Math.floor(Date.now()/1e3);if(e==null)return{ok:!1,code:"missing",reason:"the turn carries no signed settings-change record for this raise"};if(!E5(e))return{ok:!1,code:"malformed",reason:"malformed settings-change record"};let{payload:s}=e;if(s.agentOsId!==t.agentOsId)return{ok:!1,code:"mismatch",reason:"settings-change record is for another workspace"};if(s.boxId!==t.boxId)return{ok:!1,code:"mismatch",reason:"settings-change record is for another computer"};if(s.access!==t.access||!A5(s.folders,t.folders))return{ok:!1,code:"mismatch",reason:"settings-change record does not match the access the turn asks for"};if(s.exp<=o)return{ok:!1,code:"expired",reason:"settings-change record expired \u2014 save the setting again in Computers settings"};let i=Tn(e.publicKeyId,n);if(!i)return{ok:!1,code:"no_verification_key",reason:`no verification key for publicKeyId "${e.publicKeyId}"`};let a;try{a=Buffer.from(e.signature,"base64url")}catch{return{ok:!1,code:"bad_signature",reason:"signature is not base64url"}}if(a.length!==64)return{ok:!1,code:"bad_signature",reason:"signature is not a 64-byte Ed25519 signature"};let l=!1;try{let u=Buffer.from(nt(s),"utf8"),d=_5({key:Buffer.concat([C5,Buffer.from(i)]),format:"der",type:"spki"});l=S5(null,u,d,a)}catch(u){return{ok:!1,code:"bad_signature",reason:`signature verification failed: ${u.message}`}}if(!l)return{ok:!1,code:"bad_signature",reason:"Ed25519 signature mismatch"};let c=r.lastApplied??null;return c&&(c.nonce===s.nonce||!P5(s.changedAt,c.changedAt))?{ok:!1,code:"replayed",reason:"settings-change record is not newer than the one this computer last applied"}:{ok:!0,payload:s}}var ZTe,x5,C5,pD=p(()=>{"use strict";Hr();Li();ZTe=720*60*60,x5="change",C5=Buffer.from("302a300506032b6570032100","hex")});function fD(e){switch(e){case"off":return 0;case"folder":case"folders":return 1;case"full":return 2;default:return 0}}function I5(e,t){let r=fD(e.access),n=fD(t.access);if(r!==n)return r>n;if(r!==1)return!1;let o=new Set(_n(t.folders));return _n(e.folders).some(s=>!o.has(s))}function O5(e,t){if(!e||!e.byBox||typeof e.byBox!="object"||!Object.prototype.hasOwnProperty.call(e.byBox,t))return null;let r=e.byBox[t];if(!r||typeof r!="object")return null;let n=Go(r.access);if(!n)return null;let o=r.folders,s=Array.isArray(o)?o.filter(i=>typeof i=="string"):[];return{level:{access:n,folders:s},change:dD(r)}}function gD(e){let t=O5(e.signedAccess,e.boxId);if(!t)return{ok:!0,website:null,raised:!1};let r=Go(e.local.chatComputerAccess);if(r==="off")return{ok:!0,website:null,raised:!1};let n=[];e.state.website&&n.push({access:e.state.website.access,folders:e.state.website.folders}),n.push(r?{access:r,folders:_n(e.local.chatWorkFolders)}:{access:Rc(e.engine),folders:[]});let o=n.every(c=>I5(t.level,c)),s=(e.now??(()=>new Date))().toISOString(),i=e.state.website;if(!o){let c=t.change!==null?Dk(t.change,{agentOsId:e.agentOsId,boxId:e.boxId,access:t.level.access,folders:t.level.folders},{env:e.env,nowSec:e.nowSec,lastApplied:mD(i)}):null;return{ok:!0,raised:!1,website:{access:t.level.access,folders:[...t.level.folders],changedAt:c?.ok?c.payload.changedAt:i?.changedAt??"",nonce:c?.ok?c.payload.nonce:i?.nonce??"",at:s}}}let a=Dk(t.change,{agentOsId:e.agentOsId,boxId:e.boxId,access:t.level.access,folders:t.level.folders},{env:e.env,nowSec:e.nowSec,lastApplied:mD(i)}),l=i?.access??r??Rc(e.engine);return a.ok?{ok:!0,raised:!0,website:{access:t.level.access,folders:[...t.level.folders],changedAt:a.payload.changedAt,nonce:a.payload.nonce,at:s}}:{ok:!1,code:"access_raise",detail:a.code,reason:a.reason,from:l,to:t.level.access}}function mD(e){return!e||!e.changedAt&&!e.nonce?null:{changedAt:e.changedAt,nonce:e.nonce}}var hD=p(()=>{"use strict";pD();xn()});function T5(e){let r=e.chatProvider?.trim()||e.workerProvider?.trim()||"";return je(r)}function co(e,t=process.env){return T5(e)!=="gemini"?"http":vs(ht(t))==="antigravity"?"antigravity":"http"}var Xd=p(()=>{"use strict";qn();Oi()});import{spawnSync as vD}from"node:child_process";import{existsSync as N5,readFileSync as D5}from"node:fs";import{homedir as M5,platform as L5}from"node:os";import yD from"node:path";function Qd(e,t,r=process.env){return e==="cursor"?"cursor":e==="codex"?"codex":e==="gemini"?co(t,r)==="antigravity"?"antigravity":"none":e==="anthropic"?"claude-code":"none"}function B5(e,t){return e==="cursor"?$n(t):e==="codex"?t.KYNVER_CODEX_BIN?.trim()||t.CODEX_BIN?.trim()||xr():e==="antigravity"?ht(t):e==="claude-code"?t.KYNVER_CLAUDE_BIN?.trim()||t.CLAUDE_BIN?.trim()||"claude":null}function Zd(e,t=process.env,r=Date.now()){let n=B5(e,t);if(!n)return null;let o=kD.get(n);if(o&&r-o.at<RD)return o.version;let s=null;try{let[i,a]=ae(n,["--version"]),l=vD(i,a,z({encoding:"utf8",timeout:5e3})),c=`${l.stdout??""} ${l.stderr??""}`;s=l.status===0?c.match(W5)?.[0]??null:null}catch{s=null}return kD.set(n,{at:r,version:s}),s}function ep(e=process.env,t={}){if(e.ANTHROPIC_API_KEY?.trim())return!0;let r=t.home??M5(),n=t.now??Date.now(),o=bD.get(r);if(o&&n-o.at<RD)return o.signedIn;let s=U5(yD.join(e.CLAUDE_CONFIG_DIR?.trim()||yD.join(r,".claude"),".credentials.json"));return!s&&(t.os??L5())==="darwin"&&(s=(t.keychain??F5)()),bD.set(r,{at:n,signedIn:s}),s}function U5(e){if(!N5(e))return!1;try{let t=JSON.parse(D5(e,"utf8")).claudeAiOauth,r=n=>typeof n=="string"&&n.length>0;return!!t&&(r(t.refreshToken)||r(t.accessToken))}catch{return!1}}function F5(){try{return vD("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}var W5,RD,kD,bD,Qa=p(()=>{"use strict";Vn();ys();qn();qe();M();Xd();W5=/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/,RD=10*6e4,kD=new Map;bD=new Map});import{appendFileSync as K5,mkdirSync as $5}from"node:fs";import{homedir as H5}from"node:os";import Mk from"node:path";function Lk(e=H5()){return Mk.join(e,j5)}function Bk(e){let t=r=>r===void 0?void 0:r.length>wD?`${r.slice(0,wD)}\u2026`:r;return{...e,...e.command!==void 0?{command:t(e.command)}:{},...e.path!==void 0?{path:t(e.path)}:{}}}function Za(e,t=Lk()){try{return $5(Mk.dirname(t),{recursive:!0}),K5(t,`${JSON.stringify(Bk(e))}
|
|
201
|
+
`,{encoding:"utf8",mode:384}),!0}catch(r){return console.error(JSON.stringify({event:"chat_command_log_write_failed",error:r instanceof Error?r.message:String(r)})),!1}}var j5,wD,tp=p(()=>{"use strict";j5=Mk.join(".kynver","logs","chat-commands.jsonl"),wD=2e3});var ln,rp=p(()=>{"use strict";ln=class{constructor(t,r=150){this.flushFn=t;this.floorMs=r}flushFn;floorMs;buffer="";timer=null;closed=!1;push(t){this.closed||!t||(this.buffer+=t,this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flushNow()},this.floorMs)))}flushNow(){if(!this.buffer)return;let t=this.buffer;this.buffer="",this.flushFn(t)}flush(){this.closed||(this.timer&&(clearTimeout(this.timer),this.timer=null),this.flushNow())}close(){this.closed||(this.closed=!0,this.timer&&(clearTimeout(this.timer),this.timer=null),this.flushNow())}}});var uo,Wk=p(()=>{"use strict";uo=class{pending=new Set;track(t){let r=t.finally(()=>{this.pending.delete(r)});return this.pending.add(r),r}async drain(){this.pending.size!==0&&await Promise.allSettled([...this.pending])}}});function SD(e){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"))return{ok:!1,mutating:!1,reason:"argv must be a non-empty string array"};for(let n of e){if(Y5.some(o=>n===o||n.startsWith(`${o}=`)))return{ok:!1,mutating:!1,reason:`forbidden flag: ${n}`};if(n.includes(`
|
|
202
|
+
`)||n.includes("\0"))return{ok:!1,mutating:!1,reason:"control characters refused"}}let t=e[0],r=e.length>1&&!e[1].startsWith("--")?`${t} ${e[1]}`:t;if(t==="doctor"){let n=e[1]&&!e[1].startsWith("--")?e[1]:void 0;return n&&!z5.has(n)?{ok:!1,mutating:!1,reason:`verb not allowlisted: ${r}`}:{ok:!0,mutating:e.some(s=>s==="--remediate"||s==="--remediate-default-repo"||s.startsWith("--remediate="))}}return t==="cleanup"?{ok:!0,mutating:e.includes("--execute")}:r==="update finish"?{ok:!1,mutating:!0,reason:J5}:r==="run dispatch"?{ok:!1,mutating:!0,reason:G5}:V5.has(r)?{ok:!0,mutating:!1}:q5.has(r)?{ok:!0,mutating:!0}:{ok:!1,mutating:!1,reason:`verb not allowlisted: ${r}`}}var V5,G5,J5,q5,Y5,z5,_D=p(()=>{"use strict";V5=new Set(["run list","run status","worker list","worker status","worker tail","status","cron status","monitor status","monitor list","update check","update status"]),G5="run dispatch is blocked from runtime_command \u2014 use agent_os_submit_action_intent with kind dispatch_workers (live dispatch requires Action Required approval)",J5='update finish is internal to `kynver update` \u2014 call ["update"] (confirmed) to update Kynver',q5=new Set(["run create","run sweep","worker start","worker stop","worker complete","cleanup","update"]),Y5=["--secret","--api-key","--keeper-child"],z5=new Set(["runner-install","node-runtime","local-store","context-envelope","runtime-takeover"])});import{spawn as X5}from"node:child_process";function e9(e,t,r,n=process.env){let o=gS(r,{agentOsId:e,argv:t},n);return o.ok?null:`command authorization proof invalid: ${o.reason}`}async function CD(e,t,r={}){if(r.agentOsId){let a=e9(r.agentOsId,e,r.authProof,r.env??process.env);if(a)return{exitCode:null,timedOut:!1,refused:a}}else return{exitCode:null,timedOut:!1,refused:"command authorization proof required (missing agentOsId)"};let n=SD(e);if(!n.ok)return{exitCode:null,timedOut:!1,refused:n.reason};let o=r.cliEntry??process.argv[1],s=r.timeoutMs??Q5,i=new ln(t);return new Promise(a=>{let l=0,c=!1,u=X5(process.execPath,[o,...e],z({stdio:["ignore","pipe","pipe"],env:process.env})),d=m=>{if(l>=xD)return;let g=m.toString("utf8").slice(0,xD-l);l+=g.length,i.push(g)};u.stdout?.on("data",d),u.stderr?.on("data",d);let f=setTimeout(()=>{c=!0,Ze(u,"SIGTERM"),setTimeout(()=>Ze(u,"SIGKILL"),Z5).unref()},s);u.on("error",m=>{clearTimeout(f),i.push(`spawn failed: ${m.message}`),i.close(),a({exitCode:null,timedOut:!1,refused:void 0})}),u.on("close",m=>{clearTimeout(f),i.close(),a({exitCode:m,timedOut:c})})})}var Q5,Z5,xD,ED=p(()=>{"use strict";M();rp();_D();Li();Q5=10*6e4,Z5=5e3,xD=2e5});function AD(e=process.env){return e.KYNVER_OPENAI_DEFAULT_MODEL?.trim()||t9}var t9,MNe,PD=p(()=>{"use strict";ma();_u();$t();t9="gpt-5.5",MNe=600*1e3});function po(e){let t=e.chatProvider?.trim();return Vs(t||e.workerProvider?.trim()||"cursor")}function Vs(e){let t=je(e);return t==="cursor"||t==="agent"?"cursor":o9.has(t)?"gemini":ID.has(t)||ID.has(e.trim().toLowerCase())?"codex":OD.has(t)||OD.has(e.trim().toLowerCase())?"openai":(n9.has(t),"anthropic")}function Gs(e,t,r=process.env){let n=r.KYNVER_CHAT_MODEL?.trim();if(n){if(e==="cursor"){let s=hs(n,el);return s.ok?s.model:el}if(e==="gemini"&&!Uk.test(n)&&!Fk.test(n)||(e==="openai"||e==="codex")&&!Uk.test(n)&&!TD.test(n)||e==="anthropic")return n}let o=t.defaultModel?.trim();if(e==="cursor"){if(o&&!Uk.test(o)){let s=hs(o,el);return s.ok?s.model:el}return el}return e==="gemini"?o&&TD.test(o)?o:Ke(r):e==="codex"?o&&Fk.test(o)?o:r.KYNVER_CODEX_DEFAULT_MODEL?.trim()||r9:e==="openai"?o&&Fk.test(o)?o:AD(r):o||"claude-sonnet-4-6"}var el,r9,n9,o9,ID,OD,Uk,TD,Fk,tl=p(()=>{"use strict";Bn();$t();ga();PD();el="composer-2.5",r9="gpt-5.5",n9=new Set(["claude","anthropic","opus"]),o9=new Set(["gemini","gemini-api"]),ID=new Set(["codex","chatgpt","gpt"]),OD=new Set(["openai","openai-compatible","openai-api","openai_api"]);Uk=/^(?:claude[-_]|opus\b|sonnet\b|haiku\b)/i,TD=/^(?:gemini[-_]|flash\b|pro\b)/i,Fk=/^(?:gpt-|o\d|chatgpt-)/i});function rl(e){let t=new Set;for(let r of e.matchAll(/^\s*(\S+\.so[\w.]*)\s*=>\s*not found/gm))t.add(r[1]);for(let r of e.matchAll(/error while loading shared libraries:\s*(\S+?\.so[\w.]*)\s*:/g))t.add(r[1]);return[...t].sort()}function i9(e){return{apt:e.t64?1:0,dnf:2,zypper:3,pacman:4,apk:5,unknown:null}[e.family]}function a9(e,t){let r=i9(t);if(r===null)return[];let n=new Set;for(let o of e){let s=s9.find(([i])=>i.test(o));s&&n.add(s[1][r])}return[...n].sort()}function l9(e,t){if(e.length===0)return null;switch(t.family){case"apt":return["apt-get","install","-y","--no-install-recommends",...e];case"dnf":return["dnf","install","-y",...e];case"zypper":return["zypper","--non-interactive","install",...e];case"pacman":return["pacman","-S","--noconfirm","--needed",...e];case"apk":return["apk","add",...e];default:return null}}function ND(e,t){let r=a9(e,t),n=l9(r,t),o=t.family==="apt"?"sudo apt-get update && ":"";return n?`The browser needs system libraries this computer is missing. Run: ${o}sudo ${n.join(" ")} \u2014 or \`kynver browser install --deps\` if you have passwordless sudo.`:`The browser needs system libraries this computer is missing (${e.join(", ")}). Install them with your distribution's package manager, then try again.`}var s9,np=p(()=>{"use strict";s9=[[/^lib(nss3|nssutil3|smime3|ssl3)\.so/,["libnss3","libnss3","nss","mozilla-nss","nss","nss"]],[/^libnspr4\.so/,["libnspr4","libnspr4","nspr","mozilla-nspr","nspr","nspr"]],[/^libatk-1\.0\.so/,["libatk1.0-0","libatk1.0-0t64","atk","libatk-1_0-0","at-spi2-core","at-spi2-core"]],[/^libatk-bridge-2\.0\.so/,["libatk-bridge2.0-0","libatk-bridge2.0-0t64","at-spi2-atk","libatk-bridge-2_0-0","at-spi2-core","at-spi2-core"]],[/^libatspi\.so/,["libatspi2.0-0","libatspi2.0-0t64","at-spi2-core","libatspi0","at-spi2-core","at-spi2-core"]],[/^libcups\.so/,["libcups2","libcups2t64","cups-libs","libcups2","libcups","cups-libs"]],[/^libdrm\.so/,["libdrm2","libdrm2","libdrm","libdrm2","libdrm","libdrm"]],[/^libgbm\.so/,["libgbm1","libgbm1","mesa-libgbm","libgbm1","mesa","mesa-gbm"]],[/^libxkbcommon\.so/,["libxkbcommon0","libxkbcommon0","libxkbcommon","libxkbcommon0","libxkbcommon","libxkbcommon"]],[/^libXcomposite\.so/,["libxcomposite1","libxcomposite1","libXcomposite","libXcomposite1","libxcomposite","libxcomposite"]],[/^libXdamage\.so/,["libxdamage1","libxdamage1","libXdamage","libXdamage1","libxdamage","libxdamage"]],[/^libXfixes\.so/,["libxfixes3","libxfixes3","libXfixes","libXfixes3","libxfixes","libxfixes"]],[/^libXrandr\.so/,["libxrandr2","libxrandr2","libXrandr","libXrandr2","libxrandr","libxrandr"]],[/^libXext\.so/,["libxext6","libxext6","libXext","libXext6","libxext","libxext"]],[/^libX11\.so/,["libx11-6","libx11-6","libX11","libX11-6","libx11","libx11"]],[/^libxcb\.so/,["libxcb1","libxcb1","libxcb","libxcb1","libxcb","libxcb"]],[/^libpango-1\.0\.so/,["libpango-1.0-0","libpango-1.0-0","pango","libpango-1_0-0","pango","pango"]],[/^libcairo\.so/,["libcairo2","libcairo2","cairo","libcairo2","cairo","cairo"]],[/^libasound\.so/,["libasound2","libasound2t64","alsa-lib","libasound2","alsa-lib","alsa-lib"]],[/^libgtk-3\.so/,["libgtk-3-0","libgtk-3-0t64","gtk3","libgtk-3-0","gtk3","gtk+3.0"]],[/^lib(glib|gio|gobject)-2\.0\.so/,["libglib2.0-0","libglib2.0-0t64","glib2","libglib-2_0-0","glib2","glib"]],[/^libdbus-1\.so/,["libdbus-1-3","libdbus-1-3","dbus-libs","libdbus-1-3","dbus","dbus-libs"]],[/^libexpat\.so/,["libexpat1","libexpat1","expat","libexpat1","expat","expat"]],[/^libudev\.so/,["libudev1","libudev1","systemd-libs","libudev1","systemd-libs","eudev-libs"]]]});import{spawnSync as c9}from"node:child_process";function d9(e){return/(\d+\.\d+\.\d+\.\d+)/.exec(e)?.[1]??null}function p9(e,t=process.platform,r=u9){let n=new Set;if(t==="linux"){let s=r("ldd",[e],{encoding:"utf8",timeout:1e4});if(!s.error)for(let i of rl(`${s.stdout??""}
|
|
139
203
|
${s.stderr??""}`))n.add(i)}let o=null;if(t!=="win32"){let s=r(e,["--version"],{encoding:"utf8",timeout:1e4}),i=`${s.stdout??""}
|
|
140
|
-
${s.stderr??""}`;for(let a of Ga(i))n.add(a);s.status===0&&(o=R8(i))}return{version:o,missingLibs:[...n].sort()}}function M0(e,t=()=>w8(e),r=Date.now){let n=dk.get(e);if(n&&r()-n.at<S8)return n.health;let o=t();return dk.set(e,{at:r(),health:o}),o}function L0(){dk.clear()}var v8,S8,dk,pk=p(()=>{"use strict";$d();v8=(e,t,r)=>b8(e,t,r);S8=10*6e4,dk=new Map});import{existsSync as _8,readFileSync as B0}from"node:fs";function Ws(e,t){return e==="linux"?t==="x64"?"linux64":null:e==="darwin"?t==="arm64"?"mac-arm64":"mac-x64":e==="win32"?t==="ia32"?"win32":"win64":null}function W0(e,t){try{return e(t)}catch{return""}}function Ja(e=process.env,t=process.platform,r={}){if(t!=="linux")return!1;if(e.WSL_DISTRO_NAME?.trim()||e.WSL_INTEROP?.trim())return!0;let n=r.readFile??(o=>B0(o,"utf8"));return/microsoft|wsl/i.test(W0(n,"/proc/version"))}function x8(e=process.env,t=process.platform,r={}){if(t!=="linux")return{available:!0,wslg:!1};let n=r.exists??_8,o=Ja(e,t,r)&&n("/mnt/wslg");return{available:!!(e.DISPLAY?.trim()||e.WAYLAND_DISPLAY?.trim()),wslg:o}}function Kd(e=process.env,t=process.platform){return/^(1|true|yes|on)$/i.test(e.KYNVER_BROWSER_HEADLESS??"")?!0:!x8(e,t).available}function C8(e){let t={};for(let l of e.split(/\r?\n/)){let c=/^([A-Z_]+)=(.*)$/.exec(l.trim());c&&(t[c[1]]=c[2].replace(/^["']|["']$/g,""))}let r=(t.ID??"").toLowerCase(),n=`${r} ${(t.ID_LIKE??"").toLowerCase()}`,o=t.VERSION_ID??"",s="unknown";/\b(debian|ubuntu)\b/.test(n)?s="apt":/\b(fedora|rhel|centos)\b/.test(n)?s="dnf":/\b(suse|opensuse)\b/.test(n)?s="zypper":/\barch\b/.test(n)?s="pacman":/\balpine\b/.test(n)&&(s="apk");let i=Number.parseFloat(o),a=s==="apt"&&(r==="ubuntu"&&Number.isFinite(i)&&i>=24||r==="debian"&&Number.isFinite(i)&&i>=13);return{id:r,versionId:o,family:s,t64:a}}function U0(e={}){let t=e.readFile??(r=>B0(r,"utf8"));return C8(W0(t,"/etc/os-release"))}var io=p(()=>{"use strict"});import{existsSync as E8,readdirSync as A8}from"node:fs";import{homedir as P8}from"node:os";import ao from"node:path";function Hd(e=process.env){return e.KYNVER_BROWSER_INSTALL_DIR?.trim()||ao.join(P8(),".kynver","browsers")}function F0(e,t=process.env){return ao.join(Hd(t),`chrome-${e}`)}function jd(e,t){let r=ao.join(e,`chrome-${t}`);return t==="linux64"?ao.join(r,"chrome"):t==="win32"||t==="win64"?ao.join(r,"chrome.exe"):ao.join(r,"Google Chrome for Testing.app","Contents","MacOS","Google Chrome for Testing")}function I8(e,t){let r=e.split(".").map(o=>Number.parseInt(o,10)||0),n=t.split(".").map(o=>Number.parseInt(o,10)||0);for(let o=0;o<Math.max(r.length,n.length);o+=1){let s=(r[o]??0)-(n[o]??0);if(s!==0)return s}return 0}function Vd(e,t=process.env,r={}){let n=r.exists??E8,o=r.listDir??(l=>A8(l)),s=Hd(t),i;try{i=o(s)}catch{return null}let a=i.map(l=>/^chrome-(\d+(?:\.\d+){1,3})$/.exec(l)?.[1]).filter(l=>!!l).sort(I8).reverse();for(let l of a){let c=ao.join(s,`chrome-${l}`),u=jd(c,e);if(n(u))return{executable:u,version:l,installDir:c}}return null}var fk=p(()=>{"use strict"});import{existsSync as O8,readdirSync as T8}from"node:fs";import{homedir as N8}from"node:os";import Or from"node:path";function D8(e,t,r=N8()){return e==="win32"?[t.PROGRAMFILES,t["PROGRAMFILES(X86)"],t.LOCALAPPDATA].filter(o=>typeof o=="string"&&o.length>0).flatMap(o=>[Or.join(o,"Google","Chrome","Application","chrome.exe"),Or.join(o,"Microsoft","Edge","Application","msedge.exe"),Or.join(o,"Chromium","Application","chrome.exe")]):e==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",Or.join(r,"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),Or.join(r,"Applications/Chromium.app/Contents/MacOS/Chromium")]:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome","/usr/bin/chromium","/usr/bin/chromium-browser","/usr/lib/chromium/chromium","/snap/bin/chromium","/usr/bin/microsoft-edge","/usr/bin/microsoft-edge-stable","/opt/microsoft/msedge/msedge","/var/lib/flatpak/exports/bin/com.google.Chrome","/var/lib/flatpak/exports/bin/org.chromium.Chromium",Or.join(r,".local/share/flatpak/exports/bin/com.google.Chrome"),Or.join(r,".local/share/flatpak/exports/bin/org.chromium.Chromium"),...$0.map(n=>Or.join(r,".local/bin",n))]}function M8(e,t,r){let n=(e.PATH??"").split(":").filter(o=>o&&!(r&&o.startsWith("/mnt/")));for(let o of $0)for(let s of n){let i=Or.join(s,o);if(t(i))return i}return null}function lo(e={}){let t=e.env??process.env,r=e.platform??process.platform,n=e.arch??process.arch,o=e.exists??O8,s=e.config??E(),i=null,a=t.KYNVER_BROWSER_CHROME_PATH?.trim()||s.browserChromePath?.trim()||"";if(a){if(o(a))return{executable:a,source:"configured",version:null,configuredMissing:i};i=a}let l=D8(r,t,e.home).find(u=>o(u));if(l)return{executable:l,source:"system",version:null,configuredMissing:i};if(r==="linux"){let u=M8(t,o,Ja(t,r,{readFile:e.readFile}));if(u)return{executable:u,source:"system",version:null,configuredMissing:i}}let c=Ws(r,n);if(c){let u=s.browserManaged;if(u?.executable&&u.platform===c&&o(u.executable))return{executable:u.executable,source:"managed",version:u.version??null,configuredMissing:i};let d=Vd(c,t,{exists:o,listDir:e.listDir??(m=>T8(m))});if(d)return{executable:d.executable,source:"managed",version:d.version,configuredMissing:i}}return{executable:null,source:"none",version:null,configuredMissing:i}}var $0,qa=p(()=>{"use strict";H();io();fk();$0=["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge","microsoft-edge-stable"]});import{createWriteStream as L8}from"node:fs";import{rm as B8}from"node:fs/promises";function F8(e,t){let r=e?.channels?.Stable;if(!r||typeof r.version!="string"||!/^\d+(\.\d+){1,3}$/.test(r.version))return null;let n=Array.isArray(r.downloads?.chrome)?r.downloads.chrome:[];for(let o of n){let s=o;if(s.platform===t&&typeof s.url=="string"&&s.url.startsWith(H0))return{version:r.version,url:s.url}}return null}async function j0(e,t=fetch){let r=await t(W8,{signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`Chrome for Testing index returned HTTP ${r.status}`);let n=F8(await r.json(),e);if(!n)throw new Error(`No stable Chrome for Testing build is published for ${e}`);return n}async function V0(e,t,r={}){let n=r.minBytes??U8;if(!e.startsWith(H0))throw new Error("refusing to download from an unexpected host");let s=await(r.fetchFn??fetch)(e,{signal:AbortSignal.timeout(r.timeoutMs??15*6e4)});if(!s.ok||!s.body)throw new Error(`browser download returned HTTP ${s.status}`);let i=s.headers.get("content-length"),a=i?Number.parseInt(i,10):null;if(a!==null&&(a<n||a>K0))throw new Error(`browser download has an unexpected size (${a} bytes)`);let l=L8(t),c=0;try{let u=s.body.getReader();for(;;){let{done:d,value:m}=await u.read();if(d)break;if(c+=m.byteLength,c>K0)throw new Error("browser download is larger than expected");l.write(m)||await new Promise(f=>l.once("drain",()=>f())),r.onProgress?.({receivedBytes:c,totalBytes:a})}if(await new Promise((d,m)=>l.end(f=>f?m(f):d())),a!==null&&c!==a)throw new Error(`browser download was cut short (${c} of ${a} bytes)`);if(c<n)throw new Error(`browser download is too small (${c} bytes)`);return c}catch(u){throw l.destroy(),await B8(t,{force:!0}).catch(()=>{}),u}}var W8,H0,U8,K0,G0=p(()=>{"use strict";W8="https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json",H0="https://storage.googleapis.com/chrome-for-testing-public/",U8=20*1024*1024,K0=600*1024*1024});import{chmodSync as $8,mkdirSync as mk,symlinkSync as K8,writeFileSync as H8}from"node:fs";import Us from"node:path";import{crc32 as j8,inflateRawSync as V8}from"node:zlib";function Y8(e){let t=Math.max(0,e.length-65535-22);for(let r=e.length-22;r>=t;r-=1)if(e.readUInt32LE(r)===G8)return r;throw new Error("not a zip archive (no end-of-central-directory record)")}function z8(e){let t=Y8(e),r=e.readUInt16LE(t+10),n=e.readUInt32LE(t+16);if(r===65535||n===4294967295)throw new Error("zip64 archives are not supported");let o=[],s=n;for(let i=0;i<r;i+=1){if(s+46>e.length||e.readUInt32LE(s)!==J8)throw new Error("corrupt zip central directory");let a=e.readUInt16LE(s+4)>>8,l=e.readUInt16LE(s+28),c=e.readUInt16LE(s+30),u=e.readUInt16LE(s+32),d=e.readUInt32LE(s+38);o.push({name:e.subarray(s+46,s+46+l).toString("utf8"),method:e.readUInt16LE(s+10),crc:e.readUInt32LE(s+16),compressedSize:e.readUInt32LE(s+20),size:e.readUInt32LE(s+24),localHeaderOffset:e.readUInt32LE(s+42),unixMode:a===3?d>>>16&65535:null}),s+=46+l+c+u}return o}function X8(e,t){let r=t.localHeaderOffset;if(e.readUInt32LE(r)!==q8)throw new Error(`corrupt zip entry ${t.name}`);let n=r+30+e.readUInt16LE(r+26)+e.readUInt16LE(r+28),o=e.subarray(n,n+t.compressedSize),s;if(t.method===0)s=Buffer.from(o);else if(t.method===8)s=V8(o);else throw new Error(`unsupported zip compression method ${t.method} (${t.name})`);if(s.length!==t.size||j8(s)>>>0!==t.crc>>>0)throw new Error(`zip entry failed its integrity check: ${t.name}`);return s}function J0(e,t){let r=t.replace(/\\/g,"/");if(r.startsWith("/")||/^[a-zA-Z]:/.test(r))throw new Error(`unsafe zip path: ${t}`);let n=Us.resolve(e,r),o=Us.resolve(e);if(n!==o&&!n.startsWith(o+Us.sep))throw new Error(`unsafe zip path: ${t}`);return n}function q0(e,t,r=process.platform){mk(t,{recursive:!0});let n=0;for(let o of z8(e)){let s=J0(t,o.name);if(o.name.endsWith("/")){mk(s,{recursive:!0});continue}mk(Us.dirname(s),{recursive:!0});let i=X8(e,o);if(o.unixMode!==null&&(o.unixMode&Q8)===Z8&&r!=="win32"){let a=i.toString("utf8");J0(t,Us.posix.join(Us.posix.dirname(o.name.replace(/\\/g,"/")),a)),K8(a,s)}else H8(s,i),o.unixMode!==null&&r!=="win32"&&$8(s,o.unixMode&511||420);n+=1}return n}var G8,J8,q8,Q8,Z8,Y0=p(()=>{"use strict";G8=101010256,J8=33639248,q8=67324752;Q8=61440,Z8=40960});import{closeSync as z0,existsSync as gk,mkdirSync as e5,openSync as X0,readFileSync as t5,renameSync as r5,rmSync as Fs,statSync as n5,chmodSync as o5}from"node:fs";import hk from"node:path";function co(){return{...Ot}}function eD(e=Ot){return e.state!=="failed"||e.failedAt===null?0:e.failedAt+Q0[Math.min(e.attempts-1,Q0.length-1)]}function tD(e=Ot){return e.totalBytes&&e.totalBytes>0?`${Math.min(99,Math.floor(e.receivedBytes/e.totalBytes*100))}% of ${Math.round(e.totalBytes/1024/1024)} MB`:e.receivedBytes>0?`${Math.round(e.receivedBytes/1024/1024)} MB so far`:"starting"}function i5(e){let t=E();Le({...t,browserManaged:{version:e.version,platform:e.platform,executable:e.executable,installedAt:new Date().toISOString()}})}function a5(e,t){q0(t5(e),t)}function l5(e,t){try{return z0(X0(e,"wx")),!0}catch{try{if(t-n5(e).mtimeMs>s5)return Fs(e,{force:!0}),z0(X0(e,"wx")),!0}catch{}return!1}}async function c5(e,t){let r=t.env??process.env,n=t.now??Date.now,o=t.sleep??(a=>new Promise(l=>setTimeout(l,a))),s=Hd(r);e5(s,{recursive:!0});let i=hk.join(s,".install.lock");for(;!l5(i,n());)if(await o(2e3),!gk(i)){let a=Vd(e,r);if(a)return a}try{let a=await j0(e,t.fetchFn),l=F0(a.version,r),c=jd(l,e);if(!gk(c)){let d=hk.join(s,`.download-${a.version}.zip`),m=hk.join(s,`.staging-${a.version}-${process.pid}`);Fs(m,{recursive:!0,force:!0});try{await V0(a.url,d,{fetchFn:t.fetchFn,minBytes:t.minArchiveBytes,onProgress:g=>{Ot.receivedBytes=g.receivedBytes,Ot.totalBytes=g.totalBytes}}),(t.extract??a5)(d,m);let f=jd(m,e);if(!gk(f))throw new Error("the downloaded browser archive did not contain Chrome");(t.platform??process.platform)!=="win32"&&o5(f,493),Fs(l,{recursive:!0,force:!0}),r5(m,l)}finally{Fs(d,{force:!0}),Fs(m,{recursive:!0,force:!0})}}let u={executable:c,version:a.version,installDir:l};return(t.record??i5)({...u,platform:e}),u}finally{Fs(i,{force:!0})}}function Gd(e={}){if(Ya)return Ya;let t=Ws(e.platform??process.platform,e.arch??process.arch);if(!t)return Promise.reject(new $s("Google doesn't publish a ready-made Chrome for this kind of computer (Linux on ARM). Install Chromium with your package manager (for example `sudo apt-get install chromium`), then try again.","unsupported_platform"));let r=e.now??Date.now;return Ot={...Ot,state:"downloading",receivedBytes:0,totalBytes:null,error:null},Ya=c5(t,e).then(n=>(Ot={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},L0(),n)).catch(n=>{let o=n instanceof Error?n.message:String(n);throw Ot={...Ot,state:"failed",error:o.slice(0,300),failedAt:r(),attempts:Ot.attempts+1},new $s(`Couldn't download a browser for this computer: ${o.slice(0,200)}`,"download_failed")}).finally(()=>{Ya=null}),Ya}var Z0,s5,Q0,$s,Ot,Ya,Jd=p(()=>{"use strict";H();io();G0();pk();fk();Y0();Z0=150,s5=30*6e4,Q0=[6e4,5*6e4,30*6e4,120*6e4],$s=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserProvisionError"}code},Ot={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},Ya=null});function yk(e){return u5.test(e)}function rD(e=process.platform,t=typeof process.getuid=="function"?process.getuid():null){return e==="linux"&&t===0}function qd(e){nD=e}function oD(){return nD}var u5,nD,kk=p(()=>{"use strict";u5=/Running as root without --no-sandbox|No usable sandbox|setuid sandbox|SUID sandbox helper|Failed to move to new namespace|sandbox_host_linux|credentials\.cc.*(EPERM|Operation not permitted)/i;nD=null});function sD(e=process.env,t={}){let r=t.platform??process.platform,n=E(),o={executable:null,source:"none",version:null,configuredMissing:null};try{o=(t.resolve??(()=>lo({env:e,platform:r,config:n})))()}catch{}let s={version:null,missingLibs:[]};if(o.executable)try{s=(t.health??(i=>M0(i)))(o.executable)}catch{}return{supported:!0,chromeFound:o.executable!==null,localDisabled:n.browserDisabled===!0,browserSource:o.source,browserVersion:o.version??s.version,provisioning:co().state,missingLibs:s.missingLibs,wsl:Ja(e,r),headless:Kd(e,r),autoProvision:n.browserAutoProvision!==!1,sandbox:oD()}}var iD=p(()=>{"use strict";H();pk();io();qa();Jd();kk()});function Yd(e,t,r,n,o){return{chatProvider:e,toolCalls:e==="anthropic"||e==="cursor"||e==="gemini"||e==="openai"||e==="codex",runtimePackageVersion:Dt,browser:sD(),deliveryReceipt:!0,...t?{chatModels:t}:{},...r?{computer:r}:{},...n?{security:n}:{},...o?{agentEngines:o}:{}}}var aD=p(()=>{"use strict";zo();iD()});import{readFileSync as d5}from"node:fs";import{homedir as p5,platform as f5}from"node:os";import m5 from"node:path";import{execFileSync as g5}from"node:child_process";function lD(e,t=Date.now()){try{let r=JSON.parse(e),n=r.claudeAiOauth?.accessToken,o=r.claudeAiOauth?.expiresAt;return typeof n!="string"||!n||typeof o=="number"&&o-t<6e4?null:n}catch{return null}}function h5(){if(f5()==="darwin")try{let e=g5("security",["find-generic-password","-s","Claude Code-credentials","-w"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return lD(e.trim())}catch{return null}try{let e=d5(m5.join(p5(),".claude",".credentials.json"),"utf8");return lD(e)}catch{return null}}function za(e=process.env,t={}){let r=e.ANTHROPIC_API_KEY?.trim();if(r)return{kind:"api_key",key:r};let n=e.KYNVER_CHAT_USE_CLAUDE_OAUTH;if(t.oauthOptIn===!0||n==="1"||n==="true"||n==="yes"){let s=h5();if(s)return{kind:"oauth",token:s}}return null}var bk=p(()=>{"use strict"});import{existsSync as cD}from"node:fs";import{homedir as y5}from"node:os";import Xa from"node:path";import{spawnSync as k5}from"node:child_process";function b5(e){if(Xa.isAbsolute(e)||e.includes("/")||e.includes("\\"))return cD(e);try{let t=k5(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function v5(e=process.env){let t=y5(),r=[],n=e.CODEX_HOME?.trim();return n&&r.push(Xa.join(Xa.resolve(n),"auth.json")),r.push(Xa.join(t,".codex","auth.json")),r.push(Xa.join(t,".config","codex","auth.json")),r}function uD(e){return`${e.error}: ${e.detail}`}function Xd(e=process.env){let t=e.KYNVER_CODEX_BIN?.trim()||e.CODEX_BIN?.trim()||wr();return b5(t)?e.CODEX_API_KEY?.trim()?{ok:!0,creds:{codexBin:t,authSource:"api_key_env"}}:v5(e).find(n=>cD(n))?{ok:!0,creds:{codexBin:t,authSource:"oauth_local"}}:{ok:!1,error:vk,detail:"Run `codex login` on this computer, or set CODEX_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:zd,detail:"`codex` CLI not found. Install the Codex CLI (https://developers.openai.com/codex/) and keep it on PATH."}}var zd,vk,Qd=p(()=>{"use strict";Wn();zd="codex_cli_unavailable",vk="codex_not_logged_in"});import{spawnSync as R5}from"node:child_process";function S5(e,t,r){return w5.test(`${t}
|
|
141
|
-
${r}`)?!1:e===0}function dD(e,t=process.env){try{let[r,n]=se(e,["models"]),o=R5(r,n,{encoding:"utf8",windowsHide:!0,timeout:8e3,env:{...t,CI:"1",NO_COLOR:"1"}}),s=o.stdout??"",i=o.stderr??"";return o.error&&o.error.code==="ENOENT"?{ok:!1,note:"agy models: binary missing"}:S5(o.status,s,i)?{ok:!0,note:"agy models: signed in"}:{ok:!1,note:"agy models: not signed in"}}catch(r){return{ok:!1,note:r instanceof Error?r.message:"agy models probe failed"}}}var w5,pD=p(()=>{"use strict";Ge();w5=/authentication required|not logged in|you are not logged|not authenticated/i});import{existsSync as _5,readFileSync as x5}from"node:fs";import{homedir as C5}from"node:os";import fD from"node:path";import{spawnSync as E5}from"node:child_process";function A5(e){if(fD.isAbsolute(e)||e.includes("/")||e.includes("\\"))return _5(e);try{let t=E5(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function P5(){return fD.join(C5(),".gemini","antigravity-cli","settings.json")}function I5(e){if(!e?.trim())return null;try{let t=JSON.parse(e);return typeof t.modelProvider=="string"?t.modelProvider.trim().toLowerCase():null}catch{return null}}function O5(){try{return x5(P5(),"utf8")}catch{return null}}function T5(e,t){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()?I5(t)==="gemini":!1}function mD(e){return`${e.error}: ${e.detail}`}function tp(e=process.env,t={}){let r=pt(e);if(!(t.commandOnPath??A5)(r))return{ok:!1,error:Zd,detail:"`agy` not found. Install Google Antigravity (https://antigravity.google/docs/cli/install) and keep `agy` on PATH."};if((t.probeAuth??dD)(r,e).ok)return{ok:!0,creds:{bin:r,authSource:"keyring"}};let s=(t.readSettings??(()=>O5()))(e);return T5(e,s)?{ok:!0,creds:{bin:r,authSource:"api_key_settings"}}:{ok:!1,error:ep,detail:'Run `agy` once on this computer to sign in. A Gemini API key does not sign Google Antigravity in unless ~/.gemini/antigravity-cli/settings.json sets "modelProvider" to "gemini". Website chat will not fall back to hosted models.'}}var Zd,ep,rp=p(()=>{"use strict";$n();pD();Zd="antigravity_cli_unavailable",ep="antigravity_not_logged_in"});function Qa(e=process.env){let t=e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim();if(!t)return null;let r=(e.KYNVER_GEMINI_BASE_URL?.trim()||N5).replace(/\/+$/,"");return{apiKey:t,baseUrl:r,label:"gemini"}}function Za(e=process.env){let t=e.KYNVER_OPENAI_API_KEY?.trim()||e.OPENAI_API_KEY?.trim();if(t){let o=(e.KYNVER_OPENAI_BASE_URL?.trim()||e.OPENAI_BASE_URL?.trim()||D5).replace(/\/+$/,"");return{apiKey:t,baseUrl:o,label:"openai"}}let r=e.KYNVER_WORKER_BASE_URL?.trim(),n=e.KYNVER_WORKER_API_KEY?.trim();return r&&n?{apiKey:n,baseUrl:r.replace(/\/+$/,""),label:"openai"}:null}var N5,D5,Rk=p(()=>{"use strict";N5="https://generativelanguage.googleapis.com/v1beta/openai",D5="https://api.openai.com/v1"});function L5(e,t=process.env){return{anthropic:()=>{let r=za(t,{oauthOptIn:e.chatUseClaudeOauth===!0});return r?r.kind==="oauth"?"subscription":"api_key":null},codex:()=>{let r=Xd(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},cursor:()=>{let r=nu(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},gemini:()=>{let r=t;if(no({chatProvider:e.chatProvider,workerProvider:e.workerProvider},r)==="antigravity"){let n=tp(r);return n.ok?n.creds.authSource==="api_key_settings"?"api_key":"subscription":null}return Qa(t)?"api_key":null},openai:()=>Za(t)?"api_key":null}}function B5(e){if(!e?.trim())return[];let t=[];for(let r of e.split(/[\s,]+/)){let n=r.indexOf(":");if(n<=0)continue;let o=r.slice(n+1).trim();!o||o.length>80||t.push({provider:Ls(r.slice(0,n)),model:o})}return t}function wk(e,t){let r=t?.trim();r&&!e.includes(r)&&e.push(r)}function W5(e,t,r=process.env){let n=so(e),o=B5(r.KYNVER_CHAT_EXTRA_MODELS),s=[];for(let i of Sk){let a=null;try{a=t[i]()}catch{a=null}if(!a)continue;let l=i===n?Bs(i,e,r):Bs(i,{},{...r,KYNVER_CHAT_MODEL:void 0}),c=[];wk(c,l);for(let u of M5[i])wk(c,u);for(let u of o)u.provider===i&&wk(c,u.model);s.push({provider:i,models:c,defaultModel:l,auth:a})}return s.sort((i,a)=>i.provider===n?-1:a.provider===n?1:0)}function np(e,t=process.env,r=Date.now()){let n=JSON.stringify([e.chatProvider,e.workerProvider,e.defaultModel,e.chatUseClaudeOauth,t.KYNVER_CHAT_MODEL,t.KYNVER_CHAT_EXTRA_MODELS]);if(el&&el.key===n&&r-el.at<U5)return el.value;let o=W5(e,L5(e,t),t);return el={key:n,at:r,value:o},o}var Sk,M5,U5,el,_k=p(()=>{"use strict";bk();Qd();ds();rp();Md();Rk();Va();Sk=["anthropic","codex","openai","gemini","cursor"],M5={anthropic:["claude-sonnet-4-6","claude-opus-4-8","claude-opus-4-7","claude-haiku-4-5-20251001"],codex:["gpt-5.5","gpt-5.4","o4-mini"],openai:["gpt-5.5","gpt-5.4","gpt-4o-mini"],gemini:["gemini-2.5-pro","gemini-2.5-flash"],cursor:["composer-2.5"]};U5=6e4,el=null});function tl(e){if(typeof e=="string"){let n=e.indexOf(":");return n<=0?null:tl({provider:e.slice(0,n),model:e.slice(n+1)})}if(!e||typeof e!="object")return null;let t=e;if(typeof t.provider!="string"||typeof t.model!="string")return null;let r=t.model.trim();return!r||r.length>80||!/^[\w.:@/-]+$/.test(r)?null:{provider:Ls(t.provider),model:r}}function hD(e){let{requested:t,catalog:r,primary:n}=e;if(!t)return{provider:n.provider,model:n.model,requested:null,fallbackReason:null};let o=r.find(s=>s.provider===t.provider);return o&&o.models.includes(t.model)?{provider:t.provider,model:t.model,requested:null,fallbackReason:null}:{provider:n.provider,model:n.model,requested:t,fallbackReason:"model_unavailable"}}function yD(e,t){for(let r of Sk){if(t.includes(r))continue;let n=e.find(o=>o.provider===r);if(n)return{provider:r,model:n.defaultModel}}return null}function kD(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return t?F5.some(r=>r.test(t)):!1}function gD(e){return $5[e]}function bD(e,t){if(!e.fallbackReason)return null;let r=t??e.requested,n=r?`${r.provider}:${r.model}`:"auto";return`${e.fallbackReason}:${n}->${e.provider}:${e.model}`}function vD(e,t){let r=`${gD(e.provider)} (${e.model})`;if(e.fallbackReason==="usage_limit")return`${t?gD(t.provider):"Your usual model"} has reached its usage limit on your computer, so this answer comes from ${r} instead.`;if(e.fallbackReason==="model_unavailable"){let n=t??e.requested;return`${n?`${n.model}`:"The model chosen in Settings"} isn't available on your computer right now, so this answer uses Auto: ${r}. You can pick another model in Settings.`}return null}var F5,$5,xk=p(()=>{"use strict";_k();Va();F5=[/usage limit/i,/limit (?:has been )?reached/i,/hit your (?:usage )?limit/i,/rate_limit_error/i,/quota (?:exceeded|exhausted)/i,/insufficient_quota/i,/HTTP 429\b/];$5={anthropic:"Claude",codex:"ChatGPT",openai:"ChatGPT",gemini:"Gemini",cursor:"Cursor"}});function wD(e){if(!e||typeof e!="object")return!1;let t=e;return!(typeof t.type!="string"||!K5.has(t.type)||t.type==="text"&&(typeof t.text!="string"||!t.text.trim()))}function RD(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.content=="string")return t.content.trim()?{...t,content:[{type:"text",text:t.content,cache_control:rl}]}:null;if(!Array.isArray(t.content)||t.content.length===0)return null;let r=t.content[t.content.length-1];return wD(r)?{...t,content:[...t.content.slice(0,-1),{...r,cache_control:rl}]}:null}function H5(e){return Array.isArray(e)&&e.length>0&&e.every(t=>!!t&&typeof t=="object"&&t.type==="tool_result")}function j5(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!(!r||typeof r!="object"||r.role!=="user")&&!H5(r.content))return t}return-1}function Ck(e){return JSON.stringify(e??null).includes('"cache_control"')}function SD(e){if(Ck(e.system)||Ck(e.tools)||Ck(e.messages))return e;let t=e.tools;if(Array.isArray(t)&&t.length>0){let i=e.toolBreakpointName?t.findIndex(c=>!!c&&typeof c=="object"&&c.name===e.toolBreakpointName):-1,a=i>=0?i:t.length-1,l=t[a];l&&typeof l=="object"&&(t=[...t.slice(0,a),{...l,cache_control:rl},...t.slice(a+1)])}let r=e.system;if(typeof r=="string")r.trim()&&(r=[{type:"text",text:r,cache_control:rl}]);else if(Array.isArray(r)&&r.length>0){let i=r[r.length-1];wD(i)&&(r=[...r.slice(0,-1),{...i,cache_control:rl}])}let n=[...e.messages],o=-1;for(let i=n.length-1;i>=0;i-=1){let a=RD(n[i]);if(a){n[i]=a,o=i;break}}let s=j5(n)-1;if(s>=0&&s<o)for(let i=s;i>=0;i-=1){let a=RD(n[i]);if(a){n[i]=a;break}}return{system:r,tools:t,messages:n}}var rl,K5,_D=p(()=>{"use strict";rl={type:"ephemeral"},K5=new Set(["text","image","document","tool_use","tool_result","search_result","server_tool_use","web_search_tool_result","web_fetch_tool_result","code_execution_tool_result"])});function xD(e){if(!e||typeof e!="object")return null;let t=e,r=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):null,n=r(t.stepsUsed),o=r(t.maxSteps),s=r(t.segment);return typeof t.jobId!="string"||!t.jobId||n===null||o===null||o===0?null:{jobId:t.jobId.slice(0,64),stepsUsed:n,maxSteps:o,segment:s??1}}function G5(){return{blocks:[],stopReason:null,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}}function J5(e,t){let r=t;switch(r.type){case"message_start":return e.inputTokens=r.message?.usage?.input_tokens??0,e.cacheReadTokens=r.message?.usage?.cache_read_input_tokens??0,e.cacheCreationTokens=r.message?.usage?.cache_creation_input_tokens??0,"";case"content_block_start":{let n=r.index??e.blocks.length;return e.blocks[n]={type:r.content_block?.type==="tool_use"?"tool_use":"text",text:"",id:r.content_block?.id,name:r.content_block?.name,inputJson:""},""}case"content_block_delta":{let n=e.blocks[r.index??e.blocks.length-1];return n?r.delta?.type==="text_delta"&&r.delta.text?(n.text+=r.delta.text,r.delta.text):(r.delta?.type==="input_json_delta"&&r.delta.partial_json&&(n.inputJson+=r.delta.partial_json),""):""}case"message_delta":return r.delta?.stop_reason&&(e.stopReason=r.delta.stop_reason),typeof r.usage?.output_tokens=="number"&&(e.outputTokens=r.usage.output_tokens),"";default:return""}}function q5(e){let t=[];for(let r of e.blocks)if(r)if(r.type==="tool_use"){let n={};try{n=r.inputJson?JSON.parse(r.inputJson):{}}catch{n={}}t.push({type:"tool_use",id:r.id??"",name:r.name??"",input:n})}else r.text&&t.push({type:"text",text:r.text});return{content:t,stop_reason:e.stopReason??"end_turn",usage:{input_tokens:e.inputTokens,output_tokens:e.outputTokens,cache_read_input_tokens:e.cacheReadTokens,cache_creation_input_tokens:e.cacheCreationTokens}}}async function*Y5(e){let t=e.getReader(),r=new TextDecoder,n="";try{for(;;){let{done:o,value:s}=await t.read();if(o)break;n+=r.decode(s,{stream:!0});let i;for(;(i=n.indexOf(`
|
|
142
|
-
`))!==-1;){let a=n.slice(0,i).trim();if(n=n.slice(i+1),!a.startsWith("data:"))continue;let l=a.slice(5).trim();if(!(!l||l==="[DONE]"))try{yield JSON.parse(l)}catch{}}}}finally{t.releaseLock()}}function
|
|
204
|
+
${s.stderr??""}`;for(let a of rl(i))n.add(a);s.status===0&&(o=d9(i))}return{version:o,missingLibs:[...n].sort()}}function DD(e,t=()=>p9(e),r=Date.now){let n=Kk.get(e);if(n&&r()-n.at<f9)return n.health;let o=t();return Kk.set(e,{at:r(),health:o}),o}function MD(){Kk.clear()}var u9,f9,Kk,$k=p(()=>{"use strict";np();u9=(e,t,r)=>c9(e,t,r);f9=10*6e4,Kk=new Map});import{existsSync as m9,readFileSync as LD}from"node:fs";function Js(e,t){return e==="linux"?t==="x64"?"linux64":null:e==="darwin"?t==="arm64"?"mac-arm64":"mac-x64":e==="win32"?t==="ia32"?"win32":"win64":null}function BD(e,t){try{return e(t)}catch{return""}}function nl(e=process.env,t=process.platform,r={}){if(t!=="linux")return!1;if(e.WSL_DISTRO_NAME?.trim()||e.WSL_INTEROP?.trim())return!0;let n=r.readFile??(o=>LD(o,"utf8"));return/microsoft|wsl/i.test(BD(n,"/proc/version"))}function g9(e=process.env,t=process.platform,r={}){if(t!=="linux")return{available:!0,wslg:!1};let n=r.exists??m9,o=nl(e,t,r)&&n("/mnt/wslg");return{available:!!(e.DISPLAY?.trim()||e.WAYLAND_DISPLAY?.trim()),wslg:o}}function op(e=process.env,t=process.platform){return/^(1|true|yes|on)$/i.test(e.KYNVER_BROWSER_HEADLESS??"")?!0:!g9(e,t).available}function h9(e){let t={};for(let l of e.split(/\r?\n/)){let c=/^([A-Z_]+)=(.*)$/.exec(l.trim());c&&(t[c[1]]=c[2].replace(/^["']|["']$/g,""))}let r=(t.ID??"").toLowerCase(),n=`${r} ${(t.ID_LIKE??"").toLowerCase()}`,o=t.VERSION_ID??"",s="unknown";/\b(debian|ubuntu)\b/.test(n)?s="apt":/\b(fedora|rhel|centos)\b/.test(n)?s="dnf":/\b(suse|opensuse)\b/.test(n)?s="zypper":/\barch\b/.test(n)?s="pacman":/\balpine\b/.test(n)&&(s="apk");let i=Number.parseFloat(o),a=s==="apt"&&(r==="ubuntu"&&Number.isFinite(i)&&i>=24||r==="debian"&&Number.isFinite(i)&&i>=13);return{id:r,versionId:o,family:s,t64:a}}function WD(e={}){let t=e.readFile??(r=>LD(r,"utf8"));return h9(BD(t,"/etc/os-release"))}var fo=p(()=>{"use strict"});import{existsSync as y9,readdirSync as k9}from"node:fs";import{homedir as b9}from"node:os";import mo from"node:path";function sp(e=process.env){return e.KYNVER_BROWSER_INSTALL_DIR?.trim()||mo.join(b9(),".kynver","browsers")}function UD(e,t=process.env){return mo.join(sp(t),`chrome-${e}`)}function ip(e,t){let r=mo.join(e,`chrome-${t}`);return t==="linux64"?mo.join(r,"chrome"):t==="win32"||t==="win64"?mo.join(r,"chrome.exe"):mo.join(r,"Google Chrome for Testing.app","Contents","MacOS","Google Chrome for Testing")}function v9(e,t){let r=e.split(".").map(o=>Number.parseInt(o,10)||0),n=t.split(".").map(o=>Number.parseInt(o,10)||0);for(let o=0;o<Math.max(r.length,n.length);o+=1){let s=(r[o]??0)-(n[o]??0);if(s!==0)return s}return 0}function ap(e,t=process.env,r={}){let n=r.exists??y9,o=r.listDir??(l=>k9(l)),s=sp(t),i;try{i=o(s)}catch{return null}let a=i.map(l=>/^chrome-(\d+(?:\.\d+){1,3})$/.exec(l)?.[1]).filter(l=>!!l).sort(v9).reverse();for(let l of a){let c=mo.join(s,`chrome-${l}`),u=ip(c,e);if(n(u))return{executable:u,version:l,installDir:c}}return null}var Hk=p(()=>{"use strict"});import{existsSync as R9,readdirSync as w9}from"node:fs";import{homedir as S9}from"node:os";import Dr from"node:path";function _9(e,t,r=S9()){return e==="win32"?[t.PROGRAMFILES,t["PROGRAMFILES(X86)"],t.LOCALAPPDATA].filter(o=>typeof o=="string"&&o.length>0).flatMap(o=>[Dr.join(o,"Google","Chrome","Application","chrome.exe"),Dr.join(o,"Microsoft","Edge","Application","msedge.exe"),Dr.join(o,"Chromium","Application","chrome.exe")]):e==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",Dr.join(r,"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),Dr.join(r,"Applications/Chromium.app/Contents/MacOS/Chromium")]:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome","/usr/bin/chromium","/usr/bin/chromium-browser","/usr/lib/chromium/chromium","/snap/bin/chromium","/usr/bin/microsoft-edge","/usr/bin/microsoft-edge-stable","/opt/microsoft/msedge/msedge","/var/lib/flatpak/exports/bin/com.google.Chrome","/var/lib/flatpak/exports/bin/org.chromium.Chromium",Dr.join(r,".local/share/flatpak/exports/bin/com.google.Chrome"),Dr.join(r,".local/share/flatpak/exports/bin/org.chromium.Chromium"),...FD.map(n=>Dr.join(r,".local/bin",n))]}function x9(e,t,r){let n=(e.PATH??"").split(":").filter(o=>o&&!(r&&o.startsWith("/mnt/")));for(let o of FD)for(let s of n){let i=Dr.join(s,o);if(t(i))return i}return null}function go(e={}){let t=e.env??process.env,r=e.platform??process.platform,n=e.arch??process.arch,o=e.exists??R9,s=e.config??P(),i=null,a=t.KYNVER_BROWSER_CHROME_PATH?.trim()||s.browserChromePath?.trim()||"";if(a){if(o(a))return{executable:a,source:"configured",version:null,configuredMissing:i};i=a}let l=_9(r,t,e.home).find(u=>o(u));if(l)return{executable:l,source:"system",version:null,configuredMissing:i};if(r==="linux"){let u=x9(t,o,nl(t,r,{readFile:e.readFile}));if(u)return{executable:u,source:"system",version:null,configuredMissing:i}}let c=Js(r,n);if(c){let u=s.browserManaged;if(u?.executable&&u.platform===c&&o(u.executable))return{executable:u.executable,source:"managed",version:u.version??null,configuredMissing:i};let d=ap(c,t,{exists:o,listDir:e.listDir??(f=>w9(f))});if(d)return{executable:d.executable,source:"managed",version:d.version,configuredMissing:i}}return{executable:null,source:"none",version:null,configuredMissing:i}}var FD,ol=p(()=>{"use strict";$();fo();Hk();FD=["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge","microsoft-edge-stable"]});import{createWriteStream as C9}from"node:fs";import{rm as E9}from"node:fs/promises";function I9(e,t){let r=e?.channels?.Stable;if(!r||typeof r.version!="string"||!/^\d+(\.\d+){1,3}$/.test(r.version))return null;let n=Array.isArray(r.downloads?.chrome)?r.downloads.chrome:[];for(let o of n){let s=o;if(s.platform===t&&typeof s.url=="string"&&s.url.startsWith($D))return{version:r.version,url:s.url}}return null}async function HD(e,t=fetch){let r=await t(A9,{signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`Chrome for Testing index returned HTTP ${r.status}`);let n=I9(await r.json(),e);if(!n)throw new Error(`No stable Chrome for Testing build is published for ${e}`);return n}async function jD(e,t,r={}){let n=r.minBytes??P9;if(!e.startsWith($D))throw new Error("refusing to download from an unexpected host");let s=await(r.fetchFn??fetch)(e,{signal:AbortSignal.timeout(r.timeoutMs??15*6e4)});if(!s.ok||!s.body)throw new Error(`browser download returned HTTP ${s.status}`);let i=s.headers.get("content-length"),a=i?Number.parseInt(i,10):null;if(a!==null&&(a<n||a>KD))throw new Error(`browser download has an unexpected size (${a} bytes)`);let l=C9(t),c=0;try{let u=s.body.getReader();for(;;){let{done:d,value:f}=await u.read();if(d)break;if(c+=f.byteLength,c>KD)throw new Error("browser download is larger than expected");l.write(f)||await new Promise(m=>l.once("drain",()=>m())),r.onProgress?.({receivedBytes:c,totalBytes:a})}if(await new Promise((d,f)=>l.end(m=>m?f(m):d())),a!==null&&c!==a)throw new Error(`browser download was cut short (${c} of ${a} bytes)`);if(c<n)throw new Error(`browser download is too small (${c} bytes)`);return c}catch(u){throw l.destroy(),await E9(t,{force:!0}).catch(()=>{}),u}}var A9,$D,P9,KD,VD=p(()=>{"use strict";A9="https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json",$D="https://storage.googleapis.com/chrome-for-testing-public/",P9=20*1024*1024,KD=600*1024*1024});import{chmodSync as O9,mkdirSync as jk,symlinkSync as T9,writeFileSync as N9}from"node:fs";import qs from"node:path";import{crc32 as D9,inflateRawSync as M9}from"node:zlib";function U9(e){let t=Math.max(0,e.length-65535-22);for(let r=e.length-22;r>=t;r-=1)if(e.readUInt32LE(r)===L9)return r;throw new Error("not a zip archive (no end-of-central-directory record)")}function F9(e){let t=U9(e),r=e.readUInt16LE(t+10),n=e.readUInt32LE(t+16);if(r===65535||n===4294967295)throw new Error("zip64 archives are not supported");let o=[],s=n;for(let i=0;i<r;i+=1){if(s+46>e.length||e.readUInt32LE(s)!==B9)throw new Error("corrupt zip central directory");let a=e.readUInt16LE(s+4)>>8,l=e.readUInt16LE(s+28),c=e.readUInt16LE(s+30),u=e.readUInt16LE(s+32),d=e.readUInt32LE(s+38);o.push({name:e.subarray(s+46,s+46+l).toString("utf8"),method:e.readUInt16LE(s+10),crc:e.readUInt32LE(s+16),compressedSize:e.readUInt32LE(s+20),size:e.readUInt32LE(s+24),localHeaderOffset:e.readUInt32LE(s+42),unixMode:a===3?d>>>16&65535:null}),s+=46+l+c+u}return o}function K9(e,t){let r=t.localHeaderOffset;if(e.readUInt32LE(r)!==W9)throw new Error(`corrupt zip entry ${t.name}`);let n=r+30+e.readUInt16LE(r+26)+e.readUInt16LE(r+28),o=e.subarray(n,n+t.compressedSize),s;if(t.method===0)s=Buffer.from(o);else if(t.method===8)s=M9(o);else throw new Error(`unsupported zip compression method ${t.method} (${t.name})`);if(s.length!==t.size||D9(s)>>>0!==t.crc>>>0)throw new Error(`zip entry failed its integrity check: ${t.name}`);return s}function GD(e,t){let r=t.replace(/\\/g,"/");if(r.startsWith("/")||/^[a-zA-Z]:/.test(r))throw new Error(`unsafe zip path: ${t}`);let n=qs.resolve(e,r),o=qs.resolve(e);if(n!==o&&!n.startsWith(o+qs.sep))throw new Error(`unsafe zip path: ${t}`);return n}function JD(e,t,r=process.platform){jk(t,{recursive:!0});let n=0;for(let o of F9(e)){let s=GD(t,o.name);if(o.name.endsWith("/")){jk(s,{recursive:!0});continue}jk(qs.dirname(s),{recursive:!0});let i=K9(e,o);if(o.unixMode!==null&&(o.unixMode&$9)===H9&&r!=="win32"){let a=i.toString("utf8");GD(t,qs.posix.join(qs.posix.dirname(o.name.replace(/\\/g,"/")),a)),T9(a,s)}else N9(s,i),o.unixMode!==null&&r!=="win32"&&O9(s,o.unixMode&511||420);n+=1}return n}var L9,B9,W9,$9,H9,qD=p(()=>{"use strict";L9=101010256,B9=33639248,W9=67324752;$9=61440,H9=40960});import{closeSync as YD,existsSync as Vk,mkdirSync as j9,openSync as zD,readFileSync as V9,renameSync as G9,rmSync as Ys,statSync as J9,chmodSync as q9}from"node:fs";import Gk from"node:path";function ho(){return{...Mt}}function ZD(e=Mt){return e.state!=="failed"||e.failedAt===null?0:e.failedAt+XD[Math.min(e.attempts-1,XD.length-1)]}function eM(e=Mt){return e.totalBytes&&e.totalBytes>0?`${Math.min(99,Math.floor(e.receivedBytes/e.totalBytes*100))}% of ${Math.round(e.totalBytes/1024/1024)} MB`:e.receivedBytes>0?`${Math.round(e.receivedBytes/1024/1024)} MB so far`:"starting"}function z9(e){let t=P();We({...t,browserManaged:{version:e.version,platform:e.platform,executable:e.executable,installedAt:new Date().toISOString()}})}function X9(e,t){JD(V9(e),t)}function Q9(e,t){try{return YD(zD(e,"wx")),!0}catch{try{if(t-J9(e).mtimeMs>Y9)return Ys(e,{force:!0}),YD(zD(e,"wx")),!0}catch{}return!1}}async function Z9(e,t){let r=t.env??process.env,n=t.now??Date.now,o=t.sleep??(a=>new Promise(l=>setTimeout(l,a))),s=sp(r);j9(s,{recursive:!0});let i=Gk.join(s,".install.lock");for(;!Q9(i,n());)if(await o(2e3),!Vk(i)){let a=ap(e,r);if(a)return a}try{let a=await HD(e,t.fetchFn),l=UD(a.version,r),c=ip(l,e);if(!Vk(c)){let d=Gk.join(s,`.download-${a.version}.zip`),f=Gk.join(s,`.staging-${a.version}-${process.pid}`);Ys(f,{recursive:!0,force:!0});try{await jD(a.url,d,{fetchFn:t.fetchFn,minBytes:t.minArchiveBytes,onProgress:g=>{Mt.receivedBytes=g.receivedBytes,Mt.totalBytes=g.totalBytes}}),(t.extract??X9)(d,f);let m=ip(f,e);if(!Vk(m))throw new Error("the downloaded browser archive did not contain Chrome");(t.platform??process.platform)!=="win32"&&q9(m,493),Ys(l,{recursive:!0,force:!0}),G9(f,l)}finally{Ys(d,{force:!0}),Ys(f,{recursive:!0,force:!0})}}let u={executable:c,version:a.version,installDir:l};return(t.record??z9)({...u,platform:e}),u}finally{Ys(i,{force:!0})}}function lp(e={}){if(sl)return sl;let t=Js(e.platform??process.platform,e.arch??process.arch);if(!t)return Promise.reject(new zs("Google doesn't publish a ready-made Chrome for this kind of computer (Linux on ARM). Install Chromium with your package manager (for example `sudo apt-get install chromium`), then try again.","unsupported_platform"));let r=e.now??Date.now;return Mt={...Mt,state:"downloading",receivedBytes:0,totalBytes:null,error:null},sl=Z9(t,e).then(n=>(Mt={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},MD(),n)).catch(n=>{let o=n instanceof Error?n.message:String(n);throw Mt={...Mt,state:"failed",error:o.slice(0,300),failedAt:r(),attempts:Mt.attempts+1},new zs(`Couldn't download a browser for this computer: ${o.slice(0,200)}`,"download_failed")}).finally(()=>{sl=null}),sl}var QD,Y9,XD,zs,Mt,sl,cp=p(()=>{"use strict";$();fo();VD();$k();Hk();qD();QD=150,Y9=30*6e4,XD=[6e4,5*6e4,30*6e4,120*6e4],zs=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserProvisionError"}code},Mt={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},sl=null});function Jk(e){return e7.test(e)}function tM(e=process.platform,t=typeof process.getuid=="function"?process.getuid():null){return e==="linux"&&t===0}function up(e){rM=e}function nM(){return rM}var e7,rM,qk=p(()=>{"use strict";e7=/Running as root without --no-sandbox|No usable sandbox|setuid sandbox|SUID sandbox helper|Failed to move to new namespace|sandbox_host_linux|credentials\.cc.*(EPERM|Operation not permitted)/i;rM=null});function oM(e=process.env,t={}){let r=t.platform??process.platform,n=P(),o={executable:null,source:"none",version:null,configuredMissing:null};try{o=(t.resolve??(()=>go({env:e,platform:r,config:n})))()}catch{}let s={version:null,missingLibs:[]};if(o.executable)try{s=(t.health??(i=>DD(i)))(o.executable)}catch{}return{supported:!0,chromeFound:o.executable!==null,localDisabled:n.browserDisabled===!0,browserSource:o.source,browserVersion:o.version??s.version,provisioning:ho().state,missingLibs:s.missingLibs,wsl:nl(e,r),headless:op(e,r),autoProvision:n.browserAutoProvision!==!1,sandbox:nM()}}var sM=p(()=>{"use strict";$();$k();fo();ol();cp();qk()});function dp(e,t,r,n,o,s,i){return{chatProvider:e,toolCalls:e==="anthropic"||e==="cursor"||e==="gemini"||e==="openai"||e==="codex",runtimePackageVersion:Ge,browser:oM(),deliveryReceipt:!0,...t?{chatModels:t}:{},...r?{computer:r}:{},...n?{security:n}:{},...o?{agentEngines:o}:{},...s?{packageVersions:s}:{},...i?{selfUpdate:i}:{}}}var iM=p(()=>{"use strict";Vr();sM()});import{readFileSync as t7}from"node:fs";import{homedir as r7,platform as n7}from"node:os";import o7 from"node:path";import{execFileSync as s7}from"node:child_process";function aM(e,t=Date.now()){try{let r=JSON.parse(e),n=r.claudeAiOauth?.accessToken,o=r.claudeAiOauth?.expiresAt;return typeof n!="string"||!n||typeof o=="number"&&o-t<6e4?null:n}catch{return null}}function i7(){if(n7()==="darwin")try{let e=s7("security",["find-generic-password","-s","Claude Code-credentials","-w"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return aM(e.trim())}catch{return null}try{let e=t7(o7.join(r7(),".claude",".credentials.json"),"utf8");return aM(e)}catch{return null}}function il(e=process.env,t={}){let r=e.ANTHROPIC_API_KEY?.trim();if(r)return{kind:"api_key",key:r};let n=e.KYNVER_CHAT_USE_CLAUDE_OAUTH;if(t.oauthOptIn===!0||n==="1"||n==="true"||n==="yes"){let s=i7();if(s)return{kind:"oauth",token:s}}return null}var Yk=p(()=>{"use strict"});import{existsSync as lM}from"node:fs";import{homedir as a7}from"node:os";import al from"node:path";import{spawnSync as l7}from"node:child_process";function c7(e){if(al.isAbsolute(e)||e.includes("/")||e.includes("\\"))return lM(e);try{let t=l7(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function u7(e=process.env){let t=a7(),r=[],n=e.CODEX_HOME?.trim();return n&&r.push(al.join(al.resolve(n),"auth.json")),r.push(al.join(t,".codex","auth.json")),r.push(al.join(t,".config","codex","auth.json")),r}function cM(e){return`${e.error}: ${e.detail}`}function fp(e=process.env){let t=e.KYNVER_CODEX_BIN?.trim()||e.CODEX_BIN?.trim()||xr();return c7(t)?e.CODEX_API_KEY?.trim()?{ok:!0,creds:{codexBin:t,authSource:"api_key_env"}}:u7(e).find(n=>lM(n))?{ok:!0,creds:{codexBin:t,authSource:"oauth_local"}}:{ok:!1,error:zk,detail:"Run `codex login` on this computer, or set CODEX_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:pp,detail:"`codex` CLI not found. Install the Codex CLI (https://developers.openai.com/codex/) and keep it on PATH."}}var pp,zk,mp=p(()=>{"use strict";Vn();pp="codex_cli_unavailable",zk="codex_not_logged_in"});import{spawnSync as d7}from"node:child_process";function f7(e,t,r){return p7.test(`${t}
|
|
205
|
+
${r}`)?!1:e===0}function uM(e,t=process.env){try{let[r,n]=ae(e,["models"]),o=d7(r,n,{encoding:"utf8",windowsHide:!0,timeout:8e3,env:{...t,CI:"1",NO_COLOR:"1"}}),s=o.stdout??"",i=o.stderr??"";return o.error&&o.error.code==="ENOENT"?{ok:!1,note:"agy models: binary missing"}:f7(o.status,s,i)?{ok:!0,note:"agy models: signed in"}:{ok:!1,note:"agy models: not signed in"}}catch(r){return{ok:!1,note:r instanceof Error?r.message:"agy models probe failed"}}}var p7,dM=p(()=>{"use strict";qe();p7=/authentication required|not logged in|you are not logged|not authenticated/i});import{existsSync as m7,readFileSync as g7}from"node:fs";import{homedir as h7}from"node:os";import pM from"node:path";import{spawnSync as y7}from"node:child_process";function k7(e){if(pM.isAbsolute(e)||e.includes("/")||e.includes("\\"))return m7(e);try{let t=y7(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function b7(){return pM.join(h7(),".gemini","antigravity-cli","settings.json")}function v7(e){if(!e?.trim())return null;try{let t=JSON.parse(e);return typeof t.modelProvider=="string"?t.modelProvider.trim().toLowerCase():null}catch{return null}}function R7(){try{return g7(b7(),"utf8")}catch{return null}}function w7(e,t){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()?v7(t)==="gemini":!1}function fM(e){return`${e.error}: ${e.detail}`}function yp(e=process.env,t={}){let r=ht(e);if(!(t.commandOnPath??k7)(r))return{ok:!1,error:gp,detail:"`agy` not found. Install Google Antigravity (https://antigravity.google/docs/cli/install) and keep `agy` on PATH."};if((t.probeAuth??uM)(r,e).ok)return{ok:!0,creds:{bin:r,authSource:"keyring"}};let s=(t.readSettings??(()=>R7()))(e);return w7(e,s)?{ok:!0,creds:{bin:r,authSource:"api_key_settings"}}:{ok:!1,error:hp,detail:'Run `agy` once on this computer to sign in. A Gemini API key does not sign Google Antigravity in unless ~/.gemini/antigravity-cli/settings.json sets "modelProvider" to "gemini". Website chat will not fall back to hosted models.'}}var gp,hp,kp=p(()=>{"use strict";qn();dM();gp="antigravity_cli_unavailable",hp="antigravity_not_logged_in"});function ll(e=process.env){let t=e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim();if(!t)return null;let r=(e.KYNVER_GEMINI_BASE_URL?.trim()||S7).replace(/\/+$/,"");return{apiKey:t,baseUrl:r,label:"gemini"}}function cl(e=process.env){let t=e.KYNVER_OPENAI_API_KEY?.trim()||e.OPENAI_API_KEY?.trim();if(t){let o=(e.KYNVER_OPENAI_BASE_URL?.trim()||e.OPENAI_BASE_URL?.trim()||_7).replace(/\/+$/,"");return{apiKey:t,baseUrl:o,label:"openai"}}let r=e.KYNVER_WORKER_BASE_URL?.trim(),n=e.KYNVER_WORKER_API_KEY?.trim();return r&&n?{apiKey:n,baseUrl:r.replace(/\/+$/,""),label:"openai"}:null}var S7,_7,Xk=p(()=>{"use strict";S7="https://generativelanguage.googleapis.com/v1beta/openai",_7="https://api.openai.com/v1"});function C7(e,t=process.env){return{anthropic:()=>{let r=il(t,{oauthOptIn:e.chatUseClaudeOauth===!0});return r?r.kind==="oauth"?"subscription":"api_key":null},codex:()=>{let r=fp(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},cursor:()=>{let r=yu(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},gemini:()=>{let r=t;if(co({chatProvider:e.chatProvider,workerProvider:e.workerProvider},r)==="antigravity"){let n=yp(r);return n.ok?n.creds.authSource==="api_key_settings"?"api_key":"subscription":null}return ll(t)?"api_key":null},openai:()=>cl(t)?"api_key":null}}function E7(e){if(!e?.trim())return[];let t=[];for(let r of e.split(/[\s,]+/)){let n=r.indexOf(":");if(n<=0)continue;let o=r.slice(n+1).trim();!o||o.length>80||t.push({provider:Vs(r.slice(0,n)),model:o})}return t}function Qk(e,t){let r=t?.trim();r&&!e.includes(r)&&e.push(r)}function A7(e,t,r=process.env){let n=po(e),o=E7(r.KYNVER_CHAT_EXTRA_MODELS),s=[];for(let i of Zk){let a=null;try{a=t[i]()}catch{a=null}if(!a)continue;let l=i===n?Gs(i,e,r):Gs(i,{},{...r,KYNVER_CHAT_MODEL:void 0}),c=[];Qk(c,l);for(let u of x7[i])Qk(c,u);for(let u of o)u.provider===i&&Qk(c,u.model);s.push({provider:i,models:c,defaultModel:l,auth:a})}return s.sort((i,a)=>i.provider===n?-1:a.provider===n?1:0)}function bp(e,t=process.env,r=Date.now()){let n=JSON.stringify([e.chatProvider,e.workerProvider,e.defaultModel,e.chatUseClaudeOauth,t.KYNVER_CHAT_MODEL,t.KYNVER_CHAT_EXTRA_MODELS]);if(ul&&ul.key===n&&r-ul.at<P7)return ul.value;let o=A7(e,C7(e,t),t);return ul={key:n,at:r,value:o},o}var Zk,x7,P7,ul,eb=p(()=>{"use strict";Yk();mp();ks();kp();Xd();Xk();tl();Zk=["anthropic","codex","openai","gemini","cursor"],x7={anthropic:["claude-sonnet-4-6","claude-opus-4-8","claude-opus-4-7","claude-haiku-4-5-20251001"],codex:["gpt-5.5","gpt-5.4","o4-mini"],openai:["gpt-5.5","gpt-5.4","gpt-4o-mini"],gemini:["gemini-2.5-pro","gemini-2.5-flash"],cursor:["composer-2.5"]};P7=6e4,ul=null});function dl(e){if(typeof e=="string"){let n=e.indexOf(":");return n<=0?null:dl({provider:e.slice(0,n),model:e.slice(n+1)})}if(!e||typeof e!="object")return null;let t=e;if(typeof t.provider!="string"||typeof t.model!="string")return null;let r=t.model.trim();return!r||r.length>80||!/^[\w.:@/-]+$/.test(r)?null:{provider:Vs(t.provider),model:r}}function gM(e){let{requested:t,catalog:r,primary:n}=e;if(!t)return{provider:n.provider,model:n.model,requested:null,fallbackReason:null};let o=r.find(s=>s.provider===t.provider);return o&&o.models.includes(t.model)?{provider:t.provider,model:t.model,requested:null,fallbackReason:null}:{provider:n.provider,model:n.model,requested:t,fallbackReason:"model_unavailable"}}function hM(e,t){for(let r of Zk){if(t.includes(r))continue;let n=e.find(o=>o.provider===r);if(n)return{provider:r,model:n.defaultModel}}return null}function yM(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return t?I7.some(r=>r.test(t)):!1}function mM(e){return O7[e]}function kM(e,t){if(!e.fallbackReason)return null;let r=t??e.requested,n=r?`${r.provider}:${r.model}`:"auto";return`${e.fallbackReason}:${n}->${e.provider}:${e.model}`}function bM(e,t){let r=`${mM(e.provider)} (${e.model})`;if(e.fallbackReason==="usage_limit")return`${t?mM(t.provider):"Your usual model"} has reached its usage limit on your computer, so this answer comes from ${r} instead.`;if(e.fallbackReason==="model_unavailable"){let n=t??e.requested;return`${n?`${n.model}`:"The model chosen in Settings"} isn't available on your computer right now, so this answer uses Auto: ${r}. You can pick another model in Settings.`}return null}var I7,O7,tb=p(()=>{"use strict";eb();tl();I7=[/usage limit/i,/limit (?:has been )?reached/i,/hit your (?:usage )?limit/i,/rate_limit_error/i,/quota (?:exceeded|exhausted)/i,/insufficient_quota/i,/HTTP 429\b/];O7={anthropic:"Claude",codex:"ChatGPT",openai:"ChatGPT",gemini:"Gemini",cursor:"Cursor"}});function RM(e){if(!e||typeof e!="object")return!1;let t=e;return!(typeof t.type!="string"||!T7.has(t.type)||t.type==="text"&&(typeof t.text!="string"||!t.text.trim()))}function vM(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.content=="string")return t.content.trim()?{...t,content:[{type:"text",text:t.content,cache_control:pl}]}:null;if(!Array.isArray(t.content)||t.content.length===0)return null;let r=t.content[t.content.length-1];return RM(r)?{...t,content:[...t.content.slice(0,-1),{...r,cache_control:pl}]}:null}function N7(e){return Array.isArray(e)&&e.length>0&&e.every(t=>!!t&&typeof t=="object"&&t.type==="tool_result")}function D7(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!(!r||typeof r!="object"||r.role!=="user")&&!N7(r.content))return t}return-1}function rb(e){return JSON.stringify(e??null).includes('"cache_control"')}function wM(e){if(rb(e.system)||rb(e.tools)||rb(e.messages))return e;let t=e.tools;if(Array.isArray(t)&&t.length>0){let i=e.toolBreakpointName?t.findIndex(c=>!!c&&typeof c=="object"&&c.name===e.toolBreakpointName):-1,a=i>=0?i:t.length-1,l=t[a];l&&typeof l=="object"&&(t=[...t.slice(0,a),{...l,cache_control:pl},...t.slice(a+1)])}let r=e.system;if(typeof r=="string")r.trim()&&(r=[{type:"text",text:r,cache_control:pl}]);else if(Array.isArray(r)&&r.length>0){let i=r[r.length-1];RM(i)&&(r=[...r.slice(0,-1),{...i,cache_control:pl}])}let n=[...e.messages],o=-1;for(let i=n.length-1;i>=0;i-=1){let a=vM(n[i]);if(a){n[i]=a,o=i;break}}let s=D7(n)-1;if(s>=0&&s<o)for(let i=s;i>=0;i-=1){let a=vM(n[i]);if(a){n[i]=a;break}}return{system:r,tools:t,messages:n}}var pl,T7,SM=p(()=>{"use strict";pl={type:"ephemeral"},T7=new Set(["text","image","document","tool_use","tool_result","search_result","server_tool_use","web_search_tool_result","web_fetch_tool_result","code_execution_tool_result"])});function _M(e){if(!e||typeof e!="object")return null;let t=e,r=i=>typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):null,n=r(t.stepsUsed),o=r(t.maxSteps),s=r(t.segment);return typeof t.jobId!="string"||!t.jobId||n===null||o===null||o===0?null:{jobId:t.jobId.slice(0,64),stepsUsed:n,maxSteps:o,segment:s??1}}function L7(){return{blocks:[],stopReason:null,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}}function B7(e,t){let r=t;switch(r.type){case"message_start":return e.inputTokens=r.message?.usage?.input_tokens??0,e.cacheReadTokens=r.message?.usage?.cache_read_input_tokens??0,e.cacheCreationTokens=r.message?.usage?.cache_creation_input_tokens??0,"";case"content_block_start":{let n=r.index??e.blocks.length;return e.blocks[n]={type:r.content_block?.type==="tool_use"?"tool_use":"text",text:"",id:r.content_block?.id,name:r.content_block?.name,inputJson:""},""}case"content_block_delta":{let n=e.blocks[r.index??e.blocks.length-1];return n?r.delta?.type==="text_delta"&&r.delta.text?(n.text+=r.delta.text,r.delta.text):(r.delta?.type==="input_json_delta"&&r.delta.partial_json&&(n.inputJson+=r.delta.partial_json),""):""}case"message_delta":return r.delta?.stop_reason&&(e.stopReason=r.delta.stop_reason),typeof r.usage?.output_tokens=="number"&&(e.outputTokens=r.usage.output_tokens),"";default:return""}}function W7(e){let t=[];for(let r of e.blocks)if(r)if(r.type==="tool_use"){let n={};try{n=r.inputJson?JSON.parse(r.inputJson):{}}catch{n={}}t.push({type:"tool_use",id:r.id??"",name:r.name??"",input:n})}else r.text&&t.push({type:"text",text:r.text});return{content:t,stop_reason:e.stopReason??"end_turn",usage:{input_tokens:e.inputTokens,output_tokens:e.outputTokens,cache_read_input_tokens:e.cacheReadTokens,cache_creation_input_tokens:e.cacheCreationTokens}}}async function*U7(e){let t=e.getReader(),r=new TextDecoder,n="";try{for(;;){let{done:o,value:s}=await t.read();if(o)break;n+=r.decode(s,{stream:!0});let i;for(;(i=n.indexOf(`
|
|
206
|
+
`))!==-1;){let a=n.slice(0,i).trim();if(n=n.slice(i+1),!a.startsWith("data:"))continue;let l=a.slice(5).trim();if(!(!l||l==="[DONE]"))try{yield JSON.parse(l)}catch{}}}}finally{t.releaseLock()}}function F7(e=process.env){return(e.ANTHROPIC_BASE_URL?.trim()||"https://api.anthropic.com").replace(/\/$/,"")}async function xM(e){let{creds:t,model:r,payload:n}=e,o={"Content-Type":"application/json","anthropic-version":"2023-06-01"},s=n.system;t.kind==="api_key"?o["x-api-key"]=t.key:(o.Authorization=`Bearer ${t.token}`,o["anthropic-beta"]="oauth-2025-04-20",s=[{type:"text",text:M7},{type:"text",text:n.system}]);let i=wM({system:s,tools:Array.isArray(n.tools)&&n.tools.length>0?n.tools:void 0,messages:n.messages,toolBreakpointName:typeof n.cacheToolName=="string"?n.cacheToolName:void 0}),a=await fetch(`${F7()}/v1/messages`,{method:"POST",headers:o,signal:e.signal,body:JSON.stringify({model:r,max_tokens:n.maxTokens,system:i.system,messages:i.messages,...i.tools?{tools:i.tools}:{},...n.temperature!==void 0?{temperature:n.temperature}:{},stream:!0})});if(!a.ok||!a.body){let c=await a.text().catch(()=>"");throw new Error(`Anthropic stream failed: HTTP ${a.status}${c?` \u2014 ${c.slice(0,300)}`:""}`)}let l=L7();for await(let c of U7(a.body)){let u=B7(l,c);u&&e.onDelta(u)}return W7(l)}var M7,nb=p(()=>{"use strict";SM();M7="You are Claude Code, Anthropic's official CLI for Claude."});function Xt(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object")continue;let n=r;typeof n.name!="string"||!n.name.trim()||t.push({name:n.name.trim(),description:typeof n.description=="string"?n.description:"",inputSchema:n.input_schema??{}})}return t}function $7(e){let t=e.replace(/\s+/g," ").trim();return t.length>CM?`${t.slice(0,CM-1)}\u2026`:t}function AM(e,t=K7){if(e.length===0)return"";let r=["Kynver server tools:","","You can call the tools listed below. They run on the Kynver server, not on this machine.","To call one, reply with a fenced block and nothing after it:","",cn,'{"name": "<tool name>", "input": { ... }}',"```","","Rules:","- Use a name from the list below verbatim. A name that is not on the list is ignored.","- `input` must be a JSON object matching that tool's schema.","- One block per reply. Stop after it; the result comes back on the next turn.","- Say what you are about to do in one short sentence before the block.","- If no tool is needed, just answer normally and emit no block.",`- ${vp}`,"","Tools:"].join(`
|
|
143
207
|
`),n=[],o=r.length,s=[];for(let c of e){let u=`
|
|
144
|
-
- ${c.name}: ${
|
|
208
|
+
- ${c.name}: ${$7(c.description)}
|
|
145
209
|
input schema: ${JSON.stringify(c.inputSchema)}`;if(o+u.length>t){s.push(c.name);continue}o+=u.length,n.push(u)}let i=s.length,a=s.slice(0,40).join(", ")+(i>40?", \u2026":""),l=i>0?`
|
|
146
210
|
|
|
147
|
-
[${i} further tool(s) not shown this turn \u2014 do not guess their names or inputs. They exist by name only: ${a}. If the task needs one, call load_tools("connected", service) with that app's name to get a shorter list that fits.]`:"";return`${r}${n.join("")}${l}`}function
|
|
148
|
-
${
|
|
149
|
-
${r(e.length-n)}`}function
|
|
211
|
+
[${i} further tool(s) not shown this turn \u2014 do not guess their names or inputs. They exist by name only: ${a}. If the task needs one, call load_tools("connected", service) with that app's name to get a shorter list that fits.]`:"";return`${r}${n.join("")}${l}`}function V7(e){let t=[],r=0;for(;;){let n=e.indexOf(cn,r);if(n===-1)break;let o=n+cn.length,s=e.indexOf("```",o);if(s===-1||e.startsWith(cn,s))return{fences:t,unterminated:{start:n,body:e.slice(o)}};t.push({start:n,end:s+3,body:e.slice(o,s)}),r=s+3}return{fences:t,unterminated:null}}function un(e,t){let{fences:r,unterminated:n}=V7(e);if(r.length===0&&!n)return{text:e,calls:[],rejected:[],cut:null};let o=[],s=[],i="",a=0;for(let c of r){i+=e.slice(a,c.start),a=c.end;let u;try{u=JSON.parse(c.body.trim())}catch{s.push("malformed");continue}let d=u,f=typeof d?.name=="string"?d.name.trim():"";if(!f||!t.has(f)){s.push(f||"unnamed");continue}let m=d.input&&typeof d.input=="object"&&!Array.isArray(d.input)?d.input:{};o.push({name:f,input:m})}let l=null;return n&&(i+=e.slice(a,n.start),a=e.length,l={name:(j7.exec(n.body)?.[1]?.trim()??"")||null}),i+=e.slice(a),{text:i.trim(),calls:o,rejected:s,cut:l}}function EM(e,t){return`cursor_${e}_${t}`}function dn(e,t,r=""){let n=[],o=`${e.text}${r}`;return o&&n.push({type:"text",text:o}),e.calls.forEach((s,i)=>{n.push({type:"tool_use",id:EM(t,i),name:s.name,input:s.input})}),e.cut&&n.push({type:"tool_use",id:EM(t,"cut"),name:H7,input:{tool:e.cut.name,reason:"unterminated_fence"}}),{content:n,stop_reason:e.calls.length>0||e.cut?"tool_use":"end_turn"}}function G7(e){let t=Math.min(e.length,cn.length-1);for(let r=t;r>0;r-=1)if(cn.startsWith(e.slice(e.length-r)))return r;return 0}var cn,vp,K7,CM,H7,j7,zt,Xs=p(()=>{"use strict";cn="```kynver-tool",vp="Call a Kynver tool only by writing the fenced block in this reply. Never run a shell command, echo, or local script to imitate the fence. A shell command does not call the tool and the server will not run it.";K7=64e3,CM=600;H7="kynver_tool_call_cut",j7=/"name"\s*:\s*"([^"\\]*)"/;zt=class{held="";inFence=!1;push(t){this.held+=t;let r="";for(;;){if(this.inFence){let s=this.held.indexOf("```");if(s===-1)return this.held=this.held.slice(-2),r;this.held=this.held.slice(s+3),this.inFence=!1;continue}let n=this.held.indexOf(cn);if(n!==-1){r+=this.held.slice(0,n),this.held=this.held.slice(n+cn.length),this.inFence=!0;continue}let o=G7(this.held);return r+=this.held.slice(0,this.held.length-o),this.held=this.held.slice(this.held.length-o),r}}end(){if(this.inFence)return this.held="","";let t=this.held;return this.held="",t}}});function PM(e){return`[\u2026 ${e} more characters of the user's message omitted to fit this prompt \u2026]`}function J7(e){return`[\u2026 ${e} more characters of Kynver's turn context omitted to fit this prompt \u2026]`}function q7(e,t){if(e.length<=t)return e;let r=e.indexOf(IM),n=r>=0?e.indexOf(Qs,r):-1;if(r<0||n<0)return Zs(e,t,PM);let o=e.slice(0,r),s=e.slice(r,n+Qs.length),i=Zs(e.slice(n+Qs.length),Math.max(0,t-o.length),PM),a=t-o.length-i.length,l=Qs.length+1,c=s.slice(0,s.length-Qs.length),u=s.length<=a?s:`${Zs(c,Math.max(IM.length,a-l-100),J7)}
|
|
212
|
+
${Qs}`;return`${o}${u}${i}`}function ob(e){return`[\u2026 ${e} more characters of this tool result omitted to fit this prompt; call the tool again if you need them \u2026]`}function Y7(e){return`[\u2026 ${e} more characters omitted to fit this prompt \u2026]`}function Zs(e,t,r){if(e.length<=t)return e;let n=Math.max(0,t);return`${e.slice(0,n)}
|
|
213
|
+
${r(e.length-n)}`}function TM(e,t){let r=e.map(l=>({...l,kept:l.text,dropped:!1})),n=()=>r.reduce((l,c)=>c.dropped?l:l+c.kept.length+2,0),o=()=>r.filter(l=>!l.dropped).map(l=>l.kept).join(`
|
|
150
214
|
|
|
151
|
-
`);if(r.length===0||n()<=t)return{body:o(),dropped:!1};let s=-1;for(let l=r.length-1;l>=0;l-=1)if(r[l].ask){s=l;break}let i=r.length-1;s>=0&&(r[s].kept=
|
|
152
|
-
`)}function
|
|
153
|
-
`).trim():""}function
|
|
215
|
+
`);if(r.length===0||n()<=t)return{body:o(),dropped:!1};let s=-1;for(let l=r.length-1;l>=0;l-=1)if(r[l].ask){s=l;break}let i=r.length-1;s>=0&&(r[s].kept=q7(r[s].kept,8e3));for(let l=0;l<i&&n()>t;l+=1){let c=r[l];c.renderShrunk&&c.kept.length>1500&&(c.kept=c.renderShrunk(1500))}let a=s>=0?s:i;for(let l=0;l<a&&n()>t;l+=1)r[l].dropped=!0;for(let l=s+1;l<i&&n()>t;l+=1)r[l].dropped=!0;if(n()>t&&!r[i].ask){let l=n()-r[i].kept.length-2,c=Math.max(0,t-l-2),u=r[i].renderShrunk?ob:Y7;r[i].kept=Zs(r[i].kept,Math.max(0,c-u(r[i].kept.length).length-1),u)}return{body:o(),dropped:r.some(l=>l.dropped)}}var OM,IM,Qs,NM=p(()=>{"use strict";OM="[System reminder]";IM="<turn_context>",Qs="</turn_context>"});function Q7(e){if(typeof e=="string")return e;if(!Array.isArray(e))return e===void 0?"":JSON.stringify(e);let t=[];for(let r of e){if(typeof r=="string"){t.push(r);continue}if(!r||typeof r!="object")continue;let n=r;typeof n.text=="string"&&t.push(n.text)}return t.join(`
|
|
216
|
+
`)}function Z7(e){return typeof e=="string"?e.trim():Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
217
|
+
`).trim():""}function eQ(e){let t=Z7(e);return t.length>0&&!t.startsWith(OM)}function tQ(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&t.type==="tool_result")}function sb(e,t){if(typeof e=="string")return e;if(!Array.isArray(e))return"";let r=[];for(let n of e){if(!n||typeof n!="object")continue;let o=n;if(o.type==="text"&&typeof o.text=="string"&&o.text.trim())r.push(o.text);else if(o.type==="tool_result"){let s=Q7(o.content??o.text),i=t===void 0?s:Zs(s,t,ob);r.push(o.is_error?`[tool error]
|
|
154
218
|
${i}`:`[tool result]
|
|
155
219
|
${i}`)}else if(o.type==="tool_use"&&typeof o.name=="string"){let s=o.input===void 0?"":` ${JSON.stringify(o.input)}`;r.push(`[tool call: ${o.name}${s}]`)}}return r.join(`
|
|
156
|
-
`)}function
|
|
157
|
-
${l}`),a.push(t==="ask"?"This is a website chat turn in Ask mode. Answer the user in plain language. Do not invent Kynver server tool calls.":
|
|
158
|
-
${k}`,ask:!1,renderShrunk:
|
|
159
|
-
${
|
|
220
|
+
`)}function oQ(e){let t=typeof e=="string"?e:e?.access,r=typeof e=="string"||e!==void 0&&e.source!=="default";if(!t||t==="off"||!r)return[LM,rQ,"Never use runtime_command run dispatch and never implement coding tasks inline in the chat workspace when a worker was requested or dispatch failed.",BM,vp].join(" ");let n=t==="full"?"The user gave you their whole computer: you may run commands, read and write files and research the web anywhere on it.":"The user gave you access to their computer: run commands, read and write files and research the web in the folder you started in"+(t==="folders"?" and the other folders they chose.":".");return[LM,`${n} Do the work there yourself and say what you ran and what you changed.`,`Local commands are only for this computer. ${vp}`,nQ,"Send harness workers only for factory PR work (changes to the Kynver repo, PRs, harness worktrees) \u2014 call agent_os_submit_action_intent with kind dispatch_workers (dryRun:true to preview; live dispatch creates Action Required approval).",BM].join(" ")}function sQ(e){return e==="assistant"?"Assistant":e==="system"?"System":"User"}function WM(e){return sb(e)}function ib(e,t=e.executionMode==="ask"?"ask":"agent",r,n){let o=t==="agent"?r??Xt(e.tools):[],s=AM(o),i=typeof n=="string"?n:n?.access,a=[],l=typeof e.system=="string"?e.system.trim():"";l&&a.push(`System:
|
|
221
|
+
${l}`),a.push(t==="ask"?"This is a website chat turn in Ask mode. Answer the user in plain language. Do not invent Kynver server tool calls.":oQ(n)),i==="off"&&a.push(X7);let c=t==="agent"?_M(e.longJob):null;c&&a.push(`Long job in progress: step ${c.stepsUsed} of up to ${c.maxSteps} (segment ${c.segment}). Keep working through the plan \u2014 don't settle for partial data \u2014 and save progress with long_job_checkpoint after each sub-task.`),s&&a.push(s);let u=[],d=-1;if(Array.isArray(e.messages))for(let y of e.messages){if(!y||typeof y!="object")continue;let v=y,k=sb(v.content);if(!k.trim())continue;let b=sQ(v.role);v.role!=="assistant"&&v.role!=="system"&&eQ(v.content)&&(d=u.length);let S=v.content;u.push({text:`${b}:
|
|
222
|
+
${k}`,ask:!1,renderShrunk:tQ(S)?R=>`${b}:
|
|
223
|
+
${sb(S,R)}`:null})}d>=0&&(u[d].ask=!0);let f=a.join(`
|
|
160
224
|
|
|
161
|
-
`),
|
|
225
|
+
`),m=u.map(y=>y.text).join(`
|
|
162
226
|
|
|
163
|
-
`);if(!u.length||
|
|
227
|
+
`);if(!u.length||f.length+2+m.length<=DM)return{head:f,body:m};let g=Math.max(z7,DM-f.length-16),h=TM(u,g-MM.length-2);return{head:f,body:h.dropped?`${MM}
|
|
164
228
|
|
|
165
|
-
${h.body}`:h.body}}function
|
|
229
|
+
${h.body}`:h.body}}function ei(e,t=e.executionMode==="ask"?"ask":"agent",r,n){let{head:o,body:s}=ib(e,t,r,n);return s?`${o}
|
|
166
230
|
|
|
167
|
-
${s}`:o}var
|
|
168
|
-
`):void 0}function
|
|
169
|
-
`))!==-1;){let
|
|
170
|
-
`))!==-1;){let
|
|
171
|
-
`))!==-1;){let
|
|
172
|
-
`):""}function
|
|
173
|
-
`)}),r}function
|
|
174
|
-
`))!==-1;){let a=n.slice(0,i).trim();if(n=n.slice(i+1),!a.startsWith("data:"))continue;let l=a.slice(5).trim();if(!(!l||l==="[DONE]"))try{yield JSON.parse(l)}catch{}}}}finally{t.releaseLock()}}async function
|
|
175
|
-
`).filter(Boolean)}finally{
|
|
176
|
-
`,{encoding:"utf8",mode:384})}catch{}}function
|
|
231
|
+
${s}`:o}var DM,z7,X7,MM,LM,rQ,BM,nQ,fl=p(()=>{"use strict";nb();Xs();NM();DM=8e4,z7=32e3,X7="Computer access is off for this chat: do not run commands or create, change or delete files on this computer. Answer from the conversation and the Kynver tools only, and tell the user they can turn computer access on in Kynver's Computers settings if the job needs it.",MM=`[earlier turns truncated \u2014 older turns are summarised under "Earlier in this conversation" in the System section when available. Never tell the user they didn't say something just because it isn't shown here.]`;LM="This is a website chat turn in Agent mode. The user may ask you to run the factory, dispatch work, or continue a plan. Do not refuse to act.",rQ="Factory coding tasks (README changes, PRs, harness worktrees) must go through a harness worker \u2014 call agent_os_submit_action_intent with kind dispatch_workers (dryRun:true to preview; live dispatch creates Action Required approval).",BM="If dispatch or worker start fails or is blocked (memory gate, wrong box, 0 workers started), report the failure clearly to the user \u2014 do not substitute inline edits or open a PR yourself.",nQ="Credentials rule: never use credentials you find on this computer \u2014 API keys, tokens, passwords, database or storage URLs, service-account or key files, SSH keys, saved logins, anything in environment variables, shell profiles, config files or other projects \u2014 unless the user explicitly told you in this conversation to use that specific credential. If a job would need one, stop, say exactly what you would need and why, and ask. When a read or command is refused (denied path, folder sandbox, missing variable), say so plainly and do not look for another way in."});import{homedir as iQ}from"node:os";function ti(e,t=iQ()){let r=P();return Jo({engine:e,local:{chatComputerAccess:r.chatComputerAccess,chatWorkFolders:r.chatWorkFolders},home:t})}var Rp=p(()=>{"use strict";$();xn()});function Ee(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function xe(e){return typeof e=="string"&&e.trim()?e:void 0}function ab(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function lb(e,t,r,n){let o=t===null||t===0;return{kind:"command",command:e,exitCode:t,durationMs:r,outputBytes:n,ok:o,...o?{}:{reason:"exit_nonzero"}}}function cb(...e){let t=0,r=!1;for(let n of e)typeof n=="string"&&(r=!0,t+=Buffer.byteLength(n,"utf8"));return r?t:null}function ub(e){let t=new Map;return{start(r){r&&!t.has(r)&&t.set(r,e())},elapsed(r){if(!r)return null;let n=t.get(r);return t.delete(r),n===void 0?null:Math.max(0,e()-n)}}}function FM(e=Date.now){let t=ub(e);return r=>{let n=Ee(r.item);if(!n)return[];let o=xe(n.id);if(r.type==="item.started")return t.start(o),[];if(r.type!=="item.completed")return[];if(n.type==="command_execution"){let s=xe(n.command)??"",i=ab(n.exit_code),a=lb(s,i,t.elapsed(o),cb(n.aggregated_output));return n.status==="failed"&&a.ok?[{...a,ok:!1,reason:"failed"}]:[a]}if(n.type==="file_change"&&Array.isArray(n.changes)){let s=t.elapsed(o),i=n.status!=="failed";return n.changes.map(a=>Ee(a)).filter(a=>!!a&&!!xe(a.path)).map(a=>({kind:"file_change",path:xe(a.path),...xe(a.kind)?{change:xe(a.kind)}:{},durationMs:s,ok:i,...i?{}:{reason:"failed"}}))}return[]}}function KM(e=Date.now){let t=ub(e);return r=>{if(r.type!=="tool_call")return[];let n=xe(r.call_id);if(r.subtype==="started")return t.start(n),[];if(r.subtype!=="completed")return[];let o=Ee(r.tool_call);if(!o)return[];let s=t.elapsed(n),i=Ee(o.shellToolCall);if(i){let a=Ee(i.result),l=Ee(a?.success)??Ee(a?.failure),c=xe(Ee(i.args)?.command)??xe(l?.command)??"",u=ab(l?.exitCode)??(a?.failure?1:null),d=ab(l?.executionTime)??s;return[lb(c,u,d,cb(l?.stdout,l?.stderr))]}for(let[a,l]of Object.entries(aQ)){let c=Ee(o[a]);if(!c)continue;let u=Ee(c.result),d=xe(Ee(c.args)?.path)??xe(Ee(u?.success)?.path);if(!d)return[];let f=!u?.failure;return[{kind:"file_change",path:d,change:l,durationMs:s,ok:f,...f?{}:{reason:"failed"}}]}return[]}}function $M(){return e=>{if(e.event!=="step_update")return[];let t=Ee(e.step_update);if(!t||t.step_type!=="tool")return[];let r=xe(t.tool_name);return r?[{kind:"tool",command:r.trim(),ok:!0}]:[]}}function uQ(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let t=e.map(r=>Ee(r)).filter(r=>!!r&&typeof r.text=="string").map(r=>r.text);return t.length?t.join(`
|
|
232
|
+
`):void 0}function UM(e){let t=Ee(e.message)?.content;return Array.isArray(t)?t.map(r=>Ee(r)).filter(r=>!!r):[]}function HM(e=Date.now){let t=ub(e),r=new Map,n=new Set,o=(i,a,l,c,u)=>{if(i.name==="Bash"){let g=u?null:l?Number(c?.match(cQ)?.[1]??1):0,h=lb(xe(i.input.command)??"",g,a,cb(c));return u?{...h,ok:!1,reason:u}:h}let d=l||u?{reason:u??"failed"}:{},f=lQ[i.name],m=xe(i.input.file_path)??xe(i.input.notebook_path);return f&&m?{kind:"file_change",path:m,change:f,durationMs:a,ok:!l&&!u,...d}:{kind:"tool",command:i.name,durationMs:a,ok:!l&&!u,...d}};return Object.assign(i=>{if(i.type==="assistant"){for(let l of UM(i)){let c=xe(l.id),u=xe(l.name);l.type!=="tool_use"||!c||!u||r.has(c)||n.has(c)||(r.set(c,{name:u,input:Ee(l.input)??{}}),t.start(c))}return[]}if(i.type!=="user")return[];let a=[];for(let l of UM(i)){let c=xe(l.tool_use_id);if(l.type!=="tool_result"||!c)continue;let u=r.get(c);u&&(r.delete(c),n.add(c),a.push(o(u,t.elapsed(c),l.is_error===!0,uQ(l.content))))}return a},{interrupted(){let i=[...r.entries()].map(([a,l])=>(n.add(a),o(l,t.elapsed(a),!0,void 0,"interrupted")));return r.clear(),i}})}var aQ,lQ,cQ,ml=p(()=>{"use strict";aQ={writeToolCall:"write",editToolCall:"update",deleteToolCall:"delete"};lQ={Write:"write",Edit:"update",MultiEdit:"update",NotebookEdit:"update"},cQ=/exit code (\d+)/i});function Qt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function jM(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string"&&r.trim().length>0);return t.length>0?t:void 0}function VM(e){let t=Qt(e.type);if(!t)return null;if(t==="interactionUpdate"||t==="interaction_update"){let r=Qt(e.subtype)??Qt(e.updateType),n=Qt(e.blockReasonType)??Qt(e.blockReason?.type),o=jM(e.approvalReasonTypes)??jM(e.approval?.reasonTypes),s=Qt(e.toolCallId)??Qt(e.tool_call_id);if(r?.toLowerCase().includes("reject")||n?.toLowerCase().includes("reject")||o?.some(i=>i.includes("unapproved")))return{toolCallId:s,blockReasonType:n,approvalReasonTypes:o,source:"stream_event"}}if(t==="tool_call"){let r=Qt(e.subtype)?.toLowerCase();if(r!=="rejected"&&r!=="blocked"&&r!=="denied")return null;let n=e.tool_call&&typeof e.tool_call=="object"&&!Array.isArray(e.tool_call)?e.tool_call:null,o=Qt(e.toolCallId)??Qt(e.tool_call_id),s;if(n){for(let i of Object.keys(n))if(i.endsWith("ToolCall")){s=i.slice(0,-8)||i;break}}return{toolCallId:o,toolName:s,blockReasonType:r,source:"stream_event"}}return null}function wp(e){if(!pQ.test(e))return null;let t=e.match(/blockReasonType[=:]\s*(\w+)/i),r=e.match(/toolCallId[=:\s]+([^\s,]+)/i),n=e.match(/approvalReasonTypes[=:\s]*\[([^\]]+)\]/i);return{toolCallId:r?.[1],blockReasonType:t?.[1]??(e.includes("userRejected")?"userRejected":void 0),approvalReasonTypes:n?n[1].split(",").map(o=>o.trim().replace(/^["']|["']$/g,"")):e.includes("unapproved_commands")?["unapproved_commands"]:void 0,source:"stderr"}}function Sp(e){let t=[dQ];return e.toolName&&t.push(`tool=${e.toolName}`),e.toolCallId&&t.push(`toolCallId=${e.toolCallId}`),e.blockReasonType&&t.push(`blockReason=${e.blockReasonType}`),e.approvalReasonTypes?.length&&t.push(`approvalReasons=${e.approvalReasonTypes.join(",")}`),t.join(": ")}var dQ,pQ,GM=p(()=>{"use strict";dQ="cursor_tool_approval_blocked",pQ=/blockReasonType[=:]\s*(\w+)|userRejected|Shell approval gate|approvalReasonTypes|unapproved_commands/i});function _p(e){console.error(JSON.stringify({scope:"cursor/chat-turn",requestId:e.requestId??"",turnId:e.turnId??"",event:e.event,...e.exitCode!==void 0?{exitCode:e.exitCode}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{},...e.toolName?{toolName:e.toolName}:{},...e.blockReason?{blockReason:e.blockReason}:{},...e.stopReason?{stopReason:e.stopReason}:{},...e.error?{error:e.error}:{}}))}var JM=p(()=>{"use strict"});import{spawn as fQ}from"node:child_process";function db(e){return e==="ask"?"ask":"agent"}function yQ(e,t,r,n=[],o="agent"){return[...n,"-p",...o==="ask"?["--mode","ask"]:["--force"],"--trust","--workspace",t,"--output-format","stream-json","--stream-partial-output","--model",e,r]}function kQ(e,t){if(e.type==="stream_event"&&e.event&&typeof e.event=="object"){let r=e.event;if(r.type==="content_block_delta"&&r.delta?.type==="text_delta"&&r.delta.text)return r.delta.text}if(e.type==="assistant"&&e.message&&typeof e.message=="object"){let r=e.message.content;if(Array.isArray(r)){let n=r.filter(o=>!!o&&typeof o=="object"&&o.type==="text"&&typeof o.text=="string").map(o=>o.text).join("");if(n&&n.startsWith(t))return n.slice(t.length)}}return""}function bQ(e){return e.type!=="result"?"":typeof e.result=="string"?e.result:""}function pb(e,t){let r=e.trim(),n=t.trim();return r?n&&(t.length>e.length||t.length===e.length&&t!==e)?t:e:t}function fb(e,t,r){if(!e)return;if(e.startsWith(t)){let o=e.slice(t.length);o&&r(o);return}if(!t.trim()){r(e);return}let n=t.trimEnd();if(e.startsWith(n)){let o=e.slice(n.length);o&&r(o);return}e.length>t.length&&r(e.slice(t.length))}function vQ(e){let t=e.usage;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,n=typeof r.input_tokens=="number"?r.input_tokens:typeof r.inputTokens=="number"?r.inputTokens:typeof r.prompt_tokens=="number"?r.prompt_tokens:void 0,o=typeof r.output_tokens=="number"?r.output_tokens:typeof r.outputTokens=="number"?r.outputTokens:typeof r.completion_tokens=="number"?r.completion_tokens:void 0;return n===void 0&&o===void 0?null:{input_tokens:n??0,output_tokens:o??0}}function RQ(e,t){if(hQ.test(e))return`${Ng}: ${e.trim().slice(0,240)||"agent CLI is not logged in"}`;let r=e.trim().slice(0,240);return t===null?r?`cursor_chat_failed: ${r}`:"cursor_chat_failed: process exited without a code":r?`cursor_chat_failed: exit ${t} \u2014 ${r}`:`cursor_chat_failed: exit ${t}`}async function qM(e){let t=e.env??process.env,r=e.access??ti("cursor"),n=e.workspaceDir??r.workDir,o=KM(),s=db(e.payload.executionMode),i=s==="agent"?Xt(e.payload.tools):[],a=new Set(i.map(f=>f.name)),l=ei(e.payload,s,i,r),c=e.spawnTarget;if(!c){let f=$n(t),m=oa(f);c={executable:m.executable,prefixArgs:m.prefixArgs}}let u=yQ(e.model,n,l,c.prefixArgs,s),d={...Yt(t),CI:"1",NO_COLOR:"1"};return await new Promise((f,m)=>{let g;try{let x=z({cwd:n,detached:process.platform!=="win32",shell:!1,stdio:["ignore","pipe","pipe"],env:d});g=fQ(c.executable,u,x)}catch(x){if(x.code==="ENOENT"){m(new Error(`${hu}: failed to spawn \`${c.executable}\`. Install the Cursor Agent CLI and keep \`agent\` on PATH.`));return}m(x instanceof Error?x:new Error(String(x)));return}let h=!1,y=new zt,v="",k=x=>{let T=y.push(x);T&&(v+=T,e.onDelta(T))},b="",_="",S={input_tokens:0,output_tokens:0},R="",w="",L=!1,N=!1,A,O=wp(R),W=null,D=x=>{if(h)return;if(h=!0,clearTimeout(E),A&&clearTimeout(A),e.signal?.removeEventListener("abort",H),x){_p({requestId:e.requestId,turnId:e.turnId,event:"turn_error",exitCode:W,error:x.message,...O?.toolCallId?{toolCallId:O.toolCallId}:{},...O?.toolName?{toolName:O.toolName}:{},...O?.blockReasonType?{blockReason:O.blockReasonType}:{}}),m(x);return}let T=wp(R);if(T&&(O=T),O){let Z=new Error(Sp(O));_p({requestId:e.requestId,turnId:e.turnId,event:"turn_approval_blocked",exitCode:W,toolCallId:O.toolCallId,toolName:O.toolName,blockReason:O.blockReasonType,error:Z.message}),m(Z);return}let U=y.end();U&&(v+=U,e.onDelta(U));let te=pb(b,_),oe=un(te,a);fb(oe.text,v,e.onDelta),oe.rejected.length>0&&console.error(JSON.stringify({event:"cursor_tool_call_rejected",names:oe.rejected.slice(0,5),advertised:a.size}));let{content:ge,stop_reason:Ae}=dn(oe,e.turnId??"turn");_p({requestId:e.requestId,turnId:e.turnId,event:"turn_end",exitCode:W,stopReason:Ae}),f({content:ge,stop_reason:Ae,usage:S})},G=x=>{g.pid?fe(g.pid,x):Ze(g,x)},Q=()=>{G("SIGTERM"),A??=setTimeout(()=>{N||G("SIGKILL")},gQ),A.unref()},H=()=>{Q(),D(new Error("cursor_chat_aborted"))},E=setTimeout(()=>{L=!0,Q()},e.timeoutMs??mQ);if(g.on("error",x=>{if(x.code==="ENOENT"){D(new Error(`${hu}: failed to spawn \`${c.executable}\`. Install the Cursor Agent CLI and keep \`agent\` on PATH.`));return}D(x)}),e.signal){if(e.signal.aborted){H();return}e.signal.addEventListener("abort",H)}let V=x=>{let T=x.trim();if(!T)return;let U;try{U=JSON.parse(T)}catch{return}let te=kQ(U,b);te&&(b+=te,k(te));let oe=bQ(U);oe&&(_=oe);let ge=vQ(U);if(ge&&(S=ge),e.onActivity)for(let Z of o(U))e.onActivity(Z);let Ae=VM(U);Ae&&(O=Ae,Q(),D(new Error(Sp(Ae))))};g.stdout?.on("data",x=>{w+=typeof x=="string"?x:x.toString("utf8");let T;for(;(T=w.indexOf(`
|
|
233
|
+
`))!==-1;){let U=w.slice(0,T);w=w.slice(T+1),V(U)}}),g.stderr?.on("data",x=>{R+=typeof x=="string"?x:x.toString("utf8"),R.length>8e3&&(R=R.slice(-8e3));let T=wp(R);T&&(O=T,Q(),D(new Error(Sp(T))))}),g.on("close",x=>{if(N=!0,W=x,w.trim()&&V(w),L){D(new Error("cursor_chat_timeout"));return}if(x!==0&&!b&&!_){D(new Error(RQ(R,x)));return}D()})})}var mQ,gQ,hQ,xp=p(()=>{"use strict";ys();M();fl();Rp();lo();ml();ks();Xs();GM();JM();mQ=24e4,gQ=1500,hQ=/not logged in|please run[`\s]+agent login|authentication required|unauthorized|invalid api key/i});import{spawn as wQ}from"node:child_process";function xQ(e){return e==="ask"?"ask":"agent"}function CQ(e,t){return e==="ask"?["--sandbox","read-only"]:!t||t.source==="default"?["--sandbox","workspace-write"]:t.access==="off"?["--sandbox","read-only"]:t.access==="full"?["--sandbox","danger-full-access"]:["--sandbox","workspace-write","-c","sandbox_workspace_write.network_access=true",...t.extraFolders.flatMap(r=>["--add-dir",r])]}function EQ(e,t,r="agent",n=[],o=process.platform,s){return[...n,"exec",...bu(o),"--skip-git-repo-check","--json","--ask-for-approval","never",...CQ(r,s),"--model",e,t]}function AQ(e,t){if((e.type==="item.updated"||e.type==="item.completed")&&e.item&&typeof e.item=="object"){let r=e.item;if(r.type==="agent_message"&&typeof r.text=="string"&&r.text.startsWith(t))return r.text.slice(t.length)}if(e.type==="agent_message.delta"||e.type==="item.delta"){let r=typeof e.delta=="string"?e.delta:e.delta&&typeof e.delta=="object"?e.delta.text:void 0;if(typeof r=="string")return r}return""}function PQ(e){if(e.type!=="turn.completed")return null;let t=e.usage;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,n=typeof r.input_tokens=="number"?r.input_tokens:void 0,o=typeof r.output_tokens=="number"?r.output_tokens:void 0;return n===void 0&&o===void 0?null:{input_tokens:n??0,output_tokens:o??0}}function IQ(e,t){if(_Q.test(e))return`${zk}: ${e.trim().slice(0,240)||"Codex CLI is not logged in"}`;let r=e.trim().slice(0,240);return t===null?r?`codex_chat_failed: ${r}`:"codex_chat_failed: process exited without a code":r?`codex_chat_failed: exit ${t} \u2014 ${r}`:`codex_chat_failed: exit ${t}`}async function YM(e){let t=e.env??process.env,r=e.access??ti("codex"),n=e.workspaceDir??r.workDir,o=xQ(e.payload.executionMode),s=o==="agent"?Xt(e.payload.tools):[],i=new Set(s.map(f=>f.name)),a=ei(e.payload,o,s,r),l=FM(),c=e.spawnTarget??{executable:t.KYNVER_CODEX_BIN?.trim()||t.CODEX_BIN?.trim()||xr(),prefixArgs:[]},u=EQ(e.model,a,o,c.prefixArgs,process.platform,r),d={...Yt(t),CI:"1",NO_COLOR:"1"};return await new Promise((f,m)=>{let g;try{let W=z({cwd:n,detached:!1,shell:!1,stdio:["ignore","pipe","pipe"],env:d}),[D,G]=ae(c.executable,u);g=wQ(D,G,W)}catch(W){if(W.code==="ENOENT"){m(new Error(`${pp}: failed to spawn \`${c.executable}\`. Install the Codex CLI and keep \`codex\` on PATH.`));return}m(W instanceof Error?W:new Error(String(W)));return}let h=!1,y=new zt,v=W=>{let D=y.push(W);D&&e.onDelta(D)},k="",b={input_tokens:0,output_tokens:0},_="",S="",R=!1,w=W=>{if(h)return;if(h=!0,clearTimeout(A),e.signal?.removeEventListener("abort",N),W){m(W);return}let D=y.end();D&&e.onDelta(D);let G=un(k,i);G.rejected.length>0&&console.error(JSON.stringify({event:"codex_tool_call_rejected",names:G.rejected.slice(0,5),advertised:i.size})),f({...dn(G,e.turnId??"turn"),usage:b})},L=()=>Ze(g,"SIGTERM"),N=()=>{L(),w(new Error("codex_chat_aborted"))},A=setTimeout(()=>{R=!0,L()},e.timeoutMs??SQ);if(g.on("error",W=>{if(W.code==="ENOENT"){w(new Error(`${pp}: failed to spawn \`${c.executable}\`. Install the Codex CLI and keep \`codex\` on PATH.`));return}w(W)}),e.signal){if(e.signal.aborted){N();return}e.signal.addEventListener("abort",N)}let O=W=>{let D=W.trim();if(!D)return;let G;try{G=JSON.parse(D)}catch{return}let Q=AQ(G,k);Q&&(k+=Q,v(Q));let H=PQ(G);if(H&&(b=H),e.onActivity)for(let E of l(G))e.onActivity(E)};g.stdout?.on("data",W=>{S+=typeof W=="string"?W:W.toString("utf8");let D;for(;(D=S.indexOf(`
|
|
234
|
+
`))!==-1;){let G=S.slice(0,D);S=S.slice(D+1),O(G)}}),g.stderr?.on("data",W=>{_+=typeof W=="string"?W:W.toString("utf8"),_.length>8e3&&(_=_.slice(-8e3))}),g.on("close",W=>{if(S.trim()&&O(S),R){w(new Error("codex_chat_timeout"));return}if(W!==0&&!k){w(new Error(IQ(_,W)));return}w()})})}var SQ,_Q,zM=p(()=>{"use strict";Vn();Kg();M();qe();fl();Rp();ml();mp();lo();Xs();SQ=24e4,_Q=/not logged in|please run[`\s]+codex login|authentication required|unauthorized|invalid api key|401\b/i});import{spawn as OQ}from"node:child_process";function NQ(e,t,r="agent",n=[]){return[...n,...Eu({executionMode:r==="ask"?"read_only":"write",prompt:t},e)]}function DQ(e,t){if(XM.test(e))return`${hp}: ${e.trim().slice(0,240)||"Google Antigravity is not signed in"}`;let r=e.trim().slice(0,240);return t===null?r?`antigravity_chat_failed: ${r}`:"antigravity_chat_failed: process exited without a code":r?`antigravity_chat_failed: exit ${t} \u2014 ${r}`:`antigravity_chat_failed: exit ${t}`}async function QM(e){let t=e.env??process.env,r=e.access??ti("antigravity"),n=e.workspaceDir??r.workDir,o=$M(),s=db(e.payload.executionMode),i=s==="agent"?Xt(e.payload.tools):[],a=new Set(i.map(f=>f.name)),l=ei(e.payload,s,i,r),c=e.spawnTarget??{executable:ht(t),prefixArgs:[]},u=NQ(e.model,l,s,c.prefixArgs),d={...Yt(t),CI:"1",NO_COLOR:"1"};return await new Promise((f,m)=>{let g;try{let D=z({cwd:n,detached:!1,shell:!1,stdio:["ignore","pipe","pipe"],env:d}),[G,Q]=ae(c.executable,u);g=OQ(G,Q,D)}catch(D){if(D.code==="ENOENT"){m(new Error(`${gp}: failed to spawn \`${c.executable}\`. Install Google Antigravity and keep \`agy\` on PATH.`));return}m(D instanceof Error?D:new Error(String(D)));return}let h=!1,y=new zt,v=D=>{let G=y.push(D);G&&e.onDelta(G)},k="",b="",_={input_tokens:0,output_tokens:0},S="",R="",w=!1,L=D=>{if(h)return;if(h=!0,clearTimeout(O),e.signal?.removeEventListener("abort",A),D){m(D);return}let G=b.length>=k.length&&b?b:k;b.startsWith(k)&&b.length>k.length?v(b.slice(k.length)):!k&&b&&v(b);let Q=y.end();Q&&e.onDelta(Q);let H=un(G,a);f({...dn(H,e.turnId??"turn"),usage:_})},N=()=>Ze(g,"SIGTERM"),A=()=>{N(),L(new Error("antigravity_chat_aborted"))},O=setTimeout(()=>{w=!0,N()},e.timeoutMs??TQ);if(g.on("error",D=>{if(D.code==="ENOENT"){L(new Error(`${gp}: failed to spawn \`${c.executable}\`. Install Google Antigravity and keep \`agy\` on PATH.`));return}L(D)}),e.signal){if(e.signal.aborted){A();return}e.signal.addEventListener("abort",A)}let W=D=>{let G=D.trim();if(!G)return;let Q;try{Q=JSON.parse(G)}catch{return}if(e.onActivity)for(let E of o(Q))e.onActivity(E);let H=Yl(Q);if(H&&(H.textDelta&&(k+=H.textDelta,v(H.textDelta)),H.usage&&(_={input_tokens:H.usage.inputTokens??_.input_tokens,output_tokens:H.usage.outputTokens??_.output_tokens}),!!H.terminal)){if(!H.terminal.ok){let E=H.terminal.error??"antigravity cli result error";if(N(),XM.test(E)){L(new Error(`${hp}: ${E.slice(0,240)}`));return}L(new Error(`antigravity_chat_failed: ${E.slice(0,240)}`));return}b=H.terminal.finalResult??""}};g.stdout?.on("data",D=>{R+=typeof D=="string"?D:D.toString("utf8");let G;for(;(G=R.indexOf(`
|
|
235
|
+
`))!==-1;){let Q=R.slice(0,G);R=R.slice(G+1),W(Q)}}),g.stderr?.on("data",D=>{S+=typeof D=="string"?D:D.toString("utf8"),S.length>8e3&&(S=S.slice(-8e3))}),g.on("close",D=>{if(R.trim()&&W(R),w){L(new Error("antigravity_chat_timeout"));return}if(!h){if(D!==0&&!k&&!b){L(new Error(DQ(S,D)));return}L()}})})}var TQ,XM,ZM=p(()=>{"use strict";qn();Of();M();qe();kp();fl();Rp();lo();ml();xp();Xs();TQ=24e4,XM=/authentication required|not logged in|you are not logged|not authenticated/i});function MQ(){return{text:"",toolCalls:[],finishReason:null,promptTokens:0,completionTokens:0}}function LQ(e,t){let r=t,n=r.choices?.[0],o="";n?.delta?.content&&(o=n.delta.content,e.text+=o);for(let s of n?.delta?.tool_calls??[]){for(;e.toolCalls.length<=s.index;)e.toolCalls.push({id:"",name:"",argsJson:""});let i=e.toolCalls[s.index];s.id&&(i.id=s.id),s.function?.name&&(i.name+=s.function.name),s.function?.arguments&&(i.argsJson+=s.function.arguments)}return n?.finish_reason&&(e.finishReason=n.finish_reason),r.usage&&(e.promptTokens=r.usage.prompt_tokens??e.promptTokens,e.completionTokens=r.usage.completion_tokens??e.completionTokens),o}function BQ(e){let t=[];e.text&&t.push({type:"text",text:e.text});for(let n of e.toolCalls){if(!n.name)continue;let o={};try{o=n.argsJson?JSON.parse(n.argsJson):{}}catch{o={}}t.push({type:"tool_use",id:n.id||`toolu_http_${n.name}`,name:n.name,input:o})}let r=e.toolCalls.some(n=>n.name);return{content:t,stop_reason:r&&e.finishReason!=="length"?"tool_use":e.finishReason==="length"?"max_tokens":"end_turn",usage:{input_tokens:e.promptTokens,output_tokens:e.completionTokens}}}function WQ(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=r;n.type==="image"&&n.source?.type==="base64"&&typeof n.source.data=="string"&&t.push(`data:${n.source.media_type??"image/jpeg"};base64,${n.source.data}`)}return t}function UQ(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
236
|
+
`):""}function FQ(e){let t=e.role==="assistant"?"assistant":"user";if(typeof e.content=="string")return[{role:t,content:e.content}];if(!Array.isArray(e.content))return[{role:t,content:""}];if(t==="assistant"){let s=e.content.filter(a=>a.type==="text").map(a=>a.text).join(""),i=e.content.filter(a=>a.type==="tool_use").map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input??{})}}));return[{role:"assistant",content:s||null,...i.length>0?{tool_calls:i}:{}}]}let r=[],n=[],o=[];for(let s of e.content){let i=s;i.type==="tool_result"?(r.push({role:"tool",tool_call_id:i.tool_use_id,content:UQ(i.content)}),o.push(...WQ(i.content))):i.type==="text"&&i.text&&n.push(i.text)}return o.length>0&&r.push({role:"user",content:[{type:"text",text:"Screenshot from the browser tool result above:"},...o.map(s=>({type:"image_url",image_url:{url:s}}))]}),n.length>0&&r.push({role:"user",content:n.join(`
|
|
237
|
+
`)}),r}function KQ(e,t){let r=[];e.trim()&&r.push({role:"system",content:e});for(let n of t)r.push(...FQ(n??{}));return r}function $Q(e){return e.map(t=>{let r=t;return typeof r.name!="string"||!r.name?null:{type:"function",function:{name:r.name,...r.description?{description:r.description}:{},parameters:r.input_schema??{type:"object"}}}}).filter(t=>t!==null)}async function*HQ(e){let t=e.getReader(),r=new TextDecoder,n="";try{for(;;){let{done:o,value:s}=await t.read();if(o)break;n+=r.decode(s,{stream:!0});let i;for(;(i=n.indexOf(`
|
|
238
|
+
`))!==-1;){let a=n.slice(0,i).trim();if(n=n.slice(i+1),!a.startsWith("data:"))continue;let l=a.slice(5).trim();if(!(!l||l==="[DONE]"))try{yield JSON.parse(l)}catch{}}}}finally{t.releaseLock()}}async function eL(e){let{creds:t,model:r,payload:n}=e,o=Array.isArray(n.tools)?$Q(n.tools):[],s={model:r,messages:KQ(n.system,Array.isArray(n.messages)?n.messages:[]),max_completion_tokens:n.maxTokens,stream:!0,stream_options:{include_usage:!0},...o.length>0?{tools:o}:{},...n.temperature!==void 0?{temperature:n.temperature}:{}},i=await fetch(`${t.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.apiKey}`},signal:e.signal,body:JSON.stringify(s)});if(!i.ok||!i.body){let l=await i.text().catch(()=>"");throw new Error(`${t.label} stream failed: HTTP ${i.status}${l?` \u2014 ${l.slice(0,300)}`:""}`)}let a=MQ();for await(let l of HQ(i.body)){let c=LQ(a,l);c&&e.onDelta(c)}return BQ(a)}var tL=p(()=>{"use strict"});function yo(e){let t=Qd(e.provider,e.config,e.env??process.env),r=e.boxId?vc(e.payloadAccess,e.boxId):null,n=Jo({engine:t,local:{chatComputerAccess:e.config.chatComputerAccess,chatWorkFolders:e.config.chatWorkFolders},website:r,home:e.home});return{engine:t,access:n}}var Cp=p(()=>{"use strict";Qa();xn()});function rL(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.session!="string"||!jQ.test(t.session))return null;let r=typeof t.timeLeftMs=="number"&&Number.isFinite(t.timeLeftMs)?Math.max(0,Math.floor(t.timeLeftMs)):0;return{session:t.session,timeLeftMs:r}}function nL(e){return Math.max(0,Math.min(48e4,e.timeLeftMs))}var jQ,Ep=p(()=>{"use strict";jQ=/^[A-Za-z0-9_.:-]{1,128}$/});function VQ(e=Date.now){let t=new Map,r=()=>{let n=e();for(let[o,s]of t)n-s.at>9e5&&t.delete(o);for(;t.size>64;)t.delete(t.keys().next().value)};return{get(n){return r(),t.get(n)?.sessionId??null},remember(n,o){t.delete(n),t.set(n,{sessionId:o,at:e()}),r()},forget(n){t.delete(n)}}}var oL,sL=p(()=>{"use strict";oL=VQ()});function GQ(e,t){if(e.access==="off")throw new Error("claude_code_access_off");return e.access==="full"?["--permission-mode","bypassPermissions",...Ok()]:["--permission-mode","acceptEdits",`--allowedTools=${(t?.shell==="disabled"?iL.filter(n=>n!=="Bash"):[...iL]).join(",")}`,...Ok(),...t?["--settings",t.settingsFile]:[],...e.access==="folders"?e.extraFolders.flatMap(n=>["--add-dir",n]):[]]}function mb(e){return["-p","--output-format","stream-json","--include-partial-messages","--verbose",...e.model?["--model",e.model]:[],"--append-system-prompt-file",e.systemPromptFile,...e.resumeSessionId?["--resume",e.resumeSessionId]:[],...GQ(e.access,e.sandbox),"--",e.prompt]}var iL,aL=p(()=>{"use strict";lo();iL=["Bash","WebFetch","WebSearch"]});import{readdir as JQ}from"node:fs/promises";import gb from"node:path";function hb(e){let t=e.map(r=>r.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*"));return new RegExp(`^(?:${t.join("|")})$`,"i")}async function cL(e,t,r={}){let n=r.now??Date.now,o=n(),s=r.maxEntries??qQ,i=r.maxMs??YQ,a=r.maxResults??zQ,l=hb(t),c=new Set,u=[...new Set(e.map(g=>gb.resolve(g)))],d=0,f=!1,m=()=>d>=s||n()-o>i||c.size>=a;for(;u.length;){let g=[];for(let h=0;h<u.length;h+=lL){if(m()){f=!0;break}let y=u.slice(h,h+lL),v=await Promise.all(y.map(k=>JQ(k,{withFileTypes:!0}).then(b=>({dir:k,entries:b}),b=>(XQ.has(b?.code??"")||(f=!0),{dir:k,entries:[]}))));for(let{dir:k,entries:b}of v)for(let _ of b){if(d>=s){f=!0;break}d+=1;let S=gb.join(k,_.name);l.test(_.name)?c.add(QQ(S)):_.isDirectory()&&!_.isSymbolicLink()&&g.push(S)}}if(f)break;if(u=g,u.length&&m()){f=!0;break}}return{paths:[...c].sort(),scanned:d,truncated:f,durationMs:n()-o}}function QQ(e){return e.split(gb.sep).join("/")}var qQ,YQ,zQ,lL,XQ,yb=p(()=>{"use strict";qQ=25e4,YQ=15e3,zQ=2e3,lL=64,XQ=new Set(["ENOENT","EACCES","EPERM","ENOTDIR"])});import{closeSync as ZQ,existsSync as eZ,fstatSync as tZ,openSync as rZ,readSync as nZ}from"node:fs";function dL(){return{lastSuccessAt:null,lastSuccessKind:null,steps24h:0,failures24h:{}}}function aZ(e,t){let r=dL();for(let n of e){let o;try{o=JSON.parse(n)}catch{continue}let s=typeof o.at=="string"?Date.parse(o.at):Number.NaN;if(!Number.isNaN(s)&&(o.ok===!0&&(!r.lastSuccessAt||s>=Date.parse(r.lastSuccessAt))&&(r.lastSuccessAt=new Date(s).toISOString(),r.lastSuccessKind=o.kind??null),!(t-s>iZ)&&(r.steps24h+=1,o.ok===!1))){let i=typeof o.reason=="string"&&/^[a-z_]{1,40}$/.test(o.reason)?o.reason:"other";r.failures24h[i]=(r.failures24h[i]??0)+1}}return r}function lZ(e){if(!eZ(e))return[];let t=rZ(e,"r");try{let r=tZ(t).size,n=Math.min(r,oZ),o=Buffer.alloc(n);return nZ(t,o,0,n,r-n),o.toString("utf8").split(`
|
|
239
|
+
`).filter(Boolean)}finally{ZQ(t)}}function Ap(e=Lk(),t=Date.now()){let r=uL.get(e);if(r&&t-r.at<sZ)return r.summary;let n;try{n=aZ(lZ(e),t)}catch{n=dL()}return uL.set(e,{at:t,summary:n}),n}var oZ,sZ,iZ,uL,kb=p(()=>{"use strict";tp();oZ=512*1024,sZ=3e4,iZ=1440*60*1e3;uL=new Map});import{appendFileSync as cZ,mkdirSync as uZ}from"node:fs";import{homedir as dZ}from"node:os";import bb from"node:path";function pL(e=dZ()){return bb.join(e,pZ)}function fL(e){let r=(e instanceof Error?e.message:String(e)).split(":")[0].trim();return/^[a-z_]{1,40}$/.test(r)?r:"other"}function mL(e,t=pL()){try{uZ(bb.dirname(t),{recursive:!0}),cZ(t,`${JSON.stringify({kind:"step",...e})}
|
|
240
|
+
`,{encoding:"utf8",mode:384})}catch{}}function gL(e=pL()){return Ap(e)}var pZ,vb=p(()=>{"use strict";kb();pZ=bb.join(".kynver","logs","chat-claude-code-steps.jsonl")});import{spawn as fZ}from"node:child_process";import{mkdirSync as mZ,mkdtempSync as gZ,rmSync as hZ,writeFileSync as Pp}from"node:fs";import{tmpdir as yZ}from"node:os";import ko from"node:path";function EZ(){return{".curlrc":`retry = 5
|
|
177
241
|
retry-connrefused
|
|
178
242
|
retry-delay = 1
|
|
179
243
|
`,".wgetrc":`tries = 5
|
|
180
244
|
retry_connrefused = on
|
|
181
245
|
waitretry = 1
|
|
182
|
-
`}}function
|
|
183
|
-
`)}function
|
|
184
|
-
${n}`:"Continue."}function
|
|
246
|
+
`}}function PZ(){return["# Kynver folder sandbox: wait for Claude Code's in-sandbox proxy bridge (localhost:3128) before the command runs.",'if [ -z "${KYNVER_SANDBOX_BRIDGE_READY:-}" ] && [ "${SANDBOX_RUNTIME:-}" = "1" ]; then',' case "${HTTP_PROXY:-}${http_proxy:-}" in'," *localhost:3128*|*127.0.0.1:3128*)",' case "${BASH_EXECUTION_STRING:-}" in'," *TCP-LISTEN:3128*) ;;"," *)"," __kynver_i=0",` while [ "$__kynver_i" -lt ${AZ} ]; do`," if (exec 3<>/dev/tcp/127.0.0.1/3128) 2>/dev/null; then break; fi"," sleep 0.05 2>/dev/null || break"," __kynver_i=$((__kynver_i + 1))"," done"," unset __kynver_i"," export KYNVER_SANDBOX_BRIDGE_READY=1"," ;;"," esac"," ;;"," esac","fi",""].join(`
|
|
247
|
+
`)}function IZ(e){let t=ko.join(e,"net");mZ(t,{recursive:!0,mode:448});for(let[n,o]of Object.entries(EZ()))Pp(ko.join(t,n),o,{encoding:"utf8",mode:420});let r=ko.join(t,"bridge-wait.sh");return Pp(r,PZ(),{encoding:"utf8",mode:420}),{CURL_HOME:t,WGETRC:ko.join(t,".wgetrc"),BASH_ENV:r}}function wb(e){return e.type!=="stream_event"||!e.event||typeof e.event!="object"||typeof e.parent_tool_use_id=="string"&&e.parent_tool_use_id?null:e.event}function OZ(e){if(!wb(e))return"";let t=e.event;return t.type!=="content_block_delta"||t.delta?.type!=="text_delta"?"":typeof t.delta.text=="string"?t.delta.text:""}function TZ(e){if(!wb(e))return!1;let t=e.event;return t.type==="content_block_start"&&t.content_block?.type==="text"}function NZ(e){if(!wb(e))return"";let t=e.event;return t.type!=="message_delta"?"":typeof t.delta?.stop_reason=="string"?t.delta.stop_reason:""}function DZ(e,t){let r=typeof t=="number"&&Number.isFinite(t)?Math.floor(t):0;if(r<=0)return e;let n=Number(e[yL]);return Number.isFinite(n)&&n>=r?e:{...e,[yL]:String(r)}}function MZ(e){if(e.type!=="result"||!e.usage||typeof e.usage!="object")return null;let t=e.usage,r=n=>typeof n=="number"&&Number.isFinite(n)?n:0;return{input_tokens:r(t.input_tokens),output_tokens:r(t.output_tokens),cache_creation_input_tokens:r(t.cache_creation_input_tokens),cache_read_input_tokens:r(t.cache_read_input_tokens)}}function LZ(e){return typeof e.session_id=="string"&&e.session_id.trim()?e.session_id.trim():null}function BZ(e){let t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?WM(r.content).trim():"";return n?`User:
|
|
248
|
+
${n}`:"Continue."}function UZ(e){return e.streamed.trim()||e.exitCode===0&&!e.resultIsError?!1:WZ.test(e.detail)||e.numTurns===0}function FZ(e,t){let r=e.trim().slice(0,240);return vZ.test(e)?`${bZ}: ${r||"claude is not signed in"}`:t===null?r?`claude_code_failed: ${r}`:"claude_code_failed: process exited without a code":r?`claude_code_failed: exit ${t} \u2014 ${r}`:`claude_code_failed: exit ${t}`}async function KZ(e){try{return{port:(await V0(e)).port}}catch(t){return{reason:t?.message??String(t)}}}async function $Z(e){if(e.access.access!=="folder"&&e.access.access!=="folders")return null;let t=e.sandboxRuntime??xk(),r=Ck(),n=t.available&&!r,o=n?await KZ(e.egressProxy):null,s=n?await cL(e.access.folders,js):null;return s?.truncated&&console.error(JSON.stringify({event:"chat_folder_sensitive_scan_truncated",scanned:s.scanned,found:s.paths.length,durationMs:s.durationMs})),tD({access:e.access,policy:_k(e.env,e.config),runtime:t,domains:z0(e.env,e.config),startupFailure:r,egress:o,sensitiveFiles:s?.paths??[],sensitiveScanComplete:s?!s.truncated:!1})}async function Ip(e){let t=Date.now(),r=!1,n=null,o=null,s=(i,a)=>(e.onStepLogged??mL)({at:new Date().toISOString(),turnId:e.turnId??"",resumed:r,appVersion:n,durationMs:Date.now()-t,ok:i,...i?{}:{reason:fL(a)}});try{let i=await HZ(e,{markResumed:a=>{r=a},onAppVersion:a=>{n=a},onPartialFailure:a=>{o=a}});return o?s(!1,new Error(o)):s(!0),i}catch(i){throw s(!1,i),i}}async function HZ(e,t){let{markResumed:r,onAppVersion:n}=t,o=R=>{if(R.error)throw R.error;return R.failure&&t.onPartialFailure(R.failure),R.message},s=e.env??process.env,i=e.sessions??oL,a=nL(e.step);if(a<=0)throw new Error("claude_code_no_time_left");let l=Xt(e.payload.tools),c=ib(e.payload,"agent",l,e.access),u=e.spawnTarget?.executable??(s.KYNVER_CLAUDE_BIN?.trim()||s.CLAUDE_BIN?.trim()||"claude"),d=gZ(ko.join(e.tempRoot??yZ(),"kynver-claude-code-")),f=ko.join(d,"kynver-system-prompt.md"),m=ko.join(d,"kynver-claude-code-settings.json"),g=Date.now(),h=new Set(l.map(R=>R.name)),y=()=>$Z({access:e.access,env:s,config:e.config,sandboxRuntime:e.sandboxRuntime,egressProxy:e.egressProxy}),v=await y();v?.network==="domain-list"&&console.error(JSON.stringify({event:"claude_code_sandbox_egress_unavailable",turnId:e.turnId??null,reason:v.networkReason??null}));let k={},b=()=>{Pp(f,v?`${c.head}
|
|
185
249
|
|
|
186
|
-
${v.note}`:c.head,{encoding:"utf8",mode:384}),v&&
|
|
250
|
+
${v.note}`:c.head,{encoding:"utf8",mode:384}),v&&Pp(m,JSON.stringify(v.settings,null,2),{encoding:"utf8",mode:384}),k=v?.shell==="sandboxed"?IZ(d):{}},_=()=>v?{settingsFile:m,shell:v.shell}:void 0,S=async()=>{let R=i.get(e.step.session);if(R){let L=a-(Date.now()-g);if(L<=0)throw new Error("claude_code_no_time_left");r(!0);let N=await kL({...e,env:s,extraEnv:k,executable:u,sessions:i,limitMs:L,advertisedNames:h,maxTokens:e.payload.maxTokens,args:mb({model:e.model,systemPromptFile:f,access:e.access,prompt:BZ(e.payload),resumeSessionId:R,sandbox:_()}),resumed:!0,sandboxed:v?.shell==="sandboxed",onAppVersion:n});if(!N.resumeRefused)return N;i.forget(e.step.session),r(!1)}let w=a-(Date.now()-g);if(w<=0)throw new Error("claude_code_no_time_left");return kL({...e,env:s,extraEnv:k,executable:u,sessions:i,limitMs:w,advertisedNames:h,maxTokens:e.payload.maxTokens,args:mb({model:e.model,systemPromptFile:f,access:e.access,prompt:c.body||"Continue.",sandbox:_()}),resumed:!1,sandboxed:v?.shell==="sandboxed",onAppVersion:n})};try{b();let R=await S();return R.sandboxUnavailable&&v&&(Z0(R.sandboxUnavailable),v=await y(),console.error(JSON.stringify({event:"claude_code_sandbox_unavailable",turnId:e.turnId??null,reason:R.sandboxUnavailable,shell:v?.shell??null})),b(),R=await S(),R.sandboxUnavailable&&(R={error:new Error(`claude_code_sandbox_unavailable: ${R.sandboxUnavailable}`)})),(R.failure?.startsWith(Rb)||R.error?.message.startsWith(Rb))&&a-(Date.now()-g)>CZ&&(console.error(JSON.stringify({event:"claude_code_sandbox_proxy_down_retry",turnId:e.turnId??null})),R=await S()),o(R)}finally{hZ(d,{recursive:!0,force:!0})}}function kL(e){let t=HM();return new Promise(r=>{let n;try{let[E,V]=ae(e.executable,[...e.spawnTarget?.prefixArgs??[],...e.args]),x=z({cwd:e.access.workDir,detached:process.platform!=="win32",shell:!1,stdio:["ignore","pipe","pipe"],env:{...DZ(nD(e.env,e.access.access),e.maxTokens),...e.extraEnv,NO_COLOR:"1"}});n=fZ(E,V,x)}catch(E){r({error:bL(E,e.executable)});return}let o=!1,s=new zt,i="",a="",l="",c=!1,u=null,d="",f={input_tokens:0,output_tokens:0},m=null,g="",h="",y=!1,v="",k=!1,b=0,_=!1,S=E=>{let V=s.push(E);V&&(i+=V,e.onDelta(V))},R=(E,V)=>console.error(JSON.stringify({event:E,requestId:e.requestId??null,turnId:e.turnId??null,resumed:e.resumed,access:e.access.access,appVersion:m,...V})),w=E=>{o||(o=!0,clearTimeout(G),A&&k&&clearTimeout(A),e.signal?.removeEventListener("abort",D),r(E))},L=(E="")=>{let V=s.end();V&&(i+=V,e.onDelta(V));let x=pb(a,c?"":l),T=un(x,e.advertisedNames);fb(T.text,i,e.onDelta),E&&e.onDelta(E),T.rejected.length>0&&R("claude_code_tool_call_rejected",{names:T.rejected.slice(0,5)});let U=dn(T,e.turnId??"turn",E),te=U.stop_reason==="end_turn"&&d==="max_tokens";return(T.cut||te)&&R("claude_code_reply_cut",{stopReason:d||null,cutTool:T.cut?.name??null,chars:x.length}),{content:U.content,stop_reason:te?"max_tokens":U.stop_reason,usage:f}},N=E=>{n.pid?fe(n.pid,E):Ze(n,E)},A,O=()=>{N("SIGTERM"),A??=setTimeout(()=>{k||(N("SIGKILL"),setTimeout(()=>{o||H(null)},hL).unref())},hL),A.unref()},W=()=>{if(e.onActivity)for(let E of t.interrupted())e.onActivity(E)},D=()=>{O(),W(),w({error:new Error("claude_code_chat_aborted")})},G=setTimeout(()=>{y=!0,O()},e.limitMs);if(n.on("error",E=>w({error:bL(E,e.executable)})),e.signal){if(e.signal.aborted){D();return}e.signal.addEventListener("abort",D)}let Q=E=>{let V=E.trim();if(!V)return;let x;try{x=JSON.parse(V)}catch{return}let T=LZ(x);T&&e.sessions.remember(e.step.session,T),x.type==="system"&&typeof x.claude_code_version=="string"&&(m=x.claude_code_version,e.onAppVersion(m)),TZ(x)&&a&&!a.endsWith(`
|
|
187
251
|
`)&&(a+=`
|
|
188
252
|
|
|
189
253
|
`,S(`
|
|
190
254
|
|
|
191
|
-
`));let
|
|
192
|
-
`).slice(0,1e3)),
|
|
193
|
-
`))!==-1;){let
|
|
255
|
+
`));let U=OZ(x);U&&(a+=U,S(U));let te=NZ(x);if(te&&(d=te),x.type==="result"&&(typeof x.result=="string"&&(l=x.result),c=x.is_error===!0,typeof x.num_turns=="number"&&(u=x.num_turns),Array.isArray(x.errors)&&(v=x.errors.filter(oe=>typeof oe=="string").join(`
|
|
256
|
+
`).slice(0,1e3)),f=MZ(x)??f),e.onActivity)for(let oe of t(x))e.onActivity(oe);e.sandboxed&&!_&&x.type==="user"&&jZ(x)&&(b+=1,R("claude_code_sandbox_proxy_down",{hits:b}),b>=xZ&&(_=!0,O()))};n.stdout?.on("data",E=>{h+=typeof E=="string"?E:E.toString("utf8");let V;for(;(V=h.indexOf(`
|
|
257
|
+
`))!==-1;){let x=h.slice(0,V);h=h.slice(V+1),Q(x)}}),n.stderr?.on("data",E=>{g+=typeof E=="string"?E:E.toString("utf8"),g.length>8e3&&(g=g.slice(-8e3))});let H=E=>{if(k=!0,o)return;if(h.trim()&&Q(h),h="",W(),_){let U=`${Rb}: ${SZ}`;w(a.trim()?{message:L(_Z),failure:U}:{error:new Error(U)});return}if(y){R("claude_code_step_timeout",{limitMs:e.limitMs}),w(a.trim()?{message:L(wZ),failure:"claude_code_step_timeout"}:{error:new Error("claude_code_step_timeout")});return}let V=`${l}
|
|
194
258
|
${v}
|
|
195
|
-
${g}`,
|
|
196
|
-
`):"";if(
|
|
259
|
+
${g}`,x=E!==0||c;if(e.sandboxed&&eD({exitCode:E,streamed:a,numTurns:u,detail:V})){w({sandboxUnavailable:V.trim().slice(0,240)||"sandbox failed to start"});return}if(e.resumed&&UZ({exitCode:E,resultIsError:c,numTurns:u,streamed:a,detail:V})){R("claude_code_resume_refused",{exitCode:E}),w({resumeRefused:!0});return}if(x){let U=FZ(V,E);R("claude_code_turn_error",{exitCode:E,error:U,partial:!!a.trim()}),w(a.trim()?{message:L(RZ),failure:U}:{error:new Error(U)});return}let T=L();R("claude_code_turn_end",{exitCode:E,stopReason:T.stop_reason}),w({message:T})};n.on("close",H)})}function jZ(e){let t=e.message,r=Array.isArray(t?.content)?t.content:[];for(let n of r){if(!n||n.type!=="tool_result")continue;let o=typeof n.content=="string"?n.content:Array.isArray(n.content)?n.content.map(s=>typeof s?.text=="string"?s.text:"").join(`
|
|
260
|
+
`):"";if(X0(o))return!0}return!1}function bL(e,t){return e?.code==="ENOENT"?new Error(`${kZ}: failed to spawn \`${t}\`. Install Claude Code and keep \`claude\` on PATH.`):e instanceof Error?e:new Error(String(e))}var kZ,bZ,vZ,RZ,hL,wZ,Rb,SZ,_Z,xZ,CZ,AZ,yL,WZ,Sb=p(()=>{"use strict";M();qe();ml();Ep();sL();aL();lo();Yd();yb();wk();vb();fl();xp();Xs();kZ="claude_code_unavailable",bZ="claude_code_not_logged_in",vZ=/not logged in|please run \/login|invalid api key|authentication|unauthorized|401\b/i,RZ=`
|
|
197
261
|
|
|
198
|
-
(Stopped: Claude Code ended this step with an error before finishing.)`,
|
|
262
|
+
(Stopped: Claude Code ended this step with an error before finishing.)`,hL=5e3,wZ=`
|
|
199
263
|
|
|
200
|
-
(Stopped: this step reached its time limit. Longer work should run as a detached job in the folder \u2014 start_long_job \u2014 with its output written to a file there.)`,
|
|
264
|
+
(Stopped: this step reached its time limit. Longer work should run as a detached job in the folder \u2014 start_long_job \u2014 with its output written to a file there.)`,Rb="claude_code_sandbox_proxy_down",SZ=`sandbox network proxy not running (localhost:${ao} refused inside the folder sandbox)`,_Z=`
|
|
201
265
|
|
|
202
|
-
(Stopped: the folder sandbox's network proxy is not running on this computer, so shell downloads could not leave the sandbox. No website was blocked \u2014 the sandbox's own proxy bridge did not answer. Restart the Kynver daemon on that computer, or choose full computer access in Computers settings.)`,
|
|
266
|
+
(Stopped: the folder sandbox's network proxy is not running on this computer, so shell downloads could not leave the sandbox. No website was blocked \u2014 the sandbox's own proxy bridge did not answer. Restart the Kynver daemon on that computer, or choose full computer access in Computers settings.)`,xZ=2,CZ=3e4;AZ=60;yL="CLAUDE_CODE_MAX_OUTPUT_TOKENS";WZ=/no conversation found|session .*not found/i});function vL(e){if(e)return e;let t=P();return{chatProvider:t.chatProvider,workerProvider:t.workerProvider}}function _b(e,t,r=process.env,n){if(e==="cursor"){let o=yu(r);if(!o.ok)throw new Zt(DC(o));return}if(e==="codex"){let o=fp(r);if(!o.ok)throw new Zt(cM(o));return}if(e==="gemini"){let o=r;if(co(vL(n),o)==="antigravity"){let s=yp(o);if(!s.ok)throw new Zt(fM(s));return}if(!ll(r))throw new Zt("gemini_api_key_missing");return}if(e==="openai"){if(!cl(r))throw new Zt("openai_api_key_missing");return}if(!il(r,{oauthOptIn:t}))throw new Zt("no_local_credentials")}async function RL(e){let t=e.env??process.env,{provider:r,model:n,payload:o,onDelta:s,signal:i}=e;_b(r,e.useClaudeOauth,t,e.config);let a=e.config??P(),l=yo({provider:r,config:a,payloadAccess:o.computerAccess,boxId:e.boxId,env:t}),c=e.onActivity,u={access:l.access,...c?{onActivity:m=>c(m,l)}:{}};if(r==="cursor")return qM({payload:o,model:n,onDelta:s,signal:i,turnId:e.turnId,requestId:e.requestId,...u});if(r==="codex")return YM({payload:o,model:n,onDelta:s,signal:i,turnId:e.turnId,...u});if(r==="gemini"&&co(vL(e.config),t)==="antigravity")return QM({payload:o,model:n,onDelta:s,signal:i,turnId:e.turnId,env:t,...u});if(r==="gemini"||r==="openai"){let m=r==="gemini"?ll(t):cl(t);return eL({creds:m,model:n,payload:o,onDelta:s,signal:i})}let d=rL(o.claudeCode);if(d&&l.engine==="claude-code"&&l.access.access!=="off")return Ip({payload:o,model:n,onDelta:s,signal:i,step:d,turnId:e.turnId,requestId:e.requestId,env:t,config:a,...u});let f=il(t,{oauthOptIn:e.useClaudeOauth});return xM({creds:f,model:n,payload:o,onDelta:s,signal:i})}var Zt,xb=p(()=>{"use strict";Yk();nb();ks();xp();mp();zM();kp();ZM();Xd();Xk();tL();$();Cp();Ep();Sb();Zt=class extends Error{constructor(r){super(r);this.code=r;this.name="ChatCredentialError"}code}});function VZ(e,t){let r=[...e.content],n=r.findIndex(o=>!!o&&typeof o=="object"&&o.type==="text");if(n>=0){let o=r[n];r[n]={...o,text:`${t}${o.text}`}}else r.unshift({type:"text",text:t.trimEnd()});return{...e,content:r}}async function wL(e){let t=dl(e.payload.requestedModel),r=typeof e.payload.fallbackNoticeShown=="string"?e.payload.fallbackNoticeShown:null,{requestedModel:n,fallbackNoticeShown:o,...s}=e.payload,i=gM({requested:t,catalog:e.catalog,primary:e.primary}),a=t??{provider:i.provider,model:i.model},l={provider:i.provider,model:i.model},c=[],u=!1,d=null,f=null,m=()=>{let g=i.fallbackReason==="usage_limit"?l:t,h=kM(i,g),y=bM(i,g);!h||!y||h===r||d||(d=`${y}
|
|
203
267
|
|
|
204
|
-
`,
|
|
268
|
+
`,f=h,e.onDelta(d))};for(;;){c.push(i.provider);try{m();let g=await e.runTurn({provider:i.provider,model:i.model,payload:s,onDelta:y=>{y&&(u=!0),e.onDelta(y)}});return{...d?VZ(g,d):g,kynverModel:{provider:i.provider,model:i.model,requested:i.fallbackReason?a:null,fallbackReason:i.fallbackReason,noticeKey:f}}}catch(g){let y=!u&&(yM(g)||g instanceof Zt&&c.length>1)?hM(e.catalog,c):null;if(!y)throw g;console.error(JSON.stringify({event:"chat_turn_provider_fallback",from:`${i.provider}:${i.model}`,to:`${y.provider}:${y.model}`,reason:"usage_limit"})),i={...y,requested:t,fallbackReason:"usage_limit"}}}}var SL=p(()=>{"use strict";tb();xb()});function Cb(e){let t=(e??"").replace(/\s+/g," ").trim();if(!t||t.length>120)return null;for(let r of GZ)if(r.re.test(t))return r.kind;return null}function xL(e){let t=e.tag.toLowerCase(),r=(e.type??"").toLowerCase(),n=(e.role??"").toLowerCase();return t==="button"||t==="a"||n==="button"||n==="link"||n==="menuitem"||t==="input"&&(r==="submit"||r==="button"||r==="image")}function Op(e){return xL(e)?Cb(e.name):null}function CL(e){return e.tag.toLowerCase()==="textarea"?null:xL(e)?Cb(e.name):Cb(e.formSubmitLabel)}function Tp(e){if((e.type??"").toLowerCase()==="password"||JZ.test(e.autocomplete??""))return!0;let t=e.tag.toLowerCase();return t!=="input"&&t!=="textarea"?!1:_L.test(e.inputName??"")||_L.test(e.name??"")}function Eb(e){if(typeof e!="string"||!e.trim())return{ok:!1,reason:"url is required"};let t=e.trim();/^[a-z][a-z0-9+.-]*:/i.test(t)||(t=`https://${t}`);let r;try{r=new URL(t)}catch{return{ok:!1,reason:"not a valid URL"}}return r.protocol!=="http:"&&r.protocol!=="https:"?{ok:!1,reason:`only http(s) pages can be opened (got ${r.protocol})`}:r.username||r.password?{ok:!1,reason:"URLs carrying a username or password are refused"}:qZ.test(r.hostname)?{ok:!1,reason:"local and private-network addresses are refused"}:{ok:!0,url:r.toString()}}function EL(e){let t=e.map(n=>(n??"").trim()).join("|"),r=2166136261;for(let n=0;n<t.length;n+=1)r^=t.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}function AL(e){if(!e)return"";try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return""}}var GZ,JZ,_L,qZ,Ab=p(()=>{"use strict";GZ=[{kind:"purchase",re:/\b(buy|purchase|place\s+(your\s+)?order|complete\s+(your\s+)?(order|purchase)|check\s*out|pay(\s+now)?|confirm\s+(and\s+)?pay|submit\s+(order|payment)|subscribe|donate|book\s+now|rent\s+now|add\s+funds|transfer|withdraw)\b/i},{kind:"send",re:/\b(send|post|publish|tweet|reply|share\s+now|submit\s+(message|comment|review|application))\b/i},{kind:"delete",re:/\b(delete|remove\s+(account|permanently)|erase|destroy|cancel\s+(my\s+)?(account|subscription|order)|close\s+account|unsubscribe\s+all)\b/i}];JZ=/\b(current-password|new-password|one-time-code|cc-number|cc-csc|cc-exp|cc-exp-month|cc-exp-year)\b/i,_L=/(passw|passcode|pwd|\bpin\b|otp|one[-_ ]?time|2fa|mfa|verification[-_ ]?code|security[-_ ]?code|cvv|cvc|card[-_ ]?number|ccnum|ssn|social[-_ ]?security)/i;qZ=/^(localhost|.*\.localhost|.*\.local|.*\.internal|0\.0\.0\.0|\[?::1?\]?|127(\.\d{1,3}){3}|10(\.\d{1,3}){3}|192\.168(\.\d{1,3}){2}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}|169\.254(\.\d{1,3}){2}|\[?f[cd][0-9a-f]{2}:.*|\[?fe80:.*)$/i});function PL(e){return zZ.includes(e)}function IL(e){return typeof e=="string"&&YZ.includes(e)}var YZ,zZ,OL,TL,Pb,NL,Ib,DL,ML,Np,LL,BL,WL,Ob,ri=p(()=>{"use strict";YZ=["open","snapshot","click","type","select","press","scroll","screenshot","wait","tabs","close","list_logins","fill_login","save_login","request_code"],zZ=["list_logins","fill_login","save_login","request_code"];OL=12e3,TL=200,Pb=16e3,NL=95e4,Ib=4e3,DL=3e4,ML=25e3,Np=3e4,LL=10*6e4,BL=5*6e4,WL=120,Ob=8});function XZ(e){let t=e.role?.toLowerCase();if(t)return t;if(e.tag==="a")return"link";if(e.tag==="select")return"dropdown";if(e.tag==="textarea")return"textbox";if(e.tag==="input"){let r=e.type??"text";return r==="submit"||r==="button"||r==="image"?"button":r==="checkbox"||r==="radio"?r:r==="password"?"password":r==="text"?"textbox":`${r} field`}return e.tag}function QZ(e){let t=Tp(e),r=[`[${e.ref}] ${XZ(e)}`];return e.name&&r.push(JSON.stringify(e.name)),!t&&e.value&&r.push(`value=${JSON.stringify(e.value)}`),e.checked!==null&&r.push(e.checked?"(checked)":"(unchecked)"),e.disabled&&r.push("(disabled)"),t?r.push("(secret field \u2014 the user must type this themselves)"):Op(e)&&r.push("(needs the user's approval to press)"),r.join(" ")}function UL(e,t={}){let r=t.maxChars??Pb,n=`Page: ${e.title||"(untitled)"} \u2014 ${e.url}`,o=e.elements.map(QZ),s=o.length?`Interactive elements (use the [ref] with browser_click / browser_type / browser_select):
|
|
205
269
|
${o.join(`
|
|
206
270
|
`)}${e.truncatedElements?`
|
|
207
271
|
\u2026more elements not shown \u2014 scroll or wait, then snapshot again`:""}`:"Interactive elements: none visible.",i=`${n}
|
|
@@ -210,30 +274,30 @@ ${s}
|
|
|
210
274
|
|
|
211
275
|
Page text:
|
|
212
276
|
`,a=Math.max(0,r-i.length),l=e.text.length>a?`${e.text.slice(0,Math.max(0,a-14))}
|
|
213
|
-
\u2026[truncated]`:e.text;return`${i}${l}`.slice(0,r)}function
|
|
214
|
-
\u2026[truncated]`:e}var
|
|
277
|
+
\u2026[truncated]`:e.text;return`${i}${l}`.slice(0,r)}function Dp(e,t=Pb){return e.length>t?`${e.slice(0,t-14)}
|
|
278
|
+
\u2026[truncated]`:e}var Tb=p(()=>{"use strict";Ab();ri()});function FL(){return`(() => {${Nb}
|
|
215
279
|
const root = document.documentElement;
|
|
216
280
|
let seq = Number(root.getAttribute("data-kynver-ref-seq") || "0");
|
|
217
281
|
const elements = [];
|
|
218
282
|
let truncatedElements = false;
|
|
219
|
-
for (const el of document.querySelectorAll(${JSON.stringify(
|
|
283
|
+
for (const el of document.querySelectorAll(${JSON.stringify(ZZ)})) {
|
|
220
284
|
if (!__kvVisible(el)) continue;
|
|
221
|
-
if (elements.length >= ${
|
|
285
|
+
if (elements.length >= ${TL}) { truncatedElements = true; break; }
|
|
222
286
|
let ref = el.getAttribute("data-kynver-ref");
|
|
223
287
|
if (!ref) { seq += 1; ref = "e" + seq; el.setAttribute("data-kynver-ref", ref); }
|
|
224
288
|
elements.push(__kvFacts(el, ref));
|
|
225
289
|
}
|
|
226
290
|
root.setAttribute("data-kynver-ref-seq", String(seq));
|
|
227
291
|
const body = document.body;
|
|
228
|
-
const text = body ? String(body.innerText || "").replace(/\\n{3,}/g, "\\n\\n").slice(0, ${
|
|
292
|
+
const text = body ? String(body.innerText || "").replace(/\\n{3,}/g, "\\n\\n").slice(0, ${OL}) : "";
|
|
229
293
|
return { url: location.href, title: document.title, text, elements, truncatedElements };
|
|
230
|
-
})()`}function
|
|
294
|
+
})()`}function KL(e){return`(() => {${Nb}
|
|
231
295
|
const el = document.querySelector('[data-kynver-ref="' + ${JSON.stringify(e)}.replace(/[^a-z0-9]/gi, "") + '"]');
|
|
232
296
|
if (!el) return null;
|
|
233
297
|
el.scrollIntoView({ block: "center", inline: "center" });
|
|
234
298
|
const r = el.getBoundingClientRect();
|
|
235
299
|
return { x: r.left + r.width / 2, y: r.top + r.height / 2, facts: __kvFacts(el, ${JSON.stringify(e)}), url: location.href };
|
|
236
|
-
})()`}function
|
|
300
|
+
})()`}function $L(e,t){return`(() => {
|
|
237
301
|
const el = document.querySelector('[data-kynver-ref="' + ${JSON.stringify(e)}.replace(/[^a-z0-9]/gi, "") + '"]');
|
|
238
302
|
if (!el) return false;
|
|
239
303
|
el.focus();
|
|
@@ -248,7 +312,7 @@ Page text:
|
|
|
248
312
|
}
|
|
249
313
|
}
|
|
250
314
|
return true;
|
|
251
|
-
})()`}function
|
|
315
|
+
})()`}function HL(e,t){return`(() => {
|
|
252
316
|
const el = document.querySelector('[data-kynver-ref="' + ${JSON.stringify(e)}.replace(/[^a-z0-9]/gi, "") + '"]');
|
|
253
317
|
if (!el || el.tagName !== "SELECT") return { ok: false, reason: "not_select" };
|
|
254
318
|
const want = ${JSON.stringify(t)}.trim().toLowerCase();
|
|
@@ -260,17 +324,17 @@ Page text:
|
|
|
260
324
|
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
261
325
|
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
262
326
|
return { ok: true, label: (hit.label || hit.textContent || "").trim() };
|
|
263
|
-
})()`}function
|
|
327
|
+
})()`}function jL(){return`(() => {${Nb}
|
|
264
328
|
const el = document.activeElement;
|
|
265
329
|
if (!el || el === document.body) return { facts: null, url: location.href };
|
|
266
330
|
return { facts: __kvFacts(el, el.getAttribute("data-kynver-ref") || ""), url: location.href };
|
|
267
|
-
})()`}function
|
|
331
|
+
})()`}function VL(e){return`(() => { window.scrollBy(0, ${Math.trunc(e)}); return { y: Math.round(window.scrollY), max: Math.round(document.documentElement.scrollHeight - window.innerHeight) }; })()`}function GL(e,t){return`(() => {
|
|
268
332
|
const t = ${JSON.stringify(e)};
|
|
269
333
|
const s = ${JSON.stringify(t)};
|
|
270
334
|
if (t && document.body && String(document.body.innerText || "").toLowerCase().includes(t.toLowerCase())) return true;
|
|
271
335
|
if (s) { try { if (document.querySelector(s)) return true; } catch (e) { return "bad_selector"; } }
|
|
272
336
|
return false;
|
|
273
|
-
})()`}var
|
|
337
|
+
})()`}var Nb,ZZ,JL=p(()=>{"use strict";ri();Nb=String.raw`
|
|
274
338
|
const __kvText = (s, n) => String(s == null ? "" : s).replace(/\s+/g, " ").trim().slice(0, n);
|
|
275
339
|
const __kvName = (el) => {
|
|
276
340
|
const aria = el.getAttribute("aria-label");
|
|
@@ -333,11 +397,11 @@ const __kvVisible = (el) => {
|
|
|
333
397
|
const s = getComputedStyle(el);
|
|
334
398
|
return s.visibility !== "hidden" && s.display !== "none" && s.opacity !== "0";
|
|
335
399
|
};
|
|
336
|
-
`,
|
|
400
|
+
`,ZZ='a[href],button,input:not([type="hidden"]),select,textarea,summary,[role="button"],[role="link"],[role="checkbox"],[role="radio"],[role="tab"],[role="menuitem"],[role="option"],[role="combobox"],[role="textbox"],[role="switch"],[contenteditable="true"],[contenteditable=""]'});async function vo(e,t,r,n=15e3){let o=await e.send("Runtime.evaluate",{expression:r,returnByValue:!0,awaitPromise:!0},{sessionId:t.sessionId,timeoutMs:n});if(o.exceptionDetails)throw new Error(`page script failed: ${o.exceptionDetails.text??"error"}`);return o.result?.value}async function eee(e,t){return vo(e.session.host.conn,t,FL())}async function er(e,t,r){let n=await eee(e,t),o=UL(n);return{ok:!0,text:r?Dp(`${r}
|
|
337
401
|
|
|
338
|
-
${o}`):o,url:n.url,title:n.title}}function
|
|
402
|
+
${o}`):o,url:n.url,title:n.title}}function Mp(e){let t=typeof e.ref=="string"?e.ref.trim():"";return/^e\d{1,6}$/.test(t)?t:null}function XL(e,t,r,n,o){let s=EL([AL(o),t,r.toLowerCase(),n]);if(e.approvedFingerprint&&e.approvedFingerprint===s)return null;let i=(()=>{try{return new URL(o).host}catch{return o}})(),a=`${t==="press"?"Submit":"Press"} "${r||"this control"}" on ${i} (${n==="purchase"?"spends money":n==="send"?"sends or posts something":"deletes or cancels something"})`;return{ok:!1,code:"approval_required",text:`This step needs the user's approval first: ${a}.`,approval:{summary:a,fingerprint:s}}}async function gl(e,t,r){let n=e.session.host.conn;await Promise.race([n.waitFor(o=>o.method==="Page.loadEventFired"&&o.sessionId===t.sessionId,r).catch(()=>{}),(e.sleep??YL)(r)])}async function QL(e){let t=Eb(e.args.url);if(!t.ok)return{ok:!1,code:"url_refused",text:`Can't open that address: ${t.reason}.`};let n=e.args.newTab===!0?await e.manager.newTab(e.session,"about:blank"):await e.manager.activeTab(e.session),o=e.session.host.conn,s=o.waitFor(l=>l.method==="Page.loadEventFired"&&l.sessionId===n.sessionId,ML).then(()=>!0,()=>!1),i=await o.send("Page.navigate",{url:t.url},{sessionId:n.sessionId});if(i.errorText)return{ok:!1,code:"failed",text:`The page did not load: ${i.errorText}.`};let a=await s;return er(e,n,a?void 0:"The page is still loading; this is what has rendered so far.")}async function Db(e,t,r){return vo(e.session.host.conn,t,KL(r))}async function tee(e){let t=Mp(e.args);if(!t)return bo(t);let r=await e.manager.activeTab(e.session),n=await Db(e,r,t);if(!n)return bo(t);if(n.facts.disabled)return{ok:!1,code:"failed",text:`[${t}] is disabled.`};let o=Op(n.facts);if(o){let a=XL(e,"click",n.facts.name,o,n.url);if(a)return a}let s=e.session.host.conn,i={x:n.x,y:n.y,button:"left",clickCount:1};return await s.send("Input.dispatchMouseEvent",{type:"mouseMoved",x:n.x,y:n.y},{sessionId:r.sessionId}),await s.send("Input.dispatchMouseEvent",{type:"mousePressed",...i},{sessionId:r.sessionId}),await s.send("Input.dispatchMouseEvent",{type:"mouseReleased",...i},{sessionId:r.sessionId}),await gl(e,r,1200),er(e,r,`Clicked [${t}] ${JSON.stringify(n.facts.name)}.`)}async function Lp(e,t,r){let n=zL[r],o=e.session.host.conn,s={key:r==="Space"?" ":r,code:n.code,windowsVirtualKeyCode:n.vk,nativeVirtualKeyCode:n.vk};await o.send("Input.dispatchKeyEvent",{type:"keyDown",...s,...n.text?{text:n.text}:{}},{sessionId:t.sessionId}),await o.send("Input.dispatchKeyEvent",{type:"keyUp",...s},{sessionId:t.sessionId})}async function Bp(e,t){let r=await vo(e.session.host.conn,t,jL());if(!r.facts)return null;let n=CL(r.facts);if(!n)return null;let o=r.facts.formSubmitLabel??r.facts.name;return XL(e,"press",o,n,r.url)}async function ree(e){let t=Mp(e.args);if(!t)return bo(t);let r=typeof e.args.text=="string"?e.args.text:"";if(!r)return{ok:!1,code:"invalid_request",text:"text is required."};if(r.length>Ib)return{ok:!1,code:"invalid_request",text:`text is limited to ${Ib} characters.`};let n=await e.manager.activeTab(e.session),o=await Db(e,n,t);if(!o)return bo(t);if(Tp(o.facts))return{ok:!1,code:"user_input_required",text:`[${t}] ${JSON.stringify(o.facts.name)} is a password or security-code field. Kynver never types secrets you supply. If this site has a saved login, use browser_fill_login with its handle (browser_list_logins); for a texted or emailed code use browser_request_code. Otherwise ask the user to type it themselves in the Kynver browser window on their computer, then continue when they say it's done (browser_snapshot to see the page). Never ask them to paste it into chat.`};let s=e.session.host.conn;if(!await vo(s,n,$L(t,e.args.clear!==!1)))return bo(t);await s.send("Input.insertText",{text:r},{sessionId:n.sessionId});let a=`Typed ${r.length} character${r.length===1?"":"s"} into [${t}] ${JSON.stringify(o.facts.name)}.`;if(e.args.submit===!0){let l=await Bp(e,n);return l?{...l,text:`${a} ${l.text}`}:(await Lp(e,n,"Enter"),await gl(e,n,1500),er(e,n,`${a} Pressed Enter.`))}return{ok:!0,text:a}}async function nee(e){let t=Mp(e.args);if(!t)return bo(t);let r=typeof e.args.option=="string"?e.args.option.trim():"";if(!r)return{ok:!1,code:"invalid_request",text:"option (visible label or value) is required."};let n=await e.manager.activeTab(e.session),o=await vo(e.session.host.conn,n,HL(t,r));return o.ok?{ok:!0,text:`Selected ${JSON.stringify(o.label)} in [${t}].`}:o.reason==="no_option"?{ok:!1,code:"not_found",text:`No option matching ${JSON.stringify(r)}. Options: ${(o.options??[]).join(" | ")}`}:{ok:!1,code:"invalid_request",text:`[${t}] is not a dropdown \u2014 click it and pick from the list instead.`}}async function oee(e){let t=typeof e.args.key=="string"?e.args.key.trim():"",r=qL.find(o=>o.toLowerCase()===t.toLowerCase());if(!r)return{ok:!1,code:"invalid_request",text:`key must be one of: ${qL.join(", ")}.`};let n=await e.manager.activeTab(e.session);if(r==="Enter"){let o=await Bp(e,n);if(o)return o}return await Lp(e,n,r),await gl(e,n,r==="Enter"?1500:300),er(e,n,`Pressed ${r}.`)}async function see(e){let t=await e.manager.activeTab(e.session),r=Mp(e.args);if(r)return await Db(e,t,r)?{ok:!0,text:`Scrolled [${r}] into view.`}:bo(r);let n=e.args.direction==="up"?-1:1,o=Math.min(10,Math.max(1,Number(e.args.pages)||1)),s=await vo(e.session.host.conn,t,VL(n*o*700));return{ok:!0,text:`Scrolled ${n<0?"up":"down"}; now at ${s.y}px of ${Math.max(0,s.max)}px.`}}async function iee(e){let t=await e.manager.activeTab(e.session),r=e.session.host.conn;for(let n of[60,35,20]){let o=await r.send("Page.captureScreenshot",{format:"jpeg",quality:n,captureBeyondViewport:!1},{sessionId:t.sessionId}),s=typeof o.data=="string"?o.data:"";if(s&&s.length<=NL)return{ok:!0,text:"Screenshot of the visible part of the page.",imageBase64:s,imageMediaType:"image/jpeg"}}return{ok:!1,code:"failed",text:"The screenshot was too large to return; use browser_snapshot instead."}}async function aee(e){let t=await e.manager.activeTab(e.session),r=e.sleep??YL,n=typeof e.args.text=="string"&&e.args.text.trim()?e.args.text.trim().slice(0,200):null,o=typeof e.args.selector=="string"&&e.args.selector.trim()?e.args.selector.trim().slice(0,300):null,s=Math.min(Np,Math.max(0,Number(e.args.ms)||0));if(!n&&!o){let l=s||2e3;return await r(l),er(e,t,`Waited ${Math.round(l/100)/10}s.`)}let i=s||1e4,a=Date.now();for(;;){let l=await vo(e.session.host.conn,t,GL(n,o));if(l==="bad_selector")return{ok:!1,code:"invalid_request",text:"That CSS selector is not valid."};if(l===!0)return er(e,t,"Found it.");if(Date.now()-a>=i)return{ok:!1,code:"timeout",text:`Not found after ${Math.round(i/1e3)}s.`};await r(500)}}async function lee(e){let t=typeof e.args.op=="string"?e.args.op:"list",{session:r,manager:n}=e,o=r.host.conn,s=Number(e.args.tab),i=Number.isInteger(s)&&s>=1?r.tabs[s-1]:void 0;if(t==="new"){if(e.args.url!==void 0){let d=Eb(e.args.url);return d.ok?QL({...e,args:{url:d.url,newTab:!0}}):{ok:!1,code:"url_refused",text:`Can't open that address: ${d.reason}.`}}return await n.newTab(r,"about:blank"),{ok:!0,text:`Opened tab ${r.tabs.length}.`}}if(t==="switch"||t==="close")return i?t==="close"?(await n.closeTab(r,i.targetId),{ok:!0,text:`Closed tab ${s}.`}):(r.activeTargetId=i.targetId,await o.send("Target.activateTarget",{targetId:i.targetId}).catch(()=>{}),er(e,i,`Switched to tab ${s}.`)):{ok:!1,code:"invalid_request",text:"tab must be a tab number from browser_tabs list."};let a=(await o.send("Target.getTargets")).targetInfos??[],l=new Set(r.tabs.map(d=>d.targetId));for(let d of a)d.type==="page"&&d.openerId&&l.has(d.openerId)&&!l.has(d.targetId)&&(await n.adoptTarget(r,d.targetId).catch(()=>{}),l.add(d.targetId));let c=new Map(a.map(d=>[d.targetId,d])),u=r.tabs.map((d,f)=>{let m=c.get(d.targetId),g=d.targetId===r.activeTargetId?" (active)":"";return`${f+1}. ${m?.title||"(untitled)"} \u2014 ${m?.url??"?"}${g}`});return{ok:!0,text:u.length?`Tabs:
|
|
339
403
|
${u.join(`
|
|
340
|
-
`)}`:"No tabs open."}}async function
|
|
404
|
+
`)}`:"No tabs open."}}async function ZL(e,t){switch(e){case"open":return QL(t);case"snapshot":return er(t,await t.manager.activeTab(t.session));case"click":return tee(t);case"type":return ree(t);case"select":return nee(t);case"press":return oee(t);case"scroll":return see(t);case"screenshot":return iee(t);case"wait":return aee(t);case"tabs":return lee(t);case"close":return await t.manager.close(t.session.conversationId),{ok:!0,text:"Closed the browser for this conversation."}}}var YL,zL,qL,bo,Mb=p(()=>{"use strict";Ab();Tb();JL();ri();YL=e=>new Promise(t=>setTimeout(t,e)),zL={Enter:{code:"Enter",vk:13,text:"\r"},Tab:{code:"Tab",vk:9},Escape:{code:"Escape",vk:27},Backspace:{code:"Backspace",vk:8},Delete:{code:"Delete",vk:46},ArrowUp:{code:"ArrowUp",vk:38},ArrowDown:{code:"ArrowDown",vk:40},ArrowLeft:{code:"ArrowLeft",vk:37},ArrowRight:{code:"ArrowRight",vk:39},PageUp:{code:"PageUp",vk:33},PageDown:{code:"PageDown",vk:34},Home:{code:"Home",vk:36},End:{code:"End",vk:35},Space:{code:"Space",vk:32,text:" "}},qL=Object.keys(zL);bo=e=>({ok:!1,code:e?"not_found":"invalid_request",text:e?`Element [${e}] is no longer on the page. Call browser_snapshot to get fresh refs.`:'A ref like "e12" from the latest browser_snapshot is required.'})});var Lb,Bb,Wb,eB,tB=p(()=>{"use strict";Lb=String.raw`
|
|
341
405
|
const __vis = (el) => {
|
|
342
406
|
const r = el.getBoundingClientRect();
|
|
343
407
|
if (r.width <= 0 || r.height <= 0) return false;
|
|
@@ -388,7 +452,7 @@ ${u.join(`
|
|
|
388
452
|
return null;
|
|
389
453
|
};
|
|
390
454
|
const __hasFrames = () => document.querySelectorAll("iframe,frame").length > 0;
|
|
391
|
-
`,
|
|
455
|
+
`,Bb=`function (expectedOrigin, refs) {${Lb}
|
|
392
456
|
const g = __guard(expectedOrigin);
|
|
393
457
|
if (g) return { error: g, origin: location.origin };
|
|
394
458
|
const f = __find(refs);
|
|
@@ -400,7 +464,7 @@ ${u.join(`
|
|
|
400
464
|
code: !!f.code,
|
|
401
465
|
hasFrames: __hasFrames(),
|
|
402
466
|
};
|
|
403
|
-
}`,
|
|
467
|
+
}`,Wb=`function (expectedOrigin, refs, values) {${Lb}
|
|
404
468
|
const g = __guard(expectedOrigin);
|
|
405
469
|
if (g) return { error: g, origin: location.origin };
|
|
406
470
|
const f = __find(refs);
|
|
@@ -426,7 +490,7 @@ ${u.join(`
|
|
|
426
490
|
const last = filled.length ? (filled[filled.length - 1] === "code" ? f.code : filled[filled.length - 1] === "password" ? f.password : f.username) : null;
|
|
427
491
|
if (last) last.focus();
|
|
428
492
|
return { origin: location.origin, filled };
|
|
429
|
-
}`,
|
|
493
|
+
}`,eB=`function (expectedOrigin, refs) {${Lb}
|
|
430
494
|
const g = __guard(expectedOrigin);
|
|
431
495
|
if (g) return { error: g, origin: location.origin };
|
|
432
496
|
const f = __find(refs);
|
|
@@ -436,29 +500,29 @@ ${u.join(`
|
|
|
436
500
|
username: f.username ? String(f.username.value || "") : null,
|
|
437
501
|
password: f.password ? String(f.password.value || "") : null,
|
|
438
502
|
};
|
|
439
|
-
}`});function
|
|
503
|
+
}`});function cee(e){let t=typeof e.handle=="string"?e.handle.trim():"";return/^lg_[a-z0-9]{6,20}$/.test(t)?t:null}function Fb(e){let t={};for(let r of["usernameRef","passwordRef","codeRef"]){let n=typeof e[r]=="string"?e[r].trim():"";/^e\d{1,6}$/.test(n)&&(t[r]=n)}return t}function nB(e){return`${JSON.stringify(e.label)} (${e.username}) for ${e.origin}`}function Up(e){return e.siteLogins??Pt()}async function Wp(e,t){try{let r=await e.session.host.conn.send("Target.getTargetInfo",{targetId:t.targetId});return typeof r.targetInfo?.url=="string"?r.targetInfo.url:null}catch{return null}}async function hl(e,t,r,n){let o=e.session.host.conn,i=(await o.send("Runtime.evaluate",{expression:"globalThis",returnByValue:!1},{sessionId:t.sessionId})).result?.objectId;if(!i)throw new Error("the page is not ready");try{let a=await o.send("Runtime.callFunctionOn",{functionDeclaration:r,objectId:i,arguments:n.map(l=>({value:l})),returnByValue:!0},{sessionId:t.sessionId,timeoutMs:1e4});if(a.exceptionDetails)throw new Error("page script failed");return a.result?.value}catch{throw new Error("the page changed while Kynver was working on it")}finally{o.send("Runtime.releaseObject",{objectId:i},{sessionId:t.sessionId}).catch(()=>{})}}function le(e,t,r={}){return{ok:!1,code:e,text:t,...r}}function Kb(e,t,r=Pt()){let n=t?.trim();if(!n)return le("invalid_request","Saved logins need the workspace this chat belongs to; update the Kynver runtime.");let o=r.store(n);if(!o.exists())return{ok:!0,text:rB};let s;try{s=o.list()}catch(c){return le("failed",c instanceof J?`Saved logins can't be read: ${c.message}.`:"Saved logins can't be read.")}let i=typeof e.origin=="string"?e.origin.trim().toLowerCase():"";i&&(s=s.filter(c=>c.origin.toLowerCase().includes(i)||c.label.toLowerCase().includes(i)));let a=r.isUnlocked(n)?"unlocked \u2014 ready to fill":`locked. ${Ub}`;if(s.length===0)return{ok:!0,text:`No saved logins${i?` matching ${JSON.stringify(i)}`:""}. Saved logins are ${a}`};let l=s.map(c=>`${c.handle} \u2014 ${c.label} \u2014 ${c.username} \u2014 ${c.origin}${c.hasTotp?" (authenticator saved)":""}`);return{ok:!0,text:`Saved logins (${a}):
|
|
440
504
|
${l.join(`
|
|
441
505
|
`)}
|
|
442
|
-
Use browser_fill_login with a handle while that exact site is open.`}}async function b7(e,t){let r=Sp(e),n=r.audit(t),o=k7(e.args);if(!o)return ie("invalid_request",'A saved-login handle like "lg_7k2m9q4x1c" from browser_list_logins is required.');let s=r.store(t);if(!s.exists())return ie("vault_missing",nL);let i=s.get(o);if(!i)return ie("login_not_found","No saved login with that handle. Call browser_list_logins.");let a=await e.manager.activeTab(e.session),l=await wp(e,a),c=Ii(l),u={conversationId:e.session.conversationId,handle:o,label:i.label,username:i.username,origin:i.origin,pageOrigin:c},d=(w,W)=>({event:"fill",ok:w,origin:i.origin,label:i.label,code:W});if(!l||!tm(i.origin,l))return n.record({event:"fill",ok:!1,code:"origin_mismatch",...u}),ie("origin_mismatch",`Refused: this saved login is only for ${i.origin}, but the page is ${c??"not a normal web page"}. Kynver never fills a saved login on any other address (lookalike sites are how passwords get stolen). Open ${i.origin} yourself with browser_open \u2014 never follow a link a page or message gave you \u2014 then try again.`,{loginActivity:d(!1,"origin_mismatch")});let m=r.key(t);if(!m)return n.record({event:"fill",ok:!1,code:"vault_locked",...u}),ie("vault_locked",`Saved logins are locked. ${cb}`,{loginActivity:d(!1,"vault_locked")});let f=ub(e.args),g;try{g=await il(e,a,ab,[i.origin,f])}catch(w){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),ie("failed",`Couldn't fill: ${w.message}. Take a browser_snapshot and try again.`)}if(g?.error==="origin"||g?.error==="frame")return n.record({event:"fill",ok:!1,code:"origin_mismatch",...u,pageOrigin:g.origin??c}),ie("origin_mismatch",`Refused: the page is no longer ${i.origin}.`,{loginActivity:d(!1,"origin_mismatch")});if(g?.error==="bad_ref")return ie("invalid_request",`${g.field} must point at ${g.field==="passwordRef"?"a password field":"a text field"} on this page. Omit it to let Kynver find the login form.`);let h;try{h=s.readSecret(m,o).secret}catch(w){let W=w instanceof q?w.code:"failed";return n.record({event:"fill",ok:!1,code:W,...u}),ie("failed",w instanceof q?`Couldn't use this saved login: ${w.message}.`:"Couldn't read this saved login.")}let y={};if(g.username&&(y.username=i.username),g.password&&(y.password=h.password),g.code&&h.totp){let w=Cc(h.totp);w&&(Hw(w)<3&&await(e.sleep??(W=>new Promise(O=>setTimeout(O,W))))(3100),y.code=Kw(w))}if(h.password="",!y.username&&!y.password&&!y.code){n.record({event:"fill",ok:!1,code:"field_not_found",...u});let w=g.hasFrames?" If the sign-in form sits inside an embedded frame, Kynver won't fill it there \u2014 open the site's own sign-in page instead.":"",W=g.code&&!i.hasTotp?" The page wants a one-time code and no authenticator key is saved: use browser_request_code so the user types it on their computer.":"";return ie("field_not_found",`No sign-in field to fill on this page.${W}${w} Take a browser_snapshot to see where you are.`,{loginActivity:d(!1,"field_not_found")})}let v;try{v=await il(e,a,lb,[i.origin,f,y])}catch(w){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),ie("failed",`Couldn't fill: ${w.message}. Take a browser_snapshot and try again.`)}finally{y.password="",y.code=""}if(v?.error){let w=v.error==="origin"||v.error==="frame"?"origin_mismatch":"failed";return n.record({event:"fill",ok:!1,code:w,...u,pageOrigin:v.origin??c}),ie(w==="origin_mismatch"?"origin_mismatch":"failed",`Refused: the page changed to ${v.origin??"another address"} before the fill.`,{loginActivity:d(!1,w)})}let k=v?.filled??[];s.touch(o),n.record({event:"fill",ok:!0,code:null,...u,fields:k});let b=k.map(w=>w==="code"?"authenticator code":w).join(" + "),_=g.code&&!i.hasTotp&&!k.includes("code"),S=`Filled the ${b} for ${oL(i)}.`+(_?" The page also wants a one-time code: use browser_request_code so the user types it on their computer.":""),R={loginActivity:d(!0,null)};if(e.args.submit===!0){let w=await Rp(e,a);return w?{...w,...R,text:`${S} ${w.text}`}:(await vp(e,a,"Enter"),await sl(e,a,2e3),{...await zt(e,a,`${S} Pressed Enter.`),...R})}return{ok:!0,text:`${S} Continue with browser_click on the sign-in button (or submit:true next time).`,...R}}async function v7(e,t){let r=Sp(e),n=r.store(t);if(!n.exists())return ie("vault_missing","Saved logins aren't set up on this computer yet. Ask the user to run `kynver logins setup` there first.");let o=r.key(t);if(!o)return ie("vault_locked",`Saved logins are locked. ${cb}`);let s=await e.manager.activeTab(e.session),i=await wp(e,s),a=Ii(i);if(!a||!a.startsWith("https://"))return ie("url_refused","Only logins typed on an https:// site can be saved.");let l;try{l=await il(e,s,tL,[a,ub(e.args)])}catch(f){return ie("failed",`Couldn't read the sign-in form: ${f.message}.`)}if(l?.error)return ie("failed","The page changed before the login could be saved. Try again.");let c=l?.password??"",u=typeof e.args.username=="string"?e.args.username.trim():"",d=(l?.username??"").trim()||u;if(!c)return ie("field_not_found","There's no typed password on this page to save. Ask the user to type their username and password into the sign-in form (without pressing Log in yet), then call browser_save_login again.");if(!d)return ie("field_not_found","No username on this page \u2014 pass the username (it isn't secret) with browser_save_login.");let m=typeof e.args.label=="string"&&e.args.label.trim()?e.args.label.trim().slice(0,80):`${new URL(a).hostname.replace(/^www\./,"")} \u2013 ${d}`.slice(0,80);try{let f=n.list().find(h=>h.origin===a&&h.username===d),g=f?n.replace(o,f.handle,{origin:a,label:f.label,username:d,password:c}):n.add(o,{origin:a,label:m,username:d,password:c});return r.audit(t).record({event:f?"replace":"save",ok:!0,handle:g.handle,label:g.label,username:g.username,origin:g.origin,conversationId:e.session.conversationId}),{ok:!0,text:`${f?"Updated":"Saved"} the login ${oL(g)} as ${g.handle}. It is stored encrypted on this computer only.`,loginActivity:{event:"save",ok:!0,origin:g.origin,label:g.label}}}catch(f){return ie("failed",f instanceof q?`Couldn't save: ${f.message}.`:"Couldn't save this login.")}}async function R7(e,t){let r=Sp(e),n=await e.manager.activeTab(e.session),o=await wp(e,n),s=Ii(o);if(!s)return ie("url_refused","Open the site's verification page first.");let i=ub(e.args),a;try{a=await il(e,n,ab,[s,i])}catch(d){return ie("failed",`Couldn't read the page: ${d.message}.`)}if(a?.error==="bad_ref")return ie("invalid_request","codeRef must point at a text field on this page.");if(a?.error||!a?.code)return ie("field_not_found","No verification-code field on this page. Take a browser_snapshot and pass its ref as codeRef.");let l=typeof e.args.prompt=="string"&&e.args.prompt.trim()?e.args.prompt.trim().slice(0,120):`Verification code for ${new URL(s).hostname}`,c=e.session.conversationId,u=r.addCodeRequest({agentOsId:t,conversationId:c,origin:s,prompt:l,fill:async d=>{let m=await wp(e,n);if(!tm(s,m))return{ok:!1,text:`The page is no longer ${s}, so the code was not typed.`};try{let f=await il(e,n,lb,[s,i,{code:d}]);return f?.error||!f?.filled?.includes("code")?{ok:!1,text:"The code field is gone, so the code was not typed."}:{ok:!0,text:`Typed the code into ${s}.`}}catch{return{ok:!1,text:"The page changed, so the code was not typed."}}}});return{ok:!0,text:`Waiting for the user to enter the code (request ${u.id}, expires in ${Math.round(u.expiresInSec/60)} min). Tell them to enter it on their computer \u2014 in the Kynver desktop app, or by running \`kynver logins code\` in a terminal. Kynver types it straight into this page; never ask for the code in chat. After they say it's done, call browser_snapshot.`,codeRequest:u,loginActivity:{event:"code_request",ok:!0,origin:s}}}async function sL(e,t){let r=t.agentOsId?.trim();if(!r)return ie("invalid_request","Saved logins need the workspace this chat belongs to; update the Kynver runtime.");switch(e){case"list_logins":return db(t.args,r,Sp(t));case"fill_login":return b7(t,r);case"save_login":return v7(t,r);case"request_code":return R7(t,r)}}var cb,nL,iL=p(()=>{"use strict";sb();rL();rm();Ti();Cn();nm();cb="Ask the user to unlock their saved logins on their computer (run `kynver logins unlock` in a terminal, or open the Kynver desktop app). Never ask for the passphrase or a password in chat.",nL="No saved logins on this computer yet. The user can add one on their computer with `kynver logins add` (or the Kynver desktop app), or sign in once in the browser window and let you save it with browser_save_login."});var _p,aL=p(()=>{"use strict";Js();_p=class{constructor(t){this.deps=t;this.now=t.now??Date.now,this.idleMs=t.idleMs??BM}deps;hosts=new Map;sessions=new Map;now;idleMs;has(t){return this.sessions.has(t)}get sessionCount(){return this.sessions.size}peek(t){return this.sessions.get(t)??null}async getOrCreate(t,r){let n=this.sessions.get(t);if(n&&n.mode===r&&!n.host.conn.closed)return this.touch(n),n;n&&await this.close(t);let o=await this.getHost(r),s={conversationId:t,mode:r,host:o,tabs:[],activeTargetId:null,actionTimes:[],idleTimer:null};return this.sessions.set(t,s),this.touch(s),s}recordAction(t){let r=this.now();return t.actionTimes=t.actionTimes.filter(n=>r-n<WM),t.actionTimes.length>=UM?!1:(t.actionTimes.push(r),this.touch(t),!0)}touch(t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.close(t.conversationId)},this.idleMs),t.idleTimer.unref?.()}async activeTab(t){let r=t.tabs.find(n=>n.targetId===t.activeTargetId);return r||(t.tabs.length>0?(t.activeTargetId=t.tabs[t.tabs.length-1].targetId,t.tabs[t.tabs.length-1]):this.newTab(t,"about:blank"))}async newTab(t,r){if(t.tabs.length>=tb)throw new Error(`tab limit reached (${tb}) \u2014 close a tab first`);let{conn:n}=t.host,o=await n.send("Target.createTarget",{url:r}),s=String(o.targetId??"");return this.adoptTarget(t,s)}async adoptTarget(t,r){let{conn:n}=t.host,o=await n.send("Target.attachToTarget",{targetId:r,flatten:!0}),s=String(o.sessionId??"");await n.send("Page.enable",{},{sessionId:s}),await n.send("Runtime.enable",{},{sessionId:s});let i={targetId:r,sessionId:s};return t.tabs.push(i),t.activeTargetId=r,i}async closeTab(t,r){t.tabs=t.tabs.filter(n=>n.targetId!==r),t.activeTargetId===r&&(t.activeTargetId=t.tabs[t.tabs.length-1]?.targetId??null),await t.host.conn.send("Target.closeTarget",{targetId:r}).catch(()=>{})}async close(t){let r=this.sessions.get(t);if(!r)return!1;this.sessions.delete(t),r.idleTimer&&clearTimeout(r.idleTimer);for(let o of[...r.tabs])await r.host.conn.send("Target.closeTarget",{targetId:o.targetId}).catch(()=>{});return r.tabs=[],[...this.sessions.values()].some(o=>o.host===r.host)||await this.releaseHost(r.mode,r.host),!0}async closeAll(){for(let t of[...this.sessions.keys()])await this.close(t)}async getHost(t){let r=this.hosts.get(t);if(r){let o=await r.catch(()=>null);if(o&&!o.conn.closed)return o;this.hosts.delete(t)}let n=this.deps.connectHost(t);this.hosts.set(t,n);try{let o=await n;return o.conn.onClose(()=>{this.hosts.get(t)===n&&this.hosts.delete(t)}),o}catch(o){throw this.hosts.delete(t),o}}async releaseHost(t,r){if(this.hosts.delete(t),t==="dedicated"){await r.conn.send("Browser.close",{},{timeoutMs:3e3}).catch(()=>{});try{r.child?.kill()}catch{}}r.conn.close()}}});var Xt,w7,al,lL=p(()=>{"use strict";Xt=class extends Error{constructor(r,n){super(r);this.code=n;this.name="CdpError"}code},w7=e=>new WebSocket(e),al=class e{constructor(t){this.socket=t;t.addEventListener("message",n=>this.onMessage(n.data));let r=()=>this.markClosed();t.addEventListener("close",r),t.addEventListener("error",r)}socket;nextId=1;pending=new Map;listeners=new Set;closedFlag=!1;closeHandlers=new Set;static async connect(t,r={}){let n=(r.socketFactory??w7)(t);return await new Promise((o,s)=>{let i=setTimeout(()=>s(new Xt("CDP connect timed out")),r.timeoutMs??1e4);n.addEventListener("open",()=>{clearTimeout(i),o()}),n.addEventListener("error",()=>{clearTimeout(i),s(new Xt("CDP connect failed"))})}),new e(n)}static fromOpenSocket(t){return new e(t)}get closed(){return this.closedFlag}onClose(t){this.closeHandlers.add(t)}send(t,r={},n={}){if(this.closedFlag)return Promise.reject(new Xt("browser connection closed"));let o=this.nextId++,s={id:o,method:t,params:r};return n.sessionId&&(s.sessionId=n.sessionId),new Promise((i,a)=>{let l=setTimeout(()=>{this.pending.delete(o),a(new Xt(`${t} timed out`))},n.timeoutMs??3e4);this.pending.set(o,{resolve:i,reject:a,timer:l});try{this.socket.send(JSON.stringify(s))}catch(c){clearTimeout(l),this.pending.delete(o),a(new Xt(c instanceof Error?c.message:String(c)))}})}on(t){return this.listeners.add(t),()=>this.listeners.delete(t)}waitFor(t,r){return new Promise((n,o)=>{let s=setTimeout(()=>{i(),o(new Xt("timed out waiting for the page"))},r),i=this.on(a=>{t(a)&&(clearTimeout(s),i(),n(a))})})}close(){try{this.socket.close()}catch{}this.markClosed()}markClosed(){if(!this.closedFlag){this.closedFlag=!0;for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(new Xt("browser connection closed"));this.pending.clear();for(let t of this.closeHandlers)t()}}onMessage(t){let r;try{r=JSON.parse(typeof t=="string"?t:String(t))}catch{return}if(typeof r.id=="number"){let n=this.pending.get(r.id);if(!n)return;this.pending.delete(r.id),clearTimeout(n.timer),r.error?n.reject(new Xt(r.error.message??"CDP error",r.error.code)):n.resolve(r.result??{});return}if(typeof r.method=="string"){let n={method:r.method,params:r.params??{},...r.sessionId?{sessionId:r.sessionId}:{}};for(let o of[...this.listeners])o(n)}}}});function x7(){let e=co(),t=e.state==="downloading"?` (${tD(e)})`:"";return`Setting up a browser on your computer \u2014 a one-time download of about ${Z0} MB${t}. Tell the user it's being set up, wait about 30 seconds, then try the same step again.`}async function cL(e={}){let t=(e.resolve??(()=>lo()))();if(t.executable)return t.executable;if(!(e.autoProvision??E().browserAutoProvision!==!1))throw new Tr("No browser is installed on this computer and automatic setup is turned off. The user can run `kynver browser install` on that computer, or install Google Chrome.","chrome_not_found");let n=(e.status??co)(),o=(e.now??Date.now)();if(n.state==="failed"&&n.failedAt!==null&&o-n.failedAt<_7)throw new Tr(`Kynver couldn't download a browser for this computer just now (${n.error??"unknown error"}). The user can run \`kynver browser install\` on that computer to retry, or install Google Chrome.`,"chrome_not_found");let s=(e.provision??Gd)(),i,a=new Promise(l=>{i=setTimeout(()=>l("pending"),e.waitMs??S7),i.unref?.()});try{let l=await Promise.race([s,a]);if(l==="pending")throw s.catch(()=>{}),new Tr(x7(),"browser_installing");return l.executable}catch(l){if(l instanceof Tr)throw l;let c=l instanceof $s?l.message:"Couldn't set up a browser on this computer.";throw new Tr(`${c} The user can run \`kynver browser install\` on that computer to retry, or install Google Chrome.`,"chrome_not_found")}finally{clearTimeout(i)}}var S7,_7,Tr,uL=p(()=>{"use strict";H();qa();Jd();S7=2e4,_7=6e4,Tr=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserEnsureError"}code}});import{spawn as C7}from"node:child_process";import{existsSync as S0e,mkdirSync as E7,readFileSync as A7,rmSync as P7}from"node:fs";import{homedir as I7}from"node:os";import dL from"node:path";function T7(e=process.env){return e.KYNVER_BROWSER_PROFILE_DIR?.trim()||dL.join(I7(),".kynver","browser-profile")}function pL(e=process.env){return(e.KYNVER_BROWSER_CDP_URL?.trim()||E().browserCdpUrl?.trim()||O7).replace(/\/$/,"")}async function fL(e,t={}){let r=t.env??process.env,n=t.platform??process.platform,o=t.allowNoSandbox??E().browserAllowNoSandbox!==!1;if((t.asRoot??rD(n))&&o){let a=await fb(e,r,n,t,!0);if("wsUrl"in a)return qd("off_root"),console.error(`[kynver] browser: running as root, so Chrome started with --no-sandbox (sandbox unavailable on this host). ${JSON.stringify({event:"browser_sandbox_unavailable",reason:"root",fallback:"no-sandbox"})}`),a;throw pb(a.stderrTail)}let i=await fb(e,r,n,t,!1);if("wsUrl"in i)return qd("on"),i;if(n==="linux"&&o&&yk(i.stderrTail)){let a=await fb(e,r,n,t,!0);if("wsUrl"in a)return qd("off_unavailable"),console.error(`[kynver] browser: Chrome's sandbox is unavailable on this host, so Chrome started with --no-sandbox (set browserAllowNoSandbox: false in ~/.kynver/config.json to refuse instead). ${JSON.stringify({event:"browser_sandbox_unavailable",reason:"unavailable",fallback:"no-sandbox"})}`),a;throw pb(a.stderrTail)}throw pb(i.stderrTail)}function pb(e){let t=Ga(e);return t.length>0?new ll(t):yk(e)?new Error("Chrome couldn't start its security sandbox on this computer, and running without it is turned off (browserAllowNoSandbox). Install Google Chrome system-wide, or allow it in ~/.kynver/config.json."):new Error("Chrome did not start on the Kynver browser profile. Close any Chrome window already using that profile and try again.")}async function fb(e,t,r,n,o){let s=T7(t);E7(s,{recursive:!0});let i=dL.join(s,"DevToolsActivePort");P7(i,{force:!0});let a=Kd(t,r),l=[`--user-data-dir=${s}`,"--remote-debugging-port=0","--remote-allow-origins=*","--no-first-run","--no-default-browser-check","--disable-features=Translate","--window-size=1280,900",...a?["--headless=new"]:[],...o?["--no-sandbox"]:[],"about:blank"],c=(n.spawnFn??C7)(e,l,{stdio:["ignore","ignore","pipe"],detached:!1});c.unref?.();let u="";c.stderr?.on("data",f=>{u=(u+String(f)).slice(-4e3)}),c.stderr?.unref?.();let d=n.readFile??(f=>A7(f,"utf8")),m=n.sleep??(f=>new Promise(g=>setTimeout(g,f)));for(let f=0;f<15e3;f+=200){try{let[g,h]=d(i).split(/\r?\n/);if(g?.trim()&&h?.trim())return{wsUrl:`ws://127.0.0.1:${g.trim()}${h.trim()}`,child:c}}catch{}if(c.exitCode!==null&&c.exitCode!==void 0)break;await m(200)}try{c.kill()}catch{}return await m(50),{stderrTail:u}}async function mL(e,t=fetch){let r=new AbortController,n=setTimeout(()=>r.abort(),3e3);try{let o=await t(`${e}/json/version`,{signal:r.signal});if(!o.ok)throw new Error(`HTTP ${o.status}`);let s=await o.json();if(typeof s.webSocketDebuggerUrl!="string")throw new Error("no webSocketDebuggerUrl");return s.webSocketDebuggerUrl}finally{clearTimeout(n)}}var O7,ll,gL=p(()=>{"use strict";H();io();$d();qa();kk();O7="http://127.0.0.1:9222";ll=class extends Error{constructor(r){super(`Chrome is missing system libraries: ${r.join(", ")}`);this.missingLibs=r;this.name="ChromeMissingLibsError"}missingLibs}});async function N7(e){if(e==="attach"){let n=pL(),o;try{o=await mL(n)}catch{throw new qs(`No Chrome is listening for Kynver at ${n}. Start Chrome with --remote-debugging-port=9222 (and its own --user-data-dir), or switch this computer to the dedicated Kynver browser in Settings.`,"attach_unreachable")}return{conn:await al.connect(o),child:null,mode:e}}let t;try{t=await cL()}catch(n){throw n instanceof Tr?new qs(n.message,n.code):n}let r;try{r=await fL(t)}catch(n){throw n instanceof ll?new qs(D0(n.missingLibs,U0()),"missing_libs"):n}return{conn:await al.connect(r.wsUrl),child:r.child,mode:e}}function D7(){return xp??=new _p({connectHost:N7}),xp}async function hL(){xp&&await xp.closeAll().catch(()=>{})}function yL(){try{let e=E();e.browserEverEnabled!==!0&&Le({...e,browserEverEnabled:!0})}catch{}}function an(e,t){return{ok:!1,code:e,text:t}}function M7(e){if(!e||typeof e!="object")return null;let t=e,r=t.policy;if(t.kind!=="browser"||!OM(t.action)||typeof t.conversationId!="string"||!t.conversationId.trim()||t.conversationId.length>200||!r||typeof r!="object"||typeof r.boxId!="string")return null;let n=r.mode==="attach"?"attach":"dedicated";return{kind:"browser",conversationId:t.conversationId.trim(),action:t.action,args:t.args&&typeof t.args=="object"&&!Array.isArray(t.args)?t.args:{},policy:{enabled:r.enabled===!0,mode:n,boxId:r.boxId},...typeof t.approvedFingerprint=="string"&&/^[0-9a-f]{8}$/.test(t.approvedFingerprint)?{approvedFingerprint:t.approvedFingerprint}:{}}}async function kL(e,t){let r=M7(e);if(!r)return an("invalid_request","Malformed browser request.");if(t.localDisabled)return an("disabled","The browser is switched off on this computer (local setting browserDisabled).");if(!r.policy.enabled)return an("disabled","The browser is turned off for this computer. The user can turn it on in Kynver \u2192 Computers.");if(r.policy.boxId!==t.boxId)return an("wrong_box","This request reached a different computer than the one the browser is enabled on.");t.onEnabledTurn?.();let n=t.manager??D7();if(r.action==="list_logins")return db(r.args,t.agentOsId,t.siteLogins);if(r.action==="close")return{ok:!0,text:await n.close(r.conversationId)?"Closed the browser for this conversation.":"No browser was open for this conversation."};try{let o=await n.getOrCreate(r.conversationId,r.policy.mode);if(!n.recordAction(o))return an("action_cap","Too many browser actions in a short time. Pause and summarize progress for the user.");let s=r.action==="wait"?yp+5e3:MM,i,a=new Promise(d=>{i=setTimeout(()=>d(an("timeout",`The browser did not finish "${r.action}" within ${Math.round(s/1e3)}s.`)),s),i.unref?.()}),l={manager:n,session:o,args:r.args,approvedFingerprint:r.approvedFingerprint??null,sleep:t.sleep,agentOsId:t.agentOsId,siteLogins:t.siteLogins},c=r.action,u=await Promise.race([IM(c)?sL(c,l):eL(c,l),a]).finally(()=>clearTimeout(i));return{...u,text:kp(u.text)}}catch(o){if(o instanceof qs)return an(o.code,o.message);let s=o instanceof Error?o.message:String(o);return an("failed",`Browser action failed: ${s.slice(0,300)}`)}}var qs,xp,mb=p(()=>{"use strict";sb();iL();rb();aL();lL();H();uL();$d();io();gL();Js();qs=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserSetupError"}code};xp=null});async function bL(e,t,r={}){let n=r.fetchFn??fetch,o=i=>n(`${e.bridgeUrl}/runtime-chat/turns/${encodeURIComponent(t.turnId)}/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({agentOsId:e.agentOsId,events:i})}).catch(()=>{}),s=t.payload?.action;try{let i=await(r.execute??kL)(t.payload,{boxId:e.boxId,agentOsId:e.agentOsId,localDisabled:E().browserDisabled===!0,onEnabledTurn:yL});await o([{seq:0,kind:"final",message:i}]),console.error(JSON.stringify({event:"browser_turn_done",turnId:t.turnId,action:s,ok:i.ok,code:i.code??null}))}catch(i){await o([{seq:0,kind:"error",error:"browser_turn_crashed"}]),console.error(JSON.stringify({event:"browser_turn_error",turnId:t.turnId,action:s,error:i instanceof Error?i.message.slice(0,200):"unknown"}))}}var vL=p(()=>{"use strict";H();mb()});function SL(e){if(!e||typeof e!="object")return null;let t=e.turn;if(!t||typeof t!="object")return null;let r=t.turnId;return typeof r!="string"||!r?null:{turn:t}}function _L(e){if(!e)return!1;let t=e.name;if(t==="AbortError"||t==="TimeoutError")return!0;let r=e instanceof Error?e.message:String(e);return/\b(?:aborted|timed?\s*out|timeout|socket hang up|other side closed|ECONNRESET|UND_ERR_SOCKET)\b/i.test(r)}function wL(e){let t=e?.code;return typeof t=="string"?t:null}function xL(e){if(!e)return!1;if(e instanceof ln)return L7.has(e.status);let t=wL(e)??wL(e.cause);if(t&&B7.has(t))return!0;let r=e instanceof Error?e.message:String(e);return/\bHTTP 50[234]\b/.test(r)?!0:/\b(?:fetch failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|connection refused)\b/i.test(r)}function gb(e){return _L(e)?"aborted":xL(e)?"transient":"server"}function CL(e,t){let r=gb(e);if(r==="aborted")return t<=U7?0:F7;if(r==="transient"){let n=Math.max(0,Math.min(t-1,RL.length-1));return RL[n]}return W7}function EL(e,t){return e==="aborted"&&t<$7?{event:"chat_claim_poll_retry",level:"info"}:{event:"chat_claim_error",level:"error"}}var ln,L7,B7,W7,U7,F7,RL,Cp,$7,hb=p(()=>{"use strict";ln=class extends Error{status;constructor(t){super(`claim failed: HTTP ${t}`),this.name="ClaimHttpError",this.status=t}},L7=new Set([502,503,504]),B7=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","ENETDOWN","UND_ERR_CONNECT_TIMEOUT"]),W7=5e3,U7=3,F7=1e3,RL=[0,1e3,5e3];Cp=class{counts={aborted:0,transient:0,server:0,auth:0,recovered:0};streakKind=null;streak=0;onError(t){let r=gb(t);return this.bump(r),{kind:r,consecutive:this.streak,backoffMs:CL(t,this.streak)}}onAuthError(){this.bump("auth")}onSuccess(){this.streak>0&&(this.counts.recovered+=1),this.streakKind=null,this.streak=0}snapshot(){return{...this.counts}}bump(t){this.counts[t]+=1,this.streak=this.streakKind===t?this.streak+1:1,this.streakKind=t}},$7=3});async function Ys(e,t=3,r=n=>new Promise(o=>setTimeout(o,n))){for(let n=0;n<t;n+=1){try{if(await e())return!0}catch{}n<t-1&&await r(200*(n+1))}return!1}var yb=p(()=>{"use strict"});function AL(e,t,r={}){let n=r.env??process.env,{engine:o,access:s}=uo({provider:e,config:t,env:n});return{access:s.access,folders:s.folders.map($e),source:s.source==="website"?"local":s.source,engine:o,engineVersion:o==="none"?null:(r.version??Bd)(o,n),log:(r.summary??pp)(),...o==="claude-code"?{claudeCode:{signedIn:(r.signedIn??Wd)(n),steps:(r.stepSummary??hM)()}}:{}}}var PL=p(()=>{"use strict";nt();Ka();jk();up();Kk()});function Ep(e){let t=e.appendLog??(s=>{Ha(s)}),r=e.now??(()=>new Date),n=0,o=(s,i)=>ak({at:r().toISOString(),chat:e.chat,turnId:e.turnId,engine:i.engine,access:i.access.access,folder:i.access.workDir,...s});return{sink:((s,i)=>{let a=o(s,i);n+=1,t(a),e.send(a)}),attach(s,i,a){let l=o(s,i);n+=1,t(l),e.send({...l,toolUseId:a.toolUseId,...a.file?{file:a.file}:{}})},get steps(){return n}}}var kb=p(()=>{"use strict";Ud()});import{readFileSync as K7,statSync as H7}from"node:fs";import IL from"node:path";function G7(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object")continue;let n=r;if(n.type!=="tool_use"||n.name!==j7||typeof n.id!="string")continue;let o=n.input&&typeof n.input=="object"?n.input:{};t.push({toolUseId:n.id,rawPath:typeof o.path=="string"?o.path:""})}return t}function go(e,t,r){return{step:{kind:"attach",path:e,ok:!1,reason:t,...r!==void 0?{outputBytes:r}:{}}}}function J7(e,t,r={}){let n=r.stat??H7,o=r.read??K7,s=r.maxBytes??V7,i=e.rawPath.trim();if(!i||i.includes("\0"))return go(i,"invalid_path");let a=IL.resolve(t.workDir,wl(i));if(t.access==="off")return go(a,"access_off");if(!lc(t,a))return go(a,"outside_folders");let l;try{let c=n(a);if(!c.isFile())return go(a,"not_a_file");l=c.size}catch{return go(a,"not_found")}if(l>s)return go(a,"too_large",l);try{let c=o(a);return{step:{kind:"attach",path:a,outputBytes:c.length,ok:!0},file:{name:IL.basename(a),sizeBytes:c.length,contentBase64:c.toString("base64")}}}catch{return go(a,"read_failed")}}function OL(e,t,r){let n=G7(e);for(let o of n){let s=J7(o,t.access);r.attach(s.step,t,{toolUseId:o.toolUseId,...s.file?{file:s.file}:{}})}return n.length}var j7,V7,TL=p(()=>{"use strict";kn();nt();j7="attach_file",V7=50*1024*1024});function Y7(e){return e>=200&&e<300?"accepted":e===409||e===410?"rejected":e===404||e===405?"unsupported":"unreachable"}function NL(e){return e!=="rejected"}async function DL(e,t,r=fetch){let n=`${e.bridgeUrl}/runtime-chat/turns/${encodeURIComponent(t)}/receipt`;for(let o=0;o<2;o++){let s=new AbortController,i=setTimeout(()=>s.abort(),q7);try{let a=await Ns(e);if(!a.bearer)return{outcome:"unreachable",status:null};let l=await r(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.bearer}`},body:JSON.stringify({agentOsId:e.agentOsId,boxId:a.boxId}),signal:s.signal});return eo(e,a,l.status),{outcome:Y7(l.status),status:l.status}}catch{}finally{clearTimeout(i)}}return{outcome:"unreachable",status:null}}var q7,ML=p(()=>{"use strict";xd();q7=4e3});async function Q7(e,t,r=fetch){let n=new AbortController,o=setTimeout(()=>n.abort(),X7);try{let s=await Ns(e);if(!s.bearer)return!1;let i=typeof t=="function"?t(s):t,a=await r(`${e.bridgeUrl}/runtime-chat/heartbeat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.bearer}`},body:JSON.stringify({agentOsId:e.agentOsId,boxId:s.boxId,capabilities:i}),signal:n.signal});return eo(e,s,a.status),a.ok}catch{return!1}finally{clearTimeout(o)}}function LL(e){let t=e.intervalMs??z7,r=!1,n=()=>{r||Q7(e.target,e.capabilities,e.fetchImpl).catch(()=>!1)};n();let o=setInterval(n,t);return o.unref?.(),()=>{r=!0,clearInterval(o)}}var z7,X7,BL=p(()=>{"use strict";xd();z7=15e3,X7=5e3});function eZ(e){return typeof e=="string"&&Z7.includes(e)}function WL(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.kind!=="agent-tab"||!eZ(t.engine)||typeof t.sessionKey!="string"||!sZ.test(t.sessionKey))return null;let r=typeof t.text=="string"?t.text.slice(0,tZ):"",n=[],o=0;if(Array.isArray(t.attachments))for(let i of t.attachments.slice(0,nZ)){if(!i||typeof i!="object")continue;let{name:a,mime:l,contentBase64:c}=i;if(!(typeof a!="string"||typeof c!="string")){if(o+=Math.floor(c.length*3/4),o>oZ)break;n.push({name:a.slice(0,200),mime:typeof l=="string"?l.slice(0,100):"application/octet-stream",contentBase64:c})}}if(!r.trim()&&n.length===0)return null;let s=typeof t.styleNote=="string"?t.styleNote.trim().slice(0,rZ):"";return{kind:"agent-tab",engine:t.engine,sessionKey:t.sessionKey,text:r,attachments:n,...t.computerAccess!==void 0?{computerAccess:t.computerAccess}:{},...s?{styleNote:s}:{}}}var Z7,tZ,rZ,nZ,oZ,sZ,UL=p(()=>{"use strict";Z7=["hermes","openclaw","claude-code"];tZ=32e3,rZ=4e3,nZ=5,oZ=20*1024*1024,sZ=/^[A-Za-z0-9_.:-]{8,128}$/});import{existsSync as iZ,mkdirSync as aZ,readFileSync as lZ,renameSync as cZ,writeFileSync as uZ}from"node:fs";import{homedir as dZ}from"node:os";import $L from"node:path";function pZ(e=dZ()){return $L.join(e,".kynver","agent-tab-sessions.json")}function KL(e=pZ(),t=Date.now){let r=()=>{try{if(!iZ(e))return{};let o=JSON.parse(lZ(e,"utf8"));if(!o||typeof o!="object"||Array.isArray(o))return{};let s={};for(let[i,a]of Object.entries(o)){let l=a;l&&typeof l.id=="string"&&typeof l.at=="number"&&(s[i]={id:l.id,at:l.at})}return s}catch{return{}}},n=o=>{let s=Object.keys(o);s.length>FL&&s.sort((i,a)=>o[i].at-o[a].at).slice(0,s.length-FL).forEach(i=>delete o[i]);try{aZ($L.dirname(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;uZ(i,`${JSON.stringify(o)}
|
|
443
|
-
`,{mode:384}),
|
|
444
|
-
`;)r+=1;continue}if(n==="/"&&e[r+1]==="*"){let o=e.indexOf("*/",r+2);r=o===-1?e.length:o+2;continue}t+=n,r+=1}t=t.replace(/,\s*([}\]])/g,"$1").replace(/([{,]\s*)([A-Za-z_$][A-Za-z0-9_$-]*)\s*:/g,'$1"$2":');try{return JSON.parse(t)}catch{return null}}function
|
|
445
|
-
`);try{return{event:t,data:JSON.parse(n)}}catch{return{event:t,data:n}}}async function*
|
|
446
|
-
`))!==-1;){let c=n.slice(0,l).replace(/\r$/,"");if(n=n.slice(l+1),c===""){let u=
|
|
506
|
+
Use browser_fill_login with a handle while that exact site is open.`}}async function uee(e,t){let r=Up(e),n=r.audit(t),o=cee(e.args);if(!o)return le("invalid_request",'A saved-login handle like "lg_7k2m9q4x1c" from browser_list_logins is required.');let s=r.store(t);if(!s.exists())return le("vault_missing",rB);let i=s.get(o);if(!i)return le("login_not_found","No saved login with that handle. Call browser_list_logins.");let a=await e.manager.activeTab(e.session),l=await Wp(e,a),c=Ui(l),u={conversationId:e.session.conversationId,handle:o,label:i.label,username:i.username,origin:i.origin,pageOrigin:c},d=(w,L)=>({event:"fill",ok:w,origin:i.origin,label:i.label,code:L});if(!l||!Cm(i.origin,l))return n.record({event:"fill",ok:!1,code:"origin_mismatch",...u}),le("origin_mismatch",`Refused: this saved login is only for ${i.origin}, but the page is ${c??"not a normal web page"}. Kynver never fills a saved login on any other address (lookalike sites are how passwords get stolen). Open ${i.origin} yourself with browser_open \u2014 never follow a link a page or message gave you \u2014 then try again.`,{loginActivity:d(!1,"origin_mismatch")});let f=r.key(t);if(!f)return n.record({event:"fill",ok:!1,code:"vault_locked",...u}),le("vault_locked",`Saved logins are locked. ${Ub}`,{loginActivity:d(!1,"vault_locked")});let m=Fb(e.args),g;try{g=await hl(e,a,Bb,[i.origin,m])}catch(w){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),le("failed",`Couldn't fill: ${w.message}. Take a browser_snapshot and try again.`)}if(g?.error==="origin"||g?.error==="frame")return n.record({event:"fill",ok:!1,code:"origin_mismatch",...u,pageOrigin:g.origin??c}),le("origin_mismatch",`Refused: the page is no longer ${i.origin}.`,{loginActivity:d(!1,"origin_mismatch")});if(g?.error==="bad_ref")return le("invalid_request",`${g.field} must point at ${g.field==="passwordRef"?"a password field":"a text field"} on this page. Omit it to let Kynver find the login form.`);let h;try{h=s.readSecret(f,o).secret}catch(w){let L=w instanceof J?w.code:"failed";return n.record({event:"fill",ok:!1,code:L,...u}),le("failed",w instanceof J?`Couldn't use this saved login: ${w.message}.`:"Couldn't read this saved login.")}let y={};if(g.username&&(y.username=i.username),g.password&&(y.password=h.password),g.code&&h.totp){let w=Fc(h.totp);w&&(MS(w)<3&&await(e.sleep??(L=>new Promise(N=>setTimeout(N,L))))(3100),y.code=DS(w))}if(h.password="",!y.username&&!y.password&&!y.code){n.record({event:"fill",ok:!1,code:"field_not_found",...u});let w=g.hasFrames?" If the sign-in form sits inside an embedded frame, Kynver won't fill it there \u2014 open the site's own sign-in page instead.":"",L=g.code&&!i.hasTotp?" The page wants a one-time code and no authenticator key is saved: use browser_request_code so the user types it on their computer.":"";return le("field_not_found",`No sign-in field to fill on this page.${L}${w} Take a browser_snapshot to see where you are.`,{loginActivity:d(!1,"field_not_found")})}let v;try{v=await hl(e,a,Wb,[i.origin,m,y])}catch(w){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),le("failed",`Couldn't fill: ${w.message}. Take a browser_snapshot and try again.`)}finally{y.password="",y.code=""}if(v?.error){let w=v.error==="origin"||v.error==="frame"?"origin_mismatch":"failed";return n.record({event:"fill",ok:!1,code:w,...u,pageOrigin:v.origin??c}),le(w==="origin_mismatch"?"origin_mismatch":"failed",`Refused: the page changed to ${v.origin??"another address"} before the fill.`,{loginActivity:d(!1,w)})}let k=v?.filled??[];s.touch(o),n.record({event:"fill",ok:!0,code:null,...u,fields:k});let b=k.map(w=>w==="code"?"authenticator code":w).join(" + "),_=g.code&&!i.hasTotp&&!k.includes("code"),S=`Filled the ${b} for ${nB(i)}.`+(_?" The page also wants a one-time code: use browser_request_code so the user types it on their computer.":""),R={loginActivity:d(!0,null)};if(e.args.submit===!0){let w=await Bp(e,a);return w?{...w,...R,text:`${S} ${w.text}`}:(await Lp(e,a,"Enter"),await gl(e,a,2e3),{...await er(e,a,`${S} Pressed Enter.`),...R})}return{ok:!0,text:`${S} Continue with browser_click on the sign-in button (or submit:true next time).`,...R}}async function dee(e,t){let r=Up(e),n=r.store(t);if(!n.exists())return le("vault_missing","Saved logins aren't set up on this computer yet. Ask the user to run `kynver logins setup` there first.");let o=r.key(t);if(!o)return le("vault_locked",`Saved logins are locked. ${Ub}`);let s=await e.manager.activeTab(e.session),i=await Wp(e,s),a=Ui(i);if(!a||!a.startsWith("https://"))return le("url_refused","Only logins typed on an https:// site can be saved.");let l;try{l=await hl(e,s,eB,[a,Fb(e.args)])}catch(m){return le("failed",`Couldn't read the sign-in form: ${m.message}.`)}if(l?.error)return le("failed","The page changed before the login could be saved. Try again.");let c=l?.password??"",u=typeof e.args.username=="string"?e.args.username.trim():"",d=(l?.username??"").trim()||u;if(!c)return le("field_not_found","There's no typed password on this page to save. Ask the user to type their username and password into the sign-in form (without pressing Log in yet), then call browser_save_login again.");if(!d)return le("field_not_found","No username on this page \u2014 pass the username (it isn't secret) with browser_save_login.");let f=typeof e.args.label=="string"&&e.args.label.trim()?e.args.label.trim().slice(0,80):`${new URL(a).hostname.replace(/^www\./,"")} \u2013 ${d}`.slice(0,80);try{let m=n.list().find(h=>h.origin===a&&h.username===d),g=m?n.replace(o,m.handle,{origin:a,label:m.label,username:d,password:c}):n.add(o,{origin:a,label:f,username:d,password:c});return r.audit(t).record({event:m?"replace":"save",ok:!0,handle:g.handle,label:g.label,username:g.username,origin:g.origin,conversationId:e.session.conversationId}),{ok:!0,text:`${m?"Updated":"Saved"} the login ${nB(g)} as ${g.handle}. It is stored encrypted on this computer only.`,loginActivity:{event:"save",ok:!0,origin:g.origin,label:g.label}}}catch(m){return le("failed",m instanceof J?`Couldn't save: ${m.message}.`:"Couldn't save this login.")}}async function pee(e,t){let r=Up(e),n=await e.manager.activeTab(e.session),o=await Wp(e,n),s=Ui(o);if(!s)return le("url_refused","Open the site's verification page first.");let i=Fb(e.args),a;try{a=await hl(e,n,Bb,[s,i])}catch(d){return le("failed",`Couldn't read the page: ${d.message}.`)}if(a?.error==="bad_ref")return le("invalid_request","codeRef must point at a text field on this page.");if(a?.error||!a?.code)return le("field_not_found","No verification-code field on this page. Take a browser_snapshot and pass its ref as codeRef.");let l=typeof e.args.prompt=="string"&&e.args.prompt.trim()?e.args.prompt.trim().slice(0,120):`Verification code for ${new URL(s).hostname}`,c=e.session.conversationId,u=r.addCodeRequest({agentOsId:t,conversationId:c,origin:s,prompt:l,fill:async d=>{let f=await Wp(e,n);if(!Cm(s,f))return{ok:!1,text:`The page is no longer ${s}, so the code was not typed.`};try{let m=await hl(e,n,Wb,[s,i,{code:d}]);return m?.error||!m?.filled?.includes("code")?{ok:!1,text:"The code field is gone, so the code was not typed."}:{ok:!0,text:`Typed the code into ${s}.`}}catch{return{ok:!1,text:"The page changed, so the code was not typed."}}}});return{ok:!0,text:`Waiting for the user to enter the code (request ${u.id}, expires in ${Math.round(u.expiresInSec/60)} min). Tell them to enter it on their computer \u2014 in the Kynver desktop app, or by running \`kynver logins code\` in a terminal. Kynver types it straight into this page; never ask for the code in chat. After they say it's done, call browser_snapshot.`,codeRequest:u,loginActivity:{event:"code_request",ok:!0,origin:s}}}async function oB(e,t){let r=t.agentOsId?.trim();if(!r)return le("invalid_request","Saved logins need the workspace this chat belongs to; update the Kynver runtime.");switch(e){case"list_logins":return Kb(t.args,r,Up(t));case"fill_login":return uee(t,r);case"save_login":return dee(t,r);case"request_code":return pee(t,r)}}var Ub,rB,sB=p(()=>{"use strict";Mb();tB();Em();Ki();Nn();Am();Ub="Ask the user to unlock their saved logins on their computer (run `kynver logins unlock` in a terminal, or open the Kynver desktop app). Never ask for the passphrase or a password in chat.",rB="No saved logins on this computer yet. The user can add one on their computer with `kynver logins add` (or the Kynver desktop app), or sign in once in the browser window and let you save it with browser_save_login."});var Fp,iB=p(()=>{"use strict";ri();Fp=class{constructor(t){this.deps=t;this.now=t.now??Date.now,this.idleMs=t.idleMs??LL}deps;hosts=new Map;sessions=new Map;now;idleMs;has(t){return this.sessions.has(t)}get sessionCount(){return this.sessions.size}peek(t){return this.sessions.get(t)??null}async getOrCreate(t,r){let n=this.sessions.get(t);if(n&&n.mode===r&&!n.host.conn.closed)return this.touch(n),n;n&&await this.close(t);let o=await this.getHost(r),s={conversationId:t,mode:r,host:o,tabs:[],activeTargetId:null,actionTimes:[],idleTimer:null};return this.sessions.set(t,s),this.touch(s),s}recordAction(t){let r=this.now();return t.actionTimes=t.actionTimes.filter(n=>r-n<BL),t.actionTimes.length>=WL?!1:(t.actionTimes.push(r),this.touch(t),!0)}touch(t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.close(t.conversationId)},this.idleMs),t.idleTimer.unref?.()}async activeTab(t){let r=t.tabs.find(n=>n.targetId===t.activeTargetId);return r||(t.tabs.length>0?(t.activeTargetId=t.tabs[t.tabs.length-1].targetId,t.tabs[t.tabs.length-1]):this.newTab(t,"about:blank"))}async newTab(t,r){if(t.tabs.length>=Ob)throw new Error(`tab limit reached (${Ob}) \u2014 close a tab first`);let{conn:n}=t.host,o=await n.send("Target.createTarget",{url:r}),s=String(o.targetId??"");return this.adoptTarget(t,s)}async adoptTarget(t,r){let{conn:n}=t.host,o=await n.send("Target.attachToTarget",{targetId:r,flatten:!0}),s=String(o.sessionId??"");await n.send("Page.enable",{},{sessionId:s}),await n.send("Runtime.enable",{},{sessionId:s});let i={targetId:r,sessionId:s};return t.tabs.push(i),t.activeTargetId=r,i}async closeTab(t,r){t.tabs=t.tabs.filter(n=>n.targetId!==r),t.activeTargetId===r&&(t.activeTargetId=t.tabs[t.tabs.length-1]?.targetId??null),await t.host.conn.send("Target.closeTarget",{targetId:r}).catch(()=>{})}async close(t){let r=this.sessions.get(t);if(!r)return!1;this.sessions.delete(t),r.idleTimer&&clearTimeout(r.idleTimer);for(let o of[...r.tabs])await r.host.conn.send("Target.closeTarget",{targetId:o.targetId}).catch(()=>{});return r.tabs=[],[...this.sessions.values()].some(o=>o.host===r.host)||await this.releaseHost(r.mode,r.host),!0}async closeAll(){for(let t of[...this.sessions.keys()])await this.close(t)}async getHost(t){let r=this.hosts.get(t);if(r){let o=await r.catch(()=>null);if(o&&!o.conn.closed)return o;this.hosts.delete(t)}let n=this.deps.connectHost(t);this.hosts.set(t,n);try{let o=await n;return o.conn.onClose(()=>{this.hosts.get(t)===n&&this.hosts.delete(t)}),o}catch(o){throw this.hosts.delete(t),o}}async releaseHost(t,r){if(this.hosts.delete(t),t==="dedicated"){await r.conn.send("Browser.close",{},{timeoutMs:3e3}).catch(()=>{});try{r.child?.kill()}catch{}}r.conn.close()}}});var tr,fee,yl,aB=p(()=>{"use strict";tr=class extends Error{constructor(r,n){super(r);this.code=n;this.name="CdpError"}code},fee=e=>new WebSocket(e),yl=class e{constructor(t){this.socket=t;t.addEventListener("message",n=>this.onMessage(n.data));let r=()=>this.markClosed();t.addEventListener("close",r),t.addEventListener("error",r)}socket;nextId=1;pending=new Map;listeners=new Set;closedFlag=!1;closeHandlers=new Set;static async connect(t,r={}){let n=(r.socketFactory??fee)(t);return await new Promise((o,s)=>{let i=setTimeout(()=>s(new tr("CDP connect timed out")),r.timeoutMs??1e4);n.addEventListener("open",()=>{clearTimeout(i),o()}),n.addEventListener("error",()=>{clearTimeout(i),s(new tr("CDP connect failed"))})}),new e(n)}static fromOpenSocket(t){return new e(t)}get closed(){return this.closedFlag}onClose(t){this.closeHandlers.add(t)}send(t,r={},n={}){if(this.closedFlag)return Promise.reject(new tr("browser connection closed"));let o=this.nextId++,s={id:o,method:t,params:r};return n.sessionId&&(s.sessionId=n.sessionId),new Promise((i,a)=>{let l=setTimeout(()=>{this.pending.delete(o),a(new tr(`${t} timed out`))},n.timeoutMs??3e4);this.pending.set(o,{resolve:i,reject:a,timer:l});try{this.socket.send(JSON.stringify(s))}catch(c){clearTimeout(l),this.pending.delete(o),a(new tr(c instanceof Error?c.message:String(c)))}})}on(t){return this.listeners.add(t),()=>this.listeners.delete(t)}waitFor(t,r){return new Promise((n,o)=>{let s=setTimeout(()=>{i(),o(new tr("timed out waiting for the page"))},r),i=this.on(a=>{t(a)&&(clearTimeout(s),i(),n(a))})})}close(){try{this.socket.close()}catch{}this.markClosed()}markClosed(){if(!this.closedFlag){this.closedFlag=!0;for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(new tr("browser connection closed"));this.pending.clear();for(let t of this.closeHandlers)t()}}onMessage(t){let r;try{r=JSON.parse(typeof t=="string"?t:String(t))}catch{return}if(typeof r.id=="number"){let n=this.pending.get(r.id);if(!n)return;this.pending.delete(r.id),clearTimeout(n.timer),r.error?n.reject(new tr(r.error.message??"CDP error",r.error.code)):n.resolve(r.result??{});return}if(typeof r.method=="string"){let n={method:r.method,params:r.params??{},...r.sessionId?{sessionId:r.sessionId}:{}};for(let o of[...this.listeners])o(n)}}}});function hee(){let e=ho(),t=e.state==="downloading"?` (${eM(e)})`:"";return`Setting up a browser on your computer \u2014 a one-time download of about ${QD} MB${t}. Tell the user it's being set up, wait about 30 seconds, then try the same step again.`}async function lB(e={}){let t=(e.resolve??(()=>go()))();if(t.executable)return t.executable;if(!(e.autoProvision??P().browserAutoProvision!==!1))throw new Mr("No browser is installed on this computer and automatic setup is turned off. The user can run `kynver browser install` on that computer, or install Google Chrome.","chrome_not_found");let n=(e.status??ho)(),o=(e.now??Date.now)();if(n.state==="failed"&&n.failedAt!==null&&o-n.failedAt<gee)throw new Mr(`Kynver couldn't download a browser for this computer just now (${n.error??"unknown error"}). The user can run \`kynver browser install\` on that computer to retry, or install Google Chrome.`,"chrome_not_found");let s=(e.provision??lp)(),i,a=new Promise(l=>{i=setTimeout(()=>l("pending"),e.waitMs??mee),i.unref?.()});try{let l=await Promise.race([s,a]);if(l==="pending")throw s.catch(()=>{}),new Mr(hee(),"browser_installing");return l.executable}catch(l){if(l instanceof Mr)throw l;let c=l instanceof zs?l.message:"Couldn't set up a browser on this computer.";throw new Mr(`${c} The user can run \`kynver browser install\` on that computer to retry, or install Google Chrome.`,"chrome_not_found")}finally{clearTimeout(i)}}var mee,gee,Mr,cB=p(()=>{"use strict";$();ol();cp();mee=2e4,gee=6e4,Mr=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserEnsureError"}code}});import{spawn as yee}from"node:child_process";import{existsSync as HLe,mkdirSync as kee,readFileSync as bee,rmSync as vee}from"node:fs";import{homedir as Ree}from"node:os";import uB from"node:path";function See(e=process.env){return e.KYNVER_BROWSER_PROFILE_DIR?.trim()||uB.join(Ree(),".kynver","browser-profile")}function dB(e=process.env){return(e.KYNVER_BROWSER_CDP_URL?.trim()||P().browserCdpUrl?.trim()||wee).replace(/\/$/,"")}async function pB(e,t={}){let r=t.env??process.env,n=t.platform??process.platform,o=t.allowNoSandbox??P().browserAllowNoSandbox!==!1;if((t.asRoot??tM(n))&&o){let a=await Hb(e,r,n,t,!0);if("wsUrl"in a)return up("off_root"),console.error(`[kynver] browser: running as root, so Chrome started with --no-sandbox (sandbox unavailable on this host). ${JSON.stringify({event:"browser_sandbox_unavailable",reason:"root",fallback:"no-sandbox"})}`),a;throw $b(a.stderrTail)}let i=await Hb(e,r,n,t,!1);if("wsUrl"in i)return up("on"),i;if(n==="linux"&&o&&Jk(i.stderrTail)){let a=await Hb(e,r,n,t,!0);if("wsUrl"in a)return up("off_unavailable"),console.error(`[kynver] browser: Chrome's sandbox is unavailable on this host, so Chrome started with --no-sandbox (set browserAllowNoSandbox: false in ~/.kynver/config.json to refuse instead). ${JSON.stringify({event:"browser_sandbox_unavailable",reason:"unavailable",fallback:"no-sandbox"})}`),a;throw $b(a.stderrTail)}throw $b(i.stderrTail)}function $b(e){let t=rl(e);return t.length>0?new kl(t):Jk(e)?new Error("Chrome couldn't start its security sandbox on this computer, and running without it is turned off (browserAllowNoSandbox). Install Google Chrome system-wide, or allow it in ~/.kynver/config.json."):new Error("Chrome did not start on the Kynver browser profile. Close any Chrome window already using that profile and try again.")}async function Hb(e,t,r,n,o){let s=See(t);kee(s,{recursive:!0});let i=uB.join(s,"DevToolsActivePort");vee(i,{force:!0});let a=op(t,r),l=[`--user-data-dir=${s}`,"--remote-debugging-port=0","--remote-allow-origins=*","--no-first-run","--no-default-browser-check","--disable-features=Translate","--window-size=1280,900",...a?["--headless=new"]:[],...o?["--no-sandbox"]:[],"about:blank"],c=(n.spawnFn??yee)(e,l,{stdio:["ignore","ignore","pipe"],detached:!1});c.unref?.();let u="";c.stderr?.on("data",m=>{u=(u+String(m)).slice(-4e3)}),c.stderr?.unref?.();let d=n.readFile??(m=>bee(m,"utf8")),f=n.sleep??(m=>new Promise(g=>setTimeout(g,m)));for(let m=0;m<15e3;m+=200){try{let[g,h]=d(i).split(/\r?\n/);if(g?.trim()&&h?.trim())return{wsUrl:`ws://127.0.0.1:${g.trim()}${h.trim()}`,child:c}}catch{}if(c.exitCode!==null&&c.exitCode!==void 0)break;await f(200)}try{c.kill()}catch{}return await f(50),{stderrTail:u}}async function fB(e,t=fetch){let r=new AbortController,n=setTimeout(()=>r.abort(),3e3);try{let o=await t(`${e}/json/version`,{signal:r.signal});if(!o.ok)throw new Error(`HTTP ${o.status}`);let s=await o.json();if(typeof s.webSocketDebuggerUrl!="string")throw new Error("no webSocketDebuggerUrl");return s.webSocketDebuggerUrl}finally{clearTimeout(n)}}var wee,kl,mB=p(()=>{"use strict";$();fo();np();ol();qk();wee="http://127.0.0.1:9222";kl=class extends Error{constructor(r){super(`Chrome is missing system libraries: ${r.join(", ")}`);this.missingLibs=r;this.name="ChromeMissingLibsError"}missingLibs}});async function _ee(e){if(e==="attach"){let n=dB(),o;try{o=await fB(n)}catch{throw new ni(`No Chrome is listening for Kynver at ${n}. Start Chrome with --remote-debugging-port=9222 (and its own --user-data-dir), or switch this computer to the dedicated Kynver browser in Settings.`,"attach_unreachable")}return{conn:await yl.connect(o),child:null,mode:e}}let t;try{t=await lB()}catch(n){throw n instanceof Mr?new ni(n.message,n.code):n}let r;try{r=await pB(t)}catch(n){throw n instanceof kl?new ni(ND(n.missingLibs,WD()),"missing_libs"):n}return{conn:await yl.connect(r.wsUrl),child:r.child,mode:e}}function xee(){return Kp??=new Fp({connectHost:_ee}),Kp}async function gB(){Kp&&await Kp.closeAll().catch(()=>{})}function hB(){try{let e=P();e.browserEverEnabled!==!0&&We({...e,browserEverEnabled:!0})}catch{}}function pn(e,t){return{ok:!1,code:e,text:t}}function Cee(e){if(!e||typeof e!="object")return null;let t=e,r=t.policy;if(t.kind!=="browser"||!IL(t.action)||typeof t.conversationId!="string"||!t.conversationId.trim()||t.conversationId.length>200||!r||typeof r!="object"||typeof r.boxId!="string")return null;let n=r.mode==="attach"?"attach":"dedicated";return{kind:"browser",conversationId:t.conversationId.trim(),action:t.action,args:t.args&&typeof t.args=="object"&&!Array.isArray(t.args)?t.args:{},policy:{enabled:r.enabled===!0,mode:n,boxId:r.boxId},...typeof t.approvedFingerprint=="string"&&/^[0-9a-f]{8}$/.test(t.approvedFingerprint)?{approvedFingerprint:t.approvedFingerprint}:{}}}async function yB(e,t){let r=Cee(e);if(!r)return pn("invalid_request","Malformed browser request.");if(t.localDisabled)return pn("disabled","The browser is switched off on this computer (local setting browserDisabled).");if(!r.policy.enabled)return pn("disabled","The browser is turned off for this computer. The user can turn it on in Kynver \u2192 Computers.");if(r.policy.boxId!==t.boxId)return pn("wrong_box","This request reached a different computer than the one the browser is enabled on.");t.onEnabledTurn?.();let n=t.manager??xee();if(r.action==="list_logins")return Kb(r.args,t.agentOsId,t.siteLogins);if(r.action==="close")return{ok:!0,text:await n.close(r.conversationId)?"Closed the browser for this conversation.":"No browser was open for this conversation."};try{let o=await n.getOrCreate(r.conversationId,r.policy.mode);if(!n.recordAction(o))return pn("action_cap","Too many browser actions in a short time. Pause and summarize progress for the user.");let s=r.action==="wait"?Np+5e3:DL,i,a=new Promise(d=>{i=setTimeout(()=>d(pn("timeout",`The browser did not finish "${r.action}" within ${Math.round(s/1e3)}s.`)),s),i.unref?.()}),l={manager:n,session:o,args:r.args,approvedFingerprint:r.approvedFingerprint??null,sleep:t.sleep,agentOsId:t.agentOsId,siteLogins:t.siteLogins},c=r.action,u=await Promise.race([PL(c)?oB(c,l):ZL(c,l),a]).finally(()=>clearTimeout(i));return{...u,text:Dp(u.text)}}catch(o){if(o instanceof ni)return pn(o.code,o.message);let s=o instanceof Error?o.message:String(o);return pn("failed",`Browser action failed: ${s.slice(0,300)}`)}}var ni,Kp,jb=p(()=>{"use strict";Mb();sB();Tb();iB();aB();$();cB();np();fo();mB();ri();ni=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserSetupError"}code};Kp=null});async function kB(e,t,r={}){let n=r.fetchFn??fetch,o=i=>n(`${e.bridgeUrl}/runtime-chat/turns/${encodeURIComponent(t.turnId)}/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({agentOsId:e.agentOsId,events:i})}).catch(()=>{}),s=t.payload?.action;try{let i=await(r.execute??yB)(t.payload,{boxId:e.boxId,agentOsId:e.agentOsId,localDisabled:P().browserDisabled===!0,onEnabledTurn:hB});await o([{seq:0,kind:"final",message:i}]),console.error(JSON.stringify({event:"browser_turn_done",turnId:t.turnId,action:s,ok:i.ok,code:i.code??null}))}catch(i){await o([{seq:0,kind:"error",error:"browser_turn_crashed"}]),console.error(JSON.stringify({event:"browser_turn_error",turnId:t.turnId,action:s,error:i instanceof Error?i.message.slice(0,200):"unknown"}))}}var bB=p(()=>{"use strict";$();jb()});function wB(e){if(!e||typeof e!="object")return null;let t=e.turn;if(!t||typeof t!="object")return null;let r=t.turnId;return typeof r!="string"||!r?null:{turn:t}}function SB(e){if(!e)return!1;let t=e.name;if(t==="AbortError"||t==="TimeoutError")return!0;let r=e instanceof Error?e.message:String(e);return/\b(?:aborted|timed?\s*out|timeout|socket hang up|other side closed|ECONNRESET|UND_ERR_SOCKET)\b/i.test(r)}function RB(e){let t=e?.code;return typeof t=="string"?t:null}function _B(e){if(!e)return!1;if(e instanceof fn)return Eee.has(e.status);let t=RB(e)??RB(e.cause);if(t&&Aee.has(t))return!0;let r=e instanceof Error?e.message:String(e);return/\bHTTP 50[234]\b/.test(r)?!0:/\b(?:fetch failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|connection refused)\b/i.test(r)}function Vb(e){return SB(e)?"aborted":_B(e)?"transient":"server"}function xB(e,t){let r=Vb(e);if(r==="aborted")return t<=Iee?0:Oee;if(r==="transient"){let n=Math.max(0,Math.min(t-1,vB.length-1));return vB[n]}return Pee}function CB(e,t){return e==="aborted"&&t<Tee?{event:"chat_claim_poll_retry",level:"info"}:{event:"chat_claim_error",level:"error"}}var fn,Eee,Aee,Pee,Iee,Oee,vB,$p,Tee,Gb=p(()=>{"use strict";fn=class extends Error{status;constructor(t){super(`claim failed: HTTP ${t}`),this.name="ClaimHttpError",this.status=t}},Eee=new Set([502,503,504]),Aee=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","ENETDOWN","UND_ERR_CONNECT_TIMEOUT"]),Pee=5e3,Iee=3,Oee=1e3,vB=[0,1e3,5e3];$p=class{counts={aborted:0,transient:0,server:0,auth:0,recovered:0};streakKind=null;streak=0;onError(t){let r=Vb(t);return this.bump(r),{kind:r,consecutive:this.streak,backoffMs:xB(t,this.streak)}}onAuthError(){this.bump("auth")}onSuccess(){this.streak>0&&(this.counts.recovered+=1),this.streakKind=null,this.streak=0}snapshot(){return{...this.counts}}bump(t){this.counts[t]+=1,this.streak=this.streakKind===t?this.streak+1:1,this.streakKind=t}},Tee=3});async function Ro(e,t=3,r=n=>new Promise(o=>setTimeout(o,n))){for(let n=0;n<t;n+=1){try{if(await e())return!0}catch{}n<t-1&&await r(200*(n+1))}return!1}var Jb=p(()=>{"use strict"});function EB(e,t,r={}){let n=r.env??process.env,{engine:o,access:s}=yo({provider:e,config:t,env:n});return{access:s.access,folders:s.folders.map(He),source:s.source==="website"?"local":s.source,engine:o,engineVersion:o==="none"?null:(r.version??Zd)(o,n),log:(r.summary??Ap)(),...o==="claude-code"?{claudeCode:{signedIn:(r.signedIn??ep)(n),steps:(r.stepSummary??gL)()}}:{}}}var AB=p(()=>{"use strict";at();Qa();vb();Cp();kb()});function Hp(e){let t=e.appendLog??(s=>{Za(s)}),r=e.now??(()=>new Date),n=0,o=(s,i)=>Bk({at:r().toISOString(),chat:e.chat,turnId:e.turnId,engine:i.engine,access:i.access.access,folder:i.access.workDir,...s});return{sink:((s,i)=>{let a=o(s,i);n+=1,t(a),e.send(a)}),attach(s,i,a){let l=o(s,i);n+=1,t(l),e.send({...l,toolUseId:a.toolUseId,...a.file?{file:a.file}:{}})},get steps(){return n}}}var qb=p(()=>{"use strict";tp()});import{readFileSync as Nee,statSync as Dee}from"node:fs";import PB from"node:path";function Bee(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(!r||typeof r!="object")continue;let n=r;if(n.type!=="tool_use"||n.name!==Mee||typeof n.id!="string")continue;let o=n.input&&typeof n.input=="object"?n.input:{};t.push({toolUseId:n.id,rawPath:typeof o.path=="string"?o.path:""})}return t}function wo(e,t,r){return{step:{kind:"attach",path:e,ok:!1,reason:t,...r!==void 0?{outputBytes:r}:{}}}}function Wee(e,t,r={}){let n=r.stat??Dee,o=r.read??Nee,s=r.maxBytes??Lee,i=e.rawPath.trim();if(!i||i.includes("\0"))return wo(i,"invalid_path");let a=PB.resolve(t.workDir,Tl(i));if(t.access==="off")return wo(a,"access_off");if(!wc(t,a))return wo(a,"outside_folders");let l;try{let c=n(a);if(!c.isFile())return wo(a,"not_a_file");l=c.size}catch{return wo(a,"not_found")}if(l>s)return wo(a,"too_large",l);try{let c=o(a);return{step:{kind:"attach",path:a,outputBytes:c.length,ok:!0},file:{name:PB.basename(a),sizeBytes:c.length,contentBase64:c.toString("base64")}}}catch{return wo(a,"read_failed")}}function IB(e,t,r){let n=Bee(e);for(let o of n){let s=Wee(o,t.access);r.attach(s.step,t,{toolUseId:o.toolUseId,...s.file?{file:s.file}:{}})}return n.length}var Mee,Lee,OB=p(()=>{"use strict";xn();at();Mee="attach_file",Lee=50*1024*1024});function Fee(e){return e>=200&&e<300?"accepted":e===409||e===410?"rejected":e===404||e===405?"unsupported":"unreachable"}function TB(e){return e!=="rejected"}async function NB(e,t,r=fetch){let n=`${e.bridgeUrl}/runtime-chat/turns/${encodeURIComponent(t)}/receipt`;for(let o=0;o<2;o++){let s=new AbortController,i=setTimeout(()=>s.abort(),Uee);try{let a=await $s(e);if(!a.bearer)return{outcome:"unreachable",status:null};let l=await r(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.bearer}`},body:JSON.stringify({agentOsId:e.agentOsId,boxId:a.boxId}),signal:s.signal});return io(e,a,l.status),{outcome:Fee(l.status),status:l.status}}catch{}finally{clearTimeout(i)}}return{outcome:"unreachable",status:null}}var Uee,DB=p(()=>{"use strict";Kd();Uee=4e3});async function Hee(e,t,r=fetch){let n=new AbortController,o=setTimeout(()=>n.abort(),$ee);try{let s=await $s(e);if(!s.bearer)return!1;let i=typeof t=="function"?t(s):t,a=await r(`${e.bridgeUrl}/runtime-chat/heartbeat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.bearer}`},body:JSON.stringify({agentOsId:e.agentOsId,boxId:s.boxId,capabilities:i}),signal:n.signal});return io(e,s,a.status),a.ok}catch{return!1}finally{clearTimeout(o)}}function MB(e){let t=e.intervalMs??Kee,r=!1,n=()=>{r||Hee(e.target,e.capabilities,e.fetchImpl).catch(()=>!1).then(s=>{try{e.onBeat?.(s)}catch{}})};n();let o=setInterval(n,t);return o.unref?.(),()=>{r=!0,clearInterval(o)}}var Kee,$ee,LB=p(()=>{"use strict";Kd();Kee=15e3,$ee=5e3});function Vee(e){return typeof e=="string"&&jee.includes(e)}function WB(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.kind!=="agent-tab"||!Vee(t.engine)||typeof t.sessionKey!="string"||!zee.test(t.sessionKey))return null;let r=typeof t.text=="string"?t.text.slice(0,Gee):"",n=[],o=0;if(Array.isArray(t.attachments))for(let i of t.attachments.slice(0,qee)){if(!i||typeof i!="object")continue;let{name:a,mime:l,contentBase64:c}=i;if(!(typeof a!="string"||typeof c!="string")){if(o+=Math.floor(c.length*3/4),o>Yee)break;n.push({name:a.slice(0,200),mime:typeof l=="string"?l.slice(0,100):"application/octet-stream",contentBase64:c})}}if(!r.trim()&&n.length===0)return null;let s=typeof t.styleNote=="string"?t.styleNote.trim().slice(0,Jee):"";return{kind:"agent-tab",engine:t.engine,sessionKey:t.sessionKey,text:r,attachments:n,...t.computerAccess!==void 0?{computerAccess:t.computerAccess}:{},...s?{styleNote:s}:{}}}var jee,BB,Gee,Jee,qee,Yee,zee,UB=p(()=>{"use strict";jee=["hermes","openclaw","claude-code","grok-bot"],BB={hermes:"Hermes",openclaw:"OpenClaw","claude-code":"Claude Code","grok-bot":"Grok Bot"};Gee=32e3,Jee=4e3,qee=5,Yee=20*1024*1024,zee=/^[A-Za-z0-9_.:-]{8,128}$/});import{existsSync as Xee}from"node:fs";import{homedir as Qee,platform as Zee}from"node:os";import mn from"node:path";function ete(e,t,r={}){if(t==="darwin")return mn.join(e,"Library","Application Support","Grok Bot");if(t==="win32"){let s=r.APPDATA?.trim();return mn.join(s||mn.join(e,"AppData","Roaming"),"Grok Bot")}let n=r.XDG_CONFIG_HOME?.trim(),o=n&&mn.isAbsolute(n)?n:mn.join(e,".config");return mn.join(o,"Grok Bot")}function tte(e){return[mn.join("/opt","Grok Bot","grok-bot"),mn.join(e,".local","bin","grok-bot")]}async function FB(e={}){let t=e.home??Qee(),r=e.platform??Zee(),n=e.env??process.env,o=e.exists??Xee,s=e.versionOf??(async()=>null),i=r==="linux"?tte(t):[],a=await s("grok-bot");if(!a){for(let c of i)if(o(c)&&(a=await s(c),a))break}return{installed:!!a||o(ete(t,r,n))||i.some(c=>o(c)),version:a}}var KB=p(()=>{"use strict"});async function jp(e={}){let t=await FB(e);return t.installed?{status:"not_enabled",version:t.version,detail:nte}:{status:"not_installed",version:null,detail:rte}}var rte,nte,Yb=p(()=>{"use strict";KB();rte="Grok Bot is not installed on this computer.",nte="Grok Bot is installed. Chat from Kynver is not connected."});function HB(){return ote}var $B,zb,ote,jB=p(()=>{"use strict";Yb();$B="grok_bot_no_chat_api",zb=class extends Error{code=$B;constructor(){super(`${$B}: Grok Bot has no connection that can take a message and return a reply.`),this.name="GrokBotChatUnavailableError"}},ote={id:"none",probe:e=>jp(e),relay(){return Promise.reject(new zb)}}});import{existsSync as ste,mkdirSync as ite,readFileSync as ate,renameSync as lte,writeFileSync as cte}from"node:fs";import{homedir as ute}from"node:os";import GB from"node:path";function dte(e=ute()){return GB.join(e,".kynver","agent-tab-sessions.json")}function JB(e=dte(),t=Date.now){let r=()=>{try{if(!ste(e))return{};let o=JSON.parse(ate(e,"utf8"));if(!o||typeof o!="object"||Array.isArray(o))return{};let s={};for(let[i,a]of Object.entries(o)){let l=a;l&&typeof l.id=="string"&&typeof l.at=="number"&&(s[i]={id:l.id,at:l.at})}return s}catch{return{}}},n=o=>{let s=Object.keys(o);s.length>VB&&s.sort((i,a)=>o[i].at-o[a].at).slice(0,s.length-VB).forEach(i=>delete o[i]);try{ite(GB.dirname(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;cte(i,`${JSON.stringify(o)}
|
|
507
|
+
`,{mode:384}),lte(i,e)}catch{}};return{get:o=>r()[o]?.id??null,remember:(o,s)=>{let i=r();i[o]?.id!==s&&(i[o]={id:s,at:t()},n(i))},forget:o=>{let s=r();o in s&&(delete s[o],n(s))}}}var VB,qB=p(()=>{"use strict";VB=500});import{existsSync as YB,readFileSync as pte}from"node:fs";import{homedir as zB}from"node:os";import So from"node:path";function XB(e){try{return YB(e)?pte(e,"utf8"):null}catch{return null}}function fte(e){let t=(e??"").trim().toLowerCase();return t==="localhost"||t==="::1"||t==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(t)?t==="::1"?"[::1]":t:"127.0.0.1"}function QB(e,t){let r=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):NaN;return Number.isInteger(r)&&r>0&&r<65536?r:t}function mte(e){let t={};for(let r of e.split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(n);if(!o)continue;let s=o[2].trim();s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")?s=s.slice(1,-1):s=s.replace(/\s+#.*$/,""),t[o[1]]=s}return t}function gte(e){return/^(1|true|yes|on)$/i.test((e??"").trim())}function ZB(e={}){let r=(e.env??process.env).HERMES_HOME?.trim();return r?So.resolve(r):So.join(e.home??zB(),".hermes")}function hte(e={}){return So.join(ZB(e),".env")}function Vp(e={}){let t=e.readFile??XB,r=hte(e),n=t(r),o=n===null?{}:mte(n),s=o.API_SERVER_KEY?.trim()||null;return{baseUrl:`http://${fte(o.API_SERVER_HOST)}:${QB(o.API_SERVER_PORT,8642)}`,key:s,enabled:gte(o.API_SERVER_ENABLED)||s!==null&&o.API_SERVER_ENABLED===void 0,configured:n!==null||YB(ZB(e)),configPath:r}}function yte(e){try{return JSON.parse(e)}catch{}let t="",r=0;for(;r<e.length;){let n=e[r];if(n==='"'||n==="'"){let o=n,s=r+1,i="";for(;s<e.length&&e[s]!==o;){if(e[s]==="\\"&&s+1<e.length){i+=e[s]+e[s+1],s+=2;continue}i+=o==="'"&&e[s]==='"'?'\\"':e[s],s+=1}t+=`"${i}"`,r=s+1;continue}if(n==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
|
|
508
|
+
`;)r+=1;continue}if(n==="/"&&e[r+1]==="*"){let o=e.indexOf("*/",r+2);r=o===-1?e.length:o+2;continue}t+=n,r+=1}t=t.replace(/,\s*([}\]])/g,"$1").replace(/([{,]\s*)([A-Za-z_$][A-Za-z0-9_$-]*)\s*:/g,'$1"$2":');try{return JSON.parse(t)}catch{return null}}function bl(e,t){let r=e;for(let n of t){if(!r||typeof r!="object"||Array.isArray(r))return;r=r[n]}return r}function vl(e){return typeof e=="string"&&e.trim()?e.trim():null}function kte(e={}){let t=e.env??process.env,r=t.OPENCLAW_CONFIG_PATH?.trim();if(r)return So.resolve(r);let n=t.OPENCLAW_STATE_DIR?.trim();return So.join(n?So.resolve(n):So.join(e.home??zB(),".openclaw"),"openclaw.json")}function Gp(e={}){let t=e.env??process.env,r=e.readFile??XB,n=kte(e),o=r(n),s=o===null?null:yte(o),i=vl(bl(s,["gateway","auth","mode"])),a=(i==="password"?vl(bl(s,["gateway","auth","password"]))??vl(t.OPENCLAW_GATEWAY_PASSWORD):vl(bl(s,["gateway","auth","token"]))??vl(t.OPENCLAW_GATEWAY_TOKEN))??(i==="none"?"":null);return{baseUrl:`http://127.0.0.1:${QB(t.OPENCLAW_GATEWAY_PORT??bl(s,["gateway","port"]),18789)}`,key:a,enabled:bl(s,["gateway","http","endpoints","chatCompletions","enabled"])===!0,configured:o!==null,configPath:n}}var Xb=p(()=>{"use strict"});function eW(e){let t=null,r=[];for(let o of e){if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),i=s===-1?o:o.slice(0,s),a=s===-1?"":o.slice(s+1).replace(/^ /,"");i==="event"?t=a:i==="data"&&r.push(a)}if(r.length===0)return null;let n=r.join(`
|
|
509
|
+
`);try{return{event:t,data:JSON.parse(n)}}catch{return{event:t,data:n}}}async function*tW(e){let t=e.getReader(),r=new TextDecoder,n="",o=[];try{for(;;){let{done:i,value:a}=await t.read();if(i)break;n+=r.decode(a,{stream:!0});let l;for(;(l=n.indexOf(`
|
|
510
|
+
`))!==-1;){let c=n.slice(0,l).replace(/\r$/,"");if(n=n.slice(l+1),c===""){let u=eW(o);o=[],u&&(yield u)}else o.push(c)}}n+=r.decode(),n&&o.push(n.replace(/\r$/,""));let s=eW(o);s&&(yield s)}finally{t.releaseLock()}}var rW=p(()=>{"use strict"});function Qb(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>{if(typeof t=="string")return t;if(!t||typeof t!="object")return"";let r=t;return typeof r.text=="string"&&(r.type===void 0||r.type==="text"||r.type==="output_text")?r.text:""}).join(""):""}function nW(e){if(typeof e=="string"&&e.trim())return e.trim().slice(0,300);if(!e||typeof e!="object")return null;let t=e.message;return typeof t=="string"&&t.trim()?t.trim().slice(0,300):null}function oW(e){if(!e||typeof e!="object")return"";let t=e;return typeof t.output_text=="string"?t.output_text:Array.isArray(t.output)?t.output.map(r=>{if(!r||typeof r!="object")return"";let n=r;return n.type!=="message"||n.role!==void 0&&n.role!=="assistant"?"":Qb(n.content)}).join(""):""}function Zb(e,t){if(!t||typeof t!="object")return null;let r=t,n=e??(typeof r.type=="string"?r.type:null);if(n==="response.output_text.delta")return{delta:typeof r.delta=="string"?r.delta:"",full:null,finishReason:null,error:null};if(n==="response.completed")return{delta:"",full:oW(r.response)||null,finishReason:"stop",error:null};if(n==="response.failed"||n==="error"){let d=r.response;return{delta:"",full:null,finishReason:"error",error:nW(d?.error??r.error??r.message)??"the agent reported an error"}}if(e&&e!=="message")return null;let o=r.error!==void 0&&r.error!==null?nW(r.error)??"the agent reported an error":null,i=(Array.isArray(r.choices)?r.choices:[])[0]??null,a=Qb(i?.delta?.content)||(typeof i?.text=="string"?i.text:""),l=i?.message?.content,c=l==null?null:Qb(l),u=typeof i?.finish_reason=="string"?i.finish_reason:null;return!a&&c===null&&!u&&!o?null:{delta:a,full:c,finishReason:u,error:o}}function sW(e){if(!e||typeof e!="object")return null;let t=e;return t.object==="response"||Array.isArray(t.output)||typeof t.output_text=="string"?{delta:"",full:oW(t),finishReason:"stop",error:null}:Zb(null,e)}var iW=p(()=>{"use strict"});function aW(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?t.text:"").join(""):""}function bte(e,t){if(!Array.isArray(e)||e.length===0)return null;let r=lW(t).slice(0,200),n=null;for(let o=e.length-1;o>=0;o-=1){let s=e[o];if(!(!s||typeof s!="object")){if(s.role==="assistant"){let i=aW(s.content);n===null&&i.trim()&&(n=i);continue}if(s.role!=="tool"&&s.role==="user")return n===null?null:!r||lW(aW(s.content)).includes(r)?n:null}}return null}async function cW(e){let t=e.fetchFn??fetch,r=new AbortController,n=setTimeout(()=>r.abort(),5e3),o=()=>r.abort();e.signal?.addEventListener("abort",o,{once:!0});try{let s=await t(`${e.endpoint.baseUrl}/api/sessions/${encodeURIComponent(e.sessionId)}/messages`,{headers:e.endpoint.key?{Authorization:`Bearer ${e.endpoint.key}`}:{},signal:r.signal});if(!s.ok)return await s.body?.cancel().catch(()=>{}),null;let i=await s.json().catch(()=>null);return bte(i?.data,e.sentText)}catch{return null}finally{clearTimeout(n),e.signal?.removeEventListener("abort",o)}}var lW,uW=p(()=>{"use strict";lW=e=>e.replace(/\s+/g," ").trim()});function vte(e=process.env){let t=e.KYNVER_OPENCLAW_AGENT?.trim();return t?`openclaw/${t}`:"openclaw/default"}function dW(e,t){let r=t.filter(n=>n.imageDataUrl);return r.length===0?e:[{type:"text",text:e},...r.map(n=>({type:"image_url",image_url:{url:n.imageDataUrl}}))]}function Rte(e,t){return t===401||t===403?new Error(`${e}_auth_failed: the local API refused the key in its config`):t===404?new Error(`${e}_api_off: the local chat API is not switched on`):t===429?new Error(`${e}_busy: the agent is busy, try again shortly`):new Error(`${e}_http_${t}`)}function wte(e,t,r,n){let o=`Conversation opened from Kynver chat (${t}).`,s=r?.trim();return s?e==="hermes"?`${s}
|
|
447
511
|
|
|
448
|
-
${o}`:s:e==="hermes"&&!n?o:null}async function
|
|
512
|
+
${o}`:s:e==="hermes"&&!n?o:null}async function pW(e,t){let r=e.fetchFn??fetch,n={"Content-Type":"application/json",Accept:"text/event-stream"};e.endpoint.key&&(n.Authorization=`Bearer ${e.endpoint.key}`);let o=[],s,i=wte(e.engine,e.sessionKey,e.styleNote,t!==null);i&&o.push({role:"system",content:i}),e.engine==="hermes"?(t&&(n["X-Hermes-Session-Id"]=t),o.push({role:"user",content:dW(e.text,e.attachments)}),s={model:"hermes-agent",stream:!0,messages:o}):(o.push({role:"user",content:dW(e.text,e.attachments)}),s={model:vte(),stream:!0,user:`kynver:${e.sessionKey}`,messages:o});try{return await r(`${e.endpoint.baseUrl}/v1/chat/completions`,{method:"POST",headers:n,body:JSON.stringify(s),signal:e.signal})}catch(a){throw e.signal?.aborted?new Error(`${e.engine}_aborted`):new Error(`${e.engine}_unreachable: nothing answered on ${e.endpoint.baseUrl}`,{cause:a})}}async function fW(e){let t=e.now??Date.now,r=e.engine==="hermes"?e.sessions.get(e.sessionKey):null,n=await pW(e,r);if(r&&(n.status===400||n.status===404||n.status===409)&&(await n.body?.cancel().catch(()=>{}),e.sessions.forget(e.sessionKey),n=await pW(e,null)),!n.ok||!n.body)throw await n.body?.cancel().catch(()=>{}),Rte(e.engine,n.status);let o=e.engine==="hermes"&&(n.headers.get("x-hermes-session-id")?.trim()||r)||null;e.engine==="hermes"&&o&&e.sessions.remember(e.sessionKey,o);let s="",i=!1,a=null,l=null,c=f=>{if(f.error){if(e.engine==="openclaw"&&s.trim()&&Ste.test(f.error))return"stop";throw new Error(`${e.engine}_failed: ${f.error}`)}return f.delta&&(s+=f.delta,e.sink.onDelta(f.delta)),f.full!==null&&f.full.trim()&&(l=f.full),f.finishReason&&(a=f.finishReason),"continue"},u=n.headers.get("content-type")??"";if(/application\/json/i.test(u)){let f=await n.json().catch(()=>null),m=sW(f);m&&c(m)}else{let f=new Map;for await(let m of tW(n.body)){if(m.data==="[DONE]")break;if(m.event==="hermes.tool.progress"){i=!0;let h=m.data??{},y=typeof h.toolCallId=="string"?h.toolCallId:String(h.tool??""),v=[h.emoji,h.label??h.tool].filter(k=>typeof k=="string"&&k).join(" ").slice(0,300);if(h.status==="running")f.set(y,{at:t(),label:v||"tool"}),e.sink.onTool({label:v||"tool",status:"running",durationMs:null});else{let k=f.get(y);f.delete(y),e.sink.onTool({label:k?.label??(v||String(h.tool??"tool")),status:"completed",durationMs:k===void 0?null:t()-k.at})}continue}if(m.event==="approval.request"){let h=m.data??{},y=[h.description,h.command].find(v=>typeof v=="string"&&v);e.sink.onTool({label:`Waiting for approval in ${e.engine==="hermes"?"Hermes":"OpenClaw"}${y?`: ${y.slice(0,200)}`:""}`,status:"approval",durationMs:null});continue}let g=Zb(m.event,m.data);if(g&&c(g)==="stop")break}}let d=l;if(!s.trim()&&d&&(s=d,e.sink.onDelta(d)),!s.trim()&&a==="error")throw new Error(`${e.engine}_failed: the agent stopped with an error \u2014 check its logs`);if(!s.trim()&&e.engine==="hermes"&&o){let f=await cW({endpoint:e.endpoint,sessionId:o,sentText:e.text,fetchFn:e.fetchFn,signal:e.signal});if(f&&f.trim())return e.sink.onDelta(f),{text:f,sessionId:o,recovered:!0}}if(!s.trim()&&!i)throw new Error(`${e.engine}_empty_reply: the agent sent back nothing \u2014 check its model sign-in and logs`);if(!s.trim())throw new Error(`${e.engine}_empty_reply: the agent ran its steps but sent back no answer`);return{text:s,sessionId:o}}var Ste,mW=p(()=>{"use strict";rW();iW();uW();Ste=/cannot be represented as an append-only response stream/i});import{mkdirSync as _te,readFileSync as xte,realpathSync as Cte,statSync as Ete,writeFileSync as Ate}from"node:fs";import{homedir as ev}from"node:os";import rr from"node:path";function rv(e=ev()){return rr.join(e,".kynver","agent-tabs","inbox")}function gW(e,t=80){return e.replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^\.+/,"_").slice(0,t)||"file"}function yW(e,t,r={}){if(t.length===0)return[];let n=rr.join(r.root??rv(),gW(e,120));_te(n,{recursive:!0,mode:448});let o=(r.now??Date.now)();return t.map((s,i)=>{let a=Buffer.from(s.contentBase64,"base64"),l=rr.join(n,`${o}-${i}-${gW(s.name,120)}`);Ate(l,a,{mode:384});let c=/^image\/(png|jpe?g|gif|webp|bmp|heic|heif)$/i.test(s.mime);return{name:s.name,mime:s.mime,path:l,imageDataUrl:c?`data:${s.mime.toLowerCase()};base64,${s.contentBase64}`:null}})}function qp(e,t){if(t.length===0)return e;let r=t.map(n=>`[Attached file "${n.name}" (${n.mime}) saved on this computer at ${n.path}]`);return[e.trim(),...r].filter(Boolean).join(`
|
|
449
513
|
|
|
450
|
-
`)}function
|
|
514
|
+
`)}function nv(e){let t=[];return{text:e.replace(Pte,(n,o,s,i,a)=>{let l=String(o??s??i??a??"").replace(/[),.;:!?\]]+$/,"");return l?(!t.includes(l)&&t.length<Jp&&t.push(l),""):n}).replace(/[ \t]+\n/g,`
|
|
451
515
|
`).replace(/\n{3,}/g,`
|
|
452
516
|
|
|
453
|
-
`).trim(),paths:t}}function
|
|
517
|
+
`).trim(),paths:t}}function hW(e,t=ev()){let r=rr.basename(e);if(Ite.test(r))return"credential_file";let n=rr.relative(t,e);if(!n.startsWith("..")&&!rr.isAbsolute(n)){let o=n.split(rr.sep).join("/");if(qd.some(s=>o===s))return"credential_file";if(Jd.some(s=>o===s||o.startsWith(`${s}/`)))return"private_folder"}return null}function Ote(e,t){return e==="~"?t:e.startsWith("~/")||e.startsWith("~\\")?rr.join(t,e.slice(2)):e}function ov(e,t={}){let r=t.home??ev(),n=rr.resolve(Ote(e,r)),o={path:n,name:rr.basename(n)},s=hW(n,r);if(s)return{...o,ok:!1,reason:s,sizeBytes:null,contentBase64:null};try{let i=Cte(n),a=hW(i,r);if(a)return{...o,ok:!1,reason:a,sizeBytes:null,contentBase64:null};let l=Ete(i);if(!l.isFile())return{...o,ok:!1,reason:"not_a_file",sizeBytes:null,contentBase64:null};if(l.size>tv)return{...o,ok:!1,reason:"too_large",sizeBytes:l.size,contentBase64:null};let c=xte(i);return{...o,ok:!0,reason:null,sizeBytes:c.length,contentBase64:c.toString("base64")}}catch{return{...o,ok:!1,reason:"not_found",sizeBytes:null,contentBase64:null}}}var tv,Jp,Pte,Ite,Yp=p(()=>{"use strict";Yd();yb();tv=50*1024*1024,Jp=10;Pte=/MEDIA:\s*(?:"([^"\n]+)"|'([^'\n]+)'|`([^`\n]+)`|((?:~|\/|[A-Za-z]:[\\/])[^\s"'`<>]*))/g;Ite=hb(js)});import{chmodSync as Nte,copyFileSync as Dte,mkdirSync as Mte}from"node:fs";import sv from"node:path";function Lte(e){let t=e?.trim();return t?`${kW}
|
|
454
518
|
|
|
455
|
-
${t}`:
|
|
519
|
+
${t}`:kW}function Bte(e){let t=e.config??P();return{engine:"claude-code",access:Jo({engine:"claude-code",local:{chatComputerAccess:t.chatComputerAccess,chatWorkFolders:t.chatWorkFolders},website:vc(e.payloadAccess,e.boxId),home:e.home})}}function Ute(e,t){if(t.access==="full"||t.access==="off")return e;let r=sv.join(t.workDir,Wte);return e.map(n=>{if(wc(t,n.path))return n;Mte(r,{recursive:!0,mode:448});let o=sv.join(r,sv.basename(n.path));return Dte(n.path,o),Nte(o,384),{...n,path:o}})}function Fte(e){return e.map(t=>t&&typeof t=="object"&&t.type==="text"?String(t.text??""):"").join("")}async function bW(e){let t=Bte(e);if(t.access.access==="off")throw new Error("claude_code_access_off: computer access for chat is off for this computer \u2014 choose a folder (or full access) on the Computers page to use the Claude Code tab");let r=e.config??P(),n=e.env??process.env,o=qp(e.text,Ute(e.attachments,t.access)),s=await(e.run??Ip)({payload:{system:Lte(e.styleNote),tools:[],messages:[{role:"user",content:o}],maxTokens:32e3,executionMode:"agent"},model:n.KYNVER_AGENT_TAB_CLAUDE_MODEL?.trim()??"",onDelta:e.onDelta,step:{session:e.sessionKey,timeLeftMs:48e4},access:t.access,signal:e.signal,turnId:e.turnId,onActivity:i=>e.onActivity(i,t),env:n,sessions:e.sessions,config:{chatFolderSandbox:r.chatFolderSandbox,chatFolderSandboxDomains:r.chatFolderSandboxDomains},...e.spawnTarget?{spawnTarget:e.spawnTarget}:{},...e.tempRoot?{tempRoot:e.tempRoot}:{},...e.sandboxRuntime?{sandboxRuntime:e.sandboxRuntime}:{},...e.egressProxy?{egressProxy:e.egressProxy}:{}});return{text:Fte(s.content)}}var kW,Wte,vW=p(()=>{"use strict";$();xn();Sb();Ep();Yp();kW="You are the user's own Claude Code, reached from a tab in their Kynver chat on the web. Work exactly as you would in their terminal, in the folder this session started in. Your replies are shown in a chat window, so keep them readable; there are no Kynver tools in this conversation.";Wte=".kynver-attachments"});import zp from"node:path";import{homedir as Kte}from"node:os";function Jte(e){let t=e.replace(/[\r\n]/g,""),r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-r)}function qte(e){return e.replace(/[ \t]+\n/g,`
|
|
456
520
|
`).replace(/\n{3,}/g,`
|
|
457
521
|
|
|
458
|
-
`).trim()}function
|
|
459
|
-
`,{encoding:"utf8",mode:384})}catch{}}var
|
|
522
|
+
`).trim()}function RW(e){let t=[];return e.includes("data:image/")?{text:e.replace($te,(n,o,s,i)=>{if(t.length>=Jp)return n;let a=s.toLowerCase(),l=`image-${t.length+1}.${Hte[a]??"png"}`,c=Jte(i);return c>tv?(t.push({source:"inline_image",path:l,name:l,ok:!1,reason:"too_large",sizeBytes:c,contentBase64:null}),""):(t.push({source:"inline_image",path:l,name:l,ok:!0,reason:null,sizeBytes:c,contentBase64:i.replace(/[\r\n]/g,"")}),"")}),files:t}:{text:e,files:t}}function Yte(e){let t=e.replace(Gte,n=>" ".repeat(n.length)),r=[];for(let n of t.matchAll(Vte)){let o=n[1].replace(/[),.;:!?\]]+$/,"");r.includes(o)||r.push(o)}return r}function zte(e,t){return e.startsWith("~/")?zp.join(t,e.slice(2)):e}function Xte(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(String.raw`^[ \t]*(?:[-*•][ \t]+)?(?:[A-Za-z ]{1,30}:[ \t]*)?\`?${r}\`?[ \t]*[.!]?[ \t]*$`,"gm");return e.replace(n,"")}function wW(e,t={}){let r=t.home??Kte(),n=zp.resolve(t.inboxRoot??rv(r)),o=[],s=()=>o.length<Jp,i=RW(e);o.push(...i.files);let a=nv(i.text);for(let u of a.paths){if(!s())break;o.push({source:"tag",...ov(u,{home:r})})}let l=a.text,c=new Set(o.map(u=>u.path));for(let u of Yte(l)){if(!s())break;let d=zp.resolve(zte(u,r));if(c.has(d)||d===n||d.startsWith(`${n}${zp.sep}`))continue;let f=ov(u,{home:r});!f.ok&&f.reason!=="too_large"||(c.add(f.path),o.push({source:"path",...f}),f.ok&&(l=Xte(l,u)))}return{text:qte(l),files:o}}function SW(e){return nv(RW(e).text).text}var $te,Hte,jte,Vte,Gte,_W=p(()=>{"use strict";Yp();$te=/!\[([^\]\n]{0,200})\]\(\s*data:(image\/[a-z0-9.+-]{1,40});base64,([A-Za-z0-9+/=\r\n]+)\s*\)/gi,Hte={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/bmp":"bmp"},jte=["mp4","mov","m4v","webm","mkv","mp3","m4a","wav","ogg","oga","opus","aac","flac","png","jpg","jpeg","gif","webp","heic","pdf"],Vte=new RegExp(String.raw`(?<![\w/:.~-])((?:~\/|\/)[^\s"'\`<>()\[\]{}|]*?\.(?:${jte.join("|")}))(?![\w/-])`,"gi"),Gte=/```[\s\S]*?(?:```|$)/g});function CW(e){let t=e instanceof Error?e.message:String(e);return/^([a-z][a-z0-9_]{2,60})(?::|$)/.exec(t)?.[1]??"agent_tab_failed"}function Xp(e,t,r=()=>new Date){let n={at:r().toISOString(),ok:t.ok,durationMs:Math.max(0,Math.round(t.durationMs)),error:t.ok?null:(t.error??"agent_tab_failed").slice(0,60)};return xW.set(e,n),n}function Qp(e){return xW.get(e)??null}var xW,iv=p(()=>{"use strict";xW=new Map});import{appendFileSync as Qte,mkdirSync as Zte}from"node:fs";import{homedir as ere}from"node:os";import EW from"node:path";function tre(e=ere()){return EW.join(e,".kynver","logs","agent-tabs.jsonl")}function AW(e,t=tre()){try{Zte(EW.dirname(t),{recursive:!0});let r={...e,...e.label?{label:e.label.slice(0,300)}:{}};Qte(t,`${JSON.stringify(r)}
|
|
523
|
+
`,{encoding:"utf8",mode:384})}catch{}}var PW=p(()=>{"use strict"});async function IW(e,t,r={}){let n=r.now??(()=>new Date),o=r.log??AW,s=WB(t.payload);if(!s){await e([{seq:0,kind:"error",error:"agent_tab_bad_payload"}]).catch(()=>!1);return}let i=s.engine,a=n().getTime(),l=0,c=!1,u=new AbortController,d=new uo,f=b=>{c||d.track(e([{seq:l++,...b}]).then(_=>(_||(c=!0,u.abort()),_),()=>!1))},m=new ln(b=>f({kind:"delta",text:b}),r.flushFloorMs),g=b=>{m.flush(),f({kind:"activity",activity:b})},h=b=>{let _={at:n().toISOString(),chat:null,turnId:t.turnId,kind:"tool",engine:i,access:"own",command:b.label,folder:"",durationMs:b.durationMs,ok:b.status!=="approval",...b.status==="running"?{reason:"started"}:{},...b.status==="approval"?{reason:"awaiting_approval"}:{}};g(_),b.status!=="running"&&o({at:_.at,turnId:t.turnId,engine:i,kind:"tool",label:b.label,ok:_.ok,durationMs:b.durationMs})},y=Hp({turnId:t.turnId,chat:null,send:b=>g(b),now:n}),v="",k=!1;try{if(i==="grok-bot"){let N=await(r.grokBot??HB()).relay({sessionKey:s.sessionKey,text:s.text});v=N.text,m.push(N.text),m.close(),await d.drain();let A=n().getTime()-a,O=N.text.trim();if(!O)throw new Error("grok_bot_empty_reply");Xp(i,{ok:!0,durationMs:A},n),o({at:n().toISOString(),turnId:t.turnId,engine:i,kind:"turn",ok:!0,durationMs:A});let W=l++;await Ro(()=>c?e([{seq:W,kind:"error",error:"turn_stream_aborted"}]).catch(()=>!1):e([{seq:W,kind:"final",message:{content:[{type:"text",text:O}],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:i,media:0}}}]).catch(()=>!1));return}let b=r.sessions??JB(),_=yW(s.sessionKey,s.attachments,{root:r.inboxRoot}),S;if(i==="claude-code")S=(await(r.runClaudeCode??bW)({sessionKey:s.sessionKey,text:s.text,styleNote:s.styleNote,attachments:_,payloadAccess:s.computerAccess,boxId:t.boxId,sessions:b,onDelta:A=>{v+=A,m.push(A)},onActivity:y.sink,signal:u.signal,turnId:t.turnId,home:r.home})).text||v;else{let N=(r.endpoint??(O=>O==="hermes"?Vp():Gp()))(i),A=await fW({engine:i,endpoint:N,sessionKey:s.sessionKey,text:qp(s.text,_.filter(O=>!O.imageDataUrl)),styleNote:s.styleNote,attachments:_,sessions:b,signal:u.signal,fetchFn:r.fetchFn,sink:{onDelta:O=>{v+=O,m.push(O)},onTool:h}});S=A.text,k=A.recovered===!0}let R=wW(S,{home:r.home,inboxRoot:r.inboxRoot});R.files.forEach((N,A)=>{let O=n().toISOString();g({at:O,chat:null,turnId:t.turnId,kind:"attach",engine:i,access:"own",path:N.path,folder:"",ok:N.ok,...N.reason?{reason:N.reason}:{},...!N.ok&&N.sizeBytes!==null?{sizeBytes:N.sizeBytes}:{},toolUseId:`media-${A}`,...N.ok&&N.contentBase64?{file:{name:N.name,sizeBytes:N.sizeBytes,contentBase64:N.contentBase64}}:{}}),o({at:O,turnId:t.turnId,engine:i,kind:"attach",path:N.path,ok:N.ok,reason:N.reason})}),m.close(),await d.drain();let w=n().getTime()-a;Xp(i,{ok:!0,durationMs:w},n),o({at:n().toISOString(),turnId:t.turnId,engine:i,kind:"turn",ok:!0,durationMs:w,...k?{reason:"reply_read_from_session"}:{}});let L=l++;await Ro(()=>c?e([{seq:L,kind:"error",error:"turn_stream_aborted"}]).catch(()=>!1):e([{seq:L,kind:"final",message:{content:[{type:"text",text:R.text}],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:i,media:R.files.filter(N=>N.ok).length}}}]).catch(()=>!1))}catch(b){m.close(),await d.drain();let _=b instanceof Error?b.message:String(b),S=CW(b),R=n().getTime()-a;if(Xp(i,{ok:!1,durationMs:R,error:S},n),o({at:n().toISOString(),turnId:t.turnId,engine:i,kind:"turn",ok:!1,durationMs:R,reason:S}),c)return;let w=l++;if(v.trim()){let L=`
|
|
460
524
|
|
|
461
|
-
_${nee[i]} stopped before finishing (${S})._`;await Ys(()=>e([{seq:w,kind:"final",message:{content:[{type:"text",text:kB(v)+W}],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:i,media:0,error:S}}}]).catch(()=>!1))}else await Ys(()=>e([{seq:w,kind:"error",error:_.slice(0,1500)}]).catch(()=>!1))}}var nee,CB=p(()=>{"use strict";Fd();lk();yb();kb();UL();HL();bb();cB();gB();Tp();bB();Pb();_B();nee={hermes:"Hermes",openclaw:"OpenClaw","claude-code":"Claude Code"}});import{execFile as oee}from"node:child_process";async function dee(e){let t=EB.get(e);if(t&&Date.now()-t.at<iee)return t.version;let r=await new Promise(n=>{try{let[o,s]=se(e,["--version"]);oee(o,s,X({encoding:"utf8",timeout:5e3}),(i,a,l)=>{if(i)return n(null);n(`${a??""} ${l??""}`.match(uee)?.[0]??null)})}catch{n(null)}});return EB.set(e,{at:Date.now(),version:r}),r}async function AB(e,t,r,n=aee){let o=new AbortController,s=setTimeout(()=>o.abort(),n);try{let i=await e(t,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:o.signal});return await i.body?.cancel().catch(()=>{}),i.status}catch{return null}finally{clearTimeout(s)}}function Ib(e){let t=IB.get(e)??null,r=Dp(e),n=r?.ok?Date.parse(r.at):NaN,o=[t,Number.isFinite(n)?n:null].filter(s=>s!==null);return o.length?Math.max(...o):null}function Zt(e,t,r,n){let o=Ib(e);return{engine:e,status:t,version:r,detail:n,lastRoundTrip:Dp(e),lastReadyAt:o===null?null:new Date(o).toISOString()}}async function PB(e,t,r,n,o=Date.now){if(!t.configured&&!r)return null;let s=e==="hermes"?"Hermes":"OpenClaw";if(!t.enabled)return Zt(e,"not_enabled",r,`${s}'s local chat API is off`);if(t.key===null)return Zt(e,"no_key",r,`${s}'s local chat API has no key set`);let i=`${t.baseUrl}/v1/models`,a=await AB(n,i,t.key||null)??await AB(n,i,t.key||null,lee);if(a===null){let l=Ib(e);return l!==null&&o()-l<cee?Zt(e,"ready",r,null):Zt(e,"unreachable",r,`${s} is not answering on ${t.baseUrl} \u2014 is its gateway running?`)}return a===401||a===403?Zt(e,"no_key",r,`${s} refused the key in its config (HTTP ${a})`):a===404?Zt(e,"not_enabled",r,`${s} is running but its chat API is not switched on`):(IB.set(e,o()),Zt(e,"ready",r,null))}function pee(e){let{version:t,signedIn:r}=(e.claudeCode??(()=>({version:Bd("claude-code",e.env),signedIn:Wd(e.env)})))();return t?r?(e.config??E()).chatComputerAccess==="off"?Zt("claude-code","access_off",t,"Computer access for chat is off on this computer"):Zt("claude-code","ready",t,null):Zt("claude-code","not_signed_in",t,"Claude Code is installed but not signed in"):null}async function fee(e={}){let t=e.env??process.env,r=e.fetchFn??fetch,n=e.versionOf??dee,o=t.KYNVER_HERMES_BIN?.trim()||t.HERMES_BIN?.trim()||"hermes",s=t.KYNVER_OPENCLAW_BIN?.trim()||t.OPENCLAW_BIN?.trim()||"openclaw",[i,a]=await Promise.all([n(o),n(s)]),[l,c]=await Promise.all([PB("hermes",Ap(e),i,r,e.now),PB("openclaw",Pp(e),a,r,e.now)]);return{v:1,engines:[l,c,pee(e)].filter(d=>d!==null)}}function mee(e={}){return dl||(pl&&Date.now()-pl.at<see?Promise.resolve():(dl=fee(e).then(t=>{pl={at:Date.now(),report:t}}).catch(()=>{}).finally(()=>{dl=null}),dl))}function Ob(){if(mee(),!!pl)return{v:1,engines:pl.report.engines.map(e=>{let t=Ib(e.engine);return{...e,lastRoundTrip:Dp(e.engine),lastReadyAt:t===null?null:new Date(t).toISOString()}})}}var see,iee,aee,lee,cee,uee,EB,IB,pl,dl,OB=p(()=>{"use strict";H();Ge();D();Ka();Pb();bb();see=3e4,iee=10*6e4,aee=1500,lee=5e3,cee=3e4,uee=/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/,EB=new Map;IB=new Map;pl=null,dl=null});import gee from"node:os";function hee(e){try{return xt().report(e)}catch{return null}}function LB(e,t){try{return AL(e,t)}catch{return}}function Tb(e=process.env){let t=E(),r=Rt(t,e);return Lo({boxKind:r,hostLabel:gee.hostname(),config:t,env:e})}async function vee(e,t,r){let n=r.KYNVER_RUNTIME_CHAT_BRIDGE_URL?.trim();if(n)return n.replace(/\/$/,"");if(!e)return null;let o=e.replace(/\/$/,"");if(t){let s=new AbortController,i=setTimeout(()=>s.abort(),BB);try{let a=await fetch(`${o}/api/runtime/chat-bridge`,{headers:{Authorization:`Bearer ${t}`},signal:s.signal});if(a.ok){let l=await a.json().catch(()=>null);if(typeof l?.bridgeUrl=="string"&&l.bridgeUrl.trim())return l.bridgeUrl.trim().replace(/\/$/,"")}}catch{}finally{clearTimeout(i)}}return Ree(o)}async function Ree(e){let t=new AbortController,r=setTimeout(()=>t.abort(),BB);try{let n=await fetch(`${e}/runtime-chat/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:t.signal});if(n.status===401||n.status===400||n.status===403){let o=n.headers.get("content-type")??"";if(o.includes("application/json")||o.includes("json")||(await n.text().catch(()=>"")).trimStart().startsWith("{"))return e}return null}catch{return null}finally{clearTimeout(r)}}function WB(e){return Pe()?!0:!!e&&!!Wf(e)}async function DB(e=process.env){let t=E(),r=t.agentOsId?.trim(),n=Pe();if(!r||!WB(r))return null;let o=await vee(t.apiBaseUrl,n,e);if(!o)return null;let s=so(t),i=t.apiBaseUrl?.replace(/\/$/,"")??o.replace(/\/$/,"");return{bridgeUrl:o.replace(/\/$/,""),agentOsId:r,apiKey:n??"",boxId:Tb(e),chatProvider:s,model:Bs(s,t,e),useClaudeOauth:t.chatUseClaudeOauth===!0,auth:new _d({apiBaseUrl:i,agentOsId:r,boxLabel:()=>Tb(e),loadApiKey:Pe,loadBoxCredential:()=>Wf(r),saveBoxCredential:a=>dw(r,a),clearBoxCredential:pw}),security:new Ed}}function Nb(){try{return fw().apiKey}catch{return"none"}}async function wee(e,t,r,n){let o=E(),s=so(o),i=await Db(e);if(!i.bearer)return"no_credential";let a=Yd(s,np(o),LB(s,o),e.security?.report({policy:n,auth:i.kind,credentialStore:Nb(),folderSandbox:Xy(process.env,o)}),Ob()),l=hee(e.agentOsId);l&&(a.browser.siteLogins=l);let c=i.kind==="box_token"?i.boxId:Tb();e.chatProvider=s,e.boxId=c,e.model=Bs(s,o,process.env);let u=new AbortController,d=setTimeout(()=>u.abort(),kee),m=setInterval(()=>{t()&&u.abort()},500);try{let f=await fetch(`${e.bridgeUrl}/runtime-chat/claim`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.bearer}`},body:JSON.stringify({agentOsId:e.agentOsId,boxId:e.boxId,waitMs:yee,capabilities:a,claimRetries:r}),signal:u.signal});if(f.status===204)return null;if(f.status===401||f.status===403){let y=await f.text().catch(()=>"");return console.error(JSON.stringify({event:"chat_claim_auth_error",status:f.status,bridgeUrl:e.bridgeUrl,agentOsId:e.agentOsId,authKind:i.kind,detail:y.slice(0,200)})),eo(e,i,401),"auth_error"}if(f.status===429)throw new ln(f.status);if(!f.ok)throw new ln(f.status);let g;try{g=await f.json()}catch{throw new ln(502)}let h=SL(g);if(!h)throw new ln(502);return h.turn}catch(f){if(t())return null;throw f}finally{clearTimeout(d),clearInterval(m)}}async function yt(e,t,r){let n=await Db(e),o=await fetch(`${e.bridgeUrl}/runtime-chat/turns/${encodeURIComponent(t)}/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.bearer}`},body:JSON.stringify({agentOsId:e.agentOsId,boxId:e.boxId,events:r})});return eo(e,n,o.status),o.ok}async function MB(e,t,r){return e.security?.noteRejected(r.code),console.error(JSON.stringify({event:"chat_turn_rejected",turnId:t.turnId,requestId:t.requestId??"",code:r.code,...r.detail?{detail:r.detail}:{},reason:r.reason,policy:r.policy,...r.extra??{}})),Ha({at:new Date().toISOString(),chat:t.requestId??null,turnId:t.turnId,kind:"tool",engine:"none",access:"off",command:`turn refused: ${r.code}${r.detail?` (${r.detail})`:""}`,folder:"",ok:!1,reason:`turn_rejected_${r.code}`}),await yt(e,t.turnId,[{seq:0,kind:"error",error:BN(r.code,r.detail)}]).catch(()=>{}),{ok:!1}}async function See(e,t,r){let n=WN({turnId:t.turnId,agentOsId:t.agentOsId,payload:t.payload},{agentOsId:e.agentOsId,policy:r.policy,nonces:r.nonces,env:r.env,nowSec:r.nowSec});if(!n.ok)return n.code==="replayed"&&n.replay?.state==="in_flight"?(e.security?.noteDuplicateOffer(),console.error(JSON.stringify({event:"chat_turn_duplicate_offer_dropped",turnId:t.turnId,requestId:t.requestId??"",firstSeenAt:n.replay.firstSeenAt,reason:n.reason})),{ok:!1}):MB(e,t,{code:n.code,reason:n.reason,policy:r.policy,...n.replay?{detail:n.replay.state,extra:{firstSeenAt:n.replay.firstSeenAt,firstTurnId:n.replay.turnId}}:{}});let o=r.config;if(!o)try{o=E()}catch{o={}}let s=h0({signedAccess:n.access,boxId:e.boxId,agentOsId:e.agentOsId,engine:Ld(e.chatProvider,o,r.env??process.env),local:{chatComputerAccess:o.chatComputerAccess,chatWorkFolders:o.chatWorkFolders},state:Dd(r.stateFile),env:r.env,nowSec:r.nowSec});if(!s.ok)return MB(e,t,{code:s.code,detail:s.detail,reason:s.reason,policy:r.policy,extra:{from:$a(s.from),to:$a(s.to),signed:n.signed}});s.website&&u0(s.website,{file:r.stateFile});let a={...$y(t.payload),...n.access?{computerAccess:n.access}:{}};return n.access||delete a.computerAccess,n.redelivered&&console.error(JSON.stringify({event:"chat_turn_redelivered",turnId:t.turnId,requestId:t.requestId??""})),{ok:!0,trust:{signed:n.signed,access:n.access},payload:a,redelivered:n.redelivered}}async function _ee(e,t){let r=0,n=!1,o=new oo,s=Array.isArray(t.payload?.argv)?t.payload.argv:[],i=await E0(s,a=>{n||o.track(yt(e,t.turnId,[{seq:r++,kind:"delta",text:a}]).then(l=>(l||(n=!0),l)))},{agentOsId:e.agentOsId,authProof:t.payload?.authProof});await o.drain(),n||(i.refused?await yt(e,t.turnId,[{seq:r++,kind:"error",error:`command_refused: ${i.refused}`}]).catch(()=>{}):await yt(e,t.turnId,[{seq:r++,kind:"final",message:{exitCode:i.exitCode,timedOut:i.timedOut}}]).catch(()=>{})),console.error(JSON.stringify({event:"command_turn_done",turnId:t.turnId,argv:s.slice(0,4),exitCode:i.exitCode,timedOut:i.timedOut,refused:i.refused??null}))}function xee(e,t,r,n,o){try{let s=uo({provider:t.chatProvider,config:n,payloadAccess:e.payload.computerAccess,boxId:t.boxId}),i=c0(s.access,{signed:r.signed});if(!i)return;let a=i.from?$a(i.from.access):"not set",l=$a(i.to.access),c={at:i.to.at,chat:e.requestId??null,turnId:e.turnId,kind:"access_change",engine:s.engine,access:i.to.access,folder:s.access.workDir,from:a,to:l,source:i.to.source,signed:r.signed,ok:!0};Ha({...c,kind:"tool",command:`computer access: ${a} \u2192 ${l} (${i.to.source})`}),o(c),console.error(JSON.stringify({event:"chat_access_changed",turnId:e.turnId,from:a,to:l,source:i.to.source,signed:r.signed}))}catch{}}async function Cee(e,t,r){let n=0,o=!1,s=new oo,i=new AbortController,a=t.requestId??"",l=h=>{o||s.track(yt(e,t.turnId,[{seq:n++,kind:"delta",text:h}]).then(y=>(y||(o=!0,i.abort()),y)))},c=new rn(l),u=Ep({turnId:t.turnId,chat:a||null,send:h=>{o||(c.flush(),s.track(yt(e,t.turnId,[{seq:n++,kind:"activity",activity:h}]).then(y=>(y||(o=!0,i.abort()),y))))}}),d=e.chatProvider??"anthropic",m=E(),f=np(m);r&&xee(t,e,r,m,h=>{o||s.track(yt(e,t.turnId,[{seq:n++,kind:"activity",activity:h}]).then(y=>(y||(o=!0,i.abort()),y)))});try{qk(d,e.useClaudeOauth,process.env,m)}catch(h){let y=tl(t.payload.requestedModel);if(!(y&&f.some(k=>k.provider===y.provider&&k.models.includes(y.model)))){await yt(e,t.turnId,[{seq:0,kind:"error",error:h instanceof Error?h.message:String(h)}]).catch(()=>{});return}}let g={provider:d,model:e.model};try{let h=await SM({payload:t.payload,catalog:f,primary:{provider:d,model:e.model},onDelta:k=>c.push(k),runTurn:k=>(g={provider:k.provider,model:k.model},wM({...k,signal:i.signal,turnId:t.turnId,requestId:t.requestId,useClaudeOauth:e.useClaudeOauth,config:m,boxId:e.boxId,onActivity:u.sink}))});OL(h.content,uo({provider:g.provider,config:m,payloadAccess:t.payload.computerAccess,boxId:e.boxId}),u),c.close(),await s.drain();let y=n++;if(!await Ys(()=>o?yt(e,t.turnId,[{seq:y,kind:"error",error:"turn_stream_aborted"}]).catch(()=>!1):yt(e,t.turnId,[{seq:y,kind:"final",message:h}]).catch(()=>!1))){console.error(JSON.stringify({event:"chat_turn_final_rejected",requestId:a,turnId:t.turnId,model:g.model,chatProvider:g.provider}));return}console.error(JSON.stringify({event:"chat_turn_done",requestId:a,turnId:t.turnId,model:g.model,chatProvider:g.provider,fallbackReason:h.kynverModel.fallbackReason,activitySteps:u.steps}))}catch(h){c.close(),await s.drain(),o||await yt(e,t.turnId,[{seq:n++,kind:"error",error:h instanceof Error?h.message:String(h)}]).catch(()=>{}),console.error(JSON.stringify({event:"chat_turn_error",requestId:a,turnId:t.turnId,error:h instanceof Error?h.message:String(h)}))}}async function fl(e,t){for(let n=0;n<e&&!t();n+=500)await new Promise(o=>setTimeout(o,Math.min(500,e-n)))}async function UB(e){let t=await DB(),r=()=>WB(E().agentOsId?.trim())&&!!E().agentOsId?.trim();for(t||console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:r()?"bridge_not_discovered (rollout off, discovery route missing/404, or API unreachable)":"machine_not_linked",rediscoverMs:NB}));!t&&!e.shouldStop();){if(!r()||(await fl(NB,e.shouldStop),e.shouldStop()))return;t=await DB()}if(!t||e.shouldStop())return;let n=LN(process.env,E()),o=new Cd;t.security&&(t.security.childEnv=await s0().catch(c=>({ok:!1,leaked:[],error:c instanceof Error?c.message:String(c),at:new Date().toISOString()})),t.security.childEnv.ok||console.error(JSON.stringify({event:"chat_child_env_selftest_failed",...t.security.childEnv}))),console.error(JSON.stringify({event:"chat_claim_loop_start",bridgeUrl:t.bridgeUrl,agentOsId:t.agentOsId,boxId:t.boxId,model:t.model,chatProvider:t.chatProvider,capabilities:Yd(t.chatProvider),useClaudeOauth:t.useClaudeOauth,turnSignature:n,credentialStore:Nb(),childEnvSafe:t.security?.childEnv?.ok??null,auth:t.auth?.describe().kind??"api_key"}));let s=0,i=new Cp,a=LL({target:t,capabilities:c=>{let u=E(),d=so(u);return Yd(d,np(u),LB(d,u),t.security?.report({policy:n,auth:c.kind,credentialStore:Nb(),folderSandbox:Xy(process.env,u)}),Ob())}}),l=Promise.resolve();for(;!e.shouldStop();)try{if(s>=bee){await fl(250,e.shouldStop);continue}let c=await wee(t,e.shouldStop,i.snapshot(),n);if(c==="no_credential"){console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:"machine_not_linked"})),await fl(TB,e.shouldStop);continue}if(c==="auth_error"){i.onAuthError();let u=t.auth?.describe().hasBoxCredential===!0;await fl(u?5e3:TB,e.shouldStop);continue}if(i.onSuccess(),c){let u=await DL(t,c.turnId);if(!NL(u.outcome)){console.error(JSON.stringify({event:"chat_turn_receipt_rejected",turnId:c.turnId,requestId:c.requestId??null,status:u.status}));continue}u.outcome!=="accepted"&&console.error(JSON.stringify({event:"chat_turn_receipt_unconfirmed",turnId:c.turnId,outcome:u.outcome,status:u.status}));let d=c.payload?.kind;s+=1;let m;if(d==="command"){let f=()=>_ee(t,c);m=l.then(f,f),l=m.then(()=>{},()=>{})}else{let f=await See(t,c,{policy:n,nonces:o});if(!f.ok){s-=1;continue}if(o.markStarted(c.turnId),d==="browser"){let g=await Db(t);m=bL({...t,apiKey:g.bearer},{turnId:c.turnId,payload:f.payload})}else d==="agent-tab"?m=xB(g=>yt(t,c.turnId,g),{turnId:c.turnId,payload:f.payload,boxId:t.boxId}):m=Cee(t,{...c,payload:f.payload},f.trust)}m.catch(f=>{console.error(JSON.stringify({event:"chat_turn_execution_crash",turnId:c.turnId,error:f instanceof Error?f.message:String(f)}))}).finally(()=>{s-=1,d!=="command"&&o.markFinished(c.turnId)})}}catch(c){let{kind:u,consecutive:d,backoffMs:m}=i.onError(c),f=EL(u,d),g=JSON.stringify({event:f.event,level:f.level,error:c instanceof Error?c.message:String(c),kind:u,consecutive:d,retryInMs:m});f.level==="error"?console.error(g):console.log(g),m>0&&await fl(m,e.shouldStop)}a(),await hL(),console.error(JSON.stringify({event:"chat_claim_loop_stop"}))}var yee,kee,TB,NB,BB,bee,Db,FB=p(()=>{"use strict";H();De();NN();xd();Hy();UN();FN();Nd();i0();d0();y0();Ka();Ud();Bo();Fd();lk();A0();Va();aD();_k();xk();Yk();_M();vL();mb();hb();yb();PL();kb();TL();up();ML();BL();CB();OB();hb();Ti();yee=2e4,kee=32e3,TB=6e4,NB=5*6e4,BB=5e3,bee=3,Db=Ns});import{createHash as Eee}from"node:crypto";import{chmodSync as $B,existsSync as Aee,mkdirSync as Pee,rmSync as KB}from"node:fs";import{createConnection as Iee,createServer as Oee}from"node:net";import{homedir as Tee,userInfo as Nee}from"node:os";import Dee from"node:path";function Lee(e,t=process.platform){return t==="win32"?`\\\\.\\pipe\\kynver-site-logins-${Eee("sha256").update(`${Nee().username}:${Tee()}`).digest("hex").slice(0,16)}`:Dee.join(e,"control.sock")}async function Bee(e,t){switch(t.op){case"status":return{ok:!0,data:{report:e.report(t.agentOsId),codes:e.listCodeRequests(t.agentOsId)}};case"unlock":{let r=e.store(t.agentOsId),n=e.audit(t.agentOsId);try{let o=await r.unlockWithPassphrase(t.passphrase);return e.unlock(t.agentOsId,o),o.fill(0),n.record({event:"unlock",ok:!0}),{ok:!0}}catch(o){throw n.record({event:"unlock_failed",ok:!1,code:o instanceof q?o.code:"failed"}),o}}case"lock":return e.lock(t.agentOsId),{ok:!0};case"add":{let r=e.key(t.agentOsId);if(!r)return{ok:!1,error:"saved logins are locked in the running Kynver",code:"locked"};let n=e.store(t.agentOsId),o=t.replaceHandle?n.replace(r,t.replaceHandle,t.login):n.add(r,t.login);return e.audit(t.agentOsId).record({event:t.replaceHandle?"replace":"add",ok:!0,handle:o.handle,label:o.label,username:o.username,origin:o.origin}),{ok:!0,data:o}}case"codes":return{ok:!0,data:e.listCodeRequests(t.agentOsId)};case"code":return{ok:!0,data:await e.submitCode(t.id??null,t.code,t.agentOsId)};case"wipe":return{ok:!0,data:{wiped:e.wipe(t.agentOsId)}}}}function Wee(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let r=t,n=["status","unlock","lock","add","codes","code","wipe"];return typeof r.op!="string"||!n.includes(r.op)||r.op!=="lock"&&(typeof r.agentOsId!="string"||!r.agentOsId.trim())?null:t}async function HB(e){let t=Lee(e.rootDir);if(process.platform!=="win32"){Pee(e.rootDir,{recursive:!0,mode:448});try{$B(e.rootDir,448)}catch{}if(Aee(t)){if(await Uee(t))return null;KB(t,{force:!0})}}let r=Oee(n=>{let o="";n.setEncoding("utf8"),n.setTimeout(12e4,()=>n.destroy()),n.on("data",s=>{if(o+=s,o.length>Mee)return void n.destroy();let i=o.indexOf(`
|
|
462
|
-
`);if(i<0)return;let a=
|
|
463
|
-
`);if(!a)return l({ok:!1,error:"malformed request"});Bee(e,a).then(l).catch(c=>l({ok:!1,error:c instanceof q?c.message:"the request failed",code:c instanceof q?c.code:"failed"}))}),n.on("error",()=>{})});try{await new Promise((n,o)=>{r.once("error",o),r.listen(t,()=>n())})}catch(n){return console.error(JSON.stringify({event:"site_login_control_unavailable",error:n.message.slice(0,200)})),null}if(process.platform!=="win32")try{$B(t,384)}catch{}return{path:t,close:()=>new Promise(n=>{r.close(()=>n()),process.platform!=="win32"&&KB(t,{force:!0})})}}function Uee(e){return new Promise(t=>{let r=Iee(e),n=o=>{r.destroy(),t(o)};r.once("connect",()=>n(!0)),r.once("error",()=>n(!1)),setTimeout(()=>n(!1),1e3).unref?.()})}var Mee,jB=p(()=>{"use strict";Cn();Mee=16*1024});function Kee(e){return e.config.browserDisabled===!0?"local_disabled":e.config.browserAutoProvision===!1?"auto_provision_off":!/^(1|true|yes|on)$/i.test(e.env.KYNVER_BROWSER_AUTOPROVISION??"")&&e.config.browserEverEnabled!==!0?"never_enabled":e.resolved.executable?"already_available":Ws(e.platform,e.arch)?null:"unsupported_platform"}async function VB(e,t){let r=t.sleep??(n=>new Promise(o=>setTimeout(o,n).unref?.()));for(let n=e;n>0&&!t.shouldStop();n-=1e3)await r(Math.min(1e3,n))}async function GB(e){let t=e.env??process.env,r=e.platform??process.platform,n=e.arch??process.arch,o=e.now??Date.now,s=e.log??(l=>console.error(JSON.stringify(l))),i=e.resolve??(()=>lo({env:t,platform:r,arch:n})),a=e.loadConfig??E;try{await VB(e.startDelayMs??Fee,e);for(let l=1;l<=$ee&&!e.shouldStop();l+=1){let c=Kee({config:a(),env:t,resolved:i(),platform:r,arch:n});if(c){c!=="never_enabled"&&s({event:"browser_autoprovision_skip",reason:c});return}let u=eD(co());if(u>o()&&await VB(u-o(),e),e.shouldStop())return;s({event:"browser_autoprovision_start",attempt:l});try{let d=await(e.provision??Gd)({env:t,platform:r,arch:n});s({event:"browser_autoprovision_done",version:d.version});return}catch(d){s({event:"browser_autoprovision_failed",attempt:l,error:d instanceof Error?d.message.slice(0,200):String(d)})}}}catch(l){s({event:"browser_autoprovision_crash",error:l instanceof Error?l.message.slice(0,200):String(l)})}}var Fee,$ee,JB=p(()=>{"use strict";H();io();qa();Jd();Fee=6e4,$ee=5});function Lb(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(e.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Gee(e,t){let r=Lb(e),n=Lb(t);if(!r||!n)return!1;for(let o=0;o<3;o+=1)if(r[o]!==n[o])return r[o]<n[o];return!1}function Jee(e,t){return`Kynver on this computer is out of date (installed ${e}, latest ${t}). Update with: ${Mb} then restart Kynver (or restart the computer).`}async function qee(e={}){let t=e.installed??Dt,r={installed:t,latest:null,outdated:!1,command:Mb};if((e.env??process.env).KYNVER_DISABLE_UPDATE_CHECK==="1")return r;let o=new AbortController,s=setTimeout(()=>o.abort(),jee);try{let a=await(e.fetch??fetch)(Hee,{signal:o.signal,headers:{accept:"application/json"}});if(!a.ok)return r;let l=await a.json(),c=typeof l?.version=="string"&&Lb(l.version)?l.version:null;return c?{installed:t,latest:c,outdated:Gee(t,c),command:Mb}:r}catch{return r}finally{clearTimeout(s)}}function YB(e={}){let t=e.log??(s=>console.error(s)),r=null,n=async()=>{let s=await qee(e);return s.outdated&&s.latest&&s.latest!==r&&(r=s.latest,t(JSON.stringify({event:"runtime_update_available",installed:s.installed,latest:s.latest,command:s.command})),t(Jee(s.installed,s.latest))),s};n().catch(()=>{});let o=setInterval(()=>{n().catch(()=>{})},e.intervalMs??Vee);return o.unref?.(),{stop:()=>clearInterval(o),checkNow:n}}var qB,Mb,Hee,jee,Vee,zB=p(()=>{"use strict";zo();qB="@kynver-app/runtime",Mb=`npm install -g ${qB}@latest`,Hee=`https://registry.npmjs.org/${qB}/latest`,jee=5e3,Vee=360*6e4});var eW={};ev(eW,{adoptOrAcquireOwnerLease:()=>QB,completeWorker:()=>IA,dispatchRun:()=>Ss,resolveDaemonOwnerKind:()=>XB,runDaemon:()=>ZB,runPipelineTick:()=>vd,sweepRun:()=>ed});async function Bb(e,t,r){let n=e;for(;n>0&&!t();){let o=Math.min(Qee,n),s=Date.now();await Cl(o);let i=Rm(o,Date.now()-s);if(i!==null){r?.(i);return}n-=o}}function XB(e,t={},r=process.env){return t.ownerKind?t.ownerKind:e.keeperChild===!0||e.keeperChild==="true"?"keeper":r.INVOCATION_ID?.trim()?"systemd":"foreground"}async function QB(e,t,r,n=Oc){return r?r.released||!r.isHeld()||r.metadata.agentOsId!==e?{ok:!1,reason:"owner_conflict",holder:null,remedy:"the owner lease handed to the daemon is not held for this workspace; restart the runtime"}:{ok:!0,lease:r,quarantinedMetadata:null}:n({agentOsId:e,ownerKind:t})}async function ZB(e,t={}){let r=Dm({hostCapability:t.hostCapability}),n=ze()?{loaded:0}:_R();n.loaded>0&&console.error(JSON.stringify({event:"daemon_env_file_loaded",...n}));let o=String(e.run||"").trim();o||(console.error(Em("--run")),process.exit(1));let s=String(e.agentOsId||E().agentOsId||"").trim();s||(console.error(Em("--agent-os-id")),process.exit(1)),Ho(s).ok||(console.error(Mf(s)),console.error("Diagnose: run `kynver doctor runner-install`. Still stuck? `kynver report-bug --json` (draft only \u2014 create a GitHub issue to actually send it)."),process.exit(1));let a=e.execute!==!1&&e.execute!=="false",l=Number(e.intervalMs)>0?Math.floor(Number(e.intervalMs)):Yee,c=!1,u=0,d=bw(N=>{c||console.error(JSON.stringify({event:"daemon_stop_requested",reason:N,runId:o})),c=!0}),m=await QB(s,XB(e,t),t.ownerLease);if(!m.ok){console.error(JSON.stringify({event:"daemon_start_blocked",reason:"owner_conflict",runId:o,agentOsId:s,holder:m.holder?{ownerKind:m.holder.ownerKind,pid:m.holder.pid,runtimeVersion:m.holder.runtimeVersion,acquiredAt:m.holder.acquiredAt}:null,remedy:m.remedy})),d(),process.exit(1);return}let f=m.lease;TR(f.metadata.ownerKind),x_({admission:r.allowed?{basis:r.basis,hostCapability:r.hostCapability}:null,ownerKind:f.metadata.ownerKind});let g={kind:f.metadata.ownerKind,instanceId:f.metadata.instanceId,processStart:f.metadata.processStart,runtimeVersion:f.metadata.runtimeVersion};console.error(JSON.stringify({event:"daemon_owner_lease_acquired",agentOsId:s,ownerKind:f.metadata.ownerKind,instanceId:f.metadata.instanceId,quarantinedStaleMetadata:m.quarantinedMetadata!==null}));let h=b_(o);h.killed.length>0&&console.error(JSON.stringify({event:"daemon_orphaned_worker_descendants_killed",runId:o,orphans:h.killed.map(N=>({worker:N.workerName,workerPid:N.workerPid,pid:N.orphanPid,outcome:N.result.outcome}))}));let y=null,v=N=>{y=N};try{let N=uw();(N.moved.length>0||N.stillInFile.length>0)&&console.error(JSON.stringify({event:"daemon_credentials_store",...N}))}catch(N){console.error(JSON.stringify({event:"daemon_credentials_store_error",error:N instanceof Error?N.message:String(N)}))}let k=r_();k.remediated&&console.error(JSON.stringify({event:"daemon_default_repo_remediated",defaultRepo:k.resolved?.defaultRepo??null,configPath:k.configPath}));let b=y_(E());b.ok||(console.error(JSON.stringify({event:"daemon_start_blocked",runId:o,agentOsId:s,errors:b.errors})),console.error("Diagnose: run `kynver doctor runner-install`. Still stuck? `kynver report-bug --json` (draft only \u2014 create a GitHub issue to actually send it)."),process.exit(1)),console.error(JSON.stringify({event:"daemon_start",runId:o,agentOsId:s,execute:a,intervalMs:l,boxKind:b.box.boxKind,workerCapSource:b.workerCapSource,maxConcurrentWorkers:b.maxConcurrentWorkers})),YB();let _=qo(),S=new Sd;S.start();let R=new wd({agentOsId:s,init:{ownerKind:f.metadata.ownerKind,admission:r.allowed?{basis:r.basis,hostCapability:r.hostCapability}:null}});S.setTickIsolation(R.mode),console.error(JSON.stringify({event:"daemon_tick_isolation",mode:R.mode,reason:R.reason}));let w=HB(xt()).catch(()=>null),W=UB({shouldStop:()=>c}).catch(N=>{console.error(JSON.stringify({event:"chat_claim_loop_crashed",error:N instanceof Error?N.message:String(N)}))});GB({shouldStop:()=>c});let O=!1;for(;!c;)try{if(y!==null){let I=y;y=null;let K=f.isHeld();if(console.error(JSON.stringify({event:"daemon_resume_detected",agentOsId:s,gapMs:I,ownerLeaseHeld:K})),!K){console.error(JSON.stringify({event:"daemon_owner_lease_lost",agentOsId:s,runId:o})),process.exitCode=1,c=!0;break}}S.setPhase("heartbeat"),f.renew(),OS({agentOsId:s,runId:o,instructionBundleVersion:An(),owner:g}),S.setPhase("runner_credential");let N=await pc(e.secret?String(e.secret):void 0,s,{baseUrl:e.baseUrl?String(e.baseUrl):void 0});if(!N.ok){O||(O=!0,console.error(JSON.stringify({event:"daemon_runner_credential_missing",agentOsId:s,reason:N.reason,remedy:`run \`kynver runner credential --agent-os-id ${s}\` (or \`kynver bootstrap\`); ticks resume automatically once the credential exists`}))),S.setPhase("idle"),await Bb(l,()=>c,v);continue}O&&(O=!1,console.error(JSON.stringify({event:"daemon_runner_credential_recovered",agentOsId:s}))),S.setPhase("instruction_bundle"),await m_({agentOsId:s,baseUrl:Rn(e.baseUrl?String(e.baseUrl):void 0),secret:N.secret}),S.setPhase(R.mode==="thread"?"pipeline_tick_thread":"pipeline_tick_inline");let L=await R.runTick({run:o,agentOsId:s,execute:a,...e,secret:typeof e.secret=="string"&&e.secret?e.secret:N.secret},S.report());S.setTickIsolation(L.isolation);let M=L.tick;S.setPhase("tick_log"),console.error(JSON.stringify({event:"daemon_tick",tickIsolation:L.isolation,...M})),S.setPhase("runtime_control");let V=Wr(s),J=L.inFlightWorkers??Rd(s)??0;if(IR(V,J)){let I=Zl({control:V,supervisor:f.metadata.ownerKind,inFlightWorkers:0,exiting:!0}),K=Rn(e.baseUrl?String(e.baseUrl):void 0),F=I&&K?await CS({baseUrl:K,agentOsId:s,secret:N.secret},I):!1;console.error(JSON.stringify({event:"daemon_runtime_stopped",agentOsId:s,runId:o,policyVersion:V?.policyVersion??null,requestedBy:V?.requestedByLabel??null,reported:F})),process.exitCode=Ql,c=!0;break}if(_.tickEnabled){S.setPhase("cron_tick");let I=Fc(o);if(I&&!I.authorized)console.error(JSON.stringify({event:"daemon_cron_tick_skipped",reason:"mesh_cron_lease_not_authorized",holderBoxId:I.holderBoxId}));else{let K=await Fm({env:_,agentOsIdFilter:s});K.enabled&&(K.fired>0||K.errors>0||K.lockHeld)&&console.error(JSON.stringify({event:"daemon_cron_tick",...K}))}}M.idle?u++:u=0;let T=Math.floor(Zo("daemon.maxIdleStreak",Xee)),x=Math.floor(Zo("daemon.idleIntervalMs",zee)),j=u>=T?x:l;S.setPhase("idle"),await Bb(j,()=>c,v)}catch(N){console.error(JSON.stringify({event:"daemon_tick_error",error:N.message})),S.setPhase("idle"),await Bb(l,()=>c,v)}S.setPhase("stopping"),await W,await R.close(),S.stop(),await(await w)?.close().catch(()=>{}),xt().lock();let P=vw(o);P.length>0&&console.error(JSON.stringify({event:"daemon_stop_worker_trees_killed",runId:o,workers:P.map(N=>({worker:N.workerName,pid:N.pid,outcome:N.result.outcome}))})),d(),f.release(),console.error(JSON.stringify({event:"daemon_stop",runId:o,agentOsId:s}))}var Yee,zee,Xee,Qee,Wb=p(()=>{"use strict";H();Am();n_();g_();Kr();k_();vm();yc();Tc();bt();wm();v_();Wc();Mm();$m();pr();ir();Km();D();IN();Uy();TN();FB();Ti();jB();JB();zB();Ur();bm();Wy();bu();zh();vs();Yee=6e4,zee=5*6e4,Xee=10,Qee=250});var tW=p(()=>{"use strict";z();Co();qh();_e();D()});var ml,rW=p(()=>{"use strict";ml=class extends Error{remedy;exitCode;constructor(t,r={}){super(t,r.cause===void 0?void 0:{cause:r.cause}),this.name="OperatorActionableError",this.remedy=r.remedy,this.exitCode=r.exitCode??1}}});import{existsSync as Zee,mkdirSync as ete}from"node:fs";import tte from"node:path";function rte(e){let t=typeof e.repo=="string"?e.repo.trim():"";if(t)return t;let r=Wi();return r?r.repo:(vt("","--repo (or set defaultRepo via `kynver setup` / KYNVER_DEFAULT_REPO)"),"")}function nte(e){let t=e.repoLabel??"the repo",r=[],n=e.explicitBase?.trim();n&&r.push({ref:n,source:"flag",origin:"--base"});let o=e.envBaseRef?.trim();o&&r.push({ref:o,source:"env",origin:"KYNVER_RUN_BASE_REF"});let s=e.configDefaultBase?.trim();s&&r.push({ref:s,source:"config",origin:"defaultBase in ~/.kynver/config.json"});let i=r[0];if(i){if(e.verifyRef(i.ref))return{base:i.ref,source:i.source};throw new Error([`run base ref "${i.ref}" (from ${i.origin}) does not resolve in ${t}.`,"Fetch it (`git fetch origin`) or fix the override \u2014 refusing to silently use a different base."].join(" "))}if(e.verifyRef("origin/main"))return{base:"origin/main",source:"origin/main"};let a=e.resolveRemoteHeadRef();if(a&&e.verifyRef(a))return{base:a,source:"remote-head",note:`origin/main not found in ${t} \u2014 using the remote default branch ${a}`};throw new Error([`cannot resolve a base ref for a new run in ${t}: origin/main does not exist`,a?`and the remote default branch (${a}) did not verify either.`:"and no remote default branch could be resolved (origin/HEAD unset).",`Run \`git fetch origin\` in ${t}, or pass --base <ref> / set KYNVER_RUN_BASE_REF / set defaultBase in ~/.kynver/config.json.`].join(" "))}function ote(e){let t=Q(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]);if(t.status===0){let n=t.stdout.trim().replace(/^refs\/remotes\//,"");if(n)return n}let r=Q(e,["ls-remote","--symref","origin","HEAD"]);if(r.status===0){let n=/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(r.stdout);if(n?.[1])return`origin/${n[1]}`}return null}function ste(e,t){let r=E();try{return nte({explicitBase:typeof t.base=="string"?t.base:void 0,envBaseRef:process.env.KYNVER_RUN_BASE_REF,configDefaultBase:r.defaultBase,verifyRef:n=>Q(e,["rev-parse","--verify","--quiet",`${n}^{commit}`]).status===0,resolveRemoteHeadRef:()=>ote(e),repoLabel:e})}catch(n){throw new ml(n.message,{remedy:"Diagnose: run `kynver doctor runner-install`.",cause:n})}}function Ub(e){let t=bA(rte(e));fv(t);let r=e.id?uh(String(e.id)):Sl(String(e.name||"run")),n=G(r);Zee(n)&&ite(`run already exists: ${r}`),ete(n,{recursive:!0});let o=ste(t,e);o.note&&console.error(o.note);let s=o.base,i=le(t,["rev-parse",s]).trim(),a=Nt(),l={id:r,name:String(e.name||r),repo:t,base:s,baseCommit:i,status:"created",createdAt:new Date().toISOString(),workers:{},...a.identity?{boxKind:a.identity.boxKind,runnerId:a.identity.runnerId,harnessRoot:a.identity.harnessRoot}:{}};ye(tte.join(n,"run.json"),l);let c={runId:r,runDir:n,repo:t,base:s,baseCommit:i};return console.log(JSON.stringify(c,null,2)),c}function ite(e){throw new ml(e)}var Fb=p(()=>{"use strict";ve();z();tW();D();ns();Gu();hn();H();rW()});function nW(e,t){return e.filter(n=>n.repo===t&&!Ar.has(n.status)).sort((n,o)=>(o.createdAt??"").localeCompare(n.createdAt??""))[0]??null}var oW=p(()=>{"use strict";ve();Qr()});var sW=p(()=>{"use strict";pr();Yo();Um()});var Mp=p(()=>{"use strict";pr();ir()});var Lp=p(()=>{"use strict"});var $b=p(()=>{"use strict"});var Kb=p(()=>{"use strict";sW();pr();Yo();Mp();ir();Lp();$b()});var iW=p(()=>{"use strict"});var aW=p(()=>{"use strict";Mp();Lp()});var lW=p(()=>{"use strict";ir();pr()});var cW=p(()=>{"use strict";H();nt();bt();D();$m();iW();aW();ir();Mp();lW();Xl();ki();Yo();Kb();Lp();$b();z()});var uW=p(()=>{"use strict";Kb();cW()});var dW=p(()=>{"use strict";ki();Xl();H();ir();ec();wf();bi();z()});function pW(e,t){return nW(e,t)?.id??null}var fW=p(()=>{"use strict";H();cm();Wb();Am();Mm();Tc();Fb();z();oW();ns();uW();km();Cf();ns();Va();dW()});var kW={};ev(kW,{prepareDesktopRuntime:()=>Ste,resolveDesktopRepository:()=>yW});import{spawnSync as mW}from"node:child_process";import{randomBytes as pte}from"node:crypto";import{existsSync as fte,mkdirSync as mte,readFileSync as gte,realpathSync as gW,statSync as hte,writeFileSync as yte}from"node:fs";import{homedir as kte}from"node:os";import jb from"node:path";function ke(e,t){return{ok:!1,code:e,message:t}}function bte(){return jb.join(kte(),".kynver","desktop-binding.json")}function vte(e){if(!fte(e))return null;try{let t=JSON.parse(gte(e,"utf8"));if(t?.version===1&&typeof t.cloudOrigin=="string"&&typeof t.accountId=="string"&&typeof t.agentOsId=="string"&&typeof t.repo=="string"&&typeof t.runId=="string")return t}catch{}return null}function Rte(e,t){mte(jb.dirname(e),{recursive:!0}),yte(e,`${JSON.stringify(t,null,2)}
|
|
464
|
-
`,{mode:384})}function hW(e,t){return e===401||e===403?ke("access_denied",`${t} was refused (${e})`):e===0?ke("network",`${t} could not reach Kynver`):ke("server_error",`${t} failed (${e})`)}async function Hb(e,t,r,n={}){try{let o=await it(e,{...n,headers:{...n.headers,Authorization:`Bearer ${t}`}},r),s=await o.json().catch(()=>null);return{status:o.status,body:s}}catch{return{status:0,body:null}}}function wte(e){return(e?.accessibleItems??[]).filter(t=>t.access?.isOwner===!0&&typeof t.agentOs?.id=="string").map(t=>(t.agentOs?.id).trim()).filter(Boolean)}function yW(e,t="git"){let r=mW(t,["--version"],X({encoding:"utf8"}));if(r.error||r.status!==0)return ke("no_git","Git is not installed or not on PATH");let n;try{if(n=gW.native(jb.resolve(e)),!hte(n).isDirectory())return ke("not_a_repository","The selected path is not a folder")}catch{return ke("not_a_repository","The selected folder does not exist")}let o=mW(t,["rev-parse","--is-bare-repository","--show-toplevel"],X({cwd:n,encoding:"utf8"})),s=(o.stdout??"").trim().split(/\r?\n/);if(o.status!==0||s[0]!=="false"||!s[1])return ke("not_a_repository","The selected folder is not inside a Git working tree");try{return{ok:!0,repo:gW.native(s[1].trim())}}catch{return ke("not_a_repository","The Git working tree root could not be resolved")}}async function Ste(e,t={}){let r=t.fetchImpl??fetch,n=t.acquireOwnerLease??Oc,o=t.bindingPath??bte(),s=[],i=rr(e.apiBaseUrl);if(!i)return ke("invalid_input","apiBaseUrl is required");let a=si(i),l=new URL(a).origin;if(e.agentOsId!==void 0&&!Ho(e.agentOsId).ok)return ke("invalid_input","agentOsId is not a valid workspace id");let c;try{c=Pe()}catch(S){if(S instanceof Xs)return ke("credentials_unavailable","This computer's credentials have not been provided");throw S}if(!c)return ke("credentials_unavailable","This computer is not paired");let u=await Hb(`${a}/api/users/me`,c,r);if(u.status!==200)return hW(u.status,"Account lookup");let d=typeof u.body?.id=="string"?u.body.id:"";if(!d)return ke("server_error","Account lookup returned no account id");if(e.expectedAccountId&&e.expectedAccountId!==d)return ke("account_mismatch","The paired credentials belong to a different account");let m=await Hb(`${a}/api/agent-os/provision`,c,r,{method:"POST"});!(m.status>=200&&m.status<300)&&m.status!==401&&m.status!==403&&s.push(`workspace self-provision returned ${m.status||"no response"}; continuing with existing access`);let g=await Hb(`${a}/api/agent-os`,c,r);if(g.status!==200)return hW(g.status,"Workspace lookup");let h=g.body,y;if(e.agentOsId){if(!wte(h).includes(e.agentOsId))return ke("agent_os_not_owned","That workspace is not owned by the paired account");y=e.agentOsId}else{let S=am(h);if(!S?.id)return ke("no_workspace","No workspace owned by this account was found");y=S.id}let v=yW(e.repo,t.gitBinary);if(!v.ok)return v;let k=v.repo,b=await n({agentOsId:y,ownerKind:"desktop"});if(!b.ok)return{ok:!1,code:"owner_conflict",message:b.remedy,holder:b.holder?{ownerKind:b.holder.ownerKind,pid:b.holder.pid,runtimeVersion:b.holder.runtimeVersion,acquiredAt:b.holder.acquiredAt}:null};let _=b.lease;try{Le({...E(),apiBaseUrl:a,agentOsId:y,defaultRepo:k});let S=ym(E());s.push(...S.warnings);let R=E().boxId?.trim()??"";if(!R)return _.release(),ke("local_state_error","Box identity could not be established");if(await um($r()),!He(y))try{let L=await wn(y,{baseUrl:a,apiKey:c});vn(y,L)}catch(L){let M=L.message;if(iS(M)==="access_denied")return _.release(),ke("access_denied","This computer was refused a runner credential");s.push("runner credential mint did not succeed yet; the runtime retries automatically")}let w=vte(o),W=w!==null&&w.cloudOrigin===l&&w.accountId===d&&w.agentOsId===y&&w.repo===k,O="";if(W){let L=pW(Re().filter(M=>M.id===w.runId),k);L&&(O=L)}if(!O){let L=`${Sl("desktop")}-${pte(3).toString("hex")}`;O=Ub({repo:k,name:"desktop",id:L}).runId}Rte(o,{version:1,cloudOrigin:l,accountId:d,agentOsId:y,repo:k,runId:O});let P=Rc(k);P||s.push("the repository has no origin remote; nothing can run until it has one");let{runnerId:N}=Oe({runId:O});return{ok:!0,prepared:{accountId:d,agentOsId:y,runId:O,repo:k,boxId:R,repoIdentity:P,runnerId:N},lease:_,warnings:s}}catch(S){return _.release(),ke("local_state_error",S.message)}}var bW=p(()=>{"use strict";nr();cm();lm();H();bt();pr();Yo();Tc();wc();z();mr();km();fW();Fb();D()});bt();import{pathToFileURL as _te}from"node:url";var iv="credential.persist";function av(e,t){let r,n=new Map,o=s=>{r=s.apiKey?.trim()||void 0,n=new Map(Object.entries(s.runnerTokens??{}).map(([i,a])=>[i.trim(),a.trim()]).filter(([i,a])=>i&&a))};return o(e),{kind:"desktop",getApiKey:()=>r,getRunnerToken(s){if(s)return n.get(s);if(n.size===1)return n.values().next().value},persistApiKey(s){let i=s.trim();if(!i)throw new Error("refusing to persist an empty API key");r=i,t({v:1,type:iv,kind:"apiKey",value:i})},persistRunnerToken(s,i){let a=s.trim(),l=i.trim();if(!a||!l)throw new Error("refusing to persist an empty runner token binding");n.set(a,l),t({v:1,type:iv,kind:"runnerToken",agentOsId:a,value:l})},reseed:o}}yc();wc();Cn();om();var Yw=/^lg_[a-z0-9]{6,20}$/,MK=/^cr_[0-9a-f]{12}$/,LK=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),En=(e,t,r=1)=>typeof e=="string"&&e.length>=r&&e.length<=t&&!e.includes("\0");function Jo(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function zw(e){let t=["v","type","id","agentOsId","op"];switch(e.op){case"key":return Jo(e,[...t,"key"])??(En(e.key,64,40)&&/^[A-Za-z0-9+/]{43}=$/.test(e.key)?{op:"key",key:e.key}:"invalid key");case"list":case"wipe":return Jo(e,t)??{op:e.op};case"remove":return Jo(e,[...t,"handle"])??(typeof e.handle=="string"&&Yw.test(e.handle)?{op:"remove",handle:e.handle}:"invalid handle");case"code":{let r=Jo(e,[...t,"requestId","code"]);return r||(e.requestId!==void 0&&!(typeof e.requestId=="string"&&MK.test(e.requestId))?"invalid requestId":En(e.code,16)?{op:"code",code:e.code,...e.requestId?{requestId:e.requestId}:{}}:"invalid code")}case"add":{let r=Jo(e,[...t,"login","replaceHandle"]);if(r)return r;let n=e.login;return!LK(n)||Jo(n,["origin","label","username","password","totp"])||!En(n.origin,2048)||!En(n.label,lt.maxLabel)||!En(n.username,lt.maxUsername)||!En(n.password,lt.maxPassword)||n.totp!==void 0&&!En(n.totp,lt.maxTotp,0)?"invalid login":e.replaceHandle!==void 0&&!(typeof e.replaceHandle=="string"&&Yw.test(e.replaceHandle))?"invalid replaceHandle":{op:"add",login:{origin:n.origin,label:n.label,username:n.username,password:n.password,...n.totp?{totp:n.totp}:{}},...e.replaceHandle?{replaceHandle:e.replaceHandle}:{}}}default:return"unknown site_login op"}}async function Xw(e,t,r){let n=e.store(t),o=e.audit(t);switch(r.op){case"key":{let s=Buffer.from(r.key,"base64");try{if(n.exists()&&n.keyMode()==="passphrase")return{state:e.isUnlocked(t)?"unlocked":"locked",keyMode:"passphrase"};if(n.exists())try{n.unlockWithKey(s)}catch(i){if(!(i instanceof q)||i.code!=="bad_key")throw i;e.wipe(t),o.record({event:"wipe",ok:!0,code:"keychain_key_replaced"})}return n.exists()||n.createWithKeychainKey(s),e.unlock(t,s,{keychain:!0}),{state:"unlocked",keyMode:"keychain"}}finally{s.fill(0)}}case"list":return{logins:n.list(),report:e.report(t),codes:e.listCodeRequests(t)};case"add":{let s=e.key(t);if(!s)throw new q("saved logins are locked","locked");let i=r.replaceHandle?n.replace(s,r.replaceHandle,r.login):n.add(s,r.login);return r.login.password="",o.record({event:r.replaceHandle?"replace":"add",ok:!0,handle:i.handle,label:i.label,username:i.username,origin:i.origin}),{login:i}}case"remove":{let s=n.get(r.handle),i=n.remove(r.handle);return i&&s&&o.record({event:"remove",ok:!0,handle:r.handle,label:s.label,username:s.username,origin:s.origin}),{removed:i}}case"code":return await e.submitCode(r.requestId??null,r.code,t);case"wipe":return{wiped:e.wipe(t)}}}Ti();Cn();var xte=1,Bp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,zs=/^[A-Za-z0-9_-]{1,64}$/,Cte=/^[a-z0-9][a-z0-9._-]{0,127}$/i,vW=4096,Ete=4096,Ate=16;function Vb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function gl(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function hl(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!e.includes("\0")}function Pte(e){if(!hl(e,2048))return!1;try{let t=new URL(e);return t.username||t.password||t.search||t.hash?!1:t.protocol==="https:"?!0:t.protocol==="http:"&&(t.hostname==="localhost"||t.hostname==="127.0.0.1")}catch{return!1}}function Ite(e){if(!Vb(e))return{ok:!1,message:"message must be an object"};if(e.v!==xte)return{ok:!1,message:"unsupported protocol version"};let t=r=>({ok:!1,message:r});switch(e.type){case"credentials":{let r=gl(e,["v","type","apiKey","runnerTokens"]);if(r)return t(r);if(e.apiKey!==void 0&&!hl(e.apiKey,vW))return t("invalid apiKey");let n;if(e.runnerTokens!==void 0){if(!Vb(e.runnerTokens))return t("invalid runnerTokens");let o=Object.entries(e.runnerTokens);if(o.length>Ate)return t("too many runnerTokens");n={};for(let[s,i]of o){if(!Bp.test(s)||!hl(i,vW))return t("invalid runnerTokens entry");n[s]=i}}return{ok:!0,value:{v:1,type:"credentials",...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...n?{runnerTokens:n}:{}}}}case"prepare":{let r=gl(e,["v","type","id","apiBaseUrl","repo","agentOsId","expectedAccountId"]);return r?t(r):typeof e.id!="string"||!zs.test(e.id)?t("invalid id"):Pte(e.apiBaseUrl)?hl(e.repo,Ete)?e.agentOsId!==void 0&&(typeof e.agentOsId!="string"||!Bp.test(e.agentOsId))?t("invalid agentOsId"):e.expectedAccountId!==void 0&&!hl(e.expectedAccountId,128)?t("invalid expectedAccountId"):{ok:!0,value:{v:1,type:"prepare",id:e.id,apiBaseUrl:e.apiBaseUrl,repo:e.repo,...e.agentOsId!==void 0?{agentOsId:e.agentOsId}:{},...e.expectedAccountId!==void 0?{expectedAccountId:e.expectedAccountId}:{}}}:t("invalid repo"):t("invalid apiBaseUrl")}case"policy":{let r=gl(e,["v","type","id","policy"]);if(r)return t(r);if(typeof e.id!="string"||!zs.test(e.id))return t("invalid id");let n=Ew(e.policy);return typeof n=="string"?t(`invalid policy: ${n}`):{ok:!0,value:{v:1,type:"policy",id:e.id,policy:n}}}case"start":{let r=gl(e,["v","type","id","runId","agentOsId"]);return r?t(r):typeof e.id!="string"||!zs.test(e.id)?t("invalid id"):typeof e.runId!="string"||!Cte.test(e.runId)?t("invalid runId"):typeof e.agentOsId!="string"||!Bp.test(e.agentOsId)?t("invalid agentOsId"):{ok:!0,value:{v:1,type:"start",id:e.id,runId:e.runId,agentOsId:e.agentOsId}}}case"site_login":{if(typeof e.id!="string"||!zs.test(e.id))return t("invalid id");if(typeof e.agentOsId!="string"||!Bp.test(e.agentOsId))return t("invalid agentOsId");let r=zw(e);return typeof r=="string"?t(r):{ok:!0,value:{v:1,type:"site_login",id:e.id,agentOsId:e.agentOsId,...r}}}case"stop":case"status":{let r=gl(e,["v","type","id"]);return r?t(r):typeof e.id!="string"||!zs.test(e.id)?t("invalid id"):{ok:!0,value:{v:1,type:e.type,id:e.id}}}default:return t("unknown message type")}}function Ote(e){return Vb(e)&&typeof e.id=="string"&&zs.test(e.id)?e.id:null}function Tte(e){let t=ov()?"ready":"awaiting_credentials",r=null,n=null,o=null,s=(l,c,u)=>e.send({v:1,type:"reply",id:l,ok:!1,error:{code:c,message:u}}),i=(l,c)=>e.send({v:1,type:"reply",id:l,ok:!0,result:c});async function a(l){if(Ff(l))return;let c=Ite(l);if(!c.ok){s(Ote(l),"invalid_message",c.message);return}let u=c.value;switch(u.type){case"credentials":{let d={apiKey:u.apiKey,runnerTokens:u.runnerTokens};r?r.reseed(d):(r=av(d,m=>e.send(m)),nv(r)),t==="awaiting_credentials"&&(t="ready"),e.send({v:1,type:"event",name:"credentials_accepted",state:t});return}case"status":{let d=Gf();i(u.id,{state:t,prepared:n,policyRevision:d?.revision??null});return}case"policy":{if(!Iw(u.policy))return s(u.id,"stale_policy","a newer execution policy is already installed");i(u.id,{policyRevision:u.policy.revision});return}case"prepare":{if(t==="awaiting_credentials")return s(u.id,"credentials_unavailable","credentials have not been provided");if(t!=="ready")return s(u.id,"invalid_state",`cannot prepare while ${t}`);t="preparing";let{v:d,type:m,id:f,...g}=u,h;try{h=await e.prepare(g)}catch(y){return t="ready",s(f,"local_state_error",y.message)}if(!h.ok){t="ready",e.send({v:1,type:"reply",id:f,ok:!1,error:{code:h.code,message:h.message}});return}n=h.prepared,o=h.lease,Ow({accountId:n.accountId,agentOsId:n.agentOsId}),t="prepared",i(f,{prepared:n,warnings:h.warnings});return}case"start":{if(t!=="prepared"||!n||!o)return s(u.id,"invalid_state",`cannot start while ${t}`);if(u.runId!==n.runId||u.agentOsId!==n.agentOsId)return s(u.id,"not_prepared","start must name the prepared run and workspace");let d=Gf();if(!d)return s(u.id,"policy_required","no approved execution policy has been provided");if(d.accountId!==n.accountId||d.agentOsId!==n.agentOsId)return s(u.id,"policy_mismatch","the execution policy is for another account or workspace");t="running",i(u.id,{state:t});try{await e.runDaemon({run:n.runId,agentOsId:n.agentOsId,execute:!0},{hostCapability:"desktop-supervised",ownerKind:"desktop",ownerLease:o})}finally{o.release();let m=e.daemonExitCode?.()??0;e.send({v:1,type:"event",name:"daemon_exited",state:"stopping",exitCode:m}),e.exit(m)}return}case"site_login":{if(!n||t!=="prepared"&&t!=="running")return s(u.id,"invalid_state",`saved logins are unavailable while ${t}`);if(u.agentOsId!==n.agentOsId)return s(u.id,"workspace_mismatch","saved logins belong to the prepared workspace only");let{v:d,type:m,id:f,agentOsId:g,...h}=u;try{i(f,await Xw(xt(),g,h))}catch(y){let v=y instanceof q?y.code:"failed";s(f,`site_login_${v}`,y instanceof q?y.message:"the saved-login request failed")}return}case"stop":{if(t==="running"){t="stopping",i(u.id,{state:t}),e.requestDaemonStop();return}i(u.id,{state:"stopping"}),o?.release(),e.exit(0);return}}}return{handle:a,get state(){return t}}}async function Nte(e=process){if(typeof e.send!="function"||!e.connected){console.error(JSON.stringify({event:"desktop_entry_refused",reason:"no_ipc_channel"})),e.exitCode=2;return}rv();for(let s of tv)delete e.env[s];let[{prepareDesktopRuntime:t},{runDaemon:r}]=await Promise.all([Promise.resolve().then(()=>(bW(),kW)),Promise.resolve().then(()=>(Wb(),eW))]),n=s=>{if(!e.connected||typeof e.send!="function")throw new Error("desktop IPC channel is closed");e.send(s)},o=Tte({send:n,prepare:s=>t(s),runDaemon:r,requestDaemonStop:()=>{e.emit("message",{type:hc},void 0)},exit:s=>e.exit(s),daemonExitCode:()=>typeof e.exitCode=="number"?e.exitCode:0});Tw(s=>{try{n({v:1,type:"event",name:"claim_denied",state:o.state,taskId:s.taskId,code:s.code,...s.consentRequired?{consentRequired:s.consentRequired}:{}})}catch{}}),xt().onCodeRequest(({agentOsId:s,...i})=>{try{n({v:1,type:"event",name:"site_login_code_requested",state:o.state,request:i})}catch{}}),e.on("message",s=>{o.handle(s).catch(i=>{console.error(JSON.stringify({event:"desktop_entry_error",error:i.message}))})}),e.on("disconnect",()=>{if(o.state==="running"){e.emit("message",{type:hc},void 0);return}e.exit(0)}),n({v:1,type:"event",name:"ready",state:o.state})}function Dte(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===_te(e).href}catch{return!1}}Dte()&&Nte();export{xte as DESKTOP_ENTRY_PROTOCOL_VERSION,Tte as createDesktopEntryController,Ite as parseDesktopEntryMessage,Nte as startDesktopEntry};
|
|
525
|
+
_${rre[i]} stopped before finishing (${S})._`;await Ro(()=>e([{seq:w,kind:"final",message:{content:[{type:"text",text:SW(v)+L}],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:i,media:0,error:S}}}]).catch(()=>!1))}else await Ro(()=>e([{seq:w,kind:"error",error:_.slice(0,1500)}]).catch(()=>!1))}}var rre,OW=p(()=>{"use strict";rp();Wk();Jb();qb();UB();jB();qB();Xb();mW();vW();Yp();_W();iv();PW();rre=BB});import{execFile as nre}from"node:child_process";async function ure(e){let t=TW.get(e);if(t&&Date.now()-t.at<sre)return t.version;let r=await new Promise(n=>{try{let[o,s]=ae(e,["--version"]);nre(o,s,z({encoding:"utf8",timeout:5e3}),(i,a,l)=>{if(i)return n(null);n(`${a??""} ${l??""}`.match(cre)?.[0]??null)})}catch{n(null)}});return TW.set(e,{at:Date.now(),version:r}),r}async function NW(e,t,r,n=ire){let o=new AbortController,s=setTimeout(()=>o.abort(),n);try{let i=await e(t,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:o.signal});return await i.body?.cancel().catch(()=>{}),i.status}catch{return null}finally{clearTimeout(s)}}function av(e){let t=MW.get(e)??null,r=Qp(e),n=r?.ok?Date.parse(r.at):NaN,o=[t,Number.isFinite(n)?n:null].filter(s=>s!==null);return o.length?Math.max(...o):null}function Lt(e,t,r,n){let o=av(e);return{engine:e,status:t,version:r,detail:n,lastRoundTrip:Qp(e),lastReadyAt:o===null?null:new Date(o).toISOString()}}async function DW(e,t,r,n,o=Date.now){if(!t.configured&&!r)return null;let s=e==="hermes"?"Hermes":"OpenClaw";if(!t.enabled)return Lt(e,"not_enabled",r,`${s}'s local chat API is off`);if(t.key===null)return Lt(e,"no_key",r,`${s}'s local chat API has no key set`);let i=`${t.baseUrl}/v1/models`,a=await NW(n,i,t.key||null)??await NW(n,i,t.key||null,are);if(a===null){let l=av(e);return l!==null&&o()-l<lre?Lt(e,"ready",r,null):Lt(e,"unreachable",r,`${s} is not answering on ${t.baseUrl} \u2014 is its gateway running?`)}return a===401||a===403?Lt(e,"no_key",r,`${s} refused the key in its config (HTTP ${a})`):a===404?Lt(e,"not_enabled",r,`${s} is running but its chat API is not switched on`):(MW.set(e,o()),Lt(e,"ready",r,null))}function dre(e){let{version:t,signedIn:r}=(e.claudeCode??(()=>({version:Zd("claude-code",e.env),signedIn:ep(e.env)})))();return t?r?(e.config??P()).chatComputerAccess==="off"?Lt("claude-code","access_off",t,"Computer access for chat is off on this computer"):Lt("claude-code","ready",t,null):Lt("claude-code","not_signed_in",t,"Claude Code is installed but not signed in"):null}async function pre(e){let t=await jp({home:e.home,env:e.env,exists:e.grokBotExists,versionOf:e.versionOf,platform:e.platform});return Lt("grok-bot",t.status,t.version,t.detail)}async function fre(e={}){let t=e.env??process.env,r=e.fetchFn??fetch,n=e.versionOf??ure,o=t.KYNVER_HERMES_BIN?.trim()||t.HERMES_BIN?.trim()||"hermes",s=t.KYNVER_OPENCLAW_BIN?.trim()||t.OPENCLAW_BIN?.trim()||"openclaw",[i,a]=await Promise.all([n(o),n(s)]),[l,c]=await Promise.all([DW("hermes",Vp(e),i,r,e.now),DW("openclaw",Gp(e),a,r,e.now)]),u=await pre({...e,versionOf:n});return{v:1,engines:[l,c,dre(e),u].filter(f=>f!==null)}}function mre(e={}){return Rl||(wl&&Date.now()-wl.at<ore?Promise.resolve():(Rl=fre(e).then(t=>{wl={at:Date.now(),report:t}}).catch(()=>{}).finally(()=>{Rl=null}),Rl))}function lv(){if(mre(),!!wl)return{v:1,engines:wl.report.engines.map(e=>{let t=av(e.engine);return{...e,lastRoundTrip:Qp(e.engine),lastReadyAt:t===null?null:new Date(t).toISOString()}})}}var ore,sre,ire,are,lre,cre,TW,MW,wl,Rl,LW=p(()=>{"use strict";$();qe();M();Qa();iv();Xb();Yb();ore=3e4,sre=10*6e4,ire=1500,are=5e3,lre=3e4,cre=/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/,TW=new Map;MW=new Map;wl=null,Rl=null});import{readdir as gre,readFile as hre}from"node:fs/promises";import{sep as yre}from"node:path";import{fileURLToPath as kre}from"node:url";function wre(e=import.meta.url){let t;try{t=kre(e)}catch{return"checkout"}return t.split(yre).includes("node_modules")||t.split("/").includes("node_modules")?"npm":"checkout"}function Sre(e){if(typeof e!="string")return null;let t=e.trim();return t&&t.length<=Rre?t:null}async function _re(e){try{return Sre(JSON.parse(await hre(e,"utf8")).version)}catch{return null}}function xre(e,t){if(!e)return t;try{return Id(t,e)>0?t:e}catch{return e}}async function Cre(e={}){let t={},r=new Set;for(let n of(e.scopeRoots??xN)()){let o=[];try{o=await gre(n)}catch{continue}for(let s of o)/^[a-z0-9][a-z0-9._-]*$/i.test(s)&&r.add(`${BW}${s}`)}try{for(let n of await(e.adopted??rk)())n.packageName.startsWith(BW)&&r.add(n.packageName)}catch{}for(let n of[...r].sort().slice(0,vre))for(let o of jy(n)){let s=await _re(o);s&&(t[n]=xre(t[n],s))}return t}function Ere(e){cv||oi&&e-oi.at<bre||(cv=Cre().then(t=>{oi={at:Date.now(),packages:t}}).catch(()=>{oi={at:Date.now(),packages:oi?.packages??{}}}).finally(()=>{cv=null}))}function uv(e=Date.now()){try{Ere(e)}catch{}return{v:1,runtime:{version:Ge,source:wre()},packages:{...oi?.packages??{}}}}var BW,bre,vre,Rre,oi,cv,WW=p(()=>{"use strict";Vr();Vy();nk();Hy();BW="@kynver-app/",bre=10*6e4,vre=40,Rre=32;oi=null,cv=null});function Are(e,t,r){if(!t||t===r)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`${n}(?=[\\\\/"'\\s<]|$)`,"gm"),()=>r)}function UW(e,t){return Are(e,t,"\0")!==e}var FW=p(()=>{"use strict"});import{accessSync as Pre,constants as Ire,existsSync as Ore,lstatSync as Tre,readdirSync as Nre,readFileSync as Dre,readlinkSync as Mre,realpathSync as Lre}from"node:fs";import{homedir as Bre}from"node:os";import KW from"node:path";function HW(e){return e==="win32"?KW.win32:KW.posix}function Ure(e,t,r){let n=r.dirname(e);for(let o=0;o<4;o+=1){let s=t.readText(r.join(n,"package.json"));if(s)try{if(JSON.parse(s).name===dv)return n}catch{}let i=r.dirname(n);if(i===n)break;n=i}return null}function Kre(e,t,r){let n=HW(t),o=n.dirname(e),s=t==="win32"?[n.join(o,"node_modules","npm","bin","npm-cli.js")]:[n.join(o,"..","lib","node_modules","npm","bin","npm-cli.js"),n.join(o,"node_modules","npm","bin","npm-cli.js")];for(let i of s){let a=n.normalize(i);if(r.exists(a))return a}return null}function $re(e,t,r){let n=[r.join(e,".npm-global","bin","kynver"),r.join(e,".local","bin","kynver"),r.join(e,"bin","kynver")],o=t.NPM_CONFIG_PREFIX?.trim()||t.npm_config_prefix?.trim();return o&&n.unshift(r.join(o,"bin","kynver")),[...new Set(n)]}function Hre(e,t,r,n,o){for(let s of $re(t,r,o)){let i=n.readLink(s);if(!i)continue;let a=o.isAbsolute(i)?i:o.resolve(o.dirname(s),i);if(a===e||a.startsWith(`${e}${o.sep}`))return s}}function jre(e,t,r,n){let o=n.join(t,"Library","LaunchAgents");for(let s of r.readDir(o)){if(!s.endsWith(".plist"))continue;let i=n.join(o,s),a=r.readText(i);if(!a||!/kynver/i.test(a)||!e.some(c=>a.includes(c)))continue;let l=/<key>\s*Label\s*<\/key>\s*<string>([^<]+)<\/string>/.exec(a)?.[1]?.trim();if(l)return{file:i,label:l}}return null}function Vre(e,t,r,n){for(let o of[n.join(t,".kynver","bin"),n.join(t,".kynver")])for(let s of r.readDir(o)){if(!/\.(cmd|bat|ps1)$/i.test(s))continue;let i=n.join(o,s),a=r.readText(i);if(a&&e.some(l=>a.includes(l)))return i}return null}function Zp(e={}){let t=e.platform??process.platform,r=HW(t),n=e.fs??Wre,o=e.env??process.env,s=e.home??Bre(),i=e.execPath??process.execPath,a=n.realpath(e.cliEntry??process.argv[1]??""),l=a?Ure(a,n,r):null,c={cliPath:a,packageRoot:l,nodePath:i,npmCliPath:Kre(i,t,n)};if(!l)return{...c,kind:"unknown",supervisor:"none",unsupportedReason:"I could not find where Kynver is installed on this computer."};if(!l.split($W).includes("node_modules"))return{...c,kind:"checkout",supervisor:"none",unsupportedReason:"Kynver on this computer runs from a source checkout, not an installed release, so it is updated with git (pull, then build), not from chat."};let u="unknown",d={},f=Fre.exec(l);if(f)u="release_dir",d.releasesRoot=r.join(f[1],"releases"),d.releaseName=f[2],d.releaseDir=r.join(d.releasesRoot,d.releaseName),d.shimPath=Hre(d.releaseDir,s,o,n,r);else{let y=/^(.*)[\\/]lib[\\/]node_modules[\\/]@kynver-app[\\/]runtime$/.exec(l),v=t==="win32"?/^(.*)[\\/]node_modules[\\/]@kynver-app[\\/]runtime$/.exec(l):null,k=y?.[1]??v?.[1];k&&!k.split($W).includes("node_modules")&&(u="npm_global",d.npmPrefix=k)}if(u==="unknown")return{...c,kind:u,supervisor:"none",unsupportedReason:`Kynver on this computer is installed inside another project (${l}), so updating it from chat could break that project.`};let m=[d.releaseDir,l,a].filter(y=>!!y),g="keeper";if(t==="linux"){let y=r.join(s,".config","systemd","user",Ai);n.exists(y)&&(g="systemd",d.supervisorFile=y,d.supervisorName=Ai)}else if(t==="darwin"){let y=jre(m,s,n,r);y&&(g="launchd",d.supervisorFile=y.file,d.supervisorName=y.label)}else if(t==="win32"){let y=Vre(m,s,n,r);y&&(g="windows_task",d.supervisorFile=y,d.supervisorName=o.KYNVER_WINDOWS_TASK_NAME?.trim()||"Kynver")}let h={...c,kind:u,supervisor:g,...d};return h.unsupportedReason=Gre(h,n),h.unsupportedReason||delete h.unsupportedReason,h}function Gre(e,t){if(e.kind==="npm_global")return e.npmPrefix&&!t.writable(e.npmPrefix)?`Kynver is installed in ${e.npmPrefix}, which this computer's user cannot write to (it needs admin rights), so I can't update it from here.`:void 0;if(e.kind!=="release_dir")return;if(e.releasesRoot&&!t.writable(e.releasesRoot))return`I can't write a new release next to the current one (${e.releasesRoot} is not writable).`;let r=(()=>{if(!e.supervisorFile||!e.releaseDir)return!1;let n=t.readText(e.supervisorFile);return!!n&&UW(n,e.releaseDir)})();if(e.supervisor==="keeper"||e.supervisor==="none")return"Kynver runs from a release folder without a service that starts it, so a restart would bring back the old release. Run `kynver cron install --install-systemd` once (Linux) so updates can switch releases.";if(!r&&!e.shimPath)return`The service that starts Kynver (${e.supervisorFile??e.supervisor}) doesn't name the release folder or a kynver link I can switch.`}var dv,Wre,$W,Fre,ef=p(()=>{"use strict";Ho();FW();dv="@kynver-app/runtime",Wre={exists:e=>Ore(e),readText:e=>{try{return Dre(e,"utf8")}catch{return null}},readDir:e=>{try{return Nre(e)}catch{return[]}},realpath:e=>{try{return Lre.native(e)}catch{return e}},readLink:e=>{try{return Tre(e).isSymbolicLink()?Mre(e):null}catch{return null}},writable:e=>{try{return Pre(e,Ire.W_OK),!0}catch{return!1}}},$W=/[\\/]/;Fre=/^(.*)[\\/]releases[\\/]([^\\/]+)[\\/]node_modules[\\/]@kynver-app[\\/]runtime$/});function jW(e){return`npm-${e}`}function tf(e,t="latest"){let r=`${dv}@${t}`;switch(e.kind){case"release_dir":{let n=e.releasesRoot?`${e.releasesRoot}/${jW(t)}`:`<releases>/${jW(t)}`,o=e.supervisor==="systemd"?`point ${e.supervisorName??"kynver-cron-daemon.service"} at the new folder, then \`systemctl --user daemon-reload && systemctl --user restart ${e.supervisorName??"kynver-cron-daemon.service"}\``:e.supervisor==="launchd"?`point the ${e.supervisorName??"Kynver"} launch agent at the new folder, then \`launchctl kickstart -k gui/$(id -u)/${e.supervisorName??"<label>"}\``:"point whatever starts Kynver at the new folder, then restart it";return`npm install --prefix ${n} ${r} then ${o}`}case"checkout":return`cd ${e.packageRoot??"<your Kynver checkout>"} && git pull && npm install && npm run build then restart Kynver`;default:return`npm install -g ${r} then restart Kynver (or restart the computer)`}}var pv=p(()=>{"use strict";ef()});var VW=p(()=>{"use strict"});import{mkdirSync as gUe,readFileSync as Jre,readdirSync as hUe,renameSync as yUe,writeFileSync as kUe}from"node:fs";import GW from"node:path";function qre(){return GW.join(qa(),"runtime")}function Yre(e){return GW.join(e,"summary.json")}function JW(e=qre()){try{let t=JSON.parse(Jre(Yre(e),"utf8"));if(t?.v===1)return t}catch{}return{v:1,attempts:0,succeeded:0,rolledBack:0,failed:0,last:null}}var qW=p(()=>{"use strict";Nd();VW()});function Xre(e=Date.now()){if(rf&&e-rf.at<zre)return rf.report;if(!si){let o=Zp();si={kind:o.kind,supervisor:o.supervisor,can:!o.unsupportedReason,manual:tf(o,"latest")}}let t=JW(),r=t.last,n={v:1,installKind:si.kind,supervisor:si.supervisor,canSelfUpdate:si.can,manualCommand:si.manual,attempts:t.attempts,succeeded:t.succeeded,rolledBack:t.rolledBack,failed:t.failed,last:r?{id:r.id,from:r.fromVersion,to:r.toVersion,phase:r.phase,updatedAt:r.updatedAt,restartAt:r.restartAt??null,healthOk:r.health?r.health.ok:null,message:r.message?r.message.slice(0,400):null}:null};return rf={at:e,report:n},n}function fv(){try{return Xre()}catch{return}}var si,rf,zre,YW=p(()=>{"use strict";ef();pv();qW();si=null,rf=null,zre=3e4});import{mkdirSync as Qre,readFileSync as AUe,renameSync as Zre,writeFileSync as ene}from"node:fs";import{homedir as tne}from"node:os";import mv from"node:path";function rne(e=mv.join(tne(),".kynver","state")){return mv.join(e,"chat-loop.json")}function zW(e,t=rne()){try{Qre(mv.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;ene(r,JSON.stringify({v:1,...e}),{mode:384}),Zre(r,t)}catch{}}var XW=p(()=>{"use strict"});import nne from"node:os";function one(e){try{return Pt().report(e)}catch{return null}}function rU(e,t){try{return EB(e,t)}catch{return}}function gv(e=process.env){let t=P(),r=xt(t,e);return jo({boxKind:r,hostLabel:nne.hostname(),config:t,env:e})}async function lne(e,t,r){let n=r.KYNVER_RUNTIME_CHAT_BRIDGE_URL?.trim();if(n)return n.replace(/\/$/,"");if(!e)return null;let o=e.replace(/\/$/,"");if(t){let s=new AbortController,i=setTimeout(()=>s.abort(),nU);try{let a=await fetch(`${o}/api/runtime/chat-bridge`,{headers:{Authorization:`Bearer ${t}`},signal:s.signal});if(a.ok){let l=await a.json().catch(()=>null);if(typeof l?.bridgeUrl=="string"&&l.bridgeUrl.trim())return l.bridgeUrl.trim().replace(/\/$/,"")}}catch{}finally{clearTimeout(i)}}return cne(o)}async function cne(e){let t=new AbortController,r=setTimeout(()=>t.abort(),nU);try{let n=await fetch(`${e}/runtime-chat/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:t.signal});if(n.status===401||n.status===400||n.status===403){let o=n.headers.get("content-type")??"";if(o.includes("application/json")||o.includes("json")||(await n.text().catch(()=>"")).trimStart().startsWith("{"))return e}return null}catch{return null}finally{clearTimeout(r)}}function oU(e){return _e()?!0:!!e&&!!cm(e)}async function eU(e=process.env){let t=P(),r=t.agentOsId?.trim(),n=_e();if(!r||!oU(r))return null;let o=await lne(t.apiBaseUrl,n,e);if(!o)return null;let s=po(t),i=t.apiBaseUrl?.replace(/\/$/,"")??o.replace(/\/$/,"");return{bridgeUrl:o.replace(/\/$/,""),agentOsId:r,apiKey:n??"",boxId:gv(e),chatProvider:s,model:Gs(s,t,e),useClaudeOauth:t.chatUseClaudeOauth===!0,auth:new Fd({apiBaseUrl:i,agentOsId:r,boxLabel:()=>gv(e),loadApiKey:_e,loadBoxCredential:()=>cm(r),saveBoxCredential:a=>nS(r,a),clearBoxCredential:oS}),security:new Hd}}function hv(){try{return sS().apiKey}catch{return"none"}}async function une(e,t,r,n){let o=P(),s=po(o),i=await yv(e);if(!i.bearer)return"no_credential";let a=dp(s,bp(o),rU(s,o),e.security?.report({policy:n,auth:i.kind,credentialStore:hv(),folderSandbox:Ek(process.env,o)}),lv(),uv(),fv()),l=one(e.agentOsId);l&&(a.browser.siteLogins=l);let c=i.kind==="box_token"?i.boxId:gv();e.chatProvider=s,e.boxId=c,e.model=Gs(s,o,process.env);let u=new AbortController,d=setTimeout(()=>u.abort(),ine),f=setInterval(()=>{t()&&u.abort()},500);try{let m=await fetch(`${e.bridgeUrl}/runtime-chat/claim`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.bearer}`},body:JSON.stringify({agentOsId:e.agentOsId,boxId:e.boxId,waitMs:sne,capabilities:a,claimRetries:r}),signal:u.signal});if(m.status===204)return null;if(m.status===401||m.status===403){let y=await m.text().catch(()=>"");return console.error(JSON.stringify({event:"chat_claim_auth_error",status:m.status,bridgeUrl:e.bridgeUrl,agentOsId:e.agentOsId,authKind:i.kind,detail:y.slice(0,200)})),io(e,i,401),"auth_error"}if(m.status===429)throw new fn(m.status);if(!m.ok)throw new fn(m.status);let g;try{g=await m.json()}catch{throw new fn(502)}let h=wB(g);if(!h)throw new fn(502);return h.turn}catch(m){if(t())return null;throw m}finally{clearTimeout(d),clearInterval(f)}}async function Rt(e,t,r){let n=await yv(e),o=await fetch(`${e.bridgeUrl}/runtime-chat/turns/${encodeURIComponent(t)}/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.bearer}`},body:JSON.stringify({agentOsId:e.agentOsId,boxId:e.boxId,events:r})});return io(e,n,o.status),o.ok}async function tU(e,t,r){return e.security?.noteRejected(r.code),console.error(JSON.stringify({event:"chat_turn_rejected",turnId:t.turnId,requestId:t.requestId??"",code:r.code,...r.detail?{detail:r.detail}:{},reason:r.reason,policy:r.policy,...r.extra??{}})),Za({at:new Date().toISOString(),chat:t.requestId??null,turnId:t.turnId,kind:"tool",engine:"none",access:"off",command:`turn refused: ${r.code}${r.detail?` (${r.detail})`:""}`,folder:"",ok:!1,reason:`turn_rejected_${r.code}`}),await Rt(e,t.turnId,[{seq:0,kind:"error",error:L0(r.code,r.detail)}]).catch(()=>{}),{ok:!1}}async function dne(e,t,r){let n=B0({turnId:t.turnId,agentOsId:t.agentOsId,payload:t.payload},{agentOsId:e.agentOsId,policy:r.policy,nonces:r.nonces,env:r.env,nowSec:r.nowSec});if(!n.ok)return n.code==="replayed"&&n.replay?.state==="in_flight"?(e.security?.noteDuplicateOffer(),console.error(JSON.stringify({event:"chat_turn_duplicate_offer_dropped",turnId:t.turnId,requestId:t.requestId??"",firstSeenAt:n.replay.firstSeenAt,reason:n.reason})),{ok:!1}):tU(e,t,{code:n.code,reason:n.reason,policy:r.policy,...n.replay?{detail:n.replay.state,extra:{firstSeenAt:n.replay.firstSeenAt,firstTurnId:n.replay.turnId}}:{}});n.signed&&n.access?.others==="default"&&console.error(JSON.stringify({event:"chat_turn_non_owner",turnId:t.turnId,requestId:t.requestId??"",agentOsId:e.agentOsId,boxId:e.boxId,userId:n.userId??"",access:"off"}));let o=r.config;if(!o)try{o=P()}catch{o={}}let s=gD({signedAccess:n.access,boxId:e.boxId,agentOsId:e.agentOsId,engine:Qd(e.chatProvider,o,r.env??process.env),local:{chatComputerAccess:o.chatComputerAccess,chatWorkFolders:o.chatWorkFolders},state:zd(r.stateFile),env:r.env,nowSec:r.nowSec});if(!s.ok)return tU(e,t,{code:s.code,detail:s.detail,reason:s.reason,policy:r.policy,extra:{from:Xa(s.from),to:Xa(s.to),signed:n.signed}});s.website&&cD(s.website,{file:r.stateFile});let a={...yk(t.payload),...n.access?{computerAccess:n.access}:{}};return n.access||delete a.computerAccess,n.redelivered&&console.error(JSON.stringify({event:"chat_turn_redelivered",turnId:t.turnId,requestId:t.requestId??""})),{ok:!0,trust:{signed:n.signed,access:n.access},payload:a,redelivered:n.redelivered}}async function pne(e,t){let r=0,n=!1,o=new uo,s=Array.isArray(t.payload?.argv)?t.payload.argv:[],i=await CD(s,a=>{n||o.track(Rt(e,t.turnId,[{seq:r++,kind:"delta",text:a}]).then(l=>(l||(n=!0),l)))},{agentOsId:e.agentOsId,authProof:t.payload?.authProof});await o.drain(),n||(i.refused?await Rt(e,t.turnId,[{seq:r++,kind:"error",error:`command_refused: ${i.refused}`}]).catch(()=>{}):await Rt(e,t.turnId,[{seq:r++,kind:"final",message:{exitCode:i.exitCode,timedOut:i.timedOut}}]).catch(()=>{})),console.error(JSON.stringify({event:"command_turn_done",turnId:t.turnId,argv:s.slice(0,4),exitCode:i.exitCode,timedOut:i.timedOut,refused:i.refused??null}))}function fne(e,t,r,n,o){try{let s=yo({provider:t.chatProvider,config:n,payloadAccess:e.payload.computerAccess,boxId:t.boxId}),i=lD(s.access,{signed:r.signed});if(!i)return;let a=i.from?Xa(i.from.access):"not set",l=Xa(i.to.access),c={at:i.to.at,chat:e.requestId??null,turnId:e.turnId,kind:"access_change",engine:s.engine,access:i.to.access,folder:s.access.workDir,from:a,to:l,source:i.to.source,signed:r.signed,ok:!0};Za({...c,kind:"tool",command:`computer access: ${a} \u2192 ${l} (${i.to.source})`}),o(c),console.error(JSON.stringify({event:"chat_access_changed",turnId:e.turnId,from:a,to:l,source:i.to.source,signed:r.signed}))}catch{}}async function mne(e,t,r){let n=0,o=!1,s=new uo,i=new AbortController,a=t.requestId??"",l=h=>{o||s.track(Rt(e,t.turnId,[{seq:n++,kind:"delta",text:h}]).then(y=>(y||(o=!0,i.abort()),y)))},c=new ln(l),u=Hp({turnId:t.turnId,chat:a||null,send:h=>{o||(c.flush(),s.track(Rt(e,t.turnId,[{seq:n++,kind:"activity",activity:h}]).then(y=>(y||(o=!0,i.abort()),y))))}}),d=e.chatProvider??"anthropic",f=P(),m=bp(f);r&&fne(t,e,r,f,h=>{o||s.track(Rt(e,t.turnId,[{seq:n++,kind:"activity",activity:h}]).then(y=>(y||(o=!0,i.abort()),y)))});try{_b(d,e.useClaudeOauth,process.env,f)}catch(h){let y=dl(t.payload.requestedModel);if(!(y&&m.some(k=>k.provider===y.provider&&k.models.includes(y.model)))){await Rt(e,t.turnId,[{seq:0,kind:"error",error:h instanceof Error?h.message:String(h)}]).catch(()=>{});return}}let g={provider:d,model:e.model};try{let h=await wL({payload:t.payload,catalog:m,primary:{provider:d,model:e.model},onDelta:k=>c.push(k),runTurn:k=>(g={provider:k.provider,model:k.model},RL({...k,signal:i.signal,turnId:t.turnId,requestId:t.requestId,useClaudeOauth:e.useClaudeOauth,config:f,boxId:e.boxId,onActivity:u.sink}))});IB(h.content,yo({provider:g.provider,config:f,payloadAccess:t.payload.computerAccess,boxId:e.boxId}),u),c.close(),await s.drain();let y=n++;if(!await Ro(()=>o?Rt(e,t.turnId,[{seq:y,kind:"error",error:"turn_stream_aborted"}]).catch(()=>!1):Rt(e,t.turnId,[{seq:y,kind:"final",message:h}]).catch(()=>!1))){console.error(JSON.stringify({event:"chat_turn_final_rejected",requestId:a,turnId:t.turnId,model:g.model,chatProvider:g.provider}));return}console.error(JSON.stringify({event:"chat_turn_done",requestId:a,turnId:t.turnId,model:g.model,chatProvider:g.provider,fallbackReason:h.kynverModel.fallbackReason,activitySteps:u.steps}))}catch(h){c.close(),await s.drain(),o||await Rt(e,t.turnId,[{seq:n++,kind:"error",error:h instanceof Error?h.message:String(h)}]).catch(()=>{}),console.error(JSON.stringify({event:"chat_turn_error",requestId:a,turnId:t.turnId,error:h instanceof Error?h.message:String(h)}))}}async function Sl(e,t){for(let n=0;n<e&&!t();n+=500)await new Promise(o=>setTimeout(o,Math.min(500,e-n)))}async function sU(e){let t=await eU(),r=()=>oU(P().agentOsId?.trim())&&!!P().agentOsId?.trim();for(t||console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:r()?"bridge_not_discovered (rollout off, discovery route missing/404, or API unreachable)":"machine_not_linked",rediscoverMs:ZW}));!t&&!e.shouldStop();){if(!r()||(await Sl(ZW,e.shouldStop),e.shouldStop()))return;t=await eU()}if(!t||e.shouldStop())return;let n=M0(process.env,P()),o=new $d;t.security&&(t.security.childEnv=await oD().catch(u=>({ok:!1,leaked:[],error:u instanceof Error?u.message:String(u),at:new Date().toISOString()})),t.security.childEnv.ok||console.error(JSON.stringify({event:"chat_child_env_selftest_failed",...t.security.childEnv}))),console.error(JSON.stringify({event:"chat_claim_loop_start",bridgeUrl:t.bridgeUrl,agentOsId:t.agentOsId,boxId:t.boxId,model:t.model,chatProvider:t.chatProvider,capabilities:dp(t.chatProvider),useClaudeOauth:t.useClaudeOauth,turnSignature:n,credentialStore:hv(),childEnvSafe:t.security?.childEnv?.ok??null,auth:t.auth?.describe().kind??"api_key"}));let s=0,i=0,a=new $p,l=MB({target:t,capabilities:u=>{let d=P(),f=po(d);return dp(f,bp(d),rU(f,d),t.security?.report({policy:n,auth:u.kind,credentialStore:hv(),folderSandbox:Ek(process.env,d)}),lv(),uv(),fv())},onBeat:u=>zW({pid:process.pid,runtimeVersion:Ge,at:new Date().toISOString(),heartbeatOk:u,chatTurns:Math.max(0,s-i),commandTurns:i})}),c=Promise.resolve();for(;!e.shouldStop();)try{if(s>=ane){await Sl(250,e.shouldStop);continue}let u=await une(t,e.shouldStop,a.snapshot(),n);if(u==="no_credential"){console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:"machine_not_linked"})),await Sl(QW,e.shouldStop);continue}if(u==="auth_error"){a.onAuthError();let d=t.auth?.describe().hasBoxCredential===!0;await Sl(d?5e3:QW,e.shouldStop);continue}if(a.onSuccess(),u){let d=await NB(t,u.turnId);if(!TB(d.outcome)){console.error(JSON.stringify({event:"chat_turn_receipt_rejected",turnId:u.turnId,requestId:u.requestId??null,status:d.status}));continue}d.outcome!=="accepted"&&console.error(JSON.stringify({event:"chat_turn_receipt_unconfirmed",turnId:u.turnId,outcome:d.outcome,status:d.status}));let f=u.payload?.kind;s+=1;let m;if(f==="command"){i+=1;let g=()=>pne(t,u);m=c.then(g,g),c=m.then(()=>{},()=>{})}else{let g=await dne(t,u,{policy:n,nonces:o});if(!g.ok){s-=1;continue}if(o.markStarted(u.turnId),f==="browser"){let h=await yv(t);m=kB({...t,apiKey:h.bearer},{turnId:u.turnId,payload:g.payload})}else f==="agent-tab"?m=IW(h=>Rt(t,u.turnId,h),{turnId:u.turnId,payload:g.payload,boxId:t.boxId}):m=mne(t,{...u,payload:g.payload},g.trust)}m.catch(g=>{console.error(JSON.stringify({event:"chat_turn_execution_crash",turnId:u.turnId,error:g instanceof Error?g.message:String(g)}))}).finally(()=>{s-=1,f==="command"&&(i-=1),f!=="command"&&o.markFinished(u.turnId)})}}catch(u){let{kind:d,consecutive:f,backoffMs:m}=a.onError(u),g=CB(d,f),h=JSON.stringify({event:g.event,level:g.level,error:u instanceof Error?u.message:String(u),kind:d,consecutive:f,retryInMs:m});g.level==="error"?console.error(h):console.log(h),m>0&&await Sl(m,e.shouldStop)}l(),await gB(),console.error(JSON.stringify({event:"chat_claim_loop_stop"}))}var sne,ine,QW,ZW,nU,ane,yv,iU=p(()=>{"use strict";$();Le();T0();Kd();bk();W0();U0();Yd();sD();uD();hD();Qa();tp();Vo();rp();Wk();ED();tl();iM();eb();tb();xb();SL();bB();jb();Gb();Jb();AB();qb();OB();Cp();DB();LB();OW();LW();WW();Vr();YW();XW();Gb();Ki();sne=2e4,ine=32e3,QW=6e4,ZW=5*6e4,nU=5e3,ane=3,yv=$s});import{createHash as gne}from"node:crypto";import{chmodSync as aU,existsSync as hne,mkdirSync as yne,rmSync as lU}from"node:fs";import{createConnection as kne,createServer as bne}from"node:net";import{homedir as vne,userInfo as Rne}from"node:os";import wne from"node:path";function _ne(e,t=process.platform){return t==="win32"?`\\\\.\\pipe\\kynver-site-logins-${gne("sha256").update(`${Rne().username}:${vne()}`).digest("hex").slice(0,16)}`:wne.join(e,"control.sock")}async function xne(e,t){switch(t.op){case"status":return{ok:!0,data:{report:e.report(t.agentOsId),codes:e.listCodeRequests(t.agentOsId)}};case"unlock":{let r=e.store(t.agentOsId),n=e.audit(t.agentOsId);try{let o=await r.unlockWithPassphrase(t.passphrase);return e.unlock(t.agentOsId,o),o.fill(0),n.record({event:"unlock",ok:!0}),{ok:!0}}catch(o){throw n.record({event:"unlock_failed",ok:!1,code:o instanceof J?o.code:"failed"}),o}}case"lock":return e.lock(t.agentOsId),{ok:!0};case"add":{let r=e.key(t.agentOsId);if(!r)return{ok:!1,error:"saved logins are locked in the running Kynver",code:"locked"};let n=e.store(t.agentOsId),o=t.replaceHandle?n.replace(r,t.replaceHandle,t.login):n.add(r,t.login);return e.audit(t.agentOsId).record({event:t.replaceHandle?"replace":"add",ok:!0,handle:o.handle,label:o.label,username:o.username,origin:o.origin}),{ok:!0,data:o}}case"codes":return{ok:!0,data:e.listCodeRequests(t.agentOsId)};case"code":return{ok:!0,data:await e.submitCode(t.id??null,t.code,t.agentOsId)};case"wipe":return{ok:!0,data:{wiped:e.wipe(t.agentOsId)}}}}function Cne(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let r=t,n=["status","unlock","lock","add","codes","code","wipe"];return typeof r.op!="string"||!n.includes(r.op)||r.op!=="lock"&&(typeof r.agentOsId!="string"||!r.agentOsId.trim())?null:t}async function cU(e){let t=_ne(e.rootDir);if(process.platform!=="win32"){yne(e.rootDir,{recursive:!0,mode:448});try{aU(e.rootDir,448)}catch{}if(hne(t)){if(await Ene(t))return null;lU(t,{force:!0})}}let r=bne(n=>{let o="";n.setEncoding("utf8"),n.setTimeout(12e4,()=>n.destroy()),n.on("data",s=>{if(o+=s,o.length>Sne)return void n.destroy();let i=o.indexOf(`
|
|
526
|
+
`);if(i<0)return;let a=Cne(o.slice(0,i));o="";let l=c=>n.end(`${JSON.stringify(c)}
|
|
527
|
+
`);if(!a)return l({ok:!1,error:"malformed request"});xne(e,a).then(l).catch(c=>l({ok:!1,error:c instanceof J?c.message:"the request failed",code:c instanceof J?c.code:"failed"}))}),n.on("error",()=>{})});try{await new Promise((n,o)=>{r.once("error",o),r.listen(t,()=>n())})}catch(n){return console.error(JSON.stringify({event:"site_login_control_unavailable",error:n.message.slice(0,200)})),null}if(process.platform!=="win32")try{aU(t,384)}catch{}return{path:t,close:()=>new Promise(n=>{r.close(()=>n()),process.platform!=="win32"&&lU(t,{force:!0})})}}function Ene(e){return new Promise(t=>{let r=kne(e),n=o=>{r.destroy(),t(o)};r.once("connect",()=>n(!0)),r.once("error",()=>n(!1)),setTimeout(()=>n(!1),1e3).unref?.()})}var Sne,uU=p(()=>{"use strict";Nn();Sne=16*1024});function Ine(e){return e.config.browserDisabled===!0?"local_disabled":e.config.browserAutoProvision===!1?"auto_provision_off":!/^(1|true|yes|on)$/i.test(e.env.KYNVER_BROWSER_AUTOPROVISION??"")&&e.config.browserEverEnabled!==!0?"never_enabled":e.resolved.executable?"already_available":Js(e.platform,e.arch)?null:"unsupported_platform"}async function dU(e,t){let r=t.sleep??(n=>new Promise(o=>setTimeout(o,n).unref?.()));for(let n=e;n>0&&!t.shouldStop();n-=1e3)await r(Math.min(1e3,n))}async function pU(e){let t=e.env??process.env,r=e.platform??process.platform,n=e.arch??process.arch,o=e.now??Date.now,s=e.log??(l=>console.error(JSON.stringify(l))),i=e.resolve??(()=>go({env:t,platform:r,arch:n})),a=e.loadConfig??P;try{await dU(e.startDelayMs??Ane,e);for(let l=1;l<=Pne&&!e.shouldStop();l+=1){let c=Ine({config:a(),env:t,resolved:i(),platform:r,arch:n});if(c){c!=="never_enabled"&&s({event:"browser_autoprovision_skip",reason:c});return}let u=ZD(ho());if(u>o()&&await dU(u-o(),e),e.shouldStop())return;s({event:"browser_autoprovision_start",attempt:l});try{let d=await(e.provision??lp)({env:t,platform:r,arch:n});s({event:"browser_autoprovision_done",version:d.version});return}catch(d){s({event:"browser_autoprovision_failed",attempt:l,error:d instanceof Error?d.message.slice(0,200):String(d)})}}}catch(l){s({event:"browser_autoprovision_crash",error:l instanceof Error?l.message.slice(0,200):String(l)})}}var Ane,Pne,fU=p(()=>{"use strict";$();fo();ol();cp();Ane=6e4,Pne=5});function kv(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(e.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Dne(e,t){let r=kv(e),n=kv(t);if(!r||!n)return!1;for(let o=0;o<3;o+=1)if(r[o]!==n[o])return r[o]<n[o];return!1}function Mne(e,t,r={}){let n=r.manual??`${nf} then restart Kynver (or restart the computer)`,o=r.selfUpdate===!1?"":'Say "update Kynver" in Kynver chat and it updates itself, or run `kynver update` here. ';return`Kynver on this computer is out of date (installed ${e}, latest ${t}). ${o}By hand: ${n}`}function Lne(){try{let e=Zp();return{manual:tf(e,"latest"),selfUpdate:!e.unsupportedReason}}catch{return{manual:`${nf} then restart Kynver (or restart the computer)`,selfUpdate:!1}}}async function Bne(e={}){let t=e.installed??Ge,r={installed:t,latest:null,outdated:!1,command:nf};if((e.env??process.env).KYNVER_DISABLE_UPDATE_CHECK==="1")return r;let o=new AbortController,s=setTimeout(()=>o.abort(),Tne);try{let a=await(e.fetch??fetch)(One,{signal:o.signal,headers:{accept:"application/json"}});if(!a.ok)return r;let l=await a.json(),c=typeof l?.version=="string"&&kv(l.version)?l.version:null;return c?{installed:t,latest:c,outdated:Dne(t,c),command:nf}:r}catch{return r}finally{clearTimeout(s)}}function gU(e={}){let t=e.log??(s=>console.error(s)),r=null,n=async()=>{let s=await Bne(e);if(s.outdated&&s.latest&&s.latest!==r){r=s.latest;let i=(e.advice??Lne)();t(JSON.stringify({event:"runtime_update_available",installed:s.installed,latest:s.latest,command:i.manual,selfUpdate:i.selfUpdate})),t(Mne(s.installed,s.latest,i))}return s};n().catch(()=>{});let o=setInterval(()=>{n().catch(()=>{})},e.intervalMs??Nne);return o.unref?.(),{stop:()=>clearInterval(o),checkNow:n}}var mU,nf,One,Tne,Nne,hU=p(()=>{"use strict";Vr();pv();ef();mU="@kynver-app/runtime",nf=`npm install -g ${mU}@latest`,One=`https://registry.npmjs.org/${mU}/latest`,Tne=5e3,Nne=360*6e4});var vU={};Lv(vU,{adoptOrAcquireOwnerLease:()=>kU,completeWorker:()=>EP,dispatchRun:()=>Ts,resolveDaemonOwnerKind:()=>yU,runDaemon:()=>bU,runPipelineTick:()=>Ld,sweepRun:()=>md});async function bv(e,t,r){let n=e;for(;n>0&&!t();){let o=Math.min(Kne,n),s=Date.now();await Bl(o);let i=Gm(o,Date.now()-s);if(i!==null){r?.(i);return}n-=o}}function yU(e,t={},r=process.env){return t.ownerKind?t.ownerKind:e.keeperChild===!0||e.keeperChild==="true"?"keeper":r.INVOCATION_ID?.trim()?"systemd":"foreground"}async function kU(e,t,r,n=Vc){return r?r.released||!r.isHeld()||r.metadata.agentOsId!==e?{ok:!1,reason:"owner_conflict",holder:null,remedy:"the owner lease handed to the daemon is not held for this workspace; restart the runtime"}:{ok:!0,lease:r,quarantinedMetadata:null}:n({agentOsId:e,ownerKind:t})}async function bU(e,t={}){let r=sg({hostCapability:t.hostCapability}),n=Qe()?{loaded:0}:hw();n.loaded>0&&console.error(JSON.stringify({event:"daemon_env_file_loaded",...n}));let o=String(e.run||"").trim();o||(console.error(Qm("--run")),process.exit(1));let s=String(e.agentOsId||P().agentOsId||"").trim();s||(console.error(Qm("--agent-os-id")),process.exit(1)),Xo(s).ok||(console.error(im(s)),console.error("Diagnose: run `kynver doctor runner-install`. Still stuck? `kynver report-bug --json` (draft only \u2014 create a GitHub issue to actually send it)."),process.exit(1));let a=e.execute!==!1&&e.execute!=="false",l=Number(e.intervalMs)>0?Math.floor(Number(e.intervalMs)):Wne,c=!1,u=0,d=dS(O=>{c||console.error(JSON.stringify({event:"daemon_stop_requested",reason:O,runId:o})),c=!0}),f=await kU(s,yU(e,t),t.ownerLease);if(!f.ok){console.error(JSON.stringify({event:"daemon_start_blocked",reason:"owner_conflict",runId:o,agentOsId:s,holder:f.holder?{ownerKind:f.holder.ownerKind,pid:f.holder.pid,runtimeVersion:f.holder.runtimeVersion,acquiredAt:f.holder.acquiredAt}:null,remedy:f.remedy})),d(),process.exit(1);return}let m=f.lease;_w(m.metadata.ownerKind),yx({admission:r.allowed?{basis:r.basis,hostCapability:r.hostCapability}:null,ownerKind:m.metadata.ownerKind});let g={kind:m.metadata.ownerKind,instanceId:m.metadata.instanceId,processStart:m.metadata.processStart,runtimeVersion:m.metadata.runtimeVersion};console.error(JSON.stringify({event:"daemon_owner_lease_acquired",agentOsId:s,ownerKind:m.metadata.ownerKind,instanceId:m.metadata.instanceId,quarantinedStaleMetadata:f.quarantinedMetadata!==null}));let h=dx(o);h.killed.length>0&&console.error(JSON.stringify({event:"daemon_orphaned_worker_descendants_killed",runId:o,orphans:h.killed.map(O=>({worker:O.workerName,workerPid:O.workerPid,pid:O.orphanPid,outcome:O.result.outcome}))}));let y=null,v=O=>{y=O};try{let O=rS();(O.moved.length>0||O.stillInFile.length>0)&&console.error(JSON.stringify({event:"daemon_credentials_store",...O}))}catch(O){console.error(JSON.stringify({event:"daemon_credentials_store_error",error:O instanceof Error?O.message:String(O)}))}let k=q_();k.remediated&&console.error(JSON.stringify({event:"daemon_default_repo_remediated",defaultRepo:k.resolved?.defaultRepo??null,configPath:k.configPath}));let b=cx(P());b.ok||(console.error(JSON.stringify({event:"daemon_start_blocked",runId:o,agentOsId:s,errors:b.errors})),console.error("Diagnose: run `kynver doctor runner-install`. Still stuck? `kynver report-bug --json` (draft only \u2014 create a GitHub issue to actually send it)."),process.exit(1)),console.error(JSON.stringify({event:"daemon_start",runId:o,agentOsId:s,execute:a,intervalMs:l,boxKind:b.box.boxKind,workerCapSource:b.workerCapSource,maxConcurrentWorkers:b.maxConcurrentWorkers})),gU();let _=rs(),S=new Ud;S.start();let R=new Wd({agentOsId:s,init:{ownerKind:m.metadata.ownerKind,admission:r.allowed?{basis:r.basis,hostCapability:r.hostCapability}:null}});S.setTickIsolation(R.mode),console.error(JSON.stringify({event:"daemon_tick_isolation",mode:R.mode,reason:R.reason}));let w=cU(Pt()).catch(()=>null),L=sU({shouldStop:()=>c}).catch(O=>{console.error(JSON.stringify({event:"chat_claim_loop_crashed",error:O instanceof Error?O.message:String(O)}))});pU({shouldStop:()=>c});let N=!1;for(;!c;)try{if(y!==null){let x=y;y=null;let T=m.isHeld();if(console.error(JSON.stringify({event:"daemon_resume_detected",agentOsId:s,gapMs:x,ownerLeaseHeld:T})),!T){console.error(JSON.stringify({event:"daemon_owner_lease_lost",agentOsId:s,runId:o})),process.exitCode=1,c=!0;break}}S.setPhase("heartbeat"),m.renew(),S_({agentOsId:s,runId:o,instructionBundleVersion:Mn(),owner:g}),S.setPhase("runner_credential");let O=await Cc(e.secret?String(e.secret):void 0,s,{baseUrl:e.baseUrl?String(e.baseUrl):void 0});if(!O.ok){N||(N=!0,console.error(JSON.stringify({event:"daemon_runner_credential_missing",agentOsId:s,reason:O.reason,remedy:`run \`kynver runner credential --agent-os-id ${s}\` (or \`kynver bootstrap\`); ticks resume automatically once the credential exists`}))),S.setPhase("idle"),await bv(l,()=>c,v);continue}N&&(N=!1,console.error(JSON.stringify({event:"daemon_runner_credential_recovered",agentOsId:s}))),S.setPhase("instruction_bundle"),await ix({agentOsId:s,baseUrl:An(e.baseUrl?String(e.baseUrl):void 0),secret:O.secret}),S.setPhase(R.mode==="thread"?"pipeline_tick_thread":"pipeline_tick_inline");let W=await R.runTick({run:o,agentOsId:s,execute:a,...e,secret:typeof e.secret=="string"&&e.secret?e.secret:O.secret},S.report());S.setTickIsolation(W.isolation);let D=W.tick;S.setPhase("tick_log"),console.error(JSON.stringify({event:"daemon_tick",tickIsolation:W.isolation,...D})),S.setPhase("runtime_control");let G=Kr(s),Q=W.inFlightWorkers??Bd(s)??0;if(ww(G,Q)){let x=pc({control:G,supervisor:m.metadata.ownerKind,inFlightWorkers:0,exiting:!0}),T=An(e.baseUrl?String(e.baseUrl):void 0),U=x&&T?await k_({baseUrl:T,agentOsId:s,secret:O.secret},x):!1;console.error(JSON.stringify({event:"daemon_runtime_stopped",agentOsId:s,runId:o,policyVersion:G?.policyVersion??null,requestedBy:G?.requestedByLabel??null,reported:U})),process.exitCode=dc,c=!0;break}if(_.tickEnabled){S.setPhase("cron_tick");let x=eu(o);if(x&&!x.authorized)console.error(JSON.stringify({event:"daemon_cron_tick_skipped",reason:"mesh_cron_lease_not_authorized",holderBoxId:x.holderBoxId}));else{let T=await dg({env:_,agentOsIdFilter:s});T.enabled&&(T.fired>0||T.errors>0||T.lockHeld)&&console.error(JSON.stringify({event:"daemon_cron_tick",...T}))}}D.idle?u++:u=0;let H=Math.floor(is("daemon.maxIdleStreak",Fne)),E=Math.floor(is("daemon.idleIntervalMs",Une)),V=u>=H?E:l;S.setPhase("idle"),await bv(V,()=>c,v)}catch(O){console.error(JSON.stringify({event:"daemon_tick_error",error:O.message})),S.setPhase("idle"),await bv(l,()=>c,v)}S.setPhase("stopping"),await L,await R.close(),S.stop(),await(await w)?.close().catch(()=>{}),Pt().lock();let A=pS(o);A.length>0&&console.error(JSON.stringify({event:"daemon_stop_worker_trees_killed",runId:o,workers:A.map(O=>({worker:O.workerName,pid:O.pid,outcome:O.result.outcome}))})),d(),m.release(),console.error(JSON.stringify({event:"daemon_stop",runId:o,agentOsId:s}))}var Wne,Une,Fne,Kne,vv=p(()=>{"use strict";$();Zm();Y_();ax();Gr();ux();Vm();Oc();Gc();St();Jm();px();Qc();ig();pg();gr();cr();fg();M();P0();gk();O0();iU();Ki();uU();fU();hU();$r();jm();mk();Nu();Sy();Ps();Wne=6e4,Une=5*6e4,Fne=10,Kne=250});var RU=p(()=>{"use strict";Y();No();Ry();Ce();M()});var _l,wU=p(()=>{"use strict";_l=class extends Error{remedy;exitCode;constructor(t,r={}){super(t,r.cause===void 0?void 0:{cause:r.cause}),this.name="OperatorActionableError",this.remedy=r.remedy,this.exitCode=r.exitCode??1}}});import{existsSync as $ne,mkdirSync as Hne}from"node:fs";import jne from"node:path";function Vne(e){let t=typeof e.repo=="string"?e.repo.trim():"";if(t)return t;let r=Ji();return r?r.repo:(_t("","--repo (or set defaultRepo via `kynver setup` / KYNVER_DEFAULT_REPO)"),"")}function Gne(e){let t=e.repoLabel??"the repo",r=[],n=e.explicitBase?.trim();n&&r.push({ref:n,source:"flag",origin:"--base"});let o=e.envBaseRef?.trim();o&&r.push({ref:o,source:"env",origin:"KYNVER_RUN_BASE_REF"});let s=e.configDefaultBase?.trim();s&&r.push({ref:s,source:"config",origin:"defaultBase in ~/.kynver/config.json"});let i=r[0];if(i){if(e.verifyRef(i.ref))return{base:i.ref,source:i.source};throw new Error([`run base ref "${i.ref}" (from ${i.origin}) does not resolve in ${t}.`,"Fetch it (`git fetch origin`) or fix the override \u2014 refusing to silently use a different base."].join(" "))}if(e.verifyRef("origin/main"))return{base:"origin/main",source:"origin/main"};let a=e.resolveRemoteHeadRef();if(a&&e.verifyRef(a))return{base:a,source:"remote-head",note:`origin/main not found in ${t} \u2014 using the remote default branch ${a}`};throw new Error([`cannot resolve a base ref for a new run in ${t}: origin/main does not exist`,a?`and the remote default branch (${a}) did not verify either.`:"and no remote default branch could be resolved (origin/HEAD unset).",`Run \`git fetch origin\` in ${t}, or pass --base <ref> / set KYNVER_RUN_BASE_REF / set defaultBase in ~/.kynver/config.json.`].join(" "))}function Jne(e){let t=ee(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]);if(t.status===0){let n=t.stdout.trim().replace(/^refs\/remotes\//,"");if(n)return n}let r=ee(e,["ls-remote","--symref","origin","HEAD"]);if(r.status===0){let n=/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(r.stdout);if(n?.[1])return`origin/${n[1]}`}return null}function qne(e,t){let r=P();try{return Gne({explicitBase:typeof t.base=="string"?t.base:void 0,envBaseRef:process.env.KYNVER_RUN_BASE_REF,configDefaultBase:r.defaultBase,verifyRef:n=>ee(e,["rev-parse","--verify","--quiet",`${n}^{commit}`]).status===0,resolveRemoteHeadRef:()=>Jne(e),repoLabel:e})}catch(n){throw new _l(n.message,{remedy:"Diagnose: run `kynver doctor runner-install`.",cause:n})}}function Rv(e){let t=hP(Vne(e));Yv(t);let r=e.id?Lh(String(e.id)):Nl(String(e.name||"run")),n=j(r);$ne(n)&&Yne(`run already exists: ${r}`),Hne(n,{recursive:!0});let o=qne(t,e);o.note&&console.error(o.note);let s=o.base,i=ce(t,["rev-parse",s]).trim(),a=Wt(),l={id:r,name:String(e.name||r),repo:t,base:s,baseCommit:i,status:"created",createdAt:new Date().toISOString(),workers:{},...a.identity?{boxKind:a.identity.boxKind,runnerId:a.identity.runnerId,harnessRoot:a.identity.harnessRoot}:{}};be(jne.join(n,"run.json"),l);let c={runId:r,runDir:n,repo:t,base:s,baseCommit:i};return console.log(JSON.stringify(c,null,2)),c}function Yne(e){throw new _l(e)}var wv=p(()=>{"use strict";we();Y();RU();M();us();ad();Sn();$();wU()});function SU(e,t){return e.filter(n=>n.repo===t&&!Or.has(n.status)).sort((n,o)=>(o.createdAt??"").localeCompare(n.createdAt??""))[0]??null}var _U=p(()=>{"use strict";we();rn()});var xU=p(()=>{"use strict";gr();ns();ug()});var of=p(()=>{"use strict";gr();cr()});var sf=p(()=>{"use strict"});var Sv=p(()=>{"use strict"});var _v=p(()=>{"use strict";xU();gr();ns();of();cr();sf();Sv()});var CU=p(()=>{"use strict"});var EU=p(()=>{"use strict";of();sf()});var AU=p(()=>{"use strict";cr();gr()});var PU=p(()=>{"use strict";$();at();St();M();pg();CU();EU();cr();of();AU();uc();Ho();ns();_v();sf();Sv();Y()});var IU=p(()=>{"use strict";_v();PU()});var OU=p(()=>{"use strict";Ho();uc();$();cr();fc();Jf();Pi();Y()});function TU(e,t){return SU(e,t)?.id??null}var NU=p(()=>{"use strict";$();Dm();vv();Zm();ig();Gc();wv();Y();_U();us();IU();Hm();Xf();us();tl();OU()});var WU={};Lv(WU,{prepareDesktopRuntime:()=>poe,resolveDesktopRepository:()=>BU});import{spawnSync as DU}from"node:child_process";import{randomBytes as toe}from"node:crypto";import{existsSync as roe,mkdirSync as noe,readFileSync as ooe,realpathSync as MU,statSync as soe,writeFileSync as ioe}from"node:fs";import{homedir as aoe}from"node:os";import Cv from"node:path";function ve(e,t){return{ok:!1,code:e,message:t}}function loe(){return Cv.join(aoe(),".kynver","desktop-binding.json")}function coe(e){if(!roe(e))return null;try{let t=JSON.parse(ooe(e,"utf8"));if(t?.version===1&&typeof t.cloudOrigin=="string"&&typeof t.accountId=="string"&&typeof t.agentOsId=="string"&&typeof t.repo=="string"&&typeof t.runId=="string")return t}catch{}return null}function uoe(e,t){noe(Cv.dirname(e),{recursive:!0}),ioe(e,`${JSON.stringify(t,null,2)}
|
|
528
|
+
`,{mode:384})}function LU(e,t){return e===401||e===403?ve("access_denied",`${t} was refused (${e})`):e===0?ve("network",`${t} could not reach Kynver`):ve("server_error",`${t} failed (${e})`)}async function xv(e,t,r,n={}){try{let o=await ut(e,{...n,headers:{...n.headers,Authorization:`Bearer ${t}`}},r),s=await o.json().catch(()=>null);return{status:o.status,body:s}}catch{return{status:0,body:null}}}function doe(e){return(e?.accessibleItems??[]).filter(t=>t.access?.isOwner===!0&&typeof t.agentOs?.id=="string").map(t=>(t.agentOs?.id).trim()).filter(Boolean)}function BU(e,t="git"){let r=DU(t,["--version"],z({encoding:"utf8"}));if(r.error||r.status!==0)return ve("no_git","Git is not installed or not on PATH");let n;try{if(n=MU.native(Cv.resolve(e)),!soe(n).isDirectory())return ve("not_a_repository","The selected path is not a folder")}catch{return ve("not_a_repository","The selected folder does not exist")}let o=DU(t,["rev-parse","--is-bare-repository","--show-toplevel"],z({cwd:n,encoding:"utf8"})),s=(o.stdout??"").trim().split(/\r?\n/);if(o.status!==0||s[0]!=="false"||!s[1])return ve("not_a_repository","The selected folder is not inside a Git working tree");try{return{ok:!0,repo:MU.native(s[1].trim())}}catch{return ve("not_a_repository","The Git working tree root could not be resolved")}}async function poe(e,t={}){let r=t.fetchImpl??fetch,n=t.acquireOwnerLease??Vc,o=t.bindingPath??loe(),s=[],i=or(e.apiBaseUrl);if(!i)return ve("invalid_input","apiBaseUrl is required");let a=gi(i),l=new URL(a).origin;if(e.agentOsId!==void 0&&!Xo(e.agentOsId).ok)return ve("invalid_input","agentOsId is not a valid workspace id");let c;try{c=_e()}catch(S){if(S instanceof ai)return ve("credentials_unavailable","This computer's credentials have not been provided");throw S}if(!c)return ve("credentials_unavailable","This computer is not paired");let u=await xv(`${a}/api/users/me`,c,r);if(u.status!==200)return LU(u.status,"Account lookup");let d=typeof u.body?.id=="string"?u.body.id:"";if(!d)return ve("server_error","Account lookup returned no account id");if(e.expectedAccountId&&e.expectedAccountId!==d)return ve("account_mismatch","The paired credentials belong to a different account");let f=await xv(`${a}/api/agent-os/provision`,c,r,{method:"POST"});!(f.status>=200&&f.status<300)&&f.status!==401&&f.status!==403&&s.push(`workspace self-provision returned ${f.status||"no response"}; continuing with existing access`);let g=await xv(`${a}/api/agent-os`,c,r);if(g.status!==200)return LU(g.status,"Workspace lookup");let h=g.body,y;if(e.agentOsId){if(!doe(h).includes(e.agentOsId))return ve("agent_os_not_owned","That workspace is not owned by the paired account");y=e.agentOsId}else{let S=Tm(h);if(!S?.id)return ve("no_workspace","No workspace owned by this account was found");y=S.id}let v=BU(e.repo,t.gitBinary);if(!v.ok)return v;let k=v.repo,b=await n({agentOsId:y,ownerKind:"desktop"});if(!b.ok)return{ok:!1,code:"owner_conflict",message:b.remedy,holder:b.holder?{ownerKind:b.holder.ownerKind,pid:b.holder.pid,runtimeVersion:b.holder.runtimeVersion,acquiredAt:b.holder.acquiredAt}:null};let _=b.lease;try{We({...P(),apiBaseUrl:a,agentOsId:y,defaultRepo:k});let S=$m(P());s.push(...S.warnings);let R=P().boxId?.trim()??"";if(!R)return _.release(),ve("local_state_error","Box identity could not be established");if(await Mm(jr()),!Te(y))try{let W=await Pn(y,{baseUrl:a,apiKey:c});En(y,W)}catch(W){let D=W.message;if(QS(D)==="access_denied")return _.release(),ve("access_denied","This computer was refused a runner credential");s.push("runner credential mint did not succeed yet; the runtime retries automatically")}let w=coe(o),L=w!==null&&w.cloudOrigin===l&&w.accountId===d&&w.agentOsId===y&&w.repo===k,N="";if(L){let W=TU(Se().filter(D=>D.id===w.runId),k);W&&(N=W)}if(!N){let W=`${Nl("desktop")}-${toe(3).toString("hex")}`;N=Rv({repo:k,name:"desktop",id:W}).runId}uoe(o,{version:1,cloudOrigin:l,accountId:d,agentOsId:y,repo:k,runId:N});let A=Mc(k);A||s.push("the repository has no origin remote; nothing can run until it has one");let{runnerId:O}=De({runId:N});return{ok:!0,prepared:{accountId:d,agentOsId:y,runId:N,repo:k,boxId:R,repoIdentity:A,runnerId:O},lease:_,warnings:s}}catch(S){return _.release(),ve("local_state_error",S.message)}}var UU=p(()=>{"use strict";sr();Dm();Nm();$();St();gr();ns();Gc();Lc();Y();yr();Hm();NU();wv();M()});St();import{pathToFileURL as foe}from"node:url";var $v="credential.persist";function Hv(e,t){let r,n=new Map,o=s=>{r=s.apiKey?.trim()||void 0,n=new Map(Object.entries(s.runnerTokens??{}).map(([i,a])=>[i.trim(),a.trim()]).filter(([i,a])=>i&&a))};return o(e),{kind:"desktop",getApiKey:()=>r,getRunnerToken(s){if(s)return n.get(s);if(n.size===1)return n.values().next().value},persistApiKey(s){let i=s.trim();if(!i)throw new Error("refusing to persist an empty API key");r=i,t({v:1,type:$v,kind:"apiKey",value:i})},persistRunnerToken(s,i){let a=s.trim(),l=i.trim();if(!a||!l)throw new Error("refusing to persist an empty runner token binding");n.set(a,l),t({v:1,type:$v,kind:"runnerToken",agentOsId:a,value:l})},reseed:o}}Oc();Lc();Nn();Pm();var KS=/^lg_[a-z0-9]{6,20}$/,mj=/^cr_[0-9a-f]{12}$/,gj=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Dn=(e,t,r=1)=>typeof e=="string"&&e.length>=r&&e.length<=t&&!e.includes("\0");function ts(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function $S(e){let t=["v","type","id","agentOsId","op"];switch(e.op){case"key":return ts(e,[...t,"key"])??(Dn(e.key,64,40)&&/^[A-Za-z0-9+/]{43}=$/.test(e.key)?{op:"key",key:e.key}:"invalid key");case"list":case"wipe":return ts(e,t)??{op:e.op};case"remove":return ts(e,[...t,"handle"])??(typeof e.handle=="string"&&KS.test(e.handle)?{op:"remove",handle:e.handle}:"invalid handle");case"code":{let r=ts(e,[...t,"requestId","code"]);return r||(e.requestId!==void 0&&!(typeof e.requestId=="string"&&mj.test(e.requestId))?"invalid requestId":Dn(e.code,16)?{op:"code",code:e.code,...e.requestId?{requestId:e.requestId}:{}}:"invalid code")}case"add":{let r=ts(e,[...t,"login","replaceHandle"]);if(r)return r;let n=e.login;return!gj(n)||ts(n,["origin","label","username","password","totp"])||!Dn(n.origin,2048)||!Dn(n.label,pt.maxLabel)||!Dn(n.username,pt.maxUsername)||!Dn(n.password,pt.maxPassword)||n.totp!==void 0&&!Dn(n.totp,pt.maxTotp,0)?"invalid login":e.replaceHandle!==void 0&&!(typeof e.replaceHandle=="string"&&KS.test(e.replaceHandle))?"invalid replaceHandle":{op:"add",login:{origin:n.origin,label:n.label,username:n.username,password:n.password,...n.totp?{totp:n.totp}:{}},...e.replaceHandle?{replaceHandle:e.replaceHandle}:{}}}default:return"unknown site_login op"}}async function HS(e,t,r){let n=e.store(t),o=e.audit(t);switch(r.op){case"key":{let s=Buffer.from(r.key,"base64");try{if(n.exists()&&n.keyMode()==="passphrase")return{state:e.isUnlocked(t)?"unlocked":"locked",keyMode:"passphrase"};if(n.exists())try{n.unlockWithKey(s)}catch(i){if(!(i instanceof J)||i.code!=="bad_key")throw i;e.wipe(t),o.record({event:"wipe",ok:!0,code:"keychain_key_replaced"})}return n.exists()||n.createWithKeychainKey(s),e.unlock(t,s,{keychain:!0}),{state:"unlocked",keyMode:"keychain"}}finally{s.fill(0)}}case"list":return{logins:n.list(),report:e.report(t),codes:e.listCodeRequests(t)};case"add":{let s=e.key(t);if(!s)throw new J("saved logins are locked","locked");let i=r.replaceHandle?n.replace(s,r.replaceHandle,r.login):n.add(s,r.login);return r.login.password="",o.record({event:r.replaceHandle?"replace":"add",ok:!0,handle:i.handle,label:i.label,username:i.username,origin:i.origin}),{login:i}}case"remove":{let s=n.get(r.handle),i=n.remove(r.handle);return i&&s&&o.record({event:"remove",ok:!0,handle:r.handle,label:s.label,username:s.username,origin:s.origin}),{removed:i}}case"code":return await e.submitCode(r.requestId??null,r.code,t);case"wipe":return{wiped:e.wipe(t)}}}Ki();Nn();var moe=1,af=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ii=/^[A-Za-z0-9_-]{1,64}$/,goe=/^[a-z0-9][a-z0-9._-]{0,127}$/i,FU=4096,hoe=4096,yoe=16;function Ev(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function xl(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function Cl(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!e.includes("\0")}function koe(e){if(!Cl(e,2048))return!1;try{let t=new URL(e);return t.username||t.password||t.search||t.hash?!1:t.protocol==="https:"?!0:t.protocol==="http:"&&(t.hostname==="localhost"||t.hostname==="127.0.0.1")}catch{return!1}}function boe(e){if(!Ev(e))return{ok:!1,message:"message must be an object"};if(e.v!==moe)return{ok:!1,message:"unsupported protocol version"};let t=r=>({ok:!1,message:r});switch(e.type){case"credentials":{let r=xl(e,["v","type","apiKey","runnerTokens"]);if(r)return t(r);if(e.apiKey!==void 0&&!Cl(e.apiKey,FU))return t("invalid apiKey");let n;if(e.runnerTokens!==void 0){if(!Ev(e.runnerTokens))return t("invalid runnerTokens");let o=Object.entries(e.runnerTokens);if(o.length>yoe)return t("too many runnerTokens");n={};for(let[s,i]of o){if(!af.test(s)||!Cl(i,FU))return t("invalid runnerTokens entry");n[s]=i}}return{ok:!0,value:{v:1,type:"credentials",...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...n?{runnerTokens:n}:{}}}}case"prepare":{let r=xl(e,["v","type","id","apiBaseUrl","repo","agentOsId","expectedAccountId"]);return r?t(r):typeof e.id!="string"||!ii.test(e.id)?t("invalid id"):koe(e.apiBaseUrl)?Cl(e.repo,hoe)?e.agentOsId!==void 0&&(typeof e.agentOsId!="string"||!af.test(e.agentOsId))?t("invalid agentOsId"):e.expectedAccountId!==void 0&&!Cl(e.expectedAccountId,128)?t("invalid expectedAccountId"):{ok:!0,value:{v:1,type:"prepare",id:e.id,apiBaseUrl:e.apiBaseUrl,repo:e.repo,...e.agentOsId!==void 0?{agentOsId:e.agentOsId}:{},...e.expectedAccountId!==void 0?{expectedAccountId:e.expectedAccountId}:{}}}:t("invalid repo"):t("invalid apiBaseUrl")}case"policy":{let r=xl(e,["v","type","id","policy"]);if(r)return t(r);if(typeof e.id!="string"||!ii.test(e.id))return t("invalid id");let n=bS(e.policy);return typeof n=="string"?t(`invalid policy: ${n}`):{ok:!0,value:{v:1,type:"policy",id:e.id,policy:n}}}case"start":{let r=xl(e,["v","type","id","runId","agentOsId"]);return r?t(r):typeof e.id!="string"||!ii.test(e.id)?t("invalid id"):typeof e.runId!="string"||!goe.test(e.runId)?t("invalid runId"):typeof e.agentOsId!="string"||!af.test(e.agentOsId)?t("invalid agentOsId"):{ok:!0,value:{v:1,type:"start",id:e.id,runId:e.runId,agentOsId:e.agentOsId}}}case"site_login":{if(typeof e.id!="string"||!ii.test(e.id))return t("invalid id");if(typeof e.agentOsId!="string"||!af.test(e.agentOsId))return t("invalid agentOsId");let r=$S(e);return typeof r=="string"?t(r):{ok:!0,value:{v:1,type:"site_login",id:e.id,agentOsId:e.agentOsId,...r}}}case"stop":case"status":{let r=xl(e,["v","type","id"]);return r?t(r):typeof e.id!="string"||!ii.test(e.id)?t("invalid id"):{ok:!0,value:{v:1,type:e.type,id:e.id}}}default:return t("unknown message type")}}function voe(e){return Ev(e)&&typeof e.id=="string"&&ii.test(e.id)?e.id:null}function Roe(e){let t=Fv()?"ready":"awaiting_credentials",r=null,n=null,o=null,s=(l,c,u)=>e.send({v:1,type:"reply",id:l,ok:!1,error:{code:c,message:u}}),i=(l,c)=>e.send({v:1,type:"reply",id:l,ok:!0,result:c});async function a(l){if(dm(l))return;let c=boe(l);if(!c.ok){s(voe(l),"invalid_message",c.message);return}let u=c.value;switch(u.type){case"credentials":{let d={apiKey:u.apiKey,runnerTokens:u.runnerTokens};r?r.reseed(d):(r=Hv(d,f=>e.send(f)),Uv(r)),t==="awaiting_credentials"&&(t="ready"),e.send({v:1,type:"event",name:"credentials_accepted",state:t});return}case"status":{let d=ym();i(u.id,{state:t,prepared:n,policyRevision:d?.revision??null});return}case"policy":{if(!wS(u.policy))return s(u.id,"stale_policy","a newer execution policy is already installed");i(u.id,{policyRevision:u.policy.revision});return}case"prepare":{if(t==="awaiting_credentials")return s(u.id,"credentials_unavailable","credentials have not been provided");if(t!=="ready")return s(u.id,"invalid_state",`cannot prepare while ${t}`);t="preparing";let{v:d,type:f,id:m,...g}=u,h;try{h=await e.prepare(g)}catch(y){return t="ready",s(m,"local_state_error",y.message)}if(!h.ok){t="ready",e.send({v:1,type:"reply",id:m,ok:!1,error:{code:h.code,message:h.message}});return}n=h.prepared,o=h.lease,SS({accountId:n.accountId,agentOsId:n.agentOsId}),t="prepared",i(m,{prepared:n,warnings:h.warnings});return}case"start":{if(t!=="prepared"||!n||!o)return s(u.id,"invalid_state",`cannot start while ${t}`);if(u.runId!==n.runId||u.agentOsId!==n.agentOsId)return s(u.id,"not_prepared","start must name the prepared run and workspace");let d=ym();if(!d)return s(u.id,"policy_required","no approved execution policy has been provided");if(d.accountId!==n.accountId||d.agentOsId!==n.agentOsId)return s(u.id,"policy_mismatch","the execution policy is for another account or workspace");t="running",i(u.id,{state:t});try{await e.runDaemon({run:n.runId,agentOsId:n.agentOsId,execute:!0},{hostCapability:"desktop-supervised",ownerKind:"desktop",ownerLease:o})}finally{o.release();let f=e.daemonExitCode?.()??0;e.send({v:1,type:"event",name:"daemon_exited",state:"stopping",exitCode:f}),e.exit(f)}return}case"site_login":{if(!n||t!=="prepared"&&t!=="running")return s(u.id,"invalid_state",`saved logins are unavailable while ${t}`);if(u.agentOsId!==n.agentOsId)return s(u.id,"workspace_mismatch","saved logins belong to the prepared workspace only");let{v:d,type:f,id:m,agentOsId:g,...h}=u;try{i(m,await HS(Pt(),g,h))}catch(y){let v=y instanceof J?y.code:"failed";s(m,`site_login_${v}`,y instanceof J?y.message:"the saved-login request failed")}return}case"stop":{if(t==="running"){t="stopping",i(u.id,{state:t}),e.requestDaemonStop();return}i(u.id,{state:"stopping"}),o?.release(),e.exit(0);return}}}return{handle:a,get state(){return t}}}async function woe(e=process){if(typeof e.send!="function"||!e.connected){console.error(JSON.stringify({event:"desktop_entry_refused",reason:"no_ipc_channel"})),e.exitCode=2;return}Wv();for(let s of Bv)delete e.env[s];let[{prepareDesktopRuntime:t},{runDaemon:r}]=await Promise.all([Promise.resolve().then(()=>(UU(),WU)),Promise.resolve().then(()=>(vv(),vU))]),n=s=>{if(!e.connected||typeof e.send!="function")throw new Error("desktop IPC channel is closed");e.send(s)},o=Roe({send:n,prepare:s=>t(s),runDaemon:r,requestDaemonStop:()=>{e.emit("message",{type:Ic},void 0)},exit:s=>e.exit(s),daemonExitCode:()=>typeof e.exitCode=="number"?e.exitCode:0});_S(s=>{try{n({v:1,type:"event",name:"claim_denied",state:o.state,taskId:s.taskId,code:s.code,...s.consentRequired?{consentRequired:s.consentRequired}:{}})}catch{}}),Pt().onCodeRequest(({agentOsId:s,...i})=>{try{n({v:1,type:"event",name:"site_login_code_requested",state:o.state,request:i})}catch{}}),e.on("message",s=>{o.handle(s).catch(i=>{console.error(JSON.stringify({event:"desktop_entry_error",error:i.message}))})}),e.on("disconnect",()=>{if(o.state==="running"){e.emit("message",{type:Ic},void 0);return}e.exit(0)}),n({v:1,type:"event",name:"ready",state:o.state})}function Soe(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===foe(e).href}catch{return!1}}Soe()&&woe();export{moe as DESKTOP_ENTRY_PROTOCOL_VERSION,Roe as createDesktopEntryController,boe as parseDesktopEntryMessage,woe as startDesktopEntry};
|