@kynver-app/runtime 0.2.157 → 0.2.161

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.
@@ -1,5 +1,5 @@
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 Yr}from"node:os";import Vr from"node:path";function ro(r){return r==="~"?Yr():r.startsWith("~/")||r.startsWith("~\\")?Vr.join(Yr(),r.slice(2)):r}function I(r){return Vr.resolve(ro(r))}var W=a(()=>{"use strict"});var Gr=a(()=>{"use strict"});import{existsSync as qi,mkdirSync as to,readFileSync as no,readdirSync as zi,renameSync as oo,rmSync as so,statSync as Xi,writeFileSync as io}from"node:fs";import{randomBytes as ao}from"node:crypto";import lo from"node:path";function Fe(r){console.error(r),process.exit(1)}function J(r,e){try{return JSON.parse(no(r,"utf8"))}catch(t){if(arguments.length>1)return e;Fe(`failed to read ${r}: ${t.message}`)}}function ie(r,e){to(lo.dirname(r),{recursive:!0});let t=`${r}.${process.pid}.${ao(4).toString("hex")}.tmp`;try{io(t,`${JSON.stringify(e,null,2)}
2
- `),oo(t,r)}catch(n){try{so(t,{force:!0})}catch{}throw n}}function ae(r){return String(r).replace(/\/+$/,"")}var b=a(()=>{"use strict";Gr()});var co,ta,uo,na,Jr=a(()=>{"use strict";co=["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"],ta=new Set(co),uo=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],na=new Set(uo)});var le=a(()=>{"use strict";W();b();Jr()});import{homedir as qr}from"node:os";import We from"node:path";function mo(r=qr()){return We.join(r,".kynver",fo)}function Xr(r,e=qr()){return We.resolve(r)===We.resolve(mo(e))}var fo,zr,Be=a(()=>{"use strict";le();fo="workspace",zr="main"});var Ue=a(()=>{"use strict";le();W();Be()});var Qr=a(()=>{"use strict"});var Zr=a(()=>{"use strict";Qr()});function tt(r){let e=ae(r);try{let t=new URL(e);return t.hostname.toLowerCase()===et?(t.hostname=`www.${et}`,ae(t.toString())):e}catch{return e}}function $e(r){if(r?.trim())return tt(ae(r.trim()))}async function ce(r,e,t=fetch){let n=tt(r),o=new Headers(e?.headers),s=0;for(;s<=rt;){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 ${rt} redirects for ${r}`)}var et,rt,ue=a(()=>{"use strict";b();et="kynver.com";rt=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 nt(r){let e=r?.split(":")[0]?.trim();return e?B(e):null}function q(r=process.env,e={}){let t=[],n=nt(e.boxId),o=nt(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 He(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 fe=a(()=>{"use strict"});var ot=a(()=>{"use strict"});var Ia,Ta,je=a(()=>{"use strict";Ia=25*1024*1024*1024,Ta=12*1024*1024*1024});var Ka,Ma,st=a(()=>{"use strict";je();Ka=5*1024*1024*1024,Ma=10*1024*1024*1024});var Ha,ja,Ye=a(()=>{"use strict";st();je();Ha=30*1024*1024*1024,ja=15*1024*1024*1024});function it(){return lt()}var ee=a(()=>{"use strict";Ve();b()});var ut=a(()=>{"use strict";ee();b()});var dt=a(()=>{"use strict"});var pt=a(()=>{"use strict";dt();b()});var ft=a(()=>{"use strict"});var mt=a(()=>{"use strict";ft()});var ge=a(()=>{"use strict"});var ho,yo,pl,Ge=a(()=>{"use strict";ho="claude-sonnet-5-5",yo="claude-opus-5-5",pl={[ho]:"claude-sonnet-4-6",[yo]:"claude-opus-4-8"}});var gt=a(()=>{"use strict"});var ht=a(()=>{"use strict"});var yt=a(()=>{"use strict";mt();b();ge();Ge();gt();ht()});var Tl,Je=a(()=>{"use strict";Tl=String.raw`"use strict";
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 Vr}from"node:os";import Gr from"node:path";function to(r){return r==="~"?Vr():r.startsWith("~/")||r.startsWith("~\\")?Gr.join(Vr(),r.slice(2)):r}function I(r){return Gr.resolve(to(r))}var F=a(()=>{"use strict"});var Jr=a(()=>{"use strict"});import{existsSync as Xi,mkdirSync as no,readFileSync as oo,readdirSync as Qi,renameSync as so,rmSync as io,statSync as Zi,writeFileSync as ao}from"node:fs";import{randomBytes as lo}from"node:crypto";import co from"node:path";function We(r){console.error(r),process.exit(1)}function J(r,e){try{return JSON.parse(oo(r,"utf8"))}catch(t){if(arguments.length>1)return e;We(`failed to read ${r}: ${t.message}`)}}function ie(r,e){no(co.dirname(r),{recursive:!0});let t=`${r}.${process.pid}.${lo(4).toString("hex")}.tmp`;try{ao(t,`${JSON.stringify(e,null,2)}
2
+ `),so(t,r)}catch(n){try{io(t,{force:!0})}catch{}throw n}}function ae(r){return String(r).replace(/\/+$/,"")}var b=a(()=>{"use strict";Jr()});var uo,oa,po,sa,qr=a(()=>{"use strict";uo=["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"],oa=new Set(uo),po=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],sa=new Set(po)});var le=a(()=>{"use strict";F();b();qr()});import{homedir as zr}from"node:os";import Fe from"node:path";function go(r=zr()){return Fe.join(r,".kynver",mo)}function Qr(r,e=zr()){return Fe.resolve(r)===Fe.resolve(go(e))}var mo,Xr,Be=a(()=>{"use strict";le();mo="workspace",Xr="main"});var Ue=a(()=>{"use strict";le();F();Be()});var Zr=a(()=>{"use strict"});var et=a(()=>{"use strict";Zr()});function nt(r){let e=ae(r);try{let t=new URL(e);return t.hostname.toLowerCase()===rt?(t.hostname=`www.${rt}`,ae(t.toString())):e}catch{return e}}function $e(r){if(r?.trim())return nt(ae(r.trim()))}async function ce(r,e,t=fetch){let n=nt(r),o=new Headers(e?.headers),s=0;for(;s<=tt;){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 ${tt} redirects for ${r}`)}var rt,tt,ue=a(()=>{"use strict";b();rt="kynver.com";tt=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 ot(r){let e=r?.split(":")[0]?.trim();return e?B(e):null}function q(r=process.env,e={}){let t=[],n=ot(e.boxId),o=ot(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 W=a(()=>{"use strict"});function He(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 fe=a(()=>{"use strict"});var st=a(()=>{"use strict"});var Pa,Na,je=a(()=>{"use strict";Pa=25*1024*1024*1024,Na=12*1024*1024*1024});var Wa,Fa,it=a(()=>{"use strict";je();Wa=5*1024*1024*1024,Fa=10*1024*1024*1024});var Ya,Va,Ye=a(()=>{"use strict";it();je();Ya=30*1024*1024*1024,Va=15*1024*1024*1024});function at(){return ct()}var ee=a(()=>{"use strict";Ve();b()});var dt=a(()=>{"use strict";ee();b()});var pt=a(()=>{"use strict"});var ft=a(()=>{"use strict";pt();b()});var mt=a(()=>{"use strict"});var gt=a(()=>{"use strict";mt()});var ge=a(()=>{"use strict"});var yo,Ro,ml,Ge=a(()=>{"use strict";yo="claude-sonnet-5-5",Ro="claude-opus-5-5",ml={[yo]:"claude-sonnet-4-6",[Ro]:"claude-opus-4-8"}});var ht=a(()=>{"use strict"});var yt=a(()=>{"use strict"});var Rt=a(()=>{"use strict";gt();b();ge();Ge();ht();yt()});var Nl,Je=a(()=>{"use strict";Nl=String.raw`"use strict";
3
3
  const cp = require("child_process"), fs = require("fs");
4
4
  const argv = process.argv.slice(1);
5
5
  const exitFile = argv[0], cmd = argv[1], args = argv.slice(2);
@@ -65,12 +65,12 @@ child.on("error", (e) => {
65
65
  if (!child.pid) finish(127, null, String(e && e.message));
66
66
  });
67
67
  child.on("exit", (code, signal) => finish(code, signal));
68
- `});var Rt=a(()=>{"use strict";ee();b();Je()});var St=a(()=>{"use strict";ge();Ge()});var bt=a(()=>{"use strict"});var Gl,Jl,kt=a(()=>{"use strict";le();Gl=10*6e4,Jl=60*6e4});var xt=a(()=>{"use strict"});var qe=a(()=>{"use strict"});var vt=a(()=>{"use strict"});var Et=a(()=>{"use strict";qe();vt()});var _t=a(()=>{"use strict";pt();yt();Rt();Je();ge();St();bt();kt();xt();Et();qe();b()});var Ct=a(()=>{"use strict";_t();b()});function At(r,e={}){let t=e.perWorkerMemBytes??ze,n=e.memReserveBytes??Xe,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 ze,Xe,Qe,he,wt=a(()=>{"use strict";ot();T();F();fe();ye();Ye();ee();ut();Ct();b();ze=500*1024*1024,Xe=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,ze),o=re(e.memReserveBytes,Xe),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):Qe)),i=At(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";wt()});import{homedir as Ao}from"node:os";import wo from"node:path";var Ot,er=a(()=>{"use strict";Ot=wo.join(Ao(),".kynver",".env")});var It=a(()=>{"use strict"});var Tt=a(()=>{"use strict";It()});var Pt=a(()=>{"use strict"});var Nt=a(()=>{"use strict";b()});var rr=a(()=>{"use strict";Tt();Pt();Nt()});var Dt=a(()=>{"use strict"});var Lt=a(()=>{"use strict";Dt()});var Re=a(()=>{"use strict";er();W();T();rr();Lt()});var Kt=a(()=>{"use strict";F();F()});var Mt=a(()=>{"use strict";er();rr();Re()});function Bt(r){if(!Wt)return r;if(!Ft)throw new tr;return Ft}function or(){if(Wt)throw new nr}var tr,nr,Wt,Ft,sr=a(()=>{"use strict";tr=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},nr=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},Wt=!1,Ft=null});import{existsSync as P,mkdirSync as Po,readdirSync as Se,renameSync as Ut,statSync as No}from"node:fs";import N from"node:path";function Ht(r){try{return No(r).isDirectory()}catch{return!1}}function Do(r){if(!P(r))return!0;for(let e of $t){let t=N.join(r,e);if(P(t)&&(!Ht(t)||Se(t).length>0))return!1}return!0}function Lo(r){let e=N.join(r,"runs");if(!P(e)||!Ht(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(J(n,void 0)?.id)return!0}return!1}function Ko(r){let e=N.join(r,"runs");if(!P(e))return!1;for(let t of Se(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(J(N.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function Mo(r){let e=N.join(r,"ghost");return P(e)?!P(N.join(e,"runs")):Ko(r)}function jt(r){return Lo(r.sharedRoot)?Do(r.forgeRoot)?Mo(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 Yt(r,e){Po(e,{recursive:!0});for(let t of $t){let n=N.join(r,t),o=N.join(e,t);if(P(n)){if(P(o)&&Se(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(P(o)){Ut(n,o);continue}Ut(n,o)}}}var $t,Vt=a(()=>{"use strict";b();$t=["runs","worktrees"]});import{existsSync as k}from"node:fs";import{homedir as Fo}from"node:os";import S from"node:path";function ir(r=process.env){return r.HOME?.trim()||Fo()}function ar(r=process.env){return S.join(ir(r),".kynver","harness")}function be(r){let e=S.resolve(I(r.trim()));for(;Wo.has(S.basename(e));)e=S.dirname(e);return e}function Bo(r,e=process.env){return S.join(ar(e),r)}function Uo(r=process.env){let e=ar(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(ir(r),Gt);return k(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=Bo(r.boxKind,e);if(k(S.join(o,"runs"))||k(o)&&!$o(o))return{harnessRoot:o,source:"box_scoped"};let i=ar(e);if(r.boxKind==="forge"){let l=jt({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&&Yt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&Uo(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(ir(e),Gt);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 Gt,Wo,lr=a(()=>{"use strict";W();Vt();Gt=S.join(".openclaw","harness");Wo=new Set(["runs","worktrees"])});import Jt from"node:os";function xe(r){return r?.trim()?r.trim():null}function Ho(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function jo(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 ve(r=E(),e=process.env,t={}){let n=q(e,r),o=[...n.warnings],s=[],i=!!(r.boxKind?.trim()||xe(e.KYNVER_BOX_KIND)),l=t.strict===!0||jo(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 Y="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";l||t.requireExplicitBoxKind?s.push(Y):o.push(`${Y} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=xe(r.runnerId),c=xe(e.KYNVER_RUNTIME_ID)??xe(e.OPENCLAW_RUNTIME_ID),p=u??c??Ho(n.boxKind,Jt.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=Ze({config:r,env:e,totalMemBytes:Jt.totalmem()}),j=pe(n.boxKind,d.configuredMaxWorkers??He(n.boxKind,d.autoCap)),x=ke({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:j,workerCapSource:d.workerCapSource,harnessRoot:x.harnessRoot,harnessRootSource:x.source},errors:s,warnings:o}}var Ee=a(()=>{"use strict";T();F();fe();ye();lr()});var qt=a(()=>{"use strict";Ue();F();Kt();T();Re();Mt();ue();sr();Ee()});var Jo,bd,zt=a(()=>{"use strict";Jo=["claude","cursor","codex","gemini","gemini-api","openai-compatible","venice"],bd=Jo.join("|")});var Xt=a(()=>{"use strict";W()});var Qt=a(()=>{"use strict";Xt()});import{execFileSync as qo}from"node:child_process";function dr(r=process.env){let e=r[Xo]?.trim().toLowerCase();return e==="file"?"file":e==="keychain"?"keychain":"auto"}function Qo(r,e,t){if(!Zt.test(r)||!Zt.test(e))return null;let n=Buffer.from(t,"utf8").toString("hex");return`add-generic-password -U -s ${r} -a ${e} -l Kynver-${e} -X ${n}
69
- `}function Zo(r,e,t){let n={encoding:"utf8",timeout:t.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...t.input!==void 0?{input:t.input}:{}};return qo(r,e,n)}function es(r=process.platform){return r==="darwin"?"macos":r==="linux"?"libsecret":r==="win32"?"windows":null}function cr(r,e,t){let n=JSON.stringify(t),o=JSON.stringify(e),s="[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]; $v = New-Object Windows.Security.Credentials.PasswordVault;";return r==="get"?`${s} try { $c = $v.Retrieve(${n}, ${o}); $c.RetrievePassword(); [Console]::Out.Write($c.Password) } catch { exit 3 }`:r==="set"?`${s} $s = [Console]::In.ReadToEnd().TrimEnd("\`r","\`n"); try { $old = $v.Retrieve(${n}, ${o}); $v.Remove($old) } catch {}; $v.Add((New-Object Windows.Security.Credentials.PasswordCredential(${n}, ${o}, $s)))`:`${s} try { $old = $v.Retrieve(${n}, ${o}); $v.Remove($old) } catch {}`}function en(r={}){if(dr(r.env??process.env)==="file")return null;let t=es(r.platform??process.platform);return t?new ur(t,r.exec,r.service):null}var zo,Xo,D,Zt,ur,rn=a(()=>{"use strict";zo="kynver",Xo="KYNVER_CREDENTIAL_STORE";D=5e3,Zt=/^[A-Za-z0-9_.@:-]{1,128}$/;ur=class{constructor(e,t=Zo,n=zo){this.backend=e;this.exec=t;this.service=n}backend;exec;service;get(e){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",this.service,"-a",e,"-w"],{timeoutMs:D}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",this.service,"account",e],{timeoutMs:D}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",cr("get",e,this.service)],{timeoutMs:D}).replace(/\r?\n$/,"");return n||null}catch{return null}}set(e,t){if(!t||/[\r\n]/.test(t))return!1;try{if(this.backend==="macos"){let n=Qo(this.service,e,t);if(!n)return!1;this.exec("security",["-i"],{input:n,timeoutMs:D})}else this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${e})`,"service",this.service,"account",e],{input:`${t}
70
- `,timeoutMs:D}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",cr("set",e,this.service)],{input:`${t}
71
- `,timeoutMs:D})}catch{return!1}return this.get(e)===t}delete(e){try{this.backend==="macos"?this.exec("security",["delete-generic-password","-s",this.service,"-a",e],{timeoutMs:D}):this.backend==="libsecret"?this.exec("secret-tool",["clear","service",this.service,"account",e],{timeoutMs:D}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",cr("delete",e,this.service)],{timeoutMs:D})}catch{}}}});function gr(){return pr||(pr=new fr),pr}var mr,rs,_e,fr,pr,tn=a(()=>{"use strict";rn();mr="api-key",rs=6e4,_e=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"}},fr=class{cache=new Map;keychain;env;now;constructor(e={}){this.env=e.env??process.env,this.keychain=e.keychain===void 0?en({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<rs)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=dr(this.env);if(!this.keychain){if(n==="keychain")throw new _e(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 _e(e);return o}remove(e){this.cache.delete(e),this.keychain?.delete(e)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}},pr=null});import{existsSync as on,mkdirSync as ts,readFileSync as sn,writeFileSync as ns}from"node:fs";import{homedir as os,totalmem as Vd}from"node:os";import Rr from"node:path";function ss(r){return{...r,...r.harnessRoot?.trim()?{harnessRoot:I(r.harnessRoot.trim())}:{},...r.defaultRepo?.trim()?{defaultRepo:I(r.defaultRepo.trim())}:{}}}function is(r){let e=r.defaultRepo?.trim();return!e||r.defaultBase?.trim()||!Xr(I(e))?r:{...r,defaultBase:zr}}function as(){if(!on(nn))return null;try{return JSON.parse(sn(nn,"utf8"))}catch{return null}}function E(){let r=as();return r?is(ss(r)):{}}function Ce(){if(or(),!on(hr))return{};try{return JSON.parse(sn(hr,"utf8"))}catch{return{}}}function yr(r){or(),ts(Sr,{recursive:!0}),ns(hr,`${JSON.stringify(r,null,2)}
72
- `,{mode:384})}function ls(r,e,t,n={}){let o=Ce();if(gr().write(r,t)){let i={...o,...n};delete i[e],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],r])).sort(),yr(i);return}yr({...o,...n,[e]:t})}function cs(r,e){let t=gr().read(r);return t||Ce()[e]}function an(){return Bt(us)}function ln(){return an().getApiKey()}function ds(r,e){an().persistRunnerToken(r,e)}function ps(r){let e=cn(r);return e||ms("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),e}function cn(r){let e=r||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||E().apiBaseUrl;return $e(e)}async function un(r,e,t){let n=ln(),o=cn(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 fs(e,{baseUrl:o,apiKey:n});return s&&s!==r?(ds(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 fs(r,e){let t=e?.apiKey||ln();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${ps(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 ms(r){console.error(r),process.exit(1)}var Sr,nn,hr,up,dp,us,T=a(()=>{"use strict";Ue();W();Be();Zr();ue();F();fe();ye();Ye();Re();qt();zt();Ee();Qt();sr();tn();Sr=Rr.join(os(),".kynver"),nn=Rr.join(Sr,"config.json"),hr=Rr.join(Sr,"credentials");up=500*1024*1024,dp=4*1024*1024*1024;us={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:cs(mr,"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){ls(mr,"apiKey",r)},persistRunnerToken(r,e){yr({...Ce(),runnerToken:e,runnerTokenAgentOsId:r})}}});import dn from"node:path";function Ae(r){return be(r)}function br(){let r=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(r)return Ae(r);let e=E(),t=e.harnessRoot?.trim();if(t)return Ae(t);let n=ve(e,process.env);return n.identity?n.identity.harnessRoot:ke({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function at(r){return dn.join(Ae(r),"runs")}function gs(r){return dn.join(Ae(r),"worktrees")}function lt(){let r=br();return{harnessRoot:r,runsDir:at(r),worktreesDir:gs(r)}}var Ve=a(()=>{"use strict";T();lr();Ee();b()});import{existsSync as Ln,realpathSync as Kn,readFileSync as Mn}from"node:fs";import $r from"node:path";var Fn=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),Wn=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function Bn(){try{return Mn("/proc/self/mounts","utf8")}catch{return null}}function Un(r){let e=$r.resolve(r);for(let t=0;t<64;t+=1){if(Ln(e))try{return Kn.native(e)}catch{return e}let n=$r.dirname(e);if(n===e)return e;e=n}return e}function $n(r){return r.replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function Hn(r){let e=[];for(let t of r.split(`
73
- `)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:$n(n[1]),fsType:n[2]})}return e}function Hr(r,e=process.platform){return e==="win32"?r.replace(/\\/g,"/"):r}function jn(r,e){let t=null,n=Hr(r);for(let o of e){let s=Hr(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??Un)(r),o=(e?.mountsSource??Bn)();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=jn(n,Hn(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 Wn.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}:Fn.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"}},Yn=[`CREATE TABLE IF NOT EXISTS local_meta (
68
+ `});var St=a(()=>{"use strict";ee();b();Je()});var bt=a(()=>{"use strict";ge();Ge()});var kt=a(()=>{"use strict"});var ql,zl,xt=a(()=>{"use strict";le();ql=10*6e4,zl=60*6e4});var vt=a(()=>{"use strict"});var qe=a(()=>{"use strict"});var Et=a(()=>{"use strict"});var _t=a(()=>{"use strict";qe();Et()});var Ct=a(()=>{"use strict";ft();Rt();St();Je();ge();bt();kt();xt();vt();_t();qe();b()});var At=a(()=>{"use strict";Ct();b()});function wt(r,e={}){let t=e.perWorkerMemBytes??ze,n=e.memReserveBytes??Xe,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 ze,Xe,Qe,he,Ot=a(()=>{"use strict";st();T();W();fe();ye();Ye();ee();dt();At();b();ze=500*1024*1024,Xe=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,ze),o=re(e.memReserveBytes,Xe),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):Qe)),i=wt(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";Ot()});import{homedir as wo}from"node:os";import Oo from"node:path";var It,er=a(()=>{"use strict";It=Oo.join(wo(),".kynver",".env")});var Tt=a(()=>{"use strict"});var Pt=a(()=>{"use strict";Tt()});var Nt=a(()=>{"use strict"});var Dt=a(()=>{"use strict";b()});var rr=a(()=>{"use strict";Pt();Nt();Dt()});var Lt=a(()=>{"use strict"});var Kt=a(()=>{"use strict";Lt()});var Re=a(()=>{"use strict";er();F();T();rr();Kt()});var Mt=a(()=>{"use strict";W();W()});var Wt=a(()=>{"use strict";er();rr();Re()});function Ut(r){if(!Bt)return r;if(!Ft)throw new tr;return Ft}function or(){if(Bt)throw new nr}var tr,nr,Bt,Ft,sr=a(()=>{"use strict";tr=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},nr=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},Bt=!1,Ft=null});import{existsSync as P,mkdirSync as No,readdirSync as Se,renameSync as $t,statSync as Do}from"node:fs";import N from"node:path";function jt(r){try{return Do(r).isDirectory()}catch{return!1}}function Lo(r){if(!P(r))return!0;for(let e of Ht){let t=N.join(r,e);if(P(t)&&(!jt(t)||Se(t).length>0))return!1}return!0}function Ko(r){let e=N.join(r,"runs");if(!P(e)||!jt(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(J(n,void 0)?.id)return!0}return!1}function Mo(r){let e=N.join(r,"runs");if(!P(e))return!1;for(let t of Se(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(J(N.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function Wo(r){let e=N.join(r,"ghost");return P(e)?!P(N.join(e,"runs")):Mo(r)}function Yt(r){return Ko(r.sharedRoot)?Lo(r.forgeRoot)?Wo(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 Vt(r,e){No(e,{recursive:!0});for(let t of Ht){let n=N.join(r,t),o=N.join(e,t);if(P(n)){if(P(o)&&Se(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(P(o)){$t(n,o);continue}$t(n,o)}}}var Ht,Gt=a(()=>{"use strict";b();Ht=["runs","worktrees"]});import{existsSync as k}from"node:fs";import{homedir as Fo}from"node:os";import S from"node:path";function ir(r=process.env){return r.HOME?.trim()||Fo()}function ar(r=process.env){return S.join(ir(r),".kynver","harness")}function be(r){let e=S.resolve(I(r.trim()));for(;Bo.has(S.basename(e));)e=S.dirname(e);return e}function Uo(r,e=process.env){return S.join(ar(e),r)}function $o(r=process.env){let e=ar(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(ir(r),Jt);return k(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=Uo(r.boxKind,e);if(k(S.join(o,"runs"))||k(o)&&!Ho(o))return{harnessRoot:o,source:"box_scoped"};let i=ar(e);if(r.boxKind==="forge"){let l=Yt({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&&Vt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&$o(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(ir(e),Jt);if(k(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function Ho(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 Jt,Bo,lr=a(()=>{"use strict";F();Gt();Jt=S.join(".openclaw","harness");Bo=new Set(["runs","worktrees"])});import qt from"node:os";function xe(r){return r?.trim()?r.trim():null}function jo(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function Yo(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 ve(r=E(),e=process.env,t={}){let n=q(e,r),o=[...n.warnings],s=[],i=!!(r.boxKind?.trim()||xe(e.KYNVER_BOX_KIND)),l=t.strict===!0||Yo(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 Y="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";l||t.requireExplicitBoxKind?s.push(Y):o.push(`${Y} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=xe(r.runnerId),c=xe(e.KYNVER_RUNTIME_ID)??xe(e.OPENCLAW_RUNTIME_ID),p=u??c??jo(n.boxKind,qt.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=Ze({config:r,env:e,totalMemBytes:qt.totalmem()}),j=pe(n.boxKind,d.configuredMaxWorkers??He(n.boxKind,d.autoCap)),x=ke({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:j,workerCapSource:d.workerCapSource,harnessRoot:x.harnessRoot,harnessRootSource:x.source},errors:s,warnings:o}}var Ee=a(()=>{"use strict";T();W();fe();ye();lr()});var zt=a(()=>{"use strict";Ue();W();Mt();T();Re();Wt();ue();sr();Ee()});var qo,xd,Xt=a(()=>{"use strict";qo=["claude","cursor","codex","gemini","gemini-api","openai-compatible","venice"],xd=qo.join("|")});var cr=a(()=>{"use strict";F()});var Qt=a(()=>{"use strict";cr()});import{createInterface as Td}from"node:readline/promises";var Zt=a(()=>{"use strict";cr()});import{execFileSync as Xo}from"node:child_process";function pr(r=process.env){let e=r[Zo]?.trim().toLowerCase();return e==="file"?"file":e==="keychain"?"keychain":"auto"}function es(r,e,t){if(!en.test(r)||!en.test(e))return null;let n=Buffer.from(t,"utf8").toString("hex");return`add-generic-password -U -s ${r} -a ${e} -l Kynver-${e} -X ${n}
69
+ `}function rs(r,e,t){let n={encoding:"utf8",timeout:t.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...t.input!==void 0?{input:t.input}:{}};return Xo(r,e,n)}function ts(r=process.platform){return r==="darwin"?"macos":r==="linux"?"libsecret":r==="win32"?"windows":null}function ur(r,e,t){let n=JSON.stringify(t),o=JSON.stringify(e),s="[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]; $v = New-Object Windows.Security.Credentials.PasswordVault;";return r==="get"?`${s} try { $c = $v.Retrieve(${n}, ${o}); $c.RetrievePassword(); [Console]::Out.Write($c.Password) } catch { exit 3 }`:r==="set"?`${s} $s = [Console]::In.ReadToEnd().TrimEnd("\`r","\`n"); try { $old = $v.Retrieve(${n}, ${o}); $v.Remove($old) } catch {}; $v.Add((New-Object Windows.Security.Credentials.PasswordCredential(${n}, ${o}, $s)))`:`${s} try { $old = $v.Retrieve(${n}, ${o}); $v.Remove($old) } catch {}`}function rn(r={}){if(pr(r.env??process.env)==="file")return null;let t=ts(r.platform??process.platform);return t?new dr(t,r.exec,r.service):null}var Qo,Zo,D,en,dr,tn=a(()=>{"use strict";Qo="kynver",Zo="KYNVER_CREDENTIAL_STORE";D=5e3,en=/^[A-Za-z0-9_.@:-]{1,128}$/;dr=class{constructor(e,t=rs,n=Qo){this.backend=e;this.exec=t;this.service=n}backend;exec;service;get(e){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",this.service,"-a",e,"-w"],{timeoutMs:D}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",this.service,"account",e],{timeoutMs:D}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ur("get",e,this.service)],{timeoutMs:D}).replace(/\r?\n$/,"");return n||null}catch{return null}}set(e,t){if(!t||/[\r\n]/.test(t))return!1;try{if(this.backend==="macos"){let n=es(this.service,e,t);if(!n)return!1;this.exec("security",["-i"],{input:n,timeoutMs:D})}else this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${e})`,"service",this.service,"account",e],{input:`${t}
70
+ `,timeoutMs:D}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ur("set",e,this.service)],{input:`${t}
71
+ `,timeoutMs:D})}catch{return!1}return this.get(e)===t}delete(e){try{this.backend==="macos"?this.exec("security",["delete-generic-password","-s",this.service,"-a",e],{timeoutMs:D}):this.backend==="libsecret"?this.exec("secret-tool",["clear","service",this.service,"account",e],{timeoutMs:D}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ur("delete",e,this.service)],{timeoutMs:D})}catch{}}}});function hr(){return fr||(fr=new mr),fr}var gr,ns,_e,mr,fr,nn=a(()=>{"use strict";tn();gr="api-key",ns=6e4,_e=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"}},mr=class{cache=new Map;keychain;env;now;constructor(e={}){this.env=e.env??process.env,this.keychain=e.keychain===void 0?rn({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<ns)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=pr(this.env);if(!this.keychain){if(n==="keychain")throw new _e(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 _e(e);return o}remove(e){this.cache.delete(e),this.keychain?.delete(e)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}},fr=null});import{existsSync as sn,mkdirSync as os,readFileSync as an,writeFileSync as ss}from"node:fs";import{homedir as is,totalmem as Zd}from"node:os";import Sr from"node:path";function as(r){return{...r,...r.harnessRoot?.trim()?{harnessRoot:I(r.harnessRoot.trim())}:{},...r.defaultRepo?.trim()?{defaultRepo:I(r.defaultRepo.trim())}:{}}}function ls(r){let e=r.defaultRepo?.trim();return!e||r.defaultBase?.trim()||!Qr(I(e))?r:{...r,defaultBase:Xr}}function cs(){if(!sn(on))return null;try{return JSON.parse(an(on,"utf8"))}catch{return null}}function E(){let r=cs();return r?ls(as(r)):{}}function Ce(){if(or(),!sn(yr))return{};try{return JSON.parse(an(yr,"utf8"))}catch{return{}}}function Rr(r){or(),os(br,{recursive:!0}),ss(yr,`${JSON.stringify(r,null,2)}
72
+ `,{mode:384})}function us(r,e,t,n={}){let o=Ce();if(hr().write(r,t)){let i={...o,...n};delete i[e],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],r])).sort(),Rr(i);return}Rr({...o,...n,[e]:t})}function ds(r,e){let t=hr().read(r);return t||Ce()[e]}function ln(){return Ut(ps)}function cn(){return ln().getApiKey()}function fs(r,e){ln().persistRunnerToken(r,e)}function ms(r){let e=un(r);return e||hs("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),e}function un(r){let e=r||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||E().apiBaseUrl;return $e(e)}async function dn(r,e,t){let n=cn(),o=un(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 gs(e,{baseUrl:o,apiKey:n});return s&&s!==r?(fs(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 gs(r,e){let t=e?.apiKey||cn();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${ms(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 hs(r){console.error(r),process.exit(1)}var br,on,yr,Rp,Sp,ps,T=a(()=>{"use strict";Ue();F();Be();et();ue();W();fe();ye();Ye();Re();zt();Xt();Ee();Qt();Zt();sr();nn();br=Sr.join(is(),".kynver"),on=Sr.join(br,"config.json"),yr=Sr.join(br,"credentials");Rp=500*1024*1024,Sp=4*1024*1024*1024;ps={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:ds(gr,"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){us(gr,"apiKey",r)},persistRunnerToken(r,e){Rr({...Ce(),runnerToken:e,runnerTokenAgentOsId:r})}}});import pn from"node:path";function Ae(r){return be(r)}function kr(){let r=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(r)return Ae(r);let e=E(),t=e.harnessRoot?.trim();if(t)return Ae(t);let n=ve(e,process.env);return n.identity?n.identity.harnessRoot:ke({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function lt(r){return pn.join(Ae(r),"runs")}function ys(r){return pn.join(Ae(r),"worktrees")}function ct(){let r=kr();return{harnessRoot:r,runsDir:lt(r),worktreesDir:ys(r)}}var Ve=a(()=>{"use strict";T();lr();Ee();b()});import{existsSync as Kn,realpathSync as Mn,readFileSync as Wn}from"node:fs";import Hr from"node:path";var Fn=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),Bn=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function Un(){try{return Wn("/proc/self/mounts","utf8")}catch{return null}}function $n(r){let e=Hr.resolve(r);for(let t=0;t<64;t+=1){if(Kn(e))try{return Mn.native(e)}catch{return e}let n=Hr.dirname(e);if(n===e)return e;e=n}return e}function Hn(r){return r.replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function jn(r){let e=[];for(let t of r.split(`
73
+ `)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:Hn(n[1]),fsType:n[2]})}return e}function jr(r,e=process.platform){return e==="win32"?r.replace(/\\/g,"/"):r}function Yn(r,e){let t=null,n=jr(r);for(let o of e){let s=jr(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??$n)(r),o=(e?.mountsSource??Un)();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=Yn(n,jn(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 Bn.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}:Fn.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"}},Vn=[`CREATE TABLE IF NOT EXISTS local_meta (
74
74
  key TEXT PRIMARY KEY,
75
75
  value TEXT NOT NULL
76
76
  ) STRICT`,`CREATE TABLE IF NOT EXISTS process_identity (
@@ -96,7 +96,7 @@ child.on("exit", (code, signal) => finish(code, signal));
96
96
  payload_json TEXT NOT NULL,
97
97
  created_at TEXT NOT NULL,
98
98
  PRIMARY KEY (scope, seq)
99
- ) STRICT`];function Vn(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 jr(r,e){let t=Vn(r);if(t!==null&&t>1)throw new se(t,1);r.exec("BEGIN IMMEDIATE");try{for(let n of Yn)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 Gn}from"node:fs";import Jn from"node:path";import{DatabaseSync as qn}from"node:sqlite";var Z=class extends Error{constructor(e){super(`local-run-store refused: ${e}`),this.name="FilesystemPolicyError"}},zn="local-run-store.sqlite",Xn=5e3,G=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);Gn(e.directory,{recursive:!0,mode:448});let n=Jn.join(e.directory,e.filename??zn),o=new qn(n,{timeout:e.busyTimeoutMs??Xn}),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"),jr(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
99
+ ) STRICT`];function Gn(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 Yr(r,e){let t=Gn(r);if(t!==null&&t>1)throw new se(t,1);r.exec("BEGIN IMMEDIATE");try{for(let n of Vn)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 Jn}from"node:fs";import qn from"node:path";import{DatabaseSync as zn}from"node:sqlite";var Z=class extends Error{constructor(e){super(`local-run-store refused: ${e}`),this.name="FilesystemPolicyError"}},Xn="local-run-store.sqlite",Qn=5e3,G=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);Jn(e.directory,{recursive:!0,mode:448});let n=qn.join(e.directory,e.filename??Xn),o=new zn(n,{timeout:e.busyTimeoutMs??Qn}),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"),Yr(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
100
100
  (process_key, pid, runtime_version, node_version, started_at, registered_at)
101
101
  VALUES (?, ?, ?, ?, ?, ?)
102
102
  ON CONFLICT(process_key) DO UPDATE SET
@@ -120,8 +120,8 @@ child.on("exit", (code, signal) => finish(code, signal));
120
120
  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
121
121
  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)
122
122
  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
123
- 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 Qn,renameSync as Zn}from"node:fs";function eo(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;Qn(o)&&Zn(o,`${t}${n}`)}return t}function Me(r){let e=r.quarantineStamp??(r.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=G.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=eo(n,e);try{return{store:G.open(r),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}Ve();function hs(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function ys(){return pn.classifyOptions??hs()}var pn={};function Rs(r){pn=r}var fn=300*1e3,L=null,te=0;function Ss(r,e){te+=1;try{let t=ys(),n=Me({directory:r,...t?{classifyOptions:t}:{}});return{store:n.store,status:{state:"open",harnessRoot:r,databasePath:n.store.databasePath,schemaVersion:n.store.localSchemaVersion(),recovered:n.recovered,quarantinedTo:n.quarantinedTo,reason:null,openAttempts:te},failedAtMs:null,permanentRefusal:!1}}catch(t){return{store:null,status:{state:"unavailable",harnessRoot:r,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${t.name}: ${t.message}`,openAttempts:te},failedAtMs:e,permanentRefusal:t.name==="FilesystemPolicyError"||t.name==="SchemaDowngradeRefusedError"}}}function bs(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=fn}function m(r=Date.now()){let e=br();return(!L||L.status.harnessRoot!==e||bs(L,r))&&(xr(),L=Ss(e,r)),L.store}function mn(){return L?L.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:te}}function kr(){return m(),mn()}function xr(){try{L?.store?.close()}catch{}L=null}function ks(){xr(),te=0}T();b();import{existsSync as xs,readFileSync as vs}from"node:fs";import{homedir as Es}from"node:os";import _s from"node:path";var Cs=3e4,v=null;function vr(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return _s.join(Es(),".kynver",`local-run-store-flags-${e}.json`)}function Er(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:Er(t)}function ws(r,e){try{let t=vr(r),n={contractVersion:1,agentOsId:r,flags:Er(e),deliveredAt:new Date().toISOString()};ie(t,n),v={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function _r(r=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(v&&r-v.loadedAtMs<Cs)return v.flags;try{let e=E().agentOsId?.trim();if(!e)return v={flags:{},loadedAtMs:r,file:null},v.flags;let t=vr(e);if(!xs(t))return v={flags:{},loadedAtMs:r,file:t},v.flags;let n=JSON.parse(vs(t,"utf8")),o=n?.contractVersion===1?Er(n.flags):{};return v={flags:o,loadedAtMs:r,file:t},o}catch{return v={flags:{},loadedAtMs:r,file:null},v.flags}}function Os(){v=null}var gn=[{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 hn(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=_r();for(let s of gn){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let c=hn(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 Is(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 Cr(r){return w(r)!=="off"}function Ar(r,e){return`dispatch:${r}:${e.taskId}:${e.leaseToken}`}function ne(r,e,t){if(!Cr())return;let n=m();if(n)try{n.recordOperationReceipt({idempotencyKey:Ar(r,e),operation:`dispatch-${r}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function Ts(r){ne("claim",r,{runId:r.runId,workerName:r.workerName,provider:r.provider})}function wr(r){ne("spawned",r)}function we(r,e){ne("released",r,{reasonClass:e})}function Ps(r){ne("completion-sent",r)}function Ns(r,e){ne("completion-acked",r,{outcome:e})}function Ds(r){if(!Cr())return!1;let e=m();if(!e)return!1;try{let t=e.getOperationReceipt(Ar("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 Ls(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(Ar("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 Ms=600*1e3;function Fs(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 Ws(r,e){if(w()!=="enforce")return[];let t=m();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??Ms;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,yn=10080*60*1e3,Us=1440*60*1e3,$s=500,Hs=300;function Or(r){let e={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!Cr())return e;let t=m();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-yn).toISOString(),limit:$s}),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}`),j=t.getOperationReceipt(`dispatch:released:${p}`);if(d||j){n-f>=Us&&l.length+5<=Hs&&l.push(c.idempotencyKey,`dispatch:spawned:${p}`,`dispatch:released:${p}`,`dispatch:completion-sent:${p}`,`dispatch:completion-acked:${p}`);continue}let x=p.split(":")[0]??"",Y=z(p.slice(x.length+1));if((x?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${x}:`,limit:10}):[]).some(h=>{if(Y===null)return!0;let V=h.idempotencyKey.slice(`dispatch:completion-acked:${x}:`.length),M=z(V);return M===null||M>=Y}))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>=yn}).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 Ir(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function js(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as Qs,readFileSync as Zs}from"node:fs";var U=900*1e3,Pr="admission-shadow",Tr="worker-slot:",_={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Oe=!1;function Ys(){Oe=!1}function $(r=process.env){return A(r).flags.admission}function Ie(r,e){return`${Tr}${r}:${e}`}function Vs(r,e){if($()==="off")return;let t=m();if(t)try{t.tryReserveAdmission(Ie(r,e),Pr,U)}catch{_.storeFailures+=1}}function Nr(r,e){if($()==="off")return;let t=m();if(t)try{t.releaseAdmission(Ie(r,e),Pr)}catch{_.storeFailures+=1}}function Gs(r){let e={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if($()==="off")return e;let t=m();if(!t)return e;try{let n=new Set(r.liveWorkers.map(d=>Ie(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:Tr,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&&(_.missingForLive+=i);let c=0;for(let d of r.liveWorkers)t.tryReserveAdmission(Ie(d.runId,d.workerName),Pr,U),c+=1;let p=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(p+=1,_.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:Tr,limit:500}).length,refreshed:c,deadReleased:p,missingForLive:i,orphaned:l,adoptionPass:u}}catch{return _.storeFailures+=1,e}}function Dr(){return{"admission.storeFailures":_.storeFailures,"admission.missingForLive":_.missingForLive,"admission.deadSlotsReleased":_.deadSlotsReleased}}function Js(){_.storeFailures=0,_.missingForLive=0,_.deadSlotsReleased=0,Oe=!1}var Ne="worker-slot-n:",Te=64;function Rn(r){return`${Ne}${r}`}function Pe(r,e){return`${r}:${e}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function qs(r){if($()!=="enforce")return{admitted:!0};let e=m();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(Rn(o),n,U).acquired)return{admitted:!0,slot:o};return C.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return C.enforceStoreFailures+=1,{admitted:!0}}}function Lr(r,e){if($()==="off")return;let t=m();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 zs(r){let e={refreshed:0,deadReleased:0,adopted:0};if($()!=="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: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,U),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<Te;f+=1)if(t.tryReserveAdmission(Rn(f),p,U).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,e}}function Kr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function Xs(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var ei="dispatch:claim:",ri=900*1e3,ti=10080*60*1e3,ni=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function Sn(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=Qs("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(Zs(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(r))return Number(t)}catch{}return null}async function Mr(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??ri,i=r.findOrphanPid??Sn,l=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-ti).toISOString(),limit:ni})}catch{return O.recoveryStoreFailures+=1,t}for(let c of u){let p=c.idempotencyKey.slice(ei.length),f=p.split(":")[0]??"",d=p.slice(f.length+1);if(!(!f||!d))try{let j=Date.parse(c.recordedAt);if(!Number.isFinite(j)||o-j<s||n.getOperationReceipt(`dispatch:spawned:${p}`)||n.getOperationReceipt(`dispatch:released:${p}`))continue;let x=z(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${f}:`,limit:10}).some(M=>{if(x===null)return!0;let Q=z(M.idempotencyKey.slice(`dispatch:completion-acked:${f}:`.length));return Q===null||Q>=x}))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})){wr({taskId:f,leaseToken:d}),l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let M=r.worktreePathFor({runId:y,workerName:h}),Q=M?i(M):null;if(Q!==null){O.recoveryDeferredOrphans+=1,l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${Q} references ${M}`});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 V=await r.releaseClaim({taskId:f,leaseToken:d,runId:y});V.released?(we({taskId:f,leaseToken:d},"restart_recovery"),h&&(Nr(y,h),Lr(y,h)),O.recoveredStrandedClaims+=1,l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"released"})):V.transportError?l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:V.detail}):(we({taskId:f,leaseToken:d},"restart_recovery_refused"),l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:V.detail}))}catch{O.recoveryStoreFailures+=1}}return{mode:e,scanned:u.length,outcomes:l}}function Fr(){return{"dispatchReceipts.recoveredStrandedClaims":O.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":O.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":O.recoveryStoreFailures}}function oi(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}ee();import mi from"node:path";var si="kynver-harness:",ii="@runner:";function bn(r,e){let t=r.trim(),n=e.trim();return`${si}${t}${ii}${n}`}T();import vn from"node:os";var ai="embedded-1",li=[{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"}],ci={"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(`
123
+ 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 Zn,renameSync as eo}from"node:fs";function ro(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;Zn(o)&&eo(o,`${t}${n}`)}return t}function Me(r){let e=r.quarantineStamp??(r.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=G.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=ro(n,e);try{return{store:G.open(r),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}Ve();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 Ss(){return fn.classifyOptions??Rs()}var fn={};function bs(r){fn=r}var mn=300*1e3,L=null,te=0;function ks(r,e){te+=1;try{let t=Ss(),n=Me({directory:r,...t?{classifyOptions:t}:{}});return{store:n.store,status:{state:"open",harnessRoot:r,databasePath:n.store.databasePath,schemaVersion:n.store.localSchemaVersion(),recovered:n.recovered,quarantinedTo:n.quarantinedTo,reason:null,openAttempts:te},failedAtMs:null,permanentRefusal:!1}}catch(t){return{store:null,status:{state:"unavailable",harnessRoot:r,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${t.name}: ${t.message}`,openAttempts:te},failedAtMs:e,permanentRefusal:t.name==="FilesystemPolicyError"||t.name==="SchemaDowngradeRefusedError"}}}function xs(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=mn}function m(r=Date.now()){let e=kr();return(!L||L.status.harnessRoot!==e||xs(L,r))&&(vr(),L=ks(e,r)),L.store}function gn(){return L?L.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:te}}function xr(){return m(),gn()}function vr(){try{L?.store?.close()}catch{}L=null}function vs(){vr(),te=0}T();b();import{existsSync as Es,readFileSync as _s}from"node:fs";import{homedir as Cs}from"node:os";import As from"node:path";var ws=3e4,v=null;function Er(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return As.join(Cs(),".kynver",`local-run-store-flags-${e}.json`)}function _r(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 Os(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:_r(t)}function Is(r,e){try{let t=Er(r),n={contractVersion:1,agentOsId:r,flags:_r(e),deliveredAt:new Date().toISOString()};ie(t,n),v={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function Cr(r=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(v&&r-v.loadedAtMs<ws)return v.flags;try{let e=E().agentOsId?.trim();if(!e)return v={flags:{},loadedAtMs:r,file:null},v.flags;let t=Er(e);if(!Es(t))return v={flags:{},loadedAtMs:r,file:t},v.flags;let n=JSON.parse(_s(t,"utf8")),o=n?.contractVersion===1?_r(n.flags):{};return v={flags:o,loadedAtMs:r,file:t},o}catch{return v={flags:{},loadedAtMs:r,file:null},v.flags}}function Ts(){v=null}var hn=[{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 yn(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=Cr();for(let s of hn){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let c=yn(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 Ps(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 Ar(r){return w(r)!=="off"}function wr(r,e){return`dispatch:${r}:${e.taskId}:${e.leaseToken}`}function ne(r,e,t){if(!Ar())return;let n=m();if(n)try{n.recordOperationReceipt({idempotencyKey:wr(r,e),operation:`dispatch-${r}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function Ns(r){ne("claim",r,{runId:r.runId,workerName:r.workerName,provider:r.provider})}function Or(r){ne("spawned",r)}function we(r,e){ne("released",r,{reasonClass:e})}function Ds(r){ne("completion-sent",r)}function Ls(r,e){ne("completion-acked",r,{outcome:e})}function Ks(r){if(!Ar())return!1;let e=m();if(!e)return!1;try{let t=e.getOperationReceipt(wr("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 Ws(r){if(w()!=="enforce")return!1;let e=m();if(!e)return!1;try{let t=e.getOperationReceipt(wr("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 Fs=600*1e3;function Bs(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 Us(r,e){if(w()!=="enforce")return[];let t=m();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??Fs;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 $s=900*1e3,Rn=10080*60*1e3,Hs=1440*60*1e3,js=500,Ys=300;function Ir(r){let e={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!Ar())return e;let t=m();if(!t)return e;let n=r?.nowMs??Date.now(),o=r?.strandedAfterMs??$s;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-Rn).toISOString(),limit:js}),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}`),j=t.getOperationReceipt(`dispatch:released:${p}`);if(d||j){n-f>=Hs&&l.length+5<=Ys&&l.push(c.idempotencyKey,`dispatch:spawned:${p}`,`dispatch:released:${p}`,`dispatch:completion-sent:${p}`,`dispatch:completion-acked:${p}`);continue}let x=p.split(":")[0]??"",Y=z(p.slice(x.length+1));if((x?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${x}:`,limit:10}):[]).some(h=>{if(Y===null)return!0;let V=h.idempotencyKey.slice(`dispatch:completion-acked:${x}:`.length),M=z(V);return M===null||M>=Y}))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>=Rn}).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 Tr(){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 ei,readFileSync as ri}from"node:fs";var U=900*1e3,Nr="admission-shadow",Pr="worker-slot:",_={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Oe=!1;function Gs(){Oe=!1}function $(r=process.env){return A(r).flags.admission}function Ie(r,e){return`${Pr}${r}:${e}`}function Js(r,e){if($()==="off")return;let t=m();if(t)try{t.tryReserveAdmission(Ie(r,e),Nr,U)}catch{_.storeFailures+=1}}function Dr(r,e){if($()==="off")return;let t=m();if(t)try{t.releaseAdmission(Ie(r,e),Nr)}catch{_.storeFailures+=1}}function qs(r){let e={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if($()==="off")return e;let t=m();if(!t)return e;try{let n=new Set(r.liveWorkers.map(d=>Ie(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:Pr,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&&(_.missingForLive+=i);let c=0;for(let d of r.liveWorkers)t.tryReserveAdmission(Ie(d.runId,d.workerName),Nr,U),c+=1;let p=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(p+=1,_.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:Pr,limit:500}).length,refreshed:c,deadReleased:p,missingForLive:i,orphaned:l,adoptionPass:u}}catch{return _.storeFailures+=1,e}}function Lr(){return{"admission.storeFailures":_.storeFailures,"admission.missingForLive":_.missingForLive,"admission.deadSlotsReleased":_.deadSlotsReleased}}function zs(){_.storeFailures=0,_.missingForLive=0,_.deadSlotsReleased=0,Oe=!1}var Ne="worker-slot-n:",Te=64;function Sn(r){return`${Ne}${r}`}function Pe(r,e){return`${r}:${e}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function Xs(r){if($()!=="enforce")return{admitted:!0};let e=m();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(Sn(o),n,U).acquired)return{admitted:!0,slot:o};return C.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return C.enforceStoreFailures+=1,{admitted:!0}}}function Kr(r,e){if($()==="off")return;let t=m();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 Qs(r){let e={refreshed:0,deadReleased:0,adopted:0};if($()!=="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: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,U),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<Te;f+=1)if(t.tryReserveAdmission(Sn(f),p,U).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,e}}function Mr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function Zs(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var ti="dispatch:claim:",ni=900*1e3,oi=10080*60*1e3,si=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function bn(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=ei("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(ri(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(r))return Number(t)}catch{}return null}async function Wr(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??ni,i=r.findOrphanPid??bn,l=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-oi).toISOString(),limit:si})}catch{return O.recoveryStoreFailures+=1,t}for(let c of u){let p=c.idempotencyKey.slice(ti.length),f=p.split(":")[0]??"",d=p.slice(f.length+1);if(!(!f||!d))try{let j=Date.parse(c.recordedAt);if(!Number.isFinite(j)||o-j<s||n.getOperationReceipt(`dispatch:spawned:${p}`)||n.getOperationReceipt(`dispatch:released:${p}`))continue;let x=z(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${f}:`,limit:10}).some(M=>{if(x===null)return!0;let Q=z(M.idempotencyKey.slice(`dispatch:completion-acked:${f}:`.length));return Q===null||Q>=x}))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})){Or({taskId:f,leaseToken:d}),l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let M=r.worktreePathFor({runId:y,workerName:h}),Q=M?i(M):null;if(Q!==null){O.recoveryDeferredOrphans+=1,l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${Q} references ${M}`});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 V=await r.releaseClaim({taskId:f,leaseToken:d,runId:y});V.released?(we({taskId:f,leaseToken:d},"restart_recovery"),h&&(Dr(y,h),Kr(y,h)),O.recoveredStrandedClaims+=1,l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"released"})):V.transportError?l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:V.detail}):(we({taskId:f,leaseToken:d},"restart_recovery_refused"),l.push({taskId:f,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:V.detail}))}catch{O.recoveryStoreFailures+=1}}return{mode:e,scanned:u.length,outcomes:l}}function Fr(){return{"dispatchReceipts.recoveredStrandedClaims":O.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":O.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":O.recoveryStoreFailures}}function ii(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}ee();import hi from"node:path";var ai="kynver-harness:",li="@runner:";function kn(r,e){let t=r.trim(),n=e.trim();return`${ai}${t}${li}${n}`}T();import En from"node:os";var ci="embedded-1",ui=[{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"}],di={"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(`
124
124
  `),"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(`
125
125
  `),"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(`
126
126
  `),"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(`
127
- `)},ui={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},kn={version:ai,generatedAt:"1970-01-01T00:00:00.000Z",personas:li,instructions:ci,policyThresholds:ui};var di=kn;function xn(){return di.version}F();function K(r){return r?.trim()?r.trim():null}function En(r={}){let e=r.env??process.env,t=E();return{runnerId:K(t.runnerId)??K(e.KYNVER_RUNTIME_ID)??K(e.OPENCLAW_RUNTIME_ID)??K(e.HOSTNAME)??vn.hostname(),hostname:K(e.HOSTNAME)??vn.hostname(),profile:K(e.KYNVER_RUNNER_PROFILE)??K(e.OPENCLAW_RUNNER_PROFILE),harnessRepo:K(e.KYNVER_HARNESS_REPO)??K(e.KYNVER_DEFAULT_REPO),runId:r.runId??null,instructionBundleVersion:xn()}}function _n(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();T();function wn(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 Cn(r){return new Error(`callback timeout after ${r}ms`)}async function pi(r,e){let t=wn(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(Cn(t))},t)})])}catch(i){throw s?Cn(t):i}finally{o&&clearTimeout(o)}}function fi(r,e){let t=wn(e);return{ok:!1,status:0,response:{error:r instanceof Error?r.message:String(r),timeoutMs:t}}}async function An(r,e,t,n){try{return await pi(async o=>{let s=await ce(r,{method:"POST",headers:_n(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 fi(o,n?.timeoutMs)}}async function On(r,e,t,n){let o=await An(r,e,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await un(e,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await An(r,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function In(r){let e=`${r.baseUrl}/api/agent-os/by-id/${encodeURIComponent(r.agentOsId)}/tasks/${encodeURIComponent(r.taskId)}/release`,t;try{t=await On(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 Wr=!1;function gi(){Wr=!1}async function hi(r){if(Wr||w()!=="enforce")return null;Wr=!0;try{let e=En().runnerId,t=await Mr({hasLiveWorker:r.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>mi.join(it().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await In({baseUrl:r.baseUrl,secret:r.secret,agentOsId:r.agentOsId,taskId:n,leaseOwner:bn(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 Rf=600*1e3,oe={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function Tn(){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 H(r){return A(process.env).flags[r]}var Pn="daemon-keeper",yi=1800*1e3;function Ri(r){if(H("keeper")==="off")return;let e=m();if(e)try{e.saveRecoveryCheckpoint({scope:Pn,payloadJson:JSON.stringify(r)})}catch{g.keeperStoreFailures+=1}}function Si(){if(H("keeper")!=="enforce")return null;let r=m();if(!r)return null;try{let e=r.latestRecoveryCheckpoint(Pn);if(!e)return null;let t=JSON.parse(e.payloadJson),n=Date.now()-Date.parse(e.createdAt);if(!Number.isFinite(n)||n>yi)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function Br(r){return`mesh-cron-lease:${r}`}function bi(r,e){if(H("meshLease")==="off")return;let t=m();if(t)try{let n=t.latestRecoveryCheckpoint(Br(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:Br(r),payloadJson:JSON.stringify(e)})}catch{g.meshStoreFailures+=1}}function ki(r,e){let t=H("meshLease");if(t==="off")return null;let n=m();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(Br(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 Nn="quota-preflight";function xi(r,e){if(H("quota")==="off")return;let t=m();if(t)try{t.tryReserveAdmission(De(r),Nn,e)}catch{g.quotaStoreFailures+=1}}function vi(r){if(H("quota")==="off")return;let e=m();if(e)try{e.releaseAdmission(De(r),Nn)}catch{g.quotaStoreFailures+=1}}function Ei(r,e){let t=H("quota");if(t==="off")return null;let n=m();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 Ur(){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 _i(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function Ci(r){let e=kr(),t=A(r?.env??process.env),n=(r?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,Ir());let s=Or({nowMs:n,hasLiveWorker:r?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,Fr())}return t.flags.planOutbox!=="off"&&Object.assign(o,Tn()),t.flags.admission!=="off"&&(Object.assign(o,Dr()),t.flags.admission==="enforce"&&Object.assign(o,Kr())),(t.flags.keeper!=="off"||t.flags.meshLease!=="off"||t.flags.quota!=="off")&&Object.assign(o,Ur()),{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{U as ADMISSION_RESERVATION_TTL_MS,Ne as ADMISSION_SLOT_KEY_PREFIX,Z as FilesystemPolicyError,fn as LOCAL_RUN_STORE_OPEN_RETRY_MS,gn as LOCAL_RUN_STORE_SURFACES,Ke as LOCAL_SCHEMA_VERSION,se as SchemaDowngradeRefusedError,G as SqliteLocalRunStore,Xs as __resetAdmissionEnforceCountersForTests,Js as __resetAdmissionShadowCountersForTests,oi as __resetDispatchClaimRecoveryForTests,js as __resetDispatchReceiptCountersForTests,ks as __resetLocalRunStoreLifecycleForTests,Os as __resetRemoteSurfaceFlagsCacheForTests,_i as __resetSmallSurfaceCountersForTests,gi as __resetStartupClaimRecoveryForTests,Rs as __setLocalRunStoreLifecycleTestOverrides,qs as acquireWorkerAdmissionSlot,Kr as admissionEnforceCounters,Dr as admissionShadowCounters,Is as anyLocalRunStoreSurfaceActive,Ei as assessQuotaCooldownReservation,Ci as buildLocalRunStoreTickPosture,Le as classifyDatabaseDirectory,vi as clearQuotaCooldownReservation,xr as closeLocalRunStore,Fr as dispatchClaimRecoveryCounters,Ir as dispatchReceiptCounters,w as dispatchReceiptsMode,As as extractLocalRunStoreFlagsFromOperatorTickResponse,Sn as findLiveProcessByCmdlinePath,m as getLocalRunStore,mn as getLocalRunStoreLifecycleStatus,_r as getRemoteSurfaceFlags,z as leaseTokenAttempt,Ws as listRecentDispatchStartFailures,hi as maybeRunStartupClaimRecovery,Ds as noteCompletionReplayIfAcked,Me as openSqliteLocalRunStoreWithRecovery,hn as parseLocalRunStoreSurfaceMode,ws as persistRemoteSurfaceFlags,kr as probeLocalRunStore,ki as readMeshLeaseCheckpoint,Ys as rearmAdmissionAdoptionPass,Gs as reconcileAdmissionShadow,zs as reconcileNumberedAdmissionSlots,Ns as recordCompletionAckedReceipt,Ps as recordCompletionSentReceipt,Ts as recordDispatchClaimReceipt,we as recordDispatchReleasedReceipt,wr as recordDispatchSpawnedReceipt,Fs as recordDispatchStartFailedReceipt,xi as recordQuotaCooldownReservation,Mr as recoverStrandedDispatchClaims,Ls as releaseReasonClass,Lr as releaseWorkerAdmissionSlot,Nr as releaseWorkerSlotReservation,vr as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,Si as restoreKeeperBackoffCheckpoint,Ri as saveKeeperBackoffCheckpoint,bi as saveMeshLeaseCheckpoint,Or as scanDispatchReceiptInvariants,Ks as shouldShortCircuitCompletionReplay,Ur as smallSurfaceCounters,Vs as takeWorkerSlotReservation};
127
+ `)},pi={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},xn={version:ci,generatedAt:"1970-01-01T00:00:00.000Z",personas:ui,instructions:di,policyThresholds:pi};var fi=xn;function vn(){return fi.version}W();function K(r){return r?.trim()?r.trim():null}function _n(r={}){let e=r.env??process.env,t=E();return{runnerId:K(t.runnerId)??K(e.KYNVER_RUNTIME_ID)??K(e.OPENCLAW_RUNTIME_ID)??K(e.HOSTNAME)??En.hostname(),hostname:K(e.HOSTNAME)??En.hostname(),profile:K(e.KYNVER_RUNNER_PROFILE)??K(e.OPENCLAW_RUNNER_PROFILE),harnessRepo:K(e.KYNVER_HARNESS_REPO)??K(e.KYNVER_DEFAULT_REPO),runId:r.runId??null,instructionBundleVersion:vn()}}function Cn(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();T();function On(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 An(r){return new Error(`callback timeout after ${r}ms`)}async function mi(r,e){let t=On(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(An(t))},t)})])}catch(i){throw s?An(t):i}finally{o&&clearTimeout(o)}}function gi(r,e){let t=On(e);return{ok:!1,status:0,response:{error:r instanceof Error?r.message:String(r),timeoutMs:t}}}async function wn(r,e,t,n){try{return await mi(async o=>{let s=await ce(r,{method:"POST",headers:Cn(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 gi(o,n?.timeoutMs)}}async function In(r,e,t,n){let o=await wn(r,e,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await dn(e,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await wn(r,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function Tn(r){let e=`${r.baseUrl}/api/agent-os/by-id/${encodeURIComponent(r.agentOsId)}/tasks/${encodeURIComponent(r.taskId)}/release`,t;try{t=await In(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 Br=!1;function yi(){Br=!1}async function Ri(r){if(Br||w()!=="enforce")return null;Br=!0;try{let e=_n().runnerId,t=await Wr({hasLiveWorker:r.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>hi.join(at().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await Tn({baseUrl:r.baseUrl,secret:r.secret,agentOsId:r.agentOsId,taskId:n,leaseOwner:kn(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 Cf=600*1e3,oe={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function Pn(){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 H(r){return A(process.env).flags[r]}var Nn="daemon-keeper",Si=1800*1e3;function bi(r){if(H("keeper")==="off")return;let e=m();if(e)try{e.saveRecoveryCheckpoint({scope:Nn,payloadJson:JSON.stringify(r)})}catch{g.keeperStoreFailures+=1}}function ki(){if(H("keeper")!=="enforce")return null;let r=m();if(!r)return null;try{let e=r.latestRecoveryCheckpoint(Nn);if(!e)return null;let t=JSON.parse(e.payloadJson),n=Date.now()-Date.parse(e.createdAt);if(!Number.isFinite(n)||n>Si)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function Ur(r){return`mesh-cron-lease:${r}`}function xi(r,e){if(H("meshLease")==="off")return;let t=m();if(t)try{let n=t.latestRecoveryCheckpoint(Ur(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:Ur(r),payloadJson:JSON.stringify(e)})}catch{g.meshStoreFailures+=1}}function vi(r,e){let t=H("meshLease");if(t==="off")return null;let n=m();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(Ur(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 Dn="quota-preflight";function Ei(r,e){if(H("quota")==="off")return;let t=m();if(t)try{t.tryReserveAdmission(De(r),Dn,e)}catch{g.quotaStoreFailures+=1}}function _i(r){if(H("quota")==="off")return;let e=m();if(e)try{e.releaseAdmission(De(r),Dn)}catch{g.quotaStoreFailures+=1}}function Ci(r,e){let t=H("quota");if(t==="off")return null;let n=m();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 $r(){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 Ai(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function wi(r){let e=xr(),t=A(r?.env??process.env),n=(r?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,Tr());let s=Ir({nowMs:n,hasLiveWorker:r?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,Fr())}return t.flags.planOutbox!=="off"&&Object.assign(o,Pn()),t.flags.admission!=="off"&&(Object.assign(o,Lr()),t.flags.admission==="enforce"&&Object.assign(o,Mr())),(t.flags.keeper!=="off"||t.flags.meshLease!=="off"||t.flags.quota!=="off")&&Object.assign(o,$r()),{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{U as ADMISSION_RESERVATION_TTL_MS,Ne as ADMISSION_SLOT_KEY_PREFIX,Z as FilesystemPolicyError,mn as LOCAL_RUN_STORE_OPEN_RETRY_MS,hn as LOCAL_RUN_STORE_SURFACES,Ke as LOCAL_SCHEMA_VERSION,se as SchemaDowngradeRefusedError,G as SqliteLocalRunStore,Zs as __resetAdmissionEnforceCountersForTests,zs as __resetAdmissionShadowCountersForTests,ii as __resetDispatchClaimRecoveryForTests,Vs as __resetDispatchReceiptCountersForTests,vs as __resetLocalRunStoreLifecycleForTests,Ts as __resetRemoteSurfaceFlagsCacheForTests,Ai as __resetSmallSurfaceCountersForTests,yi as __resetStartupClaimRecoveryForTests,bs as __setLocalRunStoreLifecycleTestOverrides,Xs as acquireWorkerAdmissionSlot,Mr as admissionEnforceCounters,Lr as admissionShadowCounters,Ps as anyLocalRunStoreSurfaceActive,Ci as assessQuotaCooldownReservation,wi as buildLocalRunStoreTickPosture,Le as classifyDatabaseDirectory,_i as clearQuotaCooldownReservation,vr as closeLocalRunStore,Fr as dispatchClaimRecoveryCounters,Tr as dispatchReceiptCounters,w as dispatchReceiptsMode,Os as extractLocalRunStoreFlagsFromOperatorTickResponse,bn as findLiveProcessByCmdlinePath,m as getLocalRunStore,gn as getLocalRunStoreLifecycleStatus,Cr as getRemoteSurfaceFlags,z as leaseTokenAttempt,Us as listRecentDispatchStartFailures,Ri as maybeRunStartupClaimRecovery,Ks as noteCompletionReplayIfAcked,Me as openSqliteLocalRunStoreWithRecovery,yn as parseLocalRunStoreSurfaceMode,Is as persistRemoteSurfaceFlags,xr as probeLocalRunStore,vi as readMeshLeaseCheckpoint,Gs as rearmAdmissionAdoptionPass,qs as reconcileAdmissionShadow,Qs as reconcileNumberedAdmissionSlots,Ls as recordCompletionAckedReceipt,Ds as recordCompletionSentReceipt,Ns as recordDispatchClaimReceipt,we as recordDispatchReleasedReceipt,Or as recordDispatchSpawnedReceipt,Bs as recordDispatchStartFailedReceipt,Ei as recordQuotaCooldownReservation,Wr as recoverStrandedDispatchClaims,Ms as releaseReasonClass,Kr as releaseWorkerAdmissionSlot,Dr as releaseWorkerSlotReservation,Er as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,ki as restoreKeeperBackoffCheckpoint,bi as saveKeeperBackoffCheckpoint,xi as saveMeshLeaseCheckpoint,Ir as scanDispatchReceiptInvariants,Ws as shouldShortCircuitCompletionReplay,$r as smallSurfaceCounters,Js as takeWorkerSlotReservation};