@kynver-app/runtime 0.2.141 → 0.2.144
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 +208 -208
- package/dist/desktop-entry.js +158 -158
- package/dist/index.js +232 -232
- package/package.json +1 -1
package/dist/desktop-entry.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
1
|
+
var w$=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 uw=(e,t)=>{for(var r in t)w$(e,r,{get:t[r],enumerable:!0})};function pw(){Vo=!0}function it(){return Vo}function fw(e){if(!Vo)throw new Error("installDesktopCredentialProvider requires desktop credential mode");if(e.kind!=="desktop")throw new Error("only a desktop credential provider may be installed");if(Bi)throw new Error("desktop credential provider is already installed");Bi=e}function mw(){return Bi!==null}function gw(e){if(!Vo)return e;if(!Bi)throw new Li;return Bi}function Ne(e,t=process.env){if(Vo)return;let r=t[e]?.trim();return r||void 0}function _m(){if(Vo)throw new Sm}var dw,Li,Sm,Vo,Bi,Tt=p(()=>{"use strict";dw=["KYNVER_API_KEY","KYNVER_RUNNER_TOKEN","KYNVER_CHAT_BOX_CREDENTIAL","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","OPENCLAW_RUNNER_TOKEN"],Li=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},Sm=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},Vo=!1,Bi=null});import{homedir as xm}from"node:os";import Un from"node:path";function pc(e){return e==="~"?xm():e.startsWith("~/")||e.startsWith("~\\")?Un.join(xm(),e.slice(2)):e}function De(e){return Un.resolve(pc(e))}function S$(e){let t=pc(e),r=Un.resolve(t),n=Un.resolve(xm());return r===n?"~":r.startsWith(`${n}${Un.sep}`)?`~/${Un.relative(n,r).split(Un.sep).join("/")}`:r.replace(/\\/g,"/").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^[A-Za-z]:\/home\/[^/]+(?=\/|$)/i,"~").replace(/^[A-Za-z]:\/Users\/[^/]+(?=\/|$)/i,"~")}function ze(e){return S$(e)}var ht=p(()=>{"use strict"});import{spawnSync as _$}from"node:child_process";function E$(e){return["/PID",String(e),"/T","/F"]}function A$(e){return e.error?{method:"taskkill",outcome:"failed",detail:e.error.message}:e.status===0?{method:"taskkill",outcome:"signalled"}:e.status===x$||/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 I$(e){let t=_$("taskkill",e,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","pipe"],timeout:C$});return{status:t.status,stderr:t.stderr??"",...t.error?{error:t.error}:{}}}function P$(e){return Number.isInteger(e)&&e>0}function he(e,t="SIGTERM",r={}){if(!P$(e))return{method:"none",outcome:"not_found"};if((r.platform??process.platform)==="win32"){let s=r.runTaskkill??I$;return A$(s(E$(e)))}let o=r.kill??((s,i)=>{process.kill(s,i)});try{return o(-e,t),{method:"group",outcome:"signalled"}}catch{}try{return o(e,t),{method:"pid",outcome:"signalled"}}catch(s){let i=s.code;return i==="ESRCH"?{method:"pid",outcome:"not_found"}:{method:"pid",outcome:"failed",detail:i??s.message}}}function Re(e=process.platform){return e!=="win32"}function at(e,t="SIGTERM",r={}){if((r.platform??process.platform)==="win32"&&e.pid){he(e.pid,t,r);return}try{e.kill(t)}catch{}}var x$,C$,Go=p(()=>{"use strict";x$=128,C$=15e3});import{existsSync as O$,mkdirSync as T$,readFileSync as kw,readdirSync as wle,renameSync as N$,rmSync as D$,statSync as bw,writeFileSync as M$}from"node:fs";import{randomBytes as L$}from"node:crypto";import B$ from"node:path";function yt(e){console.error(e),process.exit(1)}function Z(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function Nt(e,t){return e||yt(`missing ${t}`),e}function Ui(e){try{return JSON.parse(e)}catch{return null}}function K(e,t){try{return JSON.parse(kw(e,"utf8"))}catch(r){if(arguments.length>1)return t;yt(`failed to read ${e}: ${r.message}`)}}function we(e,t){T$(B$.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${L$(4).toString("hex")}.tmp`;try{M$(r,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`),N$(r,e)}catch(n){try{D$(r,{force:!0})}catch{}throw n}}function F(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function fc(e){return F(`${new Date().toISOString().replace(/[-:]/g,"").replace(/\..+/,"Z")}-${e}`)}function Fn(e){return String(e).replace(/\/+$/,"")}function mc(e){try{return bw(e).size}catch{return 0}}function gc(e){try{return bw(e).mtime.toISOString()}catch{return null}}function Jo(e,t){return O$(e)?kw(e,"utf8").split(`
|
|
3
3
|
`).slice(-t).join(`
|
|
4
|
-
`):""}function
|
|
5
|
-
`).map(t=>t.trim()).filter(Boolean)}function re(e,t){try{let r=yw("git",t,te({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 hw(e,t,r){let n=re(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 yc(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 Jo(n,"missing worktree path");let s=re(e,["rev-parse","HEAD"]);if(s.status!==0)return Jo(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let f=re(e,["rev-parse",n]);if(f.status!==0)return Jo(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=hw(e,i,a),c=hw(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 Jo(e,t,r=null){return{checked:!1,base:e,head:r,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:t}}var _e=p(()=>{"use strict";gt();B();Fi()});import{existsSync as $$,mkdirSync as bw}from"node:fs";import{homedir as xm}from"node:os";import qo from"node:path";function Rw(e=xm()){return qo.join(e,".kynver",H$)}function ww(e,t=xm()){return qo.resolve(e)===qo.resolve(Rw(t))}function j$(e){re(e,["config","--get","user.email"]).status!==0&&re(e,["config","user.email","kynver@local"]),re(e,["config","--get","user.name"]).status!==0&&re(e,["config","user.name","Kynver"])}function vw(e){re(e,["rev-parse","--verify","HEAD^{commit}"]).status!==0&&(j$(e),re(e,["commit","--allow-empty","-m","kynver byoc workspace"]))}function Sw(e=xm()){let t=Rw(e);bw(qo.dirname(t),{recursive:!0});let r=!1;$$(t)||(bw(t,{recursive:!0}),r=!0);let n=re(t,["rev-parse","--show-toplevel"]);if(n.status!==0)return re(t,["init","-b",kc]).status!==0&&(re(t,["init"]),re(t,["symbolic-ref","HEAD",`refs/heads/${kc}`])),vw(t),r=!0,{repo:qo.resolve(t),created:r};let o=qo.resolve(n.stdout.trim()||t);return vw(o),{repo:o,created:r}}var H$,kc,Cm=p(()=>{"use strict";_e();H$="workspace",kc="main"});import{existsSync as Am,readFileSync as xw}from"node:fs";import{homedir as Cw}from"node:os";import yt from"node:path";import{fileURLToPath as V$}from"node:url";function J$(e){let t=yt.join(e,"package.json");if(!Am(t))return null;try{let r=JSON.parse(xw(t,"utf8"));return typeof r.name=="string"?r.name.trim():null}catch{return null}}function Ew(e){return J$(e)==="kynver"}function _w(e){let t=yt.resolve(e);if(!Am(t))return null;let r=re(t,["rev-parse","--show-toplevel"]);if(r.status!==0)return null;let n=r.stdout.trim();return n.length?yt.resolve(n):null}function q$(e=import.meta.url){let t=yt.dirname(V$(e));for(let r=0;r<8;r+=1){let n=yt.join(t,"package.json");if(Am(n))try{if(JSON.parse(xw(n,"utf8")).name==="@kynver-app/runtime")return t}catch{}let o=yt.dirname(t);if(o===t)break;t=o}return null}function Em(e,t,r,n,o){if(!r)return;let s=yt.resolve(r);e.has(s)||(o?.requireMonorepo??!0)&&!Ew(s)||(e.add(s),t.push({repo:s,source:n}))}function Aw(e){let t=e?.cwd??process.cwd(),r=new Set,n=[];Em(r,n,_w(t),"cwd_git",{requireMonorepo:!1});let o=q$(e?.runtimeModuleUrl??import.meta.url);o&&Em(r,n,_w(o),"runtime_checkout");let s=Cw();for(let a of G$)Em(r,n,Ne(yt.join(s,a)),"well_known_path");let i=yt.resolve(e?.cwd??process.cwd());return n.filter(a=>{if(a.source!=="runtime_checkout"||!Ew(a.repo))return!0;let l=yt.resolve(a.repo);return i===l||i.startsWith(`${l}${yt.sep}`)})}function bc(e){return Aw(e)[0]??null}function Y$(e){let t=yt.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 vc(e){let t=Aw(e),r=t.find(o=>!Y$(o.repo));if(r)return r;if(t[0])return t[0];let{repo:n}=Sw(e?.home??Cw());return{repo:n,source:"byoc_workspace"}}var G$,Ki=p(()=>{"use strict";_e();gt();Cm();G$=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});import{existsSync as Ow,readFileSync as z$}from"node:fs";import Fn from"node:path";function Q$(e){return e.includes("/")||e.includes("\\")}function Z$(e){return(e.PATHEXT||X$).split(";").map(t=>t.trim().toLowerCase()).filter(t=>t.startsWith("."))}function eH(e){let t=Object.keys(e).find(r=>r.toUpperCase()==="PATH");return t?e[t]??"":""}function tH(e,t={}){let r=t.env??process.env,n=t.exists??Ow,o=Z$(r),s=Fn.win32.extname(e)!=="",i=a=>s?[a]:o.map(l=>`${a}${l}`);if(Q$(e)||Fn.win32.isAbsolute(e))return i(e).find(a=>n(a))??null;for(let a of eH(r).split(";").map(l=>l.trim()).filter(Boolean)){let l=i(Fn.win32.join(a,e)).find(c=>n(c));if(l)return l}return null}function Pw(e){return e.replace(/^[\\/]+/,"")}function nH(e){let t=e.split(/\r?\n/),r=new Map;for(let s of t){let i=rH.exec(s);i&&r.set(i[1].toUpperCase(),i[2])}let n=t.filter(s=>s.includes("%*")).pop();if(!n)return null;let o=Iw.exec(n);if(o)return Pw(o[1]);for(let s of n.matchAll(/%([A-Za-z_]\w*)%/g)){let i=r.get(s[1].toUpperCase()),a=i?Iw.exec(i):null;if(a)return Pw(a[1])}return null}function oH(e,t={}){if((t.platform??process.platform)!=="win32")return{executable:e,prefixArgs:[],kind:"passthrough"};let n=tH(e,t);if(!n)return{executable:e,prefixArgs:[],kind:"passthrough"};let o=Fn.win32.extname(n).toLowerCase();if(o!==".cmd"&&o!==".bat")return{executable:n,prefixArgs:[],kind:"exe"};let s=t.readText??(m=>z$(m,"utf8")),i=t.exists??Ow,a;try{a=s(n)}catch{throw new $i(n)}let l=nH(a);if(!l)throw new $i(n);let c=Fn.win32.dirname(n),u=Fn.win32.join(c,l);if(!i(u))throw new $i(n);let d=Fn.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=oH(e,r);return[n.executable,[...n.prefixArgs,...t]]}var $i,X$,Iw,rH,Fe=p(()=>{"use strict";$i=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},X$=".COM;.EXE;.BAT;.CMD";Iw=/%~?dp0%?\\?([^"%\r\n]+?\.(?:c|m)?js)\b/i,rH=/^\s*SET\s+"?([A-Za-z_]\w*)=([^"\r\n]*)"?\s*$/i});var Im=p(()=>{"use strict";Fe()});function Hi(e){let t=Un(e);try{let r=new URL(t);return r.hostname.toLowerCase()===Tw?(r.hostname=`www.${Tw}`,Un(r.toString())):t}catch{return t}}function gr(e){if(e?.trim())return Hi(Un(e.trim()))}async function kt(e,t,r=fetch){let n=Hi(e),o=new Headers(t?.headers),s=0;for(;s<=Nw;){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 ${Nw} redirects for ${e}`)}var Tw,Nw,hr=p(()=>{"use strict";B();Tw="kynver.com";Nw=10});function Wn(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 Rc(e,t){return e[t]?.trim()||null}function Dw(e){let t=e?.split(":")[0]?.trim();return t?Wn(t):null}function at(e=process.env,t={}){let r=[],n=Dw(t.boxId),o=Dw(Rc(e,"KYNVER_BOX_ID")),s=t.boxKind?.trim();if(s)return n&&n!==Wn(s)&&r.push(`config.boxId=${t.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:Wn(s),source:"config",slugInferenceBlocked:!1,warnings:r};let i=Rc(e,"KYNVER_BOX_KIND");if(i)return o&&o!==Wn(i)&&r.push(`KYNVER_BOX_ID=${Rc(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:Wn(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=Rc(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 Nt(e={},t=process.env){return at(t,e).boxKind}var We=p(()=>{"use strict"});function Pm(e,t){return e==="forge"?4:Math.max(1,t)}function yr(e,t){return e==="forge"?Math.min(Math.max(1,t),4):Math.max(1,t)}function ji(e,t){return e==="forge"&&t>4}var Yo=p(()=>{"use strict"});import{readFileSync as sH}from"node:fs";import Mw from"node:os";function Lw(e){if(e!==void 0){let t=e.match(/^MemAvailable:\s+(\d+)\s*kB/m);return t?Number(t[1])*1024:Mw.freemem()}if(process.platform==="linux")try{let r=sH("/proc/meminfo","utf8").match(/^MemAvailable:\s+(\d+)\s*kB/m);if(r)return Number(r[1])*1024}catch{}return Mw.freemem()}var Bw=p(()=>{"use strict"});import{existsSync as iH,readFileSync as aH,statfsSync as lH}from"node:fs";function Om(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!iH(e))continue;let t=aH(e,"utf8");if(/microsoft|wsl/i.test(t))return!0}catch{}return!1}function Uw(e={}){if(!(e.forceWsl===void 0?Om():e.forceWsl))return null;let r=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||zo,n=e.wslHostFreeWarnBytes??cH,o=e.wslHostFreeCriticalBytes??uH,s=e.statfs??lH,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. ${dH()}`),{ok:f,path:r,freeBytes:a,totalBytes:l,usedPercent:c,warnBelowBytes:n,criticalBelowBytes:o,reason:g,probeError:null}}function dH(){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 cH,uH,zo,Tm=p(()=>{"use strict";cH=25*1024*1024*1024,uH=12*1024*1024*1024,zo="/mnt/c"});import{execFileSync as Fw}from"node:child_process";import{existsSync as Sc,readFileSync as Ww,readdirSync as pH,statSync as fH}from"node:fs";import Nm from"node:path";function wc(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function Kw(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=Fw("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()||zo;return t&&Sc(Nm.join(r,"Users",t))?t:null}function kH(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()||zo,n=e.windowsUser??Kw();return n?`${r.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function bH(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 vH(){try{if(Sc("/proc/sys/kernel/core_pattern"))return Ww("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return Fw("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function RH(e){return!!(e&&/wsl-capture-crash/i.test(e))}function wH(e,t=zo){let r=Nm.join(t,"Users",e,".wslconfig");if(!Sc(r))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=Ww(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 SH(e){if(!Sc(e))return[];let t=pH(e,{withFileTypes:!0}),r=[];for(let n of t){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=Nm.join(e,n.name);try{let s=fH(o),i=bH(n.name);r.push({name:n.name,path:o,bytes:s.size,mtimeMs:s.mtimeMs,executableHint:i.executableHint,signal:i.signal,pid:i.pid})}catch{}}return r.sort((n,o)=>o.mtimeMs-n.mtimeMs),r}function Xo(e={}){if(!(e.forceWsl===void 0?Om():e.forceWsl))return null;let r=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||zo,n=e.windowsUser??Kw(),o=e.warnBelowBytes??wc("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",mH),s=e.criticalBelowBytes??wc("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",gH),i=e.warnCount??wc("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",hH),a=e.criticalCount??wc("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",yH),l=(e.readCorePattern??vH)(),c=RH(l),u=null;n&&(u=(e.readWslConfig??wH)(n,r));let d=u?.maxCrashDumpCount??null,f=d===-1,m=kH({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??SH)(m)}catch(j){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}: ${j.message}`,probeError:j.message}}let h=g.reduce((j,P)=>j+P.bytes,0),y=g.length,b=[...new Set(g.map(j=>j.executableHint).filter(j=>!!j))],k=h>=s,v=h>=o,S=y>=a,w=y>=i,R=!(k||S||v||w),O=null;if(!R){let j=k||S?"critical":"warning",P=(h/1024**3).toFixed(1),M=b.length>0?b.join(", "):"unknown";O=`WSL crash dumps ${j}: ${y} file(s), ${P} GiB at ${m} (executables: ${M}). `+_H({wslCaptureEnabled:c,dumpsDisabledInWslConfig:f})}return{ok:R,path:m,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:f,reason:O,probeError:null}}function _H(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 mH,gH,hH,yH,_c=p(()=>{"use strict";Tm();mH=5*1024*1024*1024,gH=10*1024*1024*1024,hH=2,yH=4});import{statfsSync as xH}from"node:fs";function Xr(e={}){let t=e.diskPath?.trim()||"/",r=e.diskFreeWarnBytes??CH,n=e.diskFreeCriticalBytes??EH,o=e.diskMaxUsedPercent??AH,s=e.diskHardMaxUsedPercent??IH,i=xH(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:Uw(e.wslHost),b=e.skipWslCrashDumpCheck?null:Xo(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,m?`used percent above cap ${o}%`:null,y&&!y.ok?y.reason:null,b&&!b.ok?b.reason:null].filter(Boolean).join("; ")),PH({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 PH(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 CH,EH,AH,IH,Vi=p(()=>{"use strict";_c();Tm();CH=30*1024*1024*1024,EH=15*1024*1024*1024,AH=80,IH=90});import{existsSync as OH,readdirSync as TH}from"node:fs";import NH from"node:path";function Dt(e){let t=new Set;for(let n of Object.keys(e.workers||{}))t.add(U(n));let r=NH.join(q(e.id),"workers");if(!OH(r))return[...t];for(let n of TH(r,{withFileTypes:!0}))n.isDirectory()&&t.add(U(n.name));return[...t]}var Qo=p(()=>{"use strict";Z();B()});function Dm(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 $w(e){let t=e.trim();if(!t)return null;let r=Dm(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let l=Dm(s[1]??"");l&&n.push(l)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let l=Dm(t.slice(i,a+1));l&&n.push(l)}return n.length>0?n[n.length-1]:null}function Hw(e){let t=e.finalResult??e.final_result;if(t!=null)return typeof t=="string"?$w(t)??(t.trim()||null):t;let r=typeof e.summary=="string"?e.summary.trim():"";if(!r)return null;let n=$w(r);return n||r}var jw=p(()=>{"use strict"});import{existsSync as DH,readFileSync as MH}from"node:fs";function Vw(e){return e==="complete"}function kr(e){return Vw(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(!DH(e))return t;let r=Date.now()+LH,n=new Date(r).toISOString(),o=MH(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=
|
|
4
|
+
`):""}function hc(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function yc(e){return new Promise(t=>setTimeout(t,e))}function ne(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function vw(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 Cm(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var U=p(()=>{"use strict";Go()});function $$(e){let t=e[Im];return t?new Set(t.split(/[\s,]+/).map(r=>r.trim()).filter(Boolean)):new Set}function H$(e,t={}){return U$.has(e)?!0:W$.has(e)||t.operatorAllow?.has(e)||K$.some(r=>e.endsWith(r))?!1:F$.some(r=>e.endsWith(r))}function Fi(e){let t=$$(e),r={...e};for(let n of Object.keys(r))H$(n,{operatorAllow:t})&&delete r[n];return r}var Em,U$,F$,Am,W$,K$,Im,Wi=p(()=>{"use strict";Em=["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"],U$=new Set(Em),F$=["_SECRET","_API_KEY","_KEK","_KEY","_TOKEN","_PASSWORD","_PASSPHRASE","_SALT"],Am=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],W$=new Set(Am),K$=["_PUBLIC_KEY"],Im="KYNVER_WORKER_ENV_ALLOW"});import{existsSync as j$,statSync as V$}from"node:fs";import{spawnSync as ww}from"node:child_process";function de(e,t,r={}){let n=ww("git",t,Z({cwd:e,encoding:"utf8"}));if(n.status!==0&&!r.allowFailure){let o=G$(e,t,n);if(r.throwError)throw new Error(o);yt(o)}return n.stdout||""}function G$(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 J$(e){let t=e.trim();if(!t)return"git repo path is empty";let r=De(t);if(!j$(r))return r===t?`git repo path does not exist: ${r}`:`git repo path does not exist: ${r} (from ${t})`;try{if(!V$(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 Sw(e){let t=J$(e);t&&yt(t),de(De(e.trim()),["rev-parse","--show-toplevel"])}function Ki(e){return de(e,["status","--short"],{allowFailure:!0}).split(`
|
|
5
|
+
`).map(t=>t.trim()).filter(Boolean)}function ee(e,t){try{let r=ww("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 Rw(e,t,r){let n=ee(e,["merge-base","--is-ancestor",t,r]);return n.status===0?{isAncestor:!0,error:null}:n.status===1?{isAncestor:!1,error:null}:{isAncestor:null,error:n.error||n.stderr||n.stdout||`git exited ${n.status}`}}function kc(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 qo(n,"missing worktree path");let s=ee(e,["rev-parse","HEAD"]);if(s.status!==0)return qo(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let f=ee(e,["rev-parse",n]);if(f.status!==0)return qo(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=Rw(e,i,a),c=Rw(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 qo(e,t,r=null){return{checked:!1,base:e,head:r,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:t}}var _e=p(()=>{"use strict";ht();U();Wi()});import{existsSync as q$,mkdirSync as _w}from"node:fs";import{homedir as Pm}from"node:os";import Yo from"node:path";function Cw(e=Pm()){return Yo.join(e,".kynver",Y$)}function Ew(e,t=Pm()){return Yo.resolve(e)===Yo.resolve(Cw(t))}function z$(e){ee(e,["config","--get","user.email"]).status!==0&&ee(e,["config","user.email","kynver@local"]),ee(e,["config","--get","user.name"]).status!==0&&ee(e,["config","user.name","Kynver"])}function xw(e){ee(e,["rev-parse","--verify","HEAD^{commit}"]).status!==0&&(z$(e),ee(e,["commit","--allow-empty","-m","kynver byoc workspace"]))}function Aw(e=Pm()){let t=Cw(e);_w(Yo.dirname(t),{recursive:!0});let r=!1;q$(t)||(_w(t,{recursive:!0}),r=!0);let n=ee(t,["rev-parse","--show-toplevel"]);if(n.status!==0)return ee(t,["init","-b",bc]).status!==0&&(ee(t,["init"]),ee(t,["symbolic-ref","HEAD",`refs/heads/${bc}`])),xw(t),r=!0,{repo:Yo.resolve(t),created:r};let o=Yo.resolve(n.stdout.trim()||t);return xw(o),{repo:o,created:r}}var Y$,bc,Om=p(()=>{"use strict";_e();Y$="workspace",bc="main"});import{existsSync as Nm,readFileSync as Pw}from"node:fs";import{homedir as Ow}from"node:os";import kt from"node:path";import{fileURLToPath as X$}from"node:url";function Z$(e){let t=kt.join(e,"package.json");if(!Nm(t))return null;try{let r=JSON.parse(Pw(t,"utf8"));return typeof r.name=="string"?r.name.trim():null}catch{return null}}function Tw(e){return Z$(e)==="kynver"}function Iw(e){let t=kt.resolve(e);if(!Nm(t))return null;let r=ee(t,["rev-parse","--show-toplevel"]);if(r.status!==0)return null;let n=r.stdout.trim();return n.length?kt.resolve(n):null}function eH(e=import.meta.url){let t=kt.dirname(X$(e));for(let r=0;r<8;r+=1){let n=kt.join(t,"package.json");if(Nm(n))try{if(JSON.parse(Pw(n,"utf8")).name==="@kynver-app/runtime")return t}catch{}let o=kt.dirname(t);if(o===t)break;t=o}return null}function Tm(e,t,r,n,o){if(!r)return;let s=kt.resolve(r);e.has(s)||(o?.requireMonorepo??!0)&&!Tw(s)||(e.add(s),t.push({repo:s,source:n}))}function Nw(e){let t=e?.cwd??process.cwd(),r=new Set,n=[];Tm(r,n,Iw(t),"cwd_git",{requireMonorepo:!1});let o=eH(e?.runtimeModuleUrl??import.meta.url);o&&Tm(r,n,Iw(o),"runtime_checkout");let s=Ow();for(let a of Q$)Tm(r,n,De(kt.join(s,a)),"well_known_path");let i=kt.resolve(e?.cwd??process.cwd());return n.filter(a=>{if(a.source!=="runtime_checkout"||!Tw(a.repo))return!0;let l=kt.resolve(a.repo);return i===l||i.startsWith(`${l}${kt.sep}`)})}function vc(e){return Nw(e)[0]??null}function tH(e){let t=kt.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 Rc(e){let t=Nw(e),r=t.find(o=>!tH(o.repo));if(r)return r;if(t[0])return t[0];let{repo:n}=Aw(e?.home??Ow());return{repo:n,source:"byoc_workspace"}}var Q$,$i=p(()=>{"use strict";_e();ht();Om();Q$=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});import{existsSync as Lw,readFileSync as rH}from"node:fs";import Wn from"node:path";function oH(e){return e.includes("/")||e.includes("\\")}function sH(e){return(e.PATHEXT||nH).split(";").map(t=>t.trim().toLowerCase()).filter(t=>t.startsWith("."))}function iH(e){let t=Object.keys(e).find(r=>r.toUpperCase()==="PATH");return t?e[t]??"":""}function aH(e,t={}){let r=t.env??process.env,n=t.exists??Lw,o=sH(r),s=Wn.win32.extname(e)!=="",i=a=>s?[a]:o.map(l=>`${a}${l}`);if(oH(e)||Wn.win32.isAbsolute(e))return i(e).find(a=>n(a))??null;for(let a of iH(r).split(";").map(l=>l.trim()).filter(Boolean)){let l=i(Wn.win32.join(a,e)).find(c=>n(c));if(l)return l}return null}function Mw(e){return e.replace(/^[\\/]+/,"")}function cH(e){let t=e.split(/\r?\n/),r=new Map;for(let s of t){let i=lH.exec(s);i&&r.set(i[1].toUpperCase(),i[2])}let n=t.filter(s=>s.includes("%*")).pop();if(!n)return null;let o=Dw.exec(n);if(o)return Mw(o[1]);for(let s of n.matchAll(/%([A-Za-z_]\w*)%/g)){let i=r.get(s[1].toUpperCase()),a=i?Dw.exec(i):null;if(a)return Mw(a[1])}return null}function uH(e,t={}){if((t.platform??process.platform)!=="win32")return{executable:e,prefixArgs:[],kind:"passthrough"};let n=aH(e,t);if(!n)return{executable:e,prefixArgs:[],kind:"passthrough"};let o=Wn.win32.extname(n).toLowerCase();if(o!==".cmd"&&o!==".bat")return{executable:n,prefixArgs:[],kind:"exe"};let s=t.readText??(m=>rH(m,"utf8")),i=t.exists??Lw,a;try{a=s(n)}catch{throw new Hi(n)}let l=cH(a);if(!l)throw new Hi(n);let c=Wn.win32.dirname(n),u=Wn.win32.join(c,l);if(!i(u))throw new Hi(n);let d=Wn.win32.join(c,"node.exe");return{executable:i(d)?d:t.nodeExecutable??process.execPath,prefixArgs:[u],kind:"node-shim"}}function se(e,t,r={}){let n=uH(e,r);return[n.executable,[...n.prefixArgs,...t]]}var Hi,nH,Dw,lH,We=p(()=>{"use strict";Hi=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},nH=".COM;.EXE;.BAT;.CMD";Dw=/%~?dp0%?\\?([^"%\r\n]+?\.(?:c|m)?js)\b/i,lH=/^\s*SET\s+"?([A-Za-z_]\w*)=([^"\r\n]*)"?\s*$/i});var Dm=p(()=>{"use strict";We()});function ji(e){let t=Fn(e);try{let r=new URL(t);return r.hostname.toLowerCase()===Bw?(r.hostname=`www.${Bw}`,Fn(r.toString())):t}catch{return t}}function hr(e){if(e?.trim())return ji(Fn(e.trim()))}async function bt(e,t,r=fetch){let n=ji(e),o=new Headers(t?.headers),s=0;for(;s<=Uw;){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 ${Uw} redirects for ${e}`)}var Bw,Uw,yr=p(()=>{"use strict";U();Bw="kynver.com";Uw=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 wc(e,t){return e[t]?.trim()||null}function Fw(e){let t=e?.split(":")[0]?.trim();return t?Kn(t):null}function lt(e=process.env,t={}){let r=[],n=Fw(t.boxId),o=Fw(wc(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=wc(e,"KYNVER_BOX_KIND");if(i)return o&&o!==Kn(i)&&r.push(`KYNVER_BOX_ID=${wc(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=wc(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 Dt(e={},t=process.env){return lt(t,e).boxKind}var Ke=p(()=>{"use strict"});function Mm(e,t){return e==="forge"?4:Math.max(1,t)}function kr(e,t){return e==="forge"?Math.min(Math.max(1,t),4):Math.max(1,t)}function Vi(e,t){return e==="forge"&&t>4}var zo=p(()=>{"use strict"});import{readFileSync as dH}from"node:fs";import Ww from"node:os";function Kw(e){if(e!==void 0){let t=e.match(/^MemAvailable:\s+(\d+)\s*kB/m);return t?Number(t[1])*1024:Ww.freemem()}if(process.platform==="linux")try{let r=dH("/proc/meminfo","utf8").match(/^MemAvailable:\s+(\d+)\s*kB/m);if(r)return Number(r[1])*1024}catch{}return Ww.freemem()}var $w=p(()=>{"use strict"});import{existsSync as pH,readFileSync as fH,statfsSync as mH}from"node:fs";function Lm(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!pH(e))continue;let t=fH(e,"utf8");if(/microsoft|wsl/i.test(t))return!0}catch{}return!1}function Hw(e={}){if(!(e.forceWsl===void 0?Lm():e.forceWsl))return null;let r=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Xo,n=e.wslHostFreeWarnBytes??gH,o=e.wslHostFreeCriticalBytes??hH,s=e.statfs??mH,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. ${yH()}`),{ok:f,path:r,freeBytes:a,totalBytes:l,usedPercent:c,warnBelowBytes:n,criticalBelowBytes:o,reason:g,probeError:null}}function yH(){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 gH,hH,Xo,Bm=p(()=>{"use strict";gH=25*1024*1024*1024,hH=12*1024*1024*1024,Xo="/mnt/c"});import{execFileSync as jw}from"node:child_process";import{existsSync as _c,readFileSync as Vw,readdirSync as kH,statSync as bH}from"node:fs";import Um from"node:path";function Sc(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function Gw(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=jw("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()||Xo;return t&&_c(Um.join(r,"Users",t))?t:null}function _H(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()||Xo,n=e.windowsUser??Gw();return n?`${r.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function xH(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 CH(){try{if(_c("/proc/sys/kernel/core_pattern"))return Vw("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return jw("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function EH(e){return!!(e&&/wsl-capture-crash/i.test(e))}function AH(e,t=Xo){let r=Um.join(t,"Users",e,".wslconfig");if(!_c(r))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=Vw(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 IH(e){if(!_c(e))return[];let t=kH(e,{withFileTypes:!0}),r=[];for(let n of t){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=Um.join(e,n.name);try{let s=bH(o),i=xH(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 Qo(e={}){if(!(e.forceWsl===void 0?Lm():e.forceWsl))return null;let r=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Xo,n=e.windowsUser??Gw(),o=e.warnBelowBytes??Sc("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",vH),s=e.criticalBelowBytes??Sc("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",RH),i=e.warnCount??Sc("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",wH),a=e.criticalCount??Sc("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",SH),l=(e.readCorePattern??CH)(),c=EH(l),u=null;n&&(u=(e.readWslConfig??AH)(n,r));let d=u?.maxCrashDumpCount??null,f=d===-1,m=_H({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??IH)(m)}catch(W){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}: ${W.message}`,probeError:W.message}}let h=g.reduce((W,O)=>W+O.bytes,0),k=g.length,v=[...new Set(g.map(W=>W.executableHint).filter(W=>!!W))],y=h>=s,b=h>=o,S=k>=a,w=k>=i,R=!(y||S||b||w),T=null;if(!R){let W=y||S?"critical":"warning",O=(h/1024**3).toFixed(1),L=v.length>0?v.join(", "):"unknown";T=`WSL crash dumps ${W}: ${k} file(s), ${O} GiB at ${m} (executables: ${L}). `+PH({wslCaptureEnabled:c,dumpsDisabledInWslConfig:f})}return{ok:R,path:m,windowsUser:n,dumpCount:k,totalBytes:h,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:g,executables:v,corePattern:l,wslCaptureEnabled:c,maxCrashDumpCount:d,dumpsDisabledInWslConfig:f,reason:T,probeError:null}}function PH(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 vH,RH,wH,SH,xc=p(()=>{"use strict";Bm();vH=5*1024*1024*1024,RH=10*1024*1024*1024,wH=2,SH=4});import{statfsSync as OH}from"node:fs";function Qr(e={}){let t=e.diskPath?.trim()||"/",r=e.diskFreeWarnBytes??TH,n=e.diskFreeCriticalBytes??NH,o=e.diskMaxUsedPercent??DH,s=e.diskHardMaxUsedPercent??MH,i=OH(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,k=e.skipWslHostCheck?null:Hw(e.wslHost),v=e.skipWslCrashDumpCheck?null:Qo(e.wslCrashDumps),y=h&&(k?k.ok:!0)&&(v?v.ok:!0),b=null;return y||(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,k&&!k.ok?k.reason:null,v&&!v.ok?v.reason:null].filter(Boolean).join("; ")),LH({ok:y,path:t,freeBytes:a,totalBytes:l,usedPercent:c,warnBelowBytes:r,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:b,wslHost:k,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 LH(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 TH,NH,DH,MH,Gi=p(()=>{"use strict";xc();Bm();TH=30*1024*1024*1024,NH=15*1024*1024*1024,DH=80,MH=90});import{existsSync as BH,readdirSync as UH}from"node:fs";import FH from"node:path";function Mt(e){let t=new Set;for(let n of Object.keys(e.workers||{}))t.add(F(n));let r=FH.join(J(e.id),"workers");if(!BH(r))return[...t];for(let n of UH(r,{withFileTypes:!0}))n.isDirectory()&&t.add(F(n.name));return[...t]}var Zo=p(()=>{"use strict";Q();U()});function Fm(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 Jw(e){let t=e.trim();if(!t)return null;let r=Fm(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let l=Fm(s[1]??"");l&&n.push(l)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let l=Fm(t.slice(i,a+1));l&&n.push(l)}return n.length>0?n[n.length-1]:null}function qw(e){let t=e.finalResult??e.final_result;if(t!=null)return typeof t=="string"?Jw(t)??(t.trim()||null):t;let r=typeof e.summary=="string"?e.summary.trim():"";if(!r)return null;let n=Jw(r);return n||r}var Yw=p(()=>{"use strict"});import{existsSync as WH,readFileSync as KH}from"node:fs";function zw(e){return e==="complete"}function br(e){return zw(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function Me(e){let t={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!WH(e))return t;let r=Date.now()+$H,n=new Date(r).toISOString(),o=KH(e,"utf8").split(`
|
|
6
|
+
`).filter(Boolean);for(let s of o){let i=Ui(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(t.heartbeatCount++,a.ts){let l=String(a.ts),c=Date.parse(l);Number.isFinite(c)&&c>r?t.timestampAnomalies.push({kind:"future_heartbeat_timestamp",observedAt:l,clampedTo:n}):t.lastHeartbeatAt=l}a.phase!==void 0&&a.phase!==null&&(t.lastHeartbeatPhase=String(a.phase)),a.summary!==void 0&&a.summary!==null&&(t.lastHeartbeatSummary=String(a.summary)),zw(t.lastHeartbeatPhase)&&(t.terminalFinalResult=qw(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 $H,$n=p(()=>{"use strict";Yw();U();$H=6e4});function Qw(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function Cc(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 Zw(e){let t=Qw(e[0]);return!!(t&&HH.has(t))}function VH(e){let t=e.trim();return t.includes("/")?t.split("/").pop()??t:t}function GH(e){if(!e||e.includes("*"))return null;let t=VH(e);return!t||t.includes("/")?null:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(t)?t:null}function eS(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function Wm(e){if(!e)return!1;let t=e.trim();return t.startsWith("!")&&!t.includes("/")&&!t.endsWith("/**")}function JH(e){if(!e.startsWith("--glob="))return e;let t=e.slice(7);return t.startsWith("!")&&!t.includes("/")&&!t.endsWith("/**")?`--glob=${t}/**`:e}function qH(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;Xw.has(n)&&(r+=1);continue}t.push(n)}}return t}function YH(e){let t=!1,r=e.map((o,s)=>{let i=JH(o),a=e[s-1];return a&&Xw.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(t=!0),i}),n=qH(r);if(n.length===2){let[o,s]=n;if(Wm(s))return{argv:[r[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};let i=GH(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 tS(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 Ec(e){let t=e.trim();if(!t)return{command:t,wrapped:!1};let r=Cc(t);if(!r.length)return{command:t,wrapped:!1};let n=Qw(r[0]);if(!n||!jH.has(n))return{command:t,wrapped:!1};let o=tS(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 zH(e,t){let r=e.trim(),n=Cc(r),o=tS(n);if(o<0)return t;let s=n.slice(0,o).join(" "),i=t.includes("'")?`"${t.replace(/"/g,'\\"')}"`:`'${t}'`;return`${s} ${i}`}function XH(e){let t=e.trim(),r=Ec(t),n=Cc(r.command);if(!n.length||!Zw(n))return{segment:t,changed:!1};let o=YH(n);if(!o.changed)return{segment:t,changed:!1};let s=o.argv.join(" ");return r.wrapped?{segment:zH(t,s),changed:!0}:{segment:s,changed:!0}}function Km(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=XH(i);return a.changed&&(o=!0),a.segment});return o?{command:s.join(r),changed:!0}:{command:t,changed:!1}}function rS(e){let t=Ec(e).command,r=Cc(t.trim());return r.length&&Zw(r)?!0:/\b(rg|ripgrep)\b/i.test(t)}function nS(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 QH(e){let{pattern:t,target:r}=nS(e);return t?Wm(r)?{kind:"rg_exclude_syntax",pattern:t,target:r}:eS(r)?{kind:"bad_scope",pattern:t,target:r}:{kind:"not_repo_search",pattern:t,target:r}:{kind:"not_repo_search"}}function ZH(e){let{pattern:t,target:r}=nS(e);if(!t)return null;if(Wm(r)){let n=`${r.trim()}/**`;return{command:`rg "${t}" -g '${n}' .`,changed:!0}}return r&&eS(r)?{command:`rg -g ${r} "${t}" .`,changed:!0}:null}function ej(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 tj(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 $m(e){let t=e.meta?.trim()||(e.command?tj(e.command):null)||null;if(t){let r=QH(t),n=ej(r);if(n)return n;let o=ZH(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=Km(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 HH,jH,Xw,oS=p(()=>{"use strict";HH=new Set(["rg","ripgrep","grep"]),jH=new Set(["bash","sh","dash","zsh"]),Xw=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function Ji(e,t=200){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}function oj(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 qi(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function sj(e){let t=e.metadata;if(!qi(t))return null;let r=t.vulnerabilities;if(!qi(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 ij(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 aj(e,t){let r=e.error;if(qi(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?Ji(o.split(`
|
|
7
|
+
`).find(Boolean)??o,160):"npm audit failed"}function lj(e){let t=`${e.stdout}
|
|
8
|
+
${e.stderr}`.trim(),r=oj(t);if(!r||!qi(r)){let o=Ji(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(qi(r.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${aj(r,e.stderr)}`};let n=sj(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:ij(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function cj(e){return rj.test(e)}function uj(e){let t=Ec(e).command;return sS.test(e)||sS.test(t)||rS(e)}function dj(e){let t=$m({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&&nj.test(n)){let i=Ji(n,160);return{kind:"command_failure",exitCode:1,summary:t??`ripgrep failed (exit 1): ${i}`}}let o=Km(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=Ji(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 iS(e){let t=e.stdout??"",r=e.stderr??"",n=e.interleavedOutput??"";if(cj(e.command)){let i=t.trim()||n.trim()||r.trim();return lj({exitCode:e.exitCode,stdout:i,stderr:r})}if(uj(e.command))return dj({command:e.command,exitCode:e.exitCode,stdout:t,stderr:r,interleaved:n});let o=$m({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=Ji(n||t||r||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var rj,sS,nj,aS=p(()=>{"use strict";oS();rj=/\bnpm\s+audit\b/i,sS=/\b(rg|ripgrep)\b/i,nj=/\b(error|invalid|unknown|panic|not found)\b/i});function Yi(e){return typeof e=="string"&&pj.test(e.trim())}function Ac(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 pj,Ic=p(()=>{"use strict";pj=/^(?:provider authentication failed:\s*)?(?:(?:Failed to authenticate|authentication (?:failed|error))(?::\s*[^\n.!?]+)?|OAuth session expired and could not be refreshed)[.!]?$/i});function Pc(e,t){if(!t.pinned)return mj[e.trim()]}function Oc(e){return e?["--fallback-model",e]:[]}function gj(e,t){return`Claude Code on this computer doesn't know ${e}, so Kynver used ${t}. Update Claude Code (run \`claude update\`) to use the newer model.`}function Hm(e){if(e.type!=="system"||e.subtype!=="model_fallback"||e.trigger!=="model_not_found")return null;let t=typeof e.original_model=="string"?e.original_model:"the requested model",r=typeof e.fallback_model=="string"?e.fallback_model:"an older model";return gj(t,r)}var $e,Zr,fj,mj,lS,cS,vr=p(()=>{"use strict";$e="claude-sonnet-5-5",Zr="claude-opus-5-5",fj="claude-haiku-4-5-20251001",mj={[$e]:"claude-sonnet-4-6",[Zr]:"claude-opus-4-8"},lS=[$e,Zr,"claude-sonnet-4-6","claude-opus-4-8","claude-opus-4-7",fj];cS=/isn't described by this version's model catalog|\bunrecognized_model\b|issue with the selected model/i});function jm(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function hj(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 Tc(e){if(e.event==="step_update"&&jm(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"||!jm(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=jm(t.usage)?hj(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 Vm=p(()=>{"use strict"});function Gm(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function uS(){return{assistantText:""}}function yj(e,t){if(!(t.role!=="assistant"||typeof t.content!="string")){if(t.delta===!0){e.assistantText+=t.content;return}e.assistantText=t.content}}function kj(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=(Gm(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 bj(e){return e.type!=="result"||e.status!=="success"&&e.status!=="error"?!1:typeof e.result!="string"}function dS(e,t){if(e.type==="message"&&(e.role==="assistant"||e.role==="user"))return yj(t,e),{};if(e.type==="tool_use"&&typeof e.tool_name=="string"&&e.tool_name.trim())return{currentTool:e.tool_name.trim()};if(!bj(e))return null;let r=Gm(e.stats)?kj(e.stats):void 0;if(e.status==="error"){let o=Gm(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 pS=p(()=>{"use strict"});import{existsSync as vj,readFileSync as Rj}from"node:fs";function wj(e){let t=e.timestamp_ms;return e.timestamp||e.ts||(t?new Date(t).toISOString():void 0)}function Sj(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 _j(e,t){e.finalResult=t.result||t.subtype||t.terminal_reason||"completed",Ac(t)&&(e.providerTerminalError=!0,e.error=String(t.result||t.api_error_status||"stream result error"))}function es(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function xj(e){let t=e.usage;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Cj(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 Ej(e,t){let r=xj(t);if(!r)return;let n=es(r.input_tokens)??es(r.inputTokens)??es(r.prompt_tokens),o=es(r.output_tokens)??es(r.outputTokens)??es(r.completion_tokens);if(n===void 0&&o===void 0)return;let s=Cj(t)??e.usage?.model;e.usage={...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...s?{model:s}:{}}}function Aj(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 Ij(e,t){t.kind==="success"||t.kind==="search_no_matches"||(e.lastShellOutcome=t)}function Hn(e){let t={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null,usage:null};if(!vj(e))return t;let r=Rj(e,"utf8").split(`
|
|
9
|
+
`).filter(Boolean),n=null,o=uS();for(let s of r){let i=Ui(s);if(!i||typeof i!="object"||Array.isArray(i))continue;if(i.type==="turn.started"&&(n=null,t.finalResult=null),i.type==="item.completed"){let f=i.item;if(f&&typeof f=="object"&&!Array.isArray(f)){let m=f;m.type==="agent_message"&&typeof m.text=="string"&&m.text.trim()&&(n=m.text)}}i.type==="turn.completed"&&n&&!t.providerTerminalError&&(t.finalResult=n,n=null);let a=wj(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=Sj(f);m&&(t.currentTool=m)}let l=Aj(i);l&&Ij(t,iS({command:l.command,exitCode:l.exitCode,stdout:l.stdout,stderr:l.stderr,interleavedOutput:l.interleaved}));let c=Tc(i),u=c?null:dS(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"&&_j(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"}Ej(t,i)}return t}var zi=p(()=>{"use strict";aS();U();Ic();vr();Vm();pS()});import{accessSync as Pj,constants as Oj,existsSync as Tj,readFileSync as Nj}from"node:fs";import Jm from"node:path";function mS(e){return Jm.join(e,Dj)}function Mj(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 fS(e){try{return Pj(e,Oj.X_OK),!0}catch{return!1}}function Lj(e,t=process.env){if(!e)return!1;if(e.includes("/"))return fS(e);for(let r of(t.PATH??"").split(Jm.delimiter))if(r&&fS(Jm.join(r,e)))return!0;return!1}function ct(e,t,r,n={}){let o=n.env??process.env;return!r||!Mj(o,n.platform)?[e,t]:Lj(e,o)?[n.nodeExecutable??process.execPath,["-e",Bj,mS(r),e,...t]]:[e,t]}function Uj(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Nc(e){if(!e)return null;let t=mS(e);if(!Tj(t))return null;try{let r=JSON.parse(Nj(t,"utf8")),n=r.oomEvidence;return{exitCode:Uj(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 gS(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 Dj,Bj,Rr=p(()=>{"use strict";Dj="exit.json";Bj=String.raw`"use strict";
|
|
10
10
|
const cp = require("child_process"), fs = require("fs");
|
|
11
11
|
const argv = process.argv.slice(1);
|
|
12
12
|
const exitFile = argv[0], cmd = argv[1], args = argv.slice(2);
|
|
@@ -72,24 +72,24 @@ child.on("error", (e) => {
|
|
|
72
72
|
if (!child.pid) finish(127, null, String(e && e.message));
|
|
73
73
|
});
|
|
74
74
|
child.on("exit", (code, signal) => finish(code, signal));
|
|
75
|
-
`});import Nj from"node:path";function Hm(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.handoffState;return typeof t=="string"&&Mj.has(t)}function Nc(e){return!!(e&&Dj.test(e))}function fS(e){if(e.noRestartAt?.trim())return"stopped_by_hand";if(e.finalResult&&!Hm(e.finalResult))return"finished";if(e.alive)return e.stale?"stuck":"running";let t=e.error?.trim()??"",r=e.exit??null;if(r?.oomEvidence||Nc(t))return"oom";let n=e.reconcileReason??"";return/reconciled stale worker/i.test(n)?"stuck":dS.test(t)||dS.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 mS(e){let t=[Lj(e.stopClass)],r=uS(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 Lj(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 gS(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,pS/2):pS/2;return Math.min(Bj,n*2**e)}function hS(e,t,r){let n=0,o;try{o=se(e)}catch{return 0}for(let s of Object.keys(o.workers||{})){if(r&&s===r)continue;let i=K(Nj.join(q(o.id),"workers",U(s),"worker.json"),void 0);if(!(!i||i.taskId!==t)){if(i.stopClass==="oom"||i.oomEvidence){n+=1;continue}if(Tc(i.workerDir)?.oomEvidence){n+=1;continue}!i.stopClass&&i.stderrPath&&Nc(Go(i.stderrPath,20))&&(n+=1)}}return n}function yS(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 Dj,dS,Mj,pS,Bj,jm=p(()=>{"use strict";Z();B();vr();Dj=/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,dS=/\btimed? ?out\b|\btimeout\b|deadline exceeded/i,Mj=new Set(["exited_without_final_result","exited_without_complete_heartbeat","exit_failure"]);pS=2048,Bj=8192});function kS(e,t=240){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}function zi(e){let t=(e??"").trim();if(!t)return null;if(qi(t))return{blocked:!0,reason:`provider authentication failed: ${kS(t)}`};for(let r of Uj)if(r.test.test(t))return{blocked:!0,reason:`${r.label}: ${kS(t)}`};return null}var Uj,Vm=p(()=>{"use strict";Ac();br();Uj=[{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:oS,label:"Claude Code doesn't know this model (update Claude Code with `claude update`, or pick another model)"},{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 bS(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function Fj(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 Wj(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:bS(e.head)}function Kj(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 es(e){if(e.alive||Fj(e.finalResult))return null;let t=(e.changedFiles??[]).filter(i=>i.trim()).length,r=bS(e.headCommit)??Wj(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:Kj(s,t,r)}}var Dc=p(()=>{"use strict"});import{existsSync as $j,readFileSync as Hj,statSync as wS}from"node:fs";import Mc from"node:path";function Jj(e,t=process.env){let r=e?Vj:jj,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 qj(e){return e.baseCommit?.trim()||e.base?.trim()||"origin/main"}function Gm(e){try{return wS(e).mtimeMs}catch{return-1}}function Yj(e){let t=Mc.join(e,".git");try{if(wS(t).isDirectory())return t;let r=/^gitdir:\s*(.+)$/m.exec(Hj(t,"utf8"));return r?Mc.resolve(e,r[1].trim()):null}catch{return null}}function vS(e){let t=Yj(e);return[Gm(e),t?Gm(Mc.join(t,"HEAD")):-2,t?Gm(Mc.join(t,"index")):-2].join(":")}function RS(e,t){return{changedFiles:Wi(e),gitAncestry:yc(e,{base:t.base,baseCommit:t.baseCommit})}}function zj(e,t){for(Zr.delete(e),Zr.set(e,t);Zr.size>Gj;){let r=Zr.keys().next().value;if(r===void 0)break;Zr.delete(r)}}function SS(e,t,r){let n=qj(t);if(!e||!e.trim())return Xi.missingWorktree++,{changedFiles:[],gitAncestry:Jo(n,"missing worktree path")};let o=`${e}\0${n}`;if(!$j(e))return Zr.delete(o),Xi.missingWorktree++,{changedFiles:[],gitAncestry:Jo(n,`worktree no longer exists: ${e}`)};if(r.alive)return Zr.delete(o),Xi.liveProbes++,RS(e,t);let s=r.ttlMs??Jj(!!t.baseCommit?.trim()),i=r.now??Date.now(),a=vS(e),l=Zr.get(o);if(s>0&&l&&l.fingerprint===a&&i<l.expiresAt)return Xi.hits++,l.probe;Xi.misses++;let c=RS(e,t);if(s>0){let u=.8+.4*(r.random??Math.random)();zj(o,{fingerprint:vS(e),expiresAt:i+Math.round(s*u),probe:c})}return c}var jj,Vj,Gj,Zr,Xi,_S=p(()=>{"use strict";_e();jj=10*6e4,Vj=60*6e4,Gj=2048,Zr=new Map,Xi={hits:0,misses:0,liveProbes:0,missingWorktree:0}});function Qi(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function Xj(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 Qj(e){if(Qi(e.headCommit)||Qi(e.prUrl)||Qi(e.artifactBundlePath)||Qi(e.patchPath))return!0;let t=e.gitAncestry;return!!(t?.checked&&t.headIsAncestorOfBase===!1&&Qi(t.head))}function ts(e){return Xj(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:Qj(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 xS(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var Lc=p(()=>{"use strict"});function Jm(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 CS(e){let t=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(t)?t.length:0}function rs(e){let t=e.trim();if(!t)return null;let r=Jm(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let u=Jm(s[1]??"");u&&n.push(u)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let u=Jm(t.slice(i,a+1));u&&n.push(u)}if(n.length===0)return null;let l=n[n.length-1],c=CS(l);for(let u of n){let d=CS(u);d>c&&(l=u,c=d)}return l}var Bc=p(()=>{"use strict"});function ES(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 AS(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function Zj(e){return new Set(e.map(t=>AS(ES(t)??t)).filter(Boolean))}function IS(e,t,r){let n=ES(e)??e;if(!n)return"unrelated";let o=AS(n);return Zj(t).has(o)?"contract":r?(r.outcome==="skipped"||r.outcome==="blocked")&&r.reason?.trim()?"support":(r.outcome==="merged","unrelated"):"unrelated"}var PS=p(()=>{"use strict"});function ns(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function e1(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function Hn(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:ns(e)}function Uc(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function OS(e){let t=null;if(typeof e=="string"){let o=rs(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=Hn(String(s.prUrl??s.pr_url??"")),a=ns(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:ns(s.mergeCommit??s.merge_commit),reason:ns(s.reason)})}return n}function TS(e,t){let r=[],n=Hn(ns(e.prUrl)??"");if(n&&r.push(n),t&&typeof t=="object"&&!Array.isArray(t)){let o=t,s=Hn(String(o.prUrl??o.pr_url??""));s&&r.push(s)}return[...new Set(r)]}function NS(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(!e1(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?Hn(ns(t.targetPrUrl)??"")??(t.targetPrUrls.length===1?Hn(t.targetPrUrls[0]):null):null;if(s){let d=TS(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=OS(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=OS(n),a=new Map(i.map(d=>[Uc(d.prUrl),d])),l=new Set(t.targetPrUrls.map(d=>Uc(Hn(d)??d)).filter(Boolean)),c=TS(r,n);if(t.landingOnly)for(let d of c){let f=a.get(Uc(d)),m=IS(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=Uc(Hn(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 DS(e){if(e.blocked)return e.detail??e.reason}var MS=p(()=>{"use strict";Bc();PS()});function r1(e){let t=Date.now();if(e.providerTerminalError||Ec(e.finalResult)||e.finalResult&&e.error?.trim()||qi(e.error)||qi(e.finalResult)){let o=e.error||(typeof e.finalResult=="string"?e.finalResult:"provider terminal error");return{state:"blocked",reason:zi(o)?.reason??`provider terminal error: ${o}`}}if(e.completionBlocker&&!LS(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&o1(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=ts(o);if(s.blocked){let i=xS(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=NS({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=DS(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(n1(e))return{state:"done",reason:"empty abandoned worker record"};let o=zi(e.error);if(o)return{state:"blocked",reason:o.reason};let s=es({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=Nc(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>t1)return{state:"needs_attention",reason:`no first stream event ${Rm(r)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&t-n>qm?{state:"stale",reason:`no log/event/heartbeat activity for ${Rm(n)}s`}:{state:"ok",reason:"recent activity"}}function LS(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function n1(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 o1(e){let t=null;if(typeof e=="string"?t=rs(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 BS(e,t,r){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:t||(n??kr(r))}function US(e){let t=$n(e.stdoutPath),r=De(e.heartbeatPath);return BS(e,t.finalResult,r)}function ce(e,t={}){let r=$n(e.stdoutPath),n=De(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=BS(e,r.finalResult,n),i=o?!1:oe(e.pid),a=fc(e.stdoutPath),l=fc(e.stderrPath),c=fc(e.heartbeatPath),{changedFiles:u,gitAncestry:d}=SS(e.worktreePath,{base:t.base,baseCommit:t.baseCommit},{alive:i}),f=gw([r.lastEventAt,n.lastHeartbeatAt,mc(e.stdoutPath),mc(e.stderrPath),mc(e.heartbeatPath)]),m=i?null:Tc(e.workerDir),g=s&&!Hm(s)?s:null,h=r.error||!i&&!s&&Go(e.stderrPath,10).trim()||void 0,y=h||!i&&s&&!g&&Go(e.stderrPath,10).trim()||void 0,b=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,k=LS(b)?null:b,v=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,S=r1({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:v,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),w=k||S.state==="blocked"?"blocked":o||S.state==="done"?"done":s?"exited":i?"running":"exited",_=e.stopClass&&e.stopClass!=="running"&&e.stopClass!=="finished"?e.stopClass:null,R=fS({alive:i,finalResult:s,error:y??null,stale:S.state==="stale",noRestartAt:e.noRestartAt??null,reconcileReason:e.reconcileReason??null,exit:m}),O=_&&!i&&!g?_:R,j=O==="running"||O==="finished"?null:(_===O?e.stopReason:void 0)??mS({stopClass:O,exit:m,error:y??null,reconcileReason:e.reconcileReason??null});return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:w,stopClass:O,stopReason:j,exit:m,attention:S,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 $e(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Ym(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}function Fc(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 t1,qm,Ie=p(()=>{"use strict";Kn();Yi();jm();vr();Ac();Vm();Dc();_S();Lc();MS();Bc();B();t1=18e4,qm=6e5});import{readFileSync as s1}from"node:fs";function i1(e){if(!e||process.platform!=="linux")return null;try{return s1(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ")}catch{return null}}function FS(e){if(!e.pid||process.platform!=="linux")return!0;let t=i1(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 en(e){return typeof e.completionBlocker=="string"&&e.completionBlocker.trim()||typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim()||!oe(e.pid)||!FS(e)?!1:!US(e)}var Wc=p(()=>{"use strict";Ie();B()});import KS from"node:os";import $S from"node:path";function WS(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function a1(e=A(),t,r){let n=WS(e.perWorkerMemBytes,Kc),o=WS(e.memReserveBytes,$c),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):Hc)),i=is({config:e,configuredMaxWorkersOverride:t,totalMemBytes:r??KS.totalmem()});return{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i.configuredMaxWorkers,autoCap:i.autoCap,workerCapSource:i.workerCapSource}}function HS(e,t={}){let r=t.perWorkerMemBytes??Kc,n=t.memReserveBytes??$c,o=t.memUtilization??Hc,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/r));return Math.min(i,jc)}function l1(){return Lw()}function c1(e){let t=0;for(let r of Dt(e)){let n=K($S.join(q(e.id),"workers",U(r),"worker.json"),void 0);!n||!en(n)||t++}return t}function zm(){let e=0;for(let t of xe())e+=c1(t);return e}function os(){let e=[];for(let t of xe())for(let r of Dt(t)){let n=K($S.join(q(t.id),"workers",U(r),"worker.json"),void 0);n&&en(n)&&e.push({runId:t.id,workerName:r})}return e}function Zi(e){let t=e.config??A(),r=e.totalMemBytes??KS.totalmem(),{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i,autoCap:a,workerCapSource:l}=a1(t,e.configuredMaxWorkersOverride,r),c=Nt(t),u=e.freeMemBytes??l1(),d=e.activeWorkers??zm(),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=yr(c,i??h),b=Math.max(0,Math.min(y,m)),k=Math.max(0,b-d),S=Math.min(k,g),_=e.skipDiskGate||process.env.KYNVER_RESOURCE_GATE_SKIP_DISK==="1"?void 0:Xr({diskPath:e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/"});_&&!_.ok&&(S=0);let R=null;return S<=0&&(_&&!_.ok?R=_.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:m,maxConcurrentWorkers:b,activeWorkers:d,slotsAvailable:S,reason:R,..._?{diskGate:_}:{}}}var Kc,$c,Hc,jc,ss=p(()=>{"use strict";Bw();$();We();Yo();ea();Vi();Z();Qo();Wc();B();Kc=500*1024*1024,$c=4*1024*1024*1024,Hc=.85,jc=64});function ta(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function is(e){let t=e.config??{},r=e.env??process.env,n=ta(t.perWorkerMemBytes,Kc),o=ta(t.memReserveBytes,$c),s=Math.min(1,Math.max(.1,Number(t.memUtilization)>0?Number(t.memUtilization):Hc)),i=HS(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:ta(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(t.maxConcurrentWorkers!==void 0&&t.maxConcurrentWorkers!==null){let c=ta(t.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,jc),autoCap:i,workerCapSource:"config"}}let l=(r.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||r.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&r.KYNVER_MAX_WORKERS&&ta(r.KYNVER_MAX_WORKERS,0)||null;return l?{configuredMaxWorkers:Math.min(l,jc),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var ea=p(()=>{"use strict";ss()});import{existsSync as u1,mkdirSync as Uue,readFileSync as d1,writeFileSync as Fue}from"node:fs";import{homedir as p1}from"node:os";import f1 from"node:path";function m1(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 Vc(e=tn){return u1(e)?m1(d1(e,"utf8")):new Map}function jS(e=tn,t={}){let r=Vc(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 tn,Rr=p(()=>{"use strict";tn=f1.join(p1(),".kynver",".env")});var VS=p(()=>{"use strict"});var GS=p(()=>{"use strict";VS()});var Gc=p(()=>{"use strict"});import{existsSync as g1,readFileSync as h1}from"node:fs";import{homedir as y1}from"node:os";import k1 from"node:path";function Qm(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Xm(e){return typeof e=="string"&&e.trim()?e:null}function Zm(e){let t=Qm(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=Xm(t.requestedAt);return o?{desiredState:r,policyVersion:n,requestedAt:o,requestedByLabel:Xm(t.requestedByLabel),reason:Xm(t.reason)}:null}function JS(e){let t=Qm(Qm(e)?.response);return!t||t.runtimeControl===void 0?null:Zm(t.runtimeControl)}function qS(e,t=y1()){let r=e.replace(/[^A-Za-z0-9_-]/g,"_");return k1.join(t,".kynver",`runtime-control-${r}.json`)}function eg(e,t,r){try{let n=rn(e,r);if(n&&n.policyVersion>t.policyVersion)return;we(qS(e,r),{contractVersion:1,agentOsId:e,control:t,deliveredAt:new Date().toISOString()})}catch{}}function rn(e,t){try{let r=qS(e,t);if(!g1(r))return null;let n=JSON.parse(h1(r,"utf8"));return n.agentOsId!==e?null:Zm(n.control)}catch{return null}}function as(e){return e?.desiredState??"running"}function b1(e){return e==="keeper"||e==="desktop"}function v1(e,t,r=!1){let n=as(e);return n==="paused"?"paused":n==="stopped"?r&&t===0?"stopped":"stopping":"running"}function qc(e){return e.control?{policyVersion:e.control.policyVersion,state:v1(e.control,e.inFlightWorkers,e.exiting),supervised:b1(e.supervisor),inFlightWorkers:Math.max(0,Math.floor(e.inFlightWorkers))}:null}function YS(e){let t=as(e);return t==="paused"?"runtime_paused":t==="stopped"?"runtime_stopped":null}function zS(e,t){return as(e)==="stopped"&&t===0}function QS(e){XS=e}function ZS(){return XS}var Jc,XS,nn=p(()=>{"use strict";B();Jc=83;XS=null});var ra,ls=p(()=>{"use strict";GS();Gc();nn();ra="kynver-cron-daemon.service"});import{existsSync as R1,readFileSync as w1}from"node:fs";function tg(){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(R1("/proc/version")){let e=w1("/proc/version","utf8");if(/microsoft/i.test(e))return"wsl"}}catch{}return"linux"}return"linux"}var Yc=p(()=>{"use strict"});var rg=p(()=>{"use strict";Yc()});var na=p(()=>{"use strict";Rr();gt();$();ls();rg()});import C1 from"node:os";function oa(e,t){let r=(t??C1.hostname()).trim().toLowerCase().replace(/\s+/g,"-")||"unknown-host";return`${e}:${r}`}function t_(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function zc(e,t){let r=e.trim();if(!r)return oa(t);let n=r.indexOf(":");if(n>=0){let o=r.slice(0,n).trim().toLowerCase()||t,s=t_(r.slice(n+1));return s?`${o}:${s}`:oa(o)}return`${t}:${t_(r)}`}function cs(e){let t=e.explicitBoxId?.trim()||e.env?.KYNVER_BOX_ID?.trim()||e.config?.boxId?.trim();return t?zc(t,e.boxKind):oa(e.boxKind,e.hostLabel)}var us=p(()=>{"use strict";We();We()});var r_=p(()=>{"use strict";Rr();ls();na()});import{existsSync as wr,mkdirSync as E1,readdirSync as Xc,renameSync as n_,statSync as A1}from"node:fs";import Sr from"node:path";function s_(e){try{return A1(e).isDirectory()}catch{return!1}}function I1(e){if(!wr(e))return!0;for(let t of o_){let r=Sr.join(e,t);if(wr(r)&&(!s_(r)||Xc(r).length>0))return!1}return!0}function P1(e){let t=Sr.join(e,"runs");if(!wr(t)||!s_(t))return!1;for(let r of Xc(t,{withFileTypes:!0})){if(!r.isDirectory()||r.name==="runs")continue;let n=Sr.join(t,r.name,"run.json");if(K(n,void 0)?.id)return!0}return!1}function O1(e){let t=Sr.join(e,"runs");if(!wr(t))return!1;for(let r of Xc(t,{withFileTypes:!0})){if(!r.isDirectory())continue;if(K(Sr.join(t,r.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function T1(e){let t=Sr.join(e,"ghost");return wr(t)?!wr(Sr.join(t,"runs")):O1(e)}function i_(e){return P1(e.sharedRoot)?I1(e.forgeRoot)?T1(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 a_(e,t){E1(t,{recursive:!0});for(let r of o_){let n=Sr.join(e,r),o=Sr.join(t,r);if(wr(n)){if(wr(o)&&Xc(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(wr(o)){n_(n,o);continue}n_(n,o)}}}var o_,l_=p(()=>{"use strict";B();o_=["runs","worktrees"]});import{existsSync as je}from"node:fs";import{homedir as N1}from"node:os";import Me from"node:path";function ng(e=process.env){return e.HOME?.trim()||N1()}function og(e=process.env){return Me.join(ng(e),".kynver","harness")}function Qc(e){let t=Me.resolve(Ne(e.trim()));for(;D1.has(Me.basename(t));)t=Me.dirname(t);return t}function M1(e,t=process.env){return Me.join(og(t),e)}function L1(e=process.env){let t=og(e);if(je(Me.join(t,"runs")))return!0;if(je(t)&&!je(Me.join(t,"ghost"))&&!je(Me.join(t,"forge")))return je(t);let r=Me.join(ng(e),c_);return je(r)}function Zc(e){let t=e.env??process.env,r=t.KYNVER_HARNESS_ROOT?.trim()||t.OPUS_HARNESS_ROOT?.trim();if(r)return{harnessRoot:Qc(r),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:Qc(n),source:"config"};let o=M1(e.boxKind,t);if(je(Me.join(o,"runs"))||je(o)&&!B1(o))return{harnessRoot:o,source:"box_scoped"};let i=og(t);if(e.boxKind==="forge"){let a=i_({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&&a_(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&L1(t)){if(je(Me.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(je(i)&&!je(Me.join(i,"ghost"))&&!je(Me.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let l=Me.join(ng(t),c_);if(je(l))return{harnessRoot:l,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function B1(e){if(!je(e))return!0;for(let t of["runs","worktrees"]){let r=Me.join(e,t);if(je(r))return!1}return!0}var c_,D1,sg=p(()=>{"use strict";gt();l_();c_=Me.join(".openclaw","harness");D1=new Set(["runs","worktrees"])});import u_ from"node:os";function eu(e){return e?.trim()?e.trim():null}function U1(e,t){let r=t.trim().toLowerCase()||"host";return`${e}-${r}`.replace(/[^a-z0-9._-]+/g,"-")}function F1(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 Jt(e=A(),t=process.env,r={}){let n=at(t,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||eu(t.KYNVER_BOX_KIND)),a=r.strict===!0||F1(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=eu(e.runnerId),c=eu(t.KYNVER_RUNTIME_ID)??eu(t.OPENCLAW_RUNTIME_ID),u=l??c??U1(n.boxKind,u_.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=is({config:e,env:t,totalMemBytes:u_.totalmem()}),m=yr(n.boxKind,f.configuredMaxWorkers??Pm(n.boxKind,f.autoCap)),g=Zc({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 jn=p(()=>{"use strict";$();We();Yo();ea();sg()});var ig=p(()=>{"use strict";Ki();We();us();$();na();r_();hr();Ot();jn()});function ze(e){let t=e.trim().toLowerCase();return K1[t]??t}var f_,W1,K1,sa=p(()=>{"use strict";f_=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],W1=f_.join("|"),K1={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 g_}from"node:fs";import{homedir as h_}from"node:os";import tu from"node:path";function ds(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return y_.includes(t)?t:null}function Vn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){if(typeof r!="string"||!r.trim()||r.includes("\0"))continue;let n=Ne(r.trim());if(t.includes(n)||t.push(n),t.length>=H1)break}return t}function ru(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=ds(s.access);return i?{access:i,folders:Vn(s.folders)}:null}function nu(e){return $1.has(e)?"folder":"off"}function m_(e=h_()){let t=tu.join(e,".kynver",k_);return g_(t,{recursive:!0}),t}function ps(e){let t=e.home??h_(),r=ds(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:Vn(e.local?.chatWorkFolders)},o="local"):(n={access:nu(e.engine),folders:[]},o="default");let{access:s}=n;if(s==="off")return{access:s,folders:[],workDir:m_(t),extraFolders:[],source:o};let i=n.folders;s==="folder"&&(i=i.slice(0,1)),i.length===0&&s!=="full"&&(i=[m_(t)]);for(let l of i)try{g_(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 ou(e,t){if(e.access==="off")return!1;if(e.access==="full")return!0;let r=tu.resolve(t);return e.folders.some(n=>{let o=tu.relative(n,r);return o===""||!o.startsWith("..")&&!tu.isAbsolute(o)})}var y_,$1,H1,k_,Gn=p(()=>{"use strict";gt();y_=["off","folder","folders","full"],$1=new Set(["cursor","codex","antigravity"]),H1=16,k_="chat-workspace"});var b_=p(()=>{"use strict";Gn()});import{execFileSync as j1}from"node:child_process";function cg(e=process.env){let t=e[V1]?.trim().toLowerCase();return t==="file"?"file":t==="keychain"?"keychain":"auto"}function G1(e,t,r){let n={encoding:"utf8",timeout:r.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...r.input!==void 0?{input:r.input}:{}};return j1(e,t,n)}function J1(e=process.platform){return e==="darwin"?"macos":e==="linux"?"libsecret":e==="win32"?"windows":null}function ag(e,t){let r=JSON.stringify(Jn),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 v_(e={}){if(cg(e.env??process.env)==="file")return null;let r=J1(e.platform??process.platform);return r?new lg(r,e.exec):null}var Jn,V1,_r,lg,R_=p(()=>{"use strict";Jn="kynver",V1="KYNVER_CREDENTIAL_STORE";_r=5e3;lg=class{constructor(t,r=G1){this.backend=t;this.exec=r}backend;exec;get(t){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",Jn,"-a",t,"-w"],{timeoutMs:_r}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",Jn,"account",t],{timeoutMs:_r}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ag("get",t)],{timeoutMs:_r}).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",Jn,"-a",t,"-l",`Kynver (${t})`,"-w",r],{timeoutMs:_r}):this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${t})`,"service",Jn,"account",t],{input:`${r}
|
|
76
|
-
`,timeoutMs:
|
|
77
|
-
`,timeoutMs:
|
|
78
|
-
`,{mode:384})}function
|
|
79
|
-
`,{mode:384})}function E_(e,t,r,n={}){let o=xr();if(on().write(e,r)){let i={...o,...n};delete i[t],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],e])).sort(),ia(i);return}ia({...o,...n,[t]:r})}function A_(e,t){let r=on().read(e);return r||xr()[t]}function I_(){if(st())return{backend:null,moved:[],stillInFile:[]};let e=on(),t=xr(),r=[],n=[],o=[[fs,"apiKey"],[ms,"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={...xr()};for(let i of r)delete s[i];s.store="keychain",s.keychainAccounts=Array.from(new Set([...s.keychainAccounts??[],...r.map(i=>i==="apiKey"?fs:ms)])).sort(),ia(s)}return{backend:e.backend,moved:r,stillInFile:n}}function kg(){return uw(rV)}function Ce(){return kg().getApiKey()}function Le(e){return kg().getRunnerToken(e)}function qn(e,t){kg().persistRunnerToken(e,t)}function bg(e){let t=Te("KYNVER_CHAT_BOX_CREDENTIAL");if(t)return t;if(st())return iu?.agentOsId===e?iu.credential:void 0;let r=xr();if(!(r.chatBoxCredentialAgentOsId&&r.chatBoxCredentialAgentOsId!==e))return A_(ms,"chatBoxCredential")}function P_(e,t){if(st()){iu={agentOsId:e,credential:t};return}E_(ms,"chatBoxCredential",t,{chatBoxCredentialAgentOsId:e})}function O_(){if(st()){iu=null;return}on().remove(ms);let e={...xr()};delete e.chatBoxCredential,delete e.chatBoxCredentialAgentOsId,ia(e)}function T_(){let e=on();return process.env.KYNVER_API_KEY?{backend:e.backend,apiKey:"env"}:e.read(fs)?{backend:e.backend,apiKey:"keychain"}:xr().apiKey?{backend:e.backend,apiKey:"file"}:{backend:e.backend,apiKey:"none"}}function me(e){let t=aa(e);return t||M_("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),t}function Yn(e){return aa(e)}function aa(e){let t=e||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||A().apiBaseUrl;return gr(t)}function nV(e,t){let r=e||Le(t)||(t?void 0:Le(A().agentOsId));if(r)return String(r);let n=Te("KYNVER_RUNTIME_SECRET")||Te("KYNVER_CRON_SECRET")||Te("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 cu(e,t,r){let n=nV(e,t);if(n)return{ok:!0,secret:n};let o=Ce(),s=aa(r?.baseUrl);if(o&&t&&s)try{let i=await zn(t,{baseUrl:s,apiKey:o});return qn(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 ye(e,t,r){let n=await cu(e,t,r);if(n.ok)return n.secret;M_(n.reason)}async function N_(e,t){let r=Ce(),n=aa(t?.baseUrl);if(!r||!e||!n)return null;try{let o=await zn(e,{baseUrl:n,apiKey:r});return qn(e,o),o}catch{return null}}async function D_(e,t,r){let n=Ce(),o=aa(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 zn(t,{baseUrl:o,apiKey:n});return s&&s!==e?(qn(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 zn(e,t){let r=t?.apiKey||Ce();if(!r)throw new Error("API key required \u2014 run `kynver login` first");let o=`${me(t?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(e)}/runner-credentials`,s=await kt(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 M_(e){console.error(e),process.exit(1)}var au,fg,mg,Z1,eV,Mpe,Lpe,rV,iu,$=p(()=>{"use strict";Ki();gt();Cm();Im();hr();We();Yo();ea();Vi();na();ig();sa();jn();b_();Ot();pg();au=gg.join(Q1(),".kynver"),fg=gg.join(au,"config.json"),mg=gg.join(au,"credentials"),Z1=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,eV=new Set(["aos","aos-1","agent-os-id","agentosid","agent_os_id","<agent-os-id>","<agentosid>","todo","changeme","change-me","placeholder"]);Mpe=500*1024*1024,Lpe=4*1024*1024*1024;rV={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:A_(fs,"apiKey")},getRunnerToken(e){let t=xr();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){E_(fs,"apiKey",e)},persistRunnerToken(e,t){ia({...xr(),runnerToken:t,runnerTokenAgentOsId:e})}};iu=null});import vg from"node:path";function Be(e){return Qc(e)}function bt(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return Be(e);let t=A(),r=t.harnessRoot?.trim();if(r)return Be(r);let n=Jt(t,process.env);return n.identity?n.identity.harnessRoot:Zc({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function ct(e){return vg.join(Be(e),"runs")}function hs(e){return vg.join(Be(e),"worktrees")}function L_(){let e=bt();return{harnessRoot:e,runsDir:ct(e),worktreesDir:hs(e)}}function Cr(e,t){return vg.join(e,U(t))}var Mt=p(()=>{"use strict";$();sg();jn();B()});import{existsSync as uu,readdirSync as oV,statSync as sV}from"node:fs";import Xn from"node:path";function ke(){return L_()}function se(e){let{runsDir:t}=ke(),r=Xn.join(Cr(t,U(e)),"run.json");return uu(r)||ht(`run '${e}' not found`),K(r)}function xe(){let{runsDir:e}=ke();return B_(e)}function du(e){return B_(ct(e))}function iV(e){try{return sV(e).isDirectory()}catch{return!1}}function B_(e){if(!uu(e))return[];let t=[];for(let r of oV(e,{withFileTypes:!0})){if(r.name==="runs")continue;let n=Xn.join(e,r.name);if(!iV(n))continue;let o=K(Xn.join(n,"run.json"),void 0);o?.id&&t.push(o)}return t}function Qn(e,t){let{runsDir:r}=ke(),n=Xn.join(Cr(r,U(e)),"run.json"),o=Xn.join(Cr(r,U(e)),"workers",U(t),"worker.json");return uu(o)||(uu(n)||ht(`run '${e}' not found`),ht(`worker '${t}' not found in run '${e}'`)),K(o)}function Xe(e){let{runsDir:t}=ke();we(Xn.join(Cr(t,e.id),"run.json"),e)}function ne(e,t){let{runsDir:r}=ke();we(Xn.join(Cr(r,e),"workers",t.name,"worker.json"),t)}function q(e){let{harnessRoot:t}=ke();return la(t,e)}function la(e,t){return Cr(ct(e),U(t))}var Z=p(()=>{"use strict";Mt();B()});import aV from"node:path";function lV(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 ys(e){let t=se(e),r=[];for(let n of Object.keys(t.workers||{})){let o=K(aV.join(q(t.id),"workers",U(n),"worker.json"),void 0);!o?.taskId||!en(o)||r.push({runId:t.id,workerName:n,taskId:o.taskId,pid:o.pid,...lV(o)})}return r}var pu=p(()=>{"use strict";Z();Wc();B()});function Rg(e){return typeof e=="object"&&e!==null&&e.type===fu}function U_(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=>{Rg(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 F_(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return[];let n=t.collect??ys,o=t.killTree??he,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 fu,mu=p(()=>{"use strict";pu();Vo();fu="kynver:daemon-stop"});import{createHash as cV}from"node:crypto";function ut(e){return JSON.stringify(wg(e))}function wg(e){if(Array.isArray(e))return e.map(wg);if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=wg(e[r]);return t}return e}function W_(e){return`ib-${cV("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function ca(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 gu(e){if(!e)return[];let t=[];for(let r of e.split(/[,\s]+/)){let n=ca(r);n&&t.push(n)}return t}function ua(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 hu(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 sn=p(()=>{"use strict"});import{createHash as uV,createPublicKey as dV,verify as pV}from"node:crypto";function gV(e){return`ca-${uV("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function Zn(e,t=process.env){let r=gu(t.KYNVER_COMMAND_AUTH_PUBLIC_KEY);if(r.length>0)return r.find(o=>gV(o)===e)??null;let n=mV[e];return!n||e===K_&&!hu(t)?null:ca(n)}function hV(e){return dV({key:Buffer.concat([fV,Buffer.from(e)]),format:"der",type:"spki"})}function yV(e,t){return!Array.isArray(e)||e.length!==t.length?!1:e.every((r,n)=>typeof r=="string"&&r===t[n])}function kV(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 $_(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!kV(e))return{ok:!1,reason:"malformed command authorization proof"};if(e.payload.agentOsId!==t.agentOsId)return{ok:!1,reason:"agentOsId mismatch"};if(!yV(e.payload.argv,t.argv))return{ok:!1,reason:"argv mismatch"};if(e.payload.exp<=n)return{ok:!1,reason:"proof expired"};let o=Zn(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(ut(e.payload),"utf8");return pV(null,i,hV(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 fV,K_,mV,da=p(()=>{"use strict";sn();fV=Buffer.from("302a300506032b6570032100","hex"),K_="ca-6297fb8e1773",mV={[K_]:"16ae5cb2a61f8c94cf1b86e8258f9c2f2ff6aba5e6136250a422209b6e866881","ca-456fd128f3b3":"f29cbd559410c2578d7f9732ccd86570073355ccdb36af0d1b7dff15908466e7","ca-fc6a2e593f40":"9c0d2fec00bdfce3a448d3fb1b9b9ecfe0dad587dd37f4de492ad9ca91f53def"}});function yu(e){let t=typeof e.description=="string"?e.description:"",r=typeof e.executorRef=="string"?e.executorRef:"",o=[...t.matchAll(bV)].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(vV))try{let i=JSON.parse(s[1]);if(i.readOnly===!0||i.executionMode==="read_only")return"read_only"}catch{}return"write"}var bV,vV,Sg=p(()=>{"use strict";bV=/\[execution-mode:\s*(write|read[_-]?only)\s*\]/gi,vV=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/gi});import{createPublicKey as RV,verify as wV}from"node:crypto";function _g(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 xV.test(i)&&i.length<=512?i:null}function H_(e){let t=e.task??{};return e.landPrDispatch===!0||t.executor==="land_pr"?"land_pr":t.executor==="verify_live"?"verify_live":yu(t)==="read_only"?"read_only":"write"}function CV(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(",")!==[..._V].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)||!ku.includes(r.operationClass))}function j_(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!CV(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+SV+60)return{ok:!1,code:"malformed",reason:"authorization lifetime exceeds the allowed window"};let s=Zn(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=RV({key:Buffer.concat([EV,Buffer.from(s)]),format:"der",type:"spki"});return wV(null,Buffer.from(ut(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 SV,ku,_V,xV,EV,V_=p(()=>{"use strict";da();sn();Sg();SV=120,ku=["write","read_only","land_pr","verify_live"],_V=["agentOsId","attempt","exp","kind","leaseOwner","leaseToken","operationClass","repoIdentity","requestNonce","taskId","tenantId","v"],xV=/^[a-z0-9.-]+(?::\d+)?(?:\/[A-Za-z0-9._~-]+){2,}$/;EV=Buffer.from("302a300506032b6570032100","hex")});import{spawnSync as AV}from"node:child_process";import{randomBytes as IV}from"node:crypto";function G_(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!==PV)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"||!OV.test(t.agentOsId))return"invalid agentOsId";if(typeof t.repoIdentity!="string"||_g(`https://${t.repoIdentity}`)!==t.repoIdentity)return"invalid repoIdentity";let n=t.approvedOperationClasses;if(!Array.isArray(n)||n.length>ku.length)return"invalid approvedOperationClasses";let o=new Set;for(let s of n){if(typeof s!="string"||!ku.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 TV(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=H_(e.decision),a=j_(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 q_(){return st()}function Y_(e){return pa&&e.revision<pa.revision?!1:(pa=e,!0)}function Eg(){return pa}function z_(e){J_=e}function X_(e){return Cg.add(e),()=>Cg.delete(e)}function Q_(e){return{v:1,repoIdentity:e,requestNonce:IV(16).toString("base64url")}}function bu(e){let t=AV("git",["-C",e,"remote","get-url","origin"],te({encoding:"utf8",timeout:1e4}));return t.status!==0||typeof t.stdout!="string"?null:_g(t.stdout.trim())}function Z_(e){let t=TV({...e,policy:pa,identity:J_,consumed:NV});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 Cg)try{o(n)}catch{}}return t}var PV,OV,xg,pa,J_,NV,Cg,vu=p(()=>{"use strict";Ot();V_();B();PV=1,OV=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;xg=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}};pa=null,J_=null,NV=new xg,Cg=new Set});import{createCipheriv as DV,createDecipheriv as MV,randomBytes as Ig,scrypt as LV,timingSafeEqual as BV}from"node:crypto";function tx(){return Ig(Pg)}function rx(e=UV){return{name:"scrypt",N:e.N,r:e.r,p:e.p,salt:Ig(16).toString("base64")}}function Tg(e,t,r=FV){if(t.name!=="scrypt"||!Number.isInteger(t.N)||t.N<r||t.r<8||t.p<1)return Promise.reject(new Lt("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 Lt("the vault file's salt is invalid")):new Promise((o,s)=>{LV(e.normalize("NFKC"),n,Pg,{N:t.N,r:t.r,p:t.p,maxmem:128*t.N*t.r*2},(i,a)=>i?s(i):o(a))})}function an(e,t,r){if(e.length!==Pg)throw new Lt("bad key length");let n=Ig(ex),o=DV("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 eo(e,t,r){try{let n=Buffer.from(t.n,"base64"),o=Buffer.from(t.c,"base64");if(n.length!==ex||o.length<Ag)throw new Lt;let s=MV("aes-256-gcm",e,n);return s.setAAD(Buffer.from(r,"utf8")),s.setAuthTag(o.subarray(o.length-Ag)),Buffer.concat([s.update(o.subarray(0,o.length-Ag)),s.final()])}catch(n){throw n instanceof Lt?n:new Lt}}function Ng(e){for(let t of e)if(t.includes(`
|
|
80
|
-
`))throw new
|
|
81
|
-
`)}function
|
|
82
|
-
`,{mode:384}),
|
|
83
|
-
`,{mode:384}),
|
|
84
|
-
`).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=
|
|
85
|
-
`).filter(Boolean).slice(-
|
|
75
|
+
`});import Fj from"node:path";function qm(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.handoffState;return typeof t=="string"&&Kj.has(t)}function Dc(e){return!!(e&&Wj.test(e))}function kS(e){if(e.noRestartAt?.trim())return"stopped_by_hand";if(e.finalResult&&!qm(e.finalResult))return"finished";if(e.alive)return e.stale?"stuck":"running";let t=e.error?.trim()??"",r=e.exit??null;if(r?.oomEvidence||Dc(t))return"oom";let n=e.reconcileReason??"";return/reconciled stale worker/i.test(n)?"stuck":hS.test(t)||hS.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 bS(e){let t=[$j(e.stopClass)],r=gS(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 $j(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 vS(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,yS/2):yS/2;return Math.min(Hj,n*2**e)}function RS(e,t,r){let n=0,o;try{o=oe(e)}catch{return 0}for(let s of Object.keys(o.workers||{})){if(r&&s===r)continue;let i=K(Fj.join(J(o.id),"workers",F(s),"worker.json"),void 0);if(!(!i||i.taskId!==t)){if(i.stopClass==="oom"||i.oomEvidence){n+=1;continue}if(Nc(i.workerDir)?.oomEvidence){n+=1;continue}!i.stopClass&&i.stderrPath&&Dc(Jo(i.stderrPath,20))&&(n+=1)}}return n}function wS(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 Wj,hS,Kj,yS,Hj,Ym=p(()=>{"use strict";Q();U();Rr();Wj=/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,hS=/\btimed? ?out\b|\btimeout\b|deadline exceeded/i,Kj=new Set(["exited_without_final_result","exited_without_complete_heartbeat","exit_failure"]);yS=2048,Hj=8192});function SS(e,t=240){let r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1)}\u2026`:r}function Xi(e){let t=(e??"").trim();if(!t)return null;if(Yi(t))return{blocked:!0,reason:`provider authentication failed: ${SS(t)}`};for(let r of jj)if(r.test.test(t))return{blocked:!0,reason:`${r.label}: ${SS(t)}`};return null}var jj,zm=p(()=>{"use strict";Ic();vr();jj=[{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:cS,label:"Claude Code doesn't know this model (update Claude Code with `claude update`, or pick another model)"},{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 _S(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function Vj(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 Gj(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:_S(e.head)}function Jj(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 ts(e){if(e.alive||Vj(e.finalResult))return null;let t=(e.changedFiles??[]).filter(i=>i.trim()).length,r=_S(e.headCommit)??Gj(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:Jj(s,t,r)}}var Mc=p(()=>{"use strict"});import{existsSync as qj,readFileSync as Yj,statSync as ES}from"node:fs";import Lc from"node:path";function Zj(e,t=process.env){let r=e?Xj:zj,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 e1(e){return e.baseCommit?.trim()||e.base?.trim()||"origin/main"}function Xm(e){try{return ES(e).mtimeMs}catch{return-1}}function t1(e){let t=Lc.join(e,".git");try{if(ES(t).isDirectory())return t;let r=/^gitdir:\s*(.+)$/m.exec(Yj(t,"utf8"));return r?Lc.resolve(e,r[1].trim()):null}catch{return null}}function xS(e){let t=t1(e);return[Xm(e),t?Xm(Lc.join(t,"HEAD")):-2,t?Xm(Lc.join(t,"index")):-2].join(":")}function CS(e,t){return{changedFiles:Ki(e),gitAncestry:kc(e,{base:t.base,baseCommit:t.baseCommit})}}function r1(e,t){for(en.delete(e),en.set(e,t);en.size>Qj;){let r=en.keys().next().value;if(r===void 0)break;en.delete(r)}}function AS(e,t,r){let n=e1(t);if(!e||!e.trim())return Qi.missingWorktree++,{changedFiles:[],gitAncestry:qo(n,"missing worktree path")};let o=`${e}\0${n}`;if(!qj(e))return en.delete(o),Qi.missingWorktree++,{changedFiles:[],gitAncestry:qo(n,`worktree no longer exists: ${e}`)};if(r.alive)return en.delete(o),Qi.liveProbes++,CS(e,t);let s=r.ttlMs??Zj(!!t.baseCommit?.trim()),i=r.now??Date.now(),a=xS(e),l=en.get(o);if(s>0&&l&&l.fingerprint===a&&i<l.expiresAt)return Qi.hits++,l.probe;Qi.misses++;let c=CS(e,t);if(s>0){let u=.8+.4*(r.random??Math.random)();r1(o,{fingerprint:xS(e),expiresAt:i+Math.round(s*u),probe:c})}return c}var zj,Xj,Qj,en,Qi,IS=p(()=>{"use strict";_e();zj=10*6e4,Xj=60*6e4,Qj=2048,en=new Map,Qi={hits:0,misses:0,liveProbes:0,missingWorktree:0}});function Zi(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function n1(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 o1(e){if(Zi(e.headCommit)||Zi(e.prUrl)||Zi(e.artifactBundlePath)||Zi(e.patchPath))return!0;let t=e.gitAncestry;return!!(t?.checked&&t.headIsAncestorOfBase===!1&&Zi(t.head))}function rs(e){return n1(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:o1(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 PS(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var Bc=p(()=>{"use strict"});function Qm(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 OS(e){let t=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(t)?t.length:0}function ns(e){let t=e.trim();if(!t)return null;let r=Qm(t);if(r)return r;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(t))!==null;){let u=Qm(s[1]??"");u&&n.push(u)}let i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){let u=Qm(t.slice(i,a+1));u&&n.push(u)}if(n.length===0)return null;let l=n[n.length-1],c=OS(l);for(let u of n){let d=OS(u);d>c&&(l=u,c=d)}return l}var Uc=p(()=>{"use strict"});function TS(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 NS(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function s1(e){return new Set(e.map(t=>NS(TS(t)??t)).filter(Boolean))}function DS(e,t,r){let n=TS(e)??e;if(!n)return"unrelated";let o=NS(n);return s1(t).has(o)?"contract":r?(r.outcome==="skipped"||r.outcome==="blocked")&&r.reason?.trim()?"support":(r.outcome==="merged","unrelated"):"unrelated"}var MS=p(()=>{"use strict"});function os(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function i1(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function jn(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:os(e)}function Fc(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`${t[1].toLowerCase()}/pull/${t[2]}`:e.trim().toLowerCase()}function LS(e){let t=null;if(typeof e=="string"){let o=ns(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=jn(String(s.prUrl??s.pr_url??"")),a=os(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:os(s.mergeCommit??s.merge_commit),reason:os(s.reason)})}return n}function BS(e,t){let r=[],n=jn(os(e.prUrl)??"");if(n&&r.push(n),t&&typeof t=="object"&&!Array.isArray(t)){let o=t,s=jn(String(o.prUrl??o.pr_url??""));s&&r.push(s)}return[...new Set(r)]}function US(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(!i1(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?jn(os(t.targetPrUrl)??"")??(t.targetPrUrls.length===1?jn(t.targetPrUrls[0]):null):null;if(s){let d=BS(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=LS(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=LS(n),a=new Map(i.map(d=>[Fc(d.prUrl),d])),l=new Set(t.targetPrUrls.map(d=>Fc(jn(d)??d)).filter(Boolean)),c=BS(r,n);if(t.landingOnly)for(let d of c){let f=a.get(Fc(d)),m=DS(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=Fc(jn(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 FS(e){if(e.blocked)return e.detail??e.reason}var WS=p(()=>{"use strict";Uc();MS()});function l1(e){let t=Date.now();if(e.providerTerminalError||Ac(e.finalResult)||e.finalResult&&e.error?.trim()||Yi(e.error)||Yi(e.finalResult)){let o=e.error||(typeof e.finalResult=="string"?e.finalResult:"provider terminal error");return{state:"blocked",reason:Xi(o)?.reason??`provider terminal error: ${o}`}}if(e.completionBlocker&&!KS(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&u1(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=rs(o);if(s.blocked){let i=PS(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=US({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=FS(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(c1(e))return{state:"done",reason:"empty abandoned worker record"};let o=Xi(e.error);if(o)return{state:"blocked",reason:o.reason};let s=ts({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=Dc(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>a1)return{state:"needs_attention",reason:`no first stream event ${Cm(r)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&t-n>Zm?{state:"stale",reason:`no log/event/heartbeat activity for ${Cm(n)}s`}:{state:"ok",reason:"recent activity"}}function KS(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function c1(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 u1(e){let t=null;if(typeof e=="string"?t=ns(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 $S(e,t,r){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:t||(n??br(r))}function HS(e){let t=Hn(e.stdoutPath),r=Me(e.heartbeatPath);return $S(e,t.finalResult,r)}function le(e,t={}){let r=Hn(e.stdoutPath),n=Me(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=$S(e,r.finalResult,n),i=o?!1:ne(e.pid),a=mc(e.stdoutPath),l=mc(e.stderrPath),c=mc(e.heartbeatPath),{changedFiles:u,gitAncestry:d}=AS(e.worktreePath,{base:t.base,baseCommit:t.baseCommit},{alive:i}),f=vw([r.lastEventAt,n.lastHeartbeatAt,gc(e.stdoutPath),gc(e.stderrPath),gc(e.heartbeatPath)]),m=i?null:Nc(e.workerDir),g=s&&!qm(s)?s:null,h=r.error||!i&&!s&&Jo(e.stderrPath,10).trim()||void 0,k=h||!i&&s&&!g&&Jo(e.stderrPath,10).trim()||void 0,v=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,y=KS(v)?null:v,b=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,S=l1({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:y,landingContract:b,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),w=y||S.state==="blocked"?"blocked":o||S.state==="done"?"done":s?"exited":i?"running":"exited",_=e.stopClass&&e.stopClass!=="running"&&e.stopClass!=="finished"?e.stopClass:null,R=kS({alive:i,finalResult:s,error:k??null,stale:S.state==="stale",noRestartAt:e.noRestartAt??null,reconcileReason:e.reconcileReason??null,exit:m}),T=_&&!i&&!g?_:R,W=T==="running"||T==="finished"?null:(_===T?e.stopReason:void 0)??bS({stopClass:T,exit:m,error:k??null,reconcileReason:e.reconcileReason??null});return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:w,stopClass:T,stopReason:W,exit:m,attention:S,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 He(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function eg(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}function Wc(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 a1,Zm,Ie=p(()=>{"use strict";$n();zi();Ym();Rr();Ic();zm();Mc();IS();Bc();WS();Uc();U();a1=18e4,Zm=6e5});import{readFileSync as d1}from"node:fs";function p1(e){if(!e||process.platform!=="linux")return null;try{return d1(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ")}catch{return null}}function jS(e){if(!e.pid||process.platform!=="linux")return!0;let t=p1(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 tn(e){return typeof e.completionBlocker=="string"&&e.completionBlocker.trim()||typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim()||!ne(e.pid)||!jS(e)?!1:!HS(e)}var Kc=p(()=>{"use strict";Ie();U()});import GS from"node:os";import JS from"node:path";function VS(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function f1(e=A(),t,r){let n=VS(e.perWorkerMemBytes,$c),o=VS(e.memReserveBytes,Hc),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):jc)),i=as({config:e,configuredMaxWorkersOverride:t,totalMemBytes:r??GS.totalmem()});return{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i.configuredMaxWorkers,autoCap:i.autoCap,workerCapSource:i.workerCapSource}}function qS(e,t={}){let r=t.perWorkerMemBytes??$c,n=t.memReserveBytes??Hc,o=t.memUtilization??jc,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/r));return Math.min(i,Vc)}function m1(){return Kw()}function g1(e){let t=0;for(let r of Mt(e)){let n=K(JS.join(J(e.id),"workers",F(r),"worker.json"),void 0);!n||!tn(n)||t++}return t}function tg(){let e=0;for(let t of xe())e+=g1(t);return e}function ss(){let e=[];for(let t of xe())for(let r of Mt(t)){let n=K(JS.join(J(t.id),"workers",F(r),"worker.json"),void 0);n&&tn(n)&&e.push({runId:t.id,workerName:r})}return e}function ea(e){let t=e.config??A(),r=e.totalMemBytes??GS.totalmem(),{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s,configuredMaxWorkers:i,autoCap:a,workerCapSource:l}=f1(t,e.configuredMaxWorkersOverride,r),c=Dt(t),u=e.freeMemBytes??m1(),d=e.activeWorkers??tg(),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,k=kr(c,i??h),v=Math.max(0,Math.min(k,m)),y=Math.max(0,v-d),S=Math.min(y,g),_=e.skipDiskGate||process.env.KYNVER_RESOURCE_GATE_SKIP_DISK==="1"?void 0:Qr({diskPath:e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/"});_&&!_.ok&&(S=0);let R=null;return S<=0&&(_&&!_.ok?R=_.reason??"disk gate blocked worker admission":d>=v?R=`at worker limit (${d}/${v} 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:m,maxConcurrentWorkers:v,activeWorkers:d,slotsAvailable:S,reason:R,..._?{diskGate:_}:{}}}var $c,Hc,jc,Vc,is=p(()=>{"use strict";$w();$();Ke();zo();ta();Gi();Q();Zo();Kc();U();$c=500*1024*1024,Hc=4*1024*1024*1024,jc=.85,Vc=64});function ra(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function as(e){let t=e.config??{},r=e.env??process.env,n=ra(t.perWorkerMemBytes,$c),o=ra(t.memReserveBytes,Hc),s=Math.min(1,Math.max(.1,Number(t.memUtilization)>0?Number(t.memUtilization):jc)),i=qS(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:ra(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(t.maxConcurrentWorkers!==void 0&&t.maxConcurrentWorkers!==null){let c=ra(t.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,Vc),autoCap:i,workerCapSource:"config"}}let l=(r.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||r.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&r.KYNVER_MAX_WORKERS&&ra(r.KYNVER_MAX_WORKERS,0)||null;return l?{configuredMaxWorkers:Math.min(l,Vc),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var ta=p(()=>{"use strict";is()});import{existsSync as h1,mkdirSync as Gue,readFileSync as y1,writeFileSync as Jue}from"node:fs";import{homedir as k1}from"node:os";import b1 from"node:path";function v1(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 Gc(e=rn){return h1(e)?v1(y1(e,"utf8")):new Map}function YS(e=rn,t={}){let r=Gc(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 rn,wr=p(()=>{"use strict";rn=b1.join(k1(),".kynver",".env")});var zS=p(()=>{"use strict"});var XS=p(()=>{"use strict";zS()});var Jc=p(()=>{"use strict"});import{existsSync as R1,readFileSync as w1}from"node:fs";import{homedir as S1}from"node:os";import _1 from"node:path";function ng(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function rg(e){return typeof e=="string"&&e.trim()?e:null}function og(e){let t=ng(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=rg(t.requestedAt);return o?{desiredState:r,policyVersion:n,requestedAt:o,requestedByLabel:rg(t.requestedByLabel),reason:rg(t.reason)}:null}function QS(e){let t=ng(ng(e)?.response);return!t||t.runtimeControl===void 0?null:og(t.runtimeControl)}function ZS(e,t=S1()){let r=e.replace(/[^A-Za-z0-9_-]/g,"_");return _1.join(t,".kynver",`runtime-control-${r}.json`)}function sg(e,t,r){try{let n=nn(e,r);if(n&&n.policyVersion>t.policyVersion)return;we(ZS(e,r),{contractVersion:1,agentOsId:e,control:t,deliveredAt:new Date().toISOString()})}catch{}}function nn(e,t){try{let r=ZS(e,t);if(!R1(r))return null;let n=JSON.parse(w1(r,"utf8"));return n.agentOsId!==e?null:og(n.control)}catch{return null}}function ls(e){return e?.desiredState??"running"}function x1(e){return e==="keeper"||e==="desktop"}function C1(e,t,r=!1){let n=ls(e);return n==="paused"?"paused":n==="stopped"?r&&t===0?"stopped":"stopping":"running"}function Yc(e){return e.control?{policyVersion:e.control.policyVersion,state:C1(e.control,e.inFlightWorkers,e.exiting),supervised:x1(e.supervisor),inFlightWorkers:Math.max(0,Math.floor(e.inFlightWorkers))}:null}function e_(e){let t=ls(e);return t==="paused"?"runtime_paused":t==="stopped"?"runtime_stopped":null}function t_(e,t){return ls(e)==="stopped"&&t===0}function n_(e){r_=e}function o_(){return r_}var qc,r_,on=p(()=>{"use strict";U();qc=83;r_=null});var na,cs=p(()=>{"use strict";XS();Jc();on();na="kynver-cron-daemon.service"});import{existsSync as E1,readFileSync as A1}from"node:fs";function ig(){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(E1("/proc/version")){let e=A1("/proc/version","utf8");if(/microsoft/i.test(e))return"wsl"}}catch{}return"linux"}return"linux"}var zc=p(()=>{"use strict"});var ag=p(()=>{"use strict";zc()});var oa=p(()=>{"use strict";wr();ht();$();cs();ag()});import T1 from"node:os";function sa(e,t){let r=(t??T1.hostname()).trim().toLowerCase().replace(/\s+/g,"-")||"unknown-host";return`${e}:${r}`}function i_(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function Xc(e,t){let r=e.trim();if(!r)return sa(t);let n=r.indexOf(":");if(n>=0){let o=r.slice(0,n).trim().toLowerCase()||t,s=i_(r.slice(n+1));return s?`${o}:${s}`:sa(o)}return`${t}:${i_(r)}`}function us(e){let t=e.explicitBoxId?.trim()||e.env?.KYNVER_BOX_ID?.trim()||e.config?.boxId?.trim();return t?Xc(t,e.boxKind):sa(e.boxKind,e.hostLabel)}var ds=p(()=>{"use strict";Ke();Ke()});var a_=p(()=>{"use strict";wr();cs();oa()});import{existsSync as Sr,mkdirSync as N1,readdirSync as Qc,renameSync as l_,statSync as D1}from"node:fs";import _r from"node:path";function u_(e){try{return D1(e).isDirectory()}catch{return!1}}function M1(e){if(!Sr(e))return!0;for(let t of c_){let r=_r.join(e,t);if(Sr(r)&&(!u_(r)||Qc(r).length>0))return!1}return!0}function L1(e){let t=_r.join(e,"runs");if(!Sr(t)||!u_(t))return!1;for(let r of Qc(t,{withFileTypes:!0})){if(!r.isDirectory()||r.name==="runs")continue;let n=_r.join(t,r.name,"run.json");if(K(n,void 0)?.id)return!0}return!1}function B1(e){let t=_r.join(e,"runs");if(!Sr(t))return!1;for(let r of Qc(t,{withFileTypes:!0})){if(!r.isDirectory())continue;if(K(_r.join(t,r.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function U1(e){let t=_r.join(e,"ghost");return Sr(t)?!Sr(_r.join(t,"runs")):B1(e)}function d_(e){return L1(e.sharedRoot)?M1(e.forgeRoot)?U1(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 p_(e,t){N1(t,{recursive:!0});for(let r of c_){let n=_r.join(e,r),o=_r.join(t,r);if(Sr(n)){if(Sr(o)&&Qc(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(Sr(o)){l_(n,o);continue}l_(n,o)}}}var c_,f_=p(()=>{"use strict";U();c_=["runs","worktrees"]});import{existsSync as Ve}from"node:fs";import{homedir as F1}from"node:os";import Le from"node:path";function lg(e=process.env){return e.HOME?.trim()||F1()}function cg(e=process.env){return Le.join(lg(e),".kynver","harness")}function Zc(e){let t=Le.resolve(De(e.trim()));for(;W1.has(Le.basename(t));)t=Le.dirname(t);return t}function K1(e,t=process.env){return Le.join(cg(t),e)}function $1(e=process.env){let t=cg(e);if(Ve(Le.join(t,"runs")))return!0;if(Ve(t)&&!Ve(Le.join(t,"ghost"))&&!Ve(Le.join(t,"forge")))return Ve(t);let r=Le.join(lg(e),m_);return Ve(r)}function eu(e){let t=e.env??process.env,r=t.KYNVER_HARNESS_ROOT?.trim()||t.OPUS_HARNESS_ROOT?.trim();if(r)return{harnessRoot:Zc(r),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:Zc(n),source:"config"};let o=K1(e.boxKind,t);if(Ve(Le.join(o,"runs"))||Ve(o)&&!H1(o))return{harnessRoot:o,source:"box_scoped"};let i=cg(t);if(e.boxKind==="forge"){let a=d_({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&&p_(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&$1(t)){if(Ve(Le.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(Ve(i)&&!Ve(Le.join(i,"ghost"))&&!Ve(Le.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let l=Le.join(lg(t),m_);if(Ve(l))return{harnessRoot:l,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function H1(e){if(!Ve(e))return!0;for(let t of["runs","worktrees"]){let r=Le.join(e,t);if(Ve(r))return!1}return!0}var m_,W1,ug=p(()=>{"use strict";ht();f_();m_=Le.join(".openclaw","harness");W1=new Set(["runs","worktrees"])});import g_ from"node:os";function tu(e){return e?.trim()?e.trim():null}function j1(e,t){let r=t.trim().toLowerCase()||"host";return`${e}-${r}`.replace(/[^a-z0-9._-]+/g,"-")}function V1(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 qt(e=A(),t=process.env,r={}){let n=lt(t,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||tu(t.KYNVER_BOX_KIND)),a=r.strict===!0||V1(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=tu(e.runnerId),c=tu(t.KYNVER_RUNTIME_ID)??tu(t.OPENCLAW_RUNTIME_ID),u=l??c??j1(n.boxKind,g_.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=as({config:e,env:t,totalMemBytes:g_.totalmem()}),m=kr(n.boxKind,f.configuredMaxWorkers??Mm(n.boxKind,f.autoCap)),g=eu({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 Vn=p(()=>{"use strict";$();Ke();zo();ta();ug()});var dg=p(()=>{"use strict";$i();Ke();ds();$();oa();a_();yr();Tt();Vn()});function Xe(e){let t=e.trim().toLowerCase();return J1[t]??t}var k_,G1,J1,ia=p(()=>{"use strict";k_=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],G1=k_.join("|"),J1={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 v_}from"node:fs";import{homedir as R_}from"node:os";import ru from"node:path";function ps(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return w_.includes(t)?t:null}function Gn(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>=Y1)break}return t}function nu(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=ps(s.access);return i?{access:i,folders:Gn(s.folders)}:null}function ou(e){return q1.has(e)?"folder":"off"}function b_(e=R_()){let t=ru.join(e,".kynver",S_);return v_(t,{recursive:!0}),t}function fs(e){let t=e.home??R_(),r=ps(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:Gn(e.local?.chatWorkFolders)},o="local"):(n={access:ou(e.engine),folders:[]},o="default");let{access:s}=n;if(s==="off")return{access:s,folders:[],workDir:b_(t),extraFolders:[],source:o};let i=n.folders;s==="folder"&&(i=i.slice(0,1)),i.length===0&&s!=="full"&&(i=[b_(t)]);for(let l of i)try{v_(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 su(e,t){if(e.access==="off")return!1;if(e.access==="full")return!0;let r=ru.resolve(t);return e.folders.some(n=>{let o=ru.relative(n,r);return o===""||!o.startsWith("..")&&!ru.isAbsolute(o)})}var w_,q1,Y1,S_,Jn=p(()=>{"use strict";ht();w_=["off","folder","folders","full"],q1=new Set(["cursor","codex","antigravity"]),Y1=16,S_="chat-workspace"});var __=p(()=>{"use strict";Jn()});import{execFileSync as z1}from"node:child_process";function mg(e=process.env){let t=e[X1]?.trim().toLowerCase();return t==="file"?"file":t==="keychain"?"keychain":"auto"}function Q1(e,t,r){let n={encoding:"utf8",timeout:r.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...r.input!==void 0?{input:r.input}:{}};return z1(e,t,n)}function Z1(e=process.platform){return e==="darwin"?"macos":e==="linux"?"libsecret":e==="win32"?"windows":null}function pg(e,t){let r=JSON.stringify(qn),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 x_(e={}){if(mg(e.env??process.env)==="file")return null;let r=Z1(e.platform??process.platform);return r?new fg(r,e.exec):null}var qn,X1,xr,fg,C_=p(()=>{"use strict";qn="kynver",X1="KYNVER_CREDENTIAL_STORE";xr=5e3;fg=class{constructor(t,r=Q1){this.backend=t;this.exec=r}backend;exec;get(t){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",qn,"-a",t,"-w"],{timeoutMs:xr}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",qn,"account",t],{timeoutMs:xr}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",pg("get",t)],{timeoutMs:xr}).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",qn,"-a",t,"-l",`Kynver (${t})`,"-w",r],{timeoutMs:xr}):this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${t})`,"service",qn,"account",t],{input:`${r}
|
|
76
|
+
`,timeoutMs:xr}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",pg("set",t)],{input:`${r}
|
|
77
|
+
`,timeoutMs:xr})}catch{return!1}return this.get(t)===r}delete(t){try{this.backend==="macos"?this.exec("security",["delete-generic-password","-s",qn,"-a",t],{timeoutMs:xr}):this.backend==="libsecret"?this.exec("secret-tool",["clear","service",qn,"account",t],{timeoutMs:xr}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",pg("delete",t)],{timeoutMs:xr})}catch{}}}});function sn(){return gg||(gg=new hg),gg}var ms,gs,eV,iu,hg,gg,yg=p(()=>{"use strict";C_();ms="api-key",gs="chat-box-credential",eV=6e4,iu=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"}},hg=class{cache=new Map;keychain;env;now;constructor(t={}){this.env=t.env??process.env,this.keychain=t.keychain===void 0?x_({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<eV)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=mg(this.env);if(!this.keychain){if(n==="keychain")throw new iu(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 iu(t);return o}remove(t){this.cache.delete(t),this.keychain?.delete(t)}invalidate(t){t?this.cache.delete(t):this.cache.clear()}},gg=null});import{existsSync as E_,mkdirSync as A_,readFileSync as I_,writeFileSync as P_}from"node:fs";import{homedir as oV,totalmem as xpe}from"node:os";import vg from"node:path";function hs(e){let t=String(e??"").trim();if(!t)return{ok:!1,reason:"missing"};let r=t.toLowerCase();return iV.has(r)?{ok:!1,value:t,reason:"placeholder"}:sV.test(t)?{ok:!0,value:t}:{ok:!1,value:t,reason:"not a UUID"}}function Rg(e){let t=hs(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 O_(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:De(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:De(e.defaultRepo.trim())}:{}}}function cu(e){let t=e.defaultRepo?.trim();return!t||e.defaultBase?.trim()||!Ew(De(t))?e:{...e,defaultBase:bc}}function aV(){if(!E_(kg))return null;try{return JSON.parse(I_(kg,"utf8"))}catch{return null}}function A(){let e=aV();return e?cu(O_(e)):{}}function je(e){A_(lu,{recursive:!0}),P_(kg,`${JSON.stringify(cu(y_(e)),null,2)}
|
|
78
|
+
`,{mode:384})}function y_(e){return O_(e)}function wg(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:ze(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:ze(e.defaultRepo.trim())}:{},...e.chatWorkFolders?.length?{chatWorkFolders:e.chatWorkFolders.map(ze)}:{}}}function Cr(){if(_m(),!E_(bg))return{};try{return JSON.parse(I_(bg,"utf8"))}catch{return{}}}function aa(e){_m(),A_(lu,{recursive:!0}),P_(bg,`${JSON.stringify(e,null,2)}
|
|
79
|
+
`,{mode:384})}function T_(e,t,r,n={}){let o=Cr();if(sn().write(e,r)){let i={...o,...n};delete i[t],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],e])).sort(),aa(i);return}aa({...o,...n,[t]:r})}function N_(e,t){let r=sn().read(e);return r||Cr()[t]}function D_(){if(it())return{backend:null,moved:[],stillInFile:[]};let e=sn(),t=Cr(),r=[],n=[],o=[[ms,"apiKey"],[gs,"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={...Cr()};for(let i of r)delete s[i];s.store="keychain",s.keychainAccounts=Array.from(new Set([...s.keychainAccounts??[],...r.map(i=>i==="apiKey"?ms:gs)])).sort(),aa(s)}return{backend:e.backend,moved:r,stillInFile:n}}function Sg(){return gw(lV)}function Ce(){return Sg().getApiKey()}function Be(e){return Sg().getRunnerToken(e)}function Yn(e,t){Sg().persistRunnerToken(e,t)}function _g(e){let t=Ne("KYNVER_CHAT_BOX_CREDENTIAL");if(t)return t;if(it())return au?.agentOsId===e?au.credential:void 0;let r=Cr();if(!(r.chatBoxCredentialAgentOsId&&r.chatBoxCredentialAgentOsId!==e))return N_(gs,"chatBoxCredential")}function M_(e,t){if(it()){au={agentOsId:e,credential:t};return}T_(gs,"chatBoxCredential",t,{chatBoxCredentialAgentOsId:e})}function L_(){if(it()){au=null;return}sn().remove(gs);let e={...Cr()};delete e.chatBoxCredential,delete e.chatBoxCredentialAgentOsId,aa(e)}function B_(){let e=sn();return process.env.KYNVER_API_KEY?{backend:e.backend,apiKey:"env"}:e.read(ms)?{backend:e.backend,apiKey:"keychain"}:Cr().apiKey?{backend:e.backend,apiKey:"file"}:{backend:e.backend,apiKey:"none"}}function me(e){let t=la(e);return t||W_("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),t}function zn(e){return la(e)}function la(e){let t=e||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||A().apiBaseUrl;return hr(t)}function cV(e,t){let r=e||Be(t)||(t?void 0:Be(A().agentOsId));if(r)return String(r);let n=Ne("KYNVER_RUNTIME_SECRET")||Ne("KYNVER_CRON_SECRET")||Ne("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 uu(e,t,r){let n=cV(e,t);if(n)return{ok:!0,secret:n};let o=Ce(),s=la(r?.baseUrl);if(o&&t&&s)try{let i=await Xn(t,{baseUrl:s,apiKey:o});return Yn(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 ye(e,t,r){let n=await uu(e,t,r);if(n.ok)return n.secret;W_(n.reason)}async function U_(e,t){let r=Ce(),n=la(t?.baseUrl);if(!r||!e||!n)return null;try{let o=await Xn(e,{baseUrl:n,apiKey:r});return Yn(e,o),o}catch{return null}}async function F_(e,t,r){let n=Ce(),o=la(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 Xn(t,{baseUrl:o,apiKey:n});return s&&s!==e?(Yn(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 Xn(e,t){let r=t?.apiKey||Ce();if(!r)throw new Error("API key required \u2014 run `kynver login` first");let o=`${me(t?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(e)}/runner-credentials`,s=await bt(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 W_(e){console.error(e),process.exit(1)}var lu,kg,bg,sV,iV,Hpe,jpe,lV,au,$=p(()=>{"use strict";$i();ht();Om();Dm();yr();Ke();zo();ta();Gi();oa();dg();ia();Vn();__();Tt();yg();lu=vg.join(oV(),".kynver"),kg=vg.join(lu,"config.json"),bg=vg.join(lu,"credentials"),sV=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,iV=new Set(["aos","aos-1","agent-os-id","agentosid","agent_os_id","<agent-os-id>","<agentosid>","todo","changeme","change-me","placeholder"]);Hpe=500*1024*1024,jpe=4*1024*1024*1024;lV={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:N_(ms,"apiKey")},getRunnerToken(e){let t=Cr();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){T_(ms,"apiKey",e)},persistRunnerToken(e,t){aa({...Cr(),runnerToken:t,runnerTokenAgentOsId:e})}};au=null});import xg from"node:path";function Ue(e){return Zc(e)}function vt(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return Ue(e);let t=A(),r=t.harnessRoot?.trim();if(r)return Ue(r);let n=qt(t,process.env);return n.identity?n.identity.harnessRoot:eu({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function ut(e){return xg.join(Ue(e),"runs")}function ys(e){return xg.join(Ue(e),"worktrees")}function K_(){let e=vt();return{harnessRoot:e,runsDir:ut(e),worktreesDir:ys(e)}}function Er(e,t){return xg.join(e,F(t))}var Lt=p(()=>{"use strict";$();ug();Vn();U()});import{existsSync as du,readdirSync as uV,statSync as dV}from"node:fs";import Qn from"node:path";function ke(){return K_()}function oe(e){let{runsDir:t}=ke(),r=Qn.join(Er(t,F(e)),"run.json");return du(r)||yt(`run '${e}' not found`),K(r)}function xe(){let{runsDir:e}=ke();return $_(e)}function pu(e){return $_(ut(e))}function pV(e){try{return dV(e).isDirectory()}catch{return!1}}function $_(e){if(!du(e))return[];let t=[];for(let r of uV(e,{withFileTypes:!0})){if(r.name==="runs")continue;let n=Qn.join(e,r.name);if(!pV(n))continue;let o=K(Qn.join(n,"run.json"),void 0);o?.id&&t.push(o)}return t}function Zn(e,t){let{runsDir:r}=ke(),n=Qn.join(Er(r,F(e)),"run.json"),o=Qn.join(Er(r,F(e)),"workers",F(t),"worker.json");return du(o)||(du(n)||yt(`run '${e}' not found`),yt(`worker '${t}' not found in run '${e}'`)),K(o)}function Qe(e){let{runsDir:t}=ke();we(Qn.join(Er(t,e.id),"run.json"),e)}function te(e,t){let{runsDir:r}=ke();we(Qn.join(Er(r,e),"workers",t.name,"worker.json"),t)}function J(e){let{harnessRoot:t}=ke();return ca(t,e)}function ca(e,t){return Er(ut(e),F(t))}var Q=p(()=>{"use strict";Lt();U()});import fV from"node:path";function mV(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 ks(e){let t=oe(e),r=[];for(let n of Object.keys(t.workers||{})){let o=K(fV.join(J(t.id),"workers",F(n),"worker.json"),void 0);!o?.taskId||!tn(o)||r.push({runId:t.id,workerName:n,taskId:o.taskId,pid:o.pid,...mV(o)})}return r}var fu=p(()=>{"use strict";Q();Kc();U()});function Cg(e){return typeof e=="object"&&e!==null&&e.type===mu}function H_(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=>{Cg(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 j_(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return[];let n=t.collect??ks,o=t.killTree??he,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 mu,gu=p(()=>{"use strict";fu();Go();mu="kynver:daemon-stop"});import{createHash as gV}from"node:crypto";function dt(e){return JSON.stringify(Eg(e))}function Eg(e){if(Array.isArray(e))return e.map(Eg);if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Eg(e[r]);return t}return e}function V_(e){return`ib-${gV("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function ua(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 hu(e){if(!e)return[];let t=[];for(let r of e.split(/[,\s]+/)){let n=ua(r);n&&t.push(n)}return t}function da(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 yu(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 an=p(()=>{"use strict"});import{createHash as hV,createPublicKey as yV,verify as kV}from"node:crypto";function RV(e){return`ca-${hV("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function eo(e,t=process.env){let r=hu(t.KYNVER_COMMAND_AUTH_PUBLIC_KEY);if(r.length>0)return r.find(o=>RV(o)===e)??null;let n=vV[e];return!n||e===G_&&!yu(t)?null:ua(n)}function wV(e){return yV({key:Buffer.concat([bV,Buffer.from(e)]),format:"der",type:"spki"})}function SV(e,t){return!Array.isArray(e)||e.length!==t.length?!1:e.every((r,n)=>typeof r=="string"&&r===t[n])}function _V(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 J_(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!_V(e))return{ok:!1,reason:"malformed command authorization proof"};if(e.payload.agentOsId!==t.agentOsId)return{ok:!1,reason:"agentOsId mismatch"};if(!SV(e.payload.argv,t.argv))return{ok:!1,reason:"argv mismatch"};if(e.payload.exp<=n)return{ok:!1,reason:"proof expired"};let o=eo(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(dt(e.payload),"utf8");return kV(null,i,wV(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 bV,G_,vV,pa=p(()=>{"use strict";an();bV=Buffer.from("302a300506032b6570032100","hex"),G_="ca-6297fb8e1773",vV={[G_]:"16ae5cb2a61f8c94cf1b86e8258f9c2f2ff6aba5e6136250a422209b6e866881","ca-456fd128f3b3":"f29cbd559410c2578d7f9732ccd86570073355ccdb36af0d1b7dff15908466e7","ca-fc6a2e593f40":"9c0d2fec00bdfce3a448d3fb1b9b9ecfe0dad587dd37f4de492ad9ca91f53def"}});function ku(e){let t=typeof e.description=="string"?e.description:"",r=typeof e.executorRef=="string"?e.executorRef:"",o=[...t.matchAll(xV)].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(CV))try{let i=JSON.parse(s[1]);if(i.readOnly===!0||i.executionMode==="read_only")return"read_only"}catch{}return"write"}var xV,CV,Ag=p(()=>{"use strict";xV=/\[execution-mode:\s*(write|read[_-]?only)\s*\]/gi,CV=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/gi});import{createPublicKey as EV,verify as AV}from"node:crypto";function Ig(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 OV.test(i)&&i.length<=512?i:null}function q_(e){let t=e.task??{};return e.landPrDispatch===!0||t.executor==="land_pr"?"land_pr":t.executor==="verify_live"?"verify_live":ku(t)==="read_only"?"read_only":"write"}function TV(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(",")!==[...PV].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)||!bu.includes(r.operationClass))}function Y_(e,t,r=process.env,n=Math.floor(Date.now()/1e3)){if(!TV(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+IV+60)return{ok:!1,code:"malformed",reason:"authorization lifetime exceeds the allowed window"};let s=eo(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=EV({key:Buffer.concat([NV,Buffer.from(s)]),format:"der",type:"spki"});return AV(null,Buffer.from(dt(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 IV,bu,PV,OV,NV,z_=p(()=>{"use strict";pa();an();Ag();IV=120,bu=["write","read_only","land_pr","verify_live"],PV=["agentOsId","attempt","exp","kind","leaseOwner","leaseToken","operationClass","repoIdentity","requestNonce","taskId","tenantId","v"],OV=/^[a-z0-9.-]+(?::\d+)?(?:\/[A-Za-z0-9._~-]+){2,}$/;NV=Buffer.from("302a300506032b6570032100","hex")});import{spawnSync as DV}from"node:child_process";import{randomBytes as MV}from"node:crypto";function X_(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!==LV)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"||!BV.test(t.agentOsId))return"invalid agentOsId";if(typeof t.repoIdentity!="string"||Ig(`https://${t.repoIdentity}`)!==t.repoIdentity)return"invalid repoIdentity";let n=t.approvedOperationClasses;if(!Array.isArray(n)||n.length>bu.length)return"invalid approvedOperationClasses";let o=new Set;for(let s of n){if(typeof s!="string"||!bu.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 UV(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=q_(e.decision),a=Y_(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 Z_(){return it()}function ex(e){return fa&&e.revision<fa.revision?!1:(fa=e,!0)}function Tg(){return fa}function tx(e){Q_=e}function rx(e){return Og.add(e),()=>Og.delete(e)}function nx(e){return{v:1,repoIdentity:e,requestNonce:MV(16).toString("base64url")}}function vu(e){let t=DV("git",["-C",e,"remote","get-url","origin"],Z({encoding:"utf8",timeout:1e4}));return t.status!==0||typeof t.stdout!="string"?null:Ig(t.stdout.trim())}function ox(e){let t=UV({...e,policy:fa,identity:Q_,consumed:FV});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 Og)try{o(n)}catch{}}return t}var LV,BV,Pg,fa,Q_,FV,Og,Ru=p(()=>{"use strict";Tt();z_();U();LV=1,BV=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;Pg=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}};fa=null,Q_=null,FV=new Pg,Og=new Set});import{createCipheriv as WV,createDecipheriv as KV,randomBytes as Dg,scrypt as $V,timingSafeEqual as HV}from"node:crypto";function ix(){return Dg(Mg)}function ax(e=jV){return{name:"scrypt",N:e.N,r:e.r,p:e.p,salt:Dg(16).toString("base64")}}function Bg(e,t,r=VV){if(t.name!=="scrypt"||!Number.isInteger(t.N)||t.N<r||t.r<8||t.p<1)return Promise.reject(new Bt("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 Bt("the vault file's salt is invalid")):new Promise((o,s)=>{$V(e.normalize("NFKC"),n,Mg,{N:t.N,r:t.r,p:t.p,maxmem:128*t.N*t.r*2},(i,a)=>i?s(i):o(a))})}function ln(e,t,r){if(e.length!==Mg)throw new Bt("bad key length");let n=Dg(sx),o=WV("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 to(e,t,r){try{let n=Buffer.from(t.n,"base64"),o=Buffer.from(t.c,"base64");if(n.length!==sx||o.length<Ng)throw new Bt;let s=KV("aes-256-gcm",e,n);return s.setAAD(Buffer.from(r,"utf8")),s.setAuthTag(o.subarray(o.length-Ng)),Buffer.concat([s.update(o.subarray(0,o.length-Ng)),s.final()])}catch(n){throw n instanceof Bt?n:new Bt}}function Ug(e){for(let t of e)if(t.includes(`
|
|
80
|
+
`))throw new Bt("invalid vault field");return e.join(`
|
|
81
|
+
`)}function Wg(e){return Ug(["kynver-site-login/v1/record",e.agentOsId,e.handle,e.origin,e.label,e.username,e.hasTotp?"totp":"no-totp"])}function lx(e,t){return e.length===t.length&&HV(e,t)}var Mg,sx,Ng,jV,VV,Lg,Bt,Fg,wu,Su,Kg=p(()=>{"use strict";Mg=32,sx=12,Ng=16,jV={N:2**17,r:8,p:1},VV=2**14,Lg=10,Bt=class extends Error{constructor(t="the saved-login vault could not be decrypted"){super(t),this.name="VaultCryptoError"}};Fg=e=>Ug(["kynver-site-login/v1/vault-key",e]),wu=e=>Ug(["kynver-site-login/v1/key-check",e]),Su=Buffer.from("kynver-site-login-key-check-v1","utf8")});function cx(e,t={}){if(typeof e!="string"||!e.trim())return{ok:!1,reason:"a site address is required"};let r=e.trim();/^[a-z][a-z0-9+.-]*:/i.test(r)||(r=`https://${r}`);let n;try{n=new URL(r)}catch{return{ok:!1,reason:"not a valid web address"}}return n.protocol!=="https:"?{ok:!1,reason:"saved logins are only used on https:// sites"}:n.username||n.password?{ok:!1,reason:"the address must not contain a username or password"}:t.allowLan===!0&&JV.test(n.hostname)&&n.hostname.split(".").every(s=>Number(s)<=255)?{ok:!0,origin:n.origin,unicodeHost:!1}:!n.hostname.includes(".")||GV.test(n.hostname)?{ok:!1,reason:"use the site's public address (e.g. https://www.instagram.com)"}:{ok:!0,origin:n.origin,unicodeHost:n.hostname.split(".").some(s=>s.startsWith("xn--"))}}function ma(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 $g(e,t){let r=ma(t);return r!==null&&r===e}var GV,JV,Hg=p(()=>{"use strict";GV=/^(localhost|.*\.localhost|.*\.local|.*\.internal|0\.0\.0\.0|\[.*\]|\d{1,3}(\.\d{1,3}){3})$/i,JV=/^(10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})$/});import{createHmac as qV}from"node:crypto";function ux(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|YV.indexOf(s),r+=5,r>=8&&(o.push(n>>>r-8&255),r-=8);return o.length?Buffer.from(o):null}function _u(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=ux(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=ux(t);return r?{key:r,algorithm:"SHA1",digits:6,period:30}:null}function zV(e,t,r,n){let o=Buffer.alloc(8);o.writeBigUInt64BE(t);let s=qV(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 dx(e,t=Date.now()){let r=BigInt(Math.floor(t/1e3/e.period));return zV(e.key,r,e.digits,e.algorithm)}function px(e,t=Date.now()){let r=Math.floor(t/1e3)%e.period;return e.period-r}var YV,jg=p(()=>{"use strict";YV="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"});var Ge,xu=p(()=>{"use strict";Ge={maxRecords:200,maxLabel:80,maxUsername:254,maxPassword:1024,maxTotp:512}});import{createHash as XV,randomBytes as gx}from"node:crypto";import{chmodSync as fx,existsSync as QV,mkdirSync as ZV,readFileSync as eG,renameSync as tG,rmSync as rG,writeFileSync as nG}from"node:fs";import{homedir as oG}from"node:os";import hx from"node:path";function ga(){return hx.join(oG(),".kynver","site-logins")}function Vg(e){return`${XV("sha256").update(`kynver-site-login:${e}`).digest("hex").slice(0,32)}.vault.json`}function mx(e,t,r,n=!0){let o=typeof e=="string"?e.trim():"";if(!o&&n)throw new q(`${t} is required`,"invalid");if(o.length>r)throw new q(`${t} is too long (max ${r})`,"invalid");if(yx.test(o))throw new q(`${t} contains control characters`,"invalid");return o}function sG(){let e="abcdefghijkmnpqrstuvwxyz23456789",t=gx(10);return`lg_${Array.from(t,r=>e[r%e.length]).join("")}`}var q,yx,Cu,cn=p(()=>{"use strict";Kg();Hg();jg();xu();q=class extends Error{constructor(r,n){super(r);this.code=n;this.name="SiteLoginError"}code},yx=/[\u0000-\u001f\u007f]/;Cu=class{constructor(t){this.opts=t;let r=t.agentOsId.trim();if(!r||yx.test(r)||r.length>200)throw new q("invalid workspace id","invalid");this.agentOsId=r,this.rootDir=t.rootDir??ga(),this.filePath=hx.join(this.rootDir,Vg(r)),this.now=t.now??Date.now}opts;agentOsId;filePath;rootDir;now;exists(){return QV(this.filePath)}keyMode(){return this.exists()?this.read().keyMode:null}async createWithPassphrase(t){if(this.exists())throw new q("a saved-login vault already exists on this computer","exists");if(t.length<Lg)throw new q(`the vault passphrase must be at least ${Lg} characters`,"invalid");let r=ix(),n=ax(this.opts.scryptCost),o=await Bg(t,n,this.opts.minScryptN);return this.write({v:1,agentOsId:this.agentOsId,keyMode:"passphrase",kdf:n,wrappedKey:ln(o,r,Fg(this.agentOsId)),keyCheck:ln(r,Su,wu(this.agentOsId)),records:[]}),o.fill(0),r}createWithKeychainKey(t){if(this.exists())throw new q("a saved-login vault already exists on this computer","exists");this.write({v:1,agentOsId:this.agentOsId,keyMode:"keychain",keyCheck:ln(t,Su,wu(this.agentOsId)),records:[]})}async unlockWithPassphrase(t){let r=this.read();if(r.keyMode!=="passphrase"||!r.kdf||!r.wrappedKey)throw new q("this vault is unlocked by the Kynver desktop app, not a passphrase","invalid");let n=null;try{n=await Bg(t,r.kdf,this.opts.minScryptN);let o=to(n,r.wrappedKey,Fg(this.agentOsId));return this.verifyKey(r,o),o}catch(o){throw o instanceof q?o:o instanceof Bt&&/unsafe|salt/.test(o.message)?new q(o.message,"corrupt"):new q("wrong vault passphrase","bad_key")}finally{n?.fill(0)}}unlockWithKey(t){return this.verifyKey(this.read(),t),t}wipe(){return this.exists()?(rG(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>=Ge.maxRecords)throw new q(`at most ${Ge.maxRecords} saved logins per workspace`,"full");let o=this.buildRecord(t,r,sG(),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 q("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 q("no saved login with that id","not_found");let s;try{s=to(t,o.secret,Wg({agentOsId:this.agentOsId,...o}))}catch{throw new q("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 q("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=cx(r.origin,{allowLan:r.allowLan===!0});if(!s.ok)throw new q(s.reason,"invalid");let i=mx(r.label,"label",Ge.maxLabel),a=mx(r.username,"username",Ge.maxUsername),l=typeof r.password=="string"?r.password:"";if(!l)throw new q("password is required","invalid");if(l.length>Ge.maxPassword)throw new q("password is too long","invalid");let c=typeof r.totp=="string"&&r.totp.trim()?r.totp.trim():void 0;if(c&&(c.length>Ge.maxTotp||!_u(c)))throw new q("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:ln(t,d,Wg({agentOsId:this.agentOsId,...u}))}}finally{d.fill(0)}}verifyKey(t,r){try{let n=to(r,t.keyCheck,wu(this.agentOsId));if(!lx(n,Su))throw new Error("mismatch")}catch{throw new q("the vault key does not open this vault","bad_key")}}read(){if(!this.exists())throw new q("no saved-login vault on this computer yet","missing");let t;try{t=JSON.parse(eG(this.filePath,"utf8"))}catch{throw new q("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 q("the saved-login vault file is not a vault Kynver understands","corrupt");if(t.agentOsId!==this.agentOsId)throw new q("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){ZV(this.rootDir,{recursive:!0,mode:448});try{fx(this.rootDir,448)}catch{}let r=`${this.filePath}.${gx(4).toString("hex")}.tmp`;nG(r,`${JSON.stringify(t)}
|
|
82
|
+
`,{mode:384}),tG(r,this.filePath);try{fx(this.filePath,384)}catch{}}}});import{appendFileSync as lG,chmodSync as cG,existsSync as Rx,mkdirSync as uG,readFileSync as wx,renameSync as dG,statSync as pG,writeFileSync as fG}from"node:fs";import mG from"node:path";var gG,Sx,hG,Eu,_x=p(()=>{"use strict";cn();gG=512*1024,Sx=1e3,hG=10080*60*1e3,Eu=class{constructor(t,r=ga(),n=Date.now){this.rootDir=r;this.now=n;this.filePath=mG.join(r,Vg(t).replace(/\.vault\.json$/,".audit.jsonl"))}rootDir;now;filePath;record(t){let r={at:new Date(this.now()).toISOString(),...t};try{uG(this.rootDir,{recursive:!0,mode:448}),this.rotateIfLarge(),lG(this.filePath,`${JSON.stringify(r)}
|
|
83
|
+
`,{mode:384}),cG(this.filePath,384)}catch{}return r}entries(t=Sx){if(!Rx(this.filePath))return[];try{return wx(this.filePath,"utf8").split(`
|
|
84
|
+
`).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=hG){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(!Rx(this.filePath)||pG(this.filePath).size<gG)return;let t=wx(this.filePath,"utf8").split(`
|
|
85
|
+
`).filter(Boolean).slice(-Sx/2),r=`${this.filePath}.tmp`;fG(r,`${t.join(`
|
|
86
86
|
`)}
|
|
87
|
-
`,{mode:384}),sG(r,this.filePath)}}});import{randomBytes as dG}from"node:crypto";import{existsSync as pG,rmSync as fG}from"node:fs";function vx(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 Qe(){return Rx??=new Kg,Rx}var mG,gG,Kg,Rx,bs=p(()=>{"use strict";bx();ln();mG=720*60*1e3,gG=300*1e3,Kg=class{rootDir;now;idleMs;keys=new Map;codes=new Map;codeListeners=new Set;constructor(t={}){this.rootDir=t.rootDir??ma(),this.now=t.now??Date.now,this.idleMs=t.idleMs??mG}store(t){return new xu({agentOsId:t,rootDir:this.rootDir,now:this.now})}audit(t){return new Cu(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 pG(o)&&fG(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_${dG(6).toString("hex")}`,createdAt:r,expiresAt:r+gG};this.codes.set(n.id,n);let o=vx(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=>vx(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)}};Rx=null});var wx=p(()=>{"use strict";B()});var Sx=p(()=>{"use strict";Vo()});var _x=p(()=>{"use strict";$();wx();hr();Sx()});function yG(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 $g(e){if(!e)return null;let t=yG(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 Hg=p(()=>{"use strict"});function xx(e){return/\((?:401|403)\)/.test(e)?"access_denied":"transient"}var jg=p(()=>{"use strict";$();hr();B();_x();Hg()});import{existsSync as kG}from"node:fs";import{homedir as bG}from"node:os";import vG from"node:path";function Cx(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 ga(e,t,r=1){let n=Number(process.env[e]);return!Number.isFinite(n)||n<r?t:Math.floor(n)}function cn(){let e=process.env.KYNVER_CRON_STORE_PATH?.trim()||process.env.OPENCLAW_CRON_STORE_PATH?.trim();return e||vG.join(bG(),".kynver","agent-os-cron.json")}function RG(e=cn()){let t=process.env.KYNVER_CRON_TICK_STATE_PATH?.trim();return t||`${e.replace(/\.json$/i,"")}.tick-state.json`}function wG(){let e=A();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 Ex(){let e=A();return Te("KYNVER_CRON_SECRET")||Te("OPENCLAW_CRON_SECRET")||Te("KYNVER_RUNTIME_SECRET")||Le(e.agentOsId)?.trim()||Le()?.trim()||null}function vs(){let e=cn(),t=RG(e),r=wG(),n=Ex(),o=!!(r&&n),s=kG(e),i=o&&(s||Cx("KYNVER_CRON_TICK_FORCE",!1));return{storePath:e,statePath:t,lockPath:`${t}.lock`,fireBaseUrl:r,secret:n,tickEnabled:Cx("KYNVER_CRON_TICK_ENABLED",i),tickIntervalMs:ga("KYNVER_CRON_TICK_INTERVAL_MS",6e4,5e3),missedRunPolicy:process.env.KYNVER_CRON_MISSED_RUN_POLICY?.trim().toLowerCase()==="skip"?"skip":"catch_up",maxCatchUpPerTick:ga("KYNVER_CRON_MAX_CATCH_UP_PER_TICK",3,0),maxRetries:ga("KYNVER_CRON_MAX_RETRIES",3,0),retryBackoffMs:ga("KYNVER_CRON_RETRY_BACKOFF_MS",6e4,1e3),inflightLeaseMs:ga("KYNVER_CRON_INFLIGHT_LEASE_MS",12e4,5e3)}}var Er=p(()=>{"use strict";$();Ot()});import{promises as SG}from"node:fs";async function Ax(e){try{return await SG.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function _G(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t.entries)?t.entries:[]}catch{return[]}}async function Eu(e=cn()){let t=await Ax(e);return _G(t)}async function xG(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 Vg(e=cn()){return await Ax(e)!==null?{created:!1}:(await xG(e,[]),{created:!0})}var Rs=p(()=>{"use strict";Er()});import{existsSync as CG,readFileSync as EG}from"node:fs";import{dirname as Gg,join as Px}from"node:path";import{fileURLToPath as Ix}from"node:url";function AG(e){let t=Gg(Ix(e));for(let r=0;r<6;r+=1){if(CG(Px(t,"package.json")))return t;let n=Gg(t);if(n===t)break;t=n}throw new Error(`package.json not found above ${Gg(Ix(e))}`)}function IG(e=import.meta.url){let t=Px(AG(e),"package.json"),r=JSON.parse(EG(t,"utf8"));if(typeof r.version!="string"||!r.version.trim())throw new Error(`Missing package.json version at ${t}`);return r.version}var Ze,un=p(()=>{"use strict";Ze=IG()});import{spawnSync as PG}from"node:child_process";import{readFileSync as OG}from"node:fs";function TG(e,t){let r=PG(e,t,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:15e3});return{status:r.status,stdout:r.stdout??""}}function NG(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 DG(e){return Number.isInteger(e)&&e>0}function Ox(e,t={}){if(!DG(e))return null;let r=t.platform??process.platform,n=t.readText??(s=>OG(s,"utf8")),o=t.run??TG;try{if(r==="linux"){let s=NG(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 Jg=p(()=>{"use strict"});import{createHash as LG,randomUUID as Bx}from"node:crypto";import{closeSync as BG,constants as qg,existsSync as UG,mkdirSync as Yg,openSync as FG,readFileSync as WG,renameSync as zg,rmSync as Au,writeFileSync as KG}from"node:fs";import{createConnection as $G,createServer as Tx}from"node:net";import{homedir as HG,tmpdir as jG}from"node:os";import qt from"node:path";function VG(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function Ux(e){let t=e.stateRoot??qt.join(HG(),".kynver"),r=e.platform??process.platform,n=LG("sha256").update(`${qt.resolve(t)}\0${e.agentOsId}`).digest("hex").slice(0,24),o=qt.join(t,"locks"),s=qt.join(o,`${n.slice(0,16)}.sock`);r==="linux"?s=`\0kynver-daemon-owner-${n}`:Buffer.byteLength(s)>100&&(s=qt.join(jG(),`kynver-owner-${n.slice(0,16)}.sock`));let i=qt.join(t,`daemon-owner-${VG(e.agentOsId)}.json`);return{lockKey:n,lockFile:qt.join(o,`daemon-owner-${n}.lock`),metadataFile:i,quarantineFile:i.replace(/\.json$/,".stale.json"),socketAddress:s}}function JG(e){Yg(qt.dirname(e),{recursive:!0});let t;try{t=FG(e,qg.O_RDWR|qg.O_CREAT|GG)}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{BG(t)}catch{}}}}}}function Nx(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 qG(e,t=2e3){return new Promise(r=>{let n=$G({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 YG(e,t){e.startsWith("\0")||Yg(qt.dirname(e),{recursive:!0,mode:448});let r=Tx(a=>a.destroy());if(await Nx(r,e)==="listening")return{held:Dx(r,e)};if(!t||e.startsWith("\0"))return{busy:!0};if(await qG(e))return{busy:!0};let o=`${e}.stale-${process.pid}-${Bx().slice(0,8)}`;try{zg(e,o),Au(o,{force:!0})}catch{}let s=Tx(a=>a.destroy());return await Nx(s,e).catch(()=>"in_use")==="listening"?{held:Dx(s,e)}:{busy:!0}}function Dx(e,t){e.unref();let r=!0;return{isHeld:()=>r&&e.listening,release:()=>{r&&(r=!1,e.close(),t.startsWith("\0")||Au(t,{force:!0}))}}}async function zG(e,t){return t==="win32"?JG(e.lockFile):YG(e.socketAddress,t!=="linux")}function XG(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 Mx(e){try{let t=JSON.parse(WG(Ux(e).metadataFile,"utf8"));return XG(t)?t:null}catch{return null}}function Lx(e,t){Yg(qt.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;KG(r,`${JSON.stringify(t,null,2)}
|
|
88
|
-
`,{mode:384}),
|
|
87
|
+
`,{mode:384}),dG(r,this.filePath)}}});import{randomBytes as yG}from"node:crypto";import{existsSync as kG,rmSync as bG}from"node:fs";function xx(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 Ze(){return Cx??=new Gg,Cx}var vG,RG,Gg,Cx,vs=p(()=>{"use strict";_x();cn();vG=720*60*1e3,RG=300*1e3,Gg=class{rootDir;now;idleMs;keys=new Map;codes=new Map;codeListeners=new Set;constructor(t={}){this.rootDir=t.rootDir??ga(),this.now=t.now??Date.now,this.idleMs=t.idleMs??vG}store(t){return new Cu({agentOsId:t,rootDir:this.rootDir,now:this.now})}audit(t){return new Eu(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 kG(o)&&bG(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_${yG(6).toString("hex")}`,createdAt:r,expiresAt:r+RG};this.codes.set(n.id,n);let o=xx(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=>xx(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)}};Cx=null});var Ex=p(()=>{"use strict";U()});var Ax=p(()=>{"use strict";Go()});var Ix=p(()=>{"use strict";$();Ex();yr();Ax()});function SG(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 Jg(e){if(!e)return null;let t=SG(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 qg=p(()=>{"use strict"});function Px(e){return/\((?:401|403)\)/.test(e)?"access_denied":"transient"}var Yg=p(()=>{"use strict";$();yr();U();Ix();qg()});import{existsSync as _G}from"node:fs";import{homedir as xG}from"node:os";import CG from"node:path";function Ox(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 ha(e,t,r=1){let n=Number(process.env[e]);return!Number.isFinite(n)||n<r?t:Math.floor(n)}function un(){let e=process.env.KYNVER_CRON_STORE_PATH?.trim()||process.env.OPENCLAW_CRON_STORE_PATH?.trim();return e||CG.join(xG(),".kynver","agent-os-cron.json")}function EG(e=un()){let t=process.env.KYNVER_CRON_TICK_STATE_PATH?.trim();return t||`${e.replace(/\.json$/i,"")}.tick-state.json`}function AG(){let e=A();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 Tx(){let e=A();return Ne("KYNVER_CRON_SECRET")||Ne("OPENCLAW_CRON_SECRET")||Ne("KYNVER_RUNTIME_SECRET")||Be(e.agentOsId)?.trim()||Be()?.trim()||null}function Rs(){let e=un(),t=EG(e),r=AG(),n=Tx(),o=!!(r&&n),s=_G(e),i=o&&(s||Ox("KYNVER_CRON_TICK_FORCE",!1));return{storePath:e,statePath:t,lockPath:`${t}.lock`,fireBaseUrl:r,secret:n,tickEnabled:Ox("KYNVER_CRON_TICK_ENABLED",i),tickIntervalMs:ha("KYNVER_CRON_TICK_INTERVAL_MS",6e4,5e3),missedRunPolicy:process.env.KYNVER_CRON_MISSED_RUN_POLICY?.trim().toLowerCase()==="skip"?"skip":"catch_up",maxCatchUpPerTick:ha("KYNVER_CRON_MAX_CATCH_UP_PER_TICK",3,0),maxRetries:ha("KYNVER_CRON_MAX_RETRIES",3,0),retryBackoffMs:ha("KYNVER_CRON_RETRY_BACKOFF_MS",6e4,1e3),inflightLeaseMs:ha("KYNVER_CRON_INFLIGHT_LEASE_MS",12e4,5e3)}}var Ar=p(()=>{"use strict";$();Tt()});import{promises as IG}from"node:fs";async function Nx(e){try{return await IG.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function PG(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t.entries)?t.entries:[]}catch{return[]}}async function Au(e=un()){let t=await Nx(e);return PG(t)}async function OG(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 zg(e=un()){return await Nx(e)!==null?{created:!1}:(await OG(e,[]),{created:!0})}var ws=p(()=>{"use strict";Ar()});import{existsSync as TG,readFileSync as NG}from"node:fs";import{dirname as Xg,join as Mx}from"node:path";import{fileURLToPath as Dx}from"node:url";function DG(e){let t=Xg(Dx(e));for(let r=0;r<6;r+=1){if(TG(Mx(t,"package.json")))return t;let n=Xg(t);if(n===t)break;t=n}throw new Error(`package.json not found above ${Xg(Dx(e))}`)}function MG(e=import.meta.url){let t=Mx(DG(e),"package.json"),r=JSON.parse(NG(t,"utf8"));if(typeof r.version!="string"||!r.version.trim())throw new Error(`Missing package.json version at ${t}`);return r.version}var et,dn=p(()=>{"use strict";et=MG()});import{spawnSync as LG}from"node:child_process";import{readFileSync as BG}from"node:fs";function UG(e,t){let r=LG(e,t,{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:15e3});return{status:r.status,stdout:r.stdout??""}}function FG(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 WG(e){return Number.isInteger(e)&&e>0}function Lx(e,t={}){if(!WG(e))return null;let r=t.platform??process.platform,n=t.readText??(s=>BG(s,"utf8")),o=t.run??UG;try{if(r==="linux"){let s=FG(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 Qg=p(()=>{"use strict"});import{createHash as $G,randomUUID as $x}from"node:crypto";import{closeSync as HG,constants as Zg,existsSync as jG,mkdirSync as eh,openSync as VG,readFileSync as GG,renameSync as th,rmSync as Iu,writeFileSync as JG}from"node:fs";import{createConnection as qG,createServer as Bx}from"node:net";import{homedir as YG,tmpdir as zG}from"node:os";import Yt from"node:path";function XG(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function Hx(e){let t=e.stateRoot??Yt.join(YG(),".kynver"),r=e.platform??process.platform,n=$G("sha256").update(`${Yt.resolve(t)}\0${e.agentOsId}`).digest("hex").slice(0,24),o=Yt.join(t,"locks"),s=Yt.join(o,`${n.slice(0,16)}.sock`);r==="linux"?s=`\0kynver-daemon-owner-${n}`:Buffer.byteLength(s)>100&&(s=Yt.join(zG(),`kynver-owner-${n.slice(0,16)}.sock`));let i=Yt.join(t,`daemon-owner-${XG(e.agentOsId)}.json`);return{lockKey:n,lockFile:Yt.join(o,`daemon-owner-${n}.lock`),metadataFile:i,quarantineFile:i.replace(/\.json$/,".stale.json"),socketAddress:s}}function ZG(e){eh(Yt.dirname(e),{recursive:!0});let t;try{t=VG(e,Zg.O_RDWR|Zg.O_CREAT|QG)}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{HG(t)}catch{}}}}}}function Ux(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 eJ(e,t=2e3){return new Promise(r=>{let n=qG({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 tJ(e,t){e.startsWith("\0")||eh(Yt.dirname(e),{recursive:!0,mode:448});let r=Bx(a=>a.destroy());if(await Ux(r,e)==="listening")return{held:Fx(r,e)};if(!t||e.startsWith("\0"))return{busy:!0};if(await eJ(e))return{busy:!0};let o=`${e}.stale-${process.pid}-${$x().slice(0,8)}`;try{th(e,o),Iu(o,{force:!0})}catch{}let s=Bx(a=>a.destroy());return await Ux(s,e).catch(()=>"in_use")==="listening"?{held:Fx(s,e)}:{busy:!0}}function Fx(e,t){e.unref();let r=!0;return{isHeld:()=>r&&e.listening,release:()=>{r&&(r=!1,e.close(),t.startsWith("\0")||Iu(t,{force:!0}))}}}async function rJ(e,t){return t==="win32"?ZG(e.lockFile):tJ(e.socketAddress,t!=="linux")}function nJ(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 Wx(e){try{let t=JSON.parse(GG(Hx(e).metadataFile,"utf8"));return nJ(t)?t:null}catch{return null}}function Kx(e,t){eh(Yt.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;JG(r,`${JSON.stringify(t,null,2)}
|
|
88
|
+
`,{mode:384}),th(r,e)}function oJ(e){if(!jG(e.metadataFile))return null;try{return th(e.metadataFile,e.quarantineFile),e.quarantineFile}catch{return Iu(e.metadataFile,{force:!0}),null}}function jx(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 Pu(e){let t=e.platform??process.platform,r=Hx(e),n=await rJ(r,t);if("busy"in n){let u=Wx(e);return{ok:!1,reason:"owner_conflict",holder:u,remedy:jx(u)}}let o=oJ(r),s=(e.now??new Date).toISOString(),i={version:1,agentOsId:e.agentOsId,ownerKind:e.ownerKind,instanceId:$x(),pid:process.pid,processStart:e.processStart!==void 0?e.processStart:Lx(process.pid),runtimeVersion:et,platform:t,acquiredAt:s,lastRenewedAt:s};try{Kx(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{Kx(r.metadataFile,i)}catch{}}},release(){if(l)return;l=!0,Wx(e)?.instanceId===i.instanceId&&Iu(r.metadataFile,{force:!0}),a.release()}},quarantinedMetadata:o}}var QG,Ou=p(()=>{"use strict";dn();Qg();QG=Zg.UV_FS_O_EXLOCK??268435456});var sJ,iJ,aJ,lJ,Ss,rh=p(()=>{"use strict";sJ="embedded-1",iJ=[{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"}],aJ={"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(`
|
|
89
89
|
`),"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(`
|
|
90
90
|
`),"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(`
|
|
91
91
|
`),"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(`
|
|
92
|
-
`)},
|
|
92
|
+
`)},lJ={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},Ss={version:sJ,generatedAt:"1970-01-01T00:00:00.000Z",personas:iJ,instructions:aJ,policyThresholds:lJ}});function Gx(){return _s}function no(){return _s.version}function zt(){return Vx}function Jx(e,t){_s=e,Vx=t}function ya(e){let t=_s.instructions[e];if(typeof t=="string"&&t.trim())return t;let r=Ss.instructions[e];return typeof r=="string"?r:""}function xs(e,t){let r=_s.policyThresholds[e];if(typeof r=="number"&&Number.isFinite(r))return r;let n=Ss.policyThresholds[e];return typeof n=="number"&&Number.isFinite(n)?n:t}function qx(e){if(!e)return null;let t=e.trim().toLowerCase();return _s.personas.find(r=>r.slug===t)??null}var _s,Vx,pn=p(()=>{"use strict";rh();_s=Ss,Vx="embedded"});import Yx from"node:os";function Ir(e){return e?.trim()?e.trim():null}function Fe(e={}){let t=e.env??process.env,r=A();return{runnerId:Ir(r.runnerId)??Ir(t.KYNVER_RUNTIME_ID)??Ir(t.OPENCLAW_RUNTIME_ID)??Ir(t.HOSTNAME)??Yx.hostname(),hostname:Ir(t.HOSTNAME)??Yx.hostname(),profile:Ir(t.KYNVER_RUNNER_PROFILE)??Ir(t.OPENCLAW_RUNNER_PROFILE),harnessRepo:Ir(t.KYNVER_HARNESS_REPO)??Ir(t.KYNVER_DEFAULT_REPO),runId:e.runId??null,instructionBundleVersion:no()}}var Pr=p(()=>{"use strict";$();pn();Ke()});import cJ from"node:os";function nh(e=A(),t=process.env){let r=lt(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=qt(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=Xc(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=sa(r.boxKind,cJ.hostname()),s=!0,n.push(`persisted boxId=${i.boxId} to ~/.kynver/config.json`)),Vi(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=kr(r.boxKind,o);c!==o&&(o=c,i.maxConcurrentWorkers=c,s=!0,n.push(`clamped maxConcurrentWorkers to ${c} for ${r.boxKind} pool`))}return s&&je(i),{repaired:s,boxKind:r.boxKind,maxConcurrentWorkers:o??4,warnings:n}}var oh=p(()=>{"use strict";$();Ke();ds();zo();Vn()});function Ut(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 Cs=p(()=>{"use strict"});function uJ(e){let t=e.runnerId??Fe().runnerId;return`${e.baseUrl.replace(/\/+$/,"")}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/runtime-control/runner?runnerId=${encodeURIComponent(t)}`}async function zx(e,t){try{return(await(e.fetchImpl??fetch)(uJ(e),{method:"POST",headers:Ut(e.secret),body:JSON.stringify({ack:t})})).ok}catch{return!1}}var sh=p(()=>{"use strict";Cs();Pr();on()});var Xx=p(()=>{"use strict";$();U();sh();on()});function Qx(){let e=process.env.KYNVER_GIT_COMMIT_SHA?.trim();return{contractVersion:1,nodeVersion:process.versions.node,runtimePackageVersion:et,buildIdentity:e&&dJ.test(e)?e.toLowerCase():null,platform:process.platform,arch:process.arch}}var dJ,Zx=p(()=>{"use strict";dn();dJ=/^[0-9a-f]{7,40}$/i});import{mkdirSync as pJ,readFileSync as vge,renameSync as fJ,writeFileSync as mJ}from"node:fs";import{homedir as gJ}from"node:os";import eC from"node:path";function hJ(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return eC.join(gJ(),".kynver",`daemon-heartbeat-${t}.json`)}function tC(e){try{let t=hJ(e.agentOsId);pJ(eC.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:Qx(),...e.owner?{owner:e.owner}:{}},n=`${t}.tmp-${process.pid}`;mJ(n,JSON.stringify(r),"utf8"),fJ(n,t)}catch{}}var ih=p(()=>{"use strict";Zx();Qg()});function ah(e,t,r=6e4){let n=t-e;return n>r?n:null}var lh=p(()=>{"use strict"});function kJ(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 rC(e,t){let r=kJ(e);if(r!==null&&r>1)throw new ch(r,1);e.exec("BEGIN IMMEDIATE");try{for(let n of yJ)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 ch,yJ,nC=p(()=>{"use strict";ch=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"}},yJ=[`CREATE TABLE IF NOT EXISTS local_meta (
|
|
93
93
|
key TEXT PRIMARY KEY,
|
|
94
94
|
value TEXT NOT NULL
|
|
95
95
|
) STRICT`,`CREATE TABLE IF NOT EXISTS process_identity (
|
|
@@ -115,8 +115,8 @@ child.on("exit", (code, signal) => finish(code, signal));
|
|
|
115
115
|
payload_json TEXT NOT NULL,
|
|
116
116
|
created_at TEXT NOT NULL,
|
|
117
117
|
PRIMARY KEY (scope, seq)
|
|
118
|
-
) STRICT`]});import{existsSync as
|
|
119
|
-
`)){let n=r.trim().split(/\s+/);n.length<3||t.push({mountPoint:
|
|
118
|
+
) STRICT`]});import{existsSync as bJ,realpathSync as vJ,readFileSync as RJ}from"node:fs";import oC from"node:path";function _J(){try{return RJ("/proc/self/mounts","utf8")}catch{return null}}function xJ(e){let t=oC.resolve(e);for(let r=0;r<64;r+=1){if(bJ(t))try{return vJ.native(t)}catch{return t}let n=oC.dirname(t);if(n===t)return t;t=n}return t}function CJ(e){return e.replace(/\\(\d{3})/g,(t,r)=>String.fromCharCode(Number.parseInt(r,8)))}function EJ(e){let t=[];for(let r of e.split(`
|
|
119
|
+
`)){let n=r.trim().split(/\s+/);n.length<3||t.push({mountPoint:CJ(n[1]),fsType:n[2]})}return t}function sC(e,t=process.platform){return t==="win32"?e.replace(/\\/g,"/"):e}function AJ(e,t){let r=null,n=sC(e);for(let o of t){let s=sC(o.mountPoint),i=s.endsWith("/")?s:`${s}/`;(n===s||`${n}/`.startsWith(i))&&(!r||o.mountPoint.length>r.mountPoint.length)&&(r=o)}return r}function iC(e,t){let n=(t?.resolveRealPath??xJ)(e),o=(t?.mountsSource??_J)();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=AJ(n,EJ(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 SJ.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}:wJ.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 wJ,SJ,aC=p(()=>{"use strict";wJ=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),SJ=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 PJ}from"node:fs";import OJ from"node:path";import{DatabaseSync as TJ}from"node:sqlite";var Nu,NJ,DJ,ka,lC=p(()=>{"use strict";nC();aC();Nu=class extends Error{constructor(t){super(`local-run-store refused: ${t}`),this.name="FilesystemPolicyError"}},NJ="local-run-store.sqlite",DJ=5e3,ka=class e{db;now;databasePath;constructor(t,r,n){this.db=t,this.databasePath=r,this.now=n}static open(t){let r=iC(t.directory,t.classifyOptions);if(r.verdict!=="accepted")throw new Nu(r.reason);PJ(t.directory,{recursive:!0,mode:448});let n=OJ.join(t.directory,t.filename??NJ),o=new TJ(n,{timeout:t.busyTimeoutMs??DJ}),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 Nu(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),rC(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
|
|
120
120
|
(process_key, pid, runtime_version, node_version, started_at, registered_at)
|
|
121
121
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
122
122
|
ON CONFLICT(process_key) DO UPDATE SET
|
|
@@ -140,170 +140,170 @@ child.on("exit", (code, signal) => finish(code, signal));
|
|
|
140
140
|
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
|
|
141
141
|
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)
|
|
142
142
|
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
|
|
143
|
-
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
|
|
144
|
-
`)}var che,uhe,dhe,phe,ch=p(()=>{"use strict";nn();Gx();$();th();B();mu();nh();ba();che=15*6e4,uhe=2*6e4,dhe=5*6e4,phe=30*6e4});import JJ from"node:path";function qJ(e){return JJ.resolve(Ne(e.trim()))}function Es(e,t,r){let n=e?.trim();return n?{repo:qJ(n),source:t,persistedInConfig:r}:null}function kC(e){return e?{repo:e.repo,source:e.source,persistedInConfig:!1}:null}function va(e={}){let t=e.env??process.env,r=e.config??A(),n=Es(r.defaultRepo,"config",!0);if(n)return n;let o=Es(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(o)return o;let s=Es(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return s||kC(bc({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl}))}function bC(e={}){let t=e.env??process.env,r=e.config??A(),n=Es(r.defaultRepo,"config",!0);if(n)return n;let o=Es(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(o)return o;let s=Es(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return s||kC(vc({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl,home:e.home}))}function vC(e,t){let r={...t??A(),defaultRepo:Ne(e)};return He(r),lu(r)}function uh(e){return{defaultRepo:Ye(e.repo),source:e.source,persistedInConfig:e.persistedInConfig}}var As=p(()=>{"use strict";$();Ki();gt()});import YJ from"node:path";import{homedir as zJ}from"node:os";function RC(e){let t=A(),r=bC({...e,config:t});if(!r)return{ok:!1,remediated:!1,alreadyPersisted:!1,configPath:Ye(dh),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:Ye(dh),resolved:uh(r),config:yg(t)};let n=vC(r.repo,t),o=uh({...r,persistedInConfig:!0,source:"config"});return{ok:!0,remediated:!0,alreadyPersisted:!1,configPath:Ye(dh),resolved:o,config:yg(n),remediation:"defaultRepo persisted in ~/.kynver/config.json \u2014 `kynver run create` no longer requires --repo."}}var dh,wC=p(()=>{"use strict";gt();$();As();dh=YJ.join(zJ(),".kynver","config.json")});import{mkdirSync as XJ,readFileSync as QJ,renameSync as ZJ,writeFileSync as e2}from"node:fs";import{homedir as t2}from"node:os";import SC from"node:path";function _C(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return SC.join(t2(),".kynver",`instruction-bundle-${t}.json`)}function xC(e,t){try{let r=_C(e);XJ(SC.dirname(r),{recursive:!0});let n=`${r}.tmp-${process.pid}`;e2(n,JSON.stringify(t),{encoding:"utf8",mode:384}),ZJ(n,r)}catch{}}function CC(e){try{let t=QJ(_C(e),"utf8"),r=JSON.parse(t);return ua(r)?r:null}catch{return null}}var EC=p(()=>{"use strict";sn()});function AC(e,t=process.env){for(let n of gu(t.KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY))if(W_(n)===e)return n;if(e===r2&&!hu(t))return null;let r=n2[e];return r?ca(r):null}var r2,n2,IC=p(()=>{"use strict";sn();r2="ib-3bab6314f0ba",n2={"ib-3bab6314f0ba":"53a2040646cd479e1f5f1aea9abf7848ce8b62e32001efb8044dfd90e8ab87ed","ib-26e6c695da06":"bb1700f25b2ee7d7cdcdb9f446f0f44ef2cc22a3096bc161232fb658e7cdaf38","ib-49e76cb8052c":"8fc646b5c4f8f402120477452608398f035c3cddd2e7aa8bb328e97b84dcf6d8","ib-f990c4fcc3dd":"fb4119813196e466429716bab7055c528cd79b4ec94c40a9c63c5c8313548df6"}});import{createPublicKey as o2,verify as s2}from"node:crypto";function a2(e){return o2({key:Buffer.concat([i2,Buffer.from(e)]),format:"der",type:"spki"})}function l2(e,t){if(!ua(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(ut(e.bundle),"utf8");return s2(null,n,a2(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 PC(e,t=process.env){if(!ua(e))return{ok:!1,reason:"malformed signed bundle payload"};let r=AC(e.publicKeyId,t);return r?l2(e,r):{ok:!1,reason:`no verification key for publicKeyId "${e.publicKeyId}" (not pinned; set KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY)`}}var i2,OC=p(()=>{"use strict";IC();sn();i2=Buffer.from("302a300506032b6570032100","hex")});function wa(e,t){console.error(JSON.stringify({event:e,...t}))}function TC(e,t,r){let n=PC(e);return n.ok?($x(n.bundle,t),t==="server"&&xC(r,e),!0):(wa("instruction_bundle_signature_invalid",{agentOsId:r,source:t,publicKeyId:e.publicKeyId,reason:n.reason}),!1)}function Ra(e){if(Tr.diskCacheTried)return!1;Tr.diskCacheTried=!0;let t=CC(e);return t?TC(t,"disk",e):!1}async function NC(e){let t=e.nowMs??Date.now(),r=()=>({source:Yt(),version:ro(),updated:!1});if(!e.force&&t-Tr.lastAttemptAtMs<c2)return r();Tr.lastAttemptAtMs=t;let n=e.baseUrl?.trim().replace(/\/$/,""),o=e.secret?.trim();if(!n||!o)return Yt()==="embedded"&&Ra(e.agentOsId)?{...r(),updated:!0}:r();let s=e.fetchImpl??fetch,i=new AbortController,a=setTimeout(()=>i.abort(),u2);try{let l=Bt(o);delete l["Content-Type"],Tr.etag&&Yt()==="server"&&(l["If-None-Match"]=Tr.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 Tr.routeMissingLogged||(Tr.routeMissingLogged=!0,wa("instruction_bundle_route_missing",{agentOsId:e.agentOsId,baseUrl:n})),Yt()==="embedded"&&Ra(e.agentOsId)?{...r(),updated:!0}:r();if(!c.ok)return wa("instruction_bundle_fetch_failed",{agentOsId:e.agentOsId,status:c.status}),Yt()==="embedded"&&Ra(e.agentOsId)?{...r(),updated:!0}:r();let u=await c.json().catch(()=>null);return!u||!TC(u,"server",e.agentOsId)?Yt()==="embedded"&&Ra(e.agentOsId)?{...r(),updated:!0}:r():(Tr.etag=c.headers.get("etag"),wa("instruction_bundle_loaded",{agentOsId:e.agentOsId,version:ro(),publicKeyId:u.publicKeyId}),{...r(),updated:!0})}catch(l){return wa("instruction_bundle_fetch_error",{agentOsId:e.agentOsId,error:l instanceof Error?l.message:String(l)}),Yt()==="embedded"&&Ra(e.agentOsId)?{...r(),updated:!0}:r()}finally{clearTimeout(a)}}var c2,u2,Tr,DC=p(()=>{"use strict";xs();EC();dn();OC();c2=15*6e4,u2=1e4,Tr={lastAttemptAtMs:0,etag:null,diskCacheTried:!1,routeMissingLogged:!1}});import d2 from"node:os";function MC(e,t){console.error(JSON.stringify({event:"daemon_identity",level:e,message:t}))}function LC(e=A(),t=process.env){let r=at(t,e),n=is({config:e,totalMemBytes:d2.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=yr(r.boxKind,i);ji(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)MC("warn",c);for(let c of s)MC("error",c);return{ok:l,box:r,workerCapSource:n.workerCapSource,maxConcurrentWorkers:a,autoCap:n.autoCap,warnings:o,errors:s}}var BC=p(()=>{"use strict";$();We();Yo();ea()});import{spawnSync as p2}from"node:child_process";import{existsSync as f2,readFileSync as m2}from"node:fs";import g2 from"node:path";function y2(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+h2<s.startedAtMs||o.push({workerName:s.workerName,workerPid:s.pid,orphanPid:i.pid}));return o}function k2(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 b2(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=p2("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:3e4});if(o.status!==0)return[];try{return k2(o.stdout??"")}catch{return[]}}function v2(e,t=oe){try{let r=xe().find(o=>o.id===e);if(!r)return[];let n=[];for(let o of Object.keys(r.workers||{})){let s=g2.join(q(r.id),"workers",U(o),"worker.json");if(!f2(s))continue;let i=JSON.parse(m2(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 UC(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return{checkedWorkers:0,killed:[]};let n=t.isAlive??oe,o=(t.collect??(l=>v2(l,n)))(e);if(o.length===0)return{checkedWorkers:0,killed:[]};let s=(t.query??b2)(o.map(l=>l.pid)),i=t.killTree??he,a=y2(s,o,n).map(l=>({...l,result:i(l.orphanPid,"SIGKILL")}));return{checkedWorkers:o.length,killed:a}}var h2,FC=p(()=>{"use strict";Z();B();Vo();h2=5e3});import{mkdirSync as R2,readFileSync as w2,renameSync as S2,writeFileSync as _2}from"node:fs";import{homedir as x2}from"node:os";import Mu from"node:path";function WC(){return Mu.join(x2(),".kynver")}function C2(e=WC()){return Mu.join(e,"doctor-native-windows.json")}function KC(e=WC()){return Mu.join(e,"native-windows-state.json")}function E2(e,t){R2(Mu.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;_2(r,`${JSON.stringify(t,null,2)}
|
|
145
|
-
`,{mode:384}),
|
|
146
|
-
`,"utf8");try{await _a.rename(n,e)}catch(o){let s=o.code;if(s!=="EPERM"&&s!=="EEXIST"&&s!=="EACCES")throw o;await _a.unlink(n).catch(()=>{})}}async function nE(e,t){await X2(e,t)}function oE(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 Bu,vh=p(()=>{"use strict";Bu={version:1,jobs:{}}});function Q2(e,t){if(!e.inflightUntil)return!1;let r=Date.parse(e.inflightUntil);return!Number.isNaN(r)&&r>t}function Z2(e){return!!e.completedAt}function eq(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 tq(e,t,r){if(t.nextFireAt)return t.nextFireAt;let n=tE(e.spec,r);return t.nextFireAt=n,n}function rq(e,t,r,n){if(e.paused||Z2(t)||Q2(t,r)||!eq(e,t,n,r))return!1;let o=t.nextFireAt?Date.parse(t.nextFireAt):NaN;return Number.isNaN(o)?!1:r>=o}function nq(e,t,r){e.spec.scheduleKind==="cron"&&(t.nextFireAt=kh(e.spec,r))}async function Rh(e={}){let t=e.env??vs(),r=e.now??new Date,n=r.getTime(),o=e.agentOsIdFilter?Le(e.agentOsIdFilter):Le();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=XC(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 Eu(t.storePath),a=e.agentOsIdFilter?i.filter(h=>h.spec.target.agentOsId===e.agentOsIdFilter):i,l=await bh(t.statePath),c=[];for(let h of a){let y=oE(l,h.providerScheduleId);tq(h,y,r),rq(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,f=0,m=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=kh(h.spec,r),f++;continue}}if(m<=0){f++;continue}y.inflightUntil=new Date(n+t.inflightLeaseMs).toISOString(),y.lastAttemptAt=r.toISOString(),nq(h,y,r);try{let b=Le(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 JC({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++,m--):(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 nE(t.statePath,l),{enabled:!0,scanned:a.length,due:c.length,fired:u,skippedJobs:f,errors:d,...g.length?{errorDetails:g}:{}}}finally{QC(t.lockPath)}}var wh=p(()=>{"use strict";Er();qC();ZC();$();rE();Rs();vh()});import sE from"node:path";function Uu(e){let t=K(sE.join(q(e),iE),null);return pC(e,t)??t}function aE(e,t){let r={...t,updatedAt:new Date().toISOString()};we(sE.join(q(e),iE),r),dC(e,r)}function lE(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 iE,Sh=p(()=>{"use strict";B();Z();ba();iE="mesh-cron-lease.json"});function dE(e){xa=e}function pE(e=Date.now()){return!xa||xa.stallCount===cE&&e-uE<9e5?null:(cE=xa.stallCount,uE=e,xa)}var xa,cE,uE,_h=p(()=>{"use strict";xa=null,cE=-1,uE=0});function mE(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 fE(e){return new Error(`callback timeout after ${e}ms`)}async function gE(e,t){let r=mE(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(fE(r))},r)})])}catch(i){throw s?fE(r):i}finally{o&&clearTimeout(o)}}function hE(e,t){let r=mE(t);return{ok:!1,status:0,response:{error:e instanceof Error?e.message:String(e),timeoutMs:r}}}async function no(e,t,r,n){try{return await gE(async o=>{let s=await kt(e,{method:"POST",headers:Bt(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 hE(o,n?.timeoutMs)}}async function fe(e,t,r,n){let o=await no(e,t,r,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await D_(t,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await no(e,s.token,r,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function xh(e,t,r){try{return await gE(async n=>{let o=await kt(e,{method:"GET",headers:Bt(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 hE(n,r?.timeoutMs)}}var Ge=p(()=>{"use strict";xs();hr();$()});function yE(){let e=Number(process.env.KYNVER_DISPATCH_CALLBACK_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):3e5}var kE=p(()=>{"use strict"});function Ca(e){console.error(JSON.stringify({event:"dispatch_progress",ts:new Date().toISOString(),...e}))}function bE(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 Ch(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 vE=p(()=>{"use strict"});function iq(e){return oq.includes(e)}function aq(e){return sq.includes(e)}function RE(e){return{slug:e.slug,displayName:e.displayName,description:e.description,dispatchLane:e.dispatchLane===null||iq(e.dispatchLane)?e.dispatchLane:null,defaultRoleLane:aq(e.defaultRoleLane)?e.defaultRoleLane:"implementer"}}function cq(e){if(!e)return null;let t=e.trim().toLowerCase(),r=lq.get(t)??null,n=Hx(t);if(!n)return r;let o=RE(n);return r?{...o,dispatchLane:r.dispatchLane,defaultRoleLane:r.defaultRoleLane}:o}function Eh(e){return cq(e)?.defaultRoleLane??null}function SE(){return wE.filter(e=>e.dispatchLane==="review").map(e=>e.slug)}var oq,sq,wE,lq,Fu=p(()=>{"use strict";Xg();dn();oq=["implementation","review","landing"],sq=["plan_author","implementer","report_reviewer","deep_reviewer","runtime_verifier","system"];wE=ws.personas.map(RE),lq=new Map(wE.map(e=>[e.slug,e]))});function _E(e){return(e??"").trim().toLowerCase()}function uq(e){switch(_E(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 dq(e){let t=_E(e);if(!t)return;if(t==="implementation"||t==="review"||t==="landing"||t==="any")return t;let r=uq(t);if(r)return r;if(t==="implement"||t==="repair"||t==="coding")return"implementation";if(t==="land"||t==="merge")return"landing"}function xE(e){return dq(e)??"any"}var CE=p(()=>{"use strict";Fu()});function pq(e=process.env){let t=A();return Nt(t,e)!=="forge"}function Wu(e,t=process.env){if(pq(t))return e?.maxConcurrentWorkers??void 0}async function Ku(e,t){let r=me(t.baseUrl?String(t.baseUrl):void 0),n=await ye(t.secret?String(t.secret):void 0,e,{baseUrl:r}),o=`${r}/api/agent-os/by-id/${encodeURIComponent(e)}/runtime`;try{let s=await xh(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 Ah=p(()=>{"use strict";Ge();$();We()});async function EE(e,t=fq){let r=await t.fetchPreferences(e.agentOsId,e.args),n=t.configuredOverride(r,e.env);return t.observe({runId:e.runId,configuredMaxWorkersOverride:n})}var fq,AE=p(()=>{"use strict";Ah();ss();fq={fetchPreferences:Ku,configuredOverride:Wu,observe:Zi}});function $u(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function Ih(e){return e.toLowerCase()}function mq(e){let t=$u(e,"roleLane");if(t)return t;let r=Ih($u(e,"executorRef")),n=Ih($u(e,"title")),o=Ih($u(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=Eh(o);if(i)return o==="lorentz"&&(s.includes("deep")||s.includes("security"))?"deep_reviewer":i;if(s.includes("review"))return"report_reviewer"}function IE(e){let t=mq(e);return t?{...e,roleLane:t}:e}var PE=p(()=>{"use strict";Fu()});function OE(e){let t=e.trim();return gq.test(t)||hq.test(t)}function TE(e){let t=e.trim().toLowerCase();return t.startsWith("gpt-")||t.startsWith("gpt5")||t.includes("codex")}function Ph(e){let t=e.trim().toLowerCase();return t.includes("composer")||t.includes("cursor")}function NE(e){return e.trim().toLowerCase().startsWith("gemini-")}function yq(e){return TE(e)?"codex":OE(e)?"claude":NE(e)?"gemini":(Ph(e),"cursor")}function kq(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 bq(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?OE(n)||TE(n)||Ph(n)||NE(n)?{lane:r,model:n,provider:yq(n),rule:"executor_ref:harness_lane_model"}:{lane:r,rule:"executor_ref:harness_lane"}:{lane:r,rule:"executor_ref:harness_lane"}}function vt(e){let t=typeof e=="string"?e.trim():"";return t?kq(t)??bq(t):null}function DE(e){let t=vt(e);return t?!!(t.provider&&t.provider!=="cursor"||t.model&&!Ph(t.model)):!1}var gq,hq,Hu=p(()=>{"use strict";gq=/^claude[-_]/i,hq=/^(?:opus|sonnet|haiku)\b/i});function Ea(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function Nr(e){if(!e?.trim())return!1;let t=e.trim().toLowerCase();return vq.has(t)?!0:t.includes("claude")||t.includes("opus")}function ju(e){if(!e)return!1;let t=e.workerProviderOverride;if(typeof t=="string"&&Nr(t))return!0;let r=Ea(e,"executorRef").toLowerCase();if(r==="provider:claude"||r.startsWith("provider:claude:")||r.includes("claude-worker-override")||r.includes("operator-claude"))return!0;let n=vt(Ea(e,"executorRef"));if(n?.provider&&Nr(n.provider)||n?.model&&Nr(wq(n.model)))return!0;let o=Ea(e,"description");if(Rq.some(i=>i.test(o)))return!0;let s=Ea(e,"title");return!!/\[use-claude-worker\]/i.test(s)}function wq(e){let t=e.trim().toLowerCase();return/^claude[-_]/.test(t)||/^(?:opus|sonnet|haiku)\b/.test(t)?"claude":t}function Sq(e,t){return{provider:Dr,model:Vu,rule:`policy:cursor_default${t}`,requestedModel:e}}function xq(e){return _q.some(t=>e.startsWith(t))}function Oh(e){if(!e)return!1;let t=e.workerProviderOverride;return typeof t=="string"&&t.trim()||vt(Ea(e,"executorRef"))?.provider?!0:ju(e)}function ME(e){let{routing:t,task:r}=e,n=e.explicitProvider?.trim().toLowerCase();if(e.explicitProviderIsOperatorOverride&&Nr(n))return{...t,provider:"claude",rule:t.rule.startsWith("explicit:")?t.rule:"explicit:operator_provider"};if(n||xq(t.rule)||Oh(r)||!Nr(t.provider))return t;let o=t.rule&&t.rule!=="default:global"?`:${t.rule.replace(/:/g,"_")}`:"";return Sq(t.model,o)}function LE(e,t=Dr){let r=e?.trim();return r?ze(r):t}var Dr,vq,Rq,_q,oo=p(()=>{"use strict";Hu();Gu();sa();sa();Dr="cursor",vq=new Set(["claude","opus","anthropic"]),Rq=[/\[worker-provider:\s*claude\]/i,/\[use-claude-worker\]/i,/\[operator-worker-provider:\s*claude\]/i];_q=["explicit:","executor_ref:","factory:","task:"]});function Is(e){return BE[e]}function UE(){return Object.values(BE)}var BE,Th=p(()=>{"use strict";BE={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{createHash as FE}from"node:crypto";import{statSync as Cq}from"node:fs";import{spawnSync as WE}from"node:child_process";function zt(e){try{let t=Cq(e),r=`${e}|${t.size}|${t.mtimeMs}`;return FE("sha256").update(r).digest("hex").slice(0,16)}catch{return}}function Ps(e){return FE("sha256").update(`env:${e}`).digest("hex").slice(0,16)}function Rt(e,t){for(let r of t){let n=process.env[r]?.trim();if(n)return n}return e}function Ft(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=ie(e,t),i=WE(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 Ju(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=ie(e,t);return WE(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 so=p(()=>{"use strict";Fe()});import{existsSync as Eq}from"node:fs";import{homedir as Aq}from"node:os";import Aa from"node:path";function Pq(){let e=Aq();return[process.env.CODEX_HOME?.trim()?Aa.join(Aa.resolve(process.env.CODEX_HOME.trim()),"auth.json"):null,Aa.join(e,".codex","auth.json"),Aa.join(e,".config","codex","auth.json")].filter(r=>!!r)}function Oq(e){return Aa.dirname(e)}function Tq(e){let t,r;for(let n of Pq()){if(!Eq(n))continue;t??=n;let o=Ft(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status",env:{CODEX_HOME:Oq(n)}});if(r??=o,o.ok)return{authPath:n,login:o}}return{authPath:t,login:r??Ft(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status"})}}function KE(e=new Date().toISOString()){let t=Rt(Iq,["KYNVER_CODEX_BIN","CODEX_BIN"]);if(process.env.CODEX_API_KEY?.trim())return{providerId:"codex",ready:!0,authSource:"api_key_env",sessionFingerprint:Ps("CODEX_API_KEY"),checkedAt:e,note:"CODEX_API_KEY present (env binding \u2014 cloud credits path, no token stored in Kynver)"};let{authPath:r,login:n}=Tq(t),o=!!r&&n.ok;return{providerId:"codex",ready:o,authSource:"oauth_local",sessionFingerprint:r?zt(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 Iq,$E=p(()=>{"use strict";so();Iq="codex"});import{existsSync as Nq}from"node:fs";import{homedir as Dq}from"node:os";import Nh from"node:path";function Mq(){let e=process.env.HERMES_HOME?.trim(),t=e?Nh.resolve(e):Nh.join(Dq(),".hermes");return Nh.join(t,"auth.json")}function qu(e=new Date().toISOString()){let t=Rt("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=Ft(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=Mq(),o=Nq(n),s=Ju(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?zt(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 Dh=p(()=>{"use strict";so()});function Os(e=new Date().toISOString()){let t=KE(e);if(t.ready)return{...t,path:"codex_cli"};let r=qu(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 Yu=p(()=>{"use strict";$E();Dh()});function VE(e,t){let r=Is(e);return t==="privileged"?r.supportsPrivilegedPlatformActions:t==="low"?r.supportsLowRiskOrchestration:!0}function Lq(e,t){let r=Is(e.providerId),n=Is(t.providerId),o=HE.indexOf(r.costTier)-HE.indexOf(n.costTier);if(o!==0)return o;let s=jE[e.binding.authSource]-jE[t.binding.authSource];return s!==0?s:e.providerId.localeCompare(t.providerId)}function Mh(e){let t=UE().map(a=>({providerId:a.id,binding:e.inventory.bindings[a.id]})).filter(a=>a.binding.ready&&VE(a.providerId,e.riskClass));if(t.length===0)return null;let n=[...t].sort(Lq)[0],o="codex";if(n.providerId===o)return{providerId:n.providerId,binding:n.binding};let s=e.inventory.bindings[o],i;return VE(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 HE,jE,GE=p(()=>{"use strict";Th();HE=["low","medium","high"],jE={oauth_local:0,subscription_hermes:0,runner_token:1,api_key_env:2,none:3}});import{existsSync as Bq}from"node:fs";import{homedir as Uq}from"node:os";import Fq from"node:path";function Kq(){let e=Uq();return[Fq.join(e,".claude",".credentials.json")]}function JE(e=new Date().toISOString()){let t=Rt(Wq,["KYNVER_CLAUDE_BIN","CLAUDE_BIN"]);if(process.env.ANTHROPIC_API_KEY?.trim())return{providerId:"claude",ready:!1,authSource:"api_key_env",sessionFingerprint:Ps("ANTHROPIC_API_KEY"),checkedAt:e,note:"ANTHROPIC_API_KEY present but scrubbed from worker env (deployment secret) \u2014 use `claude` CLI login (OAuth) for harness workers"};let r=Ft(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=Kq().find(i=>Bq(i)),o=Ju(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?zt(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 Wq,qE=p(()=>{"use strict";so();Wq="claude"});function wt(e,t={}){let r=Ui(e);if(!t.reviewWorker)return r;let n={...r,[$q]:"1"};for(let o of Hq)delete n[o];return n}var $q,Hq,io=p(()=>{"use strict";Fi();$q="KYNVER_NO_PROD_DB_CREDENTIALS",Hq=["KYNVER_ENV_FILE"]});function YE(e){return e.replace(jq,"")}function zu(e){return/^claude[-_]/i.test(e)||/^(?:opus|sonnet|haiku)\b/i.test(e)}function Vq(e){let t=e.trim().toLowerCase();return t.startsWith("gemini-")||t==="auto"||t==="pro"||t==="flash"||t==="flash-lite"}function Jq(e){let t=e.trim().toLowerCase();return Gq.has(t)?"auto":null}function Lh(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=YE(r).trim()||t;return zE.test(o)||!zu(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 Ts(e,t){let r=(e??"").trim();return r?zu(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 Bh(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 Ns(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=YE(r).trim()||t;return zu(o)||!Vq(o)&&zE.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 Ds(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let n=Jq(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")`}:zu(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 jq,zE,Gq,Xt=p(()=>{"use strict";jq=/-(?:thinking(?:-(?:high|medium|low|minimal|max|none))?|high|medium|low|minimal)$/i;zE=/^(?:gpt-|gpt5|o1|o3|o4|gemini-|grok-|composer|deepseek|llama|mistral|qwen|command-)/i;Gq=new Set(["cursor"])});import{existsSync as Ia,readdirSync as qq}from"node:fs";import ao from"node:path";function zq(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 Xq(e){let t=ao.join(e,"versions");if(!Ia(t))return null;let r=null,n=-1;for(let o of qq(t,{withFileTypes:!0})){if(!o.isDirectory()||!Yq.test(o.name))continue;let s=zq(o.name);s==null||s<=n||(n=s,r=ao.join(t,o.name))}return r}function Xu(e){let t=e?.trim()||ao.join(process.env.LOCALAPPDATA||"","cursor-agent"),r=ao.join(t,"node.exe"),n=ao.join(t,"index.js");if(Ia(r)&&Ia(n))return{nodeExe:r,indexJs:n,versionDir:t};let o=Xq(t);if(!o)return null;let s=ao.join(o,"node.exe"),i=ao.join(o,"index.js");return!Ia(s)||!Ia(i)?null:{nodeExe:s,indexJs:i,versionDir:o}}var Yq,XE=p(()=>{"use strict";Yq=/^\d{4}\.\d{1,2}\.\d{1,2}-[a-f0-9]+$/i});import{closeSync as Fh,existsSync as eA,mkdirSync as Qq,openSync as Wh,statSync as Zq,unlinkSync as QE}from"node:fs";import{spawn as eY}from"node:child_process";import tY from"node:os";import Qt from"node:path";function sY(e,t,r){return{executable:e,prefixArgs:[t],shell:!1,detached:Re(),bundledVersionDir:r}}function Pa(e){if(process.platform==="win32"){let t=/\.(cmd|bat)$/i.test(e),r=/node\.exe$/i.test(e)&&eA(Qt.join(Qt.dirname(e),"index.js"));if(t||r||e==="agent"){let o=t?Xu(Qt.dirname(e)):r?{nodeExe:e,indexJs:Qt.join(Qt.dirname(e),"index.js"),versionDir:Qt.dirname(e)}:Xu();if(o)return sY(o.nodeExe,o.indexJs,o.versionDir);throw new Error("Cursor Agent on Windows has no headless bundled node.exe under %LOCALAPPDATA%\\cursor-agent\\versions\\\u2026. Run `agent login` / update Cursor Agent CLI, use `--provider claude`, or set KYNVER_CURSOR_AGENT_ROOT to the cursor-agent folder.")}}return{executable:e,prefixArgs:[],shell:!1,detached:Re()}}function iY(e,t,r){return wt({...process.env,CI:"1",NO_COLOR:"1",...t.bundledVersionDir?{CURSOR_INVOKED_AS:Qt.basename(e)||"agent.cmd"}:{}},{reviewWorker:r})}function tA(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Kh(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 aY(){let e=process.env.KYNVER_CURSOR_START_LOCK_DIR?.trim()||Qt.join(tY.homedir(),".kynver","locks");return Qq(e,{recursive:!0}),Qt.join(e,"cursor-agent-start.lock")}function lY(){if(process.env.KYNVER_CURSOR_START_LOCK==="0")return()=>{};let e=aY(),t=Kh("KYNVER_CURSOR_START_LOCK_TIMEOUT_MS",nY),r=Kh("KYNVER_CURSOR_START_LOCK_STALE_MS",oY),n=Date.now();for(;;)try{let o=Wh(e,"wx");return Fh(o),()=>{try{QE(e)}catch{}}}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-Zq(e).mtimeMs>r){QE(e);continue}}catch{continue}if(Date.now()-n>t)throw new Error(`timed out waiting for Cursor agent start lock: ${e}`);tA(250)}}function lo(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=Xu(e.KYNVER_CURSOR_AGENT_ROOT?.trim()||void 0);if(r)return r.nodeExe;let n=Qt.join(e.LOCALAPPDATA||"","cursor-agent","agent.cmd");if(eA(n))return n}return"agent"}function cY(){return lo(process.env)}function ZE(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 Uh,rY,nY,oY,rA,Ms=p(()=>{"use strict";vr();B();io();Xt();XE();Uh="composer-2.5",rY=15e3,nY=6e4,oY=3e4;rA={name:"cursor",defaultModel:Uh,preflightModel(e){return Ds(e,Uh)},start(e){let t=Ds(e.model,Uh);if(!t.ok)throw new Error(`cursor provider model preflight failed: ${t.note}`);let r=t.model,n=Wh(e.stdoutPath,"a"),o=Wh(e.stderrPath,"a"),s=["ignore",n,o],i=cY(),a=Pa(i),l=lY(),c;try{let[u,d]=a.shell?[a.executable,ZE(e,r,a.prefixArgs)]:lt(a.executable,ZE(e,r,a.prefixArgs),e.workerDir);c=eY(u,d,te({cwd:e.worktreePath,detached:a.detached,shell:a.shell,stdio:s,env:iY(i,a,e.reviewWorker)})),tA(Kh("KYNVER_CURSOR_START_LOCK_HOLD_MS",rY))}finally{l(),Fh(n),Fh(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 uY}from"node:child_process";function Qu(e,t=process.env){try{let r;try{r=Pa(e)}catch{r={executable:e,prefixArgs:[]}}let n=uY(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 $h=p(()=>{"use strict";Ls();Ms()});import{existsSync as nA}from"node:fs";import{homedir as dY}from"node:os";import co from"node:path";import{spawnSync as pY}from"node:child_process";function fY(e){if(co.isAbsolute(e)||e.includes("/")||e.includes("\\"))return nA(e);try{let t=pY(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function Zu(e=process.env){let t=[],r=e.KYNVER_CURSOR_AUTH_HOME?.trim();r&&(t.push(co.join(r,".config","cursor","auth.json")),t.push(co.join(r,".cursor-agent","auth.json")));let n=dY();if(t.push(co.join(n,".config","cursor","auth.json")),t.push(co.join(n,".cursor-agent","auth.json")),process.platform==="win32"){let o=e.LOCALAPPDATA?.trim(),s=e.APPDATA?.trim();o&&t.push(co.join(o,"cursor-agent","auth.json")),s&&t.push(co.join(s,"cursor","auth.json"))}return t}function oA(e){return`${e.error}: ${e.detail}`}function td(e=process.env){let t=lo(e);return fY(t)?e.CURSOR_API_KEY?.trim()?{ok:!0,creds:{agentBin:t,authSource:"api_key_env"}}:Zu(e).find(n=>nA(n))?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:Qu(t,e).ok?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:{ok:!1,error:Hh,detail:"Run `agent login` on this computer, or set CURSOR_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:ed,detail:"`agent` CLI not found. Install the Cursor Agent CLI (https://cursor.com/docs/cli/headless) and keep it on PATH."}}var ed,Hh,Ls=p(()=>{"use strict";Ms();$h();ed="cursor_cli_unavailable",Hh="cursor_not_logged_in"});import{existsSync as mY}from"node:fs";function sA(e=new Date().toISOString()){let t=Rt(gY,["KYNVER_CURSOR_AGENT_BIN","CURSOR_AGENT_BIN"]);if(process.env.CURSOR_API_KEY?.trim())return{providerId:"cursor",ready:!1,authSource:"api_key_env",sessionFingerprint:Ps("CURSOR_API_KEY"),checkedAt:e,note:"CURSOR_API_KEY present but scrubbed from worker env (deployment secret) \u2014 use `agent login` (OAuth) for harness workers"};let r=Ft(t,["-v"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=Zu().find(a=>mY(a)),o=Qu(t),s=!!n||o.ok,i=r.ok&&s;return{providerId:"cursor",ready:i,authSource:"oauth_local",sessionFingerprint:n?zt(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 gY,iA=p(()=>{"use strict";Ls();$h();so();gY="agent"});import{existsSync as hY,readFileSync as yY}from"node:fs";import{homedir as kY}from"node:os";import jh from"node:path";function vY(){let e=process.env.HERMES_HOME?.trim(),t=e?jh.resolve(e):jh.join(kY(),".hermes");return jh.join(t,".env")}function RY(e){try{let t=yY(e,"utf8"),r=[];for(let n of bY)new RegExp(`^${n}=`,"m").test(t)&&r.push(n);return r}catch{return[]}}function aA(e=new Date().toISOString()){let t=Rt("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=Ft(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=vY(),o=hY(n),s=o?RY(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?zt(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 bY,lA=p(()=>{"use strict";so();bY=["OPENAI_API_KEY","ANTHROPIC_API_KEY","KYNVER_API_KEY","KYNVER_BASE_URL"]});function cA(e={}){let t=e.nowIso?.()??new Date().toISOString(),r=Os(t),n={codex:r,cursor:sA(t),claude:JE(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:aA(t),hermesOpenAiCodex:qu(t),codexAdapterPath:r.path,readyCount:o}}var uA=p(()=>{"use strict";qE();Yu();iA();lA();Dh()});function Vh(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function _Y(e){let t=Vh(e,"executorRef").toLowerCase(),r=Vh(e,"title").toLowerCase(),n=Vh(e,"description").toLowerCase(),o=`${t}
|
|
143
|
+
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 MJ,renameSync as LJ}from"node:fs";function BJ(e,t){let r=`${e}.quarantine-${t}`;for(let n of["","-wal","-shm"]){let o=`${e}${n}`;MJ(o)&&LJ(o,`${r}${n}`)}return r}function cC(e){let t=e.quarantineStamp??(e.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),r=null;try{let s=ka.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=BJ(n,t);try{return{store:ka.open(e),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([r,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}var uC=p(()=>{"use strict";lC()});function UJ(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function FJ(){return WJ.classifyOptions??UJ()}function $J(e){Du+=1;try{let t=FJ(),r=cC({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:Du},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:Du},failedAtMs:Date.now(),permanentRefusal:t.name==="FilesystemPolicyError"||t.name==="SchemaDowngradeRefusedError"}}}function HJ(e,t){return e.store||e.permanentRefusal?!1:e.failedAtMs===null?!0:t-e.failedAtMs>=KJ}function pe(e=Date.now()){let t=vt();return(!Or||Or.status.harnessRoot!==t||HJ(Or,e))&&(VJ(),Or=$J(t)),Or.store}function jJ(){return Or?Or.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:Du}}function dC(){return pe(),jJ()}function VJ(){try{Or?.store?.close()}catch{}Or=null}var WJ,KJ,Or,Du,fn=p(()=>{"use strict";Lt();uC();WJ={},KJ=300*1e3,Or=null,Du=0});import{existsSync as GJ,readFileSync as JJ}from"node:fs";import{homedir as qJ}from"node:os";import YJ from"node:path";function pC(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return YJ.join(qJ(),".kynver",`local-run-store-flags-${t}.json`)}function uh(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 fC(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:uh(r)}function mC(e,t){try{let r=pC(e),n={contractVersion:1,agentOsId:e,flags:uh(t),deliveredAt:new Date().toISOString()};we(r,n),Ft={flags:n.flags,loadedAtMs:Date.now(),file:r}}catch{}}function gC(e=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(Ft&&e-Ft.loadedAtMs<zJ)return Ft.flags;try{let t=A().agentOsId?.trim();if(!t)return Ft={flags:{},loadedAtMs:e,file:null},Ft.flags;let r=pC(t);if(!GJ(r))return Ft={flags:{},loadedAtMs:e,file:r},Ft.flags;let n=JSON.parse(JJ(r,"utf8")),o=n?.contractVersion===1?uh(n.flags):{};return Ft={flags:o,loadedAtMs:e,file:r},o}catch{return Ft={flags:{},loadedAtMs:e,file:null},Ft.flags}}var zJ,Ft,dh=p(()=>{"use strict";$();U();zJ=3e4,Ft=null});function QJ(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 Tr(e=process.env){let t={},r={},n=[],o=gC();for(let s of XJ){let i=e[s.env];if(typeof i=="string"&&i.trim()!==""){let c=QJ(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 XJ,Es=p(()=>{"use strict";dh();XJ=[{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 ba(e){return Tr(process.env).flags[e]}function ph(e){return`mesh-cron-lease:${e}`}function hC(e,t){if(ba("meshLease")==="off")return;let r=pe();if(r)try{let n=r.latestRecoveryCheckpoint(ph(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:ph(e),payloadJson:JSON.stringify(t)})}catch{tt.meshStoreFailures+=1}}function yC(e,t){let r=ba("meshLease");if(r==="off")return null;let n=pe();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(ph(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&&(tt.meshLeaseDivergences+=1),r!=="enforce"?null:i&&t?.updatedAt&&s?.updatedAt&&Date.parse(t.updatedAt)>Date.parse(s.updatedAt)?(tt.meshEnforceStaleInversions+=1,null):s}catch{return tt.meshStoreFailures+=1,null}}function Mu(e){return`quota-cooldown:${e}`}function bC(e,t){if(ba("quota")==="off")return;let r=pe();if(r)try{r.tryReserveAdmission(Mu(e),kC,t)}catch{tt.quotaStoreFailures+=1}}function vC(e){if(ba("quota")==="off")return;let t=pe();if(t)try{t.releaseAdmission(Mu(e),kC)}catch{tt.quotaStoreFailures+=1}}function RC(e,t){let r=ba("quota");if(r==="off")return null;let n=pe();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:Mu(e),limit:50}).find(i=>i.key===Mu(e)),s=!!o;return s!==t&&(tt.quotaVerdictDivergences+=1),r==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return tt.quotaStoreFailures+=1,null}}function wC(){return{"keeper.storeFailures":tt.keeperStoreFailures,"meshLease.storeFailures":tt.meshStoreFailures,"meshLease.divergences":tt.meshLeaseDivergences,"meshLease.enforceStaleInversions":tt.meshEnforceStaleInversions,"quota.storeFailures":tt.quotaStoreFailures,"quota.verdictDivergences":tt.quotaVerdictDivergences}}var tt,Zge,kC,va=p(()=>{"use strict";fn();Es();tt={keeperStoreFailures:0,meshStoreFailures:0,quotaStoreFailures:0,meshLeaseDivergences:0,meshEnforceStaleInversions:0,quotaVerdictDivergences:0};Zge=1800*1e3;kC="quota-preflight"});function fh(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(`
|
|
144
|
+
`)}var yhe,khe,bhe,vhe,mh=p(()=>{"use strict";on();Xx();$();ih();U();gu();lh();va();yhe=15*6e4,khe=2*6e4,bhe=5*6e4,vhe=30*6e4});import ZJ from"node:path";function e2(e){return ZJ.resolve(De(e.trim()))}function As(e,t,r){let n=e?.trim();return n?{repo:e2(n),source:t,persistedInConfig:r}:null}function SC(e){return e?{repo:e.repo,source:e.source,persistedInConfig:!1}:null}function Ra(e={}){let t=e.env??process.env,r=e.config??A(),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||SC(vc({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl}))}function _C(e={}){let t=e.env??process.env,r=e.config??A(),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||SC(Rc({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl,home:e.home}))}function xC(e,t){let r={...t??A(),defaultRepo:De(e)};return je(r),cu(r)}function gh(e){return{defaultRepo:ze(e.repo),source:e.source,persistedInConfig:e.persistedInConfig}}var Is=p(()=>{"use strict";$();$i();ht()});import t2 from"node:path";import{homedir as r2}from"node:os";function CC(e){let t=A(),r=_C({...e,config:t});if(!r)return{ok:!1,remediated:!1,alreadyPersisted:!1,configPath:ze(hh),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:ze(hh),resolved:gh(r),config:wg(t)};let n=xC(r.repo,t),o=gh({...r,persistedInConfig:!0,source:"config"});return{ok:!0,remediated:!0,alreadyPersisted:!1,configPath:ze(hh),resolved:o,config:wg(n),remediation:"defaultRepo persisted in ~/.kynver/config.json \u2014 `kynver run create` no longer requires --repo."}}var hh,EC=p(()=>{"use strict";ht();$();Is();hh=t2.join(r2(),".kynver","config.json")});import{mkdirSync as n2,readFileSync as o2,renameSync as s2,writeFileSync as i2}from"node:fs";import{homedir as a2}from"node:os";import AC from"node:path";function IC(e){let t=e.replace(/[^A-Za-z0-9_-]/g,"_");return AC.join(a2(),".kynver",`instruction-bundle-${t}.json`)}function PC(e,t){try{let r=IC(e);n2(AC.dirname(r),{recursive:!0});let n=`${r}.tmp-${process.pid}`;i2(n,JSON.stringify(t),{encoding:"utf8",mode:384}),s2(n,r)}catch{}}function OC(e){try{let t=o2(IC(e),"utf8"),r=JSON.parse(t);return da(r)?r:null}catch{return null}}var TC=p(()=>{"use strict";an()});function NC(e,t=process.env){for(let n of hu(t.KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY))if(V_(n)===e)return n;if(e===l2&&!yu(t))return null;let r=c2[e];return r?ua(r):null}var l2,c2,DC=p(()=>{"use strict";an();l2="ib-3bab6314f0ba",c2={"ib-3bab6314f0ba":"53a2040646cd479e1f5f1aea9abf7848ce8b62e32001efb8044dfd90e8ab87ed","ib-26e6c695da06":"bb1700f25b2ee7d7cdcdb9f446f0f44ef2cc22a3096bc161232fb658e7cdaf38","ib-49e76cb8052c":"8fc646b5c4f8f402120477452608398f035c3cddd2e7aa8bb328e97b84dcf6d8","ib-f990c4fcc3dd":"fb4119813196e466429716bab7055c528cd79b4ec94c40a9c63c5c8313548df6"}});import{createPublicKey as u2,verify as d2}from"node:crypto";function f2(e){return u2({key:Buffer.concat([p2,Buffer.from(e)]),format:"der",type:"spki"})}function m2(e,t){if(!da(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(dt(e.bundle),"utf8");return d2(null,n,f2(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 MC(e,t=process.env){if(!da(e))return{ok:!1,reason:"malformed signed bundle payload"};let r=NC(e.publicKeyId,t);return r?m2(e,r):{ok:!1,reason:`no verification key for publicKeyId "${e.publicKeyId}" (not pinned; set KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY)`}}var p2,LC=p(()=>{"use strict";DC();an();p2=Buffer.from("302a300506032b6570032100","hex")});function Sa(e,t){console.error(JSON.stringify({event:e,...t}))}function BC(e,t,r){let n=MC(e);return n.ok?(Jx(n.bundle,t),t==="server"&&PC(r,e),!0):(Sa("instruction_bundle_signature_invalid",{agentOsId:r,source:t,publicKeyId:e.publicKeyId,reason:n.reason}),!1)}function wa(e){if(Nr.diskCacheTried)return!1;Nr.diskCacheTried=!0;let t=OC(e);return t?BC(t,"disk",e):!1}async function UC(e){let t=e.nowMs??Date.now(),r=()=>({source:zt(),version:no(),updated:!1});if(!e.force&&t-Nr.lastAttemptAtMs<g2)return r();Nr.lastAttemptAtMs=t;let n=e.baseUrl?.trim().replace(/\/$/,""),o=e.secret?.trim();if(!n||!o)return zt()==="embedded"&&wa(e.agentOsId)?{...r(),updated:!0}:r();let s=e.fetchImpl??fetch,i=new AbortController,a=setTimeout(()=>i.abort(),h2);try{let l=Ut(o);delete l["Content-Type"],Nr.etag&&zt()==="server"&&(l["If-None-Match"]=Nr.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 Nr.routeMissingLogged||(Nr.routeMissingLogged=!0,Sa("instruction_bundle_route_missing",{agentOsId:e.agentOsId,baseUrl:n})),zt()==="embedded"&&wa(e.agentOsId)?{...r(),updated:!0}:r();if(!c.ok)return Sa("instruction_bundle_fetch_failed",{agentOsId:e.agentOsId,status:c.status}),zt()==="embedded"&&wa(e.agentOsId)?{...r(),updated:!0}:r();let u=await c.json().catch(()=>null);return!u||!BC(u,"server",e.agentOsId)?zt()==="embedded"&&wa(e.agentOsId)?{...r(),updated:!0}:r():(Nr.etag=c.headers.get("etag"),Sa("instruction_bundle_loaded",{agentOsId:e.agentOsId,version:no(),publicKeyId:u.publicKeyId}),{...r(),updated:!0})}catch(l){return Sa("instruction_bundle_fetch_error",{agentOsId:e.agentOsId,error:l instanceof Error?l.message:String(l)}),zt()==="embedded"&&wa(e.agentOsId)?{...r(),updated:!0}:r()}finally{clearTimeout(a)}}var g2,h2,Nr,FC=p(()=>{"use strict";Cs();TC();pn();LC();g2=15*6e4,h2=1e4,Nr={lastAttemptAtMs:0,etag:null,diskCacheTried:!1,routeMissingLogged:!1}});import y2 from"node:os";function WC(e,t){console.error(JSON.stringify({event:"daemon_identity",level:e,message:t}))}function KC(e=A(),t=process.env){let r=lt(t,e),n=as({config:e,totalMemBytes:y2.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=kr(r.boxKind,i);Vi(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)WC("warn",c);for(let c of s)WC("error",c);return{ok:l,box:r,workerCapSource:n.workerCapSource,maxConcurrentWorkers:a,autoCap:n.autoCap,warnings:o,errors:s}}var $C=p(()=>{"use strict";$();Ke();zo();ta()});import{spawnSync as k2}from"node:child_process";import{existsSync as b2,readFileSync as v2}from"node:fs";import R2 from"node:path";function S2(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+w2<s.startedAtMs||o.push({workerName:s.workerName,workerPid:s.pid,orphanPid:i.pid}));return o}function _2(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 x2(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=k2("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:3e4});if(o.status!==0)return[];try{return _2(o.stdout??"")}catch{return[]}}function C2(e,t=ne){try{let r=xe().find(o=>o.id===e);if(!r)return[];let n=[];for(let o of Object.keys(r.workers||{})){let s=R2.join(J(r.id),"workers",F(o),"worker.json");if(!b2(s))continue;let i=JSON.parse(v2(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 HC(e,t={}){if((t.platform??process.platform)!=="win32"||!e)return{checkedWorkers:0,killed:[]};let n=t.isAlive??ne,o=(t.collect??(l=>C2(l,n)))(e);if(o.length===0)return{checkedWorkers:0,killed:[]};let s=(t.query??x2)(o.map(l=>l.pid)),i=t.killTree??he,a=S2(s,o,n).map(l=>({...l,result:i(l.orphanPid,"SIGKILL")}));return{checkedWorkers:o.length,killed:a}}var w2,jC=p(()=>{"use strict";Q();U();Go();w2=5e3});import{mkdirSync as E2,readFileSync as A2,renameSync as I2,writeFileSync as P2}from"node:fs";import{homedir as O2}from"node:os";import Lu from"node:path";function VC(){return Lu.join(O2(),".kynver")}function T2(e=VC()){return Lu.join(e,"doctor-native-windows.json")}function GC(e=VC()){return Lu.join(e,"native-windows-state.json")}function N2(e,t){E2(Lu.dirname(e),{recursive:!0});let r=`${e}.tmp-${process.pid}`;P2(r,`${JSON.stringify(t,null,2)}
|
|
145
|
+
`,{mode:384}),I2(r,e)}function kh(e){try{return JSON.parse(A2(e,"utf8"))}catch{return null}}function D2(e){let t=kh(T2(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 JC(e=new Date,t){try{let r=GC(t),n=kh(r)??{};N2(r,{...n,lastWorkerCompletedAt:e.toISOString()})}catch{}}function M2(e){let t=kh(GC(e));return typeof t?.lastWorkerCompletedAt=="string"?t.lastWorkerCompletedAt:null}function YC(e){yh=e.admission,qC=e.ownerKind}function zC(e={}){let t=e.platform??process.platform,r=e.hostKind??ig(),n=r==="win32";return{hostKind:r,wsl:r==="wsl",platform:t,arch:process.arch,nodeVersion:process.versions.node,runtimeVersion:et,ownerKind:qC,nativeWindows:n?{admission:yh?.basis??null,hostCapability:yh?.hostCapability??null,lastDoctor:D2(e.root),lastWorkerCompletedAt:M2(e.root)}:null}}var yh,qC,Bu=p(()=>{"use strict";zc();dn();yh=null,qC=null});function L2(e){return typeof e=="string"&&XC.includes(e)}function B2(e,t){let r=e[t]?.trim().toLowerCase();return r==="1"||r==="true"||r==="yes"||r==="on"}function F2(e={}){let t=e.platform??process.platform,r=e.env??process.env;return e.hostCapability!==void 0&&!L2(e.hostCapability)?{allowed:!1,reason:"invalid_host_capability",remedy:"hostCapability must be one of: "+XC.join(", ")}:t!=="win32"?{allowed:!0,basis:"not_native_windows",hostCapability:e.hostCapability??null}:e.hostCapability?{allowed:!0,basis:"host_capability",hostCapability:e.hostCapability}:B2(r,bh)?{allowed:!0,basis:"experimental_env_override",hostCapability:null}:{allowed:!1,reason:"native_windows_unqualified",remedy:U2}}function vh(e={}){let t=F2(e);return t.allowed?(t.basis==="experimental_env_override"&&console.error(JSON.stringify({event:"daemon_native_windows_experimental",override:bh,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 XC,bh,U2,Rh=p(()=>{"use strict";XC=["desktop-supervised","native-windows-qualified"],bh="KYNVER_DAEMON_ALLOW_NATIVE_WINDOWS";U2=`Run the daemon inside WSL: .\\scripts\\start-tier2-wsl.ps1 \u2014 or set ${bh}=1 for the experimental native path (not yet qualified; \`kynver doctor runner-install\` reports the host).`});function W2(e){return e.replace(/\/+$/,"")}async function QC(e){let t=e.fetchFn??fetch,r=e.entry.spec.callbackPath.startsWith("/")?e.entry.spec.callbackPath:`/${e.entry.spec.callbackPath}`,n=`${W2(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:Ut(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 ZC=p(()=>{"use strict";Cs()});import{closeSync as K2,existsSync as wh,openSync as $2,readFileSync as H2,unlinkSync as eE,writeFileSync as j2}from"node:fs";function tE(e){if(!wh(e))return null;try{let t=JSON.parse(H2(e,"utf8"));if(typeof t.pid=="number"&&typeof t.at=="string")return t}catch{return null}return null}function G2(e){let t=tE(e);if(!t||!ne(t.pid))return!0;let r=Date.parse(t.at);return Number.isNaN(r)?!0:Date.now()-r>V2}function rE(e){if(wh(e)&&!G2(e)){let t=tE(e);return{acquired:!1,reason:t?`held by pid ${t.pid}`:"held by another process"}}if(wh(e))try{eE(e)}catch{}try{let t=$2(e,"wx");return j2(t,JSON.stringify({pid:process.pid,at:new Date().toISOString()}),"utf8"),K2(t),{acquired:!0}}catch(t){if(t.code==="EEXIST")return{acquired:!1,reason:"concurrent acquire"};throw t}}function nE(e){try{eE(e)}catch{}}var V2,oE=p(()=>{"use strict";U();V2=10*6e4});function q2(e){return J2.test(e.trim())}function Y2(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 _a(e,t,r,n){let o=e.trim();return o==="*"?!0:Y2(o,r,n).has(t)}function z2(e,t){let r=e.trim().split(/\s+/);if(r.length!==5)return!1;let[n,o,s,i,a]=r;return _a(n,t.getUTCMinutes(),0,59)&&_a(o,t.getUTCHours(),0,23)&&_a(s,t.getUTCDate(),1,31)&&_a(i,t.getUTCMonth()+1,1,12)&&_a(a,t.getUTCDay(),0,6)}function Q2(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),0,0))}function sE(e,t){if(!q2(e))return null;let r=Q2(t);r=new Date(r.getTime()+6e4);for(let n=0;n<X2;n++){if(z2(e,r))return r;r=new Date(r.getTime()+6e4)}return null}function iE(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=sE(e.cron.trim(),t);return r?r.toISOString():null}return null}function Sh(e,t){if(e.scheduleKind!=="cron"||!e.cron?.trim())return null;let r=sE(e.cron.trim(),t);return r?r.toISOString():null}var J2,X2,aE=p(()=>{"use strict";J2=/^[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+\s+[\d*/,\-?LW#]+$/;X2=366*24*60});import{randomBytes as Z2}from"node:crypto";import{promises as xa}from"node:fs";import eq from"node:path";async function tq(e){try{return await xa.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function rq(e){if(!e)return{...Uu,jobs:{...Uu.jobs}};try{let t=JSON.parse(e);return t?.version!==1||typeof t.jobs!="object"||!t.jobs?{...Uu,jobs:{}}:t}catch{return{...Uu,jobs:{}}}}async function _h(e){let t=await tq(e);return rq(t)}async function nq(e,t){await xa.mkdir(eq.dirname(e),{recursive:!0});let r=Z2(6).toString("hex"),n=`${e}.tmp-${process.pid}-${Date.now()}-${r}`;await xa.writeFile(n,`${JSON.stringify(t,null,2)}
|
|
146
|
+
`,"utf8");try{await xa.rename(n,e)}catch(o){let s=o.code;if(s!=="EPERM"&&s!=="EEXIST"&&s!=="EACCES")throw o;await xa.unlink(n).catch(()=>{})}}async function lE(e,t){await nq(e,t)}function cE(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 Uu,xh=p(()=>{"use strict";Uu={version:1,jobs:{}}});function oq(e,t){if(!e.inflightUntil)return!1;let r=Date.parse(e.inflightUntil);return!Number.isNaN(r)&&r>t}function sq(e){return!!e.completedAt}function iq(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 aq(e,t,r){if(t.nextFireAt)return t.nextFireAt;let n=iE(e.spec,r);return t.nextFireAt=n,n}function lq(e,t,r,n){if(e.paused||sq(t)||oq(t,r)||!iq(e,t,n,r))return!1;let o=t.nextFireAt?Date.parse(t.nextFireAt):NaN;return Number.isNaN(o)?!1:r>=o}function cq(e,t,r){e.spec.scheduleKind==="cron"&&(t.nextFireAt=Sh(e.spec,r))}async function Ch(e={}){let t=e.env??Rs(),r=e.now??new Date,n=r.getTime(),o=e.agentOsIdFilter?Be(e.agentOsIdFilter):Be();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=rE(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 Au(t.storePath),a=e.agentOsIdFilter?i.filter(h=>h.spec.target.agentOsId===e.agentOsIdFilter):i,l=await _h(t.statePath),c=[];for(let h of a){let k=cE(l,h.providerScheduleId);aq(h,k,r),lq(h,k,n,t)&&c.push({entry:h,job:k})}c.sort((h,k)=>{let v=Date.parse(h.job.nextFireAt??"")||0,y=Date.parse(k.job.nextFireAt??"")||0;return v-y});let u=0,d=0,f=0,m=t.maxCatchUpPerTick,g=[];for(let{entry:h,job:k}of c){if(t.missedRunPolicy==="skip"&&h.spec.scheduleKind==="cron"){let v=Date.parse(k.nextFireAt??"");if(!Number.isNaN(v)&&v<n-t.tickIntervalMs*2){k.nextFireAt=Sh(h.spec,r),f++;continue}}if(m<=0){f++;continue}k.inflightUntil=new Date(n+t.inflightLeaseMs).toISOString(),k.lastAttemptAt=r.toISOString(),cq(h,k,r);try{let v=Be(h.spec.target.agentOsId)||t.secret;if(!v){k.inflightUntil=null,k.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,error:"missing_fire_credentials"});continue}let y=await QC({entry:h,baseUrl:t.fireBaseUrl,secret:v,fetchFn:e.fetchFn});k.inflightUntil=null,y.ok?(k.lastFiredAt=r.toISOString(),k.consecutiveFailures=0,h.spec.scheduleKind==="runAt"&&(k.completedAt=r.toISOString(),k.nextFireAt=null),u++,m--):(k.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,url:y.url,status:y.status,body:y.body}))}catch(v){k.inflightUntil=null,k.consecutiveFailures+=1,d++,g.push({providerScheduleId:h.providerScheduleId,callbackPath:h.spec.callbackPath,error:v instanceof Error?v.message:String(v)})}}return await lE(t.statePath,l),{enabled:!0,scanned:a.length,due:c.length,fired:u,skippedJobs:f,errors:d,...g.length?{errorDetails:g}:{}}}finally{nE(t.lockPath)}}var Eh=p(()=>{"use strict";Ar();ZC();oE();$();aE();ws();xh()});import uE from"node:path";function Fu(e){let t=K(uE.join(J(e),dE),null);return yC(e,t)??t}function pE(e,t){let r={...t,updatedAt:new Date().toISOString()};we(uE.join(J(e),dE),r),hC(e,r)}function fE(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 dE,Ah=p(()=>{"use strict";U();Q();va();dE="mesh-cron-lease.json"});function hE(e){Ca=e}function yE(e=Date.now()){return!Ca||Ca.stallCount===mE&&e-gE<9e5?null:(mE=Ca.stallCount,gE=e,Ca)}var Ca,mE,gE,Ih=p(()=>{"use strict";Ca=null,mE=-1,gE=0});function bE(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 kE(e){return new Error(`callback timeout after ${e}ms`)}async function vE(e,t){let r=bE(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(kE(r))},r)})])}catch(i){throw s?kE(r):i}finally{o&&clearTimeout(o)}}function RE(e,t){let r=bE(t);return{ok:!1,status:0,response:{error:e instanceof Error?e.message:String(e),timeoutMs:r}}}async function oo(e,t,r,n){try{return await vE(async o=>{let s=await bt(e,{method:"POST",headers:Ut(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 RE(o,n?.timeoutMs)}}async function fe(e,t,r,n){let o=await oo(e,t,r,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await F_(t,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await oo(e,s.token,r,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function Ph(e,t,r){try{return await vE(async n=>{let o=await bt(e,{method:"GET",headers:Ut(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 RE(n,r?.timeoutMs)}}var Je=p(()=>{"use strict";Cs();yr();$()});function wE(){let e=Number(process.env.KYNVER_DISPATCH_CALLBACK_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):3e5}var SE=p(()=>{"use strict"});function Ea(e){console.error(JSON.stringify({event:"dispatch_progress",ts:new Date().toISOString(),...e}))}function _E(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 Oh(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 xE=p(()=>{"use strict"});function pq(e){return uq.includes(e)}function fq(e){return dq.includes(e)}function CE(e){return{slug:e.slug,displayName:e.displayName,description:e.description,dispatchLane:e.dispatchLane===null||pq(e.dispatchLane)?e.dispatchLane:null,defaultRoleLane:fq(e.defaultRoleLane)?e.defaultRoleLane:"implementer"}}function gq(e){if(!e)return null;let t=e.trim().toLowerCase(),r=mq.get(t)??null,n=qx(t);if(!n)return r;let o=CE(n);return r?{...o,dispatchLane:r.dispatchLane,defaultRoleLane:r.defaultRoleLane}:o}function Th(e){return gq(e)?.defaultRoleLane??null}function AE(){return EE.filter(e=>e.dispatchLane==="review").map(e=>e.slug)}var uq,dq,EE,mq,Wu=p(()=>{"use strict";rh();pn();uq=["implementation","review","landing"],dq=["plan_author","implementer","report_reviewer","deep_reviewer","runtime_verifier","system"];EE=Ss.personas.map(CE),mq=new Map(EE.map(e=>[e.slug,e]))});function IE(e){return(e??"").trim().toLowerCase()}function hq(e){switch(IE(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 yq(e){let t=IE(e);if(!t)return;if(t==="implementation"||t==="review"||t==="landing"||t==="any")return t;let r=hq(t);if(r)return r;if(t==="implement"||t==="repair"||t==="coding")return"implementation";if(t==="land"||t==="merge")return"landing"}function PE(e){return yq(e)??"any"}var OE=p(()=>{"use strict";Wu()});function kq(e=process.env){let t=A();return Dt(t,e)!=="forge"}function Ku(e,t=process.env){if(kq(t))return e?.maxConcurrentWorkers??void 0}async function $u(e,t){let r=me(t.baseUrl?String(t.baseUrl):void 0),n=await ye(t.secret?String(t.secret):void 0,e,{baseUrl:r}),o=`${r}/api/agent-os/by-id/${encodeURIComponent(e)}/runtime`;try{let s=await Ph(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 Nh=p(()=>{"use strict";Je();$();Ke()});async function TE(e,t=bq){let r=await t.fetchPreferences(e.agentOsId,e.args),n=t.configuredOverride(r,e.env);return t.observe({runId:e.runId,configuredMaxWorkersOverride:n})}var bq,NE=p(()=>{"use strict";Nh();is();bq={fetchPreferences:$u,configuredOverride:Ku,observe:ea}});function Hu(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function Dh(e){return e.toLowerCase()}function vq(e){let t=Hu(e,"roleLane");if(t)return t;let r=Dh(Hu(e,"executorRef")),n=Dh(Hu(e,"title")),o=Dh(Hu(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=Th(o);if(i)return o==="lorentz"&&(s.includes("deep")||s.includes("security"))?"deep_reviewer":i;if(s.includes("review"))return"report_reviewer"}function DE(e){let t=vq(e);return t?{...e,roleLane:t}:e}var ME=p(()=>{"use strict";Wu()});function LE(e){let t=e.trim();return Rq.test(t)||wq.test(t)}function BE(e){let t=e.trim().toLowerCase();return t.startsWith("gpt-")||t.startsWith("gpt5")||t.includes("codex")}function Mh(e){let t=e.trim().toLowerCase();return t.includes("composer")||t.includes("cursor")}function UE(e){return e.trim().toLowerCase().startsWith("gemini-")}function Sq(e){return BE(e)?"codex":LE(e)?"claude":UE(e)?"gemini":(Mh(e),"cursor")}function _q(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 xq(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?LE(n)||BE(n)||Mh(n)||UE(n)?{lane:r,model:n,provider:Sq(n),rule:"executor_ref:harness_lane_model"}:{lane:r,rule:"executor_ref:harness_lane"}:{lane:r,rule:"executor_ref:harness_lane"}}function Rt(e){let t=typeof e=="string"?e.trim():"";return t?_q(t)??xq(t):null}function FE(e){let t=Rt(e);return t?!!(t.provider&&t.provider!=="cursor"||t.model&&!Mh(t.model)):!1}var Rq,wq,ju=p(()=>{"use strict";Rq=/^claude[-_]/i,wq=/^(?:opus|sonnet|haiku)\b/i});function Aa(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function Dr(e){if(!e?.trim())return!1;let t=e.trim().toLowerCase();return Cq.has(t)?!0:t.includes("claude")||t.includes("opus")}function Vu(e){if(!e)return!1;let t=e.workerProviderOverride;if(typeof t=="string"&&Dr(t))return!0;let r=Aa(e,"executorRef").toLowerCase();if(r==="provider:claude"||r.startsWith("provider:claude:")||r.includes("claude-worker-override")||r.includes("operator-claude"))return!0;let n=Rt(Aa(e,"executorRef"));if(n?.provider&&Dr(n.provider)||n?.model&&Dr(Aq(n.model)))return!0;let o=Aa(e,"description");if(Eq.some(i=>i.test(o)))return!0;let s=Aa(e,"title");return!!/\[use-claude-worker\]/i.test(s)}function Aq(e){let t=e.trim().toLowerCase();return/^claude[-_]/.test(t)||/^(?:opus|sonnet|haiku)\b/.test(t)?"claude":t}function Iq(e,t){return{provider:Mr,model:Gu,rule:`policy:cursor_default${t}`,requestedModel:e}}function Oq(e){return Pq.some(t=>e.startsWith(t))}function Lh(e){if(!e)return!1;let t=e.workerProviderOverride;return typeof t=="string"&&t.trim()||Rt(Aa(e,"executorRef"))?.provider?!0:Vu(e)}function WE(e){let{routing:t,task:r}=e,n=e.explicitProvider?.trim().toLowerCase();if(e.explicitProviderIsOperatorOverride&&Dr(n))return{...t,provider:"claude",rule:t.rule.startsWith("explicit:")?t.rule:"explicit:operator_provider"};if(n||Oq(t.rule)||Lh(r)||!Dr(t.provider))return t;let o=t.rule&&t.rule!=="default:global"?`:${t.rule.replace(/:/g,"_")}`:"";return Iq(t.model,o)}function KE(e,t=Mr){let r=e?.trim();return r?Xe(r):t}var Mr,Cq,Eq,Pq,so=p(()=>{"use strict";ju();Ju();ia();ia();Mr="cursor",Cq=new Set(["claude","opus","anthropic"]),Eq=[/\[worker-provider:\s*claude\]/i,/\[use-claude-worker\]/i,/\[operator-worker-provider:\s*claude\]/i];Pq=["explicit:","executor_ref:","factory:","task:"]});function Ps(e){return $E[e]}function HE(){return Object.values($E)}var $E,Bh=p(()=>{"use strict";$E={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{createHash as jE}from"node:crypto";import{statSync as Tq}from"node:fs";import{spawnSync as VE}from"node:child_process";function Xt(e){try{let t=Tq(e),r=`${e}|${t.size}|${t.mtimeMs}`;return jE("sha256").update(r).digest("hex").slice(0,16)}catch{return}}function Os(e){return jE("sha256").update(`env:${e}`).digest("hex").slice(0,16)}function wt(e,t){for(let r of t){let n=process.env[r]?.trim();if(n)return n}return e}function Wt(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=se(e,t),i=VE(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 qu(e,t,r={}){let n=r.timeoutMs??8e3;try{let[o,s]=se(e,t);return VE(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 io=p(()=>{"use strict";We()});import{existsSync as Nq}from"node:fs";import{homedir as Dq}from"node:os";import Ia from"node:path";function Lq(){let e=Dq();return[process.env.CODEX_HOME?.trim()?Ia.join(Ia.resolve(process.env.CODEX_HOME.trim()),"auth.json"):null,Ia.join(e,".codex","auth.json"),Ia.join(e,".config","codex","auth.json")].filter(r=>!!r)}function Bq(e){return Ia.dirname(e)}function Uq(e){let t,r;for(let n of Lq()){if(!Nq(n))continue;t??=n;let o=Wt(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status",env:{CODEX_HOME:Bq(n)}});if(r??=o,o.ok)return{authPath:n,login:o}}return{authPath:t,login:r??Wt(e,["login","status"],{okNote:"codex login status: authenticated",failPrefix:"codex login status"})}}function GE(e=new Date().toISOString()){let t=wt(Mq,["KYNVER_CODEX_BIN","CODEX_BIN"]);if(process.env.CODEX_API_KEY?.trim())return{providerId:"codex",ready:!0,authSource:"api_key_env",sessionFingerprint:Os("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}=Uq(t),o=!!r&&n.ok;return{providerId:"codex",ready:o,authSource:"oauth_local",sessionFingerprint:r?Xt(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 Mq,JE=p(()=>{"use strict";io();Mq="codex"});import{existsSync as Fq}from"node:fs";import{homedir as Wq}from"node:os";import Uh from"node:path";function Kq(){let e=process.env.HERMES_HOME?.trim(),t=e?Uh.resolve(e):Uh.join(Wq(),".hermes");return Uh.join(t,"auth.json")}function Yu(e=new Date().toISOString()){let t=wt("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=Wt(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=Kq(),o=Fq(n),s=qu(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?Xt(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 Fh=p(()=>{"use strict";io()});function Ts(e=new Date().toISOString()){let t=GE(e);if(t.ready)return{...t,path:"codex_cli"};let r=Yu(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 zu=p(()=>{"use strict";JE();Fh()});function zE(e,t){let r=Ps(e);return t==="privileged"?r.supportsPrivilegedPlatformActions:t==="low"?r.supportsLowRiskOrchestration:!0}function $q(e,t){let r=Ps(e.providerId),n=Ps(t.providerId),o=qE.indexOf(r.costTier)-qE.indexOf(n.costTier);if(o!==0)return o;let s=YE[e.binding.authSource]-YE[t.binding.authSource];return s!==0?s:e.providerId.localeCompare(t.providerId)}function Wh(e){let t=HE().map(a=>({providerId:a.id,binding:e.inventory.bindings[a.id]})).filter(a=>a.binding.ready&&zE(a.providerId,e.riskClass));if(t.length===0)return null;let n=[...t].sort($q)[0],o="codex";if(n.providerId===o)return{providerId:n.providerId,binding:n.binding};let s=e.inventory.bindings[o],i;return zE(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 qE,YE,XE=p(()=>{"use strict";Bh();qE=["low","medium","high"],YE={oauth_local:0,subscription_hermes:0,runner_token:1,api_key_env:2,none:3}});import{existsSync as Hq}from"node:fs";import{homedir as jq}from"node:os";import Vq from"node:path";function Jq(){let e=jq();return[Vq.join(e,".claude",".credentials.json")]}function QE(e=new Date().toISOString()){let t=wt(Gq,["KYNVER_CLAUDE_BIN","CLAUDE_BIN"]);if(process.env.ANTHROPIC_API_KEY?.trim())return{providerId:"claude",ready:!1,authSource:"api_key_env",sessionFingerprint:Os("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=Wt(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=Jq().find(i=>Hq(i)),o=qu(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?Xt(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 Gq,ZE=p(()=>{"use strict";io();Gq="claude"});function St(e,t={}){let r=Fi(e);if(!t.reviewWorker)return r;let n={...r,[qq]:"1"};for(let o of Yq)delete n[o];return n}var qq,Yq,ao=p(()=>{"use strict";Wi();qq="KYNVER_NO_PROD_DB_CREDENTIALS",Yq=["KYNVER_ENV_FILE"]});function eA(e){return e.replace(zq,"")}function Xu(e){return/^claude[-_]/i.test(e)||/^(?:opus|sonnet|haiku)\b/i.test(e)}function Xq(e){let t=e.trim().toLowerCase();return t.startsWith("gemini-")||t==="auto"||t==="pro"||t==="flash"||t==="flash-lite"}function Zq(e){let t=e.trim().toLowerCase();return Qq.has(t)?"auto":null}function Kh(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=eA(r).trim()||t;return tA.test(o)||!Xu(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?Xu(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 $h(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 Ds(e,t){let r=(e??"").trim();if(!r)return{ok:!0,model:t,normalized:!1};let o=eA(r).trim()||t;return Xu(o)||!Xq(o)&&tA.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=Zq(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")`}:Xu(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 zq,tA,Qq,Qt=p(()=>{"use strict";zq=/-(?:thinking(?:-(?:high|medium|low|minimal|max|none))?|high|medium|low|minimal)$/i;tA=/^(?:gpt-|gpt5|o1|o3|o4|gemini-|grok-|composer|deepseek|llama|mistral|qwen|command-)/i;Qq=new Set(["cursor"])});import{existsSync as Pa,readdirSync as eY}from"node:fs";import lo from"node:path";function rY(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 nY(e){let t=lo.join(e,"versions");if(!Pa(t))return null;let r=null,n=-1;for(let o of eY(t,{withFileTypes:!0})){if(!o.isDirectory()||!tY.test(o.name))continue;let s=rY(o.name);s==null||s<=n||(n=s,r=lo.join(t,o.name))}return r}function Qu(e){let t=e?.trim()||lo.join(process.env.LOCALAPPDATA||"","cursor-agent"),r=lo.join(t,"node.exe"),n=lo.join(t,"index.js");if(Pa(r)&&Pa(n))return{nodeExe:r,indexJs:n,versionDir:t};let o=nY(t);if(!o)return null;let s=lo.join(o,"node.exe"),i=lo.join(o,"index.js");return!Pa(s)||!Pa(i)?null:{nodeExe:s,indexJs:i,versionDir:o}}var tY,rA=p(()=>{"use strict";tY=/^\d{4}\.\d{1,2}\.\d{1,2}-[a-f0-9]+$/i});import{closeSync as jh,existsSync as sA,mkdirSync as oY,openSync as Vh,statSync as sY,unlinkSync as nA}from"node:fs";import{spawn as iY}from"node:child_process";import aY from"node:os";import Zt from"node:path";function dY(e,t,r){return{executable:e,prefixArgs:[t],shell:!1,detached:Re(),bundledVersionDir:r}}function Oa(e){if(process.platform==="win32"){let t=/\.(cmd|bat)$/i.test(e),r=/node\.exe$/i.test(e)&&sA(Zt.join(Zt.dirname(e),"index.js"));if(t||r||e==="agent"){let o=t?Qu(Zt.dirname(e)):r?{nodeExe:e,indexJs:Zt.join(Zt.dirname(e),"index.js"),versionDir:Zt.dirname(e)}:Qu();if(o)return dY(o.nodeExe,o.indexJs,o.versionDir);throw new Error("Cursor Agent on Windows has no headless bundled node.exe under %LOCALAPPDATA%\\cursor-agent\\versions\\\u2026. Run `agent login` / update Cursor Agent CLI, use `--provider claude`, or set KYNVER_CURSOR_AGENT_ROOT to the cursor-agent folder.")}}return{executable:e,prefixArgs:[],shell:!1,detached:Re()}}function pY(e,t,r){return St({...process.env,CI:"1",NO_COLOR:"1",...t.bundledVersionDir?{CURSOR_INVOKED_AS:Zt.basename(e)||"agent.cmd"}:{}},{reviewWorker:r})}function iA(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Gh(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 fY(){let e=process.env.KYNVER_CURSOR_START_LOCK_DIR?.trim()||Zt.join(aY.homedir(),".kynver","locks");return oY(e,{recursive:!0}),Zt.join(e,"cursor-agent-start.lock")}function mY(){if(process.env.KYNVER_CURSOR_START_LOCK==="0")return()=>{};let e=fY(),t=Gh("KYNVER_CURSOR_START_LOCK_TIMEOUT_MS",cY),r=Gh("KYNVER_CURSOR_START_LOCK_STALE_MS",uY),n=Date.now();for(;;)try{let o=Vh(e,"wx");return jh(o),()=>{try{nA(e)}catch{}}}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-sY(e).mtimeMs>r){nA(e);continue}}catch{continue}if(Date.now()-n>t)throw new Error(`timed out waiting for Cursor agent start lock: ${e}`);iA(250)}}function co(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=Qu(e.KYNVER_CURSOR_AGENT_ROOT?.trim()||void 0);if(r)return r.nodeExe;let n=Zt.join(e.LOCALAPPDATA||"","cursor-agent","agent.cmd");if(sA(n))return n}return"agent"}function gY(){return co(process.env)}function oA(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 Hh,lY,cY,uY,aA,Ls=p(()=>{"use strict";Rr();U();ao();Qt();rA();Hh="composer-2.5",lY=15e3,cY=6e4,uY=3e4;aA={name:"cursor",defaultModel:Hh,preflightModel(e){return Ms(e,Hh)},start(e){let t=Ms(e.model,Hh);if(!t.ok)throw new Error(`cursor provider model preflight failed: ${t.note}`);let r=t.model,n=Vh(e.stdoutPath,"a"),o=Vh(e.stderrPath,"a"),s=["ignore",n,o],i=gY(),a=Oa(i),l=mY(),c;try{let[u,d]=a.shell?[a.executable,oA(e,r,a.prefixArgs)]:ct(a.executable,oA(e,r,a.prefixArgs),e.workerDir);c=iY(u,d,Z({cwd:e.worktreePath,detached:a.detached,shell:a.shell,stdio:s,env:pY(i,a,e.reviewWorker)})),iA(Gh("KYNVER_CURSOR_START_LOCK_HOLD_MS",lY))}finally{l(),jh(n),jh(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 hY}from"node:child_process";function Zu(e,t=process.env){try{let r;try{r=Oa(e)}catch{r={executable:e,prefixArgs:[]}}let n=hY(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 Jh=p(()=>{"use strict";Bs();Ls()});import{existsSync as lA}from"node:fs";import{homedir as yY}from"node:os";import uo from"node:path";import{spawnSync as kY}from"node:child_process";function bY(e){if(uo.isAbsolute(e)||e.includes("/")||e.includes("\\"))return lA(e);try{let t=kY(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function ed(e=process.env){let t=[],r=e.KYNVER_CURSOR_AUTH_HOME?.trim();r&&(t.push(uo.join(r,".config","cursor","auth.json")),t.push(uo.join(r,".cursor-agent","auth.json")));let n=yY();if(t.push(uo.join(n,".config","cursor","auth.json")),t.push(uo.join(n,".cursor-agent","auth.json")),process.platform==="win32"){let o=e.LOCALAPPDATA?.trim(),s=e.APPDATA?.trim();o&&t.push(uo.join(o,"cursor-agent","auth.json")),s&&t.push(uo.join(s,"cursor","auth.json"))}return t}function cA(e){return`${e.error}: ${e.detail}`}function rd(e=process.env){let t=co(e);return bY(t)?e.CURSOR_API_KEY?.trim()?{ok:!0,creds:{agentBin:t,authSource:"api_key_env"}}:ed(e).find(n=>lA(n))?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:Zu(t,e).ok?{ok:!0,creds:{agentBin:t,authSource:"oauth_local"}}:{ok:!1,error:qh,detail:"Run `agent login` on this computer, or set CURSOR_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:td,detail:"`agent` CLI not found. Install the Cursor Agent CLI (https://cursor.com/docs/cli/headless) and keep it on PATH."}}var td,qh,Bs=p(()=>{"use strict";Ls();Jh();td="cursor_cli_unavailable",qh="cursor_not_logged_in"});import{existsSync as vY}from"node:fs";function uA(e=new Date().toISOString()){let t=wt(RY,["KYNVER_CURSOR_AGENT_BIN","CURSOR_AGENT_BIN"]);if(process.env.CURSOR_API_KEY?.trim())return{providerId:"cursor",ready:!1,authSource:"api_key_env",sessionFingerprint:Os("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=Wt(t,["-v"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=ed().find(a=>vY(a)),o=Zu(t),s=!!n||o.ok,i=r.ok&&s;return{providerId:"cursor",ready:i,authSource:"oauth_local",sessionFingerprint:n?Xt(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 RY,dA=p(()=>{"use strict";Bs();Jh();io();RY="agent"});import{existsSync as wY,readFileSync as SY}from"node:fs";import{homedir as _Y}from"node:os";import Yh from"node:path";function CY(){let e=process.env.HERMES_HOME?.trim(),t=e?Yh.resolve(e):Yh.join(_Y(),".hermes");return Yh.join(t,".env")}function EY(e){try{let t=SY(e,"utf8"),r=[];for(let n of xY)new RegExp(`^${n}=`,"m").test(t)&&r.push(n);return r}catch{return[]}}function pA(e=new Date().toISOString()){let t=wt("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),r=Wt(t,["--version"],{okNote:`${t} CLI available`,failPrefix:`${t} CLI not available`}),n=CY(),o=wY(n),s=o?EY(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?Xt(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 xY,fA=p(()=>{"use strict";io();xY=["OPENAI_API_KEY","ANTHROPIC_API_KEY","KYNVER_API_KEY","KYNVER_BASE_URL"]});function mA(e={}){let t=e.nowIso?.()??new Date().toISOString(),r=Ts(t),n={codex:r,cursor:uA(t),claude:QE(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:pA(t),hermesOpenAiCodex:Yu(t),codexAdapterPath:r.path,readyCount:o}}var gA=p(()=>{"use strict";ZE();zu();dA();fA();Fh()});function zh(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function PY(e){let t=zh(e,"executorRef").toLowerCase(),r=zh(e,"title").toLowerCase(),n=zh(e,"description").toLowerCase(),o=`${t}
|
|
147
147
|
${r}
|
|
148
|
-
${n}`;return
|
|
149
|
-
`}function
|
|
150
|
-
`,{mode:384}),t}function rd(e){try{return EY(hA(e)),!0}catch{return!1}}var PY,OY,be,Oa,fA,TY,NY,DY,dt=p(()=>{"use strict";Mr();PY="KYNVER_WORKER_MCP_TOOLS",OY="mcp-config.json",be="kynver",Oa=["agent_os_context_envelope","agent_os_search_memory","agent_os_search_skills","agent_os_get_skill","agent_os_progress_note"],fA=Oa.map(e=>`mcp__${be}__${e}`),TY={"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"]};NY=["claude","cursor","codex","openai-compatible","gemini","gemini-api"],DY=["openai-compatible","gemini-api"]});import{closeSync as kA,openSync as bA}from"node:fs";import{spawn as LY}from"node:child_process";function BY(e,t){let n=RA(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 RA(e,t,r){return["--model",t,...Pc(r),"-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:fA).join(",")}`]:[],"--",e.prompt]}var vA,Yh=p(()=>{"use strict";vr();io();B();Fe();Xt();br();dt();br();vA={name:"claude",defaultModel:Ke,preflightModel(e){return Lh(e,Ke)},start(e){let t=Lh(e.model,Ke);if(!t.ok)throw new Error(`claude provider model preflight failed: ${t.note}`);let r=t.model;BY(e,r);let n=Ic(r,{pinned:e.modelPinned===!0}),[o,s]=ie("claude",RA(e,r,n)),i=bA(e.stdoutPath,"a"),a=bA(e.stderrPath,"a"),l=["ignore",i,a],[c,u]=lt(o,s,e.workerDir),d=LY(c,u,te({cwd:e.worktreePath,detached:Re(),stdio:l,env:wt(process.env,{reviewWorker:e.reviewWorker})}));if(kA(i),kA(a),!d.pid)throw new Error("failed to spawn claude worker process (is the `claude` CLI on PATH?)");return d.unref(),{pid:d.pid,model:r}}}});var Bs,nd=p(()=>{"use strict";Bs="gpt-5.6-sol"});import{closeSync as wA,openSync as SA}from"node:fs";import{spawn as UY}from"node:child_process";function FY(e,t){return wt({...process.env,CI:"1",NO_COLOR:"1",HERMES_ACCEPT_HOOKS:process.env.HERMES_ACCEPT_HOOKS??"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function WY(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 zh,_A,xA=p(()=>{"use strict";vr();io();B();Fe();so();Xt();nd();zh=process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||Bs;_A={name:"hermes-codex",defaultModel:zh,preflightModel(e){return Ts(e,zh)},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=Ts(e.model,zh);if(!t.ok)throw new Error(`hermes-codex provider model preflight failed: ${t.note}`);let r=t.model,n=Rt("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),[o,s]=ie(n,WY(r,e.prompt)),i=SA(e.stdoutPath,"a"),a=SA(e.stderrPath,"a"),l=["ignore",i,a],[c,u]=lt(o,s,e.workerDir),d=UY(c,u,te({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:l,env:FY(e.reviewWorker,e.codexHome)}));if(wA(i),wA(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 HY(e=process.env){return e[KY]?.trim().toLowerCase()==="elevated"?"elevated":$Y}function od(e=process.platform,t=process.env){return e!=="win32"?[]:["-c",`windows.sandbox="${HY(t)}"`]}var KY,$Y,Xh=p(()=>{"use strict";KY="KYNVER_CODEX_WINDOWS_SANDBOX",$Y="unelevated"});import{closeSync as CA,existsSync as jY,openSync as EA}from"node:fs";import{spawn as Qh}from"node:child_process";function VY(){return process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||Bs}function Br(){return process.env.KYNVER_CODEX_BIN?.trim()||process.env.CODEX_BIN?.trim()||"codex"}function GY(e,t){return wt({...process.env,CI:"1",NO_COLOR:"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function JY(e,t,r,n=process.platform,o=process.env){return["--ask-for-approval","never","exec",...od(n,o),"--json","--sandbox",r==="read_only"?"read-only":"workspace-write","--model",e,t]}function qY(e,t,r,n){if(process.platform==="win32"){let[l,c]=ie(e,t);return Qh(l,c,r)}if(!jY("/usr/bin/script")){let[l,c]=lt(e,t,n);return Qh(l,c,r)}let s=[e,...t].map(l=>`'${l.replace(/'/g,"'\\''")}'`).join(" "),[i,a]=lt("script",["-qfc",s,"/dev/null"],n);return Qh(i,a,r)}var Lr,AA,po=p(()=>{"use strict";vr();io();B();Fe();Yu();Xt();xA();Xh();nd();Lr=VY();AA={name:"codex",defaultModel:Lr,preflightModel(e){return Ts(e,Lr)},start(e){if(Os().path==="hermes_openai_codex"&&e.executionMode!=="read_only")return _A.start(e);let r=Ts(e.model,Lr);if(!r.ok)throw new Error(`codex provider model preflight failed: ${r.note}`);let n=r.model,o=EA(e.stdoutPath,"a"),s=EA(e.stderrPath,"a"),i=["ignore",o,s],a=Br(),l=JY(n,e.prompt,e.executionMode),c;try{c=qY(a,l,te({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:i,env:GY(e.reviewWorker,e.codexHome)}),e.workerDir)}finally{CA(o),CA(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 sd}from"node:fs";import fo from"node:path";import{fileURLToPath as YY}from"node:url";function zY(e,t){let r=fo.resolve(e);for(;;){let n=fo.join(r,t);if(sd(n))return n;let o=fo.dirname(r);if(o===r)return null;r=o}}function XY(e){return zY(e,fo.join("node_modules",".bin","tsx"))??"npx"}function Zh(e,t){if(e.endsWith(".ts")){let r=XY(fo.dirname(e));return{command:r,argsPrefix:r==="npx"?["tsx",e]:[e],cliPath:e}}return{command:t,argsPrefix:[e],cliPath:e}}function id(e){if(e.explicitCliPath)return sd(e.explicitCliPath)?Zh(e.explicitCliPath,e.nodeExecutable):null;let t=YY(new URL(".",e.importMetaUrl)),r=fo.join(t,"cli.js");if(sd(r))return Zh(r,e.nodeExecutable);let n=fo.join(t,"cli.ts");return sd(n)?Zh(n,e.nodeExecutable):null}var ey=p(()=>{"use strict"});function ZY(e){return`/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/worker`}async function Da(e,t,r){let n=await e.fetchImpl(`${e.apiBaseUrl}${t}`,{method:r?.method??"GET",headers:{[QY]: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 Ma(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function ad(e,t,r){let n=ZY(e);switch(t){case"agent_os_context_envelope":{let o=new URLSearchParams({task:e.taskId}),s=Ma(r.memoryQuery);s&&o.set("memoryQuery",s);let i=Ma(r.mode);return i&&o.set("mode",i),Da(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)),Da(e,`${n}/memory-search?${o.toString()}`)}case"agent_os_search_skills":{let o=new URLSearchParams,s=Ma(r.query);s&&o.set("q",s),typeof r.limit=="number"&&o.set("limit",String(r.limit));let i=o.toString();return Da(e,`${n}/skills${i?`?${i}`:""}`)}case"agent_os_get_skill":return Da(e,`${n}/skills/${encodeURIComponent(String(r.slug??""))}`);case"agent_os_progress_note":return Da(e,`${n}/progress-note`,{method:"POST",body:{note:String(r.note??""),...r.kind==="blocked"?{kind:"blocked"}:{},...Ma(r.eventKey)?{eventKey:Ma(r.eventKey)}:{}}})}}function Us(e){return Oa.includes(e)}var QY,La,ld=p(()=>{"use strict";dt();QY="X-Kynver-Job-Token",La={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 Ba(e){return Ta(e).filter(Us).map(t=>{let r=La[t];return{type:"function",function:{name:r.name,description:r.description,parameters:r.inputSchema}}})}var cd=p(()=>{"use strict";ld();dt()});import{closeSync as IA,openSync as PA}from"node:fs";import ez from"node:path";import{fileURLToPath as tz}from"node:url";import{spawn as rz}from"node:child_process";function ty(e=process.env){return e.KYNVER_WORKER_MODEL?.trim()||void 0}function oz(e=process.env){let t=e.KYNVER_WORKER_BASE_URL?.trim();if(!t)throw new Ua(`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 Ua(`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 Ua(`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):nz;return{baseUrl:t.replace(/\/+$/,""),...e.KYNVER_WORKER_API_KEY?.trim()?{apiKey:e.KYNVER_WORKER_API_KEY.trim()}:{},timeoutMs:o}}function ud(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:sz},{role:"user",content:r}],...n&&n.length?{tools:n,tool_choice:"auto"}:{}}}}function iz(){let e=tz(new URL(".",import.meta.url)),t=import.meta.url.endsWith(".ts"),r=ez.join(e,t?"openai-compatible-runner.ts":"openai-compatible-runner.js"),n=id({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 az(e,t,r){let n=e.workerToolGrant,o=n?Ba(n.capabilities):void 0;return{provider:mo,model:r,request:ud(t,r,e.prompt,o),timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}function dd(e,t,r){let n=iz(),o=PA(e.stdoutPath,"a"),s=PA(e.stderrPath,"a"),i=["pipe",o,s],[a,l]=lt(n.command,n.argsPrefix,e.workerDir),c=rz(a,l,te({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:i,env:wt(process.env,{reviewWorker:e.reviewWorker})}));if(IA(o),IA(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 mo,nz,Ua,sz,OA,Fa=p(()=>{"use strict";vr();io();B();ey();Xt();cd();mo="openai-compatible",nz=600*1e3;Ua=class extends Error{};sz="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.";OA={name:mo,get defaultModel(){return ty()},preflightModel(e){return Bh(e,ty())},start(e){let t=Bh(e.model,ty());if(!t.ok)throw new Error(`openai-compatible provider model preflight failed: ${t.note}`);let r=t.model,n=oz(process.env),o=az(e,n,r);return dd(e,o,r)}}});import lz from"node:path";function St(e=process.env){return e.KYNVER_GEMINI_BIN?.trim()||e.GEMINI_BIN?.trim()||"agy"}function Fs(e){let t=lz.basename(e).toLowerCase().replace(/\.cmd$/i,"").replace(/\.exe$/i,"");return t==="agy"||t==="antigravity"?"antigravity":"gemini"}function TA(e){return e.requested&&/-(?:high|medium|low)$/i.test(e.requested)?e.requested:e.model}function NA(e){let t=e.trim().toLowerCase();return!t||cz.has(t)?[]:["--model",e.trim()]}function pd(e,t){return[...NA(t),"--output-format","stream-json",...e.executionMode==="read_only"?[]:["--dangerously-skip-permissions"],"--prompt",e.prompt]}function DA(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",be]:[],"--prompt",e.prompt]}var cz,go=p(()=>{"use strict";dt();cz=new Set(["gemini-2.5-pro","gemini-2.5-flash","auto","pro","flash","flash-lite"])});import{closeSync as MA,openSync as LA}from"node:fs";import{spawn as uz}from"node:child_process";function Je(e=process.env){return e.KYNVER_GEMINI_DEFAULT_MODEL?.trim()||"gemini-2.5-pro"}function dz(e,t){return wt({...process.env,CI:"1",NO_COLOR:"1",GEMINI_CLI_TRUST_WORKSPACE:"true",...t?{GEMINI_CLI_HOME:t}:{}},{reviewWorker:e})}var Zt,BA,Wa=p(()=>{"use strict";vr();io();B();Fe();go();Xt();Zt="gemini";BA={name:Zt,get defaultModel(){return Je()},preflightModel(e){return Ns(e,Je())},start(e){let t=Ns(e.model,Je());if(!t.ok)throw new Error(`gemini provider model preflight failed: ${t.note}`);let r=St(),n=Fs(r),o=n==="antigravity"?TA(t):t.model,s=n==="antigravity"?pd(e,o):DA(e,o),[i,a]=ie(r,s),l=LA(e.stdoutPath,"a"),c=LA(e.stderrPath,"a"),u=["ignore",l,c],[d,f]=lt(i,a,e.workerDir),m=uz(d,f,te({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:u,env:dz(e.reviewWorker,n==="gemini"?e.geminiCliHome:void 0)}));if(MA(l),MA(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 fz(e=process.env){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()||void 0}function mz(e=process.env){let t=fz(e);if(!t)throw new Ka('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()||UA,n;try{n=new URL(r)}catch{throw new Ka(`KYNVER_GEMINI_BASE_URL is not a valid URL: "${r}" \u2014 expected e.g. ${UA}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Ka(`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):pz;return{baseUrl:r.replace(/\/+$/,""),apiKey:t,timeoutMs:s}}function gz(e,t,r){let n=e.workerToolGrant,o=n?Ba(n.capabilities):void 0,s=ud(t,r,e.prompt,o);return{provider:er,model:r,request:s,timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}var er,UA,pz,Ka,FA,ry=p(()=>{"use strict";Fa();cd();Xt();Wa();er="gemini-api",UA="https://generativelanguage.googleapis.com/v1beta/openai",pz=600*1e3,Ka=class extends Error{};FA={name:er,get defaultModel(){return Je()},preflightModel(e){return Ns(e,Je())},start(e){let t=Ns(e.model,Je());if(!t.ok)throw new Error(`gemini-api provider model preflight failed: ${t.note}`);let r=t.model,n=mz(process.env),o=gz(e,n,r);return dd(e,o,r)}}});function tt(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function yz(e){if(!e)return;let t=tt(e,"workerModelOverride")||tt(e,"modelOverride");return t||`${tt(e,"title")}
|
|
151
|
-
${
|
|
152
|
-
${tt(e,"executorRef")}`.match(/\[(?:worker-)?model:\s*([^\]\n]+)\]/i)?.[1]?.trim()||void 0}function WA(e){return e.toLowerCase()}function $A(e,t=A(),r=process.env){return e==="explicit:cli"||e==="explicit:spawn"?!0:e==="default:global"?!!(t.defaultModel?.trim()||r.KYNVER_DEFAULT_MODEL?.trim()):!1}function oy(e=A()){let t=e.defaultModel?.trim();if(t)return t;let r=process.env.KYNVER_DEFAULT_MODEL?.trim();return r||hz}function fd(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-")?Zt:"cursor"}function kz(e,t){let r=e.trim().toLowerCase(),n=t?.trim();return r==="cursor"?{model:Vu,provider:"cursor",rule:n&&n!=="cursor"?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="claude"||r==="anthropic"?{model:Ke,provider:"claude",rule:n&&n!=="claude"?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini"||r==="google"?{model:Je(),provider:Zt,rule:n&&n!==Zt?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini-api"||r==="gemini_api"||r==="google-api"?{model:Je(),provider:er,rule:n&&n!==er?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:null}function KA(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 HA(e,t,r){return bz.has(e)?Qr:t.includes("review")||/^review[\s:]/.test(r)||r.includes("critique")?Qr:Ke}function vz(e){let t=WA(tt(e,"executorRef")),r=tt(e,"title").toLowerCase(),n=tt(e,"priority")||"normal",o=WA(tt(e,"roleLane"));if(t.includes("provider:claude")||t.startsWith("claude:")){let i=HA(o,t,r);return{provider:"claude",model:i,rule:i===Qr?"factory:claude_review":"factory:claude_implementation"}}if(t.includes("provider:codex")||t.startsWith("codex:"))return{provider:"codex",model:Lr,rule:"lane:codex_orchestration"};if(t.includes("provider:chatgpt")||t.startsWith("chatgpt:")||t.includes("provider:gpt")||t.startsWith("gpt:")){let i=vt(tt(e,"executorRef"));return{provider:"codex",...i?.model?{model:i.model}:{model:Lr},rule:"lane:codex_orchestration"}}if(t.includes("provider:openai")||t.startsWith("openai-compatible:")){let i=vt(tt(e,"executorRef"));return{provider:mo,...i?.model?{model:i.model}:{},rule:"lane:openai_compatible"}}if(t.includes("provider:gemini-api")||t.startsWith("gemini-api:")){let i=vt(tt(e,"executorRef"));return{provider:er,...i?.model?{model:i.model}:{model:Je()},rule:"lane:gemini_api"}}if(t.includes("provider:gemini")||t.startsWith("gemini:")){let i=vt(tt(e,"executorRef"));return{provider:Zt,...i?.model?{model:i.model}:{model:Je()},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:Lr,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 KA(t,r)||o==="deep_reviewer"?{provider:"cursor",rule:"lane:deep_review"}:{provider:"cursor",rule:"lane:review"};if(KA(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=oy();return{model:s,provider:fd(s),rule:"default:global"}}function Rz(e){return e?vt(tt(e,"executorRef")):null}function wz(e){switch(ze(e)){case Zt:case er:return Je();case"claude":return Ke;case"codex":return Lr;case"cursor":return Vu;default:return}}function VA(e,t,r){let n=ze(t);return n===e.provider&&e.rule===r?e:{...e,provider:n,model:wz(n)??e.model,rule:r}}function Sz(e,t){let r=t?.trim();return!r||e.rule.startsWith("explicit:")&&e.rule!==ny?e:VA(e,r,ny)}function _z(e,t){if(t.explicitProvider?.trim()||Oh(t.task))return e;let r=t.configuredProvider?.trim();if(!r)return e;let n=ze(r);return n===Dr||n===e.provider?e:VA(e,n,jA)}function md(e){let t,r=Rz(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=kz(l,e.explicitProvider);c?t=c:t={model:l,provider:e.explicitProvider?.trim()||fd(l),rule:"explicit:cli",requestedModel:l}}else if(n)t={model:n,provider:o||fd(n),rule:r?.rule??"executor_ref:model",requestedModel:n};else if(e.task&&ju(e.task)){let l=yz(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=HA(d,f,m),u=c===Qr?"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=vz(e.task);t={...l,requestedModel:l.model}}else{let l=oy();t={model:l,provider:e.explicitProvider?.trim()||fd(l),rule:"default:global",requestedModel:l}}t=Sz(t,e.explicitProvider),t=_z(t,{explicitProvider:e.explicitProvider,task:e.task,configuredProvider:e.configuredProvider});let s=!!e.configuredProvider?.trim()&&ze(e.configuredProvider)!==Dr&&t.rule==="config:worker_provider",i=ME({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===ny||i.rule===jA||Nr(i.provider)&&(e.explicitProviderIsOperatorOverride||ju(e.task))||i.provider===mo||i.provider===Zt||i.provider===er||i.provider==="codex")return i;let a=dA({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??Lr:i.model,rule:a.rule,requestedModel:i.requestedModel,orchestrationAudit:a.audit}}function GA(e,t,r){return e||t||r||oy()||Ke}var hz,Vu,bz,ny,jA,Gu=p(()=>{"use strict";$();Hu();pA();Yh();po();Fa();Wa();ry();oo();hz=Ke,Vu="composer-2.5";bz=new Set(["report_reviewer","deep_reviewer","plan_reviewer"]);ny="explicit:cli_provider",jA="config:worker_provider"});function xz(e){let t=e?.executorRef;return typeof t=="string"?t.trim():""}function JA(e){return e?.trim()||void 0}function qA(e){let t=xz(e.task),r=vt(t),n=e.explicitProvider?.trim().toLowerCase(),o=JA(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=JA(e.routing.model),u={provider:l,model:c,rule:e.routing.rule};return s&&s!=="cursor"||t&&DE(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&&!Nr(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 YA=p(()=>{"use strict";Hu();oo()});function zA(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function XA(){return{maxTaskAttempts:zA(process.env.KYNVER_MAX_TASK_ATTEMPTS,Math.floor(_s("harness.maxTaskAttempts",4))),dispatchCooldownMs:zA(process.env.KYNVER_DISPATCH_COOLDOWN_MS,Math.floor(_s("harness.dispatchCooldownMs",5e3)))}}var QA=p(()=>{"use strict";dn()});function iy(e){return e?.trim()?e.trim():null}function Cz(e){let t=iy(e);if(!t?.startsWith(sy))return null;let r=t.slice(sy.length),n=r.indexOf(ZA);return n>=0?r.slice(0,n).trim()||null:r.trim()||null}function $a(e,t){let r=e.trim(),n=t.trim();return`${sy}${r}${ZA}${n}`}function Ez(e,t){let r=iy(t);return r?Cz(e)===r:!1}function gd(e){let t=iy(e.workerLeaseOwner);return t&&Ez(t,e.runId)?t:$a(e.runId,e.runnerId)}var sy,ZA,Ha=p(()=>{"use strict";sy="kynver-harness:",ZA="@runner:"});async function hd(e){let t=new Map,r=e.agentOsId?.trim();if(!r||e.taskIds.length===0)return t;let n=me(e.baseUrl);try{let o=await ye(e.secret,r,{baseUrl:n}),s=`${n}/api/agent-os/by-id/${encodeURIComponent(r)}/harness/monitor/task-leases`,i=await fe(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 ay=p(()=>{"use strict";$();Ge()});async function yd(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 hd({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)&&ne(e.worker.runId,{...e.worker,...l?{leaseOwner:l}:{},leaseToken:a}),{leaseOwner:l,leaseToken:a}}var ly=p(()=>{"use strict";ay();Z()});import Az from"node:path";function eI(e,t){return K(Az.join(q(e),"workers",U(t),"worker.json"),void 0)}async function tI(e,t){let r=se(e),n=String(t.agentOsId||"");if(!n)return{renewed:[],failed:[],skipped:[]};let o=me(t.baseUrl?String(t.baseUrl):void 0),s=await ye(t.secret?String(t.secret):void 0,n,{baseUrl:o}),i=Number(t.leaseMs)>0?Math.floor(Number(t.leaseMs)):uy,a=Ue({runId:e}).runnerId,l=[],c=[],u=[];for(let d of Object.keys(r.workers||{})){let f=eI(e,d);if(!f?.taskId||!f.agentOsId){u.push(d);continue}if(!oe(f.pid)){u.push(d);continue}if(ce(f).status==="done"){u.push(d);continue}let g=gd({runId:e,workerLeaseOwner:f.leaseOwner??null,runnerId:a}),h=await yd({worker:f,agentOsId:n,baseUrl:o,secret:s}),y=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/${encodeURIComponent(f.taskId)}/renew-lease`,b=await fe(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 rI(e,t){let r=se(e);for(let n of Object.keys(r.workers||{})){let o=eI(e,n);if(!(!o||o.taskId!==t||!oe(o.pid)||ce(o).status==="done"))return!0}return!1}var cy=p(()=>{"use strict";$();Ge();Z();Ie();B();kd();Ha();Ir();ly()});import Iz from"node:path";function nI(e){return typeof e?.noRestartAt=="string"&&e.noRestartAt.trim().length>0}function oI(e,t,r,n){return nI(t)||(t.noRestartAt=new Date().toISOString(),t.noRestartSource=r,n&&(t.noRestartReason=n),t.steerRestartRequired=!1,ne(e,t)),t}function bd(e,t={}){let r=t.isAlive??oe,n=t.kill??he,o=t.sleep??gc;return!e||!r(e)?null:(n(e,"SIGTERM"),o(1e3),r(e)?(n(e,"SIGKILL"),"SIGKILL"):"SIGTERM")}function dy(e,t,r,n,o={}){oI(e,t,r,n);let s=bd(t.pid,o),i=bd(t.completionSidecarPid,o);return{workerSignal:s,sidecarSignal:i}}function sI(e,t,r={}){let n=r.isAlive??oe,o=se(e),s=[];for(let i of Object.keys(o.workers||{})){if(r.except&&i===r.except)continue;let a=K(Iz.join(q(o.id),"workers",U(i),"worker.json"),void 0);!a||a.taskId!==t||n(a.pid)||!a.completionSidecarPid||!n(a.completionSidecarPid)||(bd(a.completionSidecarPid,r),a.completionSidecarPid=void 0,a.watcherClearedForRelaunchAt=new Date().toISOString(),ne(o.id,a),s.push(i))}return s}function Pz(e=process.env){let t=String(e.KYNVER_ALLOW_UNWATCHED_WORKER??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function iI(e,t,r,n={}){if(!Pz(n.env))throw dy(e,t,"watcher_attach_failed",r,n.deps),t.status="failed",ne(e,t),new Error(`watcher_attach_failed: ${r}; worker stopped instead of running unwatched`)}var Ws=p(()=>{"use strict";Z();B()});function lI(e){let t=e.baseCommit?.trim()??"",r=[];t&&t!==aI&&r.push({ref:t,source:"baseCommit"});let n=e.base?.trim()??"";n&&n!==aI&&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 aI,cI=p(()=>{"use strict";aI="unknown"});function vd(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function uI(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:vd(e)}function Nz(e){let t=(e.title??"").trim().toLowerCase();if(t.startsWith("fix:")||t.startsWith("repair:"))return!0;let r=(e.executorRef??"").toLowerCase();return!!(r.startsWith(Tz)||r.includes("repair")||r.includes("unblock"))}function Dz(e){let t={repairEnforceOriginalPr:!1,targetPrUrl:null,targetPrBranch:null};if(!e)return t;let r=e.match(Oz);if(!r?.[1])return t;try{let n=JSON.parse(r[1]),o=vd(String(n.targetPrUrl??n.target_pr_url??"")),s=vd(String(n.targetPrBranch??n.target_pr_branch??""));return{repairEnforceOriginalPr:n.repairEnforceOriginalPr===!0||n.repair_enforce_original_pr===!0||!!o,targetPrUrl:o?uI(o):null,targetPrBranch:s}}catch{return t}}function dI(e){if(!Nz(e))return null;let t=Dz(e.description),r=e.prUrl?uI(e.prUrl):null,n=t.targetPrUrl??r;return n?{targetPrUrl:n,targetPrBranch:t.targetPrBranch??vd(e.branch)}:null}function pI(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 Oz,Tz,py=p(()=>{"use strict";Oz=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/i,Tz="next-action-fix:"});var fI=p(()=>{"use strict"});function mI(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=[...ha(`worker.prompt.progress.${n}`).split(`
|
|
153
|
-
`),o],i=
|
|
154
|
-
`),a=
|
|
155
|
-
`);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.",...
|
|
156
|
-
`),"",...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?[...
|
|
157
|
-
`)}var
|
|
158
|
-
${n}`,s=
|
|
159
|
-
`).map(t=>t.trim()).find(Boolean)??""}function
|
|
148
|
+
${n}`;return AY.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":IY.some(s=>s.test(o))?"low":"elevated"}function OY(e){let t=Ps(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 TY(e){let t=e.inventory??mA();return e.codexBinding?{...t,bindings:{...t.bindings,codex:e.codexBinding}}:t}function po(e){let t=OY({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 hA(e){let t=e.task??{},r=PY(t),n=TY({inventory:e.inventory,codexBinding:e.codexBinding??(e.inventory?null:Ts())}),o=e.preferLowCost===!1?null:e.explicitProvider?.trim().toLowerCase(),s=e.explicitModel?.trim()||void 0,i=Mr;if(o==="codex"||o==="provider:codex"){let c=n.bindings.codex;if(!c.ready){let u=Wh({inventory:n,riskClass:r});return po(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 po({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 po({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 po({providerId:"claude",binding:c,riskClass:r,routingRule:"orchestration:explicit_claude",model:s})}let a=Wh({inventory:n,riskClass:r});if(a)return po({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 po({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 AY,IY,yA=p(()=>{"use strict";so();Bh();zu();XE();gA();AY=[/\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],IY=[/\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 Xh(e){return`${JSON.stringify(e)}
|
|
149
|
+
`}function Qh(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 Kt,Lr=p(()=>{"use strict";Kt="KYNVER_WORKER_BROKER_SOCKET"});import{unlinkSync as NY,writeFileSync as DY}from"node:fs";import MY from"node:path";function Na(e){if(!e||e.length===0)return[...Ta];let t=new Set;for(let r of e)for(let n of UY[r]??[])t.add(n);return Ta.filter(r=>t.has(r))}function bA(e){return Na(e).map(t=>`mcp__${be}__${t}`)}function KY(e){return FY.includes(e)}function Zh(e){return WY.includes(e)}function vA(e){return KY(e)&&!Zh(e)}function Da(e=process.env){let t=e[LY]?.trim().toLowerCase();return t?t==="1"||t==="true"||t==="yes"||t==="on":!0}function RA(e){return MY.join(e,BY)}function wA(e){let t=RA(e.workerDir),r={mcpServers:{[be]:{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Kt]:e.brokerSocketPath}}}};return DY(t,`${JSON.stringify(r,null,2)}
|
|
150
|
+
`,{mode:384}),t}function nd(e){try{return NY(RA(e)),!0}catch{return!1}}var LY,BY,be,Ta,kA,UY,FY,WY,pt=p(()=>{"use strict";Lr();LY="KYNVER_WORKER_MCP_TOOLS",BY="mcp-config.json",be="kynver",Ta=["agent_os_context_envelope","agent_os_search_memory","agent_os_search_skills","agent_os_get_skill","agent_os_progress_note"],kA=Ta.map(e=>`mcp__${be}__${e}`),UY={"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"]};FY=["claude","cursor","codex","openai-compatible","gemini","gemini-api"],WY=["openai-compatible","gemini-api"]});import{closeSync as SA,openSync as _A}from"node:fs";import{spawn as $Y}from"node:child_process";function HY(e,t){let n=CA(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 CA(e,t,r){return["--model",t,...Oc(r),"-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:kA).join(",")}`]:[],"--",e.prompt]}var xA,ey=p(()=>{"use strict";Rr();ao();U();We();Qt();vr();pt();vr();xA={name:"claude",defaultModel:$e,preflightModel(e){return Kh(e,$e)},start(e){let t=Kh(e.model,$e);if(!t.ok)throw new Error(`claude provider model preflight failed: ${t.note}`);let r=t.model;HY(e,r);let n=Pc(r,{pinned:e.modelPinned===!0}),[o,s]=se("claude",CA(e,r,n)),i=_A(e.stdoutPath,"a"),a=_A(e.stderrPath,"a"),l=["ignore",i,a],[c,u]=ct(o,s,e.workerDir),d=$Y(c,u,Z({cwd:e.worktreePath,detached:Re(),stdio:l,env:St(process.env,{reviewWorker:e.reviewWorker})}));if(SA(i),SA(a),!d.pid)throw new Error("failed to spawn claude worker process (is the `claude` CLI on PATH?)");return d.unref(),{pid:d.pid,model:r}}}});var Us,od=p(()=>{"use strict";Us="gpt-5.6-sol"});import{closeSync as EA,openSync as AA}from"node:fs";import{spawn as jY}from"node:child_process";function VY(e,t){return St({...process.env,CI:"1",NO_COLOR:"1",HERMES_ACCEPT_HOOKS:process.env.HERMES_ACCEPT_HOOKS??"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function GY(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 ty,IA,PA=p(()=>{"use strict";Rr();ao();U();We();io();Qt();od();ty=process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||Us;IA={name:"hermes-codex",defaultModel:ty,preflightModel(e){return Ns(e,ty)},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,ty);if(!t.ok)throw new Error(`hermes-codex provider model preflight failed: ${t.note}`);let r=t.model,n=wt("hermes",["KYNVER_HERMES_BIN","HERMES_BIN"]),[o,s]=se(n,GY(r,e.prompt)),i=AA(e.stdoutPath,"a"),a=AA(e.stderrPath,"a"),l=["ignore",i,a],[c,u]=ct(o,s,e.workerDir),d=jY(c,u,Z({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:l,env:VY(e.reviewWorker,e.codexHome)}));if(EA(i),EA(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 YY(e=process.env){return e[JY]?.trim().toLowerCase()==="elevated"?"elevated":qY}function sd(e=process.platform,t=process.env){return e!=="win32"?[]:["-c",`windows.sandbox="${YY(t)}"`]}var JY,qY,ry=p(()=>{"use strict";JY="KYNVER_CODEX_WINDOWS_SANDBOX",qY="unelevated"});import{closeSync as OA,existsSync as zY,openSync as TA}from"node:fs";import{spawn as ny}from"node:child_process";function XY(){return process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||Us}function Ur(){return process.env.KYNVER_CODEX_BIN?.trim()||process.env.CODEX_BIN?.trim()||"codex"}function QY(e,t){return St({...process.env,CI:"1",NO_COLOR:"1",...t?{CODEX_HOME:t}:{}},{reviewWorker:e})}function ZY(e,t,r,n=process.platform,o=process.env){return["--ask-for-approval","never","exec",...sd(n,o),"--json","--sandbox",r==="read_only"?"read-only":"workspace-write","--model",e,t]}function ez(e,t,r,n){if(process.platform==="win32"){let[l,c]=se(e,t);return ny(l,c,r)}if(!zY("/usr/bin/script")){let[l,c]=ct(e,t,n);return ny(l,c,r)}let s=[e,...t].map(l=>`'${l.replace(/'/g,"'\\''")}'`).join(" "),[i,a]=ct("script",["-qfc",s,"/dev/null"],n);return ny(i,a,r)}var Br,NA,fo=p(()=>{"use strict";Rr();ao();U();We();zu();Qt();PA();ry();od();Br=XY();NA={name:"codex",defaultModel:Br,preflightModel(e){return Ns(e,Br)},start(e){if(Ts().path==="hermes_openai_codex"&&e.executionMode!=="read_only")return IA.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=TA(e.stdoutPath,"a"),s=TA(e.stderrPath,"a"),i=["ignore",o,s],a=Ur(),l=ZY(n,e.prompt,e.executionMode),c;try{c=ez(a,l,Z({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:i,env:QY(e.reviewWorker,e.codexHome)}),e.workerDir)}finally{OA(o),OA(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 id}from"node:fs";import mo from"node:path";import{fileURLToPath as tz}from"node:url";function rz(e,t){let r=mo.resolve(e);for(;;){let n=mo.join(r,t);if(id(n))return n;let o=mo.dirname(r);if(o===r)return null;r=o}}function nz(e){return rz(e,mo.join("node_modules",".bin","tsx"))??"npx"}function oy(e,t){if(e.endsWith(".ts")){let r=nz(mo.dirname(e));return{command:r,argsPrefix:r==="npx"?["tsx",e]:[e],cliPath:e}}return{command:t,argsPrefix:[e],cliPath:e}}function ad(e){if(e.explicitCliPath)return id(e.explicitCliPath)?oy(e.explicitCliPath,e.nodeExecutable):null;let t=tz(new URL(".",e.importMetaUrl)),r=mo.join(t,"cli.js");if(id(r))return oy(r,e.nodeExecutable);let n=mo.join(t,"cli.ts");return id(n)?oy(n,e.nodeExecutable):null}var sy=p(()=>{"use strict"});function sz(e){return`/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/worker`}async function Ma(e,t,r){let n=await e.fetchImpl(`${e.apiBaseUrl}${t}`,{method:r?.method??"GET",headers:{[oz]: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 La(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function ld(e,t,r){let n=sz(e);switch(t){case"agent_os_context_envelope":{let o=new URLSearchParams({task:e.taskId}),s=La(r.memoryQuery);s&&o.set("memoryQuery",s);let i=La(r.mode);return i&&o.set("mode",i),Ma(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)),Ma(e,`${n}/memory-search?${o.toString()}`)}case"agent_os_search_skills":{let o=new URLSearchParams,s=La(r.query);s&&o.set("q",s),typeof r.limit=="number"&&o.set("limit",String(r.limit));let i=o.toString();return Ma(e,`${n}/skills${i?`?${i}`:""}`)}case"agent_os_get_skill":return Ma(e,`${n}/skills/${encodeURIComponent(String(r.slug??""))}`);case"agent_os_progress_note":return Ma(e,`${n}/progress-note`,{method:"POST",body:{note:String(r.note??""),...r.kind==="blocked"?{kind:"blocked"}:{},...La(r.eventKey)?{eventKey:La(r.eventKey)}:{}}})}}function Fs(e){return Ta.includes(e)}var oz,Ba,cd=p(()=>{"use strict";pt();oz="X-Kynver-Job-Token",Ba={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 Ua(e){return Na(e).filter(Fs).map(t=>{let r=Ba[t];return{type:"function",function:{name:r.name,description:r.description,parameters:r.inputSchema}}})}var ud=p(()=>{"use strict";cd();pt()});import{closeSync as DA,openSync as MA}from"node:fs";import iz from"node:path";import{fileURLToPath as az}from"node:url";import{spawn as lz}from"node:child_process";function iy(e=process.env){return e.KYNVER_WORKER_MODEL?.trim()||void 0}function uz(e=process.env){let t=e.KYNVER_WORKER_BASE_URL?.trim();if(!t)throw new Fa(`the "openai-compatible" worker provider requires KYNVER_WORKER_BASE_URL on the daemon host \u2014 point it at any OpenAI-compatible chat-completions endpoint (e.g. http://localhost:11434/v1 for Ollama, http://localhost:8000/v1 for vLLM, or your gateway's /v1 URL). Set KYNVER_WORKER_API_KEY too when the endpoint requires auth.`);let r;try{r=new URL(t)}catch{throw new Fa(`KYNVER_WORKER_BASE_URL is not a valid URL: "${t}" \u2014 expected e.g. http://localhost:11434/v1`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Fa(`KYNVER_WORKER_BASE_URL must be http(s), got "${r.protocol}//" \u2014 e.g. http://localhost:11434/v1`);let n=Number(e.KYNVER_WORKER_TIMEOUT_MS??""),o=Number.isFinite(n)&&n>0?Math.floor(n):cz;return{baseUrl:t.replace(/\/+$/,""),...e.KYNVER_WORKER_API_KEY?.trim()?{apiKey:e.KYNVER_WORKER_API_KEY.trim()}:{},timeoutMs:o}}function dd(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:dz},{role:"user",content:r}],...n&&n.length?{tools:n,tool_choice:"auto"}:{}}}}function pz(){let e=az(new URL(".",import.meta.url)),t=import.meta.url.endsWith(".ts"),r=iz.join(e,t?"openai-compatible-runner.ts":"openai-compatible-runner.js"),n=ad({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 fz(e,t,r){let n=e.workerToolGrant,o=n?Ua(n.capabilities):void 0;return{provider:go,model:r,request:dd(t,r,e.prompt,o),timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}function pd(e,t,r){let n=pz(),o=MA(e.stdoutPath,"a"),s=MA(e.stderrPath,"a"),i=["pipe",o,s],[a,l]=ct(n.command,n.argsPrefix,e.workerDir),c=lz(a,l,Z({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:i,env:St(process.env,{reviewWorker:e.reviewWorker})}));if(DA(o),DA(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 go,cz,Fa,dz,LA,Wa=p(()=>{"use strict";Rr();ao();U();sy();Qt();ud();go="openai-compatible",cz=600*1e3;Fa=class extends Error{};dz="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.";LA={name:go,get defaultModel(){return iy()},preflightModel(e){return $h(e,iy())},start(e){let t=$h(e.model,iy());if(!t.ok)throw new Error(`openai-compatible provider model preflight failed: ${t.note}`);let r=t.model,n=uz(process.env),o=fz(e,n,r);return pd(e,o,r)}}});import mz from"node:path";function _t(e=process.env){return e.KYNVER_GEMINI_BIN?.trim()||e.GEMINI_BIN?.trim()||"agy"}function Ws(e){let t=mz.basename(e).toLowerCase().replace(/\.cmd$/i,"").replace(/\.exe$/i,"");return t==="agy"||t==="antigravity"?"antigravity":"gemini"}function BA(e){return e.requested&&/-(?:high|medium|low)$/i.test(e.requested)?e.requested:e.model}function UA(e){let t=e.trim().toLowerCase();return!t||gz.has(t)?[]:["--model",e.trim()]}function fd(e,t){return[...UA(t),"--output-format","stream-json",...e.executionMode==="read_only"?[]:["--dangerously-skip-permissions"],"--prompt",e.prompt]}function FA(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",be]:[],"--prompt",e.prompt]}var gz,ho=p(()=>{"use strict";pt();gz=new Set(["gemini-2.5-pro","gemini-2.5-flash","auto","pro","flash","flash-lite"])});import{closeSync as WA,openSync as KA}from"node:fs";import{spawn as hz}from"node:child_process";function qe(e=process.env){return e.KYNVER_GEMINI_DEFAULT_MODEL?.trim()||"gemini-2.5-pro"}function yz(e,t){return St({...process.env,CI:"1",NO_COLOR:"1",GEMINI_CLI_TRUST_WORKSPACE:"true",...t?{GEMINI_CLI_HOME:t}:{}},{reviewWorker:e})}var er,$A,Ka=p(()=>{"use strict";Rr();ao();U();We();ho();Qt();er="gemini";$A={name:er,get defaultModel(){return qe()},preflightModel(e){return Ds(e,qe())},start(e){let t=Ds(e.model,qe());if(!t.ok)throw new Error(`gemini provider model preflight failed: ${t.note}`);let r=_t(),n=Ws(r),o=n==="antigravity"?BA(t):t.model,s=n==="antigravity"?fd(e,o):FA(e,o),[i,a]=se(r,s),l=KA(e.stdoutPath,"a"),c=KA(e.stderrPath,"a"),u=["ignore",l,c],[d,f]=ct(i,a,e.workerDir),m=hz(d,f,Z({cwd:e.worktreePath,detached:Re(),shell:!1,stdio:u,env:yz(e.reviewWorker,n==="gemini"?e.geminiCliHome:void 0)}));if(WA(l),WA(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 bz(e=process.env){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()||void 0}function vz(e=process.env){let t=bz(e);if(!t)throw new $a('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()||HA,n;try{n=new URL(r)}catch{throw new $a(`KYNVER_GEMINI_BASE_URL is not a valid URL: "${r}" \u2014 expected e.g. ${HA}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new $a(`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):kz;return{baseUrl:r.replace(/\/+$/,""),apiKey:t,timeoutMs:s}}function Rz(e,t,r){let n=e.workerToolGrant,o=n?Ua(n.capabilities):void 0,s=dd(t,r,e.prompt,o);return{provider:tr,model:r,request:s,timeoutMs:t.timeoutMs,heartbeatPath:e.heartbeatPath,endpointOrigin:new URL(t.baseUrl).origin,...n&&o&&o.length?{workerTools:n}:{}}}var tr,HA,kz,$a,jA,ay=p(()=>{"use strict";Wa();ud();Qt();Ka();tr="gemini-api",HA="https://generativelanguage.googleapis.com/v1beta/openai",kz=600*1e3,$a=class extends Error{};jA={name:tr,get defaultModel(){return qe()},preflightModel(e){return Ds(e,qe())},start(e){let t=Ds(e.model,qe());if(!t.ok)throw new Error(`gemini-api provider model preflight failed: ${t.note}`);let r=t.model,n=vz(process.env),o=Rz(e,n,r);return pd(e,o,r)}}});function rt(e,t){let r=e[t];return typeof r=="string"?r.trim():""}function Sz(e){if(!e)return;let t=rt(e,"workerModelOverride")||rt(e,"modelOverride");return t||`${rt(e,"title")}
|
|
151
|
+
${rt(e,"description")}
|
|
152
|
+
${rt(e,"executorRef")}`.match(/\[(?:worker-)?model:\s*([^\]\n]+)\]/i)?.[1]?.trim()||void 0}function VA(e){return e.toLowerCase()}function JA(e,t=A(),r=process.env){return e==="explicit:cli"||e==="explicit:spawn"?!0:e==="default:global"?!!(t.defaultModel?.trim()||r.KYNVER_DEFAULT_MODEL?.trim()):!1}function cy(e=A()){let t=e.defaultModel?.trim();if(t)return t;let r=process.env.KYNVER_DEFAULT_MODEL?.trim();return r||wz}function md(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-")?er:"cursor"}function _z(e,t){let r=e.trim().toLowerCase(),n=t?.trim();return r==="cursor"?{model:Gu,provider:"cursor",rule:n&&n!=="cursor"?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="claude"||r==="anthropic"?{model:$e,provider:"claude",rule:n&&n!=="claude"?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini"||r==="google"?{model:qe(),provider:er,rule:n&&n!==er?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:r==="gemini-api"||r==="gemini_api"||r==="google-api"?{model:qe(),provider:tr,rule:n&&n!==tr?"explicit:model_provider_alias_overrode_provider":"explicit:model_provider_alias",requestedModel:e}:null}function GA(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 qA(e,t,r){return xz.has(e)?Zr:t.includes("review")||/^review[\s:]/.test(r)||r.includes("critique")?Zr:$e}function Cz(e){let t=VA(rt(e,"executorRef")),r=rt(e,"title").toLowerCase(),n=rt(e,"priority")||"normal",o=VA(rt(e,"roleLane"));if(t.includes("provider:claude")||t.startsWith("claude:")){let i=qA(o,t,r);return{provider:"claude",model:i,rule:i===Zr?"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=Rt(rt(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=Rt(rt(e,"executorRef"));return{provider:go,...i?.model?{model:i.model}:{},rule:"lane:openai_compatible"}}if(t.includes("provider:gemini-api")||t.startsWith("gemini-api:")){let i=Rt(rt(e,"executorRef"));return{provider:tr,...i?.model?{model:i.model}:{model:qe()},rule:"lane:gemini_api"}}if(t.includes("provider:gemini")||t.startsWith("gemini:")){let i=Rt(rt(e,"executorRef"));return{provider:er,...i?.model?{model:i.model}:{model:qe()},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 GA(t,r)||o==="deep_reviewer"?{provider:"cursor",rule:"lane:deep_review"}:{provider:"cursor",rule:"lane:review"};if(GA(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=cy();return{model:s,provider:md(s),rule:"default:global"}}function Ez(e){return e?Rt(rt(e,"executorRef")):null}function Az(e){switch(Xe(e)){case er:case tr:return qe();case"claude":return $e;case"codex":return Br;case"cursor":return Gu;default:return}}function zA(e,t,r){let n=Xe(t);return n===e.provider&&e.rule===r?e:{...e,provider:n,model:Az(n)??e.model,rule:r}}function Iz(e,t){let r=t?.trim();return!r||e.rule.startsWith("explicit:")&&e.rule!==ly?e:zA(e,r,ly)}function Pz(e,t){if(t.explicitProvider?.trim()||Lh(t.task))return e;let r=t.configuredProvider?.trim();if(!r)return e;let n=Xe(r);return n===Mr||n===e.provider?e:zA(e,n,YA)}function gd(e){let t,r=Ez(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=_z(l,e.explicitProvider);c?t=c:t={model:l,provider:e.explicitProvider?.trim()||md(l),rule:"explicit:cli",requestedModel:l}}else if(n)t={model:n,provider:o||md(n),rule:r?.rule??"executor_ref:model",requestedModel:n};else if(e.task&&Vu(e.task)){let l=Sz(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=qA(d,f,m),u=c===Zr?"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=Cz(e.task);t={...l,requestedModel:l.model}}else{let l=cy();t={model:l,provider:e.explicitProvider?.trim()||md(l),rule:"default:global",requestedModel:l}}t=Iz(t,e.explicitProvider),t=Pz(t,{explicitProvider:e.explicitProvider,task:e.task,configuredProvider:e.configuredProvider});let s=!!e.configuredProvider?.trim()&&Xe(e.configuredProvider)!==Mr&&t.rule==="config:worker_provider",i=WE({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===ly||i.rule===YA||Dr(i.provider)&&(e.explicitProviderIsOperatorOverride||Vu(e.task))||i.provider===go||i.provider===er||i.provider===tr||i.provider==="codex")return i;let a=hA({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 XA(e,t,r){return e||t||r||cy()||$e}var wz,Gu,xz,ly,YA,Ju=p(()=>{"use strict";$();ju();yA();ey();fo();Wa();Ka();ay();so();wz=$e,Gu="composer-2.5";xz=new Set(["report_reviewer","deep_reviewer","plan_reviewer"]);ly="explicit:cli_provider",YA="config:worker_provider"});function Oz(e){let t=e?.executorRef;return typeof t=="string"?t.trim():""}function QA(e){return e?.trim()||void 0}function ZA(e){let t=Oz(e.task),r=Rt(t),n=e.explicitProvider?.trim().toLowerCase(),o=QA(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=QA(e.routing.model),u={provider:l,model:c,rule:e.routing.rule};return s&&s!=="cursor"||t&&FE(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&&!Dr(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 eI=p(()=>{"use strict";ju();so()});function tI(e,t){let r=Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}function rI(){return{maxTaskAttempts:tI(process.env.KYNVER_MAX_TASK_ATTEMPTS,Math.floor(xs("harness.maxTaskAttempts",4))),dispatchCooldownMs:tI(process.env.KYNVER_DISPATCH_COOLDOWN_MS,Math.floor(xs("harness.dispatchCooldownMs",5e3)))}}var nI=p(()=>{"use strict";pn()});function dy(e){return e?.trim()?e.trim():null}function Tz(e){let t=dy(e);if(!t?.startsWith(uy))return null;let r=t.slice(uy.length),n=r.indexOf(oI);return n>=0?r.slice(0,n).trim()||null:r.trim()||null}function Ha(e,t){let r=e.trim(),n=t.trim();return`${uy}${r}${oI}${n}`}function Nz(e,t){let r=dy(t);return r?Tz(e)===r:!1}function hd(e){let t=dy(e.workerLeaseOwner);return t&&Nz(t,e.runId)?t:Ha(e.runId,e.runnerId)}var uy,oI,ja=p(()=>{"use strict";uy="kynver-harness:",oI="@runner:"});async function yd(e){let t=new Map,r=e.agentOsId?.trim();if(!r||e.taskIds.length===0)return t;let n=me(e.baseUrl);try{let o=await ye(e.secret,r,{baseUrl:n}),s=`${n}/api/agent-os/by-id/${encodeURIComponent(r)}/harness/monitor/task-leases`,i=await fe(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 py=p(()=>{"use strict";$();Je()});async function kd(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 yd({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)&&te(e.worker.runId,{...e.worker,...l?{leaseOwner:l}:{},leaseToken:a}),{leaseOwner:l,leaseToken:a}}var fy=p(()=>{"use strict";py();Q()});import Dz from"node:path";function sI(e,t){return K(Dz.join(J(e),"workers",F(t),"worker.json"),void 0)}async function iI(e,t){let r=oe(e),n=String(t.agentOsId||"");if(!n)return{renewed:[],failed:[],skipped:[]};let o=me(t.baseUrl?String(t.baseUrl):void 0),s=await ye(t.secret?String(t.secret):void 0,n,{baseUrl:o}),i=Number(t.leaseMs)>0?Math.floor(Number(t.leaseMs)):gy,a=Fe({runId:e}).runnerId,l=[],c=[],u=[];for(let d of Object.keys(r.workers||{})){let f=sI(e,d);if(!f?.taskId||!f.agentOsId){u.push(d);continue}if(!ne(f.pid)){u.push(d);continue}if(le(f).status==="done"){u.push(d);continue}let g=hd({runId:e,workerLeaseOwner:f.leaseOwner??null,runnerId:a}),h=await kd({worker:f,agentOsId:n,baseUrl:o,secret:s}),k=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/${encodeURIComponent(f.taskId)}/renew-lease`,v=await fe(k,s,{leaseOwner:h.leaseOwner??g,leaseDurationMs:i,...h.leaseToken?{leaseToken:h.leaseToken}:{}},{agentOsId:n,baseUrl:o});if(v.ok){l.push(d);continue}let y=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:y})}return{renewed:l,failed:c,skipped:u}}function aI(e,t){let r=oe(e);for(let n of Object.keys(r.workers||{})){let o=sI(e,n);if(!(!o||o.taskId!==t||!ne(o.pid)||le(o).status==="done"))return!0}return!1}var my=p(()=>{"use strict";$();Je();Q();Ie();U();bd();ja();Pr();fy()});import Mz from"node:path";function lI(e){return typeof e?.noRestartAt=="string"&&e.noRestartAt.trim().length>0}function cI(e,t,r,n){return lI(t)||(t.noRestartAt=new Date().toISOString(),t.noRestartSource=r,n&&(t.noRestartReason=n),t.steerRestartRequired=!1,te(e,t)),t}function vd(e,t={}){let r=t.isAlive??ne,n=t.kill??he,o=t.sleep??hc;return!e||!r(e)?null:(n(e,"SIGTERM"),o(1e3),r(e)?(n(e,"SIGKILL"),"SIGKILL"):"SIGTERM")}function hy(e,t,r,n,o={}){cI(e,t,r,n);let s=vd(t.pid,o),i=vd(t.completionSidecarPid,o);return{workerSignal:s,sidecarSignal:i}}function uI(e,t,r={}){let n=r.isAlive??ne,o=oe(e),s=[];for(let i of Object.keys(o.workers||{})){if(r.except&&i===r.except)continue;let a=K(Mz.join(J(o.id),"workers",F(i),"worker.json"),void 0);!a||a.taskId!==t||n(a.pid)||!a.completionSidecarPid||!n(a.completionSidecarPid)||(vd(a.completionSidecarPid,r),a.completionSidecarPid=void 0,a.watcherClearedForRelaunchAt=new Date().toISOString(),te(o.id,a),s.push(i))}return s}function Lz(e=process.env){let t=String(e.KYNVER_ALLOW_UNWATCHED_WORKER??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function dI(e,t,r,n={}){if(!Lz(n.env))throw hy(e,t,"watcher_attach_failed",r,n.deps),t.status="failed",te(e,t),new Error(`watcher_attach_failed: ${r}; worker stopped instead of running unwatched`)}var Ks=p(()=>{"use strict";Q();U()});function fI(e){let t=e.baseCommit?.trim()??"",r=[];t&&t!==pI&&r.push({ref:t,source:"baseCommit"});let n=e.base?.trim()??"";n&&n!==pI&&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 pI,mI=p(()=>{"use strict";pI="unknown"});function Rd(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function gI(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:Rd(e)}function Fz(e){let t=(e.title??"").trim().toLowerCase();if(t.startsWith("fix:")||t.startsWith("repair:"))return!0;let r=(e.executorRef??"").toLowerCase();return!!(r.startsWith(Uz)||r.includes("repair")||r.includes("unblock"))}function Wz(e){let t={repairEnforceOriginalPr:!1,targetPrUrl:null,targetPrBranch:null};if(!e)return t;let r=e.match(Bz);if(!r?.[1])return t;try{let n=JSON.parse(r[1]),o=Rd(String(n.targetPrUrl??n.target_pr_url??"")),s=Rd(String(n.targetPrBranch??n.target_pr_branch??""));return{repairEnforceOriginalPr:n.repairEnforceOriginalPr===!0||n.repair_enforce_original_pr===!0||!!o,targetPrUrl:o?gI(o):null,targetPrBranch:s}}catch{return t}}function hI(e){if(!Fz(e))return null;let t=Wz(e.description),r=e.prUrl?gI(e.prUrl):null,n=t.targetPrUrl??r;return n?{targetPrUrl:n,targetPrBranch:t.targetPrBranch??Rd(e.branch)}:null}function yI(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 Bz,Uz,yy=p(()=>{"use strict";Bz=/<!--\s*harness-contract:\s*(\{[\s\S]*?\})\s*-->/i,Uz="next-action-fix:"});var kI=p(()=>{"use strict"});function bI(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=[...ya(`worker.prompt.progress.${n}`).split(`
|
|
153
|
+
`),o],i=ya(`worker.prompt.merge_gate.${n}`).split(`
|
|
154
|
+
`),a=ya(`worker.prompt.plan_artifacts.${n}`).split(`
|
|
155
|
+
`);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.",...ya("worker.prompt.core_rules").split(`
|
|
156
|
+
`),"",...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?[...yI({targetPrUrl:e.repairTargetPrUrl,targetPrBranch:e.repairTargetBranch??null}),""]:[],"Task:",e.task].join(`
|
|
157
|
+
`)}var vI=p(()=>{"use strict";yy();pn();kI()});function wI(e){if(RI)return RI;let t=e?.trim();if(t){let o=wd[Xe(t)];if(!o)throw new Error(`unknown worker provider "${t}" \u2014 supported: ${Object.keys(wd).join(", ")}`);return o}let r=KE(A().workerProvider),n=wd[r];if(!n)throw new Error(`unknown worker provider "${r}" \u2014 supported: ${Object.keys(wd).join(", ")}`);return n}var wd,RI,SI=p(()=>{"use strict";$();so();ey();fo();Ls();Ka();ay();Wa();wd={claude:xA,codex:NA,cursor:aA,[er]:$A,[tr]:jA,[go]:LA},RI=null});function _I(e){return!!e.completionReportedAt?.trim()}function Sd(e,t,r){e.completionReportedAt=r.completionReportedAt,e.completionOutcome=r.completionOutcome,r.completionResponse!==void 0&&(e.completionResponse=r.completionResponse),te(t,e)}var ky=p(()=>{"use strict";Q()});function Kz(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function by(e){return!!(Kz(e.completionBlocker)||e.completionOutcome==="rejected")}function Va(e){return _I(e)&&!by(e)}var _d=p(()=>{"use strict";ky()});function vy(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ga(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function CI(e){let t=vy(e);if(!t)return{routeOutcome:null,taskAdvanced:!1,detail:null};let r=Ga(t.outcome),n=Ga(t.detail)??Ga(t.error),o=vy(t.task),s=vy(t.closedTask),i=o?Ga(o.status):null,a=s?Ga(s.status):null,c=r==="skipped_terminal_task"&&(i!==null&&xI.has(i)||a!==null&&xI.has(a))||r!==null&&$z.has(r)||i==="awaiting_review"||i==="done"||a==="done";return{routeOutcome:r,taskAdvanced:c,detail:n}}function EI(e){return e.taskAdvanced}var $z,xI,AI=p(()=>{"use strict";$z=new Set(["review_scheduled","review_already_scheduled","closed","dispatched","dispatch_already_done","steer_restart_required"]),xI=new Set(["done","failed","cancelled"])});var II=p(()=>{"use strict"});function Gz(e){if(!e)return null;let t=e.trim().toLowerCase();return t.length?t:null}function Ry(e){return/\b(deep[- ]?review|plan review|review .*plan|security review|red[- ]team|lb\d+|runtime verification)\b/.test(e)}function Jz(e,t){return e.startsWith("factory:")?e.includes("lb")||Ry(t):!1}function Cd(e){let t=(e.executorRef??"").toLowerCase(),r=(e.title??"").toLowerCase(),n=(e.description??"").toLowerCase(),o=`${r}
|
|
158
|
+
${n}`,s=Gz(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(Hz)||t===jz||t.startsWith("daemon-review:")||s&&xd.has(s)&&(t.includes("evidence")||t.includes("validate")||t.includes("review")||Jz(t,o)||Ry(o))||t.startsWith(Vz)&&e.parentTaskId&&s&&xd.has(s)||e.planId&&!e.parentTaskId&&s&&xd.has(s)&&Ry(o)||r.includes("expert pr review")||e.parentTaskId&&(r.startsWith("review:")||r.includes("review required")||r.includes("runtime review"))&&s&&xd.has(s))}var Hz,jz,Vz,xd,wy=p(()=>{"use strict";Hz="expert-lane-pr-review:",jz="plan-review-task",Vz="scheduledjob:",xd=new Set(["lorentz","dalton","rhea","sentinel"])});function OI(e){return!!(e&&Yz.test(e))}function Ye(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function TI(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:Ye(e.head)}function NI(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?Ye(r[0]):null}function zz(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 Xz(e,t){if(t.changedFiles.length>0)return!1;let r=Ye(e.personaSlug)?.toLowerCase();if(r&&qz.has(r))return!0;let n=Ye(e.routingRule)??"";return!!(n&&PI.test(n))}function Qz(e,t){if(e.changedFiles.length>0)return!0;let r=Ye(t?.baseRef);if(r&&t?.exec&&t.worktreePath){let n=zz(t.worktreePath,r,t.exec);if(n===0)return!1;if(n!==null&&n>0)return!0}return!!(Ye(e.headCommit)||TI(e.gitAncestry))}function DI(e){if(!e.dispatched)return{required:!1,reason:"not_dispatched"};if(Cd({title:e.taskTitle??void 0,personaSlug:e.personaSlug,parentTaskId:e.parentTaskId,executorRef:e.executorRef}))return{required:!1,reason:"expert_review_task"};let t=Ye(e.routingRule)??"";if(t&&PI.test(t))return{required:!1,reason:"review_lane"};let r=e.worker??{personaSlug:e.personaSlug,routingRule:e.routingRule};if(Xz(r,e.snapshot))return{required:!1,reason:"review_artifact"};if(Ye(e.patchPath)||Ye(e.artifactBundlePath))return{required:!1,reason:"patch_or_bundle"};if(Ye(e.repairTargetPrUrl))return{required:!1,reason:"repair_target_pr"};if(Ye(e.prUrl)??Ye(e.taskPrUrl)??Ye(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 Qz(e.snapshot,s)?{required:!0,snapshot:e.snapshot}:{required:!1,reason:"no_work_product"}}function MI(e,t){return{changedFiles:e.changedFiles,branch:e.branch,worktreePath:e.worktreePath,gitAncestry:e.gitAncestry,finalResult:e.finalResult,headCommit:Ye(t?.headCommit)??TI(e.gitAncestry),prUrl:Ye(t?.prUrl)??null}}var PI,qz,Yz,Sy=p(()=>{"use strict";wy();Wu();PI=/^(lane:)?(review|deep_review|planning|landing)(:|$)/i,qz=new Set(AE()),Yz=/no commits between/i});function BI(e){let t=e.trim();if(!t)return null;let r=t.match(/^git@github\.com:([^/]+\/[^/\s]+?)(?:\.git)?$/i);if(r)return LI(r[1]);let n=t.match(/^ssh:\/\/git@github\.com\/([^/]+\/[^/\s]+?)(?:\.git)?$/i);if(n)return LI(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 LI(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 UI=p(()=>{"use strict"});import{spawnSync as Zz}from"node:child_process";function e6(e,t,r){try{let n=Zz(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 t6(e){return e.split(`
|
|
159
|
+
`).map(t=>t.trim()).find(Boolean)??""}function WI(e,t){let r=t.git(e,["remote","get-url","origin"]);return r.status!==0?null:BI(r.stdout)}function yo(e,t){let r=t.git(e,["rev-parse","HEAD"]);return r.status!==0?null:r.stdout.trim()||null}function Ed(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 r6(e,t){let r=t?.trim();return!r||!/^[\w.-]{1,128}$/.test(r)||new RegExp(`^${FI}:`,"m").test(e)?e:`${e.trimEnd()}
|
|
160
160
|
|
|
161
|
-
${
|
|
162
|
-
`)}function
|
|
161
|
+
${FI}: ${r}`}function Ja(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",r6(n,e.taskId)]);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=yo(t,s)??void 0;return{ok:!0,committed:o,pushed:!0,headCommit:a}}function KI(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 $I(e){let t=Ed(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=n6(r.stdout)??Ed(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 n6(e){let r=t6(e).match(/https?:\/\/[^\s]+\/pull\/\d+/i);return r?r[0]:null}var Ad,FI,Id=p(()=>{"use strict";UI();_e();Ad={git:(e,t)=>ee(e,t),gh:(e,t)=>e6("gh",e,t)};FI="Kynver-Task"});function HI(e){return`t-${F(e)}-a`}function jI(e,t){let r=HI(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 qa(e){return e.trim().toLowerCase()}function VI(e,t){if(!e.length)return null;if(t){let r=qa(t),n=e.find(o=>qa(o.url)===r);if(n)return n}return[...e].sort((r,n)=>n.number-r.number)[0]??null}function GI(e,t){let r=qa(t);return e.filter(n=>qa(n.url)!==r).map(n=>n.url)}function JI(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 o6(e){let t=new Set,r=[];for(let n of e){let o=qa(n.url);t.has(o)||(t.add(o),r.push(n))}return r}function s6(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?[]:JI(o.stdout).filter(s=>jI(s,r))}function i6(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=HI(r);return JI(o.stdout).filter(i=>i.headRefName.toLowerCase().includes(s)||jI(i,r))}function _y(e,t,r,n){let o=r.trim();if(!o)return[];let s=s6(e,t,o,n),i=i6(e,t,o,n);return o6([...s,...i])}var Pd=p(()=>{"use strict";U()});function a6(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 xy(e){let t=GI(e.rows,e.canonicalPrUrl),r=[],n=[];for(let o of t){let s=a6(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 Cy=p(()=>{"use strict";Pd()});function qI(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 YI=p(()=>{"use strict"});function l6(e){return e.gh(process.cwd(),["--version"]).status===0}function c6(e,t){return`AgentOS harness: ${e} (${t})`}function u6(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(`
|
|
162
|
+
`)}function mn(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function d6(e){return mn(e.prUrlHint)??NI(e.status.finalResult)??mn(e.worker.taskPrUrl)??null}function p6(e){let{snapshot:t,canonical:r,workerName:n,exec:o}=e,s=!1,i=!1,a=t.headCommit??yo(t.worktreePath,o)??void 0;if(t.changedFiles.length>0){let l=Ja({worktreePath:t.worktreePath,branch:t.branch,commitMessage:`chore(harness): update PR handoff for ${n}`,taskId:e.taskId,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=KI({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=yo(t.worktreePath,o)??a}return{ok:!0,prUrl:r.url,headCommit:a,committed:s,pushed:i}}function Ey(e){if(e.snapshot.changedFiles.length===0)return{ok:!0,prUrl:e.prUrl,headCommit:e.snapshot.headCommit??yo(e.snapshot.worktreePath,e.exec)??void 0};let t=Ja({worktreePath:e.snapshot.worktreePath,branch:e.snapshot.branch,commitMessage:e.commitMessage,taskId:e.taskId,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 Ay(e,t=Ad){let r=d6(e),n=MI(e.status,{prUrl:r,headCommit:null}),o=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main";if(!DI({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?Ey({snapshot:n,prUrl:r,commitMessage:`chore(harness): update PR handoff for ${e.worker.name}`,taskId:mn(e.worker.taskId),exec:t}):{ok:!0};if(r)return Ey({snapshot:n,prUrl:r,commitMessage:`chore(harness): update PR handoff for ${e.worker.name}`,taskId:mn(e.worker.taskId),exec:t});if(!l6(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=WI(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,S=!1,w=n.headCommit??yo(n.worktreePath,t)??void 0;if(n.changedFiles.length>0){let _=Ja({worktreePath:n.worktreePath,branch:n.branch,commitMessage:`fix(harness): repair target PR ${a}`,taskId:mn(e.worker.taskId),hasDirtyFiles:!0,exec:t});if(!_.ok)return{ok:!1,reason:`PR-ready handoff blocked: ${_.detail??"git commit/push failed"}`,nextAction:"Commit and push to the target PR branch, then rerun `kynver worker complete`."};b=_.committed,S=_.pushed,w=_.headCommit??w}else{let _=t.git(n.worktreePath,["push","-u","origin",n.branch]);if(_.status!==0&&!/already up to date/i.test(_.stderr||_.stdout))return{ok:!1,reason:`PR-ready handoff blocked: ${_.stderr||_.stdout||"git push failed"}`,nextAction:"Push the target branch to origin, then rerun `kynver worker complete`."};S=_.status===0}return{ok:!0,prUrl:a,headCommit:w,committed:b,pushed:S}}let l=mn(e.worker.taskId),c=[];if(l){c=_y(n.worktreePath,i,l,t);let b=VI(c);if(b){let S=p6({snapshot:n,canonical:b,workerName:e.worker.name,taskId:l,exec:t});return S.ok&&S.prUrl&&xy({worktreePath:n.worktreePath,repo:i,rows:c,canonicalPrUrl:S.prUrl,exec:t}),S}}let u=Ed(n.worktreePath,i,n.branch,t);if(u)return Ey({snapshot:n,prUrl:u,commitMessage:`chore(harness): update PR handoff for ${e.worker.name}`,taskId:mn(e.worker.taskId),exec:t});let d=n.changedFiles.length>0,f=!1,m=!1,g=n.headCommit??void 0,h=Ja({worktreePath:n.worktreePath,branch:n.branch,commitMessage:`chore(harness): PR-ready handoff for ${e.worker.name}`,taskId:mn(e.worker.taskId),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??yo(n.worktreePath,t)??void 0;let k=g?qI(n.worktreePath,i,g,t):null;if(k)return{ok:!0,prUrl:k.prUrl,headCommit:g,committed:f,pushed:m,created:!1};let v=e.run.base?.trim()||"main",y=$I({worktreePath:n.worktreePath,repo:i,branch:n.branch,base:v.replace(/^origin\//,""),title:c6(e.worker.name,e.worker.runId),body:u6(e.worker.taskId,e.worker.name,e.worker.runId),exec:t});if(!y.ok||!y.prUrl){if(OI(y.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"}${y.detail?` (${y.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&&y.prUrl){let S=[...c.length>0?c:_y(n.worktreePath,i,l,t),{url:y.prUrl,number:Number.parseInt(y.prUrl.match(/\/pull\/(\d+)/)?.[1]??"",10)||0,headRefName:n.branch,createdAt:""}];xy({worktreePath:n.worktreePath,repo:i,rows:S,canonicalPrUrl:y.prUrl,exec:t})}return{ok:!0,prUrl:y.prUrl,headCommit:g??void 0,committed:f,pushed:m,created:y.created}}var zI=p(()=>{"use strict";Sy();Pd();Cy();Id();YI()});var XI=p(()=>{"use strict";II();Sy();Id();Pd();Cy();zI()});import f6 from"node:path";function Py(e){clearInterval(Iy.get(e)),Iy.delete(e)}function Oy(e,t){if(Py(e),!Ya.has(e))return;let r=setInterval(()=>{(K(f6.join(e,"worker.json"),null)?.completionReportedAt||!ne(t))&&$s(e)},1e3);r.unref(),Iy.set(e,r)}function Ty(e,t){Py(e);let r=Ya.get(e);r&&r.close(),Ya.set(e,t)}async function gn(e){Py(e);let t=Ya.get(e);return t?(Ya.delete(e),await t.close(),!0):!1}function $s(e){gn(e).catch(()=>{})}var Ya,Iy,Ny=p(()=>{"use strict";U();Ya=new Map,Iy=new Map});import{appendFileSync as m6,existsSync as ZI,mkdirSync as eP,readFileSync as g6,rmSync as QI,writeFileSync as h6}from"node:fs";import Fr from"node:path";function rP(e){return Fr.join(e,tP)}function y6(e){return de(e,["ls-files","--error-unmatch",tP.split(Fr.sep).join("/")],{allowFailure:!0}).trim().length>0}function k6(e){let t=de(e,["rev-parse","--git-common-dir"],{allowFailure:!0}).trim();if(!t)return;let r=Fr.isAbsolute(t)?t:Fr.join(e,t),n=Fr.join(r,"info","exclude"),o=".cursor/mcp.json";try{eP(Fr.dirname(n),{recursive:!0});let s=ZI(n)?g6(n,"utf8"):"";if(s.split(/\r?\n/).some(i=>i.trim()===o))return;m6(n,`${s.endsWith(`
|
|
163
163
|
`)||!s?"":`
|
|
164
164
|
`}${o}
|
|
165
|
-
`)}catch{}}function
|
|
166
|
-
`,{mode:384}),
|
|
167
|
-
`)}function
|
|
165
|
+
`)}catch{}}function nP(e){if(y6(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=rP(e.worktreePath);eP(Fr.dirname(t),{recursive:!0});let r={mcpServers:{[be]:{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Kt]:e.brokerSocketPath}}}};return h6(t,`${JSON.stringify(r,null,2)}
|
|
166
|
+
`,{mode:384}),k6(e.worktreePath),{ok:!0,configPath:t}}function Od(e){let t=rP(e);if(!ZI(t))return!1;try{QI(t,{force:!0});let r=Fr.dirname(t);return QI(r,{recursive:!1}),!0}catch{return!0}}var tP,Dy=p(()=>{"use strict";_e();Lr();pt();tP=Fr.join(".cursor","mcp.json")});import{copyFileSync as b6,existsSync as Td,mkdirSync as v6,readFileSync as R6,rmSync as w6,symlinkSync as S6,writeFileSync as _6}from"node:fs";import{spawnSync as x6}from"node:child_process";import{homedir as C6}from"node:os";import hn from"node:path";function oP(e){return hn.join(e,E6)}function A6(e=process.env){let t=e.CODEX_HOME?.trim();if(t)return hn.resolve(t);let r=C6();for(let n of[hn.join(r,".codex"),hn.join(r,".config","codex")])if(Td(n))return n;return null}function I6(e){return["","# Added per task by the Kynver harness. Carries a broker socket path, never a credential.",`[mcp_servers.${be}]`,'command = "npx"','args = ["-y", "-p", "@kynver-app/mcp-agent-os", "kynver-worker-mcp"]',"",`[mcp_servers.${be}.env]`,`${Kt} = ${JSON.stringify(e)}`,""].join(`
|
|
167
|
+
`)}function P6(e){return new RegExp(String.raw`^\s*\[\s*mcp_servers\s*\.\s*"?${be}"?\s*[\].]`,"m").test(e)}function sP(e){let t=A6(e.env??process.env),r=t?hn.join(t,"config.toml"):null,n=r&&Td(r)?R6(r,"utf8"):"";if(n&&P6(n))return{ok:!1,reason:"user_config_owns_server",detail:`the Codex config already declares an "${be}" MCP server \u2014 refusing to write a duplicate stanza`};let o=oP(e.workerDir);v6(o,{recursive:!0,mode:448});let s=!n||n.endsWith(`
|
|
168
168
|
`)?"":`
|
|
169
|
-
`;return
|
|
169
|
+
`;return _6(hn.join(o,"config.toml"),`${n}${s}${I6(e.brokerSocketPath)}`,{mode:384}),{ok:!0,codexHome:o,authMode:O6(t,o)}}function O6(e,t){let r=e?hn.join(e,"auth.json"):null;if(!r||!Td(r))return"none";let n=hn.join(t,"auth.json");try{return S6(r,n,"file"),"symlink"}catch{try{return b6(r,n),"copy"}catch{return"none"}}}function za(e){let t=oP(e);if(!Td(t))return!1;try{return w6(t,{recursive:!0,force:!0}),!0}catch{return!1}}function iP(e,t,r=1e4){try{let[n,o]=se(t,["--version"]),s=x6(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 E6,My=p(()=>{"use strict";We();Lr();pt();E6="codex-home"});import{appendFileSync as T6,existsSync as Ly,mkdirSync as lP,readFileSync as cP,rmSync as aP,writeFileSync as N6}from"node:fs";import Wr from"node:path";function dP(e){return Wr.join(e,uP)}function D6(e){return de(e,["ls-files","--error-unmatch",uP.split(Wr.sep).join("/")],{allowFailure:!0}).trim().length>0}function M6(e){if(!Ly(e))return{};try{let t=JSON.parse(cP(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 L6(e){let t=de(e,["rev-parse","--git-common-dir"],{allowFailure:!0}).trim();if(!t)return;let r=Wr.isAbsolute(t)?t:Wr.join(e,t),n=Wr.join(r,"info","exclude"),o=".agents/mcp_config.json";try{lP(Wr.dirname(n),{recursive:!0});let s=Ly(n)?cP(n,"utf8"):"";if(s.split(/\r?\n/).some(i=>i.trim()===o))return;T6(n,`${s.endsWith(`
|
|
170
170
|
`)||!s?"":`
|
|
171
171
|
`}${o}
|
|
172
|
-
`)}catch{}}function
|
|
173
|
-
`,{mode:384}),
|
|
174
|
-
`,{mode:384}),{ok:!0,geminiCliHome:o,authMode:V6(r,s)}}function V6(e,t){let r=["oauth_creds.json","google_accounts.json"],n="none";for(let o of r){let s=Wr.join(e,o);if(!Ny(s))continue;let i=Wr.join(t,o);try{M6(s,i,"file"),n==="none"&&(n="symlink")}catch{try{O6(s,i),n="copy"}catch{}}}return n}function Nd(e){let t=lP(e);if(!Ny(t))return!1;try{return D6(t,{recursive:!0,force:!0}),!0}catch{return!1}}var U6,Dy=p(()=>{"use strict";Mr();dt();U6="gemini-home"});import G6 from"node:path";function uP(e){return!!(typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim())}function q6(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 hn(e){let t=e.finalResult??null,r=typeof e.lastHeartbeatSummary=="string"?e.lastHeartbeatSummary:q6(t);return{finalResult:t??r??"completed",summary:r}}function Dd(e,t,r){if(uP(e)&&e.status==="done"&&e.completionSnapshot!=null)return;let n=new Date().toISOString(),o=hn(t),s=r?.source?.trim();e.completionReportedAt=n,e.completionSnapshot=o,e.status="done",s&&(e.completionAckSource=s),ne(e.runId,e),e.workerDir&&(Ks(e.workerDir),rd(e.workerDir),Ya(e.workerDir),Nd(e.workerDir)),e.worktreePath&&(Pd(e.worktreePath),Td(e.worktreePath))}function Y6(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 dP(e,t,r={}){let n=Y6(t);if(n.size===0)return[];let o=se(e),s=[];for(let i of Object.keys(o.workers||{})){let a=K(G6.join(q(o.id),"workers",U(i),"worker.json"),void 0);if(!a?.taskId||uP(a))continue;let l=n.get(a.taskId);if(!l||l==="running"||!J6.has(l))continue;let c=ce(a,{base:o.base,baseCommit:o.baseCommit}),u;if(l==="cancelled"){let d=dy(o.id,a,"board_task_cancelled","board task cancelled",r);u=!!(d.workerSignal||d.sidecarSignal)}Dd(a,c,{source:`board-task-${l}`}),s.push({worker:i,taskId:a.taskId,taskStatus:l,...u?{stopped:u}:{}})}return s}var J6,Md=p(()=>{"use strict";Z();Ie();B();dt();Ay();Iy();Py();Ty();Dy();Ws();J6=new Set(["awaiting_review","blocked","done","needs_input","waiting","scheduled","ready","cancelled","failed"])});function Ld(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 z6(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 X6(e){let t=zi(e);return t?{summary:t.reason,handoffState:"exit_failure",blocked:t.blocked}:null}function Q6(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 Bd(e){let{worker:t,status:r}=e;if(Ld(r.finalResult)){let u=De(t.heartbeatPath),d=kr(u),f=Ld(d)&&JSON.stringify(d)===JSON.stringify(r.finalResult)?"heartbeat_complete":"stdout_stream";return{finalResult:r.finalResult,source:f,snapshot:hn(r)}}if(r.alive)return null;let n=$n(t.stdoutPath);if(Ld(n.finalResult)){let u={...r,finalResult:n.finalResult};return{finalResult:n.finalResult,source:"stdout_stream",snapshot:hn(u)}}let o=De(t.heartbeatPath),s=kr(o);if(Ld(s)){let u={...r,finalResult:s,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:s,source:"heartbeat_complete",snapshot:hn(u)}}let i=X6(r.error??n.error);if(i){let u={...r,finalResult:i};return{finalResult:i,source:"exit_failure",snapshot:hn(u)}}let a=z6(o);if(a){let u={...r,finalResult:a,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:a,source:"heartbeat_summary",snapshot:hn(u)}}let l=Q6({status:r,heartbeat:o}),c={...r,finalResult:l,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:l,source:"exit_no_final_result",snapshot:hn(c)}}function Ud(e,t){return e.completionSnapshot?.finalResult!=null?!1:(e.completionSnapshot=t.snapshot,e.completionHandoffSource=t.source,!0)}var My=p(()=>{"use strict";Kn();Vm();Md();Yi()});function Fd(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 pP(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 Ly=p(()=>{"use strict"});function fP(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function mP(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function hP(e){let t=mP(e);if(!t)return[];let r=mP(t.worktreeHandoff),n=fP(r?.disposableArtifactsRemoved);return n.length?n:fP(t.disposableArtifactsRemoved)}function gP(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function yP(e,t){let r=Fd(e);if(r.length===0)return!0;if(t.length===0)return!1;let n=new Set(t.map(o=>gP(o)));return r.every(o=>{let s=gP(pP(o));return n.has(s)})}var kP=p(()=>{"use strict";Ly()});function Wd(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function bP(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function Z6(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 e4(e){let t=bP(e.disposableArtifactsRemoved),r=hP(e.finalResult);return[...new Set([...t,...r])]}function vP(e){let t=bP(e.changedFiles),r=Fd(t),n=e4(e),o=r.length===0||yP(t,n);return Wd(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`}:Wd(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`}:Wd(e.artifactBundlePath)||Wd(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}:Z6(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 RP=p(()=>{"use strict";kP();Ly()});function Kr(e=process.env){return Or(e).flags.dispatchReceipts}function By(e){return Kr(e)!=="off"}function Uy(e,t){return`dispatch:${e}:${t.taskId}:${t.leaseToken}`}function Xa(e,t,r){if(!By())return;let n=pe();if(n)try{n.recordOperationReceipt({idempotencyKey:Uy(e,t),operation:`dispatch-${e}`,resultJson:r===void 0?null:JSON.stringify(r)})}catch{pt.storeFailures+=1}}function SP(e){Xa("claim",e,{runId:e.runId,workerName:e.workerName,provider:e.provider})}function Kd(e){Xa("spawned",e)}function $s(e,t){Xa("released",e,{reasonClass:t})}function _P(e){Xa("completion-sent",e)}function Fy(e,t){Xa("completion-acked",e,{outcome:t})}function xP(e){if(!By())return!1;let t=pe();if(!t)return!1;try{let r=t.getOperationReceipt(Uy("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 pt.completionReplaysObserved+=1,!0}}catch{pt.storeFailures+=1}return!1}function Wy(e){let t=String(e??"").split(":")[0]?.trim()??"";return t.length>0?t.slice(0,64):"unknown"}function CP(e){if(Kr()!=="enforce")return!1;let t=pe();if(!t)return!1;try{let r=t.getOperationReceipt(Uy("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"?(pt.completionReplaysShortCircuited+=1,!0):!1}catch{return pt.storeFailures+=1,!1}}function EP(e,t){if(Kr()!=="enforce")return;let r=pe();if(r)try{r.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${e}:${t}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:t})})}catch{pt.storeFailures+=1}}function AP(e,t){if(Kr()!=="enforce")return[];let r=pe();if(!r)return[];let n=t?.nowMs??Date.now(),o=t?.windowMs??t4;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 pt.storeFailures+=1,[]}}function za(e){let t=e.split(":")[0]??"",r=Number(t);return Number.isInteger(r)&&r>=0?r:null}function IP(e){let t={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!By())return t;let r=pe();if(!r)return t;let n=e?.nowMs??Date.now(),o=e?.strandedAfterMs??r4;try{let s=r.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-wP).toISOString(),limit:o4}),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>=n4&&a.length+5<=s4&&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=za(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),w=za(S);return w===null||w>=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(Kr()==="enforce"){let c=r.listOperationReceipts({limit:100}).filter(u=>{let d=Date.parse(u.recordedAt);return Number.isFinite(d)&&n-d>=wP}).map(u=>u.idempotencyKey);if(c.length>0){let u=r.deleteOperationReceiptsByKeys(c);l+=u,pt.agedReceiptsPruned+=u}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:l}}catch{return pt.storeFailures+=1,t}}function PP(){return{"dispatchReceipts.storeFailures":pt.storeFailures,"dispatchReceipts.completionReplaysObserved":pt.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":pt.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":pt.agedReceiptsPruned}}var pt,t4,r4,wP,n4,o4,s4,Hs=p(()=>{"use strict";pn();Cs();pt={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};t4=600*1e3;r4=900*1e3,wP=10080*60*1e3,n4=1440*60*1e3,o4=500,s4=300});function OP(){$y=!1}function $r(e=process.env){return Or(e).flags.admission}function $d(e,t){return`${Ky}${e}:${t}`}function TP(e,t){if($r()==="off")return;let r=pe();if(r)try{r.tryReserveAdmission($d(e,t),Hy,js)}catch{yn.storeFailures+=1}}function Qa(e,t){if($r()==="off")return;let r=pe();if(r)try{r.releaseAdmission($d(e,t),Hy)}catch{yn.storeFailures+=1}}function NP(e){let t={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if($r()==="off")return t;let r=pe();if(!r)return t;try{let n=new Set(e.liveWorkers.map(f=>$d(f.runId,f.workerName))),o=r.listAdmissionReservations({keyPrefix:Ky,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=!$y;$y=!0,!l&&i>0&&(yn.missingForLive+=i);let c=0;for(let f of e.liveWorkers)r.tryReserveAdmission($d(f.runId,f.workerName),Hy,js),c+=1;let u=0;for(let f of o)n.has(f.key)||r.releaseAdmission(f.key,f.owner)&&(u+=1,yn.deadSlotsReleased+=1);return{liveReservations:r.listAdmissionReservations({keyPrefix:Ky,limit:500}).length,refreshed:c,deadReleased:u,missingForLive:i,orphaned:a,adoptionPass:l}}catch{return yn.storeFailures+=1,t}}function DP(){return{"admission.storeFailures":yn.storeFailures,"admission.missingForLive":yn.missingForLive,"admission.deadSlotsReleased":yn.deadSlotsReleased}}var js,Hy,Ky,yn,$y,yo=p(()=>{"use strict";pn();Cs();js=900*1e3,Hy="admission-shadow",Ky="worker-slot:",yn={storeFailures:0,missingForLive:0,deadSlotsReleased:0},$y=!1});function MP(e){return`${jy}${e}`}function jd(e,t){return`${e}:${t}`}function LP(e){if($r()!=="enforce")return{admitted:!0};let t=pe();if(!t)return{admitted:!0};let r=Math.max(0,Math.min(Hd,Math.floor(e.maxSlots)));if(e.diskActiveWorkers>=r)return kn.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=jd(e.runId,e.workerName);for(let o=0;o<r;o+=1)if(t.tryReserveAdmission(MP(o),n,js).acquired)return{admitted:!0,slot:o};return kn.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return kn.enforceStoreFailures+=1,{admitted:!0}}}function bn(e,t){if($r()==="off")return;let r=pe();if(r)try{let n=jd(e,t),o=r.listAdmissionReservations({keyPrefix:jy,limit:Hd});for(let s of o)s.owner===n&&r.releaseAdmission(s.key,n)}catch{kn.enforceStoreFailures+=1}}function BP(e){let t={refreshed:0,deadReleased:0,adopted:0};if($r()!=="enforce")return t;let r=pe();if(!r)return t;try{let n=new Set(e.liveWorkers.map(c=>jd(c.runId,c.workerName))),o=r.listAdmissionReservations({keyPrefix:jy,limit:Hd}),s=0,i=0,a=new Set;for(let c of o)n.has(c.owner)?(r.tryReserveAdmission(c.key,c.owner,js),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=jd(c.runId,c.workerName);if(!a.has(u)){for(let d=0;d<Hd;d+=1)if(r.tryReserveAdmission(MP(d),u,js).acquired){l+=1;break}}}return{refreshed:s,deadReleased:i,adopted:l}}catch{return kn.enforceStoreFailures+=1,t}}function UP(){return{"admission.enforceStoreFailures":kn.enforceStoreFailures,"admission.refusedSlotsExhausted":kn.admissionsRefusedSlots,"admission.refusedDiskBackstop":kn.admissionsRefusedDiskBackstop}}var jy,Hd,kn,Vs=p(()=>{"use strict";pn();yo();jy="worker-slot-n:",Hd=64;kn={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0}});import i4 from"node:path";function Vy(e){let t=e.trim();if(!a4.test(t))throw new Error(`invalid run id: ${e}`);return t}function c4(e){let t=e.trim();if(!l4.test(t))throw new Error(`invalid worker name: ${e}`);return t}function KP(e){return typeof e=="string"?e.trim():""}function Vd(e){let t=KP(e.run),r=KP(e.name);return(!t||FP.has(t))&&ht(`missing --run RUN_ID (${WP})`),(!r||FP.has(r))&&ht(`missing --name WORKER_NAME (${WP})`),{runId:Vy(t),workerName:c4(r)}}function $P(e){let t=i4.resolve(e);if(t.includes(".."))throw new Error("repo path must not contain .. segments");return t}var a4,l4,FP,WP,Gd=p(()=>{"use strict";B();a4=/^[a-z0-9][a-z0-9._-]{0,127}$/i,l4=/^[a-z0-9][a-z0-9._-]{0,63}$/i,FP=new Set(["undefined","null"]),WP="usage: kynver worker <action> --run RUN_ID --name WORKER_NAME"});import{existsSync as u4,mkdirSync as d4,readFileSync as p4,writeFileSync as f4}from"node:fs";import{homedir as m4}from"node:os";import HP from"node:path";function Jy(e){let t=e?.trim();return!!(t&&g4.test(t))}function b4(){let e=(process.env.KYNVER_PROVIDER_QUOTA_PREFLIGHT??"on").trim().toLowerCase();return e!=="off"&&e!=="0"&&e!=="false"&&e!=="no"}function Gy(){let e=Number.parseInt(process.env.KYNVER_PROVIDER_QUOTA_COOLDOWN_MINUTES??"",10);return Number.isFinite(e)?Math.min(k4,Math.max(y4,e)):h4}function jP(){let e=process.env.KYNVER_PROVIDER_QUOTA_STORE_PATH?.trim();return e||HP.join(m4(),".kynver","provider-quota-cooldowns.json")}function Za(e){return(e??"").trim().toLowerCase()}function qy(){let e=jP();if(!u4(e))return{};try{let t=JSON.parse(p4(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[Za(n)]={lastExhaustedAt:s,reason:typeof i=="string"?i.slice(0,500):""})}return r}catch{return{}}}function Yy(e){let t=jP();try{d4(HP.dirname(t),{recursive:!0}),f4(t,`${JSON.stringify(e,null,2)}
|
|
175
|
-
`,"utf8")}catch{}}function
|
|
176
|
-
`))throw new
|
|
177
|
-
`)}function
|
|
178
|
-
`),
|
|
172
|
+
`)}catch{}}function pP(e){if(D6(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=dP(e.worktreePath),r=M6(t);if(be in r)return{ok:!1,reason:"user_config_owns_server",detail:`the workspace MCP config already declares an "${be}" server \u2014 refusing to overwrite it`};lP(Wr.dirname(t),{recursive:!0});let n={mcpServers:{...r,[be]:{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Kt]:e.brokerSocketPath}}}};return N6(t,`${JSON.stringify(n,null,2)}
|
|
173
|
+
`,{mode:384}),L6(e.worktreePath),{ok:!0,configPath:t}}function Nd(e){let t=dP(e);if(!Ly(t))return!1;try{return aP(t,{force:!0}),aP(Wr.dirname(t),{recursive:!1}),!0}catch{return!0}}var uP,By=p(()=>{"use strict";_e();Lr();pt();uP=Wr.join(".agents","mcp_config.json")});import{copyFileSync as B6,existsSync as Uy,mkdirSync as U6,readFileSync as F6,rmSync as W6,symlinkSync as K6,writeFileSync as $6}from"node:fs";import{homedir as H6}from"node:os";import Kr from"node:path";function fP(e){return Kr.join(e,j6)}function V6(e){return e.HOME?.trim()||e.USERPROFILE?.trim()||H6()}function G6(e=process.env){let t=e.GEMINI_CLI_HOME?.trim();return t?Kr.join(Kr.resolve(t),".gemini"):Kr.join(V6(e),".gemini")}function J6(e){if(!Uy(e))return{};try{let t=JSON.parse(F6(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function q6(e){let t=e.mcpServers;return!t||typeof t!="object"||Array.isArray(t)?!1:be in t}function Y6(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function z6(e){return{command:"npx",args:["-y","-p","@kynver-app/mcp-agent-os","kynver-worker-mcp"],env:{[Kt]:e},trust:!0}}function mP(e){let t=e.env??process.env,r=G6(t),n=J6(Kr.join(r,"settings.json"));if(q6(n))return{ok:!1,reason:"user_config_owns_server",detail:`the Gemini CLI settings already declare an "${be}" MCP server \u2014 refusing to write a duplicate stanza`};let o=fP(e.workerDir),s=Kr.join(o,".gemini");U6(s,{recursive:!0,mode:448});let i=n.mcpServers&&typeof n.mcpServers=="object"&&!Array.isArray(n.mcpServers)?n.mcpServers:{},a={...n,mcp:{...Y6(n.mcp),autoAllowInHeadless:!0},mcpServers:{...i,[be]:z6(e.brokerSocketPath)}};return $6(Kr.join(s,"settings.json"),`${JSON.stringify(a,null,2)}
|
|
174
|
+
`,{mode:384}),{ok:!0,geminiCliHome:o,authMode:X6(r,s)}}function X6(e,t){let r=["oauth_creds.json","google_accounts.json"],n="none";for(let o of r){let s=Kr.join(e,o);if(!Uy(s))continue;let i=Kr.join(t,o);try{K6(s,i,"file"),n==="none"&&(n="symlink")}catch{try{B6(s,i),n="copy"}catch{}}}return n}function Dd(e){let t=fP(e);if(!Uy(t))return!1;try{return W6(t,{recursive:!0,force:!0}),!0}catch{return!1}}var j6,Fy=p(()=>{"use strict";Lr();pt();j6="gemini-home"});import Q6 from"node:path";function gP(e){return!!(typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim())}function e4(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 yn(e){let t=e.finalResult??null,r=typeof e.lastHeartbeatSummary=="string"?e.lastHeartbeatSummary:e4(t);return{finalResult:t??r??"completed",summary:r}}function Md(e,t,r){if(gP(e)&&e.status==="done"&&e.completionSnapshot!=null)return;let n=new Date().toISOString(),o=yn(t),s=r?.source?.trim();e.completionReportedAt=n,e.completionSnapshot=o,e.status="done",s&&(e.completionAckSource=s),te(e.runId,e),e.workerDir&&($s(e.workerDir),nd(e.workerDir),za(e.workerDir),Dd(e.workerDir)),e.worktreePath&&(Od(e.worktreePath),Nd(e.worktreePath))}function t4(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 hP(e,t,r={}){let n=t4(t);if(n.size===0)return[];let o=oe(e),s=[];for(let i of Object.keys(o.workers||{})){let a=K(Q6.join(J(o.id),"workers",F(i),"worker.json"),void 0);if(!a?.taskId||gP(a))continue;let l=n.get(a.taskId);if(!l||l==="running"||!Z6.has(l))continue;let c=le(a,{base:o.base,baseCommit:o.baseCommit}),u;if(l==="cancelled"){let d=hy(o.id,a,"board_task_cancelled","board task cancelled",r);u=!!(d.workerSignal||d.sidecarSignal)}Md(a,c,{source:`board-task-${l}`}),s.push({worker:i,taskId:a.taskId,taskStatus:l,...u?{stopped:u}:{}})}return s}var Z6,Ld=p(()=>{"use strict";Q();Ie();U();pt();Ny();Dy();My();By();Fy();Ks();Z6=new Set(["awaiting_review","blocked","done","needs_input","waiting","scheduled","ready","cancelled","failed"])});function Bd(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 r4(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 n4(e){let t=Xi(e);return t?{summary:t.reason,handoffState:"exit_failure",blocked:t.blocked}:null}function o4(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 Ud(e){let{worker:t,status:r}=e;if(Bd(r.finalResult)){let u=Me(t.heartbeatPath),d=br(u),f=Bd(d)&&JSON.stringify(d)===JSON.stringify(r.finalResult)?"heartbeat_complete":"stdout_stream";return{finalResult:r.finalResult,source:f,snapshot:yn(r)}}if(r.alive)return null;let n=Hn(t.stdoutPath);if(Bd(n.finalResult)){let u={...r,finalResult:n.finalResult};return{finalResult:n.finalResult,source:"stdout_stream",snapshot:yn(u)}}let o=Me(t.heartbeatPath),s=br(o);if(Bd(s)){let u={...r,finalResult:s,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:s,source:"heartbeat_complete",snapshot:yn(u)}}let i=n4(r.error??n.error);if(i){let u={...r,finalResult:i};return{finalResult:i,source:"exit_failure",snapshot:yn(u)}}let a=r4(o);if(a){let u={...r,finalResult:a,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:a,source:"heartbeat_summary",snapshot:yn(u)}}let l=o4({status:r,heartbeat:o}),c={...r,finalResult:l,lastHeartbeatPhase:o.lastHeartbeatPhase,lastHeartbeatSummary:o.lastHeartbeatSummary};return{finalResult:l,source:"exit_no_final_result",snapshot:yn(c)}}function Fd(e,t){return e.completionSnapshot?.finalResult!=null?!1:(e.completionSnapshot=t.snapshot,e.completionHandoffSource=t.source,!0)}var Wy=p(()=>{"use strict";$n();zm();Ld();zi()});function Wd(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 yP(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 Ky=p(()=>{"use strict"});function kP(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function bP(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function RP(e){let t=bP(e);if(!t)return[];let r=bP(t.worktreeHandoff),n=kP(r?.disposableArtifactsRemoved);return n.length?n:kP(t.disposableArtifactsRemoved)}function vP(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function wP(e,t){let r=Wd(e);if(r.length===0)return!0;if(t.length===0)return!1;let n=new Set(t.map(o=>vP(o)));return r.every(o=>{let s=vP(yP(o));return n.has(s)})}var SP=p(()=>{"use strict";Ky()});function Kd(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function _P(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function s4(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 i4(e){let t=_P(e.disposableArtifactsRemoved),r=RP(e.finalResult);return[...new Set([...t,...r])]}function xP(e){let t=_P(e.changedFiles),r=Wd(t),n=i4(e),o=r.length===0||wP(t,n);return Kd(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`}:Kd(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`}:Kd(e.artifactBundlePath)||Kd(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}:s4(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 CP=p(()=>{"use strict";SP();Ky()});function $r(e=process.env){return Tr(e).flags.dispatchReceipts}function $y(e){return $r(e)!=="off"}function Hy(e,t){return`dispatch:${e}:${t.taskId}:${t.leaseToken}`}function Qa(e,t,r){if(!$y())return;let n=pe();if(n)try{n.recordOperationReceipt({idempotencyKey:Hy(e,t),operation:`dispatch-${e}`,resultJson:r===void 0?null:JSON.stringify(r)})}catch{ft.storeFailures+=1}}function AP(e){Qa("claim",e,{runId:e.runId,workerName:e.workerName,provider:e.provider})}function $d(e){Qa("spawned",e)}function Hs(e,t){Qa("released",e,{reasonClass:t})}function IP(e){Qa("completion-sent",e)}function jy(e,t){Qa("completion-acked",e,{outcome:t})}function PP(e){if(!$y())return!1;let t=pe();if(!t)return!1;try{let r=t.getOperationReceipt(Hy("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 ft.completionReplaysObserved+=1,!0}}catch{ft.storeFailures+=1}return!1}function Vy(e){let t=String(e??"").split(":")[0]?.trim()??"";return t.length>0?t.slice(0,64):"unknown"}function OP(e){if($r()!=="enforce")return!1;let t=pe();if(!t)return!1;try{let r=t.getOperationReceipt(Hy("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"?(ft.completionReplaysShortCircuited+=1,!0):!1}catch{return ft.storeFailures+=1,!1}}function TP(e,t){if($r()!=="enforce")return;let r=pe();if(r)try{r.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${e}:${t}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:t})})}catch{ft.storeFailures+=1}}function NP(e,t){if($r()!=="enforce")return[];let r=pe();if(!r)return[];let n=t?.nowMs??Date.now(),o=t?.windowMs??a4;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 ft.storeFailures+=1,[]}}function Xa(e){let t=e.split(":")[0]??"",r=Number(t);return Number.isInteger(r)&&r>=0?r:null}function DP(e){let t={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!$y())return t;let r=pe();if(!r)return t;let n=e?.nowMs??Date.now(),o=e?.strandedAfterMs??l4;try{let s=r.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-EP).toISOString(),limit:u4}),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>=c4&&a.length+5<=d4&&a.push(c.idempotencyKey,`dispatch:spawned:${u}`,`dispatch:released:${u}`,`dispatch:completion-sent:${u}`,`dispatch:completion-acked:${u}`);continue}let g=u.split(":")[0]??"",h=Xa(u.slice(g.length+1));if((g?r.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${g}:`,limit:10}):[]).some(b=>{if(h===null)return!0;let S=b.idempotencyKey.slice(`dispatch:completion-acked:${g}:`.length),w=Xa(S);return w===null||w>=h}))continue;let y=!1;if(e?.hasLiveWorker&&c.resultJson)try{let b=JSON.parse(c.resultJson);b.runId&&b.workerName&&(y=e.hasLiveWorker({runId:b.runId,workerName:b.workerName}))}catch{y=!1}y||(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>=EP}).map(u=>u.idempotencyKey);if(c.length>0){let u=r.deleteOperationReceiptsByKeys(c);l+=u,ft.agedReceiptsPruned+=u}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:l}}catch{return ft.storeFailures+=1,t}}function MP(){return{"dispatchReceipts.storeFailures":ft.storeFailures,"dispatchReceipts.completionReplaysObserved":ft.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":ft.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":ft.agedReceiptsPruned}}var ft,a4,l4,EP,c4,u4,d4,js=p(()=>{"use strict";fn();Es();ft={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};a4=600*1e3;l4=900*1e3,EP=10080*60*1e3,c4=1440*60*1e3,u4=500,d4=300});function LP(){Jy=!1}function Hr(e=process.env){return Tr(e).flags.admission}function Hd(e,t){return`${Gy}${e}:${t}`}function BP(e,t){if(Hr()==="off")return;let r=pe();if(r)try{r.tryReserveAdmission(Hd(e,t),qy,Vs)}catch{kn.storeFailures+=1}}function Za(e,t){if(Hr()==="off")return;let r=pe();if(r)try{r.releaseAdmission(Hd(e,t),qy)}catch{kn.storeFailures+=1}}function UP(e){let t={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(Hr()==="off")return t;let r=pe();if(!r)return t;try{let n=new Set(e.liveWorkers.map(f=>Hd(f.runId,f.workerName))),o=r.listAdmissionReservations({keyPrefix:Gy,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=!Jy;Jy=!0,!l&&i>0&&(kn.missingForLive+=i);let c=0;for(let f of e.liveWorkers)r.tryReserveAdmission(Hd(f.runId,f.workerName),qy,Vs),c+=1;let u=0;for(let f of o)n.has(f.key)||r.releaseAdmission(f.key,f.owner)&&(u+=1,kn.deadSlotsReleased+=1);return{liveReservations:r.listAdmissionReservations({keyPrefix:Gy,limit:500}).length,refreshed:c,deadReleased:u,missingForLive:i,orphaned:a,adoptionPass:l}}catch{return kn.storeFailures+=1,t}}function FP(){return{"admission.storeFailures":kn.storeFailures,"admission.missingForLive":kn.missingForLive,"admission.deadSlotsReleased":kn.deadSlotsReleased}}var Vs,qy,Gy,kn,Jy,ko=p(()=>{"use strict";fn();Es();Vs=900*1e3,qy="admission-shadow",Gy="worker-slot:",kn={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Jy=!1});function WP(e){return`${Yy}${e}`}function Vd(e,t){return`${e}:${t}`}function KP(e){if(Hr()!=="enforce")return{admitted:!0};let t=pe();if(!t)return{admitted:!0};let r=Math.max(0,Math.min(jd,Math.floor(e.maxSlots)));if(e.diskActiveWorkers>=r)return bn.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=Vd(e.runId,e.workerName);for(let o=0;o<r;o+=1)if(t.tryReserveAdmission(WP(o),n,Vs).acquired)return{admitted:!0,slot:o};return bn.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return bn.enforceStoreFailures+=1,{admitted:!0}}}function vn(e,t){if(Hr()==="off")return;let r=pe();if(r)try{let n=Vd(e,t),o=r.listAdmissionReservations({keyPrefix:Yy,limit:jd});for(let s of o)s.owner===n&&r.releaseAdmission(s.key,n)}catch{bn.enforceStoreFailures+=1}}function $P(e){let t={refreshed:0,deadReleased:0,adopted:0};if(Hr()!=="enforce")return t;let r=pe();if(!r)return t;try{let n=new Set(e.liveWorkers.map(c=>Vd(c.runId,c.workerName))),o=r.listAdmissionReservations({keyPrefix:Yy,limit:jd}),s=0,i=0,a=new Set;for(let c of o)n.has(c.owner)?(r.tryReserveAdmission(c.key,c.owner,Vs),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=Vd(c.runId,c.workerName);if(!a.has(u)){for(let d=0;d<jd;d+=1)if(r.tryReserveAdmission(WP(d),u,Vs).acquired){l+=1;break}}}return{refreshed:s,deadReleased:i,adopted:l}}catch{return bn.enforceStoreFailures+=1,t}}function HP(){return{"admission.enforceStoreFailures":bn.enforceStoreFailures,"admission.refusedSlotsExhausted":bn.admissionsRefusedSlots,"admission.refusedDiskBackstop":bn.admissionsRefusedDiskBackstop}}var Yy,jd,bn,Gs=p(()=>{"use strict";fn();ko();Yy="worker-slot-n:",jd=64;bn={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0}});import p4 from"node:path";function zy(e){let t=e.trim();if(!f4.test(t))throw new Error(`invalid run id: ${e}`);return t}function g4(e){let t=e.trim();if(!m4.test(t))throw new Error(`invalid worker name: ${e}`);return t}function GP(e){return typeof e=="string"?e.trim():""}function Gd(e){let t=GP(e.run),r=GP(e.name);return(!t||jP.has(t))&&yt(`missing --run RUN_ID (${VP})`),(!r||jP.has(r))&&yt(`missing --name WORKER_NAME (${VP})`),{runId:zy(t),workerName:g4(r)}}function JP(e){let t=p4.resolve(e);if(t.includes(".."))throw new Error("repo path must not contain .. segments");return t}var f4,m4,jP,VP,Jd=p(()=>{"use strict";U();f4=/^[a-z0-9][a-z0-9._-]{0,127}$/i,m4=/^[a-z0-9][a-z0-9._-]{0,63}$/i,jP=new Set(["undefined","null"]),VP="usage: kynver worker <action> --run RUN_ID --name WORKER_NAME"});import{existsSync as h4,mkdirSync as y4,readFileSync as k4,writeFileSync as b4}from"node:fs";import{homedir as v4}from"node:os";import qP from"node:path";function Qy(e){let t=e?.trim();return!!(t&&R4.test(t))}function x4(){let e=(process.env.KYNVER_PROVIDER_QUOTA_PREFLIGHT??"on").trim().toLowerCase();return e!=="off"&&e!=="0"&&e!=="false"&&e!=="no"}function Xy(){let e=Number.parseInt(process.env.KYNVER_PROVIDER_QUOTA_COOLDOWN_MINUTES??"",10);return Number.isFinite(e)?Math.min(_4,Math.max(S4,e)):w4}function YP(){let e=process.env.KYNVER_PROVIDER_QUOTA_STORE_PATH?.trim();return e||qP.join(v4(),".kynver","provider-quota-cooldowns.json")}function el(e){return(e??"").trim().toLowerCase()}function Zy(){let e=YP();if(!h4(e))return{};try{let t=JSON.parse(k4(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[el(n)]={lastExhaustedAt:s,reason:typeof i=="string"?i.slice(0,500):""})}return r}catch{return{}}}function ek(e){let t=YP();try{y4(qP.dirname(t),{recursive:!0}),b4(t,`${JSON.stringify(e,null,2)}
|
|
175
|
+
`,"utf8")}catch{}}function C4(e,t,r=Date.now()){let n=el(e);if(!n)return;let o=Zy();o[n]={lastExhaustedAt:new Date(r).toISOString(),reason:t.trim().slice(0,500)},ek(o),bC(n,Xy()*6e4)}function E4(e){let t=el(e);if(!t)return!1;vC(t);let r=Zy();return t in r?(delete r[t],ek(r),!0):!1}function zP(e,t=Date.now()){if(!x4())return{ok:!0};let r=el(e);if(!r)return{ok:!0};let n=Zy(),o=n[r],s=!!(o&&Number.isFinite(Date.parse(o.lastExhaustedAt))&&Date.parse(o.lastExhaustedAt)+Xy()*6e4>t),i=RC(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+Xy()*6e4;if(!Number.isFinite(a)||l<=t)return delete n[r],ek(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 A4(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 XP(e){let t=el(e.provider);if(!t)return"none";let r=A4(e.finalResult)??(typeof e.error=="string"&&e.error.trim()?e.error.trim():null);return r?Qy(r)?(C4(t,r,e.nowMs??Date.now()),"recorded"):E4(t)?"cleared":"none":"none"}var R4,w4,S4,_4,qd=p(()=>{"use strict";va();R4=/\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,w4=30,S4=5,_4=240});function QP(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 ZP=p(()=>{"use strict"});function zd(e){return typeof e=="string"&&I4.test(e)&&!P4.has(e)&&!e.startsWith("KYNVER_")}var I4,eO,Yd,xt,P4,Js=p(()=>{"use strict";I4=/^[A-Z][A-Z0-9_]{1,63}$/,eO=/^sec_[0-9a-f]{20}$/,Yd=/^sr_[0-9a-f]{24}$/,xt={maxSecrets:100,maxValueBytes:16384,maxPurposeChars:200,minValueChars:4,minRedactChars:6},P4=new Set(["PATH","HOME","SHELL","USER","LOGNAME","NODE_OPTIONS","LD_PRELOAD","LD_LIBRARY_PATH","DYLD_INSERT_LIBRARIES","DYLD_LIBRARY_PATH","PWD","TMPDIR"])});import{createCipheriv as ZSe,createDecipheriv as O4,createECDH as T4,createHash as N4,hkdfSync as D4,randomBytes as e_e}from"node:crypto";function M4(e){for(let t of[e.agentOsId,e.requestId,e.name])if(!t||t.includes(`
|
|
176
|
+
`))throw new mt("invalid envelope context");return["kynver-secret/v1",e.agentOsId,e.requestId,e.name].join(`
|
|
177
|
+
`)}function rO(e){return N4("sha256").update(e).digest("hex").slice(0,16).toUpperCase().match(/.{4}/g).join("-")}function L4(e,t,r){return Buffer.from(D4("sha256",e,t,Buffer.from(r,"utf8"),32))}function Xd(e,t){if(typeof e!="string"||e.length>64*1024)throw new mt;let r=Buffer.from(e,"base64");if(t!==void 0&&r.length!==t)throw new mt;return r}function Qd(e){if(!e||typeof e!="object")return null;let t=e;if(t.v!==1||t.alg!==tO)return null;for(let r of["epk","salt","iv","ct","kid"])if(typeof t[r]!="string"||t[r].length>64*1024)return null;return{v:1,alg:tO,epk:t.epk,salt:t.salt,iv:t.iv,ct:t.ct,kid:t.kid}}function Zd(e,t,r){let n=M4(r);try{let o=T4("prime256v1");o.setPrivateKey(e);let s=o.computeSecret(Xd(t.epk,65)),i=L4(s,Xd(t.salt,16),n),a=Xd(t.iv,12),l=Xd(t.ct);if(l.length<17)throw new mt;let c=O4("aes-256-gcm",i,a);c.setAAD(Buffer.from(n,"utf8")),c.setAuthTag(l.subarray(l.length-16));let u=Buffer.concat([c.update(l.subarray(0,l.length-16)),c.final()]);if(u.length===0||u.length>xt.maxValueBytes)throw new mt("The secret is empty or too long.");return u.toString("utf8")}catch(o){throw o instanceof mt?o:new mt}}var tO,mt,ep=p(()=>{"use strict";Js();tO="ECDH-P256+HKDF-SHA256+A256GCM",mt=class extends Error{constructor(t="The secret could not be opened on this computer."){super(t),this.name="SecretEnvelopeError"}}});import{createECDH as iO,randomBytes as B4}from"node:crypto";import{chmodSync as aO,existsSync as nO,mkdirSync as U4,readFileSync as F4,readdirSync as W4,renameSync as K4,writeFileSync as $4}from"node:fs";import{homedir as H4}from"node:os";import lO from"node:path";function Ct(){return lO.join(H4(),".kynver","secrets")}function tl(e){U4(e,{recursive:!0,mode:448});try{aO(e,448)}catch{}}function rk(e,t){let r=`${e}.${process.pid}.tmp`;$4(r,t,{mode:384});try{aO(r,384)}catch{}K4(r,e)}function sO(e){if(!e)return null;try{let t=JSON.parse(e);if(t.v===1&&typeof t.ecdh=="string"&&typeof t.vault=="string")return{v:1,ecdh:t.ecdh,vault:t.vault}}catch{}return null}function tp(e,t){let r=Buffer.from(e.ecdh,"base64"),n=Buffer.from(e.vault,"base64");if(r.length!==32||n.length!==32)throw new Error("secret store keys are corrupt");let o=iO("prime256v1");o.setPrivateKey(r);let s=o.getPublicKey();return{ecdhPrivateKey:r,publicKeyRaw:s,fingerprint:rO(s),vaultKey:n,keyStore:t}}function rp(e={}){let t=e.root??Ct(),r=e.keychain??sn(),n=r.available?sO(r.read(oO)):null;if(n)return tp(n,"keychain");let o=j4(t),s=nO(o)?sO(F4(o,"utf8")):null;if(s)return tp(s,"file");if(nO(t)&&W4(t).some(d=>d.endsWith(".vault.json")))throw new tk;let i=iO("prime256v1");i.generateKeys();let a=Buffer.alloc(32),l=i.getPrivateKey();l.copy(a,32-l.length);let c={v:1,ecdh:a.toString("base64"),vault:B4(32).toString("base64")},u=JSON.stringify(c);return r.write(oO,u)?tp(c,"keychain"):(tl(t),rk(o,`${u}
|
|
178
|
+
`),tp(c,"file"))}var oO,j4,tk,rl=p(()=>{"use strict";yg();ep();oO="secret-store-keys";j4=e=>lO.join(e,"keys.json"),tk=class extends Error{constructor(){super("Saved secrets exist on this computer but their key can't be read (is the OS keyring locked?). Unlock it and try again."),this.name="SecretKeysUnavailableError"}}});function V4(e){let t=new Set([e]),r=Buffer.from(e,"utf8").toString("base64");t.add(r),t.add(r.replace(/=+$/,"")),t.add(r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""));let n=encodeURIComponent(e);n!==e&&t.add(n);let o=e.trim();return o&&o!==e&&t.add(o),[...t].filter(s=>s.length>=xt.minRedactChars)}function G4(e){return e.length>=xt.minValueChars&&e.length<xt.minRedactChars}function J4(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cO(e){let t=[];for(let o of e){let s=`[redacted ${o.name}]`;G4(o.value)&&t.push({needle:o.value,label:s,token:!0});for(let i of V4(o.value))t.push({needle:i,label:s,token:!1})}t.sort((o,s)=>s.needle.length-o.needle.length||Number(o.token)-Number(s.token));let r=new Set,n=t.filter(o=>{let s=`${o.token?"t":"s"}:${o.needle}`;return r.has(s)?!1:(r.add(s),!0)});return{empty:n.length===0,maxLength:n.reduce((o,s)=>Math.max(o,s.needle.length),0),partialSuffixLength(o){let s=0;for(let i of n){let a=i.needle[0];for(let l=Math.min(i.needle.length-1,o.length);l>s;l--)if(o[o.length-l]===a&&o.endsWith(i.needle.slice(0,l))){s=l;break}}return s},redact(o){if(!o||n.length===0)return o;let s=o;for(let i of n)if(i.token){let a=new RegExp(`(^|[^A-Za-z0-9_])${J4(i.needle)}(?=$|[^A-Za-z0-9_])`,"g");s=s.replace(a,`$1${i.label}`)}else s.includes(i.needle)&&(s=s.split(i.needle).join(i.label));return s}}}function uO(e,t){let r="";return{write(n){if(e.empty)return void t(n);let o=e.redact(r+n),s=e.partialSuffixLength(o),i=o.slice(0,o.length-s);r=o.slice(o.length-s),i&&t(i)},flush(){r&&t(e.redact(r)),r=""}}}var nk=p(()=>{"use strict";Js()});import{createHash as q4,randomBytes as Y4}from"node:crypto";import{existsSync as z4,readFileSync as X4,rmSync as Q4}from"node:fs";import Z4 from"node:path";function nl(e){return`${q4("sha256").update(`kynver-secret:${e}`).digest("hex").slice(0,32)}.vault.json`}var Pe,np,qs,Ys,op=p(()=>{"use strict";Kg();rl();Js();Pe=class extends Error{constructor(r,n){super(r);this.code=n;this.name="SecretStoreError"}code};np=(e,t,r)=>{for(let n of[e,t,r])if(n.includes(`
|
|
179
179
|
`))throw new Pe("invalid field","invalid");return["kynver-secret/v1/value",e,t,r].join(`
|
|
180
|
-
`)},
|
|
181
|
-
`)}list(){return this.read().secrets.map(Js)}find(t){let r=this.read().secrets.find(n=>t.handle?n.handle===t.handle:n.name===t.name);return r?Js(r):null}put(t){if(!Yd(t.name))throw new Pe("That secret name isn't allowed.","invalid");let r=Buffer.byteLength(t.value,"utf8");if(r===0)throw new Pe("The secret is empty.","invalid");if(t.value.trim().length<_t.minValueChars)throw new Pe(`The secret is too short \u2014 use at least ${_t.minValueChars} characters.`,"invalid");if(r>_t.maxValueBytes)throw new Pe("The secret is too long.","invalid");let n=(t.purpose??"").replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,_t.maxPurposeChars),o=this.read(),s=this.now().toISOString(),i=o.secrets.find(c=>c.name===t.name);if(i)return i.value=an(this.opts.vaultKey,Buffer.from(t.value,"utf8"),rp(this.opts.agentOsId,i.handle,i.name)),i.updatedAt=s,n&&(i.purpose=n),this.write(o),{summary:Js(i),replaced:!0};if(o.secrets.length>=_t.maxSecrets)throw new Pe("This computer already holds the most secrets allowed.","full");let a=`sec_${H4(10).toString("hex")}`,l={handle:a,name:t.name,purpose:n,createdAt:s,updatedAt:s,lastUsedAt:null,useCount:0,value:an(this.opts.vaultKey,Buffer.from(t.value,"utf8"),rp(this.opts.agentOsId,a,t.name))};return o.secrets.push(l),this.write(o),{summary:Js(l),replaced:!1}}reveal(t){let r=this.read().secrets.find(n=>t.handle?n.handle===t.handle:n.name===t.name);if(!r)throw new Pe("No saved secret by that name.","not_found");try{let n=eo(this.opts.vaultKey,r.value,rp(this.opts.agentOsId,r.handle,r.name)).toString("utf8");return{summary:Js(r),value:n}}catch{throw new Pe(`The saved value for ${r.name} can't be read on this computer. Save it again.`,"unreadable")}}revealAllForRedaction(){let t=[];for(let r of this.read().secrets)try{t.push({name:r.name,value:eo(this.opts.vaultKey,r.value,rp(this.opts.agentOsId,r.handle,r.name)).toString("utf8")})}catch{}return t}touch(t){if(t.length===0)return;let r=this.read(),n=this.now().toISOString();for(let o of r.secrets)t.includes(o.handle)&&(o.lastUsedAt=n,o.useCount+=1);this.write(r)}remove(t){let r=this.read(),n=r.secrets.findIndex(s=>t.handle?s.handle===t.handle:s.name===t.name);if(n<0)throw new Pe("No saved secret by that name.","not_found");let[o]=r.secrets.splice(n,1);return r.secrets.length===0?G4(this.file,{force:!0}):this.write(r),Js(o)}}});import{statSync as q4}from"node:fs";import Y4 from"node:path";function X4(e,t){return`${t}\0${e}`}function Q4(e){try{let t=q4(e);return t.isFile()?`${t.mtimeMs}:${t.size}`:null}catch{return null}}function tr(e,t=xt()){if(!e)return null;let r=Y4.join(t,rl(e)),n=Q4(r),o=X4(e,t);if(!n)return Ys.delete(o),null;let s=Ys.get(o);if(s&&s.stamp===n)return s.redactor;try{let i=tp({root:t}),a=oO(new qs({agentOsId:e,vaultKey:i.vaultKey,root:t}).revealAllForRedaction());return Ys.set(o,{stamp:n,redactor:a}),a}catch{return null}}function Zy(e){if(!e){Ys.clear();return}let t=`\0${e}`;for(let r of Ys.keys())r.endsWith(t)&&Ys.delete(r)}function op(e,t,r){if(typeof e=="string")return t.redact(e);if(r>z4||e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>op(o,t,r+1));let n={};for(let[o,s]of Object.entries(e))n[o]=op(s,t,r+1);return n}function iO(e,t,r=xt()){let n=tr(e,r);return!n||n.empty||!t?t:n.redact(t)}function aO(e,t,r=xt()){let n=tr(e,r);return!n||n.empty?t:op(t,n,0)}function lO(e,t,r=xt()){let n=tr(e,r);if(!n||n.empty||t.length===0)return t;let o;try{o=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return t}if(o.includes("\0"))return t;let s=n.redact(o);return s===o?t:Buffer.from(s,"utf8")}function sp(e,t,r=tr(e)){return!r||r.empty?t:t.map(n=>op(n,r,0))}var z4,Ys,Hr=p(()=>{"use strict";tl();Qy();np();z4=64,Ys=new Map});import ap from"node:path";async function cO(e,t,r){let n=await fetch(e,{method:"POST",headers:Bt(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 Z4(e){if(e&&typeof e=="object"){let t=e.error;if(typeof t=="string"&&t.trim())return t.trim()}}function uO(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function nl(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function eX(e){return e.completionBlocker?`blocked:${e.completionBlocker}`:e.completionOutcome?e.completionOutcome:e.completionReportedAt?"completion_acknowledged":e.finished?"worker_finished":"in_progress"}function tX(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 pO(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function rX(e){return e.prUrl?"pr_handoff":e.headCommit?"commit_handoff":e.changedFiles.length>0?"dirty_worktree":"none"}function zs(e,t){(e.completionBlocker??void 0)!==(t??void 0)&&(t?e.completionBlocker=t:delete e.completionBlocker,ne(e.runId,e))}function nX(e){e.completionBlocker&&(delete e.completionBlocker,ne(e.runId,e))}function ip(e){return e?{base:e.base,baseCommit:e.baseCommit}:{}}function oX(e,t){return{...e,...t.prUrl?{prUrl:t.prUrl}:{},...t.headCommit?{headCommit:t.headCommit}:{}}}async function Xs(e){let{runId:t,workerName:r}=Vd(e),n=Qn(t,r),o=se(n.runId),s=ce(n,ip(o)),i=(e.agentOsId?String(e.agentOsId):n.agentOsId)||"",a=(e.taskId?String(e.taskId):n.taskId)||null;if(!$e(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&&ja(n))return{ok:!0,skipped:!0,reason:"completion-already-acknowledged",httpStatus:200};if(!l&&my(n)&&nX(n),!s.finalResult&&s.alive===!1){let R=Bd({worker:n,status:s});R&&Ud(n,R)&&(ne(n.runId,n),n=Qn(t,r),s=ce(n,ip(o)))}if(!(e.skipPrHandoff===!0||e.skipPrHandoff==="true")&&!n.steerRestartRequired&&n.dispatched&&a){let R=Sy({worker:n,run:o,status:s});if(!R.ok)return zs(n,R.reason),{ok:!1,reason:R.reason,nextAction:R.nextAction,completionBlocked:!0};(R.prUrl||R.headCommit)&&(s=ce(n,ip(o)),s=oX(s,R))}let u=s.gitAncestry.headIsAncestorOfBase===!1&&s.gitAncestry.head?s.gitAncestry.head:s.headCommit;if(n.dispatched&&!n.steerRestartRequired){let R=vP({changedFiles:s.changedFiles,finalResult:s.finalResult,prUrl:s.prUrl,headCommit:u,disposableArtifactsRemoved:n.disposableArtifactsRemoved});if(!R.allowed){let O=R.detail??`worktree completion blocked (${R.state})`;return zs(n,O),{ok:!1,reason:O,nextAction:"Clean the worktree (commit, open a PR, or `kynver worker discard-disposable --path <file>`), then rerun `kynver worker complete`.",completionBlocked:!0}}}try{GP({provider:n.provider??s.provider??null,finalResult:s.finalResult})}catch{}let d=me(e.baseUrl?String(e.baseUrl):void 0),f=e.secret?String(e.secret):void 0,m=await ye(f,i,{baseUrl:d});a&&(await yd({worker:n,agentOsId:i,baseUrl:d,secret:m}),n=Qn(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=JP({usage:s.usage,provider:n.provider??s.provider??null,model:typeof n.model=="string"?n.model:s.model??null}),b=aO(i,{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(xP(k),CP(k)){let R={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:{replayShortCircuited:!0}};return wd(n,n.runId,R),Dd(n,s,{source:"harness-completion"}),zs(n,void 0),Qa(n.runId,n.name),bn(n.runId,n.name),{ok:!0,httpStatus:200,response:{ok:!0,replayShortCircuited:!0},reason:"completion_replay_short_circuited",...s.prUrl?{prHandoff:{prUrl:s.prUrl}}:{}}}_P(k)}let v=await cO(g,m,b);if((v.status===401||v.status===403)&&!f){let R=await N_(i,{baseUrl:d});R&&R!==m&&(m=R,v=await cO(g,m,b))}if(v.ok){let R=RI(v.parsed);if(!wI(R)){let N=`completion acknowledged but board not advanced: ${R.detail??(R.routeOutcome?`harness completion returned ${R.routeOutcome}`:"harness completion did not advance the linked task")}`;zs(n,N);let L={completionReportedAt:new Date().toISOString(),completionOutcome:"rejected",completionResponse:v.parsed};return wd(n,n.runId,L),k&&Fy(k,"rejected"),{ok:!1,httpStatus:v.status,response:v.parsed,reason:N,completionBlocked:!0}}zs(n,void 0);let O=R.routeOutcome??"acknowledged",j={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:v.parsed};wd(n,n.runId,j),Dd(n,s,{source:"harness-completion"}),k&&Fy(k,"acknowledged"),Qa(n.runId,n.name),bn(n.runId,n.name);let P=s.prUrl;return{ok:!0,httpStatus:v.status,response:v.parsed,reason:O,...P?{prHandoff:{prUrl:P}}:{}}}let S=v.status===401||v.status===403,w=Z4(v.parsed)??(S?"runner token unauthorized":"non-2xx response"),_=S?`completion replay rejected (${v.status}): ${w}`:`completion replay failed (${v.status}): ${w}`;return zs(n,_),{ok:!1,httpStatus:v.status,response:v.parsed,completionBlocked:!0}}async function fO(e){try{let{runId:t,workerName:r}=Vd(e),n=Qn(t,r),o=se(n.runId),s=ce(n,ip(o)),i=(e.agentOsId?String(e.agentOsId):n.agentOsId)||"",a=(e.taskId?String(e.taskId):n.taskId)||null;if(!$e(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 Xs(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 mO(e){let{run:t,workerName:r,worker:n}=e,o=ce(n,{base:t.base,baseCommit:t.baseCommit}),s=o.gitAncestry.headIsAncestorOfBase===!1&&o.gitAncestry.head?o.gitAncestry.head:void 0,i=es({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=pO(l)?void 0:l,u=c?"blocked":o.status,d=c?"blocked":o.attention.state,f=uO(n.completionResponse),m=uO(f?.task),g=nl(f?.outcome),h=nl(f?.status),y=Array.isArray(f?.warnings)?f.warnings.filter(_=>typeof _=="string"&&_.trim().length>0):[],b=nl(m?.prUrl)??nl(f?.prUrl),k=nl(n.completionReportedAt),v=eX({finished:$e(o),completionBlocker:c,completionOutcome:g,completionReportedAt:k}),S=tX({completionBlocker:c,completionOutcome:g,completionReportedAt:k,finished:$e(o)}),w=rX({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 _=n.instructionPolicyEvidence;if(!_||typeof _!="object")return null;let R=_.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:w,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 sX(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&&!pO(r)?!1:typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim()||e.completionOutcome==="acknowledged"?!0:t==="done"}function iX(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 ol(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 dO(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 aX(e){let t=e.filter(dO),r=e.filter(n=>{if(dO(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 gO(e,t,r){let n={runId:e.id,name:e.name,status:Fc(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:ol(t,"status"),attentionCounts:ol(t,"attention"),lifecycleCounts:ol(t,"lifecycleStage")},n.controller=aX(t)),n}function lX(e){return e.status==="done"&&e.attention==="done"}function ek(e){let t=se(e),n=Object.keys(t.workers||{}).map(s=>{let i=K(ap.join(q(t.id),"workers",U(s),"worker.json"),void 0);return i?mO({run:t,workerName:s,worker:i}):{worker:s,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=gO(t,n,!1);return we(ap.join(q(t.id),"last-board.json"),o),o}function tk(e){let t=se(e),n=Object.keys(t.workers||{}).map(i=>{let a=K(ap.join(q(t.id),"workers",U(i),"worker.json"),void 0);return a?sX(a)?iX(i,a):mO({run:t,workerName:i,worker:a}):{worker:i,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=n.filter(i=>!lX(i)),s=gO(t,o,!0);return s.status=Fc(t.status,n),s.summary={...s.summary??{},totalWorkerCount:n.length,shownWorkerCount:o.length,omittedTerminalDoneWorkerCount:n.length-o.length,allStatusCounts:ol(n,"status"),allAttentionCounts:ol(n,"attention")},we(ap.join(q(t.id),"last-board-compact.json"),s),s}async function hO(e,t){let r=String(e.run||""),n=String(e.agentOsId||"");if(!r||!n)return null;let o=ek(r),s=me(e.baseUrl?String(e.baseUrl):void 0),i=await ye(e.secret?String(e.secret):void 0,n,{baseUrl:s}),a=`${s}/api/agent-os/by-id/${encodeURIComponent(n)}/harness/snapshot`,l=await fe(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 Qs=p(()=>{"use strict";$();Ws();xs();SI();Ge();Z();Dc();GI();Ie();My();Yi();RP();fy();Sd();Hs();yo();Vs();Md();B();Gd();ly();Jd();qP();Hr()});var yO=p(()=>{"use strict";Ge();Z();Ws();B()});import{spawn as cX}from"node:child_process";import{existsSync as uX,openSync as dX,closeSync as kO}from"node:fs";import pX from"node:path";function bO(e){let t=e.nodeExecutable??process.execPath,r=id({importMetaUrl:import.meta.url,explicitCliPath:e.cliPath,nodeExecutable:t});if(!r)return;let n=r.cliPath;if(!uX(n))return;let o=pX.join(e.workerDir,"auto-complete.log"),s;try{s=dX(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=cX(r.command,a,te({detached:Re(),stdio:i,env:process.env}));return s!==void 0&&kO(s),l.unref(),{pid:l.pid,logPath:o,cliPath:n}}catch{if(s!==void 0)try{kO(s)}catch{}return}}var uxe,vO=p(()=>{"use strict";B();Sd();Z();Ie();Qs();B();Gd();ey();$();yO();uxe=360*60*1e3});var RO=p(()=>{"use strict"});function wO(e,t,r){de(e,["fetch","origin",r,"--prune"],{allowFailure:!0});let n=`origin/${r}`,o=re(e,["worktree","add","-B",r,t,n]);if(o.status===0)return;let s=re(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 SO=p(()=>{"use strict";_e()});import{createHash as fX}from"node:crypto";import{chmodSync as mX,mkdirSync as gX}from"node:fs";import _O from"node:os";import hX from"node:path";function xO(e,t){return fX("sha256").update(e).digest("hex").slice(0,t)}function rk(e){let t=e.platform??process.platform,r=xO(e.agentOsId,12),n=xO(e.workerKey,16);if(t==="win32")return{socketPath:`${kX}kynver-worker-${r}-${n}`,socketDir:null,isNamedPipe:!0,relocated:!1};let o=hX.posix,s=e.homeDir??_O.homedir(),i=o.join(s,".kynver","brokers",r),a=o.join(i,`${n}.sock`);if(Buffer.byteLength(a,"utf8")<=yX)return{socketPath:a,socketDir:i,isNamedPipe:!1,relocated:!1};let l=o.join(e.tmpDir??_O.tmpdir(),`kynver-brokers-${r}`);return{socketPath:o.join(l,`${n}.sock`),socketDir:l,isNamedPipe:!1,relocated:!0}}function nk(e){e.socketDir&&(gX(e.socketDir,{recursive:!0,mode:448}),mX(e.socketDir,448))}var yX,kX,ok=p(()=>{"use strict";yX=100,kX="\\\\.\\pipe\\"});import bX from"node:net";import{chmodSync as vX,unlinkSync as RX}from"node:fs";var sl,IO=p(()=>{"use strict";Mr();ld();ok();dt();sl=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=Ta(t.capabilities),this.server=bX.createServer(r=>{this.handleConnection(r)}),this.server.on("error",()=>{})}static async start(t){let r=new e(t);if(nk(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{vX(t.address.socketPath,384)}catch{}return r}get identitySummary(){return this.opts.identity.summary}get toolDescriptors(){return this.grantedTools.filter(Us).map(t=>La[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{RX(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(`
|
|
180
|
+
`)},qs=e=>({handle:e.handle,name:e.name,purpose:e.purpose,createdAt:e.createdAt,updatedAt:e.updatedAt,lastUsedAt:e.lastUsedAt,useCount:e.useCount}),Ys=class{constructor(t){this.opts=t;if(!t.agentOsId.trim())throw new Pe("workspace is required","invalid");this.root=t.root??Ct(),this.file=Z4.join(this.root,nl(t.agentOsId)),this.now=t.now??(()=>new Date)}opts;file;root;now;read(){if(!z4(this.file))return{v:1,agentOsId:this.opts.agentOsId,secrets:[]};let t;try{t=JSON.parse(X4(this.file,"utf8"))}catch{throw new Pe("The saved-secrets file is damaged.","corrupt")}if(t.v!==1||!Array.isArray(t.secrets))throw new Pe("The saved-secrets file is damaged.","corrupt");if(t.agentOsId!==this.opts.agentOsId)throw new Pe("This saved-secrets file belongs to another workspace.","corrupt");return{v:1,agentOsId:t.agentOsId,secrets:t.secrets}}write(t){tl(this.root),rk(this.file,`${JSON.stringify(t)}
|
|
181
|
+
`)}list(){return this.read().secrets.map(qs)}find(t){let r=this.read().secrets.find(n=>t.handle?n.handle===t.handle:n.name===t.name);return r?qs(r):null}put(t){if(!zd(t.name))throw new Pe("That secret name isn't allowed.","invalid");let r=Buffer.byteLength(t.value,"utf8");if(r===0)throw new Pe("The secret is empty.","invalid");if(t.value.trim().length<xt.minValueChars)throw new Pe(`The secret is too short \u2014 use at least ${xt.minValueChars} characters.`,"invalid");if(r>xt.maxValueBytes)throw new Pe("The secret is too long.","invalid");let n=(t.purpose??"").replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,xt.maxPurposeChars),o=this.read(),s=this.now().toISOString(),i=o.secrets.find(c=>c.name===t.name);if(i)return i.value=ln(this.opts.vaultKey,Buffer.from(t.value,"utf8"),np(this.opts.agentOsId,i.handle,i.name)),i.updatedAt=s,n&&(i.purpose=n),this.write(o),{summary:qs(i),replaced:!0};if(o.secrets.length>=xt.maxSecrets)throw new Pe("This computer already holds the most secrets allowed.","full");let a=`sec_${Y4(10).toString("hex")}`,l={handle:a,name:t.name,purpose:n,createdAt:s,updatedAt:s,lastUsedAt:null,useCount:0,value:ln(this.opts.vaultKey,Buffer.from(t.value,"utf8"),np(this.opts.agentOsId,a,t.name))};return o.secrets.push(l),this.write(o),{summary:qs(l),replaced:!1}}reveal(t){let r=this.read().secrets.find(n=>t.handle?n.handle===t.handle:n.name===t.name);if(!r)throw new Pe("No saved secret by that name.","not_found");try{let n=to(this.opts.vaultKey,r.value,np(this.opts.agentOsId,r.handle,r.name)).toString("utf8");return{summary:qs(r),value:n}}catch{throw new Pe(`The saved value for ${r.name} can't be read on this computer. Save it again.`,"unreadable")}}revealAllForRedaction(){let t=[];for(let r of this.read().secrets)try{t.push({name:r.name,value:to(this.opts.vaultKey,r.value,np(this.opts.agentOsId,r.handle,r.name)).toString("utf8")})}catch{}return t}touch(t){if(t.length===0)return;let r=this.read(),n=this.now().toISOString();for(let o of r.secrets)t.includes(o.handle)&&(o.lastUsedAt=n,o.useCount+=1);this.write(r)}remove(t){let r=this.read(),n=r.secrets.findIndex(s=>t.handle?s.handle===t.handle:s.name===t.name);if(n<0)throw new Pe("No saved secret by that name.","not_found");let[o]=r.secrets.splice(n,1);return r.secrets.length===0?Q4(this.file,{force:!0}):this.write(r),qs(o)}}});import{statSync as eX}from"node:fs";import tX from"node:path";function nX(e,t){return`${t}\0${e}`}function oX(e){try{let t=eX(e);return t.isFile()?`${t.mtimeMs}:${t.size}`:null}catch{return null}}function rr(e,t=Ct()){if(!e)return null;let r=tX.join(t,nl(e)),n=oX(r),o=nX(e,t);if(!n)return zs.delete(o),null;let s=zs.get(o);if(s&&s.stamp===n)return s.redactor;try{let i=rp({root:t}),a=cO(new Ys({agentOsId:e,vaultKey:i.vaultKey,root:t}).revealAllForRedaction());return zs.set(o,{stamp:n,redactor:a}),a}catch{return null}}function ok(e){if(!e){zs.clear();return}let t=`\0${e}`;for(let r of zs.keys())r.endsWith(t)&&zs.delete(r)}function sp(e,t,r){if(typeof e=="string")return t.redact(e);if(r>rX||e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>sp(o,t,r+1));let n={};for(let[o,s]of Object.entries(e))n[o]=sp(s,t,r+1);return n}function dO(e,t,r=Ct()){let n=rr(e,r);return!n||n.empty||!t?t:n.redact(t)}function pO(e,t,r=Ct()){let n=rr(e,r);return!n||n.empty?t:sp(t,n,0)}function fO(e,t,r=Ct()){let n=rr(e,r);if(!n||n.empty||t.length===0)return t;let o;try{o=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return t}if(o.includes("\0"))return t;let s=n.redact(o);return s===o?t:Buffer.from(s,"utf8")}function ip(e,t,r=rr(e)){return!r||r.empty?t:t.map(n=>sp(n,r,0))}var rX,zs,jr=p(()=>{"use strict";rl();nk();op();rX=64,zs=new Map});import lp from"node:path";async function mO(e,t,r){let n=await fetch(e,{method:"POST",headers:Ut(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 sX(e){if(e&&typeof e=="object"){let t=e.error;if(typeof t=="string"&&t.trim())return t.trim()}}function gO(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ol(e){if(typeof e!="string")return null;let t=e.trim();return t.length?t:null}function iX(e){return e.completionBlocker?`blocked:${e.completionBlocker}`:e.completionOutcome?e.completionOutcome:e.completionReportedAt?"completion_acknowledged":e.finished?"worker_finished":"in_progress"}function aX(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 yO(e){let t=e?.trim();return t?/completion acknowledged but board not advanced/i.test(t)&&/task already terminal/i.test(t):!1}function lX(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,te(e.runId,e))}function cX(e){e.completionBlocker&&(delete e.completionBlocker,te(e.runId,e))}function ap(e){return e?{base:e.base,baseCommit:e.baseCommit}:{}}function uX(e,t){return{...e,...t.prUrl?{prUrl:t.prUrl}:{},...t.headCommit?{headCommit:t.headCommit}:{}}}async function Qs(e){let{runId:t,workerName:r}=Gd(e),n=Zn(t,r),o=oe(n.runId),s=le(n,ap(o)),i=(e.agentOsId?String(e.agentOsId):n.agentOsId)||"",a=(e.taskId?String(e.taskId):n.taskId)||null;if(!He(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&&Va(n))return{ok:!0,skipped:!0,reason:"completion-already-acknowledged",httpStatus:200};if(!l&&by(n)&&cX(n),!s.finalResult&&s.alive===!1){let R=Ud({worker:n,status:s});R&&Fd(n,R)&&(te(n.runId,n),n=Zn(t,r),s=le(n,ap(o)))}if(!(e.skipPrHandoff===!0||e.skipPrHandoff==="true")&&!n.steerRestartRequired&&n.dispatched&&a){let R=Ay({worker:n,run:o,status:s});if(!R.ok)return Xs(n,R.reason),{ok:!1,reason:R.reason,nextAction:R.nextAction,completionBlocked:!0};(R.prUrl||R.headCommit)&&(s=le(n,ap(o)),s=uX(s,R))}let u=s.gitAncestry.headIsAncestorOfBase===!1&&s.gitAncestry.head?s.gitAncestry.head:s.headCommit;if(n.dispatched&&!n.steerRestartRequired){let R=xP({changedFiles:s.changedFiles,finalResult:s.finalResult,prUrl:s.prUrl,headCommit:u,disposableArtifactsRemoved:n.disposableArtifactsRemoved});if(!R.allowed){let T=R.detail??`worktree completion blocked (${R.state})`;return Xs(n,T),{ok:!1,reason:T,nextAction:"Clean the worktree (commit, open a PR, or `kynver worker discard-disposable --path <file>`), then rerun `kynver worker complete`.",completionBlocked:!0}}}try{XP({provider:n.provider??s.provider??null,finalResult:s.finalResult})}catch{}let d=me(e.baseUrl?String(e.baseUrl):void 0),f=e.secret?String(e.secret):void 0,m=await ye(f,i,{baseUrl:d});a&&(await kd({worker:n,agentOsId:i,baseUrl:d,secret:m}),n=Zn(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 k=QP({usage:s.usage,provider:n.provider??s.provider??null,model:typeof n.model=="string"?n.model:s.model??null}),v=pO(i,{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(),...k?{workerUsage:k}:{},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}}),y=a&&n.leaseToken?{taskId:a,leaseToken:n.leaseToken}:null;if(y){if(PP(y),OP(y)){let R={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:{replayShortCircuited:!0}};return Sd(n,n.runId,R),Md(n,s,{source:"harness-completion"}),Xs(n,void 0),Za(n.runId,n.name),vn(n.runId,n.name),{ok:!0,httpStatus:200,response:{ok:!0,replayShortCircuited:!0},reason:"completion_replay_short_circuited",...s.prUrl?{prHandoff:{prUrl:s.prUrl}}:{}}}IP(y)}let b=await mO(g,m,v);if((b.status===401||b.status===403)&&!f){let R=await U_(i,{baseUrl:d});R&&R!==m&&(m=R,b=await mO(g,m,v))}if(b.ok){let R=CI(b.parsed);if(!EI(R)){let M=`completion acknowledged but board not advanced: ${R.detail??(R.routeOutcome?`harness completion returned ${R.routeOutcome}`:"harness completion did not advance the linked task")}`;Xs(n,M);let B={completionReportedAt:new Date().toISOString(),completionOutcome:"rejected",completionResponse:b.parsed};return Sd(n,n.runId,B),y&&jy(y,"rejected"),{ok:!1,httpStatus:b.status,response:b.parsed,reason:M,completionBlocked:!0}}Xs(n,void 0);let T=R.routeOutcome??"acknowledged",W={completionReportedAt:new Date().toISOString(),completionOutcome:"acknowledged",completionResponse:b.parsed};Sd(n,n.runId,W),Md(n,s,{source:"harness-completion"}),y&&jy(y,"acknowledged"),Za(n.runId,n.name),vn(n.runId,n.name);let O=s.prUrl;return{ok:!0,httpStatus:b.status,response:b.parsed,reason:T,...O?{prHandoff:{prUrl:O}}:{}}}let S=b.status===401||b.status===403,w=sX(b.parsed)??(S?"runner token unauthorized":"non-2xx response"),_=S?`completion replay rejected (${b.status}): ${w}`:`completion replay failed (${b.status}): ${w}`;return Xs(n,_),{ok:!1,httpStatus:b.status,response:b.parsed,completionBlocked:!0}}async function kO(e){try{let{runId:t,workerName:r}=Gd(e),n=Zn(t,r),o=oe(n.runId),s=le(n,ap(o)),i=(e.agentOsId?String(e.agentOsId):n.agentOsId)||"",a=(e.taskId?String(e.taskId):n.taskId)||null;if(!He(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 Qs(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 bO(e){let{run:t,workerName:r,worker:n}=e,o=le(n,{base:t.base,baseCommit:t.baseCommit}),s=o.gitAncestry.headIsAncestorOfBase===!1&&o.gitAncestry.head?o.gitAncestry.head:void 0,i=ts({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=yO(l)?void 0:l,u=c?"blocked":o.status,d=c?"blocked":o.attention.state,f=gO(n.completionResponse),m=gO(f?.task),g=ol(f?.outcome),h=ol(f?.status),k=Array.isArray(f?.warnings)?f.warnings.filter(_=>typeof _=="string"&&_.trim().length>0):[],v=ol(m?.prUrl)??ol(f?.prUrl),y=ol(n.completionReportedAt),b=iX({finished:He(o),completionBlocker:c,completionOutcome:g,completionReportedAt:y}),S=aX({completionBlocker:c,completionOutcome:g,completionReportedAt:y,finished:He(o)}),w=lX({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 _=n.instructionPolicyEvidence;if(!_||typeof _!="object")return null;let R=_.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:v,handoffState:w,gitAncestry:o.gitAncestry,finalResult:o.finalResult,lifecycleStage:b,completionReportedAt:y,completionOutcome:n.completionOutcome??null,completionRouteStatus:h,completionRouteOutcome:g,completionWarnings:k,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 dX(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&&!yO(r)?!1:typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim()||e.completionOutcome==="acknowledged"?!0:t==="done"}function pX(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 sl(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 hO(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 fX(e){let t=e.filter(hO),r=e.filter(n=>{if(hO(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 vO(e,t,r){let n={runId:e.id,name:e.name,status:Wc(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:sl(t,"status"),attentionCounts:sl(t,"attention"),lifecycleCounts:sl(t,"lifecycleStage")},n.controller=fX(t)),n}function mX(e){return e.status==="done"&&e.attention==="done"}function sk(e){let t=oe(e),n=Object.keys(t.workers||{}).map(s=>{let i=K(lp.join(J(t.id),"workers",F(s),"worker.json"),void 0);return i?bO({run:t,workerName:s,worker:i}):{worker:s,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=vO(t,n,!1);return we(lp.join(J(t.id),"last-board.json"),o),o}function ik(e){let t=oe(e),n=Object.keys(t.workers||{}).map(i=>{let a=K(lp.join(J(t.id),"workers",F(i),"worker.json"),void 0);return a?dX(a)?pX(i,a):bO({run:t,workerName:i,worker:a}):{worker:i,status:"missing",attention:"needs_attention",attentionReason:"worker.json not found"}}),o=n.filter(i=>!mX(i)),s=vO(t,o,!0);return s.status=Wc(t.status,n),s.summary={...s.summary??{},totalWorkerCount:n.length,shownWorkerCount:o.length,omittedTerminalDoneWorkerCount:n.length-o.length,allStatusCounts:sl(n,"status"),allAttentionCounts:sl(n,"attention")},we(lp.join(J(t.id),"last-board-compact.json"),s),s}async function RO(e,t){let r=String(e.run||""),n=String(e.agentOsId||"");if(!r||!n)return null;let o=sk(r),s=me(e.baseUrl?String(e.baseUrl):void 0),i=await ye(e.secret?String(e.secret):void 0,n,{baseUrl:s}),a=`${s}/api/agent-os/by-id/${encodeURIComponent(n)}/harness/snapshot`,l=await fe(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 Zs=p(()=>{"use strict";$();Ks();Cs();AI();Je();Q();Mc();XI();Ie();Wy();zi();CP();ky();_d();js();ko();Gs();Ld();U();Jd();fy();qd();ZP();jr()});var wO=p(()=>{"use strict";Je();Q();Ks();U()});import{spawn as gX}from"node:child_process";import{existsSync as hX,openSync as yX,closeSync as SO}from"node:fs";import kX from"node:path";function _O(e){let t=e.nodeExecutable??process.execPath,r=ad({importMetaUrl:import.meta.url,explicitCliPath:e.cliPath,nodeExecutable:t});if(!r)return;let n=r.cliPath;if(!hX(n))return;let o=kX.join(e.workerDir,"auto-complete.log"),s;try{s=yX(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=gX(r.command,a,Z({detached:Re(),stdio:i,env:process.env}));return s!==void 0&&SO(s),l.unref(),{pid:l.pid,logPath:o,cliPath:n}}catch{if(s!==void 0)try{SO(s)}catch{}return}}var kxe,xO=p(()=>{"use strict";U();_d();Q();Ie();Zs();U();Jd();sy();$();wO();kxe=360*60*1e3});var CO=p(()=>{"use strict"});function EO(e,t,r){de(e,["fetch","origin",r,"--prune"],{allowFailure:!0});let n=`origin/${r}`,o=ee(e,["worktree","add","-B",r,t,n]);if(o.status===0)return;let s=ee(e,["worktree","add","-b",r,t,"HEAD"]);if(s.status!==0){let i=o.stderr||o.stdout||s.stderr||s.stdout||"git worktree add failed for repair target branch";throw new Error(i)}}var AO=p(()=>{"use strict";_e()});import{createHash as bX}from"node:crypto";import{chmodSync as vX,mkdirSync as RX}from"node:fs";import IO from"node:os";import wX from"node:path";function PO(e,t){return bX("sha256").update(e).digest("hex").slice(0,t)}function ak(e){let t=e.platform??process.platform,r=PO(e.agentOsId,12),n=PO(e.workerKey,16);if(t==="win32")return{socketPath:`${_X}kynver-worker-${r}-${n}`,socketDir:null,isNamedPipe:!0,relocated:!1};let o=wX.posix,s=e.homeDir??IO.homedir(),i=o.join(s,".kynver","brokers",r),a=o.join(i,`${n}.sock`);if(Buffer.byteLength(a,"utf8")<=SX)return{socketPath:a,socketDir:i,isNamedPipe:!1,relocated:!1};let l=o.join(e.tmpDir??IO.tmpdir(),`kynver-brokers-${r}`);return{socketPath:o.join(l,`${n}.sock`),socketDir:l,isNamedPipe:!1,relocated:!0}}function lk(e){e.socketDir&&(RX(e.socketDir,{recursive:!0,mode:448}),vX(e.socketDir,448))}var SX,_X,ck=p(()=>{"use strict";SX=100,_X="\\\\.\\pipe\\"});import xX from"node:net";import{chmodSync as CX,unlinkSync as EX}from"node:fs";var il,DO=p(()=>{"use strict";Lr();cd();ck();pt();il=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=Na(t.capabilities),this.server=xX.createServer(r=>{this.handleConnection(r)}),this.server.on("error",()=>{})}static async start(t){let r=new e(t);if(lk(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{CX(t.address.socketPath,384)}catch{}return r}get identitySummary(){return this.opts.identity.summary}get toolDescriptors(){return this.grantedTools.filter(Fs).map(t=>Ba[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{EX(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(`
|
|
182
182
|
`);for(;s>=0;){let i=n.slice(0,s);n=n.slice(s+1),i.trim()&&this.handleLine(t,i),s=n.indexOf(`
|
|
183
|
-
`)}})}write(t,r){if(!t.destroyed)try{t.write(Gh(r))}catch{}}async handleLine(t,r){let n=Jh(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(!Us(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 ad({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 sk(){return PO}var PO,OO=p(()=>{"use strict";PO={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 TO=p(()=>{"use strict";Mr()});var NO=p(()=>{"use strict";IO();OO();Mr();ld();TO();Ay();ok()});import{existsSync as wX,mkdirSync as SX}from"node:fs";import Zs from"node:path";async function DO(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=U(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||Dr,model:t.model,rule:t.routingRule||"explicit:spawn",requestedModel:t.requestedModel??t.model}:md({explicitModel:t.model,explicitProvider:t.provider,explicitProviderIsOperatorOverride:!!t.provider?.trim(),configuredProvider:A().workerProvider}),s=yI(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}=ke(),l=Zs.join(q(e.id),"workers",n);SX(l,{recursive:!0});let c=Zs.join(a,e.id,n),u=t.repairTargetBranch?.trim()||void 0,d=u||t.branch||`agent/${e.id}/${n}`;if(wX(c))throw new Error(`worktree path already exists: ${c}`);if(de(e.repo,["fetch","origin","--prune"],{allowFailure:!0}),u)wO(e.repo,c,u);else{let x=lI({baseCommit:e.baseCommit,base:e.base,verifyRef:G=>de(e.repo,["rev-parse","--verify","--quiet",`${G}^{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=de(e.repo,["rev-parse",x.ref],{allowFailure:!0}).trim()||x.ref,Xe(e)),de(e.repo,["worktree","add","-b",d,c,e.baseCommit],{throwError:!0})}let f=Zs.join(l,"stdout.jsonl"),m=Zs.join(l,"stderr.log"),g=Zs.join(l,"heartbeat.jsonl"),h=mI({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=xd({title:t.taskTitle,personaSlug:t.personaSlug,parentTaskId:t.parentTaskId,executorRef:t.executorRef}),v,S,w,_,R=t.workerMcpToken?.trim();if(R&&qh(s.name)&&Na()){let x=Yn();x&&t.agentOsId&&t.taskId?(S={apiBaseUrl:x,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 O=gA(s.name);if(R&&O&&Na()){let x=Yn();if(x&&t.agentOsId&&t.taskId){let G=rk({agentOsId:String(t.agentOsId),workerKey:l}),T=await sl.start({address:G,apiBaseUrl:x,agentOsId:String(t.agentOsId),taskId:String(t.taskId),token:R,capabilities:t.workerMcpCapabilities??null,expiresAt:t.workerMcpExpiresAt??Date.now()+_X,workerPid:process.pid,identity:sk(),onRefusal:C=>console.error(`[supervisor] ${n}: worker tools refused a call (${C})`)});if(Ey(l,T),s.name==="codex"){let C=eP({workerDir:l,brokerSocketPath:G.socketPath});if(C.ok){let D=tP(C.codexHome,Br());D.ok?(w=C.codexHome,v=w):(Ya(l),await mn(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 codex rejected the generated config (${D.detail}); spawning with the normal environment`))}else await mn(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${C.detail}`)}else if(s.name==="cursor"){let C=QI({worktreePath:c,brokerSocketPath:G.socketPath});C.ok?v=C.configPath:(await mn(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${C.detail}`))}else if(s.name==="gemini"&&Fs(St())==="antigravity"){let C=aP({worktreePath:c,brokerSocketPath:G.socketPath});C.ok?v=C.configPath:(await mn(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${C.detail}`))}else if(s.name==="gemini"){let C=cP({workerDir:l,brokerSocketPath:G.socketPath});C.ok?(_=C.geminiCliHome,v=_):(await mn(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${C.detail}`))}else v=yA({workerDir:l,brokerSocketPath:G.socketPath});v&&console.error(`[supervisor] ${n}: worker tools enabled via broker (${T.identitySummary})`)}else console.error(`[supervisor] ${n}: worker MCP tools skipped (missing API base URL or task identity) \u2014 spawning without tools`)}let j=t.taskId?gS(hS(e.id,String(t.taskId),n)):null,P;try{P=yS(j,()=>s.start({name:n,task:t.task,ownedPaths:t.ownedPaths,model:i,modelPinned:$A(o.rule),branch:d,worktreePath:c,workerDir:l,stdoutPath:f,stderrPath:m,heartbeatPath:g,prompt:h,reviewWorker:k,executionMode:t.executionMode??"write",...S?{workerToolGrant:S}:{},...w?{codexHome:w}:{},..._?{geminiCliHome:_}:{},...v?{mcpConfigPath:v,mcpAllowedTools:mA(t.workerMcpCapabilities)}:{}}))}catch(x){throw v&&(rd(l),Pd(c),Ya(l),Nd(l),Td(c),Ks(l)),de(e.repo,["worktree","remove","--force",c],{allowFailure:!0}),de(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,b===void 0?delete process.env.KYNVER_HARNESS_AGENT_OS_ID:process.env.KYNVER_HARNESS_AGENT_OS_ID=b}let M=GA(P.model,i,s.defaultModel),N=A(),L=at(process.env,N),V=Ue().runnerId,W=cs({boxKind:L.boxKind,config:N,env:process.env}),F={name:n,runId:e.id,status:"running",pid:P.pid,model:M,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:L.boxKind,boxId:W,runtimeId:V,startedAt:new Date().toISOString(),...j?{oomRetryHeapMb:j}:{}};if(ne(e.id,F),Cy(l,P.pid),e.workers={...e.workers||{},[n]:{workerDir:l,statusPath:Zs.join(l,"worker.json")}},e.status="running",Xe(e),F.agentOsId&&F.taskId){let x;try{x=bO({runId:e.id,workerName:n,workerDir:l,agentOsId:F.agentOsId})}catch(G){let T=`completion sidecar failed to spawn: ${G.message}`;F.completionBlocker=T,ne(e.id,F)}if(x)x.pid&&(F.completionSidecarPid=x.pid,ne(e.id,F));else{let G=F.completionBlocker??"completion sidecar failed to spawn (CLI not found or spawn error)";F.completionBlocker=G,F.completionSidecarSpawnFailedAt=new Date().toISOString(),ne(e.id,F),iI(e.id,F,G)}}return F}var _X,MO=p(()=>{"use strict";Ws();jm();_e();Z();Z();cI();gI();B();Gu();oo();kI();vO();RO();SO();We();us();$();dt();Iy();Py();po();Dy();go();Ty();NO();Ir();yy();_X=7200*1e3});function xX(e,t){let r=Le(t)?.trim();return r||Te("KYNVER_RUNNER_TOKEN",e)||Te("OPENCLAW_RUNNER_TOKEN",e)||null}function CX(e){let t=Ce()?.trim();return t||Te("KYNVER_API_KEY",e)||Te("KYNVER_RUNTIME_SECRET",e)||Te("KYNVER_CRON_SECRET",e)||Te("OPENCLAW_CRON_SECRET",e)||null}async function LO(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=xX(r,e.agentOsId),l=CX(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 BO=p(()=>{"use strict";$();Ot()});function EX(e,t){let r=e.KYNVER_API_URL?.trim()||e.KYNVER_CRON_FIRE_BASE_URL?.trim()||t.apiBaseUrl?.trim()||null;return r?gr(r)??null:null}function AX(e,t){return(e.KYNVER_DEFAULT_REPO?.trim()||e.KYNVER_HARNESS_REPO?.trim()||t.defaultRepo?.trim()||null)??null}function IX(e,t,r){let n=e.KYNVER_HARNESS_ROOT?.trim()||t.harnessRoot?.trim()||null;return n||r||null}function UO(e,t={}){let r=t.env??process.env,n=t.nowMs??Date.now(),o=t.config??{},s=EX(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=AX(r,o),l=IX(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 FO=p(()=>{"use strict";hr()});var il=p(()=>{"use strict"});var al=p(()=>{"use strict"});var ak=p(()=>{"use strict";$();al()});var ck=p(()=>{"use strict";il()});import{mkdirSync as KO}from"node:fs";import{homedir as PX,tmpdir as WCe}from"node:os";import lp from"node:path";function $O(){let e=process.env.KYNVER_STATE_ROOT;return e?lp.resolve(e):lp.join(PX(),".kynver","state")}function cp(){return lp.join($O(),"plan-outbox")}function OX(){return lp.join($O(),"plan-outbox-archive")}function HO(){let e=cp(),t=OX();return KO(e,{recursive:!0}),KO(t,{recursive:!0}),{outboxDir:e,archiveDir:t}}var ll=p(()=>{"use strict"});function jO(){return{"planOutbox.storeFailures":cl.storeFailures,"planOutbox.corruptItemsSeen":cl.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":cl.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":cl.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":cl.halfArchivesCompleted}}var VCe,cl,ul=p(()=>{"use strict";pn();Cs();VCe=600*1e3,cl={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0}});import{existsSync as DX,readFileSync as MX,renameSync as YCe,readdirSync as zCe,rmSync as XCe,writeFileSync as QCe,unlinkSync as ZCe}from"node:fs";import VO from"node:path";function GO(e){if(!DX(e))return null;try{return JSON.parse(MX(e,"utf8"))}catch{return null}}function up(e){let{outboxDir:t}=HO();return{jsonPath:VO.join(t,`${e.id}.json`),bodyPath:VO.join(t,e.bodyPath)}}var dl=p(()=>{"use strict";ul();il();ck();ll()});var JO=p(()=>{"use strict";il();al();ak()});var uk=p(()=>{"use strict";ak();al();ck();ll();ul();dl();JO()});import KX from"node:path";function dk(e){let t=KX.join(cp(),`${e}.json`);return GO(t)}var qO=p(()=>{"use strict";dl();ul();uk();ll()});function pk(e){let t=up(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(`
|
|
184
|
-
`)}function
|
|
185
|
-
`),
|
|
186
|
-
`)}var
|
|
187
|
-
`)}function h3(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 ti(e){let t=e.pipeline===!0||e.pipeline==="true";try{let J=function(){return T.filter(I=>I.started).length},X=function(I,E){Ca({runId:l.id,agentOsId:u,phase:I,startedCount:J(),outcomeCount:T.length,cappedStarts:P,...E})},ge=function(){return T.some(I=>(typeof I.error=="string"?I.error:"").startsWith("dispatch_start_readback_failed:"))},ae=function(I){return I.landPrDispatch===!0?!0:I.task?.executor==="land_pr"};var r=J,n=X,o=ge,s=ae;let i=ZO();if(!i.ok||!i.identity){let I=eT(i);if(t)return{ok:!1,error:I,boundary:i};console.error(`run dispatch failed: ${I}`),process.exit(1)}let a=i.identity;for(let I of i.warnings)console.error(`[dispatch] runner-boundary warning: ${I}`);let l=se(String(Tt(String(e.run||""),"--run"))),c=XO(l,a);if(!c.ok){let I=c.reason??"run does not belong to this runner boundary";if(t)return{ok:!1,error:I,runId:l.id,runnerBoundary:a};console.error(`run dispatch failed: ${I}`),process.exit(1)}c.stamped&&console.error(`[dispatch] stamped run ${l.id} with boxKind=${a.boxKind} runnerId=${a.runnerId}`);let u=String(Tt(String(e.agentOsId||""),"--agent-os-id")),d=me(e.baseUrl?String(e.baseUrl):void 0),f=await ye(e.secret?String(e.secret):void 0,u,{baseUrl:d}),m=e.execute===!0||e.execute==="true",g=!m,h=Ue({runId:l.id}),y=$a(l.id,h.runnerId),b=q_(),k=b?bu(l.repo):null,v=new WeakMap;if(b&&m&&!k){let I="desktop_execution_policy_denied:repo_identity_unavailable: the repository has no origin remote";if(t)return{ok:!1,error:I,runId:l.id};console.error(`run dispatch failed: ${I}`),process.exit(1)}let S=e.diskPath?Xr({diskPath:String(e.diskPath)}):Xr({diskPath:l.repo}),w=await EE({runId:l.id,agentOsId:u,args:e}),_=h3(e),R=_.size>0,O=Number(e.maxStarts)>0?Math.floor(Number(e.maxStarts)):1,j=R?Math.min(O,_.size):O;if(e.reconcileStaleBlockers===!0||e.reconcileStaleBlockers==="true"){let I=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/lane-hygiene`;try{await fe(I,f,{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 P=g?j:Math.min(j,w.slotsAvailable);if(!g&&P<=0){let I={runId:l.id,agentOsId:u,dryRun:!1,skipped:!0,reason:w.reason??"no resource slots",resourceGate:w};if(t)return{ok:!0,...I};console.log(JSON.stringify(I,null,2));return}let M=ys(l.id),N=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/tasks/dispatch-next`,L=(I,E)=>({agentOsId:u,...E?{claimAuthorization:E}:{},dryRun:g,maxStarts:I,leaseOwner:y,leaseDurationMs:Number(e.leaseMs)>0?Math.floor(Number(e.leaseMs)):uy,runnerDiskGate:S,runnerResourceGate:w,activeHarnessWorkers:M,runnerPresence:h,harnessBoardSnapshot:ek(l.id),...e.lane?{lane:xE(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(H=>H.trim()).filter(Boolean)}:{}}),V=yE(),W=async I=>{let E=b&&k?Q_(k):void 0,H=await fe(N,f,L(I,E),{agentOsId:u,baseUrl:d,timeoutMs:V})??{ok:!1,status:0,response:null},Q=H.response;if(E&&Array.isArray(Q?.result?.started))for(let le of Q.result.started)le&&typeof le=="object"&&v.set(le,E.requestNonce);return{dispatch:H,result:Q?.result}};g||Ca({runId:l.id,agentOsId:u,phase:"awaiting_dispatch_next",timeoutMs:V});let F=await W(R||g?P:1);if(!F.dispatch.ok||!F.result){let I=Ch(F.dispatch.response),E={runId:l.id,agentOsId:u,action:"dispatch",httpStatus:F.dispatch.status,response:F.dispatch.response,authRefreshed:F.dispatch.refreshedAuth===!0,authRefreshFailure:F.dispatch.authRefreshFailure,...I?{timeout:!0}:{}};if(I&&Ca({runId:l.id,agentOsId:u,phase:"timeout",timeout:!0,httpStatus:F.dispatch.status}),t)return{ok:!1,...E};console.log(JSON.stringify(E,null,2)),process.exit(1)}let x=F.result;if(g){let I=BT(x),E=UT(x),H={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:I?.capacityIdle===!0,admissionExhaustion:I,dispatchSkipDrain:E};if(t)return{ok:!0,...H};console.log(JSON.stringify(H,null,2));return}let G=XA(),T=[],C=[],D=Number(x.inspected)||0,ee=!1;async function Y(I,E,H){let Q=await pl({baseUrl:d,secret:f,agentOsId:u,taskId:String(I.id),leaseOwner:y,leaseToken:I.leaseToken?String(I.leaseToken):null,failureDetail:E});I.leaseToken&&$s({taskId:String(I.id),leaseToken:String(I.leaseToken).trim()},Wy(E));let le={taskId:I.id,started:!1,error:E,released:Q.released,releaseResponse:Q.releaseResponse,...H};return T.push(le),X("outcome",{lastOutcome:le}),!1}async function p$(I){let E=I.task,H=String(E.id);if(R&&!_.has(H))return Y(E,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[..._]});if(!(E.prUrl?String(E.prUrl):""))return Y(E,"land_pr task missing prUrl");try{let le=await _T({decision:I,baseUrl:d,secret:f,agentOsId:u,cwd:l.repo,operation:{agentOsId:u,taskId:H,runId:l.id,workerName:`land-pr-${H}`,leaseOwner:y,leaseToken:typeof E.leaseToken=="string"?E.leaseToken:"",receiptDir:`${q(l.id)}/land-pr-operations`}}),Pt=await CT({baseUrl:d,secret:f,agentOsId:u,runId:l.id,task:E,report:le});return Pt.ok?(T.push({taskId:H,started:!0,landPr:!0,outcome:le.outcome,completionStatus:Pt.status}),!0):Y(E,`land_pr completion POST failed (HTTP ${Pt.status})`,{landPr:!0,outcome:le.outcome})}catch(le){return Y(E,le.message)}}async function f$(I){let E="duplicate_dispatch_prevented: live local worker already owns this task",H=await pl({baseUrl:d,secret:f,agentOsId:u,taskId:String(I.id),leaseOwner:y,leaseToken:I.leaseToken?String(I.leaseToken):null,failureDetail:E});I.leaseToken&&$s({taskId:String(I.id),leaseToken:String(I.leaseToken).trim()},Wy(E));let Q={taskId:I.id,started:!1,error:E,alreadyRunning:!0,nonFatal:!0,released:H.released,releaseResponse:H.releaseResponse};return T.push(Q),X("outcome",{lastOutcome:Q}),!1}async function m$(I){let E=I.task,H=p3(I),Q=String(E.id);if(R&&!_.has(Q))return Y(E,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[..._]});let le=f3(E.personaSlug);if(le&&(!H?.personaInjectionReady||!H.personaMarkdown))return Y(E,`persona_injection_required: missing anchored context-envelope persona block for "${le}"`);if(le&&!H?.runtimeEnvelopeReady)return Y(E,`runtime_envelope_required: missing AgentRuntimeEnvelope launch receipt for persona "${le}"`);if(rI(l.id,Q))return f$(E);let Pt=Number(E.attempt)||1;if(Pt>G.maxTaskAttempts)return Y(E,`task attempt ${Pt} exceeds KYNVER_MAX_TASK_ATTEMPTS (${G.maxTaskAttempts})`);let Mn=E.leaseToken?String(E.leaseToken).trim():"";if(!Mn)return Y(E,"dispatch_start_failed: claimed task missing leaseToken \u2014 refusing local spawn");let Ln=U(`t-${E.id}-a${E.attempt}`),mr=md({explicitModel:e.model?String(e.model):void 0,explicitProvider:e.provider?String(e.provider):void 0,explicitProviderIsOperatorOverride:!!e.provider,configuredProvider:A().workerProvider,task:IE(E)});SP({taskId:Q,leaseToken:Mn,runId:l.id,workerName:Ln,provider:mr.provider??null});let hm=qA({task:E,routing:mr,explicitProvider:e.provider?String(e.provider):void 0,explicitModel:e.model?String(e.model):void 0});if(!hm.ok)return Y(E,hm.error??"model_routing_mismatch",{modelRoutingGuard:hm});if(DT(E)){let ot=await MT({agentOsId:u,taskId:Q,baseUrl:d,secret:f});if(ot&&ot.dispatchable===!1)return Y(E,`pr_review_head_reconcile_blocked: ${ot.reason??ot.outcome??"stale PR head"}`,{headReconcile:ot});if(ot?.activeReviewTaskId&&ot.activeReviewTaskId!==Q)return Y(E,`pr_review_head_reconcile_retargeted: active review is ${ot.activeReviewTaskId}`,{headReconcile:ot})}let ac=VP(mr.provider);if(!ac.ok)return Y(E,`provider_quota_exhausted: ${ac.reason}`,{nonFatal:!0,providerQuotaPreflight:{provider:ac.provider,retryAt:ac.retryAtIso}});try{let ot=E.planId?String(E.planId):void 0,lc=dI({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}),nw=LP({runId:l.id,workerName:Ln,maxSlots:w.maxConcurrentWorkers,diskActiveWorkers:zm()});if(!nw.admitted)return Y(E,`admission_refused: ${nw.reason}`,{nonFatal:!0});let cc=H?.workerMcpToken??null;if(cc&&Na()){let Ho=UO({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`),cc=null;else{let ym=await LO(Ho.context);ym.reachable||(console.error(`[dispatch] worker tools skipped for task ${String(E.id)}: tool endpoint probe failed (${ym.error??`HTTP ${ym.httpStatus}`}) \u2014 spawning without tools`),cc=null)}}sI(l.id,String(E.id),{except:Ln});let Gt=await DO(l,{name:Ln,task:g3(E,u),ownedPaths:e.owned?String(e.owned).split(",").map(Ho=>Ho.trim()).filter(Boolean):[],model:mr.model,provider:mr.provider,routingRule:mr.rule,requestedModel:mr.requestedModel,agentOsId:u,taskId:String(E.id),planId:ot,branch:lc?.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:lc?.targetPrUrl??(E.prUrl?String(E.prUrl):void 0),repairTargetPrUrl:lc?.targetPrUrl,repairTargetBranch:lc?.targetPrBranch??void 0,instructionPolicyMarkdown:H?.instructionPolicyMarkdown??null,instructionPolicyFingerprint:H?.instructionPolicyFingerprint??null,instructionPolicyEvidence:H?.instructionPolicyEvidence??null,memoryQualityCapture:H?.memoryQualityCapture??null,memoryQualityPromptMarkdown:H?.memoryQualityPromptMarkdown??null,personaMarkdown:H?.personaMarkdown??null,personaSlug:H?.personaSlug??le,personaEvidence:H?.personaEvidence??null,contextEnvelopeMarkdown:H?.contextEnvelopeMarkdown??null,contextEnvelopeEvidence:H?.contextEnvelopeEvidence??null,runtimeEnvelopeMarkdown:H?.runtimeEnvelopeMarkdown??null,runtimeEnvelopeEvidence:H?.runtimeEnvelopeEvidence??null,workerMcpToken:cc,workerMcpCapabilities:H?.workerMcpCapabilities??null,workerMcpExpiresAt:H?.workerMcpExpiresAt??null,leaseOwner:y,leaseToken:Mn,dispatched:!0,executionMode:yu(E)}),uc=await PT({agentOsId:u,taskId:String(E.id),leaseOwner:y,expectedLeaseToken:Mn,worker:Gt,baseUrl:d,secret:f});if(!uc.ok)return TT(l.id,Gt,uc.error??"dispatch_start_readback_failed"),bn(l.id,Ln),Y(E,uc.error??"dispatch_start_readback_failed",{readback:uc.detail??null});Gt.leaseToken!==Mn&&(Gt.leaseToken=Mn,Gt.leaseOwner=y,ne(l.id,Gt)),Kd({taskId:Q,leaseToken:Mn}),TP(l.id,Ln);let ow={taskId:E.id,started:!0,worker:Gt.name,pid:Gt.pid,branch:Gt.branch,model:Gt.model,provider:mr.provider,routingRule:mr.rule,instructionPolicyFingerprint:H?.instructionPolicyFingerprint??null,instructionPolicyRuleCount:Array.isArray(H?.instructionPolicyEvidence?.ruleSlugs)?H.instructionPolicyEvidence.ruleSlugs.length:null,personaSlug:H?.personaSlug??le,personaOperatingRuleCount:H?.personaEvidence?.operatingRuleCount??null};return T.push(ow),X("worker_started",{lastOutcome:ow}),H?.instructionPolicyFingerprint&&console.error(`[dispatch] task ${Q}: instruction policy injected fingerprint=${H.instructionPolicyFingerprint}`),H?.personaSlug&&console.error(`[dispatch] task ${Q}: persona context injected slug=${H.personaSlug}`),H?.contextEnvelopeReady&&console.error(`[dispatch] task ${Q}: context envelope injected anchor=${H.contextEnvelopeEvidence?.anchorTaskId??Q}`),H?.runtimeEnvelopeReady&&console.error(`[dispatch] task ${Q}: runtime envelope injected id=${H.runtimeEnvelopeEvidence?.envelopeId??"unknown"}`),!0}catch(ot){return bn(l.id,Ln),Y(E,ot.message)}}let gm=new Set;for(let I of AP(l.id))gm.add(I);async function QR(I){let E=I.task,H=String(E.id);if(gm.has(H))return Y(E,"dispatch_retry_loop_prevented: task already failed to start this tick");let Q=b?Z_({decision:I,leaseOwner:y,repoIdentity:k,requestNonce:v.get(I)??null}):null,le=Q&&!Q.allow?await Y(E,`desktop_execution_policy_denied:${Q.code}: ${Q.reason}`,{desktopPolicyDenied:Q.code,...Q.code==="operation_not_approved"?{nonFatal:!0}:{}}):ae(I)?await p$(I):await m$(I);return le||(gm.add(H),EP(H,l.id)),le}for(let I of x.started)await QR(I);if(C.push(...x.skipped??[]),R)for(let I of C){let E=String(I.task.id);_.has(E)&&T.push({taskId:E,started:!1,error:`exact_target_not_started:${I.skipReason}`,skipReason:I.skipReason,detail:I.reason??null,requestedTargetTaskIds:[..._]})}for(;!R&&T.length<P;){if(ge()){let H={started:!1,error:"dispatch_circuit_breaker: start readback failed; stopping top-up for this tick",nonFatal:!0};T.push(H),X("circuit_breaker",{lastOutcome:H});break}let I=await W(1);if(!I.dispatch.ok||!I.result){let H=bE(I.dispatch.response),Q=J();ee=H&&Q>0;let le=Ch(I.dispatch.response),Pt={started:!1,error:le?"dispatch_next timed out during top-up":"dispatch_next request failed during top-up",httpStatus:I.dispatch.status,response:I.dispatch.response,...le?{timeout:!0}:{},...ee?{nonFatal:!0,partialTopUp:!0}:{}};T.push(Pt),X("top_up_failed",{partialTopUpInterrupted:ee,lastOutcome:Pt});break}D+=Number(I.result.inspected)||0,C.push(...I.result.skipped??[]);let E=I.result.started??[];if(E.length===0)break;for(let H of E){if(T.length>=P)break;await QR(H)}}let ic=T.filter(I=>I.started).length,zr=BT(x),$o=UT(x),ZR=ic===0&&(zr?.capacityIdle===!0||Number(x.resourceGate?.slotsAvailable)>0);if(ZR&&zr?.summary){let I=zr.skipReasonCounts?.retry_ceiling_exceeded??0,E=x.overAttemptIdleRecovery??zr.overAttemptIdleRecovery,H=E?.attempted===!0?`; over_attempt_recovery minted=${E.minted??0} started=${E.started??0}`:I>0?"; over_attempt_recovery not attempted":"",Q=$o?`; dispatch_skip_drain scanned=${$o.scanned??0} advanced=${$o.advanced??0}`:"",le=zr.progressionReport?.summary?`; ${zr.progressionReport.summary}`:"",Pt=$o?.prLifecycleAttempt?.summary?`; ${$o.prLifecycleAttempt.summary}`:"";console.error(`[dispatch] ${zr.summary}${I>0?`; retry_ceiling_exceeded=${I}`:""}${H}${Q}${le}${Pt}`)}let ew={runId:l.id,agentOsId:u,dryRun:!1,leaseOwner:y,startedCount:ic,capacityIdle:ZR,admissionExhaustion:zr,dispatchSkipDrain:$o,outcomes:T,skipped:C.map(I=>({taskId:I.task.id,skipReason:I.skipReason})),inspected:D,pagesScanned:x.pagesScanned??null,candidatesExhausted:x.candidatesExhausted??null,diskGate:x.diskGate,resourceGate:x.resourceGate,...ee?{partialTopUpInterrupted:!0}:{},dispatchCallbackTimeoutMs:V},tw=I=>!I.started&&I.nonFatal!==!0,g$=T.some(tw),rw=ee&&ic>0?!0:!g$;if(Ca({runId:l.id,agentOsId:u,phase:"complete",partial:ee,startedCount:ic,ok:rw}),t)return{ok:rw,...ew};console.log(JSON.stringify(ew,null,2)),T.some(tw)&&process.exit(1)}catch(i){if(t)return{ok:!1,error:i.message};console.error(`run dispatch failed: ${i.message}`),process.exit(1)}}var uy,kd=p(()=>{"use strict";$();vu();Ge();kE();vE();CE();Vi();AE();ss();Z();Z();PE();Gu();YA();QA();cy();MO();Ws();BO();FO();dt();pu();Qs();B();zO();py();Ha();Ir();QO();tT();gk();Jd();xT();ET();IT();OT();NT();Z();LT();Sg();Hs();yo();Vs();uy=3600*1e3});function ri(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 k3(e){let{maxStarts:t,...r}=e;return r}async function vk(e,t){if(t<=0)return{ok:!0,skipped:!0,reason:"no slots",maxStarts:0,startedCount:0};let r=k3(e);if(r.targetTaskId||r.targetTaskIds){let u=await ti({...r,execute:!0,pipeline:!0,maxStarts:String(t)});return{...typeof u=="object"&&u!==null?u:{},passes:{target:u},startedCount:ri(u)}}let n=Math.min(t,y3),o=Math.max(0,t-n),s=await ti({...r,execute:!0,pipeline:!0,lane:"review",maxStarts:String(n)}),i=ri(s),a=o+(n-i);if(a<=0)return{...typeof s=="object"&&s!==null?s:{},passes:{review:s},startedCount:i};let l=await ti({...r,execute:!0,pipeline:!0,maxStarts:String(a)}),c=ri(l);return{passes:{review:s,work:l},startedCount:i+c,ok:!0}}var y3,FT=p(()=>{"use strict";kd();y3=1});function WT(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 KT=p(()=>{"use strict"});function b3(e){let r=e.response?.dispatch;return r&&typeof r=="object"?r:null}function fl(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function v3(e){let t=Number(process.env[e]);return!Number.isFinite(t)||t<=0?null:Math.floor(t)}function $T(e,t){let r=b3(t),n=fl(r?.recommendedMaxStarts),o=fl(r?.actionableReady),s=fl(r?.queuedTasks),i=fl(r?.boardAdvancedThisTick)??0,a=fl(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=v3("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 HT=p(()=>{"use strict"});import R3 from"node:path";function bo(e){let t=Dt(e);if(t.length===0)return"failed";let r=!1,n=!1,o=!1,s=!1;for(let i of t){let a=K(R3.join(q(e.id),"workers",U(i),"worker.json"),void 0);if(!a)continue;let l=ce(a,{base:e.base,baseCommit:e.baseCommit});if(l.alive&&!l.finalResult){r=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Ym(l)&&(s=!0),l.finalResult&&l.attention.state==="done"&&(n=!0)}return r||o||s?null:n?"completed":"failed"}function ml(){let e=[];for(let t of xe()){if(!w3.has(t.status))continue;let r=bo(t);if(!r||r===t.status)continue;let n=t.status;t.status=r,Xe(t),e.push({runId:t.id,from:n,to:r})}return e}var w3,jr,Rn=p(()=>{"use strict";Z();Qo();Ie();B();w3=new Set(["running","dispatching","pending","queued","needs_attention"]),jr=new Set(["completed","failed","cancelled","done"])});import Kt from"node:path";function dp(e){return e.includes(S3)}function Rk(e,t){return Kt.join(ct(Be(e)),U(t))}function wn(e,t,r){return Kt.join(Rk(e,t),"workers",U(r))}function jT(e,t,r){let n=Be(e);return Kt.join(n,"runs","runs",U(t),"workers",U(r))}function wk(){return["stdout.jsonl","stderr.log","heartbeat.jsonl","last-status.json","auto-complete.log","worker.json"]}function vo(e){return{workerJsonPath:Kt.join(e,"worker.json"),stdoutPath:Kt.join(e,"stdout.jsonl"),stderrPath:Kt.join(e,"stderr.log"),heartbeatPath:Kt.join(e,"heartbeat.jsonl"),lastStatusPath:Kt.join(e,"last-status.json")}}function VT(e){let t=vo(wn(e.harnessRoot,e.runId,e.workerName)).workerJsonPath;return e.statusPath&&!dp(e.statusPath)?e.statusPath:t}var S3,Sk=p(()=>{"use strict";Mt();B();S3=`${Kt.sep}runs${Kt.sep}runs${Kt.sep}`});import{existsSync as _3,readFileSync as x3,readdirSync as C3,statSync as E3,writeFileSync as A3}from"node:fs";import I3 from"node:path";function M3(e,t=[]){if(!e)return e;let r=e,n=[...new Set(t.map(o=>o?.trim()).filter(o=>!!o&&o.length>=O3))].sort((o,s)=>s.length-o.length);for(let o of n){r.includes(o)&&(r=r.split(o).join(mt));let s=JSON.stringify(o).slice(1,-1);s!==o&&r.includes(s)&&(r=r.split(s).join(mt))}for(let[o,s]of P3)r=r.replace(o,s);return r}function GT(e=process.env,t=[]){let r=[];for(let[n,o]of Object.entries(e))o&&T3.test(n)&&r.push(o);for(let n of t)try{let o=n();o&&r.push(o)}catch{}return r}function JT(e,t=0){if(t>3||!_3(e))return[];let r=[];for(let n of C3(e,{withFileTypes:!0})){let o=I3.join(e,n.name);n.isDirectory()?r.push(...JT(o,t+1)):n.isFile()&&N3.test(n.name)&&r.push(o)}return r}function qT(e,t=[]){let r={masked:[],clean:0,failed:[]},n;try{n=JT(e)}catch{return r}for(let o of n)try{if(E3(o).size>D3){r.failed.push(o);continue}let s=x3(o,"utf8"),i=M3(s,t);if(i===s){r.clean+=1;continue}A3(o,i,"utf8"),r.masked.push(o)}catch{r.failed.push(o)}return r}var mt,_k,P3,O3,T3,N3,D3,YT=p(()=>{"use strict";mt="<redacted>",_k=`[^\\s"'\\\\,}\\]]`,P3=[[new RegExp(`\\b(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|rediss):\\/\\/${_k}+`,"gi"),mt],[new RegExp(`\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s/@:"']+:[^\\s/@"']+@${_k}+`,"gi"),mt],[/\bkynver_u_[A-Za-z0-9_-]+/g,mt],[/\bkyn_[A-Za-z0-9]{12,}/g,mt],[/\bsk-ant-[A-Za-z0-9_-]+/g,mt],[/\bsk-[A-Za-z0-9_-]{8,}/g,mt],[/\bkr[a-z]1\.[A-Za-z0-9._~+/=-]{8,}/g,mt],[/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}/g,mt],[/\bgithub_pat_[A-Za-z0-9_]{16,}/g,mt],[/\b(Bearer|Basic)\s+(?!<redacted>)[A-Za-z0-9._~+/=-]{8,}/gi,`$1 ${mt}`],[new RegExp(`(\\b(?:[A-Z0-9_]*(?:API_KEY|APIKEY|TOKEN|SECRET|PASSWORD)|DATABASE_URL|KYNVER_DATABASE_URL)\\s*=\\s*)(?!<redacted>)${_k}+`,"g"),`$1${mt}`]],O3=12,T3=/(?:API_KEY|APIKEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)$/i,N3=/(?:\.jsonl|\.log|\.txt|^stdout.*|^stderr.*)$/i,D3=256*1024*1024});import{existsSync as Sn,mkdirSync as L3,readdirSync as XT,renameSync as B3,statSync as xk}from"node:fs";import ve from"node:path";function QT(e,t){let r=ve.resolve(e),n=ve.resolve(ct(t)),o=ve.relative(n,r);return o!==".."&&!o.startsWith("..")&&!ve.isAbsolute(o)}function Ck(e){if(!Sn(e))return[];try{return XT(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&t.name!=="runs").map(t=>t.name)}catch{return[]}}function Ek(e){let t=ve.join(e,"workers");if(!Sn(t))return[];try{return XT(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}function ZT(e){return ve.join(e,"archived-workers")}function F3(e,t){let r=ve.join(ZT(e),U(t));return Sn(r)?`${r}-${Date.now()}`:r}function zT(e,t,r){if(!Sn(e))return!1;try{let n=t-xk(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<r}catch{return!1}}function eN(e,t=Date.now(),r=gl){if(!Sn(e))return!1;let n=vo(e),o=K(n.workerJsonPath,void 0);if(o?.status==="running"&&oe(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!!(zT(n.stdoutPath,t,r)||zT(n.heartbeatPath,t,r))}function W3(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-xk(ve.join(e,"worker.json")).mtimeMs}catch{return 0}}function K3(e,t,r,n){if(eN(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=W3(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 ni(e,t=Date.now(),r=gl){for(let n of Ek(e))if(eN(ve.join(e,"workers",n),t,r))return!0;return!1}function $3(){let t=va()?.repo??"",r="unknown";if(t)try{let n=de(t,["rev-parse","origin/main"],{allowFailure:!0}).trim();n&&(r=n)}catch{}return{repo:t,base:"origin/main",baseCommit:r}}function H3(e,t){let r=ve.join(ct(e),U(t));if(!Sn(r))return null;let n=Ek(r);if(n.length===0)return null;let o;try{o=xk(r).birthtime.toISOString()}catch{o=new Date().toISOString()}let s={};for(let a of n){let l=wn(e,t,a);s[a]={workerDir:l,statusPath:ve.join(l,"worker.json")}}let i=ni(r);return{id:t,name:t,...$3(),status:i?"running":"needs_attention",createdAt:o,workers:s}}function Ak(e){let t=Be(e??bt()),r=ct(t),n=[];for(let o of Ck(r)){let s=ve.join(r,o,"run.json");if(Sn(s)){n.push({runId:o,action:"skipped",reason:"run.json present"});continue}let i=H3(t,o);if(!i){n.push({runId:o,action:"skipped",reason:"no worker dirs on disk"});continue}Xe(i),n.push({runId:o,action:"repaired_run_json",reason:ni(ve.join(r,o))?"synthesized run.json while worker artifacts still active":"synthesized run.json from orphan worker metadata dirs"})}return{runs:n}}function Ik(e,t={}){let r=Be(e??bt()),n=ct(r),o=t.now??Date.now(),s=t.archiveAgeMs??U3,i=[],a=null,l=()=>a??=(t.knownSecrets??(()=>GT(process.env,[Ce,()=>Le()])))();Ak(r);for(let c of Ck(n)){let u=ve.join(n,c),d=ve.join(u,"run.json"),f=K(d,void 0);if(!f?.id)continue;let m=new Set([...Object.keys(f.workers||{}),...Ek(u)]),g=!1;for(let h of m){let y=ve.join(u,"workers",U(h)),b=ve.join(y,"worker.json"),k=K(b,void 0);if(!k){let w=ve.join(ZT(u),U(h));if(Sn(w)&&(f.workers[U(h)]||f.workers[h])){delete f.workers[U(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:w});continue}i.push({runId:f.id,worker:h,action:"skipped",reason:"worker.json missing"});continue}let v=K3(y,k,o,s);if(!v.eligible){i.push({runId:f.id,worker:h,action:"skipped",reason:v.reason});continue}let S=F3(u,h);L3(ve.dirname(S),{recursive:!0}),B3(y,S),qT(S,l()),delete f.workers[U(h)],delete f.workers[h],g=!0,i.push({runId:f.id,worker:h,action:"archived",reason:v.reason,archivePath:S})}g&&Xe(f)}return{workers:i}}function tN(e,t=Date.now()){let r=new Set,n=ct(e);for(let o of Ck(n)){let s=ve.join(n,o);ni(s,t)&&r.add(`${e}\0${o}`)}return r}var gl,U3,oi=p(()=>{"use strict";As();_e();Kn();Mt();Z();Sk();B();$();YT();gl=900*1e3,U3=3600*1e3});import{existsSync as _n,lstatSync as j3,readdirSync as V3,readlinkSync as G3,renameSync as Pk,unlinkSync as J3}from"node:fs";import rr from"node:path";function q3(e,t){let r=Rk(e,t),n;try{n=j3(r)}catch{return null}if(!n.isSymbolicLink())return null;let o=rr.resolve(rr.dirname(r),G3(r));if(ni(o)||ni(r))return null;let s=`${r}.materialize-${Date.now()}`;return Pk(o,s),J3(r),Pk(s,r),o}function Y3(e){let t=[];for(let r of wk()){let n=rr.join(e.fromDir,r),o=rr.join(e.toDir,r);!_n(n)||_n(o)||(Pk(n,o),t.push(r))}return t}function rN(e,t){let r=vo(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 z3(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 X3(e){let t=vo(e.canonicalDir),r=K(t.lastStatusPath,void 0),n=_n(t.stdoutPath),o=_n(t.heartbeatPath);if(!(n||o||r!=null))return null;let i=n?$n(t.stdoutPath):{finalResult:null},a=o?De(t.heartbeatPath):De(""),l=kr(a),c=z3({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:rr.join(ke().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}),rN(u,e.canonicalDir),u}function Q3(e,t){let r=!1,n={...e.workers||{}};for(let[o,s]of Object.entries(n)){let i=wn(t,e.id,o),a=rr.join(i,"worker.json");(dp(s.workerDir)||dp(s.statusPath)||s.workerDir!==i||s.statusPath!==a)&&(n[o]={workerDir:i,statusPath:a},r=!0)}return r&&(e.workers=n,Xe(e)),r}function Z3(e){let t=[],r=wn(e.harnessRoot,e.run.id,e.workerName),n=jT(e.harnessRoot,e.run.id,e.workerName),o=vo(r),s=Y3({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=VT({harnessRoot:e.harnessRoot,runId:e.run.id,workerName:e.workerName,statusPath:e.statusPath}),a=K(i,void 0);if(!a&&_n(o.workerJsonPath)&&(a=K(o.workerJsonPath,void 0)),!a){let l=X3({run:e.run,workerName:e.workerName,canonicalDir:r,harnessRoot:e.harnessRoot});if(l)return ne(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=_n(r),u=wk().some(d=>_n(rr.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:rr.join(ke().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 ne(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 rN(a,r)?(a.reconciledAt=new Date().toISOString(),a.reconcileReason=a.reconcileReason??"repaired nested runs/runs path fields",ne(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 e8(e,t){let r=rr.join(q(e.id),"workers");if(!_n(r))return[];let n=new Set(Object.keys(e.workers||{})),o=[];for(let s of V3(r,{withFileTypes:!0}))s.isDirectory()&&(n.has(s.name)||o.push(s.name));return o}function nN(){let{harnessRoot:e}=ke(),t=Ak(e),r=[];for(let n of xe()){let o=q3(e,n.id);o&&r.push({runId:n.id,worker:"*",action:"materialized_run_symlink",reason:`replaced symlink with real run dir (was ${o})`}),Q3(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 e8(n,e))s.add(i),n.workers={...n.workers||{},[i]:{workerDir:wn(e,n.id,i),statusPath:rr.join(wn(e,n.id,i),"worker.json")}},Xe(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(...Z3({run:n,workerName:i,harnessRoot:e,statusPath:a?.statusPath}))}}return{workers:r,runMetadataRetention:t}}var oN=p(()=>{"use strict";Kn();Yi();Sk();oi();Z();B()});import{execFileSync as sN}from"node:child_process";import iN from"node:path";function Ok(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:null}function t8(e){let t=Ok(e)?.match(/\/pull\/(\d+)$/);if(!t)return null;let r=Number.parseInt(t[1],10);return Number.isFinite(r)?r:null}function r8(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function n8(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 o8(e){let t=null;if(typeof e=="string"?t=rs(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=Ok(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 s8(e){try{let n=sN("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=sN("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:Ok(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 i8(e){let t=De(e.heartbeatPath);return e.completionSnapshot?.finalResult??kr(t)}function a8(e){let t=new Map,r=q(e.id);for(let n of Dt(e)){let o=K(iN.join(r,"workers",U(n),"worker.json"),void 0);if(o)for(let s of o8(i8(o))){let i=t8(s.prUrl);i!=null&&!t.has(i)&&t.set(i,s)}}return t}function l8(e,t){let r=De(e.heartbeatPath),n=[e.name,e.repairTargetPrUrl,e.taskPrUrl,e.branch,r.lastHeartbeatSummary,r8(t)].filter(Boolean).join(`
|
|
188
|
-
`);return n8(n)}function c8(e){return e.localOnly===!0&&!e.taskId&&!e.agentOsId}function Tk(e={}){let t=e.lookupPr??s8,r=[],n=new Map;for(let o of xe()){let s=a8(o),i=q(o.id);for(let a of Dt(o)){let l=iN.join(i,"workers",U(a),"worker.json"),c=K(l,void 0);if(!c||!c8(c))continue;let u=ce(c,{base:o.base,baseCommit:o.baseCommit});if(u.attention.state!=="needs_attention")continue;let d=null;for(let m of l8(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",ne(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 aN=p(()=>{"use strict";Kn();Bc();Ie();Z();Qo();B()});import u8 from"node:path";function p8(){return process.env.KYNVER_NO_STALE_CLEANUP==="1"}function lN(e,t){let r=Bd({worker:e,status:t}),n=r?Ud(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 f8(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 Nk(){let e=nN();if(p8()){let s=Tk(),i=Ik();return{workers:[],finalizedRuns:ml(),metadataReconcile:e,localPrAttentionReconcile:s,terminalWorkerArchive:i}}let t=[],r=Date.now();for(let s of xe())for(let i of Dt(s)){let a=u8.join(q(s.id),"workers",U(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=ce(l,{base:s.base,baseCommit:s.baseCommit});if(c.finalResult){if(l.status==="running"){let u=lN(l,c);l.status=u.nextStatus,l.reconciledAt=new Date().toISOString(),l.reconcileReason=u.reason,l.stopClass="finished",ne(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=lN(l,c);l.status=u.nextStatus,l.reconciledAt=new Date().toISOString(),l.reconcileReason=u.reason,f8(l,c),ne(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&&oe(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>d8,m=Number.isFinite(d)&&r-d>qm;if(f&&m){he(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}`,ne(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=Tk(),o=Ik();return{workers:t,finalizedRuns:ml(),metadataReconcile:e,localPrAttentionReconcile:n,terminalWorkerArchive:o}}var d8,Dk=p(()=>{"use strict";Rn();Z();Qo();My();Ie();B();oN();aN();oi();d8=900*1e3});import{readdirSync as m8,readFileSync as g8}from"node:fs";function v8(e){if(process.platform!=="linux"||!e.trim())return null;let t=[];try{t=m8("/proc")}catch{return null}for(let r of t)if(/^\d+$/.test(r)&&Number(r)!==process.pid)try{if(g8(`/proc/${r}/cmdline`,"utf8").replace(/\0/g," ").includes(e))return Number(r)}catch{}return null}async function cN(e){let t=Kr(),r={mode:t,scanned:0,outcomes:[]};if(t!=="enforce")return r;let n=pe();if(!n)return r;let o=e.nowMs??Date.now(),s=e.strandedAfterMs??y8,i=e.findOrphanPid??v8,a=[],l;try{l=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-k8).toISOString(),limit:b8})}catch{return Ro.recoveryStoreFailures+=1,r}for(let c of l){let u=c.idempotencyKey.slice(h8.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=za(f);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${d}:`,limit:10}).some(w=>{if(g===null)return!0;let _=za(w.idempotencyKey.slice(`dispatch:completion-acked:${d}:`.length));return _===null||_>=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})){Kd({taskId:d,leaseToken:f}),a.push({taskId:d,leaseToken:f,runId:k,workerName:v,action:"finalized_late"});continue}if(k&&v){let w=e.worktreePathFor({runId:k,workerName:v}),_=w?i(w):null;if(_!==null){Ro.recoveryDeferredOrphans+=1,a.push({taskId:d,leaseToken:f,runId:k,workerName:v,action:"deferred_orphan",detail:`live pid ${_} references ${w}`});continue}}if(!k){a.push({taskId:d,leaseToken:f,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:f,runId:k});S.released?($s({taskId:d,leaseToken:f},"restart_recovery"),v&&(Qa(k,v),bn(k,v)),Ro.recoveredStrandedClaims+=1,a.push({taskId:d,leaseToken:f,runId:k,workerName:v,action:"released"})):S.transportError?a.push({taskId:d,leaseToken:f,runId:k,workerName:v,action:"deferred_transport",detail:S.detail}):($s({taskId:d,leaseToken:f},"restart_recovery_refused"),a.push({taskId:d,leaseToken:f,runId:k,workerName:v,action:"release_refused",detail:S.detail}))}catch{Ro.recoveryStoreFailures+=1}}return{mode:t,scanned:l.length,outcomes:a}}function uN(){return{"dispatchReceipts.recoveredStrandedClaims":Ro.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":Ro.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":Ro.recoveryStoreFailures}}var h8,y8,k8,b8,Ro,Mk=p(()=>{"use strict";pn();Hs();yo();Vs();h8="dispatch:claim:",y8=900*1e3,k8=10080*60*1e3,b8=200,Ro={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0}});import R8 from"node:path";async function pN(e){if(dN||Kr()!=="enforce")return null;dN=!0;try{let t=Ue().runnerId,r=await cN({hasLiveWorker:e.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>R8.join(ke().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await pl({baseUrl:e.baseUrl,secret:e.secret,agentOsId:e.agentOsId,taskId:n,leaseOwner:$a(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 dN,fN=p(()=>{"use strict";Z();Ha();Ir();gk();Mk();Hs();dN=!1});import w8 from"node:os";function mN(e,t={}){let r=A(),n=(t.boxKind??Nt(r)).trim().toLowerCase()||"forge",o=t.hostLabel??w8.hostname();return{boxId:cs({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:VC()}}var gN=p(()=>{"use strict";$();We();us();Lu()});import S8 from"node:path";async function pp(e){let t=e.pipeline===!0||e.pipeline==="true";try{let r=se(String(Tt(String(e.run||""),"--run"))),n=String(Tt(String(e.agentOsId||""),"--agent-os-id")),o=me(e.baseUrl?String(e.baseUrl):void 0),s=await ye(e.secret?String(e.secret):void 0,n,{baseUrl:o}),i=Ue({runId:r.id}).runnerId,a=await hO({run:r.id,agentOsId:n,...e},"run_sweep"),l=[];for(let f of Object.keys(r.workers||{})){let m=K(S8.join(q(r.id),"workers",U(f),"worker.json"),void 0);if(!m||!m.dispatched||!m.taskId)continue;let g=ce(m);if(g.alive||g.finalResult||m.completionReportedAt)continue;try{let k=await Xs({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=gd({runId:r.id,workerLeaseOwner:m.leaseOwner??null,runnerId:i}),y=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/${encodeURIComponent(String(m.taskId))}/release`,b;try{b=await fe(y,s,{agentOsId:n,leaseOwner:h,...m.leaseToken?.trim()?{leaseToken:m.leaseToken.trim()}:{}},{agentOsId:n,baseUrl:o})}catch(k){b={ok:!1,error:k.message}}l.push({worker:f,taskId:m.taskId,pid:m.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 fe(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 Lk=p(()=>{"use strict";$();Ge();Z();Ie();B();Ha();Ir();Qs()});async function hN(e){let t=me(e.baseUrl),r=await ye(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 fe(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 yN=p(()=>{"use strict";$();Ge()});import _8 from"node:path";async function kN(e,t){let r=se(e),n=String(t.agentOsId||"");if(!n)return[];let o=[];for(let s of Object.keys(r.workers||{})){let i=K(_8.join(q(r.id),"workers",U(s),"worker.json"),void 0);if(!i?.dispatched||!i.taskId)continue;let a=ce(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 hN({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,ne(r.id,i)),o.push({worker:s,phase:"heartbeat_blocker",ok:l.ok})}return o}var bN=p(()=>{"use strict";Ie();Z();B();yN()});function vN(e){let t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(t==="node_modules"||t.startsWith("node_modules/"))return!0;for(let r of Bk)if(t===r||t.startsWith(`${r}/`))return!0;return!1}var Bk,Uk=p(()=>{"use strict";Bk=[".next",".turbo","dist","build",".cache","node_modules/.cache"]});function Ct(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!vN(n)})}var wo=p(()=>{"use strict";Uk()});function So(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 hl(e){let t=e.gitAncestry?.relation;return t==="merged"||t==="synced"?Ct(e.changedFiles).length>0:!!(So(e.finalResult)||t==="ahead"||t==="diverged"||e.changedFiles.length>0&&e.finalResult)}var yl=p(()=>{"use strict";wo()});function kl(e){return e.status||(e.status=ce(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function Fk(e,t){if(e.status)return Ct(e.status.changedFiles).length>0;let r=t?t.porcelain(e.worktreePath):Wi(e.worktreePath);return Ct(r).length>0}function x8(e){let t=e.worker.completionSnapshot?.finalResult;return t??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Wk(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=x8(e);if(o&&!oe(r.pid)){let i=t?.gitStatusCache?t.gitStatusCache.porcelain(e.worktreePath):Wi(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"}:yc(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??So(s)};return e.status=u,u}return kl(e)}var fp=p(()=>{"use strict";_e();Ie();wo();yl();B()});function C8(e,t=Date.now(),r=gl){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 si(e,t=Date.now(),r=gl){return oe(e.pid)?!0:C8(e,t,r)}var mp=p(()=>{"use strict";Kn();oi();B()});function E8(e,t){return t?t.runTerminalCache.derive(e.run):bo(e.run)}function Vr(e,t=Date.now()){return si(e.worker,t)}function Kk(e,t){return jr.has(e.run.status)?!1:E8(e,t)!==null}function RN(e,t,r=Date.now()){if(Vr(e,r))return!0;if(jr.has(e.run.status)||Kk(e,t))return!1;let n=kl(e);return $e(n)?!1:!!Vr(e,r)}var $k=p(()=>{"use strict";Rn();Ie();fp();mp()});function wN(e,t){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(Vr(e))return!0;let n=t??kl(e);return!!(!$e(n)||hl(n)||Ct(n.changedFiles).length>0||ts({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:So(n.finalResult)}).blocked)}var SN=p(()=>{"use strict";Lc();fp();wo();$k();Ie();yl()});import{existsSync as xN,mkdirSync as A8,writeFileSync as _N}from"node:fs";import gp from"node:path";function CN(e,t,r){return gp.join(e,"salvage",U(t),U(r))}function EN(e){return xN(gp.join(CN(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function AN(e){let t=CN(e.harnessRoot,e.indexed.runId,e.indexed.workerName);A8(t,{recursive:!0});let r=gp.join(t,"salvage.patch"),n=!1;if(xN(e.indexed.worktreePath)){let s=re(e.indexed.worktreePath,["diff","HEAD"]),i=re(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(l=>l.trim()).join(`
|
|
189
|
-
`);a.trim()&&(
|
|
183
|
+
`)}})}write(t,r){if(!t.destroyed)try{t.write(Xh(r))}catch{}}async handleLine(t,r){let n=Qh(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(!Fs(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 ld({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 uk(){return MO}var MO,LO=p(()=>{"use strict";MO={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 BO=p(()=>{"use strict";Lr()});var UO=p(()=>{"use strict";DO();LO();Lr();cd();BO();Ny();ck()});import{existsSync as AX,mkdirSync as IX}from"node:fs";import ei from"node:path";async function FO(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=F(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||Mr,model:t.model,rule:t.routingRule||"explicit:spawn",requestedModel:t.requestedModel??t.model}:gd({explicitModel:t.model,explicitProvider:t.provider,explicitProviderIsOperatorOverride:!!t.provider?.trim(),configuredProvider:A().workerProvider}),s=wI(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}=ke(),l=ei.join(J(e.id),"workers",n);IX(l,{recursive:!0});let c=ei.join(a,e.id,n),u=t.repairTargetBranch?.trim()||void 0,d=u||t.branch||`agent/${e.id}/${n}`;if(AX(c))throw new Error(`worktree path already exists: ${c}`);if(de(e.repo,["fetch","origin","--prune"],{allowFailure:!0}),u)EO(e.repo,c,u);else{let x=fI({baseCommit:e.baseCommit,base:e.base,verifyRef:V=>de(e.repo,["rev-parse","--verify","--quiet",`${V}^{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=de(e.repo,["rev-parse",x.ref],{allowFailure:!0}).trim()||x.ref,Qe(e)),de(e.repo,["worktree","add","-b",d,c,e.baseCommit],{throwError:!0})}let f=ei.join(l,"stdout.jsonl"),m=ei.join(l,"stderr.log"),g=ei.join(l,"heartbeat.jsonl"),h=bI({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)}),k=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 y=Cd({title:t.taskTitle,personaSlug:t.personaSlug,parentTaskId:t.parentTaskId,executorRef:t.executorRef}),b,S,w,_,R=t.workerMcpToken?.trim();if(R&&Zh(s.name)&&Da()){let x=zn();x&&t.agentOsId&&t.taskId?(S={apiBaseUrl:x,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 T=vA(s.name);if(R&&T&&Da()){let x=zn();if(x&&t.agentOsId&&t.taskId){let V=ak({agentOsId:String(t.agentOsId),workerKey:l}),N=await il.start({address:V,apiBaseUrl:x,agentOsId:String(t.agentOsId),taskId:String(t.taskId),token:R,capabilities:t.workerMcpCapabilities??null,expiresAt:t.workerMcpExpiresAt??Date.now()+PX,workerPid:process.pid,identity:uk(),onRefusal:C=>console.error(`[supervisor] ${n}: worker tools refused a call (${C})`)});if(Ty(l,N),s.name==="codex"){let C=sP({workerDir:l,brokerSocketPath:V.socketPath});if(C.ok){let D=iP(C.codexHome,Ur());D.ok?(w=C.codexHome,b=w):(za(l),await gn(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 codex rejected the generated config (${D.detail}); spawning with the normal environment`))}else await gn(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${C.detail}`)}else if(s.name==="cursor"){let C=nP({worktreePath:c,brokerSocketPath:V.socketPath});C.ok?b=C.configPath:(await gn(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${C.detail}`))}else if(s.name==="gemini"&&Ws(_t())==="antigravity"){let C=pP({worktreePath:c,brokerSocketPath:V.socketPath});C.ok?b=C.configPath:(await gn(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${C.detail}`))}else if(s.name==="gemini"){let C=mP({workerDir:l,brokerSocketPath:V.socketPath});C.ok?(_=C.geminiCliHome,b=_):(await gn(l),console.error(`[supervisor] ${n}: worker tools skipped \u2014 ${C.detail}`))}else b=wA({workerDir:l,brokerSocketPath:V.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 W=t.taskId?vS(RS(e.id,String(t.taskId),n)):null,O;try{O=wS(W,()=>s.start({name:n,task:t.task,ownedPaths:t.ownedPaths,model:i,modelPinned:JA(o.rule),branch:d,worktreePath:c,workerDir:l,stdoutPath:f,stderrPath:m,heartbeatPath:g,prompt:h,reviewWorker:y,executionMode:t.executionMode??"write",...S?{workerToolGrant:S}:{},...w?{codexHome:w}:{},..._?{geminiCliHome:_}:{},...b?{mcpConfigPath:b,mcpAllowedTools:bA(t.workerMcpCapabilities)}:{}}))}catch(x){throw b&&(nd(l),Od(c),za(l),Dd(l),Nd(c),$s(l)),de(e.repo,["worktree","remove","--force",c],{allowFailure:!0}),de(e.repo,["branch","-D",d],{allowFailure:!0}),x}finally{k===void 0?delete process.env.KYNVER_HARNESS_TASK_ID:process.env.KYNVER_HARNESS_TASK_ID=k,v===void 0?delete process.env.KYNVER_HARNESS_AGENT_OS_ID:process.env.KYNVER_HARNESS_AGENT_OS_ID=v}let L=XA(O.model,i,s.defaultModel),M=A(),B=lt(process.env,M),G=Fe().runnerId,re=us({boxKind:B.boxKind,config:M,env:process.env}),I={name:n,runId:e.id,status:"running",pid:O.pid,model:L,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:B.boxKind,boxId:re,runtimeId:G,startedAt:new Date().toISOString(),...W?{oomRetryHeapMb:W}:{}};if(te(e.id,I),Oy(l,O.pid),e.workers={...e.workers||{},[n]:{workerDir:l,statusPath:ei.join(l,"worker.json")}},e.status="running",Qe(e),I.agentOsId&&I.taskId){let x;try{x=_O({runId:e.id,workerName:n,workerDir:l,agentOsId:I.agentOsId})}catch(V){let N=`completion sidecar failed to spawn: ${V.message}`;I.completionBlocker=N,te(e.id,I)}if(x)x.pid&&(I.completionSidecarPid=x.pid,te(e.id,I));else{let V=I.completionBlocker??"completion sidecar failed to spawn (CLI not found or spawn error)";I.completionBlocker=V,I.completionSidecarSpawnFailedAt=new Date().toISOString(),te(e.id,I),dI(e.id,I,V)}}return I}var PX,WO=p(()=>{"use strict";Ks();Ym();_e();Q();Q();mI();vI();U();Ju();so();SI();xO();CO();AO();Ke();ds();$();pt();Dy();My();fo();Fy();ho();By();UO();Pr();wy();PX=7200*1e3});function OX(e,t){let r=Be(t)?.trim();return r||Ne("KYNVER_RUNNER_TOKEN",e)||Ne("OPENCLAW_RUNNER_TOKEN",e)||null}function TX(e){let t=Ce()?.trim();return t||Ne("KYNVER_API_KEY",e)||Ne("KYNVER_RUNTIME_SECRET",e)||Ne("KYNVER_CRON_SECRET",e)||Ne("OPENCLAW_CRON_SECRET",e)||null}async function KO(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=OX(r,e.agentOsId),l=TX(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,k=g.status<500;return{reachable:k,authSource:c,endpoint:d,httpStatus:g.status,responseMs:h,probedAt:s,error:k?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 $O=p(()=>{"use strict";$();Tt()});function NX(e,t){let r=e.KYNVER_API_URL?.trim()||e.KYNVER_CRON_FIRE_BASE_URL?.trim()||t.apiBaseUrl?.trim()||null;return r?hr(r)??null:null}function DX(e,t){return(e.KYNVER_DEFAULT_REPO?.trim()||e.KYNVER_HARNESS_REPO?.trim()||t.defaultRepo?.trim()||null)??null}function MX(e,t,r){let n=e.KYNVER_HARNESS_ROOT?.trim()||t.harnessRoot?.trim()||null;return n||r||null}function HO(e,t={}){let r=t.env??process.env,n=t.nowMs??Date.now(),o=t.config??{},s=NX(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=DX(r,o),l=MX(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 jO=p(()=>{"use strict";yr()});var al=p(()=>{"use strict"});var ll=p(()=>{"use strict"});var pk=p(()=>{"use strict";$();ll()});var mk=p(()=>{"use strict";al()});import{mkdirSync as GO}from"node:fs";import{homedir as LX,tmpdir as qCe}from"node:os";import cp from"node:path";function JO(){let e=process.env.KYNVER_STATE_ROOT;return e?cp.resolve(e):cp.join(LX(),".kynver","state")}function up(){return cp.join(JO(),"plan-outbox")}function BX(){return cp.join(JO(),"plan-outbox-archive")}function qO(){let e=up(),t=BX();return GO(e,{recursive:!0}),GO(t,{recursive:!0}),{outboxDir:e,archiveDir:t}}var cl=p(()=>{"use strict"});function YO(){return{"planOutbox.storeFailures":ul.storeFailures,"planOutbox.corruptItemsSeen":ul.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":ul.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":ul.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":ul.halfArchivesCompleted}}var ZCe,ul,dl=p(()=>{"use strict";fn();Es();ZCe=600*1e3,ul={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0}});import{existsSync as WX,readFileSync as KX,renameSync as nEe,readdirSync as oEe,rmSync as sEe,writeFileSync as iEe,unlinkSync as aEe}from"node:fs";import zO from"node:path";function XO(e){if(!WX(e))return null;try{return JSON.parse(KX(e,"utf8"))}catch{return null}}function dp(e){let{outboxDir:t}=qO();return{jsonPath:zO.join(t,`${e.id}.json`),bodyPath:zO.join(t,e.bodyPath)}}var pl=p(()=>{"use strict";dl();al();mk();cl()});var QO=p(()=>{"use strict";al();ll();pk()});var gk=p(()=>{"use strict";pk();ll();mk();cl();dl();pl();QO()});import JX from"node:path";function hk(e){let t=JX.join(up(),`${e}.json`);return XO(t)}var ZO=p(()=>{"use strict";pl();dl();gk();cl()});function yk(e){let t=dp(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(`
|
|
184
|
+
`)}function kk(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 eT=p(()=>{"use strict";pl()});var tT=p(()=>{"use strict";al();gk();ZO();pl();eT();cl();ll()});function bk(e){return e?.trim()?e.trim():null}function rT(e,t){let r=bk(e.boxKind),n=bk(e.runnerId),o=bk(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,Qe(e),{ok:!0,stamped:!0}):{ok:!0}}var nT=p(()=>{"use strict";Q()});function oT(e=process.env){return qt(A(),e,{requireExplicitBoxKind:!0})}function sT(e){return[...e.errors,...e.warnings].join("; ")}var iT=p(()=>{"use strict";$();Vn()});async function fl(e){let t=`${e.baseUrl}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/tasks/${encodeURIComponent(e.taskId)}/release`,r;try{r=await fe(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 vk=p(()=>{"use strict";Je()});function ti(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 aT(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 Rk=p(()=>{"use strict"});function Rn(e){return typeof e.name=="string"&&e.name||typeof e.context=="string"&&e.context||typeof e.workflowName=="string"&&e.workflowName||"unknown check"}function cT(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 uT(e){let t=Array.isArray(e)?e:[],r=new Map;for(let n of t){let o=n&&typeof n=="object"?n:{},s=Rn(o),i=r.get(s);(!i||cT(o)>=cT(i))&&r.set(s,o)}return[...r.values()]}function qX(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 dT(e){let t=uT(e),r=[],n=[],o=[];for(let s of t){if(qX(s)){o.push(Rn(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&&lT.has(i))){if(i){n.push(`${Rn(s)}=${i}`);continue}if(!(l&&lT.has(l))){if(l&&l!=="PENDING"&&l!=="EXPECTED"){n.push(`${Rn(s)}=${l}`);continue}if(l==="PENDING"||l==="EXPECTED"){r.push(`${Rn(s)}=${l}`);continue}if(a&&a!=="COMPLETED"){r.push(`${Rn(s)}=${a}`);continue}r.push(`${Rn(s)}=PENDING`)}}}return{pending:r,failed:n,ignoredActions:o}}function pT(e){return uT(e).some(r=>{let n=Rn(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 fT(e,t){let r=e==="UNSTABLE"&&t.ignoredActions.length>0;return!YX.has(e)&&!r?`mergeStateStatus is ${e}`:null}var lT,YX,mT=p(()=>{"use strict";lT=new Set(["SUCCESS","SKIPPED","NEUTRAL"]);YX=new Set(["CLEAN","HAS_HOOKS"])});import{spawnSync as zX}from"node:child_process";function gT(){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=zX("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 hT=p(()=>{"use strict"});import{createHash as XX,randomUUID as QX}from"node:crypto";import{closeSync as yT,fsyncSync as kT,mkdirSync as ZX,openSync as bT,realpathSync as e3,writeFileSync as t3}from"node:fs";import wk from"node:path";function RT(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 vT(e,t,r,n){ZX(e,{recursive:!0,mode:448});let o=e3(e),s=bT(wk.join(o,`${t}.${r}.json`),"wx",384);try{t3(s,JSON.stringify({...n,phase:r},null,2)+`
|
|
185
|
+
`),kT(s)}finally{yT(s)}for(let i=o;;i=wk.dirname(i)){let a=bT(i,"r");try{kT(a)}catch(l){if(!r3(l))throw l}finally{yT(a)}if(i===wk.dirname(i))break}}function r3(e,t=process.platform){return t==="win32"&&e?.code==="EPERM"}function wT(e,t,r,n){let o={acceptedReview:n,agentOsId:e.agentOsId,taskId:e.taskId,runId:e.runId,workerName:e.workerName,leaseOwner:e.leaseOwner,leaseTokenSha256:XX("sha256").update(e.leaseToken).digest("hex")},s={...o,prUrl:t,invocationId:QX(),startedAt:new Date().toISOString(),finishedAt:null,headSha:r,mergedAt:null,mergeCommit:null,source:"daemon_land_pr",mergeInvoked:!1};return vT(e.receiptDir,s.invocationId,"pending",s),{finish(i){let a={...o,...i,invocationId:s.invocationId,startedAt:s.startedAt,finishedAt:new Date().toISOString()};return vT(e.receiptDir,s.invocationId,"finished",{...s,...a}),a}}}var ST=p(()=>{"use strict"});import{spawnSync as _T}from"node:child_process";function _k(e){return e?.trim()?["--repo",e.trim()]:[]}function xT(e){let t=/github\.com\/([^/]+)\/([^/]+)\/pull\/\d+/i.exec(e.trim());return t?`${t[1]}/${t[2]}`:null}function CT(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 a3(e){let t=typeof e.title=="string"?e.title.trim():"",r=typeof e.body=="string"?e.body.trim():"",n=s3.test(t)||i3.test(r),o=n3.test(r),s=o3.test(r);return n||o||s||e.vercelCheckSuccess===!0}function l3(e){if(!a3({title:e.title,body:e.body,vercelCheckSuccess:pT(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 c3(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=dT(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=fT(e.mergeStateStatus,t);if(r)throw new Error(`PR #${e.number} ${r}`)}function u3(e){c3(e),l3(e)}function d3(e){try{return u3(e),null}catch(t){return t instanceof Error?t.message:String(t)}}function p3(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 f3(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 m3(e,t){if(!t?.trim())return;let r=_T("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}`)&&_T("git",["worktree","remove","--force",o],{windowsHide:!0,cwd:e,encoding:"utf8"}))}}async function ET(e){let t=e.cwd??process.cwd(),r=e.exec??Ad,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(!ti(o)||o.prUrl!==n||o.agentOsId!==e.operation?.agentOsId||!e.revalidateAcceptedReview)return s();let i=gT();if(!i.configured)return{prUrl:n,outcome:"blocked",reason:i.reason};let a=CT(r,t,["pr","view",n,..._k(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=d3(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)||!RT(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(!ti(u)||!aT(o,u))return s();let d=wT(e.operation,n,o.headSha,o),f;try{f=r.gh(t,["pr","merge",c,..._k(e.repo),"--squash","--match-head-commit",o.headSha])}catch{let k=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:k}}let m=(k,v)=>d.finish({attribution:v,mergeInvoked:!0,headSha:a.headRefOid,mergedAt:k?.mergedAt??null,mergeCommit:k?.mergeCommit?.oid??null,mergeExitCode:f.status});if(f.status!==0){let k=Sk(r,t,c,e.repo);return k?{prUrl:k.url||a.url||n,outcome:"skipped",mergeCommit:k.mergeCommit?.oid??null,provenance:m(k,"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=Sk(r,t,c,e.repo);if(g||(g=Sk(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 k=f3(r,t,e.repo);p3(r,t,k,a.headRefName),m3(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 Sk(e,t,r,n){try{let o=CT(e,t,["pr","view",r,..._k(n),"--json","number,url,mergedAt,mergeCommit,state"]);return o.state==="MERGED"?o:null}catch{return null}}var n3,o3,s3,i3,AT=p(()=>{"use strict";Rk();Id();mT();hT();ST();n3=/^##\s*(test\s*plan|verification|test\s*evidence|verify)\b/im,o3=/typecheck|npm run (test|build|typecheck)|vitest|tsc\b|verify-pr-local|local verify|local-verify|tests? (pass|green)|build green|node --test/i,s3=/^docs[(:]/i,i3=/docs[- ]only|documentation only|no[- ]code change|no code changes|low[- ]risk|plan tracker only|markdown only/i});async function IT(e){let t=e.decision.task,r=e.decision.acceptedReview,n=String(t.prUrl??"");return ET({prUrl:n,cwd:e.cwd,repo:xT(n),exec:e.exec,operation:e.operation,acceptedReview:ti(r)?r:void 0,revalidateAcceptedReview:async()=>{let o=await fe(`${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&&ti(s.acceptedReview)?s.acceptedReview:null}})}var PT=p(()=>{"use strict";Je();Rk();AT()});async function OT(e){let t=await ye(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 fe(n,t,s,{agentOsId:e.agentOsId,baseUrl:e.baseUrl});return{ok:i.ok,status:i.status}}var TT=p(()=>{"use strict";$();Je()});function NT(){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(`
|
|
186
|
+
`)}var DT=p(()=>{"use strict"});function bo(e){return`${g3} ${e.trim()}`}function h3(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 y3(e){let{snapshot:t,leaseOwner:r,expectedLeaseToken:n,worker:o}=e;if(!t)return{ok:!1,error:bo("task lease snapshot missing after spawn"),detail:{taskId:o.taskId,leaseOwner:r,expectedLeaseToken:n}};if(t.status!=="running")return{ok:!1,error:bo(`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:bo(`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:bo(`leaseToken mismatch (board=${i||"null"}, expected=${n})`),detail:{taskId:t.taskId,boardLeaseToken:i||null,expectedLeaseToken:n},snapshot:t};let a=h3(o);return a?{ok:!1,error:bo(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:bo(`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:bo("AgentOS heartbeatAt missing after claim"),detail:{taskId:t.taskId},snapshot:t}}async function MT(e){let t=await yd({agentOsId:e.agentOsId,taskIds:[e.taskId],baseUrl:e.baseUrl,secret:e.secret});return y3({snapshot:t.get(e.taskId)??null,leaseOwner:e.leaseOwner,expectedLeaseToken:e.expectedLeaseToken,worker:e.worker})}var g3,LT=p(()=>{"use strict";py();g3="dispatch_start_readback_failed:"});function BT(e,t,r){t.pid&&ne(t.pid)&&(he(t.pid,"SIGTERM"),ne(t.pid)&&he(t.pid,"SIGKILL"));let n={...t,status:"failed",pid:void 0,completionBlocker:r,dispatchStartReadbackFailed:!0};return te(e,n),n}var UT=p(()=>{"use strict";U();Q()});function FT(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 WT(e){let t=`${e.baseUrl}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/tasks/${encodeURIComponent(e.taskId)}/review-head-reconcile`,r=await fe(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 KT=p(()=>{"use strict";Je()});function $T(e){let t=e.admissionExhaustion;return!t||typeof t!="object"?null:t}function HT(e){let t=e.dispatchSkipDrain;return!t||typeof t!="object"?null:t}function k3(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=v3(r.runtimeEnvelopeReceipt),h=r.runtimeEnvelopeReady===!0,k=r.memoryQualityCapture&&typeof r.memoryQualityCapture=="object"?r.memoryQualityCapture:null,v=typeof r.memoryQualityPromptMarkdown=="string"?r.memoryQualityPromptMarkdown:typeof k?.promptMarkdown=="string"?k.promptMarkdown:null,y=r.workerMcpToolGrant&&typeof r.workerMcpToolGrant=="object"?r.workerMcpToolGrant:null,b=y&&typeof y.token=="string"&&y.token.trim()?y.token.trim():null,S=b&&Array.isArray(y?.capabilities)?y.capabilities.filter(_=>typeof _=="string"&&_.trim().length>0):null,w=b&&typeof y?.exp=="number"&&Number.isFinite(y.exp)?y.exp*1e3:null;return{instructionPolicyMarkdown:n,instructionPolicyFingerprint:o,instructionPolicyEvidence:s,memoryQualityCapture:k,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:S,workerMcpExpiresAt:w}}function b3(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length?t:null}function v3(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 R3(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("",NT());let n=kk(e);if(n?.outboxId){let o=hk(n.outboxId);o?r.push("",yk(o)):r.push("","## Plan persistence risk","",`Unconfirmed AgentOS plan write (outboxId=${n.outboxId}).`)}return r.join(`
|
|
187
|
+
`)}function w3(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 ri(e){let t=e.pipeline===!0||e.pipeline==="true";try{let ue=function(){return N.filter(P=>P.started).length},H=function(P,E){Ea({runId:l.id,agentOsId:u,phase:P,startedCount:ue(),outcomeCount:N.length,cappedStarts:O,...E})},ie=function(){return N.some(P=>(typeof P.error=="string"?P.error:"").startsWith("dispatch_start_readback_failed:"))},Te=function(P){return P.landPrDispatch===!0?!0:P.task?.executor==="land_pr"};var r=ue,n=H,o=ie,s=Te;let i=oT();if(!i.ok||!i.identity){let P=sT(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=oe(String(Nt(String(e.run||""),"--run"))),c=rT(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(Nt(String(e.agentOsId||""),"--agent-os-id")),d=me(e.baseUrl?String(e.baseUrl):void 0),f=await ye(e.secret?String(e.secret):void 0,u,{baseUrl:d}),m=e.execute===!0||e.execute==="true",g=!m,h=Fe({runId:l.id}),k=Ha(l.id,h.runnerId),v=Z_(),y=v?vu(l.repo):null,b=new WeakMap;if(v&&m&&!y){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 S=e.diskPath?Qr({diskPath:String(e.diskPath)}):Qr({diskPath:l.repo}),w=await TE({runId:l.id,agentOsId:u,args:e}),_=w3(e),R=_.size>0,T=Number(e.maxStarts)>0?Math.floor(Number(e.maxStarts)):1,W=R?Math.min(T,_.size):T;if(e.reconcileStaleBlockers===!0||e.reconcileStaleBlockers==="true"){let P=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/lane-hygiene`;try{await fe(P,f,{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 O=g?W:Math.min(W,w.slotsAvailable);if(!g&&O<=0){let P={runId:l.id,agentOsId:u,dryRun:!1,skipped:!0,reason:w.reason??"no resource slots",resourceGate:w};if(t)return{ok:!0,...P};console.log(JSON.stringify(P,null,2));return}let L=ks(l.id),M=`${d}/api/agent-os/by-id/${encodeURIComponent(u)}/tasks/dispatch-next`,B=(P,E)=>({agentOsId:u,...E?{claimAuthorization:E}:{},dryRun:g,maxStarts:P,leaseOwner:k,leaseDurationMs:Number(e.leaseMs)>0?Math.floor(Number(e.leaseMs)):gy,runnerDiskGate:S,runnerResourceGate:w,activeHarnessWorkers:L,runnerPresence:h,harnessBoardSnapshot:sk(l.id),...e.lane?{lane:PE(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(j=>j.trim()).filter(Boolean)}:{}}),G=wE(),re=async P=>{let E=v&&y?nx(y):void 0,j=await fe(M,f,B(P,E),{agentOsId:u,baseUrl:d,timeoutMs:G})??{ok:!1,status:0,response:null},X=j.response;if(E&&Array.isArray(X?.result?.started))for(let ae of X.result.started)ae&&typeof ae=="object"&&b.set(ae,E.requestNonce);return{dispatch:j,result:X?.result}};g||Ea({runId:l.id,agentOsId:u,phase:"awaiting_dispatch_next",timeoutMs:G});let I=await re(R||g?O:1);if(!I.dispatch.ok||!I.result){let P=Oh(I.dispatch.response),E={runId:l.id,agentOsId:u,action:"dispatch",httpStatus:I.dispatch.status,response:I.dispatch.response,authRefreshed:I.dispatch.refreshedAuth===!0,authRefreshFailure:I.dispatch.authRefreshFailure,...P?{timeout:!0}:{}};if(P&&Ea({runId:l.id,agentOsId:u,phase:"timeout",timeout:!0,httpStatus:I.dispatch.status}),t)return{ok:!1,...E};console.log(JSON.stringify(E,null,2)),process.exit(1)}let x=I.result;if(g){let P=$T(x),E=HT(x),j={runId:l.id,agentOsId:u,dryRun:!0,wouldStart:x.started.map(X=>({taskId:X.task.id,title:X.task.title,reason:X.reason})),skipped:x.skipped.map(X=>({taskId:X.task.id,skipReason:X.skipReason,reason:X.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:E};if(t)return{ok:!0,...j};console.log(JSON.stringify(j,null,2));return}let V=rI(),N=[],C=[],D=Number(x.inspected)||0,z=!1;async function Y(P,E,j){let X=await fl({baseUrl:d,secret:f,agentOsId:u,taskId:String(P.id),leaseOwner:k,leaseToken:P.leaseToken?String(P.leaseToken):null,failureDetail:E});P.leaseToken&&Hs({taskId:String(P.id),leaseToken:String(P.leaseToken).trim()},Vy(E));let ae={taskId:P.id,started:!1,error:E,released:X.released,releaseResponse:X.releaseResponse,...j};return N.push(ae),H("outcome",{lastOutcome:ae}),!1}async function ge(P){let E=P.task,j=String(E.id);if(R&&!_.has(j))return Y(E,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[..._]});if(!(E.prUrl?String(E.prUrl):""))return Y(E,"land_pr task missing prUrl");try{let ae=await IT({decision:P,baseUrl:d,secret:f,agentOsId:u,cwd:l.repo,operation:{agentOsId:u,taskId:j,runId:l.id,workerName:`land-pr-${j}`,leaseOwner:k,leaseToken:typeof E.leaseToken=="string"?E.leaseToken:"",receiptDir:`${J(l.id)}/land-pr-operations`}}),Ot=await OT({baseUrl:d,secret:f,agentOsId:u,runId:l.id,task:E,report:ae});return Ot.ok?(N.push({taskId:j,started:!0,landPr:!0,outcome:ae.outcome,completionStatus:Ot.status}),!0):Y(E,`land_pr completion POST failed (HTTP ${Ot.status})`,{landPr:!0,outcome:ae.outcome})}catch(ae){return Y(E,ae.message)}}async function b$(P){let E="duplicate_dispatch_prevented: live local worker already owns this task",j=await fl({baseUrl:d,secret:f,agentOsId:u,taskId:String(P.id),leaseOwner:k,leaseToken:P.leaseToken?String(P.leaseToken):null,failureDetail:E});P.leaseToken&&Hs({taskId:String(P.id),leaseToken:String(P.leaseToken).trim()},Vy(E));let X={taskId:P.id,started:!1,error:E,alreadyRunning:!0,nonFatal:!0,released:j.released,releaseResponse:j.releaseResponse};return N.push(X),H("outcome",{lastOutcome:X}),!1}async function v$(P){let E=P.task,j=k3(P),X=String(E.id);if(R&&!_.has(X))return Y(E,"exact_target_mismatch: dispatch-next returned a different task than requested",{requestedTargetTaskIds:[..._]});let ae=b3(E.personaSlug);if(ae&&(!j?.personaInjectionReady||!j.personaMarkdown))return Y(E,`persona_injection_required: missing anchored context-envelope persona block for "${ae}"`);if(ae&&!j?.runtimeEnvelopeReady)return Y(E,`runtime_envelope_required: missing AgentRuntimeEnvelope launch receipt for persona "${ae}"`);if(aI(l.id,X))return b$(E);let Ot=Number(E.attempt)||1;if(Ot>V.maxTaskAttempts)return Y(E,`task attempt ${Ot} exceeds KYNVER_MAX_TASK_ATTEMPTS (${V.maxTaskAttempts})`);let Ln=E.leaseToken?String(E.leaseToken).trim():"";if(!Ln)return Y(E,"dispatch_start_failed: claimed task missing leaseToken \u2014 refusing local spawn");let Bn=F(`t-${E.id}-a${E.attempt}`),gr=gd({explicitModel:e.model?String(e.model):void 0,explicitProvider:e.provider?String(e.provider):void 0,explicitProviderIsOperatorOverride:!!e.provider,configuredProvider:A().workerProvider,task:DE(E)});AP({taskId:X,leaseToken:Ln,runId:l.id,workerName:Bn,provider:gr.provider??null});let Rm=ZA({task:E,routing:gr,explicitProvider:e.provider?String(e.provider):void 0,explicitModel:e.model?String(e.model):void 0});if(!Rm.ok)return Y(E,Rm.error??"model_routing_mismatch",{modelRoutingGuard:Rm});if(FT(E)){let st=await WT({agentOsId:u,taskId:X,baseUrl:d,secret:f});if(st&&st.dispatchable===!1)return Y(E,`pr_review_head_reconcile_blocked: ${st.reason??st.outcome??"stale PR head"}`,{headReconcile:st});if(st?.activeReviewTaskId&&st.activeReviewTaskId!==X)return Y(E,`pr_review_head_reconcile_retargeted: active review is ${st.activeReviewTaskId}`,{headReconcile:st})}let lc=zP(gr.provider);if(!lc.ok)return Y(E,`provider_quota_exhausted: ${lc.reason}`,{nonFatal:!0,providerQuotaPreflight:{provider:lc.provider,retryAt:lc.retryAtIso}});try{let st=E.planId?String(E.planId):void 0,cc=hI({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}),lw=KP({runId:l.id,workerName:Bn,maxSlots:w.maxConcurrentWorkers,diskActiveWorkers:tg()});if(!lw.admitted)return Y(E,`admission_refused: ${lw.reason}`,{nonFatal:!0});let uc=j?.workerMcpToken??null;if(uc&&Da()){let jo=HO({jobId:`dispatch:${String(E.id)}`,agentOsId:u,taskId:String(E.id)},{config:{agentOsId:u,apiBaseUrl:d}});if(!jo.ok)console.error(`[dispatch] worker tools skipped for task ${String(E.id)}: context hydration failed (${jo.code}: ${jo.detail}) \u2014 spawning without tools`),uc=null;else{let wm=await KO(jo.context);wm.reachable||(console.error(`[dispatch] worker tools skipped for task ${String(E.id)}: tool endpoint probe failed (${wm.error??`HTTP ${wm.httpStatus}`}) \u2014 spawning without tools`),uc=null)}}uI(l.id,String(E.id),{except:Bn});let Jt=await FO(l,{name:Bn,task:R3(E,u),ownedPaths:e.owned?String(e.owned).split(",").map(jo=>jo.trim()).filter(Boolean):[],model:gr.model,provider:gr.provider,routingRule:gr.rule,requestedModel:gr.requestedModel,agentOsId:u,taskId:String(E.id),planId:st,branch:cc?.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:cc?.targetPrUrl??(E.prUrl?String(E.prUrl):void 0),repairTargetPrUrl:cc?.targetPrUrl,repairTargetBranch:cc?.targetPrBranch??void 0,instructionPolicyMarkdown:j?.instructionPolicyMarkdown??null,instructionPolicyFingerprint:j?.instructionPolicyFingerprint??null,instructionPolicyEvidence:j?.instructionPolicyEvidence??null,memoryQualityCapture:j?.memoryQualityCapture??null,memoryQualityPromptMarkdown:j?.memoryQualityPromptMarkdown??null,personaMarkdown:j?.personaMarkdown??null,personaSlug:j?.personaSlug??ae,personaEvidence:j?.personaEvidence??null,contextEnvelopeMarkdown:j?.contextEnvelopeMarkdown??null,contextEnvelopeEvidence:j?.contextEnvelopeEvidence??null,runtimeEnvelopeMarkdown:j?.runtimeEnvelopeMarkdown??null,runtimeEnvelopeEvidence:j?.runtimeEnvelopeEvidence??null,workerMcpToken:uc,workerMcpCapabilities:j?.workerMcpCapabilities??null,workerMcpExpiresAt:j?.workerMcpExpiresAt??null,leaseOwner:k,leaseToken:Ln,dispatched:!0,executionMode:ku(E)}),dc=await MT({agentOsId:u,taskId:String(E.id),leaseOwner:k,expectedLeaseToken:Ln,worker:Jt,baseUrl:d,secret:f});if(!dc.ok)return BT(l.id,Jt,dc.error??"dispatch_start_readback_failed"),vn(l.id,Bn),Y(E,dc.error??"dispatch_start_readback_failed",{readback:dc.detail??null});Jt.leaseToken!==Ln&&(Jt.leaseToken=Ln,Jt.leaseOwner=k,te(l.id,Jt)),$d({taskId:X,leaseToken:Ln}),BP(l.id,Bn);let cw={taskId:E.id,started:!0,worker:Jt.name,pid:Jt.pid,branch:Jt.branch,model:Jt.model,provider:gr.provider,routingRule:gr.rule,instructionPolicyFingerprint:j?.instructionPolicyFingerprint??null,instructionPolicyRuleCount:Array.isArray(j?.instructionPolicyEvidence?.ruleSlugs)?j.instructionPolicyEvidence.ruleSlugs.length:null,personaSlug:j?.personaSlug??ae,personaOperatingRuleCount:j?.personaEvidence?.operatingRuleCount??null};return N.push(cw),H("worker_started",{lastOutcome:cw}),j?.instructionPolicyFingerprint&&console.error(`[dispatch] task ${X}: instruction policy injected fingerprint=${j.instructionPolicyFingerprint}`),j?.personaSlug&&console.error(`[dispatch] task ${X}: persona context injected slug=${j.personaSlug}`),j?.contextEnvelopeReady&&console.error(`[dispatch] task ${X}: context envelope injected anchor=${j.contextEnvelopeEvidence?.anchorTaskId??X}`),j?.runtimeEnvelopeReady&&console.error(`[dispatch] task ${X}: runtime envelope injected id=${j.runtimeEnvelopeEvidence?.envelopeId??"unknown"}`),!0}catch(st){return vn(l.id,Bn),Y(E,st.message)}}let vm=new Set;for(let P of NP(l.id))vm.add(P);async function nw(P){let E=P.task,j=String(E.id);if(vm.has(j))return Y(E,"dispatch_retry_loop_prevented: task already failed to start this tick");let X=v?ox({decision:P,leaseOwner:k,repoIdentity:y,requestNonce:b.get(P)??null}):null,ae=X&&!X.allow?await Y(E,`desktop_execution_policy_denied:${X.code}: ${X.reason}`,{desktopPolicyDenied:X.code,...X.code==="operation_not_approved"?{nonFatal:!0}:{}}):Te(P)?await ge(P):await v$(P);return ae||(vm.add(j),TP(j,l.id)),ae}for(let P of x.started)await nw(P);if(C.push(...x.skipped??[]),R)for(let P of C){let E=String(P.task.id);_.has(E)&&N.push({taskId:E,started:!1,error:`exact_target_not_started:${P.skipReason}`,skipReason:P.skipReason,detail:P.reason??null,requestedTargetTaskIds:[..._]})}for(;!R&&N.length<O;){if(ie()){let j={started:!1,error:"dispatch_circuit_breaker: start readback failed; stopping top-up for this tick",nonFatal:!0};N.push(j),H("circuit_breaker",{lastOutcome:j});break}let P=await re(1);if(!P.dispatch.ok||!P.result){let j=_E(P.dispatch.response),X=ue();z=j&&X>0;let ae=Oh(P.dispatch.response),Ot={started:!1,error:ae?"dispatch_next timed out during top-up":"dispatch_next request failed during top-up",httpStatus:P.dispatch.status,response:P.dispatch.response,...ae?{timeout:!0}:{},...z?{nonFatal:!0,partialTopUp:!0}:{}};N.push(Ot),H("top_up_failed",{partialTopUpInterrupted:z,lastOutcome:Ot});break}D+=Number(P.result.inspected)||0,C.push(...P.result.skipped??[]);let E=P.result.started??[];if(E.length===0)break;for(let j of E){if(N.length>=O)break;await nw(j)}}let ac=N.filter(P=>P.started).length,Xr=$T(x),Ho=HT(x),ow=ac===0&&(Xr?.capacityIdle===!0||Number(x.resourceGate?.slotsAvailable)>0);if(ow&&Xr?.summary){let P=Xr.skipReasonCounts?.retry_ceiling_exceeded??0,E=x.overAttemptIdleRecovery??Xr.overAttemptIdleRecovery,j=E?.attempted===!0?`; over_attempt_recovery minted=${E.minted??0} started=${E.started??0}`:P>0?"; over_attempt_recovery not attempted":"",X=Ho?`; dispatch_skip_drain scanned=${Ho.scanned??0} advanced=${Ho.advanced??0}`:"",ae=Xr.progressionReport?.summary?`; ${Xr.progressionReport.summary}`:"",Ot=Ho?.prLifecycleAttempt?.summary?`; ${Ho.prLifecycleAttempt.summary}`:"";console.error(`[dispatch] ${Xr.summary}${P>0?`; retry_ceiling_exceeded=${P}`:""}${j}${X}${ae}${Ot}`)}let sw={runId:l.id,agentOsId:u,dryRun:!1,leaseOwner:k,startedCount:ac,capacityIdle:ow,admissionExhaustion:Xr,dispatchSkipDrain:Ho,outcomes:N,skipped:C.map(P=>({taskId:P.task.id,skipReason:P.skipReason})),inspected:D,pagesScanned:x.pagesScanned??null,candidatesExhausted:x.candidatesExhausted??null,diskGate:x.diskGate,resourceGate:x.resourceGate,...z?{partialTopUpInterrupted:!0}:{},dispatchCallbackTimeoutMs:G},iw=P=>!P.started&&P.nonFatal!==!0,R$=N.some(iw),aw=z&&ac>0?!0:!R$;if(Ea({runId:l.id,agentOsId:u,phase:"complete",partial:z,startedCount:ac,ok:aw}),t)return{ok:aw,...sw};console.log(JSON.stringify(sw,null,2)),N.some(iw)&&process.exit(1)}catch(i){if(t)return{ok:!1,error:i.message};console.error(`run dispatch failed: ${i.message}`),process.exit(1)}}var gy,bd=p(()=>{"use strict";$();Ru();Je();SE();xE();OE();Gi();NE();is();Q();Q();ME();Ju();eI();nI();my();WO();Ks();$O();jO();pt();fu();Zs();U();tT();yy();ja();Pr();nT();iT();vk();qd();PT();TT();DT();LT();UT();Q();KT();Ag();js();ko();Gs();gy=3600*1e3});function ni(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 _3(e){let{maxStarts:t,...r}=e;return r}async function xk(e,t){if(t<=0)return{ok:!0,skipped:!0,reason:"no slots",maxStarts:0,startedCount:0};let r=_3(e);if(r.targetTaskId||r.targetTaskIds){let u=await ri({...r,execute:!0,pipeline:!0,maxStarts:String(t)});return{...typeof u=="object"&&u!==null?u:{},passes:{target:u},startedCount:ni(u)}}let n=Math.min(t,S3),o=Math.max(0,t-n),s=await ri({...r,execute:!0,pipeline:!0,lane:"review",maxStarts:String(n)}),i=ni(s),a=o+(n-i);if(a<=0)return{...typeof s=="object"&&s!==null?s:{},passes:{review:s},startedCount:i};let l=await ri({...r,execute:!0,pipeline:!0,maxStarts:String(a)}),c=ni(l);return{passes:{review:s,work:l},startedCount:i+c,ok:!0}}var S3,jT=p(()=>{"use strict";bd();S3=1});function VT(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 GT=p(()=>{"use strict"});function x3(e){let r=e.response?.dispatch;return r&&typeof r=="object"?r:null}function ml(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function C3(e){let t=Number(process.env[e]);return!Number.isFinite(t)||t<=0?null:Math.floor(t)}function JT(e,t){let r=x3(t),n=ml(r?.recommendedMaxStarts),o=ml(r?.actionableReady),s=ml(r?.queuedTasks),i=ml(r?.boardAdvancedThisTick)??0,a=ml(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=C3("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 qT=p(()=>{"use strict"});import E3 from"node:path";function vo(e){let t=Mt(e);if(t.length===0)return"failed";let r=!1,n=!1,o=!1,s=!1;for(let i of t){let a=K(E3.join(J(e.id),"workers",F(i),"worker.json"),void 0);if(!a)continue;let l=le(a,{base:e.base,baseCommit:e.baseCommit});if(l.alive&&!l.finalResult){r=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),eg(l)&&(s=!0),l.finalResult&&l.attention.state==="done"&&(n=!0)}return r||o||s?null:n?"completed":"failed"}function gl(){let e=[];for(let t of xe()){if(!A3.has(t.status))continue;let r=vo(t);if(!r||r===t.status)continue;let n=t.status;t.status=r,Qe(t),e.push({runId:t.id,from:n,to:r})}return e}var A3,Vr,wn=p(()=>{"use strict";Q();Zo();Ie();U();A3=new Set(["running","dispatching","pending","queued","needs_attention"]),Vr=new Set(["completed","failed","cancelled","done"])});import $t from"node:path";function pp(e){return e.includes(I3)}function Ck(e,t){return $t.join(ut(Ue(e)),F(t))}function Sn(e,t,r){return $t.join(Ck(e,t),"workers",F(r))}function YT(e,t,r){let n=Ue(e);return $t.join(n,"runs","runs",F(t),"workers",F(r))}function Ek(){return["stdout.jsonl","stderr.log","heartbeat.jsonl","last-status.json","auto-complete.log","worker.json"]}function Ro(e){return{workerJsonPath:$t.join(e,"worker.json"),stdoutPath:$t.join(e,"stdout.jsonl"),stderrPath:$t.join(e,"stderr.log"),heartbeatPath:$t.join(e,"heartbeat.jsonl"),lastStatusPath:$t.join(e,"last-status.json")}}function zT(e){let t=Ro(Sn(e.harnessRoot,e.runId,e.workerName)).workerJsonPath;return e.statusPath&&!pp(e.statusPath)?e.statusPath:t}var I3,Ak=p(()=>{"use strict";Lt();U();I3=`${$t.sep}runs${$t.sep}runs${$t.sep}`});import{existsSync as P3,readFileSync as O3,readdirSync as T3,statSync as N3,writeFileSync as D3}from"node:fs";import M3 from"node:path";function K3(e,t=[]){if(!e)return e;let r=e,n=[...new Set(t.map(o=>o?.trim()).filter(o=>!!o&&o.length>=B3))].sort((o,s)=>s.length-o.length);for(let o of n){r.includes(o)&&(r=r.split(o).join(gt));let s=JSON.stringify(o).slice(1,-1);s!==o&&r.includes(s)&&(r=r.split(s).join(gt))}for(let[o,s]of L3)r=r.replace(o,s);return r}function XT(e=process.env,t=[]){let r=[];for(let[n,o]of Object.entries(e))o&&U3.test(n)&&r.push(o);for(let n of t)try{let o=n();o&&r.push(o)}catch{}return r}function QT(e,t=0){if(t>3||!P3(e))return[];let r=[];for(let n of T3(e,{withFileTypes:!0})){let o=M3.join(e,n.name);n.isDirectory()?r.push(...QT(o,t+1)):n.isFile()&&F3.test(n.name)&&r.push(o)}return r}function ZT(e,t=[]){let r={masked:[],clean:0,failed:[]},n;try{n=QT(e)}catch{return r}for(let o of n)try{if(N3(o).size>W3){r.failed.push(o);continue}let s=O3(o,"utf8"),i=K3(s,t);if(i===s){r.clean+=1;continue}D3(o,i,"utf8"),r.masked.push(o)}catch{r.failed.push(o)}return r}var gt,Ik,L3,B3,U3,F3,W3,eN=p(()=>{"use strict";gt="<redacted>",Ik=`[^\\s"'\\\\,}\\]]`,L3=[[new RegExp(`\\b(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|rediss):\\/\\/${Ik}+`,"gi"),gt],[new RegExp(`\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s/@:"']+:[^\\s/@"']+@${Ik}+`,"gi"),gt],[/\bkynver_u_[A-Za-z0-9_-]+/g,gt],[/\bkyn_[A-Za-z0-9]{12,}/g,gt],[/\bsk-ant-[A-Za-z0-9_-]+/g,gt],[/\bsk-[A-Za-z0-9_-]{8,}/g,gt],[/\bkr[a-z]1\.[A-Za-z0-9._~+/=-]{8,}/g,gt],[/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}/g,gt],[/\bgithub_pat_[A-Za-z0-9_]{16,}/g,gt],[/\b(Bearer|Basic)\s+(?!<redacted>)[A-Za-z0-9._~+/=-]{8,}/gi,`$1 ${gt}`],[new RegExp(`(\\b(?:[A-Z0-9_]*(?:API_KEY|APIKEY|TOKEN|SECRET|PASSWORD)|DATABASE_URL|KYNVER_DATABASE_URL)\\s*=\\s*)(?!<redacted>)${Ik}+`,"g"),`$1${gt}`]],B3=12,U3=/(?:API_KEY|APIKEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)$/i,F3=/(?:\.jsonl|\.log|\.txt|^stdout.*|^stderr.*)$/i,W3=256*1024*1024});import{existsSync as _n,mkdirSync as $3,readdirSync as rN,renameSync as H3,statSync as Pk}from"node:fs";import ve from"node:path";function nN(e,t){let r=ve.resolve(e),n=ve.resolve(ut(t)),o=ve.relative(n,r);return o!==".."&&!o.startsWith("..")&&!ve.isAbsolute(o)}function Ok(e){if(!_n(e))return[];try{return rN(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&t.name!=="runs").map(t=>t.name)}catch{return[]}}function Tk(e){let t=ve.join(e,"workers");if(!_n(t))return[];try{return rN(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}function oN(e){return ve.join(e,"archived-workers")}function V3(e,t){let r=ve.join(oN(e),F(t));return _n(r)?`${r}-${Date.now()}`:r}function tN(e,t,r){if(!_n(e))return!1;try{let n=t-Pk(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<r}catch{return!1}}function sN(e,t=Date.now(),r=hl){if(!_n(e))return!1;let n=Ro(e),o=K(n.workerJsonPath,void 0);if(o?.status==="running"&&ne(o.pid))return!0;let s=Me(n.heartbeatPath);if(s.lastHeartbeatAt){let i=t-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<r)return!0}return!!(tN(n.stdoutPath,t,r)||tN(n.heartbeatPath,t,r))}function G3(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-Pk(ve.join(e,"worker.json")).mtimeMs}catch{return 0}}function J3(e,t,r,n){if(sN(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=G3(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 oi(e,t=Date.now(),r=hl){for(let n of Tk(e))if(sN(ve.join(e,"workers",n),t,r))return!0;return!1}function q3(){let t=Ra()?.repo??"",r="unknown";if(t)try{let n=de(t,["rev-parse","origin/main"],{allowFailure:!0}).trim();n&&(r=n)}catch{}return{repo:t,base:"origin/main",baseCommit:r}}function Y3(e,t){let r=ve.join(ut(e),F(t));if(!_n(r))return null;let n=Tk(r);if(n.length===0)return null;let o;try{o=Pk(r).birthtime.toISOString()}catch{o=new Date().toISOString()}let s={};for(let a of n){let l=Sn(e,t,a);s[a]={workerDir:l,statusPath:ve.join(l,"worker.json")}}let i=oi(r);return{id:t,name:t,...q3(),status:i?"running":"needs_attention",createdAt:o,workers:s}}function Nk(e){let t=Ue(e??vt()),r=ut(t),n=[];for(let o of Ok(r)){let s=ve.join(r,o,"run.json");if(_n(s)){n.push({runId:o,action:"skipped",reason:"run.json present"});continue}let i=Y3(t,o);if(!i){n.push({runId:o,action:"skipped",reason:"no worker dirs on disk"});continue}Qe(i),n.push({runId:o,action:"repaired_run_json",reason:oi(ve.join(r,o))?"synthesized run.json while worker artifacts still active":"synthesized run.json from orphan worker metadata dirs"})}return{runs:n}}function Dk(e,t={}){let r=Ue(e??vt()),n=ut(r),o=t.now??Date.now(),s=t.archiveAgeMs??j3,i=[],a=null,l=()=>a??=(t.knownSecrets??(()=>XT(process.env,[Ce,()=>Be()])))();Nk(r);for(let c of Ok(n)){let u=ve.join(n,c),d=ve.join(u,"run.json"),f=K(d,void 0);if(!f?.id)continue;let m=new Set([...Object.keys(f.workers||{}),...Tk(u)]),g=!1;for(let h of m){let k=ve.join(u,"workers",F(h)),v=ve.join(k,"worker.json"),y=K(v,void 0);if(!y){let w=ve.join(oN(u),F(h));if(_n(w)&&(f.workers[F(h)]||f.workers[h])){delete f.workers[F(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:w});continue}i.push({runId:f.id,worker:h,action:"skipped",reason:"worker.json missing"});continue}let b=J3(k,y,o,s);if(!b.eligible){i.push({runId:f.id,worker:h,action:"skipped",reason:b.reason});continue}let S=V3(u,h);$3(ve.dirname(S),{recursive:!0}),H3(k,S),ZT(S,l()),delete f.workers[F(h)],delete f.workers[h],g=!0,i.push({runId:f.id,worker:h,action:"archived",reason:b.reason,archivePath:S})}g&&Qe(f)}return{workers:i}}function iN(e,t=Date.now()){let r=new Set,n=ut(e);for(let o of Ok(n)){let s=ve.join(n,o);oi(s,t)&&r.add(`${e}\0${o}`)}return r}var hl,j3,si=p(()=>{"use strict";Is();_e();$n();Lt();Q();Ak();U();$();eN();hl=900*1e3,j3=3600*1e3});import{existsSync as xn,lstatSync as z3,readdirSync as X3,readlinkSync as Q3,renameSync as Mk,unlinkSync as Z3}from"node:fs";import nr from"node:path";function e8(e,t){let r=Ck(e,t),n;try{n=z3(r)}catch{return null}if(!n.isSymbolicLink())return null;let o=nr.resolve(nr.dirname(r),Q3(r));if(oi(o)||oi(r))return null;let s=`${r}.materialize-${Date.now()}`;return Mk(o,s),Z3(r),Mk(s,r),o}function t8(e){let t=[];for(let r of Ek()){let n=nr.join(e.fromDir,r),o=nr.join(e.toDir,r);!xn(n)||xn(o)||(Mk(n,o),t.push(r))}return t}function aN(e,t){let r=Ro(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 r8(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 n8(e){let t=Ro(e.canonicalDir),r=K(t.lastStatusPath,void 0),n=xn(t.stdoutPath),o=xn(t.heartbeatPath);if(!(n||o||r!=null))return null;let i=n?Hn(t.stdoutPath):{finalResult:null},a=o?Me(t.heartbeatPath):Me(""),l=br(a),c=r8({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:nr.join(ke().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}),aN(u,e.canonicalDir),u}function o8(e,t){let r=!1,n={...e.workers||{}};for(let[o,s]of Object.entries(n)){let i=Sn(t,e.id,o),a=nr.join(i,"worker.json");(pp(s.workerDir)||pp(s.statusPath)||s.workerDir!==i||s.statusPath!==a)&&(n[o]={workerDir:i,statusPath:a},r=!0)}return r&&(e.workers=n,Qe(e)),r}function s8(e){let t=[],r=Sn(e.harnessRoot,e.run.id,e.workerName),n=YT(e.harnessRoot,e.run.id,e.workerName),o=Ro(r),s=t8({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=zT({harnessRoot:e.harnessRoot,runId:e.run.id,workerName:e.workerName,statusPath:e.statusPath}),a=K(i,void 0);if(!a&&xn(o.workerJsonPath)&&(a=K(o.workerJsonPath,void 0)),!a){let l=n8({run:e.run,workerName:e.workerName,canonicalDir:r,harnessRoot:e.harnessRoot});if(l)return te(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=xn(r),u=Ek().some(d=>xn(nr.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:nr.join(ke().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 te(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 aN(a,r)?(a.reconciledAt=new Date().toISOString(),a.reconcileReason=a.reconcileReason??"repaired nested runs/runs path fields",te(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 i8(e,t){let r=nr.join(J(e.id),"workers");if(!xn(r))return[];let n=new Set(Object.keys(e.workers||{})),o=[];for(let s of X3(r,{withFileTypes:!0}))s.isDirectory()&&(n.has(s.name)||o.push(s.name));return o}function lN(){let{harnessRoot:e}=ke(),t=Nk(e),r=[];for(let n of xe()){let o=e8(e,n.id);o&&r.push({runId:n.id,worker:"*",action:"materialized_run_symlink",reason:`replaced symlink with real run dir (was ${o})`}),o8(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 i8(n,e))s.add(i),n.workers={...n.workers||{},[i]:{workerDir:Sn(e,n.id,i),statusPath:nr.join(Sn(e,n.id,i),"worker.json")}},Qe(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(...s8({run:n,workerName:i,harnessRoot:e,statusPath:a?.statusPath}))}}return{workers:r,runMetadataRetention:t}}var cN=p(()=>{"use strict";$n();zi();Ak();si();Q();U()});import{execFileSync as uN}from"node:child_process";import dN from"node:path";function Lk(e){let t=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return t?`https://github.com/${t[1]}/pull/${t[2]}`:null}function a8(e){let t=Lk(e)?.match(/\/pull\/(\d+)$/);if(!t)return null;let r=Number.parseInt(t[1],10);return Number.isFinite(r)?r:null}function l8(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function c8(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 u8(e){let t=null;if(typeof e=="string"?t=ns(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=Lk(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 d8(e){try{let n=uN("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=uN("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:Lk(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 p8(e){let t=Me(e.heartbeatPath);return e.completionSnapshot?.finalResult??br(t)}function f8(e){let t=new Map,r=J(e.id);for(let n of Mt(e)){let o=K(dN.join(r,"workers",F(n),"worker.json"),void 0);if(o)for(let s of u8(p8(o))){let i=a8(s.prUrl);i!=null&&!t.has(i)&&t.set(i,s)}}return t}function m8(e,t){let r=Me(e.heartbeatPath),n=[e.name,e.repairTargetPrUrl,e.taskPrUrl,e.branch,r.lastHeartbeatSummary,l8(t)].filter(Boolean).join(`
|
|
188
|
+
`);return c8(n)}function g8(e){return e.localOnly===!0&&!e.taskId&&!e.agentOsId}function Bk(e={}){let t=e.lookupPr??d8,r=[],n=new Map;for(let o of xe()){let s=f8(o),i=J(o.id);for(let a of Mt(o)){let l=dN.join(i,"workers",F(a),"worker.json"),c=K(l,void 0);if(!c||!g8(c))continue;let u=le(c,{base:o.base,baseCommit:o.baseCommit});if(u.attention.state!=="needs_attention")continue;let d=null;for(let m of m8(c,u.finalResult)){if(d=s.get(m)??null,!d){let g=o.repo||c.worktreePath,h=`${g}#${m}`,k=n.has(h)?n.get(h)??null:t({repoDir:g,prNumber:m});n.has(h)||n.set(h,k),k&&(k.state==="MERGED"||k.mergedAt)&&(d={prUrl:k.prUrl,mergeCommit:k.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",te(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 pN=p(()=>{"use strict";$n();Uc();Ie();Q();Zo();U()});import h8 from"node:path";function k8(){return process.env.KYNVER_NO_STALE_CLEANUP==="1"}function fN(e,t){let r=Ud({worker:e,status:t}),n=r?Fd(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 b8(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 Uk(){let e=lN();if(k8()){let s=Bk(),i=Dk();return{workers:[],finalizedRuns:gl(),metadataReconcile:e,localPrAttentionReconcile:s,terminalWorkerArchive:i}}let t=[],r=Date.now();for(let s of xe())for(let i of Mt(s)){let a=h8.join(J(s.id),"workers",F(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=le(l,{base:s.base,baseCommit:s.baseCommit});if(c.finalResult){if(l.status==="running"){let u=fN(l,c);l.status=u.nextStatus,l.reconciledAt=new Date().toISOString(),l.reconcileReason=u.reason,l.stopClass="finished",te(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=fN(l,c);l.status=u.nextStatus,l.reconciledAt=new Date().toISOString(),l.reconcileReason=u.reason,b8(l,c),te(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&&ne(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>y8,m=Number.isFinite(d)&&r-d>Zm;if(f&&m){he(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}`,te(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=Bk(),o=Dk();return{workers:t,finalizedRuns:gl(),metadataReconcile:e,localPrAttentionReconcile:n,terminalWorkerArchive:o}}var y8,Fk=p(()=>{"use strict";wn();Q();Zo();Wy();Ie();U();cN();pN();si();y8=900*1e3});import{readdirSync as v8,readFileSync as R8}from"node:fs";function C8(e){if(process.platform!=="linux"||!e.trim())return null;let t=[];try{t=v8("/proc")}catch{return null}for(let r of t)if(/^\d+$/.test(r)&&Number(r)!==process.pid)try{if(R8(`/proc/${r}/cmdline`,"utf8").replace(/\0/g," ").includes(e))return Number(r)}catch{}return null}async function mN(e){let t=$r(),r={mode:t,scanned:0,outcomes:[]};if(t!=="enforce")return r;let n=pe();if(!n)return r;let o=e.nowMs??Date.now(),s=e.strandedAfterMs??S8,i=e.findOrphanPid??C8,a=[],l;try{l=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-_8).toISOString(),limit:x8})}catch{return wo.recoveryStoreFailures+=1,r}for(let c of l){let u=c.idempotencyKey.slice(w8.length),d=u.split(":")[0]??"",f=u.slice(d.length+1);if(!(!d||!f))try{let m=Date.parse(c.recordedAt);if(!Number.isFinite(m)||o-m<s||n.getOperationReceipt(`dispatch:spawned:${u}`)||n.getOperationReceipt(`dispatch:released:${u}`))continue;let g=Xa(f);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${d}:`,limit:10}).some(w=>{if(g===null)return!0;let _=Xa(w.idempotencyKey.slice(`dispatch:completion-acked:${d}:`.length));return _===null||_>=g}))continue;let v={};try{v=c.resultJson?JSON.parse(c.resultJson):{}}catch{v={}}let y=v.runId??null,b=v.workerName??null;if(y&&b&&e.hasLiveWorker({runId:y,workerName:b})){$d({taskId:d,leaseToken:f}),a.push({taskId:d,leaseToken:f,runId:y,workerName:b,action:"finalized_late"});continue}if(y&&b){let w=e.worktreePathFor({runId:y,workerName:b}),_=w?i(w):null;if(_!==null){wo.recoveryDeferredOrphans+=1,a.push({taskId:d,leaseToken:f,runId:y,workerName:b,action:"deferred_orphan",detail:`live pid ${_} references ${w}`});continue}}if(!y){a.push({taskId:d,leaseToken:f,runId:y,workerName:b,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let S=await e.releaseClaim({taskId:d,leaseToken:f,runId:y});S.released?(Hs({taskId:d,leaseToken:f},"restart_recovery"),b&&(Za(y,b),vn(y,b)),wo.recoveredStrandedClaims+=1,a.push({taskId:d,leaseToken:f,runId:y,workerName:b,action:"released"})):S.transportError?a.push({taskId:d,leaseToken:f,runId:y,workerName:b,action:"deferred_transport",detail:S.detail}):(Hs({taskId:d,leaseToken:f},"restart_recovery_refused"),a.push({taskId:d,leaseToken:f,runId:y,workerName:b,action:"release_refused",detail:S.detail}))}catch{wo.recoveryStoreFailures+=1}}return{mode:t,scanned:l.length,outcomes:a}}function gN(){return{"dispatchReceipts.recoveredStrandedClaims":wo.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":wo.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":wo.recoveryStoreFailures}}var w8,S8,_8,x8,wo,Wk=p(()=>{"use strict";fn();js();ko();Gs();w8="dispatch:claim:",S8=900*1e3,_8=10080*60*1e3,x8=200,wo={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0}});import E8 from"node:path";async function yN(e){if(hN||$r()!=="enforce")return null;hN=!0;try{let t=Fe().runnerId,r=await mN({hasLiveWorker:e.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>E8.join(ke().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await fl({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 hN,kN=p(()=>{"use strict";Q();ja();Pr();vk();Wk();js();hN=!1});import A8 from"node:os";function bN(e,t={}){let r=A(),n=(t.boxKind??Dt(r)).trim().toLowerCase()||"forge",o=t.hostLabel??A8.hostname();return{boxId:us({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:zC()}}var vN=p(()=>{"use strict";$();Ke();ds();Bu()});import I8 from"node:path";async function fp(e){let t=e.pipeline===!0||e.pipeline==="true";try{let r=oe(String(Nt(String(e.run||""),"--run"))),n=String(Nt(String(e.agentOsId||""),"--agent-os-id")),o=me(e.baseUrl?String(e.baseUrl):void 0),s=await ye(e.secret?String(e.secret):void 0,n,{baseUrl:o}),i=Fe({runId:r.id}).runnerId,a=await RO({run:r.id,agentOsId:n,...e},"run_sweep"),l=[];for(let f of Object.keys(r.workers||{})){let m=K(I8.join(J(r.id),"workers",F(f),"worker.json"),void 0);if(!m||!m.dispatched||!m.taskId)continue;let g=le(m);if(g.alive||g.finalResult||m.completionReportedAt)continue;try{let y=await Qs({run:r.id,name:f,agentOsId:n,...e.baseUrl?{baseUrl:String(e.baseUrl)}:{},...e.secret?{secret:String(e.secret)}:{}});if(y.ok&&!y.skipped){l.push({worker:f,taskId:m.taskId,pid:m.pid,released:!1,deathReported:!0,stopClass:g.stopClass??null});continue}}catch{}let h=hd({runId:r.id,workerLeaseOwner:m.leaseOwner??null,runnerId:i}),k=`${o}/api/agent-os/by-id/${encodeURIComponent(n)}/tasks/${encodeURIComponent(String(m.taskId))}/release`,v;try{v=await fe(k,s,{agentOsId:n,leaseOwner:h,...m.leaseToken?.trim()?{leaseToken:m.leaseToken.trim()}:{}},{agentOsId:n,baseUrl:o})}catch(y){v={ok:!1,error:y.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 fe(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 Kk=p(()=>{"use strict";$();Je();Q();Ie();U();ja();Pr();Zs()});async function RN(e){let t=me(e.baseUrl),r=await ye(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 fe(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 wN=p(()=>{"use strict";$();Je()});import P8 from"node:path";async function SN(e,t){let r=oe(e),n=String(t.agentOsId||"");if(!n)return[];let o=[];for(let s of Object.keys(r.workers||{})){let i=K(P8.join(J(r.id),"workers",F(s),"worker.json"),void 0);if(!i?.dispatched||!i.taskId)continue;let a=le(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 RN({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,te(r.id,i)),o.push({worker:s,phase:"heartbeat_blocker",ok:l.ok})}return o}var _N=p(()=>{"use strict";Ie();Q();U();wN()});function xN(e){let t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(t==="node_modules"||t.startsWith("node_modules/"))return!0;for(let r of $k)if(t===r||t.startsWith(`${r}/`))return!0;return!1}var $k,Hk=p(()=>{"use strict";$k=[".next",".turbo","dist","build",".cache","node_modules/.cache"]});function Et(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!xN(n)})}var So=p(()=>{"use strict";Hk()});function _o(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 yl(e){let t=e.gitAncestry?.relation;return t==="merged"||t==="synced"?Et(e.changedFiles).length>0:!!(_o(e.finalResult)||t==="ahead"||t==="diverged"||e.changedFiles.length>0&&e.finalResult)}var kl=p(()=>{"use strict";So()});function bl(e){return e.status||(e.status=le(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function jk(e,t){if(e.status)return Et(e.status.changedFiles).length>0;let r=t?t.porcelain(e.worktreePath):Ki(e.worktreePath);return Et(r).length>0}function O8(e){let t=e.worker.completionSnapshot?.finalResult;return t??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Vk(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=O8(e);if(o&&!ne(r.pid)){let i=t?.gitStatusCache?t.gitStatusCache.porcelain(e.worktreePath):Ki(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"}:kc(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??_o(s)};return e.status=u,u}return bl(e)}var mp=p(()=>{"use strict";_e();Ie();So();kl();U()});function T8(e,t=Date.now(),r=hl){let n=Me(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=t-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<r}function ii(e,t=Date.now(),r=hl){return ne(e.pid)?!0:T8(e,t,r)}var gp=p(()=>{"use strict";$n();si();U()});function N8(e,t){return t?t.runTerminalCache.derive(e.run):vo(e.run)}function Gr(e,t=Date.now()){return ii(e.worker,t)}function Gk(e,t){return Vr.has(e.run.status)?!1:N8(e,t)!==null}function CN(e,t,r=Date.now()){if(Gr(e,r))return!0;if(Vr.has(e.run.status)||Gk(e,t))return!1;let n=bl(e);return He(n)?!1:!!Gr(e,r)}var Jk=p(()=>{"use strict";wn();Ie();mp();gp()});function EN(e,t){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(Gr(e))return!0;let n=t??bl(e);return!!(!He(n)||yl(n)||Et(n.changedFiles).length>0||rs({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:_o(n.finalResult)}).blocked)}var AN=p(()=>{"use strict";Bc();mp();So();Jk();Ie();kl()});import{existsSync as PN,mkdirSync as D8,writeFileSync as IN}from"node:fs";import hp from"node:path";function ON(e,t,r){return hp.join(e,"salvage",F(t),F(r))}function TN(e){return PN(hp.join(ON(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function NN(e){let t=ON(e.harnessRoot,e.indexed.runId,e.indexed.workerName);D8(t,{recursive:!0});let r=hp.join(t,"salvage.patch"),n=!1;if(PN(e.indexed.worktreePath)){let s=ee(e.indexed.worktreePath,["diff","HEAD"]),i=ee(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(l=>l.trim()).join(`
|
|
189
|
+
`);a.trim()&&(IN(r,a.endsWith(`
|
|
190
190
|
`)?a:`${a}
|
|
191
|
-
`),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
|
|
192
|
-
`),o}var IN=p(()=>{"use strict";_e();B()});import hp from"node:path";function P8(e){e.writeSalvageEvidence&&I8.has(e.skipReason)&&(Vr(e.indexed,e.now)||EN({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})||AN({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}))}function O8(e){let{indexed:t,worktreesAgeMs:r,terminalWorktreesAgeMs:n}=e;return t&&(jr.has(t.run.status)||e.liveness&&Kk(t,e.liveness)||e.liveness&&$e(Wk(t,e.liveness))&&!Vr(t))?n:r}function T8(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:O8(e)}function N8(e,t){if(e.harnessRoot?.trim())return hp.resolve(e.harnessRoot);let r=t.worker.workerDir;if(!r)return null;let n=`${hp.sep}runs${hp.sep}`,o=r.indexOf(n);return o<0?null:r.slice(0,o+n.length-1)}function PN(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=T8(e);if(n<=0&&!r&&l<=0)return"worktrees_disabled";if(l>0&&o<l)return"below_age_threshold";if(Vr(t,a))return"active_worker";let c=Wk(t,e.liveness),u=N8(e,t),d=g=>{if(u)try{P8({indexed:t,harnessRoot:u,skipReason:g,status:c,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})}catch{}return g};if(wN(t,c)){let g=d("completion_blocked");if(g)return g}if(Fk(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(RN(t,e.liveness,a)||!$e(c))return"run_still_active";if(hl(c)){let g=d("pr_or_unmerged_commits");if(g)return g}if(Ct(c.changedFiles).length>0){let g=d("dirty_worktree");if(g)return g}if(ts({finalResult:c.finalResult,changedFiles:c.changedFiles,gitAncestry:c.gitAncestry,prUrl:So(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 Hk(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(hp.resolve(o))||t&&Vr(t)?"active_worker":t&&Fk(t,e.gitStatusCache)?"dirty_worktree":null}function ON(e){return Hk(e)}var I8,TN=p(()=>{"use strict";Lc();fp();Ie();Rn();$k();SN();IN();wo();yl();wo();yl();I8=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"])});var yp=p(()=>{"use strict"});function DN(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)NN.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||NN.has(s.skipReason)&&o(s.path,s.skipReason);return r}var NN,MN=p(()=>{"use strict";yp();NN=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"])});import LN from"node:path";function M8(e,t){return si(e,t)}function BN(e,t=Date.now()){let r=new Set,n=new Set;for(let o of e){for(let s of du(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let l=K(LN.join(la(o,s.id),"workers",U(a),"worker.json"),void 0);if(!l?.worktreePath)continue;let c=LN.resolve(l.worktreePath);M8(l,t)&&(i=!0,r.add(c))}i&&n.add(`${o}\0${s.id}`)}for(let s of tN(o))n.add(s)}return{activeWorktreePaths:r,liveRunKeys:n}}function UN(e,t,r,n){return r?n.has(`${t}\0${r}`):!1}var jk=p(()=>{"use strict";Z();Mt();oi();mp();B()});import{existsSync as FN,readdirSync as WN,statSync as L8}from"node:fs";import KN from"node:path";function B8(e,t){try{let r=L8(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function U8(e,t){let r=KN.join(e,"runs",t,"run.json");return FN(r)?K(r,null):null}function $N(e){try{return WN(e).length===0}catch{return!1}}function HN(e){let{harnessRoot:t,runId:r,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(UN(n,t,r,i.liveRunKeys)||!$N(n))return"run_still_active";let a=U8(t,r);return a&&!jr.has(a.status)&&!bo(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function jN(e){if(!FN(e.worktreesDir))return[];let t=[],r;try{r=WN(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=KN.join(e.worktreesDir,o);$N(s)&&t.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:B8(s,e.now)})}return t}var VN=p(()=>{"use strict";jk();Rn();B()});import{execFileSync as F8}from"node:child_process";import{existsSync as GN,readdirSync as W8,statSync as K8}from"node:fs";import $8 from"node:path";function j8(e,t=H8){if(!GN(e))return 0;try{let n=F8("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 Gr(e,t=5e4){if(!GN(e))return 0;let r=j8(e);if(r!==null)return r;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=W8(i)}catch{continue}for(let l of a){if(o++>t)return null;let c=$8.join(i,l),u;try{u=K8(c)}catch{continue}u.isDirectory()?s.push(c):n+=u.size}}return n}var H8,bl=p(()=>{"use strict";H8=2500});import{lstatSync as V8,readdirSync as G8}from"node:fs";function JN(e){try{let t=V8(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 qN(e,t=32){let r=JN(e);if(!r)return!1;if(r.foreign)return!0;try{let n=G8(e),o=0;for(let s of n){if(o>=t)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=JN(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}var YN=p(()=>{"use strict"});import Et from"node:path";function zN(e,t,r,n){let o=Et.resolve(e),s=`${Et.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=Et.relative(r,i);if(a.startsWith("..")||Et.isAbsolute(a))return"path_outside_harness";let l=a.split(Et.sep);return l.length<3||l[l.length-1]!==n||!o.startsWith(Et.resolve(t))?"path_outside_harness":null}function kp(e,t,r){return zN(e,t,r,"node_modules")}function bp(e,t,r){return zN(e,t,r,".next")}function vp(e,t,r){let n=Et.resolve(e),o=Et.relative(r,n);return o.startsWith("..")||Et.isAbsolute(o)||o.split(Et.sep).length<3||!n.startsWith(Et.resolve(t))?"path_outside_harness":null}function XN(e,t,r){let n=Et.resolve(e);return kp(n,t,r)===null||bp(n,t,r)===null||vp(n,t,r)===null}var Vk=p(()=>{"use strict"});import{spawnSync as J8}from"node:child_process";import QN from"node:path";function e0(){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 ZN(e){let t=J8("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:t.status===0,stderr:`${t.stderr??""}${t.stdout??""}`.trim()}}function t0(e,t,r){if(!XN(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=ZN(["chown","-R",`${n}:${o}`,QN.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=ZN(["rm","-rf",QN.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 Gk,r0=p(()=>{"use strict";Vk();Gk="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 q8,rmSync as Y8}from"node:fs";function z8(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function n0(e,t,r={}){if(!q8(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?hs(n):null,i=e.bytes??Gr(e.path)??void 0,a=r.removePath??Y8,l=r.hasForeignOwnedEntry??qN;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(c){if(!z8(c)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let u=l(e.path),d=e0();if(!(d==="force"||d==="auto"&&u))return u?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; ${Gk}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let m=t0(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}; ${Gk}`}}}var o0=p(()=>{"use strict";bl();Mt();YN();r0()});import{existsSync as Jk,rmSync as s0}from"node:fs";function qk(e){let t=e.harnessRoot;return!t||!QT(e.path,t)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function Yk(e,t){let r=qk(e);if(r)return r;let n=n0(e,t);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function i0(e,t){return Yk(e,t)}function a0(e,t){return Yk(e,t)}function l0(e,t){return Yk(e,t)}function c0(e,t){let r=qk(e);if(r)return r;if(!Jk(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??Gr(e.path);return s0(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 u0(e,t){let r=qk(e);if(r)return r;if(!Jk(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??Gr(e.path);return n&&de(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Jk(e.path)&&s0(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 d0=p(()=>{"use strict";_e();bl();o0();oi();Vk()});import{existsSync as Rp,readdirSync as wp,statSync as X8}from"node:fs";import nr from"node:path";function zk(e,t){try{let r=X8(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function f0(e,t){let r=nr.relative(t,e);return r===""||!r.startsWith("..")&&!nr.isAbsolute(r)}function p0(e,t,r,n){let o=[];for(let s of Bk){if(s===".next")continue;let i=nr.join(e,s);if(!Rp(i))continue;let a=nr.resolve(i);r.has(a)||f0(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:zk(a,t.now)}))}return o}function m0(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||t.push(...p0(n.worktreePath,e,r,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!Rp(e.worktreesDir))return t;for(let n of wp(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=nr.join(e.worktreesDir,n.name);for(let s of wp(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=nr.join(o,s.name);t.push(...p0(i,e,r,{runId:n.name,worker:s.name}))}}return t}function g0(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;Rp(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:zk(a,e.now)})))}if(!r||!Rp(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(nr.resolve(i.worktreePath));for(let i of wp(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=nr.join(e.worktreesDir,i.name),l;try{l=wp(a,{withFileTypes:!0})}catch{continue}for(let c of l){if(!c.isDirectory())continue;let u=nr.resolve(nr.join(a,c.name));o.has(u)||s.has(u)||f0(u,e.harnessRoot)&&(o.add(u),n.push({kind:"remove_worktree",path:u,bytes:null,runId:i.name,worker:c.name,ageMs:zk(u,e.now)}))}}return n}var h0=p(()=>{"use strict";Uk()});import{existsSync as b0,readdirSync as y0,statSync as Q8}from"node:fs";import ii from"node:path";function e5(e,t){try{let r=Q8(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function t5(e,t){let r=ii.relative(t,e);return r===""||!r.startsWith("..")&&!ii.isAbsolute(r)}function r5(e,t,r,n,o,s){if(!b0(n))return;let i=ii.resolve(n);t.has(i)||t5(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:e5(i,r.now)}))}function k0(e,t,r,n,o){for(let s of Z8)r5(e,t,r,ii.join(n,s.dirName),s.kind,o)}function v0(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||k0(t,r,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!b0(e.worktreesDir))return t;for(let n of y0(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=ii.join(e.worktreesDir,n.name),s;try{s=y0(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=ii.join(o,i.name);k0(t,r,e,a,{runId:n.name,worker:i.name})}}return t}var Z8,R0=p(()=>{"use strict";Z8=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}]});import{existsSync as w0,statSync as n5}from"node:fs";import or from"node:path";function o5(e,t){try{let r=n5(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function s5(e){let t=[],r=null;for(let n of e.split(`
|
|
193
|
-
`)){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
|
|
194
|
-
`).map(c=>c.trim()).filter(c=>c.length>0);if(
|
|
195
|
-
`).map(r=>r.trim()).filter(Boolean)}var C5,Q0=p(()=>{"use strict";C5=5e3});var xp,Z0=p(()=>{"use strict";Q0();xp=class{cache=new Map;porcelain(t){let r=t,n=this.cache.get(r);if(n!==void 0)return n;let o=X0(r)??[];return this.cache.set(r,o),o}}});var Cp,eD=p(()=>{"use strict";Rn();Cp=class{cache=new Map;derive(t){let r=this.cache.get(t.id);if(r!==void 0)return r;let n=bo(t);return this.cache.set(t.id,n),n}}});function A5(e){let t={};for(let r of e)t[r.kind]=(t[r.kind]??0)+1;return t}function tD(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:A5(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 rD=p(()=>{"use strict"});import It from"node:path";function I5(e={}){let t=e.harnessRoot?Be(e.harnessRoot):bt(),r=W0({harnessRoot:t}),n=e.now??Date.now();return{harnessRoot:t,scanRoots:r,now:n}}function P5(e){return typeof e=="string"?{reason:e}:e}function ai(e,t,r,n){e.push({path:t,reason:r,...n?{detail:n}:{}})}function Ep(e,t,r){return!t||e.bytes!=null?e:{...e,bytes:Gr(e.path,r)}}function nD(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 O5(e,t){return e.kind==="remove_next_cache"?a0(e,t):i0(e,t)}function T5(e,t,r){return e.kind==="remove_next_cache"?bp(e.path,t,r):kp(e.path,t,r)}function N5(e){let t=new Map;for(let r of e)for(let[n,o]of C0(r))t.set(n,o);return t}function oD(e,t){return e.runId&&e.worker?It.join(t,e.runId,e.worker):It.resolve(e.path,"..")}function sD(e){return e.indexed?!1:eb({harnessRoot:e.harnessRoot,runId:e.candidate.runId,workerName:e.candidate.worker,now:e.now})}function D5(e={}){let t=Qk(e),r=$0();t=H0(t,r);let n=I5(e);At("scan",`${n.scanRoots.length} harness root(s)`);let o=BN(n.scanRoots,n.now),s=t.finalizeStaleRuns?ml().map(P=>({runId:P.runId,from:P.from,to:P.to})):[];s.length>0&&At("finalize",`${s.length} stale run(s) marked terminal`),At("index","building worktree index");let i=N5(n.scanRoots);At("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new Cp,gitStatusCache:new xp,gitRevCache:new _p},l=[],c=[],u=new Set,d=t.maxActionsPerSweep,f=()=>c.length>=d;for(let P of n.scanRoots){if(f())break;At("root",P);let M=It.join(P,"worktrees"),N=x0(i,P),L={harnessRoot:P,worktreesDir:M,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter,index:N,now:n.now},V=t.scanDependencyCaches?v0(L):[];At("dependency",t.scanDependencyCaches?`${V.length} cache candidate(s) at ${P}`:"skipped (worktree-only sweep)");let W=0;for(let T of V){if(f())break;W+=1,W%50===0&&At("dependency",`${W}/${V.length} evaluated`);let C=It.resolve(T.path);if(u.has(C))continue;u.add(C);let D={...T,path:C},ee=T5(D,P,M);if(ee){ai(l,D.path,ee),c.push({...D,executed:!1,skipped:!0,skipReason:ee});continue}let J=oD(D,M),X=N.get(It.resolve(J))??null,ge=sD({candidate:D,indexed:X,harnessRoot:P,now:n.now}),Y=Hk({indexed:X,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:D.ageMs,worktreePath:J,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:ge,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(Y){ai(l,D.path,Y),c.push({...D,executed:!1,skipped:!0,skipReason:Y});continue}c.push(O5(Ep(D,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(t.scanDependencyCaches)for(let T of m0(L)){if(f())break;let C=It.resolve(T.path);if(u.has(C))continue;u.add(C);let D={...T,path:C},ee=vp(D.path,P,M);if(ee){ai(l,D.path,ee),c.push({...D,executed:!1,skipped:!0,skipReason:ee});continue}let J=oD(D,M),X=N.get(It.resolve(J))??null,ge=sD({candidate:D,indexed:X,harnessRoot:P,now:n.now}),Y=ON({indexed:X,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:D.ageMs,worktreePath:J,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:ge,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(Y){ai(l,D.path,Y),c.push({...D,executed:!1,skipped:!0,skipReason:Y});continue}c.push(l0(Ep(D,t.accountBytes,t.byteAccountingEntryCap),t.execute))}let F=[...g0(L),...S0(L)];At("worktrees",`${F.length} candidate(s) at ${P}`);let x=new Set,G=0;for(let T of F){if(f())break;G+=1,G%50===0&&At("worktrees",`${G}/${F.length} evaluated`);let C=It.resolve(T.path);if(x.has(C))continue;x.add(C);let D={...T,path:C},ee=N.get(It.resolve(D.path))??null,J=ee?null:D0({worktreePath:D.path,harnessRoot:P,runId:D.runId,workerName:D.worker,now:n.now}),X=PN({indexed:ee,worktreePath:It.resolve(D.path),includeOrphans:t.includeOrphans,worktreesAgeMs:t.worktreesAgeMs,terminalWorktreesAgeMs:t.terminalWorktreesAgeMs,ageMs:D.ageMs,orphanSafety:J,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:P,writeSalvageEvidence:t.execute});if(X){let{reason:ge,detail:Y}=P5(X);ai(l,D.path,ge,Y),c.push({...D,executed:!1,skipped:!0,skipReason:ge});continue}c.push(u0(Ep(D,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(!f()&&t.runDirectoriesAgeMs>=0)for(let T of jN({harnessRoot:P,worktreesDir:M,runDirectoriesAgeMs:t.runDirectoriesAgeMs,runIdFilter:t.runIdFilter,activeGuards:o,now:n.now})){if(f())break;let C=It.resolve(T.path);if(u.has(C))continue;u.add(C);let D={...T,path:C},ee=D.runId??It.basename(C),J=HN({harnessRoot:P,runId:ee,runPath:C,ageMs:D.ageMs,runDirectoriesAgeMs:t.runDirectoriesAgeMs,activeGuards:o});if(J){ai(l,D.path,J),c.push({...D,executed:!1,skipped:!0,skipReason:J});continue}c.push(c0(Ep(D,t.accountBytes,t.byteAccountingEntryCap),t.execute))}}let m=0,g=0,h=0,y=0,b=0,k=0;for(let P of c)P.bytes&&(m+=P.bytes),!P.skipped&&!P.executed&&P.bytes&&(h+=P.bytes),P.executed?(b+=1,y+=P.bytes??0,P.kind==="remove_run_directory"&&(g+=1)):P.skipped&&(k+=1,P.skipReason==="dry_run"&&P.bytes&&(h+=P.bytes));let v=t.accountBytes?B0({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:t.storagePerRunEntryCap}):void 0,S=Xo(),w=t.execute&&J0(S),_=w?G0({execute:!0}):null,R=S?{observed:!0,execute:w,dumpCount:S.dumpCount,totalBytes:S.totalBytes,removedCount:_?.removed.length??0,removedBytes:_?.removedBytes??0,executables:S.executables,path:S.path,reason:S.reason}:void 0;_&&_.removed.length>0&&(y+=_.removedBytes,b+=_.removed.length,At("wsl-crashes",`removed ${_.removed.length} dump(s), ${_.removedBytes} bytes`)),At("complete",`${c.length} action(s), ${k} skipped, ${b} removed`);let O=DN(c,l),j=tD({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:b,skippedPaths:k,skipReasons:nD(c,l)},...v?{storage:v}:{},...O.length>0?{preservedLivePaths:O}:{},...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:m,reclaimableBytes:h,removedBytes:y,removedPaths:b,skippedPaths:k,skipReasons:nD(c,l)},...v?{storage:v}:{},...O.length>0?{preservedLivePaths:O}:{},...g>0?{removedRunDirectories:g}:{},...R?{wslCrashDumps:R}:{},compactSummary:j}}function iD(e){let t=O0(e);return D5({execute:t.execute,finalizeStaleRuns:t.finalizeStaleRuns,accountBytes:t.accountBytes,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter})}function aD(){return process.env.KYNVER_PIPELINE_CLEANUP!=="0"}var lD=p(()=>{"use strict";Mt();TN();MN();VN();d0();h0();R0();_0();E0();Rn();bl();T0();M0();U0();K0();jk();j0();q0();_c();Y0();z0();Z0();eD();rD()});function cD(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 Ap(e,t){let r=cD(e),n=cD(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 M5,v0e,rb=p(()=>{"use strict";Ki();M5={"@kynver-app/runtime":"0.1.83","@kynver-app/openclaw-agent-os":"0.1.43","@kynver-app/mcp-agent-os":"0.3.34"},v0e=Object.keys(M5)});import{readFile as L5}from"node:fs/promises";import{homedir as B5}from"node:os";import xn from"node:path";function li(e){let t=e?.trim();return t||null}function F5(e){return[...new Set(e.filter(t=>!!t))]}function uD(){let e=B5(),t=li(process.env.KYNVER_OPENCLAW_NPM_ROOT)??li(process.env.OPENCLAW_NPM_ROOT)??xn.join(e,".openclaw","npm"),r=li(process.env.KYNVER_NPM_GLOBAL_ROOT)??li(process.env.KYNVER_NPM_GLOBAL_MODULES_ROOT)??(li(process.env.NPM_CONFIG_PREFIX)?xn.join(li(process.env.NPM_CONFIG_PREFIX),"lib","node_modules"):xn.join(e,".npm-global","lib","node_modules"));return F5([xn.join(t,"lib","node_modules"),xn.join(t,"node_modules"),r.endsWith("node_modules")?r:xn.join(r,"lib","node_modules")])}async function W5(e){try{let t=JSON.parse(await L5(e,"utf8"));return typeof t.version=="string"&&t.version.trim()?t.version.trim():null}catch{return null}}function dD(){return uD().map(e=>xn.join(e,"@kynver-app"))}function nb(e){let t=uD(),r=new Set,n=[];for(let o of t){let s=xn.join(o,e,"package.json");r.has(s)||(r.add(s),n.push(s))}return n}async function pD(e=new Date().toISOString()){let t={};for(let r of U5){let n=null;for(let o of nb(r)){let s=await W5(o);s&&(!n||Ap(s,n.version)>0)&&(n={version:s,path:o})}n&&(t[r]={version:n.version,observedAt:e,path:n.path})}return t}var U5,ob=p(()=>{"use strict";rb();U5=["@kynver-app/runtime","@kynver-app/openclaw-agent-os","@kynver-app/mcp-agent-os"]});import{spawnSync as K5}from"node:child_process";var $5,H5,fD,mD=p(()=>{"use strict";$5=1e4,H5=4*1024*1024,fD=(e,t,r)=>{try{let n=K5(e,t,{windowsHide:!0,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r?.timeoutMs??$5,maxBuffer:H5});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 Ip(e,t,r){return`${e} ${t} ${r}`}function sb(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 gD(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 Pp=p(()=>{"use strict"});function lb(){return Date.now()<ib}function Y5(e){let t=`${e.stdout}
|
|
196
|
-
${e.stderr}`.toLowerCase();return t.includes("api rate limit exceeded")||t.includes("rate limit exceeded")||t.includes("secondary rate limit")}function hD(e){Y5(e)&&(ib=Math.max(ib,Date.now()+q5))}function ab(e,t){if(lb())return null;let r=e("gh",["api",...t]);if(!r.ok||!r.stdout.trim())return hD(r),null;try{return JSON.parse(r.stdout)}catch{return null}}function z5(e,t,r,n){if(lb())return null;let o=e("gh",["pr","view",String(r),"--repo",t,"--json",n.join(",")]);if(!o.ok||!o.stdout.trim())return hD(o),null;try{return JSON.parse(o.stdout)}catch{return null}}function cb(e){return lb()?!1:process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()?!0:e("gh",["auth","token"]).ok}function ci(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function X5(e){return Array.isArray(e)?e.map(t=>ci(t)).filter(t=>t!==null).slice(0,V5).map(t=>({context:t.context??null,state:t.state??null,target_url:t.target_url??null,description:t.description??null})):[]}function Q5(e,t,r){let n=ab(e,[`repos/${t}/commits/${r}/status`]);return n?{state:n.state??null,statuses:X5(n.statuses)}:null}var j5,V5,G5,J5,q5,ib,yD,kD,bD,vD=p(()=>{"use strict";Pp();j5=8e3,V5=30,G5=100,J5=400,q5=3600*1e3,ib=0;yD={provider:"github",kind:"pr_snapshot",version:"2",isAvailable:cb,collect(e,t){let r=gD(e);if(!r)return null;let n=z5(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=ci(n.author),s=ci(n.mergeCommit),i=ci(n.headRepositoryOwner),a=typeof n.body=="string"?n.body.slice(0,j5):null,l=Array.isArray(n.statusCheckRollup)?n.statusCheckRollup.map(u=>ci(u)).filter(u=>u!==null).slice(0,G5).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=>ci(u)).map(u=>typeof u?.path=="string"?u.path.trim():"").filter(Boolean).slice(0,J5):[];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}}},kD={provider:"github",kind:"commit_status",version:"1",isAvailable:cb,collect(e,t){let r=sb(e);return r?Q5(t,r.repo,r.sha):null}},bD={provider:"github",kind:"branch_reachability",version:"1",isAvailable:cb,collect(e,t){let r=sb(e);if(!r)return null;let n=ab(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=ab(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 ub(e){db.some(t=>t.provider===e.provider&&t.kind===e.kind)||db.push(e)}function RD(e,t){return db.find(r=>r.provider===e&&r.kind===t)??null}function wD(){ub(yD),ub(kD),ub(bD)}var db,SD=p(()=>{"use strict";vD();db=[]});function _D(e,t={}){wD();let r=t.run??fD,n=t.now??(()=>new Date),o=t.maxSubjects??Z5,s=Date.now()+(t.deadlineMs??e9),i=new Set,a=e.filter(m=>{let g=Ip(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=Ip(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 b=RD(m.provider,m.kind);if(!b){d.skipped.push({...m,reason:"no_recipe"});continue}let k=`${b.provider} ${b.kind}`,v=f.get(k);if(v===void 0&&(v=b.isAvailable(r),f.set(k,v)),!v){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 S=b.collect(m.subject,r);if(S==null){d.skipped.push({...m,reason:"collect_failed"});continue}d.collected+=1;let w={provider:m.provider,kind:m.kind,subject:m.subject,payload:S,observedAt:n().toISOString(),collectorVersion:b.version};d.items.push(w),t.cache?.set(g,w,n())}return d}var Z5,e9,xD=p(()=>{"use strict";mD();SD();Pp();Z5=1,e9=25e3});import CD from"node:path";function ED(e){return CD.join(q(e),t9)}function o9(e){return CD.join(q(e),r9)}function AD(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 ID(e){let t=K(ED(e),null);return AD(t?.wanted)}function PD(e,t){we(ED(e),{savedAt:new Date().toISOString(),wanted:t})}function OD(e,t={}){let r=t.ttlMs??n9,n=o9(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&&(we(n,{savedAt:new Date().toISOString(),items:s}),i=!1)}}}function TD(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.providerEvidenceWanted;return Array.isArray(t)?AD(t):null}var t9,r9,n9,pb=p(()=>{"use strict";Z();B();Pp();t9="provider-evidence-wanted.json",r9="provider-evidence-cache.json",n9=600*1e3});import s9 from"node:path";function fb(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 u9(){return s9.join(ke().harnessRoot,i9)}function d9(e){let t=e.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),r=e==="github"?l9:c9;return fb(`KYNVER_PROVIDER_EVIDENCE_${t}_PER_MINUTE`,fb("KYNVER_PROVIDER_EVIDENCE_LIVE_COLLECTS_PER_MINUTE",r))}function ND(){return fb("KYNVER_PROVIDER_EVIDENCE_SHARED_CACHE_TTL_MS",a9)}function p9(e){return Math.floor(e.getTime()/6e4)*6e4}function f9(e){return`${e.provider}:${e.kind}`}function DD(e,t={}){let r=OD(e,{ttlMs:t.ttlMs??ND()}),n=t.file??u9(),o=K(n,null),s={...o?.items??{}},i={...o?.budget??{}},a=t.ttlMs??ND(),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=d9(u.provider);if(m===0)return!0;let g=f9(u),h=p9(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&&(we(n,{savedAt:new Date().toISOString(),items:s,budget:i}),l=!1)}}}var i9,a9,l9,c9,MD=p(()=>{"use strict";Z();B();pb();i9="provider-evidence-shared-cache.json",a9=6e4,l9=1,c9=1});function LD(e){let t=iC(),r=Or(e?.env??process.env),n=(e?.now??(()=>new Date))().getTime(),o={};if(r.flags.dispatchReceipts!=="off"){Object.assign(o,PP());let s=IP({nowMs:n,hasLiveWorker:e?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,r.flags.dispatchReceipts==="enforce"&&Object.assign(o,uN())}return r.flags.planOutbox!=="off"&&Object.assign(o,jO()),r.flags.admission!=="off"&&(Object.assign(o,DP()),r.flags.admission==="enforce"&&Object.assign(o,UP())),(r.flags.keeper!=="off"||r.flags.meshLease!=="off"||r.flags.quota!=="off")&&Object.assign(o,yC()),{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 BD=p(()=>{"use strict";pn();Cs();Hs();Mk();ul();yo();Vs();ba()});import{createHash as UD}from"node:crypto";import{access as m9,mkdir as sDe,readFile as FD,rename as iDe,writeFile as aDe}from"node:fs/promises";import{constants as g9}from"node:fs";import{homedir as mb}from"node:os";import rt from"node:path";function k9(){return process.env.KYNVER_MCP_UPDATE_INVENTORY_FILE?.trim()||rt.join(mb(),".kynver","mcp-installations.json")}function b9(e){return e==="openclaw"?process.env.KYNVER_OPENCLAW_NPM_ROOT?.trim()||rt.join(mb(),".openclaw","npm"):process.env.KYNVER_NPM_GLOBAL_ROOT?.trim()||process.env.NPM_CONFIG_PREFIX?.trim()||rt.join(mb(),".npm-global")}function v9(e){let t=rt.resolve(e);if(rt.basename(t)!=="node_modules")return t;let r=rt.dirname(t);return rt.basename(r)==="lib"?rt.dirname(r):r}function R9(e,t){return[rt.join(e,"lib","node_modules",t,"package.json"),rt.join(e,"node_modules",t,"package.json")]}async function w9(e){try{return await m9(e,g9.R_OK),!0}catch{return!1}}async function gb(e=k9()){let t;try{t=JSON.parse(await FD(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||!y9.test(r.inventoryKey)||!h9.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 S9(e,t,r){if(typeof e.bin=="string")return rt.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"&&!rt.isAbsolute(s)&&!s.split(/[\\/]/).includes("..")?rt.join(r,s):null}function _9(e){return UD("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 x9(e){let t=[];for(let r of e){let n=v9(b9(r.prefix)),o=(await Promise.all(R9(n,r.packageName).map(async m=>({candidate:m,ok:await w9(m)})))).find(m=>m.ok)?.candidate;if(!o)continue;let s=JSON.parse(await FD(o,"utf8"));if(s.name!==r.packageName||typeof s.version!="string"||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(s.version))continue;let i=rt.dirname(o),a=S9(s,r,i),l=r.packageName==="@kynver-app/runtime",c=r.lifecycle??"runtime_stdio",u=UD("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:_9(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 WD(){return x9(await gb())}var h9,y9,hb=p(()=>{"use strict";h9=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/i,y9=/^[A-Za-z0-9._:-]{8,128}$/});import{createHash as C9,createHmac as E9,timingSafeEqual as A9}from"node:crypto";function yb(e){let t=e.trim().split(".");return t.length!==3||t[0]!=="krc1"||!t[1]||!t[2]?null:{tokenId:t[1],tokenHash:C9("sha256").update(`krc1.${t[1]}.${t[2]}`,"utf8").digest("hex")}}function KD(e,t,r){let n=yb(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=E9("sha256",Buffer.from(n.tokenHash,"hex")).update(JSON.stringify(e.claims),"utf8").digest(),i=Buffer.from(e.signature,"base64url");return i.length===s.length&&A9(i,s)}var kb=p(()=>{"use strict"});import{createHash as I9}from"node:crypto";import{access as bb,mkdtemp as P9,readFile as GD,rm as O9}from"node:fs/promises";import{constants as vb}from"node:fs";import{tmpdir as T9}from"node:os";import ui from"node:path";import{spawn as N9}from"node:child_process";import{Client as D9}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as M9}from"@modelcontextprotocol/sdk/client/stdio.js";function JD(){return"npm"}function HD(e,t){return Buffer.byteLength(e)>=$D?e:(e+t.toString("utf8")).slice(0,$D)}function B9(e){let t=process.env.KYNVER_MCP_UPDATE_NPM_CACHE?.trim(),r=t&&ui.isAbsolute(t)?t:e,n={PATH:process.env.PATH,SystemRoot:process.env.SystemRoot,TEMP:process.env.TEMP,TMP:process.env.TMP,npm_config_registry:Rb,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 qD(e,t,r=wb,n){return new Promise((o,s)=>{let i,a;try{[i,a]=ie(e,t)}catch(m){s(m);return}let l=N9(i,a,{shell:!1,windowsHide:!0,detached:Re(),env:B9(n),stdio:["ignore","pipe","pipe"]}),c="",u="",d=!1;l.stdout.on("data",m=>{c=HD(c,m)}),l.stderr.on("data",m=>{u=HD(u,m)});let f=setTimeout(()=>{d=!0,l.pid&&he(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 U9(e,t){let[r,n]=t.split("-",2);return!n||!["sha256","sha384","sha512"].includes(r)?!1:I9(r).update(e).digest("base64")===n}async function F9(e,t,r,n){let o=await qD(JD(),["pack",`${e}@${t}`,"--json","--pack-destination",n,`--registry=${Rb}`,"--ignore-scripts"],wb,ui.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"||ui.basename(i)!==i)throw new Error("artifact_receipt_invalid");let a=ui.join(n,i);if(!U9(await GD(a),r))throw new Error("artifact_integrity_mismatch");return a}async function W9(e,t,r){if((await qD(JD(),["install","--global","--prefix",e,t,`--registry=${Rb}`,"--no-audit","--fund=false"],wb,r)).code!==0)throw new Error("package_install_failed")}async function YD(e){let t=JSON.parse(await GD(e.local.packageJsonPath,"utf8"));if(t.name!==e.report.packageName||typeof t.version!="string")throw new Error("installed_identity_mismatch");return t.version}function K9(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 jD(e){if(!e.local.binPath)throw new Error("mcp_binary_missing");await bb(e.local.binPath,vb.X_OK).catch(async()=>bb(e.local.binPath,vb.R_OK));let t=new M9({command:e.local.binPath,args:[],env:K9(e.local.envAllowlist),stderr:"pipe"}),r=new D9({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")),L9)})]);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 VD(e,t,r,n,o){let s=await P9(ui.join(T9(),"kynver-mcp-update-"));try{let i=await F9(t,r,n,s);if(await o(),await W9(e.local.prefix,i,ui.join(s,"npm-cache")),await YD(e)!==r)throw new Error("installed_version_mismatch")}finally{await O9(s,{recursive:!0,force:!0})}}async function zD(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 bb(e.local.prefix,vb.W_OK).catch(()=>{throw new Error("npm_prefix_not_writable")});let o=await YD(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 VD(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 jD(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 VD(e,t.packageName,t.installedVersion,t.rollbackIntegrity,async()=>{await n.beforePackageMutation?.()}),e.local.lifecycle==="runtime_stdio"){let c=await jD(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 Rb,$D,wb,L9,XD=p(()=>{"use strict";Vo();Fe();Rb="https://registry.npmjs.org",$D=512*1024,wb=2*6e4,L9=2e4});import{createHmac as $9,timingSafeEqual as H9}from"node:crypto";import{mkdir as j9,readFile as V9,rename as G9,writeFile as J9}from"node:fs/promises";import{homedir as q9}from"node:os";import Sb from"node:path";function wl(){return process.env.KYNVER_MCP_UPDATE_STATE_ROOT?.trim()||Sb.join(q9(),".kynver","state","mcp-updates")}function QD(e){if(!/^[A-Za-z0-9_-]{8,128}$/.test(e))throw new Error("invalid update operation identity");return Sb.join(wl(),`${e}.json`)}function ZD(e,t){let r=yb(t);return r?$9("sha256",Buffer.from(r.tokenHash,"hex")).update(JSON.stringify(e),"utf8").digest("base64url"):null}async function eM(e,t){try{let r=JSON.parse(await V9(QD(e),"utf8"));if(r.version!==2||r.operationId!==e||typeof r.integrityMac!="string")return null;let{integrityMac:n,...o}=r,s=ZD(o,t);if(!s)return null;let i=Buffer.from(n,"utf8"),a=Buffer.from(s,"utf8");return i.length!==a.length||!H9(i,a)?null:r}catch{return null}}async function tM(e,t){let r=ZD(e,t);if(!r)throw new Error("invalid_runner_credential_for_receipt");let n=QD(e.operationId);await j9(Sb.dirname(n),{recursive:!0,mode:448});let o=`${n}.${process.pid}.tmp`;await J9(o,`${JSON.stringify({...e,integrityMac:r},null,2)}
|
|
197
|
-
`,{mode:384}),await G9(o,n)}var Op=p(()=>{"use strict";kb()});import{randomBytes as _b}from"node:crypto";import{mkdir as xb,readFile as Cb,rename as Y9,rm as Tp,stat as z9,writeFile as rM}from"node:fs/promises";import Co from"node:path";function nM(){return Co.join(wl(),X9)}async function oM(){try{let e=JSON.parse(await Cb(Co.join(nM(),"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:sM(e.pid)}}catch{return null}}function sM(e){if(!Number.isSafeInteger(e)||e<=0)return!0;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function Q9(e){try{return await z9(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function iM(){return Z9("mcp_update")}async function Z9(e){let t=nM(),r=`${t}.reclaiming`;await xb(Co.dirname(t),{recursive:!0,mode:448});let n=!1;try{if(await Q9(r))return null;for(let o=0;o<2;o+=1)try{await xb(t,{mode:448});let s={pid:process.pid,nonce:_b(18).toString("base64url"),acquiredAt:new Date().toISOString(),holder:e};return await rM(Co.join(t,"owner.json"),JSON.stringify(s),{mode:384}),n&&(await Tp(r,{recursive:!0,force:!0}),n=!1),{release:async()=>{try{let i=JSON.parse(await Cb(Co.join(t,"owner.json"),"utf8"));i.pid===s.pid&&i.nonce===s.nonce&&await Tp(t,{recursive:!0,force:!0})}catch{}}}}catch(s){if(s.code!=="EEXIST")throw s;if(!n)try{await xb(r,{mode:448}),n=!0,await rM(Co.join(r,"owner.json"),JSON.stringify({pid:process.pid,nonce:_b(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 Cb(Co.join(t,"owner.json"),"utf8"))}catch{return null}if(sM(i.pid))return null;let a=`${t}.stale-${process.pid}-${_b(8).toString("hex")}`;await Y9(t,a),await Tp(a,{recursive:!0,force:!0})}return null}finally{n&&await Tp(r,{recursive:!0,force:!0})}}var X9,aM=p(()=>{"use strict";Op();X9="host-mutation.lock"});function Np(e,t,r){return`${e}/api/agent-os/by-id/${encodeURIComponent(t)}/mcp-updates/${r}`}function e7(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 lM(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 t7(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 cM(e){let t=me(e.baseUrl),r=await WD();if(r.length===0)return{ok:!0,stage:"not_configured"};let n=await no(Np(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 iM();if(!o){let s=await oM();return{ok:!0,stage:"host_mutation_busy",...s?{heldBy:s.holder}:{}}}try{let s=await no(Np(t,e.agentOsId,"claim"),e.secret,{activeOwnedSessions:e.activeOwnedSessions});if(!s.ok)return{ok:!1,stage:"claim",status:s.status};let i=e7(s.response);if(!i)return{ok:!0,stage:"idle"};if(!KD(i,e.secret,e.agentOsId))return{ok:!1,stage:"command_auth"};let a=await eM(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||!lM(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&&lM(a.recovery,i)?a.recovery:t7(k,i)}let u=a?.acceptedAt??new Date().toISOString(),d=async(k,v,S)=>{await tM({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 f="claimed",m=async k=>{if(!(await no(Np(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 zD(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 no(Np(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 uM=p(()=>{"use strict";$();Ge();hb();kb();XD();aM();Op()});import dM from"node:path";function r7(){let e=process.env.KYNVER_PIPELINE_SWEEP_ENABLED;return e?e==="1"||e.toLowerCase()==="true":!1}async function n7(e,t){let r=se(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(dM.join(q(r.id),"workers",U(i),"worker.json"),void 0);if(!a?.taskId||a.localOnly||en(a))continue;if(ja(a)){n.push({worker:i,ok:!0,taskId:a.taskId??null,skipped:!0});continue}if(s>=o)break;s++;let l=ce(a);if(!$e(l))continue;let c=es({alive:l.alive,finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry});if(!a.dispatched&&!l.finalResult&&!c?.salvageable)continue;let u=await Xs({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 o7(e,t,r,n,o){let s=me(n.baseUrl?String(n.baseUrl):void 0),i=await ye(n.secret?String(n.secret):void 0,e,{baseUrl:s}),a=`${s}/api/agent-os/by-id/${encodeURIComponent(e)}/operator/tick`,l=await pD(),c=ys(t),u=null;try{let w=ID(t);if(w.length>0){let _=DD(t);u=_D(w,{cache:_}),_.flush?.()}else u=null}catch{u=null}try{if($r()!=="off"){let w=os();NP({liveWorkers:w}),BP({liveWorkers:w})}else OP()}catch{}let d=({runId:w,workerName:_})=>{try{let{runsDir:R}=ke(),O=dM.join(Cr(R,U(w)),"workers",U(_),"worker.json"),j=K(O,null);return j?en(j):!1}catch{return!1}};await pN({agentOsId:e,baseUrl:s,secret:i,hasLiveWorker:d});let f=null;try{f=LD({hasLiveWorker:d})}catch{f=null}let m=null;try{m=qc({control:rn(e),supervisor:ZS(),inFlightWorkers:os().length})}catch{m=null}let g=Uu(t),h=pE(),y=await fe(a,i,{agentOsId:e,runId:t,ingestHarness:!0,harnessBoardSnapshot:tk(t),resourceGate:r,boxResourceSnapshot:mN(r,{harnessRunId:t,boxKind:Nt(A())}),packageVersions:l,...o?{harnessCleanup:o}:{},runnerPresence:Ue({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}),b=TD(y.response);if(b)try{PD(t,b)}catch{}let k=lE(y);if(k)try{aE(t,k)}catch{}let v=lC(y);v&&cC(e,v);let S=JS(y);return S&&eg(e,S),{ok:y.ok,httpStatus:y.status,response:y.response,...u?{providerEvidence:{attempted:u.attempted,collected:u.collected,skipped:u.skipped.length}}:{}}}async function Dp(e){let t=String(Tt(String(e.run||""),"--run")),r=String(Tt(String(e.agentOsId||""),"--agent-os-id")),n=e.execute!==!1&&e.execute!=="false";tk(t);let o=await Ku(r,e),s=Wu(o),i=Zi({runId:t,configuredMaxWorkersOverride:s}),a=aD()?iD(t):void 0,l=await o7(r,t,i,e,a),c;if(n)try{let P=me(e.baseUrl?String(e.baseUrl):void 0),M=await ye(e.secret?String(e.secret):void 0,r,{baseUrl:P});c=await cM({agentOsId:r,secret:M,baseUrl:P,activeOwnedSessions:os().length})}catch(P){c={ok:!1,stage:"cycle",error:P instanceof Error?P.message:"update cycle failed"}}let u=dP(t,l),d=await tI(t,e),f=await n7(t,e);f.some(P=>P.ok&&!P.skipped)&&$C();let m=Zi({runId:t,configuredMaxWorkersOverride:s}),g=Nk(),h=await kN(t,e),y=$T(m,l),b=y.maxStarts,k=rn(r),v=YS(k);v&&(b=0);let S=r7()?await pp({run:t,agentOsId:r,pipeline:!0,...e}):{ok:!0,skipped:!0,reason:"pipeline_sweep_disabled"},w=null,_=0,R=WT(l),O=b;if(n&&O>0&&R.length>0){let P=Math.min(O,R.length),M=await vk({...e,run:t,agentOsId:r,targetTaskIds:R.join(",")},P),N=ri(M);_+=N,O=Math.max(0,O-N),w={exactTargetTaskIds:R,exact:M,startedCount:_}}if(n&&O>0){let P=await vk({...e,run:t,agentOsId:r},O),M=ri(P);_+=M,w=w&&typeof w=="object"?{...w,broad:P,startedCount:_}:P}else!n||b<=0?w||(w={ok:!0,skipped:!0,reason:v??(n?m.reason??"no slots or queued work":"execute disabled"),maxStarts:0,dispatchAdvice:y,...R.length?{exactTargetTaskIds:R,exactOnly:!0}:{}}):w&&typeof w=="object"&&(w={...w,broadSkipped:!0,startedCount:_});let j=!y.underutilized&&b===0&&f.length===0&&_===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:S,dispatchAdvice:y,dispatch:w,idle:j,runtimeControl:k?{desiredState:k.desiredState,policyVersion:k.policyVersion}:null}}var Eb=p(()=>{"use strict";nn();pu();$();Ge();FT();KT();HT();Dk();ss();yo();fN();Vs();gN();Lu();Z();Mt();Dc();Ie();Lk();B();bN();cy();Qs();Sd();Wc();Ah();$();We();lD();Md();ob();Ir();xD();MD();pb();Sh();BD();ih();uM();_h()});function Mp(e){return as(rn(e))!=="stopped"?null:os().length}var Ab=p(()=>{"use strict";ss();nn()});function pM(e){if(!e||typeof e!="object")return!1;let t=e;return t.type==="result"&&typeof t.id=="number"&&typeof t.ok=="boolean"}var fM=p(()=>{"use strict"});import{existsSync as s7}from"node:fs";import{fileURLToPath as i7}from"node:url";import{SHARE_ENV as a7,Worker as l7}from"node:worker_threads";function u7(e=import.meta.url){for(let t of[`./${mM}`,`../${mM}`]){let r=new URL(t,e);try{if(s7(i7(r)))return r}catch{}}return null}function d7(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??st()?{mode:"inline",reason:"desktop_sidecar"}:e.script?{mode:"thread",reason:"default"}:{mode:"inline",reason:"thread_entry_not_built"}}var mM,c7,p7,Lp,gM=p(()=>{"use strict";Ot();_h();dn();Eb();Ab();fM();mM="daemon-tick-thread.js",c7=3;p7=(e,t)=>new l7(e,{workerData:t,env:a7,name:"kynver-pipeline-tick"}),Lp=class{constructor(t){this.options=t;this.script=t.script===void 0?u7():t.script;let r=d7({env:t.env,desktopMode:t.desktopMode,script:this.script});this.modeValue=r.mode,this.reason=r.reason,this.createWorker=t.createWorker??p7,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 dE(r),{tick:await Dp(t),inFlightWorkers:Mp(this.options.agentOsId),isolation:"inline"}}bundleIfChanged(){let t=Kx(),r=Yt(),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(!pM(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>=c7&&(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 f7,performance as m7}from"node:perf_hooks";var g7,h7,y7,k7,hM,Bp,yM=p(()=>{"use strict";g7=1e3,h7=250,y7=5,k7=5e3,hM=e=>Number.isFinite(e)?Math.round(e/1e6):0,Bp=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??g7,this.sampleIntervalMs=t.sampleIntervalMs??h7,this.now=t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??(()=>m7.now()),this.log=t.log??(r=>console.error(r)),this.histogram=t.histogram??f7({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>k7)return this.histogram.reset(),this.phasesInWindow=new Set([this.phase]),null;let s=Math.max(0,Math.round(n-this.sampleIntervalMs)),i=hM(this.histogram.max),a=hM(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(-y7),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]}}}});function vM(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 RM(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 bM(e){let t=e?.code;return typeof t=="string"?t:null}function wM(e){if(!e)return!1;if(e instanceof Cn)return b7.has(e.status);let t=bM(e)??bM(e.cause);if(t&&v7.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 Ib(e){return RM(e)?"aborted":wM(e)?"transient":"server"}function SM(e,t){let r=Ib(e);if(r==="aborted")return t<=w7?0:S7;if(r==="transient"){let n=Math.max(0,Math.min(t-1,kM.length-1));return kM[n]}return R7}function _M(e,t){return e==="aborted"&&t<_7?{event:"chat_claim_poll_retry",level:"info"}:{event:"chat_claim_error",level:"error"}}var Cn,b7,v7,R7,w7,S7,kM,Up,_7,Fp=p(()=>{"use strict";Cn=class extends Error{status;constructor(t){super(`claim failed: HTTP ${t}`),this.name="ClaimHttpError",this.status=t}},b7=new Set([502,503,504]),v7=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","ENETDOWN","UND_ERR_CONNECT_TIMEOUT"]),R7=5e3,w7=3,S7=1e3,kM=[0,1e3,5e3];Up=class{counts={aborted:0,transient:0,server:0,auth:0,recovered:0};streakKind=null;streak=0;onError(t){let r=Ib(t);return this.bump(r),{kind:r,consecutive:this.streak,backoffMs:SM(t,this.streak)}}onAuthError(){this.bump("auth")}onSuccess(){this.streak>0&&(this.counts.recovered+=1),this.streakKind=null,this.streak=0}snapshot(){return{...this.counts}}bump(t){this.counts[t]+=1,this.streak=this.streakKind===t?this.streak+1:1,this.streakKind=t}},_7=3});var x7,C7,E7,Wp,xM=p(()=>{"use strict";hr();x7=5*6e4,C7=5*6e4,E7=2160*60*60,Wp=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()>x7?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<C7)return;let r=`${this.deps.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(this.deps.agentOsId)}/runner-credentials`;try{let n=await kt(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({capabilities:["chat.relay"],ttlSeconds:E7,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 kt(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}}}});function CM(e=process.env){return e.KYNVER_OPENAI_DEFAULT_MODEL?.trim()||A7}var A7,tLe,EM=p(()=>{"use strict";Fa();cd();Xt();A7="gpt-5.5",tLe=600*1e3});function sr(e){let t=e.chatProvider?.trim();return di(t||e.workerProvider?.trim()||"cursor")}function di(e){let t=ze(e);return t==="cursor"||t==="agent"?"cursor":O7.has(t)?"gemini":AM.has(t)||AM.has(e.trim().toLowerCase())?"codex":IM.has(t)||IM.has(e.trim().toLowerCase())?"openai":(P7.has(t),"anthropic")}function Eo(e,t,r=process.env){let n=r.KYNVER_CHAT_MODEL?.trim();if(n){if(e==="cursor"){let s=Ds(n,Sl);return s.ok?s.model:Sl}if(e==="gemini"&&!Pb.test(n)&&!Ob.test(n)||(e==="openai"||e==="codex")&&!Pb.test(n)&&!PM.test(n)||e==="anthropic")return n}let o=t.defaultModel?.trim();if(e==="cursor"){if(o&&!Pb.test(o)){let s=Ds(o,Sl);return s.ok?s.model:Sl}return Sl}return e==="gemini"?o&&PM.test(o)?o:Je(r):e==="codex"?o&&Ob.test(o)?o:r.KYNVER_CODEX_DEFAULT_MODEL?.trim()||I7:e==="openai"?o&&Ob.test(o)?o:CM(r):o||Ke}var Sl,I7,P7,O7,AM,IM,Pb,PM,Ob,En=p(()=>{"use strict";oo();Xt();Wa();EM();br();nd();Sl="composer-2.5",I7=Bs,P7=new Set(["claude","anthropic","opus"]),O7=new Set(["gemini","gemini-api"]),AM=new Set(["codex","chatgpt","gpt"]),IM=new Set(["openai","openai-compatible","openai-api","openai_api"]);Pb=/^(?:claude[-_]|opus\b|sonnet\b|haiku\b)/i,PM=/^(?:gemini[-_]|flash\b|pro\b)/i,Ob=/^(?:gpt-|o\d|chatgpt-)/i});var Kp,OM=p(()=>{"use strict";Kp=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 T7 from"node:os";function _l(e=process.env){let t=A(),r=Nt(t,e);return cs({boxKind:r,hostLabel:T7.hostname(),config:t,env:e})}async function N7(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(),TM);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 D7(o)}async function D7(e){let t=new AbortController,r=setTimeout(()=>t.abort(),TM);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 Tb(e){return Ce()?!0:!!e&&!!bg(e)}async function $p(e=process.env){let t=A(),r=t.agentOsId?.trim(),n=Ce();if(!r||!Tb(r))return null;let o=await N7(t.apiBaseUrl,n,e);if(!o)return null;let s=sr(t),i=t.apiBaseUrl?.replace(/\/$/,"")??o.replace(/\/$/,"");return{bridgeUrl:o.replace(/\/$/,""),agentOsId:r,apiKey:n??"",boxId:_l(e),chatProvider:s,model:Eo(s,t,e),useClaudeOauth:t.chatUseClaudeOauth===!0,auth:new Wp({apiBaseUrl:i,agentOsId:r,boxLabel:()=>_l(e),loadApiKey:Ce,loadBoxCredential:()=>bg(r),saveBoxCredential:a=>P_(r,a),clearBoxCredential:O_}),security:new Kp,apiBaseUrl:i}}var TM,Hp=p(()=>{"use strict";$();We();us();xM();En();OM();TM=5e3});import{verify as M7,createPublicKey as L7}from"node:crypto";function F7(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 NM(e){return!e||typeof e!="object"||Array.isArray(e)?null:e[B7]??null}function W7(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function K7(e,t){let r=Date.parse(e),n=Date.parse(t);return Number.isNaN(r)?!1:Number.isNaN(n)?!0:r>n}function Nb(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(!F7(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||!W7(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=Zn(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(ut(s),"utf8"),d=L7({key:Buffer.concat([U7,Buffer.from(i)]),format:"der",type:"spki"});l=M7(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||!K7(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 wLe,B7,U7,DM=p(()=>{"use strict";sn();da();wLe=720*60*60,B7="change",U7=Buffer.from("302a300506032b6570032100","hex")});function MM(e){switch(e){case"off":return 0;case"folder":case"folders":return 1;case"full":return 2;default:return 0}}function $7(e,t){let r=MM(e.access),n=MM(t.access);if(r!==n)return r>n;if(r!==1)return!1;let o=new Set(Vn(t.folders));return Vn(e.folders).some(s=>!o.has(s))}function H7(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=ds(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:NM(r)}}function BM(e){let t=H7(e.signedAccess,e.boxId);if(!t)return{ok:!0,website:null,raised:!1};let r=ds(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:Vn(e.local.chatWorkFolders)}:{access:nu(e.engine),folders:[]});let o=n.every(c=>$7(t.level,c)),s=(e.now??(()=>new Date))().toISOString(),i=e.state.website;if(!o){let c=t.change!==null?Nb(t.change,{agentOsId:e.agentOsId,boxId:e.boxId,access:t.level.access,folders:t.level.folders},{env:e.env,nowSec:e.nowSec,lastApplied:LM(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=Nb(t.change,{agentOsId:e.agentOsId,boxId:e.boxId,access:t.level.access,folders:t.level.folders},{env:e.env,nowSec:e.nowSec,lastApplied:LM(i)}),l=i?.access??r??nu(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 LM(e){return!e||!e.changedAt&&!e.nonce?null:{changedAt:e.changedAt,nonce:e.nonce}}var UM=p(()=>{"use strict";DM();Gn()});import{existsSync as j7,mkdirSync as V7,readFileSync as G7,writeFileSync as J7}from"node:fs";import{homedir as q7}from"node:os";import Db from"node:path";function Mb(e=q7()){return Db.join(e,Y7)}function FM(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function z7(e){return typeof e.access!="string"?null:{access:e.access,folders:FM(e.folders),source:e.source??"default",signed:e.signed===!0,at:typeof e.at=="string"?e.at:""}}function X7(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(typeof r.access=="string")return{access:r.access,folders:FM(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 jp(e=Mb()){try{if(!j7(e))return{applied:null,website:null};let t=JSON.parse(G7(e,"utf8"));if(!t||typeof t!="object")return{applied:null,website:null};let r=z7(t);return{applied:r,website:X7(t.website,r)}}catch{return{applied:null,website:null}}}function WM(e,t){try{V7(Db.dirname(e),{recursive:!0});let r={...t.applied??{},...t.website?{website:t.website}:{}};J7(e,`${JSON.stringify(r,null,2)}
|
|
198
|
-
`,{mode:384})}catch{}}function
|
|
199
|
-
`,{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 rQ,HM,xl=p(()=>{"use strict";rQ=Bb.join(".kynver","logs","chat-commands.jsonl"),HM=2e3});function nQ(e){let r=e.chatProvider?.trim()||e.workerProvider?.trim()||"";return ze(r)}function Ao(e,t=process.env){return nQ(e)!=="gemini"?"http":Fs(St(t))==="antigravity"?"antigravity":"http"}var Vp=p(()=>{"use strict";go();sa()});import{spawnSync as JM}from"node:child_process";import{existsSync as oQ,readFileSync as sQ}from"node:fs";import{homedir as iQ,platform as aQ}from"node:os";import jM from"node:path";function Gp(e,t,r=process.env){return e==="cursor"?"cursor":e==="codex"?"codex":e==="gemini"?Ao(t,r)==="antigravity"?"antigravity":"none":e==="anthropic"?"claude-code":"none"}function lQ(e,t){return e==="cursor"?lo(t):e==="codex"?t.KYNVER_CODEX_BIN?.trim()||t.CODEX_BIN?.trim()||Br():e==="antigravity"?St(t):e==="claude-code"?t.KYNVER_CLAUDE_BIN?.trim()||t.CLAUDE_BIN?.trim()||"claude":null}function Jp(e,t=process.env,r=Date.now()){let n=lQ(e,t);if(!n)return null;let o=VM.get(n);if(o&&r-o.at<qM)return o.version;let s=null;try{let[i,a]=ie(n,["--version"]),l=JM(i,a,te({encoding:"utf8",timeout:5e3})),c=`${l.stdout??""} ${l.stderr??""}`;s=l.status===0?c.match(cQ)?.[0]??null:null}catch{s=null}return VM.set(n,{at:r,version:s}),s}function qp(e=process.env,t={}){if(e.ANTHROPIC_API_KEY?.trim())return!0;let r=t.home??iQ(),n=t.now??Date.now(),o=GM.get(r);if(o&&n-o.at<qM)return o.signedIn;let s=uQ(jM.join(e.CLAUDE_CONFIG_DIR?.trim()||jM.join(r,".claude"),".credentials.json"));return!s&&(t.os??aQ())==="darwin"&&(s=(t.keychain??dQ)()),GM.set(r,{at:n,signedIn:s}),s}function uQ(e){if(!oQ(e))return!1;try{let t=JSON.parse(sQ(e,"utf8")).claudeAiOauth,r=n=>typeof n=="string"&&n.length>0;return!!t&&(r(t.refreshToken)||r(t.accessToken))}catch{return!1}}function dQ(){try{return JM("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}var cQ,qM,VM,GM,Cl=p(()=>{"use strict";po();Ms();go();Fe();B();Vp();cQ=/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/,qM=10*6e4,VM=new Map;GM=new Map});import{createHash as pQ,verify as fQ,createPublicKey as mQ}from"node:crypto";function Kb(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};return delete t[YM],t}function hQ(e){return pQ("sha256").update(ut(Kb(e)),"utf8").digest("hex")}function $b(e){return!e||typeof e!="object"||Array.isArray(e)?null:e[YM]??null}function yQ(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 kQ(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:ut(r)===ut(t)}function Wb(e,t){return{state:t,firstSeenAt:new Date(e.firstSeenSec*1e3).toISOString(),turnId:e.turnId}}function bQ(e){return mQ({key:Buffer.concat([gQ,Buffer.from(e)]),format:"der",type:"spki"})}function zM(e,t,r={}){let n=r.env??process.env,o=r.nowSec??Math.floor(Date.now()/1e3),s=$b(e);if(s===null)return{ok:!1,code:"unsigned",reason:"turn carries no signed envelope"};if(!yQ(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=Zn(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(ut(i.payload),"utf8");c=fQ(null,d,bQ(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(hQ(e)!==i.payload.payloadHash)return{ok:!1,code:"payload_tampered",reason:"turn payload does not match its signed hash"};if(!kQ(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 (${vQ(u.replay)})`,replay:u.replay}}function vQ(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 YM,gQ,Yp,zp=p(()=>{"use strict";sn();da();YM="turnEnvelope",gQ=Buffer.from("302a300506032b6570032100","hex");Yp=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:Wb(n,"turn_mismatch")}:n.state==="verified"?{ok:!0,redelivered:!0}:{ok:!1,replay:Wb(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:Wb(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 XM(e=process.env,t={}){let r=(e[RQ]??t.chatTurnSignature??"").toString().trim().toLowerCase();return r==="optional"||r==="off"||r==="0"||r==="false"?"optional":"required"}function QM(e,t){return t?`turn_rejected_${e}: ${t}`:`turn_rejected_${e}`}function ZM(e,t){if(!($b(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:wQ(o)?o:null,signed:!1,userId:null,redelivered:!1}}let n=zM(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 wQ(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.byBox;return!!t&&typeof t=="object"&&!Array.isArray(t)}var RQ,Hb=p(()=>{"use strict";zp();RQ="KYNVER_CHAT_TURN_SIGNATURE"});function jb(e){return typeof e=="string"&&xQ.test(e.trim())?e.trim():null}function Xp(e){return`Kynver conversation id: ${e}. When work you start from this conversation later finishes, fails, needs the user or opens / merges a PR, post the update here only: \`kynver tab post --conversation ${e} "<text>"\` (or the agent_tab_post tool with this conversationId). When you create a Kynver task for it, pass originConversationId=${e} so its updates come back here too.`}function tL(e,t){let r=jb(e);return r?{[SQ]:r,[_Q]:t}:{}}var SQ,_Q,eL,xQ,Qp=p(()=>{"use strict";SQ="KYNVER_CONVERSATION",_Q="KYNVER_AGENT_TAB_ENGINE",eL="X-Kynver-Conversation",xQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i});function EQ(e){return typeof e=="string"&&CQ.includes(e)}function nL(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.kind!=="agent-tab"||!EQ(t.engine)||typeof t.sessionKey!="string"||!TQ.test(t.sessionKey))return null;let r=typeof t.text=="string"?t.text.slice(0,rL):"",n=[],o=0;if(Array.isArray(t.attachments))for(let c of t.attachments.slice(0,PQ)){if(!c||typeof c!="object")continue;let{name:u,mime:d,contentBase64:f}=c;if(!(typeof u!="string"||typeof f!="string")){if(o+=Math.floor(f.length*3/4),o>OQ)break;n.push({name:u.slice(0,200),mime:typeof d=="string"?d.slice(0,100):"application/octet-stream",contentBase64:f})}}let s=NQ(t.control);if(!s&&!r.trim()&&n.length===0)return null;let i=typeof t.styleNote=="string"?t.styleNote.trim().slice(0,IQ):"",a=typeof t.replyTurnId=="string"&&AQ.test(t.replyTurnId)?t.replyTurnId:null,l=jb(t.conversationId);return{kind:"agent-tab",engine:t.engine,sessionKey:t.sessionKey,text:r,attachments:n,...t.computerAccess!==void 0?{computerAccess:t.computerAccess}:{},...i?{styleNote:i}:{},...a?{replyTurnId:a}:{},...s?{control:s}:{},...l?{conversationId:l}:{}}}function NQ(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.op==="stop"?{op:"stop"}:t.op==="steer"&&typeof t.text=="string"&&t.text.trim()?{op:"steer",text:t.text.slice(0,rL)}:null}var CQ,Zp,AQ,rL,IQ,PQ,OQ,TQ,Vb=p(()=>{"use strict";Qp();CQ=["hermes","openclaw","claude-code","grok-bot"],Zp={hermes:"Hermes",openclaw:"OpenClaw","claude-code":"Claude Code","grok-bot":"Grok Bot"};AQ=/^[A-Za-z0-9-]{8,64}$/,rL=32e3,IQ=4e3,PQ=5,OQ=20*1024*1024,TQ=/^[A-Za-z0-9_.:-]{8,128}$/});import{createHash as DQ}from"node:crypto";function FQ(e){return`${e.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/agent-tabs/box`}function WQ(e,t,r){let n=e.trim()?e:`${t} finished without writing a reply.`;return r.length>0&&(n+=`
|
|
191
|
+
`),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 IN(hp.join(t,"evidence.json"),`${JSON.stringify(o,null,2)}
|
|
192
|
+
`),o}var DN=p(()=>{"use strict";_e();U()});import yp from"node:path";function L8(e){e.writeSalvageEvidence&&M8.has(e.skipReason)&&(Gr(e.indexed,e.now)||TN({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})||NN({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}))}function B8(e){let{indexed:t,worktreesAgeMs:r,terminalWorktreesAgeMs:n}=e;return t&&(Vr.has(t.run.status)||e.liveness&&Gk(t,e.liveness)||e.liveness&&He(Vk(t,e.liveness))&&!Gr(t))?n:r}function U8(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:B8(e)}function F8(e,t){if(e.harnessRoot?.trim())return yp.resolve(e.harnessRoot);let r=t.worker.workerDir;if(!r)return null;let n=`${yp.sep}runs${yp.sep}`,o=r.indexOf(n);return o<0?null:r.slice(0,o+n.length-1)}function MN(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=U8(e);if(n<=0&&!r&&l<=0)return"worktrees_disabled";if(l>0&&o<l)return"below_age_threshold";if(Gr(t,a))return"active_worker";let c=Vk(t,e.liveness),u=F8(e,t),d=g=>{if(u)try{L8({indexed:t,harnessRoot:u,skipReason:g,status:c,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})}catch{}return g};if(EN(t,c)){let g=d("completion_blocked");if(g)return g}if(jk(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(CN(t,e.liveness,a)||!He(c))return"run_still_active";if(yl(c)){let g=d("pr_or_unmerged_commits");if(g)return g}if(Et(c.changedFiles).length>0){let g=d("dirty_worktree");if(g)return g}if(rs({finalResult:c.finalResult,changedFiles:c.changedFiles,gitAncestry:c.gitAncestry,prUrl:_o(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 qk(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(yp.resolve(o))||t&&Gr(t)?"active_worker":t&&jk(t,e.gitStatusCache)?"dirty_worktree":null}function LN(e){return qk(e)}var M8,BN=p(()=>{"use strict";Bc();mp();Ie();wn();Jk();AN();DN();So();kl();So();kl();M8=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"])});var kp=p(()=>{"use strict"});function FN(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)UN.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||UN.has(s.skipReason)&&o(s.path,s.skipReason);return r}var UN,WN=p(()=>{"use strict";kp();UN=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"])});import KN from"node:path";function K8(e,t){return ii(e,t)}function $N(e,t=Date.now()){let r=new Set,n=new Set;for(let o of e){for(let s of pu(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let l=K(KN.join(ca(o,s.id),"workers",F(a),"worker.json"),void 0);if(!l?.worktreePath)continue;let c=KN.resolve(l.worktreePath);K8(l,t)&&(i=!0,r.add(c))}i&&n.add(`${o}\0${s.id}`)}for(let s of iN(o))n.add(s)}return{activeWorktreePaths:r,liveRunKeys:n}}function HN(e,t,r,n){return r?n.has(`${t}\0${r}`):!1}var Yk=p(()=>{"use strict";Q();Lt();si();gp();U()});import{existsSync as jN,readdirSync as VN,statSync as $8}from"node:fs";import GN from"node:path";function H8(e,t){try{let r=$8(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function j8(e,t){let r=GN.join(e,"runs",t,"run.json");return jN(r)?K(r,null):null}function JN(e){try{return VN(e).length===0}catch{return!1}}function qN(e){let{harnessRoot:t,runId:r,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(HN(n,t,r,i.liveRunKeys)||!JN(n))return"run_still_active";let a=j8(t,r);return a&&!Vr.has(a.status)&&!vo(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function YN(e){if(!jN(e.worktreesDir))return[];let t=[],r;try{r=VN(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=GN.join(e.worktreesDir,o);JN(s)&&t.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:H8(s,e.now)})}return t}var zN=p(()=>{"use strict";Yk();wn();U()});import{execFileSync as V8}from"node:child_process";import{existsSync as XN,readdirSync as G8,statSync as J8}from"node:fs";import q8 from"node:path";function z8(e,t=Y8){if(!XN(e))return 0;try{let n=V8("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 Jr(e,t=5e4){if(!XN(e))return 0;let r=z8(e);if(r!==null)return r;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=G8(i)}catch{continue}for(let l of a){if(o++>t)return null;let c=q8.join(i,l),u;try{u=J8(c)}catch{continue}u.isDirectory()?s.push(c):n+=u.size}}return n}var Y8,vl=p(()=>{"use strict";Y8=2500});import{lstatSync as X8,readdirSync as Q8}from"node:fs";function QN(e){try{let t=X8(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 ZN(e,t=32){let r=QN(e);if(!r)return!1;if(r.foreign)return!0;try{let n=Q8(e),o=0;for(let s of n){if(o>=t)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=QN(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}var e0=p(()=>{"use strict"});import At from"node:path";function t0(e,t,r,n){let o=At.resolve(e),s=`${At.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=At.relative(r,i);if(a.startsWith("..")||At.isAbsolute(a))return"path_outside_harness";let l=a.split(At.sep);return l.length<3||l[l.length-1]!==n||!o.startsWith(At.resolve(t))?"path_outside_harness":null}function bp(e,t,r){return t0(e,t,r,"node_modules")}function vp(e,t,r){return t0(e,t,r,".next")}function Rp(e,t,r){let n=At.resolve(e),o=At.relative(r,n);return o.startsWith("..")||At.isAbsolute(o)||o.split(At.sep).length<3||!n.startsWith(At.resolve(t))?"path_outside_harness":null}function r0(e,t,r){let n=At.resolve(e);return bp(n,t,r)===null||vp(n,t,r)===null||Rp(n,t,r)===null}var zk=p(()=>{"use strict"});import{spawnSync as Z8}from"node:child_process";import n0 from"node:path";function s0(){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 o0(e){let t=Z8("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:t.status===0,stderr:`${t.stderr??""}${t.stdout??""}`.trim()}}function i0(e,t,r){if(!r0(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=o0(["chown","-R",`${n}:${o}`,n0.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=o0(["rm","-rf",n0.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 Xk,a0=p(()=>{"use strict";zk();Xk="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 e5,rmSync as t5}from"node:fs";function r5(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function l0(e,t,r={}){if(!e5(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?ys(n):null,i=e.bytes??Jr(e.path)??void 0,a=r.removePath??t5,l=r.hasForeignOwnedEntry??ZN;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(c){if(!r5(c)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let u=l(e.path),d=s0();if(!(d==="force"||d==="auto"&&u))return u?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; ${Xk}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let m=i0(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}; ${Xk}`}}}var c0=p(()=>{"use strict";vl();Lt();e0();a0()});import{existsSync as Qk,rmSync as u0}from"node:fs";function Zk(e){let t=e.harnessRoot;return!t||!nN(e.path,t)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function eb(e,t){let r=Zk(e);if(r)return r;let n=l0(e,t);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function d0(e,t){return eb(e,t)}function p0(e,t){return eb(e,t)}function f0(e,t){return eb(e,t)}function m0(e,t){let r=Zk(e);if(r)return r;if(!Qk(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??Jr(e.path);return u0(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 g0(e,t){let r=Zk(e);if(r)return r;if(!Qk(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??Jr(e.path);return n&&de(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Qk(e.path)&&u0(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 h0=p(()=>{"use strict";_e();vl();c0();si();zk()});import{existsSync as wp,readdirSync as Sp,statSync as n5}from"node:fs";import or from"node:path";function tb(e,t){try{let r=n5(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function k0(e,t){let r=or.relative(t,e);return r===""||!r.startsWith("..")&&!or.isAbsolute(r)}function y0(e,t,r,n){let o=[];for(let s of $k){if(s===".next")continue;let i=or.join(e,s);if(!wp(i))continue;let a=or.resolve(i);r.has(a)||k0(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:tb(a,t.now)}))}return o}function b0(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||t.push(...y0(n.worktreePath,e,r,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!wp(e.worktreesDir))return t;for(let n of Sp(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=or.join(e.worktreesDir,n.name);for(let s of Sp(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=or.join(o,s.name);t.push(...y0(i,e,r,{runId:n.name,worker:s.name}))}}return t}function v0(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;wp(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:tb(a,e.now)})))}if(!r||!wp(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(or.resolve(i.worktreePath));for(let i of Sp(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=or.join(e.worktreesDir,i.name),l;try{l=Sp(a,{withFileTypes:!0})}catch{continue}for(let c of l){if(!c.isDirectory())continue;let u=or.resolve(or.join(a,c.name));o.has(u)||s.has(u)||k0(u,e.harnessRoot)&&(o.add(u),n.push({kind:"remove_worktree",path:u,bytes:null,runId:i.name,worker:c.name,ageMs:tb(u,e.now)}))}}return n}var R0=p(()=>{"use strict";Hk()});import{existsSync as _0,readdirSync as w0,statSync as o5}from"node:fs";import ai from"node:path";function i5(e,t){try{let r=o5(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function a5(e,t){let r=ai.relative(t,e);return r===""||!r.startsWith("..")&&!ai.isAbsolute(r)}function l5(e,t,r,n,o,s){if(!_0(n))return;let i=ai.resolve(n);t.has(i)||a5(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:i5(i,r.now)}))}function S0(e,t,r,n,o){for(let s of s5)l5(e,t,r,ai.join(n,s.dirName),s.kind,o)}function x0(e){let t=[],r=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||S0(t,r,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!_0(e.worktreesDir))return t;for(let n of w0(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=ai.join(e.worktreesDir,n.name),s;try{s=w0(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=ai.join(o,i.name);S0(t,r,e,a,{runId:n.name,worker:i.name})}}return t}var s5,C0=p(()=>{"use strict";s5=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}]});import{existsSync as E0,statSync as c5}from"node:fs";import sr from"node:path";function u5(e,t){try{let r=c5(e).mtimeMs;return Math.max(0,t-r)}catch{return 0}}function d5(e){let t=[],r=null;for(let n of e.split(`
|
|
193
|
+
`)){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 p5(e,t){let r=sr.relative(sr.resolve(t),sr.resolve(e));return r!==""&&!r.startsWith("..")&&!sr.isAbsolute(r)}function A0(e){if(!e.includeOrphans||!E0(e.worktreesDir))return[];let t=new Set;for(let s of e.index.values())s.run.repo&&t.add(sr.resolve(s.run.repo));let r=new Set;for(let s of e.index.values())r.add(sr.resolve(s.worktreePath));let n=[],o=new Set;for(let s of t){let i=0,a;try{a=de(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let l=d5(a);for(let c of l){if(i>=f5)break;let u=sr.resolve(c.path);if(u===sr.resolve(s)||!p5(u,e.worktreesDir)||r.has(u)||o.has(u)||!E0(u))continue;let f=sr.relative(e.worktreesDir,u).split(sr.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:u5(u,e.now)})}}return n}var f5,I0=p(()=>{"use strict";_e();f5=200});import Rl from"node:path";function P0(e,t){let r=Rl.resolve(t),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?Rl.resolve(s.harnessRoot):null;i&&i!==r||n.set(o,s)}return n}function O0(e){let t=new Map;for(let r of pu(e))for(let n of Object.keys(r.workers||{})){let o=Rl.join(ca(e,r.id),"workers",F(n),"worker.json"),s=K(o,void 0);s?.worktreePath&&t.set(Rl.resolve(s.worktreePath),{harnessRoot:e,worktreePath:Rl.resolve(s.worktreePath),runId:r.id,workerName:n,run:r,worker:s})}return t}var T0=p(()=>{"use strict";Q();U()});function wl(e){let t=process.env[e];return t==="1"||t==="true"||t==="yes"}function xo(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)&&n>=0?n:t}function nb(e={}){let t=e.execute===!0||e.execute!==!1&&wl("KYNVER_CLEANUP_EXECUTE"),r=e.finalizeStaleRuns!==!1&&!wl("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??xo("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??xo("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??xo("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??xo("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),l=e.maxActionsPerSweep??xo("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),c=e.includeOrphans===!0||wl("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=wl("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&&!wl("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),m=xo("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),g=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:f&&m>0?m:null,h=xo("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),k=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:k}}function L0(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 nb({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 B0=p(()=>{"use strict";kp()});import{existsSync as ob,statSync as g5}from"node:fs";import Co from"node:path";function h5(e,t){let r=Co.relative(t,e);return r===""||!r.startsWith("..")&&!Co.isAbsolute(r)}function y5(e,t,r){if(!ob(e))return!1;try{let n=t-g5(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<r}catch{return!1}}function sb(e){if(!e.runId||!e.workerName)return!1;let t=e.now??Date.now(),r=e.heartbeatFreshMs??U0,n=Co.resolve(e.harnessRoot,"runs"),o=Co.resolve(n,e.runId,"workers",e.workerName);if(!h5(o,n))return!1;let s=K(Co.join(o,"worker.json"),void 0);return s&&ii(s,t,r)?!0:s?!1:y5(Co.join(o,"heartbeat.jsonl"),t,r)}function F0(e){let t=e.now??Date.now(),r=e.heartbeatFreshMs??U0;if(!ob(e.worktreePath))return null;if(e.runId&&e.workerName&&sb(e))return"active_worker";let n=Co.join(e.worktreePath,".git");if(!ob(n))return null;let o=ee(e.worktreePath,["status","--porcelain"]);if(o.status!==0)return"pr_or_unmerged_commits";let s=o.stdout.split(`
|
|
194
|
+
`).map(c=>c.trim()).filter(c=>c.length>0);if(Et(s).length>0)return"dirty_worktree";let i=ee(e.worktreePath,["rev-list","--count","@{u}..HEAD"]);if(i.status===0){let c=Number(i.stdout.trim());if(Number.isFinite(c)&&c>0)return"pr_or_unmerged_commits"}let a=ee(e.worktreePath,["rev-list","--count","origin/main..HEAD"]);if(a.status!==0)return i.status!==0?"pr_or_unmerged_commits":null;let l=Number(a.stdout.trim());return Number.isFinite(l)&&l>0?"pr_or_unmerged_commits":null}var U0,W0=p(()=>{"use strict";_e();So();gp();U();U0=1800*1e3});import{existsSync as k5,readdirSync as K0,statSync as b5}from"node:fs";import v5 from"node:path";function $0(e={}){let t=Ue(e.harnessRoot??vt()),r=ys(t),n=e.now??Date.now(),o=new Date(n).toISOString();if(!k5(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=K0(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=v5.join(r,u.name);try{let f=b5(d);l=l===null?f.mtimeMs:Math.min(l,f.mtimeMs)}catch{}try{for(let f of K0(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=Jr(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 H0=p(()=>{"use strict";Lt();vl()});import{existsSync as R5}from"node:fs";import{homedir as w5}from"node:os";import j0 from"node:path";function ib(e,t,r){if(!r?.trim())return;let n=Ue(r.trim());e.has(n)||(e.add(n),t.push(n))}function _5(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 V0(e={}){let t=new Set,r=[];ib(t,r,e.harnessRoot??vt());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])ib(t,r,o);if(_5(e))for(let o of S5){let s=j0.resolve(o);!t.has(s)&&R5(s)&&ib(t,r,s)}return r}var S5,G0=p(()=>{"use strict";Lt();S5=["/var/tmp/kynver-harness",j0.join(w5(),".openclaw","harness")]});function x5(e){let t=process.env[e];return t==="1"||t==="true"||t==="yes"}function C5(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function J0(e={}){let t=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",r=C5("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=Qr({...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 q0(e,t){if(!t.pressured)return e;let r=e.execute||!x5("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 Y0=p(()=>{"use strict";Gi();kp()});import{unlinkSync as E5}from"node:fs";function _p(e){let t=process.env[e];return t==="1"||t==="true"||t==="yes"}function z0(e,t){let r=process.env[e];if(!r)return t;let n=Number(r);return Number.isFinite(n)?n:t}function A5(e,t,r){return e.length===0?[]:r?[...e]:e.length<=t?[]:e.slice(t)}function X0(e={}){let t=e.execute===!0||_p("KYNVER_WSL_CRASH_DUMP_EXECUTE")||_p("KYNVER_CLEANUP_EXECUTE"),r=e.purgeAll===!0||_p("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),n=Math.max(0,e.keepNewest??z0("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",r?0:1)),o=Qo({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=A5(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{E5(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 Q0(e){return e?_p("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>z0("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}var Z0=p(()=>{"use strict";xc()});function It(e,t){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let r=t?`: ${t}`:"";console.error(`[kynver cleanup] ${e}${r}`)}var eD=p(()=>{"use strict"});var xp,tD=p(()=>{"use strict";_e();xp=class{aheadOfMain=new Map;countAheadOfMain(t,r="origin/main"){let n=`${t}\0${r}`;if(this.aheadOfMain.has(n))return this.aheadOfMain.get(n)??null;let o=ee(t,["rev-list","--count",`${r}..HEAD`]);if(o.status!==0)return this.aheadOfMain.set(n,null),null;let s=Number(o.stdout.trim()),i=Number.isFinite(s)?s:null;return this.aheadOfMain.set(n,i),i}}});import{spawnSync as I5}from"node:child_process";import{existsSync as P5}from"node:fs";import O5 from"node:path";function N5(e,t){if(!P5(O5.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let r=I5("git",t,{windowsHide:!0,cwd:e,encoding:"utf8",timeout:T5}),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 rD(e){let t=N5(e,["status","--short"]);return t.error==="not_a_git_repo"?[]:t.error==="git_timeout"||t.status!==0?null:t.stdout.split(`
|
|
195
|
+
`).map(r=>r.trim()).filter(Boolean)}var T5,nD=p(()=>{"use strict";T5=5e3});var Cp,oD=p(()=>{"use strict";nD();Cp=class{cache=new Map;porcelain(t){let r=t,n=this.cache.get(r);if(n!==void 0)return n;let o=rD(r)??[];return this.cache.set(r,o),o}}});var Ep,sD=p(()=>{"use strict";wn();Ep=class{cache=new Map;derive(t){let r=this.cache.get(t.id);if(r!==void 0)return r;let n=vo(t);return this.cache.set(t.id,n),n}}});function D5(e){let t={};for(let r of e)t[r.kind]=(t[r.kind]??0)+1;return t}function iD(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:D5(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 aD=p(()=>{"use strict"});import Pt from"node:path";function M5(e={}){let t=e.harnessRoot?Ue(e.harnessRoot):vt(),r=V0({harnessRoot:t}),n=e.now??Date.now();return{harnessRoot:t,scanRoots:r,now:n}}function L5(e){return typeof e=="string"?{reason:e}:e}function li(e,t,r,n){e.push({path:t,reason:r,...n?{detail:n}:{}})}function Ap(e,t,r){return!t||e.bytes!=null?e:{...e,bytes:Jr(e.path,r)}}function lD(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 B5(e,t){return e.kind==="remove_next_cache"?p0(e,t):d0(e,t)}function U5(e,t,r){return e.kind==="remove_next_cache"?vp(e.path,t,r):bp(e.path,t,r)}function F5(e){let t=new Map;for(let r of e)for(let[n,o]of O0(r))t.set(n,o);return t}function cD(e,t){return e.runId&&e.worker?Pt.join(t,e.runId,e.worker):Pt.resolve(e.path,"..")}function uD(e){return e.indexed?!1:sb({harnessRoot:e.harnessRoot,runId:e.candidate.runId,workerName:e.candidate.worker,now:e.now})}function W5(e={}){let t=nb(e),r=J0();t=q0(t,r);let n=M5(e);It("scan",`${n.scanRoots.length} harness root(s)`);let o=$N(n.scanRoots,n.now),s=t.finalizeStaleRuns?gl().map(O=>({runId:O.runId,from:O.from,to:O.to})):[];s.length>0&&It("finalize",`${s.length} stale run(s) marked terminal`),It("index","building worktree index");let i=F5(n.scanRoots);It("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new Ep,gitStatusCache:new Cp,gitRevCache:new xp},l=[],c=[],u=new Set,d=t.maxActionsPerSweep,f=()=>c.length>=d;for(let O of n.scanRoots){if(f())break;It("root",O);let L=Pt.join(O,"worktrees"),M=P0(i,O),B={harnessRoot:O,worktreesDir:L,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter,index:M,now:n.now},G=t.scanDependencyCaches?x0(B):[];It("dependency",t.scanDependencyCaches?`${G.length} cache candidate(s) at ${O}`:"skipped (worktree-only sweep)");let re=0;for(let N of G){if(f())break;re+=1,re%50===0&&It("dependency",`${re}/${G.length} evaluated`);let C=Pt.resolve(N.path);if(u.has(C))continue;u.add(C);let D={...N,path:C},z=U5(D,O,L);if(z){li(l,D.path,z),c.push({...D,executed:!1,skipped:!0,skipReason:z});continue}let ue=cD(D,L),H=M.get(Pt.resolve(ue))??null,ie=uD({candidate:D,indexed:H,harnessRoot:O,now:n.now}),Y=qk({indexed:H,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:D.ageMs,worktreePath:ue,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:ie,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(Y){li(l,D.path,Y),c.push({...D,executed:!1,skipped:!0,skipReason:Y});continue}c.push(B5(Ap(D,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(t.scanDependencyCaches)for(let N of b0(B)){if(f())break;let C=Pt.resolve(N.path);if(u.has(C))continue;u.add(C);let D={...N,path:C},z=Rp(D.path,O,L);if(z){li(l,D.path,z),c.push({...D,executed:!1,skipped:!0,skipReason:z});continue}let ue=cD(D,L),H=M.get(Pt.resolve(ue))??null,ie=uD({candidate:D,indexed:H,harnessRoot:O,now:n.now}),Y=LN({indexed:H,includeOrphans:!0,nodeModulesAgeMs:t.nodeModulesAgeMs,ageMs:D.ageMs,worktreePath:ue,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:ie,diskPressure:t.diskPressure,gitStatusCache:a.gitStatusCache});if(Y){li(l,D.path,Y),c.push({...D,executed:!1,skipped:!0,skipReason:Y});continue}c.push(f0(Ap(D,t.accountBytes,t.byteAccountingEntryCap),t.execute))}let I=[...v0(B),...A0(B)];It("worktrees",`${I.length} candidate(s) at ${O}`);let x=new Set,V=0;for(let N of I){if(f())break;V+=1,V%50===0&&It("worktrees",`${V}/${I.length} evaluated`);let C=Pt.resolve(N.path);if(x.has(C))continue;x.add(C);let D={...N,path:C},z=M.get(Pt.resolve(D.path))??null,ue=z?null:F0({worktreePath:D.path,harnessRoot:O,runId:D.runId,workerName:D.worker,now:n.now}),H=MN({indexed:z,worktreePath:Pt.resolve(D.path),includeOrphans:t.includeOrphans,worktreesAgeMs:t.worktreesAgeMs,terminalWorktreesAgeMs:t.terminalWorktreesAgeMs,ageMs:D.ageMs,orphanSafety:ue,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:O,writeSalvageEvidence:t.execute});if(H){let{reason:ie,detail:Y}=L5(H);li(l,D.path,ie,Y),c.push({...D,executed:!1,skipped:!0,skipReason:ie});continue}c.push(g0(Ap(D,t.accountBytes,t.byteAccountingEntryCap),t.execute))}if(!f()&&t.runDirectoriesAgeMs>=0)for(let N of YN({harnessRoot:O,worktreesDir:L,runDirectoriesAgeMs:t.runDirectoriesAgeMs,runIdFilter:t.runIdFilter,activeGuards:o,now:n.now})){if(f())break;let C=Pt.resolve(N.path);if(u.has(C))continue;u.add(C);let D={...N,path:C},z=D.runId??Pt.basename(C),ue=qN({harnessRoot:O,runId:z,runPath:C,ageMs:D.ageMs,runDirectoriesAgeMs:t.runDirectoriesAgeMs,activeGuards:o});if(ue){li(l,D.path,ue),c.push({...D,executed:!1,skipped:!0,skipReason:ue});continue}c.push(m0(Ap(D,t.accountBytes,t.byteAccountingEntryCap),t.execute))}}let m=0,g=0,h=0,k=0,v=0,y=0;for(let O of c)O.bytes&&(m+=O.bytes),!O.skipped&&!O.executed&&O.bytes&&(h+=O.bytes),O.executed?(v+=1,k+=O.bytes??0,O.kind==="remove_run_directory"&&(g+=1)):O.skipped&&(y+=1,O.skipReason==="dry_run"&&O.bytes&&(h+=O.bytes));let b=t.accountBytes?$0({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:t.storagePerRunEntryCap}):void 0,S=Qo(),w=t.execute&&Q0(S),_=w?X0({execute:!0}):null,R=S?{observed:!0,execute:w,dumpCount:S.dumpCount,totalBytes:S.totalBytes,removedCount:_?.removed.length??0,removedBytes:_?.removedBytes??0,executables:S.executables,path:S.path,reason:S.reason}:void 0;_&&_.removed.length>0&&(k+=_.removedBytes,v+=_.removed.length,It("wsl-crashes",`removed ${_.removed.length} dump(s), ${_.removedBytes} bytes`)),It("complete",`${c.length} action(s), ${y} skipped, ${v} removed`);let T=FN(c,l),W=iD({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:k,removedPaths:v,skippedPaths:y,skipReasons:lD(c,l)},...b?{storage:b}:{},...T.length>0?{preservedLivePaths:T}:{},...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:m,reclaimableBytes:h,removedBytes:k,removedPaths:v,skippedPaths:y,skipReasons:lD(c,l)},...b?{storage:b}:{},...T.length>0?{preservedLivePaths:T}:{},...g>0?{removedRunDirectories:g}:{},...R?{wslCrashDumps:R}:{},compactSummary:W}}function dD(e){let t=L0(e);return W5({execute:t.execute,finalizeStaleRuns:t.finalizeStaleRuns,accountBytes:t.accountBytes,nodeModulesAgeMs:t.nodeModulesAgeMs,worktreesAgeMs:t.worktreesAgeMs,includeOrphans:t.includeOrphans,runIdFilter:t.runIdFilter})}function pD(){return process.env.KYNVER_PIPELINE_CLEANUP!=="0"}var fD=p(()=>{"use strict";Lt();BN();WN();zN();h0();R0();C0();I0();T0();wn();vl();B0();W0();H0();G0();Yk();Y0();Z0();xc();eD();tD();oD();sD();aD()});function mD(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 Ip(e,t){let r=mD(e),n=mD(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 K5,A0e,ab=p(()=>{"use strict";$i();K5={"@kynver-app/runtime":"0.1.83","@kynver-app/openclaw-agent-os":"0.1.43","@kynver-app/mcp-agent-os":"0.3.34"},A0e=Object.keys(K5)});import{readFile as $5}from"node:fs/promises";import{homedir as H5}from"node:os";import Cn from"node:path";function ci(e){let t=e?.trim();return t||null}function V5(e){return[...new Set(e.filter(t=>!!t))]}function gD(){let e=H5(),t=ci(process.env.KYNVER_OPENCLAW_NPM_ROOT)??ci(process.env.OPENCLAW_NPM_ROOT)??Cn.join(e,".openclaw","npm"),r=ci(process.env.KYNVER_NPM_GLOBAL_ROOT)??ci(process.env.KYNVER_NPM_GLOBAL_MODULES_ROOT)??(ci(process.env.NPM_CONFIG_PREFIX)?Cn.join(ci(process.env.NPM_CONFIG_PREFIX),"lib","node_modules"):Cn.join(e,".npm-global","lib","node_modules"));return V5([Cn.join(t,"lib","node_modules"),Cn.join(t,"node_modules"),r.endsWith("node_modules")?r:Cn.join(r,"lib","node_modules")])}async function G5(e){try{let t=JSON.parse(await $5(e,"utf8"));return typeof t.version=="string"&&t.version.trim()?t.version.trim():null}catch{return null}}function hD(){return gD().map(e=>Cn.join(e,"@kynver-app"))}function lb(e){let t=gD(),r=new Set,n=[];for(let o of t){let s=Cn.join(o,e,"package.json");r.has(s)||(r.add(s),n.push(s))}return n}async function yD(e=new Date().toISOString()){let t={};for(let r of j5){let n=null;for(let o of lb(r)){let s=await G5(o);s&&(!n||Ip(s,n.version)>0)&&(n={version:s,path:o})}n&&(t[r]={version:n.version,observedAt:e,path:n.path})}return t}var j5,cb=p(()=>{"use strict";ab();j5=["@kynver-app/runtime","@kynver-app/openclaw-agent-os","@kynver-app/mcp-agent-os"]});import{spawnSync as J5}from"node:child_process";var q5,Y5,kD,bD=p(()=>{"use strict";q5=1e4,Y5=4*1024*1024,kD=(e,t,r)=>{try{let n=J5(e,t,{windowsHide:!0,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r?.timeoutMs??q5,maxBuffer:Y5});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 Pp(e,t,r){return`${e} ${t} ${r}`}function ub(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 vD(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 Op=p(()=>{"use strict"});function fb(){return Date.now()<db}function t9(e){let t=`${e.stdout}
|
|
196
|
+
${e.stderr}`.toLowerCase();return t.includes("api rate limit exceeded")||t.includes("rate limit exceeded")||t.includes("secondary rate limit")}function RD(e){t9(e)&&(db=Math.max(db,Date.now()+e9))}function pb(e,t){if(fb())return null;let r=e("gh",["api",...t]);if(!r.ok||!r.stdout.trim())return RD(r),null;try{return JSON.parse(r.stdout)}catch{return null}}function r9(e,t,r,n){if(fb())return null;let o=e("gh",["pr","view",String(r),"--repo",t,"--json",n.join(",")]);if(!o.ok||!o.stdout.trim())return RD(o),null;try{return JSON.parse(o.stdout)}catch{return null}}function mb(e){return fb()?!1:process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()?!0:e("gh",["auth","token"]).ok}function ui(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function n9(e){return Array.isArray(e)?e.map(t=>ui(t)).filter(t=>t!==null).slice(0,X5).map(t=>({context:t.context??null,state:t.state??null,target_url:t.target_url??null,description:t.description??null})):[]}function o9(e,t,r){let n=pb(e,[`repos/${t}/commits/${r}/status`]);return n?{state:n.state??null,statuses:n9(n.statuses)}:null}var z5,X5,Q5,Z5,e9,db,wD,SD,_D,xD=p(()=>{"use strict";Op();z5=8e3,X5=30,Q5=100,Z5=400,e9=3600*1e3,db=0;wD={provider:"github",kind:"pr_snapshot",version:"2",isAvailable:mb,collect(e,t){let r=vD(e);if(!r)return null;let n=r9(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=ui(n.author),s=ui(n.mergeCommit),i=ui(n.headRepositoryOwner),a=typeof n.body=="string"?n.body.slice(0,z5):null,l=Array.isArray(n.statusCheckRollup)?n.statusCheckRollup.map(u=>ui(u)).filter(u=>u!==null).slice(0,Q5).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=>ui(u)).map(u=>typeof u?.path=="string"?u.path.trim():"").filter(Boolean).slice(0,Z5):[];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}}},SD={provider:"github",kind:"commit_status",version:"1",isAvailable:mb,collect(e,t){let r=ub(e);return r?o9(t,r.repo,r.sha):null}},_D={provider:"github",kind:"branch_reachability",version:"1",isAvailable:mb,collect(e,t){let r=ub(e);if(!r)return null;let n=pb(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=pb(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 gb(e){hb.some(t=>t.provider===e.provider&&t.kind===e.kind)||hb.push(e)}function CD(e,t){return hb.find(r=>r.provider===e&&r.kind===t)??null}function ED(){gb(wD),gb(SD),gb(_D)}var hb,AD=p(()=>{"use strict";xD();hb=[]});function ID(e,t={}){ED();let r=t.run??kD,n=t.now??(()=>new Date),o=t.maxSubjects??s9,s=Date.now()+(t.deadlineMs??i9),i=new Set,a=e.filter(m=>{let g=Pp(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=Pp(m.provider,m.kind,m.subject),h=n(),k=t.cache?.get(g,h)??null;if(k){d.cached+=1,d.collected+=1,d.items.push(k);continue}if(Date.now()>s){d.skipped.push({...m,reason:"budget_exhausted"});continue}let v=CD(m.provider,m.kind);if(!v){d.skipped.push({...m,reason:"no_recipe"});continue}let y=`${v.provider} ${v.kind}`,b=f.get(y);if(b===void 0&&(b=v.isAvailable(r),f.set(y,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 S=v.collect(m.subject,r);if(S==null){d.skipped.push({...m,reason:"collect_failed"});continue}d.collected+=1;let w={provider:m.provider,kind:m.kind,subject:m.subject,payload:S,observedAt:n().toISOString(),collectorVersion:v.version};d.items.push(w),t.cache?.set(g,w,n())}return d}var s9,i9,PD=p(()=>{"use strict";bD();AD();Op();s9=1,i9=25e3});import OD from"node:path";function TD(e){return OD.join(J(e),a9)}function u9(e){return OD.join(J(e),l9)}function ND(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 DD(e){let t=K(TD(e),null);return ND(t?.wanted)}function MD(e,t){we(TD(e),{savedAt:new Date().toISOString(),wanted:t})}function LD(e,t={}){let r=t.ttlMs??c9,n=u9(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&&(we(n,{savedAt:new Date().toISOString(),items:s}),i=!1)}}}function BD(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.providerEvidenceWanted;return Array.isArray(t)?ND(t):null}var a9,l9,c9,yb=p(()=>{"use strict";Q();U();Op();a9="provider-evidence-wanted.json",l9="provider-evidence-cache.json",c9=600*1e3});import d9 from"node:path";function kb(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 h9(){return d9.join(ke().harnessRoot,p9)}function y9(e){let t=e.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),r=e==="github"?m9:g9;return kb(`KYNVER_PROVIDER_EVIDENCE_${t}_PER_MINUTE`,kb("KYNVER_PROVIDER_EVIDENCE_LIVE_COLLECTS_PER_MINUTE",r))}function UD(){return kb("KYNVER_PROVIDER_EVIDENCE_SHARED_CACHE_TTL_MS",f9)}function k9(e){return Math.floor(e.getTime()/6e4)*6e4}function b9(e){return`${e.provider}:${e.kind}`}function FD(e,t={}){let r=LD(e,{ttlMs:t.ttlMs??UD()}),n=t.file??h9(),o=K(n,null),s={...o?.items??{}},i={...o?.budget??{}},a=t.ttlMs??UD(),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=y9(u.provider);if(m===0)return!0;let g=b9(u),h=k9(f),k=i[g];return!k||k.windowStartMs!==h?(i[g]={windowStartMs:h,used:1},l=!0,!0):k.used>=m?!1:(k.used+=1,l=!0,!0)},flush(){r.flush(),l&&(we(n,{savedAt:new Date().toISOString(),items:s,budget:i}),l=!1)}}}var p9,f9,m9,g9,WD=p(()=>{"use strict";Q();U();yb();p9="provider-evidence-shared-cache.json",f9=6e4,m9=1,g9=1});function KD(e){let t=dC(),r=Tr(e?.env??process.env),n=(e?.now??(()=>new Date))().getTime(),o={};if(r.flags.dispatchReceipts!=="off"){Object.assign(o,MP());let s=DP({nowMs:n,hasLiveWorker:e?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,r.flags.dispatchReceipts==="enforce"&&Object.assign(o,gN())}return r.flags.planOutbox!=="off"&&Object.assign(o,YO()),r.flags.admission!=="off"&&(Object.assign(o,FP()),r.flags.admission==="enforce"&&Object.assign(o,HP())),(r.flags.keeper!=="off"||r.flags.meshLease!=="off"||r.flags.quota!=="off")&&Object.assign(o,wC()),{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 $D=p(()=>{"use strict";fn();Es();js();Wk();dl();ko();Gs();va()});import{createHash as HD}from"node:crypto";import{access as v9,mkdir as fDe,readFile as jD,rename as mDe,writeFile as gDe}from"node:fs/promises";import{constants as R9}from"node:fs";import{homedir as bb}from"node:os";import nt from"node:path";function _9(){return process.env.KYNVER_MCP_UPDATE_INVENTORY_FILE?.trim()||nt.join(bb(),".kynver","mcp-installations.json")}function x9(e){return e==="openclaw"?process.env.KYNVER_OPENCLAW_NPM_ROOT?.trim()||nt.join(bb(),".openclaw","npm"):process.env.KYNVER_NPM_GLOBAL_ROOT?.trim()||process.env.NPM_CONFIG_PREFIX?.trim()||nt.join(bb(),".npm-global")}function C9(e){let t=nt.resolve(e);if(nt.basename(t)!=="node_modules")return t;let r=nt.dirname(t);return nt.basename(r)==="lib"?nt.dirname(r):r}function E9(e,t){return[nt.join(e,"lib","node_modules",t,"package.json"),nt.join(e,"node_modules",t,"package.json")]}async function A9(e){try{return await v9(e,R9.R_OK),!0}catch{return!1}}async function vb(e=_9()){let t;try{t=JSON.parse(await jD(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||!S9.test(r.inventoryKey)||!w9.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 I9(e,t,r){if(typeof e.bin=="string")return nt.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"&&!nt.isAbsolute(s)&&!s.split(/[\\/]/).includes("..")?nt.join(r,s):null}function P9(e){return HD("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 O9(e){let t=[];for(let r of e){let n=C9(x9(r.prefix)),o=(await Promise.all(E9(n,r.packageName).map(async m=>({candidate:m,ok:await A9(m)})))).find(m=>m.ok)?.candidate;if(!o)continue;let s=JSON.parse(await jD(o,"utf8"));if(s.name!==r.packageName||typeof s.version!="string"||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(s.version))continue;let i=nt.dirname(o),a=I9(s,r,i),l=r.packageName==="@kynver-app/runtime",c=r.lifecycle??"runtime_stdio",u=HD("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:P9(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 VD(){return O9(await vb())}var w9,S9,Rb=p(()=>{"use strict";w9=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/i,S9=/^[A-Za-z0-9._:-]{8,128}$/});import{createHash as T9,createHmac as N9,timingSafeEqual as D9}from"node:crypto";function wb(e){let t=e.trim().split(".");return t.length!==3||t[0]!=="krc1"||!t[1]||!t[2]?null:{tokenId:t[1],tokenHash:T9("sha256").update(`krc1.${t[1]}.${t[2]}`,"utf8").digest("hex")}}function GD(e,t,r){let n=wb(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=N9("sha256",Buffer.from(n.tokenHash,"hex")).update(JSON.stringify(e.claims),"utf8").digest(),i=Buffer.from(e.signature,"base64url");return i.length===s.length&&D9(i,s)}var Sb=p(()=>{"use strict"});import{createHash as M9}from"node:crypto";import{access as _b,mkdtemp as L9,readFile as XD,rm as B9}from"node:fs/promises";import{constants as xb}from"node:fs";import{tmpdir as U9}from"node:os";import di from"node:path";import{spawn as F9}from"node:child_process";import{Client as W9}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as K9}from"@modelcontextprotocol/sdk/client/stdio.js";function QD(){return"npm"}function qD(e,t){return Buffer.byteLength(e)>=JD?e:(e+t.toString("utf8")).slice(0,JD)}function H9(e){let t=process.env.KYNVER_MCP_UPDATE_NPM_CACHE?.trim(),r=t&&di.isAbsolute(t)?t:e,n={PATH:process.env.PATH,SystemRoot:process.env.SystemRoot,TEMP:process.env.TEMP,TMP:process.env.TMP,npm_config_registry:Cb,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 ZD(e,t,r=Eb,n){return new Promise((o,s)=>{let i,a;try{[i,a]=se(e,t)}catch(m){s(m);return}let l=F9(i,a,{shell:!1,windowsHide:!0,detached:Re(),env:H9(n),stdio:["ignore","pipe","pipe"]}),c="",u="",d=!1;l.stdout.on("data",m=>{c=qD(c,m)}),l.stderr.on("data",m=>{u=qD(u,m)});let f=setTimeout(()=>{d=!0,l.pid&&he(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 j9(e,t){let[r,n]=t.split("-",2);return!n||!["sha256","sha384","sha512"].includes(r)?!1:M9(r).update(e).digest("base64")===n}async function V9(e,t,r,n){let o=await ZD(QD(),["pack",`${e}@${t}`,"--json","--pack-destination",n,`--registry=${Cb}`,"--ignore-scripts"],Eb,di.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"||di.basename(i)!==i)throw new Error("artifact_receipt_invalid");let a=di.join(n,i);if(!j9(await XD(a),r))throw new Error("artifact_integrity_mismatch");return a}async function G9(e,t,r){if((await ZD(QD(),["install","--global","--prefix",e,t,`--registry=${Cb}`,"--no-audit","--fund=false"],Eb,r)).code!==0)throw new Error("package_install_failed")}async function eM(e){let t=JSON.parse(await XD(e.local.packageJsonPath,"utf8"));if(t.name!==e.report.packageName||typeof t.version!="string")throw new Error("installed_identity_mismatch");return t.version}function J9(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 YD(e){if(!e.local.binPath)throw new Error("mcp_binary_missing");await _b(e.local.binPath,xb.X_OK).catch(async()=>_b(e.local.binPath,xb.R_OK));let t=new K9({command:e.local.binPath,args:[],env:J9(e.local.envAllowlist),stderr:"pipe"}),r=new W9({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")),$9)})]);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 zD(e,t,r,n,o){let s=await L9(di.join(U9(),"kynver-mcp-update-"));try{let i=await V9(t,r,n,s);if(await o(),await G9(e.local.prefix,i,di.join(s,"npm-cache")),await eM(e)!==r)throw new Error("installed_version_mismatch")}finally{await B9(s,{recursive:!0,force:!0})}}async function tM(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 _b(e.local.prefix,xb.W_OK).catch(()=>{throw new Error("npm_prefix_not_writable")});let o=await eM(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 zD(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 YD(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 zD(e,t.packageName,t.installedVersion,t.rollbackIntegrity,async()=>{await n.beforePackageMutation?.()}),e.local.lifecycle==="runtime_stdio"){let c=await YD(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 Cb,JD,Eb,$9,rM=p(()=>{"use strict";Go();We();Cb="https://registry.npmjs.org",JD=512*1024,Eb=2*6e4,$9=2e4});import{createHmac as q9,timingSafeEqual as Y9}from"node:crypto";import{mkdir as z9,readFile as X9,rename as Q9,writeFile as Z9}from"node:fs/promises";import{homedir as e7}from"node:os";import Ab from"node:path";function Sl(){return process.env.KYNVER_MCP_UPDATE_STATE_ROOT?.trim()||Ab.join(e7(),".kynver","state","mcp-updates")}function nM(e){if(!/^[A-Za-z0-9_-]{8,128}$/.test(e))throw new Error("invalid update operation identity");return Ab.join(Sl(),`${e}.json`)}function oM(e,t){let r=wb(t);return r?q9("sha256",Buffer.from(r.tokenHash,"hex")).update(JSON.stringify(e),"utf8").digest("base64url"):null}async function sM(e,t){try{let r=JSON.parse(await X9(nM(e),"utf8"));if(r.version!==2||r.operationId!==e||typeof r.integrityMac!="string")return null;let{integrityMac:n,...o}=r,s=oM(o,t);if(!s)return null;let i=Buffer.from(n,"utf8"),a=Buffer.from(s,"utf8");return i.length!==a.length||!Y9(i,a)?null:r}catch{return null}}async function iM(e,t){let r=oM(e,t);if(!r)throw new Error("invalid_runner_credential_for_receipt");let n=nM(e.operationId);await z9(Ab.dirname(n),{recursive:!0,mode:448});let o=`${n}.${process.pid}.tmp`;await Z9(o,`${JSON.stringify({...e,integrityMac:r},null,2)}
|
|
197
|
+
`,{mode:384}),await Q9(o,n)}var Tp=p(()=>{"use strict";Sb()});import{randomBytes as Ib}from"node:crypto";import{mkdir as Pb,readFile as Ob,rename as t7,rm as Np,stat as r7,writeFile as aM}from"node:fs/promises";import Eo from"node:path";function lM(){return Eo.join(Sl(),n7)}async function cM(){try{let e=JSON.parse(await Ob(Eo.join(lM(),"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:uM(e.pid)}}catch{return null}}function uM(e){if(!Number.isSafeInteger(e)||e<=0)return!0;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function o7(e){try{return await r7(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function dM(){return s7("mcp_update")}async function s7(e){let t=lM(),r=`${t}.reclaiming`;await Pb(Eo.dirname(t),{recursive:!0,mode:448});let n=!1;try{if(await o7(r))return null;for(let o=0;o<2;o+=1)try{await Pb(t,{mode:448});let s={pid:process.pid,nonce:Ib(18).toString("base64url"),acquiredAt:new Date().toISOString(),holder:e};return await aM(Eo.join(t,"owner.json"),JSON.stringify(s),{mode:384}),n&&(await Np(r,{recursive:!0,force:!0}),n=!1),{release:async()=>{try{let i=JSON.parse(await Ob(Eo.join(t,"owner.json"),"utf8"));i.pid===s.pid&&i.nonce===s.nonce&&await Np(t,{recursive:!0,force:!0})}catch{}}}}catch(s){if(s.code!=="EEXIST")throw s;if(!n)try{await Pb(r,{mode:448}),n=!0,await aM(Eo.join(r,"owner.json"),JSON.stringify({pid:process.pid,nonce:Ib(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 Ob(Eo.join(t,"owner.json"),"utf8"))}catch{return null}if(uM(i.pid))return null;let a=`${t}.stale-${process.pid}-${Ib(8).toString("hex")}`;await t7(t,a),await Np(a,{recursive:!0,force:!0})}return null}finally{n&&await Np(r,{recursive:!0,force:!0})}}var n7,pM=p(()=>{"use strict";Tp();n7="host-mutation.lock"});function Dp(e,t,r){return`${e}/api/agent-os/by-id/${encodeURIComponent(t)}/mcp-updates/${r}`}function i7(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 fM(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 a7(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 mM(e){let t=me(e.baseUrl),r=await VD();if(r.length===0)return{ok:!0,stage:"not_configured"};let n=await oo(Dp(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 dM();if(!o){let s=await cM();return{ok:!0,stage:"host_mutation_busy",...s?{heldBy:s.holder}:{}}}try{let s=await oo(Dp(t,e.agentOsId,"claim"),e.secret,{activeOwnedSessions:e.activeOwnedSessions});if(!s.ok)return{ok:!1,stage:"claim",status:s.status};let i=i7(s.response);if(!i)return{ok:!0,stage:"idle"};if(!GD(i,e.secret,e.agentOsId))return{ok:!1,stage:"command_auth"};let a=await sM(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||!fM(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 y=r.find(b=>b.report.inventoryKey===i.claims.inventoryKey);if(!y||y.report.inventoryFingerprint!==i.claims.inventoryFingerprint)return{ok:!1,stage:"inventory_changed"};l=y,c=a&&fM(a.recovery,i)?a.recovery:a7(y,i)}let u=a?.acceptedAt??new Date().toISOString(),d=async(y,b,S)=>{await iM({version:2,operationId:i.claims.operationId,attempt:i.claims.attempt,nonce:i.claims.nonce,acceptedAt:u,phase:y,terminal:b,...S?{outcome:S}:{},recovery:c},e.secret)};await d(a?.attempt===i.claims.attempt?a.phase:"claimed",!1);let f="claimed",m=async y=>{if(!(await oo(Dp(t,e.agentOsId,`operations/${encodeURIComponent(i.claims.operationId)}/events`),e.secret,{attempt:i.claims.attempt,fenceToken:i.claims.fenceToken,phase:y})).ok)throw new Error("progress_rejected");f=y,await d(y,!1)},g=y=>m(y),h=()=>m(f),k;try{k=await tM(l,i.claims,g,{recoveryVerifiedTargetInstalled:c.verifiedTargetInstalled,beforePackageMutation:h,onTargetInstalled:async()=>{c={...c,verifiedTargetInstalled:!0},await d("target_installed",!1)}})}catch(y){k={outcome:"failed",observedVersion:null,handshakeVerified:!1,toolCount:null,failureCode:y instanceof Error?y.message:"update_failed"}}let v=await oo(Dp(t,e.agentOsId,`operations/${encodeURIComponent(i.claims.operationId)}/complete`),e.secret,{attempt:i.claims.attempt,fenceToken:i.claims.fenceToken,...k});return v.ok?(await d(k.outcome,!0,k.outcome),{ok:k.outcome==="succeeded",stage:"complete",outcome:k.outcome}):{ok:!1,stage:"complete",status:v.status,outcome:k.outcome}}finally{await o.release()}}var gM=p(()=>{"use strict";$();Je();Rb();Sb();rM();pM();Tp()});import hM from"node:path";function l7(){let e=process.env.KYNVER_PIPELINE_SWEEP_ENABLED;return e?e==="1"||e.toLowerCase()==="true":!1}async function c7(e,t){let r=oe(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(hM.join(J(r.id),"workers",F(i),"worker.json"),void 0);if(!a?.taskId||a.localOnly||tn(a))continue;if(Va(a)){n.push({worker:i,ok:!0,taskId:a.taskId??null,skipped:!0});continue}if(s>=o)break;s++;let l=le(a);if(!He(l))continue;let c=ts({alive:l.alive,finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry});if(!a.dispatched&&!l.finalResult&&!c?.salvageable)continue;let u=await Qs({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 u7(e,t,r,n,o){let s=me(n.baseUrl?String(n.baseUrl):void 0),i=await ye(n.secret?String(n.secret):void 0,e,{baseUrl:s}),a=`${s}/api/agent-os/by-id/${encodeURIComponent(e)}/operator/tick`,l=await yD(),c=ks(t),u=null;try{let w=DD(t);if(w.length>0){let _=FD(t);u=ID(w,{cache:_}),_.flush?.()}else u=null}catch{u=null}try{if(Hr()!=="off"){let w=ss();UP({liveWorkers:w}),$P({liveWorkers:w})}else LP()}catch{}let d=({runId:w,workerName:_})=>{try{let{runsDir:R}=ke(),T=hM.join(Er(R,F(w)),"workers",F(_),"worker.json"),W=K(T,null);return W?tn(W):!1}catch{return!1}};await yN({agentOsId:e,baseUrl:s,secret:i,hasLiveWorker:d});let f=null;try{f=KD({hasLiveWorker:d})}catch{f=null}let m=null;try{m=Yc({control:nn(e),supervisor:o_(),inFlightWorkers:ss().length})}catch{m=null}let g=Fu(t),h=yE(),k=await fe(a,i,{agentOsId:e,runId:t,ingestHarness:!0,harnessBoardSnapshot:ik(t),resourceGate:r,boxResourceSnapshot:bN(r,{harnessRunId:t,boxKind:Dt(A())}),packageVersions:l,...o?{harnessCleanup:o}:{},runnerPresence:Fe({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=BD(k.response);if(v)try{MD(t,v)}catch{}let y=fE(k);if(y)try{pE(t,y)}catch{}let b=fC(k);b&&mC(e,b);let S=QS(k);return S&&sg(e,S),{ok:k.ok,httpStatus:k.status,response:k.response,...u?{providerEvidence:{attempted:u.attempted,collected:u.collected,skipped:u.skipped.length}}:{}}}async function Mp(e){let t=String(Nt(String(e.run||""),"--run")),r=String(Nt(String(e.agentOsId||""),"--agent-os-id")),n=e.execute!==!1&&e.execute!=="false";ik(t);let o=await $u(r,e),s=Ku(o),i=ea({runId:t,configuredMaxWorkersOverride:s}),a=pD()?dD(t):void 0,l=await u7(r,t,i,e,a),c;if(n)try{let O=me(e.baseUrl?String(e.baseUrl):void 0),L=await ye(e.secret?String(e.secret):void 0,r,{baseUrl:O});c=await mM({agentOsId:r,secret:L,baseUrl:O,activeOwnedSessions:ss().length})}catch(O){c={ok:!1,stage:"cycle",error:O instanceof Error?O.message:"update cycle failed"}}let u=hP(t,l),d=await iI(t,e),f=await c7(t,e);f.some(O=>O.ok&&!O.skipped)&&JC();let m=ea({runId:t,configuredMaxWorkersOverride:s}),g=Uk(),h=await SN(t,e),k=JT(m,l),v=k.maxStarts,y=nn(r),b=e_(y);b&&(v=0);let S=l7()?await fp({run:t,agentOsId:r,pipeline:!0,...e}):{ok:!0,skipped:!0,reason:"pipeline_sweep_disabled"},w=null,_=0,R=VT(l),T=v;if(n&&T>0&&R.length>0){let O=Math.min(T,R.length),L=await xk({...e,run:t,agentOsId:r,targetTaskIds:R.join(",")},O),M=ni(L);_+=M,T=Math.max(0,T-M),w={exactTargetTaskIds:R,exact:L,startedCount:_}}if(n&&T>0){let O=await xk({...e,run:t,agentOsId:r},T),L=ni(O);_+=L,w=w&&typeof w=="object"?{...w,broad:O,startedCount:_}:O}else!n||v<=0?w||(w={ok:!0,skipped:!0,reason:b??(n?m.reason??"no slots or queued work":"execute disabled"),maxStarts:0,dispatchAdvice:k,...R.length?{exactTargetTaskIds:R,exactOnly:!0}:{}}):w&&typeof w=="object"&&(w={...w,broadSkipped:!0,startedCount:_});let W=!k.underutilized&&v===0&&f.length===0&&_===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:S,dispatchAdvice:k,dispatch:w,idle:W,runtimeControl:y?{desiredState:y.desiredState,policyVersion:y.policyVersion}:null}}var Tb=p(()=>{"use strict";on();fu();$();Je();jT();GT();qT();Fk();is();ko();kN();Gs();vN();Bu();Q();Lt();Mc();Ie();Kk();U();_N();my();Zs();_d();Kc();Nh();$();Ke();fD();Ld();cb();Pr();PD();WD();yb();Ah();$D();dh();gM();Ih()});function Lp(e){return ls(nn(e))!=="stopped"?null:ss().length}var Nb=p(()=>{"use strict";is();on()});function yM(e){if(!e||typeof e!="object")return!1;let t=e;return t.type==="result"&&typeof t.id=="number"&&typeof t.ok=="boolean"}var kM=p(()=>{"use strict"});import{existsSync as d7}from"node:fs";import{fileURLToPath as p7}from"node:url";import{SHARE_ENV as f7,Worker as m7}from"node:worker_threads";function h7(e=import.meta.url){for(let t of[`./${bM}`,`../${bM}`]){let r=new URL(t,e);try{if(d7(p7(r)))return r}catch{}}return null}function y7(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??it()?{mode:"inline",reason:"desktop_sidecar"}:e.script?{mode:"thread",reason:"default"}:{mode:"inline",reason:"thread_entry_not_built"}}var bM,g7,k7,Bp,vM=p(()=>{"use strict";Tt();Ih();pn();Tb();Nb();kM();bM="daemon-tick-thread.js",g7=3;k7=(e,t)=>new m7(e,{workerData:t,env:f7,name:"kynver-pipeline-tick"}),Bp=class{constructor(t){this.options=t;this.script=t.script===void 0?h7():t.script;let r=y7({env:t.env,desktopMode:t.desktopMode,script:this.script});this.modeValue=r.mode,this.reason=r.reason,this.createWorker=t.createWorker??k7,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 hE(r),{tick:await Mp(t),inFlightWorkers:Lp(this.options.agentOsId),isolation:"inline"}}bundleIfChanged(){let t=Gx(),r=zt(),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(!yM(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>=g7&&(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 b7,performance as v7}from"node:perf_hooks";var R7,w7,S7,_7,RM,Up,wM=p(()=>{"use strict";R7=1e3,w7=250,S7=5,_7=5e3,RM=e=>Number.isFinite(e)?Math.round(e/1e6):0,Up=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??R7,this.sampleIntervalMs=t.sampleIntervalMs??w7,this.now=t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??(()=>v7.now()),this.log=t.log??(r=>console.error(r)),this.histogram=t.histogram??b7({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>_7)return this.histogram.reset(),this.phasesInWindow=new Set([this.phase]),null;let s=Math.max(0,Math.round(n-this.sampleIntervalMs)),i=RM(this.histogram.max),a=RM(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(-S7),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]}}}});function xM(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 CM(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 _M(e){let t=e?.code;return typeof t=="string"?t:null}function EM(e){if(!e)return!1;if(e instanceof En)return x7.has(e.status);let t=_M(e)??_M(e.cause);if(t&&C7.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 Db(e){return CM(e)?"aborted":EM(e)?"transient":"server"}function AM(e,t){let r=Db(e);if(r==="aborted")return t<=A7?0:I7;if(r==="transient"){let n=Math.max(0,Math.min(t-1,SM.length-1));return SM[n]}return E7}function IM(e,t){return e==="aborted"&&t<P7?{event:"chat_claim_poll_retry",level:"info"}:{event:"chat_claim_error",level:"error"}}var En,x7,C7,E7,A7,I7,SM,Fp,P7,Wp=p(()=>{"use strict";En=class extends Error{status;constructor(t){super(`claim failed: HTTP ${t}`),this.name="ClaimHttpError",this.status=t}},x7=new Set([502,503,504]),C7=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","ENETDOWN","UND_ERR_CONNECT_TIMEOUT"]),E7=5e3,A7=3,I7=1e3,SM=[0,1e3,5e3];Fp=class{counts={aborted:0,transient:0,server:0,auth:0,recovered:0};streakKind=null;streak=0;onError(t){let r=Db(t);return this.bump(r),{kind:r,consecutive:this.streak,backoffMs:AM(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}},P7=3});var O7,T7,N7,Kp,PM=p(()=>{"use strict";yr();O7=5*6e4,T7=5*6e4,N7=2160*60*60,Kp=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()>O7?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<T7)return;let r=`${this.deps.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(this.deps.agentOsId)}/runner-credentials`;try{let n=await bt(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({capabilities:["chat.relay"],ttlSeconds:N7,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 bt(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}}}});function OM(e=process.env){return e.KYNVER_OPENAI_DEFAULT_MODEL?.trim()||D7}var D7,cLe,TM=p(()=>{"use strict";Wa();ud();Qt();D7="gpt-5.5",cLe=600*1e3});function ir(e){let t=e.chatProvider?.trim();return pi(t||e.workerProvider?.trim()||"cursor")}function pi(e){let t=Xe(e);return t==="cursor"||t==="agent"?"cursor":B7.has(t)?"gemini":NM.has(t)||NM.has(e.trim().toLowerCase())?"codex":DM.has(t)||DM.has(e.trim().toLowerCase())?"openai":(L7.has(t),"anthropic")}function Ao(e,t,r=process.env){let n=r.KYNVER_CHAT_MODEL?.trim();if(n){if(e==="cursor"){let s=Ms(n,_l);return s.ok?s.model:_l}if(e==="gemini"&&!Mb.test(n)&&!Lb.test(n)||(e==="openai"||e==="codex")&&!Mb.test(n)&&!MM.test(n)||e==="anthropic")return n}let o=t.defaultModel?.trim();if(e==="cursor"){if(o&&!Mb.test(o)){let s=Ms(o,_l);return s.ok?s.model:_l}return _l}return e==="gemini"?o&&MM.test(o)?o:qe(r):e==="codex"?o&&Lb.test(o)?o:r.KYNVER_CODEX_DEFAULT_MODEL?.trim()||M7:e==="openai"?o&&Lb.test(o)?o:OM(r):o||$e}var _l,M7,L7,B7,NM,DM,Mb,MM,Lb,An=p(()=>{"use strict";so();Qt();Ka();TM();vr();od();_l="composer-2.5",M7=Us,L7=new Set(["claude","anthropic","opus"]),B7=new Set(["gemini","gemini-api"]),NM=new Set(["codex","chatgpt","gpt"]),DM=new Set(["openai","openai-compatible","openai-api","openai_api"]);Mb=/^(?:claude[-_]|opus\b|sonnet\b|haiku\b)/i,MM=/^(?:gemini[-_]|flash\b|pro\b)/i,Lb=/^(?:gpt-|o\d|chatgpt-)/i});var $p,LM=p(()=>{"use strict";$p=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 U7 from"node:os";function xl(e=process.env){let t=A(),r=Dt(t,e);return us({boxKind:r,hostLabel:U7.hostname(),config:t,env:e})}async function F7(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(),BM);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 W7(o)}async function W7(e){let t=new AbortController,r=setTimeout(()=>t.abort(),BM);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 Bb(e){return Ce()?!0:!!e&&!!_g(e)}async function Hp(e=process.env){let t=A(),r=t.agentOsId?.trim(),n=Ce();if(!r||!Bb(r))return null;let o=await F7(t.apiBaseUrl,n,e);if(!o)return null;let s=ir(t),i=t.apiBaseUrl?.replace(/\/$/,"")??o.replace(/\/$/,"");return{bridgeUrl:o.replace(/\/$/,""),agentOsId:r,apiKey:n??"",boxId:xl(e),chatProvider:s,model:Ao(s,t,e),useClaudeOauth:t.chatUseClaudeOauth===!0,auth:new Kp({apiBaseUrl:i,agentOsId:r,boxLabel:()=>xl(e),loadApiKey:Ce,loadBoxCredential:()=>_g(r),saveBoxCredential:a=>M_(r,a),clearBoxCredential:L_}),security:new $p,apiBaseUrl:i}}var BM,jp=p(()=>{"use strict";$();Ke();ds();PM();An();LM();BM=5e3});import{verify as K7,createPublicKey as $7}from"node:crypto";function V7(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 UM(e){return!e||typeof e!="object"||Array.isArray(e)?null:e[H7]??null}function G7(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function J7(e,t){let r=Date.parse(e),n=Date.parse(t);return Number.isNaN(r)?!1:Number.isNaN(n)?!0:r>n}function Ub(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(!V7(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||!G7(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=eo(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(dt(s),"utf8"),d=$7({key:Buffer.concat([j7,Buffer.from(i)]),format:"der",type:"spki"});l=K7(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||!J7(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 PLe,H7,j7,FM=p(()=>{"use strict";an();pa();PLe=720*60*60,H7="change",j7=Buffer.from("302a300506032b6570032100","hex")});function WM(e){switch(e){case"off":return 0;case"folder":case"folders":return 1;case"full":return 2;default:return 0}}function q7(e,t){let r=WM(e.access),n=WM(t.access);if(r!==n)return r>n;if(r!==1)return!1;let o=new Set(Gn(t.folders));return Gn(e.folders).some(s=>!o.has(s))}function Y7(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=ps(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:UM(r)}}function $M(e){let t=Y7(e.signedAccess,e.boxId);if(!t)return{ok:!0,website:null,raised:!1};let r=ps(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:Gn(e.local.chatWorkFolders)}:{access:ou(e.engine),folders:[]});let o=n.every(c=>q7(t.level,c)),s=(e.now??(()=>new Date))().toISOString(),i=e.state.website;if(!o){let c=t.change!==null?Ub(t.change,{agentOsId:e.agentOsId,boxId:e.boxId,access:t.level.access,folders:t.level.folders},{env:e.env,nowSec:e.nowSec,lastApplied:KM(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=Ub(t.change,{agentOsId:e.agentOsId,boxId:e.boxId,access:t.level.access,folders:t.level.folders},{env:e.env,nowSec:e.nowSec,lastApplied:KM(i)}),l=i?.access??r??ou(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 KM(e){return!e||!e.changedAt&&!e.nonce?null:{changedAt:e.changedAt,nonce:e.nonce}}var HM=p(()=>{"use strict";FM();Jn()});import{existsSync as z7,mkdirSync as X7,readFileSync as Q7,writeFileSync as Z7}from"node:fs";import{homedir as eQ}from"node:os";import Fb from"node:path";function Wb(e=eQ()){return Fb.join(e,tQ)}function jM(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function rQ(e){return typeof e.access!="string"?null:{access:e.access,folders:jM(e.folders),source:e.source??"default",signed:e.signed===!0,at:typeof e.at=="string"?e.at:""}}function nQ(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(typeof r.access=="string")return{access:r.access,folders:jM(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 Vp(e=Wb()){try{if(!z7(e))return{applied:null,website:null};let t=JSON.parse(Q7(e,"utf8"));if(!t||typeof t!="object")return{applied:null,website:null};let r=rQ(t);return{applied:r,website:nQ(t.website,r)}}catch{return{applied:null,website:null}}}function VM(e,t){try{X7(Fb.dirname(e),{recursive:!0});let r={...t.applied??{},...t.website?{website:t.website}:{}};Z7(e,`${JSON.stringify(r,null,2)}
|
|
198
|
+
`,{mode:384})}catch{}}function oQ(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 GM(e,t={signed:!1}){let r=t.file??Wb(),n=t.now??(()=>new Date),o={access:e.access,folders:[...e.folders],source:e.source,signed:t.signed,at:n().toISOString()},s=Vp(r);return oQ(s.applied,o)?null:(VM(r,{applied:o,website:s.website}),{from:s.applied,to:o})}function JM(e,t={}){let r=t.file??Wb(),n=t.now??(()=>new Date),o=Vp(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:(VM(r,{applied:o.applied,website:s}),s)}function fi(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 tQ,Kb=p(()=>{"use strict";tQ=Fb.join(".kynver","chat-access-state.json")});import{appendFileSync as sQ,mkdirSync as iQ}from"node:fs";import{homedir as aQ}from"node:os";import $b from"node:path";function Hb(e=aQ()){return $b.join(e,lQ)}function jb(e){let t=r=>r===void 0?void 0:r.length>qM?`${r.slice(0,qM)}\u2026`:r;return{...e,...e.command!==void 0?{command:t(e.command)}:{},...e.path!==void 0?{path:t(e.path)}:{}}}function mi(e,t=Hb()){try{return iQ($b.dirname(t),{recursive:!0}),sQ(t,`${JSON.stringify(jb(e))}
|
|
199
|
+
`,{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 lQ,qM,Cl=p(()=>{"use strict";lQ=$b.join(".kynver","logs","chat-commands.jsonl"),qM=2e3});function cQ(e){let r=e.chatProvider?.trim()||e.workerProvider?.trim()||"";return Xe(r)}function Io(e,t=process.env){return cQ(e)!=="gemini"?"http":Ws(_t(t))==="antigravity"?"antigravity":"http"}var Gp=p(()=>{"use strict";ho();ia()});import{execFile as uQ,spawnSync as QM}from"node:child_process";import{existsSync as dQ,readFileSync as pQ}from"node:fs";import{homedir as fQ,platform as mQ}from"node:os";import YM from"node:path";function Yp(e,t,r=process.env){return e==="cursor"?"cursor":e==="codex"?"codex":e==="gemini"?Io(t,r)==="antigravity"?"antigravity":"none":e==="anthropic"?"claude-code":"none"}function gQ(e,t){return e==="cursor"?co(t):e==="codex"?t.KYNVER_CODEX_BIN?.trim()||t.CODEX_BIN?.trim()||Ur():e==="antigravity"?_t(t):e==="claude-code"?t.KYNVER_CLAUDE_BIN?.trim()||t.CLAUDE_BIN?.trim()||"claude":null}function zM(e,t,r){let n=`${t??""} ${r??""}`;return e===0?n.match(hQ)?.[0]??null:null}function zp(e,t=process.env,r=Date.now()){let n=gQ(e,t);if(!n)return null;let o=Jp.get(n);if(o&&r-o.at<ZM)return o.version;if(o){if(!qp.has(n)){qp.add(n);try{let[i,a]=se(n,["--version"]);uQ(i,a,Z({encoding:"utf8",timeout:5e3}),(l,c,u)=>{qp.delete(n),Jp.set(n,{at:Date.now(),version:l?null:zM(0,c,u)})})}catch{qp.delete(n),Jp.set(n,{at:r,version:o.version})}}return o.version}let s=null;try{let[i,a]=se(n,["--version"]),l=QM(i,a,Z({encoding:"utf8",timeout:5e3}));s=zM(l.status,l.stdout,l.stderr)}catch{s=null}return Jp.set(n,{at:r,version:s}),s}function Xp(e=process.env,t={}){if(e.ANTHROPIC_API_KEY?.trim())return!0;let r=t.home??fQ(),n=t.now??Date.now(),o=XM.get(r);if(o&&n-o.at<ZM)return o.signedIn;let s=yQ(YM.join(e.CLAUDE_CONFIG_DIR?.trim()||YM.join(r,".claude"),".credentials.json"));return!s&&(t.os??mQ())==="darwin"&&(s=(t.keychain??kQ)()),XM.set(r,{at:n,signedIn:s}),s}function yQ(e){if(!dQ(e))return!1;try{let t=JSON.parse(pQ(e,"utf8")).claudeAiOauth,r=n=>typeof n=="string"&&n.length>0;return!!t&&(r(t.refreshToken)||r(t.accessToken))}catch{return!1}}function kQ(){try{return QM("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}var hQ,ZM,Jp,qp,XM,El=p(()=>{"use strict";fo();Ls();ho();We();U();Gp();hQ=/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/,ZM=10*6e4,Jp=new Map,qp=new Set;XM=new Map});import{createHash as bQ,verify as vQ,createPublicKey as RQ}from"node:crypto";function Gb(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};return delete t[eL],t}function SQ(e){return bQ("sha256").update(dt(Gb(e)),"utf8").digest("hex")}function Jb(e){return!e||typeof e!="object"||Array.isArray(e)?null:e[eL]??null}function _Q(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 xQ(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:dt(r)===dt(t)}function Vb(e,t){return{state:t,firstSeenAt:new Date(e.firstSeenSec*1e3).toISOString(),turnId:e.turnId}}function CQ(e){return RQ({key:Buffer.concat([wQ,Buffer.from(e)]),format:"der",type:"spki"})}function tL(e,t,r={}){let n=r.env??process.env,o=r.nowSec??Math.floor(Date.now()/1e3),s=Jb(e);if(s===null)return{ok:!1,code:"unsigned",reason:"turn carries no signed envelope"};if(!_Q(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=eo(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(dt(i.payload),"utf8");c=vQ(null,d,CQ(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(SQ(e)!==i.payload.payloadHash)return{ok:!1,code:"payload_tampered",reason:"turn payload does not match its signed hash"};if(!xQ(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 (${EQ(u.replay)})`,replay:u.replay}}function EQ(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 eL,wQ,Qp,Zp=p(()=>{"use strict";an();pa();eL="turnEnvelope",wQ=Buffer.from("302a300506032b6570032100","hex");Qp=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:Vb(n,"turn_mismatch")}:n.state==="verified"?{ok:!0,redelivered:!0}:{ok:!1,replay:Vb(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:Vb(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 rL(e=process.env,t={}){let r=(e[AQ]??t.chatTurnSignature??"").toString().trim().toLowerCase();return r==="optional"||r==="off"||r==="0"||r==="false"?"optional":"required"}function nL(e,t){return t?`turn_rejected_${e}: ${t}`:`turn_rejected_${e}`}function oL(e,t){if(!(Jb(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:IQ(o)?o:null,signed:!1,userId:null,redelivered:!1}}let n=tL(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 IQ(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.byBox;return!!t&&typeof t=="object"&&!Array.isArray(t)}var AQ,qb=p(()=>{"use strict";Zp();AQ="KYNVER_CHAT_TURN_SIGNATURE"});function Yb(e){return typeof e=="string"&&TQ.test(e.trim())?e.trim():null}function ef(e){return`Kynver conversation id: ${e}. When work you start from this conversation later finishes, fails, needs the user or opens / merges a PR, post the update here only: \`kynver tab post --conversation ${e} "<text>"\` (or the agent_tab_post tool with this conversationId). When you create a Kynver task for it, pass originConversationId=${e} so its updates come back here too.`}function iL(e,t){let r=Yb(e);return r?{[PQ]:r,[OQ]:t}:{}}var PQ,OQ,sL,TQ,tf=p(()=>{"use strict";PQ="KYNVER_CONVERSATION",OQ="KYNVER_AGENT_TAB_ENGINE",sL="X-Kynver-Conversation",TQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i});function DQ(e){return typeof e=="string"&&NQ.includes(e)}function lL(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"||!FQ.test(t.sessionKey))return null;let r=typeof t.text=="string"?t.text.slice(0,aL):"",n=[],o=0;if(Array.isArray(t.attachments))for(let c of t.attachments.slice(0,BQ)){if(!c||typeof c!="object")continue;let{name:u,mime:d,contentBase64:f}=c;if(!(typeof u!="string"||typeof f!="string")){if(o+=Math.floor(f.length*3/4),o>UQ)break;n.push({name:u.slice(0,200),mime:typeof d=="string"?d.slice(0,100):"application/octet-stream",contentBase64:f})}}let s=WQ(t.control);if(!s&&!r.trim()&&n.length===0)return null;let i=typeof t.styleNote=="string"?t.styleNote.trim().slice(0,LQ):"",a=typeof t.replyTurnId=="string"&&MQ.test(t.replyTurnId)?t.replyTurnId:null,l=Yb(t.conversationId);return{kind:"agent-tab",engine:t.engine,sessionKey:t.sessionKey,text:r,attachments:n,...t.computerAccess!==void 0?{computerAccess:t.computerAccess}:{},...i?{styleNote:i}:{},...a?{replyTurnId:a}:{},...s?{control:s}:{},...l?{conversationId:l}:{}}}function WQ(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.op==="stop"?{op:"stop"}:t.op==="steer"&&typeof t.text=="string"&&t.text.trim()?{op:"steer",text:t.text.slice(0,aL)}:null}var NQ,rf,MQ,aL,LQ,BQ,UQ,FQ,zb=p(()=>{"use strict";tf();NQ=["hermes","openclaw","claude-code","grok-bot"],rf={hermes:"Hermes",openclaw:"OpenClaw","claude-code":"Claude Code","grok-bot":"Grok Bot"};MQ=/^[A-Za-z0-9-]{8,64}$/,aL=32e3,LQ=4e3,BQ=5,UQ=20*1024*1024,FQ=/^[A-Za-z0-9_.:-]{8,128}$/});import{createHash as KQ}from"node:crypto";function GQ(e){return`${e.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/agent-tabs/box`}function JQ(e,t,r){let n=e.trim()?e:`${t} finished without writing a reply.`;return r.length>0&&(n+=`
|
|
200
200
|
|
|
201
|
-
_${r.length===1?"A file":`${r.length} files`} couldn't be attached: ${r.join(", ")}._`),n.length>
|
|
202
|
-
`).filter(Boolean)}finally{
|
|
203
|
-
`,{encoding:"utf8",mode:384})}catch{}}function
|
|
204
|
-
`)||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&&!
|
|
205
|
-
${r}`)?!1:e===0}function ML(e,t=process.env){try{let[r,n]=ie(e,["models"]),o=PZ(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"}:TZ(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 OZ,LL=p(()=>{"use strict";Fe();OZ=/authentication required|not logged in|you are not logged|not authenticated/i});import{existsSync as NZ,readFileSync as DZ}from"node:fs";import{homedir as MZ}from"node:os";import BL from"node:path";import{spawnSync as LZ}from"node:child_process";function BZ(e){if(BL.isAbsolute(e)||e.includes("/")||e.includes("\\"))return NZ(e);try{let t=LZ(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function UZ(){return BL.join(MZ(),".gemini","antigravity-cli","settings.json")}function FZ(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 WZ(){try{return DZ(UZ(),"utf8")}catch{return null}}function KZ(e,t){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()?FZ(t)==="gemini":!1}function UL(e){return`${e.error}: ${e.detail}`}function ff(e=process.env,t={}){let r=St(e);if(!(t.commandOnPath??BZ)(r))return{ok:!1,error:df,detail:"`agy` not found. Install Google Antigravity (https://antigravity.google/docs/cli/install) and keep `agy` on PATH."};if((t.probeAuth??ML)(r,e).ok)return{ok:!0,creds:{bin:r,authSource:"keyring"}};let s=(t.readSettings??(()=>WZ()))(e);return KZ(e,s)?{ok:!0,creds:{bin:r,authSource:"api_key_settings"}}:{ok:!1,error:pf,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 df,pf,mf=p(()=>{"use strict";go();LL();df="antigravity_cli_unavailable",pf="antigravity_not_logged_in"});function Ol(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()||$Z).replace(/\/+$/,"");return{apiKey:t,baseUrl:r,label:"gemini"}}function Tl(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()||HZ).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 $Z,HZ,rv=p(()=>{"use strict";$Z="https://generativelanguage.googleapis.com/v1beta/openai",HZ="https://api.openai.com/v1"});function VZ(e,t=process.env){return{anthropic:()=>{let r=Il(t,{oauthOptIn:e.chatUseClaudeOauth===!0});return r?r.kind==="oauth"?"subscription":"api_key":null},codex:()=>{let r=cf(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},cursor:()=>{let r=td(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},gemini:()=>{let r=t;if(Ao({chatProvider:e.chatProvider,workerProvider:e.workerProvider},r)==="antigravity"){let n=ff(r);return n.ok?n.creds.authSource==="api_key_settings"?"api_key":"subscription":null}return Ol(t)?"api_key":null},openai:()=>Tl(t)?"api_key":null}}function GZ(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:di(r.slice(0,n)),model:o})}return t}function nv(e,t){let r=t?.trim();r&&!e.includes(r)&&e.push(r)}function JZ(e,t,r=process.env){let n=sr(e),o=GZ(r.KYNVER_CHAT_EXTRA_MODELS),s=[];for(let i of ov){let a=null;try{a=t[i]()}catch{a=null}if(!a)continue;let l=i===n?Eo(i,e,r):Eo(i,{},{...r,KYNVER_CHAT_MODEL:void 0}),c=[];nv(c,l);for(let u of jZ[i])nv(c,u);for(let u of o)u.provider===i&&nv(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 yi(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(Nl&&Nl.key===n&&r-Nl.at<qZ)return Nl.value;let o=JZ(e,VZ(e,t),t);return Nl={key:n,at:r,value:o},o}var ov,jZ,qZ,Nl,Dl=p(()=>{"use strict";br();ev();uf();Ls();mf();Vp();rv();En();ov=["anthropic","codex","openai","gemini","cursor"],jZ={anthropic:nS,codex:["gpt-5.6-sol","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"]};qZ=6e4,Nl=null});function Ml(e){if(typeof e=="string"){let n=e.indexOf(":");return n<=0?null:Ml({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:di(t.provider),model:r}}function WL(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 KL(e,t){for(let r of ov){if(t.includes(r))continue;let n=e.find(o=>o.provider===r);if(n)return{provider:r,model:n.defaultModel}}return null}function $L(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return t?YZ.some(r=>r.test(t)):!1}function FL(e){return zZ[e]}function HL(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 jL(e,t){let r=`${FL(e.provider)} (${e.model})`;if(e.fallbackReason==="usage_limit")return`${t?FL(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 YZ,zZ,sv=p(()=>{"use strict";Dl();En();YZ=[/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/];zZ={anthropic:"Claude",codex:"ChatGPT",openai:"ChatGPT",gemini:"Gemini",cursor:"Cursor"}});async function $t(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 iv=p(()=>{"use strict"});function GL(e){if(!e||typeof e!="object")return!1;let t=e;return!(typeof t.type!="string"||!XZ.has(t.type)||t.type==="text"&&(typeof t.text!="string"||!t.text.trim()))}function VL(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:Ll}]}:null;if(!Array.isArray(t.content)||t.content.length===0)return null;let r=t.content[t.content.length-1];return GL(r)?{...t,content:[...t.content.slice(0,-1),{...r,cache_control:Ll}]}:null}function QZ(e){return Array.isArray(e)&&e.length>0&&e.every(t=>!!t&&typeof t=="object"&&t.type==="tool_result")}function ZZ(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!(!r||typeof r!="object"||r.role!=="user")&&!QZ(r.content))return t}return-1}function av(e){return JSON.stringify(e??null).includes('"cache_control"')}function JL(e){if(av(e.system)||av(e.tools)||av(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:Ll},...t.slice(a+1)])}let r=e.system;if(typeof r=="string")r.trim()&&(r=[{type:"text",text:r,cache_control:Ll}]);else if(Array.isArray(r)&&r.length>0){let i=r[r.length-1];GL(i)&&(r=[...r.slice(0,-1),{...i,cache_control:Ll}])}let n=[...e.messages],o=-1;for(let i=n.length-1;i>=0;i-=1){let a=VL(n[i]);if(a){n[i]=a,o=i;break}}let s=ZZ(n)-1;if(s>=0&&s<o)for(let i=s;i>=0;i-=1){let a=VL(n[i]);if(a){n[i]=a;break}}return{system:r,tools:t,messages:n}}var Ll,XZ,qL=p(()=>{"use strict";Ll={type:"ephemeral"},XZ=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 YL(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 tee(){return{blocks:[],stopReason:null,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}}function ree(e){let t=e;return t.type==="content_block_start"&&t.content_block?.type==="tool_use"?!0:t.type==="content_block_delta"&&t.delta?.type==="input_json_delta"}function nee(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 oee(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*see(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
|
|
201
|
+
_${r.length===1?"A file":`${r.length} files`} couldn't be attached: ${r.join(", ")}._`),n.length>cL?`${n.slice(0,cL-1)}\u2026`:n}function dL(e){let t=e.fetchFn??fetch,r=e.wait??VQ,n=e.redactText??(c=>dO(e.agentOsId,c)),o=c=>{let u=fO(e.agentOsId,c),d;try{d=new TextDecoder("utf-8",{fatal:!0}).decode(u)}catch{return u}if(d.includes("\0"))return u;let f=n(d);return f===d?u:Buffer.from(f,"utf8")},s=GQ(e),i=new URL(e.apiBaseUrl).origin,a=async(c,u)=>{let f={Authorization:`Bearer ${await e.bearer()}`},m=u.body;u.json!==void 0&&(f["Content-Type"]="application/json",m=JSON.stringify(u.json));let g=await t(c,{method:u.method??"POST",headers:f,body:m});return g.status===401&&e.onUnauthorized?.(),g},l=async c=>{try{let u=o(Buffer.from(c.contentBase64,"base64")),d=KQ("sha256").update(u).digest("hex"),f=await a(`${s}/uploads`,{json:{name:n(c.name).slice(0,200),size:u.length,sha256:d}});if(!f.ok)return null;let m=await f.json();for(let k=0;k<m.parts;k++){let v=u.subarray(k*m.partBytes,(k+1)*m.partBytes),y=new URL(m.partUrl.replace("{index}",String(k)),i).toString(),b=!1;for(let S=0;S<3&&!b;S++)b=!!(await t(y,{method:"PUT",body:new Uint8Array(v)}).catch(()=>null))?.ok,b||await r(1e3*(S+1));if(!b)return null}let g=await a(new URL(m.completeUrl,i).toString(),{method:"POST"});if(!g.ok)return null;let h=await g.json();return typeof h.file?.id=="string"?h.file.id:null}catch{return null}};return{async heartbeat(c){try{let u=await a(`${s}/turns/${encodeURIComponent(c)}/heartbeat`,{json:{}});if(u.status!==404&&u.status!==410)return"continue";let d=await u.json().catch(()=>null);return d?.code==="turn_stopped"?"stop":u.status===404&&d?.code==="turn_unknown"?"continue":"gone"}catch{return"continue"}},async deliver({replyTurnId:c,engine:u,text:d,files:f}){let m=[],g=[],h=0;for(let v of f.slice(0,jQ)){let y=v.sizeBytes??Math.floor(v.contentBase64.length*3/4),b=n(v.name).slice(0,200);if(y<=$Q&&h+y<=HQ){let w=o(Buffer.from(v.contentBase64,"base64"));h+=w.length,m.push({name:b,contentBase64:w.toString("base64")});continue}let S=await l(v);S?m.push({fileId:S}):g.push(b.slice(0,80))}let k={engine:u,idempotencyKey:`turn-reply:${c}`,turnId:c,text:JQ(n(d),qQ[u],g),attachments:m,notify:!0};for(let v=0;;v++){let y=0;try{let S=await a(`${s}/posts`,{json:k});if(y=S.status,S.ok)return!0}catch{y=0}if(!(y===0||y===401||y===408||y===429||y>=500)||v>=uL.length)return!1;await r(uL[v])}}}}var cL,$Q,HQ,jQ,uL,VQ,qQ,pL=p(()=>{"use strict";jr();zb();cL=32e3,$Q=8*1024*1024,HQ=20*1024*1024,jQ=10,uL=[2e3,4e3,8e3,16e3,32e3],VQ=e=>new Promise(t=>setTimeout(t,e));qQ=rf});async function gi(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 qr(e,t,r){r===401&&t.kind==="box_token"&&e.auth?.invalidateToken()}var hi=p(()=>{"use strict"});import{closeSync as YQ,existsSync as zQ,fstatSync as XQ,openSync as QQ,readSync as ZQ}from"node:fs";function mL(e){if(!(typeof e!="string"||!e.trim()))return e.length>fL?`${e.slice(0,fL)}\u2026`:e}function hL(){return{lastSuccessAt:null,lastSuccessKind:null,steps24h:0,failures24h:{},recentFailures:[]}}function oZ(e,t){let r=hL(),n=[];for(let o of e){let s;try{s=JSON.parse(o)}catch{continue}let i=typeof s.at=="string"?Date.parse(s.at):Number.NaN;if(!Number.isNaN(i)&&(s.ok===!0&&(!r.lastSuccessAt||i>=Date.parse(r.lastSuccessAt))&&(r.lastSuccessAt=new Date(i).toISOString(),r.lastSuccessKind=s.kind??null),!(t-i>nZ)&&(r.steps24h+=1,s.ok===!1))){let a=typeof s.reason=="string"&&/^[a-z_]{1,40}$/.test(s.reason)?s.reason:"other";r.failures24h[a]=(r.failures24h[a]??0)+1;let l=mL(s.command),c=mL(s.path);n.push({at:new Date(i).toISOString(),kind:typeof s.kind=="string"?s.kind:null,...l?{command:l}:{},...c?{path:c}:{},...typeof s.exitCode=="number"&&Number.isFinite(s.exitCode)?{exitCode:Math.trunc(s.exitCode)}:{},reason:a})}}return r.recentFailures=n.sort((o,s)=>Date.parse(s.at)-Date.parse(o.at)).slice(0,eZ),r}function sZ(e){if(!zQ(e))return[];let t=QQ(e,"r");try{let r=XQ(t).size,n=Math.min(r,tZ),o=Buffer.alloc(n);return ZQ(t,o,0,n,r-n),o.toString("utf8").split(`
|
|
202
|
+
`).filter(Boolean)}finally{YQ(t)}}function nf(e=Hb(),t=Date.now()){let r=gL.get(e);if(r&&t-r.at<rZ)return r.summary;let n;try{n=oZ(sZ(e),t)}catch{n=hL()}return gL.set(e,{at:t,summary:n}),n}var eZ,fL,tZ,rZ,nZ,gL,Xb=p(()=>{"use strict";Cl();eZ=20,fL=240;tZ=512*1024,rZ=3e4,nZ=1440*60*1e3;gL=new Map});import{appendFileSync as iZ,mkdirSync as aZ}from"node:fs";import{homedir as lZ}from"node:os";import Qb from"node:path";function yL(e=lZ()){return Qb.join(e,cZ)}function kL(e){let r=(e instanceof Error?e.message:String(e)).split(":")[0].trim();return/^[a-z_]{1,40}$/.test(r)?r:"other"}function bL(e,t=yL()){try{aZ(Qb.dirname(t),{recursive:!0}),iZ(t,`${JSON.stringify({kind:"step",...e})}
|
|
203
|
+
`,{encoding:"utf8",mode:384})}catch{}}function vL(e=yL()){return nf(e)}var cZ,Zb=p(()=>{"use strict";Xb();cZ=Qb.join(".kynver","logs","chat-claude-code-steps.jsonl")});function Po(e){let t=Yp(e.provider,e.config,e.env??process.env),r=e.boxId?nu(e.payloadAccess,e.boxId):null,n=fs({engine:t,local:{chatComputerAccess:e.config.chatComputerAccess,chatWorkFolders:e.config.chatWorkFolders},website:r,home:e.home});return{engine:t,access:n}}var of=p(()=>{"use strict";El();Jn()});function RL(e,t,r={}){let n=r.env??process.env,{engine:o,access:s}=Po({provider:e,config:t,env:n});return{access:s.access,folders:s.folders.map(ze),source:s.source==="website"?"local":s.source,engine:o,engineVersion:o==="none"?null:(r.version??zp)(o,n),log:(r.summary??nf)(),...o==="claude-code"?{claudeCode:{signedIn:(r.signedIn??Xp)(n),steps:(r.stepSummary??vL)()}}:{}}}var wL=p(()=>{"use strict";ht();El();Zb();of();Xb()});function SL(e){try{return Ze().report(e)}catch{return null}}function sf(e,t){try{return RL(e,t)}catch{return}}function Al(){try{return B_().apiKey}catch{return"none"}}async function yi(e,t){for(let n=0;n<e&&!t();n+=500)await new Promise(o=>setTimeout(o,Math.min(500,e-n)))}var Oo,af=p(()=>{"use strict";$();vs();wL();hi();Oo=gi});function _L(e){let t=null;return dL({apiBaseUrl:e.apiBaseUrl??new URL(e.bridgeUrl).origin,agentOsId:e.agentOsId,bearer:async()=>(t=await Oo(e),t.bearer),onUnauthorized:()=>{t&&qr(e,t,401)}})}async function Ee(e,t,r){let n=await Oo(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:ip(e.agentOsId,r)})});return qr(e,n,o.status),o.ok}var Il=p(()=>{"use strict";pL();hi();jr();af()});async function xL(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??{}})),mi({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 Ee(e,t.turnId,[{seq:0,kind:"error",error:nL(r.code,r.detail)}]).catch(()=>{}),{ok:!1}}async function ev(e,t,r){let n=oL({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}):xL(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=A()}catch{o={}}let s=$M({signedAccess:n.access,boxId:e.boxId,agentOsId:e.agentOsId,engine:Yp(e.chatProvider,o,r.env??process.env),local:{chatComputerAccess:o.chatComputerAccess,chatWorkFolders:o.chatWorkFolders},state:Vp(r.stateFile),env:r.env,nowSec:r.nowSec});if(!s.ok)return xL(e,t,{code:s.code,detail:s.detail,reason:s.reason,policy:r.policy,extra:{from:fi(s.from),to:fi(s.to),signed:n.signed}});s.website&&JM(s.website,{file:r.stateFile});let a={...Gb(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}}var tv=p(()=>{"use strict";$();HM();Kb();Cl();El();Zp();qb();Il()});var uZ,In,lf=p(()=>{"use strict";nk();uZ=150,In=class{constructor(t,r=uZ,n,o=!1){this.flushFn=t;this.floorMs=r;this.leading=o;this.stream=n&&!n.empty?uO(n,s=>{s&&this.flushFn(s)}):null}flushFn;floorMs;leading;buffer="";timer=null;closed=!1;sentAny=!1;stream;push(t){if(!(this.closed||!t)){if(this.buffer+=t,this.leading&&!this.sentAny){this.sentAny=!0,this.flushNow();return}this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flushNow()},this.floorMs))}}flushNow(t=!1){let r=this.buffer;if(this.buffer="",this.stream){r&&this.stream.write(r),t&&this.stream.flush();return}r&&this.flushFn(r)}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(!0))}}});function CL(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(gZ.some(o=>n===o||n.startsWith(`${o}=`)))return{ok:!1,mutating:!1,reason:`forbidden flag: ${n}`};if(n.includes(`
|
|
204
|
+
`)||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&&!hZ.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:fZ}:r==="run dispatch"?{ok:!1,mutating:!0,reason:pZ}:dZ.has(r)?{ok:!0,mutating:!1}:mZ.has(r)?{ok:!0,mutating:!0}:{ok:!1,mutating:!1,reason:`verb not allowlisted: ${r}`}}var dZ,pZ,fZ,mZ,gZ,hZ,EL=p(()=>{"use strict";dZ=new Set(["run list","run status","worker list","worker status","worker tail","status","cron status","monitor status","monitor list","update check","update status"]),pZ="run dispatch is blocked from runtime_command \u2014 use agent_os_submit_action_intent with kind dispatch_workers (live dispatch requires Action Required approval)",fZ='update finish is internal to `kynver update` \u2014 call ["update"] (confirmed) to update Kynver',mZ=new Set(["run create","run sweep","worker start","worker stop","worker complete","cleanup","update"]),gZ=["--secret","--api-key","--keeper-child"],hZ=new Set(["runner-install","node-runtime","local-store","context-envelope","runtime-takeover"])});import{spawn as yZ}from"node:child_process";function vZ(e,t,r,n=process.env){let o=J_(r,{agentOsId:e,argv:t},n);return o.ok?null:`command authorization proof invalid: ${o.reason}`}async function IL(e,t,r={}){if(r.agentOsId){let a=vZ(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=CL(e);if(!n.ok)return{exitCode:null,timedOut:!1,refused:n.reason};let o=r.cliEntry??process.argv[1],s=r.timeoutMs??kZ,i=new In(t,void 0,rr(r.agentOsId??""));return new Promise(a=>{let l=0,c=!1,u=yZ(process.execPath,[o,...e],Z({stdio:["ignore","pipe","pipe"],env:process.env})),d=m=>{if(l>=AL)return;let g=m.toString("utf8").slice(0,AL-l);l+=g.length,i.push(g)};u.stdout?.on("data",d),u.stderr?.on("data",d);let f=setTimeout(()=>{c=!0,at(u,"SIGTERM"),setTimeout(()=>at(u,"SIGKILL"),bZ).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 kZ,bZ,AL,PL=p(()=>{"use strict";U();lf();jr();EL();pa();kZ=10*6e4,bZ=5e3,AL=2e5});var Pn,cf=p(()=>{"use strict";Pn=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])}}});async function rv(e,t){let r=0,n=!1,o=new Pn,s=Array.isArray(t.payload?.argv)?t.payload.argv:[],i=await IL(s,a=>{n||o.track(Ee(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 Ee(e,t.turnId,[{seq:r++,kind:"error",error:`command_refused: ${i.refused}`}]).catch(()=>{}):await Ee(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}))}var nv=p(()=>{"use strict";PL();cf();Il()});function uf(e){let t=e.appendLog??(s=>{mi(s)}),r=e.now??(()=>new Date),n=0,o=(s,i)=>jb({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 ov=p(()=>{"use strict";Cl()});import{readFileSync as RZ,statSync as wZ}from"node:fs";import OL from"node:path";function xZ(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!==SZ||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 To(e,t,r){return{step:{kind:"attach",path:e,ok:!1,reason:t,...r!==void 0?{outputBytes:r}:{}}}}function CZ(e,t,r={}){let n=r.stat??wZ,o=r.read??RZ,s=r.maxBytes??_Z,i=e.rawPath.trim();if(!i||i.includes("\0"))return To(i,"invalid_path");let a=OL.resolve(t.workDir,pc(i));if(t.access==="off")return To(a,"access_off");if(!su(t,a))return To(a,"outside_folders");let l;try{let c=n(a);if(!c.isFile())return To(a,"not_a_file");l=c.size}catch{return To(a,"not_found")}if(l>s)return To(a,"too_large",l);try{let c=o(a);return{step:{kind:"attach",path:a,outputBytes:c.length,ok:!0},file:{name:OL.basename(a),sizeBytes:c.length,contentBase64:c.toString("base64")}}}catch{return To(a,"read_failed")}}function TL(e,t,r){let n=xZ(e);for(let o of n){let s=CZ(o,t.access);r.attach(s.step,t,{toolUseId:o.toolUseId,...s.file?{file:s.file}:{}})}return n.length}var SZ,_Z,NL=p(()=>{"use strict";Jn();ht();SZ="attach_file",_Z=50*1024*1024});function ML(e){if(e.startsWith(`${DL}:`)||!Qy(e))return e;let t=e.replace(/\s+/g," ").trim().slice(0,300);return`${DL}: ${t}`}var DL,LL=p(()=>{"use strict";qd();DL="provider_usage_exhausted"});import{readFileSync as EZ}from"node:fs";import{homedir as AZ,platform as IZ}from"node:os";import PZ from"node:path";import{execFileSync as OZ}from"node:child_process";function BL(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 TZ(){if(IZ()==="darwin")try{let e=OZ("security",["find-generic-password","-s","Claude Code-credentials","-w"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return BL(e.trim())}catch{return null}try{let e=EZ(PZ.join(AZ(),".claude",".credentials.json"),"utf8");return BL(e)}catch{return null}}function Pl(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=TZ();if(s)return{kind:"oauth",token:s}}return null}var sv=p(()=>{"use strict"});import{existsSync as UL}from"node:fs";import{homedir as NZ}from"node:os";import Ol from"node:path";import{spawnSync as DZ}from"node:child_process";function MZ(e){if(Ol.isAbsolute(e)||e.includes("/")||e.includes("\\"))return UL(e);try{let t=DZ(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function LZ(e=process.env){let t=NZ(),r=[],n=e.CODEX_HOME?.trim();return n&&r.push(Ol.join(Ol.resolve(n),"auth.json")),r.push(Ol.join(t,".codex","auth.json")),r.push(Ol.join(t,".config","codex","auth.json")),r}function FL(e){return`${e.error}: ${e.detail}`}function pf(e=process.env){let t=e.KYNVER_CODEX_BIN?.trim()||e.CODEX_BIN?.trim()||Ur();return MZ(t)?e.CODEX_API_KEY?.trim()?{ok:!0,creds:{codexBin:t,authSource:"api_key_env"}}:LZ(e).find(n=>UL(n))?{ok:!0,creds:{codexBin:t,authSource:"oauth_local"}}:{ok:!1,error:iv,detail:"Run `codex login` on this computer, or set CODEX_API_KEY. Website chat will not fall back to hosted models."}:{ok:!1,error:df,detail:"`codex` CLI not found. Install the Codex CLI (https://developers.openai.com/codex/) and keep it on PATH."}}var df,iv,ff=p(()=>{"use strict";fo();df="codex_cli_unavailable",iv="codex_not_logged_in"});import{spawnSync as BZ}from"node:child_process";function FZ(e,t,r){return UZ.test(`${t}
|
|
205
|
+
${r}`)?!1:e===0}function WL(e,t=process.env){try{let[r,n]=se(e,["models"]),o=BZ(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"}:FZ(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 UZ,KL=p(()=>{"use strict";We();UZ=/authentication required|not logged in|you are not logged|not authenticated/i});import{existsSync as WZ,readFileSync as KZ}from"node:fs";import{homedir as $Z}from"node:os";import $L from"node:path";import{spawnSync as HZ}from"node:child_process";function jZ(e){if($L.isAbsolute(e)||e.includes("/")||e.includes("\\"))return WZ(e);try{let t=HZ(process.platform==="win32"?"where":"which",[e],{windowsHide:!0,encoding:"utf8",timeout:3e3});return t.status===0&&!!t.stdout?.trim()}catch{return!1}}function VZ(){return $L.join($Z(),".gemini","antigravity-cli","settings.json")}function GZ(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 JZ(){try{return KZ(VZ(),"utf8")}catch{return null}}function qZ(e,t){return e.KYNVER_GEMINI_API_KEY?.trim()||e.GEMINI_API_KEY?.trim()?GZ(t)==="gemini":!1}function HL(e){return`${e.error}: ${e.detail}`}function hf(e=process.env,t={}){let r=_t(e);if(!(t.commandOnPath??jZ)(r))return{ok:!1,error:mf,detail:"`agy` not found. Install Google Antigravity (https://antigravity.google/docs/cli/install) and keep `agy` on PATH."};if((t.probeAuth??WL)(r,e).ok)return{ok:!0,creds:{bin:r,authSource:"keyring"}};let s=(t.readSettings??(()=>JZ()))(e);return qZ(e,s)?{ok:!0,creds:{bin:r,authSource:"api_key_settings"}}:{ok:!1,error:gf,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 mf,gf,yf=p(()=>{"use strict";ho();KL();mf="antigravity_cli_unavailable",gf="antigravity_not_logged_in"});function Tl(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()||YZ).replace(/\/+$/,"");return{apiKey:t,baseUrl:r,label:"gemini"}}function Nl(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()||zZ).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 YZ,zZ,av=p(()=>{"use strict";YZ="https://generativelanguage.googleapis.com/v1beta/openai",zZ="https://api.openai.com/v1"});function QZ(e,t=process.env){return{anthropic:()=>{let r=Pl(t,{oauthOptIn:e.chatUseClaudeOauth===!0});return r?r.kind==="oauth"?"subscription":"api_key":null},codex:()=>{let r=pf(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},cursor:()=>{let r=rd(t);return r.ok?r.creds.authSource==="api_key_env"?"api_key":"subscription":null},gemini:()=>{let r=t;if(Io({chatProvider:e.chatProvider,workerProvider:e.workerProvider},r)==="antigravity"){let n=hf(r);return n.ok?n.creds.authSource==="api_key_settings"?"api_key":"subscription":null}return Tl(t)?"api_key":null},openai:()=>Nl(t)?"api_key":null}}function ZZ(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:pi(r.slice(0,n)),model:o})}return t}function lv(e,t){let r=t?.trim();r&&!e.includes(r)&&e.push(r)}function eee(e,t,r=process.env){let n=ir(e),o=ZZ(r.KYNVER_CHAT_EXTRA_MODELS),s=[];for(let i of cv){let a=null;try{a=t[i]()}catch{a=null}if(!a)continue;let l=i===n?Ao(i,e,r):Ao(i,{},{...r,KYNVER_CHAT_MODEL:void 0}),c=[];lv(c,l);for(let u of XZ[i])lv(c,u);for(let u of o)u.provider===i&&lv(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 ki(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(Dl&&Dl.key===n&&r-Dl.at<tee)return Dl.value;let o=eee(e,QZ(e,t),t);return Dl={key:n,at:r,value:o},o}var cv,XZ,tee,Dl,Ml=p(()=>{"use strict";vr();sv();ff();Bs();yf();Gp();av();An();cv=["anthropic","codex","openai","gemini","cursor"],XZ={anthropic:lS,codex:["gpt-5.6-sol","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"]};tee=6e4,Dl=null});function Ll(e){if(typeof e=="string"){let n=e.indexOf(":");return n<=0?null:Ll({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:pi(t.provider),model:r}}function VL(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 GL(e,t){for(let r of cv){if(t.includes(r))continue;let n=e.find(o=>o.provider===r);if(n)return{provider:r,model:n.defaultModel}}return null}function JL(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return t?ree.some(r=>r.test(t)):!1}function jL(e){return nee[e]}function qL(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 YL(e,t){let r=`${jL(e.provider)} (${e.model})`;if(e.fallbackReason==="usage_limit")return`${t?jL(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 ree,nee,uv=p(()=>{"use strict";Ml();An();ree=[/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/];nee={anthropic:"Claude",codex:"ChatGPT",openai:"ChatGPT",gemini:"Gemini",cursor:"Cursor"}});async function Ht(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 dv=p(()=>{"use strict"});function XL(e){if(!e||typeof e!="object")return!1;let t=e;return!(typeof t.type!="string"||!oee.has(t.type)||t.type==="text"&&(typeof t.text!="string"||!t.text.trim()))}function zL(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:Bl}]}:null;if(!Array.isArray(t.content)||t.content.length===0)return null;let r=t.content[t.content.length-1];return XL(r)?{...t,content:[...t.content.slice(0,-1),{...r,cache_control:Bl}]}:null}function see(e){return Array.isArray(e)&&e.length>0&&e.every(t=>!!t&&typeof t=="object"&&t.type==="tool_result")}function iee(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!(!r||typeof r!="object"||r.role!=="user")&&!see(r.content))return t}return-1}function pv(e){return JSON.stringify(e??null).includes('"cache_control"')}function QL(e){if(pv(e.system)||pv(e.tools)||pv(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:Bl},...t.slice(a+1)])}let r=e.system;if(typeof r=="string")r.trim()&&(r=[{type:"text",text:r,cache_control:Bl}]);else if(Array.isArray(r)&&r.length>0){let i=r[r.length-1];XL(i)&&(r=[...r.slice(0,-1),{...i,cache_control:Bl}])}let n=[...e.messages],o=-1;for(let i=n.length-1;i>=0;i-=1){let a=zL(n[i]);if(a){n[i]=a,o=i;break}}let s=iee(n)-1;if(s>=0&&s<o)for(let i=s;i>=0;i-=1){let a=zL(n[i]);if(a){n[i]=a;break}}return{system:r,tools:t,messages:n}}var Bl,oee,ZL=p(()=>{"use strict";Bl={type:"ephemeral"},oee=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 eB(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 lee(){return{blocks:[],stopReason:null,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}}function cee(e){let t=e;return t.type==="content_block_start"&&t.content_block?.type==="tool_use"?!0:t.type==="content_block_delta"&&t.delta?.type==="input_json_delta"}function uee(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 dee(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*pee(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 fee(e=process.env){return(e.ANTHROPIC_BASE_URL?.trim()||"https://api.anthropic.com").replace(/\/$/,"")}async function tB(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:aee},{type:"text",text:n.system}]);let i=QL({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(`${fee()}/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=lee();for await(let c of pee(a.body)){let u=uee(l,c);u?e.onDelta(u):cee(c)&&e.onToolProgress?.()}return dee(l)}var aee,fv=p(()=>{"use strict";ZL();aee="You are Claude Code, Anthropic's official CLI for Claude."});function lr(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 gee(e){let t=e.replace(/\s+/g," ").trim();return t.length>rB?`${t.slice(0,rB-1)}\u2026`:t}function oB(e,t=mee){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:","",On,'{"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.",`- ${kf}`,"","Tools:"].join(`
|
|
207
207
|
`),n=[],o=r.length,s=[];for(let c of e){let u=`
|
|
208
|
-
- ${c.name}: ${
|
|
208
|
+
- ${c.name}: ${gee(c.description)}
|
|
209
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?`
|
|
210
210
|
|
|
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
|
|
212
|
-
${
|
|
213
|
-
${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 kee(e){let t=[],r=0;for(;;){let n=e.indexOf(On,r);if(n===-1)break;let o=n+On.length,s=e.indexOf("```",o);if(s===-1||e.startsWith(On,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 Tn(e,t){let{fences:r,unterminated:n}=kee(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:(yee.exec(n.body)?.[1]?.trim()??"")||null}),i+=e.slice(a),{text:i.trim(),calls:o,rejected:s,cut:l}}function nB(e,t){return`cursor_${e}_${t}`}function Nn(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:nB(t,i),name:s.name,input:s.input})}),e.cut&&n.push({type:"tool_use",id:nB(t,"cut"),name:hee,input:{tool:e.cut.name,reason:"unterminated_fence"}}),{content:n,stop_reason:e.calls.length>0||e.cut?"tool_use":"end_turn"}}function bee(e){let t=Math.min(e.length,On.length-1);for(let r=t;r>0;r-=1)if(On.startsWith(e.slice(e.length-r)))return r;return 0}var On,kf,mee,rB,hee,yee,ar,bi=p(()=>{"use strict";On="```kynver-tool",kf="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.";mee=64e3,rB=600;hee="kynver_tool_call_cut",yee=/"name"\s*:\s*"([^"\\]*)"/;ar=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(On);if(n!==-1){r+=this.held.slice(0,n),this.held=this.held.slice(n+On.length),this.inFence=!0;continue}let o=bee(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 sB(e){return`[\u2026 ${e} more characters of the user's message omitted to fit this prompt \u2026]`}function vee(e){return`[\u2026 ${e} more characters of Kynver's turn context omitted to fit this prompt \u2026]`}function Ree(e,t){if(e.length<=t)return e;let r=e.indexOf(iB),n=r>=0?e.indexOf(vi,r):-1;if(r<0||n<0)return Ri(e,t,sB);let o=e.slice(0,r),s=e.slice(r,n+vi.length),i=Ri(e.slice(n+vi.length),Math.max(0,t-o.length),sB),a=t-o.length-i.length,l=vi.length+1,c=s.slice(0,s.length-vi.length),u=s.length<=a?s:`${Ri(c,Math.max(iB.length,a-l-100),vee)}
|
|
212
|
+
${vi}`;return`${o}${u}${i}`}function mv(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 wee(e){return`[\u2026 ${e} more characters omitted to fit this prompt \u2026]`}function Ri(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 lB(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(`
|
|
214
214
|
|
|
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=
|
|
216
|
-
`)}function
|
|
217
|
-
`).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=Ree(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?mv:wee;r[i].kept=Ri(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 aB,iB,vi,cB=p(()=>{"use strict";aB="[System reminder]";iB="<turn_context>",vi="</turn_context>"});function xee(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 Cee(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 Eee(e){let t=Cee(e);return t.length>0&&!t.startsWith(aB)}function Aee(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&t.type==="tool_result")}function gv(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=xee(o.content??o.text),i=t===void 0?s:Ri(s,t,mv);r.push(o.is_error?`[tool error]
|
|
218
218
|
${i}`:`[tool result]
|
|
219
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(`
|
|
220
|
-
`)}function
|
|
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.":
|
|
222
|
-
${
|
|
223
|
-
${
|
|
220
|
+
`)}function Oee(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[pB,Iee,"Never use runtime_command run dispatch and never implement coding tasks inline in the chat workspace when a worker was requested or dispatch failed.",fB,kf].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[pB,`${n} Do the work there yourself and say what you ran and what you changed.`,`Local commands are only for this computer. ${kf}`,Pee,"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).",fB].join(" ")}function Tee(e){return e==="assistant"?"Assistant":e==="system"?"System":"User"}function mB(e){return gv(e)}function hv(e,t=e.executionMode==="ask"?"ask":"agent",r,n){let o=t==="agent"?r??lr(e.tools):[],s=oB(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.":Oee(n)),i==="off"&&a.push(_ee);let c=t==="agent"?eB(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 k of e.messages){if(!k||typeof k!="object")continue;let v=k,y=gv(v.content);if(!y.trim())continue;let b=Tee(v.role);v.role!=="assistant"&&v.role!=="system"&&Eee(v.content)&&(d=u.length);let w=v.content;u.push({text:`${b}:
|
|
222
|
+
${y}`,ask:!1,renderShrunk:Aee(w)?_=>`${b}:
|
|
223
|
+
${gv(w,_)}`:null})}d>=0&&(u[d].ask=!0);let f=a.join(`
|
|
224
224
|
|
|
225
|
-
`),m=u.map(
|
|
225
|
+
`),m=u.map(k=>k.text).join(`
|
|
226
226
|
|
|
227
|
-
`);if(!u.length||f.length+2+m.length<=
|
|
227
|
+
`);if(!u.length||f.length+2+m.length<=uB)return{head:f,body:m};let g=Math.max(See,uB-f.length-16),h=lB(u,g-dB.length-2);return{head:f,body:h.dropped?`${dB}
|
|
228
228
|
|
|
229
|
-
${h.body}`:h.body}}function
|
|
229
|
+
${h.body}`:h.body}}function wi(e,t=e.executionMode==="ask"?"ask":"agent",r,n){let{head:o,body:s}=hv(e,t,r,n);return s?`${o}
|
|
230
230
|
|
|
231
|
-
${s}`:o}var
|
|
232
|
-
`):void 0}function
|
|
233
|
-
`))!==-1;){let
|
|
234
|
-
`))!==-1;){let
|
|
235
|
-
`))!==-1;){let
|
|
236
|
-
`):""}function
|
|
237
|
-
`)}),r}function
|
|
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
|
|
239
|
-
`;e.write(`HTTP/1.1 ${t} ${t===
|
|
231
|
+
${s}`:o}var uB,See,_ee,dB,pB,Iee,fB,Pee,Ul=p(()=>{"use strict";fv();bi();cB();uB=8e4,See=32e3,_ee="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.",dB=`[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.]`;pB="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.",Iee="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).",fB="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.",Pee="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."});function gB(e,t=1e4,r=Date.now){let n=0;return{noteToolBytes(){let o=r();n!==0&&o-n<t||(n=o,e())}}}var yv=p(()=>{"use strict"});function hB(e,t=1e4){let r=setInterval(e,t);return typeof r.unref=="function"&&r.unref(),()=>clearInterval(r)}var yB=p(()=>{"use strict";yv()});import{homedir as Dee}from"node:os";function Si(e,t=Dee()){let r=A();return fs({engine:e,local:{chatComputerAccess:r.chatComputerAccess,chatWorkFolders:r.chatWorkFolders},home:t})}var bf=p(()=>{"use strict";$();Jn()});function Bee(e){let t=e[Im];return new Set(t?t.split(/[\s,]+/).map(r=>r.trim()).filter(Boolean):[])}function kv(e,t={}){return Lee.has(e)||t.operatorAllow?.has(e)||e===vv?!1:Mee.some(r=>r.test(e))}function cr(e=process.env){let t=Fi(e);for(let n of bv)delete t[n];let r=Bee(e);for(let n of Object.keys(t))kv(n,{operatorAllow:r})&&delete t[n];return t[vv]="1",t}function kB(e){let t=e.toUpperCase();return Kee.has(t)||t===vv?!0:Fee.has(t)?!kv(t):Wee.some(r=>t.startsWith(r))?!kv(t)&&!/(_KEY|_TOKEN|_SECRET|_PASSWORD)$/i.test(t):!1}function $ee(e=process.env){let t={};for(let[n,o]of Object.entries(e))typeof o=="string"&&kB(n)&&(t[n]=o);let r=cr(t);for(let n of Object.keys(r))kB(n)||delete r[n];return r}function bB(e,t){return t==="folder"||t==="folders"?$ee(e):cr(e)}function Rv(){return[`--disallowedTools=${Hee.join(",")}`]}var bv,vv,Mee,Lee,Uee,Fee,Wee,Kee,Hee,No=p(()=>{"use strict";Wi();bv=["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"],vv="KYNVER_CHAT_CHILD",Mee=[/_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],Lee=new Set(Am);Uee=["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"],Fee=new Set(Uee.map(e=>e.toUpperCase())),Wee=["LC_","CLAUDE_CODE_","CLAUDE_","ANTHROPIC_","DISABLE_","MAX_THINKING_","BASH_DEFAULT_","BASH_MAX_"],Kee=new Set(["CLAUDE_CODE_OAUTH_TOKEN"]);Hee=["Read(~/.kynver/credentials)","Read(~/.kynver/credentials.*)","Read(~/.kynver/chat-box-credential)","Read(~/.kynver/site-logins/**)"]});function Oe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ae(e){return typeof e=="string"&&e.trim()?e:void 0}function wv(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Sv(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 _v(...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 xv(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 RB(e=Date.now){let t=xv(e);return r=>{let n=Oe(r.item);if(!n)return[];let o=Ae(n.id);if(r.type==="item.started")return t.start(o),[];if(r.type!=="item.completed")return[];if(n.type==="command_execution"){let s=Ae(n.command)??"",i=wv(n.exit_code),a=Sv(s,i,t.elapsed(o),_v(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=>Oe(a)).filter(a=>!!a&&!!Ae(a.path)).map(a=>({kind:"file_change",path:Ae(a.path),...Ae(a.kind)?{change:Ae(a.kind)}:{},durationMs:s,ok:i,...i?{}:{reason:"failed"}}))}return[]}}function wB(e=Date.now){let t=xv(e);return r=>{if(r.type!=="tool_call")return[];let n=Ae(r.call_id);if(r.subtype==="started")return t.start(n),[];if(r.subtype!=="completed")return[];let o=Oe(r.tool_call);if(!o)return[];let s=t.elapsed(n),i=Oe(o.shellToolCall);if(i){let a=Oe(i.result),l=Oe(a?.success)??Oe(a?.failure),c=Ae(Oe(i.args)?.command)??Ae(l?.command)??"",u=wv(l?.exitCode)??(a?.failure?1:null),d=wv(l?.executionTime)??s;return[Sv(c,u,d,_v(l?.stdout,l?.stderr))]}for(let[a,l]of Object.entries(jee)){let c=Oe(o[a]);if(!c)continue;let u=Oe(c.result),d=Ae(Oe(c.args)?.path)??Ae(Oe(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 SB(){return e=>{if(e.event!=="step_update")return[];let t=Oe(e.step_update);if(!t||t.step_type!=="tool")return[];let r=Ae(t.tool_name);return r?[{kind:"tool",command:r.trim(),ok:!0}]:[]}}function Jee(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let t=e.map(r=>Oe(r)).filter(r=>!!r&&typeof r.text=="string").map(r=>r.text);return t.length?t.join(`
|
|
232
|
+
`):void 0}function vB(e){let t=Oe(e.message)?.content;return Array.isArray(t)?t.map(r=>Oe(r)).filter(r=>!!r):[]}function _B(e=Date.now){let t=xv(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(Gee)?.[1]??1):0,h=Sv(Ae(i.input.command)??"",g,a,_v(c));return u?{...h,ok:!1,reason:u}:h}let d=l||u?{reason:u??"failed"}:{},f=Vee[i.name],m=Ae(i.input.file_path)??Ae(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 vB(i)){let c=Ae(l.id),u=Ae(l.name);l.type!=="tool_use"||!c||!u||r.has(c)||n.has(c)||(r.set(c,{name:u,input:Oe(l.input)??{}}),t.start(c))}return[]}if(i.type!=="user")return[];let a=[];for(let l of vB(i)){let c=Ae(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,Jee(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 jee,Vee,Gee,Fl=p(()=>{"use strict";jee={writeToolCall:"write",editToolCall:"update",deleteToolCall:"delete"};Vee={Write:"write",Edit:"update",MultiEdit:"update",NotebookEdit:"update"},Gee=/exit code (\d+)/i});function ur(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function xB(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 CB(e){let t=ur(e.type);if(!t)return null;if(t==="interactionUpdate"||t==="interaction_update"){let r=ur(e.subtype)??ur(e.updateType),n=ur(e.blockReasonType)??ur(e.blockReason?.type),o=xB(e.approvalReasonTypes)??xB(e.approval?.reasonTypes),s=ur(e.toolCallId)??ur(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=ur(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=ur(e.toolCallId)??ur(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 vf(e){if(!Yee.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 Rf(e){let t=[qee];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 qee,Yee,EB=p(()=>{"use strict";qee="cursor_tool_approval_blocked",Yee=/blockReasonType[=:]\s*(\w+)|userRejected|Shell approval gate|approvalReasonTypes|unapproved_commands/i});function wf(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 AB=p(()=>{"use strict"});import{spawn as zee}from"node:child_process";function Cv(e){return e==="ask"?"ask":"agent"}function ete(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 tte(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 rte(e){return e.type!=="result"?"":typeof e.result=="string"?e.result:""}function Ev(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 Av(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 nte(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 ote(e,t){if(Zee.test(e))return`${qh}: ${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 IB(e){let t=e.env??process.env,r=e.access??Si("cursor"),n=e.workspaceDir??r.workDir,o=wB(),s=Cv(e.payload.executionMode),i=s==="agent"?lr(e.payload.tools):[],a=new Set(i.map(f=>f.name)),l=wi(e.payload,s,i,r),c=e.spawnTarget;if(!c){let f=co(t),m=Oa(f);c={executable:m.executable,prefixArgs:m.prefixArgs}}let u=ete(e.model,n,l,c.prefixArgs,s),d={...cr(t),CI:"1",NO_COLOR:"1"};return await new Promise((f,m)=>{let g;try{let C=Z({cwd:n,detached:process.platform!=="win32",shell:!1,stdio:["ignore","pipe","pipe"],env:d});g=zee(c.executable,u,C)}catch(C){if(C.code==="ENOENT"){m(new Error(`${td}: failed to spawn \`${c.executable}\`. Install the Cursor Agent CLI and keep \`agent\` on PATH.`));return}m(C instanceof Error?C:new Error(String(C)));return}let h=e.onToolProgress?hB(e.onToolProgress,e.heartbeatMs):()=>{},k=!1,v=new ar,y="",b=C=>{let D=v.push(C);D&&(y+=D,e.onDelta(D))},S="",w="",_={input_tokens:0,output_tokens:0},R="",T="",W=!1,O=!1,L,M=vf(R),B=null,G=C=>{if(k)return;if(k=!0,h(),clearTimeout(V),L&&clearTimeout(L),e.signal?.removeEventListener("abort",x),C){wf({requestId:e.requestId,turnId:e.turnId,event:"turn_error",exitCode:B,error:C.message,...M?.toolCallId?{toolCallId:M.toolCallId}:{},...M?.toolName?{toolName:M.toolName}:{},...M?.blockReasonType?{blockReason:M.blockReasonType}:{}}),m(C);return}let D=vf(R);if(D&&(M=D),M){let Te=new Error(Rf(M));wf({requestId:e.requestId,turnId:e.turnId,event:"turn_approval_blocked",exitCode:B,toolCallId:M.toolCallId,toolName:M.toolName,blockReason:M.blockReasonType,error:Te.message}),m(Te);return}let z=v.end();z&&(y+=z,e.onDelta(z));let ue=Ev(S,w),H=Tn(ue,a);Av(H.text,y,e.onDelta),H.rejected.length>0&&console.error(JSON.stringify({event:"cursor_tool_call_rejected",names:H.rejected.slice(0,5),advertised:a.size}));let{content:ie,stop_reason:Y}=Nn(H,e.turnId??"turn");wf({requestId:e.requestId,turnId:e.turnId,event:"turn_end",exitCode:B,stopReason:Y}),f({content:ie,stop_reason:Y,usage:_})},re=C=>{g.pid?he(g.pid,C):at(g,C)},I=()=>{re("SIGTERM"),L??=setTimeout(()=>{O||re("SIGKILL")},Qee),L.unref()},x=()=>{I(),G(new Error("cursor_chat_aborted"))},V=setTimeout(()=>{W=!0,I()},e.timeoutMs??Xee);if(g.on("error",C=>{if(C.code==="ENOENT"){G(new Error(`${td}: failed to spawn \`${c.executable}\`. Install the Cursor Agent CLI and keep \`agent\` on PATH.`));return}G(C)}),e.signal){if(e.signal.aborted){x();return}e.signal.addEventListener("abort",x)}let N=C=>{let D=C.trim();if(!D)return;let z;try{z=JSON.parse(D)}catch{return}let ue=tte(z,S);ue&&(S+=ue,b(ue));let H=rte(z);H&&(w=H);let ie=nte(z);if(ie&&(_=ie),e.onActivity)for(let Te of o(z))e.onActivity(Te);let Y=CB(z);Y&&(M=Y,I(),G(new Error(Rf(Y))))};g.stdout?.on("data",C=>{T+=typeof C=="string"?C:C.toString("utf8");let D;for(;(D=T.indexOf(`
|
|
233
|
+
`))!==-1;){let z=T.slice(0,D);T=T.slice(D+1),N(z)}}),g.stderr?.on("data",C=>{R+=typeof C=="string"?C:C.toString("utf8"),R.length>8e3&&(R=R.slice(-8e3));let D=vf(R);D&&(M=D,I(),G(new Error(Rf(D))))}),g.on("close",C=>{if(O=!0,B=C,T.trim()&&N(T),W){G(new Error("cursor_chat_timeout"));return}if(C!==0&&!S&&!w){G(new Error(ote(R,C)));return}G()})})}var Xee,Qee,Zee,Sf=p(()=>{"use strict";Ls();U();Ul();yB();bf();No();Fl();Bs();bi();EB();AB();Xee=24e4,Qee=1500,Zee=/not logged in|please run[`\s]+agent login|authentication required|unauthorized|invalid api key/i});import{spawn as ste}from"node:child_process";function lte(e){return e==="ask"?"ask":"agent"}function cte(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 ute(e,t,r="agent",n=[],o=process.platform,s){return[...n,"exec",...sd(o),"--skip-git-repo-check","--json","--ask-for-approval","never",...cte(r,s),"--model",e,t]}function dte(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 pte(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 fte(e,t){if(ate.test(e))return`${iv}: ${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 PB(e){let t=e.env??process.env,r=e.access??Si("codex"),n=e.workspaceDir??r.workDir,o=lte(e.payload.executionMode),s=o==="agent"?lr(e.payload.tools):[],i=new Set(s.map(f=>f.name)),a=wi(e.payload,o,s,r),l=RB(),c=e.spawnTarget??{executable:t.KYNVER_CODEX_BIN?.trim()||t.CODEX_BIN?.trim()||Ur(),prefixArgs:[]},u=ute(e.model,a,o,c.prefixArgs,process.platform,r),d={...cr(t),CI:"1",NO_COLOR:"1"};return await new Promise((f,m)=>{let g;try{let M=Z({cwd:n,detached:!1,shell:!1,stdio:["ignore","pipe","pipe"],env:d}),[B,G]=se(c.executable,u);g=ste(B,G,M)}catch(M){if(M.code==="ENOENT"){m(new Error(`${df}: failed to spawn \`${c.executable}\`. Install the Codex CLI and keep \`codex\` on PATH.`));return}m(M instanceof Error?M:new Error(String(M)));return}let h=!1,k=new ar,v=M=>{let B=k.push(M);B&&e.onDelta(B)},y="",b={input_tokens:0,output_tokens:0},S="",w="",_=!1,R=M=>{if(h)return;if(h=!0,clearTimeout(O),e.signal?.removeEventListener("abort",W),M){m(M);return}let B=k.end();B&&e.onDelta(B);let G=Tn(y,i);G.rejected.length>0&&console.error(JSON.stringify({event:"codex_tool_call_rejected",names:G.rejected.slice(0,5),advertised:i.size})),f({...Nn(G,e.turnId??"turn"),usage:b})},T=()=>at(g,"SIGTERM"),W=()=>{T(),R(new Error("codex_chat_aborted"))},O=setTimeout(()=>{_=!0,T()},e.timeoutMs??ite);if(g.on("error",M=>{if(M.code==="ENOENT"){R(new Error(`${df}: failed to spawn \`${c.executable}\`. Install the Codex CLI and keep \`codex\` on PATH.`));return}R(M)}),e.signal){if(e.signal.aborted){W();return}e.signal.addEventListener("abort",W)}let L=M=>{let B=M.trim();if(!B)return;let G;try{G=JSON.parse(B)}catch{return}let re=dte(G,y);re&&(y+=re,v(re));let I=pte(G);if(I&&(b=I),e.onActivity)for(let x of l(G))e.onActivity(x)};g.stdout?.on("data",M=>{w+=typeof M=="string"?M:M.toString("utf8");let B;for(;(B=w.indexOf(`
|
|
234
|
+
`))!==-1;){let G=w.slice(0,B);w=w.slice(B+1),L(G)}}),g.stderr?.on("data",M=>{S+=typeof M=="string"?M:M.toString("utf8"),S.length>8e3&&(S=S.slice(-8e3))}),g.on("close",M=>{if(w.trim()&&L(w),_){R(new Error("codex_chat_timeout"));return}if(M!==0&&!y){R(new Error(fte(S,M)));return}R()})})}var ite,ate,OB=p(()=>{"use strict";fo();ry();U();We();Ul();bf();Fl();ff();No();bi();ite=24e4,ate=/not logged in|please run[`\s]+codex login|authentication required|unauthorized|invalid api key|401\b/i});import{spawn as mte}from"node:child_process";function hte(e,t,r="agent",n=[]){return[...n,...fd({executionMode:r==="ask"?"read_only":"write",prompt:t},e)]}function yte(e,t){if(TB.test(e))return`${gf}: ${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 NB(e){let t=e.env??process.env,r=e.access??Si("antigravity"),n=e.workspaceDir??r.workDir,o=SB(),s=Cv(e.payload.executionMode),i=s==="agent"?lr(e.payload.tools):[],a=new Set(i.map(f=>f.name)),l=wi(e.payload,s,i,r),c=e.spawnTarget??{executable:_t(t),prefixArgs:[]},u=hte(e.model,l,s,c.prefixArgs),d={...cr(t),CI:"1",NO_COLOR:"1"};return await new Promise((f,m)=>{let g;try{let B=Z({cwd:n,detached:!1,shell:!1,stdio:["ignore","pipe","pipe"],env:d}),[G,re]=se(c.executable,u);g=mte(G,re,B)}catch(B){if(B.code==="ENOENT"){m(new Error(`${mf}: failed to spawn \`${c.executable}\`. Install Google Antigravity and keep \`agy\` on PATH.`));return}m(B instanceof Error?B:new Error(String(B)));return}let h=!1,k=new ar,v=B=>{let G=k.push(B);G&&e.onDelta(G)},y="",b="",S={input_tokens:0,output_tokens:0},w="",_="",R=!1,T=B=>{if(h)return;if(h=!0,clearTimeout(L),e.signal?.removeEventListener("abort",O),B){m(B);return}let G=b.length>=y.length&&b?b:y;b.startsWith(y)&&b.length>y.length?v(b.slice(y.length)):!y&&b&&v(b);let re=k.end();re&&e.onDelta(re);let I=Tn(G,a);f({...Nn(I,e.turnId??"turn"),usage:S})},W=()=>at(g,"SIGTERM"),O=()=>{W(),T(new Error("antigravity_chat_aborted"))},L=setTimeout(()=>{R=!0,W()},e.timeoutMs??gte);if(g.on("error",B=>{if(B.code==="ENOENT"){T(new Error(`${mf}: failed to spawn \`${c.executable}\`. Install Google Antigravity and keep \`agy\` on PATH.`));return}T(B)}),e.signal){if(e.signal.aborted){O();return}e.signal.addEventListener("abort",O)}let M=B=>{let G=B.trim();if(!G)return;let re;try{re=JSON.parse(G)}catch{return}if(e.onActivity)for(let x of o(re))e.onActivity(x);let I=Tc(re);if(I&&(I.textDelta&&(y+=I.textDelta,v(I.textDelta)),I.usage&&(S={input_tokens:I.usage.inputTokens??S.input_tokens,output_tokens:I.usage.outputTokens??S.output_tokens}),!!I.terminal)){if(!I.terminal.ok){let x=I.terminal.error??"antigravity cli result error";if(W(),TB.test(x)){T(new Error(`${gf}: ${x.slice(0,240)}`));return}T(new Error(`antigravity_chat_failed: ${x.slice(0,240)}`));return}b=I.terminal.finalResult??""}};g.stdout?.on("data",B=>{_+=typeof B=="string"?B:B.toString("utf8");let G;for(;(G=_.indexOf(`
|
|
235
|
+
`))!==-1;){let re=_.slice(0,G);_=_.slice(G+1),M(re)}}),g.stderr?.on("data",B=>{w+=typeof B=="string"?B:B.toString("utf8"),w.length>8e3&&(w=w.slice(-8e3))}),g.on("close",B=>{if(_.trim()&&M(_),R){T(new Error("antigravity_chat_timeout"));return}if(!h){if(B!==0&&!y&&!b){T(new Error(yte(w,B)));return}T()}})})}var gte,TB,DB=p(()=>{"use strict";ho();Vm();U();We();yf();Ul();bf();No();Fl();Sf();bi();gte=24e4,TB=/authentication required|not logged in|you are not logged|not authenticated/i});function kte(){return{text:"",toolCalls:[],finishReason:null,promptTokens:0,completionTokens:0}}function bte(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 vte(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 Rte(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 wte(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
236
|
+
`):""}function Ste(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:wte(i.content)}),o.push(...Rte(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 _te(e,t){let r=[];e.trim()&&r.push({role:"system",content:e});for(let n of t)r.push(...Ste(n??{}));return r}function xte(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*Cte(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 MB(e){let{creds:t,model:r,payload:n}=e,o=Array.isArray(n.tools)?xte(n.tools):[],s={model:r,messages:_te(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=kte();for await(let l of Cte(i.body)){let c=bte(a,l);c&&e.onDelta(c)}return vte(a)}var LB=p(()=>{"use strict"});function BB(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.session!="string"||!Ete.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 UB(e){let t=typeof e.maxMs=="number"&&e.maxMs>0?e.maxMs:48e4;return Math.max(0,Math.min(t,e.timeLeftMs))}var Ete,_f=p(()=>{"use strict";Ete=/^[A-Za-z0-9_.:-]{1,128}$/});function Ate(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 FB,WB=p(()=>{"use strict";FB=Ate()});function Ite(e,t){if(e.access==="off")throw new Error("claude_code_access_off");return e.access==="full"?["--permission-mode","bypassPermissions",...Rv()]:["--permission-mode","acceptEdits",`--allowedTools=${(t?.shell==="disabled"?KB.filter(n=>n!=="Bash"):[...KB]).join(",")}`,...Rv(),...t?["--settings",t.settingsFile]:[],...e.access==="folders"?e.extraFolders.flatMap(n=>["--add-dir",n]):[]]}function Iv(e){return["-p","--output-format","stream-json","--include-partial-messages","--verbose",...e.model?["--model",e.model,...Oc(e.fallbackModel)]:[],"--append-system-prompt-file",e.systemPromptFile,...e.resumeSessionId?["--resume",e.resumeSessionId]:[],...Ite(e.access,e.sandbox),"--",e.prompt]}var KB,$B=p(()=>{"use strict";No();vr();KB=["Bash","WebFetch","WebSearch"]});import{lookup as Pte}from"node:dns/promises";import{createServer as Ote,request as Tte}from"node:http";import{connect as Nte,isIP as VB,isIPv4 as Dte}from"node:net";function GB(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 Wl(e){let t=GB(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 Lte(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=GB(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 Bte(e){let t=Lte(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 Wl(n(t[6],t[7]));if(t[0]===8194)return Wl(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 HB(e){let t=VB(e);return t===4?Wl(e):t===6?Bte(e):!0}function Ute(e){return e==="localhost"||e.endsWith(".localhost")||e==="localhost6"||e==="ip6-localhost"}function Fte(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 JB(e){return(await Pte(e,{all:!0})).map(r=>r.address)}async function jB(e,t=JB){let r=Fte(e);if(!r||r.length>Mte)return{allowed:!1,host:r,reason:"invalid host"};if(Ute(r))return{allowed:!1,host:r,reason:`${r} is this computer (loopback): local services are not reachable from a folder step`};if(VB(r))return HB(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=>HB(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=>Dte(s))??n[0]}}function Pv(e,t,r){let n=`Kynver folder sandbox: ${r}
|
|
239
|
+
`;e.write(`HTTP/1.1 ${t} ${t===Ov?"Forbidden":"Bad Gateway"}\r
|
|
240
240
|
Content-Type: text/plain\r
|
|
241
241
|
Content-Length: ${Buffer.byteLength(n)}\r
|
|
242
242
|
Connection: close\r
|
|
243
243
|
\r
|
|
244
|
-
${n}`),e.end()}function
|
|
244
|
+
${n}`),e.end()}function Kte(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 $te(e={}){let t=e.lookup??JB,r=e.dial??((m,g)=>Nte({host:m,port:g})),n=e.idleMs??Wte,o={allowed:0,denied:0},s=(m,g,h)=>{let k=Kte(m.url);if(g.on("error",()=>g.destroy()),!k){o.denied+=1,Pv(g,400,"CONNECT needs host:port");return}jB(k.host,t).then(v=>{if(!v.allowed){o.denied+=1,Pv(g,Ov,v.reason);return}o.allowed+=1;let y=r(v.address,k.port,v.host),b=!1;y.setTimeout(n,()=>y.destroy()),y.once("connect",()=>{b=!0,g.write(`HTTP/1.1 200 Connection Established\r
|
|
245
245
|
\r
|
|
246
|
-
`),h.length&&
|
|
246
|
+
`),h.length&&y.write(h),y.pipe(g),g.pipe(y)}),y.on("error",S=>{if(b){g.destroy();return}Pv(g,502,`could not connect to ${v.host}:${k.port} (${S.code??S.message})`)}),y.on("close",()=>g.end()),g.on("close",()=>y.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
|
|
247
247
|
`);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
|
|
248
|
-
`);return}let
|
|
249
|
-
`);return}o.allowed+=1;let
|
|
250
|
-
`)}),m.pipe(v)})},a=()=>{let m=_te(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 HB(e={}){return Si?.listening()?Si:(wf||(wf=Mte(e).then(t=>(Si=t,Wl=null,t)).catch(t=>{throw Si=null,Wl=`egress proxy could not start: ${t?.message??String(t)}`.slice(0,240),new Error(Wl)}).finally(()=>{wf=null})),wf)}function jB(){return Si?.listening()?{status:"running",port:Si.port}:Wl?{status:"failed",reason:Wl}:{status:"not_started"}}var Ate,Nte,Cv,Si,wf,Wl,Ev=p(()=>{"use strict";Ate=253;Nte=10*6e4,Cv=403;Si=null,wf=null,Wl=null});import{existsSync as Lte}from"node:fs";import _f from"node:path";function Iv(e=process.env,t={}){let r=(e[Bte]??t.chatFolderSandbox??"").toString().trim().toLowerCase();return r==="best-effort"||r==="best_effort"||r==="optional"?"best_effort":"required"}function qB(e=process.env,t={}){let r=[],n=e[Ute];n&&r.push(...n.split(/[\s,]+/)),Array.isArray(t.chatFolderSandboxDomains)&&r.push(...t.chatFolderSandboxDomains.filter(s=>typeof s=="string"));let o=[...Fte];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 Sf(e){return`~/${e}`}function $te(){let e=[];for(let t of xf)e.push(`Read(${Sf(t)}/**)`,`Edit(${Sf(t)}/**)`);for(let t of Cf)e.push(`Read(${Sf(t)})`,`Edit(${Sf(t)})`);for(let t of _i)e.push(`Read(//**/${t})`,`Edit(//**/${t})`);return e}function Hte(e,t=[],r={}){let n=["~/",...Kte];for(let o of xf)n.push(`~/${o}`);for(let o of Cf)n.push(`~/${o}`);for(let o of t)n.push(Av(o));if(r.scanComplete!==!0)for(let o of e)for(let s of _i)n.push(_f.posix.join(Av(o),"**",s));return n}function jte(e){return[...e.map(Av),...Wte.map(t=>`~/${t}`)]}function Av(e){return e.split(_f.sep).join("/")}function VB(e){let t={deny:$te(),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:Hte(e.folders,e.sensitiveFiles,{scanComplete:e.sensitiveScanComplete}),allowRead:jte(e.folders)},network:{allowedDomains:e.domains,allowLocalBinding:!0,...typeof r=="number"&&r>0?{httpProxyPort:r}:{}}}}}function YB(e){return!!e&&Vte.test(e)}function Gte(e,t,r){return(t.PATH??"").split(_f.delimiter).filter(Boolean).some(o=>r(_f.join(o,e)))}function Jte(e={}){let t=e.platform??process.platform,r=e.env??process.env,n=e.exists??Lte;if(t==="darwin")return{kind:"seatbelt",available:!0,missing:[]};if(t==="linux"){let o=["bwrap","socat"].filter(s=>!Gte(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 Pv(){return GB??=Jte(),GB}function XB(e){zB=e.trim().slice(0,240)||"sandbox failed to start"}function Ov(){return zB}function QB(e){return e.streamed.trim()||e.exitCode===0||e.numTurns!==null&&e.numTurns>0?!1:qte.test(e.detail)&&Yte.test(e.detail)}function ZB(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:VB({folders:t,sandbox:!0,domains:e.domains,egressProxyPort:o,sensitiveFiles:e.sensitiveFiles,sensitiveScanComplete:e.sensitiveScanComplete}),note:o?`${JB} ${zte}`:`${JB} ${Xte}`}}let n=VB({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:Zte}:{shell:"disabled",policy:e.policy,runtime:e.runtime,reason:r,settings:n,note:Qte}}function Ef(e=process.env,t={},r={}){let n=r.runtime??Pv(),o=r.startupFailure===void 0?Ov():r.startupFailure,s=Iv(e,t),i=n.available?o??void 0:n.reason,a=i?s==="best_effort"?"unconfined":"disabled":"sandboxed",l=r.egress??jB(),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 Bte,Ute,Fte,xf,Cf,_i,Wte,Kte,No,Vte,GB,zB,qte,Yte,JB,zte,Xte,Qte,Zte,Kl=p(()=>{"use strict";Ev();Bte="KYNVER_CHAT_FOLDER_SANDBOX",Ute="KYNVER_CHAT_FOLDER_SANDBOX_DOMAINS";Fte=["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"];xf=[".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"],Cf=[".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"],_i=[".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.*"],Wte=[".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"],Kte=["/home","/root","/Users","/mnt","/media","/Volumes"];No=3128,Vte=new RegExp([`failed to connect to (?:localhost|127\\.0\\.0\\.1|::1|\\[::1\\]) port ${No}\\b`,`(?:localhost|127\\.0\\.0\\.1|\\[::1\\]|::1):${No}\\b[^\\n]{0,80}?(?:connection refused|econnrefused)`,`(?:connection refused|econnrefused)[^\\n]{0,80}?(?:localhost|127\\.0\\.0\\.1|::1):${No}\\b`,`(?:cannot|could not|unable to) connect to proxy[^\\n]{0,80}?${No}\\b`,`proxyerror[^\\n]{0,120}?${No}\\b`].join("|"),"i");GB=null;zB=null;qte=/sandbox/i,Yte=/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;JB="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.",zte="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.",Xte="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.",Qte="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.",Zte="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."});import{readdir as ere}from"node:fs/promises";import Tv from"node:path";function Nv(e){let t=e.map(r=>r.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*"));return new RegExp(`^(?:${t.join("|")})$`,"i")}async function tU(e,t,r={}){let n=r.now??Date.now,o=n(),s=r.maxEntries??tre,i=r.maxMs??rre,a=r.maxResults??nre,l=Nv(t),c=new Set,u=[...new Set(e.map(g=>Tv.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+=eU){if(m()){f=!0;break}let y=u.slice(h,h+eU),b=await Promise.all(y.map(k=>ere(k,{withFileTypes:!0}).then(v=>({dir:k,entries:v}),v=>(ore.has(v?.code??"")||(f=!0),{dir:k,entries:[]}))));for(let{dir:k,entries:v}of b)for(let S of v){if(d>=s){f=!0;break}d+=1;let w=Tv.join(k,S.name);l.test(S.name)?c.add(sre(w)):S.isDirectory()&&!S.isSymbolicLink()&&g.push(w)}}if(f)break;if(u=g,u.length&&m()){f=!0;break}}return{paths:[...c].sort(),scanned:d,truncated:f,durationMs:n()-o}}function sre(e){return e.split(Tv.sep).join("/")}var tre,rre,nre,eU,ore,Dv=p(()=>{"use strict";tre=25e4,rre=15e3,nre=2e3,eU=64,ore=new Set(["ENOENT","EACCES","EPERM","ENOTDIR"])});import{spawn as ire}from"node:child_process";import{mkdirSync as are,mkdtempSync as lre,rmSync as cre,writeFileSync as Af}from"node:fs";import{tmpdir as ure}from"node:os";import Do from"node:path";function vre(){return{".curlrc":`retry = 5
|
|
248
|
+
`);return}let k=h.port?Number(h.port):80;jB(h.hostname,t).then(v=>{if(!v.allowed){o.denied+=1,g.writeHead(Ov,{"Content-Type":"text/plain",Connection:"close"}).end(`Kynver folder sandbox: ${v.reason}
|
|
249
|
+
`);return}o.allowed+=1;let y={...m.headers};delete y["proxy-connection"],delete y["proxy-authorization"];let b=Tte({host:v.address,port:k,method:m.method,path:`${h.pathname}${h.search}`,headers:y,setHost:!1,createConnection:()=>r(v.address,k,v.host)},S=>{g.writeHead(S.statusCode??502,S.headers),S.pipe(g)});b.setTimeout(n,()=>b.destroy(new Error("idle"))),b.on("error",S=>{g.headersSent||g.writeHead(502,{"Content-Type":"text/plain"}),g.end(`Kynver folder sandbox: could not reach ${v.host}:${k} (${S.code??S.message})
|
|
250
|
+
`)}),m.pipe(b)})},a=()=>{let m=Ote(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 qB(e={}){return _i?.listening()?_i:(xf||(xf=$te(e).then(t=>(_i=t,Kl=null,t)).catch(t=>{throw _i=null,Kl=`egress proxy could not start: ${t?.message??String(t)}`.slice(0,240),new Error(Kl)}).finally(()=>{xf=null})),xf)}function YB(){return _i?.listening()?{status:"running",port:_i.port}:Kl?{status:"failed",reason:Kl}:{status:"not_started"}}var Mte,Wte,Ov,_i,xf,Kl,Tv=p(()=>{"use strict";Mte=253;Wte=10*6e4,Ov=403;_i=null,xf=null,Kl=null});import{existsSync as Hte}from"node:fs";import Ef from"node:path";function Dv(e=process.env,t={}){let r=(e[jte]??t.chatFolderSandbox??"").toString().trim().toLowerCase();return r==="best-effort"||r==="best_effort"||r==="optional"?"best_effort":"required"}function ZB(e=process.env,t={}){let r=[],n=e[Vte];n&&r.push(...n.split(/[\s,]+/)),Array.isArray(t.chatFolderSandboxDomains)&&r.push(...t.chatFolderSandboxDomains.filter(s=>typeof s=="string"));let o=[...Gte];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 Cf(e){return`~/${e}`}function Yte(){let e=[];for(let t of Af)e.push(`Read(${Cf(t)}/**)`,`Edit(${Cf(t)}/**)`);for(let t of If)e.push(`Read(${Cf(t)})`,`Edit(${Cf(t)})`);for(let t of xi)e.push(`Read(//**/${t})`,`Edit(//**/${t})`);return e}function zte(e,t=[],r={}){let n=["~/",...qte];for(let o of Af)n.push(`~/${o}`);for(let o of If)n.push(`~/${o}`);for(let o of t)n.push(Nv(o));if(r.scanComplete!==!0)for(let o of e)for(let s of xi)n.push(Ef.posix.join(Nv(o),"**",s));return n}function Xte(e){return[...e.map(Nv),...Jte.map(t=>`~/${t}`)]}function Nv(e){return e.split(Ef.sep).join("/")}function zB(e){let t={deny:Yte(),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:zte(e.folders,e.sensitiveFiles,{scanComplete:e.sensitiveScanComplete}),allowRead:Xte(e.folders)},network:{allowedDomains:e.domains,allowLocalBinding:!0,...typeof r=="number"&&r>0?{httpProxyPort:r}:{}}}}}function eU(e){return!!e&&Qte.test(e)}function Zte(e,t,r){return(t.PATH??"").split(Ef.delimiter).filter(Boolean).some(o=>r(Ef.join(o,e)))}function ere(e={}){let t=e.platform??process.platform,r=e.env??process.env,n=e.exists??Hte;if(t==="darwin")return{kind:"seatbelt",available:!0,missing:[]};if(t==="linux"){let o=["bwrap","socat"].filter(s=>!Zte(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 Mv(){return XB??=ere(),XB}function rU(e){tU=e.trim().slice(0,240)||"sandbox failed to start"}function Lv(){return tU}function nU(e){return e.streamed.trim()||e.exitCode===0||e.numTurns!==null&&e.numTurns>0?!1:tre.test(e.detail)&&rre.test(e.detail)}function oU(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:zB({folders:t,sandbox:!0,domains:e.domains,egressProxyPort:o,sensitiveFiles:e.sensitiveFiles,sensitiveScanComplete:e.sensitiveScanComplete}),note:o?`${QB} ${nre}`:`${QB} ${ore}`}}let n=zB({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:ire}:{shell:"disabled",policy:e.policy,runtime:e.runtime,reason:r,settings:n,note:sre}}function Pf(e=process.env,t={},r={}){let n=r.runtime??Mv(),o=r.startupFailure===void 0?Lv():r.startupFailure,s=Dv(e,t),i=n.available?o??void 0:n.reason,a=i?s==="best_effort"?"unconfined":"disabled":"sandboxed",l=r.egress??YB(),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 jte,Vte,Gte,Af,If,xi,Jte,qte,Do,Qte,XB,tU,tre,rre,QB,nre,ore,sre,ire,$l=p(()=>{"use strict";Tv();jte="KYNVER_CHAT_FOLDER_SANDBOX",Vte="KYNVER_CHAT_FOLDER_SANDBOX_DOMAINS";Gte=["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"];Af=[".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"],If=[".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"],xi=[".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.*"],Jte=[".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"],qte=["/home","/root","/Users","/mnt","/media","/Volumes"];Do=3128,Qte=new RegExp([`failed to connect to (?:localhost|127\\.0\\.0\\.1|::1|\\[::1\\]) port ${Do}\\b`,`(?:localhost|127\\.0\\.0\\.1|\\[::1\\]|::1):${Do}\\b[^\\n]{0,80}?(?:connection refused|econnrefused)`,`(?:connection refused|econnrefused)[^\\n]{0,80}?(?:localhost|127\\.0\\.0\\.1|::1):${Do}\\b`,`(?:cannot|could not|unable to) connect to proxy[^\\n]{0,80}?${Do}\\b`,`proxyerror[^\\n]{0,120}?${Do}\\b`].join("|"),"i");XB=null;tU=null;tre=/sandbox/i,rre=/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;QB="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.",nre="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.",ore="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.",sre="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.",ire="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."});import{readdir as are}from"node:fs/promises";import Bv from"node:path";function Uv(e){let t=e.map(r=>r.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*"));return new RegExp(`^(?:${t.join("|")})$`,"i")}async function iU(e,t,r={}){let n=r.now??Date.now,o=n(),s=r.maxEntries??lre,i=r.maxMs??cre,a=r.maxResults??ure,l=Uv(t),c=new Set,u=[...new Set(e.map(g=>Bv.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+=sU){if(m()){f=!0;break}let k=u.slice(h,h+sU),v=await Promise.all(k.map(y=>are(y,{withFileTypes:!0}).then(b=>({dir:y,entries:b}),b=>(dre.has(b?.code??"")||(f=!0),{dir:y,entries:[]}))));for(let{dir:y,entries:b}of v)for(let S of b){if(d>=s){f=!0;break}d+=1;let w=Bv.join(y,S.name);l.test(S.name)?c.add(pre(w)):S.isDirectory()&&!S.isSymbolicLink()&&g.push(w)}}if(f)break;if(u=g,u.length&&m()){f=!0;break}}return{paths:[...c].sort(),scanned:d,truncated:f,durationMs:n()-o}}function pre(e){return e.split(Bv.sep).join("/")}var lre,cre,ure,sU,dre,Fv=p(()=>{"use strict";lre=25e4,cre=15e3,ure=2e3,sU=64,dre=new Set(["ENOENT","EACCES","EPERM","ENOTDIR"])});import{spawn as fre}from"node:child_process";import{mkdirSync as mre,mkdtempSync as gre,rmSync as hre,writeFileSync as Of}from"node:fs";import{tmpdir as yre}from"node:os";import Mo from"node:path";function Ere(){return{".curlrc":`retry = 5
|
|
251
251
|
retry-connrefused
|
|
252
252
|
retry-delay = 1
|
|
253
253
|
`,".wgetrc":`tries = 5
|
|
254
254
|
retry_connrefused = on
|
|
255
255
|
waitretry = 1
|
|
256
|
-
`}}function
|
|
257
|
-
`)}function
|
|
258
|
-
${n}`:"Continue."}function
|
|
256
|
+
`}}function Ire(){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 ${Are} ]; 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(`
|
|
257
|
+
`)}function Pre(e){let t=Mo.join(e,"net");mre(t,{recursive:!0,mode:448});for(let[n,o]of Object.entries(Ere()))Of(Mo.join(t,n),o,{encoding:"utf8",mode:420});let r=Mo.join(t,"bridge-wait.sh");return Of(r,Ire(),{encoding:"utf8",mode:420}),{CURL_HOME:t,WGETRC:Mo.join(t,".wgetrc"),BASH_ENV:r}}function Kv(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 Ore(e){if(!Kv(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 Tre(e){if(!Kv(e))return!1;let t=e.event;return t.type==="content_block_start"&&t.content_block?.type==="text"}function Nre(e){if(!Kv(e))return"";let t=e.event;return t.type!=="message_delta"?"":typeof t.delta?.stop_reason=="string"?t.delta.stop_reason:""}function Dre(e,t){let r=typeof t=="number"&&Number.isFinite(t)?Math.floor(t):0;if(r<=0)return e;let n=Number(e[lU]);return Number.isFinite(n)&&n>=r?e:{...e,[lU]:String(r)}}function Mre(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 Lre(e){return typeof e.session_id=="string"&&e.session_id.trim()?e.session_id.trim():null}function Bre(e){let t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?mB(r.content).trim():"";return n?`User:
|
|
258
|
+
${n}`:"Continue."}function Fre(e){return e.streamed.trim()||e.exitCode===0&&!e.resultIsError?!1:Ure.test(e.detail)||e.numTurns===0}function Wre(e,t){let r=e.trim().slice(0,240);return vre.test(e)?`${bre}: ${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 Kre(e){try{return{port:(await qB(e)).port}}catch(t){return{reason:t?.message??String(t)}}}async function $re(e){if(e.access.access!=="folder"&&e.access.access!=="folders")return null;let t=e.sandboxRuntime??Mv(),r=Lv(),n=t.available&&!r,o=n?await Kre(e.egressProxy):null,s=n?await iU(e.access.folders,xi):null;return s?.truncated&&console.error(JSON.stringify({event:"chat_folder_sensitive_scan_truncated",scanned:s.scanned,found:s.paths.length,durationMs:s.durationMs})),oU({access:e.access,policy:Dv(e.env,e.config),runtime:t,domains:ZB(e.env,e.config),startupFailure:r,egress:o,sensitiveFiles:s?.paths??[],sensitiveScanComplete:s?!s.truncated:!1})}async function Tf(e){let t=Date.now(),r=!1,n=null,o=null,s=(i,a)=>(e.onStepLogged??bL)({at:new Date().toISOString(),turnId:e.turnId??"",resumed:r,appVersion:n,durationMs:Date.now()-t,ok:i,...i?{}:{reason:kL(a)}});try{let i=await Hre(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 Hre(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??FB,a=UB(e.step);if(a<=0)throw new Error("claude_code_no_time_left");let l=lr(e.payload.tools),c=hv(e.payload,"agent",l,e.access),u=e.spawnTarget?.executable??(s.KYNVER_CLAUDE_BIN?.trim()||s.CLAUDE_BIN?.trim()||"claude"),d=gre(Mo.join(e.tempRoot??yre(),"kynver-claude-code-")),f=Mo.join(d,"kynver-system-prompt.md"),m=Pc(e.model,{pinned:e.modelPinned===!0}),g=Mo.join(d,"kynver-claude-code-settings.json"),h=Date.now(),k=new Set(l.map(R=>R.name)),v=()=>$re({access:e.access,env:s,config:e.config,sandboxRuntime:e.sandboxRuntime,egressProxy:e.egressProxy}),y=await v();y?.network==="domain-list"&&console.error(JSON.stringify({event:"claude_code_sandbox_egress_unavailable",turnId:e.turnId??null,reason:y.networkReason??null}));let b={},S=()=>{Of(f,y?`${c.head}
|
|
259
259
|
|
|
260
|
-
${
|
|
260
|
+
${y.note}`:c.head,{encoding:"utf8",mode:384}),y&&Of(g,JSON.stringify(y.settings,null,2),{encoding:"utf8",mode:384}),b=y?.shell==="sandboxed"?Pre(d):{}},w=()=>y?{settingsFile:g,shell:y.shell}:void 0,_=async()=>{let R=i.get(e.step.session);if(R){let W=a-(Date.now()-h);if(W<=0)throw new Error("claude_code_no_time_left");r(!0);let O=await cU({...e,env:s,extraEnv:{...e.extraEnv,...b},executable:u,sessions:i,limitMs:W,advertisedNames:k,maxTokens:e.payload.maxTokens,args:Iv({model:e.model,fallbackModel:m,systemPromptFile:f,access:e.access,prompt:Bre(e.payload),resumeSessionId:R,sandbox:w()}),resumed:!0,sandboxed:y?.shell==="sandboxed",onAppVersion:n});if(!O.resumeRefused)return O;i.forget(e.step.session),r(!1)}let T=a-(Date.now()-h);if(T<=0)throw new Error("claude_code_no_time_left");return cU({...e,env:s,extraEnv:{...e.extraEnv,...b},executable:u,sessions:i,limitMs:T,advertisedNames:k,maxTokens:e.payload.maxTokens,args:Iv({model:e.model,fallbackModel:m,systemPromptFile:f,access:e.access,prompt:c.body||"Continue.",sandbox:w()}),resumed:!1,sandboxed:y?.shell==="sandboxed",onAppVersion:n})};try{S();let R=await _();return R.sandboxUnavailable&&y&&(rU(R.sandboxUnavailable),y=await v(),console.error(JSON.stringify({event:"claude_code_sandbox_unavailable",turnId:e.turnId??null,reason:R.sandboxUnavailable,shell:y?.shell??null})),S(),R=await _(),R.sandboxUnavailable&&(R={error:new Error(`claude_code_sandbox_unavailable: ${R.sandboxUnavailable}`)})),(R.failure?.startsWith(Wv)||R.error?.message.startsWith(Wv))&&a-(Date.now()-h)>Cre&&(console.error(JSON.stringify({event:"claude_code_sandbox_proxy_down_retry",turnId:e.turnId??null})),R=await _()),o(R)}finally{hre(d,{recursive:!0,force:!0})}}function cU(e){let t=_B();return new Promise(r=>{let n;try{let[x,V]=se(e.executable,[...e.spawnTarget?.prefixArgs??[],...e.args]),N=Z({cwd:e.access.workDir,detached:process.platform!=="win32",shell:!1,stdio:["ignore","pipe","pipe"],env:{...Dre(bB(e.env,e.access.access),e.maxTokens),...e.extraEnv,NO_COLOR:"1"}});n=fre(x,V,N)}catch(x){r({error:uU(x,e.executable)});return}let o=!1,s=new ar,i="",a="",l="",c=!1,u=null,d="",f={input_tokens:0,output_tokens:0},m=null,g="",h="",k=!1,v="",y=!1,b=0,S=!1,w=x=>{let V=s.push(x);V&&(i+=V,e.onDelta(V))},_=(x,V)=>console.error(JSON.stringify({event:x,requestId:e.requestId??null,turnId:e.turnId??null,resumed:e.resumed,access:e.access.access,appVersion:m,...V})),R=x=>{o||(o=!0,clearTimeout(G),O&&y&&clearTimeout(O),e.signal?.removeEventListener("abort",B),r(x))},T=(x="")=>{let V=s.end();V&&(i+=V,e.onDelta(V));let N=Ev(a,c?"":l),C=Tn(N,e.advertisedNames);Av(C.text,i,e.onDelta),x&&e.onDelta(x),C.rejected.length>0&&_("claude_code_tool_call_rejected",{names:C.rejected.slice(0,5)});let D=Nn(C,e.turnId??"turn",x),z=D.stop_reason==="end_turn"&&d==="max_tokens";return(C.cut||z)&&_("claude_code_reply_cut",{stopReason:d||null,cutTool:C.cut?.name??null,chars:N.length}),{content:D.content,stop_reason:z?"max_tokens":D.stop_reason,usage:f}},W=x=>{n.pid?he(n.pid,x):at(n,x)},O,L=()=>{W("SIGTERM"),O??=setTimeout(()=>{y||(W("SIGKILL"),setTimeout(()=>{o||I(null)},aU).unref())},aU),O.unref()},M=()=>{if(e.onActivity)for(let x of t.interrupted())e.onActivity(x)},B=()=>{L(),M(),R({error:new Error("claude_code_chat_aborted")})},G=setTimeout(()=>{k=!0,L()},e.limitMs);if(n.on("error",x=>R({error:uU(x,e.executable)})),e.signal){if(e.signal.aborted){B();return}e.signal.addEventListener("abort",B)}let re=x=>{let V=x.trim();if(!V)return;let N;try{N=JSON.parse(V)}catch{return}let C=Lre(N);C&&e.sessions.remember(e.step.session,C);let D=Hm(N);D&&console.error(`[chat] ${D}`),N.type==="system"&&typeof N.claude_code_version=="string"&&(m=N.claude_code_version,e.onAppVersion(m)),Tre(N)&&a&&!a.endsWith(`
|
|
261
261
|
`)&&(a+=`
|
|
262
262
|
|
|
263
263
|
`,w(`
|
|
264
264
|
|
|
265
|
-
`));let
|
|
266
|
-
`).slice(0,1e3)),f=
|
|
267
|
-
`))!==-1;){let
|
|
268
|
-
${
|
|
269
|
-
${g}`,
|
|
270
|
-
`):"";if(
|
|
265
|
+
`));let z=Ore(N);z&&(a+=z,w(z));let ue=Nre(N);if(ue&&(d=ue),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(H=>typeof H=="string").join(`
|
|
266
|
+
`).slice(0,1e3)),f=Mre(N)??f),e.onActivity)for(let H of t(N))e.onActivity(H);e.sandboxed&&!S&&N.type==="user"&&jre(N)&&(b+=1,_("claude_code_sandbox_proxy_down",{hits:b}),b>=xre&&(S=!0,L()))};n.stdout?.on("data",x=>{h+=typeof x=="string"?x:x.toString("utf8");let V;for(;(V=h.indexOf(`
|
|
267
|
+
`))!==-1;){let N=h.slice(0,V);h=h.slice(V+1),re(N)}}),n.stderr?.on("data",x=>{g+=typeof x=="string"?x:x.toString("utf8"),g.length>8e3&&(g=g.slice(-8e3))});let I=x=>{if(y=!0,o)return;if(h.trim()&&re(h),h="",M(),S){let D=`${Wv}: ${Sre}`;R(a.trim()?{message:T(_re),failure:D}:{error:new Error(D)});return}if(k){_("claude_code_step_timeout",{limitMs:e.limitMs}),R(a.trim()?{message:T(wre),failure:"claude_code_step_timeout"}:{error:new Error("claude_code_step_timeout")});return}let V=`${l}
|
|
268
|
+
${v}
|
|
269
|
+
${g}`,N=x!==0||c;if(e.sandboxed&&nU({exitCode:x,streamed:a,numTurns:u,detail:V})){R({sandboxUnavailable:V.trim().slice(0,240)||"sandbox failed to start"});return}if(e.resumed&&Fre({exitCode:x,resultIsError:c,numTurns:u,streamed:a,detail:V})){_("claude_code_resume_refused",{exitCode:x}),R({resumeRefused:!0});return}if(N){let D=Wre(V,x);_("claude_code_turn_error",{exitCode:x,error:D,partial:!!a.trim()}),R(a.trim()?{message:T(Rre),failure:D}:{error:new Error(D)});return}let C=T();_("claude_code_turn_end",{exitCode:x,stopReason:C.stop_reason}),R({message:C})};n.on("close",I)})}function jre(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(`
|
|
270
|
+
`):"";if(eU(o))return!0}return!1}function uU(e,t){return e?.code==="ENOENT"?new Error(`${kre}: failed to spawn \`${t}\`. Install Claude Code and keep \`claude\` on PATH.`):e instanceof Error?e:new Error(String(e))}var kre,bre,vre,Rre,aU,wre,Wv,Sre,_re,xre,Cre,Are,lU,Ure,$v=p(()=>{"use strict";U();We();vr();Fl();_f();WB();$B();No();$l();Fv();Tv();Zb();Ul();Sf();bi();kre="claude_code_unavailable",bre="claude_code_not_logged_in",vre=/not logged in|please run \/login|invalid api key|authentication|unauthorized|401\b/i,Rre=`
|
|
271
271
|
|
|
272
|
-
(Stopped: Claude Code ended this step with an error before finishing.)`,
|
|
272
|
+
(Stopped: Claude Code ended this step with an error before finishing.)`,aU=5e3,wre=`
|
|
273
273
|
|
|
274
|
-
(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.)`,
|
|
274
|
+
(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.)`,Wv="claude_code_sandbox_proxy_down",Sre=`sandbox network proxy not running (localhost:${Do} refused inside the folder sandbox)`,_re=`
|
|
275
275
|
|
|
276
|
-
(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.)`,
|
|
276
|
+
(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.)`,xre=2,Cre=3e4;Are=60;lU="CLAUDE_CODE_MAX_OUTPUT_TOKENS";Ure=/no conversation found|session .*not found/i});function dU(e){if(e)return e;let t=A();return{chatProvider:t.chatProvider,workerProvider:t.workerProvider}}function Hv(e,t,r=process.env,n){if(e==="cursor"){let o=rd(r);if(!o.ok)throw new dr(cA(o));return}if(e==="codex"){let o=pf(r);if(!o.ok)throw new dr(FL(o));return}if(e==="gemini"){let o=r;if(Io(dU(n),o)==="antigravity"){let s=hf(o);if(!s.ok)throw new dr(HL(s));return}if(!Tl(r))throw new dr("gemini_api_key_missing");return}if(e==="openai"){if(!Nl(r))throw new dr("openai_api_key_missing");return}if(!Pl(r,{oauthOptIn:t}))throw new dr("no_local_credentials")}async function pU(e){let t=e.env??process.env,{provider:r,model:n,payload:o,onDelta:s,signal:i}=e;Hv(r,e.useClaudeOauth,t,e.config);let a=e.config??A(),l=Po({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 IB({payload:o,model:n,onDelta:s,signal:i,turnId:e.turnId,requestId:e.requestId,onToolProgress:e.onToolProgress,...u});if(r==="codex")return PB({payload:o,model:n,onDelta:s,signal:i,turnId:e.turnId,...u});if(r==="gemini"&&Io(dU(e.config),t)==="antigravity")return NB({payload:o,model:n,onDelta:s,signal:i,turnId:e.turnId,env:t,...u});if(r==="gemini"||r==="openai"){let m=r==="gemini"?Tl(t):Nl(t);return MB({creds:m,model:n,payload:o,onDelta:s,signal:i})}let d=BB(o.claudeCode);if(d&&l.engine==="claude-code"&&l.access.access!=="off")return Tf({payload:o,model:n,modelPinned:e.modelPinned,onDelta:s,signal:i,step:d,turnId:e.turnId,requestId:e.requestId,env:t,config:a,...u});let f=Pl(t,{oauthOptIn:e.useClaudeOauth});return tB({creds:f,model:n,payload:o,onDelta:s,onToolProgress:e.onToolProgress,signal:i})}var dr,jv=p(()=>{"use strict";sv();fv();Bs();Sf();ff();OB();yf();DB();Gp();av();LB();$();of();_f();$v();dr=class extends Error{constructor(r){super(r);this.code=r;this.name="ChatCredentialError"}code}});function Vre(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 fU(e){let t=Ll(e.payload.requestedModel),r=typeof e.payload.fallbackNoticeShown=="string"?e.payload.fallbackNoticeShown:null,{requestedModel:n,fallbackNoticeShown:o,...s}=e.payload,i=VL({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=qL(i,g),k=YL(i,g);!h||!k||h===r||d||(d=`${k}
|
|
277
277
|
|
|
278
|
-
`,f=h,e.onDelta(d))};for(;;){c.push(i.provider);try{m();let g=i.fallbackReason==="usage_limit"?!1:t&&!i.fallbackReason?!0:e.primaryPinned===!0,h=await e.runTurn({provider:i.provider,model:i.model,modelPinned:g,payload:s,onDelta:
|
|
279
|
-
`;)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
|
|
280
|
-
`,{mode:384}),
|
|
281
|
-
`);try{return{event:t,data:JSON.parse(n)}}catch{return{event:t,data:n}}}async function*
|
|
282
|
-
`))!==-1;){let c=n.slice(0,l).replace(/\r$/,"");if(n=n.slice(l+1),c===""){let u=
|
|
278
|
+
`,f=h,e.onDelta(d))};for(;;){c.push(i.provider);try{m();let g=i.fallbackReason==="usage_limit"?!1:t&&!i.fallbackReason?!0:e.primaryPinned===!0,h=await e.runTurn({provider:i.provider,model:i.model,modelPinned:g,payload:s,onDelta:v=>{v&&(u=!0),e.onDelta(v)}});return{...d?Vre(h,d):h,kynverModel:{provider:i.provider,model:i.model,requested:i.fallbackReason?a:null,fallbackReason:i.fallbackReason,noticeKey:f}}}catch(g){let k=!u&&(JL(g)||g instanceof dr&&c.length>1)?GL(e.catalog,c):null;if(!k)throw g;console.error(JSON.stringify({event:"chat_turn_provider_fallback",from:`${i.provider}:${i.model}`,to:`${k.provider}:${k.model}`,reason:"usage_limit"})),i={...k,requested:t,fallbackReason:"usage_limit"}}}}var mU=p(()=>{"use strict";uv();jv()});var Nf,gU=p(()=>{"use strict";Nf=class{constructor(t,r=Date.now){this.claimReceivedAt=t;this.now=r}claimReceivedAt;now;modelStartAt=null;firstDeltaAt=null;noteModelStart(){this.modelStartAt===null&&(this.modelStartAt=this.now())}noteDelta(){this.firstDeltaAt===null&&(this.firstDeltaAt=this.now())}stamp(){if(this.modelStartAt===null)return null;let t=this.now(),r=this.firstDeltaAt??this.modelStartAt;return{claimToModelMs:Math.max(0,this.modelStartAt-this.claimReceivedAt),ttftMs:this.firstDeltaAt===null?null:Math.max(0,this.firstDeltaAt-this.modelStartAt),generateMs:Math.max(0,t-r)}}}});function Gre(e,t,r,n,o){try{let s=Po({provider:t.chatProvider,config:n,payloadAccess:e.payload.computerAccess,boxId:t.boxId}),i=GM(s.access,{signed:r.signed});if(!i)return;let a=i.from?fi(i.from.access):"not set",l=fi(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};mi({...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 Vv(e,t,r){let n=Date.now(),o=0,s=!1,i=new Pn,a=new AbortController,l=t.requestId??"",c=new Nf(t.claimReceivedAtMs??n),u=y=>{s||i.track(Ee(e,t.turnId,[{seq:o++,kind:"delta",text:y}]).then(b=>(b||(s=!0,a.abort()),b)))},d=new In(u,void 0,rr(e.agentOsId),!0),f=gB(()=>{s||i.track(Ee(e,t.turnId,[{seq:o++,kind:"activity",activity:{kind:"tool_progress"}}]).then(y=>(y||(s=!0,a.abort()),y)))}),m=uf({turnId:t.turnId,chat:l||null,send:y=>{s||(d.flush(),i.track(Ee(e,t.turnId,[{seq:o++,kind:"activity",activity:y}]).then(b=>(b||(s=!0,a.abort()),b))))}}),g=e.chatProvider??"anthropic",h=A(),k=ki(h);r&&Gre(t,e,r,h,y=>{s||i.track(Ee(e,t.turnId,[{seq:o++,kind:"activity",activity:y}]).then(b=>(b||(s=!0,a.abort()),b)))});try{Hv(g,e.useClaudeOauth,process.env,h)}catch(y){let b=Ll(t.payload.requestedModel);if(!(b&&k.some(w=>w.provider===b.provider&&w.models.includes(b.model)))){let w=y instanceof Error?y.message:String(y);await Ht(()=>Ee(e,t.turnId,[{seq:0,kind:"error",error:w}]).catch(()=>!1));return}}let v={provider:g,model:e.model};try{let y=await fU({payload:t.payload,catalog:k,primary:{provider:g,model:e.model},primaryPinned:!!(process.env.KYNVER_CHAT_MODEL?.trim()||h.defaultModel?.trim()),onDelta:R=>{c.noteDelta(),d.push(R)},runTurn:R=>(c.noteModelStart(),v={provider:R.provider,model:R.model},pU({...R,onToolProgress:()=>f.noteToolBytes(),signal:a.signal,turnId:t.turnId,requestId:t.requestId,useClaudeOauth:e.useClaudeOauth,config:h,boxId:e.boxId,onActivity:m.sink}))});TL(y.content,Po({provider:v.provider,config:h,payloadAccess:t.payload.computerAccess,boxId:e.boxId}),m),d.close(),await i.drain();let b=c.stamp(),S=b?{...y,kynverTiming:b}:y,w=o++;if(!await Ht(()=>s?Ee(e,t.turnId,[{seq:w,kind:"error",error:"turn_stream_aborted"}]).catch(()=>!1):Ee(e,t.turnId,[{seq:w,kind:"final",message:S}]).catch(()=>!1))){console.error(JSON.stringify({event:"chat_turn_final_rejected",requestId:l,turnId:t.turnId,model:v.model,chatProvider:v.provider}));return}console.error(JSON.stringify({event:"chat_turn_done",requestId:l,turnId:t.turnId,model:v.model,chatProvider:v.provider,fallbackReason:y.kynverModel.fallbackReason,activitySteps:m.steps,...b??{},durationMs:Date.now()-n}))}catch(y){if(d.close(),await i.drain(),!s){let b=ML(y instanceof Error?y.message:String(y)),S=o++;await Ht(()=>Ee(e,t.turnId,[{seq:S,kind:"error",error:b}]).catch(()=>!1))}console.error(JSON.stringify({event:"chat_turn_error",requestId:l,turnId:t.turnId,error:y instanceof Error?y.message:String(y),durationMs:Date.now()-n}))}}var Gv=p(()=>{"use strict";$();Kb();ov();NL();Cl();LL();Ml();uv();dv();of();mU();jv();gU();lf();yv();cf();jr();Il()});function yU(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 Hl(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 hU.set(e,n),n}function Df(e){return hU.get(e)??null}var hU,Jv=p(()=>{"use strict";hU=new Map});import{existsSync as kU,readFileSync as Jre}from"node:fs";import{homedir as bU}from"node:os";import Lo from"node:path";function vU(e){try{return kU(e)?Jre(e,"utf8"):null}catch{return null}}function qre(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 RU(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 Yre(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 zre(e){return/^(1|true|yes|on)$/i.test((e??"").trim())}function wU(e={}){let r=(e.env??process.env).HERMES_HOME?.trim();return r?Lo.resolve(r):Lo.join(e.home??bU(),".hermes")}function Xre(e={}){return Lo.join(wU(e),".env")}function Mf(e={}){let t=e.readFile??vU,r=Xre(e),n=t(r),o=n===null?{}:Yre(n),s=o.API_SERVER_KEY?.trim()||null;return{baseUrl:`http://${qre(o.API_SERVER_HOST)}:${RU(o.API_SERVER_PORT,8642)}`,key:s,enabled:zre(o.API_SERVER_ENABLED)||s!==null&&o.API_SERVER_ENABLED===void 0,configured:n!==null||kU(wU(e)),configPath:r}}function Qre(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]!==`
|
|
279
|
+
`;)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 jl(e,t){let r=e;for(let n of t){if(!r||typeof r!="object"||Array.isArray(r))return;r=r[n]}return r}function Vl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Zre(e={}){let t=e.env??process.env,r=t.OPENCLAW_CONFIG_PATH?.trim();if(r)return Lo.resolve(r);let n=t.OPENCLAW_STATE_DIR?.trim();return Lo.join(n?Lo.resolve(n):Lo.join(e.home??bU(),".openclaw"),"openclaw.json")}function Lf(e={}){let t=e.env??process.env,r=e.readFile??vU,n=Zre(e),o=r(n),s=o===null?null:Qre(o),i=Vl(jl(s,["gateway","auth","mode"])),a=(i==="password"?Vl(jl(s,["gateway","auth","password"]))??Vl(t.OPENCLAW_GATEWAY_PASSWORD):Vl(jl(s,["gateway","auth","token"]))??Vl(t.OPENCLAW_GATEWAY_TOKEN))??(i==="none"?"":null);return{baseUrl:`http://127.0.0.1:${RU(t.OPENCLAW_GATEWAY_PORT??jl(s,["gateway","port"]),18789)}`,key:a,enabled:jl(s,["gateway","http","endpoints","chatCompletions","enabled"])===!0,configured:o!==null,configPath:n}}var qv=p(()=>{"use strict"});import{existsSync as ene}from"node:fs";import{homedir as tne,platform as rne}from"node:os";import Dn from"node:path";function nne(e,t,r={}){if(t==="darwin")return Dn.join(e,"Library","Application Support","Grok Bot");if(t==="win32"){let s=r.APPDATA?.trim();return Dn.join(s||Dn.join(e,"AppData","Roaming"),"Grok Bot")}let n=r.XDG_CONFIG_HOME?.trim(),o=n&&Dn.isAbsolute(n)?n:Dn.join(e,".config");return Dn.join(o,"Grok Bot")}function one(e){return[Dn.join("/opt","Grok Bot","grok-bot"),Dn.join(e,".local","bin","grok-bot")]}async function SU(e={}){let t=e.home??tne(),r=e.platform??rne(),n=e.env??process.env,o=e.exists??ene,s=e.versionOf??(async()=>null),i=r==="linux"?one(t):[],a=await s("grok-bot");if(!a){for(let c of i)if(o(c)&&(a=await s(c),a))break}return{installed:!!a||o(nne(t,r,n))||i.some(c=>o(c)),version:a}}var _U=p(()=>{"use strict"});async function Bf(e={}){let t=await SU(e);return t.installed?{status:"not_enabled",version:t.version,detail:ine}:{status:"not_installed",version:null,detail:sne}}var sne,ine,Yv=p(()=>{"use strict";_U();sne="Grok Bot is not installed on this computer.",ine="Grok Bot is installed. Kynver chat for this tab does not use the desktop app."});import{execFile as ane}from"node:child_process";async function mne(e){let t=xU.get(e);if(t&&Date.now()-t.at<cne)return t.version;let r=await new Promise(n=>{try{let[o,s]=se(e,["--version"]);ane(o,s,Z({encoding:"utf8",timeout:5e3}),(i,a,l)=>{if(i)return n(null);n(`${a??""} ${l??""}`.match(fne)?.[0]??null)})}catch{n(null)}});return xU.set(e,{at:Date.now(),version:r}),r}async function CU(e,t,r,n=une){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 zv(e){let t=AU.get(e)??null,r=Df(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 jt(e,t,r,n){let o=zv(e);return{engine:e,status:t,version:r,detail:n,lastRoundTrip:Df(e),lastReadyAt:o===null?null:new Date(o).toISOString()}}async function EU(e,t,r,n,o=Date.now){if(!t.configured&&!r)return null;let s=e==="hermes"?"Hermes":"OpenClaw";if(!t.enabled)return jt(e,"not_enabled",r,`${s}'s local chat API is off`);if(t.key===null)return jt(e,"no_key",r,`${s}'s local chat API has no key set`);let i=`${t.baseUrl}/v1/models`,a=await CU(n,i,t.key||null)??await CU(n,i,t.key||null,dne);if(a===null){let l=zv(e);return l!==null&&o()-l<pne?jt(e,"ready",r,null):jt(e,"unreachable",r,`${s} is not answering on ${t.baseUrl} \u2014 is its gateway running?`)}return a===401||a===403?jt(e,"no_key",r,`${s} refused the key in its config (HTTP ${a})`):a===404?jt(e,"not_enabled",r,`${s} is running but its chat API is not switched on`):(AU.set(e,o()),jt(e,"ready",r,null))}function gne(e){let{version:t,signedIn:r}=(e.claudeCode??(()=>({version:zp("claude-code",e.env),signedIn:Xp(e.env)})))();return t?r?(e.config??A()).chatComputerAccess==="off"?jt("claude-code","access_off",t,"Computer access for chat is off on this computer"):jt("claude-code","ready",t,null):jt("claude-code","not_signed_in",t,"Claude Code is installed but not signed in"):null}async function hne(e){let t=await Bf({home:e.home,env:e.env,exists:e.grokBotExists,versionOf:e.versionOf,platform:e.platform});return jt("grok-bot",t.status,t.version,t.detail)}async function yne(e={}){let t=e.env??process.env,r=e.fetchFn??fetch,n=e.versionOf??mne,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([EU("hermes",Mf(e),i,r,e.now),EU("openclaw",Lf(e),a,r,e.now)]),u=await hne({...e,versionOf:n});return{v:1,engines:[l,c,gne(e),u].filter(f=>f!==null)}}function kne(e={}){return Gl||(Jl&&Date.now()-Jl.at<lne?Promise.resolve():(Gl=yne(e).then(t=>{Jl={at:Date.now(),report:t}}).catch(()=>{}).finally(()=>{Gl=null}),Gl))}function Uf(){if(kne(),!!Jl)return{v:1,engines:Jl.report.engines.map(e=>{let t=zv(e.engine);return{...e,lastRoundTrip:Df(e.engine),lastReadyAt:t===null?null:new Date(t).toISOString()}})}}var lne,cne,une,dne,pne,fne,xU,AU,Jl,Gl,Xv=p(()=>{"use strict";$();We();U();El();Jv();qv();Yv();lne=3e4,cne=10*6e4,une=1500,dne=5e3,pne=3e4,fne=/\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?/,xU=new Map;AU=new Map;Jl=null,Gl=null});function IU(){return bne}var bne,PU=p(()=>{"use strict";Yv();bne={id:"mailbox",probe:e=>Bf(e),relay(){return Promise.resolve({text:"",mailbox:!0})}}});import{existsSync as vne,mkdirSync as Rne,readFileSync as wne,renameSync as Sne,writeFileSync as _ne}from"node:fs";import{homedir as xne}from"node:os";import TU from"node:path";function Cne(e=xne()){return TU.join(e,".kynver","agent-tab-sessions.json")}function NU(e=Cne(),t=Date.now){let r=()=>{try{if(!vne(e))return{};let o=JSON.parse(wne(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>OU&&s.sort((i,a)=>o[i].at-o[a].at).slice(0,s.length-OU).forEach(i=>delete o[i]);try{Rne(TU.dirname(e),{recursive:!0,mode:448});let i=`${e}.${process.pid}.tmp`;_ne(i,`${JSON.stringify(o)}
|
|
280
|
+
`,{mode:384}),Sne(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 OU,DU=p(()=>{"use strict";OU=500});function MU(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(`
|
|
281
|
+
`);try{return{event:t,data:JSON.parse(n)}}catch{return{event:t,data:n}}}async function*Ff(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(`
|
|
282
|
+
`))!==-1;){let c=n.slice(0,l).replace(/\r$/,"");if(n=n.slice(l+1),c===""){let u=MU(o);o=[],u&&(yield u)}else o.push(c)}}n+=r.decode(),n&&o.push(n.replace(/\r$/,""));let s=MU(o);s&&(yield s)}finally{t.releaseLock()}}var Qv=p(()=>{"use strict"});function Zv(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 LU(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 BU(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"?"":Zv(n.content)}).join(""):""}function eR(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:BU(r.response)||null,finishReason:"stop",error:null};if(n==="response.failed"||n==="error"){let d=r.response;return{delta:"",full:null,finishReason:"error",error:LU(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?LU(r.error)??"the agent reported an error":null,i=(Array.isArray(r.choices)?r.choices:[])[0]??null,a=Zv(i?.delta?.content)||(typeof i?.text=="string"?i.text:""),l=i?.message?.content,c=l==null?null:Zv(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 UU(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:BU(t),finishReason:"stop",error:null}:eR(null,e)}var FU=p(()=>{"use strict"});function WU(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?t.text:"").join(""):""}function Ene(e,t){if(!Array.isArray(e)||e.length===0)return null;let r=KU(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=WU(s.content);n===null&&i.trim()&&(n=i);continue}if(s.role!=="tool"&&s.role==="user")return n===null?null:!r||KU(WU(s.content)).includes(r)?n:null}}return null}async function $U(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 Ene(i?.data,e.sentText)}catch{return null}finally{clearTimeout(n),e.signal?.removeEventListener("abort",o)}}var KU,HU=p(()=>{"use strict";KU=e=>e.replace(/\s+/g," ").trim()});function Ane(e=process.env){let t=e.KYNVER_OPENCLAW_AGENT?.trim();return t?`openclaw/${t}`:"openclaw/default"}function Wf(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 Ine(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 tR(e,t,r,n,o){let s=`Conversation opened from Kynver chat (${t}).`,i=o?ef(o):null,a=r?.trim();if(a){let l=e==="hermes"?`${a}
|
|
283
283
|
|
|
284
284
|
${s}`:a;return i?`${l}
|
|
285
285
|
|
|
286
|
-
${i}`:l}return e==="hermes"&&!n?s:null}async function
|
|
286
|
+
${i}`:l}return e==="hermes"&&!n?s:null}async function jU(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=tR(e.engine,e.sessionKey,e.styleNote,t!==null,e.conversationId);e.conversationId&&(n[sL]=e.conversationId),i&&o.push({role:"system",content:i}),e.engine==="hermes"?(t&&(n["X-Hermes-Session-Id"]=t),o.push({role:"user",content:Wf(e.text,e.attachments)}),s={model:"hermes-agent",stream:!0,messages:o}):(o.push({role:"user",content:Wf(e.text,e.attachments)}),s={model:Ane(),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 rR(e){let t=e.now??Date.now,r=e.engine==="hermes"?e.sessions.get(e.sessionKey):null,n=await jU(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 jU(e,null)),!n.ok||!n.body)throw await n.body?.cancel().catch(()=>{}),Ine(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()&&Pne.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=UU(f);m&&c(m)}else{let f=new Map;for await(let m of Ff(n.body)){if(m.data==="[DONE]")break;if(m.event==="hermes.tool.progress"){i=!0;let h=m.data??{},k=typeof h.toolCallId=="string"?h.toolCallId:String(h.tool??""),v=[h.emoji,h.label??h.tool].filter(y=>typeof y=="string"&&y).join(" ").slice(0,300);if(h.status==="running")f.set(k,{at:t(),label:v||"tool"}),e.sink.onTool({label:v||"tool",status:"running",durationMs:null});else{let y=f.get(k);f.delete(k),e.sink.onTool({label:y?.label??(v||String(h.tool??"tool")),status:"completed",durationMs:y===void 0?null:t()-y.at})}continue}if(m.event==="approval.request"){let h=m.data??{},k=[h.description,h.command].find(v=>typeof v=="string"&&v);e.sink.onTool({label:`Waiting for approval in ${e.engine==="hermes"?"Hermes":"OpenClaw"}${k?`: ${k.slice(0,200)}`:""}`,status:"approval",durationMs:null});continue}let g=eR(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 $U({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 Pne,nR=p(()=>{"use strict";tf();Qv();FU();HU();Pne=/cannot be represented as an append-only response stream/i});import{mkdirSync as One,readFileSync as Tne,realpathSync as Nne,statSync as Dne,writeFileSync as Mne}from"node:fs";import{homedir as oR}from"node:os";import pr from"node:path";function iR(e=oR()){return pr.join(e,".kynver","agent-tabs","inbox")}function VU(e,t=80){return e.replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^\.+/,"_").slice(0,t)||"file"}function JU(e,t,r={}){if(t.length===0)return[];let n=pr.join(r.root??iR(),VU(e,120));One(n,{recursive:!0,mode:448});let o=(r.now??Date.now)();return t.map((s,i)=>{let a=Buffer.from(s.contentBase64,"base64"),l=pr.join(n,`${o}-${i}-${VU(s.name,120)}`);Mne(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 $f(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(`
|
|
287
287
|
|
|
288
|
-
`)}function
|
|
288
|
+
`)}function aR(e){let t=[];return{text:e.replace(Lne,(n,o,s,i,a)=>{let l=String(o??s??i??a??"").replace(/[),.;:!?\]]+$/,"");return l?(!t.includes(l)&&t.length<Kf&&t.push(l),""):n}).replace(/[ \t]+\n/g,`
|
|
289
289
|
`).replace(/\n{3,}/g,`
|
|
290
290
|
|
|
291
|
-
`).trim(),paths:t}}function
|
|
291
|
+
`).trim(),paths:t}}function GU(e,t=oR()){let r=pr.basename(e);if(Bne.test(r))return"credential_file";let n=pr.relative(t,e);if(!n.startsWith("..")&&!pr.isAbsolute(n)){let o=n.split(pr.sep).join("/");if(If.some(s=>o===s))return"credential_file";if(Af.some(s=>o===s||o.startsWith(`${s}/`)))return"private_folder"}return null}function Une(e,t){return e==="~"?t:e.startsWith("~/")||e.startsWith("~\\")?pr.join(t,e.slice(2)):e}function lR(e,t={}){let r=t.home??oR(),n=pr.resolve(Une(e,r)),o={path:n,name:pr.basename(n)},s=GU(n,r);if(s)return{...o,ok:!1,reason:s,sizeBytes:null,contentBase64:null};try{let i=Nne(n),a=GU(i,r);if(a)return{...o,ok:!1,reason:a,sizeBytes:null,contentBase64:null};let l=Dne(i);if(!l.isFile())return{...o,ok:!1,reason:"not_a_file",sizeBytes:null,contentBase64:null};if(l.size>sR)return{...o,ok:!1,reason:"too_large",sizeBytes:l.size,contentBase64:null};let c=Tne(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 sR,Kf,Lne,Bne,Hf=p(()=>{"use strict";$l();Fv();sR=50*1024*1024,Kf=10;Lne=/MEDIA:\s*(?:"([^"\n]+)"|'([^'\n]+)'|`([^`\n]+)`|((?:~|\/|[A-Za-z]:[\\/])[^\s"'`<>]*))/g;Bne=Uv(xi)});import{chmodSync as Wne,copyFileSync as Kne,mkdirSync as $ne}from"node:fs";import cR from"node:path";function Hne(e,t){let r=e?.trim(),n=r?`${qU}
|
|
292
292
|
|
|
293
|
-
${r}`:
|
|
293
|
+
${r}`:qU;return t?`${n}
|
|
294
294
|
|
|
295
|
-
${
|
|
295
|
+
${ef(t)}`:n}function jne(e){let t=e.config??A();return{engine:"claude-code",access:fs({engine:"claude-code",local:{chatComputerAccess:t.chatComputerAccess,chatWorkFolders:t.chatWorkFolders},website:nu(e.payloadAccess,e.boxId),home:e.home})}}function Gne(e,t){if(t.access==="full"||t.access==="off")return e;let r=cR.join(t.workDir,Vne);return e.map(n=>{if(su(t,n.path))return n;$ne(r,{recursive:!0,mode:448});let o=cR.join(r,cR.basename(n.path));return Kne(n.path,o),Wne(o,384),{...n,path:o}})}function Jne(e){return e.map(t=>t&&typeof t=="object"&&t.type==="text"?String(t.text??""):"").join("")}async function YU(e){let t=jne(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??A(),n=e.env??process.env,o=$f(e.text,Gne(e.attachments,t.access)),s=await(e.run??Tf)({payload:{system:Hne(e.styleNote,e.conversationId),tools:[],messages:[{role:"user",content:o}],maxTokens:32e3,executionMode:"agent"},model:n.KYNVER_AGENT_TAB_CLAUDE_MODEL?.trim()??"",onDelta:e.onDelta,step:e.maxStepMs?{session:e.sessionKey,timeLeftMs:e.maxStepMs,maxMs:e.maxStepMs}:{session:e.sessionKey,timeLeftMs:48e4},access:t.access,signal:e.signal,turnId:e.turnId,onActivity:i=>e.onActivity(i,t),env:n,extraEnv:iL(e.conversationId,"claude-code"),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:Jne(s.content)}}var qU,Vne,zU=p(()=>{"use strict";tf();$();Jn();$v();_f();Hf();qU="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.";Vne=".kynver-attachments"});import jf from"node:path";import{homedir as qne}from"node:os";function eoe(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 toe(e){return e.replace(/[ \t]+\n/g,`
|
|
296
296
|
`).replace(/\n{3,}/g,`
|
|
297
297
|
|
|
298
|
-
`).trim()}function
|
|
299
|
-
`,{encoding:"utf8",mode:384})}catch{}}var
|
|
298
|
+
`).trim()}function XU(e){let t=[];return e.includes("data:image/")?{text:e.replace(Yne,(n,o,s,i)=>{if(t.length>=Kf)return n;let a=s.toLowerCase(),l=`image-${t.length+1}.${zne[a]??"png"}`,c=eoe(i);return c>sR?(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 roe(e){let t=e.replace(Zne,n=>" ".repeat(n.length)),r=[];for(let n of t.matchAll(Qne)){let o=n[1].replace(/[),.;:!?\]]+$/,"");r.includes(o)||r.push(o)}return r}function noe(e,t){return e.startsWith("~/")?jf.join(t,e.slice(2)):e}function ooe(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 QU(e,t={}){let r=t.home??qne(),n=jf.resolve(t.inboxRoot??iR(r)),o=[],s=()=>o.length<Kf,i=XU(e);o.push(...i.files);let a=aR(i.text);for(let u of a.paths){if(!s())break;o.push({source:"tag",...lR(u,{home:r})})}let l=a.text,c=new Set(o.map(u=>u.path));for(let u of roe(l)){if(!s())break;let d=jf.resolve(noe(u,r));if(c.has(d)||d===n||d.startsWith(`${n}${jf.sep}`))continue;let f=lR(u,{home:r});!f.ok&&f.reason!=="too_large"||(c.add(f.path),o.push({source:"path",...f}),f.ok&&(l=ooe(l,u)))}return{text:toe(l),files:o}}function uR(e){return aR(XU(e).text).text}var Yne,zne,Xne,Qne,Zne,ZU=p(()=>{"use strict";Hf();Yne=/!\[([^\]\n]{0,200})\]\(\s*data:(image\/[a-z0-9.+-]{1,40});base64,([A-Za-z0-9+/=\r\n]+)\s*\)/gi,zne={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/bmp":"bmp"},Xne=["mp4","mov","m4v","webm","mkv","mp3","m4a","wav","ogg","oga","opus","aac","flac","png","jpg","jpeg","gif","webp","heic","pdf"],Qne=new RegExp(String.raw`(?<![\w/:.~-])((?:~\/|\/)[^\s"'\`<>()\[\]{}|]*?\.(?:${Xne.join("|")}))(?![\w/-])`,"gi"),Zne=/```[\s\S]*?(?:```|$)/g});import{appendFileSync as soe,mkdirSync as ioe}from"node:fs";import{homedir as aoe}from"node:os";import eF from"node:path";function loe(e=aoe()){return eF.join(e,".kynver","logs","agent-tabs.jsonl")}function tF(e,t=loe()){try{ioe(eF.dirname(t),{recursive:!0});let r={...e,...e.label?{label:e.label.slice(0,300)}:{}};soe(t,`${JSON.stringify(r)}
|
|
299
|
+
`,{encoding:"utf8",mode:384})}catch{}}var rF=p(()=>{"use strict"});function oF(e,t=45e3){let r=setInterval(()=>{try{e()}catch{}},t);return r.unref?.(),()=>clearInterval(r)}var nF,sF=p(()=>{"use strict";nF="heartbeat"});function coe(){let e=new Map;return{register(t,r){return e.set(t,r),()=>{e.get(t)?.turnId===r.turnId&&e.delete(t)}},setSteer(t,r,n){let o=e.get(t);o&&o.turnId===r&&e.set(t,{...o,steer:n})},get(t){return e.get(t)??null}}}var iF,aF=p(()=>{"use strict";iF=coe()});async function lF(e,t,r){let n=e.get(t);return n?r.op==="stop"?n.stop():!n.steer||!r.text?n.withImages?"unsupported_media":"unsupported":n.steer(r.text):"no_run"}function cF(e,t,r,n){return{seq:e,kind:"final",message:{content:[{type:"text",text:""}],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:t,media:0,control:{op:r.op,outcome:n}}}}}var uF=p(()=>{"use strict"});function hF(e){return!gF.has(e.baseUrl)}function ql(e,t=!0){let r={};return t&&(r["Content-Type"]="application/json"),e.key&&(r.Authorization=`Bearer ${e.key}`),r}async function yF(e,t={}){if((t.env??process.env).KYNVER_HERMES_RUNS==="0")return!1;let r=(t.now??Date.now)(),n=dF.get(e.baseUrl);if(n&&r-n.at<uoe)return n.ok;let o=!1;try{let s=await(t.fetchFn??fetch)(`${e.baseUrl}/v1/capabilities`,{headers:ql(e,!1),signal:AbortSignal.timeout(3e3)});if(s.ok){let a=(await s.json().catch(()=>null))?.features??{};o=!!(a.run_submission&&a.run_events_sse&&a.run_steer&&a.run_stop)}else await s.body?.cancel().catch(()=>{})}catch{o=!1}return dF.set(e.baseUrl,{at:r,ok:o}),o}function poe(e){return typeof e=="string"&&doe.includes(e)}async function pF(e,t,r,n){try{let o=await(e.fetchFn??fetch)(`${e.endpoint.baseUrl}/v1/runs/${encodeURIComponent(t)}/${r}`,{method:"POST",headers:ql(e.endpoint),body:JSON.stringify(n),signal:AbortSignal.timeout(mF)});return await o.body?.cancel().catch(()=>{}),o.ok?"delivered":o.status===404||o.status===409?"no_run":"failed"}catch{return"failed"}}function foe(e){return e===401||e===403?new Error("hermes_auth_failed: the local API refused the key in its config"):e===429?new Error("hermes_busy: the agent is busy, try again shortly"):new Ci(`hermes_runs_http_${e}`)}function fF(e){let t=typeof e.tool=="string"?e.tool:"tool",r=typeof e.preview=="string"&&e.preview.trim()?`: ${e.preview.trim()}`:"";return`${t}${r}`.slice(0,300)}async function kF(e,t){let r=e.fetchFn??fetch,n=e.now??Date.now,o=e.sessions.get(e.sessionKey),s=tR("hermes",e.sessionKey,e.styleNote,o!==null),i=e.attachments.some(S=>S.imageDataUrl),a;try{a=await r(`${e.endpoint.baseUrl}/v1/runs`,{method:"POST",headers:ql(e.endpoint),body:JSON.stringify({model:"hermes-agent",input:i?[{role:"user",content:Wf(e.text,e.attachments)}]:e.text,...o?{session_id:o}:{},...s?{instructions:s}:{}}),signal:e.signal})}catch(S){throw e.signal?.aborted?new Error("hermes_aborted"):new Error(`hermes_unreachable: nothing answered on ${e.endpoint.baseUrl}`,{cause:S})}if(!a.ok)throw await a.body?.cancel().catch(()=>{}),i&&moe.has(a.status)&&gF.add(e.endpoint.baseUrl),foe(a.status);let l=await a.json().catch(()=>null),c=typeof l?.run_id=="string"?l.run_id:null;if(!c)throw new Ci("hermes_runs_no_run_id");let u=null,d={runId:c,steer:S=>pF(e,c,"steer",{text:S}),stop:()=>u??=pF(e,c,"stop",{})};t?.(d);let f=()=>{poe(e.signal?.reason)&&d.stop()};e.signal?.addEventListener("abort",f,{once:!0});let m="",g=null,h=null,k=null,v=new Map;try{let S=await r(`${e.endpoint.baseUrl}/v1/runs/${encodeURIComponent(c)}/events`,{headers:{...ql(e.endpoint,!1),Accept:"text/event-stream"},signal:e.signal}).catch(w=>{throw e.signal?.aborted?new Error("hermes_aborted"):new Error(`hermes_unreachable: the run's events stream closed (${w instanceof Error?w.message:String(w)})`)});if(!S.ok||!S.body)throw await S.body?.cancel().catch(()=>{}),new Error(`hermes_http_${S.status}`);for await(let w of Ff(S.body)){let _=w.data&&typeof w.data=="object"?w.data:{},R=typeof _.event=="string"?_.event:w.event;if(R==="message.delta"&&typeof _.delta=="string")m+=_.delta,e.sink.onDelta(_.delta);else if(R==="message.interim"&&typeof _.text=="string"&&!_.already_streamed){let T=`${m&&!m.endsWith(`
|
|
300
300
|
`)?`
|
|
301
301
|
|
|
302
|
-
`:""}${
|
|
302
|
+
`:""}${_.text}`;m+=T,e.sink.onDelta(T)}else if(R==="tool.started"){let T=typeof _.tool_call_id=="string"?_.tool_call_id:String(_.tool??""),W=fF(_);v.set(T,{at:n(),label:W}),e.sink.onTool({label:W,status:"running",durationMs:null})}else if(R==="tool.completed"){let T=typeof _.tool_call_id=="string"?_.tool_call_id:String(_.tool??""),W=v.get(T);v.delete(T),e.sink.onTool({label:W?.label??fF(_),status:"completed",durationMs:W?n()-W.at:typeof _.duration=="number"?Math.round(_.duration*1e3):null})}else if(R==="approval.request"){let T=[_.description,_.command].find(W=>typeof W=="string"&&W);e.sink.onTool({label:`Waiting for approval in Hermes${T?`: ${T.slice(0,200)}`:""}`,status:"approval",durationMs:null})}else if(R==="run.completed"){h="completed",typeof _.output=="string"&&(g=_.output);break}else if(R==="run.failed"||R==="run.interrupted"){h="failed",k=typeof _.error=="string"?_.error:"the agent stopped with an error \u2014 check its logs";break}else if(R==="run.cancelled"){h="cancelled";break}}}catch(S){throw e.signal?.aborted?new Error("hermes_aborted"):S}finally{e.signal?.removeEventListener("abort",f)}if(e.signal?.aborted||h==="cancelled")throw new Error("hermes_aborted");let y=await goe(e,c);!h&&y&&(y.status==="completed"?g=y.output??g:y.status==="failed"&&(k=y.error??"the agent stopped with an error \u2014 check its logs"));let b=y?.sessionId??o??c;if(e.sessions.remember(e.sessionKey,b),k&&!m.trim())throw new Error(`hermes_failed: ${k}`);if(!m.trim()&&g&&g.trim()&&(m=g,e.sink.onDelta(g)),!m.trim())throw new Error("hermes_empty_reply: the agent sent back nothing \u2014 check its model sign-in and logs");return{text:m,sessionId:b}}async function goe(e,t){try{let r=await(e.fetchFn??fetch)(`${e.endpoint.baseUrl}/v1/runs/${encodeURIComponent(t)}`,{headers:ql(e.endpoint,!1),signal:AbortSignal.timeout(mF)});if(!r.ok)return await r.body?.cancel().catch(()=>{}),null;let n=await r.json().catch(()=>null);return n?{status:typeof n.status=="string"?n.status:"",output:typeof n.output=="string"?n.output:null,error:typeof n.error=="string"?n.error:null,sessionId:typeof n.session_id=="string"&&n.session_id?n.session_id:null}:null}catch{return null}}var Ci,uoe,mF,dF,gF,doe,moe,bF=p(()=>{"use strict";Qv();nR();Ci=class extends Error{constructor(t){super(t),this.name="HermesRunsUnavailable"}},uoe=5*6e4,mF=1e4,dF=new Map,gF=new Set;doe=["website_stop","too_long"];moe=new Set([400,415,422])});async function wF(e,t,r={}){let n=r.now??(()=>new Date),o=r.log??tF,s=lL(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=r.runs??iF;if(s.control){let I=await lF(l,s.sessionKey,s.control);o({at:n().toISOString(),turnId:t.turnId,engine:i,kind:"turn",ok:I==="delivered",durationMs:n().getTime()-a,reason:`control_${s.control.op}_${I}`}),await Ht(()=>e([cF(0,i,s.control,I)]).catch(()=>!1));return}let c=0,u=!1,d=new AbortController,f=new Pn,m=s.replyTurnId&&r.late?s.replyTurnId:null,g=!1,h=null,k=I=>{d.signal.aborted||(h=I,d.abort(I))},v=()=>{!m||!r.late||r.late.heartbeat(m).then(I=>{I==="stop"?k("website_stop"):I==="gone"&&k("website_gone")})},y=()=>{if(!u){if(u=!0,m&&!d.signal.aborted){g=!0,o({at:n().toISOString(),turnId:t.turnId,engine:i,kind:"detached",ok:!0,durationMs:n().getTime()-a}),v(),setTimeout(v,Math.min(5e3,r.heartbeatMs??45e3)).unref?.();return}d.abort("relay_closed")}},b=I=>{u||f.track(e([{seq:c++,...I}]).then(x=>(x||y(),x),()=>!1))},S=oF(()=>{g?v():u||b({kind:"activity",activity:{kind:nF,at:n().toISOString(),turnId:t.turnId}})},r.heartbeatMs??45e3),w=m?setTimeout(()=>k("too_long"),r.maxTurnMs??72e5):null;w?.unref?.();let _=async(I,x)=>{if(!m||!r.late)return;let V=await r.late.deliver({replyTurnId:m,engine:i,text:I,files:x});o({at:n().toISOString(),turnId:t.turnId,engine:i,kind:"late_reply",ok:V,durationMs:n().getTime()-a})},R=new In(I=>b({kind:"delta",text:I}),r.flushFloorMs,r.redactor),T=I=>{R.flush(),b({kind:"activity",activity:I})},W=I=>{let x={at:n().toISOString(),chat:null,turnId:t.turnId,kind:"tool",engine:i,access:"own",command:I.label,folder:"",durationMs:I.durationMs,ok:I.status!=="approval",...I.status==="running"?{reason:"started"}:{},...I.status==="approval"?{reason:"awaiting_approval"}:{}};T(x),I.status!=="running"&&o({at:x.at,turnId:t.turnId,engine:i,kind:"tool",label:I.label,ok:x.ok,durationMs:I.durationMs})},O=uf({turnId:t.turnId,chat:null,send:I=>T(I),now:n}),L="",M=!1,B=null,G=null,re=l.register(s.sessionKey,{engine:i,turnId:t.turnId,withImages:s.attachments.some(I=>/^image\/(png|jpe?g|gif|webp|bmp|heic|heif)$/i.test(I.mime)),stop:async()=>(G&&await G.stop(),k("website_stop"),"delivered")});try{if(i==="grok-bot"){let H=await(r.grokBot??IU()).relay({sessionKey:s.sessionKey,text:s.text}),ie=n().getTime()-a;if(H.mailbox){Hl(i,{ok:!0,durationMs:ie},n),o({at:n().toISOString(),turnId:t.turnId,engine:i,kind:"turn",ok:!0,durationMs:ie});let ge=c++;await Ht(()=>u?e([{seq:ge,kind:"error",error:"turn_stream_aborted"}]).catch(()=>!1):e([{seq:ge,kind:"final",message:{content:[],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:i,media:0,mailbox:!0}}}]).catch(()=>!1));return}L=H.text,R.push(H.text),R.close(),await f.drain();let Y=H.text.trim();if(!Y)throw new Error("grok_bot_empty_reply");Hl(i,{ok:!0,durationMs:ie},n),o({at:n().toISOString(),turnId:t.turnId,engine:i,kind:"turn",ok:!0,durationMs:ie});let Te=c++;await Ht(()=>u?e([{seq:Te,kind:"error",error:"turn_stream_aborted"}]).catch(()=>!1):e([{seq:Te,kind:"final",message:{content:[{type:"text",text:Y}],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:i,media:0}}}]).catch(()=>!1));return}let I=r.sessions??NU(),x=JU(s.sessionKey,s.attachments,{root:r.inboxRoot}),V;if(i==="claude-code")V=(await(r.runClaudeCode??YU)({sessionKey:s.sessionKey,text:s.text,styleNote:s.styleNote,conversationId:s.conversationId,attachments:x,payloadAccess:s.computerAccess,boxId:t.boxId,sessions:I,onDelta:ie=>{L+=ie,R.push(ie)},onActivity:O.sink,signal:d.signal,turnId:t.turnId,home:r.home,...m?{maxStepMs:r.maxTurnMs??72e5}:{}})).text||L;else{let H=(r.endpoint??(ge=>ge==="hermes"?Mf():Lf()))(i),ie={engine:i,endpoint:H,sessionKey:s.sessionKey,text:$f(s.text,x.filter(ge=>!ge.imageDataUrl)),styleNote:s.styleNote,conversationId:s.conversationId,attachments:x,sessions:I,signal:d.signal,fetchFn:r.fetchFn,sink:{onDelta:ge=>{L+=ge,R.push(ge)},onTool:W}},Y=i==="hermes"&&(x.every(ge=>!ge.imageDataUrl)||hF(H))&&await(r.hermesRuns??(ge=>yF(ge,{fetchFn:r.fetchFn})))(H),Te;if(Y)try{Te=await kF(ie,ge=>{G=ge,l.setSteer(s.sessionKey,t.turnId,ge.steer)})}catch(ge){if(!(ge instanceof Ci))throw ge;Te=await rR(ie)}else Te=await rR(ie);V=Te.text,M=Te.recovered===!0,B=i==="hermes"?G!==null:null}let N=QU(V,{home:r.home,inboxRoot:r.inboxRoot});N.files.forEach((H,ie)=>{let Y=n().toISOString();T({at:Y,chat:null,turnId:t.turnId,kind:"attach",engine:i,access:"own",path:H.path,folder:"",ok:H.ok,...H.reason?{reason:H.reason}:{},...!H.ok&&H.sizeBytes!==null?{sizeBytes:H.sizeBytes}:{},toolUseId:`media-${ie}`,...H.ok&&H.contentBase64?{file:{name:H.name,sizeBytes:H.sizeBytes,contentBase64:H.contentBase64}}:{}}),o({at:Y,turnId:t.turnId,engine:i,kind:"attach",path:H.path,ok:H.ok,reason:H.reason})}),re(),R.close(),await f.drain();let C=n().getTime()-a;Hl(i,{ok:!0,durationMs:C},n),o({at:n().toISOString(),turnId:t.turnId,engine:i,kind:"turn",ok:!0,durationMs:C,...M?{reason:"reply_read_from_session"}:{}});let D=()=>N.files.filter(H=>H.ok&&H.contentBase64).map(H=>({name:H.name,contentBase64:H.contentBase64,sizeBytes:H.sizeBytes}));if(g){await _(N.text,D());return}let z=c++;!await Ht(()=>u?e([{seq:z,kind:"error",error:"turn_stream_aborted"}]).catch(()=>!1):e([{seq:z,kind:"final",message:{content:[{type:"text",text:N.text}],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:i,media:N.files.filter(H=>H.ok).length,...B===null?{}:{viaRun:B}}}}]).catch(()=>!1))&&m&&!u&&await _(N.text,D())}catch(I){re(),R.close(),await f.drain();let x=I instanceof Error?I.message:String(I),V=yU(I),N=n().getTime()-a;if(Hl(i,{ok:!1,durationMs:N,error:V},n),o({at:n().toISOString(),turnId:t.turnId,engine:i,kind:"turn",ok:!1,durationMs:N,reason:h??V}),g){if(h)return;let D=uR(L).trim();await _(D?`${D}
|
|
303
303
|
|
|
304
|
-
_${
|
|
304
|
+
_${dR[i]} stopped before finishing (${V})._`:`${dR[i]} couldn't finish this message (${V}).`,[]);return}if(u)return;let C=c++;if(L.trim()){let D=`
|
|
305
305
|
|
|
306
|
-
_${
|
|
306
|
+
_${dR[i]} stopped before finishing (${V})._`;await Ht(()=>e([{seq:C,kind:"final",message:{content:[{type:"text",text:uR(L)+D}],stop_reason:"end_turn",usage:{input_tokens:0,output_tokens:0},agentTab:{engine:i,media:0,error:V}}}]).catch(()=>!1))}else await Ht(()=>e([{seq:C,kind:"error",error:x.slice(0,1500)}]).catch(()=>!1))}finally{re(),S(),w&&clearTimeout(w)}}var dR,SF=p(()=>{"use strict";lf();cf();dv();ov();zb();PU();DU();qv();nR();zU();Hf();ZU();Jv();rF();sF();aF();uF();bF();dR=rf});function pR(e){let t=(e??"").replace(/\s+/g," ").trim();if(!t||t.length>120)return null;for(let r of hoe)if(r.re.test(t))return r.kind;return null}function xF(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 Vf(e){return xF(e)?pR(e.name):null}function CF(e){return e.tag.toLowerCase()==="textarea"?null:xF(e)?pR(e.name):pR(e.formSubmitLabel)}function Gf(e){if((e.type??"").toLowerCase()==="password"||yoe.test(e.autocomplete??""))return!0;let t=e.tag.toLowerCase();return t!=="input"&&t!=="textarea"?!1:_F.test(e.inputName??"")||_F.test(e.name??"")}function fR(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"}:koe.test(r.hostname)?{ok:!1,reason:"local and private-network addresses are refused"}:{ok:!0,url:r.toString()}}function EF(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 AF(e){if(!e)return"";try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return""}}var hoe,yoe,_F,koe,mR=p(()=>{"use strict";hoe=[{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}];yoe=/\b(current-password|new-password|one-time-code|cc-number|cc-csc|cc-exp|cc-exp-month|cc-exp-year)\b/i,_F=/(passw|passcode|pwd|\bpin\b|otp|one[-_ ]?time|2fa|mfa|verification[-_ ]?code|security[-_ ]?code|cvv|cvc|card[-_ ]?number|ccnum|ssn|social[-_ ]?security)/i;koe=/^(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 IF(e){return voe.includes(e)}function PF(e){return typeof e=="string"&&boe.includes(e)}var boe,voe,OF,TF,gR,NF,hR,DF,MF,Jf,LF,BF,UF,yR,Ei=p(()=>{"use strict";boe=["open","snapshot","click","type","select","press","scroll","screenshot","wait","tabs","close","list_logins","fill_login","save_login","request_code"],voe=["list_logins","fill_login","save_login","request_code"];OF=12e3,TF=200,gR=16e3,NF=95e4,hR=4e3,DF=3e4,MF=25e3,Jf=3e4,LF=10*6e4,BF=5*6e4,UF=120,yR=8});function Roe(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 woe(e){let t=Gf(e),r=[`[${e.ref}] ${Roe(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)"):Vf(e)&&r.push("(needs the user's approval to press)"),r.join(" ")}function FF(e,t={}){let r=t.maxChars??gR,n=`Page: ${e.title||"(untitled)"} \u2014 ${e.url}`,o=e.elements.map(woe),s=o.length?`Interactive elements (use the [ref] with browser_click / browser_type / browser_select):
|
|
307
307
|
${o.join(`
|
|
308
308
|
`)}${e.truncatedElements?`
|
|
309
309
|
\u2026more elements not shown \u2014 scroll or wait, then snapshot again`:""}`:"Interactive elements: none visible.",i=`${n}
|
|
@@ -312,30 +312,30 @@ ${s}
|
|
|
312
312
|
|
|
313
313
|
Page text:
|
|
314
314
|
`,a=Math.max(0,r-i.length),l=e.text.length>a?`${e.text.slice(0,Math.max(0,a-14))}
|
|
315
|
-
\u2026[truncated]`:e.text;return`${i}${l}`.slice(0,r)}function
|
|
316
|
-
\u2026[truncated]`:e}var
|
|
315
|
+
\u2026[truncated]`:e.text;return`${i}${l}`.slice(0,r)}function qf(e,t=gR){return e.length>t?`${e.slice(0,t-14)}
|
|
316
|
+
\u2026[truncated]`:e}var kR=p(()=>{"use strict";mR();Ei()});function WF(){return`(() => {${bR}
|
|
317
317
|
const root = document.documentElement;
|
|
318
318
|
let seq = Number(root.getAttribute("data-kynver-ref-seq") || "0");
|
|
319
319
|
const elements = [];
|
|
320
320
|
let truncatedElements = false;
|
|
321
|
-
for (const el of document.querySelectorAll(${JSON.stringify(
|
|
321
|
+
for (const el of document.querySelectorAll(${JSON.stringify(Soe)})) {
|
|
322
322
|
if (!__kvVisible(el)) continue;
|
|
323
|
-
if (elements.length >= ${
|
|
323
|
+
if (elements.length >= ${TF}) { truncatedElements = true; break; }
|
|
324
324
|
let ref = el.getAttribute("data-kynver-ref");
|
|
325
325
|
if (!ref) { seq += 1; ref = "e" + seq; el.setAttribute("data-kynver-ref", ref); }
|
|
326
326
|
elements.push(__kvFacts(el, ref));
|
|
327
327
|
}
|
|
328
328
|
root.setAttribute("data-kynver-ref-seq", String(seq));
|
|
329
329
|
const body = document.body;
|
|
330
|
-
const text = body ? String(body.innerText || "").replace(/\\n{3,}/g, "\\n\\n").slice(0, ${
|
|
330
|
+
const text = body ? String(body.innerText || "").replace(/\\n{3,}/g, "\\n\\n").slice(0, ${OF}) : "";
|
|
331
331
|
return { url: location.href, title: document.title, text, elements, truncatedElements };
|
|
332
|
-
})()`}function
|
|
332
|
+
})()`}function KF(e){return`(() => {${bR}
|
|
333
333
|
const el = document.querySelector('[data-kynver-ref="' + ${JSON.stringify(e)}.replace(/[^a-z0-9]/gi, "") + '"]');
|
|
334
334
|
if (!el) return null;
|
|
335
335
|
el.scrollIntoView({ block: "center", inline: "center" });
|
|
336
336
|
const r = el.getBoundingClientRect();
|
|
337
337
|
return { x: r.left + r.width / 2, y: r.top + r.height / 2, facts: __kvFacts(el, ${JSON.stringify(e)}), url: location.href };
|
|
338
|
-
})()`}function
|
|
338
|
+
})()`}function $F(e,t){return`(() => {
|
|
339
339
|
const el = document.querySelector('[data-kynver-ref="' + ${JSON.stringify(e)}.replace(/[^a-z0-9]/gi, "") + '"]');
|
|
340
340
|
if (!el) return false;
|
|
341
341
|
el.focus();
|
|
@@ -350,7 +350,7 @@ Page text:
|
|
|
350
350
|
}
|
|
351
351
|
}
|
|
352
352
|
return true;
|
|
353
|
-
})()`}function
|
|
353
|
+
})()`}function HF(e,t){return`(() => {
|
|
354
354
|
const el = document.querySelector('[data-kynver-ref="' + ${JSON.stringify(e)}.replace(/[^a-z0-9]/gi, "") + '"]');
|
|
355
355
|
if (!el || el.tagName !== "SELECT") return { ok: false, reason: "not_select" };
|
|
356
356
|
const want = ${JSON.stringify(t)}.trim().toLowerCase();
|
|
@@ -362,17 +362,17 @@ Page text:
|
|
|
362
362
|
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
363
363
|
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
364
364
|
return { ok: true, label: (hit.label || hit.textContent || "").trim() };
|
|
365
|
-
})()`}function
|
|
365
|
+
})()`}function jF(){return`(() => {${bR}
|
|
366
366
|
const el = document.activeElement;
|
|
367
367
|
if (!el || el === document.body) return { facts: null, url: location.href };
|
|
368
368
|
return { facts: __kvFacts(el, el.getAttribute("data-kynver-ref") || ""), url: location.href };
|
|
369
|
-
})()`}function
|
|
369
|
+
})()`}function VF(e){return`(() => { window.scrollBy(0, ${Math.trunc(e)}); return { y: Math.round(window.scrollY), max: Math.round(document.documentElement.scrollHeight - window.innerHeight) }; })()`}function GF(e,t){return`(() => {
|
|
370
370
|
const t = ${JSON.stringify(e)};
|
|
371
371
|
const s = ${JSON.stringify(t)};
|
|
372
372
|
if (t && document.body && String(document.body.innerText || "").toLowerCase().includes(t.toLowerCase())) return true;
|
|
373
373
|
if (s) { try { if (document.querySelector(s)) return true; } catch (e) { return "bad_selector"; } }
|
|
374
374
|
return false;
|
|
375
|
-
})()`}var
|
|
375
|
+
})()`}var bR,Soe,JF=p(()=>{"use strict";Ei();bR=String.raw`
|
|
376
376
|
const __kvText = (s, n) => String(s == null ? "" : s).replace(/\s+/g, " ").trim().slice(0, n);
|
|
377
377
|
const __kvName = (el) => {
|
|
378
378
|
const aria = el.getAttribute("aria-label");
|
|
@@ -435,11 +435,11 @@ const __kvVisible = (el) => {
|
|
|
435
435
|
const s = getComputedStyle(el);
|
|
436
436
|
return s.visibility !== "hidden" && s.display !== "none" && s.opacity !== "0";
|
|
437
437
|
};
|
|
438
|
-
`,
|
|
438
|
+
`,Soe='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 Uo(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 _oe(e,t){return Uo(e.session.host.conn,t,WF())}async function fr(e,t,r){let n=await _oe(e,t),o=FF(n);return{ok:!0,text:r?qf(`${r}
|
|
439
439
|
|
|
440
|
-
${o}`):o,url:n.url,title:n.title}}function
|
|
440
|
+
${o}`):o,url:n.url,title:n.title}}function Yf(e){let t=typeof e.ref=="string"?e.ref.trim():"";return/^e\d{1,6}$/.test(t)?t:null}function XF(e,t,r,n,o){let s=EF([AF(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 Yl(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??YF)(r)])}async function QF(e){let t=fR(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,MF).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 fr(e,n,a?void 0:"The page is still loading; this is what has rendered so far.")}async function vR(e,t,r){return Uo(e.session.host.conn,t,KF(r))}async function xoe(e){let t=Yf(e.args);if(!t)return Bo(t);let r=await e.manager.activeTab(e.session),n=await vR(e,r,t);if(!n)return Bo(t);if(n.facts.disabled)return{ok:!1,code:"failed",text:`[${t}] is disabled.`};let o=Vf(n.facts);if(o){let a=XF(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 Yl(e,r,1200),fr(e,r,`Clicked [${t}] ${JSON.stringify(n.facts.name)}.`)}async function zf(e,t,r){let n=zF[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 Xf(e,t){let r=await Uo(e.session.host.conn,t,jF());if(!r.facts)return null;let n=CF(r.facts);if(!n)return null;let o=r.facts.formSubmitLabel??r.facts.name;return XF(e,"press",o,n,r.url)}async function Coe(e){let t=Yf(e.args);if(!t)return Bo(t);let r=typeof e.args.text=="string"?e.args.text:"";if(!r)return{ok:!1,code:"invalid_request",text:"text is required."};if(r.length>hR)return{ok:!1,code:"invalid_request",text:`text is limited to ${hR} characters.`};let n=await e.manager.activeTab(e.session),o=await vR(e,n,t);if(!o)return Bo(t);if(Gf(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 Uo(s,n,$F(t,e.args.clear!==!1)))return Bo(t);await s.send("Input.insertText",{text:r},{sessionId:n.sessionId});let a=`Typed ${r.length} character${r.length===1?"":"s"} into [${t}] ${JSON.stringify(o.facts.name)}.`;if(e.args.submit===!0){let l=await Xf(e,n);return l?{...l,text:`${a} ${l.text}`}:(await zf(e,n,"Enter"),await Yl(e,n,1500),fr(e,n,`${a} Pressed Enter.`))}return{ok:!0,text:a}}async function Eoe(e){let t=Yf(e.args);if(!t)return Bo(t);let r=typeof e.args.option=="string"?e.args.option.trim():"";if(!r)return{ok:!1,code:"invalid_request",text:"option (visible label or value) is required."};let n=await e.manager.activeTab(e.session),o=await Uo(e.session.host.conn,n,HF(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 Aoe(e){let t=typeof e.args.key=="string"?e.args.key.trim():"",r=qF.find(o=>o.toLowerCase()===t.toLowerCase());if(!r)return{ok:!1,code:"invalid_request",text:`key must be one of: ${qF.join(", ")}.`};let n=await e.manager.activeTab(e.session);if(r==="Enter"){let o=await Xf(e,n);if(o)return o}return await zf(e,n,r),await Yl(e,n,r==="Enter"?1500:300),fr(e,n,`Pressed ${r}.`)}async function Ioe(e){let t=await e.manager.activeTab(e.session),r=Yf(e.args);if(r)return await vR(e,t,r)?{ok:!0,text:`Scrolled [${r}] into view.`}:Bo(r);let n=e.args.direction==="up"?-1:1,o=Math.min(10,Math.max(1,Number(e.args.pages)||1)),s=await Uo(e.session.host.conn,t,VF(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 Poe(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<=NF)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 Ooe(e){let t=await e.manager.activeTab(e.session),r=e.sleep??YF,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(Jf,Math.max(0,Number(e.args.ms)||0));if(!n&&!o){let l=s||2e3;return await r(l),fr(e,t,`Waited ${Math.round(l/100)/10}s.`)}let i=s||1e4,a=Date.now();for(;;){let l=await Uo(e.session.host.conn,t,GF(n,o));if(l==="bad_selector")return{ok:!1,code:"invalid_request",text:"That CSS selector is not valid."};if(l===!0)return fr(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 Toe(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=fR(e.args.url);return d.ok?QF({...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(()=>{}),fr(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:
|
|
441
441
|
${u.join(`
|
|
442
|
-
`)}`:"No tabs open."}}async function
|
|
442
|
+
`)}`:"No tabs open."}}async function ZF(e,t){switch(e){case"open":return QF(t);case"snapshot":return fr(t,await t.manager.activeTab(t.session));case"click":return xoe(t);case"type":return Coe(t);case"select":return Eoe(t);case"press":return Aoe(t);case"scroll":return Ioe(t);case"screenshot":return Poe(t);case"wait":return Ooe(t);case"tabs":return Toe(t);case"close":return await t.manager.close(t.session.conversationId),{ok:!0,text:"Closed the browser for this conversation."}}}var YF,zF,qF,Bo,RR=p(()=>{"use strict";mR();kR();JF();Ei();YF=e=>new Promise(t=>setTimeout(t,e)),zF={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:" "}},qF=Object.keys(zF);Bo=e=>({ok:!1,code:e?"not_found":"invalid_request",text:e?`Element [${e}] is no longer on the page. Call browser_snapshot to get fresh refs.`:'A ref like "e12" from the latest browser_snapshot is required.'})});var wR,SR,_R,eW,tW=p(()=>{"use strict";wR=String.raw`
|
|
443
443
|
const __vis = (el) => {
|
|
444
444
|
const r = el.getBoundingClientRect();
|
|
445
445
|
if (r.width <= 0 || r.height <= 0) return false;
|
|
@@ -490,7 +490,7 @@ ${u.join(`
|
|
|
490
490
|
return null;
|
|
491
491
|
};
|
|
492
492
|
const __hasFrames = () => document.querySelectorAll("iframe,frame").length > 0;
|
|
493
|
-
`,
|
|
493
|
+
`,SR=`function (expectedOrigin, refs) {${wR}
|
|
494
494
|
const g = __guard(expectedOrigin);
|
|
495
495
|
if (g) return { error: g, origin: location.origin };
|
|
496
496
|
const f = __find(refs);
|
|
@@ -502,7 +502,7 @@ ${u.join(`
|
|
|
502
502
|
code: !!f.code,
|
|
503
503
|
hasFrames: __hasFrames(),
|
|
504
504
|
};
|
|
505
|
-
}`,
|
|
505
|
+
}`,_R=`function (expectedOrigin, refs, values) {${wR}
|
|
506
506
|
const g = __guard(expectedOrigin);
|
|
507
507
|
if (g) return { error: g, origin: location.origin };
|
|
508
508
|
const f = __find(refs);
|
|
@@ -528,7 +528,7 @@ ${u.join(`
|
|
|
528
528
|
const last = filled.length ? (filled[filled.length - 1] === "code" ? f.code : filled[filled.length - 1] === "password" ? f.password : f.username) : null;
|
|
529
529
|
if (last) last.focus();
|
|
530
530
|
return { origin: location.origin, filled };
|
|
531
|
-
}`,
|
|
531
|
+
}`,eW=`function (expectedOrigin, refs) {${wR}
|
|
532
532
|
const g = __guard(expectedOrigin);
|
|
533
533
|
if (g) return { error: g, origin: location.origin };
|
|
534
534
|
const f = __find(refs);
|
|
@@ -538,14 +538,14 @@ ${u.join(`
|
|
|
538
538
|
username: f.username ? String(f.username.value || "") : null,
|
|
539
539
|
password: f.password ? String(f.password.value || "") : null,
|
|
540
540
|
};
|
|
541
|
-
}`});function
|
|
541
|
+
}`});function Noe(e){let t=typeof e.handle=="string"?e.handle.trim():"";return/^lg_[a-z0-9]{6,20}$/.test(t)?t:null}function CR(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 nW(e){return`${JSON.stringify(e.label)} (${e.username}) for ${e.origin}`}function Zf(e){return e.siteLogins??Ze()}async function Qf(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 zl(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 ce(e,t,r={}){return{ok:!1,code:e,text:t,...r}}function ER(e,t,r=Ze()){let n=t?.trim();if(!n)return ce("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:rW};let s;try{s=o.list()}catch(c){return ce("failed",c instanceof q?`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. ${xR}`;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}):
|
|
542
542
|
${l.join(`
|
|
543
543
|
`)}
|
|
544
|
-
Use browser_fill_login with a handle while that exact site is open.`}}async function Coe(e,t){let r=qf(e),n=r.audit(t),o=xoe(e.args);if(!o)return ue("invalid_request",'A saved-login handle like "lg_7k2m9q4x1c" from browser_list_logins is required.');let s=r.store(t);if(!s.exists())return ue("vault_missing",YF);let i=s.get(o);if(!i)return ue("login_not_found","No saved login with that handle. Call browser_list_logins.");let a=await e.manager.activeTab(e.session),l=await Jf(e,a),c=fa(l),u={conversationId:e.session.conversationId,handle:o,label:i.label,username:i.username,origin:i.origin,pageOrigin:c},d=(R,O)=>({event:"fill",ok:R,origin:i.origin,label:i.label,code:O});if(!l||!Bg(i.origin,l))return n.record({event:"fill",ok:!1,code:"origin_mismatch",...u}),ue("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}),ue("vault_locked",`Saved logins are locked. ${vR}`,{loginActivity:d(!1,"vault_locked")});let m=RR(e.args),g;try{g=await Yl(e,a,kR,[i.origin,m])}catch(R){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),ue("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}),ue("origin_mismatch",`Refused: the page is no longer ${i.origin}.`,{loginActivity:d(!1,"origin_mismatch")});if(g?.error==="bad_ref")return ue("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(R){let O=R instanceof z?R.code:"failed";return n.record({event:"fill",ok:!1,code:O,...u}),ue("failed",R instanceof z?`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=Su(h.totp);R&&(ax(R)<3&&await(e.sleep??(O=>new Promise(j=>setTimeout(j,O))))(3100),y.code=ix(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.":"",O=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 ue("field_not_found",`No sign-in field to fill on this page.${O}${R} Take a browser_snapshot to see where you are.`,{loginActivity:d(!1,"field_not_found")})}let b;try{b=await Yl(e,a,bR,[i.origin,m,y])}catch(R){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),ue("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}),ue(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"),w=`Filled the ${v} for ${zF(i)}.`+(S?" The page also wants a one-time code: use browser_request_code so the user types it on their computer.":""),_={loginActivity:d(!0,null)};if(e.args.submit===!0){let R=await Gf(e,a);return R?{...R,..._,text:`${w} ${R.text}`}:(await Vf(e,a,"Enter"),await ql(e,a,2e3),{...await pr(e,a,`${w} Pressed Enter.`),..._})}return{ok:!0,text:`${w} Continue with browser_click on the sign-in button (or submit:true next time).`,..._}}async function Eoe(e,t){let r=qf(e),n=r.store(t);if(!n.exists())return ue("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 ue("vault_locked",`Saved logins are locked. ${vR}`);let s=await e.manager.activeTab(e.session),i=await Jf(e,s),a=fa(i);if(!a||!a.startsWith("https://"))return ue("url_refused","Only logins typed on an https:// site can be saved.");let l;try{l=await Yl(e,s,JF,[a,RR(e.args)])}catch(m){return ue("failed",`Couldn't read the sign-in form: ${m.message}.`)}if(l?.error)return ue("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 ue("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 ue("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 ${zF(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 ue("failed",m instanceof z?`Couldn't save: ${m.message}.`:"Couldn't save this login.")}}async function Aoe(e,t){let r=qf(e),n=await e.manager.activeTab(e.session),o=await Jf(e,n),s=fa(o);if(!s)return ue("url_refused","Open the site's verification page first.");let i=RR(e.args),a;try{a=await Yl(e,n,kR,[s,i])}catch(d){return ue("failed",`Couldn't read the page: ${d.message}.`)}if(a?.error==="bad_ref")return ue("invalid_request","codeRef must point at a text field on this page.");if(a?.error||!a?.code)return ue("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 Jf(e,n);if(!Bg(s,f))return{ok:!1,text:`The page is no longer ${s}, so the code was not typed.`};try{let m=await Yl(e,n,bR,[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 XF(e,t){let r=t.agentOsId?.trim();if(!r)return ue("invalid_request","Saved logins need the workspace this chat belongs to; update the Kynver runtime.");switch(e){case"list_logins":return wR(t.args,r,qf(t));case"fill_login":return Coe(t,r);case"save_login":return Eoe(t,r);case"request_code":return Aoe(t,r)}}var vR,YF,QF=p(()=>{"use strict";hR();qF();Ug();bs();ln();Fg();vR="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.",YF="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 Yf,ZF=p(()=>{"use strict";Ci();Yf=class{constructor(t){this.deps=t;this.now=t.now??Date.now,this.idleMs=t.idleMs??IF}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<PF),t.actionTimes.length>=OF?!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>=pR)throw new Error(`tab limit reached (${pR}) \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 fr,Ioe,zl,eW=p(()=>{"use strict";fr=class extends Error{constructor(r,n){super(r);this.code=n;this.name="CdpError"}code},Ioe=e=>new WebSocket(e),zl=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??Ioe)(t);return await new Promise((o,s)=>{let i=setTimeout(()=>s(new fr("CDP connect timed out")),r.timeoutMs??1e4);n.addEventListener("open",()=>{clearTimeout(i),o()}),n.addEventListener("error",()=>{clearTimeout(i),s(new fr("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 fr("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 fr(`${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 fr(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 fr("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 fr("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 fr(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)}}}});import{existsSync as Poe,readFileSync as tW}from"node:fs";function Ei(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 rW(e,t){try{return e(t)}catch{return""}}function Xl(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=>tW(o,"utf8"));return/microsoft|wsl/i.test(rW(n,"/proc/version"))}function Ooe(e=process.env,t=process.platform,r={}){if(t!=="linux")return{available:!0,wslg:!1};let n=r.exists??Poe,o=Xl(e,t,r)&&n("/mnt/wslg");return{available:!!(e.DISPLAY?.trim()||e.WAYLAND_DISPLAY?.trim()),wslg:o}}function zf(e=process.env,t=process.platform){return/^(1|true|yes|on)$/i.test(e.KYNVER_BROWSER_HEADLESS??"")?!0:!Ooe(e,t).available}function Toe(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 nW(e={}){let t=e.readFile??(r=>tW(r,"utf8"));return Toe(rW(t,"/etc/os-release"))}var Uo=p(()=>{"use strict"});import{existsSync as Noe,readdirSync as Doe}from"node:fs";import{homedir as Moe}from"node:os";import Fo from"node:path";function Xf(e=process.env){return e.KYNVER_BROWSER_INSTALL_DIR?.trim()||Fo.join(Moe(),".kynver","browsers")}function oW(e,t=process.env){return Fo.join(Xf(t),`chrome-${e}`)}function Qf(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 Loe(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 Zf(e,t=process.env,r={}){let n=r.exists??Noe,o=r.listDir??(l=>Doe(l)),s=Xf(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(Loe).reverse();for(let l of a){let c=Fo.join(s,`chrome-${l}`),u=Qf(c,e);if(n(u))return{executable:u,version:l,installDir:c}}return null}var SR=p(()=>{"use strict"});import{existsSync as Boe,readdirSync as Uoe}from"node:fs";import{homedir as Foe}from"node:os";import qr from"node:path";function Woe(e,t,r=Foe()){return e==="win32"?[t.PROGRAMFILES,t["PROGRAMFILES(X86)"],t.LOCALAPPDATA].filter(o=>typeof o=="string"&&o.length>0).flatMap(o=>[qr.join(o,"Google","Chrome","Application","chrome.exe"),qr.join(o,"Microsoft","Edge","Application","msedge.exe"),qr.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",qr.join(r,"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),qr.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",qr.join(r,".local/share/flatpak/exports/bin/com.google.Chrome"),qr.join(r,".local/share/flatpak/exports/bin/org.chromium.Chromium"),...sW.map(n=>qr.join(r,".local/bin",n))]}function Koe(e,t,r){let n=(e.PATH??"").split(":").filter(o=>o&&!(r&&o.startsWith("/mnt/")));for(let o of sW)for(let s of n){let i=qr.join(s,o);if(t(i))return i}return null}function Wo(e={}){let t=e.env??process.env,r=e.platform??process.platform,n=e.arch??process.arch,o=e.exists??Boe,s=e.config??A(),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=Woe(r,t,e.home).find(u=>o(u));if(l)return{executable:l,source:"system",version:null,configuredMissing:i};if(r==="linux"){let u=Koe(t,o,Xl(t,r,{readFile:e.readFile}));if(u)return{executable:u,source:"system",version:null,configuredMissing:i}}let c=Ei(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=Zf(c,t,{exists:o,listDir:e.listDir??(f=>Uoe(f))});if(d)return{executable:d.executable,source:"managed",version:d.version,configuredMissing:i}}return{executable:null,source:"none",version:null,configuredMissing:i}}var sW,Ql=p(()=>{"use strict";$();Uo();SR();sW=["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge","microsoft-edge-stable"]});import{createWriteStream as $oe}from"node:fs";import{rm as Hoe}from"node:fs/promises";function Goe(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(aW))return{version:r.version,url:s.url}}return null}async function lW(e,t=fetch){let r=await t(joe,{signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`Chrome for Testing index returned HTTP ${r.status}`);let n=Goe(await r.json(),e);if(!n)throw new Error(`No stable Chrome for Testing build is published for ${e}`);return n}async function cW(e,t,r={}){let n=r.minBytes??Voe;if(!e.startsWith(aW))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>iW))throw new Error(`browser download has an unexpected size (${a} bytes)`);let l=$oe(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>iW)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 Hoe(t,{force:!0}).catch(()=>{}),u}}var joe,aW,Voe,iW,uW=p(()=>{"use strict";joe="https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json",aW="https://storage.googleapis.com/chrome-for-testing-public/",Voe=20*1024*1024,iW=600*1024*1024});function Zl(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 qoe(e){return{apt:e.t64?1:0,dnf:2,zypper:3,pacman:4,apk:5,unknown:null}[e.family]}function Yoe(e,t){let r=qoe(t);if(r===null)return[];let n=new Set;for(let o of e){let s=Joe.find(([i])=>i.test(o));s&&n.add(s[1][r])}return[...n].sort()}function zoe(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 dW(e,t){let r=Yoe(e,t),n=zoe(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 Joe,em=p(()=>{"use strict";Joe=[[/^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 Xoe}from"node:child_process";function Zoe(e){return/(\d+\.\d+\.\d+\.\d+)/.exec(e)?.[1]??null}function ese(e,t=process.platform,r=Qoe){let n=new Set;if(t==="linux"){let s=r("ldd",[e],{encoding:"utf8",timeout:1e4});if(!s.error)for(let i of Zl(`${s.stdout??""}
|
|
544
|
+
Use browser_fill_login with a handle while that exact site is open.`}}async function Doe(e,t){let r=Zf(e),n=r.audit(t),o=Noe(e.args);if(!o)return ce("invalid_request",'A saved-login handle like "lg_7k2m9q4x1c" from browser_list_logins is required.');let s=r.store(t);if(!s.exists())return ce("vault_missing",rW);let i=s.get(o);if(!i)return ce("login_not_found","No saved login with that handle. Call browser_list_logins.");let a=await e.manager.activeTab(e.session),l=await Qf(e,a),c=ma(l),u={conversationId:e.session.conversationId,handle:o,label:i.label,username:i.username,origin:i.origin,pageOrigin:c},d=(R,T)=>({event:"fill",ok:R,origin:i.origin,label:i.label,code:T});if(!l||!$g(i.origin,l))return n.record({event:"fill",ok:!1,code:"origin_mismatch",...u}),ce("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}),ce("vault_locked",`Saved logins are locked. ${xR}`,{loginActivity:d(!1,"vault_locked")});let m=CR(e.args),g;try{g=await zl(e,a,SR,[i.origin,m])}catch(R){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),ce("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}),ce("origin_mismatch",`Refused: the page is no longer ${i.origin}.`,{loginActivity:d(!1,"origin_mismatch")});if(g?.error==="bad_ref")return ce("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(R){let T=R instanceof q?R.code:"failed";return n.record({event:"fill",ok:!1,code:T,...u}),ce("failed",R instanceof q?`Couldn't use this saved login: ${R.message}.`:"Couldn't read this saved login.")}let k={};if(g.username&&(k.username=i.username),g.password&&(k.password=h.password),g.code&&h.totp){let R=_u(h.totp);R&&(px(R)<3&&await(e.sleep??(T=>new Promise(W=>setTimeout(W,T))))(3100),k.code=dx(R))}if(h.password="",!k.username&&!k.password&&!k.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.":"",T=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 ce("field_not_found",`No sign-in field to fill on this page.${T}${R} Take a browser_snapshot to see where you are.`,{loginActivity:d(!1,"field_not_found")})}let v;try{v=await zl(e,a,_R,[i.origin,m,k])}catch(R){return n.record({event:"fill",ok:!1,code:"page_changed",...u}),ce("failed",`Couldn't fill: ${R.message}. Take a browser_snapshot and try again.`)}finally{k.password="",k.code=""}if(v?.error){let R=v.error==="origin"||v.error==="frame"?"origin_mismatch":"failed";return n.record({event:"fill",ok:!1,code:R,...u,pageOrigin:v.origin??c}),ce(R==="origin_mismatch"?"origin_mismatch":"failed",`Refused: the page changed to ${v.origin??"another address"} before the fill.`,{loginActivity:d(!1,R)})}let y=v?.filled??[];s.touch(o),n.record({event:"fill",ok:!0,code:null,...u,fields:y});let b=y.map(R=>R==="code"?"authenticator code":R).join(" + "),S=g.code&&!i.hasTotp&&!y.includes("code"),w=`Filled the ${b} for ${nW(i)}.`+(S?" The page also wants a one-time code: use browser_request_code so the user types it on their computer.":""),_={loginActivity:d(!0,null)};if(e.args.submit===!0){let R=await Xf(e,a);return R?{...R,..._,text:`${w} ${R.text}`}:(await zf(e,a,"Enter"),await Yl(e,a,2e3),{...await fr(e,a,`${w} Pressed Enter.`),..._})}return{ok:!0,text:`${w} Continue with browser_click on the sign-in button (or submit:true next time).`,..._}}async function Moe(e,t){let r=Zf(e),n=r.store(t);if(!n.exists())return ce("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 ce("vault_locked",`Saved logins are locked. ${xR}`);let s=await e.manager.activeTab(e.session),i=await Qf(e,s),a=ma(i);if(!a||!a.startsWith("https://"))return ce("url_refused","Only logins typed on an https:// site can be saved.");let l;try{l=await zl(e,s,eW,[a,CR(e.args)])}catch(m){return ce("failed",`Couldn't read the sign-in form: ${m.message}.`)}if(l?.error)return ce("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 ce("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 ce("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 ${nW(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 ce("failed",m instanceof q?`Couldn't save: ${m.message}.`:"Couldn't save this login.")}}async function Loe(e,t){let r=Zf(e),n=await e.manager.activeTab(e.session),o=await Qf(e,n),s=ma(o);if(!s)return ce("url_refused","Open the site's verification page first.");let i=CR(e.args),a;try{a=await zl(e,n,SR,[s,i])}catch(d){return ce("failed",`Couldn't read the page: ${d.message}.`)}if(a?.error==="bad_ref")return ce("invalid_request","codeRef must point at a text field on this page.");if(a?.error||!a?.code)return ce("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 Qf(e,n);if(!$g(s,f))return{ok:!1,text:`The page is no longer ${s}, so the code was not typed.`};try{let m=await zl(e,n,_R,[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 oW(e,t){let r=t.agentOsId?.trim();if(!r)return ce("invalid_request","Saved logins need the workspace this chat belongs to; update the Kynver runtime.");switch(e){case"list_logins":return ER(t.args,r,Zf(t));case"fill_login":return Doe(t,r);case"save_login":return Moe(t,r);case"request_code":return Loe(t,r)}}var xR,rW,sW=p(()=>{"use strict";RR();tW();Hg();vs();cn();jg();xR="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.",rW="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 em,iW=p(()=>{"use strict";Ei();em=class{constructor(t){this.deps=t;this.now=t.now??Date.now,this.idleMs=t.idleMs??LF}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<BF),t.actionTimes.length>=UF?!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>=yR)throw new Error(`tab limit reached (${yR}) \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 mr,Boe,Xl,aW=p(()=>{"use strict";mr=class extends Error{constructor(r,n){super(r);this.code=n;this.name="CdpError"}code},Boe=e=>new WebSocket(e),Xl=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??Boe)(t);return await new Promise((o,s)=>{let i=setTimeout(()=>s(new mr("CDP connect timed out")),r.timeoutMs??1e4);n.addEventListener("open",()=>{clearTimeout(i),o()}),n.addEventListener("error",()=>{clearTimeout(i),s(new mr("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 mr("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 mr(`${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 mr(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 mr("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 mr("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 mr(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)}}}});import{existsSync as Uoe,readFileSync as lW}from"node:fs";function Ai(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 cW(e,t){try{return e(t)}catch{return""}}function Ql(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=>lW(o,"utf8"));return/microsoft|wsl/i.test(cW(n,"/proc/version"))}function Foe(e=process.env,t=process.platform,r={}){if(t!=="linux")return{available:!0,wslg:!1};let n=r.exists??Uoe,o=Ql(e,t,r)&&n("/mnt/wslg");return{available:!!(e.DISPLAY?.trim()||e.WAYLAND_DISPLAY?.trim()),wslg:o}}function tm(e=process.env,t=process.platform){return/^(1|true|yes|on)$/i.test(e.KYNVER_BROWSER_HEADLESS??"")?!0:!Foe(e,t).available}function Woe(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 uW(e={}){let t=e.readFile??(r=>lW(r,"utf8"));return Woe(cW(t,"/etc/os-release"))}var Fo=p(()=>{"use strict"});import{existsSync as Koe,readdirSync as $oe}from"node:fs";import{homedir as Hoe}from"node:os";import Wo from"node:path";function rm(e=process.env){return e.KYNVER_BROWSER_INSTALL_DIR?.trim()||Wo.join(Hoe(),".kynver","browsers")}function dW(e,t=process.env){return Wo.join(rm(t),`chrome-${e}`)}function nm(e,t){let r=Wo.join(e,`chrome-${t}`);return t==="linux64"?Wo.join(r,"chrome"):t==="win32"||t==="win64"?Wo.join(r,"chrome.exe"):Wo.join(r,"Google Chrome for Testing.app","Contents","MacOS","Google Chrome for Testing")}function joe(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 om(e,t=process.env,r={}){let n=r.exists??Koe,o=r.listDir??(l=>$oe(l)),s=rm(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(joe).reverse();for(let l of a){let c=Wo.join(s,`chrome-${l}`),u=nm(c,e);if(n(u))return{executable:u,version:l,installDir:c}}return null}var AR=p(()=>{"use strict"});import{existsSync as Voe,readdirSync as Goe}from"node:fs";import{homedir as Joe}from"node:os";import Yr from"node:path";function qoe(e,t,r=Joe()){return e==="win32"?[t.PROGRAMFILES,t["PROGRAMFILES(X86)"],t.LOCALAPPDATA].filter(o=>typeof o=="string"&&o.length>0).flatMap(o=>[Yr.join(o,"Google","Chrome","Application","chrome.exe"),Yr.join(o,"Microsoft","Edge","Application","msedge.exe"),Yr.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",Yr.join(r,"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),Yr.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",Yr.join(r,".local/share/flatpak/exports/bin/com.google.Chrome"),Yr.join(r,".local/share/flatpak/exports/bin/org.chromium.Chromium"),...pW.map(n=>Yr.join(r,".local/bin",n))]}function Yoe(e,t,r){let n=(e.PATH??"").split(":").filter(o=>o&&!(r&&o.startsWith("/mnt/")));for(let o of pW)for(let s of n){let i=Yr.join(s,o);if(t(i))return i}return null}function Ko(e={}){let t=e.env??process.env,r=e.platform??process.platform,n=e.arch??process.arch,o=e.exists??Voe,s=e.config??A(),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=qoe(r,t,e.home).find(u=>o(u));if(l)return{executable:l,source:"system",version:null,configuredMissing:i};if(r==="linux"){let u=Yoe(t,o,Ql(t,r,{readFile:e.readFile}));if(u)return{executable:u,source:"system",version:null,configuredMissing:i}}let c=Ai(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=om(c,t,{exists:o,listDir:e.listDir??(f=>Goe(f))});if(d)return{executable:d.executable,source:"managed",version:d.version,configuredMissing:i}}return{executable:null,source:"none",version:null,configuredMissing:i}}var pW,Zl=p(()=>{"use strict";$();Fo();AR();pW=["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge","microsoft-edge-stable"]});import{createWriteStream as zoe}from"node:fs";import{rm as Xoe}from"node:fs/promises";function ese(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(mW))return{version:r.version,url:s.url}}return null}async function gW(e,t=fetch){let r=await t(Qoe,{signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`Chrome for Testing index returned HTTP ${r.status}`);let n=ese(await r.json(),e);if(!n)throw new Error(`No stable Chrome for Testing build is published for ${e}`);return n}async function hW(e,t,r={}){let n=r.minBytes??Zoe;if(!e.startsWith(mW))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>fW))throw new Error(`browser download has an unexpected size (${a} bytes)`);let l=zoe(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>fW)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 Xoe(t,{force:!0}).catch(()=>{}),u}}var Qoe,mW,Zoe,fW,yW=p(()=>{"use strict";Qoe="https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json",mW="https://storage.googleapis.com/chrome-for-testing-public/",Zoe=20*1024*1024,fW=600*1024*1024});function ec(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 rse(e){return{apt:e.t64?1:0,dnf:2,zypper:3,pacman:4,apk:5,unknown:null}[e.family]}function nse(e,t){let r=rse(t);if(r===null)return[];let n=new Set;for(let o of e){let s=tse.find(([i])=>i.test(o));s&&n.add(s[1][r])}return[...n].sort()}function ose(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 kW(e,t){let r=nse(e,t),n=ose(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 tse,sm=p(()=>{"use strict";tse=[[/^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 sse}from"node:child_process";function ase(e){return/(\d+\.\d+\.\d+\.\d+)/.exec(e)?.[1]??null}function lse(e,t=process.platform,r=ise){let n=new Set;if(t==="linux"){let s=r("ldd",[e],{encoding:"utf8",timeout:1e4});if(!s.error)for(let i of ec(`${s.stdout??""}
|
|
545
545
|
${s.stderr??""}`))n.add(i)}let o=null;if(t!=="win32"){let s=r(e,["--version"],{encoding:"utf8",timeout:1e4}),i=`${s.stdout??""}
|
|
546
|
-
${s.stderr??""}`;for(let a of Zl(i))n.add(a);s.status===0&&(o=Zoe(i))}return{version:o,missingLibs:[...n].sort()}}function pW(e,t=()=>ese(e),r=Date.now){let n=_R.get(e);if(n&&r()-n.at<tse)return n.health;let o=t();return _R.set(e,{at:r(),health:o}),o}function fW(){_R.clear()}var Qoe,tse,_R,xR=p(()=>{"use strict";em();Qoe=(e,t,r)=>Xoe(e,t,r);tse=10*6e4,_R=new Map});import{chmodSync as rse,mkdirSync as CR,symlinkSync as nse,writeFileSync as ose}from"node:fs";import Ai from"node:path";import{crc32 as sse,inflateRawSync as ise}from"node:zlib";function use(e){let t=Math.max(0,e.length-65535-22);for(let r=e.length-22;r>=t;r-=1)if(e.readUInt32LE(r)===ase)return r;throw new Error("not a zip archive (no end-of-central-directory record)")}function dse(e){let t=use(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)!==lse)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 pse(e,t){let r=t.localHeaderOffset;if(e.readUInt32LE(r)!==cse)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=ise(o);else throw new Error(`unsupported zip compression method ${t.method} (${t.name})`);if(s.length!==t.size||sse(s)>>>0!==t.crc>>>0)throw new Error(`zip entry failed its integrity check: ${t.name}`);return s}function mW(e,t){let r=t.replace(/\\/g,"/");if(r.startsWith("/")||/^[a-zA-Z]:/.test(r))throw new Error(`unsafe zip path: ${t}`);let n=Ai.resolve(e,r),o=Ai.resolve(e);if(n!==o&&!n.startsWith(o+Ai.sep))throw new Error(`unsafe zip path: ${t}`);return n}function gW(e,t,r=process.platform){CR(t,{recursive:!0});let n=0;for(let o of dse(e)){let s=mW(t,o.name);if(o.name.endsWith("/")){CR(s,{recursive:!0});continue}CR(Ai.dirname(s),{recursive:!0});let i=pse(e,o);if(o.unixMode!==null&&(o.unixMode&fse)===mse&&r!=="win32"){let a=i.toString("utf8");mW(t,Ai.posix.join(Ai.posix.dirname(o.name.replace(/\\/g,"/")),a)),nse(a,s)}else ose(s,i),o.unixMode!==null&&r!=="win32"&&rse(s,o.unixMode&511||420);n+=1}return n}var ase,lse,cse,fse,mse,hW=p(()=>{"use strict";ase=101010256,lse=33639248,cse=67324752;fse=61440,mse=40960});import{closeSync as yW,existsSync as ER,mkdirSync as gse,openSync as kW,readFileSync as hse,renameSync as yse,rmSync as Ii,statSync as kse,chmodSync as bse}from"node:fs";import AR from"node:path";function Ko(){return{...jt}}function RW(e=jt){return e.state!=="failed"||e.failedAt===null?0:e.failedAt+bW[Math.min(e.attempts-1,bW.length-1)]}function wW(e=jt){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 Rse(e){let t=A();He({...t,browserManaged:{version:e.version,platform:e.platform,executable:e.executable,installedAt:new Date().toISOString()}})}function wse(e,t){gW(hse(e),t)}function Sse(e,t){try{return yW(kW(e,"wx")),!0}catch{try{if(t-kse(e).mtimeMs>vse)return Ii(e,{force:!0}),yW(kW(e,"wx")),!0}catch{}return!1}}async function _se(e,t){let r=t.env??process.env,n=t.now??Date.now,o=t.sleep??(a=>new Promise(l=>setTimeout(l,a))),s=Xf(r);gse(s,{recursive:!0});let i=AR.join(s,".install.lock");for(;!Sse(i,n());)if(await o(2e3),!ER(i)){let a=Zf(e,r);if(a)return a}try{let a=await lW(e,t.fetchFn),l=oW(a.version,r),c=Qf(l,e);if(!ER(c)){let d=AR.join(s,`.download-${a.version}.zip`),f=AR.join(s,`.staging-${a.version}-${process.pid}`);Ii(f,{recursive:!0,force:!0});try{await cW(a.url,d,{fetchFn:t.fetchFn,minBytes:t.minArchiveBytes,onProgress:g=>{jt.receivedBytes=g.receivedBytes,jt.totalBytes=g.totalBytes}}),(t.extract??wse)(d,f);let m=Qf(f,e);if(!ER(m))throw new Error("the downloaded browser archive did not contain Chrome");(t.platform??process.platform)!=="win32"&&bse(m,493),Ii(l,{recursive:!0,force:!0}),yse(f,l)}finally{Ii(d,{force:!0}),Ii(f,{recursive:!0,force:!0})}}let u={executable:c,version:a.version,installDir:l};return(t.record??Rse)({...u,platform:e}),u}finally{Ii(i,{force:!0})}}function tm(e={}){if(ec)return ec;let t=Ei(e.platform??process.platform,e.arch??process.arch);if(!t)return Promise.reject(new Pi("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 jt={...jt,state:"downloading",receivedBytes:0,totalBytes:null,error:null},ec=_se(t,e).then(n=>(jt={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},fW(),n)).catch(n=>{let o=n instanceof Error?n.message:String(n);throw jt={...jt,state:"failed",error:o.slice(0,300),failedAt:r(),attempts:jt.attempts+1},new Pi(`Couldn't download a browser for this computer: ${o.slice(0,200)}`,"download_failed")}).finally(()=>{ec=null}),ec}var vW,vse,bW,Pi,jt,ec,rm=p(()=>{"use strict";$();Uo();uW();xR();SR();hW();vW=150,vse=30*6e4,bW=[6e4,5*6e4,30*6e4,120*6e4],Pi=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserProvisionError"}code},jt={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},ec=null});function Ese(){let e=Ko(),t=e.state==="downloading"?` (${wW(e)})`:"";return`Setting up a browser on your computer \u2014 a one-time download of about ${vW} MB${t}. Tell the user it's being set up, wait about 30 seconds, then try the same step again.`}async function SW(e={}){let t=(e.resolve??(()=>Wo()))();if(t.executable)return t.executable;if(!(e.autoProvision??A().browserAutoProvision!==!1))throw new Yr("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??Ko)(),o=(e.now??Date.now)();if(n.state==="failed"&&n.failedAt!==null&&o-n.failedAt<Cse)throw new Yr(`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??tm)(),i,a=new Promise(l=>{i=setTimeout(()=>l("pending"),e.waitMs??xse),i.unref?.()});try{let l=await Promise.race([s,a]);if(l==="pending")throw s.catch(()=>{}),new Yr(Ese(),"browser_installing");return l.executable}catch(l){if(l instanceof Yr)throw l;let c=l instanceof Pi?l.message:"Couldn't set up a browser on this computer.";throw new Yr(`${c} The user can run \`kynver browser install\` on that computer to retry, or install Google Chrome.`,"chrome_not_found")}finally{clearTimeout(i)}}var xse,Cse,Yr,_W=p(()=>{"use strict";$();Ql();rm();xse=2e4,Cse=6e4,Yr=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserEnsureError"}code}});function IR(e){return Ase.test(e)}function xW(e=process.platform,t=typeof process.getuid=="function"?process.getuid():null){return e==="linux"&&t===0}function nm(e){CW=e}function EW(){return CW}var Ase,CW,PR=p(()=>{"use strict";Ase=/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;CW=null});import{spawn as Ise}from"node:child_process";import{existsSync as sje,mkdirSync as Pse,readFileSync as Ose,rmSync as Tse}from"node:fs";import{homedir as Nse}from"node:os";import AW from"node:path";function Mse(e=process.env){return e.KYNVER_BROWSER_PROFILE_DIR?.trim()||AW.join(Nse(),".kynver","browser-profile")}function IW(e=process.env){return(e.KYNVER_BROWSER_CDP_URL?.trim()||A().browserCdpUrl?.trim()||Dse).replace(/\/$/,"")}async function PW(e,t={}){let r=t.env??process.env,n=t.platform??process.platform,o=t.allowNoSandbox??A().browserAllowNoSandbox!==!1;if((t.asRoot??xW(n))&&o){let a=await TR(e,r,n,t,!0);if("wsUrl"in a)return nm("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 OR(a.stderrTail)}let i=await TR(e,r,n,t,!1);if("wsUrl"in i)return nm("on"),i;if(n==="linux"&&o&&IR(i.stderrTail)){let a=await TR(e,r,n,t,!0);if("wsUrl"in a)return nm("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 OR(a.stderrTail)}throw OR(i.stderrTail)}function OR(e){let t=Zl(e);return t.length>0?new tc(t):IR(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 TR(e,t,r,n,o){let s=Mse(t);Pse(s,{recursive:!0});let i=AW.join(s,"DevToolsActivePort");Tse(i,{force:!0});let a=zf(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??Ise)(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=>Ose(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 OW(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 Dse,tc,TW=p(()=>{"use strict";$();Uo();em();Ql();PR();Dse="http://127.0.0.1:9222";tc=class extends Error{constructor(r){super(`Chrome is missing system libraries: ${r.join(", ")}`);this.missingLibs=r;this.name="ChromeMissingLibsError"}missingLibs}});async function Lse(e){if(e==="attach"){let n=IW(),o;try{o=await OW(n)}catch{throw new Oi(`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 zl.connect(o),child:null,mode:e}}let t;try{t=await SW()}catch(n){throw n instanceof Yr?new Oi(n.message,n.code):n}let r;try{r=await PW(t)}catch(n){throw n instanceof tc?new Oi(dW(n.missingLibs,nW()),"missing_libs"):n}return{conn:await zl.connect(r.wsUrl),child:r.child,mode:e}}function Bse(){return om??=new Yf({connectHost:Lse}),om}async function NW(){om&&await om.closeAll().catch(()=>{})}function DW(){try{let e=A();e.browserEverEnabled!==!0&&He({...e,browserEverEnabled:!0})}catch{}}function Dn(e,t){return{ok:!1,code:e,text:t}}function Use(e){if(!e||typeof e!="object")return null;let t=e,r=t.policy;if(t.kind!=="browser"||!SF(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 MW(e,t){let r=Use(e);if(!r)return Dn("invalid_request","Malformed browser request.");if(t.localDisabled)return Dn("disabled","The browser is switched off on this computer (local setting browserDisabled).");if(!r.policy.enabled)return Dn("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 Dn("wrong_box","This request reached a different computer than the one the browser is enabled on.");t.onEnabledTurn?.();let n=t.manager??Bse();if(r.action==="list_logins")return wR(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 Dn("action_cap","Too many browser actions in a short time. Pause and summarize progress for the user.");let s=r.action==="wait"?$f+5e3:EF,i,a=new Promise(d=>{i=setTimeout(()=>d(Dn("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([wF(c)?XF(c,l):GF(c,l),a]).finally(()=>clearTimeout(i));return{...u,text:Hf(u.text)}}catch(o){if(o instanceof Oi)return Dn(o.code,o.message);let s=o instanceof Error?o.message:String(o);return Dn("failed",`Browser action failed: ${s.slice(0,300)}`)}}var Oi,om,NR=p(()=>{"use strict";hR();QF();fR();ZF();eW();$();_W();em();Uo();TW();Ci();Oi=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserSetupError"}code};om=null});import{mkdirSync as Fse,readFileSync as Eje,renameSync as Wse,writeFileSync as Kse}from"node:fs";import{homedir as $se}from"node:os";import DR from"node:path";function Hse(e=DR.join($se(),".kynver","state")){return DR.join(e,"chat-loop.json")}function LW(e,t=Hse()){try{Fse(DR.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;Kse(r,JSON.stringify({v:1,...e}),{mode:384}),Wse(r,t)}catch{}}var BW=p(()=>{"use strict"});function jse(e,t,r){if(!t||t===r)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`${n}(?=[\\\\/"'\\s<]|$)`,"gm"),()=>r)}function UW(e,t){return jse(e,t,"\0")!==e}var FW=p(()=>{"use strict"});import{accessSync as Vse,constants as Gse,existsSync as Jse,lstatSync as qse,readdirSync as Yse,readFileSync as zse,readlinkSync as Xse,realpathSync as Qse}from"node:fs";import{homedir as Zse}from"node:os";import WW from"node:path";function $W(e){return e==="win32"?WW.win32:WW.posix}function tie(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===MR)return n}catch{}let i=r.dirname(n);if(i===n)break;n=i}return null}function nie(e,t,r){let n=$W(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 oie(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 sie(e,t,r,n,o){for(let s of oie(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 iie(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 aie(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 sm(e={}){let t=e.platform??process.platform,r=$W(t),n=e.fs??eie,o=e.env??process.env,s=e.home??Zse(),i=e.execPath??process.execPath,a=n.realpath(e.cliEntry??process.argv[1]??""),l=a?tie(a,n,r):null,c={cliPath:a,packageRoot:l,nodePath:i,npmCliPath:nie(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(KW).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=rie.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=sie(d.releaseDir,s,o,n,r);else{let y=/^(.*)[\\/]lib[\\/]node_modules[\\/]@kynver-app[\\/]runtime$/.exec(l),b=t==="win32"?/^(.*)[\\/]node_modules[\\/]@kynver-app[\\/]runtime$/.exec(l):null,k=y?.[1]??b?.[1];k&&!k.split(KW).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",ra);n.exists(y)&&(g="systemd",d.supervisorFile=y,d.supervisorName=ra)}else if(t==="darwin"){let y=iie(m,s,n,r);y&&(g="launchd",d.supervisorFile=y.file,d.supervisorName=y.label)}else if(t==="win32"){let y=aie(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=lie(h,n),h.unsupportedReason||delete h.unsupportedReason,h}function lie(e,t){if(e.kind==="npm_global")return e.npmPrefix&&!t.writable(e.npmPrefix)?`Kynver is installed in ${e.npmPrefix}, which this computer's user cannot write to (it needs admin rights), so I can't update it from here.`:void 0;if(e.kind!=="release_dir")return;if(e.releasesRoot&&!t.writable(e.releasesRoot))return`I can't write a new release next to the current one (${e.releasesRoot} is not writable).`;let r=(()=>{if(!e.supervisorFile||!e.releaseDir)return!1;let n=t.readText(e.supervisorFile);return!!n&&UW(n,e.releaseDir)})();if(e.supervisor==="keeper"||e.supervisor==="none")return"Kynver runs from a release folder without a service that starts it, so a restart would bring back the old release. Run `kynver cron install --install-systemd` once (Linux) so updates can switch releases.";if(!r&&!e.shimPath)return`The service that starts Kynver (${e.supervisorFile??e.supervisor}) doesn't name the release folder or a kynver link I can switch.`}var MR,eie,KW,rie,im=p(()=>{"use strict";ls();FW();MR="@kynver-app/runtime",eie={exists:e=>Jse(e),readText:e=>{try{return zse(e,"utf8")}catch{return null}},readDir:e=>{try{return Yse(e)}catch{return[]}},realpath:e=>{try{return Qse.native(e)}catch{return e}},readLink:e=>{try{return qse(e).isSymbolicLink()?Xse(e):null}catch{return null}},writable:e=>{try{return Vse(e,Gse.W_OK),!0}catch{return!1}}},KW=/[\\/]/;rie=/^(.*)[\\/]releases[\\/]([^\\/]+)[\\/]node_modules[\\/]@kynver-app[\\/]runtime$/});function HW(e){return`npm-${e}`}function am(e,t="latest"){let r=`${MR}@${t}`;switch(e.kind){case"release_dir":{let n=e.releasesRoot?`${e.releasesRoot}/${HW(t)}`:`<releases>/${HW(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 LR=p(()=>{"use strict";im()});var jW=p(()=>{"use strict"});import{mkdirSync as Hje,readFileSync as cie,readdirSync as jje,renameSync as Vje,writeFileSync as Gje}from"node:fs";import VW from"node:path";function uie(){return VW.join(wl(),"runtime")}function die(e){return VW.join(e,"summary.json")}function GW(e=uie()){try{let t=JSON.parse(cie(die(e),"utf8"));if(t?.v===1)return t}catch{}return{v:1,attempts:0,succeeded:0,rolledBack:0,failed:0,last:null}}var JW=p(()=>{"use strict";Op();jW()});function fie(e=Date.now()){if(lm&&e-lm.at<pie)return lm.report;if(!Ti){let o=sm();Ti={kind:o.kind,supervisor:o.supervisor,can:!o.unsupportedReason,manual:am(o,"latest")}}let t=GW(),r=t.last,n={v:1,installKind:Ti.kind,supervisor:Ti.supervisor,canSelfUpdate:Ti.can,manualCommand:Ti.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 lm={at:e,report:n},n}function cm(){try{return fie()}catch{return}}var Ti,lm,pie,BR=p(()=>{"use strict";im();LR();JW();Ti=null,lm=null,pie=3e4});import{readdir as mie,readFile as gie}from"node:fs/promises";import{sep as hie}from"node:path";import{fileURLToPath as yie}from"node:url";function Rie(e=import.meta.url){let t;try{t=yie(e)}catch{return"checkout"}return t.split(hie).includes("node_modules")||t.split("/").includes("node_modules")?"npm":"checkout"}function wie(e){if(typeof e!="string")return null;let t=e.trim();return t&&t.length<=vie?t:null}async function Sie(e){try{return wie(JSON.parse(await gie(e,"utf8")).version)}catch{return null}}function YW(e){return e.toLowerCase().endsWith(".bak")}function _ie(e,t){if(!e)return t;try{return Ap(t,e)>0?t:e}catch{return e}}async function xie(e={}){let t={},r=new Set;for(let n of(e.scopeRoots??dD)()){let o=[];try{o=await mie(n)}catch{continue}for(let s of o)YW(s)||/^[a-z0-9][a-z0-9._-]*$/i.test(s)&&r.add(`${qW}${s}`)}try{for(let n of await(e.adopted??gb)())n.packageName.startsWith(qW)&&!YW(n.packageName)&&r.add(n.packageName)}catch{}for(let n of[...r].sort().slice(0,bie))for(let o of nb(n)){let s=await Sie(o);s&&(t[n]=_ie(t[n],s))}return t}function Cie(e){UR||Ni&&e-Ni.at<kie||(UR=xie().then(t=>{Ni={at:Date.now(),packages:t}}).catch(()=>{Ni={at:Date.now(),packages:Ni?.packages??{}}}).finally(()=>{UR=null}))}function um(e=Date.now()){try{Cie(e)}catch{}return{v:1,runtime:{version:Ze,source:Rie()},packages:{...Ni?.packages??{}}}}var qW,kie,bie,vie,Ni,UR,FR=p(()=>{"use strict";un();ob();hb();rb();qW="@kynver-app/",kie=10*6e4,bie=40,vie=32;Ni=null,UR=null});async function zW(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:sp(e.agentOsId,i)})}).catch(()=>{}),s=t.payload?.action;try{let i=await(r.execute??MW)(t.payload,{boxId:e.boxId,agentOsId:e.agentOsId,localDisabled:A().browserDisabled===!0,onEnabledTurn:DW});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 XW=p(()=>{"use strict";$();NR();Hr()});import{appendFileSync as Eie,chmodSync as Aie,existsSync as QW,readFileSync as Iie,renameSync as Pie,statSync as Oie}from"node:fs";import Tie from"node:path";function ZW(e,t=xt()){return Tie.join(t,rl(e).replace(/\.vault\.json$/,".audit.jsonl"))}function eK(e,t,r=xt()){try{el(r);let n=ZW(e,r);QW(n)&&Oie(n).size>Nie&&Pie(n,`${n}.1`),Eie(n,`${JSON.stringify({at:new Date().toISOString(),...t})}
|
|
547
|
-
`,{mode:384});try{
|
|
548
|
-
`).filter(Boolean).slice(-t).flatMap(o=>{try{return[JSON.parse(o)]}catch{return[]}}):[]}var Nie,rK=p(()=>{"use strict";tl();np();Nie=512*1024});function sK(e,t){return e.report(t)}function Mie(e){return e.state==="none"?nt("login_vault_missing","Saved logins aren't set up on this computer yet. Run `kynver logins setup` (or open the Kynver desktop app), then try again."):e.state==="locked"?nt("login_vault_locked","Saved logins are locked on this computer. Run `kynver logins unlock`, then try again."):null}function Lie(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t;for(let n of Object.keys(r))if(!["o","u","p","t","l"].includes(n))return null;return typeof r.o!="string"||typeof r.u!="string"||typeof r.p!="string"||r.t!==void 0&&typeof r.t!="string"||r.l!==void 0&&typeof r.l!="string"?null:{origin:r.o,username:r.u,password:r.p,...r.t?{totp:r.t}:{},...r.l?{label:r.l}:{}}}function Bie(e){let t=(e.label??"").trim().slice(0,Ve.maxLabel);if(t)return t;try{return new URL(e.origin.includes("://")?e.origin:`https://${e.origin}`).hostname.slice(0,Ve.maxLabel)}catch{return"Website login"}}function iK(e,t,r,n){let o=n.store(t.agentOsId),s=n.audit(t.agentOsId);try{switch(e.op){case"login_list":return{ok:!0,logins:o.list(),vault:n.report(t.agentOsId)};case"login_delete":{let i=e.handle;if(typeof i!="string"||!oK.test(i))return nt("invalid_handle","That saved-login handle isn't valid.");let a=o.get(i),l=o.remove(i);return l&&a&&s.record({event:"remove",ok:!0,handle:i,label:a.label,username:a.username,origin:a.origin,code:"chat_card"}),l?{ok:!0,removed:!0}:nt("not_found","No saved login with that handle on this computer.")}case"login_store":{let i=e.requestId;if(typeof i!="string"||!qd.test(i))return nt("invalid_request","That request id isn't valid.");let a=e.replaceHandle;if(a!==void 0&&!(typeof a=="string"&&oK.test(a)))return nt("invalid_handle","That saved-login handle isn't valid.");let l=Xd(e.envelope);if(!l)return nt("invalid_envelope","The sealed login is malformed.");if(l.kid!==r.fingerprint)return s.record({event:"add",ok:!1,code:"key_mismatch"}),nt("key_mismatch","The login was sealed for a different computer key. Reload the card and try again.");let c=Mie(n.report(t.agentOsId));if(c)return c;let u=n.key(t.agentOsId);if(!u)return nt("login_vault_locked","Saved logins are locked on this computer. Run `kynver logins unlock`, then try again.");let d;try{d=Qd(r.ecdhPrivateKey,l,{agentOsId:t.agentOsId,requestId:i,name:Die(a)})}catch(h){return s.record({event:"add",ok:!1,code:"open_failed"}),nt("open_failed",h instanceof ft?h.message:"The login could not be opened.")}let f=Lie(d);if(d="",!f)return nt("invalid_login","The sealed login has an unexpected shape.");let m={origin:f.origin,label:Bie(f),username:f.username,password:f.password,totp:f.totp,allowLan:!0},g=a?o.replace(u,a,m):o.add(u,m);return f.password="",s.record({event:a?"replace":"add",ok:!0,handle:g.handle,label:g.label,username:g.username,origin:g.origin,code:"chat_card"}),{ok:!0,login:g,...a?{replaced:!0}:{}}}default:return nt("unknown_op","Unknown saved-login operation.")}}catch(i){return i instanceof z?nt(i.code,i.message):nt("store_failed","The saved-login vault on this computer hit an error.")}}var nK,oK,Die,nt,aK=p(()=>{"use strict";Zd();Gs();ln();_u();nK="site_login",oK=/^lg_[a-z0-9]{6,20}$/,Die=e=>e?`${nK}:${e}`:nK,nt=(e,t)=>({ok:!1,code:e,text:t})});function Vt(e,t){return{ok:!1,code:e,text:t}}async function lK(e,t,r={}){let n=e??{};if(typeof n.boxId!="string"||n.boxId!==t.boxId)return Vt("wrong_computer","This request was meant for another computer.");let o;try{o=(r.keys??tp)()}catch(a){return Vt("keys_unavailable",a instanceof Error?a.message:"This computer's secret store isn't available.")}let s=new qs({agentOsId:t.agentOsId,vaultKey:o.vaultKey,root:r.root}),i=a=>(r.audit??eK)(t.agentOsId,a,r.root);try{switch(n.op){case"describe":return{ok:!0,publicKey:o.publicKeyRaw.toString("base64"),fingerprint:o.fingerprint,keyStore:o.keyStore,secrets:s.list(),siteLogins:sK(r.siteLogins??Qe(),t.agentOsId)};case"login_store":case"login_list":case"login_delete":return iK(n,t,o,r.siteLogins??Qe());case"list":return{ok:!0,fingerprint:o.fingerprint,keyStore:o.keyStore,secrets:s.list(),audit:tK(t.agentOsId,30,r.root)};case"store":{let a=n.name,l=n.requestId;if(!Yd(a))return Vt("invalid_name","That secret name isn't allowed.");if(typeof l!="string"||!qd.test(l))return Vt("invalid_request","That request id isn't valid.");let c=Xd(n.envelope);if(!c)return Vt("invalid_envelope","The sealed value is malformed.");if(c.kid!==o.fingerprint)return i({event:"refused",name:a,ok:!1,via:"chat",requestId:l,code:"key_mismatch"}),Vt("key_mismatch","The value was sealed for a different computer key. Reload the card and try again.");let u;try{u=Qd(o.ecdhPrivateKey,c,{agentOsId:t.agentOsId,requestId:l,name:a})}catch(m){return i({event:"refused",name:a,ok:!1,via:"chat",requestId:l,code:"open_failed"}),Vt("open_failed",m instanceof ft?m.message:"The secret could not be opened.")}let d=typeof n.purpose=="string"?n.purpose:"",f=s.put({name:a,value:u,purpose:d});return u="",Zy(t.agentOsId),i({event:f.replaced?"rotate":"store",name:a,handle:f.summary.handle,ok:!0,via:n.via==="settings"?"settings":"chat",requestId:l}),{ok:!0,handle:f.summary.handle,name:a,replaced:f.replaced}}case"delete":{let a=n.handle;if(typeof a!="string"||!YP.test(a))return Vt("invalid_handle","That secret handle isn't valid.");let l=s.remove({handle:a});return Zy(t.agentOsId),i({event:"delete",name:l.name,handle:a,ok:!0,via:n.via==="chat"?"chat":"settings"}),{ok:!0,handle:a,name:l.name}}default:return Vt("unknown_op","Unknown secret operation.")}}catch(a){return a instanceof Pe?Vt(a.code,a.message):Vt("store_failed","The secret store on this computer hit an error.")}}var cK=p(()=>{"use strict";rK();Zd();Hr();tl();np();aK();bs();Gs()});async function uK(e,t,r,n={}){let o=t.payload?.op;try{let s=await lK(t.payload,r,n);await e([{seq:0,kind:"final",message:s}]),console.error(JSON.stringify({event:"secret_turn_done",turnId:t.turnId,op:o,ok:s.ok,code:s.ok?null:s.code}))}catch{await Promise.resolve(e([{seq:0,kind:"error",error:"secret_turn_crashed"}])).catch(()=>{}),console.error(JSON.stringify({event:"secret_turn_error",turnId:t.turnId,op:o}))}}var dK=p(()=>{"use strict";cK()});function pK(e=process.env,t={}){let r=t.platform??process.platform,n=A(),o={executable:null,source:"none",version:null,configuredMissing:null};try{o=(t.resolve??(()=>Wo({env:e,platform:r,config:n})))()}catch{}let s={version:null,missingLibs:[]};if(o.executable)try{s=(t.health??(i=>pW(i)))(o.executable)}catch{}return{supported:!0,chromeFound:o.executable!==null,localDisabled:n.browserDisabled===!0,browserSource:o.source,browserVersion:o.version??s.version,provisioning:Ko().state,missingLibs:s.missingLibs,wsl:Xl(e,r),headless:zf(e,r),autoProvision:n.browserAutoProvision!==!1,sandbox:EW()}}var fK=p(()=>{"use strict";$();xR();Uo();Ql();rm();PR()});function rc(e,t,r,n,o,s,i){return{chatProvider:e,toolCalls:e==="anthropic"||e==="cursor"||e==="gemini"||e==="openai"||e==="codex",runtimePackageVersion:Ze,browser:pK(),deliveryReceipt:!0,...t?{chatModels:t}:{},...r?{computer:r}:{},...n?{security:n}:{},...o?{agentEngines:o}:{},...s?{packageVersions:s}:{},...i?{selfUpdate:i}:{}}}var WR=p(()=>{"use strict";un();fK()});import{spawn as Uie}from"node:child_process";async function mK(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=lr(o),i=new Set([...mv,...wm]);return new Promise(a=>{let l="",c=!1,u=m=>{c||(c=!0,clearTimeout(f),a({...m,at:r().toISOString()}))},d;try{d=Uie(t.execPath??process.execPath,["-e",Fie],te({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 Fie,gK=p(()=>{"use strict";B();To();Fi();Fie="process.stdout.write(JSON.stringify(Object.keys(process.env)))"});function Kie(e){return e>=200&&e<300?"accepted":e===409||e===410?"rejected":e===404||e===405?"unsupported":"unreachable"}function hK(e){return e!=="rejected"}async function yK(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(),Wie);try{let a=await mi(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 Jr(e,a,l.status),{outcome:Kie(l.status),status:l.status}}catch{}finally{clearTimeout(i)}}return{outcome:"unreachable",status:null}}var Wie,kK=p(()=>{"use strict";gi();Wie=4e3});async function jie(e,t,r=fetch){let n=new AbortController,o=setTimeout(()=>n.abort(),Hie);try{let s=await mi(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 Jr(e,s,a.status),a.ok}catch{return!1}finally{clearTimeout(o)}}function bK(e){let t=e.intervalMs??$ie,r=!1,n=()=>{r||jie(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 $ie,Hie,vK=p(()=>{"use strict";gi();$ie=15e3,Hie=5e3});function RK(e){return e==="body"?12e4:32e3}var wK=p(()=>{"use strict"});async function SK(e,t,r,n){let o=A(),s=sr(o),i=await Po(e);if(!i.bearer)return"no_credential";let a=rc(s,yi(o),rf(s,o),e.security?.report({policy:n,auth:i.kind,credentialStore:El(),folderSandbox:Ef(process.env,o)}),Df(),um(),cm()),l=kL(e.agentOsId);l&&(a.browser.siteLogins=l);let c=i.kind==="box_token"?i.boxId:_l();e.chatProvider=s,e.boxId=c,e.model=Eo(s,o,process.env);let u=new AbortController,d="headers",f=()=>setTimeout(()=>u.abort(),RK(d)),m=f(),g=setInterval(()=>{t()&&u.abort()},500);try{let h=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:Vie,capabilities:a,claimRetries:r}),signal:u.signal});if(h.status===204)return null;if(h.status===401||h.status===403){let k=await h.text().catch(()=>"");return console.error(JSON.stringify({event:"chat_claim_auth_error",status:h.status,bridgeUrl:e.bridgeUrl,agentOsId:e.agentOsId,authKind:i.kind,detail:k.slice(0,200)})),Jr(e,i,401),"auth_error"}if(h.status===429)throw new Cn(h.status);if(!h.ok)throw new Cn(h.status);d="body",clearTimeout(m),m=f();let y;try{y=await h.json()}catch{throw new Cn(502)}let b=vM(y);if(!b)throw new Cn(502);return b.turn}catch(h){if(t())return null;throw h}finally{clearTimeout(m),clearInterval(g)}}var Vie,_K=p(()=>{"use strict";$();Gv();BR();FR();WR();Fp();Kl();Dl();En();gi();wK();Hp();nf();Vie=2e4});async function KR(e){let t=await $p(),r=()=>Tb(A().agentOsId?.trim())&&!!A().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:CK}));!t&&!e.shouldStop();){if(!r()||(await hi(CK,e.shouldStop),e.shouldStop()))return;t=await $p()}if(!t||e.shouldStop())return;let n=XM(process.env,A()),o=new Yp;t.security&&(t.security.childEnv=await mK().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:rc(t.chatProvider),useClaudeOauth:t.useClaudeOauth,turnSignature:n,credentialStore:El(),childEnvSafe:t.security?.childEnv?.ok??null,auth:t.auth?.describe().kind??"api_key"}));let s=0,i=0,a=new Up,l=bK({target:t,capabilities:u=>{let d=A(),f=sr(d);return rc(f,yi(d),rf(f,d),t.security?.report({policy:n,auth:u.kind,credentialStore:El(),folderSandbox:Ef(process.env,d)}),Df(),um(),cm())},onBeat:u=>LW({pid:process.pid,runtimeVersion:Ze,at:new Date().toISOString(),heartbeatOk:u,chatTurns:Math.max(0,s-i),commandTurns:i})}),c=Promise.resolve();for(;!e.shouldStop();)try{if(s>=Gie){await hi(250,e.shouldStop);continue}let u=await SK(t,e.shouldStop,a.snapshot(),n);if(u==="no_credential"){console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:"machine_not_linked"})),await hi(xK,e.shouldStop);continue}if(u==="auth_error"){a.onAuthError();let d=t.auth?.describe().hasBoxCredential===!0;await hi(d?5e3:xK,e.shouldStop);continue}if(a.onSuccess(),u){let d=await yK(t,u.turnId);if(!hK(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=()=>Xb(t,u);m=c.then(g,g),c=m.then(()=>{},()=>{})}else{let g=await Yb(t,u,{policy:n,nonces:o});if(!g.ok){s-=1;continue}if(o.markStarted(u.turnId),f==="browser"){let h=await Po(t);m=zW({...t,apiKey:h.bearer},{turnId:u.turnId,payload:g.payload})}else f==="secret"?m=uK(h=>Ee(t,u.turnId,h),{turnId:u.turnId,payload:g.payload},{agentOsId:t.agentOsId,boxId:t.boxId}):f==="agent-tab"?m=gF(h=>Ee(t,u.turnId,h),{turnId:u.turnId,payload:g.payload,boxId:t.boxId},{late:bL(t),redactor:tr(t.agentOsId)}):m=Wv(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=_M(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 hi(m,e.shouldStop)}l(),await NW(),console.error(JSON.stringify({event:"chat_claim_loop_stop"}))}var xK,CK,Gie,EK=p(()=>{"use strict";$();Gv();hF();NR();un();BW();BR();FR();XW();dK();Hr();WR();gK();Fp();Kl();kK();vK();Dl();En();zp();Hb();Hp();Kv();_K();Qb();Al();nf();zb();xK=6e4,CK=5*6e4,Gie=3});var AK=p(()=>{"use strict";Fp();Hp();zb();Qb();Kv();EK()});import{createHash as Jie}from"node:crypto";import{chmodSync as IK,existsSync as qie,mkdirSync as Yie,rmSync as PK}from"node:fs";import{createConnection as zie,createServer as Xie}from"node:net";import{homedir as Qie,userInfo as Zie}from"node:os";import eae from"node:path";function rae(e,t=process.platform){return t==="win32"?`\\\\.\\pipe\\kynver-site-logins-${Jie("sha256").update(`${Zie().username}:${Qie()}`).digest("hex").slice(0,16)}`:eae.join(e,"control.sock")}async function nae(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 z?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 oae(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 OK(e){let t=rae(e.rootDir);if(process.platform!=="win32"){Yie(e.rootDir,{recursive:!0,mode:448});try{IK(e.rootDir,448)}catch{}if(qie(t)){if(await sae(t))return null;PK(t,{force:!0})}}let r=Xie(n=>{let o="";n.setEncoding("utf8"),n.setTimeout(12e4,()=>n.destroy()),n.on("data",s=>{if(o+=s,o.length>tae)return void n.destroy();let i=o.indexOf(`
|
|
549
|
-
`);if(i<0)return;let a=
|
|
550
|
-
`);if(!a)return l({ok:!1,error:"malformed request"});nae(e,a).then(l).catch(c=>l({ok:!1,error:c instanceof z?c.message:"the request failed",code:c instanceof z?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{IK(t,384)}catch{}return{path:t,close:()=>new Promise(n=>{r.close(()=>n()),process.platform!=="win32"&&PK(t,{force:!0})})}}function sae(e){return new Promise(t=>{let r=zie(e),n=o=>{r.destroy(),t(o)};r.once("connect",()=>n(!0)),r.once("error",()=>n(!1)),setTimeout(()=>n(!1),1e3).unref?.()})}var tae,TK=p(()=>{"use strict";ln();tae=16*1024});function lae(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":Ei(e.platform,e.arch)?null:"unsupported_platform"}async function NK(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 DK(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??(()=>Wo({env:t,platform:r,arch:n})),a=e.loadConfig??A;try{await NK(e.startDelayMs??iae,e);for(let l=1;l<=aae&&!e.shouldStop();l+=1){let c=lae({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=RW(Ko());if(u>o()&&await NK(u-o(),e),e.shouldStop())return;s({event:"browser_autoprovision_start",attempt:l});try{let d=await(e.provision??tm)({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 iae,aae,MK=p(()=>{"use strict";$();Uo();Ql();rm();iae=6e4,aae=5});function $R(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(e.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function pae(e,t){let r=$R(e),n=$R(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 fae(e,t,r={}){let n=r.manual??`${dm} 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 mae(){try{let e=sm();return{manual:am(e,"latest"),selfUpdate:!e.unsupportedReason}}catch{return{manual:`${dm} then restart Kynver (or restart the computer)`,selfUpdate:!1}}}async function gae(e={}){let t=e.installed??Ze,r={installed:t,latest:null,outdated:!1,command:dm};if((e.env??process.env).KYNVER_DISABLE_UPDATE_CHECK==="1")return r;let o=new AbortController,s=setTimeout(()=>o.abort(),uae);try{let a=await(e.fetch??fetch)(cae,{signal:o.signal,headers:{accept:"application/json"}});if(!a.ok)return r;let l=await a.json(),c=typeof l?.version=="string"&&$R(l.version)?l.version:null;return c?{installed:t,latest:c,outdated:pae(t,c),command:dm}:r}catch{return r}finally{clearTimeout(s)}}function BK(e={}){let t=e.log??(s=>console.error(s)),r=null,n=async()=>{let s=await gae(e);if(s.outdated&&s.latest&&s.latest!==r){r=s.latest;let i=(e.advice??mae)();t(JSON.stringify({event:"runtime_update_available",installed:s.installed,latest:s.latest,command:i.manual,selfUpdate:i.selfUpdate})),t(fae(s.installed,s.latest,i))}return s};n().catch(()=>{});let o=setInterval(()=>{n().catch(()=>{})},e.intervalMs??dae);return o.unref?.(),{stop:()=>clearInterval(o),checkNow:n}}var LK,dm,cae,uae,dae,UK=p(()=>{"use strict";un();LR();im();LK="@kynver-app/runtime",dm=`npm install -g ${LK}@latest`,cae=`https://registry.npmjs.org/${LK}/latest`,uae=5e3,dae=360*6e4});var $K={};sw($K,{adoptOrAcquireOwnerLease:()=>WK,completeWorker:()=>fO,dispatchRun:()=>ti,resolveDaemonOwnerKind:()=>FK,runDaemon:()=>KK,runPipelineTick:()=>Dp,sweepRun:()=>pp});async function HR(e,t,r){let n=e;for(;n>0&&!t();){let o=Math.min(bae,n),s=Date.now();await hc(o);let i=rh(o,Date.now()-s);if(i!==null){r?.(i);return}n-=o}}function FK(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 WK(e,t,r,n=Iu){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 KK(e,t={}){let r=gh({hostCapability:t.hostCapability}),n=st()?{loaded:0}:jS();n.loaded>0&&console.error(JSON.stringify({event:"daemon_env_file_loaded",...n}));let o=String(e.run||"").trim();o||(console.error(lh("--run")),process.exit(1));let s=String(e.agentOsId||A().agentOsId||"").trim();s||(console.error(lh("--agent-os-id")),process.exit(1)),gs(s).ok||(console.error(hg(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)):hae,c=!1,u=0,d=U_(M=>{c||console.error(JSON.stringify({event:"daemon_stop_requested",reason:M,runId:o})),c=!0}),f=await WK(s,FK(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;QS(m.metadata.ownerKind),jC({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=UC(o);h.killed.length>0&&console.error(JSON.stringify({event:"daemon_orphaned_worker_descendants_killed",runId:o,orphans:h.killed.map(M=>({worker:M.workerName,workerPid:M.workerPid,pid:M.orphanPid,outcome:M.result.outcome}))}));let y=null,b=M=>{y=M};try{let M=I_();(M.moved.length>0||M.stillInFile.length>0)&&console.error(JSON.stringify({event:"daemon_credentials_store",...M}))}catch(M){console.error(JSON.stringify({event:"daemon_credentials_store_error",error:M instanceof Error?M.message:String(M)}))}let k=RC();k.remediated&&console.error(JSON.stringify({event:"daemon_default_repo_remediated",defaultRepo:k.resolved?.defaultRepo??null,configPath:k.configPath}));let v=LC(A());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})),BK();let S=vs(),w=new Bp;w.start();let _=new Lp({agentOsId:s,init:{ownerKind:m.metadata.ownerKind,admission:r.allowed?{basis:r.basis,hostCapability:r.hostCapability}:null}});w.setTickIsolation(_.mode),console.error(JSON.stringify({event:"daemon_tick_isolation",mode:_.mode,reason:_.reason}));let R=OK(Qe()).catch(()=>null),O=KR({shouldStop:()=>c}).catch(M=>{console.error(JSON.stringify({event:"chat_claim_loop_crashed",error:M instanceof Error?M.message:String(M)}))});DK({shouldStop:()=>c});let j=!1;for(;!c;)try{if(y!==null){let T=y;y=null;let C=m.isHeld();if(console.error(JSON.stringify({event:"daemon_resume_detected",agentOsId:s,gapMs:T,ownerLeaseHeld:C})),!C){console.error(JSON.stringify({event:"daemon_owner_lease_lost",agentOsId:s,runId:o})),process.exitCode=1,c=!0;break}}w.setPhase("heartbeat"),m.renew(),zx({agentOsId:s,runId:o,instructionBundleVersion:ro(),owner:g}),w.setPhase("runner_credential");let M=await cu(e.secret?String(e.secret):void 0,s,{baseUrl:e.baseUrl?String(e.baseUrl):void 0});if(!M.ok){j||(j=!0,console.error(JSON.stringify({event:"daemon_runner_credential_missing",agentOsId:s,reason:M.reason,remedy:`run \`kynver runner credential --agent-os-id ${s}\` (or \`kynver bootstrap\`); ticks resume automatically once the credential exists`}))),w.setPhase("idle"),await HR(l,()=>c,b);continue}j&&(j=!1,console.error(JSON.stringify({event:"daemon_runner_credential_recovered",agentOsId:s}))),w.setPhase("instruction_bundle"),await NC({agentOsId:s,baseUrl:Yn(e.baseUrl?String(e.baseUrl):void 0),secret:M.secret}),w.setPhase(_.mode==="thread"?"pipeline_tick_thread":"pipeline_tick_inline");let N=await _.runTick({run:o,agentOsId:s,execute:a,...e,secret:typeof e.secret=="string"&&e.secret?e.secret:M.secret},w.report());w.setTickIsolation(N.isolation);let L=N.tick;w.setPhase("tick_log"),console.error(JSON.stringify({event:"daemon_tick",tickIsolation:N.isolation,...L})),w.setPhase("runtime_control");let V=rn(s),W=N.inFlightWorkers??Mp(s)??0;if(zS(V,W)){let T=qc({control:V,supervisor:m.metadata.ownerKind,inFlightWorkers:0,exiting:!0}),C=Yn(e.baseUrl?String(e.baseUrl):void 0),D=T&&C?await Vx({baseUrl:C,agentOsId:s,secret:M.secret},T):!1;console.error(JSON.stringify({event:"daemon_runtime_stopped",agentOsId:s,runId:o,policyVersion:V?.policyVersion??null,requestedBy:V?.requestedByLabel??null,reported:D})),process.exitCode=Jc,c=!0;break}if(S.tickEnabled){w.setPhase("cron_tick");let T=Uu(o);if(T&&!T.authorized)console.error(JSON.stringify({event:"daemon_cron_tick_skipped",reason:"mesh_cron_lease_not_authorized",holderBoxId:T.holderBoxId}));else{let C=await Rh({env:S,agentOsIdFilter:s});C.enabled&&(C.fired>0||C.errors>0||C.lockHeld)&&console.error(JSON.stringify({event:"daemon_cron_tick",...C}))}}L.idle?u++:u=0;let F=Math.floor(_s("daemon.maxIdleStreak",kae)),x=Math.floor(_s("daemon.idleIntervalMs",yae)),G=u>=F?x:l;w.setPhase("idle"),await HR(G,()=>c,b)}catch(M){console.error(JSON.stringify({event:"daemon_tick_error",error:M.message})),w.setPhase("idle"),await HR(l,()=>c,b)}w.setPhase("stopping"),await O,await _.close(),w.stop(),await(await R)?.close().catch(()=>{}),Qe().lock();let P=F_(o);P.length>0&&console.error(JSON.stringify({event:"daemon_stop_worker_trees_killed",runId:o,workers:P.map(M=>({worker:M.workerName,pid:M.pid,outcome:M.result.outcome}))})),d(),m.release(),console.error(JSON.stringify({event:"daemon_stop",runId:o,agentOsId:s}))}var hae,yae,kae,bae,jR=p(()=>{"use strict";$();ch();wC();DC();dn();BC();th();mu();Pu();Ot();nh();FC();Lu();hh();wh();Er();Rr();Sh();B();gM();Ab();yM();AK();bs();TK();MK();UK();nn();eh();Eb();kd();Lk();Qs();hae=6e4,yae=5*6e4,kae=10,bae=250});var HK=p(()=>{"use strict";Z();Qo();Dk();Ie();B()});var nc,jK=p(()=>{"use strict";nc=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 vae,mkdirSync as Rae}from"node:fs";import wae from"node:path";function Sae(e){let t=typeof e.repo=="string"?e.repo.trim():"";if(t)return t;let r=va();return r?r.repo:(Tt("","--repo (or set defaultRepo via `kynver setup` / KYNVER_DEFAULT_REPO)"),"")}function _ae(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}`};let l=e.resolveLocalOnlyBranch?.()?.trim();if(l&&e.verifyRef(l))return{base:l,source:"local-branch",note:`${t} has no git remote \u2014 cutting the run from the local branch ${l}`};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 xae(e){let t=re(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=re(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 Cae(e){let t=re(e,["remote"]);if(t.status!==0||t.stdout.trim())return null;let r=re(e,["symbolic-ref","--quiet","--short","HEAD"]);return(r.status===0?r.stdout.trim():"")||"main"}function Eae(e,t){let r=A();try{return _ae({explicitBase:typeof t.base=="string"?t.base:void 0,envBaseRef:process.env.KYNVER_RUN_BASE_REF,configDefaultBase:r.defaultBase,verifyRef:n=>re(e,["rev-parse","--verify","--quiet",`${n}^{commit}`]).status===0,resolveRemoteHeadRef:()=>xae(e),resolveLocalOnlyBranch:()=>Cae(e),repoLabel:e})}catch(n){throw new nc(n.message,{remedy:"Diagnose: run `kynver doctor runner-install`.",cause:n})}}function VR(e){let t=$P(Sae(e));kw(t);let r=e.id?Vy(String(e.id)):pc(String(e.name||"run")),n=q(r);vae(n)&&Aae(`run already exists: ${r}`),Rae(n,{recursive:!0});let o=Eae(t,e);o.note&&console.error(o.note);let s=o.base,i=de(t,["rev-parse",s]).trim(),a=Jt(),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}:{}};we(wae.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 Aae(e){throw new nc(e)}var GR=p(()=>{"use strict";_e();Z();HK();B();As();Gd();jn();$();jK()});function VK(e,t){return e.filter(n=>n.repo===t&&!jr.has(n.status)).sort((n,o)=>(o.createdAt??"").localeCompare(n.createdAt??""))[0]??null}var GK=p(()=>{"use strict";_e();Rn()});var JK=p(()=>{"use strict";Er();Rs();vh()});var pm=p(()=>{"use strict";Er();Rr()});var fm=p(()=>{"use strict"});var JR=p(()=>{"use strict"});var qR=p(()=>{"use strict";JK();Er();Rs();pm();Rr();fm();JR()});var qK=p(()=>{"use strict"});var YK=p(()=>{"use strict";pm();fm()});var zK=p(()=>{"use strict";Rr();Er()});var XK=p(()=>{"use strict";$();gt();Ot();B();wh();qK();YK();Rr();pm();zK();Gc();ls();Rs();qR();fm();JR();Z()});var QK=p(()=>{"use strict";qR();XK()});import{homedir as Dae}from"node:os";import Mae from"node:path";var I2e,P2e,ZK=p(()=>{"use strict";I2e=Mae.join(Dae(),".kynver","logs","kynver.log"),P2e=10*6e4});var e$=p(()=>{"use strict";Im();En()});var t$=p(()=>{"use strict";e$()});var r$=p(()=>{"use strict";ls();Gc();$();Rr();Yc();rg();na();Z()});function n$(e,t){return VK(e,t)?.id??null}var o$=p(()=>{"use strict";$();jg();jR();ch();hh();Pu();GR();Z();GK();As();QK();Zg();ig();As();En();ZK();t$();r$()});var c$={};sw(c$,{prepareDesktopRuntime:()=>Jae,resolveDesktopRepository:()=>l$});import{spawnSync as s$}from"node:child_process";import{randomBytes as Lae}from"node:crypto";import{existsSync as Bae,mkdirSync as Uae,readFileSync as Fae,realpathSync as i$,statSync as Wae,writeFileSync as Kae}from"node:fs";import{homedir as $ae}from"node:os";import zR from"node:path";function Se(e,t){return{ok:!1,code:e,message:t}}function Hae(){return zR.join($ae(),".kynver","desktop-binding.json")}function jae(e){if(!Bae(e))return null;try{let t=JSON.parse(Fae(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 Vae(e,t){Uae(zR.dirname(e),{recursive:!0}),Kae(e,`${JSON.stringify(t,null,2)}
|
|
551
|
-
`,{mode:384})}function a$(e,t){return e===401||e===403?Se("access_denied",`${t} was refused (${e})`):e===0?Se("network",`${t} could not reach Kynver`):Se("server_error",`${t} failed (${e})`)}async function YR(e,t,r,n={}){try{let o=await kt(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 Gae(e){return(e?.accessibleItems??[]).filter(t=>t.access?.isOwner===!0&&typeof t.agentOs?.id=="string").map(t=>(t.agentOs?.id).trim()).filter(Boolean)}function l$(e,t="git"){let r=s$(t,["--version"],te({encoding:"utf8"}));if(r.error||r.status!==0)return Se("no_git","Git is not installed or not on PATH");let n;try{if(n=i$.native(zR.resolve(e)),!Wae(n).isDirectory())return Se("not_a_repository","The selected path is not a folder")}catch{return Se("not_a_repository","The selected folder does not exist")}let o=s$(t,["rev-parse","--is-bare-repository","--show-toplevel"],te({cwd:n,encoding:"utf8"})),s=(o.stdout??"").trim().split(/\r?\n/);if(o.status!==0||s[0]!=="false"||!s[1])return Se("not_a_repository","The selected folder is not inside a Git working tree");try{return{ok:!0,repo:i$.native(s[1].trim())}}catch{return Se("not_a_repository","The Git working tree root could not be resolved")}}async function Jae(e,t={}){let r=t.fetchImpl??fetch,n=t.acquireOwnerLease??Iu,o=t.bindingPath??Hae(),s=[],i=gr(e.apiBaseUrl);if(!i)return Se("invalid_input","apiBaseUrl is required");let a=Hi(i),l=new URL(a).origin;if(e.agentOsId!==void 0&&!gs(e.agentOsId).ok)return Se("invalid_input","agentOsId is not a valid workspace id");let c;try{c=Ce()}catch(w){if(w instanceof Mi)return Se("credentials_unavailable","This computer's credentials have not been provided");throw w}if(!c)return Se("credentials_unavailable","This computer is not paired");let u=await YR(`${a}/api/users/me`,c,r);if(u.status!==200)return a$(u.status,"Account lookup");let d=typeof u.body?.id=="string"?u.body.id:"";if(!d)return Se("server_error","Account lookup returned no account id");if(e.expectedAccountId&&e.expectedAccountId!==d)return Se("account_mismatch","The paired credentials belong to a different account");let f=await YR(`${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 YR(`${a}/api/agent-os`,c,r);if(g.status!==200)return a$(g.status,"Workspace lookup");let h=g.body,y;if(e.agentOsId){if(!Gae(h).includes(e.agentOsId))return Se("agent_os_not_owned","That workspace is not owned by the paired account");y=e.agentOsId}else{let w=$g(h);if(!w?.id)return Se("no_workspace","No workspace owned by this account was found");y=w.id}let b=l$(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{He({...A(),apiBaseUrl:a,agentOsId:y,defaultRepo:k});let w=Qg(A());s.push(...w.warnings);let _=A().boxId?.trim()??"";if(!_)return S.release(),Se("local_state_error","Box identity could not be established");if(await Vg(cn()),!Le(y))try{let N=await zn(y,{baseUrl:a,apiKey:c});qn(y,N)}catch(N){let L=N.message;if(xx(L)==="access_denied")return S.release(),Se("access_denied","This computer was refused a runner credential");s.push("runner credential mint did not succeed yet; the runtime retries automatically")}let R=jae(o),O=R!==null&&R.cloudOrigin===l&&R.accountId===d&&R.agentOsId===y&&R.repo===k,j="";if(O){let N=n$(xe().filter(L=>L.id===R.runId),k);N&&(j=N)}if(!j){let N=`${pc("desktop")}-${Lae(3).toString("hex")}`;j=VR({repo:k,name:"desktop",id:N}).runId}Vae(o,{version:1,cloudOrigin:l,accountId:d,agentOsId:y,repo:k,runId:j});let P=bu(k);P||s.push("the repository has no origin remote; nothing can run until it has one");let{runnerId:M}=Ue({runId:j});return{ok:!0,prepared:{accountId:d,agentOsId:y,runId:j,repo:k,boxId:_,repoIdentity:P,runnerId:M},lease:S,warnings:s}}catch(w){return S.release(),Se("local_state_error",w.message)}}var u$=p(()=>{"use strict";hr();jg();Hg();$();Ot();Er();Rs();Pu();vu();Z();Ir();Zg();o$();GR();B()});Ot();import{pathToFileURL as qae}from"node:url";var dw="credential.persist";function pw(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:dw,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:dw,kind:"runnerToken",agentOsId:a,value:l})},reseed:o}}mu();vu();ln();_u();var fx=/^lg_[a-z0-9]{6,20}$/,eG=/^cr_[0-9a-f]{12}$/,tG=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),to=(e,t,r=1)=>typeof e=="string"&&e.length>=r&&e.length<=t&&!e.includes("\0");function ks(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function mx(e){let t=["v","type","id","agentOsId","op"];switch(e.op){case"key":return ks(e,[...t,"key"])??(to(e.key,64,40)&&/^[A-Za-z0-9+/]{43}=$/.test(e.key)?{op:"key",key:e.key}:"invalid key");case"list":case"wipe":return ks(e,t)??{op:e.op};case"remove":return ks(e,[...t,"handle"])??(typeof e.handle=="string"&&fx.test(e.handle)?{op:"remove",handle:e.handle}:"invalid handle");case"code":{let r=ks(e,[...t,"requestId","code"]);return r||(e.requestId!==void 0&&!(typeof e.requestId=="string"&&eG.test(e.requestId))?"invalid requestId":to(e.code,16)?{op:"code",code:e.code,...e.requestId?{requestId:e.requestId}:{}}:"invalid code")}case"add":{let r=ks(e,[...t,"login","replaceHandle"]);if(r)return r;let n=e.login;return!tG(n)||ks(n,["origin","label","username","password","totp"])||!to(n.origin,2048)||!to(n.label,Ve.maxLabel)||!to(n.username,Ve.maxUsername)||!to(n.password,Ve.maxPassword)||n.totp!==void 0&&!to(n.totp,Ve.maxTotp,0)?"invalid login":e.replaceHandle!==void 0&&!(typeof e.replaceHandle=="string"&&fx.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 gx(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 z)||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 z("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)}}}bs();ln();var Yae=1,mm=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Di=/^[A-Za-z0-9_-]{1,64}$/,zae=/^[a-z0-9][a-z0-9._-]{0,127}$/i,d$=4096,Xae=4096,Qae=16;function XR(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function oc(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function sc(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!e.includes("\0")}function Zae(e){if(!sc(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 ele(e){if(!XR(e))return{ok:!1,message:"message must be an object"};if(e.v!==Yae)return{ok:!1,message:"unsupported protocol version"};let t=r=>({ok:!1,message:r});switch(e.type){case"credentials":{let r=oc(e,["v","type","apiKey","runnerTokens"]);if(r)return t(r);if(e.apiKey!==void 0&&!sc(e.apiKey,d$))return t("invalid apiKey");let n;if(e.runnerTokens!==void 0){if(!XR(e.runnerTokens))return t("invalid runnerTokens");let o=Object.entries(e.runnerTokens);if(o.length>Qae)return t("too many runnerTokens");n={};for(let[s,i]of o){if(!mm.test(s)||!sc(i,d$))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=oc(e,["v","type","id","apiBaseUrl","repo","agentOsId","expectedAccountId"]);return r?t(r):typeof e.id!="string"||!Di.test(e.id)?t("invalid id"):Zae(e.apiBaseUrl)?sc(e.repo,Xae)?e.agentOsId!==void 0&&(typeof e.agentOsId!="string"||!mm.test(e.agentOsId))?t("invalid agentOsId"):e.expectedAccountId!==void 0&&!sc(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=oc(e,["v","type","id","policy"]);if(r)return t(r);if(typeof e.id!="string"||!Di.test(e.id))return t("invalid id");let n=G_(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=oc(e,["v","type","id","runId","agentOsId"]);return r?t(r):typeof e.id!="string"||!Di.test(e.id)?t("invalid id"):typeof e.runId!="string"||!zae.test(e.runId)?t("invalid runId"):typeof e.agentOsId!="string"||!mm.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"||!Di.test(e.id))return t("invalid id");if(typeof e.agentOsId!="string"||!mm.test(e.agentOsId))return t("invalid agentOsId");let r=mx(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=oc(e,["v","type","id"]);return r?t(r):typeof e.id!="string"||!Di.test(e.id)?t("invalid id"):{ok:!0,value:{v:1,type:e.type,id:e.id}}}default:return t("unknown message type")}}function tle(e){return XR(e)&&typeof e.id=="string"&&Di.test(e.id)?e.id:null}function rle(e){let t=cw()?"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(Rg(l))return;let c=ele(l);if(!c.ok){s(tle(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=pw(d,f=>e.send(f)),lw(r)),t==="awaiting_credentials"&&(t="ready"),e.send({v:1,type:"event",name:"credentials_accepted",state:t});return}case"status":{let d=Eg();i(u.id,{state:t,prepared:n,policyRevision:d?.revision??null});return}case"policy":{if(!Y_(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,z_({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=Eg();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 gx(Qe(),g,h))}catch(y){let b=y instanceof z?y.code:"failed";s(m,`site_login_${b}`,y instanceof z?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 nle(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}aw();for(let s of iw)delete e.env[s];let[{prepareDesktopRuntime:t},{runDaemon:r}]=await Promise.all([Promise.resolve().then(()=>(u$(),c$)),Promise.resolve().then(()=>(jR(),$K))]),n=s=>{if(!e.connected||typeof e.send!="function")throw new Error("desktop IPC channel is closed");e.send(s)},o=rle({send:n,prepare:s=>t(s),runDaemon:r,requestDaemonStop:()=>{e.emit("message",{type:fu},void 0)},exit:s=>e.exit(s),daemonExitCode:()=>typeof e.exitCode=="number"?e.exitCode:0});X_(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{}}),Qe().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:fu},void 0);return}e.exit(0)}),n({v:1,type:"event",name:"ready",state:o.state})}function ole(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===qae(e).href}catch{return!1}}ole()&&nle();export{Yae as DESKTOP_ENTRY_PROTOCOL_VERSION,rle as createDesktopEntryController,ele as parseDesktopEntryMessage,nle as startDesktopEntry};
|
|
546
|
+
${s.stderr??""}`;for(let a of ec(i))n.add(a);s.status===0&&(o=ase(i))}return{version:o,missingLibs:[...n].sort()}}function bW(e,t=()=>lse(e),r=Date.now){let n=IR.get(e);if(n&&r()-n.at<cse)return n.health;let o=t();return IR.set(e,{at:r(),health:o}),o}function vW(){IR.clear()}var ise,cse,IR,PR=p(()=>{"use strict";sm();ise=(e,t,r)=>sse(e,t,r);cse=10*6e4,IR=new Map});import{chmodSync as use,mkdirSync as OR,symlinkSync as dse,writeFileSync as pse}from"node:fs";import Ii from"node:path";import{crc32 as fse,inflateRawSync as mse}from"node:zlib";function kse(e){let t=Math.max(0,e.length-65535-22);for(let r=e.length-22;r>=t;r-=1)if(e.readUInt32LE(r)===gse)return r;throw new Error("not a zip archive (no end-of-central-directory record)")}function bse(e){let t=kse(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)!==hse)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 vse(e,t){let r=t.localHeaderOffset;if(e.readUInt32LE(r)!==yse)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=mse(o);else throw new Error(`unsupported zip compression method ${t.method} (${t.name})`);if(s.length!==t.size||fse(s)>>>0!==t.crc>>>0)throw new Error(`zip entry failed its integrity check: ${t.name}`);return s}function RW(e,t){let r=t.replace(/\\/g,"/");if(r.startsWith("/")||/^[a-zA-Z]:/.test(r))throw new Error(`unsafe zip path: ${t}`);let n=Ii.resolve(e,r),o=Ii.resolve(e);if(n!==o&&!n.startsWith(o+Ii.sep))throw new Error(`unsafe zip path: ${t}`);return n}function wW(e,t,r=process.platform){OR(t,{recursive:!0});let n=0;for(let o of bse(e)){let s=RW(t,o.name);if(o.name.endsWith("/")){OR(s,{recursive:!0});continue}OR(Ii.dirname(s),{recursive:!0});let i=vse(e,o);if(o.unixMode!==null&&(o.unixMode&Rse)===wse&&r!=="win32"){let a=i.toString("utf8");RW(t,Ii.posix.join(Ii.posix.dirname(o.name.replace(/\\/g,"/")),a)),dse(a,s)}else pse(s,i),o.unixMode!==null&&r!=="win32"&&use(s,o.unixMode&511||420);n+=1}return n}var gse,hse,yse,Rse,wse,SW=p(()=>{"use strict";gse=101010256,hse=33639248,yse=67324752;Rse=61440,wse=40960});import{closeSync as _W,existsSync as TR,mkdirSync as Sse,openSync as xW,readFileSync as _se,renameSync as xse,rmSync as Pi,statSync as Cse,chmodSync as Ese}from"node:fs";import NR from"node:path";function $o(){return{...Vt}}function AW(e=Vt){return e.state!=="failed"||e.failedAt===null?0:e.failedAt+CW[Math.min(e.attempts-1,CW.length-1)]}function IW(e=Vt){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 Ise(e){let t=A();je({...t,browserManaged:{version:e.version,platform:e.platform,executable:e.executable,installedAt:new Date().toISOString()}})}function Pse(e,t){wW(_se(e),t)}function Ose(e,t){try{return _W(xW(e,"wx")),!0}catch{try{if(t-Cse(e).mtimeMs>Ase)return Pi(e,{force:!0}),_W(xW(e,"wx")),!0}catch{}return!1}}async function Tse(e,t){let r=t.env??process.env,n=t.now??Date.now,o=t.sleep??(a=>new Promise(l=>setTimeout(l,a))),s=rm(r);Sse(s,{recursive:!0});let i=NR.join(s,".install.lock");for(;!Ose(i,n());)if(await o(2e3),!TR(i)){let a=om(e,r);if(a)return a}try{let a=await gW(e,t.fetchFn),l=dW(a.version,r),c=nm(l,e);if(!TR(c)){let d=NR.join(s,`.download-${a.version}.zip`),f=NR.join(s,`.staging-${a.version}-${process.pid}`);Pi(f,{recursive:!0,force:!0});try{await hW(a.url,d,{fetchFn:t.fetchFn,minBytes:t.minArchiveBytes,onProgress:g=>{Vt.receivedBytes=g.receivedBytes,Vt.totalBytes=g.totalBytes}}),(t.extract??Pse)(d,f);let m=nm(f,e);if(!TR(m))throw new Error("the downloaded browser archive did not contain Chrome");(t.platform??process.platform)!=="win32"&&Ese(m,493),Pi(l,{recursive:!0,force:!0}),xse(f,l)}finally{Pi(d,{force:!0}),Pi(f,{recursive:!0,force:!0})}}let u={executable:c,version:a.version,installDir:l};return(t.record??Ise)({...u,platform:e}),u}finally{Pi(i,{force:!0})}}function im(e={}){if(tc)return tc;let t=Ai(e.platform??process.platform,e.arch??process.arch);if(!t)return Promise.reject(new Oi("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 Vt={...Vt,state:"downloading",receivedBytes:0,totalBytes:null,error:null},tc=Tse(t,e).then(n=>(Vt={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},vW(),n)).catch(n=>{let o=n instanceof Error?n.message:String(n);throw Vt={...Vt,state:"failed",error:o.slice(0,300),failedAt:r(),attempts:Vt.attempts+1},new Oi(`Couldn't download a browser for this computer: ${o.slice(0,200)}`,"download_failed")}).finally(()=>{tc=null}),tc}var EW,Ase,CW,Oi,Vt,tc,am=p(()=>{"use strict";$();Fo();yW();PR();AR();SW();EW=150,Ase=30*6e4,CW=[6e4,5*6e4,30*6e4,120*6e4],Oi=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserProvisionError"}code},Vt={state:"idle",receivedBytes:0,totalBytes:null,error:null,failedAt:null,attempts:0},tc=null});function Mse(){let e=$o(),t=e.state==="downloading"?` (${IW(e)})`:"";return`Setting up a browser on your computer \u2014 a one-time download of about ${EW} MB${t}. Tell the user it's being set up, wait about 30 seconds, then try the same step again.`}async function PW(e={}){let t=(e.resolve??(()=>Ko()))();if(t.executable)return t.executable;if(!(e.autoProvision??A().browserAutoProvision!==!1))throw new zr("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??$o)(),o=(e.now??Date.now)();if(n.state==="failed"&&n.failedAt!==null&&o-n.failedAt<Dse)throw new zr(`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??im)(),i,a=new Promise(l=>{i=setTimeout(()=>l("pending"),e.waitMs??Nse),i.unref?.()});try{let l=await Promise.race([s,a]);if(l==="pending")throw s.catch(()=>{}),new zr(Mse(),"browser_installing");return l.executable}catch(l){if(l instanceof zr)throw l;let c=l instanceof Oi?l.message:"Couldn't set up a browser on this computer.";throw new zr(`${c} The user can run \`kynver browser install\` on that computer to retry, or install Google Chrome.`,"chrome_not_found")}finally{clearTimeout(i)}}var Nse,Dse,zr,OW=p(()=>{"use strict";$();Zl();am();Nse=2e4,Dse=6e4,zr=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserEnsureError"}code}});function DR(e){return Lse.test(e)}function TW(e=process.platform,t=typeof process.getuid=="function"?process.getuid():null){return e==="linux"&&t===0}function lm(e){NW=e}function DW(){return NW}var Lse,NW,MR=p(()=>{"use strict";Lse=/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;NW=null});import{spawn as Bse}from"node:child_process";import{existsSync as gje,mkdirSync as Use,readFileSync as Fse,rmSync as Wse}from"node:fs";import{homedir as Kse}from"node:os";import MW from"node:path";function Hse(e=process.env){return e.KYNVER_BROWSER_PROFILE_DIR?.trim()||MW.join(Kse(),".kynver","browser-profile")}function LW(e=process.env){return(e.KYNVER_BROWSER_CDP_URL?.trim()||A().browserCdpUrl?.trim()||$se).replace(/\/$/,"")}async function BW(e,t={}){let r=t.env??process.env,n=t.platform??process.platform,o=t.allowNoSandbox??A().browserAllowNoSandbox!==!1;if((t.asRoot??TW(n))&&o){let a=await BR(e,r,n,t,!0);if("wsUrl"in a)return lm("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 LR(a.stderrTail)}let i=await BR(e,r,n,t,!1);if("wsUrl"in i)return lm("on"),i;if(n==="linux"&&o&&DR(i.stderrTail)){let a=await BR(e,r,n,t,!0);if("wsUrl"in a)return lm("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 LR(a.stderrTail)}throw LR(i.stderrTail)}function LR(e){let t=ec(e);return t.length>0?new rc(t):DR(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 BR(e,t,r,n,o){let s=Hse(t);Use(s,{recursive:!0});let i=MW.join(s,"DevToolsActivePort");Wse(i,{force:!0});let a=tm(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??Bse)(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=>Fse(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 UW(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 $se,rc,FW=p(()=>{"use strict";$();Fo();sm();Zl();MR();$se="http://127.0.0.1:9222";rc=class extends Error{constructor(r){super(`Chrome is missing system libraries: ${r.join(", ")}`);this.missingLibs=r;this.name="ChromeMissingLibsError"}missingLibs}});async function jse(e){if(e==="attach"){let n=LW(),o;try{o=await UW(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 Xl.connect(o),child:null,mode:e}}let t;try{t=await PW()}catch(n){throw n instanceof zr?new Ti(n.message,n.code):n}let r;try{r=await BW(t)}catch(n){throw n instanceof rc?new Ti(kW(n.missingLibs,uW()),"missing_libs"):n}return{conn:await Xl.connect(r.wsUrl),child:r.child,mode:e}}function Vse(){return cm??=new em({connectHost:jse}),cm}async function WW(){cm&&await cm.closeAll().catch(()=>{})}function KW(){try{let e=A();e.browserEverEnabled!==!0&&je({...e,browserEverEnabled:!0})}catch{}}function Mn(e,t){return{ok:!1,code:e,text:t}}function Gse(e){if(!e||typeof e!="object")return null;let t=e,r=t.policy;if(t.kind!=="browser"||!PF(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 $W(e,t){let r=Gse(e);if(!r)return Mn("invalid_request","Malformed browser request.");if(t.localDisabled)return Mn("disabled","The browser is switched off on this computer (local setting browserDisabled).");if(!r.policy.enabled)return Mn("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 Mn("wrong_box","This request reached a different computer than the one the browser is enabled on.");t.onEnabledTurn?.();let n=t.manager??Vse();if(r.action==="list_logins")return ER(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 Mn("action_cap","Too many browser actions in a short time. Pause and summarize progress for the user.");let s=r.action==="wait"?Jf+5e3:DF,i,a=new Promise(d=>{i=setTimeout(()=>d(Mn("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([IF(c)?oW(c,l):ZF(c,l),a]).finally(()=>clearTimeout(i));return{...u,text:qf(u.text)}}catch(o){if(o instanceof Ti)return Mn(o.code,o.message);let s=o instanceof Error?o.message:String(o);return Mn("failed",`Browser action failed: ${s.slice(0,300)}`)}}var Ti,cm,UR=p(()=>{"use strict";RR();sW();kR();iW();aW();$();OW();sm();Fo();FW();Ei();Ti=class extends Error{constructor(r,n){super(r);this.code=n;this.name="BrowserSetupError"}code};cm=null});import{mkdirSync as Jse,readFileSync as Bje,renameSync as qse,writeFileSync as Yse}from"node:fs";import{homedir as zse}from"node:os";import FR from"node:path";function Xse(e=FR.join(zse(),".kynver","state")){return FR.join(e,"chat-loop.json")}function HW(e,t=Xse()){try{Jse(FR.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;Yse(r,JSON.stringify({v:1,...e}),{mode:384}),qse(r,t)}catch{}}var jW=p(()=>{"use strict"});function Qse(e,t,r){if(!t||t===r)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`${n}(?=[\\\\/"'\\s<]|$)`,"gm"),()=>r)}function VW(e,t){return Qse(e,t,"\0")!==e}var GW=p(()=>{"use strict"});import{accessSync as Zse,constants as eie,existsSync as tie,lstatSync as rie,readdirSync as nie,readFileSync as oie,readlinkSync as sie,realpathSync as iie}from"node:fs";import{homedir as aie}from"node:os";import JW from"node:path";function YW(e){return e==="win32"?JW.win32:JW.posix}function cie(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===WR)return n}catch{}let i=r.dirname(n);if(i===n)break;n=i}return null}function die(e,t,r){let n=YW(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 pie(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 fie(e,t,r,n,o){for(let s of pie(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 mie(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 gie(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 um(e={}){let t=e.platform??process.platform,r=YW(t),n=e.fs??lie,o=e.env??process.env,s=e.home??aie(),i=e.execPath??process.execPath,a=n.realpath(e.cliEntry??process.argv[1]??""),l=a?cie(a,n,r):null,c={cliPath:a,packageRoot:l,nodePath:i,npmCliPath:die(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(qW).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=uie.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=fie(d.releaseDir,s,o,n,r);else{let k=/^(.*)[\\/]lib[\\/]node_modules[\\/]@kynver-app[\\/]runtime$/.exec(l),v=t==="win32"?/^(.*)[\\/]node_modules[\\/]@kynver-app[\\/]runtime$/.exec(l):null,y=k?.[1]??v?.[1];y&&!y.split(qW).includes("node_modules")&&(u="npm_global",d.npmPrefix=y)}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(k=>!!k),g="keeper";if(t==="linux"){let k=r.join(s,".config","systemd","user",na);n.exists(k)&&(g="systemd",d.supervisorFile=k,d.supervisorName=na)}else if(t==="darwin"){let k=mie(m,s,n,r);k&&(g="launchd",d.supervisorFile=k.file,d.supervisorName=k.label)}else if(t==="win32"){let k=gie(m,s,n,r);k&&(g="windows_task",d.supervisorFile=k,d.supervisorName=o.KYNVER_WINDOWS_TASK_NAME?.trim()||"Kynver")}let h={...c,kind:u,supervisor:g,...d};return h.unsupportedReason=hie(h,n),h.unsupportedReason||delete h.unsupportedReason,h}function hie(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&&VW(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 WR,lie,qW,uie,dm=p(()=>{"use strict";cs();GW();WR="@kynver-app/runtime",lie={exists:e=>tie(e),readText:e=>{try{return oie(e,"utf8")}catch{return null}},readDir:e=>{try{return nie(e)}catch{return[]}},realpath:e=>{try{return iie.native(e)}catch{return e}},readLink:e=>{try{return rie(e).isSymbolicLink()?sie(e):null}catch{return null}},writable:e=>{try{return Zse(e,eie.W_OK),!0}catch{return!1}}},qW=/[\\/]/;uie=/^(.*)[\\/]releases[\\/]([^\\/]+)[\\/]node_modules[\\/]@kynver-app[\\/]runtime$/});function zW(e){return`npm-${e}`}function pm(e,t="latest"){let r=`${WR}@${t}`;switch(e.kind){case"release_dir":{let n=e.releasesRoot?`${e.releasesRoot}/${zW(t)}`:`<releases>/${zW(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 KR=p(()=>{"use strict";dm()});var XW=p(()=>{"use strict"});import{mkdirSync as Zje,readFileSync as yie,readdirSync as e1e,renameSync as t1e,writeFileSync as r1e}from"node:fs";import QW from"node:path";function kie(){return QW.join(Sl(),"runtime")}function bie(e){return QW.join(e,"summary.json")}function ZW(e=kie()){try{let t=JSON.parse(yie(bie(e),"utf8"));if(t?.v===1)return t}catch{}return{v:1,attempts:0,succeeded:0,rolledBack:0,failed:0,last:null}}var eK=p(()=>{"use strict";Tp();XW()});function Rie(e=Date.now()){if(fm&&e-fm.at<vie)return fm.report;if(!Ni){let o=um();Ni={kind:o.kind,supervisor:o.supervisor,can:!o.unsupportedReason,manual:pm(o,"latest")}}let t=ZW(),r=t.last,n={v:1,installKind:Ni.kind,supervisor:Ni.supervisor,canSelfUpdate:Ni.can,manualCommand:Ni.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 fm={at:e,report:n},n}function mm(){try{return Rie()}catch{return}}var Ni,fm,vie,$R=p(()=>{"use strict";dm();KR();eK();Ni=null,fm=null,vie=3e4});import{readdir as wie,readFile as Sie}from"node:fs/promises";import{sep as _ie}from"node:path";import{fileURLToPath as xie}from"node:url";function Iie(e=import.meta.url){let t;try{t=xie(e)}catch{return"checkout"}return t.split(_ie).includes("node_modules")||t.split("/").includes("node_modules")?"npm":"checkout"}function Pie(e){if(typeof e!="string")return null;let t=e.trim();return t&&t.length<=Aie?t:null}async function Oie(e){try{return Pie(JSON.parse(await Sie(e,"utf8")).version)}catch{return null}}function rK(e){return e.toLowerCase().endsWith(".bak")}function Tie(e,t){if(!e)return t;try{return Ip(t,e)>0?t:e}catch{return e}}async function Nie(e={}){let t={},r=new Set;for(let n of(e.scopeRoots??hD)()){let o=[];try{o=await wie(n)}catch{continue}for(let s of o)rK(s)||/^[a-z0-9][a-z0-9._-]*$/i.test(s)&&r.add(`${tK}${s}`)}try{for(let n of await(e.adopted??vb)())n.packageName.startsWith(tK)&&!rK(n.packageName)&&r.add(n.packageName)}catch{}for(let n of[...r].sort().slice(0,Eie))for(let o of lb(n)){let s=await Oie(o);s&&(t[n]=Tie(t[n],s))}return t}function Die(e){HR||Di&&e-Di.at<Cie||(HR=Nie().then(t=>{Di={at:Date.now(),packages:t}}).catch(()=>{Di={at:Date.now(),packages:Di?.packages??{}}}).finally(()=>{HR=null}))}function gm(e=Date.now()){try{Die(e)}catch{}return{v:1,runtime:{version:et,source:Iie()},packages:{...Di?.packages??{}}}}var tK,Cie,Eie,Aie,Di,HR,jR=p(()=>{"use strict";dn();cb();Rb();ab();tK="@kynver-app/",Cie=10*6e4,Eie=40,Aie=32;Di=null,HR=null});async function nK(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:ip(e.agentOsId,i)})}).catch(()=>{}),s=t.payload?.action;try{let i=await(r.execute??$W)(t.payload,{boxId:e.boxId,agentOsId:e.agentOsId,localDisabled:A().browserDisabled===!0,onEnabledTurn:KW});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 oK=p(()=>{"use strict";$();UR();jr()});import{appendFileSync as Mie,chmodSync as Lie,existsSync as sK,readFileSync as Bie,renameSync as Uie,statSync as Fie}from"node:fs";import Wie from"node:path";function iK(e,t=Ct()){return Wie.join(t,nl(e).replace(/\.vault\.json$/,".audit.jsonl"))}function aK(e,t,r=Ct()){try{tl(r);let n=iK(e,r);sK(n)&&Fie(n).size>Kie&&Uie(n,`${n}.1`),Mie(n,`${JSON.stringify({at:new Date().toISOString(),...t})}
|
|
547
|
+
`,{mode:384});try{Lie(n,384)}catch{}}catch{}}function lK(e,t=50,r=Ct()){let n=iK(e,r);return sK(n)?Bie(n,"utf8").split(`
|
|
548
|
+
`).filter(Boolean).slice(-t).flatMap(o=>{try{return[JSON.parse(o)]}catch{return[]}}):[]}var Kie,cK=p(()=>{"use strict";rl();op();Kie=512*1024});function pK(e,t){return e.report(t)}function Hie(e){return e.state==="none"?ot("login_vault_missing","Saved logins aren't set up on this computer yet. Run `kynver logins setup` (or open the Kynver desktop app), then try again."):e.state==="locked"?ot("login_vault_locked","Saved logins are locked on this computer. Run `kynver logins unlock`, then try again."):null}function jie(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t;for(let n of Object.keys(r))if(!["o","u","p","t","l"].includes(n))return null;return typeof r.o!="string"||typeof r.u!="string"||typeof r.p!="string"||r.t!==void 0&&typeof r.t!="string"||r.l!==void 0&&typeof r.l!="string"?null:{origin:r.o,username:r.u,password:r.p,...r.t?{totp:r.t}:{},...r.l?{label:r.l}:{}}}function Vie(e){let t=(e.label??"").trim().slice(0,Ge.maxLabel);if(t)return t;try{return new URL(e.origin.includes("://")?e.origin:`https://${e.origin}`).hostname.slice(0,Ge.maxLabel)}catch{return"Website login"}}function fK(e,t,r,n){let o=n.store(t.agentOsId),s=n.audit(t.agentOsId);try{switch(e.op){case"login_list":return{ok:!0,logins:o.list(),vault:n.report(t.agentOsId)};case"login_delete":{let i=e.handle;if(typeof i!="string"||!dK.test(i))return ot("invalid_handle","That saved-login handle isn't valid.");let a=o.get(i),l=o.remove(i);return l&&a&&s.record({event:"remove",ok:!0,handle:i,label:a.label,username:a.username,origin:a.origin,code:"chat_card"}),l?{ok:!0,removed:!0}:ot("not_found","No saved login with that handle on this computer.")}case"login_store":{let i=e.requestId;if(typeof i!="string"||!Yd.test(i))return ot("invalid_request","That request id isn't valid.");let a=e.replaceHandle;if(a!==void 0&&!(typeof a=="string"&&dK.test(a)))return ot("invalid_handle","That saved-login handle isn't valid.");let l=Qd(e.envelope);if(!l)return ot("invalid_envelope","The sealed login is malformed.");if(l.kid!==r.fingerprint)return s.record({event:"add",ok:!1,code:"key_mismatch"}),ot("key_mismatch","The login was sealed for a different computer key. Reload the card and try again.");let c=Hie(n.report(t.agentOsId));if(c)return c;let u=n.key(t.agentOsId);if(!u)return ot("login_vault_locked","Saved logins are locked on this computer. Run `kynver logins unlock`, then try again.");let d;try{d=Zd(r.ecdhPrivateKey,l,{agentOsId:t.agentOsId,requestId:i,name:$ie(a)})}catch(h){return s.record({event:"add",ok:!1,code:"open_failed"}),ot("open_failed",h instanceof mt?h.message:"The login could not be opened.")}let f=jie(d);if(d="",!f)return ot("invalid_login","The sealed login has an unexpected shape.");let m={origin:f.origin,label:Vie(f),username:f.username,password:f.password,totp:f.totp,allowLan:!0},g=a?o.replace(u,a,m):o.add(u,m);return f.password="",s.record({event:a?"replace":"add",ok:!0,handle:g.handle,label:g.label,username:g.username,origin:g.origin,code:"chat_card"}),{ok:!0,login:g,...a?{replaced:!0}:{}}}default:return ot("unknown_op","Unknown saved-login operation.")}}catch(i){return i instanceof q?ot(i.code,i.message):ot("store_failed","The saved-login vault on this computer hit an error.")}}var uK,dK,$ie,ot,mK=p(()=>{"use strict";ep();Js();cn();xu();uK="site_login",dK=/^lg_[a-z0-9]{6,20}$/,$ie=e=>e?`${uK}:${e}`:uK,ot=(e,t)=>({ok:!1,code:e,text:t})});function Gt(e,t){return{ok:!1,code:e,text:t}}async function gK(e,t,r={}){let n=e??{};if(typeof n.boxId!="string"||n.boxId!==t.boxId)return Gt("wrong_computer","This request was meant for another computer.");let o;try{o=(r.keys??rp)()}catch(a){return Gt("keys_unavailable",a instanceof Error?a.message:"This computer's secret store isn't available.")}let s=new Ys({agentOsId:t.agentOsId,vaultKey:o.vaultKey,root:r.root}),i=a=>(r.audit??aK)(t.agentOsId,a,r.root);try{switch(n.op){case"describe":return{ok:!0,publicKey:o.publicKeyRaw.toString("base64"),fingerprint:o.fingerprint,keyStore:o.keyStore,secrets:s.list(),siteLogins:pK(r.siteLogins??Ze(),t.agentOsId)};case"login_store":case"login_list":case"login_delete":return fK(n,t,o,r.siteLogins??Ze());case"list":return{ok:!0,fingerprint:o.fingerprint,keyStore:o.keyStore,secrets:s.list(),audit:lK(t.agentOsId,30,r.root)};case"store":{let a=n.name,l=n.requestId;if(!zd(a))return Gt("invalid_name","That secret name isn't allowed.");if(typeof l!="string"||!Yd.test(l))return Gt("invalid_request","That request id isn't valid.");let c=Qd(n.envelope);if(!c)return Gt("invalid_envelope","The sealed value is malformed.");if(c.kid!==o.fingerprint)return i({event:"refused",name:a,ok:!1,via:"chat",requestId:l,code:"key_mismatch"}),Gt("key_mismatch","The value was sealed for a different computer key. Reload the card and try again.");let u;try{u=Zd(o.ecdhPrivateKey,c,{agentOsId:t.agentOsId,requestId:l,name:a})}catch(m){return i({event:"refused",name:a,ok:!1,via:"chat",requestId:l,code:"open_failed"}),Gt("open_failed",m instanceof mt?m.message:"The secret could not be opened.")}let d=typeof n.purpose=="string"?n.purpose:"",f=s.put({name:a,value:u,purpose:d});return u="",ok(t.agentOsId),i({event:f.replaced?"rotate":"store",name:a,handle:f.summary.handle,ok:!0,via:n.via==="settings"?"settings":"chat",requestId:l}),{ok:!0,handle:f.summary.handle,name:a,replaced:f.replaced}}case"delete":{let a=n.handle;if(typeof a!="string"||!eO.test(a))return Gt("invalid_handle","That secret handle isn't valid.");let l=s.remove({handle:a});return ok(t.agentOsId),i({event:"delete",name:l.name,handle:a,ok:!0,via:n.via==="chat"?"chat":"settings"}),{ok:!0,handle:a,name:l.name}}default:return Gt("unknown_op","Unknown secret operation.")}}catch(a){return a instanceof Pe?Gt(a.code,a.message):Gt("store_failed","The secret store on this computer hit an error.")}}var hK=p(()=>{"use strict";cK();ep();jr();rl();op();mK();vs();Js()});async function yK(e,t,r,n={}){let o=t.payload?.op;try{let s=await gK(t.payload,r,n);await e([{seq:0,kind:"final",message:s}]),console.error(JSON.stringify({event:"secret_turn_done",turnId:t.turnId,op:o,ok:s.ok,code:s.ok?null:s.code}))}catch{await Promise.resolve(e([{seq:0,kind:"error",error:"secret_turn_crashed"}])).catch(()=>{}),console.error(JSON.stringify({event:"secret_turn_error",turnId:t.turnId,op:o}))}}var kK=p(()=>{"use strict";hK()});function bK(e=process.env,t={}){let r=t.platform??process.platform,n=A(),o={executable:null,source:"none",version:null,configuredMissing:null};try{o=(t.resolve??(()=>Ko({env:e,platform:r,config:n})))()}catch{}let s={version:null,missingLibs:[]};if(o.executable)try{s=(t.health??(i=>bW(i)))(o.executable)}catch{}return{supported:!0,chromeFound:o.executable!==null,localDisabled:n.browserDisabled===!0,browserSource:o.source,browserVersion:o.version??s.version,provisioning:$o().state,missingLibs:s.missingLibs,wsl:Ql(e,r),headless:tm(e,r),autoProvision:n.browserAutoProvision!==!1,sandbox:DW()}}var vK=p(()=>{"use strict";$();PR();Fo();Zl();am();MR()});function nc(e,t,r,n,o,s,i){return{chatProvider:e,toolCalls:e==="anthropic"||e==="cursor"||e==="gemini"||e==="openai"||e==="codex",runtimePackageVersion:et,browser:bK(),deliveryReceipt:!0,...t?{chatModels:t}:{},...r?{computer:r}:{},...n?{security:n}:{},...o?{agentEngines:o}:{},...s?{packageVersions:s}:{},...i?{selfUpdate:i}:{}}}var VR=p(()=>{"use strict";dn();vK()});import{spawn as Gie}from"node:child_process";async function RK(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=cr(o),i=new Set([...bv,...Em]);return new Promise(a=>{let l="",c=!1,u=m=>{c||(c=!0,clearTimeout(f),a({...m,at:r().toISOString()}))},d;try{d=Gie(t.execPath??process.execPath,["-e",Jie],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 Jie,wK=p(()=>{"use strict";U();No();Wi();Jie="process.stdout.write(JSON.stringify(Object.keys(process.env)))"});function Yie(e){return e>=200&&e<300?"accepted":e===409||e===410?"rejected":e===404||e===405?"unsupported":"unreachable"}function SK(e){return e!=="rejected"}async function _K(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(),qie);try{let a=await gi(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 qr(e,a,l.status),{outcome:Yie(l.status),status:l.status}}catch{}finally{clearTimeout(i)}}return{outcome:"unreachable",status:null}}var qie,xK=p(()=>{"use strict";hi();qie=4e3});async function Qie(e,t,r=fetch){let n=new AbortController,o=setTimeout(()=>n.abort(),Xie);try{let s=await gi(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 qr(e,s,a.status),a.ok}catch{return!1}finally{clearTimeout(o)}}function CK(e){let t=e.intervalMs??zie,r=!1,n=()=>{r||Qie(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 zie,Xie,EK=p(()=>{"use strict";hi();zie=15e3,Xie=5e3});function AK(e){return e==="body"?12e4:32e3}var IK=p(()=>{"use strict"});async function PK(e,t,r,n){let o=A(),s=ir(o),i=await Oo(e);if(!i.bearer)return"no_credential";let a=nc(s,ki(o),sf(s,o),e.security?.report({policy:n,auth:i.kind,credentialStore:Al(),folderSandbox:Pf(process.env,o)}),Uf(),gm(),mm()),l=SL(e.agentOsId);l&&(a.browser.siteLogins=l);let c=i.kind==="box_token"?i.boxId:xl();e.chatProvider=s,e.boxId=c,e.model=Ao(s,o,process.env);let u=new AbortController,d="headers",f=()=>setTimeout(()=>u.abort(),AK(d)),m=f(),g=setInterval(()=>{t()&&u.abort()},500);try{let h=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:Zie,capabilities:a,claimRetries:r}),signal:u.signal});if(h.status===204)return null;if(h.status===401||h.status===403){let y=await h.text().catch(()=>"");return console.error(JSON.stringify({event:"chat_claim_auth_error",status:h.status,bridgeUrl:e.bridgeUrl,agentOsId:e.agentOsId,authKind:i.kind,detail:y.slice(0,200)})),qr(e,i,401),"auth_error"}if(h.status===429)throw new En(h.status);if(!h.ok)throw new En(h.status);d="body",clearTimeout(m),m=f();let k;try{k=await h.json()}catch{throw new En(502)}let v=xM(k);if(!v)throw new En(502);return{...v.turn,claimReceivedAtMs:Date.now()}}catch(h){if(t())return null;throw h}finally{clearTimeout(m),clearInterval(g)}}var Zie,OK=p(()=>{"use strict";$();Xv();$R();jR();VR();Wp();$l();Ml();An();hi();IK();jp();af();Zie=2e4});async function GR(e){let t=await Hp(),r=()=>Bb(A().agentOsId?.trim())&&!!A().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:NK}));!t&&!e.shouldStop();){if(!r()||(await yi(NK,e.shouldStop),e.shouldStop()))return;t=await Hp()}if(!t||e.shouldStop())return;let n=rL(process.env,A()),o=new Qp;t.security&&(t.security.childEnv=await RK().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:nc(t.chatProvider),useClaudeOauth:t.useClaudeOauth,turnSignature:n,credentialStore:Al(),childEnvSafe:t.security?.childEnv?.ok??null,auth:t.auth?.describe().kind??"api_key"}));let s=0,i=0,a=new Fp,l=CK({target:t,capabilities:u=>{let d=A(),f=ir(d);return nc(f,ki(d),sf(f,d),t.security?.report({policy:n,auth:u.kind,credentialStore:Al(),folderSandbox:Pf(process.env,d)}),Uf(),gm(),mm())},onBeat:u=>HW({pid:process.pid,runtimeVersion:et,at:new Date().toISOString(),heartbeatOk:u,chatTurns:Math.max(0,s-i),commandTurns:i})}),c=Promise.resolve();for(;!e.shouldStop();)try{if(s>=eae){await yi(250,e.shouldStop);continue}let u=await PK(t,e.shouldStop,a.snapshot(),n);if(u==="no_credential"){console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:"machine_not_linked"})),await yi(TK,e.shouldStop);continue}if(u==="auth_error"){a.onAuthError();let d=t.auth?.describe().hasBoxCredential===!0;await yi(d?5e3:TK,e.shouldStop);continue}if(a.onSuccess(),u){let d=await _K(t,u.turnId);if(!SK(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=()=>rv(t,u);m=c.then(g,g),c=m.then(()=>{},()=>{})}else{let g=await ev(t,u,{policy:n,nonces:o});if(!g.ok){s-=1;continue}if(o.markStarted(u.turnId),f==="browser"){let h=await Oo(t);m=nK({...t,apiKey:h.bearer},{turnId:u.turnId,payload:g.payload})}else f==="secret"?m=yK(h=>Ee(t,u.turnId,h),{turnId:u.turnId,payload:g.payload},{agentOsId:t.agentOsId,boxId:t.boxId}):f==="agent-tab"?m=wF(h=>Ee(t,u.turnId,h),{turnId:u.turnId,payload:g.payload,boxId:t.boxId},{late:_L(t),redactor:rr(t.agentOsId)}):m=Vv(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=IM(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 yi(m,e.shouldStop)}l(),await WW(),console.error(JSON.stringify({event:"chat_claim_loop_stop"}))}var TK,NK,eae,DK=p(()=>{"use strict";$();Xv();SF();UR();dn();jW();$R();jR();oK();kK();jr();VR();wK();Wp();$l();xK();EK();Ml();An();Zp();qb();jp();Gv();OK();nv();Il();af();tv();TK=6e4,NK=5*6e4,eae=3});var MK=p(()=>{"use strict";Wp();jp();tv();nv();Gv();DK()});import{createHash as tae}from"node:crypto";import{chmodSync as LK,existsSync as rae,mkdirSync as nae,rmSync as BK}from"node:fs";import{createConnection as oae,createServer as sae}from"node:net";import{homedir as iae,userInfo as aae}from"node:os";import lae from"node:path";function uae(e,t=process.platform){return t==="win32"?`\\\\.\\pipe\\kynver-site-logins-${tae("sha256").update(`${aae().username}:${iae()}`).digest("hex").slice(0,16)}`:lae.join(e,"control.sock")}async function dae(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 pae(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 UK(e){let t=uae(e.rootDir);if(process.platform!=="win32"){nae(e.rootDir,{recursive:!0,mode:448});try{LK(e.rootDir,448)}catch{}if(rae(t)){if(await fae(t))return null;BK(t,{force:!0})}}let r=sae(n=>{let o="";n.setEncoding("utf8"),n.setTimeout(12e4,()=>n.destroy()),n.on("data",s=>{if(o+=s,o.length>cae)return void n.destroy();let i=o.indexOf(`
|
|
549
|
+
`);if(i<0)return;let a=pae(o.slice(0,i));o="";let l=c=>n.end(`${JSON.stringify(c)}
|
|
550
|
+
`);if(!a)return l({ok:!1,error:"malformed request"});dae(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{LK(t,384)}catch{}return{path:t,close:()=>new Promise(n=>{r.close(()=>n()),process.platform!=="win32"&&BK(t,{force:!0})})}}function fae(e){return new Promise(t=>{let r=oae(e),n=o=>{r.destroy(),t(o)};r.once("connect",()=>n(!0)),r.once("error",()=>n(!1)),setTimeout(()=>n(!1),1e3).unref?.()})}var cae,FK=p(()=>{"use strict";cn();cae=16*1024});function hae(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":Ai(e.platform,e.arch)?null:"unsupported_platform"}async function WK(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 KK(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??(()=>Ko({env:t,platform:r,arch:n})),a=e.loadConfig??A;try{await WK(e.startDelayMs??mae,e);for(let l=1;l<=gae&&!e.shouldStop();l+=1){let c=hae({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=AW($o());if(u>o()&&await WK(u-o(),e),e.shouldStop())return;s({event:"browser_autoprovision_start",attempt:l});try{let d=await(e.provision??im)({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 mae,gae,$K=p(()=>{"use strict";$();Fo();Zl();am();mae=6e4,gae=5});function JR(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(e.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function vae(e,t){let r=JR(e),n=JR(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 Rae(e,t,r={}){let n=r.manual??`${hm} 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 wae(){try{let e=um();return{manual:pm(e,"latest"),selfUpdate:!e.unsupportedReason}}catch{return{manual:`${hm} then restart Kynver (or restart the computer)`,selfUpdate:!1}}}async function Sae(e={}){let t=e.installed??et,r={installed:t,latest:null,outdated:!1,command:hm};if((e.env??process.env).KYNVER_DISABLE_UPDATE_CHECK==="1")return r;let o=new AbortController,s=setTimeout(()=>o.abort(),kae);try{let a=await(e.fetch??fetch)(yae,{signal:o.signal,headers:{accept:"application/json"}});if(!a.ok)return r;let l=await a.json(),c=typeof l?.version=="string"&&JR(l.version)?l.version:null;return c?{installed:t,latest:c,outdated:vae(t,c),command:hm}:r}catch{return r}finally{clearTimeout(s)}}function jK(e={}){let t=e.log??(s=>console.error(s)),r=null,n=async()=>{let s=await Sae(e);if(s.outdated&&s.latest&&s.latest!==r){r=s.latest;let i=(e.advice??wae)();t(JSON.stringify({event:"runtime_update_available",installed:s.installed,latest:s.latest,command:i.manual,selfUpdate:i.selfUpdate})),t(Rae(s.installed,s.latest,i))}return s};n().catch(()=>{});let o=setInterval(()=>{n().catch(()=>{})},e.intervalMs??bae);return o.unref?.(),{stop:()=>clearInterval(o),checkNow:n}}var HK,hm,yae,kae,bae,VK=p(()=>{"use strict";dn();KR();dm();HK="@kynver-app/runtime",hm=`npm install -g ${HK}@latest`,yae=`https://registry.npmjs.org/${HK}/latest`,kae=5e3,bae=360*6e4});var YK={};uw(YK,{adoptOrAcquireOwnerLease:()=>JK,completeWorker:()=>kO,dispatchRun:()=>ri,resolveDaemonOwnerKind:()=>GK,runDaemon:()=>qK,runPipelineTick:()=>Mp,sweepRun:()=>fp});async function qR(e,t,r){let n=e;for(;n>0&&!t();){let o=Math.min(Eae,n),s=Date.now();await yc(o);let i=ah(o,Date.now()-s);if(i!==null){r?.(i);return}n-=o}}function GK(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 JK(e,t,r,n=Pu){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 qK(e,t={}){let r=vh({hostCapability:t.hostCapability}),n=it()?{loaded:0}:YS();n.loaded>0&&console.error(JSON.stringify({event:"daemon_env_file_loaded",...n}));let o=String(e.run||"").trim();o||(console.error(fh("--run")),process.exit(1));let s=String(e.agentOsId||A().agentOsId||"").trim();s||(console.error(fh("--agent-os-id")),process.exit(1)),hs(s).ok||(console.error(Rg(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)):_ae,c=!1,u=0,d=H_(L=>{c||console.error(JSON.stringify({event:"daemon_stop_requested",reason:L,runId:o})),c=!0}),f=await JK(s,GK(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;n_(m.metadata.ownerKind),YC({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=HC(o);h.killed.length>0&&console.error(JSON.stringify({event:"daemon_orphaned_worker_descendants_killed",runId:o,orphans:h.killed.map(L=>({worker:L.workerName,workerPid:L.workerPid,pid:L.orphanPid,outcome:L.result.outcome}))}));let k=null,v=L=>{k=L};try{let L=D_();(L.moved.length>0||L.stillInFile.length>0)&&console.error(JSON.stringify({event:"daemon_credentials_store",...L}))}catch(L){console.error(JSON.stringify({event:"daemon_credentials_store_error",error:L instanceof Error?L.message:String(L)}))}let y=CC();y.remediated&&console.error(JSON.stringify({event:"daemon_default_repo_remediated",defaultRepo:y.resolved?.defaultRepo??null,configPath:y.configPath}));let b=KC(A());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})),jK();let S=Rs(),w=new Up;w.start();let _=new Bp({agentOsId:s,init:{ownerKind:m.metadata.ownerKind,admission:r.allowed?{basis:r.basis,hostCapability:r.hostCapability}:null}});w.setTickIsolation(_.mode),console.error(JSON.stringify({event:"daemon_tick_isolation",mode:_.mode,reason:_.reason}));let R=UK(Ze()).catch(()=>null),T=GR({shouldStop:()=>c}).catch(L=>{console.error(JSON.stringify({event:"chat_claim_loop_crashed",error:L instanceof Error?L.message:String(L)}))});KK({shouldStop:()=>c});let W=!1;for(;!c;)try{if(k!==null){let N=k;k=null;let C=m.isHeld();if(console.error(JSON.stringify({event:"daemon_resume_detected",agentOsId:s,gapMs:N,ownerLeaseHeld:C})),!C){console.error(JSON.stringify({event:"daemon_owner_lease_lost",agentOsId:s,runId:o})),process.exitCode=1,c=!0;break}}w.setPhase("heartbeat"),m.renew(),tC({agentOsId:s,runId:o,instructionBundleVersion:no(),owner:g}),w.setPhase("runner_credential");let L=await uu(e.secret?String(e.secret):void 0,s,{baseUrl:e.baseUrl?String(e.baseUrl):void 0});if(!L.ok){W||(W=!0,console.error(JSON.stringify({event:"daemon_runner_credential_missing",agentOsId:s,reason:L.reason,remedy:`run \`kynver runner credential --agent-os-id ${s}\` (or \`kynver bootstrap\`); ticks resume automatically once the credential exists`}))),w.setPhase("idle"),await qR(l,()=>c,v);continue}W&&(W=!1,console.error(JSON.stringify({event:"daemon_runner_credential_recovered",agentOsId:s}))),w.setPhase("instruction_bundle"),await UC({agentOsId:s,baseUrl:zn(e.baseUrl?String(e.baseUrl):void 0),secret:L.secret}),w.setPhase(_.mode==="thread"?"pipeline_tick_thread":"pipeline_tick_inline");let M=await _.runTick({run:o,agentOsId:s,execute:a,...e,secret:typeof e.secret=="string"&&e.secret?e.secret:L.secret},w.report());w.setTickIsolation(M.isolation);let B=M.tick;w.setPhase("tick_log"),console.error(JSON.stringify({event:"daemon_tick",tickIsolation:M.isolation,...B})),w.setPhase("runtime_control");let G=nn(s),re=M.inFlightWorkers??Lp(s)??0;if(t_(G,re)){let N=Yc({control:G,supervisor:m.metadata.ownerKind,inFlightWorkers:0,exiting:!0}),C=zn(e.baseUrl?String(e.baseUrl):void 0),D=N&&C?await zx({baseUrl:C,agentOsId:s,secret:L.secret},N):!1;console.error(JSON.stringify({event:"daemon_runtime_stopped",agentOsId:s,runId:o,policyVersion:G?.policyVersion??null,requestedBy:G?.requestedByLabel??null,reported:D})),process.exitCode=qc,c=!0;break}if(S.tickEnabled){w.setPhase("cron_tick");let N=Fu(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 C=await Ch({env:S,agentOsIdFilter:s});C.enabled&&(C.fired>0||C.errors>0||C.lockHeld)&&console.error(JSON.stringify({event:"daemon_cron_tick",...C}))}}B.idle?u++:u=0;let I=Math.floor(xs("daemon.maxIdleStreak",Cae)),x=Math.floor(xs("daemon.idleIntervalMs",xae)),V=u>=I?x:l;w.setPhase("idle"),await qR(V,()=>c,v)}catch(L){console.error(JSON.stringify({event:"daemon_tick_error",error:L.message})),w.setPhase("idle"),await qR(l,()=>c,v)}w.setPhase("stopping"),await T,await _.close(),w.stop(),await(await R)?.close().catch(()=>{}),Ze().lock();let O=j_(o);O.length>0&&console.error(JSON.stringify({event:"daemon_stop_worker_trees_killed",runId:o,workers:O.map(L=>({worker:L.workerName,pid:L.pid,outcome:L.result.outcome}))})),d(),m.release(),console.error(JSON.stringify({event:"daemon_stop",runId:o,agentOsId:s}))}var _ae,xae,Cae,Eae,YR=p(()=>{"use strict";$();mh();EC();FC();pn();$C();ih();gu();Ou();Tt();lh();jC();Bu();Rh();Eh();Ar();wr();Ah();U();vM();Nb();wM();MK();vs();FK();$K();VK();on();sh();Tb();bd();Kk();Zs();_ae=6e4,xae=5*6e4,Cae=10,Eae=250});var zK=p(()=>{"use strict";Q();Zo();Fk();Ie();U()});var oc,XK=p(()=>{"use strict";oc=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 Aae,mkdirSync as Iae}from"node:fs";import Pae from"node:path";function Oae(e){let t=typeof e.repo=="string"?e.repo.trim():"";if(t)return t;let r=Ra();return r?r.repo:(Nt("","--repo (or set defaultRepo via `kynver setup` / KYNVER_DEFAULT_REPO)"),"")}function Tae(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}`};let l=e.resolveLocalOnlyBranch?.()?.trim();if(l&&e.verifyRef(l))return{base:l,source:"local-branch",note:`${t} has no git remote \u2014 cutting the run from the local branch ${l}`};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 Nae(e){let t=ee(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]);if(t.status===0){let n=t.stdout.trim().replace(/^refs\/remotes\//,"");if(n)return n}let r=ee(e,["ls-remote","--symref","origin","HEAD"]);if(r.status===0){let n=/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(r.stdout);if(n?.[1])return`origin/${n[1]}`}return null}function Dae(e){let t=ee(e,["remote"]);if(t.status!==0||t.stdout.trim())return null;let r=ee(e,["symbolic-ref","--quiet","--short","HEAD"]);return(r.status===0?r.stdout.trim():"")||"main"}function Mae(e,t){let r=A();try{return Tae({explicitBase:typeof t.base=="string"?t.base:void 0,envBaseRef:process.env.KYNVER_RUN_BASE_REF,configDefaultBase:r.defaultBase,verifyRef:n=>ee(e,["rev-parse","--verify","--quiet",`${n}^{commit}`]).status===0,resolveRemoteHeadRef:()=>Nae(e),resolveLocalOnlyBranch:()=>Dae(e),repoLabel:e})}catch(n){throw new oc(n.message,{remedy:"Diagnose: run `kynver doctor runner-install`.",cause:n})}}function zR(e){let t=JP(Oae(e));Sw(t);let r=e.id?zy(String(e.id)):fc(String(e.name||"run")),n=J(r);Aae(n)&&Lae(`run already exists: ${r}`),Iae(n,{recursive:!0});let o=Mae(t,e);o.note&&console.error(o.note);let s=o.base,i=de(t,["rev-parse",s]).trim(),a=qt(),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}:{}};we(Pae.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 Lae(e){throw new oc(e)}var XR=p(()=>{"use strict";_e();Q();zK();U();Is();Jd();Vn();$();XK()});function QK(e,t){return e.filter(n=>n.repo===t&&!Vr.has(n.status)).sort((n,o)=>(o.createdAt??"").localeCompare(n.createdAt??""))[0]??null}var ZK=p(()=>{"use strict";_e();wn()});var e$=p(()=>{"use strict";Ar();ws();xh()});var ym=p(()=>{"use strict";Ar();wr()});var km=p(()=>{"use strict"});var QR=p(()=>{"use strict"});var ZR=p(()=>{"use strict";e$();Ar();ws();ym();wr();km();QR()});var t$=p(()=>{"use strict"});var r$=p(()=>{"use strict";ym();km()});var n$=p(()=>{"use strict";wr();Ar()});var o$=p(()=>{"use strict";$();ht();Tt();U();Eh();t$();r$();wr();ym();n$();Jc();cs();ws();ZR();km();QR();Q()});var s$=p(()=>{"use strict";ZR();o$()});import{homedir as $ae}from"node:os";import Hae from"node:path";var F2e,W2e,i$=p(()=>{"use strict";F2e=Hae.join($ae(),".kynver","logs","kynver.log"),W2e=10*6e4});var a$=p(()=>{"use strict";Dm();An()});var l$=p(()=>{"use strict";a$()});var c$=p(()=>{"use strict";cs();Jc();$();wr();zc();ag();oa();Q()});function u$(e,t){return QK(e,t)?.id??null}var d$=p(()=>{"use strict";$();Yg();YR();mh();Rh();Ou();XR();Q();ZK();Is();s$();oh();dg();Is();An();i$();l$();c$()});var h$={};uw(h$,{prepareDesktopRuntime:()=>tle,resolveDesktopRepository:()=>g$});import{spawnSync as p$}from"node:child_process";import{randomBytes as jae}from"node:crypto";import{existsSync as Vae,mkdirSync as Gae,readFileSync as Jae,realpathSync as f$,statSync as qae,writeFileSync as Yae}from"node:fs";import{homedir as zae}from"node:os";import tw from"node:path";function Se(e,t){return{ok:!1,code:e,message:t}}function Xae(){return tw.join(zae(),".kynver","desktop-binding.json")}function Qae(e){if(!Vae(e))return null;try{let t=JSON.parse(Jae(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 Zae(e,t){Gae(tw.dirname(e),{recursive:!0}),Yae(e,`${JSON.stringify(t,null,2)}
|
|
551
|
+
`,{mode:384})}function m$(e,t){return e===401||e===403?Se("access_denied",`${t} was refused (${e})`):e===0?Se("network",`${t} could not reach Kynver`):Se("server_error",`${t} failed (${e})`)}async function ew(e,t,r,n={}){try{let o=await bt(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 ele(e){return(e?.accessibleItems??[]).filter(t=>t.access?.isOwner===!0&&typeof t.agentOs?.id=="string").map(t=>(t.agentOs?.id).trim()).filter(Boolean)}function g$(e,t="git"){let r=p$(t,["--version"],Z({encoding:"utf8"}));if(r.error||r.status!==0)return Se("no_git","Git is not installed or not on PATH");let n;try{if(n=f$.native(tw.resolve(e)),!qae(n).isDirectory())return Se("not_a_repository","The selected path is not a folder")}catch{return Se("not_a_repository","The selected folder does not exist")}let o=p$(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 Se("not_a_repository","The selected folder is not inside a Git working tree");try{return{ok:!0,repo:f$.native(s[1].trim())}}catch{return Se("not_a_repository","The Git working tree root could not be resolved")}}async function tle(e,t={}){let r=t.fetchImpl??fetch,n=t.acquireOwnerLease??Pu,o=t.bindingPath??Xae(),s=[],i=hr(e.apiBaseUrl);if(!i)return Se("invalid_input","apiBaseUrl is required");let a=ji(i),l=new URL(a).origin;if(e.agentOsId!==void 0&&!hs(e.agentOsId).ok)return Se("invalid_input","agentOsId is not a valid workspace id");let c;try{c=Ce()}catch(w){if(w instanceof Li)return Se("credentials_unavailable","This computer's credentials have not been provided");throw w}if(!c)return Se("credentials_unavailable","This computer is not paired");let u=await ew(`${a}/api/users/me`,c,r);if(u.status!==200)return m$(u.status,"Account lookup");let d=typeof u.body?.id=="string"?u.body.id:"";if(!d)return Se("server_error","Account lookup returned no account id");if(e.expectedAccountId&&e.expectedAccountId!==d)return Se("account_mismatch","The paired credentials belong to a different account");let f=await ew(`${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 ew(`${a}/api/agent-os`,c,r);if(g.status!==200)return m$(g.status,"Workspace lookup");let h=g.body,k;if(e.agentOsId){if(!ele(h).includes(e.agentOsId))return Se("agent_os_not_owned","That workspace is not owned by the paired account");k=e.agentOsId}else{let w=Jg(h);if(!w?.id)return Se("no_workspace","No workspace owned by this account was found");k=w.id}let v=g$(e.repo,t.gitBinary);if(!v.ok)return v;let y=v.repo,b=await n({agentOsId:k,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 S=b.lease;try{je({...A(),apiBaseUrl:a,agentOsId:k,defaultRepo:y});let w=nh(A());s.push(...w.warnings);let _=A().boxId?.trim()??"";if(!_)return S.release(),Se("local_state_error","Box identity could not be established");if(await zg(un()),!Be(k))try{let M=await Xn(k,{baseUrl:a,apiKey:c});Yn(k,M)}catch(M){let B=M.message;if(Px(B)==="access_denied")return S.release(),Se("access_denied","This computer was refused a runner credential");s.push("runner credential mint did not succeed yet; the runtime retries automatically")}let R=Qae(o),T=R!==null&&R.cloudOrigin===l&&R.accountId===d&&R.agentOsId===k&&R.repo===y,W="";if(T){let M=u$(xe().filter(B=>B.id===R.runId),y);M&&(W=M)}if(!W){let M=`${fc("desktop")}-${jae(3).toString("hex")}`;W=zR({repo:y,name:"desktop",id:M}).runId}Zae(o,{version:1,cloudOrigin:l,accountId:d,agentOsId:k,repo:y,runId:W});let O=vu(y);O||s.push("the repository has no origin remote; nothing can run until it has one");let{runnerId:L}=Fe({runId:W});return{ok:!0,prepared:{accountId:d,agentOsId:k,runId:W,repo:y,boxId:_,repoIdentity:O,runnerId:L},lease:S,warnings:s}}catch(w){return S.release(),Se("local_state_error",w.message)}}var y$=p(()=>{"use strict";yr();Yg();qg();$();Tt();Ar();ws();Ou();Ru();Q();Pr();oh();d$();XR();U()});Tt();import{pathToFileURL as rle}from"node:url";var hw="credential.persist";function yw(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:hw,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:hw,kind:"runnerToken",agentOsId:a,value:l})},reseed:o}}gu();Ru();cn();xu();var kx=/^lg_[a-z0-9]{6,20}$/,iG=/^cr_[0-9a-f]{12}$/,aG=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ro=(e,t,r=1)=>typeof e=="string"&&e.length>=r&&e.length<=t&&!e.includes("\0");function bs(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function bx(e){let t=["v","type","id","agentOsId","op"];switch(e.op){case"key":return bs(e,[...t,"key"])??(ro(e.key,64,40)&&/^[A-Za-z0-9+/]{43}=$/.test(e.key)?{op:"key",key:e.key}:"invalid key");case"list":case"wipe":return bs(e,t)??{op:e.op};case"remove":return bs(e,[...t,"handle"])??(typeof e.handle=="string"&&kx.test(e.handle)?{op:"remove",handle:e.handle}:"invalid handle");case"code":{let r=bs(e,[...t,"requestId","code"]);return r||(e.requestId!==void 0&&!(typeof e.requestId=="string"&&iG.test(e.requestId))?"invalid requestId":ro(e.code,16)?{op:"code",code:e.code,...e.requestId?{requestId:e.requestId}:{}}:"invalid code")}case"add":{let r=bs(e,[...t,"login","replaceHandle"]);if(r)return r;let n=e.login;return!aG(n)||bs(n,["origin","label","username","password","totp"])||!ro(n.origin,2048)||!ro(n.label,Ge.maxLabel)||!ro(n.username,Ge.maxUsername)||!ro(n.password,Ge.maxPassword)||n.totp!==void 0&&!ro(n.totp,Ge.maxTotp,0)?"invalid login":e.replaceHandle!==void 0&&!(typeof e.replaceHandle=="string"&&kx.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 vx(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)}}}vs();cn();var nle=1,bm=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Mi=/^[A-Za-z0-9_-]{1,64}$/,ole=/^[a-z0-9][a-z0-9._-]{0,127}$/i,k$=4096,sle=4096,ile=16;function rw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function sc(e,t){for(let r of Object.keys(e))if(!t.includes(r))return`unexpected field: ${r}`;return null}function ic(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!e.includes("\0")}function ale(e){if(!ic(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 lle(e){if(!rw(e))return{ok:!1,message:"message must be an object"};if(e.v!==nle)return{ok:!1,message:"unsupported protocol version"};let t=r=>({ok:!1,message:r});switch(e.type){case"credentials":{let r=sc(e,["v","type","apiKey","runnerTokens"]);if(r)return t(r);if(e.apiKey!==void 0&&!ic(e.apiKey,k$))return t("invalid apiKey");let n;if(e.runnerTokens!==void 0){if(!rw(e.runnerTokens))return t("invalid runnerTokens");let o=Object.entries(e.runnerTokens);if(o.length>ile)return t("too many runnerTokens");n={};for(let[s,i]of o){if(!bm.test(s)||!ic(i,k$))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=sc(e,["v","type","id","apiBaseUrl","repo","agentOsId","expectedAccountId"]);return r?t(r):typeof e.id!="string"||!Mi.test(e.id)?t("invalid id"):ale(e.apiBaseUrl)?ic(e.repo,sle)?e.agentOsId!==void 0&&(typeof e.agentOsId!="string"||!bm.test(e.agentOsId))?t("invalid agentOsId"):e.expectedAccountId!==void 0&&!ic(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=sc(e,["v","type","id","policy"]);if(r)return t(r);if(typeof e.id!="string"||!Mi.test(e.id))return t("invalid id");let n=X_(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=sc(e,["v","type","id","runId","agentOsId"]);return r?t(r):typeof e.id!="string"||!Mi.test(e.id)?t("invalid id"):typeof e.runId!="string"||!ole.test(e.runId)?t("invalid runId"):typeof e.agentOsId!="string"||!bm.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"||!Mi.test(e.id))return t("invalid id");if(typeof e.agentOsId!="string"||!bm.test(e.agentOsId))return t("invalid agentOsId");let r=bx(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=sc(e,["v","type","id"]);return r?t(r):typeof e.id!="string"||!Mi.test(e.id)?t("invalid id"):{ok:!0,value:{v:1,type:e.type,id:e.id}}}default:return t("unknown message type")}}function cle(e){return rw(e)&&typeof e.id=="string"&&Mi.test(e.id)?e.id:null}function ule(e){let t=mw()?"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(Cg(l))return;let c=lle(l);if(!c.ok){s(cle(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=yw(d,f=>e.send(f)),fw(r)),t==="awaiting_credentials"&&(t="ready"),e.send({v:1,type:"event",name:"credentials_accepted",state:t});return}case"status":{let d=Tg();i(u.id,{state:t,prepared:n,policyRevision:d?.revision??null});return}case"policy":{if(!ex(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(k){return t="ready",s(m,"local_state_error",k.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,tx({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=Tg();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 vx(Ze(),g,h))}catch(k){let v=k instanceof q?k.code:"failed";s(m,`site_login_${v}`,k instanceof q?k.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 dle(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}pw();for(let s of dw)delete e.env[s];let[{prepareDesktopRuntime:t},{runDaemon:r}]=await Promise.all([Promise.resolve().then(()=>(y$(),h$)),Promise.resolve().then(()=>(YR(),YK))]),n=s=>{if(!e.connected||typeof e.send!="function")throw new Error("desktop IPC channel is closed");e.send(s)},o=ule({send:n,prepare:s=>t(s),runDaemon:r,requestDaemonStop:()=>{e.emit("message",{type:mu},void 0)},exit:s=>e.exit(s),daemonExitCode:()=>typeof e.exitCode=="number"?e.exitCode:0});rx(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{}}),Ze().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:mu},void 0);return}e.exit(0)}),n({v:1,type:"event",name:"ready",state:o.state})}function ple(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===rle(e).href}catch{return!1}}ple()&&dle();export{nle as DESKTOP_ENTRY_PROTOCOL_VERSION,ule as createDesktopEntryController,lle as parseDesktopEntryMessage,dle as startDesktopEntry};
|