@kynver-app/runtime 0.2.118 → 0.2.127
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +258 -185
- package/dist/daemon-tick-thread.js +175 -0
- package/dist/desktop-entry.js +214 -143
- package/dist/index.js +281 -208
- package/dist/local-run-store/index.js +73 -9
- package/dist/server/cleanup.js +78 -14
- package/dist/server/default-repo.js +65 -1
- package/dist/server/dispatch-routing.js +67 -3
- package/dist/server/memory-cost-enforce.js +2 -2
- package/dist/server/memory-cost.js +1 -1
- package/dist/server/model-routing.js +67 -3
- package/dist/server/monitor.js +71 -7
- package/dist/server/orchestration.js +65 -1
- package/dist/server/worker-policy.js +66 -2
- package/dist/worker-broker/index.js +4 -4
- package/package.json +2 -2
|
@@ -1,9 +1,73 @@
|
|
|
1
|
-
var a=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};import{homedir as
|
|
2
|
-
`),Gn(t,r)}catch(n){try{Jn(t,{force:!0})}catch{}throw n}}function ae(r){return String(r).replace(/\/+$/,"")}var b=a(()=>{"use strict";jr()});var Qn,Di,Zn,Li,Yr=a(()=>{"use strict";Qn=["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"],Di=new Set(Qn),Zn=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],Li=new Set(Zn)});var le=a(()=>{"use strict";B();b();Yr()});var Vr=a(()=>{"use strict";le()});var Be=a(()=>{"use strict";le();B();Vr()});function qr(r){let e=ae(r);try{let t=new URL(e);return t.hostname.toLowerCase()===Gr?(t.hostname=`www.${Gr}`,ae(t.toString())):e}catch{return e}}function Ue(r){if(r?.trim())return qr(ae(r.trim()))}async function ce(r,e,t=fetch){let n=qr(r),o=new Headers(e?.headers),s=0;for(;s<=Jr;){let i=await t(n,{...e,headers:o,redirect:"manual"});if(![301,302,303,307,308].includes(i.status))return i;let l=i.headers.get("location");if(!l)return i;let u=new URL(l,n);if(u.origin!==new URL(n).origin||u.username||u.password)throw await i.body?.cancel(),new Error("kynver API fetch refused unsafe redirect (origin change or embedded credentials)");let c=(e?.method??"GET").toUpperCase();if(!["GET","HEAD"].includes(c)&&i.status!==307&&i.status!==308)return i;await i.body?.cancel(),n=u.toString(),s+=1}throw new Error(`kynver API fetch exceeded ${Jr} redirects for ${r}`)}var Gr,Jr,ue=a(()=>{"use strict";b();Gr="kynver.com";Jr=10});function U(r){let e=(r??"").trim().toLowerCase();return e==="ghost"||e==="forge"||e==="box"?e:e.includes("forge")?"forge":e.includes("ghost")||e.includes("openclaw")?"ghost":"box"}function de(r,e){return r[e]?.trim()||null}function zr(r){let e=r?.split(":")[0]?.trim();return e?U(e):null}function q(r=process.env,e={}){let t=[],n=zr(e.boxId),o=zr(de(r,"KYNVER_BOX_ID")),s=e.boxKind?.trim();if(s)return n&&n!==U(s)&&t.push(`config.boxId=${e.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:U(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=de(r,"KYNVER_BOX_KIND");if(i)return o&&o!==U(i)&&t.push(`KYNVER_BOX_ID=${de(r,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:U(i),source:"env",slugInferenceBlocked:!1,warnings:t};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:t};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:t};let l=de(r,"KYNVER_AGENT_OS_SLUG");return l&&t.push(`KYNVER_AGENT_OS_SLUG=${l} 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:!!l,warnings:t}}var F=a(()=>{"use strict"});function We(r,e){return r==="forge"?4:Math.max(1,e)}function pe(r,e){return r==="forge"?Math.min(Math.max(1,e),4):Math.max(1,e)}var me=a(()=>{"use strict"});var Xr=a(()=>{"use strict"});var ta,na,$e=a(()=>{"use strict";ta=25*1024*1024*1024,na=12*1024*1024*1024});var la,ca,Qr=a(()=>{"use strict";$e();la=5*1024*1024*1024,ca=10*1024*1024*1024});var ga,ha,He=a(()=>{"use strict";Qr();$e();ga=30*1024*1024*1024,ha=15*1024*1024*1024});function Zr(){return rt()}var fe=a(()=>{"use strict";Ye();b()});var tt=a(()=>{"use strict";fe();b()});var nt=a(()=>{"use strict"});var ot=a(()=>{"use strict";nt();b()});var st=a(()=>{"use strict"});var it=a(()=>{"use strict";st()});var ge=a(()=>{"use strict"});var at=a(()=>{"use strict"});var lt=a(()=>{"use strict"});var ct=a(()=>{"use strict";it();b();ge();at();lt()});var ut=a(()=>{"use strict";ge()});var dt=a(()=>{"use strict"});var pt=a(()=>{"use strict"});var Ve=a(()=>{"use strict"});var mt=a(()=>{"use strict"});var ft=a(()=>{"use strict";Ve();mt()});var gt=a(()=>{"use strict";ot();ct();ge();ut();dt();le();pt();ft();Ve();b()});var ht=a(()=>{"use strict";gt()});function yt(r,e={}){let t=e.perWorkerMemBytes??Ge,n=e.memReserveBytes??Je,o=e.memUtilization??qe,s=Math.max(0,Math.floor(r*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,he)}var Ge,Je,qe,he,Rt=a(()=>{"use strict";Xr();I();F();me();ye();He();fe();tt();ht();b();Ge=500*1024*1024,Je=4*1024*1024*1024,qe=.85,he=64});function re(r,e){let t=Number(r);return!Number.isFinite(t)||t<=0?e:Math.floor(t)}function ze(r){let e=r.config??{},t=r.env??process.env,n=re(e.perWorkerMemBytes,Ge),o=re(e.memReserveBytes,Je),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):qe)),i=yt(r.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(r.configuredMaxWorkersOverride!==void 0&&r.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:re(r.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(e.maxConcurrentWorkers!==void 0&&e.maxConcurrentWorkers!==null){let c=re(e.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,he),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&re(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,he),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var ye=a(()=>{"use strict";Rt()});import{homedir as lo}from"node:os";import co from"node:path";var St,Xe=a(()=>{"use strict";St=co.join(lo(),".kynver",".env")});var kt=a(()=>{"use strict"});var bt=a(()=>{"use strict";kt()});var vt=a(()=>{"use strict"});var xt=a(()=>{"use strict";b()});var Qe=a(()=>{"use strict";bt();vt();xt()});var _t=a(()=>{"use strict"});var Et=a(()=>{"use strict";_t()});var Re=a(()=>{"use strict";Xe();B();I();Qe();Et()});var Ct=a(()=>{"use strict";F();F()});var At=a(()=>{"use strict";Xe();Qe();Re()});function It(r){if(!Ot)return r;if(!wt)throw new Ze;return wt}function rr(){if(Ot)throw new er}var Ze,er,Ot,wt,tr=a(()=>{"use strict";Ze=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},er=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},Ot=!1,wt=null});import{existsSync as T,mkdirSync as fo,readdirSync as Se,renameSync as Tt,statSync as go}from"node:fs";import N from"node:path";function Pt(r){try{return go(r).isDirectory()}catch{return!1}}function ho(r){if(!T(r))return!0;for(let e of Nt){let t=N.join(r,e);if(T(t)&&(!Pt(t)||Se(t).length>0))return!1}return!0}function yo(r){let e=N.join(r,"runs");if(!T(e)||!Pt(e))return!1;for(let t of Se(e,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=N.join(e,t.name,"run.json");if(ee(n,void 0)?.id)return!0}return!1}function Ro(r){let e=N.join(r,"runs");if(!T(e))return!1;for(let t of Se(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(ee(N.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function So(r){let e=N.join(r,"ghost");return T(e)?!T(N.join(e,"runs")):Ro(r)}function Dt(r){return yo(r.sharedRoot)?ho(r.forgeRoot)?So(r.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 Lt(r,e){fo(e,{recursive:!0});for(let t of Nt){let n=N.join(r,t),o=N.join(e,t);if(T(n)){if(T(o)&&Se(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(T(o)){Tt(n,o);continue}Tt(n,o)}}}var Nt,Kt=a(()=>{"use strict";b();Nt=["runs","worktrees"]});import{existsSync as k}from"node:fs";import{homedir as ko}from"node:os";import S from"node:path";function nr(r=process.env){return r.HOME?.trim()||ko()}function or(r=process.env){return S.join(nr(r),".kynver","harness")}function ke(r){let e=S.resolve(M(r.trim()));for(;bo.has(S.basename(e));)e=S.dirname(e);return e}function vo(r,e=process.env){return S.join(or(e),r)}function xo(r=process.env){let e=or(r);if(k(S.join(e,"runs")))return!0;if(k(e)&&!k(S.join(e,"ghost"))&&!k(S.join(e,"forge")))return k(e);let t=S.join(nr(r),Mt);return k(t)}function be(r){let e=r.env??process.env,t=e.KYNVER_HARNESS_ROOT?.trim()||e.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:ke(t),source:"env"};let n=r.configuredHarnessRoot?.trim();if(n)return{harnessRoot:ke(n),source:"config"};let o=vo(r.boxKind,e);if(k(S.join(o,"runs"))||k(o)&&!_o(o))return{harnessRoot:o,source:"box_scoped"};let i=or(e);if(r.boxKind==="forge"){let l=Dt({sharedRoot:i,forgeRoot:o});if(l.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:l.blocker};if(l.action==="migrate")return r.allowForgeLegacyMigration!==!1&&Lt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&xo(e)){if(k(S.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(k(i)&&!k(S.join(i,"ghost"))&&!k(S.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=S.join(nr(e),Mt);if(k(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function _o(r){if(!k(r))return!0;for(let e of["runs","worktrees"]){let t=S.join(r,e);if(k(t))return!1}return!0}var Mt,bo,sr=a(()=>{"use strict";B();Kt();Mt=S.join(".openclaw","harness");bo=new Set(["runs","worktrees"])});import Ft from"node:os";function ve(r){return r?.trim()?r.trim():null}function Eo(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function Co(r){return r.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||r.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||r.KYNVER_DAEMON_STRICT_IDENTITY==="1"||r.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function xe(r=_(),e=process.env,t={}){let n=q(e,r),o=[...n.warnings],s=[],i=!!(r.boxKind?.trim()||ve(e.KYNVER_BOX_KIND)),l=t.strict===!0||Co(e);if((t.requireExplicitBoxKind||l)&&!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 V="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";l||t.requireExplicitBoxKind?s.push(V):o.push(`${V} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=ve(r.runnerId),c=ve(e.KYNVER_RUNTIME_ID)??ve(e.OPENCLAW_RUNTIME_ID),p=u??c??Eo(n.boxKind,Ft.hostname()),m=u?"config":c?"env":"derived";m==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${p}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let d=ze({config:r,env:e,totalMemBytes:Ft.totalmem()}),Y=pe(n.boxKind,d.configuredMaxWorkers??We(n.boxKind,d.autoCap)),v=be({boxKind:n.boxKind,configuredHarnessRoot:r.harnessRoot,env:e});return v.migrationBlocker&&s.push(v.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:p,runnerIdSource:m,maxConcurrentWorkers:Y,workerCapSource:d.workerCapSource,harnessRoot:v.harnessRoot,harnessRootSource:v.source},errors:s,warnings:o}}var _e=a(()=>{"use strict";I();F();me();ye();sr()});var Bt=a(()=>{"use strict";Be();F();Ct();I();Re();At();ue();tr();_e()});var Io,xu,Ut=a(()=>{"use strict";Io=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],xu=Io.join("|")});var Wt=a(()=>{"use strict";B()});var $t=a(()=>{"use strict";Wt()});import{execFileSync as To}from"node:child_process";function lr(r=process.env){let e=r[No]?.trim().toLowerCase();return e==="file"?"file":e==="keychain"?"keychain":"auto"}function Po(r,e,t){let n={encoding:"utf8",timeout:t.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...t.input!==void 0?{input:t.input}:{}};return To(r,e,n)}function Do(r=process.platform){return r==="darwin"?"macos":r==="linux"?"libsecret":r==="win32"?"windows":null}function ir(r,e){let t=JSON.stringify(W),n=JSON.stringify(e),o="[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]; $v = New-Object Windows.Security.Credentials.PasswordVault;";return r==="get"?`${o} try { $c = $v.Retrieve(${t}, ${n}); $c.RetrievePassword(); [Console]::Out.Write($c.Password) } catch { exit 3 }`:r==="set"?`${o} $s = [Console]::In.ReadToEnd().TrimEnd("\`r","\`n"); try { $old = $v.Retrieve(${t}, ${n}); $v.Remove($old) } catch {}; $v.Add((New-Object Windows.Security.Credentials.PasswordCredential(${t}, ${n}, $s)))`:`${o} try { $old = $v.Retrieve(${t}, ${n}); $v.Remove($old) } catch {}`}function Ht(r={}){if(lr(r.env??process.env)==="file")return null;let t=Do(r.platform??process.platform);return t?new ar(t,r.exec):null}var W,No,P,ar,jt=a(()=>{"use strict";W="kynver",No="KYNVER_CREDENTIAL_STORE";P=5e3;ar=class{constructor(e,t=Po){this.backend=e;this.exec=t}backend;exec;get(e){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",W,"-a",e,"-w"],{timeoutMs:P}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",W,"account",e],{timeoutMs:P}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ir("get",e)],{timeoutMs:P}).replace(/\r?\n$/,"");return n||null}catch{return null}}set(e,t){if(!t||/[\r\n]/.test(t))return!1;try{this.backend==="macos"?this.exec("security",["add-generic-password","-U","-s",W,"-a",e,"-l",`Kynver (${e})`,"-w",t],{timeoutMs:P}):this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${e})`,"service",W,"account",e],{input:`${t}
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
var a=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};import{homedir as Hr}from"node:os";import jr from"node:path";function Jn(r){return r==="~"?Hr():r.startsWith("~/")||r.startsWith("~\\")?jr.join(Hr(),r.slice(2)):r}function M(r){return jr.resolve(Jn(r))}var F=a(()=>{"use strict"});var Yr=a(()=>{"use strict"});import{existsSync as Di,mkdirSync as qn,readFileSync as zn,readdirSync as Li,renameSync as Xn,rmSync as Qn,statSync as Ki,writeFileSync as Zn}from"node:fs";import{randomBytes as eo}from"node:crypto";import ro from"node:path";function Fe(r){console.error(r),process.exit(1)}function q(r,e){try{return JSON.parse(zn(r,"utf8"))}catch(t){if(arguments.length>1)return e;Fe(`failed to read ${r}: ${t.message}`)}}function ae(r,e){qn(ro.dirname(r),{recursive:!0});let t=`${r}.${process.pid}.${eo(4).toString("hex")}.tmp`;try{Zn(t,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`),Xn(t,r)}catch(n){try{Qn(t,{force:!0})}catch{}throw n}}function le(r){return String(r).replace(/\/+$/,"")}var b=a(()=>{"use strict";Yr()});var to,Ui,no,$i,Vr=a(()=>{"use strict";to=["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"],Ui=new Set(to),no=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],$i=new Set(no)});var ce=a(()=>{"use strict";F();b();Vr()});var Gr=a(()=>{"use strict";ce()});var Be=a(()=>{"use strict";ce();F();Gr()});function zr(r){let e=le(r);try{let t=new URL(e);return t.hostname.toLowerCase()===Jr?(t.hostname=`www.${Jr}`,le(t.toString())):e}catch{return e}}function Ue(r){if(r?.trim())return zr(le(r.trim()))}async function ue(r,e,t=fetch){let n=zr(r),o=new Headers(e?.headers),s=0;for(;s<=qr;){let i=await t(n,{...e,headers:o,redirect:"manual"});if(![301,302,303,307,308].includes(i.status))return i;let l=i.headers.get("location");if(!l)return i;let u=new URL(l,n);if(u.origin!==new URL(n).origin||u.username||u.password)throw await i.body?.cancel(),new Error("kynver API fetch refused unsafe redirect (origin change or embedded credentials)");let c=(e?.method??"GET").toUpperCase();if(!["GET","HEAD"].includes(c)&&i.status!==307&&i.status!==308)return i;await i.body?.cancel(),n=u.toString(),s+=1}throw new Error(`kynver API fetch exceeded ${qr} redirects for ${r}`)}var Jr,qr,de=a(()=>{"use strict";b();Jr="kynver.com";qr=10});function B(r){let e=(r??"").trim().toLowerCase();return e==="ghost"||e==="forge"||e==="box"?e:e.includes("forge")?"forge":e.includes("ghost")||e.includes("openclaw")?"ghost":"box"}function pe(r,e){return r[e]?.trim()||null}function Xr(r){let e=r?.split(":")[0]?.trim();return e?B(e):null}function z(r=process.env,e={}){let t=[],n=Xr(e.boxId),o=Xr(pe(r,"KYNVER_BOX_ID")),s=e.boxKind?.trim();if(s)return n&&n!==B(s)&&t.push(`config.boxId=${e.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:B(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=pe(r,"KYNVER_BOX_KIND");if(i)return o&&o!==B(i)&&t.push(`KYNVER_BOX_ID=${pe(r,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:B(i),source:"env",slugInferenceBlocked:!1,warnings:t};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:t};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:t};let l=pe(r,"KYNVER_AGENT_OS_SLUG");return l&&t.push(`KYNVER_AGENT_OS_SLUG=${l} 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:!!l,warnings:t}}var W=a(()=>{"use strict"});function $e(r,e){return r==="forge"?4:Math.max(1,e)}function fe(r,e){return r==="forge"?Math.min(Math.max(1,e),4):Math.max(1,e)}var me=a(()=>{"use strict"});var Qr=a(()=>{"use strict"});var ca,ua,He=a(()=>{"use strict";ca=25*1024*1024*1024,ua=12*1024*1024*1024});var ga,ha,Zr=a(()=>{"use strict";He();ga=5*1024*1024*1024,ha=10*1024*1024*1024});var xa,va,je=a(()=>{"use strict";Zr();He();xa=30*1024*1024*1024,va=15*1024*1024*1024});function et(){return tt()}var re=a(()=>{"use strict";Ye();b()});var ot=a(()=>{"use strict";re();b()});var st=a(()=>{"use strict"});var it=a(()=>{"use strict";st();b()});var at=a(()=>{"use strict"});var lt=a(()=>{"use strict";at()});var he=a(()=>{"use strict"});var ct=a(()=>{"use strict"});var ut=a(()=>{"use strict"});var dt=a(()=>{"use strict";lt();b();he();ct();ut()});var il,Ve=a(()=>{"use strict";il=String.raw`"use strict";
|
|
3
|
+
const cp = require("child_process"), fs = require("fs");
|
|
4
|
+
const argv = process.argv.slice(1);
|
|
5
|
+
const exitFile = argv[0], cmd = argv[1], args = argv.slice(2);
|
|
6
|
+
const startedMs = Date.now();
|
|
7
|
+
function cgroupOomKills() {
|
|
8
|
+
try {
|
|
9
|
+
const line = fs.readFileSync("/proc/self/cgroup", "utf8").split("\n").find((l) => l.startsWith("0::"));
|
|
10
|
+
if (!line) return null;
|
|
11
|
+
const file = "/sys/fs/cgroup" + line.slice(3).trim().replace(/\/$/, "") + "/memory.events";
|
|
12
|
+
const m = /(?:^|\n)oom_kill (\d+)/.exec(fs.readFileSync(file, "utf8"));
|
|
13
|
+
return m ? Number(m[1]) : null;
|
|
14
|
+
} catch { return null; }
|
|
15
|
+
}
|
|
16
|
+
function kernelLog() {
|
|
17
|
+
const override = process.env.KYNVER_EXIT_CAPTURE_KERNEL_LOG_FILE;
|
|
18
|
+
if (override) { try { return fs.readFileSync(override, "utf8"); } catch { return ""; } }
|
|
19
|
+
const run = (bin, a) => {
|
|
20
|
+
try {
|
|
21
|
+
const r = cp.spawnSync(bin, a, { encoding: "utf8", timeout: 3000, maxBuffer: 8 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] });
|
|
22
|
+
return r.status === 0 ? String(r.stdout || "") : "";
|
|
23
|
+
} catch { return ""; }
|
|
24
|
+
};
|
|
25
|
+
return run("journalctl", ["-k", "-q", "--no-pager", "--since", "@" + Math.floor(startedMs / 1000)]) || run("dmesg", []);
|
|
26
|
+
}
|
|
27
|
+
const oomBefore = cgroupOomKills();
|
|
28
|
+
let child, finished = false;
|
|
29
|
+
function write(rec) {
|
|
30
|
+
try { fs.writeFileSync(exitFile, JSON.stringify(rec, null, 2) + "\n"); } catch {}
|
|
31
|
+
}
|
|
32
|
+
function finish(code, signal, spawnError) {
|
|
33
|
+
if (finished) return;
|
|
34
|
+
finished = true;
|
|
35
|
+
const rec = { exitCode: code, signal: signal || null, startedAt: new Date(startedMs).toISOString(), endedAt: new Date().toISOString(), childPid: child && child.pid };
|
|
36
|
+
if (spawnError) rec.spawnError = spawnError;
|
|
37
|
+
if (signal === "SIGKILL" || code === 137 || (code !== 0 && code !== null)) {
|
|
38
|
+
const oomAfter = cgroupOomKills();
|
|
39
|
+
if (oomBefore !== null && oomAfter !== null && oomAfter > oomBefore) {
|
|
40
|
+
rec.oomEvidence = { source: "cgroup", detail: "memory.events oom_kill " + oomBefore + " -> " + oomAfter };
|
|
41
|
+
} else if (signal === "SIGKILL" || code === 137) {
|
|
42
|
+
const pid = child && child.pid;
|
|
43
|
+
const hit = kernelLog().split("\n").find((l) => pid && new RegExp("(?:Killed process|oom-kill:.*pid=|Memory cgroup out of memory: Killed process) ?" + pid + "\\b").test(l));
|
|
44
|
+
if (hit) rec.oomEvidence = { source: "kernel_log", detail: hit.trim().slice(0, 300) };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
write(rec);
|
|
48
|
+
if (signal) {
|
|
49
|
+
const n = (require("os").constants.signals || {})[signal];
|
|
50
|
+
process.exit(128 + (n || 9));
|
|
51
|
+
}
|
|
52
|
+
process.exit(code === null ? 1 : code);
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
child = cp.spawn(cmd, args, { stdio: "inherit" });
|
|
56
|
+
} catch (e) {
|
|
57
|
+
process.stderr.write("failed to spawn worker process: " + (e && e.message) + "\n");
|
|
58
|
+
finish(127, null, String(e && e.message));
|
|
59
|
+
}
|
|
60
|
+
for (const s of ["SIGTERM", "SIGINT", "SIGHUP"]) process.on(s, () => { try { child.kill(s); } catch {} });
|
|
61
|
+
child.on("error", (e) => {
|
|
62
|
+
process.stderr.write("failed to spawn worker process: " + (e && e.message) + "\n");
|
|
63
|
+
if (!child.pid) finish(127, null, String(e && e.message));
|
|
64
|
+
});
|
|
65
|
+
child.on("exit", (code, signal) => finish(code, signal));
|
|
66
|
+
`});var pt=a(()=>{"use strict";re();b();Ve()});var ft=a(()=>{"use strict";he()});var mt=a(()=>{"use strict"});var bl,kl,gt=a(()=>{"use strict";ce();bl=10*6e4,kl=60*6e4});var ht=a(()=>{"use strict"});var Ge=a(()=>{"use strict"});var yt=a(()=>{"use strict"});var Rt=a(()=>{"use strict";Ge();yt()});var St=a(()=>{"use strict";it();dt();pt();Ve();he();ft();mt();gt();ht();Rt();Ge();b()});var bt=a(()=>{"use strict";St();b()});function kt(r,e={}){let t=e.perWorkerMemBytes??Je,n=e.memReserveBytes??qe,o=e.memUtilization??ze,s=Math.max(0,Math.floor(r*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,ye)}var Je,qe,ze,ye,xt=a(()=>{"use strict";Qr();I();W();me();Re();je();re();ot();bt();b();Je=500*1024*1024,qe=4*1024*1024*1024,ze=.85,ye=64});function te(r,e){let t=Number(r);return!Number.isFinite(t)||t<=0?e:Math.floor(t)}function Xe(r){let e=r.config??{},t=r.env??process.env,n=te(e.perWorkerMemBytes,Je),o=te(e.memReserveBytes,qe),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):ze)),i=kt(r.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(r.configuredMaxWorkersOverride!==void 0&&r.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:te(r.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(e.maxConcurrentWorkers!==void 0&&e.maxConcurrentWorkers!==null){let c=te(e.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,ye),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&te(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,ye),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var Re=a(()=>{"use strict";xt()});import{homedir as ho}from"node:os";import yo from"node:path";var vt,Qe=a(()=>{"use strict";vt=yo.join(ho(),".kynver",".env")});var _t=a(()=>{"use strict"});var Et=a(()=>{"use strict";_t()});var Ct=a(()=>{"use strict"});var At=a(()=>{"use strict";b()});var Ze=a(()=>{"use strict";Et();Ct();At()});var wt=a(()=>{"use strict"});var Ot=a(()=>{"use strict";wt()});var Se=a(()=>{"use strict";Qe();F();I();Ze();Ot()});var It=a(()=>{"use strict";W();W()});var Tt=a(()=>{"use strict";Qe();Ze();Se()});function Dt(r){if(!Pt)return r;if(!Nt)throw new er;return Nt}function tr(){if(Pt)throw new rr}var er,rr,Pt,Nt,nr=a(()=>{"use strict";er=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},rr=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},Pt=!1,Nt=null});import{existsSync as T,mkdirSync as ko,readdirSync as be,renameSync as Lt,statSync as xo}from"node:fs";import N from"node:path";function Mt(r){try{return xo(r).isDirectory()}catch{return!1}}function vo(r){if(!T(r))return!0;for(let e of Kt){let t=N.join(r,e);if(T(t)&&(!Mt(t)||be(t).length>0))return!1}return!0}function _o(r){let e=N.join(r,"runs");if(!T(e)||!Mt(e))return!1;for(let t of be(e,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=N.join(e,t.name,"run.json");if(q(n,void 0)?.id)return!0}return!1}function Eo(r){let e=N.join(r,"runs");if(!T(e))return!1;for(let t of be(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(q(N.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function Co(r){let e=N.join(r,"ghost");return T(e)?!T(N.join(e,"runs")):Eo(r)}function Wt(r){return _o(r.sharedRoot)?vo(r.forgeRoot)?Co(r.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 Ft(r,e){ko(e,{recursive:!0});for(let t of Kt){let n=N.join(r,t),o=N.join(e,t);if(T(n)){if(T(o)&&be(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(T(o)){Lt(n,o);continue}Lt(n,o)}}}var Kt,Bt=a(()=>{"use strict";b();Kt=["runs","worktrees"]});import{existsSync as k}from"node:fs";import{homedir as Ao}from"node:os";import S from"node:path";function or(r=process.env){return r.HOME?.trim()||Ao()}function sr(r=process.env){return S.join(or(r),".kynver","harness")}function ke(r){let e=S.resolve(M(r.trim()));for(;wo.has(S.basename(e));)e=S.dirname(e);return e}function Oo(r,e=process.env){return S.join(sr(e),r)}function Io(r=process.env){let e=sr(r);if(k(S.join(e,"runs")))return!0;if(k(e)&&!k(S.join(e,"ghost"))&&!k(S.join(e,"forge")))return k(e);let t=S.join(or(r),Ut);return k(t)}function xe(r){let e=r.env??process.env,t=e.KYNVER_HARNESS_ROOT?.trim()||e.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:ke(t),source:"env"};let n=r.configuredHarnessRoot?.trim();if(n)return{harnessRoot:ke(n),source:"config"};let o=Oo(r.boxKind,e);if(k(S.join(o,"runs"))||k(o)&&!To(o))return{harnessRoot:o,source:"box_scoped"};let i=sr(e);if(r.boxKind==="forge"){let l=Wt({sharedRoot:i,forgeRoot:o});if(l.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:l.blocker};if(l.action==="migrate")return r.allowForgeLegacyMigration!==!1&&Ft(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&Io(e)){if(k(S.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(k(i)&&!k(S.join(i,"ghost"))&&!k(S.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=S.join(or(e),Ut);if(k(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function To(r){if(!k(r))return!0;for(let e of["runs","worktrees"]){let t=S.join(r,e);if(k(t))return!1}return!0}var Ut,wo,ir=a(()=>{"use strict";F();Bt();Ut=S.join(".openclaw","harness");wo=new Set(["runs","worktrees"])});import $t from"node:os";function ve(r){return r?.trim()?r.trim():null}function No(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function Po(r){return r.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||r.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||r.KYNVER_DAEMON_STRICT_IDENTITY==="1"||r.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function _e(r=_(),e=process.env,t={}){let n=z(e,r),o=[...n.warnings],s=[],i=!!(r.boxKind?.trim()||ve(e.KYNVER_BOX_KIND)),l=t.strict===!0||Po(e);if((t.requireExplicitBoxKind||l)&&!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 V="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";l||t.requireExplicitBoxKind?s.push(V):o.push(`${V} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=ve(r.runnerId),c=ve(e.KYNVER_RUNTIME_ID)??ve(e.OPENCLAW_RUNTIME_ID),p=u??c??No(n.boxKind,$t.hostname()),f=u?"config":c?"env":"derived";f==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${p}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let d=Xe({config:r,env:e,totalMemBytes:$t.totalmem()}),Y=fe(n.boxKind,d.configuredMaxWorkers??$e(n.boxKind,d.autoCap)),x=xe({boxKind:n.boxKind,configuredHarnessRoot:r.harnessRoot,env:e});return x.migrationBlocker&&s.push(x.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:p,runnerIdSource:f,maxConcurrentWorkers:Y,workerCapSource:d.workerCapSource,harnessRoot:x.harnessRoot,harnessRootSource:x.source},errors:s,warnings:o}}var Ee=a(()=>{"use strict";I();W();me();Re();ir()});var Ht=a(()=>{"use strict";Be();W();It();I();Se();Tt();de();nr();Ee()});var Mo,Gu,jt=a(()=>{"use strict";Mo=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],Gu=Mo.join("|")});var Yt=a(()=>{"use strict";F()});var Vt=a(()=>{"use strict";Yt()});import{execFileSync as Wo}from"node:child_process";function cr(r=process.env){let e=r[Fo]?.trim().toLowerCase();return e==="file"?"file":e==="keychain"?"keychain":"auto"}function Bo(r,e,t){let n={encoding:"utf8",timeout:t.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...t.input!==void 0?{input:t.input}:{}};return Wo(r,e,n)}function Uo(r=process.platform){return r==="darwin"?"macos":r==="linux"?"libsecret":r==="win32"?"windows":null}function ar(r,e){let t=JSON.stringify(U),n=JSON.stringify(e),o="[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]; $v = New-Object Windows.Security.Credentials.PasswordVault;";return r==="get"?`${o} try { $c = $v.Retrieve(${t}, ${n}); $c.RetrievePassword(); [Console]::Out.Write($c.Password) } catch { exit 3 }`:r==="set"?`${o} $s = [Console]::In.ReadToEnd().TrimEnd("\`r","\`n"); try { $old = $v.Retrieve(${t}, ${n}); $v.Remove($old) } catch {}; $v.Add((New-Object Windows.Security.Credentials.PasswordCredential(${t}, ${n}, $s)))`:`${o} try { $old = $v.Retrieve(${t}, ${n}); $v.Remove($old) } catch {}`}function Gt(r={}){if(cr(r.env??process.env)==="file")return null;let t=Uo(r.platform??process.platform);return t?new lr(t,r.exec):null}var U,Fo,P,lr,Jt=a(()=>{"use strict";U="kynver",Fo="KYNVER_CREDENTIAL_STORE";P=5e3;lr=class{constructor(e,t=Bo){this.backend=e;this.exec=t}backend;exec;get(e){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",U,"-a",e,"-w"],{timeoutMs:P}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",U,"account",e],{timeoutMs:P}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ar("get",e)],{timeoutMs:P}).replace(/\r?\n$/,"");return n||null}catch{return null}}set(e,t){if(!t||/[\r\n]/.test(t))return!1;try{this.backend==="macos"?this.exec("security",["add-generic-password","-U","-s",U,"-a",e,"-l",`Kynver (${e})`,"-w",t],{timeoutMs:P}):this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${e})`,"service",U,"account",e],{input:`${t}
|
|
67
|
+
`,timeoutMs:P}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ar("set",e)],{input:`${t}
|
|
68
|
+
`,timeoutMs:P})}catch{return!1}return this.get(e)===t}delete(e){try{this.backend==="macos"?this.exec("security",["delete-generic-password","-s",U,"-a",e],{timeoutMs:P}):this.backend==="libsecret"?this.exec("secret-tool",["clear","service",U,"account",e],{timeoutMs:P}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ar("delete",e)],{timeoutMs:P})}catch{}}}});function fr(){return ur||(ur=new dr),ur}var pr,$o,Ce,dr,ur,qt=a(()=>{"use strict";Jt();pr="api-key",$o=6e4,Ce=class extends Error{constructor(e){super(`KYNVER_CREDENTIAL_STORE=keychain but the OS keychain could not store "${e}"; refusing to write the secret to disk`),this.name="KeychainUnavailableError"}},dr=class{cache=new Map;keychain;env;now;constructor(e={}){this.env=e.env??process.env,this.keychain=e.keychain===void 0?Gt({env:this.env}):e.keychain,this.now=e.now??Date.now}get available(){return this.keychain!==null}get backend(){return this.keychain?.backend??null}read(e){if(!this.keychain)return null;let t=this.cache.get(e);if(t&&this.now()-t.at<$o)return t.value;let n=this.keychain.get(e);return this.cache.set(e,{value:n,at:this.now()}),n}write(e,t){let n=cr(this.env);if(!this.keychain){if(n==="keychain")throw new Ce(e);return!1}let o=this.keychain.set(e,t);if(o)this.cache.set(e,{value:t,at:this.now()});else if(this.cache.delete(e),n==="keychain")throw new Ce(e);return o}remove(e){this.cache.delete(e),this.keychain?.delete(e)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}},ur=null});import{existsSync as Xt,mkdirSync as Ho,readFileSync as Qt,writeFileSync as jo}from"node:fs";import{homedir as Yo,totalmem as hd}from"node:os";import hr from"node:path";function Vo(r){return{...r,...r.harnessRoot?.trim()?{harnessRoot:M(r.harnessRoot.trim())}:{},...r.defaultRepo?.trim()?{defaultRepo:M(r.defaultRepo.trim())}:{}}}function _(){if(!Xt(zt))return{};try{return Vo(JSON.parse(Qt(zt,"utf8")))}catch{return{}}}function Ae(){if(tr(),!Xt(mr))return{};try{return JSON.parse(Qt(mr,"utf8"))}catch{return{}}}function gr(r){tr(),Ho(yr,{recursive:!0}),jo(mr,`${JSON.stringify(r,null,2)}
|
|
69
|
+
`,{mode:384})}function Go(r,e,t,n={}){let o=Ae();if(fr().write(r,t)){let i={...o,...n};delete i[e],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],r])).sort(),gr(i);return}gr({...o,...n,[e]:t})}function Jo(r,e){let t=fr().read(r);return t||Ae()[e]}function Zt(){return Dt(qo)}function en(){return Zt().getApiKey()}function zo(r,e){Zt().persistRunnerToken(r,e)}function Xo(r){let e=rn(r);return e||Zo("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),e}function rn(r){let e=r||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||_().apiBaseUrl;return Ue(e)}async function tn(r,e,t){let n=en(),o=rn(t?.baseUrl);if(!n)return{ok:!1,reason:"KYNVER_API_KEY is required to refresh a rejected runner token"};if(!e)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 Qo(e,{baseUrl:o,apiKey:n});return s&&s!==r?(zo(e,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 Qo(r,e){let t=e?.apiKey||en();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${Xo(e?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(r)}/runner-credentials`,s=await ue(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e?.enableMcpUpdates?{enableMcpUpdates:!0}:{})}),i=await s.text(),l=null;try{l=JSON.parse(i)}catch{l=null}if(!s.ok||!l?.token)throw new Error(`runner credential mint failed (${s.status}): ${l?.error??i.slice(0,200)}`);return l.token}function Zo(r){console.error(r),process.exit(1)}var yr,zt,mr,Nd,Pd,qo,I=a(()=>{"use strict";Be();F();de();W();me();Re();je();Se();Ht();jt();Ee();Vt();nr();qt();yr=hr.join(Yo(),".kynver"),zt=hr.join(yr,"config.json"),mr=hr.join(yr,"credentials");Nd=500*1024*1024,Pd=4*1024*1024*1024;qo={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:Jo(pr,"apiKey")},getRunnerToken(r){let e=Ae();if(!!e.runnerToken&&!!r&&e.runnerTokenAgentOsId===r)return e.runnerToken;let n=process.env.KYNVER_RUNNER_TOKEN?.trim();if(n)return n;if(e.runnerToken&&!(r&&e.runnerTokenAgentOsId&&e.runnerTokenAgentOsId!==r))return e.runnerToken},persistApiKey(r){Go(pr,"apiKey",r)},persistRunnerToken(r,e){gr({...Ae(),runnerToken:e,runnerTokenAgentOsId:r})}}});import nn from"node:path";function we(r){return ke(r)}function Rr(){let r=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(r)return we(r);let e=_(),t=e.harnessRoot?.trim();if(t)return we(t);let n=_e(e,process.env);return n.identity?n.identity.harnessRoot:xe({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function rt(r){return nn.join(we(r),"runs")}function es(r){return nn.join(we(r),"worktrees")}function tt(){let r=Rr();return{harnessRoot:r,runsDir:rt(r),worktreesDir:es(r)}}var Ye=a(()=>{"use strict";I();ir();Ee();b()});import{existsSync as wn,realpathSync as On,readFileSync as In}from"node:fs";import Br from"node:path";var Tn=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),Nn=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function Pn(){try{return In("/proc/self/mounts","utf8")}catch{return null}}function Dn(r){let e=Br.resolve(r);for(let t=0;t<64;t+=1){if(wn(e))try{return On.native(e)}catch{return e}let n=Br.dirname(e);if(n===e)return e;e=n}return e}function Ln(r){return r.replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function Kn(r){let e=[];for(let t of r.split(`
|
|
70
|
+
`)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:Ln(n[1]),fsType:n[2]})}return e}function Ur(r,e=process.platform){return e==="win32"?r.replace(/\\/g,"/"):r}function Mn(r,e){let t=null,n=Ur(r);for(let o of e){let s=Ur(o.mountPoint),i=s.endsWith("/")?s:`${s}/`;(n===s||`${n}/`.startsWith(i))&&(!t||o.mountPoint.length>t.mountPoint.length)&&(t=o)}return t}function Ke(r,e){let n=(e?.resolveRealPath??Dn)(r),o=(e?.mountsSource??Pn)();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=Mn(n,Kn(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 Nn.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}:Tn.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 Me=1,ie=class extends Error{constructor(e,t){super(`local-run-store schema version ${e} is newer than this runtime supports (${t}); refusing to open. Upgrade the runtime or quarantine the database deliberately.`),this.name="SchemaDowngradeRefusedError"}},Wn=[`CREATE TABLE IF NOT EXISTS local_meta (
|
|
7
71
|
key TEXT PRIMARY KEY,
|
|
8
72
|
value TEXT NOT NULL
|
|
9
73
|
) STRICT`,`CREATE TABLE IF NOT EXISTS process_identity (
|
|
@@ -29,7 +93,7 @@ var a=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=
|
|
|
29
93
|
payload_json TEXT NOT NULL,
|
|
30
94
|
created_at TEXT NOT NULL,
|
|
31
95
|
PRIMARY KEY (scope, seq)
|
|
32
|
-
) STRICT`];function
|
|
96
|
+
) STRICT`];function Fn(r){if(!r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_meta'").get())return null;let t=r.prepare("SELECT value FROM local_meta WHERE key = 'schema_version'").get();if(!t?.value)return null;let n=Number.parseInt(t.value,10);return Number.isFinite(n)?n:null}function $r(r,e){let t=Fn(r);if(t!==null&&t>1)throw new ie(t,1);r.exec("BEGIN IMMEDIATE");try{for(let n of Wn)r.exec(n);r.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(1)),r.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_applied_at', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e),r.exec("COMMIT")}catch(n){throw r.exec("ROLLBACK"),n}}import{mkdirSync as Bn}from"node:fs";import Un from"node:path";import{DatabaseSync as $n}from"node:sqlite";var ee=class extends Error{constructor(e){super(`local-run-store refused: ${e}`),this.name="FilesystemPolicyError"}},Hn="local-run-store.sqlite",jn=5e3,J=class r{db;now;databasePath;constructor(e,t,n){this.db=e,this.databasePath=t,this.now=n}static open(e){let t=Ke(e.directory,e.classifyOptions);if(t.verdict!=="accepted")throw new ee(t.reason);Bn(e.directory,{recursive:!0,mode:448});let n=Un.join(e.directory,e.filename??Hn),o=new $n(n,{timeout:e.busyTimeoutMs??jn}),s=e.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 ee(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),$r(o,s().toISOString())}catch(i){throw o.close(),i}return new r(o,n,s)}inImmediateTransaction(e){this.db.exec("BEGIN IMMEDIATE");try{let t=e();return this.db.exec("COMMIT"),t}catch(t){throw this.db.exec("ROLLBACK"),t}}registerProcessIdentity(e){let t=this.now().toISOString();return this.inImmediateTransaction(()=>{this.db.prepare(`INSERT INTO process_identity
|
|
33
97
|
(process_key, pid, runtime_version, node_version, started_at, registered_at)
|
|
34
98
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
35
99
|
ON CONFLICT(process_key) DO UPDATE SET
|
|
@@ -53,8 +117,8 @@ var a=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=
|
|
|
53
117
|
LIMIT ?`).all(...s,n).map(u=>({idempotencyKey:u.idempotency_key,operation:u.operation,resultJson:u.result_json,recordedAt:u.recorded_at}))}deleteOperationReceiptsByKeys(e){return e.length===0?0:this.inImmediateTransaction(()=>{let t=this.db.prepare("DELETE FROM operation_receipts WHERE idempotency_key = ?"),n=0;for(let o of e)n+=Number(t.run(o).changes);return n})}getOperationReceipt(e){let t=this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
|
|
54
118
|
FROM operation_receipts WHERE idempotency_key = ?`).get(e);return t?{idempotencyKey:t.idempotency_key,operation:t.operation,resultJson:t.result_json,recordedAt:t.recorded_at}:null}saveRecoveryCheckpoint(e){return this.inImmediateTransaction(()=>{let t=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max_seq FROM recovery_checkpoints WHERE scope = ?").get(e.scope),n=Number(t.max_seq)+1;return this.db.prepare(`INSERT INTO recovery_checkpoints (scope, seq, payload_json, created_at)
|
|
55
119
|
VALUES (?, ?, ?, ?)`).run(e.scope,n,e.payloadJson,this.now().toISOString()),{seq:n}})}latestRecoveryCheckpoint(e){let t=this.db.prepare(`SELECT scope, seq, payload_json, created_at FROM recovery_checkpoints
|
|
56
|
-
WHERE scope = ? ORDER BY seq DESC LIMIT 1`).get(e);return t?{scope:t.scope,seq:t.seq,payloadJson:t.payload_json,createdAt:t.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(e){let t=this.db.prepare(`PRAGMA ${e}`).get();return String(Object.values(t)[0])}close(){this.db.close()}};import{existsSync as Wn,renameSync as $n}from"node:fs";function Hn(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;Wn(o)&&$n(o,`${t}${n}`)}return t}function Me(r){let e=r.quarantineStamp??(r.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=J.open(r);if(s.integrityCheck())return{store:s,recovered:!1,quarantinedTo:null};s.close()}catch(s){if(s.name==="SchemaDowngradeRefusedError"||s.name==="FilesystemPolicyError")throw s;t=s}let n=`${r.directory}/${r.filename??"local-run-store.sqlite"}`,o=Hn(n,e);try{return{store:J.open(r),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}Ye();function Jo(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function qo(){return en.classifyOptions??Jo()}var en={};function zo(r){en=r}var rn=300*1e3,D=null,te=0;function Xo(r){te+=1;try{let e=qo(),t=Me({directory:r,...e?{classifyOptions:e}:{}});return{store:t.store,status:{state:"open",harnessRoot:r,databasePath:t.store.databasePath,schemaVersion:t.store.localSchemaVersion(),recovered:t.recovered,quarantinedTo:t.quarantinedTo,reason:null,openAttempts:te},failedAtMs:null,permanentRefusal:!1}}catch(e){return{store:null,status:{state:"unavailable",harnessRoot:r,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${e.name}: ${e.message}`,openAttempts:te},failedAtMs:Date.now(),permanentRefusal:e.name==="FilesystemPolicyError"||e.name==="SchemaDowngradeRefusedError"}}}function Qo(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=rn}function f(r=Date.now()){let e=yr();return(!D||D.status.harnessRoot!==e||Qo(D,r))&&(Sr(),D=Xo(e)),D.store}function tn(){return D?D.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:te}}function Rr(){return f(),tn()}function Sr(){try{D?.store?.close()}catch{}D=null}function Zo(){Sr(),te=0}I();b();import{existsSync as es,readFileSync as rs}from"node:fs";import{homedir as ts}from"node:os";import ns from"node:path";var os=3e4,x=null;function kr(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return ns.join(ts(),".kynver",`local-run-store-flags-${e}.json`)}function br(r){if(!r||typeof r!="object"||Array.isArray(r))return{};let e=r,t={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=e[o];(s==="off"||s==="shadow"||s==="enforce")&&(t[o]=s)}return t}function ss(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r.response;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.localRunStoreFlags;return t===void 0?null:br(t)}function is(r,e){try{let t=kr(r),n={contractVersion:1,agentOsId:r,flags:br(e),deliveredAt:new Date().toISOString()};ie(t,n),x={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function vr(r=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(x&&r-x.loadedAtMs<os)return x.flags;try{let e=_().agentOsId?.trim();if(!e)return x={flags:{},loadedAtMs:r,file:null},x.flags;let t=kr(e);if(!es(t))return x={flags:{},loadedAtMs:r,file:t},x.flags;let n=JSON.parse(rs(t,"utf8")),o=n?.contractVersion===1?br(n.flags):{};return x={flags:o,loadedAtMs:r,file:t},o}catch{return x={flags:{},loadedAtMs:r,file:null},x.flags}}function as(){x=null}var nn=[{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 on(r){let e=r?.trim().toLowerCase()??"";return e===""?{mode:"off",unknown:!1}:e==="off"||e==="shadow"||e==="enforce"?{mode:e,unknown:!1}:{mode:"off",unknown:!0}}function A(r=process.env){let e={},t={},n=[],o=vr();for(let s of nn){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let c=on(i);e[s.key]=c.mode,t[s.key]="env",c.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let u=o[s.key];if(u){e[s.key]=u,t[s.key]="server";continue}e[s.key]="off",t[s.key]="default"}return{flags:e,sources:t,warnings:n}}function ls(r){return Object.values(r).some(e=>e!=="off")}var R={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};function w(r=process.env){return A(r).flags.dispatchReceipts}function xr(r){return w(r)!=="off"}function _r(r,e){return`dispatch:${r}:${e.taskId}:${e.leaseToken}`}function ne(r,e,t){if(!xr())return;let n=f();if(n)try{n.recordOperationReceipt({idempotencyKey:_r(r,e),operation:`dispatch-${r}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function cs(r){ne("claim",r,{runId:r.runId,workerName:r.workerName,provider:r.provider})}function Er(r){ne("spawned",r)}function we(r,e){ne("released",r,{reasonClass:e})}function us(r){ne("completion-sent",r)}function ds(r,e){ne("completion-acked",r,{outcome:e})}function ps(r){if(!xr())return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(_r("completion-acked",r));if(t){let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}if(n==="acknowledged")return R.completionReplaysObserved+=1,!0}}catch{R.storeFailures+=1}return!1}function ms(r){let e=String(r??"").split(":")[0]?.trim()??"";return e.length>0?e.slice(0,64):"unknown"}function fs(r){if(w()!=="enforce")return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(_r("completion-acked",r));if(!t)return!1;let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}return n==="acknowledged"?(R.completionReplaysShortCircuited+=1,!0):!1}catch{return R.storeFailures+=1,!1}}var gs=600*1e3;function hs(r,e){if(w()!=="enforce")return;let t=f();if(t)try{t.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${r}:${e}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:e})})}catch{R.storeFailures+=1}}function ys(r,e){if(w()!=="enforce")return[];let t=f();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??gs;try{return t.listOperationReceipts({operation:"dispatch-start-failed",recordedAfter:new Date(n-o).toISOString(),limit:200}).filter(s=>{try{return s.resultJson?JSON.parse(s.resultJson).runId===r:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(r.length+1))}).filter(s=>s.length>0)}catch{return R.storeFailures+=1,[]}}function z(r){let e=r.split(":")[0]??"",t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var Rs=900*1e3,sn=10080*60*1e3,Ss=1440*60*1e3,ks=500,bs=300;function Cr(r){let e={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!xr())return e;let t=f();if(!t)return e;let n=r?.nowMs??Date.now(),o=r?.strandedAfterMs??Rs;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-sn).toISOString(),limit:ks}),i=0,l=[];for(let c of s){let p=c.idempotencyKey.slice(15),m=Date.parse(c.recordedAt);if(!Number.isFinite(m)||n-m<o)continue;let d=t.getOperationReceipt(`dispatch:spawned:${p}`),Y=t.getOperationReceipt(`dispatch:released:${p}`);if(d||Y){n-m>=Ss&&l.length+5<=bs&&l.push(c.idempotencyKey,`dispatch:spawned:${p}`,`dispatch:released:${p}`,`dispatch:completion-sent:${p}`,`dispatch:completion-acked:${p}`);continue}let v=p.split(":")[0]??"",V=z(p.slice(v.length+1));if((v?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${v}:`,limit:10}):[]).some(h=>{if(V===null)return!0;let G=h.idempotencyKey.slice(`dispatch:completion-acked:${v}:`.length),K=z(G);return K===null||K>=V}))continue;let y=!1;if(r?.hasLiveWorker&&c.resultJson)try{let h=JSON.parse(c.resultJson);h.runId&&h.workerName&&(y=r.hasLiveWorker({runId:h.runId,workerName:h.workerName}))}catch{y=!1}y||(i+=1)}let u=l.length>0?t.deleteOperationReceiptsByKeys(l):0;if(w()==="enforce"){let c=t.listOperationReceipts({limit:100}).filter(p=>{let m=Date.parse(p.recordedAt);return Number.isFinite(m)&&n-m>=sn}).map(p=>p.idempotencyKey);if(c.length>0){let p=t.deleteOperationReceiptsByKeys(c);u+=p,R.agedReceiptsPruned+=p}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:u}}catch{return R.storeFailures+=1,e}}function Ar(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function vs(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as Is,readFileSync as Ts}from"node:fs";var $=900*1e3,Or="admission-shadow",wr="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Oe=!1;function xs(){Oe=!1}function H(r=process.env){return A(r).flags.admission}function Ie(r,e){return`${wr}${r}:${e}`}function _s(r,e){if(H()==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Ie(r,e),Or,$)}catch{E.storeFailures+=1}}function Ir(r,e){if(H()==="off")return;let t=f();if(t)try{t.releaseAdmission(Ie(r,e),Or)}catch{E.storeFailures+=1}}function Es(r){let e={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(H()==="off")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(d=>Ie(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:wr,limit:500}),s=new Set(o.map(d=>d.key)),i=[...n].filter(d=>!s.has(d)).length,l=o.filter(d=>!n.has(d.key)).length,u=!Oe;Oe=!0,!u&&i>0&&(E.missingForLive+=i);let c=0;for(let d of r.liveWorkers)t.tryReserveAdmission(Ie(d.runId,d.workerName),Or,$),c+=1;let p=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(p+=1,E.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:wr,limit:500}).length,refreshed:c,deadReleased:p,missingForLive:i,orphaned:l,adoptionPass:u}}catch{return E.storeFailures+=1,e}}function Tr(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function Cs(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Oe=!1}var Pe="worker-slot-n:",Te=64;function an(r){return`${Pe}${r}`}function Ne(r,e){return`${r}:${e}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function As(r){if(H()!=="enforce")return{admitted:!0};let e=f();if(!e)return{admitted:!0};let t=Math.max(0,Math.min(Te,Math.floor(r.maxSlots)));if(r.diskActiveWorkers>=t)return C.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=Ne(r.runId,r.workerName);for(let o=0;o<t;o+=1)if(e.tryReserveAdmission(an(o),n,$).acquired)return{admitted:!0,slot:o};return C.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return C.enforceStoreFailures+=1,{admitted:!0}}}function Nr(r,e){if(H()==="off")return;let t=f();if(t)try{let n=Ne(r,e),o=t.listAdmissionReservations({keyPrefix:Pe,limit:Te});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function ws(r){let e={refreshed:0,deadReleased:0,adopted:0};if(H()!=="enforce")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(c=>Ne(c.runId,c.workerName))),o=t.listAdmissionReservations({keyPrefix:Pe,limit:Te}),s=0,i=0,l=new Set;for(let c of o)n.has(c.owner)?(t.tryReserveAdmission(c.key,c.owner,$),l.add(c.owner),s+=1):t.releaseAdmission(c.key,c.owner)&&(i+=1);let u=0;for(let c of r.liveWorkers){let p=Ne(c.runId,c.workerName);if(!l.has(p)){for(let m=0;m<Te;m+=1)if(t.tryReserveAdmission(an(m),p,$).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,e}}function Pr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function Os(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var Ns="dispatch:claim:",Ps=900*1e3,Ds=10080*60*1e3,Ls=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function ln(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=Is("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(Ts(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(r))return Number(t)}catch{}return null}async function Dr(r){let e=w(),t={mode:e,scanned:0,outcomes:[]};if(e!=="enforce")return t;let n=f();if(!n)return t;let o=r.nowMs??Date.now(),s=r.strandedAfterMs??Ps,i=r.findOrphanPid??ln,l=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-Ds).toISOString(),limit:Ls})}catch{return O.recoveryStoreFailures+=1,t}for(let c of u){let p=c.idempotencyKey.slice(Ns.length),m=p.split(":")[0]??"",d=p.slice(m.length+1);if(!(!m||!d))try{let Y=Date.parse(c.recordedAt);if(!Number.isFinite(Y)||o-Y<s||n.getOperationReceipt(`dispatch:spawned:${p}`)||n.getOperationReceipt(`dispatch:released:${p}`))continue;let v=z(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${m}:`,limit:10}).some(K=>{if(v===null)return!0;let Q=z(K.idempotencyKey.slice(`dispatch:completion-acked:${m}:`.length));return Q===null||Q>=v}))continue;let X={};try{X=c.resultJson?JSON.parse(c.resultJson):{}}catch{X={}}let y=X.runId??null,h=X.workerName??null;if(y&&h&&r.hasLiveWorker({runId:y,workerName:h})){Er({taskId:m,leaseToken:d}),l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let K=r.worktreePathFor({runId:y,workerName:h}),Q=K?i(K):null;if(Q!==null){O.recoveryDeferredOrphans+=1,l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${Q} references ${K}`});continue}}if(!y){l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let G=await r.releaseClaim({taskId:m,leaseToken:d,runId:y});G.released?(we({taskId:m,leaseToken:d},"restart_recovery"),h&&(Ir(y,h),Nr(y,h)),O.recoveredStrandedClaims+=1,l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"released"})):G.transportError?l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:G.detail}):(we({taskId:m,leaseToken:d},"restart_recovery_refused"),l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:G.detail}))}catch{O.recoveryStoreFailures+=1}}return{mode:e,scanned:u.length,outcomes:l}}function Lr(){return{"dispatchReceipts.recoveredStrandedClaims":O.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":O.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":O.recoveryStoreFailures}}function Ks(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}fe();import Vs from"node:path";var Ms="kynver-harness:",Fs="@runner:";function cn(r,e){let t=r.trim(),n=e.trim();return`${Ms}${t}${Fs}${n}`}I();import pn from"node:os";var Bs="embedded-1",Us=[{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"}],Ws={"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(`
|
|
120
|
+
WHERE scope = ? ORDER BY seq DESC LIMIT 1`).get(e);return t?{scope:t.scope,seq:t.seq,payloadJson:t.payload_json,createdAt:t.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(e){let t=this.db.prepare(`PRAGMA ${e}`).get();return String(Object.values(t)[0])}close(){this.db.close()}};import{existsSync as Yn,renameSync as Vn}from"node:fs";function Gn(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;Yn(o)&&Vn(o,`${t}${n}`)}return t}function We(r){let e=r.quarantineStamp??(r.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=J.open(r);if(s.integrityCheck())return{store:s,recovered:!1,quarantinedTo:null};s.close()}catch(s){if(s.name==="SchemaDowngradeRefusedError"||s.name==="FilesystemPolicyError")throw s;t=s}let n=`${r.directory}/${r.filename??"local-run-store.sqlite"}`,o=Gn(n,e);try{return{store:J.open(r),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}Ye();function rs(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function ts(){return on.classifyOptions??rs()}var on={};function ns(r){on=r}var sn=300*1e3,D=null,ne=0;function os(r){ne+=1;try{let e=ts(),t=We({directory:r,...e?{classifyOptions:e}:{}});return{store:t.store,status:{state:"open",harnessRoot:r,databasePath:t.store.databasePath,schemaVersion:t.store.localSchemaVersion(),recovered:t.recovered,quarantinedTo:t.quarantinedTo,reason:null,openAttempts:ne},failedAtMs:null,permanentRefusal:!1}}catch(e){return{store:null,status:{state:"unavailable",harnessRoot:r,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${e.name}: ${e.message}`,openAttempts:ne},failedAtMs:Date.now(),permanentRefusal:e.name==="FilesystemPolicyError"||e.name==="SchemaDowngradeRefusedError"}}}function ss(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=sn}function m(r=Date.now()){let e=Rr();return(!D||D.status.harnessRoot!==e||ss(D,r))&&(br(),D=os(e)),D.store}function an(){return D?D.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:ne}}function Sr(){return m(),an()}function br(){try{D?.store?.close()}catch{}D=null}function is(){br(),ne=0}I();b();import{existsSync as as,readFileSync as ls}from"node:fs";import{homedir as cs}from"node:os";import us from"node:path";var ds=3e4,v=null;function kr(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return us.join(cs(),".kynver",`local-run-store-flags-${e}.json`)}function xr(r){if(!r||typeof r!="object"||Array.isArray(r))return{};let e=r,t={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=e[o];(s==="off"||s==="shadow"||s==="enforce")&&(t[o]=s)}return t}function ps(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r.response;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.localRunStoreFlags;return t===void 0?null:xr(t)}function fs(r,e){try{let t=kr(r),n={contractVersion:1,agentOsId:r,flags:xr(e),deliveredAt:new Date().toISOString()};ae(t,n),v={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function vr(r=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(v&&r-v.loadedAtMs<ds)return v.flags;try{let e=_().agentOsId?.trim();if(!e)return v={flags:{},loadedAtMs:r,file:null},v.flags;let t=kr(e);if(!as(t))return v={flags:{},loadedAtMs:r,file:t},v.flags;let n=JSON.parse(ls(t,"utf8")),o=n?.contractVersion===1?xr(n.flags):{};return v={flags:o,loadedAtMs:r,file:t},o}catch{return v={flags:{},loadedAtMs:r,file:null},v.flags}}function ms(){v=null}var ln=[{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 cn(r){let e=r?.trim().toLowerCase()??"";return e===""?{mode:"off",unknown:!1}:e==="off"||e==="shadow"||e==="enforce"?{mode:e,unknown:!1}:{mode:"off",unknown:!0}}function A(r=process.env){let e={},t={},n=[],o=vr();for(let s of ln){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let c=cn(i);e[s.key]=c.mode,t[s.key]="env",c.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let u=o[s.key];if(u){e[s.key]=u,t[s.key]="server";continue}e[s.key]="off",t[s.key]="default"}return{flags:e,sources:t,warnings:n}}function gs(r){return Object.values(r).some(e=>e!=="off")}var R={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};function w(r=process.env){return A(r).flags.dispatchReceipts}function _r(r){return w(r)!=="off"}function Er(r,e){return`dispatch:${r}:${e.taskId}:${e.leaseToken}`}function oe(r,e,t){if(!_r())return;let n=m();if(n)try{n.recordOperationReceipt({idempotencyKey:Er(r,e),operation:`dispatch-${r}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function hs(r){oe("claim",r,{runId:r.runId,workerName:r.workerName,provider:r.provider})}function Cr(r){oe("spawned",r)}function Oe(r,e){oe("released",r,{reasonClass:e})}function ys(r){oe("completion-sent",r)}function Rs(r,e){oe("completion-acked",r,{outcome:e})}function Ss(r){if(!_r())return!1;let e=m();if(!e)return!1;try{let t=e.getOperationReceipt(Er("completion-acked",r));if(t){let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}if(n==="acknowledged")return R.completionReplaysObserved+=1,!0}}catch{R.storeFailures+=1}return!1}function bs(r){let e=String(r??"").split(":")[0]?.trim()??"";return e.length>0?e.slice(0,64):"unknown"}function ks(r){if(w()!=="enforce")return!1;let e=m();if(!e)return!1;try{let t=e.getOperationReceipt(Er("completion-acked",r));if(!t)return!1;let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}return n==="acknowledged"?(R.completionReplaysShortCircuited+=1,!0):!1}catch{return R.storeFailures+=1,!1}}var xs=600*1e3;function vs(r,e){if(w()!=="enforce")return;let t=m();if(t)try{t.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${r}:${e}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:e})})}catch{R.storeFailures+=1}}function _s(r,e){if(w()!=="enforce")return[];let t=m();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??xs;try{return t.listOperationReceipts({operation:"dispatch-start-failed",recordedAfter:new Date(n-o).toISOString(),limit:200}).filter(s=>{try{return s.resultJson?JSON.parse(s.resultJson).runId===r:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(r.length+1))}).filter(s=>s.length>0)}catch{return R.storeFailures+=1,[]}}function X(r){let e=r.split(":")[0]??"",t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var Es=900*1e3,un=10080*60*1e3,Cs=1440*60*1e3,As=500,ws=300;function Ar(r){let e={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!_r())return e;let t=m();if(!t)return e;let n=r?.nowMs??Date.now(),o=r?.strandedAfterMs??Es;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-un).toISOString(),limit:As}),i=0,l=[];for(let c of s){let p=c.idempotencyKey.slice(15),f=Date.parse(c.recordedAt);if(!Number.isFinite(f)||n-f<o)continue;let d=t.getOperationReceipt(`dispatch:spawned:${p}`),Y=t.getOperationReceipt(`dispatch:released:${p}`);if(d||Y){n-f>=Cs&&l.length+5<=ws&&l.push(c.idempotencyKey,`dispatch:spawned:${p}`,`dispatch:released:${p}`,`dispatch:completion-sent:${p}`,`dispatch:completion-acked:${p}`);continue}let x=p.split(":")[0]??"",V=X(p.slice(x.length+1));if((x?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${x}:`,limit:10}):[]).some(h=>{if(V===null)return!0;let G=h.idempotencyKey.slice(`dispatch:completion-acked:${x}:`.length),K=X(G);return K===null||K>=V}))continue;let y=!1;if(r?.hasLiveWorker&&c.resultJson)try{let h=JSON.parse(c.resultJson);h.runId&&h.workerName&&(y=r.hasLiveWorker({runId:h.runId,workerName:h.workerName}))}catch{y=!1}y||(i+=1)}let u=l.length>0?t.deleteOperationReceiptsByKeys(l):0;if(w()==="enforce"){let c=t.listOperationReceipts({limit:100}).filter(p=>{let f=Date.parse(p.recordedAt);return Number.isFinite(f)&&n-f>=un}).map(p=>p.idempotencyKey);if(c.length>0){let p=t.deleteOperationReceiptsByKeys(c);u+=p,R.agedReceiptsPruned+=p}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:u}}catch{return R.storeFailures+=1,e}}function wr(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function Os(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as Ms,readFileSync as Ws}from"node:fs";var $=900*1e3,Ir="admission-shadow",Or="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Ie=!1;function Is(){Ie=!1}function H(r=process.env){return A(r).flags.admission}function Te(r,e){return`${Or}${r}:${e}`}function Ts(r,e){if(H()==="off")return;let t=m();if(t)try{t.tryReserveAdmission(Te(r,e),Ir,$)}catch{E.storeFailures+=1}}function Tr(r,e){if(H()==="off")return;let t=m();if(t)try{t.releaseAdmission(Te(r,e),Ir)}catch{E.storeFailures+=1}}function Ns(r){let e={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(H()==="off")return e;let t=m();if(!t)return e;try{let n=new Set(r.liveWorkers.map(d=>Te(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:Or,limit:500}),s=new Set(o.map(d=>d.key)),i=[...n].filter(d=>!s.has(d)).length,l=o.filter(d=>!n.has(d.key)).length,u=!Ie;Ie=!0,!u&&i>0&&(E.missingForLive+=i);let c=0;for(let d of r.liveWorkers)t.tryReserveAdmission(Te(d.runId,d.workerName),Ir,$),c+=1;let p=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(p+=1,E.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:Or,limit:500}).length,refreshed:c,deadReleased:p,missingForLive:i,orphaned:l,adoptionPass:u}}catch{return E.storeFailures+=1,e}}function Nr(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function Ps(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Ie=!1}var De="worker-slot-n:",Ne=64;function dn(r){return`${De}${r}`}function Pe(r,e){return`${r}:${e}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function Ds(r){if(H()!=="enforce")return{admitted:!0};let e=m();if(!e)return{admitted:!0};let t=Math.max(0,Math.min(Ne,Math.floor(r.maxSlots)));if(r.diskActiveWorkers>=t)return C.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=Pe(r.runId,r.workerName);for(let o=0;o<t;o+=1)if(e.tryReserveAdmission(dn(o),n,$).acquired)return{admitted:!0,slot:o};return C.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return C.enforceStoreFailures+=1,{admitted:!0}}}function Pr(r,e){if(H()==="off")return;let t=m();if(t)try{let n=Pe(r,e),o=t.listAdmissionReservations({keyPrefix:De,limit:Ne});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function Ls(r){let e={refreshed:0,deadReleased:0,adopted:0};if(H()!=="enforce")return e;let t=m();if(!t)return e;try{let n=new Set(r.liveWorkers.map(c=>Pe(c.runId,c.workerName))),o=t.listAdmissionReservations({keyPrefix:De,limit:Ne}),s=0,i=0,l=new Set;for(let c of o)n.has(c.owner)?(t.tryReserveAdmission(c.key,c.owner,$),l.add(c.owner),s+=1):t.releaseAdmission(c.key,c.owner)&&(i+=1);let u=0;for(let c of r.liveWorkers){let p=Pe(c.runId,c.workerName);if(!l.has(p)){for(let f=0;f<Ne;f+=1)if(t.tryReserveAdmission(dn(f),p,$).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,e}}function Dr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function Ks(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var Fs="dispatch:claim:",Bs=900*1e3,Us=10080*60*1e3,$s=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function pn(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=Ms("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(Ws(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(r))return Number(t)}catch{}return null}async function Lr(r){let e=w(),t={mode:e,scanned:0,outcomes:[]};if(e!=="enforce")return t;let n=m();if(!n)return t;let o=r.nowMs??Date.now(),s=r.strandedAfterMs??Bs,i=r.findOrphanPid??pn,l=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-Us).toISOString(),limit:$s})}catch{return O.recoveryStoreFailures+=1,t}for(let c of u){let p=c.idempotencyKey.slice(Fs.length),f=p.split(":")[0]??"",d=p.slice(f.length+1);if(!(!f||!d))try{let Y=Date.parse(c.recordedAt);if(!Number.isFinite(Y)||o-Y<s||n.getOperationReceipt(`dispatch:spawned:${p}`)||n.getOperationReceipt(`dispatch:released:${p}`))continue;let x=X(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${f}:`,limit:10}).some(K=>{if(x===null)return!0;let Z=X(K.idempotencyKey.slice(`dispatch:completion-acked:${f}:`.length));return Z===null||Z>=x}))continue;let Q={};try{Q=c.resultJson?JSON.parse(c.resultJson):{}}catch{Q={}}let y=Q.runId??null,h=Q.workerName??null;if(y&&h&&r.hasLiveWorker({runId:y,workerName:h})){Cr({taskId:f,leaseToken:d}),l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let K=r.worktreePathFor({runId:y,workerName:h}),Z=K?i(K):null;if(Z!==null){O.recoveryDeferredOrphans+=1,l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${Z} references ${K}`});continue}}if(!y){l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let G=await r.releaseClaim({taskId:f,leaseToken:d,runId:y});G.released?(Oe({taskId:f,leaseToken:d},"restart_recovery"),h&&(Tr(y,h),Pr(y,h)),O.recoveredStrandedClaims+=1,l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"released"})):G.transportError?l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:G.detail}):(Oe({taskId:f,leaseToken:d},"restart_recovery_refused"),l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:G.detail}))}catch{O.recoveryStoreFailures+=1}}return{mode:e,scanned:u.length,outcomes:l}}function Kr(){return{"dispatchReceipts.recoveredStrandedClaims":O.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":O.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":O.recoveryStoreFailures}}function Hs(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}re();import Zs from"node:path";var js="kynver-harness:",Ys="@runner:";function fn(r,e){let t=r.trim(),n=e.trim();return`${js}${t}${Ys}${n}`}I();import hn from"node:os";var Vs="embedded-1",Gs=[{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"}],Js={"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(`
|
|
57
121
|
`),"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(`
|
|
58
122
|
`),"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(`
|
|
59
123
|
`),"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(`
|
|
60
|
-
`)}
|
|
124
|
+
`)},qs={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},mn={version:Vs,generatedAt:"1970-01-01T00:00:00.000Z",personas:Gs,instructions:Js,policyThresholds:qs};var zs=mn;function gn(){return zs.version}W();function L(r){return r?.trim()?r.trim():null}function yn(r={}){let e=r.env??process.env,t=_();return{runnerId:L(t.runnerId)??L(e.KYNVER_RUNTIME_ID)??L(e.OPENCLAW_RUNTIME_ID)??L(e.HOSTNAME)??hn.hostname(),hostname:L(e.HOSTNAME)??hn.hostname(),profile:L(e.KYNVER_RUNNER_PROFILE)??L(e.OPENCLAW_RUNNER_PROFILE),harnessRepo:L(e.KYNVER_HARNESS_REPO)??L(e.KYNVER_DEFAULT_REPO),runId:r.runId??null,instructionBundleVersion:gn()}}function Rn(r){let e=String(r).trim();return e.startsWith("krc1.")?{"Content-Type":"application/json","X-Kynver-Runner-Token":e}:{"Content-Type":"application/json","X-Kynver-Cron-Secret":e,"X-OpenClaw-Cron-Secret":e,"X-Kynver-Runtime-Secret":e}}de();I();function kn(r){if(r!==void 0&&Number.isFinite(r)&&r>0)return Math.floor(r);let e=Number(process.env.KYNVER_CALLBACK_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):3e4}function Sn(r){return new Error(`callback timeout after ${r}ms`)}async function Xs(r,e){let t=kn(e),n=new AbortController,o,s=!1;try{return await Promise.race([r(n.signal),new Promise((i,l)=>{o=setTimeout(()=>{s=!0,n.abort(),l(Sn(t))},t)})])}catch(i){throw s?Sn(t):i}finally{o&&clearTimeout(o)}}function Qs(r,e){let t=kn(e);return{ok:!1,status:0,response:{error:r instanceof Error?r.message:String(r),timeoutMs:t}}}async function bn(r,e,t,n){try{return await Xs(async o=>{let s=await ue(r,{method:"POST",headers:Rn(e),body:JSON.stringify(t),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 Qs(o,n?.timeoutMs)}}async function xn(r,e,t,n){let o=await bn(r,e,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await tn(e,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await bn(r,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function vn(r){let e=`${r.baseUrl}/api/agent-os/by-id/${encodeURIComponent(r.agentOsId)}/tasks/${encodeURIComponent(r.taskId)}/release`,t;try{t=await xn(e,r.secret,{agentOsId:r.agentOsId,leaseOwner:r.leaseOwner,...r.leaseToken?.trim()?{leaseToken:r.leaseToken.trim()}:{},...r.failureDetail?{failureDetail:r.failureDetail}:{}},{agentOsId:r.agentOsId,baseUrl:r.baseUrl})}catch(s){return{released:!1,httpOk:!1,transportError:!0,releaseResponse:{ok:!1,error:s.message}}}let n=t.response;return{released:t.ok===!0||n?.ok===!0,httpOk:t.ok===!0,transportError:!1,releaseResponse:t.response??t}}var Mr=!1;function ei(){Mr=!1}async function ri(r){if(Mr||w()!=="enforce")return null;Mr=!0;try{let e=yn().runnerId,t=await Lr({hasLiveWorker:r.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>Zs.join(et().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await vn({baseUrl:r.baseUrl,secret:r.secret,agentOsId:r.agentOsId,taskId:n,leaseOwner:fn(s,e),leaseToken:o});return{released:i.released,transportError:i.transportError,detail:i.httpOk?void 0:JSON.stringify(i.releaseResponse).slice(0,200)}}});return t.outcomes.length>0&&console.error(`[daemon] D1b claim recovery: ${t.outcomes.map(n=>`${n.taskId}:${n.action}`).join(", ")}`),t}catch{return null}}var Fp=600*1e3,se={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function _n(){return{"planOutbox.storeFailures":se.storeFailures,"planOutbox.corruptItemsSeen":se.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":se.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":se.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":se.halfArchivesCompleted}}var g={keeperStoreFailures:0,meshStoreFailures:0,quotaStoreFailures:0,meshLeaseDivergences:0,meshEnforceStaleInversions:0,quotaVerdictDivergences:0};function j(r){return A(process.env).flags[r]}var En="daemon-keeper",ti=1800*1e3;function ni(r){if(j("keeper")==="off")return;let e=m();if(e)try{e.saveRecoveryCheckpoint({scope:En,payloadJson:JSON.stringify(r)})}catch{g.keeperStoreFailures+=1}}function oi(){if(j("keeper")!=="enforce")return null;let r=m();if(!r)return null;try{let e=r.latestRecoveryCheckpoint(En);if(!e)return null;let t=JSON.parse(e.payloadJson),n=Date.now()-Date.parse(e.createdAt);if(!Number.isFinite(n)||n>ti)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function Wr(r){return`mesh-cron-lease:${r}`}function si(r,e){if(j("meshLease")==="off")return;let t=m();if(t)try{let n=t.latestRecoveryCheckpoint(Wr(r));if(n){let o=JSON.parse(n.payloadJson);if((o.leaseToken??null)===(e.leaseToken??null)&&(o.holderBoxId??null)===(e.holderBoxId??null)&&o.authorized===e.authorized)return}t.saveRecoveryCheckpoint({scope:Wr(r),payloadJson:JSON.stringify(e)})}catch{g.meshStoreFailures+=1}}function ii(r,e){let t=j("meshLease");if(t==="off")return null;let n=m();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(Wr(r)),s=o?JSON.parse(o.payloadJson):null,i=s!==null&&((s.leaseToken??null)!==(e?.leaseToken??null)||(s.holderBoxId??null)!==(e?.holderBoxId??null)||(s.authorized??null)!==(e?.authorized??null));return i&&(g.meshLeaseDivergences+=1),t!=="enforce"?null:i&&e?.updatedAt&&s?.updatedAt&&Date.parse(e.updatedAt)>Date.parse(s.updatedAt)?(g.meshEnforceStaleInversions+=1,null):s}catch{return g.meshStoreFailures+=1,null}}function Le(r){return`quota-cooldown:${r}`}var Cn="quota-preflight";function ai(r,e){if(j("quota")==="off")return;let t=m();if(t)try{t.tryReserveAdmission(Le(r),Cn,e)}catch{g.quotaStoreFailures+=1}}function li(r){if(j("quota")==="off")return;let e=m();if(e)try{e.releaseAdmission(Le(r),Cn)}catch{g.quotaStoreFailures+=1}}function ci(r,e){let t=j("quota");if(t==="off")return null;let n=m();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:Le(r),limit:50}).find(i=>i.key===Le(r)),s=!!o;return s!==e&&(g.quotaVerdictDivergences+=1),t==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return g.quotaStoreFailures+=1,null}}function Fr(){return{"keeper.storeFailures":g.keeperStoreFailures,"meshLease.storeFailures":g.meshStoreFailures,"meshLease.divergences":g.meshLeaseDivergences,"meshLease.enforceStaleInversions":g.meshEnforceStaleInversions,"quota.storeFailures":g.quotaStoreFailures,"quota.verdictDivergences":g.quotaVerdictDivergences}}function ui(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function di(r){let e=Sr(),t=A(r?.env??process.env),n=(r?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,wr());let s=Ar({nowMs:n,hasLiveWorker:r?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,Kr())}return t.flags.planOutbox!=="off"&&Object.assign(o,_n()),t.flags.admission!=="off"&&(Object.assign(o,Nr()),t.flags.admission==="enforce"&&Object.assign(o,Dr())),(t.flags.keeper!=="off"||t.flags.meshLease!=="off"||t.flags.quota!=="off")&&Object.assign(o,Fr()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:e.state,schemaVersion:e.schemaVersion,recovered:e.recovered,unavailableClass:e.reason?e.reason.split(":")[0]??null:null,flags:t.flags,flagSources:t.sources,flagWarningCount:t.warnings.length,divergenceCounters:o}}export{$ as ADMISSION_RESERVATION_TTL_MS,De as ADMISSION_SLOT_KEY_PREFIX,ee as FilesystemPolicyError,sn as LOCAL_RUN_STORE_OPEN_RETRY_MS,ln as LOCAL_RUN_STORE_SURFACES,Me as LOCAL_SCHEMA_VERSION,ie as SchemaDowngradeRefusedError,J as SqliteLocalRunStore,Ks as __resetAdmissionEnforceCountersForTests,Ps as __resetAdmissionShadowCountersForTests,Hs as __resetDispatchClaimRecoveryForTests,Os as __resetDispatchReceiptCountersForTests,is as __resetLocalRunStoreLifecycleForTests,ms as __resetRemoteSurfaceFlagsCacheForTests,ui as __resetSmallSurfaceCountersForTests,ei as __resetStartupClaimRecoveryForTests,ns as __setLocalRunStoreLifecycleTestOverrides,Ds as acquireWorkerAdmissionSlot,Dr as admissionEnforceCounters,Nr as admissionShadowCounters,gs as anyLocalRunStoreSurfaceActive,ci as assessQuotaCooldownReservation,di as buildLocalRunStoreTickPosture,Ke as classifyDatabaseDirectory,li as clearQuotaCooldownReservation,br as closeLocalRunStore,Kr as dispatchClaimRecoveryCounters,wr as dispatchReceiptCounters,w as dispatchReceiptsMode,ps as extractLocalRunStoreFlagsFromOperatorTickResponse,pn as findLiveProcessByCmdlinePath,m as getLocalRunStore,an as getLocalRunStoreLifecycleStatus,vr as getRemoteSurfaceFlags,X as leaseTokenAttempt,_s as listRecentDispatchStartFailures,ri as maybeRunStartupClaimRecovery,Ss as noteCompletionReplayIfAcked,We as openSqliteLocalRunStoreWithRecovery,cn as parseLocalRunStoreSurfaceMode,fs as persistRemoteSurfaceFlags,Sr as probeLocalRunStore,ii as readMeshLeaseCheckpoint,Is as rearmAdmissionAdoptionPass,Ns as reconcileAdmissionShadow,Ls as reconcileNumberedAdmissionSlots,Rs as recordCompletionAckedReceipt,ys as recordCompletionSentReceipt,hs as recordDispatchClaimReceipt,Oe as recordDispatchReleasedReceipt,Cr as recordDispatchSpawnedReceipt,vs as recordDispatchStartFailedReceipt,ai as recordQuotaCooldownReservation,Lr as recoverStrandedDispatchClaims,bs as releaseReasonClass,Pr as releaseWorkerAdmissionSlot,Tr as releaseWorkerSlotReservation,kr as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,oi as restoreKeeperBackoffCheckpoint,ni as saveKeeperBackoffCheckpoint,si as saveMeshLeaseCheckpoint,Ar as scanDispatchReceiptInvariants,ks as shouldShortCircuitCompletionReplay,Fr as smallSurfaceCounters,Ts as takeWorkerSlotReservation};
|