@kynver-app/runtime 0.2.118 → 0.2.127
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +258 -185
- package/dist/daemon-tick-thread.js +175 -0
- package/dist/desktop-entry.js +214 -143
- package/dist/index.js +281 -208
- 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 +2 -2
package/dist/desktop-entry.js
CHANGED
|
@@ -1,29 +1,93 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
1
|
+
var MU=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 Tv=(e,t)=>{for(var r in t)MU(e,r,{get:t[r],enumerable:!0})};function Dv(){_o=!0}function Xe(){return _o}function Mv(e){if(!_o)throw new Error("installDesktopCredentialProvider requires desktop credential mode");if(e.kind!=="desktop")throw new Error("only a desktop credential provider may be installed");if(ai)throw new Error("desktop credential provider is already installed");ai=e}function Lv(){return ai!==null}function Bv(e){if(!_o)return e;if(!ai)throw new ii;return ai}function Ee(e,t=process.env){if(_o)return;let r=t[e]?.trim();return r||void 0}function cf(){if(_o)throw new lf}var Nv,ii,lf,_o,ai,wt=p(()=>{"use strict";Nv=["KYNVER_API_KEY","KYNVER_RUNNER_TOKEN","KYNVER_CHAT_BOX_CREDENTIAL","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","OPENCLAW_RUNNER_TOKEN"],ii=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},lf=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},_o=!1,ai=null});import{homedir as uf}from"node:os";import hn from"node:path";function Ol(e){return e==="~"?uf():e.startsWith("~/")||e.startsWith("~\\")?hn.join(uf(),e.slice(2)):e}function De(e){return hn.resolve(Ol(e))}function LU(e){let t=Ol(e),r=hn.resolve(t),n=hn.resolve(uf());return r===n?"~":r.startsWith(`${n}${hn.sep}`)?`~/${hn.relative(n,r).split(hn.sep).join("/")}`:r.replace(/\\/g,"/").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^[A-Za-z]:\/home\/[^/]+(?=\/|$)/i,"~").replace(/^[A-Za-z]:\/Users\/[^/]+(?=\/|$)/i,"~")}function $e(e){return LU(e)}var it=p(()=>{"use strict"});import{spawnSync as BU}from"node:child_process";function FU(e){return["/PID",String(e),"/T","/F"]}function KU(e){return e.error?{method:"taskkill",outcome:"failed",detail:e.error.message}:e.status===0?{method:"taskkill",outcome:"signalled"}:e.status===WU||/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 $U(e){let t=BU("taskkill",e,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","pipe"],timeout:UU});return{status:t.status,stderr:t.stderr??"",...t.error?{error:t.error}:{}}}function HU(e){return Number.isInteger(e)&&e>0}function ye(e,t="SIGTERM",r={}){if(!HU(e))return{method:"none",outcome:"not_found"};if((r.platform??process.platform)==="win32"){let s=r.runTaskkill??$U;return KU(s(FU(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 ve(e=process.platform){return e!=="win32"}function Qe(e,t="SIGTERM",r={}){if((r.platform??process.platform)==="win32"&&e.pid){ye(e.pid,t,r);return}try{e.kill(t)}catch{}}var WU,UU,li=p(()=>{"use strict";WU=128,UU=15e3});import{existsSync as jU,mkdirSync as VU,readFileSync as Fv,readdirSync as foe,renameSync as GU,rmSync as JU,statSync as Kv,writeFileSync as qU}from"node:fs";import{randomBytes as YU}from"node:crypto";import zU from"node:path";function at(e){console.error(e),process.exit(1)}function z(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function St(e,t){return e||at(`missing ${t}`),e}function ci(e){try{return JSON.parse(e)}catch{return null}}function K(e,t){try{return JSON.parse(Fv(e,"utf8"))}catch(r){if(arguments.length>1)return t;at(`failed to read ${e}: ${r.message}`)}}function ke(e,t){VU(zU.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${YU(4).toString("hex")}.tmp`;try{qU(r,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`),GU(r,e)}catch(n){try{JU(r,{force:!0})}catch{}throw n}}function B(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function Tl(e){return B(`${new Date().toISOString().replace(/[-:]/g,"").replace(/\..+/,"Z")}-${e}`)}function yn(e){return String(e).replace(/\/+$/,"")}function Nl(e){try{return Kv(e).size}catch{return 0}}function Dl(e){try{return Kv(e).mtime.toISOString()}catch{return null}}function xo(e,t){return jU(e)?Fv(e,"utf8").split(`
|
|
3
3
|
`).slice(-t).join(`
|
|
4
|
-
`):""}function
|
|
5
|
-
`).map(t=>t.trim()).filter(Boolean)}function Q(e,t){try{let r=qb("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 Jb(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 Rl(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 Bp(n,"missing worktree path");let s=Q(e,["rev-parse","HEAD"]);if(s.status!==0)return Bp(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 Bp(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=Jb(e,i,a),c=Jb(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 Bp(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";rt();N();Xs()});import{existsSync as eU,mkdirSync as zb}from"node:fs";import{homedir as Up}from"node:os";import ko from"node:path";function Qb(e=Up()){return ko.join(e,".kynver",tU)}function Zb(e,t=Up()){return ko.resolve(e)===ko.resolve(Qb(t))}function rU(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 Xb(e){Q(e,["rev-parse","--verify","HEAD^{commit}"]).status!==0&&(rU(e),Q(e,["commit","--allow-empty","-m","kynver byoc workspace"]))}function ev(e=Up()){let t=Qb(e);zb(ko.dirname(t),{recursive:!0});let r=!1;eU(t)||(zb(t,{recursive:!0}),r=!0);let n=Q(t,["rev-parse","--show-toplevel"]);if(n.status!==0)return Q(t,["init","-b","main"]),Xb(t),r=!0,{repo:ko.resolve(t),created:r};let o=ko.resolve(n.stdout.trim()||t);return Xb(o),{repo:o,created:r}}var tU,Wp=p(()=>{"use strict";ve();tU="workspace"});import{existsSync as Kp,readFileSync as rv}from"node:fs";import{homedir as nv}from"node:os";import ot from"node:path";import{fileURLToPath as nU}from"node:url";function sU(e){let t=ot.join(e,"package.json");if(!Kp(t))return null;try{let r=JSON.parse(rv(t,"utf8"));return typeof r.name=="string"?r.name.trim():null}catch{return null}}function ov(e){return sU(e)==="kynver"}function tv(e){let t=ot.resolve(e);if(!Kp(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?ot.resolve(n):null}function iU(e=import.meta.url){let t=ot.dirname(nU(e));for(let r=0;r<8;r+=1){let n=ot.join(t,"package.json");if(Kp(n))try{if(JSON.parse(rv(n,"utf8")).name==="@kynver-app/runtime")return t}catch{}let o=ot.dirname(t);if(o===t)break;t=o}return null}function Fp(e,t,r,n,o){if(!r)return;let s=ot.resolve(r);e.has(s)||(o?.requireMonorepo??!0)&&!ov(s)||(e.add(s),t.push({repo:s,source:n}))}function sv(e){let t=e?.cwd??process.cwd(),r=new Set,n=[];Fp(r,n,tv(t),"cwd_git",{requireMonorepo:!1});let o=iU(e?.runtimeModuleUrl??import.meta.url);o&&Fp(r,n,tv(o),"runtime_checkout");let s=nv();for(let a of oU)Fp(r,n,Oe(ot.join(s,a)),"well_known_path");let i=ot.resolve(e?.cwd??process.cwd());return n.filter(a=>{if(a.source!=="runtime_checkout"||!ov(a.repo))return!0;let l=ot.resolve(a.repo);return i===l||i.startsWith(`${l}${ot.sep}`)})}function wl(e){return sv(e)[0]??null}function aU(e){let t=ot.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 Sl(e){let t=sv(e),r=t.find(o=>!aU(o.repo));if(r)return r;if(t[0])return t[0];let{repo:n}=ev(e?.home??nv());return{repo:n,source:"byoc_workspace"}}var oU,Zs=p(()=>{"use strict";ve();rt();Wp();oU=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});function ei(e){let t=an(e);try{let r=new URL(t);return r.hostname.toLowerCase()===iv?(r.hostname=`www.${iv}`,an(r.toString())):t}catch{return t}}function er(e){if(e?.trim())return ei(an(e.trim()))}async function st(e,t,r=fetch){let n=ei(e),o=new Headers(t?.headers),s=0;for(;s<=av;){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 ${av} redirects for ${e}`)}var iv,av,tr=p(()=>{"use strict";N();iv="kynver.com";av=10});function ln(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 _l(e,t){return e[t]?.trim()||null}function lv(e){let t=e?.split(":")[0]?.trim();return t?ln(t):null}function Xe(e=process.env,t={}){let r=[],n=lv(t.boxId),o=lv(_l(e,"KYNVER_BOX_ID")),s=t.boxKind?.trim();if(s)return n&&n!==ln(s)&&r.push(`config.boxId=${t.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:ln(s),source:"config",slugInferenceBlocked:!1,warnings:r};let i=_l(e,"KYNVER_BOX_KIND");if(i)return o&&o!==ln(i)&&r.push(`KYNVER_BOX_ID=${_l(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:ln(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=_l(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 vt(e={},t=process.env){return Xe(t,e).boxKind}var Ne=p(()=>{"use strict"});function $p(e,t){return e==="forge"?4:Math.max(1,t)}function rr(e,t){return e==="forge"?Math.min(Math.max(1,t),4):Math.max(1,t)}function ti(e,t){return e==="forge"&&t>4}var bo=p(()=>{"use strict"});import{readFileSync as lU}from"node:fs";import cv from"node:os";function uv(e){if(e!==void 0){let t=e.match(/^MemAvailable:\s+(\d+)\s*kB/m);return t?Number(t[1])*1024:cv.freemem()}if(process.platform==="linux")try{let r=lU("/proc/meminfo","utf8").match(/^MemAvailable:\s+(\d+)\s*kB/m);if(r)return Number(r[1])*1024}catch{}return cv.freemem()}var dv=p(()=>{"use strict"});import{existsSync as cU,readFileSync as uU,statfsSync as dU}from"node:fs";function Hp(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!cU(e))continue;let t=uU(e,"utf8");if(/microsoft|wsl/i.test(t))return!0}catch{}return!1}function pv(e={}){if(!(e.forceWsl===void 0?Hp():e.forceWsl))return null;let r=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||vo,n=e.wslHostFreeWarnBytes??pU,o=e.wslHostFreeCriticalBytes??fU,s=e.statfs??dU,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. ${mU()}`),{ok:m,path:r,freeBytes:a,totalBytes:l,usedPercent:c,warnBelowBytes:n,criticalBelowBytes:o,reason:g,probeError:null}}function mU(){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 pU,fU,vo,jp=p(()=>{"use strict";pU=25*1024*1024*1024,fU=12*1024*1024*1024,vo="/mnt/c"});import{execFileSync as fv}from"node:child_process";import{existsSync as Cl,readFileSync as mv,readdirSync as gU,statSync as hU}from"node:fs";import Vp from"node:path";function xl(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function gv(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=fv("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()||vo;return t&&Cl(Vp.join(r,"Users",t))?t:null}function RU(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()||vo,n=e.windowsUser??gv();return n?`${r.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function wU(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 SU(){try{if(Cl("/proc/sys/kernel/core_pattern"))return mv("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return fv("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function _U(e){return!!(e&&/wsl-capture-crash/i.test(e))}function xU(e,t=vo){let r=Vp.join(t,"Users",e,".wslconfig");if(!Cl(r))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=mv(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 CU(e){if(!Cl(e))return[];let t=gU(e,{withFileTypes:!0}),r=[];for(let n of t){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=Vp.join(e,n.name);try{let s=hU(o),i=wU(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 Ro(e={}){if(!(e.forceWsl===void 0?Hp():e.forceWsl))return null;let r=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||vo,n=e.windowsUser??gv(),o=e.warnBelowBytes??xl("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",yU),s=e.criticalBelowBytes??xl("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",kU),i=e.warnCount??xl("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",bU),a=e.criticalCount??xl("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",vU),l=(e.readCorePattern??SU)(),c=_U(l),u=null;n&&(u=(e.readWslConfig??xU)(n,r));let d=u?.maxCrashDumpCount??null,m=d===-1,f=RU({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??CU)(f)}catch(A){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}: ${A.message}`,probeError:A.message}}let h=g.reduce((A,C)=>A+C.bytes,0),y=g.length,b=[...new Set(g.map(A=>A.executableHint).filter(A=>!!A))],k=h>=s,v=h>=o,S=y>=a,_=y>=i,R=!(k||S||v||_),M=null;if(!R){let A=k||S?"critical":"warning",C=(h/1024**3).toFixed(1),$=b.length>0?b.join(", "):"unknown";M=`WSL crash dumps ${A}: ${y} file(s), ${C} GiB at ${f} (executables: ${$}). `+EU({wslCaptureEnabled:c,dumpsDisabledInWslConfig:m})}return{ok:R,path:f,windowsUser:n,dumpCount:y,totalBytes:h,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:g,executables:b,corePattern:l,wslCaptureEnabled:c,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:M,probeError:null}}function EU(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 yU,kU,bU,vU,El=p(()=>{"use strict";jp();yU=5*1024*1024*1024,kU=10*1024*1024*1024,bU=2,vU=4});import{statfsSync as AU}from"node:fs";function Nr(e={}){let t=e.diskPath?.trim()||"/",r=e.diskFreeWarnBytes??PU,n=e.diskFreeCriticalBytes??IU,o=e.diskMaxUsedPercent??OU,s=e.diskHardMaxUsedPercent??TU,i=AU(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:pv(e.wslHost),b=e.skipWslCrashDumpCheck?null:Ro(e.wslCrashDumps),k=h&&(y?y.ok:!0)&&(b?b.ok:!0),v=null;return k||(v=[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,b&&!b.ok?b.reason:null].filter(Boolean).join("; ")),NU({ok:k,path:t,freeBytes:a,totalBytes:l,usedPercent:c,warnBelowBytes:r,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:v,wslHost:y,wslCrashDumps:b?{ok:b.ok,path:b.path,dumpCount:b.dumpCount,totalBytes:b.totalBytes,executables:b.executables,wslCaptureEnabled:b.wslCaptureEnabled,dumpsDisabledInWslConfig:b.dumpsDisabledInWslConfig,reason:b.reason,probeError:b.probeError}:null})}function NU(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 PU,IU,OU,TU,ri=p(()=>{"use strict";El();jp();PU=30*1024*1024*1024,IU=15*1024*1024*1024,OU=80,TU=90});import{existsSync as DU,readdirSync as MU}from"node:fs";import LU from"node:path";function Rt(e){let t=new Set;for(let n of Object.keys(e.workers||{}))t.add(L(n));let r=LU.join(G(e.id),"workers");if(!DU(r))return[...t];for(let n of MU(r,{withFileTypes:!0}))n.isDirectory()&&t.add(L(n.name));return[...t]}var wo=p(()=>{"use strict";z();N()});function Gp(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 hv(e){let t=e.trim();if(!t)return null;let r=Gp(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let l=Gp(s[1]??"");l&&n.push(l)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let l=Gp(t.slice(i,a+1));l&&n.push(l)}return n.length>0?n[n.length-1]:null}function yv(e){let t=e.finalResult??e.final_result;if(t!=null)return typeof t=="string"?hv(t)??(t.trim()||null):t;let r=typeof e.summary=="string"?e.summary.trim():"";if(!r)return null;let n=hv(r);return n||r}var kv=p(()=>{"use strict"});import{existsSync as BU,readFileSync as UU}from"node:fs";function bv(e){return e==="complete"}function nr(e){return bv(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function De(e){let t={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!BU(e))return t;let r=Date.now()+WU,n=new Date(r).toISOString(),o=UU(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=Ov();for(let s of r){let i=Ys(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=hW(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=yW(m);f&&(t.currentTool=f)}let l=wW(i);l&&SW(t,Pv({command:l.command,exitCode:l.exitCode,stdout:l.stdout,stderr:l.stderr,interleavedOutput:l.interleaved}));let c=Tl(i),u=c?null:Tv(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"&&kW(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"}RW(t,i)}return t}var ii=p(()=>{"use strict";Iv();N();Ol();Xp();Nv()});function Dv(e,t=240){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}function ai(e){let t=(e??"").trim();if(!t)return null;if(si(t))return{blocked:!0,reason:`provider authentication failed: ${Dv(t)}`};for(let r of _W)if(r.test.test(t))return{blocked:!0,reason:`${r.label}: ${Dv(t)}`};return null}var _W,Zp=p(()=>{"use strict";Ol();_W=[{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 Mv(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function xW(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 CW(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:Mv(e.head)}function EW(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 xo(e){if(e.alive||xW(e.finalResult))return null;let t=(e.changedFiles??[]).filter(i=>i.trim()).length,r=Mv(e.headCommit)??CW(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:EW(s,t,r)}}var Nl=p(()=>{"use strict"});function li(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function AW(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 PW(e){if(li(e.headCommit)||li(e.prUrl)||li(e.artifactBundlePath)||li(e.patchPath))return!0;let t=e.gitAncestry;return!!(t?.checked&&t.headIsAncestorOfBase===!1&&li(t.head))}function Co(e){return AW(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:PW(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 Lv(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var Dl=p(()=>{"use strict"});function ef(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 Bv(e){let t=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(t)?t.length:0}function Eo(e){let t=e.trim();if(!t)return null;let r=ef(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let u=ef(s[1]??"");u&&n.push(u)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let u=ef(t.slice(i,a+1));u&&n.push(u)}if(n.length===0)return null;let l=n[n.length-1],c=Bv(l);for(let u of n){let d=Bv(u);d>c&&(l=u,c=d)}return l}var Ml=p(()=>{"use strict"});function Uv(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 Wv(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function IW(e){return new Set(e.map(t=>Wv(Uv(t)??t)).filter(Boolean))}function Fv(e,t,r){let n=Uv(e)??e;if(!n)return"unrelated";let o=Wv(n);return IW(t).has(o)?"contract":r?(r.outcome==="skipped"||r.outcome==="blocked")&&r.reason?.trim()?"support":(r.outcome==="merged","unrelated"):"unrelated"}var Kv=p(()=>{"use strict"});function Ao(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function OW(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function un(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:Ao(e)}function Ll(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function $v(e){let t=null;if(typeof e=="string"){let o=Eo(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=un(String(s.prUrl??s.pr_url??"")),a=Ao(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:Ao(s.mergeCommit??s.merge_commit),reason:Ao(s.reason)})}return n}function Hv(e,t){let r=[],n=un(Ao(e.prUrl)??"");if(n&&r.push(n),t&&typeof t=="object"&&!Array.isArray(t)){let o=t,s=un(String(o.prUrl??o.pr_url??""));s&&r.push(s)}return[...new Set(r)]}function jv(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(!OW(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?un(Ao(t.targetPrUrl)??"")??(t.targetPrUrls.length===1?un(t.targetPrUrls[0]):null):null;if(s){let d=Hv(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=$v(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=$v(n),a=new Map(i.map(d=>[Ll(d.prUrl),d])),l=new Set(t.targetPrUrls.map(d=>Ll(un(d)??d)).filter(Boolean)),c=Hv(r,n);if(t.landingOnly)for(let d of c){let m=a.get(Ll(d)),f=Fv(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=Ll(un(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 Vv(e){if(e.blocked)return e.detail??e.reason}var Gv=p(()=>{"use strict";Ml();Kv()});function NW(e){let t=Date.now();if(e.providerTerminalError||Il(e.finalResult)||e.finalResult&&e.error?.trim()||si(e.error)||si(e.finalResult)){let o=e.error||(typeof e.finalResult=="string"?e.finalResult:"provider terminal error");return{state:"blocked",reason:ai(o)?.reason??`provider terminal error: ${o}`}}if(e.completionBlocker&&!Jv(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&MW(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=Co(o);if(s.blocked){let i=Lv(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=jv({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Vv(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(DW(e))return{state:"done",reason:"empty abandoned worker record"};let o=ai(e.error);if(o)return{state:"blocked",reason:o.reason};let s=xo({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>TW)return{state:"needs_attention",reason:`no first stream event ${Np(r)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&t-n>tf?{state:"stale",reason:`no log/event/heartbeat activity for ${Np(n)}s`}:{state:"ok",reason:"recent activity"}}function Jv(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function DW(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 MW(e){let t=null;if(typeof e=="string"?t=Eo(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 LW(e,t,r){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:t||(n??nr(r))}function te(e,t={}){let r=_o(e.stdoutPath),n=De(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=LW(e,r.finalResult,n),i=o?!1:ie(e.pid),a=kl(e.stdoutPath),l=kl(e.stderrPath),c=kl(e.heartbeatPath),u=Qs(e.worktreePath),d=Rl(e.worktreePath,{base:t.base,baseCommit:t.baseCommit}),m=Gb([r.lastEventAt,n.lastHeartbeatAt,bl(e.stdoutPath),bl(e.stderrPath),bl(e.heartbeatPath)]),f=r.error||!i&&!s&&Tp(e.stderrPath,10).trim()||void 0,g=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,h=Jv(g)?null:g,y=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,b=NW({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||b.state==="blocked"?"blocked":o||b.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:k,attention:b,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 rf(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}function Bl(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 TW,tf,Se=p(()=>{"use strict";cn();ii();Ol();Zp();Nl();ve();Dl();Gv();Ml();N();TW=18e4,tf=6e5});import{readFileSync as BW}from"node:fs";function UW(e){if(!e||process.platform!=="linux")return null;try{return BW(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ")}catch{return null}}function qv(e){if(!e.pid||process.platform!=="linux")return!0;let t=UW(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 Dr(e){if(typeof e.completionBlocker=="string"&&e.completionBlocker.trim())return!1;let t=te(e);return t.alive&&!qv(e)?!1:t.alive&&!t.finalResult&&t.attention.state!=="done"}var Ul=p(()=>{"use strict";Se()});import zv from"node:os";import Xv from"node:path";function Yv(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function WW(e=I(),t,r){let n=Yv(e.perWorkerMemBytes,Wl),o=Yv(e.memReserveBytes,Fl),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):Kl)),i=Oo({config:e,configuredMaxWorkersOverride:t,totalMemBytes:r??zv.totalmem()});return{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i.configuredMaxWorkers,autoCap:i.autoCap,workerCapSource:i.workerCapSource}}function Qv(e,t={}){let r=t.perWorkerMemBytes??Wl,n=t.memReserveBytes??Fl,o=t.memUtilization??Kl,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/r));return Math.min(i,$l)}function FW(){return uv()}function KW(e){let t=0;for(let r of Rt(e)){let n=W(Xv.join(G(e.id),"workers",L(r),"worker.json"),void 0);!n||!Dr(n)||t++}return t}function nf(){let e=0;for(let t of Re())e+=KW(t);return e}function Po(){let e=[];for(let t of Re())for(let r of Rt(t)){let n=W(Xv.join(G(t.id),"workers",L(r),"worker.json"),void 0);n&&Dr(n)&&e.push({runId:t.id,workerName:r})}return e}function ci(e){let t=e.config??I(),r=e.totalMemBytes??zv.totalmem(),{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i,autoCap:a,workerCapSource:l}=WW(t,e.configuredMaxWorkersOverride,r),c=vt(t),u=e.freeMemBytes??FW(),d=e.activeWorkers??nf(),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=rr(c,i??h),b=Math.max(0,Math.min(y,f)),k=Math.max(0,b-d),S=Math.min(k,g),w=e.skipDiskGate||process.env.KYNVER_RESOURCE_GATE_SKIP_DISK==="1"?void 0:Nr({diskPath:e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/"});w&&!w.ok&&(S=0);let R=null;return S<=0&&(w&&!w.ok?R=w.reason??"disk gate blocked worker admission":d>=b?R=`at worker limit (${d}/${b} running)`:g<=0?R="insufficient free memory \u2014 waiting for workers to finish":R="no worker slots available"),{ok:S>0,totalMemBytes:r,freeMemBytes:u,memReserveBytes:o,perWorkerMemBytes:n,configuredMaxWorkers:i,workerCapSource:l,boxKind:c,autoCap:h,capacityWorkers:f,maxConcurrentWorkers:b,activeWorkers:d,slotsAvailable:S,reason:R,...w?{diskGate:w}:{}}}var Wl,Fl,Kl,$l,Io=p(()=>{"use strict";dv();K();Ne();bo();ui();ri();z();wo();Ul();N();Wl=500*1024*1024,Fl=4*1024*1024*1024,Kl=.85,$l=64});function di(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function Oo(e){let t=e.config??{},r=e.env??process.env,n=di(t.perWorkerMemBytes,Wl),o=di(t.memReserveBytes,Fl),s=Math.min(1,Math.max(.1,Number(t.memUtilization)>0?Number(t.memUtilization):Kl)),i=Qv(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:di(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(t.maxConcurrentWorkers!==void 0&&t.maxConcurrentWorkers!==null){let c=di(t.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,$l),autoCap:i,workerCapSource:"config"}}let l=(r.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||r.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&r.KYNVER_MAX_WORKERS&&di(r.KYNVER_MAX_WORKERS,0)||null;return l?{configuredMaxWorkers:Math.min(l,$l),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var ui=p(()=>{"use strict";Io()});import{existsSync as $W,mkdirSync as mre,readFileSync as HW,writeFileSync as gre}from"node:fs";import{homedir as jW}from"node:os";import VW from"node:path";function GW(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 Hl(e=Mr){return $W(e)?GW(HW(e,"utf8")):new Map}function Zv(e=Mr,t={}){let r=Hl(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 Mr,or=p(()=>{"use strict";Mr=VW.join(jW(),".kynver",".env")});var eR=p(()=>{"use strict"});var tR=p(()=>{"use strict";eR()});var jl=p(()=>{"use strict"});import{existsSync as JW,readFileSync as qW}from"node:fs";import{homedir as YW}from"node:os";import zW from"node:path";function sf(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function of(e){return typeof e=="string"&&e.trim()?e:null}function af(e){let t=sf(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=of(t.requestedAt);return o?{desiredState:r,policyVersion:n,requestedAt:o,requestedByLabel:of(t.requestedByLabel),reason:of(t.reason)}:null}function rR(e){let t=sf(sf(e)?.response);return!t||t.runtimeControl===void 0?null:af(t.runtimeControl)}function nR(e,t=YW()){let r=e.replace(/[^A-Za-z0-9_-]/g,"_");return zW.join(t,".kynver",`runtime-control-${r}.json`)}function lf(e,t,r){try{let n=To(e,r);if(n&&n.policyVersion>t.policyVersion)return;ye(nR(e,r),{contractVersion:1,agentOsId:e,control:t,deliveredAt:new Date().toISOString()})}catch{}}function To(e,t){try{let r=nR(e,t);if(!JW(r))return null;let n=JSON.parse(qW(r,"utf8"));return n.agentOsId!==e?null:af(n.control)}catch{return null}}function Gl(e){return e?.desiredState??"running"}function XW(e){return e==="keeper"||e==="desktop"}function QW(e,t,r=!1){let n=Gl(e);return n==="paused"?"paused":n==="stopped"?r&&t===0?"stopped":"stopping":"running"}function Jl(e){return e.control?{policyVersion:e.control.policyVersion,state:QW(e.control,e.inFlightWorkers,e.exiting),supervised:XW(e.supervisor),inFlightWorkers:Math.max(0,Math.floor(e.inFlightWorkers))}:null}function oR(e){let t=Gl(e);return t==="paused"?"runtime_paused":t==="stopped"?"runtime_stopped":null}function sR(e,t){return Gl(e)==="stopped"&&t===0}function aR(e){iR=e}function lR(){return iR}var Vl,iR,dn=p(()=>{"use strict";N();Vl=83;iR=null});var pi=p(()=>{"use strict";tR();jl();dn()});import{existsSync as ZW,readFileSync as eF}from"node:fs";function cf(){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(ZW("/proc/version")){let e=eF("/proc/version","utf8");if(/microsoft/i.test(e))return"wsl"}}catch{}return"linux"}return"linux"}var ql=p(()=>{"use strict"});var uf=p(()=>{"use strict";ql()});var fi=p(()=>{"use strict";or();rt();K();pi();uf()});import sF from"node:os";function mi(e,t){let r=(t??sF.hostname()).trim().toLowerCase().replace(/\s+/g,"-")||"unknown-host";return`${e}:${r}`}function uR(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function Yl(e,t){let r=e.trim();if(!r)return mi(t);let n=r.indexOf(":");if(n>=0){let o=r.slice(0,n).trim().toLowerCase()||t,s=uR(r.slice(n+1));return s?`${o}:${s}`:mi(o)}return`${t}:${uR(r)}`}function No(e){let t=e.explicitBoxId?.trim()||e.env?.KYNVER_BOX_ID?.trim()||e.config?.boxId?.trim();return t?Yl(t,e.boxKind):mi(e.boxKind,e.hostLabel)}var Do=p(()=>{"use strict";Ne();Ne()});var dR=p(()=>{"use strict";or();pi();fi()});import{existsSync as sr,mkdirSync as iF,readdirSync as zl,renameSync as pR,statSync as aF}from"node:fs";import ir from"node:path";function mR(e){try{return aF(e).isDirectory()}catch{return!1}}function lF(e){if(!sr(e))return!0;for(let t of fR){let r=ir.join(e,t);if(sr(r)&&(!mR(r)||zl(r).length>0))return!1}return!0}function cF(e){let t=ir.join(e,"runs");if(!sr(t)||!mR(t))return!1;for(let r of zl(t,{withFileTypes:!0})){if(!r.isDirectory()||r.name==="runs")continue;let n=ir.join(t,r.name,"run.json");if(W(n,void 0)?.id)return!0}return!1}function uF(e){let t=ir.join(e,"runs");if(!sr(t))return!1;for(let r of zl(t,{withFileTypes:!0})){if(!r.isDirectory())continue;if(W(ir.join(t,r.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function dF(e){let t=ir.join(e,"ghost");return sr(t)?!sr(ir.join(t,"runs")):uF(e)}function gR(e){return cF(e.sharedRoot)?lF(e.forgeRoot)?dF(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 hR(e,t){iF(t,{recursive:!0});for(let r of fR){let n=ir.join(e,r),o=ir.join(t,r);if(sr(n)){if(sr(o)&&zl(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(sr(o)){pR(n,o);continue}pR(n,o)}}}var fR,yR=p(()=>{"use strict";N();fR=["runs","worktrees"]});import{existsSync as Be}from"node:fs";import{homedir as pF}from"node:os";import Ce from"node:path";function df(e=process.env){return e.HOME?.trim()||pF()}function pf(e=process.env){return Ce.join(df(e),".kynver","harness")}function Xl(e){let t=Ce.resolve(Oe(e.trim()));for(;fF.has(Ce.basename(t));)t=Ce.dirname(t);return t}function mF(e,t=process.env){return Ce.join(pf(t),e)}function gF(e=process.env){let t=pf(e);if(Be(Ce.join(t,"runs")))return!0;if(Be(t)&&!Be(Ce.join(t,"ghost"))&&!Be(Ce.join(t,"forge")))return Be(t);let r=Ce.join(df(e),kR);return Be(r)}function Ql(e){let t=e.env??process.env,r=t.KYNVER_HARNESS_ROOT?.trim()||t.OPUS_HARNESS_ROOT?.trim();if(r)return{harnessRoot:Xl(r),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:Xl(n),source:"config"};let o=mF(e.boxKind,t);if(Be(Ce.join(o,"runs"))||Be(o)&&!hF(o))return{harnessRoot:o,source:"box_scoped"};let i=pf(t);if(e.boxKind==="forge"){let a=gR({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&&hR(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&gF(t)){if(Be(Ce.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(Be(i)&&!Be(Ce.join(i,"ghost"))&&!Be(Ce.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let l=Ce.join(df(t),kR);if(Be(l))return{harnessRoot:l,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function hF(e){if(!Be(e))return!0;for(let t of["runs","worktrees"]){let r=Ce.join(e,t);if(Be(r))return!1}return!0}var kR,fF,ff=p(()=>{"use strict";rt();yR();kR=Ce.join(".openclaw","harness");fF=new Set(["runs","worktrees"])});import bR from"node:os";function Zl(e){return e?.trim()?e.trim():null}function yF(e,t){let r=t.trim().toLowerCase()||"host";return`${e}-${r}`.replace(/[^a-z0-9._-]+/g,"-")}function kF(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=I(),t=process.env,r={}){let n=Xe(t,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||Zl(t.KYNVER_BOX_KIND)),a=r.strict===!0||kF(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=Zl(e.runnerId),c=Zl(t.KYNVER_RUNTIME_ID)??Zl(t.OPENCLAW_RUNTIME_ID),u=l??c??yF(n.boxKind,bR.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=Oo({config:e,env:t,totalMemBytes:bR.totalmem()}),f=rr(n.boxKind,m.configuredMaxWorkers??$p(n.boxKind,m.autoCap)),g=Ql({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 pn=p(()=>{"use strict";K();Ne();bo();ui();ff()});var mf=p(()=>{"use strict";Zs();Ne();Do();K();fi();dR();tr();Tt();pn()});function $e(e){let t=e.trim().toLowerCase();return vF[t]??t}var wR,bF,vF,gi=p(()=>{"use strict";wR=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],bF=wR.join("|"),vF={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 _R}from"node:fs";import{homedir as xR}from"node:os";import ec from"node:path";function Mo(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return CR.includes(t)?t:null}function fn(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=Oe(r.trim());if(t.includes(n)||t.push(n),t.length>=wF)break}return t}function tc(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=Mo(s.access);return i?{access:i,folders:fn(s.folders)}:null}function hi(e){return RF.has(e)?"folder":"off"}function SR(e=xR()){let t=ec.join(e,".kynver",ER);return _R(t,{recursive:!0}),t}function Lo(e){let t=e.home??xR(),r=Mo(e.local?.chatComputerAccess),n,o;r==="off"?(n={access:"off",folders:[]},o="local_off"):e.website==="default"?(n={access:hi(e.engine),folders:[]},o="default"):e.website?(n=e.website,o="website"):r?(n={access:r,folders:fn(e.local?.chatWorkFolders)},o="local"):(n={access:hi(e.engine),folders:[]},o="default");let{access:s}=n;if(s==="off")return{access:s,folders:[],workDir:SR(t),extraFolders:[],source:o};let i=n.folders;s==="folder"&&(i=i.slice(0,1)),i.length===0&&s!=="full"&&(i=[SR(t)]);for(let l of i)try{_R(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 rc(e,t){if(e.access==="off")return!1;if(e.access==="full")return!0;let r=ec.resolve(t);return e.folders.some(n=>{let o=ec.relative(n,r);return o===""||!o.startsWith("..")&&!ec.isAbsolute(o)})}var CR,RF,wF,ER,mn=p(()=>{"use strict";rt();CR=["off","folder","folders","full"],RF=new Set(["cursor","codex","antigravity"]),wF=16,ER="chat-workspace"});var AR=p(()=>{"use strict";mn()});import{execFileSync as SF}from"node:child_process";function yf(e=process.env){let t=e[_F]?.trim().toLowerCase();return t==="file"?"file":t==="keychain"?"keychain":"auto"}function xF(e,t,r){let n={encoding:"utf8",timeout:r.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...r.input!==void 0?{input:r.input}:{}};return SF(e,t,n)}function CF(e=process.platform){return e==="darwin"?"macos":e==="linux"?"libsecret":e==="win32"?"windows":null}function gf(e,t){let r=JSON.stringify(gn),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 PR(e={}){if(yf(e.env??process.env)==="file")return null;let r=CF(e.platform??process.platform);return r?new hf(r,e.exec):null}var gn,_F,ar,hf,IR=p(()=>{"use strict";gn="kynver",_F="KYNVER_CREDENTIAL_STORE";ar=5e3;hf=class{constructor(t,r=xF){this.backend=t;this.exec=r}backend;exec;get(t){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",gn,"-a",t,"-w"],{timeoutMs:ar}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",gn,"account",t],{timeoutMs:ar}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",gf("get",t)],{timeoutMs:ar}).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",gn,"-a",t,"-l",`Kynver (${t})`,"-w",r],{timeoutMs:ar}):this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${t})`,"service",gn,"account",t],{input:`${r}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
`,{mode:384})}function BR(e,t,r,n={}){let o=lr();if(Wo().write(e,r)){let i={...o,...n};delete i[t],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],e])).sort(),yi(i);return}yi({...o,...n,[t]:r})}function UR(e,t){let r=Wo().read(e);return r||lr()[t]}function WR(){if(kt())return{backend:null,moved:[],stillInFile:[]};let e=Wo(),t=lr(),r=[],n=[],o=[[Bo,"apiKey"],[Uo,"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={...lr()};for(let i of r)delete s[i];s.store="keychain",s.keychainAccounts=Array.from(new Set([...s.keychainAccounts??[],...r.map(i=>i==="apiKey"?Bo:Uo)])).sort(),yi(s)}return{backend:e.backend,moved:r,stillInFile:n}}function xf(){return Kb(NF)}function Ee(){return xf().getApiKey()}function He(e){return xf().getRunnerToken(e)}function hn(e,t){xf().persistRunnerToken(e,t)}function Cf(e){let t=xe("KYNVER_CHAT_BOX_CREDENTIAL");if(t)return t;if(kt())return oc?.agentOsId===e?oc.credential:void 0;let r=lr();if(!(r.chatBoxCredentialAgentOsId&&r.chatBoxCredentialAgentOsId!==e))return UR(Uo,"chatBoxCredential")}function FR(e,t){if(kt()){oc={agentOsId:e,credential:t};return}BR(Uo,"chatBoxCredential",t,{chatBoxCredentialAgentOsId:e})}function KR(){if(kt()){oc=null;return}Wo().remove(Uo);let e={...lr()};delete e.chatBoxCredential,delete e.chatBoxCredentialAgentOsId,yi(e)}function $R(){let e=Wo();return process.env.KYNVER_API_KEY?{backend:e.backend,apiKey:"env"}:e.read(Bo)?{backend:e.backend,apiKey:"keychain"}:lr().apiKey?{backend:e.backend,apiKey:"file"}:{backend:e.backend,apiKey:"none"}}function pe(e){let t=ki(e);return t||VR("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),t}function yn(e){return ki(e)}function ki(e){let t=e||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||I().apiBaseUrl;return er(t)}function DF(e,t){let r=e||He(t)||(t?void 0:He(I().agentOsId));if(r)return String(r);let n=xe("KYNVER_RUNTIME_SECRET")||xe("KYNVER_CRON_SECRET")||xe("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 ic(e,t,r){let n=DF(e,t);if(n)return{ok:!0,secret:n};let o=Ee(),s=ki(r?.baseUrl);if(o&&t&&s)try{let i=await kn(t,{baseUrl:s,apiKey:o});return hn(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 ic(e,t,r);if(n.ok)return n.secret;VR(n.reason)}async function HR(e,t){let r=Ee(),n=ki(t?.baseUrl);if(!r||!e||!n)return null;try{let o=await kn(e,{baseUrl:n,apiKey:r});return hn(e,o),o}catch{return null}}async function jR(e,t,r){let n=Ee(),o=ki(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 kn(t,{baseUrl:o,apiKey:n});return s&&s!==e?(hn(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 kn(e,t){let r=t?.apiKey||Ee();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 st(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 VR(e){console.error(e),process.exit(1)}var sc,vf,Rf,OF,TF,aoe,loe,NF,oc,K=p(()=>{"use strict";Zs();rt();tr();Ne();bo();ui();ri();fi();mf();gi();pn();AR();Tt();OR();sc=wf.join(IF(),".kynver"),vf=wf.join(sc,"config.json"),Rf=wf.join(sc,"credentials"),OF=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,TF=new Set(["aos","aos-1","agent-os-id","agentosid","agent_os_id","<agent-os-id>","<agentosid>","todo","changeme","change-me","placeholder"]);aoe=500*1024*1024,loe=4*1024*1024*1024;NF={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:UR(Bo,"apiKey")},getRunnerToken(e){let t=lr();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){BR(Bo,"apiKey",e)},persistRunnerToken(e,t){yi({...lr(),runnerToken:t,runnerTokenAgentOsId:e})}};oc=null});import Ef from"node:path";function Ae(e){return Xl(e)}function it(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return Ae(e);let t=I(),r=t.harnessRoot?.trim();if(r)return Ae(r);let n=Nt(t,process.env);return n.identity?n.identity.harnessRoot:Ql({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function Qe(e){return Ef.join(Ae(e),"runs")}function Ko(e){return Ef.join(Ae(e),"worktrees")}function GR(){let e=it();return{harnessRoot:e,runsDir:Qe(e),worktreesDir:Ko(e)}}function cr(e,t){return Ef.join(e,L(t))}var wt=p(()=>{"use strict";K();ff();pn();N()});import{existsSync as ac,readdirSync as MF,statSync as LF}from"node:fs";import bn from"node:path";function me(){return GR()}function ae(e){let{runsDir:t}=me(),r=bn.join(cr(t,L(e)),"run.json");return ac(r)||nt(`run '${e}' not found`),W(r)}function Re(){let{runsDir:e}=me();return JR(e)}function lc(e){return JR(Qe(e))}function BF(e){try{return LF(e).isDirectory()}catch{return!1}}function JR(e){if(!ac(e))return[];let t=[];for(let r of MF(e,{withFileTypes:!0})){if(r.name==="runs")continue;let n=bn.join(e,r.name);if(!BF(n))continue;let o=W(bn.join(n,"run.json"),void 0);o?.id&&t.push(o)}return t}function vn(e,t){let{runsDir:r}=me(),n=bn.join(cr(r,L(e)),"run.json"),o=bn.join(cr(r,L(e)),"workers",L(t),"worker.json");return ac(o)||(ac(n)||nt(`run '${e}' not found`),nt(`worker '${t}' not found in run '${e}'`)),W(o)}function je(e){let{runsDir:t}=me();ye(bn.join(cr(t,e.id),"run.json"),e)}function ee(e,t){let{runsDir:r}=me();ye(bn.join(cr(r,e),"workers",t.name,"worker.json"),t)}function G(e){let{harnessRoot:t}=me();return bi(t,e)}function bi(e,t){return cr(Qe(e),L(t))}var z=p(()=>{"use strict";wt();N()});import UF from"node:path";function WF(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 $o(e){let t=ae(e),r=[];for(let n of Object.keys(t.workers||{})){let o=W(UF.join(G(t.id),"workers",L(n),"worker.json"),void 0);!o?.taskId||!Dr(o)||r.push({runId:t.id,workerName:n,taskId:o.taskId,pid:o.pid,...WF(o)})}return r}var cc=p(()=>{"use strict";z();Ul();N()});function Af(e){return typeof e=="object"&&e!==null&&e.type===uc}function qR(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=>{Af(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 YR(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return[];let n=t.collect??$o,o=t.killTree??Te,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 uc,dc=p(()=>{"use strict";cc();qs();uc="kynver:daemon-stop"});import{createHash as FF}from"node:crypto";function Ze(e){return JSON.stringify(Pf(e))}function Pf(e){if(Array.isArray(e))return e.map(Pf);if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Pf(e[r]);return t}return e}function zR(e){return`ib-${FF("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function Ho(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 vi(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 pc(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 Lr=p(()=>{"use strict"});import{createHash as KF,createPublicKey as $F,verify as HF}from"node:crypto";function GF(e){return`ca-${KF("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function Rn(e,t=process.env){let r=Ho(t.KYNVER_COMMAND_AUTH_PUBLIC_KEY);if(r)return GF(r)!==e?null:r;let n=VF[e];return!n||e===XR&&!pc(t)?null:Ho(n)}function JF(e){return $F({key:Buffer.concat([jF,Buffer.from(e)]),format:"der",type:"spki"})}function qF(e,t){return!Array.isArray(e)||e.length!==t.length?!1:e.every((r,n)=>typeof r=="string"&&r===t[n])}function YF(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 QR(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!YF(e))return{ok:!1,reason:"malformed command authorization proof"};if(e.payload.agentOsId!==t.agentOsId)return{ok:!1,reason:"agentOsId mismatch"};if(!qF(e.payload.argv,t.argv))return{ok:!1,reason:"argv mismatch"};if(e.payload.exp<=n)return{ok:!1,reason:"proof expired"};let o=Rn(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(Ze(e.payload),"utf8");return HF(null,i,JF(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 jF,XR,VF,Ri=p(()=>{"use strict";Lr();jF=Buffer.from("302a300506032b6570032100","hex"),XR="ca-6297fb8e1773",VF={[XR]:"16ae5cb2a61f8c94cf1b86e8258f9c2f2ff6aba5e6136250a422209b6e866881","ca-456fd128f3b3":"f29cbd559410c2578d7f9732ccd86570073355ccdb36af0d1b7dff15908466e7"}});function fc(e){let t=typeof e.description=="string"?e.description:"",r=typeof e.executorRef=="string"?e.executorRef:"",o=[...t.matchAll(zF)].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(XF))try{let i=JSON.parse(s[1]);if(i.readOnly===!0||i.executionMode==="read_only")return"read_only"}catch{}return"write"}var zF,XF,If=p(()=>{"use strict";zF=/\[execution-mode:\s*(write|read[_-]?only)\s*\]/gi,XF=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/gi});import{createPublicKey as QF,verify as ZF}from"node:crypto";function Of(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 rK.test(i)&&i.length<=512?i:null}function ZR(e){let t=e.task??{};return e.landPrDispatch===!0||t.executor==="land_pr"?"land_pr":t.executor==="verify_live"?"verify_live":fc(t)==="read_only"?"read_only":"write"}function nK(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(",")!==[...tK].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)||!mc.includes(r.operationClass))}function ew(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!nK(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+eK+60)return{ok:!1,code:"malformed",reason:"authorization lifetime exceeds the allowed window"};let s=Rn(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=QF({key:Buffer.concat([oK,Buffer.from(s)]),format:"der",type:"spki"});return ZF(null,Buffer.from(Ze(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 eK,mc,tK,rK,oK,tw=p(()=>{"use strict";Ri();Lr();If();eK=120,mc=["write","read_only","land_pr","verify_live"],tK=["agentOsId","attempt","exp","kind","leaseOwner","leaseToken","operationClass","repoIdentity","requestNonce","taskId","tenantId","v"],rK=/^[a-z0-9.-]+(?::\d+)?(?:\/[A-Za-z0-9._~-]+){2,}$/;oK=Buffer.from("302a300506032b6570032100","hex")});import{spawnSync as sK}from"node:child_process";import{randomBytes as iK}from"node:crypto";function rw(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!==aK)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"||!lK.test(t.agentOsId))return"invalid agentOsId";if(typeof t.repoIdentity!="string"||Of(`https://${t.repoIdentity}`)!==t.repoIdentity)return"invalid repoIdentity";let n=t.approvedOperationClasses;if(!Array.isArray(n)||n.length>mc.length)return"invalid approvedOperationClasses";let o=new Set;for(let s of n){if(typeof s!="string"||!mc.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 cK(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=ZR(e.decision),a=ew(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 ow(){return kt()}function sw(e){return wi&&e.revision<wi.revision?!1:(wi=e,!0)}function Df(){return wi}function iw(e){nw=e}function aw(e){return Nf.add(e),()=>Nf.delete(e)}function lw(e){return{v:1,repoIdentity:e,requestNonce:iK(16).toString("base64url")}}function gc(e){let t=sK("git",["-C",e,"remote","get-url","origin"],X({encoding:"utf8",timeout:1e4}));return t.status!==0||typeof t.stdout!="string"?null:Of(t.stdout.trim())}function cw(e){let t=cK({...e,policy:wi,identity:nw,consumed:uK});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 Nf)try{o(n)}catch{}}return t}var aK,lK,Tf,wi,nw,uK,Nf,hc=p(()=>{"use strict";Tt();tw();N();aK=1,lK=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;Tf=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}};wi=null,nw=null,uK=new Tf,Nf=new Set});import{createCipheriv as dK,createDecipheriv as pK,randomBytes as Lf,scrypt as fK,timingSafeEqual as mK}from"node:crypto";function dw(){return Lf(Bf)}function pw(e=gK){return{name:"scrypt",N:e.N,r:e.r,p:e.p,salt:Lf(16).toString("base64")}}function Wf(e,t,r=hK){if(t.name!=="scrypt"||!Number.isInteger(t.N)||t.N<r||t.r<8||t.p<1)return Promise.reject(new St("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 St("the vault file's salt is invalid")):new Promise((o,s)=>{fK(e.normalize("NFKC"),n,Bf,{N:t.N,r:t.r,p:t.p,maxmem:128*t.N*t.r*2},(i,a)=>i?s(i):o(a))})}function Si(e,t,r){if(e.length!==Bf)throw new St("bad key length");let n=Lf(uw),o=dK("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 yc(e,t,r){try{let n=Buffer.from(t.n,"base64"),o=Buffer.from(t.c,"base64");if(n.length!==uw||o.length<Mf)throw new St;let s=pK("aes-256-gcm",e,n);return s.setAAD(Buffer.from(r,"utf8")),s.setAuthTag(o.subarray(o.length-Mf)),Buffer.concat([s.update(o.subarray(0,o.length-Mf)),s.final()])}catch(n){throw n instanceof St?n:new St}}function Ff(e){for(let t of e)if(t.includes(`
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
4
|
+
`):""}function Ml(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Ll(e){return new Promise(t=>setTimeout(t,e))}function te(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function $v(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 df(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var M=p(()=>{"use strict";li()});function tF(e){let t=e[mf];return t?new Set(t.split(/[\s,]+/).map(r=>r.trim()).filter(Boolean)):new Set}function rF(e,t={}){return XU.has(e)?!0:ZU.has(e)||t.operatorAllow?.has(e)||eF.some(r=>e.endsWith(r))?!1:QU.some(r=>e.endsWith(r))}function ui(e){let t=tF(e),r={...e};for(let n of Object.keys(r))rF(n,{operatorAllow:t})&&delete r[n];return r}var pf,XU,QU,ff,ZU,eF,mf,di=p(()=>{"use strict";pf=["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"],XU=new Set(pf),QU=["_SECRET","_API_KEY","_KEK","_KEY","_TOKEN","_PASSWORD","_PASSPHRASE","_SALT"],ff=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],ZU=new Set(ff),eF=["_PUBLIC_KEY"],mf="KYNVER_WORKER_ENV_ALLOW"});import{existsSync as nF,statSync as oF}from"node:fs";import{spawnSync as jv}from"node:child_process";function le(e,t,r={}){let n=jv("git",t,z({cwd:e,encoding:"utf8"}));if(n.status!==0&&!r.allowFailure){let o=sF(e,t,n);if(r.throwError)throw new Error(o);at(o)}return n.stdout||""}function sF(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 iF(e){let t=e.trim();if(!t)return"git repo path is empty";let r=De(t);if(!nF(r))return r===t?`git repo path does not exist: ${r}`:`git repo path does not exist: ${r} (from ${t})`;try{if(!oF(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 Vv(e){let t=iF(e);t&&at(t),le(De(e.trim()),["rev-parse","--show-toplevel"])}function pi(e){return le(e,["status","--short"],{allowFailure:!0}).split(`
|
|
5
|
+
`).map(t=>t.trim()).filter(Boolean)}function Q(e,t){try{let r=jv("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 Hv(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 Bl(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 Co(n,"missing worktree path");let s=Q(e,["rev-parse","HEAD"]);if(s.status!==0)return Co(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let f=Q(e,["rev-parse",n]);if(f.status!==0)return Co(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=Hv(e,i,a),c=Hv(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 Co(e,t,r=null){return{checked:!1,base:e,head:r,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:t}}var Re=p(()=>{"use strict";it();M();di()});import{existsSync as aF,mkdirSync as Gv}from"node:fs";import{homedir as gf}from"node:os";import Eo from"node:path";function qv(e=gf()){return Eo.join(e,".kynver",lF)}function Yv(e,t=gf()){return Eo.resolve(e)===Eo.resolve(qv(t))}function cF(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 Jv(e){Q(e,["rev-parse","--verify","HEAD^{commit}"]).status!==0&&(cF(e),Q(e,["commit","--allow-empty","-m","kynver byoc workspace"]))}function zv(e=gf()){let t=qv(e);Gv(Eo.dirname(t),{recursive:!0});let r=!1;aF(t)||(Gv(t,{recursive:!0}),r=!0);let n=Q(t,["rev-parse","--show-toplevel"]);if(n.status!==0)return Q(t,["init","-b","main"]),Jv(t),r=!0,{repo:Eo.resolve(t),created:r};let o=Eo.resolve(n.stdout.trim()||t);return Jv(o),{repo:o,created:r}}var lF,hf=p(()=>{"use strict";Re();lF="workspace"});import{existsSync as kf,readFileSync as Qv}from"node:fs";import{homedir as Zv}from"node:os";import lt from"node:path";import{fileURLToPath as uF}from"node:url";function pF(e){let t=lt.join(e,"package.json");if(!kf(t))return null;try{let r=JSON.parse(Qv(t,"utf8"));return typeof r.name=="string"?r.name.trim():null}catch{return null}}function eR(e){return pF(e)==="kynver"}function Xv(e){let t=lt.resolve(e);if(!kf(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?lt.resolve(n):null}function fF(e=import.meta.url){let t=lt.dirname(uF(e));for(let r=0;r<8;r+=1){let n=lt.join(t,"package.json");if(kf(n))try{if(JSON.parse(Qv(n,"utf8")).name==="@kynver-app/runtime")return t}catch{}let o=lt.dirname(t);if(o===t)break;t=o}return null}function yf(e,t,r,n,o){if(!r)return;let s=lt.resolve(r);e.has(s)||(o?.requireMonorepo??!0)&&!eR(s)||(e.add(s),t.push({repo:s,source:n}))}function tR(e){let t=e?.cwd??process.cwd(),r=new Set,n=[];yf(r,n,Xv(t),"cwd_git",{requireMonorepo:!1});let o=fF(e?.runtimeModuleUrl??import.meta.url);o&&yf(r,n,Xv(o),"runtime_checkout");let s=Zv();for(let a of dF)yf(r,n,De(lt.join(s,a)),"well_known_path");let i=lt.resolve(e?.cwd??process.cwd());return n.filter(a=>{if(a.source!=="runtime_checkout"||!eR(a.repo))return!0;let l=lt.resolve(a.repo);return i===l||i.startsWith(`${l}${lt.sep}`)})}function Wl(e){return tR(e)[0]??null}function mF(e){let t=lt.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 Ul(e){let t=tR(e),r=t.find(o=>!mF(o.repo));if(r)return r;if(t[0])return t[0];let{repo:n}=zv(e?.home??Zv());return{repo:n,source:"byoc_workspace"}}var dF,fi=p(()=>{"use strict";Re();it();hf();dF=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});function mi(e){let t=yn(e);try{let r=new URL(t);return r.hostname.toLowerCase()===rR?(r.hostname=`www.${rR}`,yn(r.toString())):t}catch{return t}}function or(e){if(e?.trim())return mi(yn(e.trim()))}async function ct(e,t,r=fetch){let n=mi(e),o=new Headers(t?.headers),s=0;for(;s<=nR;){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 ${nR} redirects for ${e}`)}var rR,nR,sr=p(()=>{"use strict";M();rR="kynver.com";nR=10});function kn(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 Fl(e,t){return e[t]?.trim()||null}function oR(e){let t=e?.split(":")[0]?.trim();return t?kn(t):null}function Ze(e=process.env,t={}){let r=[],n=oR(t.boxId),o=oR(Fl(e,"KYNVER_BOX_ID")),s=t.boxKind?.trim();if(s)return n&&n!==kn(s)&&r.push(`config.boxId=${t.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:kn(s),source:"config",slugInferenceBlocked:!1,warnings:r};let i=Fl(e,"KYNVER_BOX_KIND");if(i)return o&&o!==kn(i)&&r.push(`KYNVER_BOX_ID=${Fl(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:kn(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=Fl(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 _t(e={},t=process.env){return Ze(t,e).boxKind}var Me=p(()=>{"use strict"});function bf(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 gi(e,t){return e==="forge"&&t>4}var Ao=p(()=>{"use strict"});import{readFileSync as gF}from"node:fs";import sR from"node:os";function iR(e){if(e!==void 0){let t=e.match(/^MemAvailable:\s+(\d+)\s*kB/m);return t?Number(t[1])*1024:sR.freemem()}if(process.platform==="linux")try{let r=gF("/proc/meminfo","utf8").match(/^MemAvailable:\s+(\d+)\s*kB/m);if(r)return Number(r[1])*1024}catch{}return sR.freemem()}var aR=p(()=>{"use strict"});import{existsSync as hF,readFileSync as yF,statfsSync as kF}from"node:fs";function vf(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!hF(e))continue;let t=yF(e,"utf8");if(/microsoft|wsl/i.test(t))return!0}catch{}return!1}function lR(e={}){if(!(e.forceWsl===void 0?vf():e.forceWsl))return null;let r=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Po,n=e.wslHostFreeWarnBytes??bF,o=e.wslHostFreeCriticalBytes??vF,s=e.statfs??kF,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. ${RF()}`),{ok:f,path:r,freeBytes:a,totalBytes:l,usedPercent:c,warnBelowBytes:n,criticalBelowBytes:o,reason:g,probeError:null}}function RF(){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 bF,vF,Po,Rf=p(()=>{"use strict";bF=25*1024*1024*1024,vF=12*1024*1024*1024,Po="/mnt/c"});import{execFileSync as cR}from"node:child_process";import{existsSync as $l,readFileSync as uR,readdirSync as wF,statSync as SF}from"node:fs";import wf from"node:path";function Kl(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function dR(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=cR("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()||Po;return t&&$l(wf.join(r,"Users",t))?t:null}function AF(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()||Po,n=e.windowsUser??dR();return n?`${r.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function PF(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 IF(){try{if($l("/proc/sys/kernel/core_pattern"))return uR("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return cR("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function OF(e){return!!(e&&/wsl-capture-crash/i.test(e))}function TF(e,t=Po){let r=wf.join(t,"Users",e,".wslconfig");if(!$l(r))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=uR(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 NF(e){if(!$l(e))return[];let t=wF(e,{withFileTypes:!0}),r=[];for(let n of t){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=wf.join(e,n.name);try{let s=SF(o),i=PF(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 Io(e={}){if(!(e.forceWsl===void 0?vf():e.forceWsl))return null;let r=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Po,n=e.windowsUser??dR(),o=e.warnBelowBytes??Kl("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",_F),s=e.criticalBelowBytes??Kl("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",xF),i=e.warnCount??Kl("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",CF),a=e.criticalCount??Kl("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",EF),l=(e.readCorePattern??IF)(),c=OF(l),u=null;n&&(u=(e.readWslConfig??TF)(n,r));let d=u?.maxCrashDumpCount??null,f=d===-1,m=AF({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??NF)(m)}catch(I){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}: ${I.message}`,probeError:I.message}}let h=g.reduce((I,A)=>I+A.bytes,0),y=g.length,v=[...new Set(g.map(I=>I.executableHint).filter(I=>!!I))],k=h>=s,b=h>=o,_=y>=a,S=y>=i,w=!(k||_||b||S),L=null;if(!w){let I=k||_?"critical":"warning",A=(h/1024**3).toFixed(1),O=v.length>0?v.join(", "):"unknown";L=`WSL crash dumps ${I}: ${y} file(s), ${A} GiB at ${m} (executables: ${O}). `+DF({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 DF(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 _F,xF,CF,EF,Hl=p(()=>{"use strict";Rf();_F=5*1024*1024*1024,xF=10*1024*1024*1024,CF=2,EF=4});import{statfsSync as MF}from"node:fs";function Br(e={}){let t=e.diskPath?.trim()||"/",r=e.diskFreeWarnBytes??LF,n=e.diskFreeCriticalBytes??BF,o=e.diskMaxUsedPercent??WF,s=e.diskHardMaxUsedPercent??UF,i=MF(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:lR(e.wslHost),v=e.skipWslCrashDumpCheck?null:Io(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("; ")),FF({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 FF(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 LF,BF,WF,UF,hi=p(()=>{"use strict";Hl();Rf();LF=30*1024*1024*1024,BF=15*1024*1024*1024,WF=80,UF=90});import{existsSync as KF,readdirSync as $F}from"node:fs";import HF from"node:path";function xt(e){let t=new Set;for(let n of Object.keys(e.workers||{}))t.add(B(n));let r=HF.join(V(e.id),"workers");if(!KF(r))return[...t];for(let n of $F(r,{withFileTypes:!0}))n.isDirectory()&&t.add(B(n.name));return[...t]}var Oo=p(()=>{"use strict";Y();M()});function Sf(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 pR(e){let t=e.trim();if(!t)return null;let r=Sf(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let l=Sf(s[1]??"");l&&n.push(l)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let l=Sf(t.slice(i,a+1));l&&n.push(l)}return n.length>0?n[n.length-1]:null}function fR(e){let t=e.finalResult??e.final_result;if(t!=null)return typeof t=="string"?pR(t)??(t.trim()||null):t;let r=typeof e.summary=="string"?e.summary.trim():"";if(!r)return null;let n=pR(r);return n||r}var mR=p(()=>{"use strict"});import{existsSync as jF,readFileSync as VF}from"node:fs";function gR(e){return e==="complete"}function ar(e){return gR(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function Ae(e){let t={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!jF(e))return t;let r=Date.now()+GF,n=new Date(r).toISOString(),o=VF(e,"utf8").split(`
|
|
6
|
+
`).filter(Boolean);for(let s of o){let i=ci(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)),gR(t.lastHeartbeatPhase)&&(t.terminalFinalResult=fR(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 GF,bn=p(()=>{"use strict";mR();M();GF=6e4});function yR(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function jl(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 kR(e){let t=yR(e[0]);return!!(t&&JF.has(t))}function YF(e){let t=e.trim();return t.includes("/")?t.split("/").pop()??t:t}function zF(e){if(!e||e.includes("*"))return null;let t=YF(e);return!t||t.includes("/")?null:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(t)?t:null}function bR(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function _f(e){if(!e)return!1;let t=e.trim();return t.startsWith("!")&&!t.includes("/")&&!t.endsWith("/**")}function XF(e){if(!e.startsWith("--glob="))return e;let t=e.slice(7);return t.startsWith("!")&&!t.includes("/")&&!t.endsWith("/**")?`--glob=${t}/**`:e}function QF(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;hR.has(n)&&(r+=1);continue}t.push(n)}}return t}function ZF(e){let t=!1,r=e.map((o,s)=>{let i=XF(o),a=e[s-1];return a&&hR.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(t=!0),i}),n=QF(r);if(n.length===2){let[o,s]=n;if(_f(s))return{argv:[r[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};let i=zF(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 vR(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 Vl(e){let t=e.trim();if(!t)return{command:t,wrapped:!1};let r=jl(t);if(!r.length)return{command:t,wrapped:!1};let n=yR(r[0]);if(!n||!qF.has(n))return{command:t,wrapped:!1};let o=vR(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 eK(e,t){let r=e.trim(),n=jl(r),o=vR(n);if(o<0)return t;let s=n.slice(0,o).join(" "),i=t.includes("'")?`"${t.replace(/"/g,'\\"')}"`:`'${t}'`;return`${s} ${i}`}function tK(e){let t=e.trim(),r=Vl(t),n=jl(r.command);if(!n.length||!kR(n))return{segment:t,changed:!1};let o=ZF(n);if(!o.changed)return{segment:t,changed:!1};let s=o.argv.join(" ");return r.wrapped?{segment:eK(t,s),changed:!0}:{segment:s,changed:!0}}function xf(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=tK(i);return a.changed&&(o=!0),a.segment});return o?{command:s.join(r),changed:!0}:{command:t,changed:!1}}function RR(e){let t=Vl(e).command,r=jl(t.trim());return r.length&&kR(r)?!0:/\b(rg|ripgrep)\b/i.test(t)}function wR(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 rK(e){let{pattern:t,target:r}=wR(e);return t?_f(r)?{kind:"rg_exclude_syntax",pattern:t,target:r}:bR(r)?{kind:"bad_scope",pattern:t,target:r}:{kind:"not_repo_search",pattern:t,target:r}:{kind:"not_repo_search"}}function nK(e){let{pattern:t,target:r}=wR(e);if(!t)return null;if(_f(r)){let n=`${r.trim()}/**`;return{command:`rg "${t}" -g '${n}' .`,changed:!0}}return r&&bR(r)?{command:`rg -g ${r} "${t}" .`,changed:!0}:null}function oK(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 sK(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 Cf(e){let t=e.meta?.trim()||(e.command?sK(e.command):null)||null;if(t){let r=rK(t),n=oK(r);if(n)return n;let o=nK(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=xf(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 JF,qF,hR,SR=p(()=>{"use strict";JF=new Set(["rg","ripgrep","grep"]),qF=new Set(["bash","sh","dash","zsh"]),hR=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function yi(e,t=200){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}function lK(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 ki(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function cK(e){let t=e.metadata;if(!ki(t))return null;let r=t.vulnerabilities;if(!ki(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 uK(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 dK(e,t){let r=e.error;if(ki(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?yi(o.split(`
|
|
7
|
+
`).find(Boolean)??o,160):"npm audit failed"}function pK(e){let t=`${e.stdout}
|
|
8
|
+
${e.stderr}`.trim(),r=lK(t);if(!r||!ki(r)){let o=yi(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(ki(r.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${dK(r,e.stderr)}`};let n=cK(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:uK(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function fK(e){return iK.test(e)}function mK(e){let t=Vl(e).command;return _R.test(e)||_R.test(t)||RR(e)}function gK(e){let t=Cf({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&&aK.test(n)){let i=yi(n,160);return{kind:"command_failure",exitCode:1,summary:t??`ripgrep failed (exit 1): ${i}`}}let o=xf(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=yi(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 xR(e){let t=e.stdout??"",r=e.stderr??"",n=e.interleavedOutput??"";if(fK(e.command)){let i=t.trim()||n.trim()||r.trim();return pK({exitCode:e.exitCode,stdout:i,stderr:r})}if(mK(e.command))return gK({command:e.command,exitCode:e.exitCode,stdout:t,stderr:r,interleaved:n});let o=Cf({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=yi(n||t||r||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var iK,_R,aK,CR=p(()=>{"use strict";SR();iK=/\bnpm\s+audit\b/i,_R=/\b(rg|ripgrep)\b/i,aK=/\b(error|invalid|unknown|panic|not found)\b/i});function bi(e){return typeof e=="string"&&hK.test(e.trim())}function Gl(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 hK,Jl=p(()=>{"use strict";hK=/^(?:provider authentication failed:\s*)?(?:(?:Failed to authenticate|authentication (?:failed|error))(?::\s*[^\n.!?]+)?|OAuth session expired and could not be refreshed)[.!]?$/i});function Ef(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function yK(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 ql(e){if(e.event==="step_update"&&Ef(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"||!Ef(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=Ef(t.usage)?yK(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 Af=p(()=>{"use strict"});function Pf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ER(){return{assistantText:""}}function kK(e,t){if(!(t.role!=="assistant"||typeof t.content!="string")){if(t.delta===!0){e.assistantText+=t.content;return}e.assistantText=t.content}}function bK(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=(Pf(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 vK(e){return e.type!=="result"||e.status!=="success"&&e.status!=="error"?!1:typeof e.result!="string"}function AR(e,t){if(e.type==="message"&&(e.role==="assistant"||e.role==="user"))return kK(t,e),{};if(e.type==="tool_use"&&typeof e.tool_name=="string"&&e.tool_name.trim())return{currentTool:e.tool_name.trim()};if(!vK(e))return null;let r=Pf(e.stats)?bK(e.stats):void 0;if(e.status==="error"){let o=Pf(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 PR=p(()=>{"use strict"});import{existsSync as RK,readFileSync as wK}from"node:fs";function SK(e){let t=e.timestamp_ms;return e.timestamp||e.ts||(t?new Date(t).toISOString():void 0)}function _K(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 xK(e,t){e.finalResult=t.result||t.subtype||t.terminal_reason||"completed",Gl(t)&&(e.providerTerminalError=!0,e.error=String(t.result||t.api_error_status||"stream result error"))}function To(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function CK(e){let t=e.usage;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function EK(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 AK(e,t){let r=CK(t);if(!r)return;let n=To(r.input_tokens)??To(r.inputTokens)??To(r.prompt_tokens),o=To(r.output_tokens)??To(r.outputTokens)??To(r.completion_tokens);if(n===void 0&&o===void 0)return;let s=EK(t)??e.usage?.model;e.usage={...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...s?{model:s}:{}}}function PK(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 IK(e,t){t.kind==="success"||t.kind==="search_no_matches"||(e.lastShellOutcome=t)}function vn(e){let t={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null,usage:null};if(!RK(e))return t;let r=wK(e,"utf8").split(`
|
|
9
|
+
`).filter(Boolean),n=null,o=ER();for(let s of r){let i=ci(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=SK(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=_K(f);m&&(t.currentTool=m)}let l=PK(i);l&&IK(t,xR({command:l.command,exitCode:l.exitCode,stdout:l.stdout,stderr:l.stderr,interleavedOutput:l.interleaved}));let c=ql(i),u=c?null:AR(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"&&xK(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"}AK(t,i)}return t}var vi=p(()=>{"use strict";CR();M();Jl();Af();PR()});import{accessSync as OK,constants as TK,existsSync as NK,readFileSync as DK}from"node:fs";import If from"node:path";function OR(e){return If.join(e,MK)}function LK(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 IR(e){try{return OK(e,TK.X_OK),!0}catch{return!1}}function BK(e,t=process.env){if(!e)return!1;if(e.includes("/"))return IR(e);for(let r of(t.PATH??"").split(If.delimiter))if(r&&IR(If.join(r,e)))return!0;return!1}function et(e,t,r,n={}){let o=n.env??process.env;return!r||!LK(o,n.platform)?[e,t]:BK(e,o)?[n.nodeExecutable??process.execPath,["-e",WK,OR(r),e,...t]]:[e,t]}function UK(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Yl(e){if(!e)return null;let t=OR(e);if(!NK(t))return null;try{let r=JSON.parse(DK(t,"utf8")),n=r.oomEvidence;return{exitCode:UK(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 TR(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 MK,WK,lr=p(()=>{"use strict";MK="exit.json";WK=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 FK from"node:path";function Of(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.handoffState;return typeof t=="string"&&$K.has(t)}function zl(e){return!!(e&&KK.test(e))}function MR(e){if(e.noRestartAt?.trim())return"stopped_by_hand";if(e.finalResult&&!Of(e.finalResult))return"finished";if(e.alive)return e.stale?"stuck":"running";let t=e.error?.trim()??"",r=e.exit??null;if(r?.oomEvidence||zl(t))return"oom";let n=e.reconcileReason??"";return/reconciled stale worker/i.test(n)?"stuck":NR.test(t)||NR.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 LR(e){let t=[HK(e.stopClass)],r=TR(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 HK(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 BR(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,DR/2):DR/2;return Math.min(jK,n*2**e)}function WR(e,t,r){let n=0,o;try{o=re(e)}catch{return 0}for(let s of Object.keys(o.workers||{})){if(r&&s===r)continue;let i=K(FK.join(V(o.id),"workers",B(s),"worker.json"),void 0);if(!(!i||i.taskId!==t)){if(i.stopClass==="oom"||i.oomEvidence){n+=1;continue}if(Yl(i.workerDir)?.oomEvidence){n+=1;continue}!i.stopClass&&i.stderrPath&&zl(xo(i.stderrPath,20))&&(n+=1)}}return n}function UR(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 KK,NR,$K,DR,jK,Tf=p(()=>{"use strict";Y();M();lr();KK=/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,NR=/\btimed? ?out\b|\btimeout\b|deadline exceeded/i,$K=new Set(["exited_without_final_result","exited_without_complete_heartbeat","exit_failure"]);DR=2048,jK=8192});function FR(e,t=240){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}function Ri(e){let t=(e??"").trim();if(!t)return null;if(bi(t))return{blocked:!0,reason:`provider authentication failed: ${FR(t)}`};for(let r of VK)if(r.test.test(t))return{blocked:!0,reason:`${r.label}: ${FR(t)}`};return null}var VK,Nf=p(()=>{"use strict";Jl();VK=[{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 KR(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function GK(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 JK(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:KR(e.head)}function qK(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 No(e){if(e.alive||GK(e.finalResult))return null;let t=(e.changedFiles??[]).filter(i=>i.trim()).length,r=KR(e.headCommit)??JK(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:qK(s,t,r)}}var Xl=p(()=>{"use strict"});import{existsSync as YK,readFileSync as zK,statSync as jR}from"node:fs";import Ql from"node:path";function e$(e,t=process.env){let r=e?QK:XK,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 t$(e){return e.baseCommit?.trim()||e.base?.trim()||"origin/main"}function Df(e){try{return jR(e).mtimeMs}catch{return-1}}function r$(e){let t=Ql.join(e,".git");try{if(jR(t).isDirectory())return t;let r=/^gitdir:\s*(.+)$/m.exec(zK(t,"utf8"));return r?Ql.resolve(e,r[1].trim()):null}catch{return null}}function $R(e){let t=r$(e);return[Df(e),t?Df(Ql.join(t,"HEAD")):-2,t?Df(Ql.join(t,"index")):-2].join(":")}function HR(e,t){return{changedFiles:pi(e),gitAncestry:Bl(e,{base:t.base,baseCommit:t.baseCommit})}}function n$(e,t){for(Wr.delete(e),Wr.set(e,t);Wr.size>ZK;){let r=Wr.keys().next().value;if(r===void 0)break;Wr.delete(r)}}function VR(e,t,r){let n=t$(t);if(!e||!e.trim())return wi.missingWorktree++,{changedFiles:[],gitAncestry:Co(n,"missing worktree path")};let o=`${e}\0${n}`;if(!YK(e))return Wr.delete(o),wi.missingWorktree++,{changedFiles:[],gitAncestry:Co(n,`worktree no longer exists: ${e}`)};if(r.alive)return Wr.delete(o),wi.liveProbes++,HR(e,t);let s=r.ttlMs??e$(!!t.baseCommit?.trim()),i=r.now??Date.now(),a=$R(e),l=Wr.get(o);if(s>0&&l&&l.fingerprint===a&&i<l.expiresAt)return wi.hits++,l.probe;wi.misses++;let c=HR(e,t);if(s>0){let u=.8+.4*(r.random??Math.random)();n$(o,{fingerprint:$R(e),expiresAt:i+Math.round(s*u),probe:c})}return c}var XK,QK,ZK,Wr,wi,GR=p(()=>{"use strict";Re();XK=10*6e4,QK=60*6e4,ZK=2048,Wr=new Map,wi={hits:0,misses:0,liveProbes:0,missingWorktree:0}});function Si(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function o$(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 s$(e){if(Si(e.headCommit)||Si(e.prUrl)||Si(e.artifactBundlePath)||Si(e.patchPath))return!0;let t=e.gitAncestry;return!!(t?.checked&&t.headIsAncestorOfBase===!1&&Si(t.head))}function Do(e){return o$(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:s$(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 JR(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var Zl=p(()=>{"use strict"});function Mf(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 Mo(e){let t=e.trim();if(!t)return null;let r=Mf(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let u=Mf(s[1]??"");u&&n.push(u)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let u=Mf(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 ec=p(()=>{"use strict"});function YR(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 zR(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function i$(e){return new Set(e.map(t=>zR(YR(t)??t)).filter(Boolean))}function XR(e,t,r){let n=YR(e)??e;if(!n)return"unrelated";let o=zR(n);return i$(t).has(o)?"contract":r?(r.outcome==="skipped"||r.outcome==="blocked")&&r.reason?.trim()?"support":(r.outcome==="merged","unrelated"):"unrelated"}var QR=p(()=>{"use strict"});function Lo(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function a$(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function Rn(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:Lo(e)}function tc(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function ZR(e){let t=null;if(typeof e=="string"){let o=Mo(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=Rn(String(s.prUrl??s.pr_url??"")),a=Lo(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:Lo(s.mergeCommit??s.merge_commit),reason:Lo(s.reason)})}return n}function ew(e,t){let r=[],n=Rn(Lo(e.prUrl)??"");if(n&&r.push(n),t&&typeof t=="object"&&!Array.isArray(t)){let o=t,s=Rn(String(o.prUrl??o.pr_url??""));s&&r.push(s)}return[...new Set(r)]}function tw(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(!a$(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?Rn(Lo(t.targetPrUrl)??"")??(t.targetPrUrls.length===1?Rn(t.targetPrUrls[0]):null):null;if(s){let d=ew(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=ZR(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=ZR(n),a=new Map(i.map(d=>[tc(d.prUrl),d])),l=new Set(t.targetPrUrls.map(d=>tc(Rn(d)??d)).filter(Boolean)),c=ew(r,n);if(t.landingOnly)for(let d of c){let f=a.get(tc(d)),m=XR(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=tc(Rn(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 rw(e){if(e.blocked)return e.detail??e.reason}var nw=p(()=>{"use strict";ec();QR()});function c$(e){let t=Date.now();if(e.providerTerminalError||Gl(e.finalResult)||e.finalResult&&e.error?.trim()||bi(e.error)||bi(e.finalResult)){let o=e.error||(typeof e.finalResult=="string"?e.finalResult:"provider terminal error");return{state:"blocked",reason:Ri(o)?.reason??`provider terminal error: ${o}`}}if(e.completionBlocker&&!ow(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&d$(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=Do(o);if(s.blocked){let i=JR(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=tw({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=rw(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(u$(e))return{state:"done",reason:"empty abandoned worker record"};let o=Ri(e.error);if(o)return{state:"blocked",reason:o.reason};let s=No({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=zl(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>l$)return{state:"needs_attention",reason:`no first stream event ${df(r)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&t-n>Lf?{state:"stale",reason:`no log/event/heartbeat activity for ${df(n)}s`}:{state:"ok",reason:"recent activity"}}function ow(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function u$(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 d$(e){let t=null;if(typeof e=="string"?t=Mo(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 sw(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 iw(e){let t=vn(e.stdoutPath),r=Ae(e.heartbeatPath);return sw(e,t.finalResult,r)}function se(e,t={}){let r=vn(e.stdoutPath),n=Ae(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=sw(e,r.finalResult,n),i=o?!1:te(e.pid),a=Nl(e.stdoutPath),l=Nl(e.stderrPath),c=Nl(e.heartbeatPath),{changedFiles:u,gitAncestry:d}=VR(e.worktreePath,{base:t.base,baseCommit:t.baseCommit},{alive:i}),f=$v([r.lastEventAt,n.lastHeartbeatAt,Dl(e.stdoutPath),Dl(e.stderrPath),Dl(e.heartbeatPath)]),m=i?null:Yl(e.workerDir),g=s&&!Of(s)?s:null,h=r.error||!i&&!s&&xo(e.stderrPath,10).trim()||void 0,y=h||!i&&s&&!g&&xo(e.stderrPath,10).trim()||void 0,v=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,k=ow(v)?null:v,b=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,_=c$({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=MR({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,I=L==="running"||L==="finished"?null:(R===L?e.stopReason:void 0)??LR({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:I,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 Le(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Bf(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}function rc(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 l$,Lf,xe=p(()=>{"use strict";bn();vi();Tf();lr();Jl();Nf();Xl();GR();Zl();nw();ec();M();l$=18e4,Lf=6e5});import{readFileSync as p$}from"node:fs";function f$(e){if(!e||process.platform!=="linux")return null;try{return p$(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ")}catch{return null}}function aw(e){if(!e.pid||process.platform!=="linux")return!0;let t=f$(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()||!te(e.pid)||!aw(e)?!1:!iw(e)}var nc=p(()=>{"use strict";xe();M()});import cw from"node:os";import uw from"node:path";function lw(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function m$(e=E(),t,r){let n=lw(e.perWorkerMemBytes,oc),o=lw(e.memReserveBytes,sc),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):ic)),i=Uo({config:e,configuredMaxWorkersOverride:t,totalMemBytes:r??cw.totalmem()});return{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i.configuredMaxWorkers,autoCap:i.autoCap,workerCapSource:i.workerCapSource}}function dw(e,t={}){let r=t.perWorkerMemBytes??oc,n=t.memReserveBytes??sc,o=t.memUtilization??ic,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/r));return Math.min(i,ac)}function g$(){return iR()}function h$(e){let t=0;for(let r of xt(e)){let n=K(uw.join(V(e.id),"workers",B(r),"worker.json"),void 0);!n||!Ur(n)||t++}return t}function Wf(){let e=0;for(let t of we())e+=h$(t);return e}function Bo(){let e=[];for(let t of we())for(let r of xt(t)){let n=K(uw.join(V(t.id),"workers",B(r),"worker.json"),void 0);n&&Ur(n)&&e.push({runId:t.id,workerName:r})}return e}function _i(e){let t=e.config??E(),r=e.totalMemBytes??cw.totalmem(),{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i,autoCap:a,workerCapSource:l}=m$(t,e.configuredMaxWorkersOverride,r),c=_t(t),u=e.freeMemBytes??g$(),d=e.activeWorkers??Wf(),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 oc,sc,ic,ac,Wo=p(()=>{"use strict";aR();j();Me();Ao();xi();hi();Y();Oo();nc();M();oc=500*1024*1024,sc=4*1024*1024*1024,ic=.85,ac=64});function Ci(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function Uo(e){let t=e.config??{},r=e.env??process.env,n=Ci(t.perWorkerMemBytes,oc),o=Ci(t.memReserveBytes,sc),s=Math.min(1,Math.max(.1,Number(t.memUtilization)>0?Number(t.memUtilization):ic)),i=dw(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Ci(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(t.maxConcurrentWorkers!==void 0&&t.maxConcurrentWorkers!==null){let c=Ci(t.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,ac),autoCap:i,workerCapSource:"config"}}let l=(r.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||r.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&r.KYNVER_MAX_WORKERS&&Ci(r.KYNVER_MAX_WORKERS,0)||null;return l?{configuredMaxWorkers:Math.min(l,ac),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var xi=p(()=>{"use strict";Wo()});import{existsSync as y$,mkdirSync as Pie,readFileSync as k$,writeFileSync as Iie}from"node:fs";import{homedir as b$}from"node:os";import v$ from"node:path";function R$(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 lc(e=Fr){return y$(e)?R$(k$(e,"utf8")):new Map}function pw(e=Fr,t={}){let r=lc(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=v$.join(b$(),".kynver",".env")});var fw=p(()=>{"use strict"});var mw=p(()=>{"use strict";fw()});var cc=p(()=>{"use strict"});import{existsSync as w$,readFileSync as S$}from"node:fs";import{homedir as _$}from"node:os";import x$ from"node:path";function Ff(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Uf(e){return typeof e=="string"&&e.trim()?e:null}function Kf(e){let t=Ff(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=Uf(t.requestedAt);return o?{desiredState:r,policyVersion:n,requestedAt:o,requestedByLabel:Uf(t.requestedByLabel),reason:Uf(t.reason)}:null}function gw(e){let t=Ff(Ff(e)?.response);return!t||t.runtimeControl===void 0?null:Kf(t.runtimeControl)}function hw(e,t=_$()){let r=e.replace(/[^A-Za-z0-9_-]/g,"_");return x$.join(t,".kynver",`runtime-control-${r}.json`)}function $f(e,t,r){try{let n=Kr(e,r);if(n&&n.policyVersion>t.policyVersion)return;ke(hw(e,r),{contractVersion:1,agentOsId:e,control:t,deliveredAt:new Date().toISOString()})}catch{}}function Kr(e,t){try{let r=hw(e,t);if(!w$(r))return null;let n=JSON.parse(S$(r,"utf8"));return n.agentOsId!==e?null:Kf(n.control)}catch{return null}}function Fo(e){return e?.desiredState??"running"}function C$(e){return e==="keeper"||e==="desktop"}function E$(e,t,r=!1){let n=Fo(e);return n==="paused"?"paused":n==="stopped"?r&&t===0?"stopped":"stopping":"running"}function dc(e){return e.control?{policyVersion:e.control.policyVersion,state:E$(e.control,e.inFlightWorkers,e.exiting),supervised:C$(e.supervisor),inFlightWorkers:Math.max(0,Math.floor(e.inFlightWorkers))}:null}function yw(e){let t=Fo(e);return t==="paused"?"runtime_paused":t==="stopped"?"runtime_stopped":null}function kw(e,t){return Fo(e)==="stopped"&&t===0}function vw(e){bw=e}function Rw(){return bw}var uc,bw,$r=p(()=>{"use strict";M();uc=83;bw=null});var Ei,Ko=p(()=>{"use strict";mw();cc();$r();Ei="kynver-cron-daemon.service"});import{existsSync as A$,readFileSync as P$}from"node:fs";function Hf(){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(A$("/proc/version")){let e=P$("/proc/version","utf8");if(/microsoft/i.test(e))return"wsl"}}catch{}return"linux"}return"linux"}var pc=p(()=>{"use strict"});var jf=p(()=>{"use strict";pc()});var Ai=p(()=>{"use strict";cr();it();j();Ko();jf()});import N$ from"node:os";function Pi(e,t){let r=(t??N$.hostname()).trim().toLowerCase().replace(/\s+/g,"-")||"unknown-host";return`${e}:${r}`}function Sw(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function fc(e,t){let r=e.trim();if(!r)return Pi(t);let n=r.indexOf(":");if(n>=0){let o=r.slice(0,n).trim().toLowerCase()||t,s=Sw(r.slice(n+1));return s?`${o}:${s}`:Pi(o)}return`${t}:${Sw(r)}`}function $o(e){let t=e.explicitBoxId?.trim()||e.env?.KYNVER_BOX_ID?.trim()||e.config?.boxId?.trim();return t?fc(t,e.boxKind):Pi(e.boxKind,e.hostLabel)}var Ho=p(()=>{"use strict";Me();Me()});var _w=p(()=>{"use strict";cr();Ko();Ai()});import{existsSync as ur,mkdirSync as D$,readdirSync as mc,renameSync as xw,statSync as M$}from"node:fs";import dr from"node:path";function Ew(e){try{return M$(e).isDirectory()}catch{return!1}}function L$(e){if(!ur(e))return!0;for(let t of Cw){let r=dr.join(e,t);if(ur(r)&&(!Ew(r)||mc(r).length>0))return!1}return!0}function B$(e){let t=dr.join(e,"runs");if(!ur(t)||!Ew(t))return!1;for(let r of mc(t,{withFileTypes:!0})){if(!r.isDirectory()||r.name==="runs")continue;let n=dr.join(t,r.name,"run.json");if(K(n,void 0)?.id)return!0}return!1}function W$(e){let t=dr.join(e,"runs");if(!ur(t))return!1;for(let r of mc(t,{withFileTypes:!0})){if(!r.isDirectory())continue;if(K(dr.join(t,r.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function U$(e){let t=dr.join(e,"ghost");return ur(t)?!ur(dr.join(t,"runs")):W$(e)}function Aw(e){return B$(e.sharedRoot)?L$(e.forgeRoot)?U$(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 Pw(e,t){D$(t,{recursive:!0});for(let r of Cw){let n=dr.join(e,r),o=dr.join(t,r);if(ur(n)){if(ur(o)&&mc(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(ur(o)){xw(n,o);continue}xw(n,o)}}}var Cw,Iw=p(()=>{"use strict";M();Cw=["runs","worktrees"]});import{existsSync as We}from"node:fs";import{homedir as F$}from"node:os";import Pe from"node:path";function Vf(e=process.env){return e.HOME?.trim()||F$()}function Gf(e=process.env){return Pe.join(Vf(e),".kynver","harness")}function gc(e){let t=Pe.resolve(De(e.trim()));for(;K$.has(Pe.basename(t));)t=Pe.dirname(t);return t}function $$(e,t=process.env){return Pe.join(Gf(t),e)}function H$(e=process.env){let t=Gf(e);if(We(Pe.join(t,"runs")))return!0;if(We(t)&&!We(Pe.join(t,"ghost"))&&!We(Pe.join(t,"forge")))return We(t);let r=Pe.join(Vf(e),Ow);return We(r)}function hc(e){let t=e.env??process.env,r=t.KYNVER_HARNESS_ROOT?.trim()||t.OPUS_HARNESS_ROOT?.trim();if(r)return{harnessRoot:gc(r),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:gc(n),source:"config"};let o=$$(e.boxKind,t);if(We(Pe.join(o,"runs"))||We(o)&&!j$(o))return{harnessRoot:o,source:"box_scoped"};let i=Gf(t);if(e.boxKind==="forge"){let a=Aw({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&&Pw(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&H$(t)){if(We(Pe.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(We(i)&&!We(Pe.join(i,"ghost"))&&!We(Pe.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let l=Pe.join(Vf(t),Ow);if(We(l))return{harnessRoot:l,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function j$(e){if(!We(e))return!0;for(let t of["runs","worktrees"]){let r=Pe.join(e,t);if(We(r))return!1}return!0}var Ow,K$,Jf=p(()=>{"use strict";it();Iw();Ow=Pe.join(".openclaw","harness");K$=new Set(["runs","worktrees"])});import Tw from"node:os";function yc(e){return e?.trim()?e.trim():null}function V$(e,t){let r=t.trim().toLowerCase()||"host";return`${e}-${r}`.replace(/[^a-z0-9._-]+/g,"-")}function G$(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 Lt(e=E(),t=process.env,r={}){let n=Ze(t,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||yc(t.KYNVER_BOX_KIND)),a=r.strict===!0||G$(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=yc(e.runnerId),c=yc(t.KYNVER_RUNTIME_ID)??yc(t.OPENCLAW_RUNTIME_ID),u=l??c??V$(n.boxKind,Tw.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=Uo({config:e,env:t,totalMemBytes:Tw.totalmem()}),m=ir(n.boxKind,f.configuredMaxWorkers??bf(n.boxKind,f.autoCap)),g=hc({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 wn=p(()=>{"use strict";j();Me();Ao();xi();Jf()});var qf=p(()=>{"use strict";fi();Me();Ho();j();Ai();_w();sr();wt();wn()});function He(e){let t=e.trim().toLowerCase();return q$[t]??t}var Mw,J$,q$,Ii=p(()=>{"use strict";Mw=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],J$=Mw.join("|"),q$={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 Bw}from"node:fs";import{homedir as Ww}from"node:os";import kc from"node:path";function jo(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Uw.includes(t)?t:null}function Sn(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=De(r.trim());if(t.includes(n)||t.push(n),t.length>=z$)break}return t}function bc(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=jo(s.access);return i?{access:i,folders:Sn(s.folders)}:null}function vc(e){return Y$.has(e)?"folder":"off"}function Lw(e=Ww()){let t=kc.join(e,".kynver",Fw);return Bw(t,{recursive:!0}),t}function Vo(e){let t=e.home??Ww(),r=jo(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:Sn(e.local?.chatWorkFolders)},o="local"):(n={access:vc(e.engine),folders:[]},o="default");let{access:s}=n;if(s==="off")return{access:s,folders:[],workDir:Lw(t),extraFolders:[],source:o};let i=n.folders;s==="folder"&&(i=i.slice(0,1)),i.length===0&&s!=="full"&&(i=[Lw(t)]);for(let l of i)try{Bw(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 Rc(e,t){if(e.access==="off")return!1;if(e.access==="full")return!0;let r=kc.resolve(t);return e.folders.some(n=>{let o=kc.relative(n,r);return o===""||!o.startsWith("..")&&!kc.isAbsolute(o)})}var Uw,Y$,z$,Fw,_n=p(()=>{"use strict";it();Uw=["off","folder","folders","full"],Y$=new Set(["cursor","codex","antigravity"]),z$=16,Fw="chat-workspace"});var Kw=p(()=>{"use strict";_n()});import{execFileSync as X$}from"node:child_process";function Xf(e=process.env){let t=e[Q$]?.trim().toLowerCase();return t==="file"?"file":t==="keychain"?"keychain":"auto"}function Z$(e,t,r){let n={encoding:"utf8",timeout:r.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...r.input!==void 0?{input:r.input}:{}};return X$(e,t,n)}function eH(e=process.platform){return e==="darwin"?"macos":e==="linux"?"libsecret":e==="win32"?"windows":null}function Yf(e,t){let r=JSON.stringify(xn),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 $w(e={}){if(Xf(e.env??process.env)==="file")return null;let r=eH(e.platform??process.platform);return r?new zf(r,e.exec):null}var xn,Q$,pr,zf,Hw=p(()=>{"use strict";xn="kynver",Q$="KYNVER_CREDENTIAL_STORE";pr=5e3;zf=class{constructor(t,r=Z$){this.backend=t;this.exec=r}backend;exec;get(t){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",xn,"-a",t,"-w"],{timeoutMs:pr}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",xn,"account",t],{timeoutMs:pr}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",Yf("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",xn,"-a",t,"-l",`Kynver (${t})`,"-w",r],{timeoutMs:pr}):this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${t})`,"service",xn,"account",t],{input:`${r}
|
|
74
|
+
`,timeoutMs:pr}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",Yf("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",xn,"-a",t],{timeoutMs:pr}):this.backend==="libsecret"?this.exec("secret-tool",["clear","service",xn,"account",t],{timeoutMs:pr}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",Yf("delete",t)],{timeoutMs:pr})}catch{}}}});function qo(){return Qf||(Qf=new Zf),Qf}var Go,Jo,tH,wc,Zf,Qf,jw=p(()=>{"use strict";Hw();Go="api-key",Jo="chat-box-credential",tH=6e4,wc=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"}},Zf=class{cache=new Map;keychain;env;now;constructor(t={}){this.env=t.env??process.env,this.keychain=t.keychain===void 0?$w({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<tH)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=Xf(this.env);if(!this.keychain){if(n==="keychain")throw new wc(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 wc(t);return o}remove(t){this.cache.delete(t),this.keychain?.delete(t)}invalidate(t){t?this.cache.delete(t):this.cache.clear()}},Qf=null});import{existsSync as Vw,mkdirSync as Gw,readFileSync as Jw,writeFileSync as qw}from"node:fs";import{homedir as oH,totalmem as ile}from"node:os";import rm from"node:path";function Yo(e){let t=String(e??"").trim();if(!t)return{ok:!1,reason:"missing"};let r=t.toLowerCase();return iH.has(r)?{ok:!1,value:t,reason:"placeholder"}:sH.test(t)?{ok:!0,value:t}:{ok:!1,value:t,reason:"not a UUID"}}function nm(e){let t=Yo(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 Yw(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:De(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:De(e.defaultRepo.trim())}:{}}}function E(){if(!Vw(em))return{};try{return Yw(JSON.parse(Jw(em,"utf8")))}catch{return{}}}function Be(e){Gw(_c,{recursive:!0}),qw(em,`${JSON.stringify(Dw(e),null,2)}
|
|
76
|
+
`,{mode:384})}function Dw(e){return Yw(e)}function om(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:$e(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:$e(e.defaultRepo.trim())}:{},...e.chatWorkFolders?.length?{chatWorkFolders:e.chatWorkFolders.map($e)}:{}}}function fr(){if(cf(),!Vw(tm))return{};try{return JSON.parse(Jw(tm,"utf8"))}catch{return{}}}function Oi(e){cf(),Gw(_c,{recursive:!0}),qw(tm,`${JSON.stringify(e,null,2)}
|
|
77
|
+
`,{mode:384})}function zw(e,t,r,n={}){let o=fr();if(qo().write(e,r)){let i={...o,...n};delete i[t],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],e])).sort(),Oi(i);return}Oi({...o,...n,[t]:r})}function Xw(e,t){let r=qo().read(e);return r||fr()[t]}function Qw(){if(Xe())return{backend:null,moved:[],stillInFile:[]};let e=qo(),t=fr(),r=[],n=[],o=[[Go,"apiKey"],[Jo,"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"?Go:Jo)])).sort(),Oi(s)}return{backend:e.backend,moved:r,stillInFile:n}}function sm(){return Bv(aH)}function Se(){return sm().getApiKey()}function Ie(e){return sm().getRunnerToken(e)}function Cn(e,t){sm().persistRunnerToken(e,t)}function im(e){let t=Ee("KYNVER_CHAT_BOX_CREDENTIAL");if(t)return t;if(Xe())return Sc?.agentOsId===e?Sc.credential:void 0;let r=fr();if(!(r.chatBoxCredentialAgentOsId&&r.chatBoxCredentialAgentOsId!==e))return Xw(Jo,"chatBoxCredential")}function Zw(e,t){if(Xe()){Sc={agentOsId:e,credential:t};return}zw(Jo,"chatBoxCredential",t,{chatBoxCredentialAgentOsId:e})}function eS(){if(Xe()){Sc=null;return}qo().remove(Jo);let e={...fr()};delete e.chatBoxCredential,delete e.chatBoxCredentialAgentOsId,Oi(e)}function tS(){let e=qo();return process.env.KYNVER_API_KEY?{backend:e.backend,apiKey:"env"}:e.read(Go)?{backend:e.backend,apiKey:"keychain"}:fr().apiKey?{backend:e.backend,apiKey:"file"}:{backend:e.backend,apiKey:"none"}}function pe(e){let t=Ti(e);return t||oS("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),t}function En(e){return Ti(e)}function Ti(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 or(t)}function lH(e,t){let r=e||Ie(t)||(t?void 0:Ie(E().agentOsId));if(r)return String(r);let n=Ee("KYNVER_RUNTIME_SECRET")||Ee("KYNVER_CRON_SECRET")||Ee("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 xc(e,t,r){let n=lH(e,t);if(n)return{ok:!0,secret:n};let o=Se(),s=Ti(r?.baseUrl);if(o&&t&&s)try{let i=await An(t,{baseUrl:s,apiKey:o});return Cn(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 xc(e,t,r);if(n.ok)return n.secret;oS(n.reason)}async function rS(e,t){let r=Se(),n=Ti(t?.baseUrl);if(!r||!e||!n)return null;try{let o=await An(e,{baseUrl:n,apiKey:r});return Cn(e,o),o}catch{return null}}async function nS(e,t,r){let n=Se(),o=Ti(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 An(t,{baseUrl:o,apiKey:n});return s&&s!==e?(Cn(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 An(e,t){let r=t?.apiKey||Se();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 ct(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 oS(e){console.error(e),process.exit(1)}var _c,em,tm,sH,iH,wle,Sle,aH,Sc,j=p(()=>{"use strict";fi();it();sr();Me();Ao();xi();hi();Ai();qf();Ii();wn();Kw();wt();jw();_c=rm.join(oH(),".kynver"),em=rm.join(_c,"config.json"),tm=rm.join(_c,"credentials"),sH=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,iH=new Set(["aos","aos-1","agent-os-id","agentosid","agent_os_id","<agent-os-id>","<agentosid>","todo","changeme","change-me","placeholder"]);wle=500*1024*1024,Sle=4*1024*1024*1024;aH={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:Xw(Go,"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){zw(Go,"apiKey",e)},persistRunnerToken(e,t){Oi({...fr(),runnerToken:t,runnerTokenAgentOsId:e})}};Sc=null});import am from"node:path";function Oe(e){return gc(e)}function ut(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return Oe(e);let t=E(),r=t.harnessRoot?.trim();if(r)return Oe(r);let n=Lt(t,process.env);return n.identity?n.identity.harnessRoot:hc({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function tt(e){return am.join(Oe(e),"runs")}function zo(e){return am.join(Oe(e),"worktrees")}function sS(){let e=ut();return{harnessRoot:e,runsDir:tt(e),worktreesDir:zo(e)}}function mr(e,t){return am.join(e,B(t))}var Ct=p(()=>{"use strict";j();Jf();wn();M()});import{existsSync as Cc,readdirSync as cH,statSync as uH}from"node:fs";import Pn from"node:path";function me(){return sS()}function re(e){let{runsDir:t}=me(),r=Pn.join(mr(t,B(e)),"run.json");return Cc(r)||at(`run '${e}' not found`),K(r)}function we(){let{runsDir:e}=me();return iS(e)}function Ec(e){return iS(tt(e))}function dH(e){try{return uH(e).isDirectory()}catch{return!1}}function iS(e){if(!Cc(e))return[];let t=[];for(let r of cH(e,{withFileTypes:!0})){if(r.name==="runs")continue;let n=Pn.join(e,r.name);if(!dH(n))continue;let o=K(Pn.join(n,"run.json"),void 0);o?.id&&t.push(o)}return t}function In(e,t){let{runsDir:r}=me(),n=Pn.join(mr(r,B(e)),"run.json"),o=Pn.join(mr(r,B(e)),"workers",B(t),"worker.json");return Cc(o)||(Cc(n)||at(`run '${e}' not found`),at(`worker '${t}' not found in run '${e}'`)),K(o)}function je(e){let{runsDir:t}=me();ke(Pn.join(mr(t,e.id),"run.json"),e)}function X(e,t){let{runsDir:r}=me();ke(Pn.join(mr(r,e),"workers",t.name,"worker.json"),t)}function V(e){let{harnessRoot:t}=me();return Ni(t,e)}function Ni(e,t){return mr(tt(e),B(t))}var Y=p(()=>{"use strict";Ct();M()});import pH from"node:path";function fH(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 Xo(e){let t=re(e),r=[];for(let n of Object.keys(t.workers||{})){let o=K(pH.join(V(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,...fH(o)})}return r}var Ac=p(()=>{"use strict";Y();nc();M()});function lm(e){return typeof e=="object"&&e!==null&&e.type===Pc}function aS(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=>{lm(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 lS(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return[];let n=t.collect??Xo,o=t.killTree??ye,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 Pc,Ic=p(()=>{"use strict";Ac();li();Pc="kynver:daemon-stop"});import{createHash as mH}from"node:crypto";function rt(e){return JSON.stringify(cm(e))}function cm(e){if(Array.isArray(e))return e.map(cm);if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=cm(e[r]);return t}return e}function cS(e){return`ib-${mH("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function Qo(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 Di(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 Oc(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 gH,createPublicKey as hH,verify as yH}from"node:crypto";function vH(e){return`ca-${gH("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function On(e,t=process.env){let r=Qo(t.KYNVER_COMMAND_AUTH_PUBLIC_KEY);if(r)return vH(r)!==e?null:r;let n=bH[e];return!n||e===uS&&!Oc(t)?null:Qo(n)}function RH(e){return hH({key:Buffer.concat([kH,Buffer.from(e)]),format:"der",type:"spki"})}function wH(e,t){return!Array.isArray(e)||e.length!==t.length?!1:e.every((r,n)=>typeof r=="string"&&r===t[n])}function SH(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 dS(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!SH(e))return{ok:!1,reason:"malformed command authorization proof"};if(e.payload.agentOsId!==t.agentOsId)return{ok:!1,reason:"agentOsId mismatch"};if(!wH(e.payload.argv,t.argv))return{ok:!1,reason:"argv mismatch"};if(e.payload.exp<=n)return{ok:!1,reason:"proof expired"};let o=On(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(rt(e.payload),"utf8");return yH(null,i,RH(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 kH,uS,bH,Mi=p(()=>{"use strict";Hr();kH=Buffer.from("302a300506032b6570032100","hex"),uS="ca-6297fb8e1773",bH={[uS]:"16ae5cb2a61f8c94cf1b86e8258f9c2f2ff6aba5e6136250a422209b6e866881","ca-456fd128f3b3":"f29cbd559410c2578d7f9732ccd86570073355ccdb36af0d1b7dff15908466e7"}});function Tc(e){let t=typeof e.description=="string"?e.description:"",r=typeof e.executorRef=="string"?e.executorRef:"",o=[...t.matchAll(_H)].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(xH))try{let i=JSON.parse(s[1]);if(i.readOnly===!0||i.executionMode==="read_only")return"read_only"}catch{}return"write"}var _H,xH,um=p(()=>{"use strict";_H=/\[execution-mode:\s*(write|read[_-]?only)\s*\]/gi,xH=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/gi});import{createPublicKey as CH,verify as EH}from"node:crypto";function dm(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 IH.test(i)&&i.length<=512?i:null}function pS(e){let t=e.task??{};return e.landPrDispatch===!0||t.executor==="land_pr"?"land_pr":t.executor==="verify_live"?"verify_live":Tc(t)==="read_only"?"read_only":"write"}function OH(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(",")!==[...PH].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)||!Nc.includes(r.operationClass))}function fS(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!OH(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+AH+60)return{ok:!1,code:"malformed",reason:"authorization lifetime exceeds the allowed window"};let s=On(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=CH({key:Buffer.concat([TH,Buffer.from(s)]),format:"der",type:"spki"});return EH(null,Buffer.from(rt(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 AH,Nc,PH,IH,TH,mS=p(()=>{"use strict";Mi();Hr();um();AH=120,Nc=["write","read_only","land_pr","verify_live"],PH=["agentOsId","attempt","exp","kind","leaseOwner","leaseToken","operationClass","repoIdentity","requestNonce","taskId","tenantId","v"],IH=/^[a-z0-9.-]+(?::\d+)?(?:\/[A-Za-z0-9._~-]+){2,}$/;TH=Buffer.from("302a300506032b6570032100","hex")});import{spawnSync as NH}from"node:child_process";import{randomBytes as DH}from"node:crypto";function gS(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!==MH)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"||!LH.test(t.agentOsId))return"invalid agentOsId";if(typeof t.repoIdentity!="string"||dm(`https://${t.repoIdentity}`)!==t.repoIdentity)return"invalid repoIdentity";let n=t.approvedOperationClasses;if(!Array.isArray(n)||n.length>Nc.length)return"invalid approvedOperationClasses";let o=new Set;for(let s of n){if(typeof s!="string"||!Nc.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 BH(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=pS(e.decision),a=fS(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 yS(){return Xe()}function kS(e){return Li&&e.revision<Li.revision?!1:(Li=e,!0)}function mm(){return Li}function bS(e){hS=e}function vS(e){return fm.add(e),()=>fm.delete(e)}function RS(e){return{v:1,repoIdentity:e,requestNonce:DH(16).toString("base64url")}}function Dc(e){let t=NH("git",["-C",e,"remote","get-url","origin"],z({encoding:"utf8",timeout:1e4}));return t.status!==0||typeof t.stdout!="string"?null:dm(t.stdout.trim())}function wS(e){let t=BH({...e,policy:Li,identity:hS,consumed:WH});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 fm)try{o(n)}catch{}}return t}var MH,LH,pm,Li,hS,WH,fm,Mc=p(()=>{"use strict";wt();mS();M();MH=1,LH=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;pm=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}};Li=null,hS=null,WH=new pm,fm=new Set});import{createCipheriv as UH,createDecipheriv as FH,randomBytes as hm,scrypt as KH,timingSafeEqual as $H}from"node:crypto";function _S(){return hm(ym)}function xS(e=HH){return{name:"scrypt",N:e.N,r:e.r,p:e.p,salt:hm(16).toString("base64")}}function bm(e,t,r=jH){if(t.name!=="scrypt"||!Number.isInteger(t.N)||t.N<r||t.r<8||t.p<1)return Promise.reject(new Et("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 Et("the vault file's salt is invalid")):new Promise((o,s)=>{KH(e.normalize("NFKC"),n,ym,{N:t.N,r:t.r,p:t.p,maxmem:128*t.N*t.r*2},(i,a)=>i?s(i):o(a))})}function Bi(e,t,r){if(e.length!==ym)throw new Et("bad key length");let n=hm(SS),o=UH("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 Lc(e,t,r){try{let n=Buffer.from(t.n,"base64"),o=Buffer.from(t.c,"base64");if(n.length!==SS||o.length<gm)throw new Et;let s=FH("aes-256-gcm",e,n);return s.setAAD(Buffer.from(r,"utf8")),s.setAuthTag(o.subarray(o.length-gm)),Buffer.concat([s.update(o.subarray(0,o.length-gm)),s.final()])}catch(n){throw n instanceof Et?n:new Et}}function vm(e){for(let t of e)if(t.includes(`
|
|
78
|
+
`))throw new Et("invalid vault field");return e.join(`
|
|
79
|
+
`)}function wm(e){return vm(["kynver-site-login/v1/record",e.agentOsId,e.handle,e.origin,e.label,e.username,e.hasTotp?"totp":"no-totp"])}function CS(e,t){return e.length===t.length&&$H(e,t)}var ym,SS,gm,HH,jH,km,Et,Rm,Bc,Wc,ES=p(()=>{"use strict";ym=32,SS=12,gm=16,HH={N:2**17,r:8,p:1},jH=2**14,km=10,Et=class extends Error{constructor(t="the saved-login vault could not be decrypted"){super(t),this.name="VaultCryptoError"}};Rm=e=>vm(["kynver-site-login/v1/vault-key",e]),Bc=e=>vm(["kynver-site-login/v1/key-check",e]),Wc=Buffer.from("kynver-site-login-key-check-v1","utf8")});function AS(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(".")||VH.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 Wi(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 Sm(e,t){let r=Wi(t);return r!==null&&r===e}var VH,_m=p(()=>{"use strict";VH=/^(localhost|.*\.localhost|.*\.local|.*\.internal|0\.0\.0\.0|\[.*\]|\d{1,3}(\.\d{1,3}){3})$/i});import{createHmac as GH}from"node:crypto";function PS(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|JH.indexOf(s),r+=5,r>=8&&(o.push(n>>>r-8&255),r-=8);return o.length?Buffer.from(o):null}function Uc(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=PS(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=PS(t);return r?{key:r,algorithm:"SHA1",digits:6,period:30}:null}function qH(e,t,r,n){let o=Buffer.alloc(8);o.writeBigUInt64BE(t);let s=GH(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 IS(e,t=Date.now()){let r=BigInt(Math.floor(t/1e3/e.period));return qH(e.key,r,e.digits,e.algorithm)}function OS(e,t=Date.now()){let r=Math.floor(t/1e3)%e.period;return e.period-r}var JH,xm=p(()=>{"use strict";JH="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"});var dt,Cm=p(()=>{"use strict";dt={maxRecords:200,maxLabel:80,maxUsername:254,maxPassword:1024,maxTotp:512}});import{createHash as YH,randomBytes as DS}from"node:crypto";import{chmodSync as TS,existsSync as zH,mkdirSync as XH,readFileSync as QH,renameSync as ZH,rmSync as ej,writeFileSync as tj}from"node:fs";import{homedir as rj}from"node:os";import MS from"node:path";function Ui(){return MS.join(rj(),".kynver","site-logins")}function Em(e){return`${YH("sha256").update(`kynver-site-login:${e}`).digest("hex").slice(0,32)}.vault.json`}function NS(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(LS.test(o))throw new J(`${t} contains control characters`,"invalid");return o}function nj(){let e="abcdefghijkmnpqrstuvwxyz23456789",t=DS(10);return`lg_${Array.from(t,r=>e[r%e.length]).join("")}`}var J,LS,Fc,Tn=p(()=>{"use strict";ES();_m();xm();Cm();J=class extends Error{constructor(r,n){super(r);this.code=n;this.name="SiteLoginError"}code},LS=/[\u0000-\u001f\u007f]/;Fc=class{constructor(t){this.opts=t;let r=t.agentOsId.trim();if(!r||LS.test(r)||r.length>200)throw new J("invalid workspace id","invalid");this.agentOsId=r,this.rootDir=t.rootDir??Ui(),this.filePath=MS.join(this.rootDir,Em(r)),this.now=t.now??Date.now}opts;agentOsId;filePath;rootDir;now;exists(){return zH(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<km)throw new J(`the vault passphrase must be at least ${km} characters`,"invalid");let r=_S(),n=xS(this.opts.scryptCost),o=await bm(t,n,this.opts.minScryptN);return this.write({v:1,agentOsId:this.agentOsId,keyMode:"passphrase",kdf:n,wrappedKey:Bi(o,r,Rm(this.agentOsId)),keyCheck:Bi(r,Wc,Bc(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:Bi(t,Wc,Bc(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 bm(t,r.kdf,this.opts.minScryptN);let o=Lc(n,r.wrappedKey,Rm(this.agentOsId));return this.verifyKey(r,o),o}catch(o){throw o instanceof J?o:o instanceof Et&&/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()?(ej(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>=dt.maxRecords)throw new J(`at most ${dt.maxRecords} saved logins per workspace`,"full");let o=this.buildRecord(t,r,nj(),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=Lc(t,o.secret,wm({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=AS(r.origin);if(!s.ok)throw new J(s.reason,"invalid");let i=NS(r.label,"label",dt.maxLabel),a=NS(r.username,"username",dt.maxUsername),l=typeof r.password=="string"?r.password:"";if(!l)throw new J("password is required","invalid");if(l.length>dt.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>dt.maxTotp||!Uc(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:Bi(t,d,wm({agentOsId:this.agentOsId,...u}))}}finally{d.fill(0)}}verifyKey(t,r){try{let n=Lc(r,t.keyCheck,Bc(this.agentOsId));if(!CS(n,Wc))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(QH(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){XH(this.rootDir,{recursive:!0,mode:448});try{TS(this.rootDir,448)}catch{}let r=`${this.filePath}.${DS(4).toString("hex")}.tmp`;tj(r,`${JSON.stringify(t)}
|
|
80
|
+
`,{mode:384}),ZH(r,this.filePath);try{TS(this.filePath,384)}catch{}}}});import{appendFileSync as ij,chmodSync as aj,existsSync as FS,mkdirSync as lj,readFileSync as KS,renameSync as cj,statSync as uj,writeFileSync as dj}from"node:fs";import pj from"node:path";var fj,$S,mj,Kc,HS=p(()=>{"use strict";Tn();fj=512*1024,$S=1e3,mj=10080*60*1e3,Kc=class{constructor(t,r=Ui(),n=Date.now){this.rootDir=r;this.now=n;this.filePath=pj.join(r,Em(t).replace(/\.vault\.json$/,".audit.jsonl"))}rootDir;now;filePath;record(t){let r={at:new Date(this.now()).toISOString(),...t};try{lj(this.rootDir,{recursive:!0,mode:448}),this.rotateIfLarge(),ij(this.filePath,`${JSON.stringify(r)}
|
|
81
|
+
`,{mode:384}),aj(this.filePath,384)}catch{}return r}entries(t=$S){if(!FS(this.filePath))return[];try{return KS(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=mj){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(!FS(this.filePath)||uj(this.filePath).size<fj)return;let t=KS(this.filePath,"utf8").split(`
|
|
83
|
+
`).filter(Boolean).slice(-$S/2),r=`${this.filePath}.tmp`;dj(r,`${t.join(`
|
|
20
84
|
`)}
|
|
21
|
-
`,{mode:384}),MK(r,this.filePath)}}});import{randomBytes as KK}from"node:crypto";import{existsSync as $K,rmSync as HK}from"node:fs";function Ow(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 _t(){return Tw??=new qf,Tw}var jK,VK,qf,Tw,Ci=p(()=>{"use strict";Iw();wn();jK=720*60*1e3,VK=300*1e3,qf=class{rootDir;now;idleMs;keys=new Map;codes=new Map;codeListeners=new Set;constructor(t={}){this.rootDir=t.rootDir??xi(),this.now=t.now??Date.now,this.idleMs=t.idleMs??jK}store(t){return new Rc({agentOsId:t,rootDir:this.rootDir,now:this.now})}audit(t){return new wc(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 $K(o)&&HK(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_${KK(6).toString("hex")}`,createdAt:r,expiresAt:r+VK};this.codes.set(n.id,n);let o=Ow(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=>Ow(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)}};Tw=null});var Nw=p(()=>{"use strict";N()});var Dw=p(()=>{"use strict";K();Nw();tr()});function JK(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 Yf(e){if(!e)return null;let t=JK(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 zf=p(()=>{"use strict"});function Mw(e){return/\((?:401|403)\)/.test(e)?"access_denied":"transient"}var Xf=p(()=>{"use strict";K();tr();N();Dw();zf()});import{existsSync as qK}from"node:fs";import{homedir as YK}from"node:os";import zK from"node:path";function Lw(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 Ei(e,t,r=1){let n=Number(process.env[e]);return!Number.isFinite(n)||n<r?t:Math.floor(n)}function Br(){let e=process.env.KYNVER_CRON_STORE_PATH?.trim()||process.env.OPENCLAW_CRON_STORE_PATH?.trim();return e||zK.join(YK(),".kynver","agent-os-cron.json")}function XK(e=Br()){let t=process.env.KYNVER_CRON_TICK_STATE_PATH?.trim();return t||`${e.replace(/\.json$/i,"")}.tick-state.json`}function QK(){let e=I();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 Bw(){let e=I();return xe("KYNVER_CRON_SECRET")||xe("OPENCLAW_CRON_SECRET")||xe("KYNVER_RUNTIME_SECRET")||He(e.agentOsId)?.trim()||He()?.trim()||null}function Vo(){let e=Br(),t=XK(e),r=QK(),n=Bw(),o=!!(r&&n),s=qK(e),i=o&&(s||Lw("KYNVER_CRON_TICK_FORCE",!1));return{storePath:e,statePath:t,lockPath:`${t}.lock`,fireBaseUrl:r,secret:n,tickEnabled:Lw("KYNVER_CRON_TICK_ENABLED",i),tickIntervalMs:Ei("KYNVER_CRON_TICK_INTERVAL_MS",6e4,5e3),missedRunPolicy:process.env.KYNVER_CRON_MISSED_RUN_POLICY?.trim().toLowerCase()==="skip"?"skip":"catch_up",maxCatchUpPerTick:Ei("KYNVER_CRON_MAX_CATCH_UP_PER_TICK",3,0),maxRetries:Ei("KYNVER_CRON_MAX_RETRIES",3,0),retryBackoffMs:Ei("KYNVER_CRON_RETRY_BACKOFF_MS",6e4,1e3),inflightLeaseMs:Ei("KYNVER_CRON_INFLIGHT_LEASE_MS",12e4,5e3)}}var ur=p(()=>{"use strict";K();Tt()});import{promises as ZK}from"node:fs";async function Uw(e){try{return await ZK.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function e$(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t.entries)?t.entries:[]}catch{return[]}}async function Sc(e=Br()){let t=await Uw(e);return e$(t)}async function t$(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 Qf(e=Br()){return await Uw(e)!==null?{created:!1}:(await t$(e,[]),{created:!0})}var Go=p(()=>{"use strict";ur()});import{existsSync as r$,readFileSync as n$}from"node:fs";import{dirname as Zf,join as Fw}from"node:path";import{fileURLToPath as Ww}from"node:url";function o$(e){let t=Zf(Ww(e));for(let r=0;r<6;r+=1){if(r$(Fw(t,"package.json")))return t;let n=Zf(t);if(n===t)break;t=n}throw new Error(`package.json not found above ${Zf(Ww(e))}`)}function s$(e=import.meta.url){let t=Fw(o$(e),"package.json"),r=JSON.parse(n$(t,"utf8"));if(typeof r.version!="string"||!r.version.trim())throw new Error(`Missing package.json version at ${t}`);return r.version}var Dt,Jo=p(()=>{"use strict";Dt=s$()});import{spawnSync as i$}from"node:child_process";import{readFileSync as a$}from"node:fs";function l$(e,t){let r=i$(e,t,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:15e3});return{status:r.status,stdout:r.stdout??""}}function c$(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 u$(e){return Number.isInteger(e)&&e>0}function Kw(e,t={}){if(!u$(e))return null;let r=t.platform??process.platform,n=t.readText??(s=>a$(s,"utf8")),o=t.run??l$;try{if(r==="linux"){let s=c$(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 em=p(()=>{"use strict"});import{createHash as p$,randomUUID as Jw}from"node:crypto";import{closeSync as f$,constants as tm,existsSync as m$,mkdirSync as rm,openSync as g$,readFileSync as h$,renameSync as nm,rmSync as _c,writeFileSync as y$}from"node:fs";import{createConnection as k$,createServer as $w}from"node:net";import{homedir as b$,tmpdir as v$}from"node:os";import Mt from"node:path";function R$(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function qw(e){let t=e.stateRoot??Mt.join(b$(),".kynver"),r=e.platform??process.platform,n=p$("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(v$(),`kynver-owner-${n.slice(0,16)}.sock`));let i=Mt.join(t,`daemon-owner-${R$(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 S$(e){rm(Mt.dirname(e),{recursive:!0});let t;try{t=g$(e,tm.O_RDWR|tm.O_CREAT|w$)}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{f$(t)}catch{}}}}}}function Hw(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 _$(e,t=2e3){return new Promise(r=>{let n=k$({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 x$(e,t){e.startsWith("\0")||rm(Mt.dirname(e),{recursive:!0,mode:448});let r=$w(a=>a.destroy());if(await Hw(r,e)==="listening")return{held:jw(r,e)};if(!t||e.startsWith("\0"))return{busy:!0};if(await _$(e))return{busy:!0};let o=`${e}.stale-${process.pid}-${Jw().slice(0,8)}`;try{nm(e,o),_c(o,{force:!0})}catch{}let s=$w(a=>a.destroy());return await Hw(s,e).catch(()=>"in_use")==="listening"?{held:jw(s,e)}:{busy:!0}}function jw(e,t){e.unref();let r=!0;return{isHeld:()=>r&&e.listening,release:()=>{r&&(r=!1,e.close(),t.startsWith("\0")||_c(t,{force:!0}))}}}async function C$(e,t){return t==="win32"?S$(e.lockFile):x$(e.socketAddress,t!=="linux")}function E$(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 Vw(e){try{let t=JSON.parse(h$(qw(e).metadataFile,"utf8"));return E$(t)?t:null}catch{return null}}function Gw(e,t){rm(Mt.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;y$(r,`${JSON.stringify(t,null,2)}
|
|
22
|
-
`,{mode:384}),
|
|
85
|
+
`,{mode:384}),cj(r,this.filePath)}}});import{randomBytes as gj}from"node:crypto";import{existsSync as hj,rmSync as yj}from"node:fs";function jS(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 At(){return VS??=new Am,VS}var kj,bj,Am,VS,Fi=p(()=>{"use strict";HS();Tn();kj=720*60*1e3,bj=300*1e3,Am=class{rootDir;now;idleMs;keys=new Map;codes=new Map;codeListeners=new Set;constructor(t={}){this.rootDir=t.rootDir??Ui(),this.now=t.now??Date.now,this.idleMs=t.idleMs??kj}store(t){return new Fc({agentOsId:t,rootDir:this.rootDir,now:this.now})}audit(t){return new Kc(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 hj(o)&&yj(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_${gj(6).toString("hex")}`,createdAt:r,expiresAt:r+bj};this.codes.set(n.id,n);let o=jS(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=>jS(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)}};VS=null});var GS=p(()=>{"use strict";M()});var JS=p(()=>{"use strict";j();GS();sr()});function Rj(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 Pm(e){if(!e)return null;let t=Rj(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 Im=p(()=>{"use strict"});function qS(e){return/\((?:401|403)\)/.test(e)?"access_denied":"transient"}var Om=p(()=>{"use strict";j();sr();M();JS();Im()});import{existsSync as wj}from"node:fs";import{homedir as Sj}from"node:os";import _j from"node:path";function YS(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 Ki(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||_j.join(Sj(),".kynver","agent-os-cron.json")}function xj(e=jr()){let t=process.env.KYNVER_CRON_TICK_STATE_PATH?.trim();return t||`${e.replace(/\.json$/i,"")}.tick-state.json`}function Cj(){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 zS(){let e=E();return Ee("KYNVER_CRON_SECRET")||Ee("OPENCLAW_CRON_SECRET")||Ee("KYNVER_RUNTIME_SECRET")||Ie(e.agentOsId)?.trim()||Ie()?.trim()||null}function es(){let e=jr(),t=xj(e),r=Cj(),n=zS(),o=!!(r&&n),s=wj(e),i=o&&(s||YS("KYNVER_CRON_TICK_FORCE",!1));return{storePath:e,statePath:t,lockPath:`${t}.lock`,fireBaseUrl:r,secret:n,tickEnabled:YS("KYNVER_CRON_TICK_ENABLED",i),tickIntervalMs:Ki("KYNVER_CRON_TICK_INTERVAL_MS",6e4,5e3),missedRunPolicy:process.env.KYNVER_CRON_MISSED_RUN_POLICY?.trim().toLowerCase()==="skip"?"skip":"catch_up",maxCatchUpPerTick:Ki("KYNVER_CRON_MAX_CATCH_UP_PER_TICK",3,0),maxRetries:Ki("KYNVER_CRON_MAX_RETRIES",3,0),retryBackoffMs:Ki("KYNVER_CRON_RETRY_BACKOFF_MS",6e4,1e3),inflightLeaseMs:Ki("KYNVER_CRON_INFLIGHT_LEASE_MS",12e4,5e3)}}var gr=p(()=>{"use strict";j();wt()});import{promises as Ej}from"node:fs";async function XS(e){try{return await Ej.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function Aj(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t.entries)?t.entries:[]}catch{return[]}}async function $c(e=jr()){let t=await XS(e);return Aj(t)}async function Pj(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 Tm(e=jr()){return await XS(e)!==null?{created:!1}:(await Pj(e,[]),{created:!0})}var ts=p(()=>{"use strict";gr()});import{existsSync as Ij,readFileSync as Oj}from"node:fs";import{dirname as Nm,join as ZS}from"node:path";import{fileURLToPath as QS}from"node:url";function Tj(e){let t=Nm(QS(e));for(let r=0;r<6;r+=1){if(Ij(ZS(t,"package.json")))return t;let n=Nm(t);if(n===t)break;t=n}throw new Error(`package.json not found above ${Nm(QS(e))}`)}function Nj(e=import.meta.url){let t=ZS(Tj(e),"package.json"),r=JSON.parse(Oj(t,"utf8"));if(typeof r.version!="string"||!r.version.trim())throw new Error(`Missing package.json version at ${t}`);return r.version}var Ve,Vr=p(()=>{"use strict";Ve=Nj()});import{spawnSync as Dj}from"node:child_process";import{readFileSync as Mj}from"node:fs";function Lj(e,t){let r=Dj(e,t,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:15e3});return{status:r.status,stdout:r.stdout??""}}function Bj(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 Wj(e){return Number.isInteger(e)&&e>0}function e_(e,t={}){if(!Wj(e))return null;let r=t.platform??process.platform,n=t.readText??(s=>Mj(s,"utf8")),o=t.run??Lj;try{if(r==="linux"){let s=Bj(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 Dm=p(()=>{"use strict"});import{createHash as Fj,randomUUID as i_}from"node:crypto";import{closeSync as Kj,constants as Mm,existsSync as $j,mkdirSync as Lm,openSync as Hj,readFileSync as jj,renameSync as Bm,rmSync as Hc,writeFileSync as Vj}from"node:fs";import{createConnection as Gj,createServer as t_}from"node:net";import{homedir as Jj,tmpdir as qj}from"node:os";import Bt from"node:path";function Yj(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function a_(e){let t=e.stateRoot??Bt.join(Jj(),".kynver"),r=e.platform??process.platform,n=Fj("sha256").update(`${Bt.resolve(t)}\0${e.agentOsId}`).digest("hex").slice(0,24),o=Bt.join(t,"locks"),s=Bt.join(o,`${n.slice(0,16)}.sock`);r==="linux"?s=`\0kynver-daemon-owner-${n}`:Buffer.byteLength(s)>100&&(s=Bt.join(qj(),`kynver-owner-${n.slice(0,16)}.sock`));let i=Bt.join(t,`daemon-owner-${Yj(e.agentOsId)}.json`);return{lockKey:n,lockFile:Bt.join(o,`daemon-owner-${n}.lock`),metadataFile:i,quarantineFile:i.replace(/\.json$/,".stale.json"),socketAddress:s}}function Xj(e){Lm(Bt.dirname(e),{recursive:!0});let t;try{t=Hj(e,Mm.O_RDWR|Mm.O_CREAT|zj)}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{Kj(t)}catch{}}}}}}function r_(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 Qj(e,t=2e3){return new Promise(r=>{let n=Gj({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 Zj(e,t){e.startsWith("\0")||Lm(Bt.dirname(e),{recursive:!0,mode:448});let r=t_(a=>a.destroy());if(await r_(r,e)==="listening")return{held:n_(r,e)};if(!t||e.startsWith("\0"))return{busy:!0};if(await Qj(e))return{busy:!0};let o=`${e}.stale-${process.pid}-${i_().slice(0,8)}`;try{Bm(e,o),Hc(o,{force:!0})}catch{}let s=t_(a=>a.destroy());return await r_(s,e).catch(()=>"in_use")==="listening"?{held:n_(s,e)}:{busy:!0}}function n_(e,t){e.unref();let r=!0;return{isHeld:()=>r&&e.listening,release:()=>{r&&(r=!1,e.close(),t.startsWith("\0")||Hc(t,{force:!0}))}}}async function e1(e,t){return t==="win32"?Xj(e.lockFile):Zj(e.socketAddress,t!=="linux")}function t1(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 o_(e){try{let t=JSON.parse(jj(a_(e).metadataFile,"utf8"));return t1(t)?t:null}catch{return null}}function s_(e,t){Lm(Bt.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;Vj(r,`${JSON.stringify(t,null,2)}
|
|
86
|
+
`,{mode:384}),Bm(r,e)}function r1(e){if(!$j(e.metadataFile))return null;try{return Bm(e.metadataFile,e.quarantineFile),e.quarantineFile}catch{return Hc(e.metadataFile,{force:!0}),null}}function l_(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 jc(e){let t=e.platform??process.platform,r=a_(e),n=await e1(r,t);if("busy"in n){let u=o_(e);return{ok:!1,reason:"owner_conflict",holder:u,remedy:l_(u)}}let o=r1(r),s=(e.now??new Date).toISOString(),i={version:1,agentOsId:e.agentOsId,ownerKind:e.ownerKind,instanceId:i_(),pid:process.pid,processStart:e.processStart!==void 0?e.processStart:e_(process.pid),runtimeVersion:Ve,platform:t,acquiredAt:s,lastRenewedAt:s};try{s_(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{s_(r.metadataFile,i)}catch{}}},release(){if(l)return;l=!0,o_(e)?.instanceId===i.instanceId&&Hc(r.metadataFile,{force:!0}),a.release()}},quarantinedMetadata:o}}var zj,Vc=p(()=>{"use strict";Vr();Dm();zj=Mm.UV_FS_O_EXLOCK??268435456});var n1,o1,s1,i1,rs,Wm=p(()=>{"use strict";n1="embedded-1",o1=[{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"}],s1={"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
|
+
`)},i1={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},rs={version:n1,generatedAt:"1970-01-01T00:00:00.000Z",personas:o1,instructions:s1,policyThresholds:i1}});function u_(){return ns}function Dn(){return ns.version}function Wt(){return c_}function d_(e,t){ns=e,c_=t}function $i(e){let t=ns.instructions[e];if(typeof t=="string"&&t.trim())return t;let r=rs.instructions[e];return typeof r=="string"?r:""}function os(e,t){let r=ns.policyThresholds[e];if(typeof r=="number"&&Number.isFinite(r))return r;let n=rs.policyThresholds[e];return typeof n=="number"&&Number.isFinite(n)?n:t}function p_(e){if(!e)return null;let t=e.trim().toLowerCase();return ns.personas.find(r=>r.slug===t)??null}var ns,c_,Gr=p(()=>{"use strict";Wm();ns=rs,c_="embedded"});import f_ from"node:os";function hr(e){return e?.trim()?e.trim():null}function Te(e={}){let t=e.env??process.env,r=E();return{runnerId:hr(r.runnerId)??hr(t.KYNVER_RUNTIME_ID)??hr(t.OPENCLAW_RUNTIME_ID)??hr(t.HOSTNAME)??f_.hostname(),hostname:hr(t.HOSTNAME)??f_.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:Dn()}}var yr=p(()=>{"use strict";j();Gr();Me()});import a1 from"node:os";function Um(e=E(),t=process.env){let r=Ze(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=Lt(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=fc(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=Pi(r.boxKind,a1.hostname()),s=!0,n.push(`persisted boxId=${i.boxId} to ~/.kynver/config.json`)),gi(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&&Be(i),{repaired:s,boxKind:r.boxKind,maxConcurrentWorkers:o??4,warnings:n}}var Fm=p(()=>{"use strict";j();Me();Ho();Ao();wn()});function Pt(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 ss=p(()=>{"use strict"});function l1(e){let t=e.runnerId??Te().runnerId;return`${e.baseUrl.replace(/\/+$/,"")}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/runtime-control/runner?runnerId=${encodeURIComponent(t)}`}async function m_(e,t){try{return(await(e.fetchImpl??fetch)(l1(e),{method:"POST",headers:Pt(e.secret),body:JSON.stringify({ack:t})})).ok}catch{return!1}}var Km=p(()=>{"use strict";ss();yr();$r()});var g_=p(()=>{"use strict";j();M();Km();$r()});function h_(){let e=process.env.KYNVER_GIT_COMMIT_SHA?.trim();return{contractVersion:1,nodeVersion:process.versions.node,runtimePackageVersion:Ve,buildIdentity:e&&c1.test(e)?e.toLowerCase():null,platform:process.platform,arch:process.arch}}var c1,y_=p(()=>{"use strict";Vr();c1=/^[0-9a-f]{7,40}$/i});import{mkdirSync as u1,readFileSync as Yue,renameSync as d1,writeFileSync as p1}from"node:fs";import{homedir as f1}from"node:os";import k_ from"node:path";function m1(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return k_.join(f1(),".kynver",`daemon-heartbeat-${t}.json`)}function b_(e){try{let t=m1(e.agentOsId);u1(k_.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:h_(),...e.owner?{owner:e.owner}:{}},n=`${t}.tmp-${process.pid}`;p1(n,JSON.stringify(r),"utf8"),d1(n,t)}catch{}}var $m=p(()=>{"use strict";y_();Dm()});function Hm(e,t,r=6e4){let n=t-e;return n>r?n:null}var jm=p(()=>{"use strict"});function h1(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 v_(e,t){let r=h1(e);if(r!==null&&r>1)throw new Vm(r,1);e.exec("BEGIN IMMEDIATE");try{for(let n of g1)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 Vm,g1,R_=p(()=>{"use strict";Vm=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"}},g1=[`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=tW(t);if(!r||!oi(r)){let o=ni(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 y1,realpathSync as k1,readFileSync as b1}from"node:fs";import w_ from"node:path";function w1(){try{return b1("/proc/self/mounts","utf8")}catch{return null}}function S1(e){let t=w_.resolve(e);for(let r=0;r<64;r+=1){if(y1(t))try{return k1.native(t)}catch{return t}let n=w_.dirname(t);if(n===t)return t;t=n}return t}function _1(e){return e.replace(/\\(\d{3})/g,(t,r)=>String.fromCharCode(Number.parseInt(r,8)))}function x1(e){let t=[];for(let r of e.split(`
|
|
117
|
+
`)){let n=r.trim().split(/\s+/);n.length<3||t.push({mountPoint:_1(n[1]),fsType:n[2]})}return t}function S_(e,t=process.platform){return t==="win32"?e.replace(/\\/g,"/"):e}function C1(e,t){let r=null,n=S_(e);for(let o of t){let s=S_(o.mountPoint),i=s.endsWith("/")?s:`${s}/`;(n===s||`${n}/`.startsWith(i))&&(!r||o.mountPoint.length>r.mountPoint.length)&&(r=o)}return r}function __(e,t){let n=(t?.resolveRealPath??S1)(e),o=(t?.mountsSource??w1)();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=C1(n,x1(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 R1.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}:v1.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 v1,R1,x_=p(()=>{"use strict";v1=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),R1=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 A1}from"node:fs";import P1 from"node:path";import{DatabaseSync as I1}from"node:sqlite";var Jc,O1,T1,Hi,C_=p(()=>{"use strict";R_();x_();Jc=class extends Error{constructor(t){super(`local-run-store refused: ${t}`),this.name="FilesystemPolicyError"}},O1="local-run-store.sqlite",T1=5e3,Hi=class e{db;now;databasePath;constructor(t,r,n){this.db=t,this.databasePath=r,this.now=n}static open(t){let r=__(t.directory,t.classifyOptions);if(r.verdict!=="accepted")throw new Jc(r.reason);A1(t.directory,{recursive:!0,mode:448});let n=P1.join(t.directory,t.filename??O1),o=new I1(n,{timeout:t.busyTimeoutMs??T1}),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 Jc(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),v_(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=tW(t);if(!r||!oi(r)){let o=ni(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 Oae,Tae,Nae,Dae,hm=p(()=>{"use strict";dn();tS();K();lm();N();dc();um();Ti();Oae=15*6e4,Tae=2*6e4,Nae=5*6e4,Dae=30*6e4});import SH from"node:path";function _H(e){return SH.resolve(Oe(e.trim()))}function Qo(e,t,r){let n=e?.trim();return n?{repo:_H(n),source:t,persistedInConfig:r}:null}function ES(e){return e?{repo:e.repo,source:e.source,persistedInConfig:!1}:null}function Ni(e={}){let t=e.env??process.env,r=e.config??I(),n=Qo(r.defaultRepo,"config",!0);if(n)return n;let o=Qo(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(o)return o;let s=Qo(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return s||ES(wl({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl}))}function AS(e={}){let t=e.env??process.env,r=e.config??I(),n=Qo(r.defaultRepo,"config",!0);if(n)return n;let o=Qo(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(o)return o;let s=Qo(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return s||ES(Sl({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl,home:e.home}))}function PS(e,t){let r={...t??I(),defaultRepo:Oe(e),...Zb(e)&&!t?.defaultBase?.trim()?{defaultBase:"main"}:{}};return Le(r),r}function ym(e){return{defaultRepo:Ke(e.repo),source:e.source,persistedInConfig:e.persistedInConfig}}var Zo=p(()=>{"use strict";K();Zs();rt();Wp()});import xH from"node:path";import{homedir as CH}from"node:os";function IS(e){let t=I(),r=AS({...e,config:t});if(!r)return{ok:!1,remediated:!1,alreadyPersisted:!1,configPath:Ke(km),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:Ke(km),resolved:ym(r),config:_f(t)};let n=PS(r.repo,t),o=ym({...r,persistedInConfig:!0,source:"config"});return{ok:!0,remediated:!0,alreadyPersisted:!1,configPath:Ke(km),resolved:o,config:_f(n),remediation:"defaultRepo persisted in ~/.kynver/config.json \u2014 `kynver run create` no longer requires --repo."}}var km,OS=p(()=>{"use strict";rt();K();Zo();km=xH.join(CH(),".kynver","config.json")});import{mkdirSync as EH,readFileSync as AH,renameSync as PH,writeFileSync as IH}from"node:fs";import{homedir as OH}from"node:os";import TS from"node:path";function NS(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return TS.join(OH(),".kynver",`instruction-bundle-${t}.json`)}function DS(e,t){try{let r=NS(e);EH(TS.dirname(r),{recursive:!0});let n=`${r}.tmp-${process.pid}`;IH(n,JSON.stringify(t),{encoding:"utf8",mode:384}),PH(n,r)}catch{}}function MS(e){try{let t=AH(NS(e),"utf8"),r=JSON.parse(t);return vi(r)?r:null}catch{return null}}var LS=p(()=>{"use strict";Lr()});function BS(e,t=process.env){let r=Ho(t.KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY);if(r&&zR(r)===e)return r;if(e===TH&&!pc(t))return null;let n=NH[e];return n?Ho(n):null}var TH,NH,US=p(()=>{"use strict";Lr();TH="ib-3bab6314f0ba",NH={"ib-3bab6314f0ba":"53a2040646cd479e1f5f1aea9abf7848ce8b62e32001efb8044dfd90e8ab87ed","ib-26e6c695da06":"bb1700f25b2ee7d7cdcdb9f446f0f44ef2cc22a3096bc161232fb658e7cdaf38","ib-49e76cb8052c":"8fc646b5c4f8f402120477452608398f035c3cddd2e7aa8bb328e97b84dcf6d8"}});import{createPublicKey as DH,verify as MH}from"node:crypto";function BH(e){return DH({key:Buffer.concat([LH,Buffer.from(e)]),format:"der",type:"spki"})}function UH(e,t){if(!vi(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(Ze(e.bundle),"utf8");return MH(null,n,BH(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 WS(e,t=process.env){if(!vi(e))return{ok:!1,reason:"malformed signed bundle payload"};let r=BS(e.publicKeyId,t);return r?UH(e,r):{ok:!1,reason:`no verification key for publicKeyId "${e.publicKeyId}" (not pinned; set KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY)`}}var LH,FS=p(()=>{"use strict";US();Lr();LH=Buffer.from("302a300506032b6570032100","hex")});function Mi(e,t){console.error(JSON.stringify({event:e,...t}))}function KS(e,t,r){let n=WS(e);return n.ok?(Xw(n.bundle,t),t==="server"&&DS(r,e),!0):(Mi("instruction_bundle_signature_invalid",{agentOsId:r,source:t,publicKeyId:e.publicKeyId,reason:n.reason}),!1)}function Di(e){if(gr.diskCacheTried)return!1;gr.diskCacheTried=!0;let t=MS(e);return t?KS(t,"disk",e):!1}async function $S(e){let t=e.nowMs??Date.now(),r=()=>({source:Ur(),version:_n(),updated:!1});if(!e.force&&t-gr.lastAttemptAtMs<WH)return r();gr.lastAttemptAtMs=t;let n=e.baseUrl?.trim().replace(/\/$/,""),o=e.secret?.trim();if(!n||!o)return Ur()==="embedded"&&Di(e.agentOsId)?{...r(),updated:!0}:r();let s=e.fetchImpl??fetch,i=new AbortController,a=setTimeout(()=>i.abort(),FH);try{let l=xt(o);delete l["Content-Type"],gr.etag&&Ur()==="server"&&(l["If-None-Match"]=gr.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 gr.routeMissingLogged||(gr.routeMissingLogged=!0,Mi("instruction_bundle_route_missing",{agentOsId:e.agentOsId,baseUrl:n})),Ur()==="embedded"&&Di(e.agentOsId)?{...r(),updated:!0}:r();if(!c.ok)return Mi("instruction_bundle_fetch_failed",{agentOsId:e.agentOsId,status:c.status}),Ur()==="embedded"&&Di(e.agentOsId)?{...r(),updated:!0}:r();let u=await c.json().catch(()=>null);return!u||!KS(u,"server",e.agentOsId)?Ur()==="embedded"&&Di(e.agentOsId)?{...r(),updated:!0}:r():(gr.etag=c.headers.get("etag"),Mi("instruction_bundle_loaded",{agentOsId:e.agentOsId,version:_n(),publicKeyId:u.publicKeyId}),{...r(),updated:!0})}catch(l){return Mi("instruction_bundle_fetch_error",{agentOsId:e.agentOsId,error:l instanceof Error?l.message:String(l)}),Ur()==="embedded"&&Di(e.agentOsId)?{...r(),updated:!0}:r()}finally{clearTimeout(a)}}var WH,FH,gr,HS=p(()=>{"use strict";zo();LS();xn();FS();WH=15*6e4,FH=1e4,gr={lastAttemptAtMs:0,etag:null,diskCacheTried:!1,routeMissingLogged:!1}});import KH from"node:os";function jS(e,t){console.error(JSON.stringify({event:"daemon_identity",level:e,message:t}))}function VS(e=I(),t=process.env){let r=Xe(t,e),n=Oo({config:e,totalMemBytes:KH.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=rr(r.boxKind,i);ti(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)jS("warn",c);for(let c of s)jS("error",c);return{ok:l,box:r,workerCapSource:n.workerCapSource,maxConcurrentWorkers:a,autoCap:n.autoCap,warnings:o,errors:s}}var GS=p(()=>{"use strict";K();Ne();bo();ui()});import{spawnSync as $H}from"node:child_process";import{existsSync as HH,readFileSync as jH}from"node:fs";import VH from"node:path";function JH(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+GH<s.startedAtMs||o.push({workerName:s.workerName,workerPid:s.pid,orphanPid:i.pid}));return o}function qH(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 YH(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=$H("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:3e4});if(o.status!==0)return[];try{return qH(o.stdout??"")}catch{return[]}}function zH(e,t=ie){try{let r=Re().find(o=>o.id===e);if(!r)return[];let n=[];for(let o of Object.keys(r.workers||{})){let s=VH.join(G(r.id),"workers",L(o),"worker.json");if(!HH(s))continue;let i=JSON.parse(jH(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 JS(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return{checkedWorkers:0,killed:[]};let n=t.isAlive??ie,o=(t.collect??(l=>zH(l,n)))(e);if(o.length===0)return{checkedWorkers:0,killed:[]};let s=(t.query??YH)(o.map(l=>l.pid)),i=t.killTree??Te,a=JH(s,o,n).map(l=>({...l,result:i(l.orphanPid,"SIGKILL")}));return{checkedWorkers:o.length,killed:a}}var GH,qS=p(()=>{"use strict";z();N();qs();GH=5e3});import{mkdirSync as XH,readFileSync as QH,renameSync as ZH,writeFileSync as ej}from"node:fs";import{homedir as tj}from"node:os";import Oc from"node:path";function YS(){return Oc.join(tj(),".kynver")}function rj(e=YS()){return Oc.join(e,"doctor-native-windows.json")}function zS(e=YS()){return Oc.join(e,"native-windows-state.json")}function nj(e,t){XH(Oc.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;ej(r,`${JSON.stringify(t,null,2)}
|
|
79
|
-
`,{mode:384}),
|
|
80
|
-
`,"utf8");try{await Bi.rename(n,e)}catch(o){let s=o.code;if(s!=="EPERM"&&s!=="EEXIST"&&s!=="EACCES")throw o;await Bi.unlink(n).catch(()=>{})}}async function p_(e,t){await Ej(e,t)}function f_(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 Nc,Em=p(()=>{"use strict";Nc={version:1,jobs:{}}});function Aj(e,t){if(!e.inflightUntil)return!1;let r=Date.parse(e.inflightUntil);return!Number.isNaN(r)&&r>t}function Pj(e){return!!e.completedAt}function Ij(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 Oj(e,t,r){if(t.nextFireAt)return t.nextFireAt;let n=u_(e.spec,r);return t.nextFireAt=n,n}function Tj(e,t,r,n){if(e.paused||Pj(t)||Aj(t,r)||!Ij(e,t,n,r))return!1;let o=t.nextFireAt?Date.parse(t.nextFireAt):NaN;return Number.isNaN(o)?!1:r>=o}function Nj(e,t,r){e.spec.scheduleKind==="cron"&&(t.nextFireAt=xm(e.spec,r))}async function Am(e={}){let t=e.env??Vo(),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=i_(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 Sc(t.storePath),a=e.agentOsIdFilter?i.filter(h=>h.spec.target.agentOsId===e.agentOsIdFilter):i,l=await Cm(t.statePath),c=[];for(let h of a){let y=f_(l,h.providerScheduleId);Oj(h,y,r),Tj(h,y,n,t)&&c.push({entry:h,job:y})}c.sort((h,y)=>{let b=Date.parse(h.job.nextFireAt??"")||0,k=Date.parse(y.job.nextFireAt??"")||0;return b-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 b=Date.parse(y.nextFireAt??"");if(!Number.isNaN(b)&&b<n-t.tickIntervalMs*2){y.nextFireAt=xm(h.spec,r),m++;continue}}if(f<=0){m++;continue}y.inflightUntil=new Date(n+t.inflightLeaseMs).toISOString(),y.lastAttemptAt=r.toISOString(),Nj(h,y,r);try{let b=He(h.spec.target.agentOsId)||t.secret;if(!b){y.inflightUntil=null,y.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,error:"missing_fire_credentials"});continue}let k=await r_({entry:h,baseUrl:t.fireBaseUrl,secret:b,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(b){y.inflightUntil=null,y.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,error:b instanceof Error?b.message:String(b)})}}return await p_(t.statePath,l),{enabled:!0,scanned:a.length,due:c.length,fired:u,skippedJobs:m,errors:d,...g.length?{errorDetails:g}:{}}}finally{a_(t.lockPath)}}var Pm=p(()=>{"use strict";ur();n_();l_();K();d_();Go();Em()});import m_ from"node:path";function Dc(e){let t=W(m_.join(G(e),g_),null);return RS(e,t)??t}function h_(e,t){let r={...t,updatedAt:new Date().toISOString()};ye(m_.join(G(e),g_),r),vS(e,r)}function y_(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 g_,Im=p(()=>{"use strict";N();z();Ti();g_="mesh-cron-lease.json"});function b_(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 k_(e){return new Error(`callback timeout after ${e}ms`)}async function v_(e,t){let r=b_(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(k_(r))},r)})])}catch(i){throw s?k_(r):i}finally{o&&clearTimeout(o)}}function R_(e,t){let r=b_(t);return{ok:!1,status:0,response:{error:e instanceof Error?e.message:String(e),timeoutMs:r}}}async function Cn(e,t,r,n){try{return await v_(async o=>{let s=await st(e,{method:"POST",headers:xt(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 R_(o,n?.timeoutMs)}}async function de(e,t,r,n){let o=await Cn(e,t,r,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await jR(t,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await Cn(e,s.token,r,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function Om(e,t,r){try{return await v_(async n=>{let o=await st(e,{method:"GET",headers:xt(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 R_(n,r?.timeoutMs)}}var Ue=p(()=>{"use strict";zo();tr();K()});function w_(){let e=Number(process.env.KYNVER_DISPATCH_CALLBACK_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):3e5}var S_=p(()=>{"use strict"});function Ui(e){console.error(JSON.stringify({event:"dispatch_progress",ts:new Date().toISOString(),...e}))}function __(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 Tm(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 x_=p(()=>{"use strict"});function Lj(e){return Dj.includes(e)}function Bj(e){return Mj.includes(e)}function C_(e){return{slug:e.slug,displayName:e.displayName,description:e.description,dispatchLane:e.dispatchLane===null||Lj(e.dispatchLane)?e.dispatchLane:null,defaultRoleLane:Bj(e.defaultRoleLane)?e.defaultRoleLane:"implementer"}}function Wj(e){if(!e)return null;let t=e.trim().toLowerCase(),r=Uj.get(t)??null,n=Qw(t);if(!n)return r;let o=C_(n);return r?{...o,dispatchLane:r.dispatchLane,defaultRoleLane:r.defaultRoleLane}:o}function Nm(e){return Wj(e)?.defaultRoleLane??null}function A_(){return E_.filter(e=>e.dispatchLane==="review").map(e=>e.slug)}var Dj,Mj,E_,Uj,Mc=p(()=>{"use strict";om();xn();Dj=["implementation","review","landing"],Mj=["plan_author","implementer","report_reviewer","deep_reviewer","runtime_verifier","system"];E_=qo.personas.map(C_),Uj=new Map(E_.map(e=>[e.slug,e]))});function P_(e){return(e??"").trim().toLowerCase()}function Fj(e){switch(P_(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 Kj(e){let t=P_(e);if(!t)return;if(t==="implementation"||t==="review"||t==="landing"||t==="any")return t;let r=Fj(t);if(r)return r;if(t==="implement"||t==="repair"||t==="coding")return"implementation";if(t==="land"||t==="merge")return"landing"}function I_(e){return Kj(e)??"any"}var O_=p(()=>{"use strict";Mc()});function $j(e=process.env){let t=I();return vt(t,e)!=="forge"}function Lc(e,t=process.env){if($j(t))return e?.maxConcurrentWorkers??void 0}async function Bc(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 Om(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 Dm=p(()=>{"use strict";Ue();K();Ne()});async function T_(e,t=Hj){let r=await t.fetchPreferences(e.agentOsId,e.args),n=t.configuredOverride(r,e.env);return t.observe({runId:e.runId,configuredMaxWorkersOverride:n})}var Hj,N_=p(()=>{"use strict";Dm();Io();Hj={fetchPreferences:Bc,configuredOverride:Lc,observe:ci}});function Uc(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function Mm(e){return e.toLowerCase()}function jj(e){let t=Uc(e,"roleLane");if(t)return t;let r=Mm(Uc(e,"executorRef")),n=Mm(Uc(e,"title")),o=Mm(Uc(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=Nm(o);if(i)return o==="lorentz"&&(s.includes("deep")||s.includes("security"))?"deep_reviewer":i;if(s.includes("review"))return"report_reviewer"}function D_(e){let t=jj(e);return t?{...e,roleLane:t}:e}var M_=p(()=>{"use strict";Mc()});function L_(e){let t=e.trim();return Vj.test(t)||Gj.test(t)}function B_(e){let t=e.trim().toLowerCase();return t.startsWith("gpt-")||t.startsWith("gpt5")||t.includes("codex")}function Lm(e){let t=e.trim().toLowerCase();return t.includes("composer")||t.includes("cursor")}function U_(e){return e.trim().toLowerCase().startsWith("gemini-")}function Jj(e){return B_(e)?"codex":L_(e)?"claude":U_(e)?"gemini":(Lm(e),"cursor")}function qj(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 Yj(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?L_(n)||B_(n)||Lm(n)||U_(n)?{lane:r,model:n,provider:Jj(n),rule:"executor_ref:harness_lane_model"}:{lane:r,rule:"executor_ref:harness_lane"}:{lane:r,rule:"executor_ref:harness_lane"}}function lt(e){let t=typeof e=="string"?e.trim():"";return t?qj(t)??Yj(t):null}function W_(e){let t=lt(e);return t?!!(t.provider&&t.provider!=="cursor"||t.model&&!Lm(t.model)):!1}var Vj,Gj,Wc=p(()=>{"use strict";Vj=/^claude[-_]/i,Gj=/^(?:opus|sonnet|haiku)\b/i});function Wi(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function hr(e){if(!e?.trim())return!1;let t=e.trim().toLowerCase();return zj.has(t)?!0:t.includes("claude")||t.includes("opus")}function Fc(e){if(!e)return!1;let t=e.workerProviderOverride;if(typeof t=="string"&&hr(t))return!0;let r=Wi(e,"executorRef").toLowerCase();if(r==="provider:claude"||r.startsWith("provider:claude:")||r.includes("claude-worker-override")||r.includes("operator-claude"))return!0;let n=lt(Wi(e,"executorRef"));if(n?.provider&&hr(n.provider)||n?.model&&hr(Qj(n.model)))return!0;let o=Wi(e,"description");if(Xj.some(i=>i.test(o)))return!0;let s=Wi(e,"title");return!!/\[use-claude-worker\]/i.test(s)}function Qj(e){let t=e.trim().toLowerCase();return/^claude[-_]/.test(t)||/^(?:opus|sonnet|haiku)\b/.test(t)?"claude":t}function Zj(e,t){return{provider:yr,model:Kc,rule:`policy:cursor_default${t}`,requestedModel:e}}function t1(e){return e1.some(t=>e.startsWith(t))}function Bm(e){if(!e)return!1;let t=e.workerProviderOverride;return typeof t=="string"&&t.trim()||lt(Wi(e,"executorRef"))?.provider?!0:Fc(e)}function F_(e){let{routing:t,task:r}=e,n=e.explicitProvider?.trim().toLowerCase();if(e.explicitProviderIsOperatorOverride&&hr(n))return{...t,provider:"claude",rule:t.rule.startsWith("explicit:")?t.rule:"explicit:operator_provider"};if(n||t1(t.rule)||Bm(r)||!hr(t.provider))return t;let o=t.rule&&t.rule!=="default:global"?`:${t.rule.replace(/:/g,"_")}`:"";return Zj(t.model,o)}function K_(e,t=yr){let r=e?.trim();return r?$e(r):t}var yr,zj,Xj,e1,En=p(()=>{"use strict";Wc();$c();gi();gi();yr="cursor",zj=new Set(["claude","opus","anthropic"]),Xj=[/\[worker-provider:\s*claude\]/i,/\[use-claude-worker\]/i,/\[operator-worker-provider:\s*claude\]/i];e1=["explicit:","executor_ref:","factory:","task:"]});function es(e){return $_[e]}function H_(){return Object.values($_)}var $_,Um=p(()=>{"use strict";$_={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 G_,readFileSync as r1}from"node:fs";import An from"node:path";function o1(e){return e.includes("/")||e.includes("\\")}function s1(e){return(e.PATHEXT||n1).split(";").map(t=>t.trim().toLowerCase()).filter(t=>t.startsWith("."))}function i1(e){let t=Object.keys(e).find(r=>r.toUpperCase()==="PATH");return t?e[t]??"":""}function a1(e,t={}){let r=t.env??process.env,n=t.exists??G_,o=s1(r),s=An.win32.extname(e)!=="",i=a=>s?[a]:o.map(l=>`${a}${l}`);if(o1(e)||An.win32.isAbsolute(e))return i(e).find(a=>n(a))??null;for(let a of i1(r).split(";").map(l=>l.trim()).filter(Boolean)){let l=i(An.win32.join(a,e)).find(c=>n(c));if(l)return l}return null}function V_(e){return e.replace(/^[\\/]+/,"")}function c1(e){let t=e.split(/\r?\n/),r=new Map;for(let s of t){let i=l1.exec(s);i&&r.set(i[1].toUpperCase(),i[2])}let n=t.filter(s=>s.includes("%*")).pop();if(!n)return null;let o=j_.exec(n);if(o)return V_(o[1]);for(let s of n.matchAll(/%([A-Za-z_]\w*)%/g)){let i=r.get(s[1].toUpperCase()),a=i?j_.exec(i):null;if(a)return V_(a[1])}return null}function u1(e,t={}){if((t.platform??process.platform)!=="win32")return{executable:e,prefixArgs:[],kind:"passthrough"};let n=a1(e,t);if(!n)return{executable:e,prefixArgs:[],kind:"passthrough"};let o=An.win32.extname(n).toLowerCase();if(o!==".cmd"&&o!==".bat")return{executable:n,prefixArgs:[],kind:"exe"};let s=t.readText??(f=>r1(f,"utf8")),i=t.exists??G_,a;try{a=s(n)}catch{throw new Fi(n)}let l=c1(a);if(!l)throw new Fi(n);let c=An.win32.dirname(n),u=An.win32.join(c,l);if(!i(u))throw new Fi(n);let d=An.win32.join(c,"node.exe");return{executable:i(d)?d:t.nodeExecutable??process.execPath,prefixArgs:[u],kind:"node-shim"}}function oe(e,t,r={}){let n=u1(e,r);return[n.executable,[...n.prefixArgs,...t]]}var Fi,n1,j_,l1,Ge=p(()=>{"use strict";Fi=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},n1=".COM;.EXE;.BAT;.CMD";j_=/%~?dp0%?\\?([^"%\r\n]+?\.(?:c|m)?js)\b/i,l1=/^\s*SET\s+"?([A-Za-z_]\w*)=([^"\r\n]*)"?\s*$/i});import{createHash as J_}from"node:crypto";import{statSync as d1}from"node:fs";import{spawnSync as q_}from"node:child_process";function Lt(e){try{let t=d1(e),r=`${e}|${t.size}|${t.mtimeMs}`;return J_("sha256").update(r).digest("hex").slice(0,16)}catch{return}}function ts(e){return J_("sha256").update(`env:${e}`).digest("hex").slice(0,16)}function ct(e,t){for(let r of t){let n=process.env[r]?.trim();if(n)return n}return e}function Et(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=oe(e,t),i=q_(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 Hc(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=oe(e,t);return q_(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 Pn=p(()=>{"use strict";Ge()});import{existsSync as p1}from"node:fs";import{homedir as f1}from"node:os";import Ki from"node:path";function g1(){let e=f1();return[process.env.CODEX_HOME?.trim()?Ki.join(Ki.resolve(process.env.CODEX_HOME.trim()),"auth.json"):null,Ki.join(e,".codex","auth.json"),Ki.join(e,".config","codex","auth.json")].filter(r=>!!r)}function h1(e){return Ki.dirname(e)}function y1(e){let t,r;for(let n of g1()){if(!p1(n))continue;t??=n;let o=Et(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status",env:{CODEX_HOME:h1(n)}});if(r??=o,o.ok)return{authPath:n,login:o}}return{authPath:t,login:r??Et(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status"})}}function Y_(e=new Date().toISOString()){let t=ct(m1,["KYNVER_CODEX_BIN","CODEX_BIN"]);if(process.env.CODEX_API_KEY?.trim())return{providerId:"codex",ready:!0,authSource:"api_key_env",sessionFingerprint:ts("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}=y1(t),o=!!r&&n.ok;return{providerId:"codex",ready:o,authSource:"oauth_local",sessionFingerprint:r?Lt(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 m1,z_=p(()=>{"use strict";Pn();m1="codex"});import{existsSync as k1}from"node:fs";import{homedir as b1}from"node:os";import Wm from"node:path";function v1(){let e=process.env.HERMES_HOME?.trim(),t=e?Wm.resolve(e):Wm.join(b1(),".hermes");return Wm.join(t,"auth.json")}function jc(e=new Date().toISOString()){let t=ct("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=Et(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=v1(),o=k1(n),s=Hc(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?Lt(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 Fm=p(()=>{"use strict";Pn()});function rs(e=new Date().toISOString()){let t=Y_(e);if(t.ready)return{...t,path:"codex_cli"};let r=jc(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 Vc=p(()=>{"use strict";z_();Fm()});function Z_(e,t){let r=es(e);return t==="privileged"?r.supportsPrivilegedPlatformActions:t==="low"?r.supportsLowRiskOrchestration:!0}function R1(e,t){let r=es(e.providerId),n=es(t.providerId),o=X_.indexOf(r.costTier)-X_.indexOf(n.costTier);if(o!==0)return o;let s=Q_[e.binding.authSource]-Q_[t.binding.authSource];return s!==0?s:e.providerId.localeCompare(t.providerId)}function Km(e){let t=H_().map(a=>({providerId:a.id,binding:e.inventory.bindings[a.id]})).filter(a=>a.binding.ready&&Z_(a.providerId,e.riskClass));if(t.length===0)return null;let n=[...t].sort(R1)[0],o="codex";if(n.providerId===o)return{providerId:n.providerId,binding:n.binding};let s=e.inventory.bindings[o],i;return Z_(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 X_,Q_,ex=p(()=>{"use strict";Um();X_=["low","medium","high"],Q_={oauth_local:0,subscription_hermes:0,runner_token:1,api_key_env:2,none:3}});import{existsSync as w1}from"node:fs";import{homedir as S1}from"node:os";import _1 from"node:path";function C1(){let e=S1();return[_1.join(e,".claude",".credentials.json")]}function tx(e=new Date().toISOString()){let t=ct(x1,["KYNVER_CLAUDE_BIN","CLAUDE_BIN"]);if(process.env.ANTHROPIC_API_KEY?.trim())return{providerId:"claude",ready:!1,authSource:"api_key_env",sessionFingerprint:ts("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=Et(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=C1().find(i=>w1(i)),o=Hc(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?Lt(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 x1,rx=p(()=>{"use strict";Pn();x1="claude"});function ut(e,t={}){let r=zs(e);if(!t.reviewWorker)return r;let n={...r,[E1]:"1"};for(let o of A1)delete n[o];return n}var E1,A1,In=p(()=>{"use strict";Xs();E1="KYNVER_NO_PROD_DB_CREDENTIALS",A1=["KYNVER_ENV_FILE"]});function nx(e){return e.replace(P1,"")}function Gc(e){return/^claude[-_]/i.test(e)||/^(?:opus|sonnet|haiku)\b/i.test(e)}function I1(e){let t=e.trim().toLowerCase();return t.startsWith("gemini-")||t==="auto"||t==="pro"||t==="flash"||t==="flash-lite"}function T1(e){let t=e.trim().toLowerCase();return O1.has(t)?"auto":null}function $m(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=nx(r).trim()||t;return ox.test(o)||!Gc(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 ns(e,t){let r=(e??"").trim();return r?Gc(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 Hm(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 os(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=nx(r).trim()||t;return Gc(o)||!I1(o)&&ox.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 ss(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let n=T1(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")`}:Gc(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 P1,ox,O1,Bt=p(()=>{"use strict";P1=/-(?:thinking(?:-(?:high|medium|low|minimal|max|none))?|high|medium|low|minimal)$/i;ox=/^(?:gpt-|gpt5|o1|o3|o4|gemini-|grok-|composer|deepseek|llama|mistral|qwen|command-)/i;O1=new Set(["cursor"])});import{existsSync as $i,readdirSync as N1}from"node:fs";import On from"node:path";function M1(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 L1(e){let t=On.join(e,"versions");if(!$i(t))return null;let r=null,n=-1;for(let o of N1(t,{withFileTypes:!0})){if(!o.isDirectory()||!D1.test(o.name))continue;let s=M1(o.name);s==null||s<=n||(n=s,r=On.join(t,o.name))}return r}function Jc(e){let t=e?.trim()||On.join(process.env.LOCALAPPDATA||"","cursor-agent"),r=On.join(t,"node.exe"),n=On.join(t,"index.js");if($i(r)&&$i(n))return{nodeExe:r,indexJs:n,versionDir:t};let o=L1(t);if(!o)return null;let s=On.join(o,"node.exe"),i=On.join(o,"index.js");return!$i(s)||!$i(i)?null:{nodeExe:s,indexJs:i,versionDir:o}}var D1,sx=p(()=>{"use strict";D1=/^\d{4}\.\d{1,2}\.\d{1,2}-[a-f0-9]+$/i});import{closeSync as Vm,existsSync as ax,mkdirSync as B1,openSync as Gm,statSync as U1,unlinkSync as ix}from"node:fs";import{spawn as W1}from"node:child_process";import F1 from"node:os";import Ut from"node:path";function j1(e,t,r){return{executable:e,prefixArgs:[t],shell:!1,detached:be(),bundledVersionDir:r}}function Hi(e){if(process.platform==="win32"){let t=/\.(cmd|bat)$/i.test(e),r=/node\.exe$/i.test(e)&&ax(Ut.join(Ut.dirname(e),"index.js"));if(t||r||e==="agent"){let o=t?Jc(Ut.dirname(e)):r?{nodeExe:e,indexJs:Ut.join(Ut.dirname(e),"index.js"),versionDir:Ut.dirname(e)}:Jc();if(o)return j1(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 V1(e,t,r){return ut({...process.env,CI:"1",NO_COLOR:"1",...t.bundledVersionDir?{CURSOR_INVOKED_AS:Ut.basename(e)||"agent.cmd"}:{}},{reviewWorker:r})}function lx(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Jm(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 G1(){let e=process.env.KYNVER_CURSOR_START_LOCK_DIR?.trim()||Ut.join(F1.homedir(),".kynver","locks");return B1(e,{recursive:!0}),Ut.join(e,"cursor-agent-start.lock")}function J1(){if(process.env.KYNVER_CURSOR_START_LOCK==="0")return()=>{};let e=G1(),t=Jm("KYNVER_CURSOR_START_LOCK_TIMEOUT_MS",$1),r=Jm("KYNVER_CURSOR_START_LOCK_STALE_MS",H1),n=Date.now();for(;;)try{let o=Gm(e,"wx");return Vm(o),()=>{try{ix(e)}catch{}}}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-U1(e).mtimeMs>r){ix(e);continue}}catch{continue}if(Date.now()-n>t)throw new Error(`timed out waiting for Cursor agent start lock: ${e}`);lx(250)}}function Tn(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=Jc(e.KYNVER_CURSOR_AGENT_ROOT?.trim()||void 0);if(r)return r.nodeExe;let n=Ut.join(e.LOCALAPPDATA||"","cursor-agent","agent.cmd");if(ax(n))return n}return"agent"}function q1(){return Tn(process.env)}function Y1(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 jm,K1,$1,H1,cx,is=p(()=>{"use strict";N();In();Bt();sx();jm="composer-2.5",K1=15e3,$1=6e4,H1=3e4;cx={name:"cursor",defaultModel:jm,preflightModel(e){return ss(e,jm)},start(e){let t=ss(e.model,jm);if(!t.ok)throw new Error(`cursor provider model preflight failed: ${t.note}`);let r=t.model,n=Gm(e.stdoutPath,"a"),o=Gm(e.stderrPath,"a"),s=["ignore",n,o],i=q1(),a=Hi(i),l=J1(),c;try{c=W1(a.executable,Y1(e,r,a.prefixArgs),X({cwd:e.worktreePath,detached:a.detached,shell:a.shell,stdio:s,env:V1(i,a,e.reviewWorker)})),lx(Jm("KYNVER_CURSOR_START_LOCK_HOLD_MS",K1))}finally{l(),Vm(n),Vm(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 z1}from"node:child_process";function qc(e,t=process.env){try{let r;try{r=Hi(e)}catch{r={executable:e,prefixArgs:[]}}let n=z1(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 qm=p(()=>{"use strict";as();is()});import{existsSync as ux}from"node:fs";import{homedir as X1}from"node:os";import Nn from"node:path";import{spawnSync as Q1}from"node:child_process";function Z1(e){if(Nn.isAbsolute(e)||e.includes("/")||e.includes("\\"))return ux(e);try{let t=Q1(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function Yc(e=process.env){let t=[],r=e.KYNVER_CURSOR_AUTH_HOME?.trim();r&&(t.push(Nn.join(r,".config","cursor","auth.json")),t.push(Nn.join(r,".cursor-agent","auth.json")));let n=X1();if(t.push(Nn.join(n,".config","cursor","auth.json")),t.push(Nn.join(n,".cursor-agent","auth.json")),process.platform==="win32"){let o=e.LOCALAPPDATA?.trim(),s=e.APPDATA?.trim();o&&t.push(Nn.join(o,"cursor-agent","auth.json")),s&&t.push(Nn.join(s,"cursor","auth.json"))}return t}function dx(e){return`${e.error}: ${e.detail}`}function Xc(e=process.env){let t=Tn(e);return Z1(t)?e.CURSOR_API_KEY?.trim()?{ok:!0,creds:{agentBin:t,authSource:"api_key_env"}}:Yc(e).find(n=>ux(n))?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:qc(t,e).ok?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:{ok:!1,error:Ym,detail:"Run `agent login` on this computer, or set CURSOR_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:zc,detail:"`agent` CLI not found. Install the Cursor Agent CLI (https://cursor.com/docs/cli/headless) and keep it on PATH."}}var zc,Ym,as=p(()=>{"use strict";is();qm();zc="cursor_cli_unavailable",Ym="cursor_not_logged_in"});import{existsSync as eV}from"node:fs";function px(e=new Date().toISOString()){let t=ct(tV,["KYNVER_CURSOR_AGENT_BIN","CURSOR_AGENT_BIN"]);if(process.env.CURSOR_API_KEY?.trim())return{providerId:"cursor",ready:!1,authSource:"api_key_env",sessionFingerprint:ts("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=Et(t,["-v"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=Yc().find(a=>eV(a)),o=qc(t),s=!!n||o.ok,i=r.ok&&s;return{providerId:"cursor",ready:i,authSource:"oauth_local",sessionFingerprint:n?Lt(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 tV,fx=p(()=>{"use strict";as();qm();Pn();tV="agent"});import{existsSync as rV,readFileSync as nV}from"node:fs";import{homedir as oV}from"node:os";import zm from"node:path";function iV(){let e=process.env.HERMES_HOME?.trim(),t=e?zm.resolve(e):zm.join(oV(),".hermes");return zm.join(t,".env")}function aV(e){try{let t=nV(e,"utf8"),r=[];for(let n of sV)new RegExp(`^${n}=`,"m").test(t)&&r.push(n);return r}catch{return[]}}function mx(e=new Date().toISOString()){let t=ct("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=Et(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=iV(),o=rV(n),s=o?aV(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?Lt(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 sV,gx=p(()=>{"use strict";Pn();sV=["OPENAI_API_KEY","ANTHROPIC_API_KEY","KYNVER_API_KEY","KYNVER_BASE_URL"]});function hx(e={}){let t=e.nowIso?.()??new Date().toISOString(),r=rs(t),n={codex:r,cursor:px(t),claude:tx(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:mx(t),hermesOpenAiCodex:jc(t),codexAdapterPath:r.path,readyCount:o}}var yx=p(()=>{"use strict";rx();Vc();fx();gx();Fm()});function Xm(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function uV(e){let t=Xm(e,"executorRef").toLowerCase(),r=Xm(e,"title").toLowerCase(),n=Xm(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 N1,renameSync as D1}from"node:fs";function M1(e,t){let r=`${e}.quarantine-${t}`;for(let n of["","-wal","-shm"]){let o=`${e}${n}`;N1(o)&&D1(o,`${r}${n}`)}return r}function E_(e){let t=e.quarantineStamp??(e.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),r=null;try{let s=Hi.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=M1(n,t);try{return{store:Hi.open(e),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([r,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}var A_=p(()=>{"use strict";C_()});function L1(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function B1(){return W1.classifyOptions??L1()}function F1(e){qc+=1;try{let t=B1(),r=E_({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:qc},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:qc},failedAtMs:Date.now(),permanentRefusal:t.name==="FilesystemPolicyError"||t.name==="SchemaDowngradeRefusedError"}}}function K1(e,t){return e.store||e.permanentRefusal?!1:e.failedAtMs===null?!0:t-e.failedAtMs>=U1}function ce(e=Date.now()){let t=ut();return(!kr||kr.status.harnessRoot!==t||K1(kr,e))&&(H1(),kr=F1(t)),kr.store}function $1(){return kr?kr.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:qc}}function P_(){return ce(),$1()}function H1(){try{kr?.store?.close()}catch{}kr=null}var W1,U1,kr,qc,Jr=p(()=>{"use strict";Ct();A_();W1={},U1=300*1e3,kr=null,qc=0});import{existsSync as j1,readFileSync as V1}from"node:fs";import{homedir as G1}from"node:os";import J1 from"node:path";function I_(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return J1.join(G1(),".kynver",`local-run-store-flags-${t}.json`)}function Gm(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 O_(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:Gm(r)}function T_(e,t){try{let r=I_(e),n={contractVersion:1,agentOsId:e,flags:Gm(t),deliveredAt:new Date().toISOString()};ke(r,n),It={flags:n.flags,loadedAtMs:Date.now(),file:r}}catch{}}function N_(e=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(It&&e-It.loadedAtMs<q1)return It.flags;try{let t=E().agentOsId?.trim();if(!t)return It={flags:{},loadedAtMs:e,file:null},It.flags;let r=I_(t);if(!j1(r))return It={flags:{},loadedAtMs:e,file:r},It.flags;let n=JSON.parse(V1(r,"utf8")),o=n?.contractVersion===1?Gm(n.flags):{};return It={flags:o,loadedAtMs:e,file:r},o}catch{return It={flags:{},loadedAtMs:e,file:null},It.flags}}var q1,It,Jm=p(()=>{"use strict";j();M();q1=3e4,It=null});function z1(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=N_();for(let s of Y1){let i=e[s.env];if(typeof i=="string"&&i.trim()!==""){let c=z1(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 Y1,is=p(()=>{"use strict";Jm();Y1=[{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 ji(e){return br(process.env).flags[e]}function qm(e){return`mesh-cron-lease:${e}`}function D_(e,t){if(ji("meshLease")==="off")return;let r=ce();if(r)try{let n=r.latestRecoveryCheckpoint(qm(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:qm(e),payloadJson:JSON.stringify(t)})}catch{Ge.meshStoreFailures+=1}}function M_(e,t){let r=ji("meshLease");if(r==="off")return null;let n=ce();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(qm(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&&(Ge.meshLeaseDivergences+=1),r!=="enforce"?null:i&&t?.updatedAt&&s?.updatedAt&&Date.parse(t.updatedAt)>Date.parse(s.updatedAt)?(Ge.meshEnforceStaleInversions+=1,null):s}catch{return Ge.meshStoreFailures+=1,null}}function Yc(e){return`quota-cooldown:${e}`}function B_(e,t){if(ji("quota")==="off")return;let r=ce();if(r)try{r.tryReserveAdmission(Yc(e),L_,t)}catch{Ge.quotaStoreFailures+=1}}function W_(e){if(ji("quota")==="off")return;let t=ce();if(t)try{t.releaseAdmission(Yc(e),L_)}catch{Ge.quotaStoreFailures+=1}}function U_(e,t){let r=ji("quota");if(r==="off")return null;let n=ce();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:Yc(e),limit:50}).find(i=>i.key===Yc(e)),s=!!o;return s!==t&&(Ge.quotaVerdictDivergences+=1),r==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return Ge.quotaStoreFailures+=1,null}}function F_(){return{"keeper.storeFailures":Ge.keeperStoreFailures,"meshLease.storeFailures":Ge.meshStoreFailures,"meshLease.divergences":Ge.meshLeaseDivergences,"meshLease.enforceStaleInversions":Ge.meshEnforceStaleInversions,"quota.storeFailures":Ge.quotaStoreFailures,"quota.verdictDivergences":Ge.quotaVerdictDivergences}}var Ge,Ade,L_,Vi=p(()=>{"use strict";Jr();is();Ge={keeperStoreFailures:0,meshStoreFailures:0,quotaStoreFailures:0,meshLeaseDivergences:0,meshEnforceStaleInversions:0,quotaVerdictDivergences:0};Ade=1800*1e3;L_="quota-preflight"});function Ym(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 Gde,Jde,qde,Yde,zm=p(()=>{"use strict";$r();g_();j();$m();M();Ic();jm();Vi();Gde=15*6e4,Jde=2*6e4,qde=5*6e4,Yde=30*6e4});import X1 from"node:path";function Q1(e){return X1.resolve(De(e.trim()))}function as(e,t,r){let n=e?.trim();return n?{repo:Q1(n),source:t,persistedInConfig:r}:null}function K_(e){return e?{repo:e.repo,source:e.source,persistedInConfig:!1}:null}function Gi(e={}){let t=e.env??process.env,r=e.config??E(),n=as(r.defaultRepo,"config",!0);if(n)return n;let o=as(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(o)return o;let s=as(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return s||K_(Wl({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl}))}function $_(e={}){let t=e.env??process.env,r=e.config??E(),n=as(r.defaultRepo,"config",!0);if(n)return n;let o=as(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(o)return o;let s=as(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return s||K_(Ul({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl,home:e.home}))}function H_(e,t){let r={...t??E(),defaultRepo:De(e),...Yv(e)&&!t?.defaultBase?.trim()?{defaultBase:"main"}:{}};return Be(r),r}function Xm(e){return{defaultRepo:$e(e.repo),source:e.source,persistedInConfig:e.persistedInConfig}}var ls=p(()=>{"use strict";j();fi();it();hf()});import Z1 from"node:path";import{homedir as eV}from"node:os";function j_(e){let t=E(),r=$_({...e,config:t});if(!r)return{ok:!1,remediated:!1,alreadyPersisted:!1,configPath:$e(Qm),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(Qm),resolved:Xm(r),config:om(t)};let n=H_(r.repo,t),o=Xm({...r,persistedInConfig:!0,source:"config"});return{ok:!0,remediated:!0,alreadyPersisted:!1,configPath:$e(Qm),resolved:o,config:om(n),remediation:"defaultRepo persisted in ~/.kynver/config.json \u2014 `kynver run create` no longer requires --repo."}}var Qm,V_=p(()=>{"use strict";it();j();ls();Qm=Z1.join(eV(),".kynver","config.json")});import{mkdirSync as tV,readFileSync as rV,renameSync as nV,writeFileSync as oV}from"node:fs";import{homedir as sV}from"node:os";import G_ from"node:path";function J_(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return G_.join(sV(),".kynver",`instruction-bundle-${t}.json`)}function q_(e,t){try{let r=J_(e);tV(G_.dirname(r),{recursive:!0});let n=`${r}.tmp-${process.pid}`;oV(n,JSON.stringify(t),{encoding:"utf8",mode:384}),nV(n,r)}catch{}}function Y_(e){try{let t=rV(J_(e),"utf8"),r=JSON.parse(t);return Di(r)?r:null}catch{return null}}var z_=p(()=>{"use strict";Hr()});function X_(e,t=process.env){let r=Qo(t.KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY);if(r&&cS(r)===e)return r;if(e===iV&&!Oc(t))return null;let n=aV[e];return n?Qo(n):null}var iV,aV,Q_=p(()=>{"use strict";Hr();iV="ib-3bab6314f0ba",aV={"ib-3bab6314f0ba":"53a2040646cd479e1f5f1aea9abf7848ce8b62e32001efb8044dfd90e8ab87ed","ib-26e6c695da06":"bb1700f25b2ee7d7cdcdb9f446f0f44ef2cc22a3096bc161232fb658e7cdaf38","ib-49e76cb8052c":"8fc646b5c4f8f402120477452608398f035c3cddd2e7aa8bb328e97b84dcf6d8"}});import{createPublicKey as lV,verify as cV}from"node:crypto";function dV(e){return lV({key:Buffer.concat([uV,Buffer.from(e)]),format:"der",type:"spki"})}function pV(e,t){if(!Di(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(rt(e.bundle),"utf8");return cV(null,n,dV(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 Z_(e,t=process.env){if(!Di(e))return{ok:!1,reason:"malformed signed bundle payload"};let r=X_(e.publicKeyId,t);return r?pV(e,r):{ok:!1,reason:`no verification key for publicKeyId "${e.publicKeyId}" (not pinned; set KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY)`}}var uV,ex=p(()=>{"use strict";Q_();Hr();uV=Buffer.from("302a300506032b6570032100","hex")});function qi(e,t){console.error(JSON.stringify({event:e,...t}))}function tx(e,t,r){let n=Z_(e);return n.ok?(d_(n.bundle,t),t==="server"&&q_(r,e),!0):(qi("instruction_bundle_signature_invalid",{agentOsId:r,source:t,publicKeyId:e.publicKeyId,reason:n.reason}),!1)}function Ji(e){if(vr.diskCacheTried)return!1;vr.diskCacheTried=!0;let t=Y_(e);return t?tx(t,"disk",e):!1}async function rx(e){let t=e.nowMs??Date.now(),r=()=>({source:Wt(),version:Dn(),updated:!1});if(!e.force&&t-vr.lastAttemptAtMs<fV)return r();vr.lastAttemptAtMs=t;let n=e.baseUrl?.trim().replace(/\/$/,""),o=e.secret?.trim();if(!n||!o)return Wt()==="embedded"&&Ji(e.agentOsId)?{...r(),updated:!0}:r();let s=e.fetchImpl??fetch,i=new AbortController,a=setTimeout(()=>i.abort(),mV);try{let l=Pt(o);delete l["Content-Type"],vr.etag&&Wt()==="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,qi("instruction_bundle_route_missing",{agentOsId:e.agentOsId,baseUrl:n})),Wt()==="embedded"&&Ji(e.agentOsId)?{...r(),updated:!0}:r();if(!c.ok)return qi("instruction_bundle_fetch_failed",{agentOsId:e.agentOsId,status:c.status}),Wt()==="embedded"&&Ji(e.agentOsId)?{...r(),updated:!0}:r();let u=await c.json().catch(()=>null);return!u||!tx(u,"server",e.agentOsId)?Wt()==="embedded"&&Ji(e.agentOsId)?{...r(),updated:!0}:r():(vr.etag=c.headers.get("etag"),qi("instruction_bundle_loaded",{agentOsId:e.agentOsId,version:Dn(),publicKeyId:u.publicKeyId}),{...r(),updated:!0})}catch(l){return qi("instruction_bundle_fetch_error",{agentOsId:e.agentOsId,error:l instanceof Error?l.message:String(l)}),Wt()==="embedded"&&Ji(e.agentOsId)?{...r(),updated:!0}:r()}finally{clearTimeout(a)}}var fV,mV,vr,nx=p(()=>{"use strict";ss();z_();Gr();ex();fV=15*6e4,mV=1e4,vr={lastAttemptAtMs:0,etag:null,diskCacheTried:!1,routeMissingLogged:!1}});import gV from"node:os";function ox(e,t){console.error(JSON.stringify({event:"daemon_identity",level:e,message:t}))}function sx(e=E(),t=process.env){let r=Ze(t,e),n=Uo({config:e,totalMemBytes:gV.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);gi(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)ox("warn",c);for(let c of s)ox("error",c);return{ok:l,box:r,workerCapSource:n.workerCapSource,maxConcurrentWorkers:a,autoCap:n.autoCap,warnings:o,errors:s}}var ix=p(()=>{"use strict";j();Me();Ao();xi()});import{spawnSync as hV}from"node:child_process";import{existsSync as yV,readFileSync as kV}from"node:fs";import bV from"node:path";function RV(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+vV<s.startedAtMs||o.push({workerName:s.workerName,workerPid:s.pid,orphanPid:i.pid}));return o}function wV(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 SV(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=hV("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:3e4});if(o.status!==0)return[];try{return wV(o.stdout??"")}catch{return[]}}function _V(e,t=te){try{let r=we().find(o=>o.id===e);if(!r)return[];let n=[];for(let o of Object.keys(r.workers||{})){let s=bV.join(V(r.id),"workers",B(o),"worker.json");if(!yV(s))continue;let i=JSON.parse(kV(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 ax(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return{checkedWorkers:0,killed:[]};let n=t.isAlive??te,o=(t.collect??(l=>_V(l,n)))(e);if(o.length===0)return{checkedWorkers:0,killed:[]};let s=(t.query??SV)(o.map(l=>l.pid)),i=t.killTree??ye,a=RV(s,o,n).map(l=>({...l,result:i(l.orphanPid,"SIGKILL")}));return{checkedWorkers:o.length,killed:a}}var vV,lx=p(()=>{"use strict";Y();M();li();vV=5e3});import{mkdirSync as xV,readFileSync as CV,renameSync as EV,writeFileSync as AV}from"node:fs";import{homedir as PV}from"node:os";import zc from"node:path";function cx(){return zc.join(PV(),".kynver")}function IV(e=cx()){return zc.join(e,"doctor-native-windows.json")}function ux(e=cx()){return zc.join(e,"native-windows-state.json")}function OV(e,t){xV(zc.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;AV(r,`${JSON.stringify(t,null,2)}
|
|
143
|
+
`,{mode:384}),EV(r,e)}function eg(e){try{return JSON.parse(CV(e,"utf8"))}catch{return null}}function TV(e){let t=eg(IV(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 dx(e=new Date,t){try{let r=ux(t),n=eg(r)??{};OV(r,{...n,lastWorkerCompletedAt:e.toISOString()})}catch{}}function NV(e){let t=eg(ux(e));return typeof t?.lastWorkerCompletedAt=="string"?t.lastWorkerCompletedAt:null}function fx(e){Zm=e.admission,px=e.ownerKind}function mx(e={}){let t=e.platform??process.platform,r=e.hostKind??Hf(),n=r==="win32";return{hostKind:r,wsl:r==="wsl",platform:t,arch:process.arch,nodeVersion:process.versions.node,runtimeVersion:Ve,ownerKind:px,nativeWindows:n?{admission:Zm?.basis??null,hostCapability:Zm?.hostCapability??null,lastDoctor:TV(e.root),lastWorkerCompletedAt:NV(e.root)}:null}}var Zm,px,Xc=p(()=>{"use strict";pc();Vr();Zm=null,px=null});function DV(e){return typeof e=="string"&&gx.includes(e)}function MV(e,t){let r=e[t]?.trim().toLowerCase();return r==="1"||r==="true"||r==="yes"||r==="on"}function BV(e={}){let t=e.platform??process.platform,r=e.env??process.env;return e.hostCapability!==void 0&&!DV(e.hostCapability)?{allowed:!1,reason:"invalid_host_capability",remedy:"hostCapability must be one of: "+gx.join(", ")}:t!=="win32"?{allowed:!0,basis:"not_native_windows",hostCapability:e.hostCapability??null}:e.hostCapability?{allowed:!0,basis:"host_capability",hostCapability:e.hostCapability}:MV(r,tg)?{allowed:!0,basis:"experimental_env_override",hostCapability:null}:{allowed:!1,reason:"native_windows_unqualified",remedy:LV}}function rg(e={}){let t=BV(e);return t.allowed?(t.basis==="experimental_env_override"&&console.error(JSON.stringify({event:"daemon_native_windows_experimental",override:tg,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 gx,tg,LV,ng=p(()=>{"use strict";gx=["desktop-supervised","native-windows-qualified"],tg="KYNVER_DAEMON_ALLOW_NATIVE_WINDOWS";LV=`Run the daemon inside WSL: .\\scripts\\start-tier2-wsl.ps1 \u2014 or set ${tg}=1 for the experimental native path (not yet qualified; \`kynver doctor runner-install\` reports the host).`});function WV(e){return e.replace(/\/+$/,"")}async function hx(e){let t=e.fetchFn??fetch,r=e.entry.spec.callbackPath.startsWith("/")?e.entry.spec.callbackPath:`/${e.entry.spec.callbackPath}`,n=`${WV(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:Pt(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 yx=p(()=>{"use strict";ss()});import{closeSync as UV,existsSync as og,openSync as FV,readFileSync as KV,unlinkSync as kx,writeFileSync as $V}from"node:fs";function bx(e){if(!og(e))return null;try{let t=JSON.parse(KV(e,"utf8"));if(typeof t.pid=="number"&&typeof t.at=="string")return t}catch{return null}return null}function jV(e){let t=bx(e);if(!t||!te(t.pid))return!0;let r=Date.parse(t.at);return Number.isNaN(r)?!0:Date.now()-r>HV}function vx(e){if(og(e)&&!jV(e)){let t=bx(e);return{acquired:!1,reason:t?`held by pid ${t.pid}`:"held by another process"}}if(og(e))try{kx(e)}catch{}try{let t=FV(e,"wx");return $V(t,JSON.stringify({pid:process.pid,at:new Date().toISOString()}),"utf8"),UV(t),{acquired:!0}}catch(t){if(t.code==="EEXIST")return{acquired:!1,reason:"concurrent acquire"};throw t}}function Rx(e){try{kx(e)}catch{}}var HV,wx=p(()=>{"use strict";M();HV=10*6e4});function GV(e){return VV.test(e.trim())}function JV(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 Yi(e,t,r,n){let o=e.trim();return o==="*"?!0:JV(o,r,n).has(t)}function qV(e,t){let r=e.trim().split(/\s+/);if(r.length!==5)return!1;let[n,o,s,i,a]=r;return Yi(n,t.getUTCMinutes(),0,59)&&Yi(o,t.getUTCHours(),0,23)&&Yi(s,t.getUTCDate(),1,31)&&Yi(i,t.getUTCMonth()+1,1,12)&&Yi(a,t.getUTCDay(),0,6)}function zV(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),0,0))}function Sx(e,t){if(!GV(e))return null;let r=zV(t);r=new Date(r.getTime()+6e4);for(let n=0;n<YV;n++){if(qV(e,r))return r;r=new Date(r.getTime()+6e4)}return null}function _x(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=Sx(e.cron.trim(),t);return r?r.toISOString():null}return null}function sg(e,t){if(e.scheduleKind!=="cron"||!e.cron?.trim())return null;let r=Sx(e.cron.trim(),t);return r?r.toISOString():null}var VV,YV,xx=p(()=>{"use strict";VV=/^[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+$/;YV=366*24*60});import{randomBytes as XV}from"node:crypto";import{promises as zi}from"node:fs";import QV from"node:path";async function ZV(e){try{return await zi.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function eG(e){if(!e)return{...Qc,jobs:{...Qc.jobs}};try{let t=JSON.parse(e);return t?.version!==1||typeof t.jobs!="object"||!t.jobs?{...Qc,jobs:{}}:t}catch{return{...Qc,jobs:{}}}}async function ig(e){let t=await ZV(e);return eG(t)}async function tG(e,t){await zi.mkdir(QV.dirname(e),{recursive:!0});let r=XV(6).toString("hex"),n=`${e}.tmp-${process.pid}-${Date.now()}-${r}`;await zi.writeFile(n,`${JSON.stringify(t,null,2)}
|
|
144
|
+
`,"utf8");try{await zi.rename(n,e)}catch(o){let s=o.code;if(s!=="EPERM"&&s!=="EEXIST"&&s!=="EACCES")throw o;await zi.unlink(n).catch(()=>{})}}async function Cx(e,t){await tG(e,t)}function Ex(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 Qc,ag=p(()=>{"use strict";Qc={version:1,jobs:{}}});function rG(e,t){if(!e.inflightUntil)return!1;let r=Date.parse(e.inflightUntil);return!Number.isNaN(r)&&r>t}function nG(e){return!!e.completedAt}function oG(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 sG(e,t,r){if(t.nextFireAt)return t.nextFireAt;let n=_x(e.spec,r);return t.nextFireAt=n,n}function iG(e,t,r,n){if(e.paused||nG(t)||rG(t,r)||!oG(e,t,n,r))return!1;let o=t.nextFireAt?Date.parse(t.nextFireAt):NaN;return Number.isNaN(o)?!1:r>=o}function aG(e,t,r){e.spec.scheduleKind==="cron"&&(t.nextFireAt=sg(e.spec,r))}async function lg(e={}){let t=e.env??es(),r=e.now??new Date,n=r.getTime(),o=e.agentOsIdFilter?Ie(e.agentOsIdFilter):Ie();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=vx(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 $c(t.storePath),a=e.agentOsIdFilter?i.filter(h=>h.spec.target.agentOsId===e.agentOsIdFilter):i,l=await ig(t.statePath),c=[];for(let h of a){let y=Ex(l,h.providerScheduleId);sG(h,y,r),iG(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=sg(h.spec,r),f++;continue}}if(m<=0){f++;continue}y.inflightUntil=new Date(n+t.inflightLeaseMs).toISOString(),y.lastAttemptAt=r.toISOString(),aG(h,y,r);try{let v=Ie(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 hx({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 Cx(t.statePath,l),{enabled:!0,scanned:a.length,due:c.length,fired:u,skippedJobs:f,errors:d,...g.length?{errorDetails:g}:{}}}finally{Rx(t.lockPath)}}var cg=p(()=>{"use strict";gr();yx();wx();j();xx();ts();ag()});import Ax from"node:path";function Zc(e){let t=K(Ax.join(V(e),Px),null);return M_(e,t)??t}function Ix(e,t){let r={...t,updatedAt:new Date().toISOString()};ke(Ax.join(V(e),Px),r),D_(e,r)}function Ox(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 Px,ug=p(()=>{"use strict";M();Y();Vi();Px="mesh-cron-lease.json"});function Dx(e){Xi=e}function Mx(e=Date.now()){return!Xi||Xi.stallCount===Tx&&e-Nx<9e5?null:(Tx=Xi.stallCount,Nx=e,Xi)}var Xi,Tx,Nx,dg=p(()=>{"use strict";Xi=null,Tx=-1,Nx=0});function Bx(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 Lx(e){return new Error(`callback timeout after ${e}ms`)}async function Wx(e,t){let r=Bx(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(Lx(r))},r)})])}catch(i){throw s?Lx(r):i}finally{o&&clearTimeout(o)}}function Ux(e,t){let r=Bx(t);return{ok:!1,status:0,response:{error:e instanceof Error?e.message:String(e),timeoutMs:r}}}async function Mn(e,t,r,n){try{return await Wx(async o=>{let s=await ct(e,{method:"POST",headers:Pt(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 Ux(o,n?.timeoutMs)}}async function de(e,t,r,n){let o=await Mn(e,t,r,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await nS(t,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await Mn(e,s.token,r,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function pg(e,t,r){try{return await Wx(async n=>{let o=await ct(e,{method:"GET",headers:Pt(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 Ux(n,r?.timeoutMs)}}var Ue=p(()=>{"use strict";ss();sr();j()});function Fx(){let e=Number(process.env.KYNVER_DISPATCH_CALLBACK_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):3e5}var Kx=p(()=>{"use strict"});function Qi(e){console.error(JSON.stringify({event:"dispatch_progress",ts:new Date().toISOString(),...e}))}function $x(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 fg(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 Hx=p(()=>{"use strict"});function uG(e){return lG.includes(e)}function dG(e){return cG.includes(e)}function jx(e){return{slug:e.slug,displayName:e.displayName,description:e.description,dispatchLane:e.dispatchLane===null||uG(e.dispatchLane)?e.dispatchLane:null,defaultRoleLane:dG(e.defaultRoleLane)?e.defaultRoleLane:"implementer"}}function fG(e){if(!e)return null;let t=e.trim().toLowerCase(),r=pG.get(t)??null,n=p_(t);if(!n)return r;let o=jx(n);return r?{...o,dispatchLane:r.dispatchLane,defaultRoleLane:r.defaultRoleLane}:o}function mg(e){return fG(e)?.defaultRoleLane??null}function Gx(){return Vx.filter(e=>e.dispatchLane==="review").map(e=>e.slug)}var lG,cG,Vx,pG,eu=p(()=>{"use strict";Wm();Gr();lG=["implementation","review","landing"],cG=["plan_author","implementer","report_reviewer","deep_reviewer","runtime_verifier","system"];Vx=rs.personas.map(jx),pG=new Map(Vx.map(e=>[e.slug,e]))});function Jx(e){return(e??"").trim().toLowerCase()}function mG(e){switch(Jx(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 gG(e){let t=Jx(e);if(!t)return;if(t==="implementation"||t==="review"||t==="landing"||t==="any")return t;let r=mG(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 gG(e)??"any"}var Yx=p(()=>{"use strict";eu()});function hG(e=process.env){let t=E();return _t(t,e)!=="forge"}function tu(e,t=process.env){if(hG(t))return e?.maxConcurrentWorkers??void 0}async function ru(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 pg(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 gg=p(()=>{"use strict";Ue();j();Me()});async function zx(e,t=yG){let r=await t.fetchPreferences(e.agentOsId,e.args),n=t.configuredOverride(r,e.env);return t.observe({runId:e.runId,configuredMaxWorkersOverride:n})}var yG,Xx=p(()=>{"use strict";gg();Wo();yG={fetchPreferences:ru,configuredOverride:tu,observe:_i}});function nu(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function hg(e){return e.toLowerCase()}function kG(e){let t=nu(e,"roleLane");if(t)return t;let r=hg(nu(e,"executorRef")),n=hg(nu(e,"title")),o=hg(nu(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=mg(o);if(i)return o==="lorentz"&&(s.includes("deep")||s.includes("security"))?"deep_reviewer":i;if(s.includes("review"))return"report_reviewer"}function Qx(e){let t=kG(e);return t?{...e,roleLane:t}:e}var Zx=p(()=>{"use strict";eu()});function eC(e){let t=e.trim();return bG.test(t)||vG.test(t)}function tC(e){let t=e.trim().toLowerCase();return t.startsWith("gpt-")||t.startsWith("gpt5")||t.includes("codex")}function yg(e){let t=e.trim().toLowerCase();return t.includes("composer")||t.includes("cursor")}function rC(e){return e.trim().toLowerCase().startsWith("gemini-")}function RG(e){return tC(e)?"codex":eC(e)?"claude":rC(e)?"gemini":(yg(e),"cursor")}function wG(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 SG(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?eC(n)||tC(n)||yg(n)||rC(n)?{lane:r,model:n,provider:RG(n),rule:"executor_ref:harness_lane_model"}:{lane:r,rule:"executor_ref:harness_lane"}:{lane:r,rule:"executor_ref:harness_lane"}}function pt(e){let t=typeof e=="string"?e.trim():"";return t?wG(t)??SG(t):null}function nC(e){let t=pt(e);return t?!!(t.provider&&t.provider!=="cursor"||t.model&&!yg(t.model)):!1}var bG,vG,ou=p(()=>{"use strict";bG=/^claude[-_]/i,vG=/^(?:opus|sonnet|haiku)\b/i});function Zi(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 _G.has(t)?!0:t.includes("claude")||t.includes("opus")}function su(e){if(!e)return!1;let t=e.workerProviderOverride;if(typeof t=="string"&&Rr(t))return!0;let r=Zi(e,"executorRef").toLowerCase();if(r==="provider:claude"||r.startsWith("provider:claude:")||r.includes("claude-worker-override")||r.includes("operator-claude"))return!0;let n=pt(Zi(e,"executorRef"));if(n?.provider&&Rr(n.provider)||n?.model&&Rr(CG(n.model)))return!0;let o=Zi(e,"description");if(xG.some(i=>i.test(o)))return!0;let s=Zi(e,"title");return!!/\[use-claude-worker\]/i.test(s)}function CG(e){let t=e.trim().toLowerCase();return/^claude[-_]/.test(t)||/^(?:opus|sonnet|haiku)\b/.test(t)?"claude":t}function EG(e,t){return{provider:wr,model:iu,rule:`policy:cursor_default${t}`,requestedModel:e}}function PG(e){return AG.some(t=>e.startsWith(t))}function kg(e){if(!e)return!1;let t=e.workerProviderOverride;return typeof t=="string"&&t.trim()||pt(Zi(e,"executorRef"))?.provider?!0:su(e)}function oC(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||PG(t.rule)||kg(r)||!Rr(t.provider))return t;let o=t.rule&&t.rule!=="default:global"?`:${t.rule.replace(/:/g,"_")}`:"";return EG(t.model,o)}function sC(e,t=wr){let r=e?.trim();return r?He(r):t}var wr,_G,xG,AG,Ln=p(()=>{"use strict";ou();au();Ii();Ii();wr="cursor",_G=new Set(["claude","opus","anthropic"]),xG=[/\[worker-provider:\s*claude\]/i,/\[use-claude-worker\]/i,/\[operator-worker-provider:\s*claude\]/i];AG=["explicit:","executor_ref:","factory:","task:"]});function cs(e){return iC[e]}function aC(){return Object.values(iC)}var iC,bg=p(()=>{"use strict";iC={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 uC,readFileSync as IG}from"node:fs";import Bn from"node:path";function TG(e){return e.includes("/")||e.includes("\\")}function NG(e){return(e.PATHEXT||OG).split(";").map(t=>t.trim().toLowerCase()).filter(t=>t.startsWith("."))}function DG(e){let t=Object.keys(e).find(r=>r.toUpperCase()==="PATH");return t?e[t]??"":""}function MG(e,t={}){let r=t.env??process.env,n=t.exists??uC,o=NG(r),s=Bn.win32.extname(e)!=="",i=a=>s?[a]:o.map(l=>`${a}${l}`);if(TG(e)||Bn.win32.isAbsolute(e))return i(e).find(a=>n(a))??null;for(let a of DG(r).split(";").map(l=>l.trim()).filter(Boolean)){let l=i(Bn.win32.join(a,e)).find(c=>n(c));if(l)return l}return null}function cC(e){return e.replace(/^[\\/]+/,"")}function BG(e){let t=e.split(/\r?\n/),r=new Map;for(let s of t){let i=LG.exec(s);i&&r.set(i[1].toUpperCase(),i[2])}let n=t.filter(s=>s.includes("%*")).pop();if(!n)return null;let o=lC.exec(n);if(o)return cC(o[1]);for(let s of n.matchAll(/%([A-Za-z_]\w*)%/g)){let i=r.get(s[1].toUpperCase()),a=i?lC.exec(i):null;if(a)return cC(a[1])}return null}function WG(e,t={}){if((t.platform??process.platform)!=="win32")return{executable:e,prefixArgs:[],kind:"passthrough"};let n=MG(e,t);if(!n)return{executable:e,prefixArgs:[],kind:"passthrough"};let o=Bn.win32.extname(n).toLowerCase();if(o!==".cmd"&&o!==".bat")return{executable:n,prefixArgs:[],kind:"exe"};let s=t.readText??(m=>IG(m,"utf8")),i=t.exists??uC,a;try{a=s(n)}catch{throw new ea(n)}let l=BG(a);if(!l)throw new ea(n);let c=Bn.win32.dirname(n),u=Bn.win32.join(c,l);if(!i(u))throw new ea(n);let d=Bn.win32.join(c,"node.exe");return{executable:i(d)?d:t.nodeExecutable??process.execPath,prefixArgs:[u],kind:"node-shim"}}function ie(e,t,r={}){let n=WG(e,r);return[n.executable,[...n.prefixArgs,...t]]}var ea,OG,lC,LG,Je=p(()=>{"use strict";ea=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},OG=".COM;.EXE;.BAT;.CMD";lC=/%~?dp0%?\\?([^"%\r\n]+?\.(?:c|m)?js)\b/i,LG=/^\s*SET\s+"?([A-Za-z_]\w*)=([^"\r\n]*)"?\s*$/i});import{createHash as dC}from"node:crypto";import{statSync as UG}from"node:fs";import{spawnSync as pC}from"node:child_process";function Ut(e){try{let t=UG(e),r=`${e}|${t.size}|${t.mtimeMs}`;return dC("sha256").update(r).digest("hex").slice(0,16)}catch{return}}function us(e){return dC("sha256").update(`env:${e}`).digest("hex").slice(0,16)}function ft(e,t){for(let r of t){let n=process.env[r]?.trim();if(n)return n}return e}function Ot(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=ie(e,t),i=pC(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 lu(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=ie(e,t);return pC(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 Wn=p(()=>{"use strict";Je()});import{existsSync as FG}from"node:fs";import{homedir as KG}from"node:os";import ta from"node:path";function HG(){let e=KG();return[process.env.CODEX_HOME?.trim()?ta.join(ta.resolve(process.env.CODEX_HOME.trim()),"auth.json"):null,ta.join(e,".codex","auth.json"),ta.join(e,".config","codex","auth.json")].filter(r=>!!r)}function jG(e){return ta.dirname(e)}function VG(e){let t,r;for(let n of HG()){if(!FG(n))continue;t??=n;let o=Ot(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status",env:{CODEX_HOME:jG(n)}});if(r??=o,o.ok)return{authPath:n,login:o}}return{authPath:t,login:r??Ot(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status"})}}function fC(e=new Date().toISOString()){let t=ft($G,["KYNVER_CODEX_BIN","CODEX_BIN"]);if(process.env.CODEX_API_KEY?.trim())return{providerId:"codex",ready:!0,authSource:"api_key_env",sessionFingerprint:us("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}=VG(t),o=!!r&&n.ok;return{providerId:"codex",ready:o,authSource:"oauth_local",sessionFingerprint:r?Ut(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 $G,mC=p(()=>{"use strict";Wn();$G="codex"});import{existsSync as GG}from"node:fs";import{homedir as JG}from"node:os";import vg from"node:path";function qG(){let e=process.env.HERMES_HOME?.trim(),t=e?vg.resolve(e):vg.join(JG(),".hermes");return vg.join(t,"auth.json")}function cu(e=new Date().toISOString()){let t=ft("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=Ot(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=qG(),o=GG(n),s=lu(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?Ut(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 Rg=p(()=>{"use strict";Wn()});function ds(e=new Date().toISOString()){let t=fC(e);if(t.ready)return{...t,path:"codex_cli"};let r=cu(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 uu=p(()=>{"use strict";mC();Rg()});function yC(e,t){let r=cs(e);return t==="privileged"?r.supportsPrivilegedPlatformActions:t==="low"?r.supportsLowRiskOrchestration:!0}function YG(e,t){let r=cs(e.providerId),n=cs(t.providerId),o=gC.indexOf(r.costTier)-gC.indexOf(n.costTier);if(o!==0)return o;let s=hC[e.binding.authSource]-hC[t.binding.authSource];return s!==0?s:e.providerId.localeCompare(t.providerId)}function wg(e){let t=aC().map(a=>({providerId:a.id,binding:e.inventory.bindings[a.id]})).filter(a=>a.binding.ready&&yC(a.providerId,e.riskClass));if(t.length===0)return null;let n=[...t].sort(YG)[0],o="codex";if(n.providerId===o)return{providerId:n.providerId,binding:n.binding};let s=e.inventory.bindings[o],i;return yC(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 gC,hC,kC=p(()=>{"use strict";bg();gC=["low","medium","high"],hC={oauth_local:0,subscription_hermes:0,runner_token:1,api_key_env:2,none:3}});import{existsSync as zG}from"node:fs";import{homedir as XG}from"node:os";import QG from"node:path";function eJ(){let e=XG();return[QG.join(e,".claude",".credentials.json")]}function bC(e=new Date().toISOString()){let t=ft(ZG,["KYNVER_CLAUDE_BIN","CLAUDE_BIN"]);if(process.env.ANTHROPIC_API_KEY?.trim())return{providerId:"claude",ready:!1,authSource:"api_key_env",sessionFingerprint:us("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=Ot(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=eJ().find(i=>zG(i)),o=lu(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?Ut(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 ZG,vC=p(()=>{"use strict";Wn();ZG="claude"});function mt(e,t={}){let r=ui(e);if(!t.reviewWorker)return r;let n={...r,[tJ]:"1"};for(let o of rJ)delete n[o];return n}var tJ,rJ,Un=p(()=>{"use strict";di();tJ="KYNVER_NO_PROD_DB_CREDENTIALS",rJ=["KYNVER_ENV_FILE"]});function RC(e){return e.replace(nJ,"")}function du(e){return/^claude[-_]/i.test(e)||/^(?:opus|sonnet|haiku)\b/i.test(e)}function oJ(e){let t=e.trim().toLowerCase();return t.startsWith("gemini-")||t==="auto"||t==="pro"||t==="flash"||t==="flash-lite"}function iJ(e){let t=e.trim().toLowerCase();return sJ.has(t)?"auto":null}function Sg(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=RC(r).trim()||t;return wC.test(o)||!du(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 ps(e,t){let r=(e??"").trim();return r?du(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 _g(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 fs(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=RC(r).trim()||t;return du(o)||!oJ(o)&&wC.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 ms(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let n=iJ(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")`}:du(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 nJ,wC,sJ,Ft=p(()=>{"use strict";nJ=/-(?:thinking(?:-(?:high|medium|low|minimal|max|none))?|high|medium|low|minimal)$/i;wC=/^(?:gpt-|gpt5|o1|o3|o4|gemini-|grok-|composer|deepseek|llama|mistral|qwen|command-)/i;sJ=new Set(["cursor"])});import{existsSync as ra,readdirSync as aJ}from"node:fs";import Fn from"node:path";function cJ(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 uJ(e){let t=Fn.join(e,"versions");if(!ra(t))return null;let r=null,n=-1;for(let o of aJ(t,{withFileTypes:!0})){if(!o.isDirectory()||!lJ.test(o.name))continue;let s=cJ(o.name);s==null||s<=n||(n=s,r=Fn.join(t,o.name))}return r}function pu(e){let t=e?.trim()||Fn.join(process.env.LOCALAPPDATA||"","cursor-agent"),r=Fn.join(t,"node.exe"),n=Fn.join(t,"index.js");if(ra(r)&&ra(n))return{nodeExe:r,indexJs:n,versionDir:t};let o=uJ(t);if(!o)return null;let s=Fn.join(o,"node.exe"),i=Fn.join(o,"index.js");return!ra(s)||!ra(i)?null:{nodeExe:s,indexJs:i,versionDir:o}}var lJ,SC=p(()=>{"use strict";lJ=/^\d{4}\.\d{1,2}\.\d{1,2}-[a-f0-9]+$/i});import{closeSync as Cg,existsSync as CC,mkdirSync as dJ,openSync as Eg,statSync as pJ,unlinkSync as _C}from"node:fs";import{spawn as fJ}from"node:child_process";import mJ from"node:os";import Kt from"node:path";function kJ(e,t,r){return{executable:e,prefixArgs:[t],shell:!1,detached:ve(),bundledVersionDir:r}}function na(e){if(process.platform==="win32"){let t=/\.(cmd|bat)$/i.test(e),r=/node\.exe$/i.test(e)&&CC(Kt.join(Kt.dirname(e),"index.js"));if(t||r||e==="agent"){let o=t?pu(Kt.dirname(e)):r?{nodeExe:e,indexJs:Kt.join(Kt.dirname(e),"index.js"),versionDir:Kt.dirname(e)}:pu();if(o)return kJ(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:ve()}}function bJ(e,t,r){return mt({...process.env,CI:"1",NO_COLOR:"1",...t.bundledVersionDir?{CURSOR_INVOKED_AS:Kt.basename(e)||"agent.cmd"}:{}},{reviewWorker:r})}function EC(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Ag(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 vJ(){let e=process.env.KYNVER_CURSOR_START_LOCK_DIR?.trim()||Kt.join(mJ.homedir(),".kynver","locks");return dJ(e,{recursive:!0}),Kt.join(e,"cursor-agent-start.lock")}function RJ(){if(process.env.KYNVER_CURSOR_START_LOCK==="0")return()=>{};let e=vJ(),t=Ag("KYNVER_CURSOR_START_LOCK_TIMEOUT_MS",hJ),r=Ag("KYNVER_CURSOR_START_LOCK_STALE_MS",yJ),n=Date.now();for(;;)try{let o=Eg(e,"wx");return Cg(o),()=>{try{_C(e)}catch{}}}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-pJ(e).mtimeMs>r){_C(e);continue}}catch{continue}if(Date.now()-n>t)throw new Error(`timed out waiting for Cursor agent start lock: ${e}`);EC(250)}}function Kn(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=pu(e.KYNVER_CURSOR_AGENT_ROOT?.trim()||void 0);if(r)return r.nodeExe;let n=Kt.join(e.LOCALAPPDATA||"","cursor-agent","agent.cmd");if(CC(n))return n}return"agent"}function wJ(){return Kn(process.env)}function xC(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 xg,gJ,hJ,yJ,AC,gs=p(()=>{"use strict";lr();M();Un();Ft();SC();xg="composer-2.5",gJ=15e3,hJ=6e4,yJ=3e4;AC={name:"cursor",defaultModel:xg,preflightModel(e){return ms(e,xg)},start(e){let t=ms(e.model,xg);if(!t.ok)throw new Error(`cursor provider model preflight failed: ${t.note}`);let r=t.model,n=Eg(e.stdoutPath,"a"),o=Eg(e.stderrPath,"a"),s=["ignore",n,o],i=wJ(),a=na(i),l=RJ(),c;try{let[u,d]=a.shell?[a.executable,xC(e,r,a.prefixArgs)]:et(a.executable,xC(e,r,a.prefixArgs),e.workerDir);c=fJ(u,d,z({cwd:e.worktreePath,detached:a.detached,shell:a.shell,stdio:s,env:bJ(i,a,e.reviewWorker)})),EC(Ag("KYNVER_CURSOR_START_LOCK_HOLD_MS",gJ))}finally{l(),Cg(n),Cg(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 SJ}from"node:child_process";function fu(e,t=process.env){try{let r;try{r=na(e)}catch{r={executable:e,prefixArgs:[]}}let n=SJ(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 Pg=p(()=>{"use strict";hs();gs()});import{existsSync as PC}from"node:fs";import{homedir as _J}from"node:os";import $n from"node:path";import{spawnSync as xJ}from"node:child_process";function CJ(e){if($n.isAbsolute(e)||e.includes("/")||e.includes("\\"))return PC(e);try{let t=xJ(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function mu(e=process.env){let t=[],r=e.KYNVER_CURSOR_AUTH_HOME?.trim();r&&(t.push($n.join(r,".config","cursor","auth.json")),t.push($n.join(r,".cursor-agent","auth.json")));let n=_J();if(t.push($n.join(n,".config","cursor","auth.json")),t.push($n.join(n,".cursor-agent","auth.json")),process.platform==="win32"){let o=e.LOCALAPPDATA?.trim(),s=e.APPDATA?.trim();o&&t.push($n.join(o,"cursor-agent","auth.json")),s&&t.push($n.join(s,"cursor","auth.json"))}return t}function IC(e){return`${e.error}: ${e.detail}`}function hu(e=process.env){let t=Kn(e);return CJ(t)?e.CURSOR_API_KEY?.trim()?{ok:!0,creds:{agentBin:t,authSource:"api_key_env"}}:mu(e).find(n=>PC(n))?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:fu(t,e).ok?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:{ok:!1,error:Ig,detail:"Run `agent login` on this computer, or set CURSOR_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:gu,detail:"`agent` CLI not found. Install the Cursor Agent CLI (https://cursor.com/docs/cli/headless) and keep it on PATH."}}var gu,Ig,hs=p(()=>{"use strict";gs();Pg();gu="cursor_cli_unavailable",Ig="cursor_not_logged_in"});import{existsSync as EJ}from"node:fs";function OC(e=new Date().toISOString()){let t=ft(AJ,["KYNVER_CURSOR_AGENT_BIN","CURSOR_AGENT_BIN"]);if(process.env.CURSOR_API_KEY?.trim())return{providerId:"cursor",ready:!1,authSource:"api_key_env",sessionFingerprint:us("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=Ot(t,["-v"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=mu().find(a=>EJ(a)),o=fu(t),s=!!n||o.ok,i=r.ok&&s;return{providerId:"cursor",ready:i,authSource:"oauth_local",sessionFingerprint:n?Ut(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 AJ,TC=p(()=>{"use strict";hs();Pg();Wn();AJ="agent"});import{existsSync as PJ,readFileSync as IJ}from"node:fs";import{homedir as OJ}from"node:os";import Og from"node:path";function NJ(){let e=process.env.HERMES_HOME?.trim(),t=e?Og.resolve(e):Og.join(OJ(),".hermes");return Og.join(t,".env")}function DJ(e){try{let t=IJ(e,"utf8"),r=[];for(let n of TJ)new RegExp(`^${n}=`,"m").test(t)&&r.push(n);return r}catch{return[]}}function NC(e=new Date().toISOString()){let t=ft("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=Ot(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=NJ(),o=PJ(n),s=o?DJ(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?Ut(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 TJ,DC=p(()=>{"use strict";Wn();TJ=["OPENAI_API_KEY","ANTHROPIC_API_KEY","KYNVER_API_KEY","KYNVER_BASE_URL"]});function MC(e={}){let t=e.nowIso?.()??new Date().toISOString(),r=ds(t),n={codex:r,cursor:OC(t),claude:bC(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:NC(t),hermesOpenAiCodex:cu(t),codexAdapterPath:r.path,readyCount:o}}var LC=p(()=>{"use strict";vC();uu();TC();DC();Rg()});function Tg(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function BJ(e){let t=Tg(e,"executorRef").toLowerCase(),r=Tg(e,"title").toLowerCase(),n=Tg(e,"description").toLowerCase(),o=`${t}
|
|
81
145
|
${r}
|
|
82
|
-
${n}`;return
|
|
83
|
-
`}function
|
|
84
|
-
`,{mode:384}),t}function Qc(e){try{return fV(Sx(e)),!0}catch{return!1}}var hV,yV,ge,ji,vx,kV,bV,vV,et=p(()=>{"use strict";kr();hV="KYNVER_WORKER_MCP_TOOLS",yV="mcp-config.json",ge="kynver",ji=["agent_os_context_envelope","agent_os_search_memory","agent_os_search_skills","agent_os_get_skill","agent_os_progress_note"],vx=ji.map(e=>`mcp__${ge}__${e}`),kV={"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"]};bV=["claude","cursor","codex","openai-compatible","gemini","gemini-api"],vV=["openai-compatible","gemini-api"]});import{closeSync as xx,openSync as Cx}from"node:fs";import{spawn as wV}from"node:child_process";function SV(e,t){let n=Ax(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 Ax(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:vx).join(",")}`]:[],"--",e.prompt]}var Fr,Ji,Ex,tg=p(()=>{"use strict";In();N();Ge();Bt();et();Fr="claude-sonnet-4-6",Ji="claude-opus-4-8";Ex={name:"claude",defaultModel:Fr,preflightModel(e){return $m(e,Fr)},start(e){let t=$m(e.model,Fr);if(!t.ok)throw new Error(`claude provider model preflight failed: ${t.note}`);let r=t.model;SV(e,r);let[n,o]=oe("claude",Ax(e,r)),s=Cx(e.stdoutPath,"a"),i=Cx(e.stderrPath,"a"),a=["ignore",s,i],l=wV(n,o,X({cwd:e.worktreePath,detached:be(),stdio:a,env:ut(process.env,{reviewWorker:e.reviewWorker})}));if(xx(s),xx(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 Px,openSync as Ix}from"node:fs";import{spawn as _V}from"node:child_process";function xV(e,t){return ut({...process.env,CI:"1",NO_COLOR:"1",HERMES_ACCEPT_HOOKS:process.env.HERMES_ACCEPT_HOOKS??"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function CV(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 rg,Ox,Tx=p(()=>{"use strict";In();N();Ge();Pn();Bt();rg=process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||"gpt-5.5";Ox={name:"hermes-codex",defaultModel:rg,preflightModel(e){return ns(e,rg)},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=ns(e.model,rg);if(!t.ok)throw new Error(`hermes-codex provider model preflight failed: ${t.note}`);let r=t.model,n=ct("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),[o,s]=oe(n,CV(r,e.prompt)),i=Ix(e.stdoutPath,"a"),a=Ix(e.stderrPath,"a"),l=["ignore",i,a],c=_V(o,s,X({cwd:e.worktreePath,detached:be(),shell:!1,stdio:l,env:xV(e.reviewWorker,e.codexHome)}));if(Px(i),Px(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 PV(e=process.env){return e[EV]?.trim().toLowerCase()==="elevated"?"elevated":AV}function Zc(e=process.platform,t=process.env){return e!=="win32"?[]:["-c",`windows.sandbox="${PV(t)}"`]}var EV,AV,ng=p(()=>{"use strict";EV="KYNVER_CODEX_WINDOWS_SANDBOX",AV="unelevated"});import{closeSync as Nx,existsSync as IV,openSync as Dx}from"node:fs";import{spawn as og}from"node:child_process";function OV(){return process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||"gpt-5.5"}function vr(){return process.env.KYNVER_CODEX_BIN?.trim()||process.env.CODEX_BIN?.trim()||"codex"}function TV(e,t){return ut({...process.env,CI:"1",NO_COLOR:"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function NV(e,t,r,n=process.platform,o=process.env){return["--ask-for-approval","never","exec",...Zc(n,o),"--json","--sandbox",r==="read_only"?"read-only":"workspace-write","--model",e,t]}function DV(e,t,r){if(process.platform==="win32"){let[s,i]=oe(e,t);return og(s,i,r)}if(!IV("/usr/bin/script"))return og(e,t,r);let o=[e,...t].map(s=>`'${s.replace(/'/g,"'\\''")}'`).join(" ");return og("script",["-qfc",o,"/dev/null"],r)}var br,Mx,Mn=p(()=>{"use strict";In();N();Ge();Vc();Bt();Tx();ng();br=OV();Mx={name:"codex",defaultModel:br,preflightModel(e){return ns(e,br)},start(e){if(rs().path==="hermes_openai_codex"&&e.executionMode!=="read_only")return Ox.start(e);let r=ns(e.model,br);if(!r.ok)throw new Error(`codex provider model preflight failed: ${r.note}`);let n=r.model,o=Dx(e.stdoutPath,"a"),s=Dx(e.stderrPath,"a"),i=["ignore",o,s],a=vr(),l=NV(n,e.prompt,e.executionMode),c;try{c=DV(a,l,X({cwd:e.worktreePath,detached:be(),shell:!1,stdio:i,env:TV(e.reviewWorker,e.codexHome)}))}finally{Nx(o),Nx(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 eu}from"node:fs";import Ln from"node:path";import{fileURLToPath as MV}from"node:url";function LV(e,t){let r=Ln.resolve(e);for(;;){let n=Ln.join(r,t);if(eu(n))return n;let o=Ln.dirname(r);if(o===r)return null;r=o}}function BV(e){return LV(e,Ln.join("node_modules",".bin","tsx"))??"npx"}function sg(e,t){if(e.endsWith(".ts")){let r=BV(Ln.dirname(e));return{command:r,argsPrefix:r==="npx"?["tsx",e]:[e],cliPath:e}}return{command:t,argsPrefix:[e],cliPath:e}}function tu(e){if(e.explicitCliPath)return eu(e.explicitCliPath)?sg(e.explicitCliPath,e.nodeExecutable):null;let t=MV(new URL(".",e.importMetaUrl)),r=Ln.join(t,"cli.js");if(eu(r))return sg(r,e.nodeExecutable);let n=Ln.join(t,"cli.ts");return eu(n)?sg(n,e.nodeExecutable):null}var ig=p(()=>{"use strict"});function WV(e){return`/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/worker`}async function qi(e,t,r){let n=await e.fetchImpl(`${e.apiBaseUrl}${t}`,{method:r?.method??"GET",headers:{[UV]: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 Yi(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function ru(e,t,r){let n=WV(e);switch(t){case"agent_os_context_envelope":{let o=new URLSearchParams({task:e.taskId}),s=Yi(r.memoryQuery);s&&o.set("memoryQuery",s);let i=Yi(r.mode);return i&&o.set("mode",i),qi(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)),qi(e,`${n}/memory-search?${o.toString()}`)}case"agent_os_search_skills":{let o=new URLSearchParams,s=Yi(r.query);s&&o.set("q",s),typeof r.limit=="number"&&o.set("limit",String(r.limit));let i=o.toString();return qi(e,`${n}/skills${i?`?${i}`:""}`)}case"agent_os_get_skill":return qi(e,`${n}/skills/${encodeURIComponent(String(r.slug??""))}`);case"agent_os_progress_note":return qi(e,`${n}/progress-note`,{method:"POST",body:{note:String(r.note??""),...r.kind==="blocked"?{kind:"blocked"}:{},...Yi(r.eventKey)?{eventKey:Yi(r.eventKey)}:{}}})}}function ls(e){return ji.includes(e)}var UV,zi,nu=p(()=>{"use strict";et();UV="X-Kynver-Job-Token",zi={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 Xi(e){return Vi(e).filter(ls).map(t=>{let r=zi[t];return{type:"function",function:{name:r.name,description:r.description,parameters:r.inputSchema}}})}var ou=p(()=>{"use strict";nu();et()});import{closeSync as Lx,openSync as Bx}from"node:fs";import FV from"node:path";import{fileURLToPath as KV}from"node:url";import{spawn as $V}from"node:child_process";function ag(e=process.env){return e.KYNVER_WORKER_MODEL?.trim()||void 0}function jV(e=process.env){let t=e.KYNVER_WORKER_BASE_URL?.trim();if(!t)throw new Qi(`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 Qi(`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 Qi(`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):HV;return{baseUrl:t.replace(/\/+$/,""),...e.KYNVER_WORKER_API_KEY?.trim()?{apiKey:e.KYNVER_WORKER_API_KEY.trim()}:{},timeoutMs:o}}function su(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:VV},{role:"user",content:r}],...n&&n.length?{tools:n,tool_choice:"auto"}:{}}}}function GV(){let e=KV(new URL(".",import.meta.url)),t=import.meta.url.endsWith(".ts"),r=FV.join(e,t?"openai-compatible-runner.ts":"openai-compatible-runner.js"),n=tu({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 JV(e,t,r){let n=e.workerToolGrant,o=n?Xi(n.capabilities):void 0;return{provider:Bn,model:r,request:su(t,r,e.prompt,o),timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}function iu(e,t,r){let n=GV(),o=Bx(e.stdoutPath,"a"),s=Bx(e.stderrPath,"a"),i=["pipe",o,s],a=$V(n.command,n.argsPrefix,X({cwd:e.worktreePath,detached:be(),shell:!1,stdio:i,env:ut(process.env,{reviewWorker:e.reviewWorker})}));if(Lx(o),Lx(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 Bn,HV,Qi,VV,Ux,Zi=p(()=>{"use strict";In();N();ig();Bt();ou();Bn="openai-compatible",HV=600*1e3;Qi=class extends Error{};VV="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.";Ux={name:Bn,get defaultModel(){return ag()},preflightModel(e){return Hm(e,ag())},start(e){let t=Hm(e.model,ag());if(!t.ok)throw new Error(`openai-compatible provider model preflight failed: ${t.note}`);let r=t.model,n=jV(process.env),o=JV(e,n,r);return iu(e,o,r)}}});import qV from"node:path";function dt(e=process.env){return e.KYNVER_GEMINI_BIN?.trim()||e.GEMINI_BIN?.trim()||"agy"}function cs(e){let t=qV.basename(e).toLowerCase().replace(/\.cmd$/i,"").replace(/\.exe$/i,"");return t==="agy"||t==="antigravity"?"antigravity":"gemini"}function Wx(e){return e.requested&&/-(?:high|medium|low)$/i.test(e.requested)?e.requested:e.model}function Fx(e){let t=e.trim().toLowerCase();return!t||YV.has(t)?[]:["--model",e.trim()]}function au(e,t){return[...Fx(t),"--output-format","stream-json",...e.executionMode==="read_only"?[]:["--dangerously-skip-permissions"],"--prompt",e.prompt]}function Kx(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 YV,Un=p(()=>{"use strict";et();YV=new Set(["gemini-2.5-pro","gemini-2.5-flash","auto","pro","flash","flash-lite"])});import{closeSync as $x,openSync as Hx}from"node:fs";import{spawn as zV}from"node:child_process";function We(e=process.env){return e.KYNVER_GEMINI_DEFAULT_MODEL?.trim()||"gemini-2.5-pro"}function XV(e,t){return ut({...process.env,CI:"1",NO_COLOR:"1",GEMINI_CLI_TRUST_WORKSPACE:"true",...t?{GEMINI_CLI_HOME:t}:{}},{reviewWorker:e})}var Wt,jx,ea=p(()=>{"use strict";In();N();Ge();Un();Bt();Wt="gemini";jx={name:Wt,get defaultModel(){return We()},preflightModel(e){return os(e,We())},start(e){let t=os(e.model,We());if(!t.ok)throw new Error(`gemini provider model preflight failed: ${t.note}`);let r=dt(),n=cs(r),o=n==="antigravity"?Wx(t):t.model,s=n==="antigravity"?au(e,o):Kx(e,o),[i,a]=oe(r,s),l=Hx(e.stdoutPath,"a"),c=Hx(e.stderrPath,"a"),u=["ignore",l,c],d=zV(i,a,X({cwd:e.worktreePath,detached:be(),shell:!1,stdio:u,env:XV(e.reviewWorker,n==="gemini"?e.geminiCliHome:void 0)}));if($x(l),$x(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 ZV(e=process.env){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()||void 0}function eG(e=process.env){let t=ZV(e);if(!t)throw new ta('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()||Vx,n;try{n=new URL(r)}catch{throw new ta(`KYNVER_GEMINI_BASE_URL is not a valid URL: "${r}" \u2014 expected e.g. ${Vx}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new ta(`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):QV;return{baseUrl:r.replace(/\/+$/,""),apiKey:t,timeoutMs:s}}function tG(e,t,r){let n=e.workerToolGrant,o=n?Xi(n.capabilities):void 0,s=su(t,r,e.prompt,o);return{provider:Ft,model:r,request:s,timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}var Ft,Vx,QV,ta,Gx,lg=p(()=>{"use strict";Zi();ou();Bt();ea();Ft="gemini-api",Vx="https://generativelanguage.googleapis.com/v1beta/openai",QV=600*1e3,ta=class extends Error{};Gx={name:Ft,get defaultModel(){return We()},preflightModel(e){return os(e,We())},start(e){let t=os(e.model,We());if(!t.ok)throw new Error(`gemini-api provider model preflight failed: ${t.note}`);let r=t.model,n=eG(process.env),o=tG(e,n,r);return iu(e,o,r)}}});function Je(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function nG(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 Jx(e){return e.toLowerCase()}function ug(e=I()){let t=e.defaultModel?.trim();if(t)return t;let r=process.env.KYNVER_DEFAULT_MODEL?.trim();return r||rG}function lu(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-")?Wt:"cursor"}function oG(e,t){let r=e.trim().toLowerCase(),n=t?.trim();return r==="cursor"?{model:Kc,provider:"cursor",rule:n&&n!=="cursor"?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="claude"||r==="anthropic"?{model:Fr,provider:"claude",rule:n&&n!=="claude"?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini"||r==="google"?{model:We(),provider:Wt,rule:n&&n!==Wt?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini-api"||r==="gemini_api"||r==="google-api"?{model:We(),provider:Ft,rule:n&&n!==Ft?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:null}function qx(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 Yx(e,t,r){return sG.has(e)?Ji:t.includes("review")||/^review[\s:]/.test(r)||r.includes("critique")?Ji:Fr}function iG(e){let t=Jx(Je(e,"executorRef")),r=Je(e,"title").toLowerCase(),n=Je(e,"priority")||"normal",o=Jx(Je(e,"roleLane"));if(t.includes("provider:claude")||t.startsWith("claude:")){let i=Yx(o,t,r);return{provider:"claude",model:i,rule:i===Ji?"factory:claude_review":"factory:claude_implementation"}}if(t.includes("provider:codex")||t.startsWith("codex:"))return{provider:"codex",model:br,rule:"lane:codex_orchestration"};if(t.includes("provider:chatgpt")||t.startsWith("chatgpt:")||t.includes("provider:gpt")||t.startsWith("gpt:")){let i=lt(Je(e,"executorRef"));return{provider:"codex",...i?.model?{model:i.model}:{model:br},rule:"lane:codex_orchestration"}}if(t.includes("provider:openai")||t.startsWith("openai-compatible:")){let i=lt(Je(e,"executorRef"));return{provider:Bn,...i?.model?{model:i.model}:{},rule:"lane:openai_compatible"}}if(t.includes("provider:gemini-api")||t.startsWith("gemini-api:")){let i=lt(Je(e,"executorRef"));return{provider:Ft,...i?.model?{model:i.model}:{model:We()},rule:"lane:gemini_api"}}if(t.includes("provider:gemini")||t.startsWith("gemini:")){let i=lt(Je(e,"executorRef"));return{provider:Wt,...i?.model?{model:i.model}:{model:We()},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:br,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 qx(t,r)||o==="deep_reviewer"?{provider:"cursor",rule:"lane:deep_review"}:{provider:"cursor",rule:"lane:review"};if(qx(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=ug();return{model:s,provider:lu(s),rule:"default:global"}}function aG(e){return e?lt(Je(e,"executorRef")):null}function lG(e){switch($e(e)){case Wt:case Ft:return We();case"claude":return Fr;case"codex":return br;case"cursor":return Kc;default:return}}function Xx(e,t,r){let n=$e(t);return n===e.provider&&e.rule===r?e:{...e,provider:n,model:lG(n)??e.model,rule:r}}function cG(e,t){let r=t?.trim();return!r||e.rule.startsWith("explicit:")&&e.rule!==cg?e:Xx(e,r,cg)}function uG(e,t){if(t.explicitProvider?.trim()||Bm(t.task))return e;let r=t.configuredProvider?.trim();if(!r)return e;let n=$e(r);return n===yr||n===e.provider?e:Xx(e,n,zx)}function cu(e){let t,r=aG(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=oG(l,e.explicitProvider);c?t=c:t={model:l,provider:e.explicitProvider?.trim()||lu(l),rule:"explicit:cli",requestedModel:l}}else if(n)t={model:n,provider:o||lu(n),rule:r?.rule??"executor_ref:model",requestedModel:n};else if(e.task&&Fc(e.task)){let l=nG(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=Yx(d,m,f),u=c===Ji?"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=iG(e.task);t={...l,requestedModel:l.model}}else{let l=ug();t={model:l,provider:e.explicitProvider?.trim()||lu(l),rule:"default:global",requestedModel:l}}t=cG(t,e.explicitProvider),t=uG(t,{explicitProvider:e.explicitProvider,task:e.task,configuredProvider:e.configuredProvider});let s=!!e.configuredProvider?.trim()&&$e(e.configuredProvider)!==yr&&t.rule==="config:worker_provider",i=F_({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===cg||i.rule===zx||hr(i.provider)&&(e.explicitProviderIsOperatorOverride||Fc(e.task))||i.provider===Bn||i.provider===Wt||i.provider===Ft||i.provider==="codex")return i;let a=kx({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??br:i.model,rule:a.rule,requestedModel:i.requestedModel,orchestrationAudit:a.audit}}function Qx(e,t,r){return e||t||r||ug()||Fr}var rG,Kc,sG,cg,zx,$c=p(()=>{"use strict";K();Wc();bx();tg();Mn();Zi();ea();lg();En();rG="claude-sonnet-4-6",Kc="composer-2.5";sG=new Set(["report_reviewer","deep_reviewer","plan_reviewer"]);cg="explicit:cli_provider",zx="config:worker_provider"});function dG(e){let t=e?.executorRef;return typeof t=="string"?t.trim():""}function Zx(e){return e?.trim()||void 0}function eC(e){let t=dG(e.task),r=lt(t),n=e.explicitProvider?.trim().toLowerCase(),o=Zx(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=Zx(e.routing.model),u={provider:l,model:c,rule:e.routing.rule};return s&&s!=="cursor"||t&&W_(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&&!hr(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 tC=p(()=>{"use strict";Wc();En()});function rC(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function nC(){return{maxTaskAttempts:rC(process.env.KYNVER_MAX_TASK_ATTEMPTS,Math.floor(Yo("harness.maxTaskAttempts",4))),dispatchCooldownMs:rC(process.env.KYNVER_DISPATCH_COOLDOWN_MS,Math.floor(Yo("harness.dispatchCooldownMs",5e3)))}}var oC=p(()=>{"use strict";xn()});function pg(e){return e?.trim()?e.trim():null}function pG(e){let t=pg(e);if(!t?.startsWith(dg))return null;let r=t.slice(dg.length),n=r.indexOf(sC);return n>=0?r.slice(0,n).trim()||null:r.trim()||null}function ra(e,t){let r=e.trim(),n=t.trim();return`${dg}${r}${sC}${n}`}function fG(e,t){let r=pg(t);return r?pG(e)===r:!1}function uu(e){let t=pg(e.workerLeaseOwner);return t&&fG(t,e.runId)?t:ra(e.runId,e.runnerId)}var dg,sC,na=p(()=>{"use strict";dg="kynver-harness:",sC="@runner:"});async function du(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 fg=p(()=>{"use strict";K();Ue()});async function pu(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 du({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 mg=p(()=>{"use strict";fg();z()});import mG from"node:path";function iC(e,t){return W(mG.join(G(e),"workers",L(t),"worker.json"),void 0)}async function aC(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)):hg,a=Pe({runId:e}).runnerId,l=[],c=[],u=[];for(let d of Object.keys(r.workers||{})){let m=iC(e,d);if(!m?.taskId||!m.agentOsId){u.push(d);continue}if(!ie(m.pid)){u.push(d);continue}if(te(m).status==="done"){u.push(d);continue}let g=uu({runId:e,workerLeaseOwner:m.leaseOwner??null,runnerId:a}),h=await pu({worker:m,agentOsId:n,baseUrl:o,secret:s}),y=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/${encodeURIComponent(m.taskId)}/renew-lease`,b=await de(y,s,{leaseOwner:h.leaseOwner??g,leaseDurationMs:i,...h.leaseToken?{leaseToken:h.leaseToken}:{}},{agentOsId:n,baseUrl:o});if(b.ok){l.push(d);continue}let k=b.response&&typeof b.response=="object"&&"reason"in b.response?String(b.response.reason??`http ${b.status}`):`http ${b.status}`;c.push({worker:d,reason:k})}return{renewed:l,failed:c,skipped:u}}function lC(e,t){let r=ae(e);for(let n of Object.keys(r.workers||{})){let o=iC(e,n);if(!(!o||o.taskId!==t||!ie(o.pid)||te(o).status==="done"))return!0}return!1}var gg=p(()=>{"use strict";K();Ue();z();Se();N();fu();na();pr();mg()});function uC(e){let t=e.baseCommit?.trim()??"",r=[];t&&t!==cC&&r.push({ref:t,source:"baseCommit"});let n=e.base?.trim()??"";n&&n!==cC&&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 cC,dC=p(()=>{"use strict";cC="unknown"});function mu(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function pC(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 yG(e){let t=(e.title??"").trim().toLowerCase();if(t.startsWith("fix:")||t.startsWith("repair:"))return!0;let r=(e.executorRef??"").toLowerCase();return!!(r.startsWith(hG)||r.includes("repair")||r.includes("unblock"))}function kG(e){let t={repairEnforceOriginalPr:!1,targetPrUrl:null,targetPrBranch:null};if(!e)return t;let r=e.match(gG);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?pC(o):null,targetPrBranch:s}}catch{return t}}function fC(e){if(!yG(e))return null;let t=kG(e.description),r=e.prUrl?pC(e.prUrl):null,n=t.targetPrUrl??r;return n?{targetPrUrl:n,targetPrBranch:t.targetPrBranch??mu(e.branch)}:null}function mC(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 gG,hG,yg=p(()=>{"use strict";gG=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/i,hG="next-action-fix:"});var gC=p(()=>{"use strict"});function hC(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=[...Pi(`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 MJ.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":LJ.some(s=>s.test(o))?"low":"elevated"}function WJ(e){let t=cs(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 UJ(e){let t=e.inventory??MC();return e.codexBinding?{...t,bindings:{...t.bindings,codex:e.codexBinding}}:t}function Hn(e){let t=WJ({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 BC(e){let t=e.task??{},r=BJ(t),n=UJ({inventory:e.inventory,codexBinding:e.codexBinding??(e.inventory?null:ds())}),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=wg({inventory:n,riskClass:r});return Hn(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 Hn({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 Hn({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 Hn({providerId:"claude",binding:c,riskClass:r,routingRule:"orchestration:explicit_claude",model:s})}let a=wg({inventory:n,riskClass:r});if(a)return Hn({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 Hn({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 MJ,LJ,WC=p(()=>{"use strict";Ln();bg();uu();kC();LC();MJ=[/\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],LJ=[/\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 Ng(e){return`${JSON.stringify(e)}
|
|
147
|
+
`}function Dg(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 Tt,Sr=p(()=>{"use strict";Tt="KYNVER_WORKER_BROKER_SOCKET"});import{unlinkSync as FJ,writeFileSync as KJ}from"node:fs";import $J from"node:path";function sa(e){if(!e||e.length===0)return[...oa];let t=new Set;for(let r of e)for(let n of VJ[r]??[])t.add(n);return oa.filter(r=>t.has(r))}function FC(e){return sa(e).map(t=>`mcp__${ge}__${t}`)}function qJ(e){return GJ.includes(e)}function Mg(e){return JJ.includes(e)}function KC(e){return qJ(e)&&!Mg(e)}function ia(e=process.env){let t=e[HJ]?.trim().toLowerCase();return t?t==="1"||t==="true"||t==="yes"||t==="on":!0}function $C(e){return $J.join(e,jJ)}function HC(e){let t=$C(e.workerDir),r={mcpServers:{[ge]:{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Tt]:e.brokerSocketPath}}}};return KJ(t,`${JSON.stringify(r,null,2)}
|
|
148
|
+
`,{mode:384}),t}function yu(e){try{return FJ($C(e)),!0}catch{return!1}}var HJ,jJ,ge,oa,UC,VJ,GJ,JJ,nt=p(()=>{"use strict";Sr();HJ="KYNVER_WORKER_MCP_TOOLS",jJ="mcp-config.json",ge="kynver",oa=["agent_os_context_envelope","agent_os_search_memory","agent_os_search_skills","agent_os_get_skill","agent_os_progress_note"],UC=oa.map(e=>`mcp__${ge}__${e}`),VJ={"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"]};GJ=["claude","cursor","codex","openai-compatible","gemini","gemini-api"],JJ=["openai-compatible","gemini-api"]});import{closeSync as jC,openSync as VC}from"node:fs";import{spawn as YJ}from"node:child_process";function zJ(e,t){let n=JC(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 JC(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:UC).join(",")}`]:[],"--",e.prompt]}var qr,aa,GC,Lg=p(()=>{"use strict";lr();Un();M();Je();Ft();nt();qr="claude-sonnet-4-6",aa="claude-opus-4-8";GC={name:"claude",defaultModel:qr,preflightModel(e){return Sg(e,qr)},start(e){let t=Sg(e.model,qr);if(!t.ok)throw new Error(`claude provider model preflight failed: ${t.note}`);let r=t.model;zJ(e,r);let[n,o]=ie("claude",JC(e,r)),s=VC(e.stdoutPath,"a"),i=VC(e.stderrPath,"a"),a=["ignore",s,i],[l,c]=et(n,o,e.workerDir),u=YJ(l,c,z({cwd:e.worktreePath,detached:ve(),stdio:a,env:mt(process.env,{reviewWorker:e.reviewWorker})}));if(jC(s),jC(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 YC}from"node:fs";import{spawn as XJ}from"node:child_process";function QJ(e,t){return mt({...process.env,CI:"1",NO_COLOR:"1",HERMES_ACCEPT_HOOKS:process.env.HERMES_ACCEPT_HOOKS??"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function ZJ(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 Bg,zC,XC=p(()=>{"use strict";lr();Un();M();Je();Wn();Ft();Bg=process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||"gpt-5.5";zC={name:"hermes-codex",defaultModel:Bg,preflightModel(e){return ps(e,Bg)},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=ps(e.model,Bg);if(!t.ok)throw new Error(`hermes-codex provider model preflight failed: ${t.note}`);let r=t.model,n=ft("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),[o,s]=ie(n,ZJ(r,e.prompt)),i=YC(e.stdoutPath,"a"),a=YC(e.stderrPath,"a"),l=["ignore",i,a],[c,u]=et(o,s,e.workerDir),d=XJ(c,u,z({cwd:e.worktreePath,detached:ve(),shell:!1,stdio:l,env:QJ(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 r2(e=process.env){return e[e2]?.trim().toLowerCase()==="elevated"?"elevated":t2}function ku(e=process.platform,t=process.env){return e!=="win32"?[]:["-c",`windows.sandbox="${r2(t)}"`]}var e2,t2,Wg=p(()=>{"use strict";e2="KYNVER_CODEX_WINDOWS_SANDBOX",t2="unelevated"});import{closeSync as QC,existsSync as n2,openSync as ZC}from"node:fs";import{spawn as Ug}from"node:child_process";function o2(){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 s2(e,t){return mt({...process.env,CI:"1",NO_COLOR:"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function i2(e,t,r,n=process.platform,o=process.env){return["--ask-for-approval","never","exec",...ku(n,o),"--json","--sandbox",r==="read_only"?"read-only":"workspace-write","--model",e,t]}function a2(e,t,r,n){if(process.platform==="win32"){let[l,c]=ie(e,t);return Ug(l,c,r)}if(!n2("/usr/bin/script")){let[l,c]=et(e,t,n);return Ug(l,c,r)}let s=[e,...t].map(l=>`'${l.replace(/'/g,"'\\''")}'`).join(" "),[i,a]=et("script",["-qfc",s,"/dev/null"],n);return Ug(i,a,r)}var _r,eE,jn=p(()=>{"use strict";lr();Un();M();Je();uu();Ft();XC();Wg();_r=o2();eE={name:"codex",defaultModel:_r,preflightModel(e){return ps(e,_r)},start(e){if(ds().path==="hermes_openai_codex"&&e.executionMode!=="read_only")return zC.start(e);let r=ps(e.model,_r);if(!r.ok)throw new Error(`codex provider model preflight failed: ${r.note}`);let n=r.model,o=ZC(e.stdoutPath,"a"),s=ZC(e.stderrPath,"a"),i=["ignore",o,s],a=xr(),l=i2(n,e.prompt,e.executionMode),c;try{c=a2(a,l,z({cwd:e.worktreePath,detached:ve(),shell:!1,stdio:i,env:s2(e.reviewWorker,e.codexHome)}),e.workerDir)}finally{QC(o),QC(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 bu}from"node:fs";import Vn from"node:path";import{fileURLToPath as l2}from"node:url";function c2(e,t){let r=Vn.resolve(e);for(;;){let n=Vn.join(r,t);if(bu(n))return n;let o=Vn.dirname(r);if(o===r)return null;r=o}}function u2(e){return c2(e,Vn.join("node_modules",".bin","tsx"))??"npx"}function Fg(e,t){if(e.endsWith(".ts")){let r=u2(Vn.dirname(e));return{command:r,argsPrefix:r==="npx"?["tsx",e]:[e],cliPath:e}}return{command:t,argsPrefix:[e],cliPath:e}}function vu(e){if(e.explicitCliPath)return bu(e.explicitCliPath)?Fg(e.explicitCliPath,e.nodeExecutable):null;let t=l2(new URL(".",e.importMetaUrl)),r=Vn.join(t,"cli.js");if(bu(r))return Fg(r,e.nodeExecutable);let n=Vn.join(t,"cli.ts");return bu(n)?Fg(n,e.nodeExecutable):null}var Kg=p(()=>{"use strict"});function p2(e){return`/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/worker`}async function la(e,t,r){let n=await e.fetchImpl(`${e.apiBaseUrl}${t}`,{method:r?.method??"GET",headers:{[d2]: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 ca(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function Ru(e,t,r){let n=p2(e);switch(t){case"agent_os_context_envelope":{let o=new URLSearchParams({task:e.taskId}),s=ca(r.memoryQuery);s&&o.set("memoryQuery",s);let i=ca(r.mode);return i&&o.set("mode",i),la(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)),la(e,`${n}/memory-search?${o.toString()}`)}case"agent_os_search_skills":{let o=new URLSearchParams,s=ca(r.query);s&&o.set("q",s),typeof r.limit=="number"&&o.set("limit",String(r.limit));let i=o.toString();return la(e,`${n}/skills${i?`?${i}`:""}`)}case"agent_os_get_skill":return la(e,`${n}/skills/${encodeURIComponent(String(r.slug??""))}`);case"agent_os_progress_note":return la(e,`${n}/progress-note`,{method:"POST",body:{note:String(r.note??""),...r.kind==="blocked"?{kind:"blocked"}:{},...ca(r.eventKey)?{eventKey:ca(r.eventKey)}:{}}})}}function ys(e){return oa.includes(e)}var d2,ua,wu=p(()=>{"use strict";nt();d2="X-Kynver-Job-Token",ua={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 da(e){return sa(e).filter(ys).map(t=>{let r=ua[t];return{type:"function",function:{name:r.name,description:r.description,parameters:r.inputSchema}}})}var Su=p(()=>{"use strict";wu();nt()});import{closeSync as tE,openSync as rE}from"node:fs";import f2 from"node:path";import{fileURLToPath as m2}from"node:url";import{spawn as g2}from"node:child_process";function $g(e=process.env){return e.KYNVER_WORKER_MODEL?.trim()||void 0}function y2(e=process.env){let t=e.KYNVER_WORKER_BASE_URL?.trim();if(!t)throw new pa(`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 pa(`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 pa(`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):h2;return{baseUrl:t.replace(/\/+$/,""),...e.KYNVER_WORKER_API_KEY?.trim()?{apiKey:e.KYNVER_WORKER_API_KEY.trim()}:{},timeoutMs:o}}function _u(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:k2},{role:"user",content:r}],...n&&n.length?{tools:n,tool_choice:"auto"}:{}}}}function b2(){let e=m2(new URL(".",import.meta.url)),t=import.meta.url.endsWith(".ts"),r=f2.join(e,t?"openai-compatible-runner.ts":"openai-compatible-runner.js"),n=vu({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 v2(e,t,r){let n=e.workerToolGrant,o=n?da(n.capabilities):void 0;return{provider:Gn,model:r,request:_u(t,r,e.prompt,o),timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}function xu(e,t,r){let n=b2(),o=rE(e.stdoutPath,"a"),s=rE(e.stderrPath,"a"),i=["pipe",o,s],[a,l]=et(n.command,n.argsPrefix,e.workerDir),c=g2(a,l,z({cwd:e.worktreePath,detached:ve(),shell:!1,stdio:i,env:mt(process.env,{reviewWorker:e.reviewWorker})}));if(tE(o),tE(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 Gn,h2,pa,k2,nE,fa=p(()=>{"use strict";lr();Un();M();Kg();Ft();Su();Gn="openai-compatible",h2=600*1e3;pa=class extends Error{};k2="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.";nE={name:Gn,get defaultModel(){return $g()},preflightModel(e){return _g(e,$g())},start(e){let t=_g(e.model,$g());if(!t.ok)throw new Error(`openai-compatible provider model preflight failed: ${t.note}`);let r=t.model,n=y2(process.env),o=v2(e,n,r);return xu(e,o,r)}}});import R2 from"node:path";function gt(e=process.env){return e.KYNVER_GEMINI_BIN?.trim()||e.GEMINI_BIN?.trim()||"agy"}function ks(e){let t=R2.basename(e).toLowerCase().replace(/\.cmd$/i,"").replace(/\.exe$/i,"");return t==="agy"||t==="antigravity"?"antigravity":"gemini"}function oE(e){return e.requested&&/-(?:high|medium|low)$/i.test(e.requested)?e.requested:e.model}function sE(e){let t=e.trim().toLowerCase();return!t||w2.has(t)?[]:["--model",e.trim()]}function Cu(e,t){return[...sE(t),"--output-format","stream-json",...e.executionMode==="read_only"?[]:["--dangerously-skip-permissions"],"--prompt",e.prompt]}function iE(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 w2,Jn=p(()=>{"use strict";nt();w2=new Set(["gemini-2.5-pro","gemini-2.5-flash","auto","pro","flash","flash-lite"])});import{closeSync as aE,openSync as lE}from"node:fs";import{spawn as S2}from"node:child_process";function Fe(e=process.env){return e.KYNVER_GEMINI_DEFAULT_MODEL?.trim()||"gemini-2.5-pro"}function _2(e,t){return mt({...process.env,CI:"1",NO_COLOR:"1",GEMINI_CLI_TRUST_WORKSPACE:"true",...t?{GEMINI_CLI_HOME:t}:{}},{reviewWorker:e})}var $t,cE,ma=p(()=>{"use strict";lr();Un();M();Je();Jn();Ft();$t="gemini";cE={name:$t,get defaultModel(){return Fe()},preflightModel(e){return fs(e,Fe())},start(e){let t=fs(e.model,Fe());if(!t.ok)throw new Error(`gemini provider model preflight failed: ${t.note}`);let r=gt(),n=ks(r),o=n==="antigravity"?oE(t):t.model,s=n==="antigravity"?Cu(e,o):iE(e,o),[i,a]=ie(r,s),l=lE(e.stdoutPath,"a"),c=lE(e.stderrPath,"a"),u=["ignore",l,c],[d,f]=et(i,a,e.workerDir),m=S2(d,f,z({cwd:e.worktreePath,detached:ve(),shell:!1,stdio:u,env:_2(e.reviewWorker,n==="gemini"?e.geminiCliHome:void 0)}));if(aE(l),aE(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 C2(e=process.env){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()||void 0}function E2(e=process.env){let t=C2(e);if(!t)throw new ga('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()||uE,n;try{n=new URL(r)}catch{throw new ga(`KYNVER_GEMINI_BASE_URL is not a valid URL: "${r}" \u2014 expected e.g. ${uE}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new ga(`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):x2;return{baseUrl:r.replace(/\/+$/,""),apiKey:t,timeoutMs:s}}function A2(e,t,r){let n=e.workerToolGrant,o=n?da(n.capabilities):void 0,s=_u(t,r,e.prompt,o);return{provider:Ht,model:r,request:s,timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}var Ht,uE,x2,ga,dE,Hg=p(()=>{"use strict";fa();Su();Ft();ma();Ht="gemini-api",uE="https://generativelanguage.googleapis.com/v1beta/openai",x2=600*1e3,ga=class extends Error{};dE={name:Ht,get defaultModel(){return Fe()},preflightModel(e){return fs(e,Fe())},start(e){let t=fs(e.model,Fe());if(!t.ok)throw new Error(`gemini-api provider model preflight failed: ${t.note}`);let r=t.model,n=E2(process.env),o=A2(e,n,r);return xu(e,o,r)}}});function qe(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function I2(e){if(!e)return;let t=qe(e,"workerModelOverride")||qe(e,"modelOverride");return t||`${qe(e,"title")}
|
|
149
|
+
${qe(e,"description")}
|
|
150
|
+
${qe(e,"executorRef")}`.match(/\[(?:worker-)?model:\s*([^\]\n]+)\]/i)?.[1]?.trim()||void 0}function pE(e){return e.toLowerCase()}function Vg(e=E()){let t=e.defaultModel?.trim();if(t)return t;let r=process.env.KYNVER_DEFAULT_MODEL?.trim();return r||P2}function Eu(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-")?$t:"cursor"}function O2(e,t){let r=e.trim().toLowerCase(),n=t?.trim();return r==="cursor"?{model:iu,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:Fe(),provider:$t,rule:n&&n!==$t?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini-api"||r==="gemini_api"||r==="google-api"?{model:Fe(),provider:Ht,rule:n&&n!==Ht?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:null}function fE(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 mE(e,t,r){return T2.has(e)?aa:t.includes("review")||/^review[\s:]/.test(r)||r.includes("critique")?aa:qr}function N2(e){let t=pE(qe(e,"executorRef")),r=qe(e,"title").toLowerCase(),n=qe(e,"priority")||"normal",o=pE(qe(e,"roleLane"));if(t.includes("provider:claude")||t.startsWith("claude:")){let i=mE(o,t,r);return{provider:"claude",model:i,rule:i===aa?"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=pt(qe(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=pt(qe(e,"executorRef"));return{provider:Gn,...i?.model?{model:i.model}:{},rule:"lane:openai_compatible"}}if(t.includes("provider:gemini-api")||t.startsWith("gemini-api:")){let i=pt(qe(e,"executorRef"));return{provider:Ht,...i?.model?{model:i.model}:{model:Fe()},rule:"lane:gemini_api"}}if(t.includes("provider:gemini")||t.startsWith("gemini:")){let i=pt(qe(e,"executorRef"));return{provider:$t,...i?.model?{model:i.model}:{model:Fe()},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 fE(t,r)||o==="deep_reviewer"?{provider:"cursor",rule:"lane:deep_review"}:{provider:"cursor",rule:"lane:review"};if(fE(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=Vg();return{model:s,provider:Eu(s),rule:"default:global"}}function D2(e){return e?pt(qe(e,"executorRef")):null}function M2(e){switch(He(e)){case $t:case Ht:return Fe();case"claude":return qr;case"codex":return _r;case"cursor":return iu;default:return}}function hE(e,t,r){let n=He(t);return n===e.provider&&e.rule===r?e:{...e,provider:n,model:M2(n)??e.model,rule:r}}function L2(e,t){let r=t?.trim();return!r||e.rule.startsWith("explicit:")&&e.rule!==jg?e:hE(e,r,jg)}function B2(e,t){if(t.explicitProvider?.trim()||kg(t.task))return e;let r=t.configuredProvider?.trim();if(!r)return e;let n=He(r);return n===wr||n===e.provider?e:hE(e,n,gE)}function Au(e){let t,r=D2(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=O2(l,e.explicitProvider);c?t=c:t={model:l,provider:e.explicitProvider?.trim()||Eu(l),rule:"explicit:cli",requestedModel:l}}else if(n)t={model:n,provider:o||Eu(n),rule:r?.rule??"executor_ref:model",requestedModel:n};else if(e.task&&su(e.task)){let l=I2(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=mE(d,f,m),u=c===aa?"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=N2(e.task);t={...l,requestedModel:l.model}}else{let l=Vg();t={model:l,provider:e.explicitProvider?.trim()||Eu(l),rule:"default:global",requestedModel:l}}t=L2(t,e.explicitProvider),t=B2(t,{explicitProvider:e.explicitProvider,task:e.task,configuredProvider:e.configuredProvider});let s=!!e.configuredProvider?.trim()&&He(e.configuredProvider)!==wr&&t.rule==="config:worker_provider",i=oC({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===gE||Rr(i.provider)&&(e.explicitProviderIsOperatorOverride||su(e.task))||i.provider===Gn||i.provider===$t||i.provider===Ht||i.provider==="codex")return i;let a=BC({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 yE(e,t,r){return e||t||r||Vg()||qr}var P2,iu,T2,jg,gE,au=p(()=>{"use strict";j();ou();WC();Lg();jn();fa();ma();Hg();Ln();P2="claude-sonnet-4-6",iu="composer-2.5";T2=new Set(["report_reviewer","deep_reviewer","plan_reviewer"]);jg="explicit:cli_provider",gE="config:worker_provider"});function W2(e){let t=e?.executorRef;return typeof t=="string"?t.trim():""}function kE(e){return e?.trim()||void 0}function bE(e){let t=W2(e.task),r=pt(t),n=e.explicitProvider?.trim().toLowerCase(),o=kE(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=kE(e.routing.model),u={provider:l,model:c,rule:e.routing.rule};return s&&s!=="cursor"||t&&nC(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 vE=p(()=>{"use strict";ou();Ln()});function RE(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function wE(){return{maxTaskAttempts:RE(process.env.KYNVER_MAX_TASK_ATTEMPTS,Math.floor(os("harness.maxTaskAttempts",4))),dispatchCooldownMs:RE(process.env.KYNVER_DISPATCH_COOLDOWN_MS,Math.floor(os("harness.dispatchCooldownMs",5e3)))}}var SE=p(()=>{"use strict";Gr()});function Jg(e){return e?.trim()?e.trim():null}function U2(e){let t=Jg(e);if(!t?.startsWith(Gg))return null;let r=t.slice(Gg.length),n=r.indexOf(_E);return n>=0?r.slice(0,n).trim()||null:r.trim()||null}function ha(e,t){let r=e.trim(),n=t.trim();return`${Gg}${r}${_E}${n}`}function F2(e,t){let r=Jg(t);return r?U2(e)===r:!1}function Pu(e){let t=Jg(e.workerLeaseOwner);return t&&F2(t,e.runId)?t:ha(e.runId,e.runnerId)}var Gg,_E,ya=p(()=>{"use strict";Gg="kynver-harness:",_E="@runner:"});async function Iu(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 qg=p(()=>{"use strict";j();Ue()});async function Ou(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 Iu({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 Yg=p(()=>{"use strict";qg();Y()});import K2 from"node:path";function xE(e,t){return K(K2.join(V(e),"workers",B(t),"worker.json"),void 0)}async function CE(e,t){let r=re(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)):Xg,a=Te({runId:e}).runnerId,l=[],c=[],u=[];for(let d of Object.keys(r.workers||{})){let f=xE(e,d);if(!f?.taskId||!f.agentOsId){u.push(d);continue}if(!te(f.pid)){u.push(d);continue}if(se(f).status==="done"){u.push(d);continue}let g=Pu({runId:e,workerLeaseOwner:f.leaseOwner??null,runnerId:a}),h=await Ou({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 EE(e,t){let r=re(e);for(let n of Object.keys(r.workers||{})){let o=xE(e,n);if(!(!o||o.taskId!==t||!te(o.pid)||se(o).status==="done"))return!0}return!1}var zg=p(()=>{"use strict";j();Ue();Y();xe();M();Tu();ya();yr();Yg()});import $2 from"node:path";function AE(e){return typeof e?.noRestartAt=="string"&&e.noRestartAt.trim().length>0}function PE(e,t,r,n){return AE(t)||(t.noRestartAt=new Date().toISOString(),t.noRestartSource=r,n&&(t.noRestartReason=n),t.steerRestartRequired=!1,X(e,t)),t}function Nu(e,t={}){let r=t.isAlive??te,n=t.kill??ye,o=t.sleep??Ml;return!e||!r(e)?null:(n(e,"SIGTERM"),o(1e3),r(e)?(n(e,"SIGKILL"),"SIGKILL"):"SIGTERM")}function Qg(e,t,r,n,o={}){PE(e,t,r,n);let s=Nu(t.pid,o),i=Nu(t.completionSidecarPid,o);return{workerSignal:s,sidecarSignal:i}}function IE(e,t,r={}){let n=r.isAlive??te,o=re(e),s=[];for(let i of Object.keys(o.workers||{})){if(r.except&&i===r.except)continue;let a=K($2.join(V(o.id),"workers",B(i),"worker.json"),void 0);!a||a.taskId!==t||n(a.pid)||!a.completionSidecarPid||!n(a.completionSidecarPid)||(Nu(a.completionSidecarPid,r),a.completionSidecarPid=void 0,a.watcherClearedForRelaunchAt=new Date().toISOString(),X(o.id,a),s.push(i))}return s}function H2(e=process.env){let t=String(e.KYNVER_ALLOW_UNWATCHED_WORKER??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function OE(e,t,r,n={}){if(!H2(n.env))throw Qg(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 bs=p(()=>{"use strict";Y();M()});function NE(e){let t=e.baseCommit?.trim()??"",r=[];t&&t!==TE&&r.push({ref:t,source:"baseCommit"});let n=e.base?.trim()??"";n&&n!==TE&&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 TE,DE=p(()=>{"use strict";TE="unknown"});function Du(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function ME(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:Du(e)}function G2(e){let t=(e.title??"").trim().toLowerCase();if(t.startsWith("fix:")||t.startsWith("repair:"))return!0;let r=(e.executorRef??"").toLowerCase();return!!(r.startsWith(V2)||r.includes("repair")||r.includes("unblock"))}function J2(e){let t={repairEnforceOriginalPr:!1,targetPrUrl:null,targetPrBranch:null};if(!e)return t;let r=e.match(j2);if(!r?.[1])return t;try{let n=JSON.parse(r[1]),o=Du(String(n.targetPrUrl??n.target_pr_url??"")),s=Du(String(n.targetPrBranch??n.target_pr_branch??""));return{repairEnforceOriginalPr:n.repairEnforceOriginalPr===!0||n.repair_enforce_original_pr===!0||!!o,targetPrUrl:o?ME(o):null,targetPrBranch:s}}catch{return t}}function LE(e){if(!G2(e))return null;let t=J2(e.description),r=e.prUrl?ME(e.prUrl):null,n=t.targetPrUrl??r;return n?{targetPrUrl:n,targetPrBranch:t.targetPrBranch??Du(e.branch)}:null}function BE(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 j2,V2,Zg=p(()=>{"use strict";j2=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/i,V2="next-action-fix:"});var WE=p(()=>{"use strict"});function UE(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=[...$i(`worker.prompt.progress.${n}`).split(`
|
|
151
|
+
`),o],i=$i(`worker.prompt.merge_gate.${n}`).split(`
|
|
152
|
+
`),a=$i(`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.",...$i("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?[...BE({targetPrUrl:e.repairTargetPrUrl,targetPrBranch:e.repairTargetBranch??null}),""]:[],"Task:",e.task].join(`
|
|
155
|
+
`)}var FE=p(()=>{"use strict";Zg();Gr();WE()});function $E(e){if(KE)return KE;let t=e?.trim();if(t){let o=Mu[He(t)];if(!o)throw new Error(`unknown worker provider "${t}" \u2014 supported: ${Object.keys(Mu).join(", ")}`);return o}let r=sC(E().workerProvider),n=Mu[r];if(!n)throw new Error(`unknown worker provider "${r}" \u2014 supported: ${Object.keys(Mu).join(", ")}`);return n}var Mu,KE,HE=p(()=>{"use strict";j();Ln();Lg();jn();gs();ma();Hg();fa();Mu={claude:GC,codex:eE,cursor:AC,[$t]:cE,[Ht]:dE,[Gn]:nE},KE=null});function jE(e){return!!e.completionReportedAt?.trim()}function Lu(e,t,r){e.completionReportedAt=r.completionReportedAt,e.completionOutcome=r.completionOutcome,r.completionResponse!==void 0&&(e.completionResponse=r.completionResponse),X(t,e)}var eh=p(()=>{"use strict";Y()});function q2(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function th(e){return!!(q2(e.completionBlocker)||e.completionOutcome==="rejected")}function ka(e){return jE(e)&&!th(e)}var Bu=p(()=>{"use strict";eh()});function rh(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ba(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function GE(e){let t=rh(e);if(!t)return{routeOutcome:null,taskAdvanced:!1,detail:null};let r=ba(t.outcome),n=ba(t.detail)??ba(t.error),o=rh(t.task),s=rh(t.closedTask),i=o?ba(o.status):null,a=s?ba(s.status):null,c=r==="skipped_terminal_task"&&(i!==null&&VE.has(i)||a!==null&&VE.has(a))||r!==null&&Y2.has(r)||i==="awaiting_review"||i==="done"||a==="done";return{routeOutcome:r,taskAdvanced:c,detail:n}}function JE(e){return e.taskAdvanced}var Y2,VE,qE=p(()=>{"use strict";Y2=new Set(["review_scheduled","review_already_scheduled","closed","dispatched","dispatch_already_done","steer_restart_required"]),VE=new Set(["done","failed","cancelled"])});var YE=p(()=>{"use strict"});function Z2(e){if(!e)return null;let t=e.trim().toLowerCase();return t.length?t:null}function nh(e){return/\b(deep[- ]?review|plan review|review .*plan|security review|red[- ]team|lb\d+|runtime verification)\b/.test(e)}function eq(e,t){return e.startsWith("factory:")?e.includes("lb")||nh(t):!1}function Uu(e){let t=(e.executorRef??"").toLowerCase(),r=(e.title??"").toLowerCase(),n=(e.description??"").toLowerCase(),o=`${r}
|
|
156
|
+
${n}`,s=Z2(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(z2)||t===X2||t.startsWith("daemon-review:")||s&&Wu.has(s)&&(t.includes("evidence")||t.includes("validate")||t.includes("review")||eq(t,o)||nh(o))||t.startsWith(Q2)&&e.parentTaskId&&s&&Wu.has(s)||e.planId&&!e.parentTaskId&&s&&Wu.has(s)&&nh(o)||r.includes("expert pr review")||e.parentTaskId&&(r.startsWith("review:")||r.includes("review required")||r.includes("runtime review"))&&s&&Wu.has(s))}var z2,X2,Q2,Wu,oh=p(()=>{"use strict";z2="expert-lane-pr-review:",X2="plan-review-task",Q2="scheduledjob:",Wu=new Set(["lorentz","dalton","rhea","sentinel"])});function XE(e){return!!(e&&rq.test(e))}function Ke(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function QE(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:Ke(e.head)}function ZE(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?Ke(r[0]):null}function nq(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 oq(e,t){if(t.changedFiles.length>0)return!1;let r=Ke(e.personaSlug)?.toLowerCase();if(r&&tq.has(r))return!0;let n=Ke(e.routingRule)??"";return!!(n&&zE.test(n))}function sq(e,t){if(e.changedFiles.length>0)return!0;let r=Ke(t?.baseRef);if(r&&t?.exec&&t.worktreePath){let n=nq(t.worktreePath,r,t.exec);if(n===0)return!1;if(n!==null&&n>0)return!0}return!!(Ke(e.headCommit)||QE(e.gitAncestry))}function eA(e){if(!e.dispatched)return{required:!1,reason:"not_dispatched"};if(Uu({title:e.taskTitle??void 0,personaSlug:e.personaSlug,parentTaskId:e.parentTaskId,executorRef:e.executorRef}))return{required:!1,reason:"expert_review_task"};let t=Ke(e.routingRule)??"";if(t&&zE.test(t))return{required:!1,reason:"review_lane"};let r=e.worker??{personaSlug:e.personaSlug,routingRule:e.routingRule};if(oq(r,e.snapshot))return{required:!1,reason:"review_artifact"};if(Ke(e.patchPath)||Ke(e.artifactBundlePath))return{required:!1,reason:"patch_or_bundle"};if(Ke(e.repairTargetPrUrl))return{required:!1,reason:"repair_target_pr"};if(Ke(e.prUrl)??Ke(e.taskPrUrl)??Ke(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 sq(e.snapshot,s)?{required:!0,snapshot:e.snapshot}:{required:!1,reason:"no_work_product"}}function tA(e,t){return{changedFiles:e.changedFiles,branch:e.branch,worktreePath:e.worktreePath,gitAncestry:e.gitAncestry,finalResult:e.finalResult,headCommit:Ke(t?.headCommit)??QE(e.gitAncestry),prUrl:Ke(t?.prUrl)??null}}var zE,tq,rq,sh=p(()=>{"use strict";oh();eu();zE=/^(lane:)?(review|deep_review|planning|landing)(:|$)/i,tq=new Set(Gx()),rq=/no commits between/i});function nA(e){let t=e.trim();if(!t)return null;let r=t.match(/^git@github\.com:([^/]+\/[^/\s]+?)(?:\.git)?$/i);if(r)return rA(r[1]);let n=t.match(/^ssh:\/\/git@github\.com\/([^/]+\/[^/\s]+?)(?:\.git)?$/i);if(n)return rA(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 rA(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 oA=p(()=>{"use strict"});import{spawnSync as iq}from"node:child_process";function aq(e,t,r){try{let n=iq(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 lq(e){return e.split(`
|
|
157
|
+
`).map(t=>t.trim()).find(Boolean)??""}function sA(e,t){let r=t.git(e,["remote","get-url","origin"]);return r.status!==0?null:nA(r.stdout)}function qn(e,t){let r=t.git(e,["rev-parse","HEAD"]);return r.status!==0?null:r.stdout.trim()||null}function Fu(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 va(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=qn(t,s)??void 0;return{ok:!0,committed:o,pushed:!0,headCommit:a}}function iA(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 aA(e){let t=Fu(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=cq(r.stdout)??Fu(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 cq(e){let r=lq(e).match(/https?:\/\/[^\s]+\/pull\/\d+/i);return r?r[0]:null}var Ku,$u=p(()=>{"use strict";oA();Re();Ku={git:(e,t)=>Q(e,t),gh:(e,t)=>aq("gh",e,t)}});function lA(e){return`t-${B(e)}-a`}function cA(e,t){let r=lA(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 Ra(e){return e.trim().toLowerCase()}function uA(e,t){if(!e.length)return null;if(t){let r=Ra(t),n=e.find(o=>Ra(o.url)===r);if(n)return n}return[...e].sort((r,n)=>n.number-r.number)[0]??null}function dA(e,t){let r=Ra(t);return e.filter(n=>Ra(n.url)!==r).map(n=>n.url)}function pA(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 uq(e){let t=new Set,r=[];for(let n of e){let o=Ra(n.url);t.has(o)||(t.add(o),r.push(n))}return r}function dq(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?[]:pA(o.stdout).filter(s=>cA(s,r))}function pq(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=lA(r);return pA(o.stdout).filter(i=>i.headRefName.toLowerCase().includes(s)||cA(i,r))}function ih(e,t,r,n){let o=r.trim();if(!o)return[];let s=dq(e,t,o,n),i=pq(e,t,o,n);return uq([...s,...i])}var Hu=p(()=>{"use strict";M()});function fq(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 ah(e){let t=dA(e.rows,e.canonicalPrUrl),r=[],n=[];for(let o of t){let s=fq(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 lh=p(()=>{"use strict";Hu()});function fA(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 mA=p(()=>{"use strict"});function mq(e){return e.gh(process.cwd(),["--version"]).status===0}function gq(e,t){return`AgentOS harness: ${e} (${t})`}function hq(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 uh(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function yq(e){return uh(e.prUrlHint)??ZE(e.status.finalResult)??uh(e.worker.taskPrUrl)??null}function kq(e){let{snapshot:t,canonical:r,workerName:n,exec:o}=e,s=!1,i=!1,a=t.headCommit??qn(t.worktreePath,o)??void 0;if(t.changedFiles.length>0){let l=va({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=iA({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=qn(t.worktreePath,o)??a}return{ok:!0,prUrl:r.url,headCommit:a,committed:s,pushed:i}}function ch(e){if(e.snapshot.changedFiles.length===0)return{ok:!0,prUrl:e.prUrl,headCommit:e.snapshot.headCommit??qn(e.snapshot.worktreePath,e.exec)??void 0};let t=va({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 dh(e,t=Ku){let r=yq(e),n=tA(e.status,{prUrl:r,headCommit:null}),o=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main";if(!eA({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?ch({snapshot:n,prUrl:r,commitMessage:`chore(harness): update PR handoff for ${e.worker.name}`,exec:t}):{ok:!0};if(r)return ch({snapshot:n,prUrl:r,commitMessage:`chore(harness): update PR handoff for ${e.worker.name}`,exec:t});if(!mq(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=sA(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??qn(n.worktreePath,t)??void 0;if(n.changedFiles.length>0){let R=va({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=uh(e.worker.taskId),c=[];if(l){c=ih(n.worktreePath,i,l,t);let b=uA(c);if(b){let _=kq({snapshot:n,canonical:b,workerName:e.worker.name,exec:t});return _.ok&&_.prUrl&&ah({worktreePath:n.worktreePath,repo:i,rows:c,canonicalPrUrl:_.prUrl,exec:t}),_}}let u=Fu(n.worktreePath,i,n.branch,t);if(u)return ch({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=va({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??qn(n.worktreePath,t)??void 0;let y=g?fA(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=aA({worktreePath:n.worktreePath,repo:i,branch:n.branch,base:v.replace(/^origin\//,""),title:gq(e.worker.name,e.worker.runId),body:hq(e.worker.taskId,e.worker.name,e.worker.runId),exec:t});if(!k.ok||!k.prUrl){if(XE(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:ih(n.worktreePath,i,l,t),{url:k.prUrl,number:Number.parseInt(k.prUrl.match(/\/pull\/(\d+)/)?.[1]??"",10)||0,headRefName:n.branch,createdAt:""}];ah({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 gA=p(()=>{"use strict";sh();Hu();lh();$u();mA()});var hA=p(()=>{"use strict";YE();sh();$u();Hu();lh();gA()});import bq from"node:path";function fh(e){clearInterval(ph.get(e)),ph.delete(e)}function mh(e,t){if(fh(e),!wa.has(e))return;let r=setInterval(()=>{(K(bq.join(e,"worker.json"),null)?.completionReportedAt||!te(t))&&vs(e)},1e3);r.unref(),ph.set(e,r)}function gh(e,t){fh(e);let r=wa.get(e);r&&r.close(),wa.set(e,t)}async function Yr(e){fh(e);let t=wa.get(e);return t?(wa.delete(e),await t.close(),!0):!1}function vs(e){Yr(e).catch(()=>{})}var wa,ph,hh=p(()=>{"use strict";M();wa=new Map,ph=new Map});import{appendFileSync as vq,existsSync as kA,mkdirSync as bA,readFileSync as Rq,rmSync as yA,writeFileSync as wq}from"node:fs";import Cr from"node:path";function RA(e){return Cr.join(e,vA)}function Sq(e){return le(e,["ls-files","--error-unmatch",vA.split(Cr.sep).join("/")],{allowFailure:!0}).trim().length>0}function _q(e){let t=le(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{bA(Cr.dirname(n),{recursive:!0});let s=kA(n)?Rq(n,"utf8"):"";if(s.split(/\r?\n/).some(i=>i.trim()===o))return;vq(n,`${s.endsWith(`
|
|
95
159
|
`)||!s?"":`
|
|
96
160
|
`}${o}
|
|
97
|
-
`)}catch{}}function
|
|
98
|
-
`,{mode:384}),
|
|
99
|
-
`)}function
|
|
161
|
+
`)}catch{}}function wA(e){if(Sq(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=RA(e.worktreePath);bA(Cr.dirname(t),{recursive:!0});let r={mcpServers:{[ge]:{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Tt]:e.brokerSocketPath}}}};return wq(t,`${JSON.stringify(r,null,2)}
|
|
162
|
+
`,{mode:384}),_q(e.worktreePath),{ok:!0,configPath:t}}function ju(e){let t=RA(e);if(!kA(t))return!1;try{yA(t,{force:!0});let r=Cr.dirname(t);return yA(r,{recursive:!1}),!0}catch{return!0}}var vA,yh=p(()=>{"use strict";Re();Sr();nt();vA=Cr.join(".cursor","mcp.json")});import{copyFileSync as xq,existsSync as Vu,mkdirSync as Cq,readFileSync as Eq,rmSync as Aq,symlinkSync as Pq,writeFileSync as Iq}from"node:fs";import{spawnSync as Oq}from"node:child_process";import{homedir as Tq}from"node:os";import zr from"node:path";function SA(e){return zr.join(e,Nq)}function Dq(e=process.env){let t=e.CODEX_HOME?.trim();if(t)return zr.resolve(t);let r=Tq();for(let n of[zr.join(r,".codex"),zr.join(r,".config","codex")])if(Vu(n))return n;return null}function Mq(e){return["","# Added per task by the Kynver harness. Carries a broker socket path, never a credential.",`[mcp_servers.${ge}]`,'command = "npx"','args = ["-y", "-p", "@kynver-app/mcp-agent-os", "kynver-worker-mcp"]',"",`[mcp_servers.${ge}.env]`,`${Tt} = ${JSON.stringify(e)}`,""].join(`
|
|
163
|
+
`)}function Lq(e){return new RegExp(String.raw`^\s*\[\s*mcp_servers\s*\.\s*"?${ge}"?\s*[\].]`,"m").test(e)}function _A(e){let t=Dq(e.env??process.env),r=t?zr.join(t,"config.toml"):null,n=r&&Vu(r)?Eq(r,"utf8"):"";if(n&&Lq(n))return{ok:!1,reason:"user_config_owns_server",detail:`the Codex config already declares an "${ge}" MCP server \u2014 refusing to write a duplicate stanza`};let o=SA(e.workerDir);Cq(o,{recursive:!0,mode:448});let s=!n||n.endsWith(`
|
|
100
164
|
`)?"":`
|
|
101
|
-
`;return
|
|
165
|
+
`;return Iq(zr.join(o,"config.toml"),`${n}${s}${Mq(e.brokerSocketPath)}`,{mode:384}),{ok:!0,codexHome:o,authMode:Bq(t,o)}}function Bq(e,t){let r=e?zr.join(e,"auth.json"):null;if(!r||!Vu(r))return"none";let n=zr.join(t,"auth.json");try{return Pq(r,n,"file"),"symlink"}catch{try{return xq(r,n),"copy"}catch{return"none"}}}function Sa(e){let t=SA(e);if(!Vu(t))return!1;try{return Aq(t,{recursive:!0,force:!0}),!0}catch{return!1}}function xA(e,t,r=1e4){try{let[n,o]=ie(t,["--version"]),s=Oq(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 Nq,kh=p(()=>{"use strict";Je();Sr();nt();Nq="codex-home"});import{appendFileSync as Wq,existsSync as bh,mkdirSync as EA,readFileSync as AA,rmSync as CA,writeFileSync as Uq}from"node:fs";import Er from"node:path";function IA(e){return Er.join(e,PA)}function Fq(e){return le(e,["ls-files","--error-unmatch",PA.split(Er.sep).join("/")],{allowFailure:!0}).trim().length>0}function Kq(e){if(!bh(e))return{};try{let t=JSON.parse(AA(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 $q(e){let t=le(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{EA(Er.dirname(n),{recursive:!0});let s=bh(n)?AA(n,"utf8"):"";if(s.split(/\r?\n/).some(i=>i.trim()===o))return;Wq(n,`${s.endsWith(`
|
|
102
166
|
`)||!s?"":`
|
|
103
167
|
`}${o}
|
|
104
|
-
`)}catch{}}function
|
|
105
|
-
`,{mode:384})
|
|
106
|
-
`,{mode:384}),{ok:!0,geminiCliHome:o,authMode:AJ(r,s)}}function AJ(e,t){let r=["oauth_creds.json","google_accounts.json"],n="none";for(let o of r){let s=Sr.join(e,o);if(!Wg(s))continue;let i=Sr.join(t,o);try{kJ(s,i,"file"),n==="none"&&(n="symlink")}catch{try{mJ(s,i),n="copy"}catch{}}}return n}function Eu(e){let t=cE(e);if(!Wg(t))return!1;try{return yJ(t,{recursive:!0,force:!0}),!0}catch{return!1}}var RJ,Fg=p(()=>{"use strict";kr();et();RJ="gemini-home"});import PJ from"node:path";function dE(e){return!!(typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim())}function OJ(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 Hr(e){let t=e.finalResult??null,r=typeof e.lastHeartbeatSummary=="string"?e.lastHeartbeatSummary:OJ(t);return{finalResult:t??r??"completed",summary:r}}function Au(e,t,r){if(dE(e)&&e.status==="done"&&e.completionSnapshot!=null)return;let n=new Date().toISOString(),o=Hr(t),s=r?.source?.trim();e.completionReportedAt=n,e.completionSnapshot=o,e.status="done",s&&(e.completionAckSource=s),ee(e.runId,e),e.workerDir&&(us(e.workerDir),Qc(e.workerDir),ca(e.workerDir),Eu(e.workerDir)),e.worktreePath&&(_u(e.worktreePath),Cu(e.worktreePath))}function TJ(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 pE(e,t){let r=TJ(t);if(r.size===0)return[];let n=ae(e),o=[];for(let s of Object.keys(n.workers||{})){let i=W(PJ.join(G(n.id),"workers",L(s),"worker.json"),void 0);if(!i?.taskId||dE(i))continue;let a=r.get(i.taskId);if(!a||a==="running"||!IJ.has(a))continue;let l=te(i,{base:n.base,baseCommit:n.baseCommit});Au(i,l,{source:`board-task-${a}`}),o.push({worker:s,taskId:i.taskId,taskStatus:a})}return o}var IJ,Pu=p(()=>{"use strict";z();Se();N();et();Dg();Mg();Lg();Ug();Fg();IJ=new Set(["awaiting_review","blocked","done","needs_input","waiting","scheduled","ready","cancelled","failed"])});function Iu(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 NJ(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 DJ(e){let t=ai(e);return t?{summary:t.reason,handoffState:"exit_failure",blocked:t.blocked}:null}function MJ(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 Ou(e){let{worker:t,status:r}=e;if(Iu(r.finalResult)){let u=De(t.heartbeatPath),d=nr(u),m=Iu(d)&&JSON.stringify(d)===JSON.stringify(r.finalResult)?"heartbeat_complete":"stdout_stream";return{finalResult:r.finalResult,source:m,snapshot:Hr(r)}}if(r.alive)return null;let n=_o(t.stdoutPath);if(Iu(n.finalResult)){let u={...r,finalResult:n.finalResult};return{finalResult:n.finalResult,source:"stdout_stream",snapshot:Hr(u)}}let o=De(t.heartbeatPath),s=nr(o);if(Iu(s)){let u={...r,finalResult:s,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:s,source:"heartbeat_complete",snapshot:Hr(u)}}let i=DJ(r.error??n.error);if(i){let u={...r,finalResult:i};return{finalResult:i,source:"exit_failure",snapshot:Hr(u)}}let a=NJ(o);if(a){let u={...r,finalResult:a,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:a,source:"heartbeat_summary",snapshot:Hr(u)}}let l=MJ({status:r,heartbeat:o}),c={...r,finalResult:l,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:l,source:"exit_no_final_result",snapshot:Hr(c)}}function Tu(e,t){return e.completionSnapshot?.finalResult!=null?!1:(e.completionSnapshot=t.snapshot,e.completionHandoffSource=t.source,!0)}var Kg=p(()=>{"use strict";cn();Zp();Pu();ii()});function Nu(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 fE(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 $g=p(()=>{"use strict"});function mE(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function gE(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function yE(e){let t=gE(e);if(!t)return[];let r=gE(t.worktreeHandoff),n=mE(r?.disposableArtifactsRemoved);return n.length?n:mE(t.disposableArtifactsRemoved)}function hE(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function kE(e,t){let r=Nu(e);if(r.length===0)return!0;if(t.length===0)return!1;let n=new Set(t.map(o=>hE(o)));return r.every(o=>{let s=hE(fE(o));return n.has(s)})}var bE=p(()=>{"use strict";$g()});function Du(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function vE(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function LJ(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 BJ(e){let t=vE(e.disposableArtifactsRemoved),r=yE(e.finalResult);return[...new Set([...t,...r])]}function RE(e){let t=vE(e.changedFiles),r=Nu(t),n=BJ(e),o=r.length===0||kE(t,n);return Du(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`}:Du(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`}:Du(e.artifactBundlePath)||Du(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}:LJ(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 wE=p(()=>{"use strict";bE();$g()});function _r(e=process.env){return mr(e).flags.dispatchReceipts}function Hg(e){return _r(e)!=="off"}function jg(e,t){return`dispatch:${e}:${t.taskId}:${t.leaseToken}`}function da(e,t,r){if(!Hg())return;let n=ce();if(n)try{n.recordOperationReceipt({idempotencyKey:jg(e,t),operation:`dispatch-${e}`,resultJson:r===void 0?null:JSON.stringify(r)})}catch{tt.storeFailures+=1}}function _E(e){da("claim",e,{runId:e.runId,workerName:e.workerName,provider:e.provider})}function Mu(e){da("spawned",e)}function ds(e,t){da("released",e,{reasonClass:t})}function xE(e){da("completion-sent",e)}function Vg(e,t){da("completion-acked",e,{outcome:t})}function CE(e){if(!Hg())return!1;let t=ce();if(!t)return!1;try{let r=t.getOperationReceipt(jg("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 tt.completionReplaysObserved+=1,!0}}catch{tt.storeFailures+=1}return!1}function Gg(e){let t=String(e??"").split(":")[0]?.trim()??"";return t.length>0?t.slice(0,64):"unknown"}function EE(e){if(_r()!=="enforce")return!1;let t=ce();if(!t)return!1;try{let r=t.getOperationReceipt(jg("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"?(tt.completionReplaysShortCircuited+=1,!0):!1}catch{return tt.storeFailures+=1,!1}}function AE(e,t){if(_r()!=="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{tt.storeFailures+=1}}function PE(e,t){if(_r()!=="enforce")return[];let r=ce();if(!r)return[];let n=t?.nowMs??Date.now(),o=t?.windowMs??UJ;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 tt.storeFailures+=1,[]}}function ua(e){let t=e.split(":")[0]??"",r=Number(t);return Number.isInteger(r)&&r>=0?r:null}function IE(e){let t={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!Hg())return t;let r=ce();if(!r)return t;let n=e?.nowMs??Date.now(),o=e?.strandedAfterMs??WJ;try{let s=r.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-SE).toISOString(),limit:KJ}),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>=FJ&&a.length+5<=$J&&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=ua(u.slice(g.length+1));if((g?r.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${g}:`,limit:10}):[]).some(v=>{if(h===null)return!0;let S=v.idempotencyKey.slice(`dispatch:completion-acked:${g}:`.length),_=ua(S);return _===null||_>=h}))continue;let k=!1;if(e?.hasLiveWorker&&c.resultJson)try{let v=JSON.parse(c.resultJson);v.runId&&v.workerName&&(k=e.hasLiveWorker({runId:v.runId,workerName:v.workerName}))}catch{k=!1}k||(i+=1)}let l=a.length>0?r.deleteOperationReceiptsByKeys(a):0;if(_r()==="enforce"){let c=r.listOperationReceipts({limit:100}).filter(u=>{let d=Date.parse(u.recordedAt);return Number.isFinite(d)&&n-d>=SE}).map(u=>u.idempotencyKey);if(c.length>0){let u=r.deleteOperationReceiptsByKeys(c);l+=u,tt.agedReceiptsPruned+=u}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:l}}catch{return tt.storeFailures+=1,t}}function OE(){return{"dispatchReceipts.storeFailures":tt.storeFailures,"dispatchReceipts.completionReplaysObserved":tt.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":tt.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":tt.agedReceiptsPruned}}var tt,UJ,WJ,SE,FJ,KJ,$J,ps=p(()=>{"use strict";Wr();Xo();tt={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};UJ=600*1e3;WJ=900*1e3,SE=10080*60*1e3,FJ=1440*60*1e3,KJ=500,$J=300});function TE(){qg=!1}function xr(e=process.env){return mr(e).flags.admission}function Lu(e,t){return`${Jg}${e}:${t}`}function NE(e,t){if(xr()==="off")return;let r=ce();if(r)try{r.tryReserveAdmission(Lu(e,t),Yg,fs)}catch{jr.storeFailures+=1}}function pa(e,t){if(xr()==="off")return;let r=ce();if(r)try{r.releaseAdmission(Lu(e,t),Yg)}catch{jr.storeFailures+=1}}function DE(e){let t={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(xr()==="off")return t;let r=ce();if(!r)return t;try{let n=new Set(e.liveWorkers.map(m=>Lu(m.runId,m.workerName))),o=r.listAdmissionReservations({keyPrefix:Jg,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=!qg;qg=!0,!l&&i>0&&(jr.missingForLive+=i);let c=0;for(let m of e.liveWorkers)r.tryReserveAdmission(Lu(m.runId,m.workerName),Yg,fs),c+=1;let u=0;for(let m of o)n.has(m.key)||r.releaseAdmission(m.key,m.owner)&&(u+=1,jr.deadSlotsReleased+=1);return{liveReservations:r.listAdmissionReservations({keyPrefix:Jg,limit:500}).length,refreshed:c,deadReleased:u,missingForLive:i,orphaned:a,adoptionPass:l}}catch{return jr.storeFailures+=1,t}}function ME(){return{"admission.storeFailures":jr.storeFailures,"admission.missingForLive":jr.missingForLive,"admission.deadSlotsReleased":jr.deadSlotsReleased}}var fs,Yg,Jg,jr,qg,Fn=p(()=>{"use strict";Wr();Xo();fs=900*1e3,Yg="admission-shadow",Jg="worker-slot:",jr={storeFailures:0,missingForLive:0,deadSlotsReleased:0},qg=!1});function LE(e){return`${zg}${e}`}function Uu(e,t){return`${e}:${t}`}function BE(e){if(xr()!=="enforce")return{admitted:!0};let t=ce();if(!t)return{admitted:!0};let r=Math.max(0,Math.min(Bu,Math.floor(e.maxSlots)));if(e.diskActiveWorkers>=r)return Vr.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=Uu(e.runId,e.workerName);for(let o=0;o<r;o+=1)if(t.tryReserveAdmission(LE(o),n,fs).acquired)return{admitted:!0,slot:o};return Vr.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return Vr.enforceStoreFailures+=1,{admitted:!0}}}function Gr(e,t){if(xr()==="off")return;let r=ce();if(r)try{let n=Uu(e,t),o=r.listAdmissionReservations({keyPrefix:zg,limit:Bu});for(let s of o)s.owner===n&&r.releaseAdmission(s.key,n)}catch{Vr.enforceStoreFailures+=1}}function UE(e){let t={refreshed:0,deadReleased:0,adopted:0};if(xr()!=="enforce")return t;let r=ce();if(!r)return t;try{let n=new Set(e.liveWorkers.map(c=>Uu(c.runId,c.workerName))),o=r.listAdmissionReservations({keyPrefix:zg,limit:Bu}),s=0,i=0,a=new Set;for(let c of o)n.has(c.owner)?(r.tryReserveAdmission(c.key,c.owner,fs),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=Uu(c.runId,c.workerName);if(!a.has(u)){for(let d=0;d<Bu;d+=1)if(r.tryReserveAdmission(LE(d),u,fs).acquired){l+=1;break}}}return{refreshed:s,deadReleased:i,adopted:l}}catch{return Vr.enforceStoreFailures+=1,t}}function WE(){return{"admission.enforceStoreFailures":Vr.enforceStoreFailures,"admission.refusedSlotsExhausted":Vr.admissionsRefusedSlots,"admission.refusedDiskBackstop":Vr.admissionsRefusedDiskBackstop}}var zg,Bu,Vr,ms=p(()=>{"use strict";Wr();Fn();zg="worker-slot-n:",Bu=64;Vr={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0}});import HJ from"node:path";function Xg(e){let t=e.trim();if(!jJ.test(t))throw new Error(`invalid run id: ${e}`);return t}function GJ(e){let t=e.trim();if(!VJ.test(t))throw new Error(`invalid worker name: ${e}`);return t}function $E(e){return typeof e=="string"?e.trim():""}function Wu(e){let t=$E(e.run),r=$E(e.name);return(!t||FE.has(t))&&nt(`missing --run RUN_ID (${KE})`),(!r||FE.has(r))&&nt(`missing --name WORKER_NAME (${KE})`),{runId:Xg(t),workerName:GJ(r)}}function HE(e){let t=HJ.resolve(e);if(t.includes(".."))throw new Error("repo path must not contain .. segments");return t}var jJ,VJ,FE,KE,Fu=p(()=>{"use strict";N();jJ=/^[a-z0-9][a-z0-9._-]{0,127}$/i,VJ=/^[a-z0-9][a-z0-9._-]{0,63}$/i,FE=new Set(["undefined","null"]),KE="usage: kynver worker <action> --run RUN_ID --name WORKER_NAME"});import{existsSync as JJ,mkdirSync as qJ,readFileSync as YJ,writeFileSync as zJ}from"node:fs";import{homedir as XJ}from"node:os";import jE from"node:path";function rq(e){let t=e?.trim();return!!(t&&QJ.test(t))}function nq(){let e=(process.env.KYNVER_PROVIDER_QUOTA_PREFLIGHT??"on").trim().toLowerCase();return e!=="off"&&e!=="0"&&e!=="false"&&e!=="no"}function Qg(){let e=Number.parseInt(process.env.KYNVER_PROVIDER_QUOTA_COOLDOWN_MINUTES??"",10);return Number.isFinite(e)?Math.min(tq,Math.max(eq,e)):ZJ}function VE(){let e=process.env.KYNVER_PROVIDER_QUOTA_STORE_PATH?.trim();return e||jE.join(XJ(),".kynver","provider-quota-cooldowns.json")}function fa(e){return(e??"").trim().toLowerCase()}function Zg(){let e=VE();if(!JJ(e))return{};try{let t=JSON.parse(YJ(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[fa(n)]={lastExhaustedAt:s,reason:typeof i=="string"?i.slice(0,500):""})}return r}catch{return{}}}function eh(e){let t=VE();try{qJ(jE.dirname(t),{recursive:!0}),zJ(t,`${JSON.stringify(e,null,2)}
|
|
107
|
-
`,"utf8")}catch{}}function oq(e,t,r=Date.now()){let n=fa(e);if(!n)return;let o=Zg();o[n]={lastExhaustedAt:new Date(r).toISOString(),reason:t.trim().slice(0,500)},eh(o),SS(n,Qg()*6e4)}function sq(e){let t=fa(e);if(!t)return!1;_S(t);let r=Zg();return t in r?(delete r[t],eh(r),!0):!1}function GE(e,t=Date.now()){if(!nq())return{ok:!0};let r=fa(e);if(!r)return{ok:!0};let n=Zg(),o=n[r],s=!!(o&&Number.isFinite(Date.parse(o.lastExhaustedAt))&&Date.parse(o.lastExhaustedAt)+Qg()*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+Qg()*6e4;if(!Number.isFinite(a)||l<=t)return delete n[r],eh(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 iq(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 JE(e){let t=fa(e.provider);if(!t)return"none";let r=iq(e.finalResult)??(typeof e.error=="string"&&e.error.trim()?e.error.trim():null);return r?rq(r)?(oq(t,r,e.nowMs??Date.now()),"recorded"):sq(t)?"cleared":"none":"none"}var QJ,ZJ,eq,tq,th=p(()=>{"use strict";Ti();QJ=/\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,ZJ=30,eq=5,tq=240});function qE(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 YE=p(()=>{"use strict"});import $u from"node:path";async function zE(e,t,r){let n=await fetch(e,{method:"POST",headers:xt(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 lq(e){if(e&&typeof e=="object"){let t=e.error;if(typeof t=="string"&&t.trim())return t.trim()}}function XE(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ma(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function cq(e){return e.completionBlocker?`blocked:${e.completionBlocker}`:e.completionOutcome?e.completionOutcome:e.completionReportedAt?"completion_acknowledged":e.finished?"worker_finished":"in_progress"}function uq(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 ZE(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function dq(e){return e.prUrl?"pr_handoff":e.headCommit?"commit_handoff":e.changedFiles.length>0?"dirty_worktree":"none"}function gs(e,t){(e.completionBlocker??void 0)!==(t??void 0)&&(t?e.completionBlocker=t:delete e.completionBlocker,ee(e.runId,e))}function pq(e){e.completionBlocker&&(delete e.completionBlocker,ee(e.runId,e))}function Ku(e){return e?{base:e.base,baseCommit:e.baseCommit}:{}}function fq(e,t){return{...e,...t.prUrl?{prUrl:t.prUrl}:{},...t.headCommit?{headCommit:t.headCommit}:{}}}async function Hu(e){let{runId:t,workerName:r}=Wu(e),n=vn(t,r),o=ae(n.runId),s=te(n,Ku(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&&oa(n))return{ok:!0,skipped:!0,reason:"completion-already-acknowledged",httpStatus:200};if(!l&&bg(n)&&pq(n),!s.finalResult&&s.alive===!1){let R=Ou({worker:n,status:s});R&&Tu(n,R)&&(ee(n.runId,n),n=vn(t,r),s=te(n,Ku(o)))}if(!(e.skipPrHandoff===!0||e.skipPrHandoff==="true")&&!n.steerRestartRequired&&n.dispatched&&a){let R=Pg({worker:n,run:o,status:s});if(!R.ok)return gs(n,R.reason),{ok:!1,reason:R.reason,nextAction:R.nextAction,completionBlocked:!0};(R.prUrl||R.headCommit)&&(s=te(n,Ku(o)),s=fq(s,R))}let u=s.gitAncestry.headIsAncestorOfBase===!1&&s.gitAncestry.head?s.gitAncestry.head:s.headCommit;if(n.dispatched&&!n.steerRestartRequired){let R=RE({changedFiles:s.changedFiles,finalResult:s.finalResult,prUrl:s.prUrl,headCommit:u,disposableArtifactsRemoved:n.disposableArtifactsRemoved});if(!R.allowed){let M=R.detail??`worktree completion blocked (${R.state})`;return gs(n,M),{ok:!1,reason:M,nextAction:"Clean the worktree (commit, open a PR, or `kynver worker discard-disposable --path <file>`), then rerun `kynver worker complete`.",completionBlocked:!0}}}try{JE({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 pu({worker:n,agentOsId:i,baseUrl:d,secret:f}),n=vn(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=qE({usage:s.usage,provider:n.provider??s.provider??null,model:typeof n.model=="string"?n.model:s.model??null}),b={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(CE(k),EE(k)){let R={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:{replayShortCircuited:!0}};return hu(n,n.runId,R),Au(n,s,{source:"harness-completion"}),gs(n,void 0),pa(n.runId,n.name),Gr(n.runId,n.name),{ok:!0,httpStatus:200,response:{ok:!0,replayShortCircuited:!0},reason:"completion_replay_short_circuited",...s.prUrl?{prHandoff:{prUrl:s.prUrl}}:{}}}xE(k)}let v=await zE(g,f,b);if((v.status===401||v.status===403)&&!m){let R=await HR(i,{baseUrl:d});R&&R!==f&&(f=R,v=await zE(g,f,b))}if(v.ok){let R=SC(v.parsed);if(!_C(R)){let B=`completion acknowledged but board not advanced: ${R.detail??(R.routeOutcome?`harness completion returned ${R.routeOutcome}`:"harness completion did not advance the linked task")}`;gs(n,B);let D={completionReportedAt:new Date().toISOString(),completionOutcome:"rejected",completionResponse:v.parsed};return hu(n,n.runId,D),k&&Vg(k,"rejected"),{ok:!1,httpStatus:v.status,response:v.parsed,reason:B,completionBlocked:!0}}gs(n,void 0);let M=R.routeOutcome??"acknowledged",A={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:v.parsed};hu(n,n.runId,A),Au(n,s,{source:"harness-completion"}),k&&Vg(k,"acknowledged"),pa(n.runId,n.name),Gr(n.runId,n.name);let C=s.prUrl;return{ok:!0,httpStatus:v.status,response:v.parsed,reason:M,...C?{prHandoff:{prUrl:C}}:{}}}let S=v.status===401||v.status===403,_=lq(v.parsed)??(S?"runner token unauthorized":"non-2xx response"),w=S?`completion replay rejected (${v.status}): ${_}`:`completion replay failed (${v.status}): ${_}`;return gs(n,w),{ok:!1,httpStatus:v.status,response:v.parsed,completionBlocked:!0}}async function eA(e){try{let{runId:t,workerName:r}=Wu(e),n=vn(t,r),o=ae(n.runId),s=te(n,Ku(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 Hu(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 tA(e){let{run:t,workerName:r,worker:n}=e,o=te(n,{base:t.base,baseCommit:t.baseCommit}),s=o.gitAncestry.headIsAncestorOfBase===!1&&o.gitAncestry.head?o.gitAncestry.head:void 0,i=xo({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=ZE(l)?void 0:l,u=c?"blocked":o.status,d=c?"blocked":o.attention.state,m=XE(n.completionResponse),f=XE(m?.task),g=ma(m?.outcome),h=ma(m?.status),y=Array.isArray(m?.warnings)?m.warnings.filter(w=>typeof w=="string"&&w.trim().length>0):[],b=ma(f?.prUrl)??ma(m?.prUrl),k=ma(n.completionReportedAt),v=cq({finished:Me(o),completionBlocker:c,completionOutcome:g,completionReportedAt:k}),S=uq({completionBlocker:c,completionOutcome:g,completionReportedAt:k,finished:Me(o)}),_=dq({changedFiles:o.changedFiles,headCommit:s,prUrl:b??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 w=n.instructionPolicyEvidence;if(!w||typeof w!="object")return null;let R=w.ruleSlugs;return Array.isArray(R)?R.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:b,handoffState:_,gitAncestry:o.gitAncestry,finalResult:o.finalResult,lifecycleStage:v,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:S,ancestry:o.gitAncestry.relation,ancestryChecked:o.gitAncestry.checked}}function mq(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&&!ZE(r)?!1:typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim()||e.completionOutcome==="acknowledged"?!0:t==="done"}function gq(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 ga(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 QE(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 hq(e){let t=e.filter(QE),r=e.filter(n=>{if(QE(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 rA(e,t,r){let n={runId:e.id,name:e.name,status:Bl(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:ga(t,"status"),attentionCounts:ga(t,"attention"),lifecycleCounts:ga(t,"lifecycleStage")},n.controller=hq(t)),n}function yq(e){return e.status==="done"&&e.attention==="done"}function rh(e){let t=ae(e),n=Object.keys(t.workers||{}).map(s=>{let i=W($u.join(G(t.id),"workers",L(s),"worker.json"),void 0);return i?tA({run:t,workerName:s,worker:i}):{worker:s,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=rA(t,n,!1);return ye($u.join(G(t.id),"last-board.json"),o),o}function nh(e){let t=ae(e),n=Object.keys(t.workers||{}).map(i=>{let a=W($u.join(G(t.id),"workers",L(i),"worker.json"),void 0);return a?mq(a)?gq(i,a):tA({run:t,workerName:i,worker:a}):{worker:i,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=n.filter(i=>!yq(i)),s=rA(t,o,!0);return s.status=Bl(t.status,n),s.summary={...s.summary??{},totalWorkerCount:n.length,shownWorkerCount:o.length,omittedTerminalDoneWorkerCount:n.length-o.length,allStatusCounts:ga(n,"status"),allAttentionCounts:ga(n,"attention")},ye($u.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=rh(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 hs=p(()=>{"use strict";K();zo();xC();Ue();z();Nl();JC();Se();Kg();ii();wE();kg();yu();ps();Fn();ms();Pu();N();Fu();mg();th();YE()});var oA=p(()=>{"use strict";Ue();z();N()});import{spawn as kq}from"node:child_process";import{existsSync as bq,openSync as vq,closeSync as sA}from"node:fs";import Rq from"node:path";function iA(e){let t=e.nodeExecutable??process.execPath,r=tu({importMetaUrl:import.meta.url,explicitCliPath:e.cliPath,nodeExecutable:t});if(!r)return;let n=r.cliPath;if(!bq(n))return;let o=Rq.join(e.workerDir,"auto-complete.log"),s;try{s=vq(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=kq(r.command,a,X({detached:be(),stdio:i,env:process.env}));return s!==void 0&&sA(s),l.unref(),{pid:l.pid,logPath:o,cliPath:n}}catch{if(s!==void 0)try{sA(s)}catch{}return}}var $ge,aA=p(()=>{"use strict";N();yu();z();Se();hs();N();Fu();ig();K();oA();$ge=360*60*1e3});var lA=p(()=>{"use strict"});function cA(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 uA=p(()=>{"use strict";ve()});import{createHash as wq}from"node:crypto";import{chmodSync as Sq,mkdirSync as _q}from"node:fs";import dA from"node:os";import xq from"node:path";function pA(e,t){return wq("sha256").update(e).digest("hex").slice(0,t)}function oh(e){let t=e.platform??process.platform,r=pA(e.agentOsId,12),n=pA(e.workerKey,16);if(t==="win32")return{socketPath:`${Eq}kynver-worker-${r}-${n}`,socketDir:null,isNamedPipe:!0,relocated:!1};let o=xq.posix,s=e.homeDir??dA.homedir(),i=o.join(s,".kynver","brokers",r),a=o.join(i,`${n}.sock`);if(Buffer.byteLength(a,"utf8")<=Cq)return{socketPath:a,socketDir:i,isNamedPipe:!1,relocated:!1};let l=o.join(e.tmpDir??dA.tmpdir(),`kynver-brokers-${r}`);return{socketPath:o.join(l,`${n}.sock`),socketDir:l,isNamedPipe:!1,relocated:!0}}function sh(e){e.socketDir&&(_q(e.socketDir,{recursive:!0,mode:448}),Sq(e.socketDir,448))}var Cq,Eq,ih=p(()=>{"use strict";Cq=100,Eq="\\\\.\\pipe\\"});import Aq from"node:net";import{chmodSync as Pq,unlinkSync as Iq}from"node:fs";var ha,hA=p(()=>{"use strict";kr();nu();ih();et();ha=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=Vi(t.capabilities),this.server=Aq.createServer(r=>{this.handleConnection(r)}),this.server.on("error",()=>{})}static async start(t){let r=new e(t);if(sh(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{Pq(t.address.socketPath,384)}catch{}return r}get identitySummary(){return this.opts.identity.summary}get toolDescriptors(){return this.grantedTools.filter(ls).map(t=>zi[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{Iq(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 OA(e){if(Fq(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=IA(e.worktreePath),r=Kq(t);if(ge in r)return{ok:!1,reason:"user_config_owns_server",detail:`the workspace MCP config already declares an "${ge}" server \u2014 refusing to overwrite it`};EA(Er.dirname(t),{recursive:!0});let n={mcpServers:{...r,[ge]:{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Tt]:e.brokerSocketPath}}}};return Uq(t,`${JSON.stringify(n,null,2)}
|
|
169
|
+
`,{mode:384}),$q(e.worktreePath),{ok:!0,configPath:t}}function Gu(e){let t=IA(e);if(!bh(t))return!1;try{return CA(t,{force:!0}),CA(Er.dirname(t),{recursive:!1}),!0}catch{return!0}}var PA,vh=p(()=>{"use strict";Re();Sr();nt();PA=Er.join(".agents","mcp_config.json")});import{copyFileSync as Hq,existsSync as Rh,mkdirSync as jq,readFileSync as Vq,rmSync as Gq,symlinkSync as Jq,writeFileSync as qq}from"node:fs";import{homedir as Yq}from"node:os";import Ar from"node:path";function TA(e){return Ar.join(e,zq)}function Xq(e){return e.HOME?.trim()||e.USERPROFILE?.trim()||Yq()}function Qq(e=process.env){let t=e.GEMINI_CLI_HOME?.trim();return t?Ar.join(Ar.resolve(t),".gemini"):Ar.join(Xq(e),".gemini")}function Zq(e){if(!Rh(e))return{};try{let t=JSON.parse(Vq(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function eY(e){let t=e.mcpServers;return!t||typeof t!="object"||Array.isArray(t)?!1:ge in t}function tY(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function rY(e){return{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Tt]:e},trust:!0}}function NA(e){let t=e.env??process.env,r=Qq(t),n=Zq(Ar.join(r,"settings.json"));if(eY(n))return{ok:!1,reason:"user_config_owns_server",detail:`the Gemini CLI settings already declare an "${ge}" MCP server \u2014 refusing to write a duplicate stanza`};let o=TA(e.workerDir),s=Ar.join(o,".gemini");jq(s,{recursive:!0,mode:448});let i=n.mcpServers&&typeof n.mcpServers=="object"&&!Array.isArray(n.mcpServers)?n.mcpServers:{},a={...n,mcp:{...tY(n.mcp),autoAllowInHeadless:!0},mcpServers:{...i,[ge]:rY(e.brokerSocketPath)}};return qq(Ar.join(s,"settings.json"),`${JSON.stringify(a,null,2)}
|
|
170
|
+
`,{mode:384}),{ok:!0,geminiCliHome:o,authMode:nY(r,s)}}function nY(e,t){let r=["oauth_creds.json","google_accounts.json"],n="none";for(let o of r){let s=Ar.join(e,o);if(!Rh(s))continue;let i=Ar.join(t,o);try{Jq(s,i,"file"),n==="none"&&(n="symlink")}catch{try{Hq(s,i),n="copy"}catch{}}}return n}function Ju(e){let t=TA(e);if(!Rh(t))return!1;try{return Gq(t,{recursive:!0,force:!0}),!0}catch{return!1}}var zq,wh=p(()=>{"use strict";Sr();nt();zq="gemini-home"});import oY from"node:path";function DA(e){return!!(typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim())}function iY(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:iY(t);return{finalResult:t??r??"completed",summary:r}}function qu(e,t,r){if(DA(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&&(vs(e.workerDir),yu(e.workerDir),Sa(e.workerDir),Ju(e.workerDir)),e.worktreePath&&(ju(e.worktreePath),Gu(e.worktreePath))}function aY(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 MA(e,t,r={}){let n=aY(t);if(n.size===0)return[];let o=re(e),s=[];for(let i of Object.keys(o.workers||{})){let a=K(oY.join(V(o.id),"workers",B(i),"worker.json"),void 0);if(!a?.taskId||DA(a))continue;let l=n.get(a.taskId);if(!l||l==="running"||!sY.has(l))continue;let c=se(a,{base:o.base,baseCommit:o.baseCommit}),u;if(l==="cancelled"){let d=Qg(o.id,a,"board_task_cancelled","board task cancelled",r);u=!!(d.workerSignal||d.sidecarSignal)}qu(a,c,{source:`board-task-${l}`}),s.push({worker:i,taskId:a.taskId,taskStatus:l,...u?{stopped:u}:{}})}return s}var sY,Yu=p(()=>{"use strict";Y();xe();M();nt();hh();yh();kh();vh();wh();bs();sY=new Set(["awaiting_review","blocked","done","needs_input","waiting","scheduled","ready","cancelled","failed"])});function zu(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 lY(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 cY(e){let t=Ri(e);return t?{summary:t.reason,handoffState:"exit_failure",blocked:t.blocked}:null}function uY(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 Xu(e){let{worker:t,status:r}=e;if(zu(r.finalResult)){let u=Ae(t.heartbeatPath),d=ar(u),f=zu(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=vn(t.stdoutPath);if(zu(n.finalResult)){let u={...r,finalResult:n.finalResult};return{finalResult:n.finalResult,source:"stdout_stream",snapshot:Xr(u)}}let o=Ae(t.heartbeatPath),s=ar(o);if(zu(s)){let u={...r,finalResult:s,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:s,source:"heartbeat_complete",snapshot:Xr(u)}}let i=cY(r.error??n.error);if(i){let u={...r,finalResult:i};return{finalResult:i,source:"exit_failure",snapshot:Xr(u)}}let a=lY(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=uY({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 Qu(e,t){return e.completionSnapshot?.finalResult!=null?!1:(e.completionSnapshot=t.snapshot,e.completionHandoffSource=t.source,!0)}var Sh=p(()=>{"use strict";bn();Nf();Yu();vi()});function Zu(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 LA(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 _h=p(()=>{"use strict"});function BA(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function WA(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function FA(e){let t=WA(e);if(!t)return[];let r=WA(t.worktreeHandoff),n=BA(r?.disposableArtifactsRemoved);return n.length?n:BA(t.disposableArtifactsRemoved)}function UA(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function KA(e,t){let r=Zu(e);if(r.length===0)return!0;if(t.length===0)return!1;let n=new Set(t.map(o=>UA(o)));return r.every(o=>{let s=UA(LA(o));return n.has(s)})}var $A=p(()=>{"use strict";_h()});function ed(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function HA(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function dY(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 pY(e){let t=HA(e.disposableArtifactsRemoved),r=FA(e.finalResult);return[...new Set([...t,...r])]}function jA(e){let t=HA(e.changedFiles),r=Zu(t),n=pY(e),o=r.length===0||KA(t,n);return ed(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`}:ed(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`}:ed(e.artifactBundlePath)||ed(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}:dY(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 VA=p(()=>{"use strict";$A();_h()});function Pr(e=process.env){return br(e).flags.dispatchReceipts}function xh(e){return Pr(e)!=="off"}function Ch(e,t){return`dispatch:${e}:${t.taskId}:${t.leaseToken}`}function xa(e,t,r){if(!xh())return;let n=ce();if(n)try{n.recordOperationReceipt({idempotencyKey:Ch(e,t),operation:`dispatch-${e}`,resultJson:r===void 0?null:JSON.stringify(r)})}catch{ot.storeFailures+=1}}function JA(e){xa("claim",e,{runId:e.runId,workerName:e.workerName,provider:e.provider})}function td(e){xa("spawned",e)}function Rs(e,t){xa("released",e,{reasonClass:t})}function qA(e){xa("completion-sent",e)}function Eh(e,t){xa("completion-acked",e,{outcome:t})}function YA(e){if(!xh())return!1;let t=ce();if(!t)return!1;try{let r=t.getOperationReceipt(Ch("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 ot.completionReplaysObserved+=1,!0}}catch{ot.storeFailures+=1}return!1}function Ah(e){let t=String(e??"").split(":")[0]?.trim()??"";return t.length>0?t.slice(0,64):"unknown"}function zA(e){if(Pr()!=="enforce")return!1;let t=ce();if(!t)return!1;try{let r=t.getOperationReceipt(Ch("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"?(ot.completionReplaysShortCircuited+=1,!0):!1}catch{return ot.storeFailures+=1,!1}}function XA(e,t){if(Pr()!=="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{ot.storeFailures+=1}}function QA(e,t){if(Pr()!=="enforce")return[];let r=ce();if(!r)return[];let n=t?.nowMs??Date.now(),o=t?.windowMs??fY;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 ot.storeFailures+=1,[]}}function _a(e){let t=e.split(":")[0]??"",r=Number(t);return Number.isInteger(r)&&r>=0?r:null}function ZA(e){let t={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!xh())return t;let r=ce();if(!r)return t;let n=e?.nowMs??Date.now(),o=e?.strandedAfterMs??mY;try{let s=r.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-GA).toISOString(),limit:hY}),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>=gY&&a.length+5<=yY&&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=_a(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=_a(_);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>=GA}).map(u=>u.idempotencyKey);if(c.length>0){let u=r.deleteOperationReceiptsByKeys(c);l+=u,ot.agedReceiptsPruned+=u}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:l}}catch{return ot.storeFailures+=1,t}}function eP(){return{"dispatchReceipts.storeFailures":ot.storeFailures,"dispatchReceipts.completionReplaysObserved":ot.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":ot.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":ot.agedReceiptsPruned}}var ot,fY,mY,GA,gY,hY,yY,ws=p(()=>{"use strict";Jr();is();ot={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};fY=600*1e3;mY=900*1e3,GA=10080*60*1e3,gY=1440*60*1e3,hY=500,yY=300});function tP(){Ih=!1}function Ir(e=process.env){return br(e).flags.admission}function rd(e,t){return`${Ph}${e}:${t}`}function rP(e,t){if(Ir()==="off")return;let r=ce();if(r)try{r.tryReserveAdmission(rd(e,t),Oh,Ss)}catch{Qr.storeFailures+=1}}function Ca(e,t){if(Ir()==="off")return;let r=ce();if(r)try{r.releaseAdmission(rd(e,t),Oh)}catch{Qr.storeFailures+=1}}function nP(e){let t={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(Ir()==="off")return t;let r=ce();if(!r)return t;try{let n=new Set(e.liveWorkers.map(f=>rd(f.runId,f.workerName))),o=r.listAdmissionReservations({keyPrefix:Ph,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=!Ih;Ih=!0,!l&&i>0&&(Qr.missingForLive+=i);let c=0;for(let f of e.liveWorkers)r.tryReserveAdmission(rd(f.runId,f.workerName),Oh,Ss),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:Ph,limit:500}).length,refreshed:c,deadReleased:u,missingForLive:i,orphaned:a,adoptionPass:l}}catch{return Qr.storeFailures+=1,t}}function oP(){return{"admission.storeFailures":Qr.storeFailures,"admission.missingForLive":Qr.missingForLive,"admission.deadSlotsReleased":Qr.deadSlotsReleased}}var Ss,Oh,Ph,Qr,Ih,Yn=p(()=>{"use strict";Jr();is();Ss=900*1e3,Oh="admission-shadow",Ph="worker-slot:",Qr={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Ih=!1});function sP(e){return`${Th}${e}`}function od(e,t){return`${e}:${t}`}function iP(e){if(Ir()!=="enforce")return{admitted:!0};let t=ce();if(!t)return{admitted:!0};let r=Math.max(0,Math.min(nd,Math.floor(e.maxSlots)));if(e.diskActiveWorkers>=r)return Zr.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=od(e.runId,e.workerName);for(let o=0;o<r;o+=1)if(t.tryReserveAdmission(sP(o),n,Ss).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=ce();if(r)try{let n=od(e,t),o=r.listAdmissionReservations({keyPrefix:Th,limit:nd});for(let s of o)s.owner===n&&r.releaseAdmission(s.key,n)}catch{Zr.enforceStoreFailures+=1}}function aP(e){let t={refreshed:0,deadReleased:0,adopted:0};if(Ir()!=="enforce")return t;let r=ce();if(!r)return t;try{let n=new Set(e.liveWorkers.map(c=>od(c.runId,c.workerName))),o=r.listAdmissionReservations({keyPrefix:Th,limit:nd}),s=0,i=0,a=new Set;for(let c of o)n.has(c.owner)?(r.tryReserveAdmission(c.key,c.owner,Ss),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=od(c.runId,c.workerName);if(!a.has(u)){for(let d=0;d<nd;d+=1)if(r.tryReserveAdmission(sP(d),u,Ss).acquired){l+=1;break}}}return{refreshed:s,deadReleased:i,adopted:l}}catch{return Zr.enforceStoreFailures+=1,t}}function lP(){return{"admission.enforceStoreFailures":Zr.enforceStoreFailures,"admission.refusedSlotsExhausted":Zr.admissionsRefusedSlots,"admission.refusedDiskBackstop":Zr.admissionsRefusedDiskBackstop}}var Th,nd,Zr,_s=p(()=>{"use strict";Jr();Yn();Th="worker-slot-n:",nd=64;Zr={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0}});import kY from"node:path";function Nh(e){let t=e.trim();if(!bY.test(t))throw new Error(`invalid run id: ${e}`);return t}function RY(e){let t=e.trim();if(!vY.test(t))throw new Error(`invalid worker name: ${e}`);return t}function dP(e){return typeof e=="string"?e.trim():""}function sd(e){let t=dP(e.run),r=dP(e.name);return(!t||cP.has(t))&&at(`missing --run RUN_ID (${uP})`),(!r||cP.has(r))&&at(`missing --name WORKER_NAME (${uP})`),{runId:Nh(t),workerName:RY(r)}}function pP(e){let t=kY.resolve(e);if(t.includes(".."))throw new Error("repo path must not contain .. segments");return t}var bY,vY,cP,uP,id=p(()=>{"use strict";M();bY=/^[a-z0-9][a-z0-9._-]{0,127}$/i,vY=/^[a-z0-9][a-z0-9._-]{0,63}$/i,cP=new Set(["undefined","null"]),uP="usage: kynver worker <action> --run RUN_ID --name WORKER_NAME"});import{existsSync as wY,mkdirSync as SY,readFileSync as _Y,writeFileSync as xY}from"node:fs";import{homedir as CY}from"node:os";import fP from"node:path";function OY(e){let t=e?.trim();return!!(t&&EY.test(t))}function TY(){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(IY,Math.max(PY,e)):AY}function mP(){let e=process.env.KYNVER_PROVIDER_QUOTA_STORE_PATH?.trim();return e||fP.join(CY(),".kynver","provider-quota-cooldowns.json")}function Ea(e){return(e??"").trim().toLowerCase()}function Mh(){let e=mP();if(!wY(e))return{};try{let t=JSON.parse(_Y(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[Ea(n)]={lastExhaustedAt:s,reason:typeof i=="string"?i.slice(0,500):""})}return r}catch{return{}}}function Lh(e){let t=mP();try{SY(fP.dirname(t),{recursive:!0}),xY(t,`${JSON.stringify(e,null,2)}
|
|
171
|
+
`,"utf8")}catch{}}function NY(e,t,r=Date.now()){let n=Ea(e);if(!n)return;let o=Mh();o[n]={lastExhaustedAt:new Date(r).toISOString(),reason:t.trim().slice(0,500)},Lh(o),B_(n,Dh()*6e4)}function DY(e){let t=Ea(e);if(!t)return!1;W_(t);let r=Mh();return t in r?(delete r[t],Lh(r),!0):!1}function gP(e,t=Date.now()){if(!TY())return{ok:!0};let r=Ea(e);if(!r)return{ok:!0};let n=Mh(),o=n[r],s=!!(o&&Number.isFinite(Date.parse(o.lastExhaustedAt))&&Date.parse(o.lastExhaustedAt)+Dh()*6e4>t),i=U_(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],Lh(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 MY(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 hP(e){let t=Ea(e.provider);if(!t)return"none";let r=MY(e.finalResult)??(typeof e.error=="string"&&e.error.trim()?e.error.trim():null);return r?OY(r)?(NY(t,r,e.nowMs??Date.now()),"recorded"):DY(t)?"cleared":"none":"none"}var EY,AY,PY,IY,Bh=p(()=>{"use strict";Vi();EY=/\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,AY=30,PY=5,IY=240});function yP(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 kP=p(()=>{"use strict"});import ld from"node:path";async function bP(e,t,r){let n=await fetch(e,{method:"POST",headers:Pt(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 LY(e){if(e&&typeof e=="object"){let t=e.error;if(typeof t=="string"&&t.trim())return t.trim()}}function vP(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Aa(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function BY(e){return e.completionBlocker?`blocked:${e.completionBlocker}`:e.completionOutcome?e.completionOutcome:e.completionReportedAt?"completion_acknowledged":e.finished?"worker_finished":"in_progress"}function WY(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 wP(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function UY(e){return e.prUrl?"pr_handoff":e.headCommit?"commit_handoff":e.changedFiles.length>0?"dirty_worktree":"none"}function xs(e,t){(e.completionBlocker??void 0)!==(t??void 0)&&(t?e.completionBlocker=t:delete e.completionBlocker,X(e.runId,e))}function FY(e){e.completionBlocker&&(delete e.completionBlocker,X(e.runId,e))}function ad(e){return e?{base:e.base,baseCommit:e.baseCommit}:{}}function KY(e,t){return{...e,...t.prUrl?{prUrl:t.prUrl}:{},...t.headCommit?{headCommit:t.headCommit}:{}}}async function Cs(e){let{runId:t,workerName:r}=sd(e),n=In(t,r),o=re(n.runId),s=se(n,ad(o)),i=(e.agentOsId?String(e.agentOsId):n.agentOsId)||"",a=(e.taskId?String(e.taskId):n.taskId)||null;if(!Le(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&&ka(n))return{ok:!0,skipped:!0,reason:"completion-already-acknowledged",httpStatus:200};if(!l&&th(n)&&FY(n),!s.finalResult&&s.alive===!1){let w=Xu({worker:n,status:s});w&&Qu(n,w)&&(X(n.runId,n),n=In(t,r),s=se(n,ad(o)))}if(!(e.skipPrHandoff===!0||e.skipPrHandoff==="true")&&!n.steerRestartRequired&&n.dispatched&&a){let w=dh({worker:n,run:o,status:s});if(!w.ok)return xs(n,w.reason),{ok:!1,reason:w.reason,nextAction:w.nextAction,completionBlocked:!0};(w.prUrl||w.headCommit)&&(s=se(n,ad(o)),s=KY(s,w))}let u=s.gitAncestry.headIsAncestorOfBase===!1&&s.gitAncestry.head?s.gitAncestry.head:s.headCommit;if(n.dispatched&&!n.steerRestartRequired){let w=jA({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 xs(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{hP({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 fe(f,i,{baseUrl:d});a&&(await Ou({worker:n,agentOsId:i,baseUrl:d,secret:m}),n=In(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=yP({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(YA(k),zA(k)){let w={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:{replayShortCircuited:!0}};return Lu(n,n.runId,w),qu(n,s,{source:"harness-completion"}),xs(n,void 0),Ca(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 bP(g,m,v);if((b.status===401||b.status===403)&&!f){let w=await rS(i,{baseUrl:d});w&&w!==m&&(m=w,b=await bP(g,m,v))}if(b.ok){let w=GE(b.parsed);if(!JE(w)){let U=`completion acknowledged but board not advanced: ${w.detail??(w.routeOutcome?`harness completion returned ${w.routeOutcome}`:"harness completion did not advance the linked task")}`;xs(n,U);let W={completionReportedAt:new Date().toISOString(),completionOutcome:"rejected",completionResponse:b.parsed};return Lu(n,n.runId,W),k&&Eh(k,"rejected"),{ok:!1,httpStatus:b.status,response:b.parsed,reason:U,completionBlocked:!0}}xs(n,void 0);let L=w.routeOutcome??"acknowledged",I={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:b.parsed};Lu(n,n.runId,I),qu(n,s,{source:"harness-completion"}),k&&Eh(k,"acknowledged"),Ca(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=LY(b.parsed)??(_?"runner token unauthorized":"non-2xx response"),R=_?`completion replay rejected (${b.status}): ${S}`:`completion replay failed (${b.status}): ${S}`;return xs(n,R),{ok:!1,httpStatus:b.status,response:b.parsed,completionBlocked:!0}}async function SP(e){try{let{runId:t,workerName:r}=sd(e),n=In(t,r),o=re(n.runId),s=se(n,ad(o)),i=(e.agentOsId?String(e.agentOsId):n.agentOsId)||"",a=(e.taskId?String(e.taskId):n.taskId)||null;if(!Le(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 Cs(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 _P(e){let{run:t,workerName:r,worker:n}=e,o=se(n,{base:t.base,baseCommit:t.baseCommit}),s=o.gitAncestry.headIsAncestorOfBase===!1&&o.gitAncestry.head?o.gitAncestry.head:void 0,i=No({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=wP(l)?void 0:l,u=c?"blocked":o.status,d=c?"blocked":o.attention.state,f=vP(n.completionResponse),m=vP(f?.task),g=Aa(f?.outcome),h=Aa(f?.status),y=Array.isArray(f?.warnings)?f.warnings.filter(R=>typeof R=="string"&&R.trim().length>0):[],v=Aa(m?.prUrl)??Aa(f?.prUrl),k=Aa(n.completionReportedAt),b=BY({finished:Le(o),completionBlocker:c,completionOutcome:g,completionReportedAt:k}),_=WY({completionBlocker:c,completionOutcome:g,completionReportedAt:k,finished:Le(o)}),S=UY({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 $Y(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&&!wP(r)?!1:typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim()||e.completionOutcome==="acknowledged"?!0:t==="done"}function HY(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 Pa(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 RP(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 jY(e){let t=e.filter(RP),r=e.filter(n=>{if(RP(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 xP(e,t,r){let n={runId:e.id,name:e.name,status:rc(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:Pa(t,"status"),attentionCounts:Pa(t,"attention"),lifecycleCounts:Pa(t,"lifecycleStage")},n.controller=jY(t)),n}function VY(e){return e.status==="done"&&e.attention==="done"}function Wh(e){let t=re(e),n=Object.keys(t.workers||{}).map(s=>{let i=K(ld.join(V(t.id),"workers",B(s),"worker.json"),void 0);return i?_P({run:t,workerName:s,worker:i}):{worker:s,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=xP(t,n,!1);return ke(ld.join(V(t.id),"last-board.json"),o),o}function Uh(e){let t=re(e),n=Object.keys(t.workers||{}).map(i=>{let a=K(ld.join(V(t.id),"workers",B(i),"worker.json"),void 0);return a?$Y(a)?HY(i,a):_P({run:t,workerName:i,worker:a}):{worker:i,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=n.filter(i=>!VY(i)),s=xP(t,o,!0);return s.status=rc(t.status,n),s.summary={...s.summary??{},totalWorkerCount:n.length,shownWorkerCount:o.length,omittedTerminalDoneWorkerCount:n.length-o.length,allStatusCounts:Pa(n,"status"),allAttentionCounts:Pa(n,"attention")},ke(ld.join(V(t.id),"last-board-compact.json"),s),s}async function CP(e,t){let r=String(e.run||""),n=String(e.agentOsId||"");if(!r||!n)return null;let o=Wh(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 Es=p(()=>{"use strict";j();bs();ss();qE();Ue();Y();Xl();hA();xe();Sh();vi();VA();eh();Bu();ws();Yn();_s();Yu();M();id();Yg();Bh();kP()});var EP=p(()=>{"use strict";Ue();Y();bs();M()});import{spawn as GY}from"node:child_process";import{existsSync as JY,openSync as qY,closeSync as AP}from"node:fs";import YY from"node:path";function PP(e){let t=e.nodeExecutable??process.execPath,r=vu({importMetaUrl:import.meta.url,explicitCliPath:e.cliPath,nodeExecutable:t});if(!r)return;let n=r.cliPath;if(!JY(n))return;let o=YY.join(e.workerDir,"auto-complete.log"),s;try{s=qY(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=GY(r.command,a,z({detached:ve(),stdio:i,env:process.env}));return s!==void 0&&AP(s),l.unref(),{pid:l.pid,logPath:o,cliPath:n}}catch{if(s!==void 0)try{AP(s)}catch{}return}}var yve,IP=p(()=>{"use strict";M();Bu();Y();xe();Es();M();id();Kg();j();EP();yve=360*60*1e3});var OP=p(()=>{"use strict"});function TP(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 NP=p(()=>{"use strict";Re()});import{createHash as zY}from"node:crypto";import{chmodSync as XY,mkdirSync as QY}from"node:fs";import DP from"node:os";import ZY from"node:path";function MP(e,t){return zY("sha256").update(e).digest("hex").slice(0,t)}function Fh(e){let t=e.platform??process.platform,r=MP(e.agentOsId,12),n=MP(e.workerKey,16);if(t==="win32")return{socketPath:`${tz}kynver-worker-${r}-${n}`,socketDir:null,isNamedPipe:!0,relocated:!1};let o=ZY.posix,s=e.homeDir??DP.homedir(),i=o.join(s,".kynver","brokers",r),a=o.join(i,`${n}.sock`);if(Buffer.byteLength(a,"utf8")<=ez)return{socketPath:a,socketDir:i,isNamedPipe:!1,relocated:!1};let l=o.join(e.tmpDir??DP.tmpdir(),`kynver-brokers-${r}`);return{socketPath:o.join(l,`${n}.sock`),socketDir:l,isNamedPipe:!1,relocated:!0}}function Kh(e){e.socketDir&&(QY(e.socketDir,{recursive:!0,mode:448}),XY(e.socketDir,448))}var ez,tz,$h=p(()=>{"use strict";ez=100,tz="\\\\.\\pipe\\"});import rz from"node:net";import{chmodSync as nz,unlinkSync as oz}from"node:fs";var Ia,UP=p(()=>{"use strict";Sr();wu();$h();nt();Ia=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=sa(t.capabilities),this.server=rz.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{nz(t.address.socketPath,384)}catch{}return r}get identitySummary(){return this.opts.identity.summary}get toolDescriptors(){return this.grantedTools.filter(ys).map(t=>ua[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{oz(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(Qm(r))}catch{}}async handleLine(t,r){let n=Zm(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(!ls(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 ru({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 ah(){return yA}var yA,kA=p(()=>{"use strict";yA={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 bA=p(()=>{"use strict";kr()});var vA=p(()=>{"use strict";hA();kA();kr();nu();bA();Dg();ih()});import{existsSync as Oq,mkdirSync as Tq}from"node:fs";import ys from"node:path";async function RA(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=L(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||yr,model:t.model,rule:t.routingRule||"explicit:spawn",requestedModel:t.requestedModel??t.model}:cu({explicitModel:t.model,explicitProvider:t.provider,explicitProviderIsOperatorOverride:!!t.provider?.trim(),configuredProvider:I().workerProvider}),s=bC(o.provider),i=o.model;if(s.preflightModel){let P=s.preflightModel(t.model);if(!P.ok)throw new Error(`model preflight failed for provider "${s.name}": ${P.note??"invalid model/provider combination"}`);P.normalized&&console.error(`[supervisor] ${n}: ${P.note}`),i=P.model}let{worktreesDir:a}=me(),l=ys.join(G(e.id),"workers",n);Tq(l,{recursive:!0});let c=ys.join(a,e.id,n),u=t.repairTargetBranch?.trim()||void 0,d=u||t.branch||`agent/${e.id}/${n}`;if(Oq(c))throw new Error(`worktree path already exists: ${c}`);if(le(e.repo,["fetch","origin","--prune"],{allowFailure:!0}),u)cA(e.repo,c,u);else{let P=uC({baseCommit:e.baseCommit,base:e.base,verifyRef:x=>le(e.repo,["rev-parse","--verify","--quiet",`${x}^{commit}`],{allowFailure:!0}).trim().length>0});P.repaired&&(console.error(`[supervisor] ${n}: run baseCommit ${e.baseCommit||"<empty>"} invalid \u2014 repaired to ${P.ref} (${P.source})`),e.baseCommit=le(e.repo,["rev-parse",P.ref],{allowFailure:!0}).trim()||P.ref,je(e)),le(e.repo,["worktree","add","-b",d,c,e.baseCommit],{throwError:!0})}let m=ys.join(l,"stdout.jsonl"),f=ys.join(l,"stderr.log"),g=ys.join(l,"heartbeat.jsonl"),h=hC({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,b=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=bu({title:t.taskTitle,personaSlug:t.personaSlug,parentTaskId:t.parentTaskId,executorRef:t.executorRef}),v,S,_,w,R=t.workerMcpToken?.trim();if(R&&eg(s.name)&&Gi()){let P=yn();P&&t.agentOsId&&t.taskId?(S={apiBaseUrl:P,agentOsId:String(t.agentOsId),taskId:String(t.taskId),token:R,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 M=wx(s.name);if(R&&M&&Gi()){let P=yn();if(P&&t.agentOsId&&t.taskId){let x=oh({agentOsId:String(t.agentOsId),workerKey:l}),j=await ha.start({address:x,apiBaseUrl:P,agentOsId:String(t.agentOsId),taskId:String(t.taskId),token:R,capabilities:t.workerMcpCapabilities??null,expiresAt:t.workerMcpExpiresAt??Date.now()+Nq,workerPid:process.pid,identity:ah(),onRefusal:T=>console.error(`[supervisor] ${n}: worker tools refused a call (${T})`)});if(Ng(l,j),s.name==="codex"){let T=tE({workerDir:l,brokerSocketPath:x.socketPath});if(T.ok){let V=rE(T.codexHome,vr());V.ok?(_=T.codexHome,v=_):(ca(l),await Kr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 codex rejected the generated config (${V.detail}); spawning with the normal environment`))}else await Kr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${T.detail}`)}else if(s.name==="cursor"){let T=ZC({worktreePath:c,brokerSocketPath:x.socketPath});T.ok?v=T.configPath:(await Kr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${T.detail}`))}else if(s.name==="gemini"&&cs(dt())==="antigravity"){let T=lE({worktreePath:c,brokerSocketPath:x.socketPath});T.ok?v=T.configPath:(await Kr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${T.detail}`))}else if(s.name==="gemini"){let T=uE({workerDir:l,brokerSocketPath:x.socketPath});T.ok?(w=T.geminiCliHome,v=w):(await Kr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${T.detail}`))}else v=_x({workerDir:l,brokerSocketPath:x.socketPath});v&&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 A;try{A=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",...S?{workerToolGrant:S}:{},..._?{codexHome:_}:{},...w?{geminiCliHome:w}:{},...v?{mcpConfigPath:v,mcpAllowedTools:Rx(t.workerMcpCapabilities)}:{}})}catch(P){throw v&&(Qc(l),_u(c),ca(l),Eu(l),Cu(c),us(l)),le(e.repo,["worktree","remove","--force",c],{allowFailure:!0}),le(e.repo,["branch","-D",d],{allowFailure:!0}),P}finally{y===void 0?delete process.env.KYNVER_HARNESS_TASK_ID:process.env.KYNVER_HARNESS_TASK_ID=y,b===void 0?delete process.env.KYNVER_HARNESS_AGENT_OS_ID:process.env.KYNVER_HARNESS_AGENT_OS_ID=b}let C=Qx(A.model,i,s.defaultModel),$=I(),B=Xe(process.env,$),D=Pe().runnerId,J=No({boxKind:B.boxKind,config:$,env:process.env}),H={name:n,runId:e.id,status:"running",pid:A.pid,model:C,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:B.boxKind,boxId:J,runtimeId:D,startedAt:new Date().toISOString()};if(ee(e.id,H),Tg(l,A.pid),e.workers={...e.workers||{},[n]:{workerDir:l,statusPath:ys.join(l,"worker.json")}},e.status="running",je(e),H.agentOsId&&H.taskId){let P;try{P=iA({runId:e.id,workerName:n,workerDir:l,agentOsId:H.agentOsId})}catch(x){let j=`completion sidecar failed to spawn: ${x.message}`;H.completionBlocker=j,ee(e.id,H)}if(P)P.pid&&(H.completionSidecarPid=P.pid,ee(e.id,H));else{let x="completion sidecar failed to spawn (CLI not found or spawn error)";H.completionBlocker=x,H.completionSidecarSpawnFailedAt=new Date().toISOString(),ee(e.id,H)}}return H}var Nq,wA=p(()=>{"use strict";ve();z();z();dC();yC();N();$c();En();vC();aA();lA();uA();Ne();Do();K();et();Mg();Lg();Mn();Fg();Un();Ug();vA();pr();wg();Nq=7200*1e3});function Dq(e,t){let r=He(t)?.trim();return r||xe("KYNVER_RUNNER_TOKEN",e)||xe("OPENCLAW_RUNNER_TOKEN",e)||null}function Mq(e){let t=Ee()?.trim();return t||xe("KYNVER_API_KEY",e)||xe("KYNVER_RUNTIME_SECRET",e)||xe("KYNVER_CRON_SECRET",e)||xe("OPENCLAW_CRON_SECRET",e)||null}async function SA(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=Dq(r,e.agentOsId),l=Mq(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 _A=p(()=>{"use strict";K();Tt()});function Lq(e,t){let r=e.KYNVER_API_URL?.trim()||e.KYNVER_CRON_FIRE_BASE_URL?.trim()||t.apiBaseUrl?.trim()||null;return r?er(r)??null:null}function Bq(e,t){return(e.KYNVER_DEFAULT_REPO?.trim()||e.KYNVER_HARNESS_REPO?.trim()||t.defaultRepo?.trim()||null)??null}function Uq(e,t,r){let n=e.KYNVER_HARNESS_ROOT?.trim()||t.harnessRoot?.trim()||null;return n||r||null}function xA(e,t={}){let r=t.env??process.env,n=t.nowMs??Date.now(),o=t.config??{},s=Lq(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=Bq(r,o),l=Uq(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 CA=p(()=>{"use strict";tr()});var ya=p(()=>{"use strict"});var ka=p(()=>{"use strict"});var ch=p(()=>{"use strict";K();ka()});var dh=p(()=>{"use strict";ya()});import{mkdirSync as AA}from"node:fs";import{homedir as Wq,tmpdir as hye}from"node:os";import ju from"node:path";function PA(){let e=process.env.KYNVER_STATE_ROOT;return e?ju.resolve(e):ju.join(Wq(),".kynver","state")}function Vu(){return ju.join(PA(),"plan-outbox")}function Fq(){return ju.join(PA(),"plan-outbox-archive")}function IA(){let e=Vu(),t=Fq();return AA(e,{recursive:!0}),AA(t,{recursive:!0}),{outboxDir:e,archiveDir:t}}var ba=p(()=>{"use strict"});function OA(){return{"planOutbox.storeFailures":va.storeFailures,"planOutbox.corruptItemsSeen":va.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":va.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":va.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":va.halfArchivesCompleted}}var Rye,va,Ra=p(()=>{"use strict";Wr();Xo();Rye=600*1e3,va={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0}});import{existsSync as Hq,readFileSync as jq,renameSync as xye,readdirSync as Cye,rmSync as Eye,writeFileSync as Aye,unlinkSync as Pye}from"node:fs";import TA from"node:path";function NA(e){if(!Hq(e))return null;try{return JSON.parse(jq(e,"utf8"))}catch{return null}}function Gu(e){let{outboxDir:t}=IA();return{jsonPath:TA.join(t,`${e.id}.json`),bodyPath:TA.join(t,e.bodyPath)}}var wa=p(()=>{"use strict";Ra();ya();dh();ba()});var DA=p(()=>{"use strict";ya();ka();ch()});var ph=p(()=>{"use strict";ch();ka();dh();ba();Ra();wa();DA()});import zq from"node:path";function fh(e){let t=zq.join(Vu(),`${e}.json`);return NA(t)}var MA=p(()=>{"use strict";wa();Ra();ph();ba()});function mh(e){let t=Gu(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 x2(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 bs(e){let t=e.pipeline===!0||e.pipeline==="true";try{let ue=function(){return T.filter(O=>O.started).length},Ie=function(O,E){Ui({runId:l.id,agentOsId:u,phase:O,startedCount:ue(),outcomeCount:T.length,cappedStarts:C,...E})},Qt=function(){return T.some(O=>(typeof O.error=="string"?O.error:"").startsWith("dispatch_start_readback_failed:"))},Ab=function(O){return O.landPrDispatch===!0?!0:O.task?.executor==="land_pr"};var r=ue,n=Ie,o=Qt,s=Ab;let i=FA();if(!i.ok||!i.identity){let O=KA(i);if(t)return{ok:!1,error:O,boundary:i};console.error(`run dispatch failed: ${O}`),process.exit(1)}let a=i.identity;for(let O of i.warnings)console.error(`[dispatch] runner-boundary warning: ${O}`);let l=ae(String(bt(String(e.run||""),"--run"))),c=UA(l,a);if(!c.ok){let O=c.reason??"run does not belong to this runner boundary";if(t)return{ok:!1,error:O,runId:l.id,runnerBoundary:a};console.error(`run dispatch failed: ${O}`),process.exit(1)}c.stamped&&console.error(`[dispatch] stamped run ${l.id} with boxKind=${a.boxKind} runnerId=${a.runnerId}`);let u=String(bt(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=Pe({runId:l.id}),y=ra(l.id,h.runnerId),b=ow(),k=b?gc(l.repo):null,v=new WeakMap;if(b&&f&&!k){let O="desktop_execution_policy_denied:repo_identity_unavailable: the repository has no origin remote";if(t)return{ok:!1,error:O,runId:l.id};console.error(`run dispatch failed: ${O}`),process.exit(1)}let S=e.diskPath?Nr({diskPath:String(e.diskPath)}):Nr({diskPath:l.repo}),_=await T_({runId:l.id,agentOsId:u,args:e}),w=x2(e),R=w.size>0,M=Number(e.maxStarts)>0?Math.floor(Number(e.maxStarts)):1,A=R?Math.min(M,w.size):M;if(e.reconcileStaleBlockers===!0||e.reconcileStaleBlockers==="true"){let O=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/lane-hygiene`;try{await de(O,m,{agentOsId:u,dryRun:!1,includeBoardReconcile:!0},{agentOsId:u,baseUrl:d})}catch(E){console.error(`[dispatch] reconcile-stale-blockers lane-hygiene call failed: ${E.message}`)}}let C=g?A:Math.min(A,_.slotsAvailable);if(!g&&C<=0){let O={runId:l.id,agentOsId:u,dryRun:!1,skipped:!0,reason:_.reason??"no resource slots",resourceGate:_};if(t)return{ok:!0,...O};console.log(JSON.stringify(O,null,2));return}let $=$o(l.id),B=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/tasks/dispatch-next`,D=(O,E)=>({agentOsId:u,...E?{claimAuthorization:E}:{},dryRun:g,maxStarts:O,leaseOwner:y,leaseDurationMs:Number(e.leaseMs)>0?Math.floor(Number(e.leaseMs)):hg,runnerDiskGate:S,runnerResourceGate:_,activeHarnessWorkers:$,runnerPresence:h,harnessBoardSnapshot:rh(l.id),...e.lane?{lane:I_(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)}:{}}),J=w_(),H=async O=>{let E=b&&k?lw(k):void 0,U=await de(B,m,D(O,E),{agentOsId:u,baseUrl:d,timeoutMs:J})??{ok:!1,status:0,response:null},Y=U.response;if(E&&Array.isArray(Y?.result?.started))for(let ne of Y.result.started)ne&&typeof ne=="object"&&v.set(ne,E.requestNonce);return{dispatch:U,result:Y?.result}};g||Ui({runId:l.id,agentOsId:u,phase:"awaiting_dispatch_next",timeoutMs:J});let P=await H(R||g?C:1);if(!P.dispatch.ok||!P.result){let O=Tm(P.dispatch.response),E={runId:l.id,agentOsId:u,action:"dispatch",httpStatus:P.dispatch.status,response:P.dispatch.response,authRefreshed:P.dispatch.refreshedAuth===!0,authRefreshFailure:P.dispatch.authRefreshFailure,...O?{timeout:!0}:{}};if(O&&Ui({runId:l.id,agentOsId:u,phase:"timeout",timeout:!0,httpStatus:P.dispatch.status}),t)return{ok:!1,...E};console.log(JSON.stringify(E,null,2)),process.exit(1)}let x=P.result;if(g){let O=_P(x),E=xP(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:O?.capacityIdle===!0,admissionExhaustion:O,dispatchSkipDrain:E};if(t)return{ok:!0,...U};console.log(JSON.stringify(U,null,2));return}let j=nC(),T=[],V=[],F=Number(x.inspected)||0,Z=!1;async function re(O,E,U){let Y=await Sa({baseUrl:d,secret:m,agentOsId:u,taskId:String(O.id),leaseOwner:y,leaseToken:O.leaseToken?String(O.leaseToken):null,failureDetail:E});O.leaseToken&&ds({taskId:String(O.id),leaseToken:String(O.leaseToken).trim()},Gg(E));let ne={taskId:O.id,started:!1,error:E,released:Y.released,releaseResponse:Y.releaseResponse,...U};return T.push(ne),Ie("outcome",{lastOutcome:ne}),!1}async function _B(O){let E=O.task,U=String(E.id);if(R&&!w.has(U))return re(E,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[...w]});if(!(E.prUrl?String(E.prUrl):""))return re(E,"land_pr task missing prUrl");try{let ne=await dP({decision:O,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 E.leaseToken=="string"?E.leaseToken:"",receiptDir:`${G(l.id)}/land-pr-operations`}}),yt=await fP({baseUrl:d,secret:m,agentOsId:u,runId:l.id,task:E,report:ne});return yt.ok?(T.push({taskId:U,started:!0,landPr:!0,outcome:ne.outcome,completionStatus:yt.status}),!0):re(E,`land_pr completion POST failed (HTTP ${yt.status})`,{landPr:!0,outcome:ne.outcome})}catch(ne){return re(E,ne.message)}}async function xB(O){let E="duplicate_dispatch_prevented: live local worker already owns this task",U=await Sa({baseUrl:d,secret:m,agentOsId:u,taskId:String(O.id),leaseOwner:y,leaseToken:O.leaseToken?String(O.leaseToken):null,failureDetail:E});O.leaseToken&&ds({taskId:String(O.id),leaseToken:String(O.leaseToken).trim()},Gg(E));let Y={taskId:O.id,started:!1,error:E,alreadyRunning:!0,nonFatal:!0,released:U.released,releaseResponse:U.releaseResponse};return T.push(Y),Ie("outcome",{lastOutcome:Y}),!1}async function CB(O){let E=O.task,U=R2(O),Y=String(E.id);if(R&&!w.has(Y))return re(E,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[...w]});let ne=w2(E.personaSlug);if(ne&&(!U?.personaInjectionReady||!U.personaMarkdown))return re(E,`persona_injection_required: missing anchored context-envelope persona block for "${ne}"`);if(ne&&!U?.runtimeEnvelopeReady)return re(E,`runtime_envelope_required: missing AgentRuntimeEnvelope launch receipt for persona "${ne}"`);if(lC(l.id,Y))return xB(E);let yt=Number(E.attempt)||1;if(yt>j.maxTaskAttempts)return re(E,`task attempt ${yt} exceeds KYNVER_MAX_TASK_ATTEMPTS (${j.maxTaskAttempts})`);let on=E.leaseToken?String(E.leaseToken).trim():"";if(!on)return re(E,"dispatch_start_failed: claimed task missing leaseToken \u2014 refusing local spawn");let go=L(`t-${E.id}-a${E.attempt}`),Zt=cu({explicitModel:e.model?String(e.model):void 0,explicitProvider:e.provider?String(e.provider):void 0,explicitProviderIsOperatorOverride:!!e.provider,configuredProvider:I().workerProvider,task:D_(E)});_E({taskId:Y,leaseToken:on,runId:l.id,workerName:go,provider:Zt.provider??null});let Ep=eC({task:E,routing:Zt,explicitProvider:e.provider?String(e.provider):void 0,explicitModel:e.model?String(e.model):void 0});if(!Ep.ok)return re(E,Ep.error??"model_routing_mismatch",{modelRoutingGuard:Ep});if(RP(E)){let Ye=await wP({agentOsId:u,taskId:Y,baseUrl:d,secret:m});if(Ye&&Ye.dispatchable===!1)return re(E,`pr_review_head_reconcile_blocked: ${Ye.reason??Ye.outcome??"stale PR head"}`,{headReconcile:Ye});if(Ye?.activeReviewTaskId&&Ye.activeReviewTaskId!==Y)return re(E,`pr_review_head_reconcile_retargeted: active review is ${Ye.activeReviewTaskId}`,{headReconcile:Ye})}let pl=GE(Zt.provider);if(!pl.ok)return re(E,`provider_quota_exhausted: ${pl.reason}`,{nonFatal:!0,providerQuotaPreflight:{provider:pl.provider,retryAt:pl.retryAtIso}});try{let Ye=E.planId?String(E.planId):void 0,fl=fC({title:E.title?String(E.title):void 0,description:E.description?String(E.description):null,executorRef:E.executorRef?String(E.executorRef):null,prUrl:E.prUrl?String(E.prUrl):null,branch:E.branch?String(E.branch):null}),Db=BE({runId:l.id,workerName:go,maxSlots:_.maxConcurrentWorkers,diskActiveWorkers:nf()});if(!Db.admitted)return re(E,`admission_refused: ${Db.reason}`,{nonFatal:!0});let ml=U?.workerMcpToken??null;if(ml&&Gi()){let ho=xA({jobId:`dispatch:${String(E.id)}`,agentOsId:u,taskId:String(E.id)},{config:{agentOsId:u,apiBaseUrl:d}});if(!ho.ok)console.error(`[dispatch] worker tools skipped for task ${String(E.id)}: context hydration failed (${ho.code}: ${ho.detail}) \u2014 spawning without tools`),ml=null;else{let Ap=await SA(ho.context);Ap.reachable||(console.error(`[dispatch] worker tools skipped for task ${String(E.id)}: tool endpoint probe failed (${Ap.error??`HTTP ${Ap.httpStatus}`}) \u2014 spawning without tools`),ml=null)}}let Ot=await RA(l,{name:go,task:_2(E,u),ownedPaths:e.owned?String(e.owned).split(",").map(ho=>ho.trim()).filter(Boolean):[],model:Zt.model,provider:Zt.provider,routingRule:Zt.rule,requestedModel:Zt.requestedModel,agentOsId:u,taskId:String(E.id),planId:Ye,branch:fl?.targetPrBranch??void 0,executorRef:E.executorRef?String(E.executorRef):void 0,parentTaskId:E.parentTaskId?String(E.parentTaskId):void 0,taskTitle:E.title?String(E.title):void 0,taskPrUrl:fl?.targetPrUrl??(E.prUrl?String(E.prUrl):void 0),repairTargetPrUrl:fl?.targetPrUrl,repairTargetBranch:fl?.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:ml,workerMcpCapabilities:U?.workerMcpCapabilities??null,workerMcpExpiresAt:U?.workerMcpExpiresAt??null,leaseOwner:y,leaseToken:on,dispatched:!0,executionMode:fc(E)}),gl=await yP({agentOsId:u,taskId:String(E.id),leaseOwner:y,expectedLeaseToken:on,worker:Ot,baseUrl:d,secret:m});if(!gl.ok)return bP(l.id,Ot,gl.error??"dispatch_start_readback_failed"),Gr(l.id,go),re(E,gl.error??"dispatch_start_readback_failed",{readback:gl.detail??null});Ot.leaseToken!==on&&(Ot.leaseToken=on,Ot.leaseOwner=y,ee(l.id,Ot)),Mu({taskId:Y,leaseToken:on}),NE(l.id,go);let Mb={taskId:E.id,started:!0,worker:Ot.name,pid:Ot.pid,branch:Ot.branch,model:Ot.model,provider:Zt.provider,routingRule:Zt.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 T.push(Mb),Ie("worker_started",{lastOutcome:Mb}),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 Gr(l.id,go),re(E,Ye.message)}}let Cp=new Set;for(let O of PE(l.id))Cp.add(O);async function Pb(O){let E=O.task,U=String(E.id);if(Cp.has(U))return re(E,"dispatch_retry_loop_prevented: task already failed to start this tick");let Y=b?cw({decision:O,leaseOwner:y,repoIdentity:k,requestNonce:v.get(O)??null}):null,ne=Y&&!Y.allow?await re(E,`desktop_execution_policy_denied:${Y.code}: ${Y.reason}`,{desktopPolicyDenied:Y.code,...Y.code==="operation_not_approved"?{nonFatal:!0}:{}}):Ab(O)?await _B(O):await CB(O);return ne||(Cp.add(U),AE(U,l.id)),ne}for(let O of x.started)await Pb(O);if(V.push(...x.skipped??[]),R)for(let O of V){let E=String(O.task.id);w.has(E)&&T.push({taskId:E,started:!1,error:`exact_target_not_started:${O.skipReason}`,skipReason:O.skipReason,detail:O.reason??null,requestedTargetTaskIds:[...w]})}for(;!R&&T.length<C;){if(Qt()){let U={started:!1,error:"dispatch_circuit_breaker: start readback failed; stopping top-up for this tick",nonFatal:!0};T.push(U),Ie("circuit_breaker",{lastOutcome:U});break}let O=await H(1);if(!O.dispatch.ok||!O.result){let U=__(O.dispatch.response),Y=ue();Z=U&&Y>0;let ne=Tm(O.dispatch.response),yt={started:!1,error:ne?"dispatch_next timed out during top-up":"dispatch_next request failed during top-up",httpStatus:O.dispatch.status,response:O.dispatch.response,...ne?{timeout:!0}:{},...Z?{nonFatal:!0,partialTopUp:!0}:{}};T.push(yt),Ie("top_up_failed",{partialTopUpInterrupted:Z,lastOutcome:yt});break}F+=Number(O.result.inspected)||0,V.push(...O.result.skipped??[]);let E=O.result.started??[];if(E.length===0)break;for(let U of E){if(T.length>=C)break;await Pb(U)}}let dl=T.filter(O=>O.started).length,Tr=_P(x),mo=xP(x),Ib=dl===0&&(Tr?.capacityIdle===!0||Number(x.resourceGate?.slotsAvailable)>0);if(Ib&&Tr?.summary){let O=Tr.skipReasonCounts?.retry_ceiling_exceeded??0,E=x.overAttemptIdleRecovery??Tr.overAttemptIdleRecovery,U=E?.attempted===!0?`; over_attempt_recovery minted=${E.minted??0} started=${E.started??0}`:O>0?"; over_attempt_recovery not attempted":"",Y=mo?`; dispatch_skip_drain scanned=${mo.scanned??0} advanced=${mo.advanced??0}`:"",ne=Tr.progressionReport?.summary?`; ${Tr.progressionReport.summary}`:"",yt=mo?.prLifecycleAttempt?.summary?`; ${mo.prLifecycleAttempt.summary}`:"";console.error(`[dispatch] ${Tr.summary}${O>0?`; retry_ceiling_exceeded=${O}`:""}${U}${Y}${ne}${yt}`)}let Ob={runId:l.id,agentOsId:u,dryRun:!1,leaseOwner:y,startedCount:dl,capacityIdle:Ib,admissionExhaustion:Tr,dispatchSkipDrain:mo,outcomes:T,skipped:V.map(O=>({taskId:O.task.id,skipReason:O.skipReason})),inspected:F,pagesScanned:x.pagesScanned??null,candidatesExhausted:x.candidatesExhausted??null,diskGate:x.diskGate,resourceGate:x.resourceGate,...Z?{partialTopUpInterrupted:!0}:{},dispatchCallbackTimeoutMs:J},Tb=O=>!O.started&&O.nonFatal!==!0,EB=T.some(Tb),Nb=Z&&dl>0?!0:!EB;if(Ui({runId:l.id,agentOsId:u,phase:"complete",partial:Z,startedCount:dl,ok:Nb}),t)return{ok:Nb,...Ob};console.log(JSON.stringify(Ob,null,2)),T.some(Tb)&&process.exit(1)}catch(i){if(t)return{ok:!1,error:i.message};console.error(`run dispatch failed: ${i.message}`),process.exit(1)}}var hg,fu=p(()=>{"use strict";K();hc();Ue();S_();x_();O_();ri();N_();Io();z();z();M_();$c();tC();oC();gg();wA();_A();CA();et();cc();hs();N();BA();yg();na();pr();WA();$A();yh();th();pP();mP();hP();kP();vP();z();SP();If();ps();Fn();ms();hg=3600*1e3});function vs(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 E2(e){let{maxStarts:t,...r}=e;return r}async function wh(e,t){if(t<=0)return{ok:!0,skipped:!0,reason:"no slots",maxStarts:0,startedCount:0};let r=E2(e);if(r.targetTaskId||r.targetTaskIds){let u=await bs({...r,execute:!0,pipeline:!0,maxStarts:String(t)});return{...typeof u=="object"&&u!==null?u:{},passes:{target:u},startedCount:vs(u)}}let n=Math.min(t,C2),o=Math.max(0,t-n),s=await bs({...r,execute:!0,pipeline:!0,lane:"review",maxStarts:String(n)}),i=vs(s),a=o+(n-i);if(a<=0)return{...typeof s=="object"&&s!==null?s:{},passes:{review:s},startedCount:i};let l=await bs({...r,execute:!0,pipeline:!0,maxStarts:String(a)}),c=vs(l);return{passes:{review:s,work:l},startedCount:i+c,ok:!0}}var C2,CP=p(()=>{"use strict";fu();C2=1});function EP(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 AP=p(()=>{"use strict"});function A2(e){let r=e.response?.dispatch;return r&&typeof r=="object"?r:null}function _a(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function P2(e){let t=Number(process.env[e]);return!Number.isFinite(t)||t<=0?null:Math.floor(t)}function PP(e,t){let r=A2(t),n=_a(r?.recommendedMaxStarts),o=_a(r?.actionableReady),s=_a(r?.queuedTasks),i=_a(r?.boardAdvancedThisTick)??0,a=_a(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=P2("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 IP=p(()=>{"use strict"});import I2 from"node:path";function $n(e){let t=Rt(e);if(t.length===0)return"failed";let r=!1,n=!1,o=!1,s=!1;for(let i of t){let a=W(I2.join(G(e.id),"workers",L(i),"worker.json"),void 0);if(!a)continue;let l=te(a,{base:e.base,baseCommit:e.baseCommit});if(l.alive&&!l.finalResult){r=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),rf(l)&&(s=!0),l.finalResult&&l.attention.state==="done"&&(n=!0)}return r||o||s?null:n?"completed":"failed"}function xa(){let e=[];for(let t of Re()){if(!O2.has(t.status))continue;let r=$n(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 O2,Cr,qr=p(()=>{"use strict";z();wo();Se();N();O2=new Set(["running","dispatching","pending","queued","needs_attention"]),Cr=new Set(["completed","failed","cancelled","done"])});import Pt from"node:path";function Ju(e){return e.includes(T2)}function Sh(e,t){return Pt.join(Qe(Ae(e)),L(t))}function Yr(e,t,r){return Pt.join(Sh(e,t),"workers",L(r))}function OP(e,t,r){let n=Ae(e);return Pt.join(n,"runs","runs",L(t),"workers",L(r))}function _h(){return["stdout.jsonl","stderr.log","heartbeat.jsonl","last-status.json","auto-complete.log","worker.json"]}function Hn(e){return{workerJsonPath:Pt.join(e,"worker.json"),stdoutPath:Pt.join(e,"stdout.jsonl"),stderrPath:Pt.join(e,"stderr.log"),heartbeatPath:Pt.join(e,"heartbeat.jsonl"),lastStatusPath:Pt.join(e,"last-status.json")}}function TP(e){let t=Hn(Yr(e.harnessRoot,e.runId,e.workerName)).workerJsonPath;return e.statusPath&&!Ju(e.statusPath)?e.statusPath:t}var T2,xh=p(()=>{"use strict";wt();N();T2=`${Pt.sep}runs${Pt.sep}runs${Pt.sep}`});import{existsSync as zr,mkdirSync as N2,readdirSync as DP,renameSync as D2,statSync as Ch}from"node:fs";import he from"node:path";function MP(e,t){let r=he.resolve(e),n=he.resolve(Qe(t)),o=he.relative(n,r);return o!==".."&&!o.startsWith("..")&&!he.isAbsolute(o)}function Eh(e){if(!zr(e))return[];try{return DP(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&t.name!=="runs").map(t=>t.name)}catch{return[]}}function Ah(e){let t=he.join(e,"workers");if(!zr(t))return[];try{return DP(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}function LP(e){return he.join(e,"archived-workers")}function L2(e,t){let r=he.join(LP(e),L(t));return zr(r)?`${r}-${Date.now()}`:r}function NP(e,t,r){if(!zr(e))return!1;try{let n=t-Ch(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<r}catch{return!1}}function BP(e,t=Date.now(),r=Ca){if(!zr(e))return!1;let n=Hn(e),o=W(n.workerJsonPath,void 0);if(o?.status==="running"&&ie(o.pid))return!0;let s=De(n.heartbeatPath);if(s.lastHeartbeatAt){let i=t-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<r)return!0}return!!(NP(n.stdoutPath,t,r)||NP(n.heartbeatPath,t,r))}function B2(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-Ch(he.join(e,"worker.json")).mtimeMs}catch{return 0}}function U2(e,t,r,n){if(BP(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=B2(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 Rs(e,t=Date.now(),r=Ca){for(let n of Ah(e))if(BP(he.join(e,"workers",n),t,r))return!0;return!1}function W2(){let t=Ni()?.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 F2(e,t){let r=he.join(Qe(e),L(t));if(!zr(r))return null;let n=Ah(r);if(n.length===0)return null;let o;try{o=Ch(r).birthtime.toISOString()}catch{o=new Date().toISOString()}let s={};for(let a of n){let l=Yr(e,t,a);s[a]={workerDir:l,statusPath:he.join(l,"worker.json")}}let i=Rs(r);return{id:t,name:t,...W2(),status:i?"running":"needs_attention",createdAt:o,workers:s}}function Ph(e){let t=Ae(e??it()),r=Qe(t),n=[];for(let o of Eh(r)){let s=he.join(r,o,"run.json");if(zr(s)){n.push({runId:o,action:"skipped",reason:"run.json present"});continue}let i=F2(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:Rs(he.join(r,o))?"synthesized run.json while worker artifacts still active":"synthesized run.json from orphan worker metadata dirs"})}return{runs:n}}function Ih(e,t={}){let r=Ae(e??it()),n=Qe(r),o=t.now??Date.now(),s=t.archiveAgeMs??M2,i=[];Ph(r);for(let a of Eh(n)){let l=he.join(n,a),c=he.join(l,"run.json"),u=W(c,void 0);if(!u?.id)continue;let d=new Set([...Object.keys(u.workers||{}),...Ah(l)]),m=!1;for(let f of d){let g=he.join(l,"workers",L(f)),h=he.join(g,"worker.json"),y=W(h,void 0);if(!y){let v=he.join(LP(l),L(f));if(zr(v)&&(u.workers[L(f)]||u.workers[f])){delete u.workers[L(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:v});continue}i.push({runId:u.id,worker:f,action:"skipped",reason:"worker.json missing"});continue}let b=U2(g,y,o,s);if(!b.eligible){i.push({runId:u.id,worker:f,action:"skipped",reason:b.reason});continue}let k=L2(l,f);N2(he.dirname(k),{recursive:!0}),D2(g,k),delete u.workers[L(f)],delete u.workers[f],m=!0,i.push({runId:u.id,worker:f,action:"archived",reason:b.reason,archivePath:k})}m&&je(u)}return{workers:i}}function UP(e,t=Date.now()){let r=new Set,n=Qe(e);for(let o of Eh(n)){let s=he.join(n,o);Rs(s,t)&&r.add(`${e}\0${o}`)}return r}var Ca,M2,ws=p(()=>{"use strict";Zo();ve();cn();wt();z();xh();N();Ca=900*1e3,M2=3600*1e3});import{existsSync as Xr,lstatSync as K2,readdirSync as $2,readlinkSync as H2,renameSync as Oh,unlinkSync as j2}from"node:fs";import Kt from"node:path";function V2(e,t){let r=Sh(e,t),n;try{n=K2(r)}catch{return null}if(!n.isSymbolicLink())return null;let o=Kt.resolve(Kt.dirname(r),H2(r));if(Rs(o)||Rs(r))return null;let s=`${r}.materialize-${Date.now()}`;return Oh(o,s),j2(r),Oh(s,r),o}function G2(e){let t=[];for(let r of _h()){let n=Kt.join(e.fromDir,r),o=Kt.join(e.toDir,r);!Xr(n)||Xr(o)||(Oh(n,o),t.push(r))}return t}function WP(e,t){let r=Hn(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 J2(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 q2(e){let t=Hn(e.canonicalDir),r=W(t.lastStatusPath,void 0),n=Xr(t.stdoutPath),o=Xr(t.heartbeatPath);if(!(n||o||r!=null))return null;let i=n?_o(t.stdoutPath):{finalResult:null},a=o?De(t.heartbeatPath):De(""),l=nr(a),c=J2({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}),WP(u,e.canonicalDir),u}function Y2(e,t){let r=!1,n={...e.workers||{}};for(let[o,s]of Object.entries(n)){let i=Yr(t,e.id,o),a=Kt.join(i,"worker.json");(Ju(s.workerDir)||Ju(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 z2(e){let t=[],r=Yr(e.harnessRoot,e.run.id,e.workerName),n=OP(e.harnessRoot,e.run.id,e.workerName),o=Hn(r),s=G2({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=TP({harnessRoot:e.harnessRoot,runId:e.run.id,workerName:e.workerName,statusPath:e.statusPath}),a=W(i,void 0);if(!a&&Xr(o.workerJsonPath)&&(a=W(o.workerJsonPath,void 0)),!a){let l=q2({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=Xr(r),u=_h().some(d=>Xr(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 WP(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 X2(e,t){let r=Kt.join(G(e.id),"workers");if(!Xr(r))return[];let n=new Set(Object.keys(e.workers||{})),o=[];for(let s of $2(r,{withFileTypes:!0}))s.isDirectory()&&(n.has(s.name)||o.push(s.name));return o}function FP(){let{harnessRoot:e}=me(),t=Ph(e),r=[];for(let n of Re()){let o=V2(e,n.id);o&&r.push({runId:n.id,worker:"*",action:"materialized_run_symlink",reason:`replaced symlink with real run dir (was ${o})`}),Y2(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 X2(n,e))s.add(i),n.workers={...n.workers||{},[i]:{workerDir:Yr(e,n.id,i),statusPath:Kt.join(Yr(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(...z2({run:n,workerName:i,harnessRoot:e,statusPath:a?.statusPath}))}}return{workers:r,runMetadataRetention:t}}var KP=p(()=>{"use strict";cn();ii();xh();ws();z();N()});import{execFileSync as $P}from"node:child_process";import HP from"node:path";function Th(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:null}function Q2(e){let t=Th(e)?.match(/\/pull\/(\d+)$/);if(!t)return null;let r=Number.parseInt(t[1],10);return Number.isFinite(r)?r:null}function Z2(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function eY(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 tY(e){let t=null;if(typeof e=="string"?t=Eo(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=Th(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 rY(e){try{let n=$P("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=$P("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:Th(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 nY(e){let t=De(e.heartbeatPath);return e.completionSnapshot?.finalResult??nr(t)}function oY(e){let t=new Map,r=G(e.id);for(let n of Rt(e)){let o=W(HP.join(r,"workers",L(n),"worker.json"),void 0);if(o)for(let s of tY(nY(o))){let i=Q2(s.prUrl);i!=null&&!t.has(i)&&t.set(i,s)}}return t}function sY(e,t){let r=De(e.heartbeatPath),n=[e.name,e.repairTargetPrUrl,e.taskPrUrl,e.branch,r.lastHeartbeatSummary,Z2(t)].filter(Boolean).join(`
|
|
114
|
-
`);return eY(n)}function iY(e){return e.localOnly===!0&&!e.taskId&&!e.agentOsId}function Nh(e={}){let t=e.lookupPr??rY,r=[],n=new Map;for(let o of Re()){let s=oY(o),i=G(o.id);for(let a of Rt(o)){let l=HP.join(i,"workers",L(a),"worker.json"),c=W(l,void 0);if(!c||!iY(c))continue;let u=te(c,{base:o.base,baseCommit:o.baseCommit});if(u.attention.state!=="needs_attention")continue;let d=null;for(let f of sY(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 jP=p(()=>{"use strict";cn();Ml();Se();z();wo();N()});import aY from"node:path";function cY(){return process.env.KYNVER_NO_STALE_CLEANUP==="1"}function VP(e,t){let r=Ou({worker:e,status:t}),n=r?Tu(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 Dh(){let e=FP();if(cY()){let s=Nh(),i=Ih();return{workers:[],finalizedRuns:xa(),metadataReconcile:e,localPrAttentionReconcile:s,terminalWorkerArchive:i}}let t=[],r=Date.now();for(let s of Re())for(let i of Rt(s)){let a=aY.join(G(s.id),"workers",L(i),"worker.json"),l=W(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=te(l,{base:s.base,baseCommit:s.baseCommit});if(c.finalResult){if(l.status==="running"){let u=VP(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=VP(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&&ie(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>lY,f=Number.isFinite(d)&&r-d>tf;if(m&&f){Te(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=Nh(),o=Ih();return{workers:t,finalizedRuns:xa(),metadataReconcile:e,localPrAttentionReconcile:n,terminalWorkerArchive:o}}var lY,Mh=p(()=>{"use strict";qr();z();wo();Kg();Se();N();KP();jP();ws();lY=900*1e3});import{readdirSync as uY,readFileSync as dY}from"node:fs";function hY(e){if(process.platform!=="linux"||!e.trim())return null;let t=[];try{t=uY("/proc")}catch{return null}for(let r of t)if(/^\d+$/.test(r)&&Number(r)!==process.pid)try{if(dY(`/proc/${r}/cmdline`,"utf8").replace(/\0/g," ").includes(e))return Number(r)}catch{}return null}async function GP(e){let t=_r(),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??fY,i=e.findOrphanPid??hY,a=[],l;try{l=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-mY).toISOString(),limit:gY})}catch{return jn.recoveryStoreFailures+=1,r}for(let c of l){let u=c.idempotencyKey.slice(pY.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=ua(m);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${d}:`,limit:10}).some(_=>{if(g===null)return!0;let w=ua(_.idempotencyKey.slice(`dispatch:completion-acked:${d}:`.length));return w===null||w>=g}))continue;let b={};try{b=c.resultJson?JSON.parse(c.resultJson):{}}catch{b={}}let k=b.runId??null,v=b.workerName??null;if(k&&v&&e.hasLiveWorker({runId:k,workerName:v})){Mu({taskId:d,leaseToken:m}),a.push({taskId:d,leaseToken:m,runId:k,workerName:v,action:"finalized_late"});continue}if(k&&v){let _=e.worktreePathFor({runId:k,workerName:v}),w=_?i(_):null;if(w!==null){jn.recoveryDeferredOrphans+=1,a.push({taskId:d,leaseToken:m,runId:k,workerName:v,action:"deferred_orphan",detail:`live pid ${w} references ${_}`});continue}}if(!k){a.push({taskId:d,leaseToken:m,runId:k,workerName:v,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let S=await e.releaseClaim({taskId:d,leaseToken:m,runId:k});S.released?(ds({taskId:d,leaseToken:m},"restart_recovery"),v&&(pa(k,v),Gr(k,v)),jn.recoveredStrandedClaims+=1,a.push({taskId:d,leaseToken:m,runId:k,workerName:v,action:"released"})):S.transportError?a.push({taskId:d,leaseToken:m,runId:k,workerName:v,action:"deferred_transport",detail:S.detail}):(ds({taskId:d,leaseToken:m},"restart_recovery_refused"),a.push({taskId:d,leaseToken:m,runId:k,workerName:v,action:"release_refused",detail:S.detail}))}catch{jn.recoveryStoreFailures+=1}}return{mode:t,scanned:l.length,outcomes:a}}function JP(){return{"dispatchReceipts.recoveredStrandedClaims":jn.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":jn.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":jn.recoveryStoreFailures}}var pY,fY,mY,gY,jn,Lh=p(()=>{"use strict";Wr();ps();Fn();ms();pY="dispatch:claim:",fY=900*1e3,mY=10080*60*1e3,gY=200,jn={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0}});import yY from"node:path";async function YP(e){if(qP||_r()!=="enforce")return null;qP=!0;try{let t=Pe().runnerId,r=await GP({hasLiveWorker:e.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>yY.join(me().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await Sa({baseUrl:e.baseUrl,secret:e.secret,agentOsId:e.agentOsId,taskId:n,leaseOwner:ra(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 qP,zP=p(()=>{"use strict";z();na();pr();yh();Lh();ps();qP=!1});import kY from"node:os";function XP(e,t={}){let r=I(),n=(t.boxKind??vt(r)).trim().toLowerCase()||"forge",o=t.hostLabel??kY.hostname();return{boxId:No({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:e_()}}var QP=p(()=>{"use strict";K();Ne();Do();Tc()});import bY from"node:path";async function qu(e){let t=e.pipeline===!0||e.pipeline==="true";try{let r=ae(String(bt(String(e.run||""),"--run"))),n=String(bt(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=Pe({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=W(bY.join(G(r.id),"workers",L(m),"worker.json"),void 0);if(!f||!f.dispatched||!f.taskId)continue;let g=te(f);if(g.alive||g.finalResult||f.completionReportedAt)continue;let h=uu({runId:r.id,workerLeaseOwner:f.leaseOwner??null,runnerId:i}),y=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/${encodeURIComponent(String(f.taskId))}/release`,b;try{b=await de(y,s,{agentOsId:n,leaseOwner:h,...f.leaseToken?.trim()?{leaseToken:f.leaseToken.trim()}:{}},{agentOsId:n,baseUrl:o})}catch(k){b={ok:!1,error:k.message}}l.push({worker:m,taskId:f.taskId,pid:f.pid,released:b.ok===!0||b.response?.ok===!0,response:b.response??b})}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 Bh=p(()=>{"use strict";K();Ue();z();Se();N();na();pr();hs()});async function ZP(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 eI=p(()=>{"use strict";K();Ue()});import vY from"node:path";async function tI(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=W(vY.join(G(r.id),"workers",L(s),"worker.json"),void 0);if(!i?.dispatched||!i.taskId)continue;let a=te(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 ZP({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 rI=p(()=>{"use strict";Se();z();N();eI()});function nI(e){let t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(t==="node_modules"||t.startsWith("node_modules/"))return!0;for(let r of Uh)if(t===r||t.startsWith(`${r}/`))return!0;return!1}var Uh,Wh=p(()=>{"use strict";Uh=[".next",".turbo","dist","build",".cache","node_modules/.cache"]});function pt(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 Vn=p(()=>{"use strict";Wh()});function Gn(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 Ea(e){let t=e.gitAncestry?.relation;return t==="merged"||t==="synced"?pt(e.changedFiles).length>0:!!(Gn(e.finalResult)||t==="ahead"||t==="diverged"||e.changedFiles.length>0&&e.finalResult)}var Aa=p(()=>{"use strict";Vn()});function Pa(e){return e.status||(e.status=te(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function Fh(e,t){if(e.status)return pt(e.status.changedFiles).length>0;let r=t?t.porcelain(e.worktreePath):Qs(e.worktreePath);return pt(r).length>0}function RY(e){let t=e.worker.completionSnapshot?.finalResult;return t??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Kh(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=RY(e);if(o&&!ie(r.pid)){let i=t?.gitStatusCache?t.gitStatusCache.porcelain(e.worktreePath):Qs(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"}:Rl(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??Gn(s)};return e.status=u,u}return Pa(e)}var Yu=p(()=>{"use strict";ve();Se();Vn();Aa();N()});function wY(e,t=Date.now(),r=Ca){let n=De(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=t-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<r}function Ss(e,t=Date.now(),r=Ca){return ie(e.pid)?!0:wY(e,t,r)}var zu=p(()=>{"use strict";cn();ws();N()});function SY(e,t){return t?t.runTerminalCache.derive(e.run):$n(e.run)}function Er(e,t=Date.now()){return Ss(e.worker,t)}function $h(e,t){return Cr.has(e.run.status)?!1:SY(e,t)!==null}function oI(e,t,r=Date.now()){if(Er(e,r))return!0;if(Cr.has(e.run.status)||$h(e,t))return!1;let n=Pa(e);return Me(n)?!1:!!Er(e,r)}var Hh=p(()=>{"use strict";qr();Se();Yu();zu()});function sI(e,t){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(Er(e))return!0;let n=t??Pa(e);return!!(!Me(n)||Ea(n)||pt(n.changedFiles).length>0||Co({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:Gn(n.finalResult)}).blocked)}var iI=p(()=>{"use strict";Dl();Yu();Vn();Hh();Se();Aa()});import{existsSync as lI,mkdirSync as _Y,writeFileSync as aI}from"node:fs";import Xu from"node:path";function cI(e,t,r){return Xu.join(e,"salvage",L(t),L(r))}function uI(e){return lI(Xu.join(cI(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function dI(e){let t=cI(e.harnessRoot,e.indexed.runId,e.indexed.workerName);_Y(t,{recursive:!0});let r=Xu.join(t,"salvage.patch"),n=!1;if(lI(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(Ng(r))}catch{}}async handleLine(t,r){let n=Dg(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(!ys(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 Ru({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 Hh(){return FP}var FP,KP=p(()=>{"use strict";FP={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 $P=p(()=>{"use strict";Sr()});var HP=p(()=>{"use strict";UP();KP();Sr();wu();$P();hh();$h()});import{existsSync as sz,mkdirSync as iz}from"node:fs";import As from"node:path";async function jP(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}:Au({explicitModel:t.model,explicitProvider:t.provider,explicitProviderIsOperatorOverride:!!t.provider?.trim(),configuredProvider:E().workerProvider}),s=$E(o.provider),i=o.model;if(s.preflightModel){let x=s.preflightModel(t.model);if(!x.ok)throw new Error(`model preflight failed for provider "${s.name}": ${x.note??"invalid model/provider combination"}`);x.normalized&&console.error(`[supervisor] ${n}: ${x.note}`),i=x.model}let{worktreesDir:a}=me(),l=As.join(V(e.id),"workers",n);iz(l,{recursive:!0});let c=As.join(a,e.id,n),u=t.repairTargetBranch?.trim()||void 0,d=u||t.branch||`agent/${e.id}/${n}`;if(sz(c))throw new Error(`worktree path already exists: ${c}`);if(le(e.repo,["fetch","origin","--prune"],{allowFailure:!0}),u)TP(e.repo,c,u);else{let x=NE({baseCommit:e.baseCommit,base:e.base,verifyRef:H=>le(e.repo,["rev-parse","--verify","--quiet",`${H}^{commit}`],{allowFailure:!0}).trim().length>0});x.repaired&&(console.error(`[supervisor] ${n}: run baseCommit ${e.baseCommit||"<empty>"} invalid \u2014 repaired to ${x.ref} (${x.source})`),e.baseCommit=le(e.repo,["rev-parse",x.ref],{allowFailure:!0}).trim()||x.ref,je(e)),le(e.repo,["worktree","add","-b",d,c,e.baseCommit],{throwError:!0})}let f=As.join(l,"stdout.jsonl"),m=As.join(l,"stderr.log"),g=As.join(l,"heartbeat.jsonl"),h=UE({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=Uu({title:t.taskTitle,personaSlug:t.personaSlug,parentTaskId:t.parentTaskId,executorRef:t.executorRef}),b,_,S,R,w=t.workerMcpToken?.trim();if(w&&Mg(s.name)&&ia()){let x=En();x&&t.agentOsId&&t.taskId?(_={apiBaseUrl:x,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=KC(s.name);if(w&&L&&ia()){let x=En();if(x&&t.agentOsId&&t.taskId){let H=Fh({agentOsId:String(t.agentOsId),workerKey:l}),N=await Ia.start({address:H,apiBaseUrl:x,agentOsId:String(t.agentOsId),taskId:String(t.taskId),token:w,capabilities:t.workerMcpCapabilities??null,expiresAt:t.workerMcpExpiresAt??Date.now()+az,workerPid:process.pid,identity:Hh(),onRefusal:D=>console.error(`[supervisor] ${n}: worker tools refused a call (${D})`)});if(gh(l,N),s.name==="codex"){let D=_A({workerDir:l,brokerSocketPath:H.socketPath});if(D.ok){let F=xA(D.codexHome,xr());F.ok?(S=D.codexHome,b=S):(Sa(l),await Yr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 codex rejected the generated config (${F.detail}); spawning with the normal environment`))}else await Yr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${D.detail}`)}else if(s.name==="cursor"){let D=wA({worktreePath:c,brokerSocketPath:H.socketPath});D.ok?b=D.configPath:(await Yr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${D.detail}`))}else if(s.name==="gemini"&&ks(gt())==="antigravity"){let D=OA({worktreePath:c,brokerSocketPath:H.socketPath});D.ok?b=D.configPath:(await Yr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${D.detail}`))}else if(s.name==="gemini"){let D=NA({workerDir:l,brokerSocketPath:H.socketPath});D.ok?(R=D.geminiCliHome,b=R):(await Yr(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${D.detail}`))}else b=HC({workerDir:l,brokerSocketPath:H.socketPath});b&&console.error(`[supervisor] ${n}: worker tools enabled via broker (${N.identitySummary})`)}else console.error(`[supervisor] ${n}: worker MCP tools skipped (missing API base URL or task identity) \u2014 spawning without tools`)}let I=t.taskId?BR(WR(e.id,String(t.taskId),n)):null,A;try{A=UR(I,()=>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:FC(t.workerMcpCapabilities)}:{}}))}catch(x){throw b&&(yu(l),ju(c),Sa(l),Ju(l),Gu(c),vs(l)),le(e.repo,["worktree","remove","--force",c],{allowFailure:!0}),le(e.repo,["branch","-D",d],{allowFailure:!0}),x}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=yE(A.model,i,s.defaultModel),U=E(),W=Ze(process.env,U),G=Te().runnerId,ee=$o({boxKind:W.boxKind,config:U,env:process.env}),T={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:W.boxKind,boxId:ee,runtimeId:G,startedAt:new Date().toISOString(),...I?{oomRetryHeapMb:I}:{}};if(X(e.id,T),mh(l,A.pid),e.workers={...e.workers||{},[n]:{workerDir:l,statusPath:As.join(l,"worker.json")}},e.status="running",je(e),T.agentOsId&&T.taskId){let x;try{x=PP({runId:e.id,workerName:n,workerDir:l,agentOsId:T.agentOsId})}catch(H){let N=`completion sidecar failed to spawn: ${H.message}`;T.completionBlocker=N,X(e.id,T)}if(x)x.pid&&(T.completionSidecarPid=x.pid,X(e.id,T));else{let H=T.completionBlocker??"completion sidecar failed to spawn (CLI not found or spawn error)";T.completionBlocker=H,T.completionSidecarSpawnFailedAt=new Date().toISOString(),X(e.id,T),OE(e.id,T,H)}}return T}var az,VP=p(()=>{"use strict";bs();Tf();Re();Y();Y();DE();FE();M();au();Ln();HE();IP();OP();NP();Me();Ho();j();nt();yh();kh();jn();wh();Jn();vh();HP();yr();oh();az=7200*1e3});function lz(e,t){let r=Ie(t)?.trim();return r||Ee("KYNVER_RUNNER_TOKEN",e)||Ee("OPENCLAW_RUNNER_TOKEN",e)||null}function cz(e){let t=Se()?.trim();return t||Ee("KYNVER_API_KEY",e)||Ee("KYNVER_RUNTIME_SECRET",e)||Ee("KYNVER_CRON_SECRET",e)||Ee("OPENCLAW_CRON_SECRET",e)||null}async function GP(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=lz(r,e.agentOsId),l=cz(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 JP=p(()=>{"use strict";j();wt()});function uz(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 dz(e,t){return(e.KYNVER_DEFAULT_REPO?.trim()||e.KYNVER_HARNESS_REPO?.trim()||t.defaultRepo?.trim()||null)??null}function pz(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=uz(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=dz(r,o),l=pz(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 YP=p(()=>{"use strict";sr()});var Oa=p(()=>{"use strict"});var Ta=p(()=>{"use strict"});var Vh=p(()=>{"use strict";j();Ta()});var Jh=p(()=>{"use strict";Oa()});import{mkdirSync as XP}from"node:fs";import{homedir as fz,tmpdir as JRe}from"node:os";import cd from"node:path";function QP(){let e=process.env.KYNVER_STATE_ROOT;return e?cd.resolve(e):cd.join(fz(),".kynver","state")}function ud(){return cd.join(QP(),"plan-outbox")}function mz(){return cd.join(QP(),"plan-outbox-archive")}function ZP(){let e=ud(),t=mz();return XP(e,{recursive:!0}),XP(t,{recursive:!0}),{outboxDir:e,archiveDir:t}}var Na=p(()=>{"use strict"});function eI(){return{"planOutbox.storeFailures":Da.storeFailures,"planOutbox.corruptItemsSeen":Da.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":Da.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":Da.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":Da.halfArchivesCompleted}}var QRe,Da,Ma=p(()=>{"use strict";Jr();is();QRe=600*1e3,Da={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0}});import{existsSync as yz,readFileSync as kz,renameSync as rwe,readdirSync as nwe,rmSync as owe,writeFileSync as swe,unlinkSync as iwe}from"node:fs";import tI from"node:path";function rI(e){if(!yz(e))return null;try{return JSON.parse(kz(e,"utf8"))}catch{return null}}function dd(e){let{outboxDir:t}=ZP();return{jsonPath:tI.join(t,`${e.id}.json`),bodyPath:tI.join(t,e.bodyPath)}}var La=p(()=>{"use strict";Ma();Oa();Jh();Na()});var nI=p(()=>{"use strict";Oa();Ta();Vh()});var qh=p(()=>{"use strict";Vh();Ta();Jh();Na();Ma();La();nI()});import _z from"node:path";function Yh(e){let t=_z.join(ud(),`${e}.json`);return rI(t)}var oI=p(()=>{"use strict";La();Ma();qh();Na()});function zh(e){let t=dd(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 Xh(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 sI=p(()=>{"use strict";La()});var iI=p(()=>{"use strict";Oa();qh();oI();La();sI();Na();Ta()});function Qh(e){return e?.trim()?e.trim():null}function aI(e,t){let r=Qh(e.boxKind),n=Qh(e.runnerId),o=Qh(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,je(e),{ok:!0,stamped:!0}):{ok:!0}}var lI=p(()=>{"use strict";Y()});function cI(e=process.env){return Lt(E(),e,{requireExplicitBoxKind:!0})}function uI(e){return[...e.errors,...e.warnings].join("; ")}var dI=p(()=>{"use strict";j();wn()});async function Ba(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 Zh=p(()=>{"use strict";Ue()});function Ps(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 pI(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 ey=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 mI(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 gI(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||mI(o)>=mI(i))&&r.set(s,o)}return[...r.values()]}function xz(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 hI(e){let t=gI(e),r=[],n=[],o=[];for(let s of t){if(xz(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&&fI.has(i))){if(i){n.push(`${tn(s)}=${i}`);continue}if(!(l&&fI.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 yI(e){return gI(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 kI(e,t){let r=e==="UNSTABLE"&&t.ignoredActions.length>0;return!Cz.has(e)&&!r?`mergeStateStatus is ${e}`:null}var fI,Cz,bI=p(()=>{"use strict";fI=new Set(["SUCCESS","SKIPPED","NEUTRAL"]);Cz=new Set(["CLEAN","HAS_HOOKS"])});import{spawnSync as Ez}from"node:child_process";function vI(){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=Ez("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 RI=p(()=>{"use strict"});import{createHash as Az,randomUUID as Pz}from"node:crypto";import{closeSync as wI,fsyncSync as SI,mkdirSync as Iz,openSync as _I,realpathSync as Oz,writeFileSync as Tz}from"node:fs";import ty from"node:path";function CI(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 xI(e,t,r,n){Iz(e,{recursive:!0,mode:448});let o=Oz(e),s=_I(ty.join(o,`${t}.${r}.json`),"wx",384);try{Tz(s,JSON.stringify({...n,phase:r},null,2)+`
|
|
175
|
+
`),SI(s)}finally{wI(s)}for(let i=o;;i=ty.dirname(i)){let a=_I(i,"r");try{SI(a)}catch(l){if(!Nz(l))throw l}finally{wI(a)}if(i===ty.dirname(i))break}}function Nz(e,t=process.platform){return t==="win32"&&e?.code==="EPERM"}function EI(e,t,r,n){let o={acceptedReview:n,agentOsId:e.agentOsId,taskId:e.taskId,runId:e.runId,workerName:e.workerName,leaseOwner:e.leaseOwner,leaseTokenSha256:Az("sha256").update(e.leaseToken).digest("hex")},s={...o,prUrl:t,invocationId:Pz(),startedAt:new Date().toISOString(),finishedAt:null,headSha:r,mergedAt:null,mergeCommit:null,source:"daemon_land_pr",mergeInvoked:!1};return xI(e.receiptDir,s.invocationId,"pending",s),{finish(i){let a={...o,...i,invocationId:s.invocationId,startedAt:s.startedAt,finishedAt:new Date().toISOString()};return xI(e.receiptDir,s.invocationId,"finished",{...s,...a}),a}}}var AI=p(()=>{"use strict"});import{spawnSync as PI}from"node:child_process";function ny(e){return e?.trim()?["--repo",e.trim()]:[]}function II(e){let t=/github\.com\/([^/]+)\/([^/]+)\/pull\/\d+/i.exec(e.trim());return t?`${t[1]}/${t[2]}`:null}function OI(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 Wz(e){let t=typeof e.title=="string"?e.title.trim():"",r=typeof e.body=="string"?e.body.trim():"",n=Lz.test(t)||Bz.test(r),o=Dz.test(r),s=Mz.test(r);return n||o||s||e.vercelCheckSuccess===!0}function Uz(e){if(!Wz({title:e.title,body:e.body,vercelCheckSuccess:yI(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 Fz(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=hI(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=kI(e.mergeStateStatus,t);if(r)throw new Error(`PR #${e.number} ${r}`)}function Kz(e){Fz(e),Uz(e)}function $z(e){try{return Kz(e),null}catch(t){return t instanceof Error?t.message:String(t)}}function Hz(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 jz(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 Vz(e,t){if(!t?.trim())return;let r=PI("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}`)&&PI("git",["worktree","remove","--force",o],{windowsHide:!0,cwd:e,encoding:"utf8"}))}}async function TI(e){let t=e.cwd??process.cwd(),r=e.exec??Ku,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(!Ps(o)||o.prUrl!==n||o.agentOsId!==e.operation?.agentOsId||!e.revalidateAcceptedReview)return s();let i=vI();if(!i.configured)return{prUrl:n,outcome:"blocked",reason:i.reason};let a=OI(r,t,["pr","view",n,...ny(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=$z(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)||!CI(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(!Ps(u)||!pI(o,u))return s();let d=EI(e.operation,n,o.headSha,o),f;try{f=r.gh(t,["pr","merge",c,...ny(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=ry(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=ry(r,t,c,e.repo);if(g||(g=ry(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=jz(r,t,e.repo);Hz(r,t,y,a.headRefName),Vz(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 ry(e,t,r,n){try{let o=OI(e,t,["pr","view",r,...ny(n),"--json","number,url,mergedAt,mergeCommit,state"]);return o.state==="MERGED"?o:null}catch{return null}}var Dz,Mz,Lz,Bz,NI=p(()=>{"use strict";ey();$u();bI();RI();AI();Dz=/^##\s*(test\s*plan|verification|test\s*evidence|verify)\b/im,Mz=/typecheck|npm run (test|build|typecheck)|vitest|tsc\b|verify-pr-local|local verify|local-verify|tests? (pass|green)|build green|node --test/i,Lz=/^docs[(:]/i,Bz=/docs[- ]only|documentation only|no[- ]code change|no code changes|low[- ]risk|plan tracker only|markdown only/i});async function DI(e){let t=e.decision.task,r=e.decision.acceptedReview,n=String(t.prUrl??"");return TI({prUrl:n,cwd:e.cwd,repo:II(n),exec:e.exec,operation:e.operation,acceptedReview:Ps(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&&Ps(s.acceptedReview)?s.acceptedReview:null}})}var MI=p(()=>{"use strict";Ue();ey();NI()});async function LI(e){let t=await fe(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 BI=p(()=>{"use strict";j();Ue()});function WI(){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 UI=p(()=>{"use strict"});function zn(e){return`${Gz} ${e.trim()}`}function Jz(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 qz(e){let{snapshot:t,leaseOwner:r,expectedLeaseToken:n,worker:o}=e;if(!t)return{ok:!1,error:zn("task lease snapshot missing after spawn"),detail:{taskId:o.taskId,leaseOwner:r,expectedLeaseToken:n}};if(t.status!=="running")return{ok:!1,error:zn(`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:zn(`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:zn(`leaseToken mismatch (board=${i||"null"}, expected=${n})`),detail:{taskId:t.taskId,boardLeaseToken:i||null,expectedLeaseToken:n},snapshot:t};let a=Jz(o);return a?{ok:!1,error:zn(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:zn(`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:zn("AgentOS heartbeatAt missing after claim"),detail:{taskId:t.taskId},snapshot:t}}async function FI(e){let t=await Iu({agentOsId:e.agentOsId,taskIds:[e.taskId],baseUrl:e.baseUrl,secret:e.secret});return qz({snapshot:t.get(e.taskId)??null,leaseOwner:e.leaseOwner,expectedLeaseToken:e.expectedLeaseToken,worker:e.worker})}var Gz,KI=p(()=>{"use strict";qg();Gz="dispatch_start_readback_failed:"});function $I(e,t,r){t.pid&&te(t.pid)&&(ye(t.pid,"SIGTERM"),te(t.pid)&&ye(t.pid,"SIGKILL"));let n={...t,status:"failed",pid:void 0,completionBlocker:r,dispatchStartReadbackFailed:!0};return X(e,n),n}var HI=p(()=>{"use strict";M();Y()});function jI(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 VI(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 GI=p(()=>{"use strict";Ue()});function JI(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 Yz(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=Xz(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 zz(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length?t:null}function Xz(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 Qz(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("",WI());let n=Xh(e);if(n?.outboxId){let o=Yh(n.outboxId);o?r.push("",zh(o)):r.push("","## Plan persistence risk","",`Unconfirmed AgentOS plan write (outboxId=${n.outboxId}).`)}return r.join(`
|
|
177
|
+
`)}function Zz(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 Is(e){let t=e.pipeline===!0||e.pipeline==="true";try{let ue=function(){return N.filter(P=>P.started).length},Ne=function(P,C){Qi({runId:l.id,agentOsId:u,phase:P,startedCount:ue(),outcomeCount:N.length,cappedStarts:A,...C})},rr=function(){return N.some(P=>(typeof P.error=="string"?P.error:"").startsWith("dispatch_start_readback_failed:"))},_v=function(P){return P.landPrDispatch===!0?!0:P.task?.executor==="land_pr"};var r=ue,n=Ne,o=rr,s=_v;let i=cI();if(!i.ok||!i.identity){let P=uI(i);if(t)return{ok:!1,error:P,boundary:i};console.error(`run dispatch failed: ${P}`),process.exit(1)}let a=i.identity;for(let P of i.warnings)console.error(`[dispatch] runner-boundary warning: ${P}`);let l=re(String(St(String(e.run||""),"--run"))),c=aI(l,a);if(!c.ok){let P=c.reason??"run does not belong to this runner boundary";if(t)return{ok:!1,error:P,runId:l.id,runnerBoundary:a};console.error(`run dispatch failed: ${P}`),process.exit(1)}c.stamped&&console.error(`[dispatch] stamped run ${l.id} with boxKind=${a.boxKind} runnerId=${a.runnerId}`);let u=String(St(String(e.agentOsId||""),"--agent-os-id")),d=pe(e.baseUrl?String(e.baseUrl):void 0),f=await fe(e.secret?String(e.secret):void 0,u,{baseUrl:d}),m=e.execute===!0||e.execute==="true",g=!m,h=Te({runId:l.id}),y=ha(l.id,h.runnerId),v=yS(),k=v?Dc(l.repo):null,b=new WeakMap;if(v&&m&&!k){let P="desktop_execution_policy_denied:repo_identity_unavailable: the repository has no origin remote";if(t)return{ok:!1,error:P,runId:l.id};console.error(`run dispatch failed: ${P}`),process.exit(1)}let _=e.diskPath?Br({diskPath:String(e.diskPath)}):Br({diskPath:l.repo}),S=await zx({runId:l.id,agentOsId:u,args:e}),R=Zz(e),w=R.size>0,L=Number(e.maxStarts)>0?Math.floor(Number(e.maxStarts)):1,I=w?Math.min(L,R.size):L;if(e.reconcileStaleBlockers===!0||e.reconcileStaleBlockers==="true"){let P=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/lane-hygiene`;try{await de(P,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?I:Math.min(I,S.slotsAvailable);if(!g&&A<=0){let P={runId:l.id,agentOsId:u,dryRun:!1,skipped:!0,reason:S.reason??"no resource slots",resourceGate:S};if(t)return{ok:!0,...P};console.log(JSON.stringify(P,null,2));return}let O=Xo(l.id),U=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/tasks/dispatch-next`,W=(P,C)=>({agentOsId:u,...C?{claimAuthorization:C}:{},dryRun:g,maxStarts:P,leaseOwner:y,leaseDurationMs:Number(e.leaseMs)>0?Math.floor(Number(e.leaseMs)):Xg,runnerDiskGate:_,runnerResourceGate:S,activeHarnessWorkers:O,runnerPresence:h,harnessBoardSnapshot:Wh(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($=>$.trim()).filter(Boolean)}:{}}),G=Fx(),ee=async P=>{let C=v&&k?RS(k):void 0,$=await de(U,f,W(P,C),{agentOsId:u,baseUrl:d,timeoutMs:G})??{ok:!1,status:0,response:null},q=$.response;if(C&&Array.isArray(q?.result?.started))for(let oe of q.result.started)oe&&typeof oe=="object"&&b.set(oe,C.requestNonce);return{dispatch:$,result:q?.result}};g||Qi({runId:l.id,agentOsId:u,phase:"awaiting_dispatch_next",timeoutMs:G});let T=await ee(w||g?A:1);if(!T.dispatch.ok||!T.result){let P=fg(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,...P?{timeout:!0}:{}};if(P&&Qi({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 P=JI(x),C=qI(x),$={runId:l.id,agentOsId:u,dryRun:!0,wouldStart:x.started.map(q=>({taskId:q.task.id,title:q.task.title,reason:q.reason})),skipped:x.skipped.map(q=>({taskId:q.task.id,skipReason:q.skipReason,reason:q.reason})),diskGate:x.diskGate,resourceGate:x.resourceGate,inspected:x.inspected,pagesScanned:x.pagesScanned??null,candidatesExhausted:x.candidatesExhausted??null,capacityIdle:P?.capacityIdle===!0,admissionExhaustion:P,dispatchSkipDrain:C};if(t)return{ok:!0,...$};console.log(JSON.stringify($,null,2));return}let H=wE(),N=[],D=[],F=Number(x.inspected)||0,Z=!1;async function ne(P,C,$){let q=await Ba({baseUrl:d,secret:f,agentOsId:u,taskId:String(P.id),leaseOwner:y,leaseToken:P.leaseToken?String(P.leaseToken):null,failureDetail:C});P.leaseToken&&Rs({taskId:String(P.id),leaseToken:String(P.leaseToken).trim()},Ah(C));let oe={taskId:P.id,started:!1,error:C,released:q.released,releaseResponse:q.releaseResponse,...$};return N.push(oe),Ne("outcome",{lastOutcome:oe}),!1}async function OU(P){let C=P.task,$=String(C.id);if(w&&!R.has($))return ne(C,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[...R]});if(!(C.prUrl?String(C.prUrl):""))return ne(C,"land_pr task missing prUrl");try{let oe=await DI({decision:P,baseUrl:d,secret:f,agentOsId:u,cwd:l.repo,operation:{agentOsId:u,taskId:$,runId:l.id,workerName:`land-pr-${$}`,leaseOwner:y,leaseToken:typeof C.leaseToken=="string"?C.leaseToken:"",receiptDir:`${V(l.id)}/land-pr-operations`}}),Rt=await LI({baseUrl:d,secret:f,agentOsId:u,runId:l.id,task:C,report:oe});return Rt.ok?(N.push({taskId:$,started:!0,landPr:!0,outcome:oe.outcome,completionStatus:Rt.status}),!0):ne(C,`land_pr completion POST failed (HTTP ${Rt.status})`,{landPr:!0,outcome:oe.outcome})}catch(oe){return ne(C,oe.message)}}async function TU(P){let C="duplicate_dispatch_prevented: live local worker already owns this task",$=await Ba({baseUrl:d,secret:f,agentOsId:u,taskId:String(P.id),leaseOwner:y,leaseToken:P.leaseToken?String(P.leaseToken):null,failureDetail:C});P.leaseToken&&Rs({taskId:String(P.id),leaseToken:String(P.leaseToken).trim()},Ah(C));let q={taskId:P.id,started:!1,error:C,alreadyRunning:!0,nonFatal:!0,released:$.released,releaseResponse:$.releaseResponse};return N.push(q),Ne("outcome",{lastOutcome:q}),!1}async function NU(P){let C=P.task,$=Yz(P),q=String(C.id);if(w&&!R.has(q))return ne(C,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[...R]});let oe=zz(C.personaSlug);if(oe&&(!$?.personaInjectionReady||!$.personaMarkdown))return ne(C,`persona_injection_required: missing anchored context-envelope persona block for "${oe}"`);if(oe&&!$?.runtimeEnvelopeReady)return ne(C,`runtime_envelope_required: missing AgentRuntimeEnvelope launch receipt for persona "${oe}"`);if(EE(l.id,q))return TU(C);let Rt=Number(C.attempt)||1;if(Rt>H.maxTaskAttempts)return ne(C,`task attempt ${Rt} exceeds KYNVER_MAX_TASK_ATTEMPTS (${H.maxTaskAttempts})`);let mn=C.leaseToken?String(C.leaseToken).trim():"";if(!mn)return ne(C,"dispatch_start_failed: claimed task missing leaseToken \u2014 refusing local spawn");let gn=B(`t-${C.id}-a${C.attempt}`),nr=Au({explicitModel:e.model?String(e.model):void 0,explicitProvider:e.provider?String(e.provider):void 0,explicitProviderIsOperatorOverride:!!e.provider,configuredProvider:E().workerProvider,task:Qx(C)});JA({taskId:q,leaseToken:mn,runId:l.id,workerName:gn,provider:nr.provider??null});let sf=bE({task:C,routing:nr,explicitProvider:e.provider?String(e.provider):void 0,explicitModel:e.model?String(e.model):void 0});if(!sf.ok)return ne(C,sf.error??"model_routing_mismatch",{modelRoutingGuard:sf});if(jI(C)){let ze=await VI({agentOsId:u,taskId:q,baseUrl:d,secret:f});if(ze&&ze.dispatchable===!1)return ne(C,`pr_review_head_reconcile_blocked: ${ze.reason??ze.outcome??"stale PR head"}`,{headReconcile:ze});if(ze?.activeReviewTaskId&&ze.activeReviewTaskId!==q)return ne(C,`pr_review_head_reconcile_retargeted: active review is ${ze.activeReviewTaskId}`,{headReconcile:ze})}let El=gP(nr.provider);if(!El.ok)return ne(C,`provider_quota_exhausted: ${El.reason}`,{nonFatal:!0,providerQuotaPreflight:{provider:El.provider,retryAt:El.retryAtIso}});try{let ze=C.planId?String(C.planId):void 0,Al=LE({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}),Iv=iP({runId:l.id,workerName:gn,maxSlots:S.maxConcurrentWorkers,diskActiveWorkers:Wf()});if(!Iv.admitted)return ne(C,`admission_refused: ${Iv.reason}`,{nonFatal:!0});let Pl=$?.workerMcpToken??null;if(Pl&&ia()){let So=qP({jobId:`dispatch:${String(C.id)}`,agentOsId:u,taskId:String(C.id)},{config:{agentOsId:u,apiBaseUrl:d}});if(!So.ok)console.error(`[dispatch] worker tools skipped for task ${String(C.id)}: context hydration failed (${So.code}: ${So.detail}) \u2014 spawning without tools`),Pl=null;else{let af=await GP(So.context);af.reachable||(console.error(`[dispatch] worker tools skipped for task ${String(C.id)}: tool endpoint probe failed (${af.error??`HTTP ${af.httpStatus}`}) \u2014 spawning without tools`),Pl=null)}}IE(l.id,String(C.id),{except:gn});let Mt=await jP(l,{name:gn,task:Qz(C,u),ownedPaths:e.owned?String(e.owned).split(",").map(So=>So.trim()).filter(Boolean):[],model:nr.model,provider:nr.provider,routingRule:nr.rule,requestedModel:nr.requestedModel,agentOsId:u,taskId:String(C.id),planId:ze,branch:Al?.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:Al?.targetPrUrl??(C.prUrl?String(C.prUrl):void 0),repairTargetPrUrl:Al?.targetPrUrl,repairTargetBranch:Al?.targetPrBranch??void 0,instructionPolicyMarkdown:$?.instructionPolicyMarkdown??null,instructionPolicyFingerprint:$?.instructionPolicyFingerprint??null,instructionPolicyEvidence:$?.instructionPolicyEvidence??null,memoryQualityCapture:$?.memoryQualityCapture??null,memoryQualityPromptMarkdown:$?.memoryQualityPromptMarkdown??null,personaMarkdown:$?.personaMarkdown??null,personaSlug:$?.personaSlug??oe,personaEvidence:$?.personaEvidence??null,contextEnvelopeMarkdown:$?.contextEnvelopeMarkdown??null,contextEnvelopeEvidence:$?.contextEnvelopeEvidence??null,runtimeEnvelopeMarkdown:$?.runtimeEnvelopeMarkdown??null,runtimeEnvelopeEvidence:$?.runtimeEnvelopeEvidence??null,workerMcpToken:Pl,workerMcpCapabilities:$?.workerMcpCapabilities??null,workerMcpExpiresAt:$?.workerMcpExpiresAt??null,leaseOwner:y,leaseToken:mn,dispatched:!0,executionMode:Tc(C)}),Il=await FI({agentOsId:u,taskId:String(C.id),leaseOwner:y,expectedLeaseToken:mn,worker:Mt,baseUrl:d,secret:f});if(!Il.ok)return $I(l.id,Mt,Il.error??"dispatch_start_readback_failed"),en(l.id,gn),ne(C,Il.error??"dispatch_start_readback_failed",{readback:Il.detail??null});Mt.leaseToken!==mn&&(Mt.leaseToken=mn,Mt.leaseOwner=y,X(l.id,Mt)),td({taskId:q,leaseToken:mn}),rP(l.id,gn);let Ov={taskId:C.id,started:!0,worker:Mt.name,pid:Mt.pid,branch:Mt.branch,model:Mt.model,provider:nr.provider,routingRule:nr.rule,instructionPolicyFingerprint:$?.instructionPolicyFingerprint??null,instructionPolicyRuleCount:Array.isArray($?.instructionPolicyEvidence?.ruleSlugs)?$.instructionPolicyEvidence.ruleSlugs.length:null,personaSlug:$?.personaSlug??oe,personaOperatingRuleCount:$?.personaEvidence?.operatingRuleCount??null};return N.push(Ov),Ne("worker_started",{lastOutcome:Ov}),$?.instructionPolicyFingerprint&&console.error(`[dispatch] task ${q}: instruction policy injected fingerprint=${$.instructionPolicyFingerprint}`),$?.personaSlug&&console.error(`[dispatch] task ${q}: persona context injected slug=${$.personaSlug}`),$?.contextEnvelopeReady&&console.error(`[dispatch] task ${q}: context envelope injected anchor=${$.contextEnvelopeEvidence?.anchorTaskId??q}`),$?.runtimeEnvelopeReady&&console.error(`[dispatch] task ${q}: runtime envelope injected id=${$.runtimeEnvelopeEvidence?.envelopeId??"unknown"}`),!0}catch(ze){return en(l.id,gn),ne(C,ze.message)}}let of=new Set;for(let P of QA(l.id))of.add(P);async function xv(P){let C=P.task,$=String(C.id);if(of.has($))return ne(C,"dispatch_retry_loop_prevented: task already failed to start this tick");let q=v?wS({decision:P,leaseOwner:y,repoIdentity:k,requestNonce:b.get(P)??null}):null,oe=q&&!q.allow?await ne(C,`desktop_execution_policy_denied:${q.code}: ${q.reason}`,{desktopPolicyDenied:q.code,...q.code==="operation_not_approved"?{nonFatal:!0}:{}}):_v(P)?await OU(P):await NU(P);return oe||(of.add($),XA($,l.id)),oe}for(let P of x.started)await xv(P);if(D.push(...x.skipped??[]),w)for(let P of D){let C=String(P.task.id);R.has(C)&&N.push({taskId:C,started:!1,error:`exact_target_not_started:${P.skipReason}`,skipReason:P.skipReason,detail:P.reason??null,requestedTargetTaskIds:[...R]})}for(;!w&&N.length<A;){if(rr()){let $={started:!1,error:"dispatch_circuit_breaker: start readback failed; stopping top-up for this tick",nonFatal:!0};N.push($),Ne("circuit_breaker",{lastOutcome:$});break}let P=await ee(1);if(!P.dispatch.ok||!P.result){let $=$x(P.dispatch.response),q=ue();Z=$&&q>0;let oe=fg(P.dispatch.response),Rt={started:!1,error:oe?"dispatch_next timed out during top-up":"dispatch_next request failed during top-up",httpStatus:P.dispatch.status,response:P.dispatch.response,...oe?{timeout:!0}:{},...Z?{nonFatal:!0,partialTopUp:!0}:{}};N.push(Rt),Ne("top_up_failed",{partialTopUpInterrupted:Z,lastOutcome:Rt});break}F+=Number(P.result.inspected)||0,D.push(...P.result.skipped??[]);let C=P.result.started??[];if(C.length===0)break;for(let $ of C){if(N.length>=A)break;await xv($)}}let Cl=N.filter(P=>P.started).length,Lr=JI(x),wo=qI(x),Cv=Cl===0&&(Lr?.capacityIdle===!0||Number(x.resourceGate?.slotsAvailable)>0);if(Cv&&Lr?.summary){let P=Lr.skipReasonCounts?.retry_ceiling_exceeded??0,C=x.overAttemptIdleRecovery??Lr.overAttemptIdleRecovery,$=C?.attempted===!0?`; over_attempt_recovery minted=${C.minted??0} started=${C.started??0}`:P>0?"; over_attempt_recovery not attempted":"",q=wo?`; dispatch_skip_drain scanned=${wo.scanned??0} advanced=${wo.advanced??0}`:"",oe=Lr.progressionReport?.summary?`; ${Lr.progressionReport.summary}`:"",Rt=wo?.prLifecycleAttempt?.summary?`; ${wo.prLifecycleAttempt.summary}`:"";console.error(`[dispatch] ${Lr.summary}${P>0?`; retry_ceiling_exceeded=${P}`:""}${$}${q}${oe}${Rt}`)}let Ev={runId:l.id,agentOsId:u,dryRun:!1,leaseOwner:y,startedCount:Cl,capacityIdle:Cv,admissionExhaustion:Lr,dispatchSkipDrain:wo,outcomes:N,skipped:D.map(P=>({taskId:P.task.id,skipReason:P.skipReason})),inspected:F,pagesScanned:x.pagesScanned??null,candidatesExhausted:x.candidatesExhausted??null,diskGate:x.diskGate,resourceGate:x.resourceGate,...Z?{partialTopUpInterrupted:!0}:{},dispatchCallbackTimeoutMs:G},Av=P=>!P.started&&P.nonFatal!==!0,DU=N.some(Av),Pv=Z&&Cl>0?!0:!DU;if(Qi({runId:l.id,agentOsId:u,phase:"complete",partial:Z,startedCount:Cl,ok:Pv}),t)return{ok:Pv,...Ev};console.log(JSON.stringify(Ev,null,2)),N.some(Av)&&process.exit(1)}catch(i){if(t)return{ok:!1,error:i.message};console.error(`run dispatch failed: ${i.message}`),process.exit(1)}}var Xg,Tu=p(()=>{"use strict";j();Mc();Ue();Kx();Hx();Yx();hi();Xx();Wo();Y();Y();Zx();au();vE();SE();zg();VP();bs();JP();YP();nt();Ac();Es();M();iI();Zg();ya();yr();lI();dI();Zh();Bh();MI();BI();UI();KI();HI();Y();GI();um();ws();Yn();_s();Xg=3600*1e3});function Os(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 t6(e){let{maxStarts:t,...r}=e;return r}async function oy(e,t){if(t<=0)return{ok:!0,skipped:!0,reason:"no slots",maxStarts:0,startedCount:0};let r=t6(e);if(r.targetTaskId||r.targetTaskIds){let u=await Is({...r,execute:!0,pipeline:!0,maxStarts:String(t)});return{...typeof u=="object"&&u!==null?u:{},passes:{target:u},startedCount:Os(u)}}let n=Math.min(t,e6),o=Math.max(0,t-n),s=await Is({...r,execute:!0,pipeline:!0,lane:"review",maxStarts:String(n)}),i=Os(s),a=o+(n-i);if(a<=0)return{...typeof s=="object"&&s!==null?s:{},passes:{review:s},startedCount:i};let l=await Is({...r,execute:!0,pipeline:!0,maxStarts:String(a)}),c=Os(l);return{passes:{review:s,work:l},startedCount:i+c,ok:!0}}var e6,YI=p(()=>{"use strict";Tu();e6=1});function zI(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 XI=p(()=>{"use strict"});function r6(e){let r=e.response?.dispatch;return r&&typeof r=="object"?r:null}function Wa(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function n6(e){let t=Number(process.env[e]);return!Number.isFinite(t)||t<=0?null:Math.floor(t)}function QI(e,t){let r=r6(t),n=Wa(r?.recommendedMaxStarts),o=Wa(r?.actionableReady),s=Wa(r?.queuedTasks),i=Wa(r?.boardAdvancedThisTick)??0,a=Wa(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=n6("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 ZI=p(()=>{"use strict"});import o6 from"node:path";function Xn(e){let t=xt(e);if(t.length===0)return"failed";let r=!1,n=!1,o=!1,s=!1;for(let i of t){let a=K(o6.join(V(e.id),"workers",B(i),"worker.json"),void 0);if(!a)continue;let l=se(a,{base:e.base,baseCommit:e.baseCommit});if(l.alive&&!l.finalResult){r=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Bf(l)&&(s=!0),l.finalResult&&l.attention.state==="done"&&(n=!0)}return r||o||s?null:n?"completed":"failed"}function Ua(){let e=[];for(let t of we()){if(!s6.has(t.status))continue;let r=Xn(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 s6,Or,rn=p(()=>{"use strict";Y();Oo();xe();M();s6=new Set(["running","dispatching","pending","queued","needs_attention"]),Or=new Set(["completed","failed","cancelled","done"])});import Nt from"node:path";function pd(e){return e.includes(i6)}function sy(e,t){return Nt.join(tt(Oe(e)),B(t))}function nn(e,t,r){return Nt.join(sy(e,t),"workers",B(r))}function eO(e,t,r){let n=Oe(e);return Nt.join(n,"runs","runs",B(t),"workers",B(r))}function iy(){return["stdout.jsonl","stderr.log","heartbeat.jsonl","last-status.json","auto-complete.log","worker.json"]}function Qn(e){return{workerJsonPath:Nt.join(e,"worker.json"),stdoutPath:Nt.join(e,"stdout.jsonl"),stderrPath:Nt.join(e,"stderr.log"),heartbeatPath:Nt.join(e,"heartbeat.jsonl"),lastStatusPath:Nt.join(e,"last-status.json")}}function tO(e){let t=Qn(nn(e.harnessRoot,e.runId,e.workerName)).workerJsonPath;return e.statusPath&&!pd(e.statusPath)?e.statusPath:t}var i6,ay=p(()=>{"use strict";Ct();M();i6=`${Nt.sep}runs${Nt.sep}runs${Nt.sep}`});import{existsSync as a6,readFileSync as l6,readdirSync as c6,statSync as u6,writeFileSync as d6}from"node:fs";import p6 from"node:path";function k6(e,t=[]){if(!e)return e;let r=e,n=[...new Set(t.map(o=>o?.trim()).filter(o=>!!o&&o.length>=m6))].sort((o,s)=>s.length-o.length);for(let o of n){r.includes(o)&&(r=r.split(o).join(st));let s=JSON.stringify(o).slice(1,-1);s!==o&&r.includes(s)&&(r=r.split(s).join(st))}for(let[o,s]of f6)r=r.replace(o,s);return r}function rO(e=process.env,t=[]){let r=[];for(let[n,o]of Object.entries(e))o&&g6.test(n)&&r.push(o);for(let n of t)try{let o=n();o&&r.push(o)}catch{}return r}function nO(e,t=0){if(t>3||!a6(e))return[];let r=[];for(let n of c6(e,{withFileTypes:!0})){let o=p6.join(e,n.name);n.isDirectory()?r.push(...nO(o,t+1)):n.isFile()&&h6.test(n.name)&&r.push(o)}return r}function oO(e,t=[]){let r={masked:[],clean:0,failed:[]},n;try{n=nO(e)}catch{return r}for(let o of n)try{if(u6(o).size>y6){r.failed.push(o);continue}let s=l6(o,"utf8"),i=k6(s,t);if(i===s){r.clean+=1;continue}d6(o,i,"utf8"),r.masked.push(o)}catch{r.failed.push(o)}return r}var st,ly,f6,m6,g6,h6,y6,sO=p(()=>{"use strict";st="<redacted>",ly=`[^\\s"'\\\\,}\\]]`,f6=[[new RegExp(`\\b(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|rediss):\\/\\/${ly}+`,"gi"),st],[new RegExp(`\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s/@:"']+:[^\\s/@"']+@${ly}+`,"gi"),st],[/\bkynver_u_[A-Za-z0-9_-]+/g,st],[/\bkyn_[A-Za-z0-9]{12,}/g,st],[/\bsk-ant-[A-Za-z0-9_-]+/g,st],[/\bsk-[A-Za-z0-9_-]{8,}/g,st],[/\bkr[a-z]1\.[A-Za-z0-9._~+/=-]{8,}/g,st],[/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}/g,st],[/\bgithub_pat_[A-Za-z0-9_]{16,}/g,st],[/\b(Bearer|Basic)\s+(?!<redacted>)[A-Za-z0-9._~+/=-]{8,}/gi,`$1 ${st}`],[new RegExp(`(\\b(?:[A-Z0-9_]*(?:API_KEY|APIKEY|TOKEN|SECRET|PASSWORD)|DATABASE_URL|KYNVER_DATABASE_URL)\\s*=\\s*)(?!<redacted>)${ly}+`,"g"),`$1${st}`]],m6=12,g6=/(?:API_KEY|APIKEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)$/i,h6=/(?:\.jsonl|\.log|\.txt|^stdout.*|^stderr.*)$/i,y6=256*1024*1024});import{existsSync as on,mkdirSync as b6,readdirSync as aO,renameSync as v6,statSync as cy}from"node:fs";import he from"node:path";function lO(e,t){let r=he.resolve(e),n=he.resolve(tt(t)),o=he.relative(n,r);return o!==".."&&!o.startsWith("..")&&!he.isAbsolute(o)}function uy(e){if(!on(e))return[];try{return aO(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&t.name!=="runs").map(t=>t.name)}catch{return[]}}function dy(e){let t=he.join(e,"workers");if(!on(t))return[];try{return aO(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}function cO(e){return he.join(e,"archived-workers")}function w6(e,t){let r=he.join(cO(e),B(t));return on(r)?`${r}-${Date.now()}`:r}function iO(e,t,r){if(!on(e))return!1;try{let n=t-cy(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<r}catch{return!1}}function uO(e,t=Date.now(),r=Fa){if(!on(e))return!1;let n=Qn(e),o=K(n.workerJsonPath,void 0);if(o?.status==="running"&&te(o.pid))return!0;let s=Ae(n.heartbeatPath);if(s.lastHeartbeatAt){let i=t-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<r)return!0}return!!(iO(n.stdoutPath,t,r)||iO(n.heartbeatPath,t,r))}function S6(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-cy(he.join(e,"worker.json")).mtimeMs}catch{return 0}}function _6(e,t,r,n){if(uO(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=S6(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 Ts(e,t=Date.now(),r=Fa){for(let n of dy(e))if(uO(he.join(e,"workers",n),t,r))return!0;return!1}function x6(){let t=Gi()?.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 C6(e,t){let r=he.join(tt(e),B(t));if(!on(r))return null;let n=dy(r);if(n.length===0)return null;let o;try{o=cy(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:he.join(l,"worker.json")}}let i=Ts(r);return{id:t,name:t,...x6(),status:i?"running":"needs_attention",createdAt:o,workers:s}}function py(e){let t=Oe(e??ut()),r=tt(t),n=[];for(let o of uy(r)){let s=he.join(r,o,"run.json");if(on(s)){n.push({runId:o,action:"skipped",reason:"run.json present"});continue}let i=C6(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:Ts(he.join(r,o))?"synthesized run.json while worker artifacts still active":"synthesized run.json from orphan worker metadata dirs"})}return{runs:n}}function fy(e,t={}){let r=Oe(e??ut()),n=tt(r),o=t.now??Date.now(),s=t.archiveAgeMs??R6,i=[],a=null,l=()=>a??=(t.knownSecrets??(()=>rO(process.env,[Se,()=>Ie()])))();py(r);for(let c of uy(n)){let u=he.join(n,c),d=he.join(u,"run.json"),f=K(d,void 0);if(!f?.id)continue;let m=new Set([...Object.keys(f.workers||{}),...dy(u)]),g=!1;for(let h of m){let y=he.join(u,"workers",B(h)),v=he.join(y,"worker.json"),k=K(v,void 0);if(!k){let S=he.join(cO(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=_6(y,k,o,s);if(!b.eligible){i.push({runId:f.id,worker:h,action:"skipped",reason:b.reason});continue}let _=w6(u,h);b6(he.dirname(_),{recursive:!0}),v6(y,_),oO(_,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&&je(f)}return{workers:i}}function dO(e,t=Date.now()){let r=new Set,n=tt(e);for(let o of uy(n)){let s=he.join(n,o);Ts(s,t)&&r.add(`${e}\0${o}`)}return r}var Fa,R6,Ns=p(()=>{"use strict";ls();Re();bn();Ct();Y();ay();M();j();sO();Fa=900*1e3,R6=3600*1e3});import{existsSync as sn,lstatSync as E6,readdirSync as A6,readlinkSync as P6,renameSync as my,unlinkSync as I6}from"node:fs";import jt from"node:path";function O6(e,t){let r=sy(e,t),n;try{n=E6(r)}catch{return null}if(!n.isSymbolicLink())return null;let o=jt.resolve(jt.dirname(r),P6(r));if(Ts(o)||Ts(r))return null;let s=`${r}.materialize-${Date.now()}`;return my(o,s),I6(r),my(s,r),o}function T6(e){let t=[];for(let r of iy()){let n=jt.join(e.fromDir,r),o=jt.join(e.toDir,r);!sn(n)||sn(o)||(my(n,o),t.push(r))}return t}function pO(e,t){let r=Qn(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 N6(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 D6(e){let t=Qn(e.canonicalDir),r=K(t.lastStatusPath,void 0),n=sn(t.stdoutPath),o=sn(t.heartbeatPath);if(!(n||o||r!=null))return null;let i=n?vn(t.stdoutPath):{finalResult:null},a=o?Ae(t.heartbeatPath):Ae(""),l=ar(a),c=N6({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:jt.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}),pO(u,e.canonicalDir),u}function M6(e,t){let r=!1,n={...e.workers||{}};for(let[o,s]of Object.entries(n)){let i=nn(t,e.id,o),a=jt.join(i,"worker.json");(pd(s.workerDir)||pd(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 L6(e){let t=[],r=nn(e.harnessRoot,e.run.id,e.workerName),n=eO(e.harnessRoot,e.run.id,e.workerName),o=Qn(r),s=T6({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=tO({harnessRoot:e.harnessRoot,runId:e.run.id,workerName:e.workerName,statusPath:e.statusPath}),a=K(i,void 0);if(!a&&sn(o.workerJsonPath)&&(a=K(o.workerJsonPath,void 0)),!a){let l=D6({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=iy().some(d=>sn(jt.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:jt.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 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 pO(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 B6(e,t){let r=jt.join(V(e.id),"workers");if(!sn(r))return[];let n=new Set(Object.keys(e.workers||{})),o=[];for(let s of A6(r,{withFileTypes:!0}))s.isDirectory()&&(n.has(s.name)||o.push(s.name));return o}function fO(){let{harnessRoot:e}=me(),t=py(e),r=[];for(let n of we()){let o=O6(e,n.id);o&&r.push({runId:n.id,worker:"*",action:"materialized_run_symlink",reason:`replaced symlink with real run dir (was ${o})`}),M6(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 B6(n,e))s.add(i),n.workers={...n.workers||{},[i]:{workerDir:nn(e,n.id,i),statusPath:jt.join(nn(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(...L6({run:n,workerName:i,harnessRoot:e,statusPath:a?.statusPath}))}}return{workers:r,runMetadataRetention:t}}var mO=p(()=>{"use strict";bn();vi();ay();Ns();Y();M()});import{execFileSync as gO}from"node:child_process";import hO from"node:path";function gy(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:null}function W6(e){let t=gy(e)?.match(/\/pull\/(\d+)$/);if(!t)return null;let r=Number.parseInt(t[1],10);return Number.isFinite(r)?r:null}function U6(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function F6(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 K6(e){let t=null;if(typeof e=="string"?t=Mo(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=gy(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 $6(e){try{let n=gO("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=gO("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:gy(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 H6(e){let t=Ae(e.heartbeatPath);return e.completionSnapshot?.finalResult??ar(t)}function j6(e){let t=new Map,r=V(e.id);for(let n of xt(e)){let o=K(hO.join(r,"workers",B(n),"worker.json"),void 0);if(o)for(let s of K6(H6(o))){let i=W6(s.prUrl);i!=null&&!t.has(i)&&t.set(i,s)}}return t}function V6(e,t){let r=Ae(e.heartbeatPath),n=[e.name,e.repairTargetPrUrl,e.taskPrUrl,e.branch,r.lastHeartbeatSummary,U6(t)].filter(Boolean).join(`
|
|
178
|
+
`);return F6(n)}function G6(e){return e.localOnly===!0&&!e.taskId&&!e.agentOsId}function hy(e={}){let t=e.lookupPr??$6,r=[],n=new Map;for(let o of we()){let s=j6(o),i=V(o.id);for(let a of xt(o)){let l=hO.join(i,"workers",B(a),"worker.json"),c=K(l,void 0);if(!c||!G6(c))continue;let u=se(c,{base:o.base,baseCommit:o.baseCommit});if(u.attention.state!=="needs_attention")continue;let d=null;for(let m of V6(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 yO=p(()=>{"use strict";bn();ec();xe();Y();Oo();M()});import J6 from"node:path";function Y6(){return process.env.KYNVER_NO_STALE_CLEANUP==="1"}function kO(e,t){let r=Xu({worker:e,status:t}),n=r?Qu(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 z6(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 yy(){let e=fO();if(Y6()){let s=hy(),i=fy();return{workers:[],finalizedRuns:Ua(),metadataReconcile:e,localPrAttentionReconcile:s,terminalWorkerArchive:i}}let t=[],r=Date.now();for(let s of we())for(let i of xt(s)){let a=J6.join(V(s.id),"workers",B(i),"worker.json"),l=K(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=se(l,{base:s.base,baseCommit:s.baseCommit});if(c.finalResult){if(l.status==="running"){let u=kO(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=kO(l,c);l.status=u.nextStatus,l.reconciledAt=new Date().toISOString(),l.reconcileReason=u.reason,z6(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&&te(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>q6,m=Number.isFinite(d)&&r-d>Lf;if(f&&m){ye(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=hy(),o=fy();return{workers:t,finalizedRuns:Ua(),metadataReconcile:e,localPrAttentionReconcile:n,terminalWorkerArchive:o}}var q6,ky=p(()=>{"use strict";rn();Y();Oo();Sh();xe();M();mO();yO();Ns();q6=900*1e3});import{readdirSync as X6,readFileSync as Q6}from"node:fs";function n4(e){if(process.platform!=="linux"||!e.trim())return null;let t=[];try{t=X6("/proc")}catch{return null}for(let r of t)if(/^\d+$/.test(r)&&Number(r)!==process.pid)try{if(Q6(`/proc/${r}/cmdline`,"utf8").replace(/\0/g," ").includes(e))return Number(r)}catch{}return null}async function bO(e){let t=Pr(),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??e4,i=e.findOrphanPid??n4,a=[],l;try{l=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-t4).toISOString(),limit:r4})}catch{return Zn.recoveryStoreFailures+=1,r}for(let c of l){let u=c.idempotencyKey.slice(Z6.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=_a(f);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${d}:`,limit:10}).some(S=>{if(g===null)return!0;let R=_a(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})){td({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){Zn.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?(Rs({taskId:d,leaseToken:f},"restart_recovery"),b&&(Ca(k,b),en(k,b)),Zn.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}):(Rs({taskId:d,leaseToken:f},"restart_recovery_refused"),a.push({taskId:d,leaseToken:f,runId:k,workerName:b,action:"release_refused",detail:_.detail}))}catch{Zn.recoveryStoreFailures+=1}}return{mode:t,scanned:l.length,outcomes:a}}function vO(){return{"dispatchReceipts.recoveredStrandedClaims":Zn.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":Zn.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":Zn.recoveryStoreFailures}}var Z6,e4,t4,r4,Zn,by=p(()=>{"use strict";Jr();ws();Yn();_s();Z6="dispatch:claim:",e4=900*1e3,t4=10080*60*1e3,r4=200,Zn={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0}});import o4 from"node:path";async function wO(e){if(RO||Pr()!=="enforce")return null;RO=!0;try{let t=Te().runnerId,r=await bO({hasLiveWorker:e.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>o4.join(me().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await Ba({baseUrl:e.baseUrl,secret:e.secret,agentOsId:e.agentOsId,taskId:n,leaseOwner:ha(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 RO,SO=p(()=>{"use strict";Y();ya();yr();Zh();by();ws();RO=!1});import s4 from"node:os";function _O(e,t={}){let r=E(),n=(t.boxKind??_t(r)).trim().toLowerCase()||"forge",o=t.hostLabel??s4.hostname();return{boxId:$o({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:mx()}}var xO=p(()=>{"use strict";j();Me();Ho();Xc()});import i4 from"node:path";async function fd(e){let t=e.pipeline===!0||e.pipeline==="true";try{let r=re(String(St(String(e.run||""),"--run"))),n=String(St(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=Te({runId:r.id}).runnerId,a=await CP({run:r.id,agentOsId:n,...e},"run_sweep"),l=[];for(let f of Object.keys(r.workers||{})){let m=K(i4.join(V(r.id),"workers",B(f),"worker.json"),void 0);if(!m||!m.dispatched||!m.taskId)continue;let g=se(m);if(g.alive||g.finalResult||m.completionReportedAt)continue;try{let k=await Cs({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=Pu({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 vy=p(()=>{"use strict";j();Ue();Y();xe();M();ya();yr();Es()});async function CO(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 EO=p(()=>{"use strict";j();Ue()});import a4 from"node:path";async function AO(e,t){let r=re(e),n=String(t.agentOsId||"");if(!n)return[];let o=[];for(let s of Object.keys(r.workers||{})){let i=K(a4.join(V(r.id),"workers",B(s),"worker.json"),void 0);if(!i?.dispatched||!i.taskId)continue;let a=se(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 CO({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 PO=p(()=>{"use strict";xe();Y();M();EO()});function IO(e){let t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(t==="node_modules"||t.startsWith("node_modules/"))return!0;for(let r of Ry)if(t===r||t.startsWith(`${r}/`))return!0;return!1}var Ry,wy=p(()=>{"use strict";Ry=[".next",".turbo","dist","build",".cache","node_modules/.cache"]});function ht(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!IO(n)})}var eo=p(()=>{"use strict";wy()});function to(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 Ka(e){let t=e.gitAncestry?.relation;return t==="merged"||t==="synced"?ht(e.changedFiles).length>0:!!(to(e.finalResult)||t==="ahead"||t==="diverged"||e.changedFiles.length>0&&e.finalResult)}var $a=p(()=>{"use strict";eo()});function Ha(e){return e.status||(e.status=se(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function Sy(e,t){if(e.status)return ht(e.status.changedFiles).length>0;let r=t?t.porcelain(e.worktreePath):pi(e.worktreePath);return ht(r).length>0}function l4(e){let t=e.worker.completionSnapshot?.finalResult;return t??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function _y(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=l4(e);if(o&&!te(r.pid)){let i=t?.gitStatusCache?t.gitStatusCache.porcelain(e.worktreePath):pi(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"}:Bl(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??to(s)};return e.status=u,u}return Ha(e)}var md=p(()=>{"use strict";Re();xe();eo();$a();M()});function c4(e,t=Date.now(),r=Fa){let n=Ae(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=t-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<r}function Ds(e,t=Date.now(),r=Fa){return te(e.pid)?!0:c4(e,t,r)}var gd=p(()=>{"use strict";bn();Ns();M()});function u4(e,t){return t?t.runTerminalCache.derive(e.run):Xn(e.run)}function Tr(e,t=Date.now()){return Ds(e.worker,t)}function xy(e,t){return Or.has(e.run.status)?!1:u4(e,t)!==null}function OO(e,t,r=Date.now()){if(Tr(e,r))return!0;if(Or.has(e.run.status)||xy(e,t))return!1;let n=Ha(e);return Le(n)?!1:!!Tr(e,r)}var Cy=p(()=>{"use strict";rn();xe();md();gd()});function TO(e,t){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(Tr(e))return!0;let n=t??Ha(e);return!!(!Le(n)||Ka(n)||ht(n.changedFiles).length>0||Do({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:to(n.finalResult)}).blocked)}var NO=p(()=>{"use strict";Zl();md();eo();Cy();xe();$a()});import{existsSync as MO,mkdirSync as d4,writeFileSync as DO}from"node:fs";import hd from"node:path";function LO(e,t,r){return hd.join(e,"salvage",B(t),B(r))}function BO(e){return MO(hd.join(LO(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function WO(e){let t=LO(e.harnessRoot,e.indexed.runId,e.indexed.workerName);d4(t,{recursive:!0});let r=hd.join(t,"salvage.patch"),n=!1;if(MO(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(`
|
|
179
|
+
`);a.trim()&&(DO(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 pI=p(()=>{"use strict";ve();N()});import Qu from"node:path";function CY(e){e.writeSalvageEvidence&&xY.has(e.skipReason)&&(Er(e.indexed,e.now)||uI({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})||dI({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}))}function EY(e){let{indexed:t,worktreesAgeMs:r,terminalWorktreesAgeMs:n}=e;return t&&(Cr.has(t.run.status)||e.liveness&&$h(t,e.liveness)||e.liveness&&Me(Kh(t,e.liveness))&&!Er(t))?n:r}function AY(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:EY(e)}function PY(e,t){if(e.harnessRoot?.trim())return Qu.resolve(e.harnessRoot);let r=t.worker.workerDir;if(!r)return null;let n=`${Qu.sep}runs${Qu.sep}`,o=r.indexOf(n);return o<0?null:r.slice(0,o+n.length-1)}function fI(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=AY(e);if(n<=0&&!r&&l<=0)return"worktrees_disabled";if(l>0&&o<l)return"below_age_threshold";if(Er(t,a))return"active_worker";let c=Kh(t,e.liveness),u=PY(e,t),d=g=>{if(u)try{CY({indexed:t,harnessRoot:u,skipReason:g,status:c,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})}catch{}return g};if(sI(t,c)){let g=d("completion_blocked");if(g)return g}if(Fh(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(oI(t,e.liveness,a)||!Me(c))return"run_still_active";if(Ea(c)){let g=d("pr_or_unmerged_commits");if(g)return g}if(pt(c.changedFiles).length>0){let g=d("dirty_worktree");if(g)return g}if(Co({finalResult:c.finalResult,changedFiles:c.changedFiles,gitAncestry:c.gitAncestry,prUrl:Gn(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 jh(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(Qu.resolve(o))||t&&Er(t)?"active_worker":t&&Fh(t,e.gitStatusCache)?"dirty_worktree":null}function mI(e){return jh(e)}var xY,gI=p(()=>{"use strict";Dl();Yu();Se();qr();Hh();iI();pI();Vn();Aa();Vn();Aa();xY=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"])});var Zu=p(()=>{"use strict"});function yI(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)hI.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||hI.has(s.skipReason)&&o(s.path,s.skipReason);return r}var hI,kI=p(()=>{"use strict";Zu();hI=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"])});import bI from"node:path";function OY(e,t){return Ss(e,t)}function vI(e,t=Date.now()){let r=new Set,n=new Set;for(let o of e){for(let s of lc(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let l=W(bI.join(bi(o,s.id),"workers",L(a),"worker.json"),void 0);if(!l?.worktreePath)continue;let c=bI.resolve(l.worktreePath);OY(l,t)&&(i=!0,r.add(c))}i&&n.add(`${o}\0${s.id}`)}for(let s of UP(o))n.add(s)}return{activeWorktreePaths:r,liveRunKeys:n}}function RI(e,t,r,n){return r?n.has(`${t}\0${r}`):!1}var Vh=p(()=>{"use strict";z();wt();ws();zu();N()});import{existsSync as wI,readdirSync as SI,statSync as TY}from"node:fs";import _I from"node:path";function NY(e,t){try{let r=TY(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function DY(e,t){let r=_I.join(e,"runs",t,"run.json");return wI(r)?W(r,null):null}function xI(e){try{return SI(e).length===0}catch{return!1}}function CI(e){let{harnessRoot:t,runId:r,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(RI(n,t,r,i.liveRunKeys)||!xI(n))return"run_still_active";let a=DY(t,r);return a&&!Cr.has(a.status)&&!$n(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function EI(e){if(!wI(e.worktreesDir))return[];let t=[],r;try{r=SI(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=_I.join(e.worktreesDir,o);xI(s)&&t.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:NY(s,e.now)})}return t}var AI=p(()=>{"use strict";Vh();qr();N()});import{execFileSync as MY}from"node:child_process";import{existsSync as PI,readdirSync as LY,statSync as BY}from"node:fs";import UY from"node:path";function FY(e,t=WY){if(!PI(e))return 0;try{let n=MY("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 Ar(e,t=5e4){if(!PI(e))return 0;let r=FY(e);if(r!==null)return r;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=LY(i)}catch{continue}for(let l of a){if(o++>t)return null;let c=UY.join(i,l),u;try{u=BY(c)}catch{continue}u.isDirectory()?s.push(c):n+=u.size}}return n}var WY,Ia=p(()=>{"use strict";WY=2500});import{lstatSync as KY,readdirSync as $Y}from"node:fs";function II(e){try{let t=KY(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 OI(e,t=32){let r=II(e);if(!r)return!1;if(r.foreign)return!0;try{let n=$Y(e),o=0;for(let s of n){if(o>=t)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=II(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}var TI=p(()=>{"use strict"});import ft from"node:path";function NI(e,t,r,n){let o=ft.resolve(e),s=`${ft.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=ft.relative(r,i);if(a.startsWith("..")||ft.isAbsolute(a))return"path_outside_harness";let l=a.split(ft.sep);return l.length<3||l[l.length-1]!==n||!o.startsWith(ft.resolve(t))?"path_outside_harness":null}function ed(e,t,r){return NI(e,t,r,"node_modules")}function td(e,t,r){return NI(e,t,r,".next")}function rd(e,t,r){let n=ft.resolve(e),o=ft.relative(r,n);return o.startsWith("..")||ft.isAbsolute(o)||o.split(ft.sep).length<3||!n.startsWith(ft.resolve(t))?"path_outside_harness":null}function DI(e,t,r){let n=ft.resolve(e);return ed(n,t,r)===null||td(n,t,r)===null||rd(n,t,r)===null}var Gh=p(()=>{"use strict"});import{spawnSync as HY}from"node:child_process";import MI from"node:path";function BI(){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 LI(e){let t=HY("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:t.status===0,stderr:`${t.stderr??""}${t.stdout??""}`.trim()}}function UI(e,t,r){if(!DI(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=LI(["chown","-R",`${n}:${o}`,MI.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=LI(["rm","-rf",MI.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 Jh,WI=p(()=>{"use strict";Gh();Jh="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 jY,rmSync as VY}from"node:fs";function GY(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function FI(e,t,r={}){if(!jY(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?Ko(n):null,i=e.bytes??Ar(e.path)??void 0,a=r.removePath??VY,l=r.hasForeignOwnedEntry??OI;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(c){if(!GY(c)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let u=l(e.path),d=BI();if(!(d==="force"||d==="auto"&&u))return u?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; ${Jh}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let f=UI(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}; ${Jh}`}}}var KI=p(()=>{"use strict";Ia();wt();TI();WI()});import{existsSync as qh,rmSync as $I}from"node:fs";function Yh(e){let t=e.harnessRoot;return!t||!MP(e.path,t)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function zh(e,t){let r=Yh(e);if(r)return r;let n=FI(e,t);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function HI(e,t){return zh(e,t)}function jI(e,t){return zh(e,t)}function VI(e,t){return zh(e,t)}function GI(e,t){let r=Yh(e);if(r)return r;if(!qh(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??Ar(e.path);return $I(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 JI(e,t){let r=Yh(e);if(r)return r;if(!qh(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??Ar(e.path);return n&&le(n,["worktree","remove","--force",e.path],{allowFailure:!0}),qh(e.path)&&$I(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 qI=p(()=>{"use strict";ve();Ia();KI();ws();Gh()});import{existsSync as nd,readdirSync as od,statSync as JY}from"node:fs";import $t from"node:path";function Xh(e,t){try{let r=JY(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function zI(e,t){let r=$t.relative(t,e);return r===""||!r.startsWith("..")&&!$t.isAbsolute(r)}function YI(e,t,r,n){let o=[];for(let s of Uh){if(s===".next")continue;let i=$t.join(e,s);if(!nd(i))continue;let a=$t.resolve(i);r.has(a)||zI(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:Xh(a,t.now)}))}return o}function XI(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||t.push(...YI(n.worktreePath,e,r,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!nd(e.worktreesDir))return t;for(let n of od(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=$t.join(e.worktreesDir,n.name);for(let s of od(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=$t.join(o,s.name);t.push(...YI(i,e,r,{runId:n.name,worker:s.name}))}}return t}function QI(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;nd(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:Xh(a,e.now)})))}if(!r||!nd(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add($t.resolve(i.worktreePath));for(let i of od(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=$t.join(e.worktreesDir,i.name),l;try{l=od(a,{withFileTypes:!0})}catch{continue}for(let c of l){if(!c.isDirectory())continue;let u=$t.resolve($t.join(a,c.name));o.has(u)||s.has(u)||zI(u,e.harnessRoot)&&(o.add(u),n.push({kind:"remove_worktree",path:u,bytes:null,runId:i.name,worker:c.name,ageMs:Xh(u,e.now)}))}}return n}var ZI=p(()=>{"use strict";Wh()});import{existsSync as rO,readdirSync as eO,statSync as qY}from"node:fs";import _s from"node:path";function zY(e,t){try{let r=qY(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function XY(e,t){let r=_s.relative(t,e);return r===""||!r.startsWith("..")&&!_s.isAbsolute(r)}function QY(e,t,r,n,o,s){if(!rO(n))return;let i=_s.resolve(n);t.has(i)||XY(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:zY(i,r.now)}))}function tO(e,t,r,n,o){for(let s of YY)QY(e,t,r,_s.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||tO(t,r,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!rO(e.worktreesDir))return t;for(let n of eO(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=_s.join(e.worktreesDir,n.name),s;try{s=eO(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=_s.join(o,i.name);tO(t,r,e,a,{runId:n.name,worker:i.name})}}return t}var YY,oO=p(()=>{"use strict";YY=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}]});import{existsSync as sO,statSync as ZY}from"node:fs";import Ht from"node:path";function ez(e,t){try{let r=ZY(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function tz(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 wz,MO=p(()=>{"use strict";wz=5e3});var ad,LO=p(()=>{"use strict";MO();ad=class{cache=new Map;porcelain(t){let r=t,n=this.cache.get(r);if(n!==void 0)return n;let o=DO(r)??[];return this.cache.set(r,o),o}}});var ld,BO=p(()=>{"use strict";qr();ld=class{cache=new Map;derive(t){let r=this.cache.get(t.id);if(r!==void 0)return r;let n=$n(t);return this.cache.set(t.id,n),n}}});function _z(e){let t={};for(let r of e)t[r.kind]=(t[r.kind]??0)+1;return t}function UO(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:_z(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 WO=p(()=>{"use strict"});import gt from"node:path";function xz(e={}){let t=e.harnessRoot?Ae(e.harnessRoot):it(),r=SO({harnessRoot:t}),n=e.now??Date.now();return{harnessRoot:t,scanRoots:r,now:n}}function Cz(e){return typeof e=="string"?{reason:e}:e}function xs(e,t,r,n){e.push({path:t,reason:r,...n?{detail:n}:{}})}function cd(e,t,r){return!t||e.bytes!=null?e:{...e,bytes:Ar(e.path,r)}}function FO(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 Ez(e,t){return e.kind==="remove_next_cache"?jI(e,t):HI(e,t)}function Az(e,t,r){return e.kind==="remove_next_cache"?td(e.path,t,r):ed(e.path,t,r)}function Pz(e){let t=new Map;for(let r of e)for(let[n,o]of cO(r))t.set(n,o);return t}function KO(e,t){return e.runId&&e.worker?gt.join(t,e.runId,e.worker):gt.resolve(e.path,"..")}function $O(e){return e.indexed?!1:ty({harnessRoot:e.harnessRoot,runId:e.candidate.runId,workerName:e.candidate.worker,now:e.now})}function Iz(e={}){let t=Zh(e),r=xO();t=CO(t,r);let n=xz(e);mt("scan",`${n.scanRoots.length} harness root(s)`);let o=vI(n.scanRoots,n.now),s=t.finalizeStaleRuns?xa().map(C=>({runId:C.runId,from:C.from,to:C.to})):[];s.length>0&&mt("finalize",`${s.length} stale run(s) marked terminal`),mt("index","building worktree index");let i=Pz(n.scanRoots);mt("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new ld,gitStatusCache:new ad,gitRevCache:new id},l=[],c=[],u=new Set,d=t.maxActionsPerSweep,m=()=>c.length>=d;for(let C of n.scanRoots){if(m())break;mt("root",C);let $=gt.join(C,"worktrees"),B=lO(i,C),D={harnessRoot:C,worktreesDir:$,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter,index:B,now:n.now},J=t.scanDependencyCaches?nO(D):[];mt("dependency",t.scanDependencyCaches?`${J.length} cache candidate(s) at ${C}`:"skipped (worktree-only sweep)");let H=0;for(let T of J){if(m())break;H+=1,H%50===0&&mt("dependency",`${H}/${J.length} evaluated`);let V=gt.resolve(T.path);if(u.has(V))continue;u.add(V);let F={...T,path:V},Z=Az(F,C,$);if(Z){xs(l,F.path,Z),c.push({...F,executed:!1,skipped:!0,skipReason:Z});continue}let ue=KO(F,$),Ie=B.get(gt.resolve(ue))??null,Qt=$O({candidate:F,indexed:Ie,harnessRoot:C,now:n.now}),re=jh({indexed:Ie,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:F.ageMs,worktreePath:ue,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:Qt,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(re){xs(l,F.path,re),c.push({...F,executed:!1,skipped:!0,skipReason:re});continue}c.push(Ez(cd(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(t.scanDependencyCaches)for(let T of XI(D)){if(m())break;let V=gt.resolve(T.path);if(u.has(V))continue;u.add(V);let F={...T,path:V},Z=rd(F.path,C,$);if(Z){xs(l,F.path,Z),c.push({...F,executed:!1,skipped:!0,skipReason:Z});continue}let ue=KO(F,$),Ie=B.get(gt.resolve(ue))??null,Qt=$O({candidate:F,indexed:Ie,harnessRoot:C,now:n.now}),re=mI({indexed:Ie,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:F.ageMs,worktreePath:ue,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:Qt,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(re){xs(l,F.path,re),c.push({...F,executed:!1,skipped:!0,skipReason:re});continue}c.push(VI(cd(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}let P=[...QI(D),...iO(D)];mt("worktrees",`${P.length} candidate(s) at ${C}`);let x=new Set,j=0;for(let T of P){if(m())break;j+=1,j%50===0&&mt("worktrees",`${j}/${P.length} evaluated`);let V=gt.resolve(T.path);if(x.has(V))continue;x.add(V);let F={...T,path:V},Z=B.get(gt.resolve(F.path))??null,ue=Z?null:yO({worktreePath:F.path,harnessRoot:C,runId:F.runId,workerName:F.worker,now:n.now}),Ie=fI({indexed:Z,worktreePath:gt.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:C,writeSalvageEvidence:t.execute});if(Ie){let{reason:Qt,detail:re}=Cz(Ie);xs(l,F.path,Qt,re),c.push({...F,executed:!1,skipped:!0,skipReason:Qt});continue}c.push(JI(cd(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(!m()&&t.runDirectoriesAgeMs>=0)for(let T of EI({harnessRoot:C,worktreesDir:$,runDirectoriesAgeMs:t.runDirectoriesAgeMs,runIdFilter:t.runIdFilter,activeGuards:o,now:n.now})){if(m())break;let V=gt.resolve(T.path);if(u.has(V))continue;u.add(V);let F={...T,path:V},Z=F.runId??gt.basename(V),ue=CI({harnessRoot:C,runId:Z,runPath:V,ageMs:F.ageMs,runDirectoriesAgeMs:t.runDirectoriesAgeMs,activeGuards:o});if(ue){xs(l,F.path,ue),c.push({...F,executed:!1,skipped:!0,skipReason:ue});continue}c.push(GI(cd(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}}let f=0,g=0,h=0,y=0,b=0,k=0;for(let C of c)C.bytes&&(f+=C.bytes),!C.skipped&&!C.executed&&C.bytes&&(h+=C.bytes),C.executed?(b+=1,y+=C.bytes??0,C.kind==="remove_run_directory"&&(g+=1)):C.skipped&&(k+=1,C.skipReason==="dry_run"&&C.bytes&&(h+=C.bytes));let v=t.accountBytes?vO({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:t.storagePerRunEntryCap}):void 0,S=Ro(),_=t.execute&&IO(S),w=_?PO({execute:!0}):null,R=S?{observed:!0,execute:_,dumpCount:S.dumpCount,totalBytes:S.totalBytes,removedCount:w?.removed.length??0,removedBytes:w?.removedBytes??0,executables:S.executables,path:S.path,reason:S.reason}:void 0;w&&w.removed.length>0&&(y+=w.removedBytes,b+=w.removed.length,mt("wsl-crashes",`removed ${w.removed.length} dump(s), ${w.removedBytes} bytes`)),mt("complete",`${c.length} action(s), ${k} skipped, ${b} removed`);let M=yI(c,l),A=UO({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:b,skippedPaths:k,skipReasons:FO(c,l)},...v?{storage:v}:{},...M.length>0?{preservedLivePaths:M}:{},...g>0?{removedRunDirectories:g}:{},...R?{wslCrashDumps:R}:{}});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:b,skippedPaths:k,skipReasons:FO(c,l)},...v?{storage:v}:{},...M.length>0?{preservedLivePaths:M}:{},...g>0?{removedRunDirectories:g}:{},...R?{wslCrashDumps:R}:{},compactSummary:A}}function HO(e){let t=mO(e);return Iz({execute:t.execute,finalizeStaleRuns:t.finalizeStaleRuns,accountBytes:t.accountBytes,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter})}function jO(){return process.env.KYNVER_PIPELINE_CLEANUP!=="0"}var VO=p(()=>{"use strict";wt();gI();kI();AI();qI();ZI();oO();aO();uO();qr();Ia();gO();kO();RO();_O();Vh();EO();OO();El();TO();NO();LO();BO();WO()});function GO(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 JO(e,t){let r=GO(e),n=GO(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 Oz,j_e,qO=p(()=>{"use strict";Zs();Oz={"@kynver-app/runtime":"0.1.83","@kynver-app/openclaw-agent-os":"0.1.43","@kynver-app/mcp-agent-os":"0.3.34"},j_e=Object.keys(Oz)});import{readFile as Tz}from"node:fs/promises";import{homedir as Nz}from"node:os";import Yn from"node:path";function Cs(e){let t=e?.trim();return t||null}function Mz(e){return[...new Set(e.filter(t=>!!t))]}function Lz(){let e=Nz(),t=Cs(process.env.KYNVER_OPENCLAW_NPM_ROOT)??Cs(process.env.OPENCLAW_NPM_ROOT)??Yn.join(e,".openclaw","npm"),r=Cs(process.env.KYNVER_NPM_GLOBAL_ROOT)??Cs(process.env.KYNVER_NPM_GLOBAL_MODULES_ROOT)??(Cs(process.env.NPM_CONFIG_PREFIX)?Yn.join(Cs(process.env.NPM_CONFIG_PREFIX),"lib","node_modules"):Yn.join(e,".npm-global","lib","node_modules"));return Mz([Yn.join(t,"lib","node_modules"),Yn.join(t,"node_modules"),r.endsWith("node_modules")?r:Yn.join(r,"lib","node_modules")])}async function Bz(e){try{let t=JSON.parse(await Tz(e,"utf8"));return typeof t.version=="string"&&t.version.trim()?t.version.trim():null}catch{return null}}function Uz(e){let t=Lz(),r=new Set,n=[];for(let o of t){let s=Yn.join(o,e,"package.json");r.has(s)||(r.add(s),n.push(s))}return n}async function YO(e=new Date().toISOString()){let t={};for(let r of Dz){let n=null;for(let o of Uz(r)){let s=await Bz(o);s&&(!n||JO(s,n.version)>0)&&(n={version:s,path:o})}n&&(t[r]={version:n.version,observedAt:e,path:n.path})}return t}var Dz,zO=p(()=>{"use strict";qO();Dz=["@kynver-app/runtime","@kynver-app/openclaw-agent-os","@kynver-app/mcp-agent-os"]});import{spawnSync as Wz}from"node:child_process";var Fz,Kz,XO,QO=p(()=>{"use strict";Fz=1e4,Kz=4*1024*1024,XO=(e,t,r)=>{try{let n=Wz(e,t,{windowsHide:!0,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r?.timeoutMs??Fz,maxBuffer:Kz});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 ud(e,t,r){return`${e} ${t} ${r}`}function ny(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 ZO(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 dd=p(()=>{"use strict"});function iy(){return Date.now()<oy}function Jz(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 eT(e){Jz(e)&&(oy=Math.max(oy,Date.now()+Gz))}function sy(e,t){if(iy())return null;let r=e("gh",["api",...t]);if(!r.ok||!r.stdout.trim())return eT(r),null;try{return JSON.parse(r.stdout)}catch{return null}}function qz(e,t,r,n){if(iy())return null;let o=e("gh",["pr","view",String(r),"--repo",t,"--json",n.join(",")]);if(!o.ok||!o.stdout.trim())return eT(o),null;try{return JSON.parse(o.stdout)}catch{return null}}function ay(e){return iy()?!1:process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()?!0:e("gh",["auth","token"]).ok}function Es(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Yz(e){return Array.isArray(e)?e.map(t=>Es(t)).filter(t=>t!==null).slice(0,Hz).map(t=>({context:t.context??null,state:t.state??null,target_url:t.target_url??null,description:t.description??null})):[]}function zz(e,t,r){let n=sy(e,[`repos/${t}/commits/${r}/status`]);return n?{state:n.state??null,statuses:Yz(n.statuses)}:null}var $z,Hz,jz,Vz,Gz,oy,tT,rT,nT,oT=p(()=>{"use strict";dd();$z=8e3,Hz=30,jz=100,Vz=400,Gz=3600*1e3,oy=0;tT={provider:"github",kind:"pr_snapshot",version:"2",isAvailable:ay,collect(e,t){let r=ZO(e);if(!r)return null;let n=qz(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=Es(n.author),s=Es(n.mergeCommit),i=Es(n.headRepositoryOwner),a=typeof n.body=="string"?n.body.slice(0,$z):null,l=Array.isArray(n.statusCheckRollup)?n.statusCheckRollup.map(u=>Es(u)).filter(u=>u!==null).slice(0,jz).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=>Es(u)).map(u=>typeof u?.path=="string"?u.path.trim():"").filter(Boolean).slice(0,Vz):[];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}}},rT={provider:"github",kind:"commit_status",version:"1",isAvailable:ay,collect(e,t){let r=ny(e);return r?zz(t,r.repo,r.sha):null}},nT={provider:"github",kind:"branch_reachability",version:"1",isAvailable:ay,collect(e,t){let r=ny(e);if(!r)return null;let n=sy(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=sy(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 ly(e){cy.some(t=>t.provider===e.provider&&t.kind===e.kind)||cy.push(e)}function sT(e,t){return cy.find(r=>r.provider===e&&r.kind===t)??null}function iT(){ly(tT),ly(rT),ly(nT)}var cy,aT=p(()=>{"use strict";oT();cy=[]});function lT(e,t={}){iT();let r=t.run??XO,n=t.now??(()=>new Date),o=t.maxSubjects??Xz,s=Date.now()+(t.deadlineMs??Qz),i=new Set,a=e.filter(f=>{let g=ud(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=ud(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 b=sT(f.provider,f.kind);if(!b){d.skipped.push({...f,reason:"no_recipe"});continue}let k=`${b.provider} ${b.kind}`,v=m.get(k);if(v===void 0&&(v=b.isAvailable(r),m.set(k,v)),!v){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 S=b.collect(f.subject,r);if(S==null){d.skipped.push({...f,reason:"collect_failed"});continue}d.collected+=1;let _={provider:f.provider,kind:f.kind,subject:f.subject,payload:S,observedAt:n().toISOString(),collectorVersion:b.version};d.items.push(_),t.cache?.set(g,_,n())}return d}var Xz,Qz,cT=p(()=>{"use strict";QO();aT();dd();Xz=1,Qz=25e3});import uT from"node:path";function dT(e){return uT.join(G(e),Zz)}function r6(e){return uT.join(G(e),e6)}function pT(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 fT(e){let t=W(dT(e),null);return pT(t?.wanted)}function mT(e,t){ye(dT(e),{savedAt:new Date().toISOString(),wanted:t})}function gT(e,t={}){let r=t.ttlMs??t6,n=r6(e),s={...W(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 hT(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.providerEvidenceWanted;return Array.isArray(t)?pT(t):null}var Zz,e6,t6,uy=p(()=>{"use strict";z();N();dd();Zz="provider-evidence-wanted.json",e6="provider-evidence-cache.json",t6=600*1e3});import n6 from"node:path";function dy(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 l6(){return n6.join(me().harnessRoot,o6)}function c6(e){let t=e.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),r=e==="github"?i6:a6;return dy(`KYNVER_PROVIDER_EVIDENCE_${t}_PER_MINUTE`,dy("KYNVER_PROVIDER_EVIDENCE_LIVE_COLLECTS_PER_MINUTE",r))}function yT(){return dy("KYNVER_PROVIDER_EVIDENCE_SHARED_CACHE_TTL_MS",s6)}function u6(e){return Math.floor(e.getTime()/6e4)*6e4}function d6(e){return`${e.provider}:${e.kind}`}function kT(e,t={}){let r=gT(e,{ttlMs:t.ttlMs??yT()}),n=t.file??l6(),o=W(n,null),s={...o?.items??{}},i={...o?.budget??{}},a=t.ttlMs??yT(),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=c6(u.provider);if(f===0)return!0;let g=d6(u),h=u6(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 o6,s6,i6,a6,bT=p(()=>{"use strict";z();N();uy();o6="provider-evidence-shared-cache.json",s6=6e4,i6=1,a6=1});function vT(e){let t=gS(),r=mr(e?.env??process.env),n=(e?.now??(()=>new Date))().getTime(),o={};if(r.flags.dispatchReceipts!=="off"){Object.assign(o,OE());let s=IE({nowMs:n,hasLiveWorker:e?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,r.flags.dispatchReceipts==="enforce"&&Object.assign(o,JP())}return r.flags.planOutbox!=="off"&&Object.assign(o,OA()),r.flags.admission!=="off"&&(Object.assign(o,ME()),r.flags.admission==="enforce"&&Object.assign(o,WE())),(r.flags.keeper!=="off"||r.flags.meshLease!=="off"||r.flags.quota!=="off")&&Object.assign(o,CS()),{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 RT=p(()=>{"use strict";Wr();Xo();ps();Lh();Ra();Fn();ms();Ti()});import{createHash as wT}from"node:crypto";import{access as p6,mkdir as Pxe,readFile as ST,rename as Ixe,writeFile as Oxe}from"node:fs/promises";import{constants as f6}from"node:fs";import{homedir as py}from"node:os";import qe from"node:path";function h6(){return process.env.KYNVER_MCP_UPDATE_INVENTORY_FILE?.trim()||qe.join(py(),".kynver","mcp-installations.json")}function y6(e){return e==="openclaw"?process.env.KYNVER_OPENCLAW_NPM_ROOT?.trim()||qe.join(py(),".openclaw","npm"):process.env.KYNVER_NPM_GLOBAL_ROOT?.trim()||process.env.NPM_CONFIG_PREFIX?.trim()||qe.join(py(),".npm-global")}function k6(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 b6(e,t){return[qe.join(e,"lib","node_modules",t,"package.json"),qe.join(e,"node_modules",t,"package.json")]}async function v6(e){try{return await p6(e,f6.R_OK),!0}catch{return!1}}async function R6(e=h6()){let t;try{t=JSON.parse(await ST(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||!g6.test(r.inventoryKey)||!m6.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 w6(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 S6(e){return wT("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 _6(e){let t=[];for(let r of e){let n=k6(y6(r.prefix)),o=(await Promise.all(b6(n,r.packageName).map(async f=>({candidate:f,ok:await v6(f)})))).find(f=>f.ok)?.candidate;if(!o)continue;let s=JSON.parse(await ST(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=w6(s,r,i),l=r.packageName==="@kynver-app/runtime",c=r.lifecycle??"runtime_stdio",u=wT("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:S6(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 _T(){return _6(await R6())}var m6,g6,xT=p(()=>{"use strict";m6=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/i,g6=/^[A-Za-z0-9._:-]{8,128}$/});import{createHash as x6,createHmac as C6,timingSafeEqual as E6}from"node:crypto";function fy(e){let t=e.trim().split(".");return t.length!==3||t[0]!=="krc1"||!t[1]||!t[2]?null:{tokenId:t[1],tokenHash:x6("sha256").update(`krc1.${t[1]}.${t[2]}`,"utf8").digest("hex")}}function CT(e,t,r){let n=fy(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=C6("sha256",Buffer.from(n.tokenHash,"hex")).update(JSON.stringify(e.claims),"utf8").digest(),i=Buffer.from(e.signature,"base64url");return i.length===s.length&&E6(i,s)}var my=p(()=>{"use strict"});import{createHash as A6}from"node:crypto";import{access as gy,mkdtemp as P6,readFile as OT,rm as I6}from"node:fs/promises";import{constants as hy}from"node:fs";import{tmpdir as O6}from"node:os";import As from"node:path";import{spawn as T6}from"node:child_process";import{Client as N6}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as D6}from"@modelcontextprotocol/sdk/client/stdio.js";function TT(){return"npm"}function AT(e,t){return Buffer.byteLength(e)>=ET?e:(e+t.toString("utf8")).slice(0,ET)}function L6(e){let t=process.env.KYNVER_MCP_UPDATE_NPM_CACHE?.trim(),r=t&&As.isAbsolute(t)?t:e,n={PATH:process.env.PATH,SystemRoot:process.env.SystemRoot,TEMP:process.env.TEMP,TMP:process.env.TMP,npm_config_registry:yy,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 NT(e,t,r=ky,n){return new Promise((o,s)=>{let i,a;try{[i,a]=oe(e,t)}catch(f){s(f);return}let l=T6(i,a,{shell:!1,windowsHide:!0,detached:be(),env:L6(n),stdio:["ignore","pipe","pipe"]}),c="",u="",d=!1;l.stdout.on("data",f=>{c=AT(c,f)}),l.stderr.on("data",f=>{u=AT(u,f)});let m=setTimeout(()=>{d=!0,l.pid&&Te(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 B6(e,t){let[r,n]=t.split("-",2);return!n||!["sha256","sha384","sha512"].includes(r)?!1:A6(r).update(e).digest("base64")===n}async function U6(e,t,r,n){let o=await NT(TT(),["pack",`${e}@${t}`,"--json","--pack-destination",n,`--registry=${yy}`,"--ignore-scripts"],ky,As.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"||As.basename(i)!==i)throw new Error("artifact_receipt_invalid");let a=As.join(n,i);if(!B6(await OT(a),r))throw new Error("artifact_integrity_mismatch");return a}async function W6(e,t,r){if((await NT(TT(),["install","--global","--prefix",e,t,`--registry=${yy}`,"--no-audit","--fund=false"],ky,r)).code!==0)throw new Error("package_install_failed")}async function DT(e){let t=JSON.parse(await OT(e.local.packageJsonPath,"utf8"));if(t.name!==e.report.packageName||typeof t.version!="string")throw new Error("installed_identity_mismatch");return t.version}function F6(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 PT(e){if(!e.local.binPath)throw new Error("mcp_binary_missing");await gy(e.local.binPath,hy.X_OK).catch(async()=>gy(e.local.binPath,hy.R_OK));let t=new D6({command:e.local.binPath,args:[],env:F6(e.local.envAllowlist),stderr:"pipe"}),r=new N6({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")),M6)})]);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 IT(e,t,r,n,o){let s=await P6(As.join(O6(),"kynver-mcp-update-"));try{let i=await U6(t,r,n,s);if(await o(),await W6(e.local.prefix,i,As.join(s,"npm-cache")),await DT(e)!==r)throw new Error("installed_version_mismatch")}finally{await I6(s,{recursive:!0,force:!0})}}async function MT(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 gy(e.local.prefix,hy.W_OK).catch(()=>{throw new Error("npm_prefix_not_writable")});let o=await DT(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 IT(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 PT(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 IT(e,t.packageName,t.installedVersion,t.rollbackIntegrity,async()=>{await n.beforePackageMutation?.()}),e.local.lifecycle==="runtime_stdio"){let c=await PT(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 yy,ET,ky,M6,LT=p(()=>{"use strict";qs();Ge();yy="https://registry.npmjs.org",ET=512*1024,ky=2*6e4,M6=2e4});import{createHmac as K6,timingSafeEqual as $6}from"node:crypto";import{mkdir as H6,readFile as j6,rename as V6,writeFile as G6}from"node:fs/promises";import{homedir as J6}from"node:os";import by from"node:path";function vy(){return process.env.KYNVER_MCP_UPDATE_STATE_ROOT?.trim()||by.join(J6(),".kynver","state","mcp-updates")}function BT(e){if(!/^[A-Za-z0-9_-]{8,128}$/.test(e))throw new Error("invalid update operation identity");return by.join(vy(),`${e}.json`)}function UT(e,t){let r=fy(t);return r?K6("sha256",Buffer.from(r.tokenHash,"hex")).update(JSON.stringify(e),"utf8").digest("base64url"):null}async function WT(e,t){try{let r=JSON.parse(await j6(BT(e),"utf8"));if(r.version!==2||r.operationId!==e||typeof r.integrityMac!="string")return null;let{integrityMac:n,...o}=r,s=UT(o,t);if(!s)return null;let i=Buffer.from(n,"utf8"),a=Buffer.from(s,"utf8");return i.length!==a.length||!$6(i,a)?null:r}catch{return null}}async function FT(e,t){let r=UT(e,t);if(!r)throw new Error("invalid_runner_credential_for_receipt");let n=BT(e.operationId);await H6(by.dirname(n),{recursive:!0,mode:448});let o=`${n}.${process.pid}.tmp`;await G6(o,`${JSON.stringify({...e,integrityMac:r},null,2)}
|
|
123
|
-
`,{mode:384}),await V6(o,n)}var Ry=p(()=>{"use strict";my()});import{randomBytes as wy}from"node:crypto";import{mkdir as Sy,readFile as _y,rename as q6,rm as pd,stat as Y6,writeFile as KT}from"node:fs/promises";import zn from"node:path";function $T(){return zn.join(vy(),z6)}async function HT(){try{let e=JSON.parse(await _y(zn.join($T(),"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:jT(e.pid)}}catch{return null}}function jT(e){if(!Number.isSafeInteger(e)||e<=0)return!0;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function X6(e){try{return await Y6(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function VT(){return Q6("mcp_update")}async function Q6(e){let t=$T(),r=`${t}.reclaiming`;await Sy(zn.dirname(t),{recursive:!0,mode:448});let n=!1;try{if(await X6(r))return null;for(let o=0;o<2;o+=1)try{await Sy(t,{mode:448});let s={pid:process.pid,nonce:wy(18).toString("base64url"),acquiredAt:new Date().toISOString(),holder:e};return await KT(zn.join(t,"owner.json"),JSON.stringify(s),{mode:384}),n&&(await pd(r,{recursive:!0,force:!0}),n=!1),{release:async()=>{try{let i=JSON.parse(await _y(zn.join(t,"owner.json"),"utf8"));i.pid===s.pid&&i.nonce===s.nonce&&await pd(t,{recursive:!0,force:!0})}catch{}}}}catch(s){if(s.code!=="EEXIST")throw s;if(!n)try{await Sy(r,{mode:448}),n=!0,await KT(zn.join(r,"owner.json"),JSON.stringify({pid:process.pid,nonce:wy(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 _y(zn.join(t,"owner.json"),"utf8"))}catch{return null}if(jT(i.pid))return null;let a=`${t}.stale-${process.pid}-${wy(8).toString("hex")}`;await q6(t,a),await pd(a,{recursive:!0,force:!0})}return null}finally{n&&await pd(r,{recursive:!0,force:!0})}}var z6,GT=p(()=>{"use strict";Ry();z6="host-mutation.lock"});function fd(e,t,r){return`${e}/api/agent-os/by-id/${encodeURIComponent(t)}/mcp-updates/${r}`}function Z6(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 JT(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 e4(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 qT(e){let t=pe(e.baseUrl),r=await _T();if(r.length===0)return{ok:!0,stage:"not_configured"};let n=await Cn(fd(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 VT();if(!o){let s=await HT();return{ok:!0,stage:"host_mutation_busy",...s?{heldBy:s.holder}:{}}}try{let s=await Cn(fd(t,e.agentOsId,"claim"),e.secret,{activeOwnedSessions:e.activeOwnedSessions});if(!s.ok)return{ok:!1,stage:"claim",status:s.status};let i=Z6(s.response);if(!i)return{ok:!0,stage:"idle"};if(!CT(i,e.secret,e.agentOsId))return{ok:!1,stage:"command_auth"};let a=await WT(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||!JT(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(v=>v.report.inventoryKey===i.claims.inventoryKey);if(!k||k.report.inventoryFingerprint!==i.claims.inventoryFingerprint)return{ok:!1,stage:"inventory_changed"};l=k,c=a&&JT(a.recovery,i)?a.recovery:e4(k,i)}let u=a?.acceptedAt??new Date().toISOString(),d=async(k,v,S)=>{await FT({version:2,operationId:i.claims.operationId,attempt:i.claims.attempt,nonce:i.claims.nonce,acceptedAt:u,phase:k,terminal:v,...S?{outcome:S}:{},recovery:c},e.secret)};await d(a?.attempt===i.claims.attempt?a.phase:"claimed",!1);let m="claimed",f=async k=>{if(!(await Cn(fd(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 MT(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 b=await Cn(fd(t,e.agentOsId,`operations/${encodeURIComponent(i.claims.operationId)}/complete`),e.secret,{attempt:i.claims.attempt,fenceToken:i.claims.fenceToken,...y});return b.ok?(await d(y.outcome,!0,y.outcome),{ok:y.outcome==="succeeded",stage:"complete",outcome:y.outcome}):{ok:!1,stage:"complete",status:b.status,outcome:y.outcome}}finally{await o.release()}}var YT=p(()=>{"use strict";K();Ue();xT();my();LT();GT();Ry()});import zT from"node:path";function t4(){let e=process.env.KYNVER_PIPELINE_SWEEP_ENABLED;return e?e==="1"||e.toLowerCase()==="true":!1}async function r4(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=W(zT.join(G(r.id),"workers",L(i),"worker.json"),void 0);if(!a?.taskId||a.localOnly||Dr(a))continue;if(oa(a)){n.push({worker:i,ok:!0,taskId:a.taskId??null,skipped:!0});continue}if(s>=o)break;s++;let l=te(a);if(!Me(l))continue;let c=xo({alive:l.alive,finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry});if(!a.dispatched&&!l.finalResult&&!c?.salvageable)continue;let u=await Hu({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 n4(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 YO(),c=$o(t),u=null;try{let S=fT(t);if(S.length>0){let _=kT(t);u=lT(S,{cache:_}),_.flush?.()}else u=null}catch{u=null}try{if(xr()!=="off"){let S=Po();DE({liveWorkers:S}),UE({liveWorkers:S})}else TE()}catch{}let d=({runId:S,workerName:_})=>{try{let{runsDir:w}=me(),R=zT.join(cr(w,L(S)),"workers",L(_),"worker.json"),M=W(R,null);return M?Dr(M):!1}catch{return!1}};await YP({agentOsId:e,baseUrl:s,secret:i,hasLiveWorker:d});let m=null;try{m=vT({hasLiveWorker:d})}catch{m=null}let f=null;try{f=Jl({control:To(e),supervisor:lR(),inFlightWorkers:Po().length})}catch{f=null}let g=Dc(t),h=await de(a,i,{agentOsId:e,runId:t,ingestHarness:!0,harnessBoardSnapshot:nh(t),resourceGate:r,boxResourceSnapshot:XP(r,{harnessRunId:t,boxKind:vt(I())}),packageVersions:l,...o?{harnessCleanup:o}:{},runnerPresence:Pe({runId:t}),activeHarnessWorkers:c,...g?.leaseToken?{meshCronLeaseToken:g.leaseToken}:{},...m?{localRunStore:m}:{},...f?{runtimeControlAck:f}:{},...u&&u.items.length>0?{providerEvidence:u.items}:{}},{agentOsId:e,baseUrl:s}),y=hT(h.response);if(y)try{mT(t,y)}catch{}let b=y_(h);if(b)try{h_(t,b)}catch{}let k=yS(h);k&&kS(e,k);let v=rR(h);return v&&lf(e,v),{ok:h.ok,httpStatus:h.status,response:h.response,...u?{providerEvidence:{attempted:u.attempted,collected:u.collected,skipped:u.skipped.length}}:{}}}async function md(e){let t=String(bt(String(e.run||""),"--run")),r=String(bt(String(e.agentOsId||""),"--agent-os-id")),n=e.execute!==!1&&e.execute!=="false";nh(t);let o=await Bc(r,e),s=Lc(o),i=ci({runId:t,configuredMaxWorkersOverride:s}),a=jO()?HO(t):void 0,l=await n4(r,t,i,e,a),c;if(n)try{let C=pe(e.baseUrl?String(e.baseUrl):void 0),$=await fe(e.secret?String(e.secret):void 0,r,{baseUrl:C});c=await qT({agentOsId:r,secret:$,baseUrl:C,activeOwnedSessions:Po().length})}catch(C){c={ok:!1,stage:"cycle",error:C instanceof Error?C.message:"update cycle failed"}}let u=pE(t,l),d=await aC(t,e),m=await r4(t,e);m.some(C=>C.ok&&!C.skipped)&&XS();let f=ci({runId:t,configuredMaxWorkersOverride:s}),g=Dh(),h=await tI(t,e),y=PP(f,l),b=y.maxStarts,k=To(r),v=oR(k);v&&(b=0);let S=t4()?await qu({run:t,agentOsId:r,pipeline:!0,...e}):{ok:!0,skipped:!0,reason:"pipeline_sweep_disabled"},_=null,w=0,R=EP(l),M=b;if(n&&M>0&&R.length>0){let C=Math.min(M,R.length),$=await wh({...e,run:t,agentOsId:r,targetTaskIds:R.join(",")},C),B=vs($);w+=B,M=Math.max(0,M-B),_={exactTargetTaskIds:R,exact:$,startedCount:w}}if(n&&M>0){let C=await wh({...e,run:t,agentOsId:r},M),$=vs(C);w+=$,_=_&&typeof _=="object"?{..._,broad:C,startedCount:w}:C}else!n||b<=0?_||(_={ok:!0,skipped:!0,reason:v??(n?f.reason??"no slots or queued work":"execute disabled"),maxStarts:0,dispatchAdvice:y,...R.length?{exactTargetTaskIds:R,exactOnly:!0}:{}}):_&&typeof _=="object"&&(_={..._,broadSkipped:!0,startedCount:w});let A=!y.underutilized&&b===0&&m.length===0&&w===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:S,dispatchAdvice:y,dispatch:_,idle:A,runtimeControl:k?{desiredState:k.desiredState,policyVersion:k.policyVersion}:null}}var xy=p(()=>{"use strict";dn();cc();K();Ue();CP();AP();IP();Mh();Io();Fn();zP();ms();QP();Tc();z();wt();Nl();Se();Bh();N();rI();gg();hs();yu();Ul();Dm();K();Ne();VO();Pu();zO();pr();cT();bT();uy();Im();RT();fm();YT()});var o4,s4,i4,gd,XT=p(()=>{"use strict";tr();o4=5*6e4,s4=5*6e4,i4=2160*60*60,gd=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()>o4?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<s4)return;let r=`${this.deps.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(this.deps.agentOsId)}/runner-credentials`;try{let n=await st(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({capabilities:["chat.relay"],ttlSeconds:i4,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 st(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 Ps(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 Xn(e,t,r){r===401&&t.kind==="box_token"&&e.auth?.invalidateToken()}var hd=p(()=>{"use strict"});import{createHash as a4,verify as l4,createPublicKey as c4}from"node:crypto";function Ey(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};return delete t[QT],t}function d4(e){return a4("sha256").update(Ze(Ey(e)),"utf8").digest("hex")}function Ay(e){return!e||typeof e!="object"||Array.isArray(e)?null:e[QT]??null}function p4(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 f4(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:Ze(r)===Ze(t)}function Cy(e,t){return{state:t,firstSeenAt:new Date(e.firstSeenSec*1e3).toISOString(),turnId:e.turnId}}function m4(e){return c4({key:Buffer.concat([u4,Buffer.from(e)]),format:"der",type:"spki"})}function ZT(e,t,r={}){let n=r.env??process.env,o=r.nowSec??Math.floor(Date.now()/1e3),s=Ay(e);if(s===null)return{ok:!1,code:"unsigned",reason:"turn carries no signed envelope"};if(!p4(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=Rn(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(Ze(i.payload),"utf8");c=l4(null,d,m4(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(d4(e)!==i.payload.payloadHash)return{ok:!1,code:"payload_tampered",reason:"turn payload does not match its signed hash"};if(!f4(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 (${g4(u.replay)})`,replay:u.replay}}function g4(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 QT,u4,yd,Py=p(()=>{"use strict";Lr();Ri();QT="turnEnvelope",u4=Buffer.from("302a300506032b6570032100","hex");yd=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:Cy(n,"turn_mismatch")}:n.state==="verified"?{ok:!0,redelivered:!0}:{ok:!1,replay:Cy(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:Cy(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 eN(e=process.env,t={}){let r=(e[h4]??t.chatTurnSignature??"").toString().trim().toLowerCase();return r==="optional"||r==="off"||r==="0"||r==="false"?"optional":"required"}function tN(e,t){return t?`turn_rejected_${e}: ${t}`:`turn_rejected_${e}`}function rN(e,t){if(!(Ay(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:y4(o)?o:null,signed:!1,userId:null,redelivered:!1}}let n=ZT(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 y4(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.byBox;return!!t&&typeof t=="object"&&!Array.isArray(t)}var h4,nN=p(()=>{"use strict";Py();h4="KYNVER_CHAT_TURN_SIGNATURE"});var kd,oN=p(()=>{"use strict";kd=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 k4}from"node:dns/promises";import{createServer as b4,request as v4}from"node:http";import{connect as R4,isIP as aN,isIPv4 as w4}from"node:net";function lN(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 Na(e){let t=lN(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 _4(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=lN(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 x4(e){let t=_4(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 Na(n(t[6],t[7]));if(t[0]===8194)return Na(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 sN(e){let t=aN(e);return t===4?Na(e):t===6?x4(e):!0}function C4(e){return e==="localhost"||e.endsWith(".localhost")||e==="localhost6"||e==="ip6-localhost"}function E4(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 cN(e){return(await k4(e,{all:!0})).map(r=>r.address)}async function iN(e,t=cN){let r=E4(e);if(!r||r.length>S4)return{allowed:!1,host:r,reason:"invalid host"};if(C4(r))return{allowed:!1,host:r,reason:`${r} is this computer (loopback): local services are not reachable from a folder step`};if(aN(r))return sN(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=>sN(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=>w4(s))??n[0]}}function Iy(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 DO(hd.join(t,"evidence.json"),`${JSON.stringify(o,null,2)}
|
|
182
|
+
`),o}var UO=p(()=>{"use strict";Re();M()});import yd from"node:path";function f4(e){e.writeSalvageEvidence&&p4.has(e.skipReason)&&(Tr(e.indexed,e.now)||BO({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})||WO({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}))}function m4(e){let{indexed:t,worktreesAgeMs:r,terminalWorktreesAgeMs:n}=e;return t&&(Or.has(t.run.status)||e.liveness&&xy(t,e.liveness)||e.liveness&&Le(_y(t,e.liveness))&&!Tr(t))?n:r}function g4(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:m4(e)}function h4(e,t){if(e.harnessRoot?.trim())return yd.resolve(e.harnessRoot);let r=t.worker.workerDir;if(!r)return null;let n=`${yd.sep}runs${yd.sep}`,o=r.indexOf(n);return o<0?null:r.slice(0,o+n.length-1)}function FO(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=g4(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=_y(t,e.liveness),u=h4(e,t),d=g=>{if(u)try{f4({indexed:t,harnessRoot:u,skipReason:g,status:c,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})}catch{}return g};if(TO(t,c)){let g=d("completion_blocked");if(g)return g}if(Sy(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(OO(t,e.liveness,a)||!Le(c))return"run_still_active";if(Ka(c)){let g=d("pr_or_unmerged_commits");if(g)return g}if(ht(c.changedFiles).length>0){let g=d("dirty_worktree");if(g)return g}if(Do({finalResult:c.finalResult,changedFiles:c.changedFiles,gitAncestry:c.gitAncestry,prUrl:to(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 Ey(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(yd.resolve(o))||t&&Tr(t)?"active_worker":t&&Sy(t,e.gitStatusCache)?"dirty_worktree":null}function KO(e){return Ey(e)}var p4,$O=p(()=>{"use strict";Zl();md();xe();rn();Cy();NO();UO();eo();$a();eo();$a();p4=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"])});var kd=p(()=>{"use strict"});function jO(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)HO.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||HO.has(s.skipReason)&&o(s.path,s.skipReason);return r}var HO,VO=p(()=>{"use strict";kd();HO=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"])});import GO from"node:path";function k4(e,t){return Ds(e,t)}function JO(e,t=Date.now()){let r=new Set,n=new Set;for(let o of e){for(let s of Ec(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let l=K(GO.join(Ni(o,s.id),"workers",B(a),"worker.json"),void 0);if(!l?.worktreePath)continue;let c=GO.resolve(l.worktreePath);k4(l,t)&&(i=!0,r.add(c))}i&&n.add(`${o}\0${s.id}`)}for(let s of dO(o))n.add(s)}return{activeWorktreePaths:r,liveRunKeys:n}}function qO(e,t,r,n){return r?n.has(`${t}\0${r}`):!1}var Ay=p(()=>{"use strict";Y();Ct();Ns();gd();M()});import{existsSync as YO,readdirSync as zO,statSync as b4}from"node:fs";import XO from"node:path";function v4(e,t){try{let r=b4(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function R4(e,t){let r=XO.join(e,"runs",t,"run.json");return YO(r)?K(r,null):null}function QO(e){try{return zO(e).length===0}catch{return!1}}function ZO(e){let{harnessRoot:t,runId:r,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(qO(n,t,r,i.liveRunKeys)||!QO(n))return"run_still_active";let a=R4(t,r);return a&&!Or.has(a.status)&&!Xn(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function eT(e){if(!YO(e.worktreesDir))return[];let t=[],r;try{r=zO(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=XO.join(e.worktreesDir,o);QO(s)&&t.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:v4(s,e.now)})}return t}var tT=p(()=>{"use strict";Ay();rn();M()});import{execFileSync as w4}from"node:child_process";import{existsSync as rT,readdirSync as S4,statSync as _4}from"node:fs";import x4 from"node:path";function E4(e,t=C4){if(!rT(e))return 0;try{let n=w4("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(!rT(e))return 0;let r=E4(e);if(r!==null)return r;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=S4(i)}catch{continue}for(let l of a){if(o++>t)return null;let c=x4.join(i,l),u;try{u=_4(c)}catch{continue}u.isDirectory()?s.push(c):n+=u.size}}return n}var C4,ja=p(()=>{"use strict";C4=2500});import{lstatSync as A4,readdirSync as P4}from"node:fs";function nT(e){try{let t=A4(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 oT(e,t=32){let r=nT(e);if(!r)return!1;if(r.foreign)return!0;try{let n=P4(e),o=0;for(let s of n){if(o>=t)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=nT(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}var sT=p(()=>{"use strict"});import yt from"node:path";function iT(e,t,r,n){let o=yt.resolve(e),s=`${yt.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=yt.relative(r,i);if(a.startsWith("..")||yt.isAbsolute(a))return"path_outside_harness";let l=a.split(yt.sep);return l.length<3||l[l.length-1]!==n||!o.startsWith(yt.resolve(t))?"path_outside_harness":null}function bd(e,t,r){return iT(e,t,r,"node_modules")}function vd(e,t,r){return iT(e,t,r,".next")}function Rd(e,t,r){let n=yt.resolve(e),o=yt.relative(r,n);return o.startsWith("..")||yt.isAbsolute(o)||o.split(yt.sep).length<3||!n.startsWith(yt.resolve(t))?"path_outside_harness":null}function aT(e,t,r){let n=yt.resolve(e);return bd(n,t,r)===null||vd(n,t,r)===null||Rd(n,t,r)===null}var Py=p(()=>{"use strict"});import{spawnSync as I4}from"node:child_process";import lT from"node:path";function uT(){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 cT(e){let t=I4("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:t.status===0,stderr:`${t.stderr??""}${t.stdout??""}`.trim()}}function dT(e,t,r){if(!aT(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=cT(["chown","-R",`${n}:${o}`,lT.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=cT(["rm","-rf",lT.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,pT=p(()=>{"use strict";Py();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 O4,rmSync as T4}from"node:fs";function N4(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function fT(e,t,r={}){if(!O4(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?zo(n):null,i=e.bytes??Nr(e.path)??void 0,a=r.removePath??T4,l=r.hasForeignOwnedEntry??oT;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(c){if(!N4(c)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let u=l(e.path),d=uT();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 m=dT(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}; ${Iy}`}}}var mT=p(()=>{"use strict";ja();Ct();sT();pT()});import{existsSync as Oy,rmSync as gT}from"node:fs";function Ty(e){let t=e.harnessRoot;return!t||!lO(e.path,t)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function Ny(e,t){let r=Ty(e);if(r)return r;let n=fT(e,t);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function hT(e,t){return Ny(e,t)}function yT(e,t){return Ny(e,t)}function kT(e,t){return Ny(e,t)}function bT(e,t){let r=Ty(e);if(r)return r;if(!Oy(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 gT(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 vT(e,t){let r=Ty(e);if(r)return r;if(!Oy(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&&le(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Oy(e.path)&&gT(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 RT=p(()=>{"use strict";Re();ja();mT();Ns();Py()});import{existsSync as wd,readdirSync as Sd,statSync as D4}from"node:fs";import Vt from"node:path";function Dy(e,t){try{let r=D4(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function ST(e,t){let r=Vt.relative(t,e);return r===""||!r.startsWith("..")&&!Vt.isAbsolute(r)}function wT(e,t,r,n){let o=[];for(let s of Ry){if(s===".next")continue;let i=Vt.join(e,s);if(!wd(i))continue;let a=Vt.resolve(i);r.has(a)||ST(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:Dy(a,t.now)}))}return o}function _T(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||t.push(...wT(n.worktreePath,e,r,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!wd(e.worktreesDir))return t;for(let n of Sd(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Vt.join(e.worktreesDir,n.name);for(let s of Sd(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=Vt.join(o,s.name);t.push(...wT(i,e,r,{runId:n.name,worker:s.name}))}}return t}function xT(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;wd(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:Dy(a,e.now)})))}if(!r||!wd(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(Vt.resolve(i.worktreePath));for(let i of Sd(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=Vt.join(e.worktreesDir,i.name),l;try{l=Sd(a,{withFileTypes:!0})}catch{continue}for(let c of l){if(!c.isDirectory())continue;let u=Vt.resolve(Vt.join(a,c.name));o.has(u)||s.has(u)||ST(u,e.harnessRoot)&&(o.add(u),n.push({kind:"remove_worktree",path:u,bytes:null,runId:i.name,worker:c.name,ageMs:Dy(u,e.now)}))}}return n}var CT=p(()=>{"use strict";wy()});import{existsSync as PT,readdirSync as ET,statSync as M4}from"node:fs";import Ms from"node:path";function B4(e,t){try{let r=M4(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function W4(e,t){let r=Ms.relative(t,e);return r===""||!r.startsWith("..")&&!Ms.isAbsolute(r)}function U4(e,t,r,n,o,s){if(!PT(n))return;let i=Ms.resolve(n);t.has(i)||W4(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:B4(i,r.now)}))}function AT(e,t,r,n,o){for(let s of L4)U4(e,t,r,Ms.join(n,s.dirName),s.kind,o)}function IT(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||AT(t,r,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!PT(e.worktreesDir))return t;for(let n of ET(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=Ms.join(e.worktreesDir,n.name),s;try{s=ET(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=Ms.join(o,i.name);AT(t,r,e,a,{runId:n.name,worker:i.name})}}return t}var L4,OT=p(()=>{"use strict";L4=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}]});import{existsSync as TT,statSync as F4}from"node:fs";import Gt from"node:path";function K4(e,t){try{let r=F4(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function $4(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 H4(e,t){let r=Gt.relative(Gt.resolve(t),Gt.resolve(e));return r!==""&&!r.startsWith("..")&&!Gt.isAbsolute(r)}function NT(e){if(!e.includeOrphans||!TT(e.worktreesDir))return[];let t=new Set;for(let s of e.index.values())s.run.repo&&t.add(Gt.resolve(s.run.repo));let r=new Set;for(let s of e.index.values())r.add(Gt.resolve(s.worktreePath));let n=[],o=new Set;for(let s of t){let i=0,a;try{a=le(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let l=$4(a);for(let c of l){if(i>=j4)break;let u=Gt.resolve(c.path);if(u===Gt.resolve(s)||!H4(u,e.worktreesDir)||r.has(u)||o.has(u)||!TT(u))continue;let f=Gt.relative(e.worktreesDir,u).split(Gt.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:K4(u,e.now)})}}return n}var j4,DT=p(()=>{"use strict";Re();j4=200});import Va from"node:path";function MT(e,t){let r=Va.resolve(t),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?Va.resolve(s.harnessRoot):null;i&&i!==r||n.set(o,s)}return n}function LT(e){let t=new Map;for(let r of Ec(e))for(let n of Object.keys(r.workers||{})){let o=Va.join(Ni(e,r.id),"workers",B(n),"worker.json"),s=K(o,void 0);s?.worktreePath&&t.set(Va.resolve(s.worktreePath),{harnessRoot:e,worktreePath:Va.resolve(s.worktreePath),runId:r.id,workerName:n,run:r,worker:s})}return t}var BT=p(()=>{"use strict";Y();M()});function Ga(e){let t=process.env[e];return t==="1"||t==="true"||t==="yes"}function ro(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)&&n>=0?n:t}function Ly(e={}){let t=e.execute===!0||e.execute!==!1&&Ga("KYNVER_CLEANUP_EXECUTE"),r=e.finalizeStaleRuns!==!1&&!Ga("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??ro("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??ro("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??ro("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??ro("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),l=e.maxActionsPerSweep??ro("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),c=e.includeOrphans===!0||Ga("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=Ga("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&&!Ga("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),m=ro("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),g=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:f&&m>0?m:null,h=ro("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 KT(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 Ly({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 $T=p(()=>{"use strict";kd()});import{existsSync as By,statSync as G4}from"node:fs";import no from"node:path";function J4(e,t){let r=no.relative(t,e);return r===""||!r.startsWith("..")&&!no.isAbsolute(r)}function q4(e,t,r){if(!By(e))return!1;try{let n=t-G4(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<r}catch{return!1}}function Wy(e){if(!e.runId||!e.workerName)return!1;let t=e.now??Date.now(),r=e.heartbeatFreshMs??HT,n=no.resolve(e.harnessRoot,"runs"),o=no.resolve(n,e.runId,"workers",e.workerName);if(!J4(o,n))return!1;let s=K(no.join(o,"worker.json"),void 0);return s&&Ds(s,t,r)?!0:s?!1:q4(no.join(o,"heartbeat.jsonl"),t,r)}function jT(e){let t=e.now??Date.now(),r=e.heartbeatFreshMs??HT;if(!By(e.worktreePath))return null;if(e.runId&&e.workerName&&Wy(e))return"active_worker";let n=no.join(e.worktreePath,".git");if(!By(n))return null;let o=Q(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(ht(s).length>0)return"dirty_worktree";let i=Q(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=Q(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 HT,VT=p(()=>{"use strict";Re();eo();gd();M();HT=1800*1e3});import{existsSync as Y4,readdirSync as GT,statSync as z4}from"node:fs";import X4 from"node:path";function JT(e={}){let t=Oe(e.harnessRoot??ut()),r=zo(t),n=e.now??Date.now(),o=new Date(n).toISOString();if(!Y4(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=GT(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=X4.join(r,u.name);try{let f=z4(d);l=l===null?f.mtimeMs:Math.min(l,f.mtimeMs)}catch{}try{for(let f of GT(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";Ct();ja()});import{existsSync as Q4}from"node:fs";import{homedir as Z4}from"node:os";import YT from"node:path";function Uy(e,t,r){if(!r?.trim())return;let n=Oe(r.trim());e.has(n)||(e.add(n),t.push(n))}function tX(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 zT(e={}){let t=new Set,r=[];Uy(t,r,e.harnessRoot??ut());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])Uy(t,r,o);if(tX(e))for(let o of eX){let s=YT.resolve(o);!t.has(s)&&Q4(s)&&Uy(t,r,s)}return r}var eX,XT=p(()=>{"use strict";Ct();eX=["/var/tmp/kynver-harness",YT.join(Z4(),".openclaw","harness")]});function rX(e){let t=process.env[e];return t==="1"||t==="true"||t==="yes"}function nX(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function QT(e={}){let t=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",r=nX("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 ZT(e,t){if(!t.pressured)return e;let r=e.execute||!rX("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 eN=p(()=>{"use strict";hi();kd()});import{unlinkSync as oX}from"node:fs";function _d(e){let t=process.env[e];return t==="1"||t==="true"||t==="yes"}function tN(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function sX(e,t,r){return e.length===0?[]:r?[...e]:e.length<=t?[]:e.slice(t)}function rN(e={}){let t=e.execute===!0||_d("KYNVER_WSL_CRASH_DUMP_EXECUTE")||_d("KYNVER_CLEANUP_EXECUTE"),r=e.purgeAll===!0||_d("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),n=Math.max(0,e.keepNewest??tN("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",r?0:1)),o=Io({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=sX(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{oX(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 nN(e){return e?_d("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>tN("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}var oN=p(()=>{"use strict";Hl()});function kt(e,t){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let r=t?`: ${t}`:"";console.error(`[kynver cleanup] ${e}${r}`)}var sN=p(()=>{"use strict"});var xd,iN=p(()=>{"use strict";Re();xd=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=Q(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 iX}from"node:child_process";import{existsSync as aX}from"node:fs";import lX from"node:path";function uX(e,t){if(!aX(lX.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let r=iX("git",t,{windowsHide:!0,cwd:e,encoding:"utf8",timeout:cX}),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 aN(e){let t=uX(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 cX,lN=p(()=>{"use strict";cX=5e3});var Cd,cN=p(()=>{"use strict";lN();Cd=class{cache=new Map;porcelain(t){let r=t,n=this.cache.get(r);if(n!==void 0)return n;let o=aN(r)??[];return this.cache.set(r,o),o}}});var Ed,uN=p(()=>{"use strict";rn();Ed=class{cache=new Map;derive(t){let r=this.cache.get(t.id);if(r!==void 0)return r;let n=Xn(t);return this.cache.set(t.id,n),n}}});function dX(e){let t={};for(let r of e)t[r.kind]=(t[r.kind]??0)+1;return t}function dN(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:dX(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 pN=p(()=>{"use strict"});import bt from"node:path";function pX(e={}){let t=e.harnessRoot?Oe(e.harnessRoot):ut(),r=zT({harnessRoot:t}),n=e.now??Date.now();return{harnessRoot:t,scanRoots:r,now:n}}function fX(e){return typeof e=="string"?{reason:e}:e}function Ls(e,t,r,n){e.push({path:t,reason:r,...n?{detail:n}:{}})}function Ad(e,t,r){return!t||e.bytes!=null?e:{...e,bytes:Nr(e.path,r)}}function fN(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 mX(e,t){return e.kind==="remove_next_cache"?yT(e,t):hT(e,t)}function gX(e,t,r){return e.kind==="remove_next_cache"?vd(e.path,t,r):bd(e.path,t,r)}function hX(e){let t=new Map;for(let r of e)for(let[n,o]of LT(r))t.set(n,o);return t}function mN(e,t){return e.runId&&e.worker?bt.join(t,e.runId,e.worker):bt.resolve(e.path,"..")}function gN(e){return e.indexed?!1:Wy({harnessRoot:e.harnessRoot,runId:e.candidate.runId,workerName:e.candidate.worker,now:e.now})}function yX(e={}){let t=Ly(e),r=QT();t=ZT(t,r);let n=pX(e);kt("scan",`${n.scanRoots.length} harness root(s)`);let o=JO(n.scanRoots,n.now),s=t.finalizeStaleRuns?Ua().map(A=>({runId:A.runId,from:A.from,to:A.to})):[];s.length>0&&kt("finalize",`${s.length} stale run(s) marked terminal`),kt("index","building worktree index");let i=hX(n.scanRoots);kt("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new Ed,gitStatusCache:new Cd,gitRevCache:new xd},l=[],c=[],u=new Set,d=t.maxActionsPerSweep,f=()=>c.length>=d;for(let A of n.scanRoots){if(f())break;kt("root",A);let O=bt.join(A,"worktrees"),U=MT(i,A),W={harnessRoot:A,worktreesDir:O,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter,index:U,now:n.now},G=t.scanDependencyCaches?IT(W):[];kt("dependency",t.scanDependencyCaches?`${G.length} cache candidate(s) at ${A}`:"skipped (worktree-only sweep)");let ee=0;for(let N of G){if(f())break;ee+=1,ee%50===0&&kt("dependency",`${ee}/${G.length} evaluated`);let D=bt.resolve(N.path);if(u.has(D))continue;u.add(D);let F={...N,path:D},Z=gX(F,A,O);if(Z){Ls(l,F.path,Z),c.push({...F,executed:!1,skipped:!0,skipReason:Z});continue}let ue=mN(F,O),Ne=U.get(bt.resolve(ue))??null,rr=gN({candidate:F,indexed:Ne,harnessRoot:A,now:n.now}),ne=Ey({indexed:Ne,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:F.ageMs,worktreePath:ue,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:rr,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(ne){Ls(l,F.path,ne),c.push({...F,executed:!1,skipped:!0,skipReason:ne});continue}c.push(mX(Ad(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(t.scanDependencyCaches)for(let N of _T(W)){if(f())break;let D=bt.resolve(N.path);if(u.has(D))continue;u.add(D);let F={...N,path:D},Z=Rd(F.path,A,O);if(Z){Ls(l,F.path,Z),c.push({...F,executed:!1,skipped:!0,skipReason:Z});continue}let ue=mN(F,O),Ne=U.get(bt.resolve(ue))??null,rr=gN({candidate:F,indexed:Ne,harnessRoot:A,now:n.now}),ne=KO({indexed:Ne,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:F.ageMs,worktreePath:ue,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:rr,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(ne){Ls(l,F.path,ne),c.push({...F,executed:!1,skipped:!0,skipReason:ne});continue}c.push(kT(Ad(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}let T=[...xT(W),...NT(W)];kt("worktrees",`${T.length} candidate(s) at ${A}`);let x=new Set,H=0;for(let N of T){if(f())break;H+=1,H%50===0&&kt("worktrees",`${H}/${T.length} evaluated`);let D=bt.resolve(N.path);if(x.has(D))continue;x.add(D);let F={...N,path:D},Z=U.get(bt.resolve(F.path))??null,ue=Z?null:jT({worktreePath:F.path,harnessRoot:A,runId:F.runId,workerName:F.worker,now:n.now}),Ne=FO({indexed:Z,worktreePath:bt.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:A,writeSalvageEvidence:t.execute});if(Ne){let{reason:rr,detail:ne}=fX(Ne);Ls(l,F.path,rr,ne),c.push({...F,executed:!1,skipped:!0,skipReason:rr});continue}c.push(vT(Ad(F,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(!f()&&t.runDirectoriesAgeMs>=0)for(let N of eT({harnessRoot:A,worktreesDir:O,runDirectoriesAgeMs:t.runDirectoriesAgeMs,runIdFilter:t.runIdFilter,activeGuards:o,now:n.now})){if(f())break;let D=bt.resolve(N.path);if(u.has(D))continue;u.add(D);let F={...N,path:D},Z=F.runId??bt.basename(D),ue=ZO({harnessRoot:A,runId:Z,runPath:D,ageMs:F.ageMs,runDirectoriesAgeMs:t.runDirectoriesAgeMs,activeGuards:o});if(ue){Ls(l,F.path,ue),c.push({...F,executed:!1,skipped:!0,skipReason:ue});continue}c.push(bT(Ad(F,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?JT({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:t.storagePerRunEntryCap}):void 0,_=Io(),S=t.execute&&nN(_),R=S?rN({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,kt("wsl-crashes",`removed ${R.removed.length} dump(s), ${R.removedBytes} bytes`)),kt("complete",`${c.length} action(s), ${k} skipped, ${v} removed`);let L=jO(c,l),I=dN({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:fN(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:fN(c,l)},...b?{storage:b}:{},...L.length>0?{preservedLivePaths:L}:{},...g>0?{removedRunDirectories:g}:{},...w?{wslCrashDumps:w}:{},compactSummary:I}}function hN(e){let t=KT(e);return yX({execute:t.execute,finalizeStaleRuns:t.finalizeStaleRuns,accountBytes:t.accountBytes,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter})}function yN(){return process.env.KYNVER_PIPELINE_CLEANUP!=="0"}var kN=p(()=>{"use strict";Ct();$O();VO();tT();RT();CT();OT();DT();BT();rn();ja();$T();VT();qT();XT();Ay();eN();oN();Hl();sN();iN();cN();uN();pN()});function bN(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 Pd(e,t){let r=bN(e),n=bN(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 kX,EPe,Fy=p(()=>{"use strict";fi();kX={"@kynver-app/runtime":"0.1.83","@kynver-app/openclaw-agent-os":"0.1.43","@kynver-app/mcp-agent-os":"0.3.34"},EPe=Object.keys(kX)});import{readFile as bX}from"node:fs/promises";import{homedir as vX}from"node:os";import an from"node:path";function Bs(e){let t=e?.trim();return t||null}function wX(e){return[...new Set(e.filter(t=>!!t))]}function vN(){let e=vX(),t=Bs(process.env.KYNVER_OPENCLAW_NPM_ROOT)??Bs(process.env.OPENCLAW_NPM_ROOT)??an.join(e,".openclaw","npm"),r=Bs(process.env.KYNVER_NPM_GLOBAL_ROOT)??Bs(process.env.KYNVER_NPM_GLOBAL_MODULES_ROOT)??(Bs(process.env.NPM_CONFIG_PREFIX)?an.join(Bs(process.env.NPM_CONFIG_PREFIX),"lib","node_modules"):an.join(e,".npm-global","lib","node_modules"));return wX([an.join(t,"lib","node_modules"),an.join(t,"node_modules"),r.endsWith("node_modules")?r:an.join(r,"lib","node_modules")])}async function SX(e){try{let t=JSON.parse(await bX(e,"utf8"));return typeof t.version=="string"&&t.version.trim()?t.version.trim():null}catch{return null}}function RN(){return vN().map(e=>an.join(e,"@kynver-app"))}function Ky(e){let t=vN(),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 wN(e=new Date().toISOString()){let t={};for(let r of RX){let n=null;for(let o of Ky(r)){let s=await SX(o);s&&(!n||Pd(s,n.version)>0)&&(n={version:s,path:o})}n&&(t[r]={version:n.version,observedAt:e,path:n.path})}return t}var RX,$y=p(()=>{"use strict";Fy();RX=["@kynver-app/runtime","@kynver-app/openclaw-agent-os","@kynver-app/mcp-agent-os"]});import{spawnSync as _X}from"node:child_process";var xX,CX,SN,_N=p(()=>{"use strict";xX=1e4,CX=4*1024*1024,SN=(e,t,r)=>{try{let n=_X(e,t,{windowsHide:!0,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r?.timeoutMs??xX,maxBuffer:CX});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 Id(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 xN(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 Od=p(()=>{"use strict"});function Gy(){return Date.now()<jy}function TX(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 CN(e){TX(e)&&(jy=Math.max(jy,Date.now()+OX))}function Vy(e,t){if(Gy())return null;let r=e("gh",["api",...t]);if(!r.ok||!r.stdout.trim())return CN(r),null;try{return JSON.parse(r.stdout)}catch{return null}}function NX(e,t,r,n){if(Gy())return null;let o=e("gh",["pr","view",String(r),"--repo",t,"--json",n.join(",")]);if(!o.ok||!o.stdout.trim())return CN(o),null;try{return JSON.parse(o.stdout)}catch{return null}}function Jy(e){return Gy()?!1:process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()?!0:e("gh",["auth","token"]).ok}function Ws(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function DX(e){return Array.isArray(e)?e.map(t=>Ws(t)).filter(t=>t!==null).slice(0,AX).map(t=>({context:t.context??null,state:t.state??null,target_url:t.target_url??null,description:t.description??null})):[]}function MX(e,t,r){let n=Vy(e,[`repos/${t}/commits/${r}/status`]);return n?{state:n.state??null,statuses:DX(n.statuses)}:null}var EX,AX,PX,IX,OX,jy,EN,AN,PN,IN=p(()=>{"use strict";Od();EX=8e3,AX=30,PX=100,IX=400,OX=3600*1e3,jy=0;EN={provider:"github",kind:"pr_snapshot",version:"2",isAvailable:Jy,collect(e,t){let r=xN(e);if(!r)return null;let n=NX(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=Ws(n.author),s=Ws(n.mergeCommit),i=Ws(n.headRepositoryOwner),a=typeof n.body=="string"?n.body.slice(0,EX):null,l=Array.isArray(n.statusCheckRollup)?n.statusCheckRollup.map(u=>Ws(u)).filter(u=>u!==null).slice(0,PX).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=>Ws(u)).map(u=>typeof u?.path=="string"?u.path.trim():"").filter(Boolean).slice(0,IX):[];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}}},AN={provider:"github",kind:"commit_status",version:"1",isAvailable:Jy,collect(e,t){let r=Hy(e);return r?MX(t,r.repo,r.sha):null}},PN={provider:"github",kind:"branch_reachability",version:"1",isAvailable:Jy,collect(e,t){let r=Hy(e);if(!r)return null;let n=Vy(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=Vy(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 qy(e){Yy.some(t=>t.provider===e.provider&&t.kind===e.kind)||Yy.push(e)}function ON(e,t){return Yy.find(r=>r.provider===e&&r.kind===t)??null}function TN(){qy(EN),qy(AN),qy(PN)}var Yy,NN=p(()=>{"use strict";IN();Yy=[]});function DN(e,t={}){TN();let r=t.run??SN,n=t.now??(()=>new Date),o=t.maxSubjects??LX,s=Date.now()+(t.deadlineMs??BX),i=new Set,a=e.filter(m=>{let g=Id(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=Id(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=ON(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 LX,BX,MN=p(()=>{"use strict";_N();NN();Od();LX=1,BX=25e3});import LN from"node:path";function BN(e){return LN.join(V(e),WX)}function KX(e){return LN.join(V(e),UX)}function WN(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 UN(e){let t=K(BN(e),null);return WN(t?.wanted)}function FN(e,t){ke(BN(e),{savedAt:new Date().toISOString(),wanted:t})}function KN(e,t={}){let r=t.ttlMs??FX,n=KX(e),s={...K(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&&(ke(n,{savedAt:new Date().toISOString(),items:s}),i=!1)}}}function $N(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.providerEvidenceWanted;return Array.isArray(t)?WN(t):null}var WX,UX,FX,zy=p(()=>{"use strict";Y();M();Od();WX="provider-evidence-wanted.json",UX="provider-evidence-cache.json",FX=600*1e3});import $X from"node:path";function Xy(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 JX(){return $X.join(me().harnessRoot,HX)}function qX(e){let t=e.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),r=e==="github"?VX:GX;return Xy(`KYNVER_PROVIDER_EVIDENCE_${t}_PER_MINUTE`,Xy("KYNVER_PROVIDER_EVIDENCE_LIVE_COLLECTS_PER_MINUTE",r))}function HN(){return Xy("KYNVER_PROVIDER_EVIDENCE_SHARED_CACHE_TTL_MS",jX)}function YX(e){return Math.floor(e.getTime()/6e4)*6e4}function zX(e){return`${e.provider}:${e.kind}`}function jN(e,t={}){let r=KN(e,{ttlMs:t.ttlMs??HN()}),n=t.file??JX(),o=K(n,null),s={...o?.items??{}},i={...o?.budget??{}},a=t.ttlMs??HN(),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=qX(u.provider);if(m===0)return!0;let g=zX(u),h=YX(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&&(ke(n,{savedAt:new Date().toISOString(),items:s,budget:i}),l=!1)}}}var HX,jX,VX,GX,VN=p(()=>{"use strict";Y();M();zy();HX="provider-evidence-shared-cache.json",jX=6e4,VX=1,GX=1});function GN(e){let t=P_(),r=br(e?.env??process.env),n=(e?.now??(()=>new Date))().getTime(),o={};if(r.flags.dispatchReceipts!=="off"){Object.assign(o,eP());let s=ZA({nowMs:n,hasLiveWorker:e?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,r.flags.dispatchReceipts==="enforce"&&Object.assign(o,vO())}return r.flags.planOutbox!=="off"&&Object.assign(o,eI()),r.flags.admission!=="off"&&(Object.assign(o,oP()),r.flags.admission==="enforce"&&Object.assign(o,lP())),(r.flags.keeper!=="off"||r.flags.meshLease!=="off"||r.flags.quota!=="off")&&Object.assign(o,F_()),{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 JN=p(()=>{"use strict";Jr();is();ws();by();Ma();Yn();_s();Vi()});import{createHash as qN}from"node:crypto";import{access as XX,mkdir as pIe,readFile as YN,rename as fIe,writeFile as mIe}from"node:fs/promises";import{constants as QX}from"node:fs";import{homedir as Qy}from"node:os";import Ye from"node:path";function t3(){return process.env.KYNVER_MCP_UPDATE_INVENTORY_FILE?.trim()||Ye.join(Qy(),".kynver","mcp-installations.json")}function r3(e){return e==="openclaw"?process.env.KYNVER_OPENCLAW_NPM_ROOT?.trim()||Ye.join(Qy(),".openclaw","npm"):process.env.KYNVER_NPM_GLOBAL_ROOT?.trim()||process.env.NPM_CONFIG_PREFIX?.trim()||Ye.join(Qy(),".npm-global")}function n3(e){let t=Ye.resolve(e);if(Ye.basename(t)!=="node_modules")return t;let r=Ye.dirname(t);return Ye.basename(r)==="lib"?Ye.dirname(r):r}function o3(e,t){return[Ye.join(e,"lib","node_modules",t,"package.json"),Ye.join(e,"node_modules",t,"package.json")]}async function s3(e){try{return await XX(e,QX.R_OK),!0}catch{return!1}}async function Zy(e=t3()){let t;try{t=JSON.parse(await YN(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||!e3.test(r.inventoryKey)||!ZX.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 i3(e,t,r){if(typeof e.bin=="string")return Ye.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"&&!Ye.isAbsolute(s)&&!s.split(/[\\/]/).includes("..")?Ye.join(r,s):null}function a3(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 l3(e){let t=[];for(let r of e){let n=n3(r3(r.prefix)),o=(await Promise.all(o3(n,r.packageName).map(async m=>({candidate:m,ok:await s3(m)})))).find(m=>m.ok)?.candidate;if(!o)continue;let s=JSON.parse(await YN(o,"utf8"));if(s.name!==r.packageName||typeof s.version!="string"||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(s.version))continue;let i=Ye.dirname(o),a=i3(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:a3(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 zN(){return l3(await Zy())}var ZX,e3,ek=p(()=>{"use strict";ZX=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/i,e3=/^[A-Za-z0-9._:-]{8,128}$/});import{createHash as c3,createHmac as u3,timingSafeEqual as d3}from"node:crypto";function tk(e){let t=e.trim().split(".");return t.length!==3||t[0]!=="krc1"||!t[1]||!t[2]?null:{tokenId:t[1],tokenHash:c3("sha256").update(`krc1.${t[1]}.${t[2]}`,"utf8").digest("hex")}}function XN(e,t,r){let n=tk(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=u3("sha256",Buffer.from(n.tokenHash,"hex")).update(JSON.stringify(e.claims),"utf8").digest(),i=Buffer.from(e.signature,"base64url");return i.length===s.length&&d3(i,s)}var rk=p(()=>{"use strict"});import{createHash as p3}from"node:crypto";import{access as nk,mkdtemp as f3,readFile as r0,rm as m3}from"node:fs/promises";import{constants as ok}from"node:fs";import{tmpdir as g3}from"node:os";import Us from"node:path";import{spawn as h3}from"node:child_process";import{Client as y3}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as k3}from"@modelcontextprotocol/sdk/client/stdio.js";function n0(){return"npm"}function ZN(e,t){return Buffer.byteLength(e)>=QN?e:(e+t.toString("utf8")).slice(0,QN)}function v3(e){let t=process.env.KYNVER_MCP_UPDATE_NPM_CACHE?.trim(),r=t&&Us.isAbsolute(t)?t:e,n={PATH:process.env.PATH,SystemRoot:process.env.SystemRoot,TEMP:process.env.TEMP,TMP:process.env.TMP,npm_config_registry:sk,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 o0(e,t,r=ik,n){return new Promise((o,s)=>{let i,a;try{[i,a]=ie(e,t)}catch(m){s(m);return}let l=h3(i,a,{shell:!1,windowsHide:!0,detached:ve(),env:v3(n),stdio:["ignore","pipe","pipe"]}),c="",u="",d=!1;l.stdout.on("data",m=>{c=ZN(c,m)}),l.stderr.on("data",m=>{u=ZN(u,m)});let f=setTimeout(()=>{d=!0,l.pid&&ye(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 R3(e,t){let[r,n]=t.split("-",2);return!n||!["sha256","sha384","sha512"].includes(r)?!1:p3(r).update(e).digest("base64")===n}async function w3(e,t,r,n){let o=await o0(n0(),["pack",`${e}@${t}`,"--json","--pack-destination",n,`--registry=${sk}`,"--ignore-scripts"],ik,Us.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"||Us.basename(i)!==i)throw new Error("artifact_receipt_invalid");let a=Us.join(n,i);if(!R3(await r0(a),r))throw new Error("artifact_integrity_mismatch");return a}async function S3(e,t,r){if((await o0(n0(),["install","--global","--prefix",e,t,`--registry=${sk}`,"--no-audit","--fund=false"],ik,r)).code!==0)throw new Error("package_install_failed")}async function s0(e){let t=JSON.parse(await r0(e.local.packageJsonPath,"utf8"));if(t.name!==e.report.packageName||typeof t.version!="string")throw new Error("installed_identity_mismatch");return t.version}function _3(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 e0(e){if(!e.local.binPath)throw new Error("mcp_binary_missing");await nk(e.local.binPath,ok.X_OK).catch(async()=>nk(e.local.binPath,ok.R_OK));let t=new k3({command:e.local.binPath,args:[],env:_3(e.local.envAllowlist),stderr:"pipe"}),r=new y3({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")),b3)})]);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 t0(e,t,r,n,o){let s=await f3(Us.join(g3(),"kynver-mcp-update-"));try{let i=await w3(t,r,n,s);if(await o(),await S3(e.local.prefix,i,Us.join(s,"npm-cache")),await s0(e)!==r)throw new Error("installed_version_mismatch")}finally{await m3(s,{recursive:!0,force:!0})}}async function i0(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 nk(e.local.prefix,ok.W_OK).catch(()=>{throw new Error("npm_prefix_not_writable")});let o=await s0(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 t0(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 e0(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 t0(e,t.packageName,t.installedVersion,t.rollbackIntegrity,async()=>{await n.beforePackageMutation?.()}),e.local.lifecycle==="runtime_stdio"){let c=await e0(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 sk,QN,ik,b3,a0=p(()=>{"use strict";li();Je();sk="https://registry.npmjs.org",QN=512*1024,ik=2*6e4,b3=2e4});import{createHmac as x3,timingSafeEqual as C3}from"node:crypto";import{mkdir as E3,readFile as A3,rename as P3,writeFile as I3}from"node:fs/promises";import{homedir as O3}from"node:os";import ak from"node:path";function Ja(){return process.env.KYNVER_MCP_UPDATE_STATE_ROOT?.trim()||ak.join(O3(),".kynver","state","mcp-updates")}function l0(e){if(!/^[A-Za-z0-9_-]{8,128}$/.test(e))throw new Error("invalid update operation identity");return ak.join(Ja(),`${e}.json`)}function c0(e,t){let r=tk(t);return r?x3("sha256",Buffer.from(r.tokenHash,"hex")).update(JSON.stringify(e),"utf8").digest("base64url"):null}async function u0(e,t){try{let r=JSON.parse(await A3(l0(e),"utf8"));if(r.version!==2||r.operationId!==e||typeof r.integrityMac!="string")return null;let{integrityMac:n,...o}=r,s=c0(o,t);if(!s)return null;let i=Buffer.from(n,"utf8"),a=Buffer.from(s,"utf8");return i.length!==a.length||!C3(i,a)?null:r}catch{return null}}async function d0(e,t){let r=c0(e,t);if(!r)throw new Error("invalid_runner_credential_for_receipt");let n=l0(e.operationId);await E3(ak.dirname(n),{recursive:!0,mode:448});let o=`${n}.${process.pid}.tmp`;await I3(o,`${JSON.stringify({...e,integrityMac:r},null,2)}
|
|
187
|
+
`,{mode:384}),await P3(o,n)}var Td=p(()=>{"use strict";rk()});import{randomBytes as lk}from"node:crypto";import{mkdir as ck,readFile as uk,rename as T3,rm as Nd,stat as N3,writeFile as p0}from"node:fs/promises";import oo from"node:path";function f0(){return oo.join(Ja(),D3)}async function m0(){try{let e=JSON.parse(await uk(oo.join(f0(),"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:g0(e.pid)}}catch{return null}}function g0(e){if(!Number.isSafeInteger(e)||e<=0)return!0;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function M3(e){try{return await N3(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function h0(){return L3("mcp_update")}async function L3(e){let t=f0(),r=`${t}.reclaiming`;await ck(oo.dirname(t),{recursive:!0,mode:448});let n=!1;try{if(await M3(r))return null;for(let o=0;o<2;o+=1)try{await ck(t,{mode:448});let s={pid:process.pid,nonce:lk(18).toString("base64url"),acquiredAt:new Date().toISOString(),holder:e};return await p0(oo.join(t,"owner.json"),JSON.stringify(s),{mode:384}),n&&(await Nd(r,{recursive:!0,force:!0}),n=!1),{release:async()=>{try{let i=JSON.parse(await uk(oo.join(t,"owner.json"),"utf8"));i.pid===s.pid&&i.nonce===s.nonce&&await Nd(t,{recursive:!0,force:!0})}catch{}}}}catch(s){if(s.code!=="EEXIST")throw s;if(!n)try{await ck(r,{mode:448}),n=!0,await p0(oo.join(r,"owner.json"),JSON.stringify({pid:process.pid,nonce:lk(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 uk(oo.join(t,"owner.json"),"utf8"))}catch{return null}if(g0(i.pid))return null;let a=`${t}.stale-${process.pid}-${lk(8).toString("hex")}`;await T3(t,a),await Nd(a,{recursive:!0,force:!0})}return null}finally{n&&await Nd(r,{recursive:!0,force:!0})}}var D3,y0=p(()=>{"use strict";Td();D3="host-mutation.lock"});function Dd(e,t,r){return`${e}/api/agent-os/by-id/${encodeURIComponent(t)}/mcp-updates/${r}`}function B3(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 k0(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 W3(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 b0(e){let t=pe(e.baseUrl),r=await zN();if(r.length===0)return{ok:!0,stage:"not_configured"};let n=await Mn(Dd(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 h0();if(!o){let s=await m0();return{ok:!0,stage:"host_mutation_busy",...s?{heldBy:s.holder}:{}}}try{let s=await Mn(Dd(t,e.agentOsId,"claim"),e.secret,{activeOwnedSessions:e.activeOwnedSessions});if(!s.ok)return{ok:!1,stage:"claim",status:s.status};let i=B3(s.response);if(!i)return{ok:!0,stage:"idle"};if(!XN(i,e.secret,e.agentOsId))return{ok:!1,stage:"command_auth"};let a=await u0(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||!k0(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&&k0(a.recovery,i)?a.recovery:W3(k,i)}let u=a?.acceptedAt??new Date().toISOString(),d=async(k,b,_)=>{await d0({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 Mn(Dd(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 i0(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 Mn(Dd(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 v0=p(()=>{"use strict";j();Ue();ek();rk();a0();y0();Td()});import R0 from"node:path";function U3(){let e=process.env.KYNVER_PIPELINE_SWEEP_ENABLED;return e?e==="1"||e.toLowerCase()==="true":!1}async function F3(e,t){let r=re(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=K(R0.join(V(r.id),"workers",B(i),"worker.json"),void 0);if(!a?.taskId||a.localOnly||Ur(a))continue;if(ka(a)){n.push({worker:i,ok:!0,taskId:a.taskId??null,skipped:!0});continue}if(s>=o)break;s++;let l=se(a);if(!Le(l))continue;let c=No({alive:l.alive,finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry});if(!a.dispatched&&!l.finalResult&&!c?.salvageable)continue;let u=await Cs({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 K3(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 wN(),c=Xo(t),u=null;try{let S=UN(t);if(S.length>0){let R=jN(t);u=DN(S,{cache:R}),R.flush?.()}else u=null}catch{u=null}try{if(Ir()!=="off"){let S=Bo();nP({liveWorkers:S}),aP({liveWorkers:S})}else tP()}catch{}let d=({runId:S,workerName:R})=>{try{let{runsDir:w}=me(),L=R0.join(mr(w,B(S)),"workers",B(R),"worker.json"),I=K(L,null);return I?Ur(I):!1}catch{return!1}};await wO({agentOsId:e,baseUrl:s,secret:i,hasLiveWorker:d});let f=null;try{f=GN({hasLiveWorker:d})}catch{f=null}let m=null;try{m=dc({control:Kr(e),supervisor:Rw(),inFlightWorkers:Bo().length})}catch{m=null}let g=Zc(t),h=Mx(),y=await de(a,i,{agentOsId:e,runId:t,ingestHarness:!0,harnessBoardSnapshot:Uh(t),resourceGate:r,boxResourceSnapshot:_O(r,{harnessRunId:t,boxKind:_t(E())}),packageVersions:l,...o?{harnessCleanup:o}:{},runnerPresence:Te({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=$N(y.response);if(v)try{FN(t,v)}catch{}let k=Ox(y);if(k)try{Ix(t,k)}catch{}let b=O_(y);b&&T_(e,b);let _=gw(y);return _&&$f(e,_),{ok:y.ok,httpStatus:y.status,response:y.response,...u?{providerEvidence:{attempted:u.attempted,collected:u.collected,skipped:u.skipped.length}}:{}}}async function Md(e){let t=String(St(String(e.run||""),"--run")),r=String(St(String(e.agentOsId||""),"--agent-os-id")),n=e.execute!==!1&&e.execute!=="false";Uh(t);let o=await ru(r,e),s=tu(o),i=_i({runId:t,configuredMaxWorkersOverride:s}),a=yN()?hN(t):void 0,l=await K3(r,t,i,e,a),c;if(n)try{let A=pe(e.baseUrl?String(e.baseUrl):void 0),O=await fe(e.secret?String(e.secret):void 0,r,{baseUrl:A});c=await b0({agentOsId:r,secret:O,baseUrl:A,activeOwnedSessions:Bo().length})}catch(A){c={ok:!1,stage:"cycle",error:A instanceof Error?A.message:"update cycle failed"}}let u=MA(t,l),d=await CE(t,e),f=await F3(t,e);f.some(A=>A.ok&&!A.skipped)&&dx();let m=_i({runId:t,configuredMaxWorkersOverride:s}),g=yy(),h=await AO(t,e),y=QI(m,l),v=y.maxStarts,k=Kr(r),b=yw(k);b&&(v=0);let _=U3()?await fd({run:t,agentOsId:r,pipeline:!0,...e}):{ok:!0,skipped:!0,reason:"pipeline_sweep_disabled"},S=null,R=0,w=zI(l),L=v;if(n&&L>0&&w.length>0){let A=Math.min(L,w.length),O=await oy({...e,run:t,agentOsId:r,targetTaskIds:w.join(",")},A),U=Os(O);R+=U,L=Math.max(0,L-U),S={exactTargetTaskIds:w,exact:O,startedCount:R}}if(n&&L>0){let A=await oy({...e,run:t,agentOsId:r},L),O=Os(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 I=!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:I,runtimeControl:k?{desiredState:k.desiredState,policyVersion:k.policyVersion}:null}}var dk=p(()=>{"use strict";$r();Ac();j();Ue();YI();XI();ZI();ky();Wo();Yn();SO();_s();xO();Xc();Y();Ct();Xl();xe();vy();M();PO();zg();Es();Bu();nc();gg();j();Me();kN();Yu();$y();yr();MN();VN();zy();ug();JN();Jm();v0();dg()});function Ld(e){return Fo(Kr(e))!=="stopped"?null:Bo().length}var pk=p(()=>{"use strict";Wo();$r()});function w0(e){if(!e||typeof e!="object")return!1;let t=e;return t.type==="result"&&typeof t.id=="number"&&typeof t.ok=="boolean"}var S0=p(()=>{"use strict"});import{existsSync as $3}from"node:fs";import{fileURLToPath as H3}from"node:url";import{SHARE_ENV as j3,Worker as V3}from"node:worker_threads";function J3(e=import.meta.url){for(let t of[`./${_0}`,`../${_0}`]){let r=new URL(t,e);try{if($3(H3(r)))return r}catch{}}return null}function q3(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??Xe()?{mode:"inline",reason:"desktop_sidecar"}:e.script?{mode:"thread",reason:"default"}:{mode:"inline",reason:"thread_entry_not_built"}}var _0,G3,Y3,Bd,x0=p(()=>{"use strict";wt();dg();Gr();dk();pk();S0();_0="daemon-tick-thread.js",G3=3;Y3=(e,t)=>new V3(e,{workerData:t,env:j3,name:"kynver-pipeline-tick"}),Bd=class{constructor(t){this.options=t;this.script=t.script===void 0?J3():t.script;let r=q3({env:t.env,desktopMode:t.desktopMode,script:this.script});this.modeValue=r.mode,this.reason=r.reason,this.createWorker=t.createWorker??Y3,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 Dx(r),{tick:await Md(t),inFlightWorkers:Ld(this.options.agentOsId),isolation:"inline"}}bundleIfChanged(){let t=u_(),r=Wt(),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(!w0(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>=G3&&(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 z3,performance as X3}from"node:perf_hooks";var Q3,Z3,e8,t8,C0,Wd,E0=p(()=>{"use strict";Q3=1e3,Z3=250,e8=5,t8=5e3,C0=e=>Number.isFinite(e)?Math.round(e/1e6):0,Wd=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??Q3,this.sampleIntervalMs=t.sampleIntervalMs??Z3,this.now=t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??(()=>X3.now()),this.log=t.log??(r=>console.error(r)),this.histogram=t.histogram??z3({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>t8)return this.histogram.reset(),this.phasesInWindow=new Set([this.phase]),null;let s=Math.max(0,Math.round(n-this.sampleIntervalMs)),i=C0(this.histogram.max),a=C0(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(-e8),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 r8,n8,o8,Ud,A0=p(()=>{"use strict";sr();r8=5*6e4,n8=5*6e4,o8=2160*60*60,Ud=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()>r8?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<n8)return;let r=`${this.deps.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(this.deps.agentOsId)}/runner-credentials`;try{let n=await ct(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({capabilities:["chat.relay"],ttlSeconds:o8,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 ct(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 Fs(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 so(e,t,r){r===401&&t.kind==="box_token"&&e.auth?.invalidateToken()}var Fd=p(()=>{"use strict"});import{createHash as s8,verify as i8,createPublicKey as a8}from"node:crypto";function mk(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};return delete t[P0],t}function c8(e){return s8("sha256").update(rt(mk(e)),"utf8").digest("hex")}function gk(e){return!e||typeof e!="object"||Array.isArray(e)?null:e[P0]??null}function u8(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 d8(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:rt(r)===rt(t)}function fk(e,t){return{state:t,firstSeenAt:new Date(e.firstSeenSec*1e3).toISOString(),turnId:e.turnId}}function p8(e){return a8({key:Buffer.concat([l8,Buffer.from(e)]),format:"der",type:"spki"})}function I0(e,t,r={}){let n=r.env??process.env,o=r.nowSec??Math.floor(Date.now()/1e3),s=gk(e);if(s===null)return{ok:!1,code:"unsigned",reason:"turn carries no signed envelope"};if(!u8(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=On(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(rt(i.payload),"utf8");c=i8(null,d,p8(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(c8(e)!==i.payload.payloadHash)return{ok:!1,code:"payload_tampered",reason:"turn payload does not match its signed hash"};if(!d8(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 (${f8(u.replay)})`,replay:u.replay}}function f8(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 P0,l8,Kd,hk=p(()=>{"use strict";Hr();Mi();P0="turnEnvelope",l8=Buffer.from("302a300506032b6570032100","hex");Kd=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:fk(n,"turn_mismatch")}:n.state==="verified"?{ok:!0,redelivered:!0}:{ok:!1,replay:fk(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:fk(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 O0(e=process.env,t={}){let r=(e[m8]??t.chatTurnSignature??"").toString().trim().toLowerCase();return r==="optional"||r==="off"||r==="0"||r==="false"?"optional":"required"}function T0(e,t){return t?`turn_rejected_${e}: ${t}`:`turn_rejected_${e}`}function N0(e,t){if(!(gk(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:g8(o)?o:null,signed:!1,userId:null,redelivered:!1}}let n=I0(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 g8(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.byBox;return!!t&&typeof t=="object"&&!Array.isArray(t)}var m8,D0=p(()=>{"use strict";hk();m8="KYNVER_CHAT_TURN_SIGNATURE"});var $d,M0=p(()=>{"use strict";$d=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 h8}from"node:dns/promises";import{createServer as y8,request as k8}from"node:http";import{connect as b8,isIP as W0,isIPv4 as v8}from"node:net";function U0(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 qa(e){let t=U0(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 w8(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=U0(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 S8(e){let t=w8(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 qa(n(t[6],t[7]));if(t[0]===8194)return qa(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 L0(e){let t=W0(e);return t===4?qa(e):t===6?S8(e):!0}function _8(e){return e==="localhost"||e.endsWith(".localhost")||e==="localhost6"||e==="ip6-localhost"}function x8(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 F0(e){return(await h8(e,{all:!0})).map(r=>r.address)}async function B0(e,t=F0){let r=x8(e);if(!r||r.length>R8)return{allowed:!1,host:r,reason:"invalid host"};if(_8(r))return{allowed:!1,host:r,reason:`${r} is this computer (loopback): local services are not reachable from a folder step`};if(W0(r))return L0(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=>L0(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=>v8(s))??n[0]}}function yk(e,t,r){let n=`Kynver folder sandbox: ${r}
|
|
188
|
+
`;e.write(`HTTP/1.1 ${t} ${t===kk?"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 E8(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 A8(e={}){let t=e.lookup??F0,r=e.dial??((m,g)=>b8({host:m,port:g})),n=e.idleMs??C8,o={allowed:0,denied:0},s=(m,g,h)=>{let y=E8(m.url);if(g.on("error",()=>g.destroy()),!y){o.denied+=1,yk(g,400,"CONNECT needs host:port");return}B0(y.host,t).then(v=>{if(!v.allowed){o.denied+=1,yk(g,kk,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",
|
|
195
|
+
`),h.length&&k.write(h),k.pipe(g),g.pipe(k)}),k.on("error",_=>{if(b){g.destroy();return}yk(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(v)})},a=()=>{let f=b4(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 uN(e={}){return Is?.listening()?Is:(bd||(bd=I4(e).then(t=>(Is=t,Da=null,t)).catch(t=>{throw Is=null,Da=`egress proxy could not start: ${t?.message??String(t)}`.slice(0,240),new Error(Da)}).finally(()=>{bd=null})),bd)}function dN(){return Is?.listening()?{status:"running",port:Is.port}:Da?{status:"failed",reason:Da}:{status:"not_started"}}var S4,A4,Oy,Is,bd,Da,Ty=p(()=>{"use strict";S4=253;A4=10*6e4,Oy=403;Is=null,bd=null,Da=null});import{existsSync as O4}from"node:fs";import Rd from"node:path";function Dy(e=process.env,t={}){let r=(e[T4]??t.chatFolderSandbox??"").toString().trim().toLowerCase();return r==="best-effort"||r==="best_effort"||r==="optional"?"best_effort":"required"}function gN(e=process.env,t={}){let r=[],n=e[N4];n&&r.push(...n.split(/[\s,]+/)),Array.isArray(t.chatFolderSandboxDomains)&&r.push(...t.chatFolderSandboxDomains.filter(s=>typeof s=="string"));let o=[...D4];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 B4(){let e=[];for(let t of wd)e.push(`Read(${vd(t)}/**)`,`Edit(${vd(t)}/**)`);for(let t of Sd)e.push(`Read(${vd(t)})`,`Edit(${vd(t)})`);for(let t of Os)e.push(`Read(//**/${t})`,`Edit(//**/${t})`);return e}function U4(e,t=[],r={}){let n=["~/",...L4];for(let o of wd)n.push(`~/${o}`);for(let o of Sd)n.push(`~/${o}`);for(let o of t)n.push(Ny(o));if(r.scanComplete!==!0)for(let o of e)for(let s of Os)n.push(Rd.posix.join(Ny(o),"**",s));return n}function W4(e){return[...e.map(Ny),...M4.map(t=>`~/${t}`)]}function Ny(e){return e.split(Rd.sep).join("/")}function pN(e){let t={deny:B4(),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:U4(e.folders,e.sensitiveFiles,{scanComplete:e.sensitiveScanComplete}),allowRead:W4(e.folders)},network:{allowedDomains:e.domains,allowLocalBinding:!0,...typeof r=="number"&&r>0?{httpProxyPort:r}:{}}}}}function hN(e){return!!e&&F4.test(e)}function K4(e,t,r){return(t.PATH??"").split(Rd.delimiter).filter(Boolean).some(o=>r(Rd.join(o,e)))}function $4(e={}){let t=e.platform??process.platform,r=e.env??process.env,n=e.exists??O4;if(t==="darwin")return{kind:"seatbelt",available:!0,missing:[]};if(t==="linux"){let o=["bwrap","socat"].filter(s=>!K4(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 My(){return fN??=$4(),fN}function kN(e){yN=e.trim().slice(0,240)||"sandbox failed to start"}function Ly(){return yN}function bN(e){return e.streamed.trim()||e.exitCode===0||e.numTurns!==null&&e.numTurns>0?!1:H4.test(e.detail)&&j4.test(e.detail)}function vN(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:pN({folders:t,sandbox:!0,domains:e.domains,egressProxyPort:o,sensitiveFiles:e.sensitiveFiles,sensitiveScanComplete:e.sensitiveScanComplete}),note:o?`${mN} ${V4}`:`${mN} ${G4}`}}let n=pN({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:q4}:{shell:"disabled",policy:e.policy,runtime:e.runtime,reason:r,settings:n,note:J4}}function By(e=process.env,t={},r={}){let n=r.runtime??My(),o=r.startupFailure===void 0?Ly():r.startupFailure,s=Dy(e,t),i=n.available?o??void 0:n.reason,a=i?s==="best_effort"?"unconfined":"disabled":"sandboxed",l=r.egress??dN(),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 T4,N4,D4,wd,Sd,Os,M4,L4,Qn,F4,fN,yN,H4,j4,mN,V4,G4,J4,q4,_d=p(()=>{"use strict";Ty();T4="KYNVER_CHAT_FOLDER_SANDBOX",N4="KYNVER_CHAT_FOLDER_SANDBOX_DOMAINS";D4=["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"];wd=[".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"],Sd=[".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"],Os=[".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.*"],M4=[".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"],L4=["/home","/root","/Users","/mnt","/media","/Volumes"];Qn=3128,F4=new RegExp([`failed to connect to (?:localhost|127\\.0\\.0\\.1|::1|\\[::1\\]) port ${Qn}\\b`,`(?:localhost|127\\.0\\.0\\.1|\\[::1\\]|::1):${Qn}\\b[^\\n]{0,80}?(?:connection refused|econnrefused)`,`(?:connection refused|econnrefused)[^\\n]{0,80}?(?:localhost|127\\.0\\.0\\.1|::1):${Qn}\\b`,`(?:cannot|could not|unable to) connect to proxy[^\\n]{0,80}?${Qn}\\b`,`proxyerror[^\\n]{0,120}?${Qn}\\b`].join("|"),"i");fN=null;yN=null;H4=/sandbox/i,j4=/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;mN="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.",V4="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.",G4="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.",J4="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.",q4="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 X4(e){let t=e[Lp];return new Set(t?t.split(/[\s,]+/).map(r=>r.trim()).filter(Boolean):[])}function Uy(e,t={}){return z4.has(e)||t.operatorAllow?.has(e)||e===Fy?!1:Y4.some(r=>r.test(e))}function jt(e=process.env){let t=zs(e);for(let n of Wy)delete t[n];let r=X4(e);for(let n of Object.keys(t))Uy(n,{operatorAllow:r})&&delete t[n];return t[Fy]="1",t}function RN(e){let t=e.toUpperCase();return tX.has(t)||t===Fy?!0:Z4.has(t)?!Uy(t):eX.some(r=>t.startsWith(r))?!Uy(t)&&!/(_KEY|_TOKEN|_SECRET|_PASSWORD)$/i.test(t):!1}function rX(e=process.env){let t={};for(let[n,o]of Object.entries(e))typeof o=="string"&&RN(n)&&(t[n]=o);let r=jt(t);for(let n of Object.keys(r))RN(n)||delete r[n];return r}function wN(e,t){return t==="folder"||t==="folders"?rX(e):jt(e)}function Ky(){return[`--disallowedTools=${nX.join(",")}`]}var Wy,Fy,Y4,z4,Q4,Z4,eX,tX,nX,Zn=p(()=>{"use strict";Xs();Wy=["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"],Fy="KYNVER_CHAT_CHILD",Y4=[/_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],z4=new Set(Mp);Q4=["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"],Z4=new Set(Q4.map(e=>e.toUpperCase())),eX=["LC_","CLAUDE_CODE_","CLAUDE_","ANTHROPIC_","DISABLE_","MAX_THINKING_","BASH_DEFAULT_","BASH_MAX_"],tX=new Set(["CLAUDE_CODE_OAUTH_TOKEN"]);nX=["Read(~/.kynver/credentials)","Read(~/.kynver/credentials.*)","Read(~/.kynver/chat-box-credential)","Read(~/.kynver/site-logins/**)"]});import{spawn as oX}from"node:child_process";async function SN(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=jt(o),i=new Set([...Wy,...Dp]);return new Promise(a=>{let l="",c=!1,u=f=>{c||(c=!0,clearTimeout(m),a({...f,at:r().toISOString()}))},d;try{d=oX(t.execPath??process.execPath,["-e",sX],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 sX,_N=p(()=>{"use strict";N();Zn();Xs();sX="process.stdout.write(JSON.stringify(Object.keys(process.env)))"});import{existsSync as iX,mkdirSync as aX,readFileSync as lX,writeFileSync as cX}from"node:fs";import{homedir as uX}from"node:os";import $y from"node:path";function Hy(e=uX()){return $y.join(e,dX)}function xN(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function pX(e){return typeof e.access!="string"?null:{access:e.access,folders:xN(e.folders),source:e.source??"default",signed:e.signed===!0,at:typeof e.at=="string"?e.at:""}}function fX(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(typeof r.access=="string")return{access:r.access,folders:xN(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 xd(e=Hy()){try{if(!iX(e))return{applied:null,website:null};let t=JSON.parse(lX(e,"utf8"));if(!t||typeof t!="object")return{applied:null,website:null};let r=pX(t);return{applied:r,website:fX(t.website,r)}}catch{return{applied:null,website:null}}}function CN(e,t){try{aX($y.dirname(e),{recursive:!0});let r={...t.applied??{},...t.website?{website:t.website}:{}};cX(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;B0(h.hostname,t).then(v=>{if(!v.allowed){o.denied+=1,g.writeHead(kk,{"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=k8({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=y8(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 K0(e={}){return Ks?.listening()?Ks:(Hd||(Hd=A8(e).then(t=>(Ks=t,Ya=null,t)).catch(t=>{throw Ks=null,Ya=`egress proxy could not start: ${t?.message??String(t)}`.slice(0,240),new Error(Ya)}).finally(()=>{Hd=null})),Hd)}function $0(){return Ks?.listening()?{status:"running",port:Ks.port}:Ya?{status:"failed",reason:Ya}:{status:"not_started"}}var R8,C8,kk,Ks,Hd,Ya,bk=p(()=>{"use strict";R8=253;C8=10*6e4,kk=403;Ks=null,Hd=null,Ya=null});import{existsSync as P8}from"node:fs";import Vd from"node:path";function Rk(e=process.env,t={}){let r=(e[I8]??t.chatFolderSandbox??"").toString().trim().toLowerCase();return r==="best-effort"||r==="best_effort"||r==="optional"?"best_effort":"required"}function G0(e=process.env,t={}){let r=[],n=e[O8];n&&r.push(...n.split(/[\s,]+/)),Array.isArray(t.chatFolderSandboxDomains)&&r.push(...t.chatFolderSandboxDomains.filter(s=>typeof s=="string"));let o=[...T8];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 jd(e){return`~/${e}`}function M8(){let e=[];for(let t of Gd)e.push(`Read(${jd(t)}/**)`,`Edit(${jd(t)}/**)`);for(let t of Jd)e.push(`Read(${jd(t)})`,`Edit(${jd(t)})`);for(let t of $s)e.push(`Read(//**/${t})`,`Edit(//**/${t})`);return e}function L8(e,t=[],r={}){let n=["~/",...D8];for(let o of Gd)n.push(`~/${o}`);for(let o of Jd)n.push(`~/${o}`);for(let o of t)n.push(vk(o));if(r.scanComplete!==!0)for(let o of e)for(let s of $s)n.push(Vd.posix.join(vk(o),"**",s));return n}function B8(e){return[...e.map(vk),...N8.map(t=>`~/${t}`)]}function vk(e){return e.split(Vd.sep).join("/")}function H0(e){let t={deny:M8(),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:L8(e.folders,e.sensitiveFiles,{scanComplete:e.sensitiveScanComplete}),allowRead:B8(e.folders)},network:{allowedDomains:e.domains,allowLocalBinding:!0,...typeof r=="number"&&r>0?{httpProxyPort:r}:{}}}}}function J0(e){return!!e&&W8.test(e)}function U8(e,t,r){return(t.PATH??"").split(Vd.delimiter).filter(Boolean).some(o=>r(Vd.join(o,e)))}function F8(e={}){let t=e.platform??process.platform,r=e.env??process.env,n=e.exists??P8;if(t==="darwin")return{kind:"seatbelt",available:!0,missing:[]};if(t==="linux"){let o=["bwrap","socat"].filter(s=>!U8(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 wk(){return j0??=F8(),j0}function Y0(e){q0=e.trim().slice(0,240)||"sandbox failed to start"}function Sk(){return q0}function z0(e){return e.streamed.trim()||e.exitCode===0||e.numTurns!==null&&e.numTurns>0?!1:K8.test(e.detail)&&$8.test(e.detail)}function X0(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:H0({folders:t,sandbox:!0,domains:e.domains,egressProxyPort:o,sensitiveFiles:e.sensitiveFiles,sensitiveScanComplete:e.sensitiveScanComplete}),note:o?`${V0} ${H8}`:`${V0} ${j8}`}}let n=H0({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:G8}:{shell:"disabled",policy:e.policy,runtime:e.runtime,reason:r,settings:n,note:V8}}function _k(e=process.env,t={},r={}){let n=r.runtime??wk(),o=r.startupFailure===void 0?Sk():r.startupFailure,s=Rk(e,t),i=n.available?o??void 0:n.reason,a=i?s==="best_effort"?"unconfined":"disabled":"sandboxed",l=r.egress??$0(),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 I8,O8,T8,Gd,Jd,$s,N8,D8,io,W8,j0,q0,K8,$8,V0,H8,j8,V8,G8,qd=p(()=>{"use strict";bk();I8="KYNVER_CHAT_FOLDER_SANDBOX",O8="KYNVER_CHAT_FOLDER_SANDBOX_DOMAINS";T8=["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"];Gd=[".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"],Jd=[".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"],$s=[".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.*"],N8=[".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"],D8=["/home","/root","/Users","/mnt","/media","/Volumes"];io=3128,W8=new RegExp([`failed to connect to (?:localhost|127\\.0\\.0\\.1|::1|\\[::1\\]) port ${io}\\b`,`(?:localhost|127\\.0\\.0\\.1|\\[::1\\]|::1):${io}\\b[^\\n]{0,80}?(?:connection refused|econnrefused)`,`(?:connection refused|econnrefused)[^\\n]{0,80}?(?:localhost|127\\.0\\.0\\.1|::1):${io}\\b`,`(?:cannot|could not|unable to) connect to proxy[^\\n]{0,80}?${io}\\b`,`proxyerror[^\\n]{0,120}?${io}\\b`].join("|"),"i");j0=null;q0=null;K8=/sandbox/i,$8=/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;V0="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.",H8="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.",j8="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.",V8="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.",G8="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 Y8(e){let t=e[mf];return new Set(t?t.split(/[\s,]+/).map(r=>r.trim()).filter(Boolean):[])}function xk(e,t={}){return q8.has(e)||t.operatorAllow?.has(e)||e===Ek?!1:J8.some(r=>r.test(e))}function Jt(e=process.env){let t=ui(e);for(let n of Ck)delete t[n];let r=Y8(e);for(let n of Object.keys(t))xk(n,{operatorAllow:r})&&delete t[n];return t[Ek]="1",t}function Q0(e){let t=e.toUpperCase();return Z8.has(t)||t===Ek?!0:X8.has(t)?!xk(t):Q8.some(r=>t.startsWith(r))?!xk(t)&&!/(_KEY|_TOKEN|_SECRET|_PASSWORD)$/i.test(t):!1}function e5(e=process.env){let t={};for(let[n,o]of Object.entries(e))typeof o=="string"&&Q0(n)&&(t[n]=o);let r=Jt(t);for(let n of Object.keys(r))Q0(n)||delete r[n];return r}function Z0(e,t){return t==="folder"||t==="folders"?e5(e):Jt(e)}function Ak(){return[`--disallowedTools=${t5.join(",")}`]}var Ck,Ek,J8,q8,z8,X8,Q8,Z8,t5,ao=p(()=>{"use strict";di();Ck=["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",J8=[/_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],q8=new Set(ff);z8=["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"],X8=new Set(z8.map(e=>e.toUpperCase())),Q8=["LC_","CLAUDE_CODE_","CLAUDE_","ANTHROPIC_","DISABLE_","MAX_THINKING_","BASH_DEFAULT_","BASH_MAX_"],Z8=new Set(["CLAUDE_CODE_OAUTH_TOKEN"]);t5=["Read(~/.kynver/credentials)","Read(~/.kynver/credentials.*)","Read(~/.kynver/chat-box-credential)","Read(~/.kynver/site-logins/**)"]});import{spawn as r5}from"node:child_process";async function eD(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=Jt(o),i=new Set([...Ck,...pf]);return new Promise(a=>{let l="",c=!1,u=m=>{c||(c=!0,clearTimeout(f),a({...m,at:r().toISOString()}))},d;try{d=r5(t.execPath??process.execPath,["-e",n5],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 n5,tD=p(()=>{"use strict";M();ao();di();n5="process.stdout.write(JSON.stringify(Object.keys(process.env)))"});import{existsSync as o5,mkdirSync as s5,readFileSync as i5,writeFileSync as a5}from"node:fs";import{homedir as l5}from"node:os";import Pk from"node:path";function Ik(e=l5()){return Pk.join(e,c5)}function rD(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function u5(e){return typeof e.access!="string"?null:{access:e.access,folders:rD(e.folders),source:e.source??"default",signed:e.signed===!0,at:typeof e.at=="string"?e.at:""}}function d5(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(typeof r.access=="string")return{access:r.access,folders:rD(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 Yd(e=Ik()){try{if(!o5(e))return{applied:null,website:null};let t=JSON.parse(i5(e,"utf8"));if(!t||typeof t!="object")return{applied:null,website:null};let r=u5(t);return{applied:r,website:d5(t.website,r)}}catch{return{applied:null,website:null}}}function nD(e,t){try{s5(Pk.dirname(e),{recursive:!0});let r={...t.applied??{},...t.website?{website:t.website}:{}};a5(e,`${JSON.stringify(r,null,2)}
|
|
200
|
+
`,{mode:384})}catch{}}function p5(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 oD(e,t={signed:!1}){let r=t.file??Ik(),n=t.now??(()=>new Date),o={access:e.access,folders:[...e.folders],source:e.source,signed:t.signed,at:n().toISOString()},s=Yd(r);return p5(s.applied,o)?null:(nD(r,{applied:o,website:s.website}),{from:s.applied,to:o})}function sD(e,t={}){let r=t.file??Ik(),n=t.now??(()=>new Date),o=Yd(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:(nD(r,{applied:o.applied,website:s}),s)}function za(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 c5,iD=p(()=>{"use strict";c5=Pk.join(".kynver","chat-access-state.json")});import{verify as f5,createPublicKey as m5}from"node:crypto";function y5(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 aD(e){return!e||typeof e!="object"||Array.isArray(e)?null:e[g5]??null}function k5(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function b5(e,t){let r=Date.parse(e),n=Date.parse(t);return Number.isNaN(r)?!1:Number.isNaN(n)?!0:r>n}function Ok(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(!y5(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||!k5(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=On(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(rt(s),"utf8"),d=m5({key:Buffer.concat([h5,Buffer.from(i)]),format:"der",type:"spki"});l=f5(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||!b5(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 NTe,g5,h5,lD=p(()=>{"use strict";Hr();Mi();NTe=720*60*60,g5="change",h5=Buffer.from("302a300506032b6570032100","hex")});function cD(e){switch(e){case"off":return 0;case"folder":case"folders":return 1;case"full":return 2;default:return 0}}function v5(e,t){let r=cD(e.access),n=cD(t.access);if(r!==n)return r>n;if(r!==1)return!1;let o=new Set(Sn(t.folders));return Sn(e.folders).some(s=>!o.has(s))}function R5(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=jo(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:aD(r)}}function dD(e){let t=R5(e.signedAccess,e.boxId);if(!t)return{ok:!0,website:null,raised:!1};let r=jo(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:Sn(e.local.chatWorkFolders)}:{access:vc(e.engine),folders:[]});let o=n.every(c=>v5(t.level,c)),s=(e.now??(()=>new Date))().toISOString(),i=e.state.website;if(!o){let c=t.change!==null?Ok(t.change,{agentOsId:e.agentOsId,boxId:e.boxId,access:t.level.access,folders:t.level.folders},{env:e.env,nowSec:e.nowSec,lastApplied:uD(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=Ok(t.change,{agentOsId:e.agentOsId,boxId:e.boxId,access:t.level.access,folders:t.level.folders},{env:e.env,nowSec:e.nowSec,lastApplied:uD(i)}),l=i?.access??r??vc(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 uD(e){return!e||!e.changedAt&&!e.nonce?null:{changedAt:e.changedAt,nonce:e.nonce}}var pD=p(()=>{"use strict";lD();_n()});function w5(e){let r=e.chatProvider?.trim()||e.workerProvider?.trim()||"";return He(r)}function lo(e,t=process.env){return w5(e)!=="gemini"?"http":ks(gt(t))==="antigravity"?"antigravity":"http"}var zd=p(()=>{"use strict";Jn();Ii()});import{spawnSync as hD}from"node:child_process";import{existsSync as S5,readFileSync as _5}from"node:fs";import{homedir as x5,platform as C5}from"node:os";import fD from"node:path";function Xd(e,t,r=process.env){return e==="cursor"?"cursor":e==="codex"?"codex":e==="gemini"?lo(t,r)==="antigravity"?"antigravity":"none":e==="anthropic"?"claude-code":"none"}function E5(e,t){return e==="cursor"?Kn(t):e==="codex"?t.KYNVER_CODEX_BIN?.trim()||t.CODEX_BIN?.trim()||xr():e==="antigravity"?gt(t):e==="claude-code"?t.KYNVER_CLAUDE_BIN?.trim()||t.CLAUDE_BIN?.trim()||"claude":null}function Qd(e,t=process.env,r=Date.now()){let n=E5(e,t);if(!n)return null;let o=mD.get(n);if(o&&r-o.at<yD)return o.version;let s=null;try{let[i,a]=ie(n,["--version"]),l=hD(i,a,z({encoding:"utf8",timeout:5e3})),c=`${l.stdout??""} ${l.stderr??""}`;s=l.status===0?c.match(A5)?.[0]??null:null}catch{s=null}return mD.set(n,{at:r,version:s}),s}function Zd(e=process.env,t={}){if(e.ANTHROPIC_API_KEY?.trim())return!0;let r=t.home??x5(),n=t.now??Date.now(),o=gD.get(r);if(o&&n-o.at<yD)return o.signedIn;let s=P5(fD.join(e.CLAUDE_CONFIG_DIR?.trim()||fD.join(r,".claude"),".credentials.json"));return!s&&(t.os??C5())==="darwin"&&(s=(t.keychain??I5)()),gD.set(r,{at:n,signedIn:s}),s}function P5(e){if(!S5(e))return!1;try{let t=JSON.parse(_5(e,"utf8")).claudeAiOauth,r=n=>typeof n=="string"&&n.length>0;return!!t&&(r(t.refreshToken)||r(t.accessToken))}catch{return!1}}function I5(){try{return hD("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}var A5,yD,mD,gD,Xa=p(()=>{"use strict";jn();gs();Jn();Je();M();zd();A5=/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/,yD=10*6e4,mD=new Map;gD=new Map});import{appendFileSync as O5,mkdirSync as T5}from"node:fs";import{homedir as N5}from"node:os";import Tk from"node:path";function Nk(e=N5()){return Tk.join(e,D5)}function Dk(e){let t=r=>r===void 0?void 0:r.length>kD?`${r.slice(0,kD)}\u2026`:r;return{...e,...e.command!==void 0?{command:t(e.command)}:{},...e.path!==void 0?{path:t(e.path)}:{}}}function Qa(e,t=Nk()){try{return T5(Tk.dirname(t),{recursive:!0}),O5(t,`${JSON.stringify(Dk(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 D5,kD,ep=p(()=>{"use strict";D5=Tk.join(".kynver","logs","chat-commands.jsonl"),kD=2e3});var ln,tp=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 co,Mk=p(()=>{"use strict";co=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 bD(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(U5.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&&!F5.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:B5}:r==="run dispatch"?{ok:!1,mutating:!0,reason:L5}:M5.has(r)?{ok:!0,mutating:!1}:W5.has(r)?{ok:!0,mutating:!0}:{ok:!1,mutating:!1,reason:`verb not allowlisted: ${r}`}}var M5,L5,B5,W5,U5,F5,vD=p(()=>{"use strict";M5=new Set(["run list","run status","worker list","worker status","worker tail","status","cron status","monitor status","monitor list","update check","update status"]),L5="run dispatch is blocked from runtime_command \u2014 use agent_os_submit_action_intent with kind dispatch_workers (live dispatch requires Action Required approval)",B5='update finish is internal to `kynver update` \u2014 call ["update"] (confirmed) to update Kynver',W5=new Set(["run create","run sweep","worker start","worker stop","worker complete","cleanup","update"]),U5=["--secret","--api-key","--keeper-child"],F5=new Set(["runner-install","node-runtime","local-store","context-envelope","runtime-takeover"])});import{spawn as K5}from"node:child_process";function j5(e,t,r,n=process.env){let o=dS(r,{agentOsId:e,argv:t},n);return o.ok?null:`command authorization proof invalid: ${o.reason}`}async function wD(e,t,r={}){if(r.agentOsId){let a=j5(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=bD(e);if(!n.ok)return{exitCode:null,timedOut:!1,refused:n.reason};let o=r.cliEntry??process.argv[1],s=r.timeoutMs??$5,i=new ln(t);return new Promise(a=>{let l=0,c=!1,u=K5(process.execPath,[o,...e],z({stdio:["ignore","pipe","pipe"],env:process.env})),d=m=>{if(l>=RD)return;let g=m.toString("utf8").slice(0,RD-l);l+=g.length,i.push(g)};u.stdout?.on("data",d),u.stderr?.on("data",d);let f=setTimeout(()=>{c=!0,Qe(u,"SIGTERM"),setTimeout(()=>Qe(u,"SIGKILL"),H5).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 $5,H5,RD,SD=p(()=>{"use strict";M();tp();vD();Mi();$5=10*6e4,H5=5e3,RD=2e5});function _D(e=process.env){return e.KYNVER_OPENAI_DEFAULT_MODEL?.trim()||V5}var V5,gNe,xD=p(()=>{"use strict";fa();Su();Ft();V5="gpt-5.5",gNe=600*1e3});function uo(e){let t=e.chatProvider?.trim();return Hs(t||e.workerProvider?.trim()||"cursor")}function Hs(e){let t=He(e);return t==="cursor"||t==="agent"?"cursor":q5.has(t)?"gemini":CD.has(t)||CD.has(e.trim().toLowerCase())?"codex":ED.has(t)||ED.has(e.trim().toLowerCase())?"openai":(J5.has(t),"anthropic")}function js(e,t,r=process.env){let n=r.KYNVER_CHAT_MODEL?.trim();if(n){if(e==="cursor"){let s=ms(n,Za);return s.ok?s.model:Za}if(e==="gemini"&&!Lk.test(n)&&!Bk.test(n)||(e==="openai"||e==="codex")&&!Lk.test(n)&&!AD.test(n)||e==="anthropic")return n}let o=t.defaultModel?.trim();if(e==="cursor"){if(o&&!Lk.test(o)){let s=ms(o,Za);return s.ok?s.model:Za}return Za}return e==="gemini"?o&&AD.test(o)?o:Fe(r):e==="codex"?o&&Bk.test(o)?o:r.KYNVER_CODEX_DEFAULT_MODEL?.trim()||G5:e==="openai"?o&&Bk.test(o)?o:_D(r):o||"claude-sonnet-4-6"}var Za,G5,J5,q5,CD,ED,Lk,AD,Bk,el=p(()=>{"use strict";Ln();Ft();ma();xD();Za="composer-2.5",G5="gpt-5.5",J5=new Set(["claude","anthropic","opus"]),q5=new Set(["gemini","gemini-api"]),CD=new Set(["codex","chatgpt","gpt"]),ED=new Set(["openai","openai-compatible","openai-api","openai_api"]);Lk=/^(?:claude[-_]|opus\b|sonnet\b|haiku\b)/i,AD=/^(?:gemini[-_]|flash\b|pro\b)/i,Bk=/^(?:gpt-|o\d|chatgpt-)/i});function tl(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 z5(e){return{apt:e.t64?1:0,dnf:2,zypper:3,pacman:4,apk:5,unknown:null}[e.family]}function X5(e,t){let r=z5(t);if(r===null)return[];let n=new Set;for(let o of e){let s=Y5.find(([i])=>i.test(o));s&&n.add(s[1][r])}return[...n].sort()}function Q5(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 PD(e,t){let r=X5(e,t),n=Q5(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 Y5,rp=p(()=>{"use strict";Y5=[[/^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 Z5}from"node:child_process";function t9(e){return/(\d+\.\d+\.\d+\.\d+)/.exec(e)?.[1]??null}function r9(e,t=process.platform,r=e9){let n=new Set;if(t==="linux"){let s=r("ldd",[e],{encoding:"utf8",timeout:1e4});if(!s.error)for(let i of tl(`${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 Fa(i))n.add(a);s.status===0&&(o=r3(i))}return{version:o,missingLibs:[...n].sort()}}function ZN(e,t=()=>n3(e),r=Date.now){let n=Xy.get(e);if(n&&r()-n.at<o3)return n.health;let o=t();return Xy.set(e,{at:r(),health:o}),o}function e0(){Xy.clear()}var t3,o3,Xy,Qy=p(()=>{"use strict";Td();t3=(e,t,r)=>e3(e,t,r);o3=10*6e4,Xy=new Map});import{existsSync as s3,readFileSync as t0}from"node:fs";function Ds(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 r0(e,t){try{return e(t)}catch{return""}}function Ka(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=>t0(o,"utf8"));return/microsoft|wsl/i.test(r0(n,"/proc/version"))}function i3(e=process.env,t=process.platform,r={}){if(t!=="linux")return{available:!0,wslg:!1};let n=r.exists??s3,o=Ka(e,t,r)&&n("/mnt/wslg");return{available:!!(e.DISPLAY?.trim()||e.WAYLAND_DISPLAY?.trim()),wslg:o}}function Nd(e=process.env,t=process.platform){return/^(1|true|yes|on)$/i.test(e.KYNVER_BROWSER_HEADLESS??"")?!0:!i3(e,t).available}function a3(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 n0(e={}){let t=e.readFile??(r=>t0(r,"utf8"));return a3(r0(t,"/etc/os-release"))}var no=p(()=>{"use strict"});import{existsSync as l3,readdirSync as c3}from"node:fs";import{homedir as u3}from"node:os";import oo from"node:path";function Dd(e=process.env){return e.KYNVER_BROWSER_INSTALL_DIR?.trim()||oo.join(u3(),".kynver","browsers")}function o0(e,t=process.env){return oo.join(Dd(t),`chrome-${e}`)}function Md(e,t){let r=oo.join(e,`chrome-${t}`);return t==="linux64"?oo.join(r,"chrome"):t==="win32"||t==="win64"?oo.join(r,"chrome.exe"):oo.join(r,"Google Chrome for Testing.app","Contents","MacOS","Google Chrome for Testing")}function d3(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 Ld(e,t=process.env,r={}){let n=r.exists??l3,o=r.listDir??(l=>c3(l)),s=Dd(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(d3).reverse();for(let l of a){let c=oo.join(s,`chrome-${l}`),u=Md(c,e);if(n(u))return{executable:u,version:l,installDir:c}}return null}var Zy=p(()=>{"use strict"});import{existsSync as p3,readdirSync as f3}from"node:fs";import{homedir as m3}from"node:os";import Pr from"node:path";function g3(e,t,r=m3()){return e==="win32"?[t.PROGRAMFILES,t["PROGRAMFILES(X86)"],t.LOCALAPPDATA].filter(o=>typeof o=="string"&&o.length>0).flatMap(o=>[Pr.join(o,"Google","Chrome","Application","chrome.exe"),Pr.join(o,"Microsoft","Edge","Application","msedge.exe"),Pr.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",Pr.join(r,"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),Pr.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",Pr.join(r,".local/share/flatpak/exports/bin/com.google.Chrome"),Pr.join(r,".local/share/flatpak/exports/bin/org.chromium.Chromium"),...s0.map(n=>Pr.join(r,".local/bin",n))]}function h3(e,t,r){let n=(e.PATH??"").split(":").filter(o=>o&&!(r&&o.startsWith("/mnt/")));for(let o of s0)for(let s of n){let i=Pr.join(s,o);if(t(i))return i}return null}function so(e={}){let t=e.env??process.env,r=e.platform??process.platform,n=e.arch??process.arch,o=e.exists??p3,s=e.config??I(),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=g3(r,t,e.home).find(u=>o(u));if(l)return{executable:l,source:"system",version:null,configuredMissing:i};if(r==="linux"){let u=h3(t,o,Ka(t,r,{readFile:e.readFile}));if(u)return{executable:u,source:"system",version:null,configuredMissing:i}}let c=Ds(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=Ld(c,t,{exists:o,listDir:e.listDir??(m=>f3(m))});if(d)return{executable:d.executable,source:"managed",version:d.version,configuredMissing:i}}return{executable:null,source:"none",version:null,configuredMissing:i}}var s0,$a=p(()=>{"use strict";K();no();Zy();s0=["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge","microsoft-edge-stable"]});import{createWriteStream as y3}from"node:fs";import{rm as k3}from"node:fs/promises";function R3(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(a0))return{version:r.version,url:s.url}}return null}async function l0(e,t=fetch){let r=await t(b3,{signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`Chrome for Testing index returned HTTP ${r.status}`);let n=R3(await r.json(),e);if(!n)throw new Error(`No stable Chrome for Testing build is published for ${e}`);return n}async function c0(e,t,r={}){let n=r.minBytes??v3;if(!e.startsWith(a0))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>i0))throw new Error(`browser download has an unexpected size (${a} bytes)`);let l=y3(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>i0)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 k3(t,{force:!0}).catch(()=>{}),u}}var b3,a0,v3,i0,u0=p(()=>{"use strict";b3="https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json",a0="https://storage.googleapis.com/chrome-for-testing-public/",v3=20*1024*1024,i0=600*1024*1024});import{chmodSync as w3,mkdirSync as ek,symlinkSync as S3,writeFileSync as _3}from"node:fs";import Ms from"node:path";import{crc32 as x3,inflateRawSync as C3}from"node:zlib";function I3(e){let t=Math.max(0,e.length-65535-22);for(let r=e.length-22;r>=t;r-=1)if(e.readUInt32LE(r)===E3)return r;throw new Error("not a zip archive (no end-of-central-directory record)")}function O3(e){let t=I3(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)!==A3)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 T3(e,t){let r=t.localHeaderOffset;if(e.readUInt32LE(r)!==P3)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=C3(o);else throw new Error(`unsupported zip compression method ${t.method} (${t.name})`);if(s.length!==t.size||x3(s)>>>0!==t.crc>>>0)throw new Error(`zip entry failed its integrity check: ${t.name}`);return s}function d0(e,t){let r=t.replace(/\\/g,"/");if(r.startsWith("/")||/^[a-zA-Z]:/.test(r))throw new Error(`unsafe zip path: ${t}`);let n=Ms.resolve(e,r),o=Ms.resolve(e);if(n!==o&&!n.startsWith(o+Ms.sep))throw new Error(`unsafe zip path: ${t}`);return n}function p0(e,t,r=process.platform){ek(t,{recursive:!0});let n=0;for(let o of O3(e)){let s=d0(t,o.name);if(o.name.endsWith("/")){ek(s,{recursive:!0});continue}ek(Ms.dirname(s),{recursive:!0});let i=T3(e,o);if(o.unixMode!==null&&(o.unixMode&N3)===D3&&r!=="win32"){let a=i.toString("utf8");d0(t,Ms.posix.join(Ms.posix.dirname(o.name.replace(/\\/g,"/")),a)),S3(a,s)}else _3(s,i),o.unixMode!==null&&r!=="win32"&&w3(s,o.unixMode&511||420);n+=1}return n}var E3,A3,P3,N3,D3,f0=p(()=>{"use strict";E3=101010256,A3=33639248,P3=67324752;N3=61440,D3=40960});import{closeSync as m0,existsSync as tk,mkdirSync as M3,openSync as g0,readFileSync as L3,renameSync as B3,rmSync as Ls,statSync as U3,chmodSync as W3}from"node:fs";import rk from"node:path";function io(){return{...It}}function k0(e=It){return e.state!=="failed"||e.failedAt===null?0:e.failedAt+h0[Math.min(e.attempts-1,h0.length-1)]}function b0(e=It){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 K3(e){let t=I();Le({...t,browserManaged:{version:e.version,platform:e.platform,executable:e.executable,installedAt:new Date().toISOString()}})}function $3(e,t){p0(L3(e),t)}function H3(e,t){try{return m0(g0(e,"wx")),!0}catch{try{if(t-U3(e).mtimeMs>F3)return Ls(e,{force:!0}),m0(g0(e,"wx")),!0}catch{}return!1}}async function j3(e,t){let r=t.env??process.env,n=t.now??Date.now,o=t.sleep??(a=>new Promise(l=>setTimeout(l,a))),s=Dd(r);M3(s,{recursive:!0});let i=rk.join(s,".install.lock");for(;!H3(i,n());)if(await o(2e3),!tk(i)){let a=Ld(e,r);if(a)return a}try{let a=await l0(e,t.fetchFn),l=o0(a.version,r),c=Md(l,e);if(!tk(c)){let d=rk.join(s,`.download-${a.version}.zip`),m=rk.join(s,`.staging-${a.version}-${process.pid}`);Ls(m,{recursive:!0,force:!0});try{await c0(a.url,d,{fetchFn:t.fetchFn,minBytes:t.minArchiveBytes,onProgress:g=>{It.receivedBytes=g.receivedBytes,It.totalBytes=g.totalBytes}}),(t.extract??$3)(d,m);let f=Md(m,e);if(!tk(f))throw new Error("the downloaded browser archive did not contain Chrome");(t.platform??process.platform)!=="win32"&&W3(f,493),Ls(l,{recursive:!0,force:!0}),B3(m,l)}finally{Ls(d,{force:!0}),Ls(m,{recursive:!0,force:!0})}}let u={executable:c,version:a.version,installDir:l};return(t.record??K3)({...u,platform:e}),u}finally{Ls(i,{force:!0})}}function Bd(e={}){if(Ha)return Ha;let t=Ds(e.platform??process.platform,e.arch??process.arch);if(!t)return Promise.reject(new Bs("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 It={...It,state:"downloading",receivedBytes:0,totalBytes:null,error:null},Ha=j3(t,e).then(n=>(It={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},e0(),n)).catch(n=>{let o=n instanceof Error?n.message:String(n);throw It={...It,state:"failed",error:o.slice(0,300),failedAt:r(),attempts:It.attempts+1},new Bs(`Couldn't download a browser for this computer: ${o.slice(0,200)}`,"download_failed")}).finally(()=>{Ha=null}),Ha}var y0,F3,h0,Bs,It,Ha,Ud=p(()=>{"use strict";K();no();u0();Qy();Zy();f0();y0=150,F3=30*6e4,h0=[6e4,5*6e4,30*6e4,120*6e4],Bs=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserProvisionError"}code},It={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},Ha=null});function nk(e){return V3.test(e)}function v0(e=process.platform,t=typeof process.getuid=="function"?process.getuid():null){return e==="linux"&&t===0}function Wd(e){R0=e}function w0(){return R0}var V3,R0,ok=p(()=>{"use strict";V3=/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;R0=null});function S0(e=process.env,t={}){let r=t.platform??process.platform,n=I(),o={executable:null,source:"none",version:null,configuredMissing:null};try{o=(t.resolve??(()=>so({env:e,platform:r,config:n})))()}catch{}let s={version:null,missingLibs:[]};if(o.executable)try{s=(t.health??(i=>ZN(i)))(o.executable)}catch{}return{supported:!0,chromeFound:o.executable!==null,localDisabled:n.browserDisabled===!0,browserSource:o.source,browserVersion:o.version??s.version,provisioning:io().state,missingLibs:s.missingLibs,wsl:Ka(e,r),headless:Nd(e,r),autoProvision:n.browserAutoProvision!==!1,sandbox:w0()}}var _0=p(()=>{"use strict";K();Qy();no();$a();Ud();ok()});function Fd(e,t,r,n,o){return{chatProvider:e,toolCalls:e==="anthropic"||e==="cursor"||e==="gemini"||e==="openai"||e==="codex",runtimePackageVersion:Dt,browser:S0(),deliveryReceipt:!0,...t?{chatModels:t}:{},...r?{computer:r}:{},...n?{security:n}:{},...o?{agentEngines:o}:{}}}var x0=p(()=>{"use strict";Jo();_0()});import{readFileSync as G3}from"node:fs";import{homedir as J3,platform as q3}from"node:os";import Y3 from"node:path";import{execFileSync as z3}from"node:child_process";function C0(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 X3(){if(q3()==="darwin")try{let e=z3("security",["find-generic-password","-s","Claude Code-credentials","-w"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return C0(e.trim())}catch{return null}try{let e=G3(Y3.join(J3(),".claude",".credentials.json"),"utf8");return C0(e)}catch{return null}}function ja(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=X3();if(s)return{kind:"oauth",token:s}}return null}var sk=p(()=>{"use strict"});import{existsSync as E0}from"node:fs";import{homedir as Q3}from"node:os";import Va from"node:path";import{spawnSync as Z3}from"node:child_process";function e8(e){if(Va.isAbsolute(e)||e.includes("/")||e.includes("\\"))return E0(e);try{let t=Z3(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function t8(e=process.env){let t=Q3(),r=[],n=e.CODEX_HOME?.trim();return n&&r.push(Va.join(Va.resolve(n),"auth.json")),r.push(Va.join(t,".codex","auth.json")),r.push(Va.join(t,".config","codex","auth.json")),r}function A0(e){return`${e.error}: ${e.detail}`}function $d(e=process.env){let t=e.KYNVER_CODEX_BIN?.trim()||e.CODEX_BIN?.trim()||vr();return e8(t)?e.CODEX_API_KEY?.trim()?{ok:!0,creds:{codexBin:t,authSource:"api_key_env"}}:t8(e).find(n=>E0(n))?{ok:!0,creds:{codexBin:t,authSource:"oauth_local"}}:{ok:!1,error:ik,detail:"Run `codex login` on this computer, or set CODEX_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:Kd,detail:"`codex` CLI not found. Install the Codex CLI (https://developers.openai.com/codex/) and keep it on PATH."}}var Kd,ik,Hd=p(()=>{"use strict";Mn();Kd="codex_cli_unavailable",ik="codex_not_logged_in"});import{spawnSync as r8}from"node:child_process";function o8(e,t,r){return n8.test(`${t}
|
|
141
|
-
${r}`)?!1:e===0}function P0(e,t=process.env){try{let[r,n]=oe(e,["models"]),o=r8(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"}:o8(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 n8,I0=p(()=>{"use strict";Ge();n8=/authentication required|not logged in|you are not logged|not authenticated/i});import{existsSync as s8,readFileSync as i8}from"node:fs";import{homedir as a8}from"node:os";import O0 from"node:path";import{spawnSync as l8}from"node:child_process";function c8(e){if(O0.isAbsolute(e)||e.includes("/")||e.includes("\\"))return s8(e);try{let t=l8(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function u8(){return O0.join(a8(),".gemini","antigravity-cli","settings.json")}function d8(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 p8(){try{return i8(u8(),"utf8")}catch{return null}}function f8(e,t){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()?d8(t)==="gemini":!1}function T0(e){return`${e.error}: ${e.detail}`}function Gd(e=process.env,t={}){let r=dt(e);if(!(t.commandOnPath??c8)(r))return{ok:!1,error:jd,detail:"`agy` not found. Install Google Antigravity (https://antigravity.google/docs/cli/install) and keep `agy` on PATH."};if((t.probeAuth??P0)(r,e).ok)return{ok:!0,creds:{bin:r,authSource:"keyring"}};let s=(t.readSettings??(()=>p8()))(e);return f8(e,s)?{ok:!0,creds:{bin:r,authSource:"api_key_settings"}}:{ok:!1,error:Vd,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 jd,Vd,Jd=p(()=>{"use strict";Un();I0();jd="antigravity_cli_unavailable",Vd="antigravity_not_logged_in"});function Ga(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()||m8).replace(/\/+$/,"");return{apiKey:t,baseUrl:r,label:"gemini"}}function Ja(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()||g8).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 m8,g8,ak=p(()=>{"use strict";m8="https://generativelanguage.googleapis.com/v1beta/openai",g8="https://api.openai.com/v1"});function y8(e,t=process.env){return{anthropic:()=>{let r=ja(t,{oauthOptIn:e.chatUseClaudeOauth===!0});return r?r.kind==="oauth"?"subscription":"api_key":null},codex:()=>{let r=$d(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},cursor:()=>{let r=Xc(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},gemini:()=>{let r=t;if(eo({chatProvider:e.chatProvider,workerProvider:e.workerProvider},r)==="antigravity"){let n=Gd(r);return n.ok?n.creds.authSource==="api_key_settings"?"api_key":"subscription":null}return Ga(t)?"api_key":null},openai:()=>Ja(t)?"api_key":null}}function k8(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:Ts(r.slice(0,n)),model:o})}return t}function lk(e,t){let r=t?.trim();r&&!e.includes(r)&&e.push(r)}function b8(e,t,r=process.env){let n=ro(e),o=k8(r.KYNVER_CHAT_EXTRA_MODELS),s=[];for(let i of ck){let a=null;try{a=t[i]()}catch{a=null}if(!a)continue;let l=i===n?Ns(i,e,r):Ns(i,{},{...r,KYNVER_CHAT_MODEL:void 0}),c=[];lk(c,l);for(let u of h8[i])lk(c,u);for(let u of o)u.provider===i&&lk(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 qd(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(qa&&qa.key===n&&r-qa.at<v8)return qa.value;let o=b8(e,y8(e,t),t);return qa={key:n,at:r,value:o},o}var ck,h8,v8,qa,uk=p(()=>{"use strict";sk();Hd();as();Jd();Cd();ak();Wa();ck=["anthropic","codex","openai","gemini","cursor"],h8={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"]};v8=6e4,qa=null});function Ya(e){if(typeof e=="string"){let n=e.indexOf(":");return n<=0?null:Ya({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:Ts(t.provider),model:r}}function D0(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 M0(e,t){for(let r of ck){if(t.includes(r))continue;let n=e.find(o=>o.provider===r);if(n)return{provider:r,model:n.defaultModel}}return null}function L0(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return t?R8.some(r=>r.test(t)):!1}function N0(e){return w8[e]}function B0(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 U0(e,t){let r=`${N0(e.provider)} (${e.model})`;if(e.fallbackReason==="usage_limit")return`${t?N0(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 R8,w8,dk=p(()=>{"use strict";uk();Wa();R8=[/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/];w8={anthropic:"Claude",codex:"ChatGPT",openai:"ChatGPT",gemini:"Gemini",cursor:"Cursor"}});function F0(e){if(!e||typeof e!="object")return!1;let t=e;return!(typeof t.type!="string"||!S8.has(t.type)||t.type==="text"&&(typeof t.text!="string"||!t.text.trim()))}function W0(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:za}]}:null;if(!Array.isArray(t.content)||t.content.length===0)return null;let r=t.content[t.content.length-1];return F0(r)?{...t,content:[...t.content.slice(0,-1),{...r,cache_control:za}]}:null}function _8(e){return Array.isArray(e)&&e.length>0&&e.every(t=>!!t&&typeof t=="object"&&t.type==="tool_result")}function x8(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!(!r||typeof r!="object"||r.role!=="user")&&!_8(r.content))return t}return-1}function pk(e){return JSON.stringify(e??null).includes('"cache_control"')}function K0(e){if(pk(e.system)||pk(e.tools)||pk(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:za},...t.slice(a+1)])}let r=e.system;if(typeof r=="string")r.trim()&&(r=[{type:"text",text:r,cache_control:za}]);else if(Array.isArray(r)&&r.length>0){let i=r[r.length-1];F0(i)&&(r=[...r.slice(0,-1),{...i,cache_control:za}])}let n=[...e.messages],o=-1;for(let i=n.length-1;i>=0;i-=1){let a=W0(n[i]);if(a){n[i]=a,o=i;break}}let s=x8(n)-1;if(s>=0&&s<o)for(let i=s;i>=0;i-=1){let a=W0(n[i]);if(a){n[i]=a;break}}return{system:r,tools:t,messages:n}}var za,S8,$0=p(()=>{"use strict";za={type:"ephemeral"},S8=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 H0(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 E8(){return{blocks:[],stopReason:null,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}}function A8(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 P8(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*I8(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 tl(i))n.add(a);s.status===0&&(o=t9(i))}return{version:o,missingLibs:[...n].sort()}}function ID(e,t=()=>r9(e),r=Date.now){let n=Wk.get(e);if(n&&r()-n.at<n9)return n.health;let o=t();return Wk.set(e,{at:r(),health:o}),o}function OD(){Wk.clear()}var e9,n9,Wk,Uk=p(()=>{"use strict";rp();e9=(e,t,r)=>Z5(e,t,r);n9=10*6e4,Wk=new Map});import{existsSync as o9,readFileSync as TD}from"node:fs";function Vs(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 ND(e,t){try{return e(t)}catch{return""}}function rl(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=>TD(o,"utf8"));return/microsoft|wsl/i.test(ND(n,"/proc/version"))}function s9(e=process.env,t=process.platform,r={}){if(t!=="linux")return{available:!0,wslg:!1};let n=r.exists??o9,o=rl(e,t,r)&&n("/mnt/wslg");return{available:!!(e.DISPLAY?.trim()||e.WAYLAND_DISPLAY?.trim()),wslg:o}}function np(e=process.env,t=process.platform){return/^(1|true|yes|on)$/i.test(e.KYNVER_BROWSER_HEADLESS??"")?!0:!s9(e,t).available}function i9(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 DD(e={}){let t=e.readFile??(r=>TD(r,"utf8"));return i9(ND(t,"/etc/os-release"))}var po=p(()=>{"use strict"});import{existsSync as a9,readdirSync as l9}from"node:fs";import{homedir as c9}from"node:os";import fo from"node:path";function op(e=process.env){return e.KYNVER_BROWSER_INSTALL_DIR?.trim()||fo.join(c9(),".kynver","browsers")}function MD(e,t=process.env){return fo.join(op(t),`chrome-${e}`)}function sp(e,t){let r=fo.join(e,`chrome-${t}`);return t==="linux64"?fo.join(r,"chrome"):t==="win32"||t==="win64"?fo.join(r,"chrome.exe"):fo.join(r,"Google Chrome for Testing.app","Contents","MacOS","Google Chrome for Testing")}function u9(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 ip(e,t=process.env,r={}){let n=r.exists??a9,o=r.listDir??(l=>l9(l)),s=op(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(u9).reverse();for(let l of a){let c=fo.join(s,`chrome-${l}`),u=sp(c,e);if(n(u))return{executable:u,version:l,installDir:c}}return null}var Fk=p(()=>{"use strict"});import{existsSync as d9,readdirSync as p9}from"node:fs";import{homedir as f9}from"node:os";import Dr from"node:path";function m9(e,t,r=f9()){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"),...LD.map(n=>Dr.join(r,".local/bin",n))]}function g9(e,t,r){let n=(e.PATH??"").split(":").filter(o=>o&&!(r&&o.startsWith("/mnt/")));for(let o of LD)for(let s of n){let i=Dr.join(s,o);if(t(i))return i}return null}function mo(e={}){let t=e.env??process.env,r=e.platform??process.platform,n=e.arch??process.arch,o=e.exists??d9,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=m9(r,t,e.home).find(u=>o(u));if(l)return{executable:l,source:"system",version:null,configuredMissing:i};if(r==="linux"){let u=g9(t,o,rl(t,r,{readFile:e.readFile}));if(u)return{executable:u,source:"system",version:null,configuredMissing:i}}let c=Vs(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=ip(c,t,{exists:o,listDir:e.listDir??(f=>p9(f))});if(d)return{executable:d.executable,source:"managed",version:d.version,configuredMissing:i}}return{executable:null,source:"none",version:null,configuredMissing:i}}var LD,nl=p(()=>{"use strict";j();po();Fk();LD=["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge","microsoft-edge-stable"]});import{createWriteStream as h9}from"node:fs";import{rm as y9}from"node:fs/promises";function v9(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(WD))return{version:r.version,url:s.url}}return null}async function UD(e,t=fetch){let r=await t(k9,{signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`Chrome for Testing index returned HTTP ${r.status}`);let n=v9(await r.json(),e);if(!n)throw new Error(`No stable Chrome for Testing build is published for ${e}`);return n}async function FD(e,t,r={}){let n=r.minBytes??b9;if(!e.startsWith(WD))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>BD))throw new Error(`browser download has an unexpected size (${a} bytes)`);let l=h9(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>BD)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 y9(t,{force:!0}).catch(()=>{}),u}}var k9,WD,b9,BD,KD=p(()=>{"use strict";k9="https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json",WD="https://storage.googleapis.com/chrome-for-testing-public/",b9=20*1024*1024,BD=600*1024*1024});import{chmodSync as R9,mkdirSync as Kk,symlinkSync as w9,writeFileSync as S9}from"node:fs";import Gs from"node:path";import{crc32 as _9,inflateRawSync as x9}from"node:zlib";function P9(e){let t=Math.max(0,e.length-65535-22);for(let r=e.length-22;r>=t;r-=1)if(e.readUInt32LE(r)===C9)return r;throw new Error("not a zip archive (no end-of-central-directory record)")}function I9(e){let t=P9(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)!==E9)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 O9(e,t){let r=t.localHeaderOffset;if(e.readUInt32LE(r)!==A9)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=x9(o);else throw new Error(`unsupported zip compression method ${t.method} (${t.name})`);if(s.length!==t.size||_9(s)>>>0!==t.crc>>>0)throw new Error(`zip entry failed its integrity check: ${t.name}`);return s}function $D(e,t){let r=t.replace(/\\/g,"/");if(r.startsWith("/")||/^[a-zA-Z]:/.test(r))throw new Error(`unsafe zip path: ${t}`);let n=Gs.resolve(e,r),o=Gs.resolve(e);if(n!==o&&!n.startsWith(o+Gs.sep))throw new Error(`unsafe zip path: ${t}`);return n}function HD(e,t,r=process.platform){Kk(t,{recursive:!0});let n=0;for(let o of I9(e)){let s=$D(t,o.name);if(o.name.endsWith("/")){Kk(s,{recursive:!0});continue}Kk(Gs.dirname(s),{recursive:!0});let i=O9(e,o);if(o.unixMode!==null&&(o.unixMode&T9)===N9&&r!=="win32"){let a=i.toString("utf8");$D(t,Gs.posix.join(Gs.posix.dirname(o.name.replace(/\\/g,"/")),a)),w9(a,s)}else S9(s,i),o.unixMode!==null&&r!=="win32"&&R9(s,o.unixMode&511||420);n+=1}return n}var C9,E9,A9,T9,N9,jD=p(()=>{"use strict";C9=101010256,E9=33639248,A9=67324752;T9=61440,N9=40960});import{closeSync as VD,existsSync as $k,mkdirSync as D9,openSync as GD,readFileSync as M9,renameSync as L9,rmSync as Js,statSync as B9,chmodSync as W9}from"node:fs";import Hk from"node:path";function go(){return{...Dt}}function YD(e=Dt){return e.state!=="failed"||e.failedAt===null?0:e.failedAt+JD[Math.min(e.attempts-1,JD.length-1)]}function zD(e=Dt){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 F9(e){let t=E();Be({...t,browserManaged:{version:e.version,platform:e.platform,executable:e.executable,installedAt:new Date().toISOString()}})}function K9(e,t){HD(M9(e),t)}function $9(e,t){try{return VD(GD(e,"wx")),!0}catch{try{if(t-B9(e).mtimeMs>U9)return Js(e,{force:!0}),VD(GD(e,"wx")),!0}catch{}return!1}}async function H9(e,t){let r=t.env??process.env,n=t.now??Date.now,o=t.sleep??(a=>new Promise(l=>setTimeout(l,a))),s=op(r);D9(s,{recursive:!0});let i=Hk.join(s,".install.lock");for(;!$9(i,n());)if(await o(2e3),!$k(i)){let a=ip(e,r);if(a)return a}try{let a=await UD(e,t.fetchFn),l=MD(a.version,r),c=sp(l,e);if(!$k(c)){let d=Hk.join(s,`.download-${a.version}.zip`),f=Hk.join(s,`.staging-${a.version}-${process.pid}`);Js(f,{recursive:!0,force:!0});try{await FD(a.url,d,{fetchFn:t.fetchFn,minBytes:t.minArchiveBytes,onProgress:g=>{Dt.receivedBytes=g.receivedBytes,Dt.totalBytes=g.totalBytes}}),(t.extract??K9)(d,f);let m=sp(f,e);if(!$k(m))throw new Error("the downloaded browser archive did not contain Chrome");(t.platform??process.platform)!=="win32"&&W9(m,493),Js(l,{recursive:!0,force:!0}),L9(f,l)}finally{Js(d,{force:!0}),Js(f,{recursive:!0,force:!0})}}let u={executable:c,version:a.version,installDir:l};return(t.record??F9)({...u,platform:e}),u}finally{Js(i,{force:!0})}}function ap(e={}){if(ol)return ol;let t=Vs(e.platform??process.platform,e.arch??process.arch);if(!t)return Promise.reject(new qs("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 Dt={...Dt,state:"downloading",receivedBytes:0,totalBytes:null,error:null},ol=H9(t,e).then(n=>(Dt={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},OD(),n)).catch(n=>{let o=n instanceof Error?n.message:String(n);throw Dt={...Dt,state:"failed",error:o.slice(0,300),failedAt:r(),attempts:Dt.attempts+1},new qs(`Couldn't download a browser for this computer: ${o.slice(0,200)}`,"download_failed")}).finally(()=>{ol=null}),ol}var qD,U9,JD,qs,Dt,ol,lp=p(()=>{"use strict";j();po();KD();Uk();Fk();jD();qD=150,U9=30*6e4,JD=[6e4,5*6e4,30*6e4,120*6e4],qs=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserProvisionError"}code},Dt={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},ol=null});function jk(e){return j9.test(e)}function XD(e=process.platform,t=typeof process.getuid=="function"?process.getuid():null){return e==="linux"&&t===0}function cp(e){QD=e}function ZD(){return QD}var j9,QD,Vk=p(()=>{"use strict";j9=/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;QD=null});function eM(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??(()=>mo({env:e,platform:r,config:n})))()}catch{}let s={version:null,missingLibs:[]};if(o.executable)try{s=(t.health??(i=>ID(i)))(o.executable)}catch{}return{supported:!0,chromeFound:o.executable!==null,localDisabled:n.browserDisabled===!0,browserSource:o.source,browserVersion:o.version??s.version,provisioning:go().state,missingLibs:s.missingLibs,wsl:rl(e,r),headless:np(e,r),autoProvision:n.browserAutoProvision!==!1,sandbox:ZD()}}var tM=p(()=>{"use strict";j();Uk();po();nl();lp();Vk()});function up(e,t,r,n,o,s,i){return{chatProvider:e,toolCalls:e==="anthropic"||e==="cursor"||e==="gemini"||e==="openai"||e==="codex",runtimePackageVersion:Ve,browser:eM(),deliveryReceipt:!0,...t?{chatModels:t}:{},...r?{computer:r}:{},...n?{security:n}:{},...o?{agentEngines:o}:{},...s?{packageVersions:s}:{},...i?{selfUpdate:i}:{}}}var rM=p(()=>{"use strict";Vr();tM()});import{readFileSync as V9}from"node:fs";import{homedir as G9,platform as J9}from"node:os";import q9 from"node:path";import{execFileSync as Y9}from"node:child_process";function nM(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 z9(){if(J9()==="darwin")try{let e=Y9("security",["find-generic-password","-s","Claude Code-credentials","-w"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return nM(e.trim())}catch{return null}try{let e=V9(q9.join(G9(),".claude",".credentials.json"),"utf8");return nM(e)}catch{return null}}function sl(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=z9();if(s)return{kind:"oauth",token:s}}return null}var Gk=p(()=>{"use strict"});import{existsSync as oM}from"node:fs";import{homedir as X9}from"node:os";import il from"node:path";import{spawnSync as Q9}from"node:child_process";function Z9(e){if(il.isAbsolute(e)||e.includes("/")||e.includes("\\"))return oM(e);try{let t=Q9(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function e7(e=process.env){let t=X9(),r=[],n=e.CODEX_HOME?.trim();return n&&r.push(il.join(il.resolve(n),"auth.json")),r.push(il.join(t,".codex","auth.json")),r.push(il.join(t,".config","codex","auth.json")),r}function sM(e){return`${e.error}: ${e.detail}`}function pp(e=process.env){let t=e.KYNVER_CODEX_BIN?.trim()||e.CODEX_BIN?.trim()||xr();return Z9(t)?e.CODEX_API_KEY?.trim()?{ok:!0,creds:{codexBin:t,authSource:"api_key_env"}}:e7(e).find(n=>oM(n))?{ok:!0,creds:{codexBin:t,authSource:"oauth_local"}}:{ok:!1,error:Jk,detail:"Run `codex login` on this computer, or set CODEX_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:dp,detail:"`codex` CLI not found. Install the Codex CLI (https://developers.openai.com/codex/) and keep it on PATH."}}var dp,Jk,fp=p(()=>{"use strict";jn();dp="codex_cli_unavailable",Jk="codex_not_logged_in"});import{spawnSync as t7}from"node:child_process";function n7(e,t,r){return r7.test(`${t}
|
|
205
|
+
${r}`)?!1:e===0}function iM(e,t=process.env){try{let[r,n]=ie(e,["models"]),o=t7(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"}:n7(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 r7,aM=p(()=>{"use strict";Je();r7=/authentication required|not logged in|you are not logged|not authenticated/i});import{existsSync as o7,readFileSync as s7}from"node:fs";import{homedir as i7}from"node:os";import lM from"node:path";import{spawnSync as a7}from"node:child_process";function l7(e){if(lM.isAbsolute(e)||e.includes("/")||e.includes("\\"))return o7(e);try{let t=a7(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function c7(){return lM.join(i7(),".gemini","antigravity-cli","settings.json")}function u7(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 d7(){try{return s7(c7(),"utf8")}catch{return null}}function p7(e,t){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()?u7(t)==="gemini":!1}function cM(e){return`${e.error}: ${e.detail}`}function hp(e=process.env,t={}){let r=gt(e);if(!(t.commandOnPath??l7)(r))return{ok:!1,error:mp,detail:"`agy` not found. Install Google Antigravity (https://antigravity.google/docs/cli/install) and keep `agy` on PATH."};if((t.probeAuth??iM)(r,e).ok)return{ok:!0,creds:{bin:r,authSource:"keyring"}};let s=(t.readSettings??(()=>d7()))(e);return p7(e,s)?{ok:!0,creds:{bin:r,authSource:"api_key_settings"}}:{ok:!1,error:gp,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 mp,gp,yp=p(()=>{"use strict";Jn();aM();mp="antigravity_cli_unavailable",gp="antigravity_not_logged_in"});function al(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()||f7).replace(/\/+$/,"");return{apiKey:t,baseUrl:r,label:"gemini"}}function ll(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()||m7).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 f7,m7,qk=p(()=>{"use strict";f7="https://generativelanguage.googleapis.com/v1beta/openai",m7="https://api.openai.com/v1"});function h7(e,t=process.env){return{anthropic:()=>{let r=sl(t,{oauthOptIn:e.chatUseClaudeOauth===!0});return r?r.kind==="oauth"?"subscription":"api_key":null},codex:()=>{let r=pp(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},cursor:()=>{let r=hu(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},gemini:()=>{let r=t;if(lo({chatProvider:e.chatProvider,workerProvider:e.workerProvider},r)==="antigravity"){let n=hp(r);return n.ok?n.creds.authSource==="api_key_settings"?"api_key":"subscription":null}return al(t)?"api_key":null},openai:()=>ll(t)?"api_key":null}}function y7(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:Hs(r.slice(0,n)),model:o})}return t}function Yk(e,t){let r=t?.trim();r&&!e.includes(r)&&e.push(r)}function k7(e,t,r=process.env){let n=uo(e),o=y7(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?js(i,e,r):js(i,{},{...r,KYNVER_CHAT_MODEL:void 0}),c=[];Yk(c,l);for(let u of g7[i])Yk(c,u);for(let u of o)u.provider===i&&Yk(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 kp(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(cl&&cl.key===n&&r-cl.at<b7)return cl.value;let o=k7(e,h7(e,t),t);return cl={key:n,at:r,value:o},o}var zk,g7,b7,cl,Xk=p(()=>{"use strict";Gk();fp();hs();yp();zd();qk();el();zk=["anthropic","codex","openai","gemini","cursor"],g7={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"]};b7=6e4,cl=null});function ul(e){if(typeof e=="string"){let n=e.indexOf(":");return n<=0?null:ul({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:Hs(t.provider),model:r}}function dM(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 pM(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 fM(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return t?v7.some(r=>r.test(t)):!1}function uM(e){return R7[e]}function mM(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 gM(e,t){let r=`${uM(e.provider)} (${e.model})`;if(e.fallbackReason==="usage_limit")return`${t?uM(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 v7,R7,Qk=p(()=>{"use strict";Xk();el();v7=[/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/];R7={anthropic:"Claude",codex:"ChatGPT",openai:"ChatGPT",gemini:"Gemini",cursor:"Cursor"}});function yM(e){if(!e||typeof e!="object")return!1;let t=e;return!(typeof t.type!="string"||!w7.has(t.type)||t.type==="text"&&(typeof t.text!="string"||!t.text.trim()))}function hM(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:dl}]}:null;if(!Array.isArray(t.content)||t.content.length===0)return null;let r=t.content[t.content.length-1];return yM(r)?{...t,content:[...t.content.slice(0,-1),{...r,cache_control:dl}]}:null}function S7(e){return Array.isArray(e)&&e.length>0&&e.every(t=>!!t&&typeof t=="object"&&t.type==="tool_result")}function _7(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!(!r||typeof r!="object"||r.role!=="user")&&!S7(r.content))return t}return-1}function Zk(e){return JSON.stringify(e??null).includes('"cache_control"')}function kM(e){if(Zk(e.system)||Zk(e.tools)||Zk(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:dl},...t.slice(a+1)])}let r=e.system;if(typeof r=="string")r.trim()&&(r=[{type:"text",text:r,cache_control:dl}]);else if(Array.isArray(r)&&r.length>0){let i=r[r.length-1];yM(i)&&(r=[...r.slice(0,-1),{...i,cache_control:dl}])}let n=[...e.messages],o=-1;for(let i=n.length-1;i>=0;i-=1){let a=hM(n[i]);if(a){n[i]=a,o=i;break}}let s=_7(n)-1;if(s>=0&&s<o)for(let i=s;i>=0;i-=1){let a=hM(n[i]);if(a){n[i]=a;break}}return{system:r,tools:t,messages:n}}var dl,w7,bM=p(()=>{"use strict";dl={type:"ephemeral"},w7=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 vM(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 C7(){return{blocks:[],stopReason:null,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}}function E7(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 A7(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*P7(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 I7(e=process.env){return(e.ANTHROPIC_BASE_URL?.trim()||"https://api.anthropic.com").replace(/\/$/,"")}async function RM(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:x7},{type:"text",text:n.system}]);let i=kM({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(`${I7()}/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=C7();for await(let c of P7(a.body)){let u=E7(l,c);u&&e.onDelta(u)}return A7(l)}var x7,eb=p(()=>{"use strict";bM();x7="You are Claude Code, Anthropic's official CLI for Claude."});function Yt(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 T7(e){let t=e.replace(/\s+/g," ").trim();return t.length>wM?`${t.slice(0,wM-1)}\u2026`:t}function _M(e,t=O7){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.",`- ${bp}`,"","Tools:"].join(`
|
|
143
207
|
`),n=[],o=r.length,s=[];for(let c of e){let u=`
|
|
144
|
-
- ${c.name}: ${
|
|
208
|
+
- ${c.name}: ${T7(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 M7(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}=M7(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:(D7.exec(n.body)?.[1]?.trim()??"")||null}),i+=e.slice(a),{text:i.trim(),calls:o,rejected:s,cut:l}}function SM(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:SM(t,i),name:s.name,input:s.input})}),e.cut&&n.push({type:"tool_use",id:SM(t,"cut"),name:N7,input:{tool:e.cut.name,reason:"unterminated_fence"}}),{content:n,stop_reason:e.calls.length>0||e.cut?"tool_use":"end_turn"}}function L7(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,bp,O7,wM,N7,D7,qt,Ys=p(()=>{"use strict";cn="```kynver-tool",bp="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.";O7=64e3,wM=600;N7="kynver_tool_call_cut",D7=/"name"\s*:\s*"([^"\\]*)"/;qt=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=L7(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 xM(e){return`[\u2026 ${e} more characters of the user's message omitted to fit this prompt \u2026]`}function B7(e){return`[\u2026 ${e} more characters of Kynver's turn context omitted to fit this prompt \u2026]`}function W7(e,t){if(e.length<=t)return e;let r=e.indexOf(CM),n=r>=0?e.indexOf(zs,r):-1;if(r<0||n<0)return Xs(e,t,xM);let o=e.slice(0,r),s=e.slice(r,n+zs.length),i=Xs(e.slice(n+zs.length),Math.max(0,t-o.length),xM),a=t-o.length-i.length,l=zs.length+1,c=s.slice(0,s.length-zs.length),u=s.length<=a?s:`${Xs(c,Math.max(CM.length,a-l-100),B7)}
|
|
212
|
+
${zs}`;return`${o}${u}${i}`}function tb(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 U7(e){return`[\u2026 ${e} more characters omitted to fit this prompt \u2026]`}function Xs(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 AM(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=W7(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?tb:U7;r[i].kept=Xs(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 EM,CM,zs,PM=p(()=>{"use strict";EM="[System reminder]";CM="<turn_context>",zs="</turn_context>"});function $7(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 H7(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 j7(e){let t=H7(e);return t.length>0&&!t.startsWith(EM)}function V7(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&t.type==="tool_result")}function rb(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=$7(o.content??o.text),i=t===void 0?s:Xs(s,t,tb);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 q7(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[TM,G7,"Never use runtime_command run dispatch and never implement coding tasks inline in the chat workspace when a worker was requested or dispatch failed.",NM,bp].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[TM,`${n} Do the work there yourself and say what you ran and what you changed.`,`Local commands are only for this computer. ${bp}`,J7,"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).",NM].join(" ")}function Y7(e){return e==="assistant"?"Assistant":e==="system"?"System":"User"}function DM(e){return rb(e)}function nb(e,t=e.executionMode==="ask"?"ask":"agent",r,n){let o=t==="agent"?r??Yt(e.tools):[],s=_M(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.":q7(n)),i==="off"&&a.push(K7);let c=t==="agent"?vM(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=rb(v.content);if(!k.trim())continue;let b=Y7(v.role);v.role!=="assistant"&&v.role!=="system"&&j7(v.content)&&(d=u.length);let S=v.content;u.push({text:`${b}:
|
|
222
|
+
${k}`,ask:!1,renderShrunk:V7(S)?R=>`${b}:
|
|
223
|
+
${rb(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<=IM)return{head:f,body:m};let g=Math.max(F7,IM-f.length-16),h=AM(u,g-OM.length-2);return{head:f,body:h.dropped?`${OM}
|
|
164
228
|
|
|
165
|
-
${h.body}`:h.body}}function
|
|
229
|
+
${h.body}`:h.body}}function Qs(e,t=e.executionMode==="ask"?"ask":"agent",r,n){let{head:o,body:s}=nb(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 IM,F7,K7,OM,TM,G7,NM,J7,pl=p(()=>{"use strict";eb();Ys();PM();IM=8e4,F7=32e3,K7="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.",OM=`[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.]`;TM="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.",G7="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).",NM="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.",J7="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 z7}from"node:os";function Zs(e,t=z7()){let r=E();return Vo({engine:e,local:{chatComputerAccess:r.chatComputerAccess,chatWorkFolders:r.chatWorkFolders},home:t})}var vp=p(()=>{"use strict";j();_n()});function Ce(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function _e(e){return typeof e=="string"&&e.trim()?e:void 0}function ob(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function sb(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 ib(...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 ab(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 LM(e=Date.now){let t=ab(e);return r=>{let n=Ce(r.item);if(!n)return[];let o=_e(n.id);if(r.type==="item.started")return t.start(o),[];if(r.type!=="item.completed")return[];if(n.type==="command_execution"){let s=_e(n.command)??"",i=ob(n.exit_code),a=sb(s,i,t.elapsed(o),ib(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=>Ce(a)).filter(a=>!!a&&!!_e(a.path)).map(a=>({kind:"file_change",path:_e(a.path),..._e(a.kind)?{change:_e(a.kind)}:{},durationMs:s,ok:i,...i?{}:{reason:"failed"}}))}return[]}}function BM(e=Date.now){let t=ab(e);return r=>{if(r.type!=="tool_call")return[];let n=_e(r.call_id);if(r.subtype==="started")return t.start(n),[];if(r.subtype!=="completed")return[];let o=Ce(r.tool_call);if(!o)return[];let s=t.elapsed(n),i=Ce(o.shellToolCall);if(i){let a=Ce(i.result),l=Ce(a?.success)??Ce(a?.failure),c=_e(Ce(i.args)?.command)??_e(l?.command)??"",u=ob(l?.exitCode)??(a?.failure?1:null),d=ob(l?.executionTime)??s;return[sb(c,u,d,ib(l?.stdout,l?.stderr))]}for(let[a,l]of Object.entries(X7)){let c=Ce(o[a]);if(!c)continue;let u=Ce(c.result),d=_e(Ce(c.args)?.path)??_e(Ce(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 WM(){return e=>{if(e.event!=="step_update")return[];let t=Ce(e.step_update);if(!t||t.step_type!=="tool")return[];let r=_e(t.tool_name);return r?[{kind:"tool",command:r.trim(),ok:!0}]:[]}}function eQ(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let t=e.map(r=>Ce(r)).filter(r=>!!r&&typeof r.text=="string").map(r=>r.text);return t.length?t.join(`
|
|
232
|
+
`):void 0}function MM(e){let t=Ce(e.message)?.content;return Array.isArray(t)?t.map(r=>Ce(r)).filter(r=>!!r):[]}function UM(e=Date.now){let t=ab(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(Z7)?.[1]??1):0,h=sb(_e(i.input.command)??"",g,a,ib(c));return u?{...h,ok:!1,reason:u}:h}let d=l||u?{reason:u??"failed"}:{},f=Q7[i.name],m=_e(i.input.file_path)??_e(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 MM(i)){let c=_e(l.id),u=_e(l.name);l.type!=="tool_use"||!c||!u||r.has(c)||n.has(c)||(r.set(c,{name:u,input:Ce(l.input)??{}}),t.start(c))}return[]}if(i.type!=="user")return[];let a=[];for(let l of MM(i)){let c=_e(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,eQ(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 X7,Q7,Z7,fl=p(()=>{"use strict";X7={writeToolCall:"write",editToolCall:"update",deleteToolCall:"delete"};Q7={Write:"write",Edit:"update",MultiEdit:"update",NotebookEdit:"update"},Z7=/exit code (\d+)/i});function zt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function FM(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 KM(e){let t=zt(e.type);if(!t)return null;if(t==="interactionUpdate"||t==="interaction_update"){let r=zt(e.subtype)??zt(e.updateType),n=zt(e.blockReasonType)??zt(e.blockReason?.type),o=FM(e.approvalReasonTypes)??FM(e.approval?.reasonTypes),s=zt(e.toolCallId)??zt(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=zt(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=zt(e.toolCallId)??zt(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 Rp(e){if(!rQ.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 wp(e){let t=[tQ];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 tQ,rQ,$M=p(()=>{"use strict";tQ="cursor_tool_approval_blocked",rQ=/blockReasonType[=:]\s*(\w+)|userRejected|Shell approval gate|approvalReasonTypes|unapproved_commands/i});function Sp(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 HM=p(()=>{"use strict"});import{spawn as nQ}from"node:child_process";function lb(e){return e==="ask"?"ask":"agent"}function iQ(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 aQ(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 lQ(e){return e.type!=="result"?"":typeof e.result=="string"?e.result:""}function cb(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 ub(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 cQ(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 uQ(e,t){if(sQ.test(e))return`${Ig}: ${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 jM(e){let t=e.env??process.env,r=e.access??Zs("cursor"),n=e.workspaceDir??r.workDir,o=BM(),s=lb(e.payload.executionMode),i=s==="agent"?Yt(e.payload.tools):[],a=new Set(i.map(f=>f.name)),l=Qs(e.payload,s,i,r),c=e.spawnTarget;if(!c){let f=Kn(t),m=na(f);c={executable:m.executable,prefixArgs:m.prefixArgs}}let u=iQ(e.model,n,l,c.prefixArgs,s),d={...Jt(t),CI:"1",NO_COLOR:"1"};return await new Promise((f,m)=>{let g;try{let T=z({cwd:n,detached:!1,shell:!1,stdio:["ignore","pipe","pipe"],env:d});g=nQ(c.executable,u,T)}catch(T){if(T.code==="ENOENT"){m(new Error(`${gu}: failed to spawn \`${c.executable}\`. Install the Cursor Agent CLI and keep \`agent\` on PATH.`));return}m(T instanceof Error?T:new Error(String(T)));return}let h=!1,y=new qt,v="",k=T=>{let x=y.push(T);x&&(v+=x,e.onDelta(x))},b="",_="",S={input_tokens:0,output_tokens:0},R="",w="",L=!1,I=Rp(R),A=null,O=T=>{if(h)return;if(h=!0,clearTimeout(G),e.signal?.removeEventListener("abort",W),T){Sp({requestId:e.requestId,turnId:e.turnId,event:"turn_error",exitCode:A,error:T.message,...I?.toolCallId?{toolCallId:I.toolCallId}:{},...I?.toolName?{toolName:I.toolName}:{},...I?.blockReasonType?{blockReason:I.blockReasonType}:{}}),m(T);return}let x=Rp(R);if(x&&(I=x),I){let ue=new Error(wp(I));Sp({requestId:e.requestId,turnId:e.turnId,event:"turn_approval_blocked",exitCode:A,toolCallId:I.toolCallId,toolName:I.toolName,blockReason:I.blockReasonType,error:ue.message}),m(ue);return}let H=y.end();H&&(v+=H,e.onDelta(H));let N=cb(b,_),D=un(N,a);ub(D.text,v,e.onDelta),D.rejected.length>0&&console.error(JSON.stringify({event:"cursor_tool_call_rejected",names:D.rejected.slice(0,5),advertised:a.size}));let{content:F,stop_reason:Z}=dn(D,e.turnId??"turn");Sp({requestId:e.requestId,turnId:e.turnId,event:"turn_end",exitCode:A,stopReason:Z}),f({content:F,stop_reason:Z,usage:S})},U=()=>Qe(g,"SIGTERM"),W=()=>{U(),O(new Error("cursor_chat_aborted"))},G=setTimeout(()=>{L=!0,U()},e.timeoutMs??oQ);if(g.on("error",T=>{if(T.code==="ENOENT"){O(new Error(`${gu}: failed to spawn \`${c.executable}\`. Install the Cursor Agent CLI and keep \`agent\` on PATH.`));return}O(T)}),e.signal){if(e.signal.aborted){W();return}e.signal.addEventListener("abort",W)}let ee=T=>{let x=T.trim();if(!x)return;let H;try{H=JSON.parse(x)}catch{return}let N=aQ(H,b);N&&(b+=N,k(N));let D=lQ(H);D&&(_=D);let F=cQ(H);if(F&&(S=F),e.onActivity)for(let ue of o(H))e.onActivity(ue);let Z=KM(H);Z&&(I=Z,U(),O(new Error(wp(Z))))};g.stdout?.on("data",T=>{w+=typeof T=="string"?T:T.toString("utf8");let x;for(;(x=w.indexOf(`
|
|
233
|
+
`))!==-1;){let H=w.slice(0,x);w=w.slice(x+1),ee(H)}}),g.stderr?.on("data",T=>{R+=typeof T=="string"?T:T.toString("utf8"),R.length>8e3&&(R=R.slice(-8e3));let x=Rp(R);x&&(I=x,U(),O(new Error(wp(x))))}),g.on("close",T=>{if(A=T,w.trim()&&ee(w),L){O(new Error("cursor_chat_timeout"));return}if(T!==0&&!b&&!_){O(new Error(uQ(R,T)));return}O()})})}var oQ,sQ,_p=p(()=>{"use strict";gs();M();pl();vp();ao();fl();hs();Ys();$M();HM();oQ=24e4,sQ=/not logged in|please run[`\s]+agent login|authentication required|unauthorized|invalid api key/i});import{spawn as dQ}from"node:child_process";function mQ(e){return e==="ask"?"ask":"agent"}function gQ(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 hQ(e,t,r="agent",n=[],o=process.platform,s){return[...n,"exec",...ku(o),"--skip-git-repo-check","--json","--ask-for-approval","never",...gQ(r,s),"--model",e,t]}function yQ(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 kQ(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 bQ(e,t){if(fQ.test(e))return`${Jk}: ${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 VM(e){let t=e.env??process.env,r=e.access??Zs("codex"),n=e.workspaceDir??r.workDir,o=mQ(e.payload.executionMode),s=o==="agent"?Yt(e.payload.tools):[],i=new Set(s.map(f=>f.name)),a=Qs(e.payload,o,s,r),l=LM(),c=e.spawnTarget??{executable:t.KYNVER_CODEX_BIN?.trim()||t.CODEX_BIN?.trim()||xr(),prefixArgs:[]},u=hQ(e.model,a,o,c.prefixArgs,process.platform,r),d={...Jt(t),CI:"1",NO_COLOR:"1"};return await new Promise((f,m)=>{let g;try{let U=z({cwd:n,detached:!1,shell:!1,stdio:["ignore","pipe","pipe"],env:d}),[W,G]=ie(c.executable,u);g=dQ(W,G,U)}catch(U){if(U.code==="ENOENT"){m(new Error(`${dp}: failed to spawn \`${c.executable}\`. Install the Codex CLI and keep \`codex\` on PATH.`));return}m(U instanceof Error?U:new Error(String(U)));return}let h=!1,y=new qt,v=U=>{let W=y.push(U);W&&e.onDelta(W)},k="",b={input_tokens:0,output_tokens:0},_="",S="",R=!1,w=U=>{if(h)return;if(h=!0,clearTimeout(A),e.signal?.removeEventListener("abort",I),U){m(U);return}let W=y.end();W&&e.onDelta(W);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=()=>Qe(g,"SIGTERM"),I=()=>{L(),w(new Error("codex_chat_aborted"))},A=setTimeout(()=>{R=!0,L()},e.timeoutMs??pQ);if(g.on("error",U=>{if(U.code==="ENOENT"){w(new Error(`${dp}: failed to spawn \`${c.executable}\`. Install the Codex CLI and keep \`codex\` on PATH.`));return}w(U)}),e.signal){if(e.signal.aborted){I();return}e.signal.addEventListener("abort",I)}let O=U=>{let W=U.trim();if(!W)return;let G;try{G=JSON.parse(W)}catch{return}let ee=yQ(G,k);ee&&(k+=ee,v(ee));let T=kQ(G);if(T&&(b=T),e.onActivity)for(let x of l(G))e.onActivity(x)};g.stdout?.on("data",U=>{S+=typeof U=="string"?U:U.toString("utf8");let W;for(;(W=S.indexOf(`
|
|
234
|
+
`))!==-1;){let G=S.slice(0,W);S=S.slice(W+1),O(G)}}),g.stderr?.on("data",U=>{_+=typeof U=="string"?U:U.toString("utf8"),_.length>8e3&&(_=_.slice(-8e3))}),g.on("close",U=>{if(S.trim()&&O(S),R){w(new Error("codex_chat_timeout"));return}if(U!==0&&!k){w(new Error(bQ(_,U)));return}w()})})}var pQ,fQ,GM=p(()=>{"use strict";jn();Wg();M();Je();pl();vp();fl();fp();ao();Ys();pQ=24e4,fQ=/not logged in|please run[`\s]+codex login|authentication required|unauthorized|invalid api key|401\b/i});import{spawn as vQ}from"node:child_process";function wQ(e,t,r="agent",n=[]){return[...n,...Cu({executionMode:r==="ask"?"read_only":"write",prompt:t},e)]}function SQ(e,t){if(JM.test(e))return`${gp}: ${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??Zs("antigravity"),n=e.workspaceDir??r.workDir,o=WM(),s=lb(e.payload.executionMode),i=s==="agent"?Yt(e.payload.tools):[],a=new Set(i.map(f=>f.name)),l=Qs(e.payload,s,i,r),c=e.spawnTarget??{executable:gt(t),prefixArgs:[]},u=wQ(e.model,l,s,c.prefixArgs),d={...Jt(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}),[G,ee]=ie(c.executable,u);g=vQ(G,ee,W)}catch(W){if(W.code==="ENOENT"){m(new Error(`${mp}: failed to spawn \`${c.executable}\`. Install Google Antigravity and keep \`agy\` on PATH.`));return}m(W instanceof Error?W:new Error(String(W)));return}let h=!1,y=new qt,v=W=>{let G=y.push(W);G&&e.onDelta(G)},k="",b="",_={input_tokens:0,output_tokens:0},S="",R="",w=!1,L=W=>{if(h)return;if(h=!0,clearTimeout(O),e.signal?.removeEventListener("abort",A),W){m(W);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 ee=y.end();ee&&e.onDelta(ee);let T=un(G,a);f({...dn(T,e.turnId??"turn"),usage:_})},I=()=>Qe(g,"SIGTERM"),A=()=>{I(),L(new Error("antigravity_chat_aborted"))},O=setTimeout(()=>{w=!0,I()},e.timeoutMs??RQ);if(g.on("error",W=>{if(W.code==="ENOENT"){L(new Error(`${mp}: failed to spawn \`${c.executable}\`. Install Google Antigravity and keep \`agy\` on PATH.`));return}L(W)}),e.signal){if(e.signal.aborted){A();return}e.signal.addEventListener("abort",A)}let U=W=>{let G=W.trim();if(!G)return;let ee;try{ee=JSON.parse(G)}catch{return}if(e.onActivity)for(let x of o(ee))e.onActivity(x);let T=ql(ee);if(T&&(T.textDelta&&(k+=T.textDelta,v(T.textDelta)),T.usage&&(_={input_tokens:T.usage.inputTokens??_.input_tokens,output_tokens:T.usage.outputTokens??_.output_tokens}),!!T.terminal)){if(!T.terminal.ok){let x=T.terminal.error??"antigravity cli result error";if(I(),JM.test(x)){L(new Error(`${gp}: ${x.slice(0,240)}`));return}L(new Error(`antigravity_chat_failed: ${x.slice(0,240)}`));return}b=T.terminal.finalResult??""}};g.stdout?.on("data",W=>{R+=typeof W=="string"?W:W.toString("utf8");let G;for(;(G=R.indexOf(`
|
|
235
|
+
`))!==-1;){let ee=R.slice(0,G);R=R.slice(G+1),U(ee)}}),g.stderr?.on("data",W=>{S+=typeof W=="string"?W:W.toString("utf8"),S.length>8e3&&(S=S.slice(-8e3))}),g.on("close",W=>{if(R.trim()&&U(R),w){L(new Error("antigravity_chat_timeout"));return}if(!h){if(W!==0&&!k&&!b){L(new Error(SQ(S,W)));return}L()}})})}var RQ,JM,YM=p(()=>{"use strict";Jn();Af();M();Je();yp();pl();vp();ao();fl();_p();Ys();RQ=24e4,JM=/authentication required|not logged in|you are not logged|not authenticated/i});function _Q(){return{text:"",toolCalls:[],finishReason:null,promptTokens:0,completionTokens:0}}function xQ(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 CQ(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 EQ(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 AQ(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
236
|
+
`):""}function PQ(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:AQ(i.content)}),o.push(...EQ(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 IQ(e,t){let r=[];e.trim()&&r.push({role:"system",content:e});for(let n of t)r.push(...PQ(n??{}));return r}function OQ(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*TQ(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 zM(e){let{creds:t,model:r,payload:n}=e,o=Array.isArray(n.tools)?OQ(n.tools):[],s={model:r,messages:IQ(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=_Q();for await(let l of TQ(i.body)){let c=xQ(a,l);c&&e.onDelta(c)}return CQ(a)}var XM=p(()=>{"use strict"});function ho(e){let t=Xd(e.provider,e.config,e.env??process.env),r=e.boxId?bc(e.payloadAccess,e.boxId):null,n=Vo({engine:t,local:{chatComputerAccess:e.config.chatComputerAccess,chatWorkFolders:e.config.chatWorkFolders},website:r,home:e.home});return{engine:t,access:n}}var xp=p(()=>{"use strict";Xa();_n()});function QM(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.session!="string"||!NQ.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 ZM(e){return Math.max(0,Math.min(48e4,e.timeLeftMs))}var NQ,Cp=p(()=>{"use strict";NQ=/^[A-Za-z0-9_.:-]{1,128}$/});function DQ(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 eL,tL=p(()=>{"use strict";eL=DQ()});function MQ(e,t){if(e.access==="off")throw new Error("claude_code_access_off");return e.access==="full"?["--permission-mode","bypassPermissions",...Ak()]:["--permission-mode","acceptEdits",`--allowedTools=${(t?.shell==="disabled"?rL.filter(n=>n!=="Bash"):[...rL]).join(",")}`,...Ak(),...t?["--settings",t.settingsFile]:[],...e.access==="folders"?e.extraFolders.flatMap(n=>["--add-dir",n]):[]]}function db(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]:[],...MQ(e.access,e.sandbox),"--",e.prompt]}var rL,nL=p(()=>{"use strict";ao();rL=["Bash","WebFetch","WebSearch"]});import{readdir as LQ}from"node:fs/promises";import pb from"node:path";function fb(e){let t=e.map(r=>r.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*"));return new RegExp(`^(?:${t.join("|")})$`,"i")}async function sL(e,t,r={}){let n=r.now??Date.now,o=n(),s=r.maxEntries??BQ,i=r.maxMs??WQ,a=r.maxResults??UQ,l=fb(t),c=new Set,u=[...new Set(e.map(g=>pb.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+=oL){if(m()){f=!0;break}let y=u.slice(h,h+oL),v=await Promise.all(y.map(k=>LQ(k,{withFileTypes:!0}).then(b=>({dir:k,entries:b}),b=>(FQ.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=pb.join(k,_.name);l.test(_.name)?c.add(KQ(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 KQ(e){return e.split(pb.sep).join("/")}var BQ,WQ,UQ,oL,FQ,mb=p(()=>{"use strict";BQ=25e4,WQ=15e3,UQ=2e3,oL=64,FQ=new Set(["ENOENT","EACCES","EPERM","ENOTDIR"])});import{closeSync as $Q,existsSync as HQ,fstatSync as jQ,openSync as VQ,readSync as GQ}from"node:fs";function aL(){return{lastSuccessAt:null,lastSuccessKind:null,steps24h:0,failures24h:{}}}function zQ(e,t){let r=aL();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>YQ)&&(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 XQ(e){if(!HQ(e))return[];let t=VQ(e,"r");try{let r=jQ(t).size,n=Math.min(r,JQ),o=Buffer.alloc(n);return GQ(t,o,0,n,r-n),o.toString("utf8").split(`
|
|
239
|
+
`).filter(Boolean)}finally{$Q(t)}}function Ep(e=Nk(),t=Date.now()){let r=iL.get(e);if(r&&t-r.at<qQ)return r.summary;let n;try{n=zQ(XQ(e),t)}catch{n=aL()}return iL.set(e,{at:t,summary:n}),n}var JQ,qQ,YQ,iL,gb=p(()=>{"use strict";ep();JQ=512*1024,qQ=3e4,YQ=1440*60*1e3;iL=new Map});import{appendFileSync as QQ,mkdirSync as ZQ}from"node:fs";import{homedir as eZ}from"node:os";import hb from"node:path";function lL(e=eZ()){return hb.join(e,tZ)}function cL(e){let r=(e instanceof Error?e.message:String(e)).split(":")[0].trim();return/^[a-z_]{1,40}$/.test(r)?r:"other"}function uL(e,t=lL()){try{ZQ(hb.dirname(t),{recursive:!0}),QQ(t,`${JSON.stringify({kind:"step",...e})}
|
|
240
|
+
`,{encoding:"utf8",mode:384})}catch{}}function dL(e=lL()){return Ep(e)}var tZ,yb=p(()=>{"use strict";gb();tZ=hb.join(".kynver","logs","chat-claude-code-steps.jsonl")});import{spawn as rZ}from"node:child_process";import{mkdirSync as nZ,mkdtempSync as oZ,rmSync as sZ,writeFileSync as Ap}from"node:fs";import{tmpdir as iZ}from"node:os";import yo from"node:path";function hZ(){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 kZ(){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 ${yZ} ]; 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 bZ(e){let t=yo.join(e,"net");nZ(t,{recursive:!0,mode:448});for(let[n,o]of Object.entries(hZ()))Ap(yo.join(t,n),o,{encoding:"utf8",mode:420});let r=yo.join(t,"bridge-wait.sh");return Ap(r,kZ(),{encoding:"utf8",mode:420}),{CURL_HOME:t,WGETRC:yo.join(t,".wgetrc"),BASH_ENV:r}}function bb(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 vZ(e){if(!bb(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 RZ(e){if(!bb(e))return!1;let t=e.event;return t.type==="content_block_start"&&t.content_block?.type==="text"}function wZ(e){if(!bb(e))return"";let t=e.event;return t.type!=="message_delta"?"":typeof t.delta?.stop_reason=="string"?t.delta.stop_reason:""}function SZ(e,t){let r=typeof t=="number"&&Number.isFinite(t)?Math.floor(t):0;if(r<=0)return e;let n=Number(e[fL]);return Number.isFinite(n)&&n>=r?e:{...e,[fL]:String(r)}}function _Z(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 xZ(e){return typeof e.session_id=="string"&&e.session_id.trim()?e.session_id.trim():null}function CZ(e){let t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?DM(r.content).trim():"";return n?`User:
|
|
248
|
+
${n}`:"Continue."}function AZ(e){return e.streamed.trim()||e.exitCode===0&&!e.resultIsError?!1:EZ.test(e.detail)||e.numTurns===0}function PZ(e,t){let r=e.trim().slice(0,240);return cZ.test(e)?`${lZ}: ${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 IZ(e){try{return{port:(await K0(e)).port}}catch(t){return{reason:t?.message??String(t)}}}async function OZ(e){if(e.access.access!=="folder"&&e.access.access!=="folders")return null;let t=e.sandboxRuntime??wk(),r=Sk(),n=t.available&&!r,o=n?await IZ(e.egressProxy):null,s=n?await sL(e.access.folders,$s):null;return s?.truncated&&console.error(JSON.stringify({event:"chat_folder_sensitive_scan_truncated",scanned:s.scanned,found:s.paths.length,durationMs:s.durationMs})),X0({access:e.access,policy:Rk(e.env,e.config),runtime:t,domains:G0(e.env,e.config),startupFailure:r,egress:o,sensitiveFiles:s?.paths??[],sensitiveScanComplete:s?!s.truncated:!1})}async function Pp(e){let t=Date.now(),r=!1,n=null,o=null,s=(i,a)=>(e.onStepLogged??uL)({at:new Date().toISOString(),turnId:e.turnId??"",resumed:r,appVersion:n,durationMs:Date.now()-t,ok:i,...i?{}:{reason:cL(a)}});try{let i=await TZ(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 TZ(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??eL,a=ZM(e.step);if(a<=0)throw new Error("claude_code_no_time_left");let l=Yt(e.payload.tools),c=nb(e.payload,"agent",l,e.access),u=e.spawnTarget?.executable??(s.KYNVER_CLAUDE_BIN?.trim()||s.CLAUDE_BIN?.trim()||"claude"),d=oZ(yo.join(e.tempRoot??iZ(),"kynver-claude-code-")),f=yo.join(d,"kynver-system-prompt.md"),m=yo.join(d,"kynver-claude-code-settings.json"),g=Date.now(),h=new Set(l.map(R=>R.name)),y=()=>OZ({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=()=>{Ap(f,v?`${c.head}
|
|
185
249
|
|
|
186
|
-
${
|
|
250
|
+
${v.note}`:c.head,{encoding:"utf8",mode:384}),v&&Ap(m,JSON.stringify(v.settings,null,2),{encoding:"utf8",mode:384}),k=v?.shell==="sandboxed"?bZ(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 I=await mL({...e,env:s,extraEnv:k,executable:u,sessions:i,limitMs:L,advertisedNames:h,maxTokens:e.payload.maxTokens,args:db({model:e.model,systemPromptFile:f,access:e.access,prompt:CZ(e.payload),resumeSessionId:R,sandbox:_()}),resumed:!0,sandboxed:v?.shell==="sandboxed",onAppVersion:n});if(!I.resumeRefused)return I;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 mL({...e,env:s,extraEnv:k,executable:u,sessions:i,limitMs:w,advertisedNames:h,maxTokens:e.payload.maxTokens,args:db({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&&(Y0(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(kb)||R.error?.message.startsWith(kb))&&a-(Date.now()-g)>gZ&&(console.error(JSON.stringify({event:"claude_code_sandbox_proxy_down_retry",turnId:e.turnId??null})),R=await S()),o(R)}finally{sZ(d,{recursive:!0,force:!0})}}function mL(e){let t=UM();return new Promise(r=>{let n;try{let[x,H]=ie(e.executable,[...e.spawnTarget?.prefixArgs??[],...e.args]),N=z({cwd:e.access.workDir,detached:process.platform!=="win32",shell:!1,stdio:["ignore","pipe","pipe"],env:{...SZ(Z0(e.env,e.access.access),e.maxTokens),...e.extraEnv,NO_COLOR:"1"}});n=rZ(x,H,N)}catch(x){r({error:gL(x,e.executable)});return}let o=!1,s=new qt,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=x=>{let H=s.push(x);H&&(i+=H,e.onDelta(H))},R=(x,H)=>console.error(JSON.stringify({event:x,requestId:e.requestId??null,turnId:e.turnId??null,resumed:e.resumed,access:e.access.access,appVersion:m,...H})),w=x=>{o||(o=!0,clearTimeout(G),A&&k&&clearTimeout(A),e.signal?.removeEventListener("abort",W),r(x))},L=(x="")=>{let H=s.end();H&&(i+=H,e.onDelta(H));let N=cb(a,c?"":l),D=un(N,e.advertisedNames);ub(D.text,i,e.onDelta),x&&e.onDelta(x),D.rejected.length>0&&R("claude_code_tool_call_rejected",{names:D.rejected.slice(0,5)});let F=dn(D,e.turnId??"turn",x),Z=F.stop_reason==="end_turn"&&d==="max_tokens";return(D.cut||Z)&&R("claude_code_reply_cut",{stopReason:d||null,cutTool:D.cut?.name??null,chars:N.length}),{content:F.content,stop_reason:Z?"max_tokens":F.stop_reason,usage:f}},I=x=>{n.pid?ye(n.pid,x):Qe(n,x)},A,O=()=>{I("SIGTERM"),A??=setTimeout(()=>{k||(I("SIGKILL"),setTimeout(()=>{o||T(null)},pL).unref())},pL),A.unref()},U=()=>{if(e.onActivity)for(let x of t.interrupted())e.onActivity(x)},W=()=>{O(),U(),w({error:new Error("claude_code_chat_aborted")})},G=setTimeout(()=>{y=!0,O()},e.limitMs);if(n.on("error",x=>w({error:gL(x,e.executable)})),e.signal){if(e.signal.aborted){W();return}e.signal.addEventListener("abort",W)}let ee=x=>{let H=x.trim();if(!H)return;let N;try{N=JSON.parse(H)}catch{return}let D=xZ(N);D&&e.sessions.remember(e.step.session,D),N.type==="system"&&typeof N.claude_code_version=="string"&&(m=N.claude_code_version,e.onAppVersion(m)),RZ(N)&&a&&!a.endsWith(`
|
|
187
251
|
`)&&(a+=`
|
|
188
252
|
|
|
189
|
-
`,
|
|
253
|
+
`,S(`
|
|
190
254
|
|
|
191
|
-
`));let F=
|
|
192
|
-
`).slice(0,1e3)),
|
|
193
|
-
`))!==-1;){let
|
|
194
|
-
${
|
|
195
|
-
${g}`,
|
|
196
|
-
`):"";if(
|
|
255
|
+
`));let F=vZ(N);F&&(a+=F,S(F));let Z=wZ(N);if(Z&&(d=Z),N.type==="result"&&(typeof N.result=="string"&&(l=N.result),c=N.is_error===!0,typeof N.num_turns=="number"&&(u=N.num_turns),Array.isArray(N.errors)&&(v=N.errors.filter(ue=>typeof ue=="string").join(`
|
|
256
|
+
`).slice(0,1e3)),f=_Z(N)??f),e.onActivity)for(let ue of t(N))e.onActivity(ue);e.sandboxed&&!_&&N.type==="user"&&NZ(N)&&(b+=1,R("claude_code_sandbox_proxy_down",{hits:b}),b>=mZ&&(_=!0,O()))};n.stdout?.on("data",x=>{h+=typeof x=="string"?x:x.toString("utf8");let H;for(;(H=h.indexOf(`
|
|
257
|
+
`))!==-1;){let N=h.slice(0,H);h=h.slice(H+1),ee(N)}}),n.stderr?.on("data",x=>{g+=typeof x=="string"?x:x.toString("utf8"),g.length>8e3&&(g=g.slice(-8e3))});let T=x=>{if(k=!0,o)return;if(h.trim()&&ee(h),h="",U(),_){let F=`${kb}: ${pZ}`;w(a.trim()?{message:L(fZ),failure:F}:{error:new Error(F)});return}if(y){R("claude_code_step_timeout",{limitMs:e.limitMs}),w(a.trim()?{message:L(dZ),failure:"claude_code_step_timeout"}:{error:new Error("claude_code_step_timeout")});return}let H=`${l}
|
|
258
|
+
${v}
|
|
259
|
+
${g}`,N=x!==0||c;if(e.sandboxed&&z0({exitCode:x,streamed:a,numTurns:u,detail:H})){w({sandboxUnavailable:H.trim().slice(0,240)||"sandbox failed to start"});return}if(e.resumed&&AZ({exitCode:x,resultIsError:c,numTurns:u,streamed:a,detail:H})){R("claude_code_resume_refused",{exitCode:x}),w({resumeRefused:!0});return}if(N){let F=PZ(H,x);R("claude_code_turn_error",{exitCode:x,error:F,partial:!!a.trim()}),w(a.trim()?{message:L(uZ),failure:F}:{error:new Error(F)});return}let D=L();R("claude_code_turn_end",{exitCode:x,stopReason:D.stop_reason}),w({message:D})};n.on("close",T)})}function NZ(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(J0(o))return!0}return!1}function gL(e,t){return e?.code==="ENOENT"?new Error(`${aZ}: failed to spawn \`${t}\`. Install Claude Code and keep \`claude\` on PATH.`):e instanceof Error?e:new Error(String(e))}var aZ,lZ,cZ,uZ,pL,dZ,kb,pZ,fZ,mZ,gZ,yZ,fL,EZ,vb=p(()=>{"use strict";M();Je();fl();Cp();tL();nL();ao();qd();mb();bk();yb();pl();_p();Ys();aZ="claude_code_unavailable",lZ="claude_code_not_logged_in",cZ=/not logged in|please run \/login|invalid api key|authentication|unauthorized|401\b/i,uZ=`
|
|
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.)`,pL=5e3,dZ=`
|
|
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.)`,kb="claude_code_sandbox_proxy_down",pZ=`sandbox network proxy not running (localhost:${io} refused inside the folder sandbox)`,fZ=`
|
|
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.)`,mZ=2,gZ=3e4;yZ=60;fL="CLAUDE_CODE_MAX_OUTPUT_TOKENS";EZ=/no conversation found|session .*not found/i});function hL(e){if(e)return e;let t=E();return{chatProvider:t.chatProvider,workerProvider:t.workerProvider}}function Rb(e,t,r=process.env,n){if(e==="cursor"){let o=hu(r);if(!o.ok)throw new Xt(IC(o));return}if(e==="codex"){let o=pp(r);if(!o.ok)throw new Xt(sM(o));return}if(e==="gemini"){let o=r;if(lo(hL(n),o)==="antigravity"){let s=hp(o);if(!s.ok)throw new Xt(cM(s));return}if(!al(r))throw new Xt("gemini_api_key_missing");return}if(e==="openai"){if(!ll(r))throw new Xt("openai_api_key_missing");return}if(!sl(r,{oauthOptIn:t}))throw new Xt("no_local_credentials")}async function yL(e){let t=e.env??process.env,{provider:r,model:n,payload:o,onDelta:s,signal:i}=e;Rb(r,e.useClaudeOauth,t,e.config);let a=e.config??E(),l=ho({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 jM({payload:o,model:n,onDelta:s,signal:i,turnId:e.turnId,requestId:e.requestId,...u});if(r==="codex")return VM({payload:o,model:n,onDelta:s,signal:i,turnId:e.turnId,...u});if(r==="gemini"&&lo(hL(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"?al(t):ll(t);return zM({creds:m,model:n,payload:o,onDelta:s,signal:i})}let d=QM(o.claudeCode);if(d&&l.engine==="claude-code"&&l.access.access!=="off")return Pp({payload:o,model:n,onDelta:s,signal:i,step:d,turnId:e.turnId,requestId:e.requestId,env:t,config:a,...u});let f=sl(t,{oauthOptIn:e.useClaudeOauth});return RM({creds:f,model:n,payload:o,onDelta:s,signal:i})}var Xt,wb=p(()=>{"use strict";Gk();eb();hs();_p();fp();GM();yp();YM();zd();qk();XM();j();xp();Cp();vb();Xt=class extends Error{constructor(r){super(r);this.code=r;this.name="ChatCredentialError"}code}});function DZ(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 kL(e){let t=ul(e.payload.requestedModel),r=typeof e.payload.fallbackNoticeShown=="string"?e.payload.fallbackNoticeShown:null,{requestedModel:n,fallbackNoticeShown:o,...s}=e.payload,i=dM({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=mM(i,g),y=gM(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?DZ(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&&(fM(g)||g instanceof Xt&&c.length>1)?pM(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 bL=p(()=>{"use strict";Qk();wb()});function Sb(e){let t=(e??"").replace(/\s+/g," ").trim();if(!t||t.length>120)return null;for(let r of MZ)if(r.re.test(t))return r.kind;return null}function RL(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 Ip(e){return RL(e)?Sb(e.name):null}function wL(e){return e.tag.toLowerCase()==="textarea"?null:RL(e)?Sb(e.name):Sb(e.formSubmitLabel)}function Op(e){if((e.type??"").toLowerCase()==="password"||LZ.test(e.autocomplete??""))return!0;let t=e.tag.toLowerCase();return t!=="input"&&t!=="textarea"?!1:vL.test(e.inputName??"")||vL.test(e.name??"")}function _b(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"}:BZ.test(r.hostname)?{ok:!1,reason:"local and private-network addresses are refused"}:{ok:!0,url:r.toString()}}function SL(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 _L(e){if(!e)return"";try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return""}}var MZ,LZ,vL,BZ,xb=p(()=>{"use strict";MZ=[{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}];LZ=/\b(current-password|new-password|one-time-code|cc-number|cc-csc|cc-exp|cc-exp-month|cc-exp-year)\b/i,vL=/(passw|passcode|pwd|\bpin\b|otp|one[-_ ]?time|2fa|mfa|verification[-_ ]?code|security[-_ ]?code|cvv|cvc|card[-_ ]?number|ccnum|ssn|social[-_ ]?security)/i;BZ=/^(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 xL(e){return UZ.includes(e)}function CL(e){return typeof e=="string"&&WZ.includes(e)}var WZ,UZ,EL,AL,Cb,PL,Eb,IL,OL,Tp,TL,NL,DL,Ab,ei=p(()=>{"use strict";WZ=["open","snapshot","click","type","select","press","scroll","screenshot","wait","tabs","close","list_logins","fill_login","save_login","request_code"],UZ=["list_logins","fill_login","save_login","request_code"];EL=12e3,AL=200,Cb=16e3,PL=95e4,Eb=4e3,IL=3e4,OL=25e3,Tp=3e4,TL=10*6e4,NL=5*6e4,DL=120,Ab=8});function FZ(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 KZ(e){let t=Op(e),r=[`[${e.ref}] ${FZ(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)"):Ip(e)&&r.push("(needs the user's approval to press)"),r.join(" ")}function ML(e,t={}){let r=t.maxChars??Cb,n=`Page: ${e.title||"(untitled)"} \u2014 ${e.url}`,o=e.elements.map(KZ),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 Np(e,t=Cb){return e.length>t?`${e.slice(0,t-14)}
|
|
278
|
+
\u2026[truncated]`:e}var Pb=p(()=>{"use strict";xb();ei()});function LL(){return`(() => {${Ib}
|
|
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($Z)})) {
|
|
220
284
|
if (!__kvVisible(el)) continue;
|
|
221
|
-
if (elements.length >= ${
|
|
285
|
+
if (elements.length >= ${AL}) { 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, ${EL}) : "";
|
|
229
293
|
return { url: location.href, title: document.title, text, elements, truncatedElements };
|
|
230
|
-
})()`}function
|
|
294
|
+
})()`}function BL(e){return`(() => {${Ib}
|
|
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 WL(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 UL(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 FL(){return`(() => {${Ib}
|
|
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 KL(e){return`(() => { window.scrollBy(0, ${Math.trunc(e)}); return { y: Math.round(window.scrollY), max: Math.round(document.documentElement.scrollHeight - window.innerHeight) }; })()`}function $L(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 Ib,$Z,HL=p(()=>{"use strict";ei();Ib=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
|
+
`,$Z='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 bo(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 HZ(e,t){return bo(e.session.host.conn,t,LL())}async function Qt(e,t,r){let n=await HZ(e,t),o=ML(n);return{ok:!0,text:r?Np(`${r}
|
|
337
401
|
|
|
338
|
-
${o}`):o,url:n.url,title:n.title}}function
|
|
402
|
+
${o}`):o,url:n.url,title:n.title}}function Dp(e){let t=typeof e.ref=="string"?e.ref.trim():"";return/^e\d{1,6}$/.test(t)?t:null}function JL(e,t,r,n,o){let s=SL([_L(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 ml(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??VL)(r)])}async function qL(e){let t=_b(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,OL).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 Qt(e,n,a?void 0:"The page is still loading; this is what has rendered so far.")}async function Ob(e,t,r){return bo(e.session.host.conn,t,BL(r))}async function jZ(e){let t=Dp(e.args);if(!t)return ko(t);let r=await e.manager.activeTab(e.session),n=await Ob(e,r,t);if(!n)return ko(t);if(n.facts.disabled)return{ok:!1,code:"failed",text:`[${t}] is disabled.`};let o=Ip(n.facts);if(o){let a=JL(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 ml(e,r,1200),Qt(e,r,`Clicked [${t}] ${JSON.stringify(n.facts.name)}.`)}async function Mp(e,t,r){let n=GL[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 Lp(e,t){let r=await bo(e.session.host.conn,t,FL());if(!r.facts)return null;let n=wL(r.facts);if(!n)return null;let o=r.facts.formSubmitLabel??r.facts.name;return JL(e,"press",o,n,r.url)}async function VZ(e){let t=Dp(e.args);if(!t)return ko(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>Eb)return{ok:!1,code:"invalid_request",text:`text is limited to ${Eb} characters.`};let n=await e.manager.activeTab(e.session),o=await Ob(e,n,t);if(!o)return ko(t);if(Op(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 bo(s,n,WL(t,e.args.clear!==!1)))return ko(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 Lp(e,n);return l?{...l,text:`${a} ${l.text}`}:(await Mp(e,n,"Enter"),await ml(e,n,1500),Qt(e,n,`${a} Pressed Enter.`))}return{ok:!0,text:a}}async function GZ(e){let t=Dp(e.args);if(!t)return ko(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 bo(e.session.host.conn,n,UL(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 JZ(e){let t=typeof e.args.key=="string"?e.args.key.trim():"",r=jL.find(o=>o.toLowerCase()===t.toLowerCase());if(!r)return{ok:!1,code:"invalid_request",text:`key must be one of: ${jL.join(", ")}.`};let n=await e.manager.activeTab(e.session);if(r==="Enter"){let o=await Lp(e,n);if(o)return o}return await Mp(e,n,r),await ml(e,n,r==="Enter"?1500:300),Qt(e,n,`Pressed ${r}.`)}async function qZ(e){let t=await e.manager.activeTab(e.session),r=Dp(e.args);if(r)return await Ob(e,t,r)?{ok:!0,text:`Scrolled [${r}] into view.`}:ko(r);let n=e.args.direction==="up"?-1:1,o=Math.min(10,Math.max(1,Number(e.args.pages)||1)),s=await bo(e.session.host.conn,t,KL(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 YZ(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<=PL)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 zZ(e){let t=await e.manager.activeTab(e.session),r=e.sleep??VL,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(Tp,Math.max(0,Number(e.args.ms)||0));if(!n&&!o){let l=s||2e3;return await r(l),Qt(e,t,`Waited ${Math.round(l/100)/10}s.`)}let i=s||1e4,a=Date.now();for(;;){let l=await bo(e.session.host.conn,t,$L(n,o));if(l==="bad_selector")return{ok:!1,code:"invalid_request",text:"That CSS selector is not valid."};if(l===!0)return Qt(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 XZ(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=_b(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(()=>{}),Qt(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 YL(e,t){switch(e){case"open":return qL(t);case"snapshot":return Qt(t,await t.manager.activeTab(t.session));case"click":return jZ(t);case"type":return VZ(t);case"select":return GZ(t);case"press":return JZ(t);case"scroll":return qZ(t);case"screenshot":return YZ(t);case"wait":return zZ(t);case"tabs":return XZ(t);case"close":return await t.manager.close(t.session.conversationId),{ok:!0,text:"Closed the browser for this conversation."}}}var VL,GL,jL,ko,Tb=p(()=>{"use strict";xb();Pb();HL();ei();VL=e=>new Promise(t=>setTimeout(t,e)),GL={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:" "}},jL=Object.keys(GL);ko=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 Nb,Db,Mb,zL,XL=p(()=>{"use strict";Nb=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
|
+
`,Db=`function (expectedOrigin, refs) {${Nb}
|
|
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
|
+
}`,Mb=`function (expectedOrigin, refs, values) {${Nb}
|
|
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
|
+
}`,zL=`function (expectedOrigin, refs) {${Nb}
|
|
430
494
|
const g = __guard(expectedOrigin);
|
|
431
495
|
if (g) return { error: g, origin: location.origin };
|
|
432
496
|
const f = __find(refs);
|
|
@@ -436,22 +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 QZ(e){let t=typeof e.handle=="string"?e.handle.trim():"";return/^lg_[a-z0-9]{6,20}$/.test(t)?t:null}function Bb(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 ZL(e){return`${JSON.stringify(e.label)} (${e.username}) for ${e.origin}`}function Wp(e){return e.siteLogins??At()}async function Bp(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 gl(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 ae(e,t,r={}){return{ok:!1,code:e,text:t,...r}}function Wb(e,t,r=At()){let n=t?.trim();if(!n)return ae("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:QL};let s;try{s=o.list()}catch(c){return ae("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. ${Lb}`;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 eQ(e,t){let r=mp(e),n=r.audit(t),o=Z9(e.args);if(!o)return se("invalid_request",'A saved-login handle like "lg_7k2m9q4x1c" from browser_list_logins is required.');let s=r.store(t);if(!s.exists())return se("vault_missing",RM);let i=s.get(o);if(!i)return se("login_not_found","No saved login with that handle. Call browser_list_logins.");let a=await e.manager.activeTab(e.session),l=await fp(e,a),c=_i(l),u={conversationId:e.session.conversationId,handle:o,label:i.label,username:i.username,origin:i.origin,pageOrigin:c},d=(R,M)=>({event:"fill",ok:R,origin:i.origin,label:i.label,code:M});if(!l||!Hf(i.origin,l))return n.record({event:"fill",ok:!1,code:"origin_mismatch",...u}),se("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}),se("vault_locked",`Saved logins are locked. ${Yk}`,{loginActivity:d(!1,"vault_locked")});let f=zk(e.args),g;try{g=await el(e,a,Jk,[i.origin,f])}catch(R){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),se("failed",`Couldn't fill: ${R.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}),se("origin_mismatch",`Refused: the page is no longer ${i.origin}.`,{loginActivity:d(!1,"origin_mismatch")});if(g?.error==="bad_ref")return se("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(R){let M=R instanceof q?R.code:"failed";return n.record({event:"fill",ok:!1,code:M,...u}),se("failed",R instanceof q?`Couldn't use this saved login: ${R.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 R=vc(h.totp);R&&(kw(R)<3&&await(e.sleep??(M=>new Promise(A=>setTimeout(A,M))))(3100),y.code=yw(R))}if(h.password="",!y.username&&!y.password&&!y.code){n.record({event:"fill",ok:!1,code:"field_not_found",...u});let R=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.":"",M=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 se("field_not_found",`No sign-in field to fill on this page.${M}${R} Take a browser_snapshot to see where you are.`,{loginActivity:d(!1,"field_not_found")})}let b;try{b=await el(e,a,qk,[i.origin,f,y])}catch(R){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),se("failed",`Couldn't fill: ${R.message}. Take a browser_snapshot and try again.`)}finally{y.password="",y.code=""}if(b?.error){let R=b.error==="origin"||b.error==="frame"?"origin_mismatch":"failed";return n.record({event:"fill",ok:!1,code:R,...u,pageOrigin:b.origin??c}),se(R==="origin_mismatch"?"origin_mismatch":"failed",`Refused: the page changed to ${b.origin??"another address"} before the fill.`,{loginActivity:d(!1,R)})}let k=b?.filled??[];s.touch(o),n.record({event:"fill",ok:!0,code:null,...u,fields:k});let v=k.map(R=>R==="code"?"authenticator code":R).join(" + "),S=g.code&&!i.hasTotp&&!k.includes("code"),_=`Filled the ${v} for ${wM(i)}.`+(S?" The page also wants a one-time code: use browser_request_code so the user types it on their computer.":""),w={loginActivity:d(!0,null)};if(e.args.submit===!0){let R=await pp(e,a);return R?{...R,...w,text:`${_} ${R.text}`}:(await dp(e,a,"Enter"),await Za(e,a,2e3),{...await Yt(e,a,`${_} Pressed Enter.`),...w})}return{ok:!0,text:`${_} Continue with browser_click on the sign-in button (or submit:true next time).`,...w}}async function tQ(e,t){let r=mp(e),n=r.store(t);if(!n.exists())return se("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 se("vault_locked",`Saved logins are locked. ${Yk}`);let s=await e.manager.activeTab(e.session),i=await fp(e,s),a=_i(i);if(!a||!a.startsWith("https://"))return se("url_refused","Only logins typed on an https:// site can be saved.");let l;try{l=await el(e,s,bM,[a,zk(e.args)])}catch(f){return se("failed",`Couldn't read the sign-in form: ${f.message}.`)}if(l?.error)return se("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 se("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 se("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 ${wM(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 se("failed",f instanceof q?`Couldn't save: ${f.message}.`:"Couldn't save this login.")}}async function rQ(e,t){let r=mp(e),n=await e.manager.activeTab(e.session),o=await fp(e,n),s=_i(o);if(!s)return se("url_refused","Open the site's verification page first.");let i=zk(e.args),a;try{a=await el(e,n,Jk,[s,i])}catch(d){return se("failed",`Couldn't read the page: ${d.message}.`)}if(a?.error==="bad_ref")return se("invalid_request","codeRef must point at a text field on this page.");if(a?.error||!a?.code)return se("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 fp(e,n);if(!Hf(s,m))return{ok:!1,text:`The page is no longer ${s}, so the code was not typed.`};try{let f=await el(e,n,qk,[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 SM(e,t){let r=t.agentOsId?.trim();if(!r)return se("invalid_request","Saved logins need the workspace this chat belongs to; update the Kynver runtime.");switch(e){case"list_logins":return Xk(t.args,r,mp(t));case"fill_login":return eQ(t,r);case"save_login":return tQ(t,r);case"request_code":return rQ(t,r)}}var Yk,RM,_M=p(()=>{"use strict";Vk();vM();jf();Ci();wn();Vf();Yk="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.",RM="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 gp,xM=p(()=>{"use strict";Hs();gp=class{constructor(t){this.deps=t;this.now=t.now??Date.now,this.idleMs=t.idleMs??tM}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<rM),t.actionTimes.length>=nM?!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>=Kk)throw new Error(`tab limit reached (${Kk}) \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 zt,nQ,tl,CM=p(()=>{"use strict";zt=class extends Error{constructor(r,n){super(r);this.code=n;this.name="CdpError"}code},nQ=e=>new WebSocket(e),tl=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??nQ)(t);return await new Promise((o,s)=>{let i=setTimeout(()=>s(new zt("CDP connect timed out")),r.timeoutMs??1e4);n.addEventListener("open",()=>{clearTimeout(i),o()}),n.addEventListener("error",()=>{clearTimeout(i),s(new zt("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 zt("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 zt(`${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 zt(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 zt("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 zt("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 zt(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 iQ(){let e=io(),t=e.state==="downloading"?` (${b0(e)})`:"";return`Setting up a browser on your computer \u2014 a one-time download of about ${y0} MB${t}. Tell the user it's being set up, wait about 30 seconds, then try the same step again.`}async function EM(e={}){let t=(e.resolve??(()=>so()))();if(t.executable)return t.executable;if(!(e.autoProvision??I().browserAutoProvision!==!1))throw new Ir("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??io)(),o=(e.now??Date.now)();if(n.state==="failed"&&n.failedAt!==null&&o-n.failedAt<sQ)throw new Ir(`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??Bd)(),i,a=new Promise(l=>{i=setTimeout(()=>l("pending"),e.waitMs??oQ),i.unref?.()});try{let l=await Promise.race([s,a]);if(l==="pending")throw s.catch(()=>{}),new Ir(iQ(),"browser_installing");return l.executable}catch(l){if(l instanceof Ir)throw l;let c=l instanceof Bs?l.message:"Couldn't set up a browser on this computer.";throw new Ir(`${c} The user can run \`kynver browser install\` on that computer to retry, or install Google Chrome.`,"chrome_not_found")}finally{clearTimeout(i)}}var oQ,sQ,Ir,AM=p(()=>{"use strict";K();$a();Ud();oQ=2e4,sQ=6e4,Ir=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserEnsureError"}code}});import{spawn as aQ}from"node:child_process";import{existsSync as STe,mkdirSync as lQ,readFileSync as cQ,rmSync as uQ}from"node:fs";import{homedir as dQ}from"node:os";import PM from"node:path";function fQ(e=process.env){return e.KYNVER_BROWSER_PROFILE_DIR?.trim()||PM.join(dQ(),".kynver","browser-profile")}function IM(e=process.env){return(e.KYNVER_BROWSER_CDP_URL?.trim()||I().browserCdpUrl?.trim()||pQ).replace(/\/$/,"")}async function OM(e,t={}){let r=t.env??process.env,n=t.platform??process.platform,o=t.allowNoSandbox??I().browserAllowNoSandbox!==!1;if((t.asRoot??v0(n))&&o){let a=await Zk(e,r,n,t,!0);if("wsUrl"in a)return Wd("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 Qk(a.stderrTail)}let i=await Zk(e,r,n,t,!1);if("wsUrl"in i)return Wd("on"),i;if(n==="linux"&&o&&nk(i.stderrTail)){let a=await Zk(e,r,n,t,!0);if("wsUrl"in a)return Wd("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 Qk(a.stderrTail)}throw Qk(i.stderrTail)}function Qk(e){let t=Fa(e);return t.length>0?new rl(t):nk(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 Zk(e,t,r,n,o){let s=fQ(t);lQ(s,{recursive:!0});let i=PM.join(s,"DevToolsActivePort");uQ(i,{force:!0});let a=Nd(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??aQ)(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=>cQ(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 TM(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 pQ,rl,NM=p(()=>{"use strict";K();no();Td();$a();ok();pQ="http://127.0.0.1:9222";rl=class extends Error{constructor(r){super(`Chrome is missing system libraries: ${r.join(", ")}`);this.missingLibs=r;this.name="ChromeMissingLibsError"}missingLibs}});async function mQ(e){if(e==="attach"){let n=IM(),o;try{o=await TM(n)}catch{throw new js(`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 tl.connect(o),child:null,mode:e}}let t;try{t=await EM()}catch(n){throw n instanceof Ir?new js(n.message,n.code):n}let r;try{r=await OM(t)}catch(n){throw n instanceof rl?new js(QN(n.missingLibs,n0()),"missing_libs"):n}return{conn:await tl.connect(r.wsUrl),child:r.child,mode:e}}function gQ(){return hp??=new gp({connectHost:mQ}),hp}async function DM(){hp&&await hp.closeAll().catch(()=>{})}function MM(){try{let e=I();e.browserEverEnabled!==!0&&Le({...e,browserEverEnabled:!0})}catch{}}function rn(e,t){return{ok:!1,code:e,text:t}}function hQ(e){if(!e||typeof e!="object")return null;let t=e,r=t.policy;if(t.kind!=="browser"||!YD(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 LM(e,t){let r=hQ(e);if(!r)return rn("invalid_request","Malformed browser request.");if(t.localDisabled)return rn("disabled","The browser is switched off on this computer (local setting browserDisabled).");if(!r.policy.enabled)return rn("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 rn("wrong_box","This request reached a different computer than the one the browser is enabled on.");t.onEnabledTurn?.();let n=t.manager??gQ();if(r.action==="list_logins")return Xk(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 rn("action_cap","Too many browser actions in a short time. Pause and summarize progress for the user.");let s=r.action==="wait"?lp+5e3:ZD,i,a=new Promise(d=>{i=setTimeout(()=>d(rn("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([qD(c)?SM(c,l):kM(c,l),a]).finally(()=>clearTimeout(i));return{...u,text:cp(u.text)}}catch(o){if(o instanceof js)return rn(o.code,o.message);let s=o instanceof Error?o.message:String(o);return rn("failed",`Browser action failed: ${s.slice(0,300)}`)}}var js,hp,eb=p(()=>{"use strict";Vk();_M();$k();xM();CM();K();AM();Td();no();NM();Hs();js=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserSetupError"}code};hp=null});async function BM(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??LM)(t.payload,{boxId:e.boxId,agentOsId:e.agentOsId,localDisabled:I().browserDisabled===!0,onEnabledTurn:MM});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 UM=p(()=>{"use strict";K();eb()});function KM(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 $M(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 FM(e){let t=e?.code;return typeof t=="string"?t:null}function HM(e){if(!e)return!1;if(e instanceof nn)return yQ.has(e.status);let t=FM(e)??FM(e.cause);if(t&&kQ.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 tb(e){return $M(e)?"aborted":HM(e)?"transient":"server"}function jM(e,t){let r=tb(e);if(r==="aborted")return t<=vQ?0:RQ;if(r==="transient"){let n=Math.max(0,Math.min(t-1,WM.length-1));return WM[n]}return bQ}var nn,yQ,kQ,bQ,vQ,RQ,WM,yp,rb=p(()=>{"use strict";nn=class extends Error{status;constructor(t){super(`claim failed: HTTP ${t}`),this.name="ClaimHttpError",this.status=t}},yQ=new Set([502,503,504]),kQ=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","ENETDOWN","UND_ERR_CONNECT_TIMEOUT"]),bQ=5e3,vQ=3,RQ=1e3,WM=[0,1e3,5e3];yp=class{counts={aborted:0,transient:0,server:0,auth:0,recovered:0};streakKind=null;streak=0;onError(t){let r=tb(t);return this.bump(r),{kind:r,consecutive:this.streak,backoffMs:jM(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}}});async function kp(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 nb=p(()=>{"use strict"});function VM(e,t,r={}){let n=r.env??process.env,{engine:o,access:s}=ao({provider:e,config:t,env:n});return{access:s.access,folders:s.folders.map(Ke),source:s.source==="website"?"local":s.source,engine:o,engineVersion:o==="none"?null:(r.version??Ad)(o,n),log:(r.summary??np)(),...o==="claude-code"?{claudeCode:{signedIn:(r.signedIn??Pd)(n),steps:(r.stepSummary??DD)()}}:{}}}var GM=p(()=>{"use strict";rt();La();Ik();tp();Ak()});function bp(e){let t=e.appendLog??(s=>{Ba(s)}),r=e.now??(()=>new Date),n=0,o=(s,i)=>Jy({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 ob=p(()=>{"use strict";Id()});import{readFileSync as wQ,statSync as SQ}from"node:fs";import JM from"node:path";function CQ(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!==_Q||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 po(e,t,r){return{step:{kind:"attach",path:e,ok:!1,reason:t,...r!==void 0?{outputBytes:r}:{}}}}function EQ(e,t,r={}){let n=r.stat??SQ,o=r.read??wQ,s=r.maxBytes??xQ,i=e.rawPath.trim();if(!i||i.includes("\0"))return po(i,"invalid_path");let a=JM.resolve(t.workDir,hl(i));if(t.access==="off")return po(a,"access_off");if(!rc(t,a))return po(a,"outside_folders");let l;try{let c=n(a);if(!c.isFile())return po(a,"not_a_file");l=c.size}catch{return po(a,"not_found")}if(l>s)return po(a,"too_large",l);try{let c=o(a);return{step:{kind:"attach",path:a,outputBytes:c.length,ok:!0},file:{name:JM.basename(a),sizeBytes:c.length,contentBase64:c.toString("base64")}}}catch{return po(a,"read_failed")}}function qM(e,t,r){let n=CQ(e);for(let o of n){let s=EQ(o,t.access);r.attach(s.step,t,{toolUseId:o.toolUseId,...s.file?{file:s.file}:{}})}return n.length}var _Q,xQ,YM=p(()=>{"use strict";mn();rt();_Q="attach_file",xQ=50*1024*1024});function PQ(e){return e>=200&&e<300?"accepted":e===409||e===410?"rejected":e===404||e===405?"unsupported":"unreachable"}function zM(e){return e!=="rejected"}async function XM(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(),AQ);try{let a=await Ps(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 Xn(e,a,l.status),{outcome:PQ(l.status),status:l.status}}catch{}finally{clearTimeout(i)}}return{outcome:"unreachable",status:null}}var AQ,QM=p(()=>{"use strict";hd();AQ=4e3});async function TQ(e,t,r=fetch){let n=new AbortController,o=setTimeout(()=>n.abort(),OQ);try{let s=await Ps(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 Xn(e,s,a.status),a.ok}catch{return!1}finally{clearTimeout(o)}}function ZM(e){let t=e.intervalMs??IQ,r=!1,n=()=>{r||TQ(e.target,e.capabilities,e.fetchImpl).catch(()=>!1)};n();let o=setInterval(n,t);return o.unref?.(),()=>{r=!0,clearInterval(o)}}var IQ,OQ,eL=p(()=>{"use strict";hd();IQ=15e3,OQ=5e3});function DQ(e){return typeof e=="string"&&NQ.includes(e)}function tL(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.kind!=="agent-tab"||!DQ(t.engine)||typeof t.sessionKey!="string"||!UQ.test(t.sessionKey))return null;let r=typeof t.text=="string"?t.text.slice(0,MQ):"",n=[],o=0;if(Array.isArray(t.attachments))for(let s of t.attachments.slice(0,LQ)){if(!s||typeof s!="object")continue;let{name:i,mime:a,contentBase64:l}=s;if(!(typeof i!="string"||typeof l!="string")){if(o+=Math.floor(l.length*3/4),o>BQ)break;n.push({name:i.slice(0,200),mime:typeof a=="string"?a.slice(0,100):"application/octet-stream",contentBase64:l})}}return!r.trim()&&n.length===0?null:{kind:"agent-tab",engine:t.engine,sessionKey:t.sessionKey,text:r,attachments:n,...t.computerAccess!==void 0?{computerAccess:t.computerAccess}:{}}}var NQ,MQ,LQ,BQ,UQ,rL=p(()=>{"use strict";NQ=["hermes","openclaw","claude-code"];MQ=32e3,LQ=5,BQ=20*1024*1024,UQ=/^[A-Za-z0-9_.:-]{8,128}$/});import{existsSync as WQ,mkdirSync as FQ,readFileSync as KQ,renameSync as $Q,writeFileSync as HQ}from"node:fs";import{homedir as jQ}from"node:os";import oL from"node:path";function VQ(e=jQ()){return oL.join(e,".kynver","agent-tab-sessions.json")}function sL(e=VQ(),t=Date.now){let r=()=>{try{if(!WQ(e))return{};let o=JSON.parse(KQ(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>nL&&s.sort((i,a)=>o[i].at-o[a].at).slice(0,s.length-nL).forEach(i=>delete o[i]);try{FQ(oL.dirname(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;HQ(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 ZZ(e,t){let r=Wp(e),n=r.audit(t),o=QZ(e.args);if(!o)return ae("invalid_request",'A saved-login handle like "lg_7k2m9q4x1c" from browser_list_logins is required.');let s=r.store(t);if(!s.exists())return ae("vault_missing",QL);let i=s.get(o);if(!i)return ae("login_not_found","No saved login with that handle. Call browser_list_logins.");let a=await e.manager.activeTab(e.session),l=await Bp(e,a),c=Wi(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||!Sm(i.origin,l))return n.record({event:"fill",ok:!1,code:"origin_mismatch",...u}),ae("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}),ae("vault_locked",`Saved logins are locked. ${Lb}`,{loginActivity:d(!1,"vault_locked")});let m=Bb(e.args),g;try{g=await gl(e,a,Db,[i.origin,m])}catch(w){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),ae("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}),ae("origin_mismatch",`Refused: the page is no longer ${i.origin}.`,{loginActivity:d(!1,"origin_mismatch")});if(g?.error==="bad_ref")return ae("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}),ae("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=Uc(h.totp);w&&(OS(w)<3&&await(e.sleep??(L=>new Promise(I=>setTimeout(I,L))))(3100),y.code=IS(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 ae("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 gl(e,a,Mb,[i.origin,m,y])}catch(w){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),ae("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}),ae(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 ${ZL(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 Lp(e,a);return w?{...w,...R,text:`${S} ${w.text}`}:(await Mp(e,a,"Enter"),await ml(e,a,2e3),{...await Qt(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 eee(e,t){let r=Wp(e),n=r.store(t);if(!n.exists())return ae("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 ae("vault_locked",`Saved logins are locked. ${Lb}`);let s=await e.manager.activeTab(e.session),i=await Bp(e,s),a=Wi(i);if(!a||!a.startsWith("https://"))return ae("url_refused","Only logins typed on an https:// site can be saved.");let l;try{l=await gl(e,s,zL,[a,Bb(e.args)])}catch(m){return ae("failed",`Couldn't read the sign-in form: ${m.message}.`)}if(l?.error)return ae("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 ae("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 ae("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 ${ZL(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 ae("failed",m instanceof J?`Couldn't save: ${m.message}.`:"Couldn't save this login.")}}async function tee(e,t){let r=Wp(e),n=await e.manager.activeTab(e.session),o=await Bp(e,n),s=Wi(o);if(!s)return ae("url_refused","Open the site's verification page first.");let i=Bb(e.args),a;try{a=await gl(e,n,Db,[s,i])}catch(d){return ae("failed",`Couldn't read the page: ${d.message}.`)}if(a?.error==="bad_ref")return ae("invalid_request","codeRef must point at a text field on this page.");if(a?.error||!a?.code)return ae("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 Bp(e,n);if(!Sm(s,f))return{ok:!1,text:`The page is no longer ${s}, so the code was not typed.`};try{let m=await gl(e,n,Mb,[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 eB(e,t){let r=t.agentOsId?.trim();if(!r)return ae("invalid_request","Saved logins need the workspace this chat belongs to; update the Kynver runtime.");switch(e){case"list_logins":return Wb(t.args,r,Wp(t));case"fill_login":return ZZ(t,r);case"save_login":return eee(t,r);case"request_code":return tee(t,r)}}var Lb,QL,tB=p(()=>{"use strict";Tb();XL();_m();Fi();Tn();xm();Lb="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.",QL="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 Up,rB=p(()=>{"use strict";ei();Up=class{constructor(t){this.deps=t;this.now=t.now??Date.now,this.idleMs=t.idleMs??TL}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<NL),t.actionTimes.length>=DL?!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>=Ab)throw new Error(`tab limit reached (${Ab}) \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 Zt,ree,hl,nB=p(()=>{"use strict";Zt=class extends Error{constructor(r,n){super(r);this.code=n;this.name="CdpError"}code},ree=e=>new WebSocket(e),hl=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??ree)(t);return await new Promise((o,s)=>{let i=setTimeout(()=>s(new Zt("CDP connect timed out")),r.timeoutMs??1e4);n.addEventListener("open",()=>{clearTimeout(i),o()}),n.addEventListener("error",()=>{clearTimeout(i),s(new Zt("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 Zt("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 Zt(`${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 Zt(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 Zt("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 Zt("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 Zt(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 see(){let e=go(),t=e.state==="downloading"?` (${zD(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 oB(e={}){let t=(e.resolve??(()=>mo()))();if(t.executable)return t.executable;if(!(e.autoProvision??E().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??go)(),o=(e.now??Date.now)();if(n.state==="failed"&&n.failedAt!==null&&o-n.failedAt<oee)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??ap)(),i,a=new Promise(l=>{i=setTimeout(()=>l("pending"),e.waitMs??nee),i.unref?.()});try{let l=await Promise.race([s,a]);if(l==="pending")throw s.catch(()=>{}),new Mr(see(),"browser_installing");return l.executable}catch(l){if(l instanceof Mr)throw l;let c=l instanceof qs?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 nee,oee,Mr,sB=p(()=>{"use strict";j();nl();lp();nee=2e4,oee=6e4,Mr=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserEnsureError"}code}});import{spawn as iee}from"node:child_process";import{existsSync as SLe,mkdirSync as aee,readFileSync as lee,rmSync as cee}from"node:fs";import{homedir as uee}from"node:os";import iB from"node:path";function pee(e=process.env){return e.KYNVER_BROWSER_PROFILE_DIR?.trim()||iB.join(uee(),".kynver","browser-profile")}function aB(e=process.env){return(e.KYNVER_BROWSER_CDP_URL?.trim()||E().browserCdpUrl?.trim()||dee).replace(/\/$/,"")}async function lB(e,t={}){let r=t.env??process.env,n=t.platform??process.platform,o=t.allowNoSandbox??E().browserAllowNoSandbox!==!1;if((t.asRoot??XD(n))&&o){let a=await Fb(e,r,n,t,!0);if("wsUrl"in a)return cp("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 Ub(a.stderrTail)}let i=await Fb(e,r,n,t,!1);if("wsUrl"in i)return cp("on"),i;if(n==="linux"&&o&&jk(i.stderrTail)){let a=await Fb(e,r,n,t,!0);if("wsUrl"in a)return cp("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 Ub(a.stderrTail)}throw Ub(i.stderrTail)}function Ub(e){let t=tl(e);return t.length>0?new yl(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 Fb(e,t,r,n,o){let s=pee(t);aee(s,{recursive:!0});let i=iB.join(s,"DevToolsActivePort");cee(i,{force:!0});let a=np(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??iee)(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=>lee(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 cB(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 dee,yl,uB=p(()=>{"use strict";j();po();rp();nl();Vk();dee="http://127.0.0.1:9222";yl=class extends Error{constructor(r){super(`Chrome is missing system libraries: ${r.join(", ")}`);this.missingLibs=r;this.name="ChromeMissingLibsError"}missingLibs}});async function fee(e){if(e==="attach"){let n=aB(),o;try{o=await cB(n)}catch{throw new ti(`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 hl.connect(o),child:null,mode:e}}let t;try{t=await oB()}catch(n){throw n instanceof Mr?new ti(n.message,n.code):n}let r;try{r=await lB(t)}catch(n){throw n instanceof yl?new ti(PD(n.missingLibs,DD()),"missing_libs"):n}return{conn:await hl.connect(r.wsUrl),child:r.child,mode:e}}function mee(){return Fp??=new Up({connectHost:fee}),Fp}async function dB(){Fp&&await Fp.closeAll().catch(()=>{})}function pB(){try{let e=E();e.browserEverEnabled!==!0&&Be({...e,browserEverEnabled:!0})}catch{}}function pn(e,t){return{ok:!1,code:e,text:t}}function gee(e){if(!e||typeof e!="object")return null;let t=e,r=t.policy;if(t.kind!=="browser"||!CL(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 fB(e,t){let r=gee(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??mee();if(r.action==="list_logins")return Wb(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"?Tp+5e3:IL,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([xL(c)?eB(c,l):YL(c,l),a]).finally(()=>clearTimeout(i));return{...u,text:Np(u.text)}}catch(o){if(o instanceof ti)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 ti,Fp,Kb=p(()=>{"use strict";Tb();tB();Pb();rB();nB();j();sB();rp();po();uB();ei();ti=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserSetupError"}code};Fp=null});async function mB(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??fB)(t.payload,{boxId:e.boxId,agentOsId:e.agentOsId,localDisabled:E().browserDisabled===!0,onEnabledTurn:pB});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 gB=p(()=>{"use strict";j();Kb()});function kB(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 bB(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 yB(e){let t=e?.code;return typeof t=="string"?t:null}function vB(e){if(!e)return!1;if(e instanceof fn)return hee.has(e.status);let t=yB(e)??yB(e.cause);if(t&&yee.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 $b(e){return bB(e)?"aborted":vB(e)?"transient":"server"}function RB(e,t){let r=$b(e);if(r==="aborted")return t<=bee?0:vee;if(r==="transient"){let n=Math.max(0,Math.min(t-1,hB.length-1));return hB[n]}return kee}function wB(e,t){return e==="aborted"&&t<Ree?{event:"chat_claim_poll_retry",level:"info"}:{event:"chat_claim_error",level:"error"}}var fn,hee,yee,kee,bee,vee,hB,Kp,Ree,Hb=p(()=>{"use strict";fn=class extends Error{status;constructor(t){super(`claim failed: HTTP ${t}`),this.name="ClaimHttpError",this.status=t}},hee=new Set([502,503,504]),yee=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","ENETDOWN","UND_ERR_CONNECT_TIMEOUT"]),kee=5e3,bee=3,vee=1e3,hB=[0,1e3,5e3];Kp=class{counts={aborted:0,transient:0,server:0,auth:0,recovered:0};streakKind=null;streak=0;onError(t){let r=$b(t);return this.bump(r),{kind:r,consecutive:this.streak,backoffMs:RB(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}},Ree=3});async function ri(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 SB(e,t,r={}){let n=r.env??process.env,{engine:o,access:s}=ho({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??Qd)(o,n),log:(r.summary??Ep)(),...o==="claude-code"?{claudeCode:{signedIn:(r.signedIn??Zd)(n),steps:(r.stepSummary??dL)()}}:{}}}var _B=p(()=>{"use strict";it();Xa();yb();xp();gb()});function $p(e){let t=e.appendLog??(s=>{Qa(s)}),r=e.now??(()=>new Date),n=0,o=(s,i)=>Dk({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 Vb=p(()=>{"use strict";ep()});import{readFileSync as wee,statSync as See}from"node:fs";import xB from"node:path";function Cee(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!==_ee||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 vo(e,t,r){return{step:{kind:"attach",path:e,ok:!1,reason:t,...r!==void 0?{outputBytes:r}:{}}}}function Eee(e,t,r={}){let n=r.stat??See,o=r.read??wee,s=r.maxBytes??xee,i=e.rawPath.trim();if(!i||i.includes("\0"))return vo(i,"invalid_path");let a=xB.resolve(t.workDir,Ol(i));if(t.access==="off")return vo(a,"access_off");if(!Rc(t,a))return vo(a,"outside_folders");let l;try{let c=n(a);if(!c.isFile())return vo(a,"not_a_file");l=c.size}catch{return vo(a,"not_found")}if(l>s)return vo(a,"too_large",l);try{let c=o(a);return{step:{kind:"attach",path:a,outputBytes:c.length,ok:!0},file:{name:xB.basename(a),sizeBytes:c.length,contentBase64:c.toString("base64")}}}catch{return vo(a,"read_failed")}}function CB(e,t,r){let n=Cee(e);for(let o of n){let s=Eee(o,t.access);r.attach(s.step,t,{toolUseId:o.toolUseId,...s.file?{file:s.file}:{}})}return n.length}var _ee,xee,EB=p(()=>{"use strict";_n();it();_ee="attach_file",xee=50*1024*1024});function Pee(e){return e>=200&&e<300?"accepted":e===409||e===410?"rejected":e===404||e===405?"unsupported":"unreachable"}function AB(e){return e!=="rejected"}async function PB(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(),Aee);try{let a=await Fs(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 so(e,a,l.status),{outcome:Pee(l.status),status:l.status}}catch{}finally{clearTimeout(i)}}return{outcome:"unreachable",status:null}}var Aee,IB=p(()=>{"use strict";Fd();Aee=4e3});async function Tee(e,t,r=fetch){let n=new AbortController,o=setTimeout(()=>n.abort(),Oee);try{let s=await Fs(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 so(e,s,a.status),a.ok}catch{return!1}finally{clearTimeout(o)}}function OB(e){let t=e.intervalMs??Iee,r=!1,n=()=>{r||Tee(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 Iee,Oee,TB=p(()=>{"use strict";Fd();Iee=15e3,Oee=5e3});function Dee(e){return typeof e=="string"&&Nee.includes(e)}function NB(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.kind!=="agent-tab"||!Dee(t.engine)||typeof t.sessionKey!="string"||!Uee.test(t.sessionKey))return null;let r=typeof t.text=="string"?t.text.slice(0,Mee):"",n=[],o=0;if(Array.isArray(t.attachments))for(let i of t.attachments.slice(0,Bee)){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>Wee)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,Lee):"";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 Nee,Mee,Lee,Bee,Wee,Uee,DB=p(()=>{"use strict";Nee=["hermes","openclaw","claude-code"];Mee=32e3,Lee=4e3,Bee=5,Wee=20*1024*1024,Uee=/^[A-Za-z0-9_.:-]{8,128}$/});import{existsSync as Fee,mkdirSync as Kee,readFileSync as $ee,renameSync as Hee,writeFileSync as jee}from"node:fs";import{homedir as Vee}from"node:os";import LB from"node:path";function Gee(e=Vee()){return LB.join(e,".kynver","agent-tab-sessions.json")}function BB(e=Gee(),t=Date.now){let r=()=>{try{if(!Fee(e))return{};let o=JSON.parse($ee(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>MB&&s.sort((i,a)=>o[i].at-o[a].at).slice(0,s.length-MB).forEach(i=>delete o[i]);try{Kee(LB.dirname(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;jee(i,`${JSON.stringify(o)}
|
|
507
|
+
`,{mode:384}),Hee(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 MB,WB=p(()=>{"use strict";MB=500});import{existsSync as UB,readFileSync as Jee}from"node:fs";import{homedir as FB}from"node:os";import Ro from"node:path";function KB(e){try{return UB(e)?Jee(e,"utf8"):null}catch{return null}}function qee(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 $B(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 Yee(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 zee(e){return/^(1|true|yes|on)$/i.test((e??"").trim())}function HB(e={}){let r=(e.env??process.env).HERMES_HOME?.trim();return r?Ro.resolve(r):Ro.join(e.home??FB(),".hermes")}function Xee(e={}){return Ro.join(HB(e),".env")}function Hp(e={}){let t=e.readFile??KB,r=Xee(e),n=t(r),o=n===null?{}:Yee(n),s=o.API_SERVER_KEY?.trim()||null;return{baseUrl:`http://${qee(o.API_SERVER_HOST)}:${$B(o.API_SERVER_PORT,8642)}`,key:s,enabled:zee(o.API_SERVER_ENABLED)||s!==null&&o.API_SERVER_ENABLED===void 0,configured:n!==null||UB(HB(e)),configPath:r}}function Qee(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 kl(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 bl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Zee(e={}){let t=e.env??process.env,r=t.OPENCLAW_CONFIG_PATH?.trim();if(r)return Ro.resolve(r);let n=t.OPENCLAW_STATE_DIR?.trim();return Ro.join(n?Ro.resolve(n):Ro.join(e.home??FB(),".openclaw"),"openclaw.json")}function jp(e={}){let t=e.env??process.env,r=e.readFile??KB,n=Zee(e),o=r(n),s=o===null?null:Qee(o),i=bl(kl(s,["gateway","auth","mode"])),a=(i==="password"?bl(kl(s,["gateway","auth","password"]))??bl(t.OPENCLAW_GATEWAY_PASSWORD):bl(kl(s,["gateway","auth","token"]))??bl(t.OPENCLAW_GATEWAY_TOKEN))??(i==="none"?"":null);return{baseUrl:`http://127.0.0.1:${$B(t.OPENCLAW_GATEWAY_PORT??kl(s,["gateway","port"]),18789)}`,key:a,enabled:kl(s,["gateway","http","endpoints","chatCompletions","enabled"])===!0,configured:o!==null,configPath:n}}var Gb=p(()=>{"use strict"});function jB(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*VB(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=jB(o);o=[],u&&(yield u)}else o.push(c)}}n+=r.decode(),n&&o.push(n.replace(/\r$/,""));let s=jB(o);s&&(yield s)}finally{t.releaseLock()}}var GB=p(()=>{"use strict"});function Jb(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 JB(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 qB(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"?"":Jb(n.content)}).join(""):""}function qb(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:qB(r.response)||null,finishReason:"stop",error:null};if(n==="response.failed"||n==="error"){let d=r.response;return{delta:"",full:null,finishReason:"error",error:JB(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?JB(r.error)??"the agent reported an error":null,i=(Array.isArray(r.choices)?r.choices:[])[0]??null,a=Jb(i?.delta?.content)||(typeof i?.text=="string"?i.text:""),l=i?.message?.content,c=l==null?null:Jb(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 YB(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:qB(t),finishReason:"stop",error:null}:qb(null,e)}var zB=p(()=>{"use strict"});function XB(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?t.text:"").join(""):""}function ete(e,t){if(!Array.isArray(e)||e.length===0)return null;let r=QB(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=XB(s.content);n===null&&i.trim()&&(n=i);continue}if(s.role!=="tool"&&s.role==="user")return n===null?null:!r||QB(XB(s.content)).includes(r)?n:null}}return null}async function ZB(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 ete(i?.data,e.sentText)}catch{return null}finally{clearTimeout(n),e.signal?.removeEventListener("abort",o)}}var QB,eW=p(()=>{"use strict";QB=e=>e.replace(/\s+/g," ").trim()});function tte(e=process.env){let t=e.KYNVER_OPENCLAW_AGENT?.trim();return t?`openclaw/${t}`:"openclaw/default"}function tW(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 nte(e,t,r,n){let o=`Conversation opened from Kynver chat (${t}).`,s=r?.trim();return s?e==="hermes"?`${s}
|
|
511
|
+
|
|
512
|
+
${o}`:s:e==="hermes"&&!n?o:null}async function rW(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=nte(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:tW(e.text,e.attachments)}),s={model:"hermes-agent",stream:!0,messages:o}):(o.push({role:"user",content:tW(e.text,e.attachments)}),s={model:tte(),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 nW(e){let t=e.now??Date.now,r=e.engine==="hermes"?e.sessions.get(e.sessionKey):null,n=await rW(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 rW(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()&&ote.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=YB(f);m&&c(m)}else{let f=new Map;for await(let m of VB(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=qb(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 ZB({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 ote,oW=p(()=>{"use strict";GB();zB();eW();ote=/cannot be represented as an append-only response stream/i});import{mkdirSync as ste,readFileSync as ite,realpathSync as ate,statSync as lte,writeFileSync as cte}from"node:fs";import{homedir as Yb}from"node:os";import er from"node:path";function Xb(e=Yb()){return er.join(e,".kynver","agent-tabs","inbox")}function sW(e,t=80){return e.replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^\.+/,"_").slice(0,t)||"file"}function aW(e,t,r={}){if(t.length===0)return[];let n=er.join(r.root??Xb(),sW(e,120));ste(n,{recursive:!0,mode:448});let o=(r.now??Date.now)();return t.map((s,i)=>{let a=Buffer.from(s.contentBase64,"base64"),l=er.join(n,`${o}-${i}-${sW(s.name,120)}`);cte(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 Gp(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(`
|
|
513
|
+
|
|
514
|
+
`)}function Qb(e){let t=[];return{text:e.replace(ute,(n,o,s,i,a)=>{let l=String(o??s??i??a??"").replace(/[),.;:!?\]]+$/,"");return l?(!t.includes(l)&&t.length<Vp&&t.push(l),""):n}).replace(/[ \t]+\n/g,`
|
|
515
|
+
`).replace(/\n{3,}/g,`
|
|
516
|
+
|
|
517
|
+
`).trim(),paths:t}}function iW(e,t=Yb()){let r=er.basename(e);if(dte.test(r))return"credential_file";let n=er.relative(t,e);if(!n.startsWith("..")&&!er.isAbsolute(n)){let o=n.split(er.sep).join("/");if(Jd.some(s=>o===s))return"credential_file";if(Gd.some(s=>o===s||o.startsWith(`${s}/`)))return"private_folder"}return null}function pte(e,t){return e==="~"?t:e.startsWith("~/")||e.startsWith("~\\")?er.join(t,e.slice(2)):e}function Zb(e,t={}){let r=t.home??Yb(),n=er.resolve(pte(e,r)),o={path:n,name:er.basename(n)},s=iW(n,r);if(s)return{...o,ok:!1,reason:s,sizeBytes:null,contentBase64:null};try{let i=ate(n),a=iW(i,r);if(a)return{...o,ok:!1,reason:a,sizeBytes:null,contentBase64:null};let l=lte(i);if(!l.isFile())return{...o,ok:!1,reason:"not_a_file",sizeBytes:null,contentBase64:null};if(l.size>zb)return{...o,ok:!1,reason:"too_large",sizeBytes:l.size,contentBase64:null};let c=ite(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 zb,Vp,ute,dte,Jp=p(()=>{"use strict";qd();mb();zb=50*1024*1024,Vp=10;ute=/MEDIA:\s*(?:"([^"\n]+)"|'([^'\n]+)'|`([^`\n]+)`|((?:~|\/|[A-Za-z]:[\\/])[^\s"'`<>]*))/g;dte=fb($s)});import{chmodSync as mte,copyFileSync as gte,mkdirSync as hte}from"node:fs";import ev from"node:path";function yte(e){let t=e?.trim();return t?`${lW}
|
|
447
518
|
|
|
448
|
-
|
|
519
|
+
${t}`:lW}function kte(e){let t=e.config??E();return{engine:"claude-code",access:Vo({engine:"claude-code",local:{chatComputerAccess:t.chatComputerAccess,chatWorkFolders:t.chatWorkFolders},website:bc(e.payloadAccess,e.boxId),home:e.home})}}function vte(e,t){if(t.access==="full"||t.access==="off")return e;let r=ev.join(t.workDir,bte);return e.map(n=>{if(Rc(t,n.path))return n;hte(r,{recursive:!0,mode:448});let o=ev.join(r,ev.basename(n.path));return gte(n.path,o),mte(o,384),{...n,path:o}})}function Rte(e){return e.map(t=>t&&typeof t=="object"&&t.type==="text"?String(t.text??""):"").join("")}async function cW(e){let t=kte(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??E(),n=e.env??process.env,o=Gp(e.text,vte(e.attachments,t.access)),s=await(e.run??Pp)({payload:{system:yte(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:Rte(s.content)}}var lW,bte,uW=p(()=>{"use strict";j();_n();vb();Cp();Jp();lW="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.";bte=".kynver-attachments"});import qp from"node:path";import{homedir as wte}from"node:os";function Ate(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 Pte(e){return e.replace(/[ \t]+\n/g,`
|
|
449
520
|
`).replace(/\n{3,}/g,`
|
|
450
521
|
|
|
451
|
-
`).trim()
|
|
452
|
-
`,{encoding:"utf8",mode:384})}catch{}}var
|
|
522
|
+
`).trim()}function dW(e){let t=[];return e.includes("data:image/")?{text:e.replace(Ste,(n,o,s,i)=>{if(t.length>=Vp)return n;let a=s.toLowerCase(),l=`image-${t.length+1}.${_te[a]??"png"}`,c=Ate(i);return c>zb?(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 Ite(e){let t=e.replace(Ete,n=>" ".repeat(n.length)),r=[];for(let n of t.matchAll(Cte)){let o=n[1].replace(/[),.;:!?\]]+$/,"");r.includes(o)||r.push(o)}return r}function Ote(e,t){return e.startsWith("~/")?qp.join(t,e.slice(2)):e}function Tte(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 pW(e,t={}){let r=t.home??wte(),n=qp.resolve(t.inboxRoot??Xb(r)),o=[],s=()=>o.length<Vp,i=dW(e);o.push(...i.files);let a=Qb(i.text);for(let u of a.paths){if(!s())break;o.push({source:"tag",...Zb(u,{home:r})})}let l=a.text,c=new Set(o.map(u=>u.path));for(let u of Ite(l)){if(!s())break;let d=qp.resolve(Ote(u,r));if(c.has(d)||d===n||d.startsWith(`${n}${qp.sep}`))continue;let f=Zb(u,{home:r});!f.ok&&f.reason!=="too_large"||(c.add(f.path),o.push({source:"path",...f}),f.ok&&(l=Tte(l,u)))}return{text:Pte(l),files:o}}function fW(e){return Qb(dW(e).text).text}var Ste,_te,xte,Cte,Ete,mW=p(()=>{"use strict";Jp();Ste=/!\[([^\]\n]{0,200})\]\(\s*data:(image\/[a-z0-9.+-]{1,40});base64,([A-Za-z0-9+/=\r\n]+)\s*\)/gi,_te={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/bmp":"bmp"},xte=["mp4","mov","m4v","webm","mkv","mp3","m4a","wav","ogg","oga","opus","aac","flac","png","jpg","jpeg","gif","webp","heic","pdf"],Cte=new RegExp(String.raw`(?<![\w/:.~-])((?:~\/|\/)[^\s"'\`<>()\[\]{}|]*?\.(?:${xte.join("|")}))(?![\w/-])`,"gi"),Ete=/```[\s\S]*?(?:```|$)/g});function hW(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 tv(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 gW.set(e,n),n}function Yp(e){return gW.get(e)??null}var gW,rv=p(()=>{"use strict";gW=new Map});import{appendFileSync as Nte,mkdirSync as Dte}from"node:fs";import{homedir as Mte}from"node:os";import yW from"node:path";function Lte(e=Mte()){return yW.join(e,".kynver","logs","agent-tabs.jsonl")}function kW(e,t=Lte()){try{Dte(yW.dirname(t),{recursive:!0});let r={...e,...e.label?{label:e.label.slice(0,300)}:{}};Nte(t,`${JSON.stringify(r)}
|
|
523
|
+
`,{encoding:"utf8",mode:384})}catch{}}var bW=p(()=>{"use strict"});async function vW(e,t,r={}){let n=r.now??(()=>new Date),o=r.log??kW,s=NB(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 co,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=$p({turnId:t.turnId,chat:null,send:b=>g(b),now:n}),v="",k=!1;try{let b=r.sessions??BB(),_=aW(s.sessionKey,s.attachments,{root:r.inboxRoot}),S;if(i==="claude-code")S=(await(r.runClaudeCode??cW)({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 I=(r.endpoint??(O=>O==="hermes"?Hp():jp()))(i),A=await nW({engine:i,endpoint:I,sessionKey:s.sessionKey,text:Gp(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=pW(S,{home:r.home,inboxRoot:r.inboxRoot});R.files.forEach((I,A)=>{let O=n().toISOString();g({at:O,chat:null,turnId:t.turnId,kind:"attach",engine:i,access:"own",path:I.path,folder:"",ok:I.ok,...I.reason?{reason:I.reason}:{},...!I.ok&&I.sizeBytes!==null?{sizeBytes:I.sizeBytes}:{},toolUseId:`media-${A}`,...I.ok&&I.contentBase64?{file:{name:I.name,sizeBytes:I.sizeBytes,contentBase64:I.contentBase64}}:{}}),o({at:O,turnId:t.turnId,engine:i,kind:"attach",path:I.path,ok:I.ok,reason:I.reason})}),m.close(),await d.drain();let w=n().getTime()-a;tv(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 ri(()=>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(I=>I.ok).length}}}]).catch(()=>!1))}catch(b){m.close(),await d.drain();let _=b instanceof Error?b.message:String(b),S=hW(b),R=n().getTime()-a;if(tv(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=`
|
|
453
524
|
|
|
454
|
-
_${E7[i]} stopped before finishing (${S})._`;await e([{seq:w,kind:"final",message:{content:[{type:"text",text:ab(b).text+R}],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:i,media:0,error:S}}}]).catch(()=>!1)}else await e([{seq:w,kind:"error",error:v.slice(0,1500)}]).catch(()=>!1)}}var E7,OL=p(()=>{"use strict";Od();qy();nb();ob();rL();iL();sb();kL();_L();lb();pb();PL();E7={hermes:"Hermes",openclaw:"OpenClaw","claude-code":"Claude Code"}});import{execFile as A7}from"node:child_process";async function N7(e){let t=TL.get(e);if(t&&Date.now()-t.at<I7)return t.version;let r=await new Promise(n=>{try{let[o,s]=oe(e,["--version"]);A7(o,s,X({encoding:"utf8",timeout:5e3}),(i,a,l)=>{if(i)return n(null);n(`${a??""} ${l??""}`.match(T7)?.[0]??null)})}catch{n(null)}});return TL.set(e,{at:Date.now(),version:r}),r}async function D7(e,t,r){let n=new AbortController,o=setTimeout(()=>n.abort(),O7);try{let s=await e(t,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:n.signal});return await s.body?.cancel().catch(()=>{}),s.status}catch{return null}finally{clearTimeout(o)}}function Or(e,t,r,n){return{engine:e,status:t,version:r,detail:n,lastRoundTrip:db(e)}}async function NL(e,t,r,n){if(!t.configured&&!r)return null;let o=e==="hermes"?"Hermes":"OpenClaw";if(!t.enabled)return Or(e,"not_enabled",r,`${o}'s local chat API is off`);if(t.key===null)return Or(e,"no_key",r,`${o}'s local chat API has no key set`);let s=await D7(n,`${t.baseUrl}/v1/models`,t.key||null);return s===null?Or(e,"unreachable",r,`${o} is not answering on ${t.baseUrl} \u2014 is its gateway running?`):s===401||s===403?Or(e,"no_key",r,`${o} refused the key in its config (HTTP ${s})`):s===404?Or(e,"not_enabled",r,`${o} is running but its chat API is not switched on`):Or(e,"ready",r,null)}function M7(e){let{version:t,signedIn:r}=(e.claudeCode??(()=>({version:Ad("claude-code",e.env),signedIn:Pd(e.env)})))();return t?r?(e.config??I()).chatComputerAccess==="off"?Or("claude-code","access_off",t,"Computer access for chat is off on this computer"):Or("claude-code","ready",t,null):Or("claude-code","not_signed_in",t,"Claude Code is installed but not signed in"):null}async function L7(e={}){let t=e.env??process.env,r=e.fetchFn??fetch,n=e.versionOf??N7,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([NL("hermes",vp(e),i,r),NL("openclaw",Rp(e),a,r)]);return{v:1,engines:[l,c,M7(e)].filter(d=>d!==null)}}function B7(e={}){return sl||(il&&Date.now()-il.at<P7?Promise.resolve():(sl=L7(e).then(t=>{il={at:Date.now(),report:t}}).catch(()=>{}).finally(()=>{sl=null}),sl))}function fb(){if(B7(),!!il)return{v:1,engines:il.report.engines.map(e=>({...e,lastRoundTrip:db(e.engine)}))}}var P7,I7,O7,T7,TL,il,sl,DL=p(()=>{"use strict";K();Ge();N();La();pb();sb();P7=3e4,I7=10*6e4,O7=1500,T7=/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/,TL=new Map;il=null,sl=null});import U7 from"node:os";function W7(e){try{return _t().report(e)}catch{return null}}function WL(e,t){try{return VM(e,t)}catch{return}}function mb(e=process.env){let t=I(),r=vt(t,e);return No({boxKind:r,hostLabel:U7.hostname(),config:t,env:e})}async function H7(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(),FL);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 j7(o)}async function j7(e){let t=new AbortController,r=setTimeout(()=>t.abort(),FL);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 KL(e){return Ee()?!0:!!e&&!!Cf(e)}async function BL(e=process.env){let t=I(),r=t.agentOsId?.trim(),n=Ee();if(!r||!KL(r))return null;let o=await H7(t.apiBaseUrl,n,e);if(!o)return null;let s=ro(t),i=t.apiBaseUrl?.replace(/\/$/,"")??o.replace(/\/$/,"");return{bridgeUrl:o.replace(/\/$/,""),agentOsId:r,apiKey:n??"",boxId:mb(e),chatProvider:s,model:Ns(s,t,e),useClaudeOauth:t.chatUseClaudeOauth===!0,auth:new gd({apiBaseUrl:i,agentOsId:r,boxLabel:()=>mb(e),loadApiKey:Ee,loadBoxCredential:()=>Cf(r),saveBoxCredential:a=>FR(r,a),clearBoxCredential:KR}),security:new kd}}function gb(){try{return $R().apiKey}catch{return"none"}}async function V7(e,t,r,n){let o=I(),s=ro(o),i=await hb(e);if(!i.bearer)return"no_credential";let a=Fd(s,qd(o),WL(s,o),e.security?.report({policy:n,auth:i.kind,credentialStore:gb(),folderSandbox:By(process.env,o)}),fb()),l=W7(e.agentOsId);l&&(a.browser.siteLogins=l);let c=i.kind==="box_token"?i.boxId:mb();e.chatProvider=s,e.boxId=c,e.model=Ns(s,o,process.env);let u=new AbortController,d=setTimeout(()=>u.abort(),K7),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:F7,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)})),Xn(e,i,401),"auth_error"}if(f.status===429)throw new nn(f.status);if(!f.ok)throw new nn(f.status);let g;try{g=await f.json()}catch{throw new nn(502)}let h=KM(g);if(!h)throw new nn(502);return h.turn}catch(f){if(t())return null;throw f}finally{clearTimeout(d),clearInterval(m)}}async function ht(e,t,r){let n=await hb(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 Xn(e,n,o.status),o.ok}async function UL(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??{}})),Ba({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 ht(e,t.turnId,[{seq:0,kind:"error",error:tN(r.code,r.detail)}]).catch(()=>{}),{ok:!1}}async function G7(e,t,r){let n=rN({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}):UL(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=I()}catch{o={}}let s=DN({signedAccess:n.access,boxId:e.boxId,agentOsId:e.agentOsId,engine:Ed(e.chatProvider,o,r.env??process.env),local:{chatComputerAccess:o.chatComputerAccess,chatWorkFolders:o.chatWorkFolders},state:xd(r.stateFile),env:r.env,nowSec:r.nowSec});if(!s.ok)return UL(e,t,{code:s.code,detail:s.detail,reason:s.reason,policy:r.policy,extra:{from:Ma(s.from),to:Ma(s.to),signed:n.signed}});s.website&&AN(s.website,{file:r.stateFile});let a={...Ey(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 J7(e,t){let r=0,n=!1,o=new to,s=Array.isArray(t.payload?.argv)?t.payload.argv:[],i=await VN(s,a=>{n||o.track(ht(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 ht(e,t.turnId,[{seq:r++,kind:"error",error:`command_refused: ${i.refused}`}]).catch(()=>{}):await ht(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 q7(e,t,r,n,o){try{let s=ao({provider:t.chatProvider,config:n,payloadAccess:e.payload.computerAccess,boxId:t.boxId}),i=EN(s.access,{signed:r.signed});if(!i)return;let a=i.from?Ma(i.from.access):"not set",l=Ma(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};Ba({...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 Y7(e,t,r){let n=0,o=!1,s=new to,i=new AbortController,a=t.requestId??"",l=h=>{o||s.track(ht(e,t.turnId,[{seq:n++,kind:"delta",text:h}]).then(y=>(y||(o=!0,i.abort()),y)))},c=new Qr(l),u=bp({turnId:t.turnId,chat:a||null,send:h=>{o||(c.flush(),s.track(ht(e,t.turnId,[{seq:n++,kind:"activity",activity:h}]).then(y=>(y||(o=!0,i.abort()),y))))}}),d=e.chatProvider??"anthropic",m=I(),f=qd(m);r&&q7(t,e,r,m,h=>{o||s.track(ht(e,t.turnId,[{seq:n++,kind:"activity",activity:h}]).then(y=>(y||(o=!0,i.abort()),y)))});try{Dk(d,e.useClaudeOauth,process.env,m)}catch(h){let y=Ya(t.payload.requestedModel);if(!(y&&f.some(k=>k.provider===y.provider&&k.models.includes(y.model)))){await ht(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 KD({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},FD({...k,signal:i.signal,turnId:t.turnId,requestId:t.requestId,useClaudeOauth:e.useClaudeOauth,config:m,boxId:e.boxId,onActivity:u.sink}))});qM(h.content,ao({provider:g.provider,config:m,payloadAccess:t.payload.computerAccess,boxId:e.boxId}),u),c.close(),await s.drain();let y=n++;if(!await kp(()=>o?ht(e,t.turnId,[{seq:y,kind:"error",error:"turn_stream_aborted"}]).catch(()=>!1):ht(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 ht(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 al(e,t){for(let n=0;n<e&&!t();n+=500)await new Promise(o=>setTimeout(o,Math.min(500,e-n)))}async function $L(e){let t=await BL(),r=()=>KL(I().agentOsId?.trim())&&!!I().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:LL}));!t&&!e.shouldStop();){if(!r()||(await al(LL,e.shouldStop),e.shouldStop()))return;t=await BL()}if(!t||e.shouldStop())return;let n=eN(process.env,I()),o=new yd;t.security&&(t.security.childEnv=await SN().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:Fd(t.chatProvider),useClaudeOauth:t.useClaudeOauth,turnSignature:n,credentialStore:gb(),childEnvSafe:t.security?.childEnv?.ok??null,auth:t.auth?.describe().kind??"api_key"}));let s=0,i=new yp,a=ZM({target:t,capabilities:c=>{let u=I(),d=ro(u);return Fd(d,qd(u),WL(d,u),t.security?.report({policy:n,auth:c.kind,credentialStore:gb(),folderSandbox:By(process.env,u)}),fb())}}),l=Promise.resolve();for(;!e.shouldStop();)try{if(s>=$7){await al(250,e.shouldStop);continue}let c=await V7(t,e.shouldStop,i.snapshot(),n);if(c==="no_credential"){console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:"machine_not_linked"})),await al(ML,e.shouldStop);continue}if(c==="auth_error"){i.onAuthError();let u=t.auth?.describe().hasBoxCredential===!0;await al(u?5e3:ML,e.shouldStop);continue}if(i.onSuccess(),c){let u=await XM(t,c.turnId);if(!zM(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=()=>J7(t,c);m=l.then(f,f),l=m.then(()=>{},()=>{})}else{let f=await G7(t,c,{policy:n,nonces:o});if(!f.ok){s-=1;continue}if(o.markStarted(c.turnId),d==="browser"){let g=await hb(t);m=BM({...t,apiKey:g.bearer},{turnId:c.turnId,payload:f.payload})}else d==="agent-tab"?m=IL(g=>ht(t,c.turnId,g),{turnId:c.turnId,payload:f.payload,boxId:t.boxId}):m=Y7(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);console.error(JSON.stringify({event:"chat_claim_error",error:c instanceof Error?c.message:String(c),kind:u,consecutive:d,retryInMs:m})),m>0&&await al(m,e.shouldStop)}a(),await DM(),console.error(JSON.stringify({event:"chat_claim_loop_stop"}))}var F7,K7,ML,LL,FL,$7,hb,HL=p(()=>{"use strict";K();Ne();XT();hd();Py();nN();oN();_d();_N();PN();MN();La();Id();Do();Od();qy();GN();Wa();x0();uk();dk();Mk();$D();UM();eb();rb();nb();GM();ob();YM();tp();QM();eL();OL();DL();rb();Ci();F7=2e4,K7=32e3,ML=6e4,LL=5*6e4,FL=5e3,$7=3,hb=Ps});import{createHash as z7}from"node:crypto";import{chmodSync as jL,existsSync as X7,mkdirSync as Q7,rmSync as VL}from"node:fs";import{createConnection as Z7,createServer as eZ}from"node:net";import{homedir as tZ,userInfo as rZ}from"node:os";import nZ from"node:path";function sZ(e,t=process.platform){return t==="win32"?`\\\\.\\pipe\\kynver-site-logins-${z7("sha256").update(`${rZ().username}:${tZ()}`).digest("hex").slice(0,16)}`:nZ.join(e,"control.sock")}async function iZ(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 aZ(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 GL(e){let t=sZ(e.rootDir);if(process.platform!=="win32"){Q7(e.rootDir,{recursive:!0,mode:448});try{jL(e.rootDir,448)}catch{}if(X7(t)){if(await lZ(t))return null;VL(t,{force:!0})}}let r=eZ(n=>{let o="";n.setEncoding("utf8"),n.setTimeout(12e4,()=>n.destroy()),n.on("data",s=>{if(o+=s,o.length>oZ)return void n.destroy();let i=o.indexOf(`
|
|
455
|
-
`);if(i<0)return;let a=
|
|
456
|
-
`);if(!a)return l({ok:!1,error:"malformed request"});iZ(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{jL(t,384)}catch{}return{path:t,close:()=>new Promise(n=>{r.close(()=>n()),process.platform!=="win32"&&VL(t,{force:!0})})}}function lZ(e){return new Promise(t=>{let r=Z7(e),n=o=>{r.destroy(),t(o)};r.once("connect",()=>n(!0)),r.once("error",()=>n(!1)),setTimeout(()=>n(!1),1e3).unref?.()})}var oZ,JL=p(()=>{"use strict";wn();oZ=16*1024});function dZ(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":Ds(e.platform,e.arch)?null:"unsupported_platform"}async function qL(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 YL(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??(()=>so({env:t,platform:r,arch:n})),a=e.loadConfig??I;try{await qL(e.startDelayMs??cZ,e);for(let l=1;l<=uZ&&!e.shouldStop();l+=1){let c=dZ({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=k0(io());if(u>o()&&await qL(u-o(),e),e.shouldStop())return;s({event:"browser_autoprovision_start",attempt:l});try{let d=await(e.provision??Bd)({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 cZ,uZ,zL=p(()=>{"use strict";K();no();$a();Ud();cZ=6e4,uZ=5});function kb(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(e.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function gZ(e,t){let r=kb(e),n=kb(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 hZ(e,t){return`Kynver on this computer is out of date (installed ${e}, latest ${t}). Update with: ${yb} then restart Kynver (or restart the computer).`}async function yZ(e={}){let t=e.installed??Dt,r={installed:t,latest:null,outdated:!1,command:yb};if((e.env??process.env).KYNVER_DISABLE_UPDATE_CHECK==="1")return r;let o=new AbortController,s=setTimeout(()=>o.abort(),fZ);try{let a=await(e.fetch??fetch)(pZ,{signal:o.signal,headers:{accept:"application/json"}});if(!a.ok)return r;let l=await a.json(),c=typeof l?.version=="string"&&kb(l.version)?l.version:null;return c?{installed:t,latest:c,outdated:gZ(t,c),command:yb}:r}catch{return r}finally{clearTimeout(s)}}function QL(e={}){let t=e.log??(s=>console.error(s)),r=null,n=async()=>{let s=await yZ(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(hZ(s.installed,s.latest))),s};n().catch(()=>{});let o=setInterval(()=>{n().catch(()=>{})},e.intervalMs??mZ);return o.unref?.(),{stop:()=>clearInterval(o),checkNow:n}}var XL,yb,pZ,fZ,mZ,ZL=p(()=>{"use strict";Jo();XL="@kynver-app/runtime",yb=`npm install -g ${XL}@latest`,pZ=`https://registry.npmjs.org/${XL}/latest`,fZ=5e3,mZ=360*6e4});var nB={};Lb(nB,{adoptOrAcquireOwnerLease:()=>tB,completeWorker:()=>eA,dispatchRun:()=>bs,resolveDaemonOwnerKind:()=>eB,runDaemon:()=>rB,runPipelineTick:()=>md,sweepRun:()=>qu});async function bb(e,t,r){let n=e;for(;n>0&&!t();){let o=Math.min(RZ,n),s=Date.now();await vl(o);let i=cm(o,Date.now()-s);if(i!==null){r?.(i);return}n-=o}}function eB(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 tB(e,t,r,n=xc){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 rB(e,t={}){let r=wm({hostCapability:t.hostCapability}),n=kt()?{loaded:0}:Zv();n.loaded>0&&console.error(JSON.stringify({event:"daemon_env_file_loaded",...n}));let o=String(e.run||"").trim();o||(console.error(gm("--run")),process.exit(1));let s=String(e.agentOsId||I().agentOsId||"").trim();s||(console.error(gm("--agent-os-id")),process.exit(1)),Fo(s).ok||(console.error(Sf(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)):kZ,c=!1,u=0,d=qR(A=>{c||console.error(JSON.stringify({event:"daemon_stop_requested",reason:A,runId:o})),c=!0}),m=await tB(s,eB(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;aR(f.metadata.ownerKind),ZS({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=JS(o);h.killed.length>0&&console.error(JSON.stringify({event:"daemon_orphaned_worker_descendants_killed",runId:o,orphans:h.killed.map(A=>({worker:A.workerName,workerPid:A.workerPid,pid:A.orphanPid,outcome:A.result.outcome}))}));let y=null,b=A=>{y=A};try{let A=WR();(A.moved.length>0||A.stillInFile.length>0)&&console.error(JSON.stringify({event:"daemon_credentials_store",...A}))}catch(A){console.error(JSON.stringify({event:"daemon_credentials_store_error",error:A instanceof Error?A.message:String(A)}))}let k=IS();k.remediated&&console.error(JSON.stringify({event:"daemon_default_repo_remediated",defaultRepo:k.resolved?.defaultRepo??null,configPath:k.configPath}));let v=VS(I());v.ok||(console.error(JSON.stringify({event:"daemon_start_blocked",runId:o,agentOsId:s,errors:v.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:v.box.boxKind,workerCapSource:v.workerCapSource,maxConcurrentWorkers:v.maxConcurrentWorkers})),QL();let S=Vo(),_=GL(_t()).catch(()=>null),w=$L({shouldStop:()=>c}).catch(A=>{console.error(JSON.stringify({event:"chat_claim_loop_crashed",error:A instanceof Error?A.message:String(A)}))});YL({shouldStop:()=>c});let R=!1;for(;!c;)try{if(y!==null){let H=y;y=null;let P=f.isHeld();if(console.error(JSON.stringify({event:"daemon_resume_detected",agentOsId:s,gapMs:H,ownerLeaseHeld:P})),!P){console.error(JSON.stringify({event:"daemon_owner_lease_lost",agentOsId:s,runId:o})),process.exitCode=1,c=!0;break}}f.renew(),sS({agentOsId:s,runId:o,instructionBundleVersion:_n(),owner:g});let A=await ic(e.secret?String(e.secret):void 0,s,{baseUrl:e.baseUrl?String(e.baseUrl):void 0});if(!A.ok){R||(R=!0,console.error(JSON.stringify({event:"daemon_runner_credential_missing",agentOsId:s,reason:A.reason,remedy:`run \`kynver runner credential --agent-os-id ${s}\` (or \`kynver bootstrap\`); ticks resume automatically once the credential exists`}))),await bb(l,()=>c,b);continue}R&&(R=!1,console.error(JSON.stringify({event:"daemon_runner_credential_recovered",agentOsId:s}))),await $S({agentOsId:s,baseUrl:yn(e.baseUrl?String(e.baseUrl):void 0),secret:A.secret});let C=await md({run:o,agentOsId:s,execute:a,...e,secret:typeof e.secret=="string"&&e.secret?e.secret:A.secret});console.error(JSON.stringify({event:"daemon_tick",...C}));let $=To(s);if(sR($,Po().length)){let H=Jl({control:$,supervisor:f.metadata.ownerKind,inFlightWorkers:0,exiting:!0}),P=yn(e.baseUrl?String(e.baseUrl):void 0),x=H&&P?await eS({baseUrl:P,agentOsId:s,secret:A.secret},H):!1;console.error(JSON.stringify({event:"daemon_runtime_stopped",agentOsId:s,runId:o,policyVersion:$?.policyVersion??null,requestedBy:$?.requestedByLabel??null,reported:x})),process.exitCode=Vl,c=!0;break}if(S.tickEnabled){let H=Dc(o);if(H&&!H.authorized)console.error(JSON.stringify({event:"daemon_cron_tick_skipped",reason:"mesh_cron_lease_not_authorized",holderBoxId:H.holderBoxId}));else{let P=await Am({env:S,agentOsIdFilter:s});P.enabled&&(P.fired>0||P.errors>0||P.lockHeld)&&console.error(JSON.stringify({event:"daemon_cron_tick",...P}))}}C.idle?u++:u=0;let B=Math.floor(Yo("daemon.maxIdleStreak",vZ)),D=Math.floor(Yo("daemon.idleIntervalMs",bZ)),J=u>=B?D:l;await bb(J,()=>c,b)}catch(A){console.error(JSON.stringify({event:"daemon_tick_error",error:A.message})),await bb(l,()=>c,b)}await w,await(await _)?.close().catch(()=>{}),_t().lock();let M=YR(o);M.length>0&&console.error(JSON.stringify({event:"daemon_stop_worker_trees_killed",runId:o,workers:M.map(A=>({worker:A.workerName,pid:A.pid,outcome:A.result.outcome}))})),d(),f.release(),console.error(JSON.stringify({event:"daemon_stop",runId:o,agentOsId:s}))}var kZ,bZ,vZ,RZ,vb=p(()=>{"use strict";K();hm();OS();HS();xn();GS();lm();dc();Cc();Tt();um();qS();Tc();Sm();Pm();ur();or();Im();N();xy();HL();Ci();JL();zL();Io();ZL();dn();am();xy();fu();Bh();hs();kZ=6e4,bZ=5*6e4,vZ=10,RZ=250});var oB=p(()=>{"use strict";z();wo();Mh();Se();N()});var ll,sB=p(()=>{"use strict";ll=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 wZ,mkdirSync as SZ}from"node:fs";import _Z from"node:path";function xZ(e){let t=typeof e.repo=="string"?e.repo.trim():"";if(t)return t;let r=Ni();return r?r.repo:(bt("","--repo (or set defaultRepo via `kynver setup` / KYNVER_DEFAULT_REPO)"),"")}function CZ(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 EZ(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 AZ(e,t){let r=I();try{return CZ({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:()=>EZ(e),repoLabel:e})}catch(n){throw new ll(n.message,{remedy:"Diagnose: run `kynver doctor runner-install`.",cause:n})}}function Rb(e){let t=HE(xZ(e));Yb(t);let r=e.id?Xg(String(e.id)):yl(String(e.name||"run")),n=G(r);wZ(n)&&PZ(`run already exists: ${r}`),SZ(n,{recursive:!0});let o=AZ(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(_Z.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 PZ(e){throw new ll(e)}var wb=p(()=>{"use strict";ve();z();oB();N();Zo();Fu();pn();K();sB()});function iB(e,t){return e.filter(n=>n.repo===t&&!Cr.has(n.status)).sort((n,o)=>(o.createdAt??"").localeCompare(n.createdAt??""))[0]??null}var aB=p(()=>{"use strict";ve();qr()});var lB=p(()=>{"use strict";ur();Go();Em()});var Sp=p(()=>{"use strict";ur();or()});var _p=p(()=>{"use strict"});var Sb=p(()=>{"use strict"});var _b=p(()=>{"use strict";lB();ur();Go();Sp();or();_p();Sb()});var cB=p(()=>{"use strict"});var uB=p(()=>{"use strict";Sp();_p()});var dB=p(()=>{"use strict";or();ur()});var pB=p(()=>{"use strict";K();rt();Tt();N();Pm();cB();uB();or();Sp();dB();jl();pi();Go();_b();_p();Sb();z()});var fB=p(()=>{"use strict";_b();pB()});var mB=p(()=>{"use strict";pi();jl();K();or();ql();uf();fi();z()});function gB(e,t){return iB(e,t)?.id??null}var hB=p(()=>{"use strict";K();Xf();vb();hm();Sm();Cc();wb();z();aB();Zo();fB();im();mf();Zo();Wa();mB()});var RB={};Lb(RB,{prepareDesktopRuntime:()=>GZ,resolveDesktopRepository:()=>vB});import{spawnSync as yB}from"node:child_process";import{randomBytes as MZ}from"node:crypto";import{existsSync as LZ,mkdirSync as BZ,readFileSync as UZ,realpathSync as kB,statSync as WZ,writeFileSync as FZ}from"node:fs";import{homedir as KZ}from"node:os";import Cb from"node:path";function ke(e,t){return{ok:!1,code:e,message:t}}function $Z(){return Cb.join(KZ(),".kynver","desktop-binding.json")}function HZ(e){if(!LZ(e))return null;try{let t=JSON.parse(UZ(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 jZ(e,t){BZ(Cb.dirname(e),{recursive:!0}),FZ(e,`${JSON.stringify(t,null,2)}
|
|
457
|
-
`,{mode:384})}function bB(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 xb(e,t,r,n={}){try{let o=await st(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 VZ(e){return(e?.accessibleItems??[]).filter(t=>t.access?.isOwner===!0&&typeof t.agentOs?.id=="string").map(t=>(t.agentOs?.id).trim()).filter(Boolean)}function vB(e,t="git"){let r=yB(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=kB.native(Cb.resolve(e)),!WZ(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=yB(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:kB.native(s[1].trim())}}catch{return ke("not_a_repository","The Git working tree root could not be resolved")}}async function GZ(e,t={}){let r=t.fetchImpl??fetch,n=t.acquireOwnerLease??xc,o=t.bindingPath??$Z(),s=[],i=er(e.apiBaseUrl);if(!i)return ke("invalid_input","apiBaseUrl is required");let a=ei(i),l=new URL(a).origin;if(e.agentOsId!==void 0&&!Fo(e.agentOsId).ok)return ke("invalid_input","agentOsId is not a valid workspace id");let c;try{c=Ee()}catch(_){if(_ instanceof Gs)return ke("credentials_unavailable","This computer's credentials have not been provided");throw _}if(!c)return ke("credentials_unavailable","This computer is not paired");let u=await xb(`${a}/api/users/me`,c,r);if(u.status!==200)return bB(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 xb(`${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 xb(`${a}/api/agent-os`,c,r);if(g.status!==200)return bB(g.status,"Workspace lookup");let h=g.body,y;if(e.agentOsId){if(!VZ(h).includes(e.agentOsId))return ke("agent_os_not_owned","That workspace is not owned by the paired account");y=e.agentOsId}else{let _=Yf(h);if(!_?.id)return ke("no_workspace","No workspace owned by this account was found");y=_.id}let b=vB(e.repo,t.gitBinary);if(!b.ok)return b;let k=b.repo,v=await n({agentOsId:y,ownerKind:"desktop"});if(!v.ok)return{ok:!1,code:"owner_conflict",message:v.remedy,holder:v.holder?{ownerKind:v.holder.ownerKind,pid:v.holder.pid,runtimeVersion:v.holder.runtimeVersion,acquiredAt:v.holder.acquiredAt}:null};let S=v.lease;try{Le({...I(),apiBaseUrl:a,agentOsId:y,defaultRepo:k});let _=sm(I());s.push(..._.warnings);let w=I().boxId?.trim()??"";if(!w)return S.release(),ke("local_state_error","Box identity could not be established");if(await Qf(Br()),!He(y))try{let B=await kn(y,{baseUrl:a,apiKey:c});hn(y,B)}catch(B){let D=B.message;if(Mw(D)==="access_denied")return S.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 R=HZ(o),M=R!==null&&R.cloudOrigin===l&&R.accountId===d&&R.agentOsId===y&&R.repo===k,A="";if(M){let B=gB(Re().filter(D=>D.id===R.runId),k);B&&(A=B)}if(!A){let B=`${yl("desktop")}-${MZ(3).toString("hex")}`;A=Rb({repo:k,name:"desktop",id:B}).runId}jZ(o,{version:1,cloudOrigin:l,accountId:d,agentOsId:y,repo:k,runId:A});let C=gc(k);C||s.push("the repository has no origin remote; nothing can run until it has one");let{runnerId:$}=Pe({runId:A});return{ok:!0,prepared:{accountId:d,agentOsId:y,runId:A,repo:k,boxId:w,repoIdentity:C,runnerId:$},lease:S,warnings:s}}catch(_){return S.release(),ke("local_state_error",_.message)}}var wB=p(()=>{"use strict";tr();Xf();zf();K();Tt();ur();Go();Cc();hc();z();pr();im();hB();wb();N()});Tt();import{pathToFileURL as JZ}from"node:url";var $b="credential.persist";function Hb(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:$b,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:$b,kind:"runnerToken",agentOsId:a,value:l})},reseed:o}}dc();hc();wn();Gf();var _w=/^lg_[a-z0-9]{6,20}$/,IK=/^cr_[0-9a-f]{12}$/,OK=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sn=(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 xw(e){let t=["v","type","id","agentOsId","op"];switch(e.op){case"key":return jo(e,[...t,"key"])??(Sn(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"&&_w.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"&&IK.test(e.requestId))?"invalid requestId":Sn(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!OK(n)||jo(n,["origin","label","username","password","totp"])||!Sn(n.origin,2048)||!Sn(n.label,at.maxLabel)||!Sn(n.username,at.maxUsername)||!Sn(n.password,at.maxPassword)||n.totp!==void 0&&!Sn(n.totp,at.maxTotp,0)?"invalid login":e.replaceHandle!==void 0&&!(typeof e.replaceHandle=="string"&&_w.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 Cw(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)}}}Ci();wn();var qZ=1,xp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Vs=/^[A-Za-z0-9_-]{1,64}$/,YZ=/^[a-z0-9][a-z0-9._-]{0,127}$/i,SB=4096,zZ=4096,XZ=16;function Eb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function cl(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function ul(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!e.includes("\0")}function QZ(e){if(!ul(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 ZZ(e){if(!Eb(e))return{ok:!1,message:"message must be an object"};if(e.v!==qZ)return{ok:!1,message:"unsupported protocol version"};let t=r=>({ok:!1,message:r});switch(e.type){case"credentials":{let r=cl(e,["v","type","apiKey","runnerTokens"]);if(r)return t(r);if(e.apiKey!==void 0&&!ul(e.apiKey,SB))return t("invalid apiKey");let n;if(e.runnerTokens!==void 0){if(!Eb(e.runnerTokens))return t("invalid runnerTokens");let o=Object.entries(e.runnerTokens);if(o.length>XZ)return t("too many runnerTokens");n={};for(let[s,i]of o){if(!xp.test(s)||!ul(i,SB))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=cl(e,["v","type","id","apiBaseUrl","repo","agentOsId","expectedAccountId"]);return r?t(r):typeof e.id!="string"||!Vs.test(e.id)?t("invalid id"):QZ(e.apiBaseUrl)?ul(e.repo,zZ)?e.agentOsId!==void 0&&(typeof e.agentOsId!="string"||!xp.test(e.agentOsId))?t("invalid agentOsId"):e.expectedAccountId!==void 0&&!ul(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=cl(e,["v","type","id","policy"]);if(r)return t(r);if(typeof e.id!="string"||!Vs.test(e.id))return t("invalid id");let n=rw(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=cl(e,["v","type","id","runId","agentOsId"]);return r?t(r):typeof e.id!="string"||!Vs.test(e.id)?t("invalid id"):typeof e.runId!="string"||!YZ.test(e.runId)?t("invalid runId"):typeof e.agentOsId!="string"||!xp.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"||!Vs.test(e.id))return t("invalid id");if(typeof e.agentOsId!="string"||!xp.test(e.agentOsId))return t("invalid agentOsId");let r=xw(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=cl(e,["v","type","id"]);return r?t(r):typeof e.id!="string"||!Vs.test(e.id)?t("invalid id"):{ok:!0,value:{v:1,type:e.type,id:e.id}}}default:return t("unknown message type")}}function eee(e){return Eb(e)&&typeof e.id=="string"&&Vs.test(e.id)?e.id:null}function tee(e){let t=Fb()?"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(Af(l))return;let c=ZZ(l);if(!c.ok){s(eee(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=Hb(d,m=>e.send(m)),Wb(r)),t==="awaiting_credentials"&&(t="ready"),e.send({v:1,type:"event",name:"credentials_accepted",state:t});return}case"status":{let d=Df();i(u.id,{state:t,prepared:n,policyRevision:d?.revision??null});return}case"policy":{if(!sw(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,iw({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=Df();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 Cw(_t(),g,h))}catch(y){let b=y instanceof q?y.code:"failed";s(f,`site_login_${b}`,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 ree(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}Ub();for(let s of Bb)delete e.env[s];let[{prepareDesktopRuntime:t},{runDaemon:r}]=await Promise.all([Promise.resolve().then(()=>(wB(),RB)),Promise.resolve().then(()=>(vb(),nB))]),n=s=>{if(!e.connected||typeof e.send!="function")throw new Error("desktop IPC channel is closed");e.send(s)},o=tee({send:n,prepare:s=>t(s),runDaemon:r,requestDaemonStop:()=>{e.emit("message",{type:uc},void 0)},exit:s=>e.exit(s),daemonExitCode:()=>typeof e.exitCode=="number"?e.exitCode:0});aw(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{}}),_t().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:uc},void 0);return}e.exit(0)}),n({v:1,type:"event",name:"ready",state:o.state})}function nee(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===JZ(e).href}catch{return!1}}nee()&&ree();export{qZ as DESKTOP_ENTRY_PROTOCOL_VERSION,tee as createDesktopEntryController,ZZ as parseDesktopEntryMessage,ree as startDesktopEntry};
|
|
525
|
+
_${Bte[i]} stopped before finishing (${S})._`;await ri(()=>e([{seq:w,kind:"final",message:{content:[{type:"text",text:fW(v)+L}],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:i,media:0,error:S}}}]).catch(()=>!1))}else await ri(()=>e([{seq:w,kind:"error",error:_.slice(0,1500)}]).catch(()=>!1))}}var Bte,RW=p(()=>{"use strict";tp();Mk();jb();Vb();DB();WB();Gb();oW();uW();Jp();mW();rv();bW();Bte={hermes:"Hermes",openclaw:"OpenClaw","claude-code":"Claude Code"}});import{execFile as Wte}from"node:child_process";async function Vte(e){let t=wW.get(e);if(t&&Date.now()-t.at<Fte)return t.version;let r=await new Promise(n=>{try{let[o,s]=ie(e,["--version"]);Wte(o,s,z({encoding:"utf8",timeout:5e3}),(i,a,l)=>{if(i)return n(null);n(`${a??""} ${l??""}`.match(jte)?.[0]??null)})}catch{n(null)}});return wW.set(e,{at:Date.now(),version:r}),r}async function SW(e,t,r,n=Kte){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 nv(e){let t=xW.get(e)??null,r=Yp(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 tr(e,t,r,n){let o=nv(e);return{engine:e,status:t,version:r,detail:n,lastRoundTrip:Yp(e),lastReadyAt:o===null?null:new Date(o).toISOString()}}async function _W(e,t,r,n,o=Date.now){if(!t.configured&&!r)return null;let s=e==="hermes"?"Hermes":"OpenClaw";if(!t.enabled)return tr(e,"not_enabled",r,`${s}'s local chat API is off`);if(t.key===null)return tr(e,"no_key",r,`${s}'s local chat API has no key set`);let i=`${t.baseUrl}/v1/models`,a=await SW(n,i,t.key||null)??await SW(n,i,t.key||null,$te);if(a===null){let l=nv(e);return l!==null&&o()-l<Hte?tr(e,"ready",r,null):tr(e,"unreachable",r,`${s} is not answering on ${t.baseUrl} \u2014 is its gateway running?`)}return a===401||a===403?tr(e,"no_key",r,`${s} refused the key in its config (HTTP ${a})`):a===404?tr(e,"not_enabled",r,`${s} is running but its chat API is not switched on`):(xW.set(e,o()),tr(e,"ready",r,null))}function Gte(e){let{version:t,signedIn:r}=(e.claudeCode??(()=>({version:Qd("claude-code",e.env),signedIn:Zd(e.env)})))();return t?r?(e.config??E()).chatComputerAccess==="off"?tr("claude-code","access_off",t,"Computer access for chat is off on this computer"):tr("claude-code","ready",t,null):tr("claude-code","not_signed_in",t,"Claude Code is installed but not signed in"):null}async function Jte(e={}){let t=e.env??process.env,r=e.fetchFn??fetch,n=e.versionOf??Vte,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([_W("hermes",Hp(e),i,r,e.now),_W("openclaw",jp(e),a,r,e.now)]);return{v:1,engines:[l,c,Gte(e)].filter(d=>d!==null)}}function qte(e={}){return vl||(Rl&&Date.now()-Rl.at<Ute?Promise.resolve():(vl=Jte(e).then(t=>{Rl={at:Date.now(),report:t}}).catch(()=>{}).finally(()=>{vl=null}),vl))}function ov(){if(qte(),!!Rl)return{v:1,engines:Rl.report.engines.map(e=>{let t=nv(e.engine);return{...e,lastRoundTrip:Yp(e.engine),lastReadyAt:t===null?null:new Date(t).toISOString()}})}}var Ute,Fte,Kte,$te,Hte,jte,wW,xW,Rl,vl,CW=p(()=>{"use strict";j();Je();M();Xa();rv();Gb();Ute=3e4,Fte=10*6e4,Kte=1500,$te=5e3,Hte=3e4,jte=/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/,wW=new Map;xW=new Map;Rl=null,vl=null});import{readdir as Yte,readFile as zte}from"node:fs/promises";import{sep as Xte}from"node:path";import{fileURLToPath as Qte}from"node:url";function rre(e=import.meta.url){let t;try{t=Qte(e)}catch{return"checkout"}return t.split(Xte).includes("node_modules")||t.split("/").includes("node_modules")?"npm":"checkout"}function nre(e){if(typeof e!="string")return null;let t=e.trim();return t&&t.length<=tre?t:null}async function ore(e){try{return nre(JSON.parse(await zte(e,"utf8")).version)}catch{return null}}function sre(e,t){if(!e)return t;try{return Pd(t,e)>0?t:e}catch{return e}}async function ire(e={}){let t={},r=new Set;for(let n of(e.scopeRoots??RN)()){let o=[];try{o=await Yte(n)}catch{continue}for(let s of o)/^[a-z0-9][a-z0-9._-]*$/i.test(s)&&r.add(`${EW}${s}`)}try{for(let n of await(e.adopted??Zy)())n.packageName.startsWith(EW)&&r.add(n.packageName)}catch{}for(let n of[...r].sort().slice(0,ere))for(let o of Ky(n)){let s=await ore(o);s&&(t[n]=sre(t[n],s))}return t}function are(e){sv||ni&&e-ni.at<Zte||(sv=ire().then(t=>{ni={at:Date.now(),packages:t}}).catch(()=>{ni={at:Date.now(),packages:ni?.packages??{}}}).finally(()=>{sv=null}))}function iv(e=Date.now()){try{are(e)}catch{}return{v:1,runtime:{version:Ve,source:rre()},packages:{...ni?.packages??{}}}}var EW,Zte,ere,tre,ni,sv,AW=p(()=>{"use strict";Vr();$y();ek();Fy();EW="@kynver-app/",Zte=10*6e4,ere=40,tre=32;ni=null,sv=null});function lre(e,t,r){if(!t||t===r)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`${n}(?=[\\\\/"'\\s<]|$)`,"gm"),()=>r)}function PW(e,t){return lre(e,t,"\0")!==e}var IW=p(()=>{"use strict"});import{accessSync as cre,constants as ure,existsSync as dre,lstatSync as pre,readdirSync as fre,readFileSync as mre,readlinkSync as gre,realpathSync as hre}from"node:fs";import{homedir as yre}from"node:os";import OW from"node:path";function NW(e){return e==="win32"?OW.win32:OW.posix}function bre(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===av)return n}catch{}let i=r.dirname(n);if(i===n)break;n=i}return null}function Rre(e,t,r){let n=NW(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 wre(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 Sre(e,t,r,n,o){for(let s of wre(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 _re(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 xre(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=NW(t),n=e.fs??kre,o=e.env??process.env,s=e.home??yre(),i=e.execPath??process.execPath,a=n.realpath(e.cliEntry??process.argv[1]??""),l=a?bre(a,n,r):null,c={cliPath:a,packageRoot:l,nodePath:i,npmCliPath:Rre(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(TW).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=vre.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=Sre(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(TW).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",Ei);n.exists(y)&&(g="systemd",d.supervisorFile=y,d.supervisorName=Ei)}else if(t==="darwin"){let y=_re(m,s,n,r);y&&(g="launchd",d.supervisorFile=y.file,d.supervisorName=y.label)}else if(t==="win32"){let y=xre(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=Cre(h,n),h.unsupportedReason||delete h.unsupportedReason,h}function Cre(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&&PW(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 av,kre,TW,vre,Xp=p(()=>{"use strict";Ko();IW();av="@kynver-app/runtime",kre={exists:e=>dre(e),readText:e=>{try{return mre(e,"utf8")}catch{return null}},readDir:e=>{try{return fre(e)}catch{return[]}},realpath:e=>{try{return hre.native(e)}catch{return e}},readLink:e=>{try{return pre(e).isSymbolicLink()?gre(e):null}catch{return null}},writable:e=>{try{return cre(e,ure.W_OK),!0}catch{return!1}}},TW=/[\\/]/;vre=/^(.*)[\\/]releases[\\/]([^\\/]+)[\\/]node_modules[\\/]@kynver-app[\\/]runtime$/});function DW(e){return`npm-${e}`}function Qp(e,t="latest"){let r=`${av}@${t}`;switch(e.kind){case"release_dir":{let n=e.releasesRoot?`${e.releasesRoot}/${DW(t)}`:`<releases>/${DW(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 lv=p(()=>{"use strict";Xp()});var MW=p(()=>{"use strict"});import{mkdirSync as UWe,readFileSync as Ere,readdirSync as FWe,renameSync as KWe,writeFileSync as $We}from"node:fs";import LW from"node:path";function Are(){return LW.join(Ja(),"runtime")}function Pre(e){return LW.join(e,"summary.json")}function BW(e=Are()){try{let t=JSON.parse(Ere(Pre(e),"utf8"));if(t?.v===1)return t}catch{}return{v:1,attempts:0,succeeded:0,rolledBack:0,failed:0,last:null}}var WW=p(()=>{"use strict";Td();MW()});function Ore(e=Date.now()){if(Zp&&e-Zp.at<Ire)return Zp.report;if(!oi){let o=zp();oi={kind:o.kind,supervisor:o.supervisor,can:!o.unsupportedReason,manual:Qp(o,"latest")}}let t=BW(),r=t.last,n={v:1,installKind:oi.kind,supervisor:oi.supervisor,canSelfUpdate:oi.can,manualCommand:oi.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 Zp={at:e,report:n},n}function cv(){try{return Ore()}catch{return}}var oi,Zp,Ire,UW=p(()=>{"use strict";Xp();lv();WW();oi=null,Zp=null,Ire=3e4});import{mkdirSync as Tre,readFileSync as QWe,renameSync as Nre,writeFileSync as Dre}from"node:fs";import{homedir as Mre}from"node:os";import uv from"node:path";function Lre(e=uv.join(Mre(),".kynver","state")){return uv.join(e,"chat-loop.json")}function FW(e,t=Lre()){try{Tre(uv.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;Dre(r,JSON.stringify({v:1,...e}),{mode:384}),Nre(r,t)}catch{}}var KW=p(()=>{"use strict"});import Bre from"node:os";function Wre(e){try{return At().report(e)}catch{return null}}function GW(e,t){try{return SB(e,t)}catch{return}}function dv(e=process.env){let t=E(),r=_t(t,e);return $o({boxKind:r,hostLabel:Bre.hostname(),config:t,env:e})}async function $re(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(),JW);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 Hre(o)}async function Hre(e){let t=new AbortController,r=setTimeout(()=>t.abort(),JW);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 qW(e){return Se()?!0:!!e&&!!im(e)}async function jW(e=process.env){let t=E(),r=t.agentOsId?.trim(),n=Se();if(!r||!qW(r))return null;let o=await $re(t.apiBaseUrl,n,e);if(!o)return null;let s=uo(t),i=t.apiBaseUrl?.replace(/\/$/,"")??o.replace(/\/$/,"");return{bridgeUrl:o.replace(/\/$/,""),agentOsId:r,apiKey:n??"",boxId:dv(e),chatProvider:s,model:js(s,t,e),useClaudeOauth:t.chatUseClaudeOauth===!0,auth:new Ud({apiBaseUrl:i,agentOsId:r,boxLabel:()=>dv(e),loadApiKey:Se,loadBoxCredential:()=>im(r),saveBoxCredential:a=>Zw(r,a),clearBoxCredential:eS}),security:new $d}}function pv(){try{return tS().apiKey}catch{return"none"}}async function jre(e,t,r,n){let o=E(),s=uo(o),i=await fv(e);if(!i.bearer)return"no_credential";let a=up(s,kp(o),GW(s,o),e.security?.report({policy:n,auth:i.kind,credentialStore:pv(),folderSandbox:_k(process.env,o)}),ov(),iv(),cv()),l=Wre(e.agentOsId);l&&(a.browser.siteLogins=l);let c=i.kind==="box_token"?i.boxId:dv();e.chatProvider=s,e.boxId=c,e.model=js(s,o,process.env);let u=new AbortController,d=setTimeout(()=>u.abort(),Fre),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:Ure,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)})),so(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=kB(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 vt(e,t,r){let n=await fv(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 so(e,n,o.status),o.ok}async function VW(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??{}})),Qa({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 vt(e,t.turnId,[{seq:0,kind:"error",error:T0(r.code,r.detail)}]).catch(()=>{}),{ok:!1}}async function Vre(e,t,r){let n=N0({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}):VW(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=E()}catch{o={}}let s=dD({signedAccess:n.access,boxId:e.boxId,agentOsId:e.agentOsId,engine:Xd(e.chatProvider,o,r.env??process.env),local:{chatComputerAccess:o.chatComputerAccess,chatWorkFolders:o.chatWorkFolders},state:Yd(r.stateFile),env:r.env,nowSec:r.nowSec});if(!s.ok)return VW(e,t,{code:s.code,detail:s.detail,reason:s.reason,policy:r.policy,extra:{from:za(s.from),to:za(s.to),signed:n.signed}});s.website&&sD(s.website,{file:r.stateFile});let a={...mk(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 Gre(e,t){let r=0,n=!1,o=new co,s=Array.isArray(t.payload?.argv)?t.payload.argv:[],i=await wD(s,a=>{n||o.track(vt(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 vt(e,t.turnId,[{seq:r++,kind:"error",error:`command_refused: ${i.refused}`}]).catch(()=>{}):await vt(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 Jre(e,t,r,n,o){try{let s=ho({provider:t.chatProvider,config:n,payloadAccess:e.payload.computerAccess,boxId:t.boxId}),i=oD(s.access,{signed:r.signed});if(!i)return;let a=i.from?za(i.from.access):"not set",l=za(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};Qa({...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 qre(e,t,r){let n=0,o=!1,s=new co,i=new AbortController,a=t.requestId??"",l=h=>{o||s.track(vt(e,t.turnId,[{seq:n++,kind:"delta",text:h}]).then(y=>(y||(o=!0,i.abort()),y)))},c=new ln(l),u=$p({turnId:t.turnId,chat:a||null,send:h=>{o||(c.flush(),s.track(vt(e,t.turnId,[{seq:n++,kind:"activity",activity:h}]).then(y=>(y||(o=!0,i.abort()),y))))}}),d=e.chatProvider??"anthropic",f=E(),m=kp(f);r&&Jre(t,e,r,f,h=>{o||s.track(vt(e,t.turnId,[{seq:n++,kind:"activity",activity:h}]).then(y=>(y||(o=!0,i.abort()),y)))});try{Rb(d,e.useClaudeOauth,process.env,f)}catch(h){let y=ul(t.payload.requestedModel);if(!(y&&m.some(k=>k.provider===y.provider&&k.models.includes(y.model)))){await vt(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 kL({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},yL({...k,signal:i.signal,turnId:t.turnId,requestId:t.requestId,useClaudeOauth:e.useClaudeOauth,config:f,boxId:e.boxId,onActivity:u.sink}))});CB(h.content,ho({provider:g.provider,config:f,payloadAccess:t.payload.computerAccess,boxId:e.boxId}),u),c.close(),await s.drain();let y=n++;if(!await ri(()=>o?vt(e,t.turnId,[{seq:y,kind:"error",error:"turn_stream_aborted"}]).catch(()=>!1):vt(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 vt(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 wl(e,t){for(let n=0;n<e&&!t();n+=500)await new Promise(o=>setTimeout(o,Math.min(500,e-n)))}async function YW(e){let t=await jW(),r=()=>qW(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:HW}));!t&&!e.shouldStop();){if(!r()||(await wl(HW,e.shouldStop),e.shouldStop()))return;t=await jW()}if(!t||e.shouldStop())return;let n=O0(process.env,E()),o=new Kd;t.security&&(t.security.childEnv=await eD().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:up(t.chatProvider),useClaudeOauth:t.useClaudeOauth,turnSignature:n,credentialStore:pv(),childEnvSafe:t.security?.childEnv?.ok??null,auth:t.auth?.describe().kind??"api_key"}));let s=0,i=0,a=new Kp,l=OB({target:t,capabilities:u=>{let d=E(),f=uo(d);return up(f,kp(d),GW(f,d),t.security?.report({policy:n,auth:u.kind,credentialStore:pv(),folderSandbox:_k(process.env,d)}),ov(),iv(),cv())},onBeat:u=>FW({pid:process.pid,runtimeVersion:Ve,at:new Date().toISOString(),heartbeatOk:u,chatTurns:Math.max(0,s-i),commandTurns:i})}),c=Promise.resolve();for(;!e.shouldStop();)try{if(s>=Kre){await wl(250,e.shouldStop);continue}let u=await jre(t,e.shouldStop,a.snapshot(),n);if(u==="no_credential"){console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:"machine_not_linked"})),await wl($W,e.shouldStop);continue}if(u==="auth_error"){a.onAuthError();let d=t.auth?.describe().hasBoxCredential===!0;await wl(d?5e3:$W,e.shouldStop);continue}if(a.onSuccess(),u){let d=await PB(t,u.turnId);if(!AB(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=()=>Gre(t,u);m=c.then(g,g),c=m.then(()=>{},()=>{})}else{let g=await Vre(t,u,{policy:n,nonces:o});if(!g.ok){s-=1;continue}if(o.markStarted(u.turnId),f==="browser"){let h=await fv(t);m=mB({...t,apiKey:h.bearer},{turnId:u.turnId,payload:g.payload})}else f==="agent-tab"?m=vW(h=>vt(t,u.turnId,h),{turnId:u.turnId,payload:g.payload,boxId:t.boxId}):m=qre(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=wB(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 wl(m,e.shouldStop)}l(),await dB(),console.error(JSON.stringify({event:"chat_claim_loop_stop"}))}var Ure,Fre,$W,HW,JW,Kre,fv,zW=p(()=>{"use strict";j();Me();A0();Fd();hk();D0();M0();qd();tD();iD();pD();Xa();ep();Ho();tp();Mk();SD();el();rM();Xk();Qk();wb();bL();gB();Kb();Hb();jb();_B();Vb();EB();xp();IB();TB();RW();CW();AW();Vr();UW();KW();Hb();Fi();Ure=2e4,Fre=32e3,$W=6e4,HW=5*6e4,JW=5e3,Kre=3,fv=Fs});import{createHash as Yre}from"node:crypto";import{chmodSync as XW,existsSync as zre,mkdirSync as Xre,rmSync as QW}from"node:fs";import{createConnection as Qre,createServer as Zre}from"node:net";import{homedir as ene,userInfo as tne}from"node:os";import rne from"node:path";function one(e,t=process.platform){return t==="win32"?`\\\\.\\pipe\\kynver-site-logins-${Yre("sha256").update(`${tne().username}:${ene()}`).digest("hex").slice(0,16)}`:rne.join(e,"control.sock")}async function sne(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 ine(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 ZW(e){let t=one(e.rootDir);if(process.platform!=="win32"){Xre(e.rootDir,{recursive:!0,mode:448});try{XW(e.rootDir,448)}catch{}if(zre(t)){if(await ane(t))return null;QW(t,{force:!0})}}let r=Zre(n=>{let o="";n.setEncoding("utf8"),n.setTimeout(12e4,()=>n.destroy()),n.on("data",s=>{if(o+=s,o.length>nne)return void n.destroy();let i=o.indexOf(`
|
|
526
|
+
`);if(i<0)return;let a=ine(o.slice(0,i));o="";let l=c=>n.end(`${JSON.stringify(c)}
|
|
527
|
+
`);if(!a)return l({ok:!1,error:"malformed request"});sne(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{XW(t,384)}catch{}return{path:t,close:()=>new Promise(n=>{r.close(()=>n()),process.platform!=="win32"&&QW(t,{force:!0})})}}function ane(e){return new Promise(t=>{let r=Qre(e),n=o=>{r.destroy(),t(o)};r.once("connect",()=>n(!0)),r.once("error",()=>n(!1)),setTimeout(()=>n(!1),1e3).unref?.()})}var nne,eU=p(()=>{"use strict";Tn();nne=16*1024});function une(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":Vs(e.platform,e.arch)?null:"unsupported_platform"}async function tU(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 rU(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??(()=>mo({env:t,platform:r,arch:n})),a=e.loadConfig??E;try{await tU(e.startDelayMs??lne,e);for(let l=1;l<=cne&&!e.shouldStop();l+=1){let c=une({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=YD(go());if(u>o()&&await tU(u-o(),e),e.shouldStop())return;s({event:"browser_autoprovision_start",attempt:l});try{let d=await(e.provision??ap)({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 lne,cne,nU=p(()=>{"use strict";j();po();nl();lp();lne=6e4,cne=5});function mv(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(e.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function mne(e,t){let r=mv(e),n=mv(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 gne(e,t,r={}){let n=r.manual??`${ef} 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 hne(){try{let e=zp();return{manual:Qp(e,"latest"),selfUpdate:!e.unsupportedReason}}catch{return{manual:`${ef} then restart Kynver (or restart the computer)`,selfUpdate:!1}}}async function yne(e={}){let t=e.installed??Ve,r={installed:t,latest:null,outdated:!1,command:ef};if((e.env??process.env).KYNVER_DISABLE_UPDATE_CHECK==="1")return r;let o=new AbortController,s=setTimeout(()=>o.abort(),pne);try{let a=await(e.fetch??fetch)(dne,{signal:o.signal,headers:{accept:"application/json"}});if(!a.ok)return r;let l=await a.json(),c=typeof l?.version=="string"&&mv(l.version)?l.version:null;return c?{installed:t,latest:c,outdated:mne(t,c),command:ef}:r}catch{return r}finally{clearTimeout(s)}}function sU(e={}){let t=e.log??(s=>console.error(s)),r=null,n=async()=>{let s=await yne(e);if(s.outdated&&s.latest&&s.latest!==r){r=s.latest;let i=(e.advice??hne)();t(JSON.stringify({event:"runtime_update_available",installed:s.installed,latest:s.latest,command:i.manual,selfUpdate:i.selfUpdate})),t(gne(s.installed,s.latest,i))}return s};n().catch(()=>{});let o=setInterval(()=>{n().catch(()=>{})},e.intervalMs??fne);return o.unref?.(),{stop:()=>clearInterval(o),checkNow:n}}var oU,ef,dne,pne,fne,iU=p(()=>{"use strict";Vr();lv();Xp();oU="@kynver-app/runtime",ef=`npm install -g ${oU}@latest`,dne=`https://registry.npmjs.org/${oU}/latest`,pne=5e3,fne=360*6e4});var uU={};Tv(uU,{adoptOrAcquireOwnerLease:()=>lU,completeWorker:()=>SP,dispatchRun:()=>Is,resolveDaemonOwnerKind:()=>aU,runDaemon:()=>cU,runPipelineTick:()=>Md,sweepRun:()=>fd});async function gv(e,t,r){let n=e;for(;n>0&&!t();){let o=Math.min(Rne,n),s=Date.now();await Ll(o);let i=Hm(o,Date.now()-s);if(i!==null){r?.(i);return}n-=o}}function aU(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 lU(e,t,r,n=jc){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 cU(e,t={}){let r=rg({hostCapability:t.hostCapability}),n=Xe()?{loaded:0}:pw();n.loaded>0&&console.error(JSON.stringify({event:"daemon_env_file_loaded",...n}));let o=String(e.run||"").trim();o||(console.error(Ym("--run")),process.exit(1));let s=String(e.agentOsId||E().agentOsId||"").trim();s||(console.error(Ym("--agent-os-id")),process.exit(1)),Yo(s).ok||(console.error(nm(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)):kne,c=!1,u=0,d=aS(O=>{c||console.error(JSON.stringify({event:"daemon_stop_requested",reason:O,runId:o})),c=!0}),f=await lU(s,aU(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;vw(m.metadata.ownerKind),fx({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=ax(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=Qw();(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=j_();k.remediated&&console.error(JSON.stringify({event:"daemon_default_repo_remediated",defaultRepo:k.resolved?.defaultRepo??null,configPath:k.configPath}));let b=sx(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})),sU();let _=es(),S=new Wd;S.start();let R=new Bd({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=ZW(At()).catch(()=>null),L=YW({shouldStop:()=>c}).catch(O=>{console.error(JSON.stringify({event:"chat_claim_loop_crashed",error:O instanceof Error?O.message:String(O)}))});rU({shouldStop:()=>c});let I=!1;for(;!c;)try{if(y!==null){let N=y;y=null;let D=m.isHeld();if(console.error(JSON.stringify({event:"daemon_resume_detected",agentOsId:s,gapMs:N,ownerLeaseHeld:D})),!D){console.error(JSON.stringify({event:"daemon_owner_lease_lost",agentOsId:s,runId:o})),process.exitCode=1,c=!0;break}}S.setPhase("heartbeat"),m.renew(),b_({agentOsId:s,runId:o,instructionBundleVersion:Dn(),owner:g}),S.setPhase("runner_credential");let O=await xc(e.secret?String(e.secret):void 0,s,{baseUrl:e.baseUrl?String(e.baseUrl):void 0});if(!O.ok){I||(I=!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 gv(l,()=>c,v);continue}I&&(I=!1,console.error(JSON.stringify({event:"daemon_runner_credential_recovered",agentOsId:s}))),S.setPhase("instruction_bundle"),await rx({agentOsId:s,baseUrl:En(e.baseUrl?String(e.baseUrl):void 0),secret:O.secret}),S.setPhase(R.mode==="thread"?"pipeline_tick_thread":"pipeline_tick_inline");let U=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(U.isolation);let W=U.tick;S.setPhase("tick_log"),console.error(JSON.stringify({event:"daemon_tick",tickIsolation:U.isolation,...W})),S.setPhase("runtime_control");let G=Kr(s),ee=U.inFlightWorkers??Ld(s)??0;if(kw(G,ee)){let N=dc({control:G,supervisor:m.metadata.ownerKind,inFlightWorkers:0,exiting:!0}),D=En(e.baseUrl?String(e.baseUrl):void 0),F=N&&D?await m_({baseUrl:D,agentOsId:s,secret:O.secret},N):!1;console.error(JSON.stringify({event:"daemon_runtime_stopped",agentOsId:s,runId:o,policyVersion:G?.policyVersion??null,requestedBy:G?.requestedByLabel??null,reported:F})),process.exitCode=uc,c=!0;break}if(_.tickEnabled){S.setPhase("cron_tick");let N=Zc(o);if(N&&!N.authorized)console.error(JSON.stringify({event:"daemon_cron_tick_skipped",reason:"mesh_cron_lease_not_authorized",holderBoxId:N.holderBoxId}));else{let D=await lg({env:_,agentOsIdFilter:s});D.enabled&&(D.fired>0||D.errors>0||D.lockHeld)&&console.error(JSON.stringify({event:"daemon_cron_tick",...D}))}}W.idle?u++:u=0;let T=Math.floor(os("daemon.maxIdleStreak",vne)),x=Math.floor(os("daemon.idleIntervalMs",bne)),H=u>=T?x:l;S.setPhase("idle"),await gv(H,()=>c,v)}catch(O){console.error(JSON.stringify({event:"daemon_tick_error",error:O.message})),S.setPhase("idle"),await gv(l,()=>c,v)}S.setPhase("stopping"),await L,await R.close(),S.stop(),await(await w)?.close().catch(()=>{}),At().lock();let A=lS(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 kne,bne,vne,Rne,hv=p(()=>{"use strict";j();zm();V_();nx();Gr();ix();$m();Ic();Vc();wt();jm();lx();Xc();ng();cg();gr();cr();ug();M();x0();pk();E0();zW();Fi();eU();nU();iU();$r();Km();dk();Tu();vy();Es();kne=6e4,bne=5*6e4,vne=10,Rne=250});var dU=p(()=>{"use strict";Y();Oo();ky();xe();M()});var Sl,pU=p(()=>{"use strict";Sl=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 wne,mkdirSync as Sne}from"node:fs";import _ne from"node:path";function xne(e){let t=typeof e.repo=="string"?e.repo.trim():"";if(t)return t;let r=Gi();return r?r.repo:(St("","--repo (or set defaultRepo via `kynver setup` / KYNVER_DEFAULT_REPO)"),"")}function Cne(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 Ene(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 Ane(e,t){let r=E();try{return Cne({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:()=>Ene(e),repoLabel:e})}catch(n){throw new Sl(n.message,{remedy:"Diagnose: run `kynver doctor runner-install`.",cause:n})}}function yv(e){let t=pP(xne(e));Vv(t);let r=e.id?Nh(String(e.id)):Tl(String(e.name||"run")),n=V(r);wne(n)&&Pne(`run already exists: ${r}`),Sne(n,{recursive:!0});let o=Ane(t,e);o.note&&console.error(o.note);let s=o.base,i=le(t,["rev-parse",s]).trim(),a=Lt(),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}:{}};ke(_ne.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 Pne(e){throw new Sl(e)}var kv=p(()=>{"use strict";Re();Y();dU();M();ls();id();wn();j();pU()});function fU(e,t){return e.filter(n=>n.repo===t&&!Or.has(n.status)).sort((n,o)=>(o.createdAt??"").localeCompare(n.createdAt??""))[0]??null}var mU=p(()=>{"use strict";Re();rn()});var gU=p(()=>{"use strict";gr();ts();ag()});var tf=p(()=>{"use strict";gr();cr()});var rf=p(()=>{"use strict"});var bv=p(()=>{"use strict"});var vv=p(()=>{"use strict";gU();gr();ts();tf();cr();rf();bv()});var hU=p(()=>{"use strict"});var yU=p(()=>{"use strict";tf();rf()});var kU=p(()=>{"use strict";cr();gr()});var bU=p(()=>{"use strict";j();it();wt();M();cg();hU();yU();cr();tf();kU();cc();Ko();ts();vv();rf();bv();Y()});var vU=p(()=>{"use strict";vv();bU()});var RU=p(()=>{"use strict";Ko();cc();j();cr();pc();jf();Ai();Y()});function wU(e,t){return fU(e,t)?.id??null}var SU=p(()=>{"use strict";j();Om();hv();zm();ng();Vc();kv();Y();mU();ls();vU();Fm();qf();ls();el();RU()});var AU={};Tv(AU,{prepareDesktopRuntime:()=>Gne,resolveDesktopRepository:()=>EU});import{spawnSync as _U}from"node:child_process";import{randomBytes as Mne}from"node:crypto";import{existsSync as Lne,mkdirSync as Bne,readFileSync as Wne,realpathSync as xU,statSync as Une,writeFileSync as Fne}from"node:fs";import{homedir as Kne}from"node:os";import wv from"node:path";function be(e,t){return{ok:!1,code:e,message:t}}function $ne(){return wv.join(Kne(),".kynver","desktop-binding.json")}function Hne(e){if(!Lne(e))return null;try{let t=JSON.parse(Wne(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 jne(e,t){Bne(wv.dirname(e),{recursive:!0}),Fne(e,`${JSON.stringify(t,null,2)}
|
|
528
|
+
`,{mode:384})}function CU(e,t){return e===401||e===403?be("access_denied",`${t} was refused (${e})`):e===0?be("network",`${t} could not reach Kynver`):be("server_error",`${t} failed (${e})`)}async function Rv(e,t,r,n={}){try{let o=await ct(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 Vne(e){return(e?.accessibleItems??[]).filter(t=>t.access?.isOwner===!0&&typeof t.agentOs?.id=="string").map(t=>(t.agentOs?.id).trim()).filter(Boolean)}function EU(e,t="git"){let r=_U(t,["--version"],z({encoding:"utf8"}));if(r.error||r.status!==0)return be("no_git","Git is not installed or not on PATH");let n;try{if(n=xU.native(wv.resolve(e)),!Une(n).isDirectory())return be("not_a_repository","The selected path is not a folder")}catch{return be("not_a_repository","The selected folder does not exist")}let o=_U(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 be("not_a_repository","The selected folder is not inside a Git working tree");try{return{ok:!0,repo:xU.native(s[1].trim())}}catch{return be("not_a_repository","The Git working tree root could not be resolved")}}async function Gne(e,t={}){let r=t.fetchImpl??fetch,n=t.acquireOwnerLease??jc,o=t.bindingPath??$ne(),s=[],i=or(e.apiBaseUrl);if(!i)return be("invalid_input","apiBaseUrl is required");let a=mi(i),l=new URL(a).origin;if(e.agentOsId!==void 0&&!Yo(e.agentOsId).ok)return be("invalid_input","agentOsId is not a valid workspace id");let c;try{c=Se()}catch(S){if(S instanceof ii)return be("credentials_unavailable","This computer's credentials have not been provided");throw S}if(!c)return be("credentials_unavailable","This computer is not paired");let u=await Rv(`${a}/api/users/me`,c,r);if(u.status!==200)return CU(u.status,"Account lookup");let d=typeof u.body?.id=="string"?u.body.id:"";if(!d)return be("server_error","Account lookup returned no account id");if(e.expectedAccountId&&e.expectedAccountId!==d)return be("account_mismatch","The paired credentials belong to a different account");let f=await Rv(`${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 Rv(`${a}/api/agent-os`,c,r);if(g.status!==200)return CU(g.status,"Workspace lookup");let h=g.body,y;if(e.agentOsId){if(!Vne(h).includes(e.agentOsId))return be("agent_os_not_owned","That workspace is not owned by the paired account");y=e.agentOsId}else{let S=Pm(h);if(!S?.id)return be("no_workspace","No workspace owned by this account was found");y=S.id}let v=EU(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{Be({...E(),apiBaseUrl:a,agentOsId:y,defaultRepo:k});let S=Um(E());s.push(...S.warnings);let R=E().boxId?.trim()??"";if(!R)return _.release(),be("local_state_error","Box identity could not be established");if(await Tm(jr()),!Ie(y))try{let U=await An(y,{baseUrl:a,apiKey:c});Cn(y,U)}catch(U){let W=U.message;if(qS(W)==="access_denied")return _.release(),be("access_denied","This computer was refused a runner credential");s.push("runner credential mint did not succeed yet; the runtime retries automatically")}let w=Hne(o),L=w!==null&&w.cloudOrigin===l&&w.accountId===d&&w.agentOsId===y&&w.repo===k,I="";if(L){let U=wU(we().filter(W=>W.id===w.runId),k);U&&(I=U)}if(!I){let U=`${Tl("desktop")}-${Mne(3).toString("hex")}`;I=yv({repo:k,name:"desktop",id:U}).runId}jne(o,{version:1,cloudOrigin:l,accountId:d,agentOsId:y,repo:k,runId:I});let A=Dc(k);A||s.push("the repository has no origin remote; nothing can run until it has one");let{runnerId:O}=Te({runId:I});return{ok:!0,prepared:{accountId:d,agentOsId:y,runId:I,repo:k,boxId:R,repoIdentity:A,runnerId:O},lease:_,warnings:s}}catch(S){return _.release(),be("local_state_error",S.message)}}var PU=p(()=>{"use strict";sr();Om();Im();j();wt();gr();ts();Vc();Mc();Y();yr();Fm();SU();kv();M()});wt();import{pathToFileURL as Jne}from"node:url";var Wv="credential.persist";function Uv(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:Wv,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:Wv,kind:"runnerToken",agentOsId:a,value:l})},reseed:o}}Ic();Mc();Tn();Cm();var BS=/^lg_[a-z0-9]{6,20}$/,oj=/^cr_[0-9a-f]{12}$/,sj=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Nn=(e,t,r=1)=>typeof e=="string"&&e.length>=r&&e.length<=t&&!e.includes("\0");function Zo(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function WS(e){let t=["v","type","id","agentOsId","op"];switch(e.op){case"key":return Zo(e,[...t,"key"])??(Nn(e.key,64,40)&&/^[A-Za-z0-9+/]{43}=$/.test(e.key)?{op:"key",key:e.key}:"invalid key");case"list":case"wipe":return Zo(e,t)??{op:e.op};case"remove":return Zo(e,[...t,"handle"])??(typeof e.handle=="string"&&BS.test(e.handle)?{op:"remove",handle:e.handle}:"invalid handle");case"code":{let r=Zo(e,[...t,"requestId","code"]);return r||(e.requestId!==void 0&&!(typeof e.requestId=="string"&&oj.test(e.requestId))?"invalid requestId":Nn(e.code,16)?{op:"code",code:e.code,...e.requestId?{requestId:e.requestId}:{}}:"invalid code")}case"add":{let r=Zo(e,[...t,"login","replaceHandle"]);if(r)return r;let n=e.login;return!sj(n)||Zo(n,["origin","label","username","password","totp"])||!Nn(n.origin,2048)||!Nn(n.label,dt.maxLabel)||!Nn(n.username,dt.maxUsername)||!Nn(n.password,dt.maxPassword)||n.totp!==void 0&&!Nn(n.totp,dt.maxTotp,0)?"invalid login":e.replaceHandle!==void 0&&!(typeof e.replaceHandle=="string"&&BS.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 US(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)}}}Fi();Tn();var qne=1,nf=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,si=/^[A-Za-z0-9_-]{1,64}$/,Yne=/^[a-z0-9][a-z0-9._-]{0,127}$/i,IU=4096,zne=4096,Xne=16;function Sv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function _l(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function xl(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!e.includes("\0")}function Qne(e){if(!xl(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 Zne(e){if(!Sv(e))return{ok:!1,message:"message must be an object"};if(e.v!==qne)return{ok:!1,message:"unsupported protocol version"};let t=r=>({ok:!1,message:r});switch(e.type){case"credentials":{let r=_l(e,["v","type","apiKey","runnerTokens"]);if(r)return t(r);if(e.apiKey!==void 0&&!xl(e.apiKey,IU))return t("invalid apiKey");let n;if(e.runnerTokens!==void 0){if(!Sv(e.runnerTokens))return t("invalid runnerTokens");let o=Object.entries(e.runnerTokens);if(o.length>Xne)return t("too many runnerTokens");n={};for(let[s,i]of o){if(!nf.test(s)||!xl(i,IU))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=_l(e,["v","type","id","apiBaseUrl","repo","agentOsId","expectedAccountId"]);return r?t(r):typeof e.id!="string"||!si.test(e.id)?t("invalid id"):Qne(e.apiBaseUrl)?xl(e.repo,zne)?e.agentOsId!==void 0&&(typeof e.agentOsId!="string"||!nf.test(e.agentOsId))?t("invalid agentOsId"):e.expectedAccountId!==void 0&&!xl(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=_l(e,["v","type","id","policy"]);if(r)return t(r);if(typeof e.id!="string"||!si.test(e.id))return t("invalid id");let n=gS(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=_l(e,["v","type","id","runId","agentOsId"]);return r?t(r):typeof e.id!="string"||!si.test(e.id)?t("invalid id"):typeof e.runId!="string"||!Yne.test(e.runId)?t("invalid runId"):typeof e.agentOsId!="string"||!nf.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"||!si.test(e.id))return t("invalid id");if(typeof e.agentOsId!="string"||!nf.test(e.agentOsId))return t("invalid agentOsId");let r=WS(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=_l(e,["v","type","id"]);return r?t(r):typeof e.id!="string"||!si.test(e.id)?t("invalid id"):{ok:!0,value:{v:1,type:e.type,id:e.id}}}default:return t("unknown message type")}}function eoe(e){return Sv(e)&&typeof e.id=="string"&&si.test(e.id)?e.id:null}function toe(e){let t=Lv()?"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(lm(l))return;let c=Zne(l);if(!c.ok){s(eoe(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=Uv(d,f=>e.send(f)),Mv(r)),t==="awaiting_credentials"&&(t="ready"),e.send({v:1,type:"event",name:"credentials_accepted",state:t});return}case"status":{let d=mm();i(u.id,{state:t,prepared:n,policyRevision:d?.revision??null});return}case"policy":{if(!kS(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,bS({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=mm();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 US(At(),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 roe(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}Dv();for(let s of Nv)delete e.env[s];let[{prepareDesktopRuntime:t},{runDaemon:r}]=await Promise.all([Promise.resolve().then(()=>(PU(),AU)),Promise.resolve().then(()=>(hv(),uU))]),n=s=>{if(!e.connected||typeof e.send!="function")throw new Error("desktop IPC channel is closed");e.send(s)},o=toe({send:n,prepare:s=>t(s),runDaemon:r,requestDaemonStop:()=>{e.emit("message",{type:Pc},void 0)},exit:s=>e.exit(s),daemonExitCode:()=>typeof e.exitCode=="number"?e.exitCode:0});vS(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{}}),At().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:Pc},void 0);return}e.exit(0)}),n({v:1,type:"event",name:"ready",state:o.state})}function noe(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===Jne(e).href}catch{return!1}}noe()&&roe();export{qne as DESKTOP_ENTRY_PROTOCOL_VERSION,toe as createDesktopEntryController,Zne as parseDesktopEntryMessage,roe as startDesktopEntry};
|