@kynver-app/runtime 0.2.118 → 0.2.122
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 +192 -185
- package/dist/daemon-tick-thread.js +111 -0
- package/dist/desktop-entry.js +148 -141
- package/dist/index.js +215 -208
- package/dist/local-run-store/index.js +9 -9
- package/dist/server/cleanup.js +14 -14
- package/dist/server/default-repo.js +1 -1
- package/dist/server/dispatch-routing.js +3 -3
- package/dist/server/memory-cost-enforce.js +2 -2
- package/dist/server/model-routing.js +3 -3
- package/dist/server/monitor.js +7 -7
- package/dist/server/worker-policy.js +2 -2
- package/package.json +2 -2
|
@@ -1,9 +1,9 @@
|
|
|
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 $r}from"node:os";import Hr from"node:path";function
|
|
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
|
-
`,timeoutMs:
|
|
4
|
-
`,timeoutMs:
|
|
5
|
-
`,{mode:384})}function
|
|
6
|
-
`)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:
|
|
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 $r}from"node:os";import Hr from"node:path";function Yn(r){return r==="~"?$r():r.startsWith("~/")||r.startsWith("~\\")?Hr.join($r(),r.slice(2)):r}function M(r){return Hr.resolve(Yn(r))}var W=a(()=>{"use strict"});var jr=a(()=>{"use strict"});import{existsSync as Oi,mkdirSync as Vn,readFileSync as Gn,readdirSync as Ii,renameSync as Jn,rmSync as qn,statSync as Ti,writeFileSync as zn}from"node:fs";import{randomBytes as Xn}from"node:crypto";import Qn from"node:path";function Fe(r){console.error(r),process.exit(1)}function ee(r,e){try{return JSON.parse(Gn(r,"utf8"))}catch(t){if(arguments.length>1)return e;Fe(`failed to read ${r}: ${t.message}`)}}function ie(r,e){Vn(Qn.dirname(r),{recursive:!0});let t=`${r}.${process.pid}.${Xn(4).toString("hex")}.tmp`;try{zn(t,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`),Jn(t,r)}catch(n){try{qn(t,{force:!0})}catch{}throw n}}function ae(r){return String(r).replace(/\/+$/,"")}var k=a(()=>{"use strict";jr()});var Zn,Ki,eo,Mi,Yr=a(()=>{"use strict";Zn=["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"],Ki=new Set(Zn),eo=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],Mi=new Set(eo)});var le=a(()=>{"use strict";W();k();Yr()});var Vr=a(()=>{"use strict";le()});var We=a(()=>{"use strict";le();W();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 Be(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";k();Gr="kynver.com";Jr=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 de(r,e){return r[e]?.trim()||null}function zr(r){let e=r?.split(":")[0]?.trim();return e?B(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!==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=de(r,"KYNVER_BOX_KIND");if(i)return o&&o!==B(i)&&t.push(`KYNVER_BOX_ID=${de(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=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 Ue(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 oa,sa,$e=a(()=>{"use strict";oa=25*1024*1024*1024,sa=12*1024*1024*1024});var ua,da,Qr=a(()=>{"use strict";$e();ua=5*1024*1024*1024,da=10*1024*1024*1024});var ya,Ra,He=a(()=>{"use strict";Qr();$e();ya=30*1024*1024*1024,Ra=15*1024*1024*1024});function Zr(){return rt()}var fe=a(()=>{"use strict";Ye();k()});var tt=a(()=>{"use strict";fe();k()});var nt=a(()=>{"use strict"});var ot=a(()=>{"use strict";nt();k()});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();k();ge();at();lt()});var ut=a(()=>{"use strict";ge()});var dt=a(()=>{"use strict"});var ll,cl,pt=a(()=>{"use strict";le();ll=10*6e4,cl=60*6e4});var mt=a(()=>{"use strict"});var Ve=a(()=>{"use strict"});var ft=a(()=>{"use strict"});var gt=a(()=>{"use strict";Ve();ft()});var ht=a(()=>{"use strict";ot();ct();ge();ut();dt();pt();mt();gt();Ve();k()});var yt=a(()=>{"use strict";ht();k()});function Rt(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,St=a(()=>{"use strict";Xr();I();F();me();ye();He();fe();tt();yt();k();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=Rt(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";St()});import{homedir as uo}from"node:os";import po from"node:path";var bt,Xe=a(()=>{"use strict";bt=po.join(uo(),".kynver",".env")});var kt=a(()=>{"use strict"});var vt=a(()=>{"use strict";kt()});var xt=a(()=>{"use strict"});var _t=a(()=>{"use strict";k()});var Qe=a(()=>{"use strict";vt();xt();_t()});var Et=a(()=>{"use strict"});var Ct=a(()=>{"use strict";Et()});var Re=a(()=>{"use strict";Xe();W();I();Qe();Ct()});var At=a(()=>{"use strict";F();F()});var wt=a(()=>{"use strict";Xe();Qe();Re()});function Tt(r){if(!It)return r;if(!Ot)throw new Ze;return Ot}function rr(){if(It)throw new er}var Ze,er,It,Ot,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"}},It=!1,Ot=null});import{existsSync as T,mkdirSync as ho,readdirSync as Se,renameSync as Pt,statSync as yo}from"node:fs";import P from"node:path";function Dt(r){try{return yo(r).isDirectory()}catch{return!1}}function Ro(r){if(!T(r))return!0;for(let e of Nt){let t=P.join(r,e);if(T(t)&&(!Dt(t)||Se(t).length>0))return!1}return!0}function So(r){let e=P.join(r,"runs");if(!T(e)||!Dt(e))return!1;for(let t of Se(e,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=P.join(e,t.name,"run.json");if(ee(n,void 0)?.id)return!0}return!1}function bo(r){let e=P.join(r,"runs");if(!T(e))return!1;for(let t of Se(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(ee(P.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function ko(r){let e=P.join(r,"ghost");return T(e)?!T(P.join(e,"runs")):bo(r)}function Lt(r){return So(r.sharedRoot)?Ro(r.forgeRoot)?ko(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 Kt(r,e){ho(e,{recursive:!0});for(let t of Nt){let n=P.join(r,t),o=P.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)){Pt(n,o);continue}Pt(n,o)}}}var Nt,Mt=a(()=>{"use strict";k();Nt=["runs","worktrees"]});import{existsSync as b}from"node:fs";import{homedir as vo}from"node:os";import S from"node:path";function nr(r=process.env){return r.HOME?.trim()||vo()}function or(r=process.env){return S.join(nr(r),".kynver","harness")}function be(r){let e=S.resolve(M(r.trim()));for(;xo.has(S.basename(e));)e=S.dirname(e);return e}function _o(r,e=process.env){return S.join(or(e),r)}function Eo(r=process.env){let e=or(r);if(b(S.join(e,"runs")))return!0;if(b(e)&&!b(S.join(e,"ghost"))&&!b(S.join(e,"forge")))return b(e);let t=S.join(nr(r),Ft);return b(t)}function ke(r){let e=r.env??process.env,t=e.KYNVER_HARNESS_ROOT?.trim()||e.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:be(t),source:"env"};let n=r.configuredHarnessRoot?.trim();if(n)return{harnessRoot:be(n),source:"config"};let o=_o(r.boxKind,e);if(b(S.join(o,"runs"))||b(o)&&!Co(o))return{harnessRoot:o,source:"box_scoped"};let i=or(e);if(r.boxKind==="forge"){let l=Lt({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&&Kt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&Eo(e)){if(b(S.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(b(i)&&!b(S.join(i,"ghost"))&&!b(S.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=S.join(nr(e),Ft);if(b(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function Co(r){if(!b(r))return!0;for(let e of["runs","worktrees"]){let t=S.join(r,e);if(b(t))return!1}return!0}var Ft,xo,sr=a(()=>{"use strict";W();Mt();Ft=S.join(".openclaw","harness");xo=new Set(["runs","worktrees"])});import Wt from"node:os";function ve(r){return r?.trim()?r.trim():null}function Ao(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function wo(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||wo(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??Ao(n.boxKind,Wt.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:Wt.totalmem()}),Y=pe(n.boxKind,d.configuredMaxWorkers??Ue(n.boxKind,d.autoCap)),v=ke({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";We();F();At();I();Re();wt();ue();tr();_e()});var Po,Tu,Ut=a(()=>{"use strict";Po=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],Tu=Po.join("|")});var $t=a(()=>{"use strict";W()});var Ht=a(()=>{"use strict";$t()});import{execFileSync as No}from"node:child_process";function lr(r=process.env){let e=r[Do]?.trim().toLowerCase();return e==="file"?"file":e==="keychain"?"keychain":"auto"}function Lo(r,e,t){let n={encoding:"utf8",timeout:t.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...t.input!==void 0?{input:t.input}:{}};return No(r,e,n)}function Ko(r=process.platform){return r==="darwin"?"macos":r==="linux"?"libsecret":r==="win32"?"windows":null}function ir(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 jt(r={}){if(lr(r.env??process.env)==="file")return null;let t=Ko(r.platform??process.platform);return t?new ar(t,r.exec):null}var U,Do,N,ar,Yt=a(()=>{"use strict";U="kynver",Do="KYNVER_CREDENTIAL_STORE";N=5e3;ar=class{constructor(e,t=Lo){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:N}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",U,"account",e],{timeoutMs:N}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ir("get",e)],{timeoutMs:N}).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:N}):this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${e})`,"service",U,"account",e],{input:`${t}
|
|
3
|
+
`,timeoutMs:N}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ir("set",e)],{input:`${t}
|
|
4
|
+
`,timeoutMs:N})}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:N}):this.backend==="libsecret"?this.exec("secret-tool",["clear","service",U,"account",e],{timeoutMs:N}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ir("delete",e)],{timeoutMs:N})}catch{}}}});function pr(){return cr||(cr=new ur),cr}var dr,Mo,Ee,ur,cr,Vt=a(()=>{"use strict";Yt();dr="api-key",Mo=6e4,Ee=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"}},ur=class{cache=new Map;keychain;env;now;constructor(e={}){this.env=e.env??process.env,this.keychain=e.keychain===void 0?jt({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<Mo)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=lr(this.env);if(!this.keychain){if(n==="keychain")throw new Ee(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 Ee(e);return o}remove(e){this.cache.delete(e),this.keychain?.delete(e)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}},cr=null});import{existsSync as Jt,mkdirSync as Fo,readFileSync as qt,writeFileSync as Wo}from"node:fs";import{homedir as Bo,totalmem as ed}from"node:os";import gr from"node:path";function Uo(r){return{...r,...r.harnessRoot?.trim()?{harnessRoot:M(r.harnessRoot.trim())}:{},...r.defaultRepo?.trim()?{defaultRepo:M(r.defaultRepo.trim())}:{}}}function _(){if(!Jt(Gt))return{};try{return Uo(JSON.parse(qt(Gt,"utf8")))}catch{return{}}}function Ce(){if(rr(),!Jt(mr))return{};try{return JSON.parse(qt(mr,"utf8"))}catch{return{}}}function fr(r){rr(),Fo(hr,{recursive:!0}),Wo(mr,`${JSON.stringify(r,null,2)}
|
|
5
|
+
`,{mode:384})}function $o(r,e,t,n={}){let o=Ce();if(pr().write(r,t)){let i={...o,...n};delete i[e],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],r])).sort(),fr(i);return}fr({...o,...n,[e]:t})}function Ho(r,e){let t=pr().read(r);return t||Ce()[e]}function zt(){return Tt(jo)}function Xt(){return zt().getApiKey()}function Yo(r,e){zt().persistRunnerToken(r,e)}function Vo(r){let e=Qt(r);return e||Jo("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),e}function Qt(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 Be(e)}async function Zt(r,e,t){let n=Xt(),o=Qt(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 Go(e,{baseUrl:o,apiKey:n});return s&&s!==r?(Yo(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 Go(r,e){let t=e?.apiKey||Xt();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${Vo(e?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(r)}/runner-credentials`,s=await ce(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 Jo(r){console.error(r),process.exit(1)}var hr,Gt,mr,hd,yd,jo,I=a(()=>{"use strict";We();W();ue();F();me();ye();He();Re();Bt();Ut();_e();Ht();tr();Vt();hr=gr.join(Bo(),".kynver"),Gt=gr.join(hr,"config.json"),mr=gr.join(hr,"credentials");hd=500*1024*1024,yd=4*1024*1024*1024;jo={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:Ho(dr,"apiKey")},getRunnerToken(r){let e=Ce();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){$o(dr,"apiKey",r)},persistRunnerToken(r,e){fr({...Ce(),runnerToken:e,runnerTokenAgentOsId:r})}}});import en from"node:path";function Ae(r){return be(r)}function yr(){let r=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(r)return Ae(r);let e=_(),t=e.harnessRoot?.trim();if(t)return Ae(t);let n=xe(e,process.env);return n.identity?n.identity.harnessRoot:ke({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function et(r){return en.join(Ae(r),"runs")}function qo(r){return en.join(Ae(r),"worktrees")}function rt(){let r=yr();return{harnessRoot:r,runsDir:et(r),worktreesDir:qo(r)}}var Ye=a(()=>{"use strict";I();sr();_e();k()});import{existsSync as En,realpathSync as Cn,readFileSync as An}from"node:fs";import Wr from"node:path";var wn=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),On=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function In(){try{return An("/proc/self/mounts","utf8")}catch{return null}}function Tn(r){let e=Wr.resolve(r);for(let t=0;t<64;t+=1){if(En(e))try{return Cn.native(e)}catch{return e}let n=Wr.dirname(e);if(n===e)return e;e=n}return e}function Pn(r){return r.replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function Nn(r){let e=[];for(let t of r.split(`
|
|
6
|
+
`)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:Pn(n[1]),fsType:n[2]})}return e}function Br(r,e=process.platform){return e==="win32"?r.replace(/\\/g,"/"):r}function Dn(r,e){let t=null,n=Br(r);for(let o of e){let s=Br(o.mountPoint),i=s.endsWith("/")?s:`${s}/`;(n===s||`${n}/`.startsWith(i))&&(!t||o.mountPoint.length>t.mountPoint.length)&&(t=o)}return t}function Le(r,e){let n=(e?.resolveRealPath??Tn)(r),o=(e?.mountsSource??In)();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=Dn(n,Nn(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 On.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}:wn.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 Ke=1,se=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"}},Ln=[`CREATE TABLE IF NOT EXISTS local_meta (
|
|
7
7
|
key TEXT PRIMARY KEY,
|
|
8
8
|
value TEXT NOT NULL
|
|
9
9
|
) STRICT`,`CREATE TABLE IF NOT EXISTS process_identity (
|
|
@@ -29,7 +29,7 @@ var a=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=
|
|
|
29
29
|
payload_json TEXT NOT NULL,
|
|
30
30
|
created_at TEXT NOT NULL,
|
|
31
31
|
PRIMARY KEY (scope, seq)
|
|
32
|
-
) STRICT`];function
|
|
32
|
+
) STRICT`];function Kn(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 Ur(r,e){let t=Kn(r);if(t!==null&&t>1)throw new se(t,1);r.exec("BEGIN IMMEDIATE");try{for(let n of Ln)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 Mn}from"node:fs";import Fn from"node:path";import{DatabaseSync as Wn}from"node:sqlite";var Z=class extends Error{constructor(e){super(`local-run-store refused: ${e}`),this.name="FilesystemPolicyError"}},Bn="local-run-store.sqlite",Un=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=Le(e.directory,e.classifyOptions);if(t.verdict!=="accepted")throw new Z(t.reason);Mn(e.directory,{recursive:!0,mode:448});let n=Fn.join(e.directory,e.filename??Bn),o=new Wn(n,{timeout:e.busyTimeoutMs??Un}),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 Z(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),Ur(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
33
|
(process_key, pid, runtime_version, node_version, started_at, registered_at)
|
|
34
34
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
35
35
|
ON CONFLICT(process_key) DO UPDATE SET
|
|
@@ -53,8 +53,8 @@ var a=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=
|
|
|
53
53
|
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
54
|
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
55
|
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(`
|
|
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 $n,renameSync as Hn}from"node:fs";function jn(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;$n(o)&&Hn(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=jn(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 zo(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function Xo(){return rn.classifyOptions??zo()}var rn={};function Qo(r){rn=r}var tn=300*1e3,D=null,te=0;function Zo(r){te+=1;try{let e=Xo(),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 es(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=tn}function f(r=Date.now()){let e=yr();return(!D||D.status.harnessRoot!==e||es(D,r))&&(Sr(),D=Zo(e)),D.store}function nn(){return D?D.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:te}}function Rr(){return f(),nn()}function Sr(){try{D?.store?.close()}catch{}D=null}function rs(){Sr(),te=0}I();k();import{existsSync as ts,readFileSync as ns}from"node:fs";import{homedir as os}from"node:os";import ss from"node:path";var is=3e4,x=null;function br(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return ss.join(os(),".kynver",`local-run-store-flags-${e}.json`)}function kr(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 as(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:kr(t)}function ls(r,e){try{let t=br(r),n={contractVersion:1,agentOsId:r,flags:kr(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<is)return x.flags;try{let e=_().agentOsId?.trim();if(!e)return x={flags:{},loadedAtMs:r,file:null},x.flags;let t=br(e);if(!ts(t))return x={flags:{},loadedAtMs:r,file:t},x.flags;let n=JSON.parse(ns(t,"utf8")),o=n?.contractVersion===1?kr(n.flags):{};return x={flags:o,loadedAtMs:r,file:t},o}catch{return x={flags:{},loadedAtMs:r,file:null},x.flags}}function cs(){x=null}var on=[{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 sn(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 on){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let c=sn(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 us(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 ds(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 ps(r){ne("completion-sent",r)}function ms(r,e){ne("completion-acked",r,{outcome:e})}function fs(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 gs(r){let e=String(r??"").split(":")[0]?.trim()??"";return e.length>0?e.slice(0,64):"unknown"}function hs(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 ys=600*1e3;function Rs(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 Ss(r,e){if(w()!=="enforce")return[];let t=f();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??ys;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 bs=900*1e3,an=10080*60*1e3,ks=1440*60*1e3,vs=500,xs=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??bs;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-an).toISOString(),limit:vs}),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>=ks&&l.length+5<=xs&&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>=an}).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 _s(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as Ps,readFileSync as Ns}from"node:fs";var $=900*1e3,Or="admission-shadow",wr="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Oe=!1;function Es(){Oe=!1}function H(r=process.env){return A(r).flags.admission}function Ie(r,e){return`${wr}${r}:${e}`}function Cs(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 As(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 ws(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Oe=!1}var Ne="worker-slot-n:",Te=64;function ln(r){return`${Ne}${r}`}function Pe(r,e){return`${r}:${e}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function Os(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=Pe(r.runId,r.workerName);for(let o=0;o<t;o+=1)if(e.tryReserveAdmission(ln(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=f();if(t)try{let n=Pe(r,e),o=t.listAdmissionReservations({keyPrefix:Ne,limit:Te});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function Is(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=>Pe(c.runId,c.workerName))),o=t.listAdmissionReservations({keyPrefix:Ne,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=Pe(c.runId,c.workerName);if(!l.has(p)){for(let m=0;m<Te;m+=1)if(t.tryReserveAdmission(ln(m),p,$).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,e}}function Nr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function Ts(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var Ds="dispatch:claim:",Ls=900*1e3,Ks=10080*60*1e3,Ms=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function cn(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=Ps("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(Ns(`/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??Ls,i=r.findOrphanPid??cn,l=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-Ks).toISOString(),limit:Ms})}catch{return O.recoveryStoreFailures+=1,t}for(let c of u){let p=c.idempotencyKey.slice(Ds.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),Pr(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 Fs(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}fe();import Js from"node:path";var Ws="kynver-harness:",Bs="@runner:";function un(r,e){let t=r.trim(),n=e.trim();return`${Ws}${t}${Bs}${n}`}I();import mn from"node:os";var Us="embedded-1",$s=[{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"}],Hs={"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
57
|
`),"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
58
|
`),"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
59
|
`),"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
|
-
`)}
|
|
60
|
+
`)},js={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},dn={version:Us,generatedAt:"1970-01-01T00:00:00.000Z",personas:$s,instructions:Hs,policyThresholds:js};var Ys=dn;function pn(){return Ys.version}F();function L(r){return r?.trim()?r.trim():null}function fn(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)??mn.hostname(),hostname:L(e.HOSTNAME)??mn.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:pn()}}function gn(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}}ue();I();function Rn(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 hn(r){return new Error(`callback timeout after ${r}ms`)}async function Vs(r,e){let t=Rn(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(hn(t))},t)})])}catch(i){throw s?hn(t):i}finally{o&&clearTimeout(o)}}function Gs(r,e){let t=Rn(e);return{ok:!1,status:0,response:{error:r instanceof Error?r.message:String(r),timeoutMs:t}}}async function yn(r,e,t,n){try{return await Vs(async o=>{let s=await ce(r,{method:"POST",headers:gn(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 Gs(o,n?.timeoutMs)}}async function Sn(r,e,t,n){let o=await yn(r,e,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await Zt(e,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await yn(r,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function bn(r){let e=`${r.baseUrl}/api/agent-os/by-id/${encodeURIComponent(r.agentOsId)}/tasks/${encodeURIComponent(r.taskId)}/release`,t;try{t=await Sn(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 Kr=!1;function qs(){Kr=!1}async function zs(r){if(Kr||w()!=="enforce")return null;Kr=!0;try{let e=fn().runnerId,t=await Dr({hasLiveWorker:r.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>Js.join(Zr().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await bn({baseUrl:r.baseUrl,secret:r.secret,agentOsId:r.agentOsId,taskId:n,leaseOwner:un(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 xp=600*1e3,oe={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function kn(){return{"planOutbox.storeFailures":oe.storeFailures,"planOutbox.corruptItemsSeen":oe.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":oe.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":oe.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":oe.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 vn="daemon-keeper",Xs=1800*1e3;function Qs(r){if(j("keeper")==="off")return;let e=f();if(e)try{e.saveRecoveryCheckpoint({scope:vn,payloadJson:JSON.stringify(r)})}catch{g.keeperStoreFailures+=1}}function Zs(){if(j("keeper")!=="enforce")return null;let r=f();if(!r)return null;try{let e=r.latestRecoveryCheckpoint(vn);if(!e)return null;let t=JSON.parse(e.payloadJson),n=Date.now()-Date.parse(e.createdAt);if(!Number.isFinite(n)||n>Xs)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function Mr(r){return`mesh-cron-lease:${r}`}function ei(r,e){if(j("meshLease")==="off")return;let t=f();if(t)try{let n=t.latestRecoveryCheckpoint(Mr(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:Mr(r),payloadJson:JSON.stringify(e)})}catch{g.meshStoreFailures+=1}}function ri(r,e){let t=j("meshLease");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(Mr(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 De(r){return`quota-cooldown:${r}`}var xn="quota-preflight";function ti(r,e){if(j("quota")==="off")return;let t=f();if(t)try{t.tryReserveAdmission(De(r),xn,e)}catch{g.quotaStoreFailures+=1}}function ni(r){if(j("quota")==="off")return;let e=f();if(e)try{e.releaseAdmission(De(r),xn)}catch{g.quotaStoreFailures+=1}}function oi(r,e){let t=j("quota");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:De(r),limit:50}).find(i=>i.key===De(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 si(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function ii(r){let e=Rr(),t=A(r?.env??process.env),n=(r?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,Ar());let s=Cr({nowMs:n,hasLiveWorker:r?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,Lr())}return t.flags.planOutbox!=="off"&&Object.assign(o,kn()),t.flags.admission!=="off"&&(Object.assign(o,Tr()),t.flags.admission==="enforce"&&Object.assign(o,Nr())),(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,Ne as ADMISSION_SLOT_KEY_PREFIX,Z as FilesystemPolicyError,tn as LOCAL_RUN_STORE_OPEN_RETRY_MS,on as LOCAL_RUN_STORE_SURFACES,Ke as LOCAL_SCHEMA_VERSION,se as SchemaDowngradeRefusedError,J as SqliteLocalRunStore,Ts as __resetAdmissionEnforceCountersForTests,ws as __resetAdmissionShadowCountersForTests,Fs as __resetDispatchClaimRecoveryForTests,_s as __resetDispatchReceiptCountersForTests,rs as __resetLocalRunStoreLifecycleForTests,cs as __resetRemoteSurfaceFlagsCacheForTests,si as __resetSmallSurfaceCountersForTests,qs as __resetStartupClaimRecoveryForTests,Qo as __setLocalRunStoreLifecycleTestOverrides,Os as acquireWorkerAdmissionSlot,Nr as admissionEnforceCounters,Tr as admissionShadowCounters,us as anyLocalRunStoreSurfaceActive,oi as assessQuotaCooldownReservation,ii as buildLocalRunStoreTickPosture,Le as classifyDatabaseDirectory,ni as clearQuotaCooldownReservation,Sr as closeLocalRunStore,Lr as dispatchClaimRecoveryCounters,Ar as dispatchReceiptCounters,w as dispatchReceiptsMode,as as extractLocalRunStoreFlagsFromOperatorTickResponse,cn as findLiveProcessByCmdlinePath,f as getLocalRunStore,nn as getLocalRunStoreLifecycleStatus,vr as getRemoteSurfaceFlags,z as leaseTokenAttempt,Ss as listRecentDispatchStartFailures,zs as maybeRunStartupClaimRecovery,fs as noteCompletionReplayIfAcked,Me as openSqliteLocalRunStoreWithRecovery,sn as parseLocalRunStoreSurfaceMode,ls as persistRemoteSurfaceFlags,Rr as probeLocalRunStore,ri as readMeshLeaseCheckpoint,Es as rearmAdmissionAdoptionPass,As as reconcileAdmissionShadow,Is as reconcileNumberedAdmissionSlots,ms as recordCompletionAckedReceipt,ps as recordCompletionSentReceipt,ds as recordDispatchClaimReceipt,we as recordDispatchReleasedReceipt,Er as recordDispatchSpawnedReceipt,Rs as recordDispatchStartFailedReceipt,ti as recordQuotaCooldownReservation,Dr as recoverStrandedDispatchClaims,gs as releaseReasonClass,Pr as releaseWorkerAdmissionSlot,Ir as releaseWorkerSlotReservation,br as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,Zs as restoreKeeperBackoffCheckpoint,Qs as saveKeeperBackoffCheckpoint,ei as saveMeshLeaseCheckpoint,Cr as scanDispatchReceiptInvariants,hs as shouldShortCircuitCompletionReplay,Fr as smallSurfaceCounters,Cs as takeWorkerSlotReservation};
|