@kynver-app/runtime 0.2.102 → 0.2.114
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat/chat-access-change-record.js +1 -0
- package/dist/chat/chat-turn-envelope.js +1 -0
- package/dist/cli.js +195 -149
- package/dist/desktop-entry.js +171 -125
- package/dist/index.js +219 -173
- package/dist/local-run-store/index.js +17 -15
- package/dist/server/cleanup.js +14 -14
- package/dist/server/default-repo.js +1 -1
- package/dist/server/dispatch-routing.js +3 -3
- package/dist/server/model-routing.js +3 -3
- package/dist/server/monitor.js +7 -7
- package/dist/server/worker-policy.js +2 -2
- package/package.json +12 -2
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
var a=(e,
|
|
2
|
-
`),Pn(t,e)}catch(n){try{Nn(t,{force:!0})}catch{}throw n}}function se(e){return String(e).replace(/\/+$/,"")}var k=a(()=>{"use strict";Nr()});var Kn,di,Fn,pi,Dr=a(()=>{"use strict";Kn=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],di=new Set(Kn),Fn=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],pi=new Set(Fn)});var ie=a(()=>{"use strict";V();k();Dr()});var Lr=a(()=>{"use strict";ie()});var Me=a(()=>{"use strict";ie();V();Lr()});function Fr(e){let r=se(e);try{let t=new URL(r);return t.hostname.toLowerCase()===Mr?(t.hostname=`www.${Mr}`,se(t.toString())):r}catch{return r}}function Ke(e){if(e?.trim())return Fr(se(e.trim()))}async function ae(e,r,t=fetch){let n=Fr(e),o=new Headers(r?.headers),s=0;for(;s<=Kr;){let i=await t(n,{...r,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 c=new URL(l,n);if(c.origin!==new URL(n).origin||c.username||c.password)throw await i.body?.cancel(),new Error("kynver API fetch refused unsafe redirect (origin change or embedded credentials)");let u=(r?.method??"GET").toUpperCase();if(!["GET","HEAD"].includes(u)&&i.status!==307&&i.status!==308)return i;await i.body?.cancel(),n=c.toString(),s+=1}throw new Error(`kynver API fetch exceeded ${Kr} redirects for ${e}`)}var Mr,Kr,le=a(()=>{"use strict";k();Mr="kynver.com";Kr=10});function F(e){let r=(e??"").trim().toLowerCase();return r==="ghost"||r==="forge"||r==="box"?r:r.includes("forge")?"forge":r.includes("ghost")||r.includes("openclaw")?"ghost":"box"}function ue(e,r){return e[r]?.trim()||null}function Ur(e){let r=e?.split(":")[0]?.trim();return r?F(r):null}function G(e=process.env,r={}){let t=[],n=Ur(r.boxId),o=Ur(ue(e,"KYNVER_BOX_ID")),s=r.boxKind?.trim();if(s)return n&&n!==F(s)&&t.push(`config.boxId=${r.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:F(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=ue(e,"KYNVER_BOX_KIND");if(i)return o&&o!==F(i)&&t.push(`KYNVER_BOX_ID=${ue(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:F(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=ue(e,"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 M=a(()=>{"use strict"});function Fe(e,r){return e==="forge"?4:Math.max(1,r)}function ce(e,r){return e==="forge"?Math.min(Math.max(1,r),4):Math.max(1,r)}var de=a(()=>{"use strict"});var Br=a(()=>{"use strict"});var Ni,Di,Ue=a(()=>{"use strict";Ni=25*1024*1024*1024,Di=12*1024*1024*1024});var Ui,Bi,Wr=a(()=>{"use strict";Ue();Ui=5*1024*1024*1024,Bi=10*1024*1024*1024});var Vi,Gi,Be=a(()=>{"use strict";Wr();Ue();Vi=30*1024*1024*1024,Gi=15*1024*1024*1024});function $r(){return jr()}var pe=a(()=>{"use strict";$e();k()});var Yr=a(()=>{"use strict";pe();k()});var Vr=a(()=>{"use strict"});var Gr=a(()=>{"use strict";Vr();k()});var qr=a(()=>{"use strict"});var Jr=a(()=>{"use strict";qr()});var me=a(()=>{"use strict"});var zr=a(()=>{"use strict"});var Xr=a(()=>{"use strict"});var Qr=a(()=>{"use strict";Jr();k();me();zr();Xr()});var Zr=a(()=>{"use strict";me()});var et=a(()=>{"use strict"});var rt=a(()=>{"use strict"});var He=a(()=>{"use strict"});var tt=a(()=>{"use strict"});var nt=a(()=>{"use strict";He();tt()});var ot=a(()=>{"use strict";Gr();Qr();me();Zr();et();ie();rt();nt();He();k()});var st=a(()=>{"use strict";ot()});function it(e,r={}){let t=r.perWorkerMemBytes??je,n=r.memReserveBytes??Ye,o=r.memUtilization??Ve,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,fe)}var je,Ye,Ve,fe,at=a(()=>{"use strict";Br();I();M();de();ge();Be();pe();Yr();st();k();je=500*1024*1024,Ye=4*1024*1024*1024,Ve=.85,fe=64});function Z(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function Ge(e){let r=e.config??{},t=e.env??process.env,n=Z(r.perWorkerMemBytes,je),o=Z(r.memReserveBytes,Ye),s=Math.min(1,Math.max(.1,Number(r.memUtilization)>0?Number(r.memUtilization):Ve)),i=it(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Z(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(r.maxConcurrentWorkers!==void 0&&r.maxConcurrentWorkers!==null){let u=Z(r.maxConcurrentWorkers,0)||null;if(u)return{configuredMaxWorkers:Math.min(u,fe),autoCap:i,workerCapSource:"config"}}let c=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&Z(t.KYNVER_MAX_WORKERS,0)||null;return c?{configuredMaxWorkers:Math.min(c,fe),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var ge=a(()=>{"use strict";at()});import{homedir as Gn}from"node:os";import qn from"node:path";var lt,qe=a(()=>{"use strict";lt=qn.join(Gn(),".kynver",".env")});var ut=a(()=>{"use strict"});var ct=a(()=>{"use strict";ut()});var dt=a(()=>{"use strict"});var pt=a(()=>{"use strict";k()});var Je=a(()=>{"use strict";ct();dt();pt()});var mt=a(()=>{"use strict"});var ft=a(()=>{"use strict";mt()});var ye=a(()=>{"use strict";qe();V();I();Je();ft()});var gt=a(()=>{"use strict";M();M()});var yt=a(()=>{"use strict";qe();Je();ye()});function St(e){if(!Rt)return e;if(!ht)throw new ze;return ht}function Qe(){if(Rt)throw new Xe}var ze,Xe,Rt,ht,Ze=a(()=>{"use strict";ze=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},Xe=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},Rt=!1,ht=null});import{existsSync as T,mkdirSync as Qn,readdirSync as he,renameSync as bt,statSync as Zn}from"node:fs";import P from"node:path";function vt(e){try{return Zn(e).isDirectory()}catch{return!1}}function eo(e){if(!T(e))return!0;for(let r of kt){let t=P.join(e,r);if(T(t)&&(!vt(t)||he(t).length>0))return!1}return!0}function ro(e){let r=P.join(e,"runs");if(!T(r)||!vt(r))return!1;for(let t of he(r,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=P.join(r,t.name,"run.json");if(Q(n,void 0)?.id)return!0}return!1}function to(e){let r=P.join(e,"runs");if(!T(r))return!1;for(let t of he(r,{withFileTypes:!0})){if(!t.isDirectory())continue;if(Q(P.join(r,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function no(e){let r=P.join(e,"ghost");return T(r)?!T(P.join(r,"runs")):to(e)}function xt(e){return ro(e.sharedRoot)?eo(e.forgeRoot)?no(e.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function _t(e,r){Qn(r,{recursive:!0});for(let t of kt){let n=P.join(e,t),o=P.join(r,t);if(T(n)){if(T(o)&&he(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(T(o)){bt(n,o);continue}bt(n,o)}}}var kt,Et=a(()=>{"use strict";k();kt=["runs","worktrees"]});import{existsSync as b}from"node:fs";import{homedir as oo}from"node:os";import S from"node:path";function er(e=process.env){return e.HOME?.trim()||oo()}function rr(e=process.env){return S.join(er(e),".kynver","harness")}function Re(e){let r=S.resolve(K(e.trim()));for(;so.has(S.basename(r));)r=S.dirname(r);return r}function io(e,r=process.env){return S.join(rr(r),e)}function ao(e=process.env){let r=rr(e);if(b(S.join(r,"runs")))return!0;if(b(r)&&!b(S.join(r,"ghost"))&&!b(S.join(r,"forge")))return b(r);let t=S.join(er(e),Ct);return b(t)}function Se(e){let r=e.env??process.env,t=r.KYNVER_HARNESS_ROOT?.trim()||r.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:Re(t),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:Re(n),source:"config"};let o=io(e.boxKind,r);if(b(S.join(o,"runs"))||b(o)&&!lo(o))return{harnessRoot:o,source:"box_scoped"};let i=rr(r);if(e.boxKind==="forge"){let l=xt({sharedRoot:i,forgeRoot:o});if(l.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:l.blocker};if(l.action==="migrate")return e.allowForgeLegacyMigration!==!1&&_t(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&ao(r)){if(b(S.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(b(i)&&!b(S.join(i,"ghost"))&&!b(S.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let c=S.join(er(r),Ct);if(b(c))return{harnessRoot:c,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function lo(e){if(!b(e))return!0;for(let r of["runs","worktrees"]){let t=S.join(e,r);if(b(t))return!1}return!0}var Ct,so,tr=a(()=>{"use strict";V();Et();Ct=S.join(".openclaw","harness");so=new Set(["runs","worktrees"])});import At from"node:os";function be(e){return e?.trim()?e.trim():null}function uo(e,r){let t=r.trim().toLowerCase()||"host";return`${e}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function co(e){return e.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||e.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||e.KYNVER_DAEMON_STRICT_IDENTITY==="1"||e.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function ke(e=_(),r=process.env,t={}){let n=G(r,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||be(r.KYNVER_BOX_KIND)),l=t.strict===!0||co(r);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 H="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";l||t.requireExplicitBoxKind?s.push(H):o.push(`${H} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let c=be(e.runnerId),u=be(r.KYNVER_RUNTIME_ID)??be(r.OPENCLAW_RUNTIME_ID),p=c??u??uo(n.boxKind,At.hostname()),m=c?"config":u?"env":"derived";m==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${p}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let d=Ge({config:e,env:r,totalMemBytes:At.totalmem()}),$=ce(n.boxKind,d.configuredMaxWorkers??Fe(n.boxKind,d.autoCap)),v=Se({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:r});return v.migrationBlocker&&s.push(v.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:p,runnerIdSource:m,maxConcurrentWorkers:$,workerCapSource:d.workerCapSource,harnessRoot:v.harnessRoot,harnessRootSource:v.source},errors:s,warnings:o}}var ve=a(()=>{"use strict";I();M();de();ge();tr()});var wt=a(()=>{"use strict";Me();M();gt();I();ye();yt();le();Ze();ve()});var fo,rc,Ot=a(()=>{"use strict";fo=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],rc=fo.join("|")});import{existsSync as Pt,mkdirSync as go,readFileSync as Nt,writeFileSync as yo}from"node:fs";import{homedir as ho,totalmem as dc}from"node:os";import or from"node:path";function Ro(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:K(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:K(e.defaultRepo.trim())}:{}}}function _(){if(!Pt(It))return{};try{return Ro(JSON.parse(Nt(It,"utf8")))}catch{return{}}}function xe(){if(Qe(),!Pt(nr))return{};try{return JSON.parse(Nt(nr,"utf8"))}catch{return{}}}function Tt(e){Qe(),go(sr,{recursive:!0}),yo(nr,`${JSON.stringify(e,null,2)}
|
|
3
|
-
`,
|
|
4
|
-
|
|
1
|
+
var a=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};import{homedir as $r}from"node:os";import Hr from"node:path";function jn(r){return r==="~"?$r():r.startsWith("~/")||r.startsWith("~\\")?Hr.join($r(),r.slice(2)):r}function M(r){return Hr.resolve(jn(r))}var B=a(()=>{"use strict"});var jr=a(()=>{"use strict"});import{existsSync as Ai,mkdirSync as Yn,readFileSync as Vn,readdirSync as wi,renameSync as Gn,rmSync as Jn,statSync as Oi,writeFileSync as qn}from"node:fs";import{randomBytes as zn}from"node:crypto";import Xn from"node:path";function Fe(r){console.error(r),process.exit(1)}function ee(r,e){try{return JSON.parse(Vn(r,"utf8"))}catch(t){if(arguments.length>1)return e;Fe(`failed to read ${r}: ${t.message}`)}}function ie(r,e){Yn(Xn.dirname(r),{recursive:!0});let t=`${r}.${process.pid}.${zn(4).toString("hex")}.tmp`;try{qn(t,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`),Gn(t,r)}catch(n){try{Jn(t,{force:!0})}catch{}throw n}}function ae(r){return String(r).replace(/\/+$/,"")}var b=a(()=>{"use strict";jr()});var Qn,Di,Zn,Li,Yr=a(()=>{"use strict";Qn=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],Di=new Set(Qn),Zn=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],Li=new Set(Zn)});var le=a(()=>{"use strict";B();b();Yr()});var Vr=a(()=>{"use strict";le()});var Be=a(()=>{"use strict";le();B();Vr()});function qr(r){let e=ae(r);try{let t=new URL(e);return t.hostname.toLowerCase()===Gr?(t.hostname=`www.${Gr}`,ae(t.toString())):e}catch{return e}}function Ue(r){if(r?.trim())return qr(ae(r.trim()))}async function ce(r,e,t=fetch){let n=qr(r),o=new Headers(e?.headers),s=0;for(;s<=Jr;){let i=await t(n,{...e,headers:o,redirect:"manual"});if(![301,302,303,307,308].includes(i.status))return i;let l=i.headers.get("location");if(!l)return i;let u=new URL(l,n);if(u.origin!==new URL(n).origin||u.username||u.password)throw await i.body?.cancel(),new Error("kynver API fetch refused unsafe redirect (origin change or embedded credentials)");let c=(e?.method??"GET").toUpperCase();if(!["GET","HEAD"].includes(c)&&i.status!==307&&i.status!==308)return i;await i.body?.cancel(),n=u.toString(),s+=1}throw new Error(`kynver API fetch exceeded ${Jr} redirects for ${r}`)}var Gr,Jr,ue=a(()=>{"use strict";b();Gr="kynver.com";Jr=10});function U(r){let e=(r??"").trim().toLowerCase();return e==="ghost"||e==="forge"||e==="box"?e:e.includes("forge")?"forge":e.includes("ghost")||e.includes("openclaw")?"ghost":"box"}function de(r,e){return r[e]?.trim()||null}function zr(r){let e=r?.split(":")[0]?.trim();return e?U(e):null}function q(r=process.env,e={}){let t=[],n=zr(e.boxId),o=zr(de(r,"KYNVER_BOX_ID")),s=e.boxKind?.trim();if(s)return n&&n!==U(s)&&t.push(`config.boxId=${e.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:U(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=de(r,"KYNVER_BOX_KIND");if(i)return o&&o!==U(i)&&t.push(`KYNVER_BOX_ID=${de(r,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:U(i),source:"env",slugInferenceBlocked:!1,warnings:t};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:t};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:t};let l=de(r,"KYNVER_AGENT_OS_SLUG");return l&&t.push(`KYNVER_AGENT_OS_SLUG=${l} is a workspace slug, not box identity \u2014 operators set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND; customers default to box`),{boxKind:"box",source:"default",slugInferenceBlocked:!!l,warnings:t}}var F=a(()=>{"use strict"});function We(r,e){return r==="forge"?4:Math.max(1,e)}function pe(r,e){return r==="forge"?Math.min(Math.max(1,e),4):Math.max(1,e)}var me=a(()=>{"use strict"});var Xr=a(()=>{"use strict"});var ta,na,$e=a(()=>{"use strict";ta=25*1024*1024*1024,na=12*1024*1024*1024});var la,ca,Qr=a(()=>{"use strict";$e();la=5*1024*1024*1024,ca=10*1024*1024*1024});var ga,ha,He=a(()=>{"use strict";Qr();$e();ga=30*1024*1024*1024,ha=15*1024*1024*1024});function Zr(){return rt()}var fe=a(()=>{"use strict";Ye();b()});var tt=a(()=>{"use strict";fe();b()});var nt=a(()=>{"use strict"});var ot=a(()=>{"use strict";nt();b()});var st=a(()=>{"use strict"});var it=a(()=>{"use strict";st()});var ge=a(()=>{"use strict"});var at=a(()=>{"use strict"});var lt=a(()=>{"use strict"});var ct=a(()=>{"use strict";it();b();ge();at();lt()});var ut=a(()=>{"use strict";ge()});var dt=a(()=>{"use strict"});var pt=a(()=>{"use strict"});var Ve=a(()=>{"use strict"});var mt=a(()=>{"use strict"});var ft=a(()=>{"use strict";Ve();mt()});var gt=a(()=>{"use strict";ot();ct();ge();ut();dt();le();pt();ft();Ve();b()});var ht=a(()=>{"use strict";gt()});function yt(r,e={}){let t=e.perWorkerMemBytes??Ge,n=e.memReserveBytes??Je,o=e.memUtilization??qe,s=Math.max(0,Math.floor(r*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,he)}var Ge,Je,qe,he,Rt=a(()=>{"use strict";Xr();I();F();me();ye();He();fe();tt();ht();b();Ge=500*1024*1024,Je=4*1024*1024*1024,qe=.85,he=64});function re(r,e){let t=Number(r);return!Number.isFinite(t)||t<=0?e:Math.floor(t)}function ze(r){let e=r.config??{},t=r.env??process.env,n=re(e.perWorkerMemBytes,Ge),o=re(e.memReserveBytes,Je),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):qe)),i=yt(r.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(r.configuredMaxWorkersOverride!==void 0&&r.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:re(r.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(e.maxConcurrentWorkers!==void 0&&e.maxConcurrentWorkers!==null){let c=re(e.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,he),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&re(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,he),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var ye=a(()=>{"use strict";Rt()});import{homedir as lo}from"node:os";import co from"node:path";var St,Xe=a(()=>{"use strict";St=co.join(lo(),".kynver",".env")});var kt=a(()=>{"use strict"});var bt=a(()=>{"use strict";kt()});var vt=a(()=>{"use strict"});var xt=a(()=>{"use strict";b()});var Qe=a(()=>{"use strict";bt();vt();xt()});var _t=a(()=>{"use strict"});var Et=a(()=>{"use strict";_t()});var Re=a(()=>{"use strict";Xe();B();I();Qe();Et()});var Ct=a(()=>{"use strict";F();F()});var At=a(()=>{"use strict";Xe();Qe();Re()});function It(r){if(!Ot)return r;if(!wt)throw new Ze;return wt}function rr(){if(Ot)throw new er}var Ze,er,Ot,wt,tr=a(()=>{"use strict";Ze=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},er=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},Ot=!1,wt=null});import{existsSync as T,mkdirSync as fo,readdirSync as Se,renameSync as Tt,statSync as go}from"node:fs";import N from"node:path";function Pt(r){try{return go(r).isDirectory()}catch{return!1}}function ho(r){if(!T(r))return!0;for(let e of Nt){let t=N.join(r,e);if(T(t)&&(!Pt(t)||Se(t).length>0))return!1}return!0}function yo(r){let e=N.join(r,"runs");if(!T(e)||!Pt(e))return!1;for(let t of Se(e,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=N.join(e,t.name,"run.json");if(ee(n,void 0)?.id)return!0}return!1}function Ro(r){let e=N.join(r,"runs");if(!T(e))return!1;for(let t of Se(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(ee(N.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function So(r){let e=N.join(r,"ghost");return T(e)?!T(N.join(e,"runs")):Ro(r)}function Dt(r){return yo(r.sharedRoot)?ho(r.forgeRoot)?So(r.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function Lt(r,e){fo(e,{recursive:!0});for(let t of Nt){let n=N.join(r,t),o=N.join(e,t);if(T(n)){if(T(o)&&Se(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(T(o)){Tt(n,o);continue}Tt(n,o)}}}var Nt,Kt=a(()=>{"use strict";b();Nt=["runs","worktrees"]});import{existsSync as k}from"node:fs";import{homedir as ko}from"node:os";import S from"node:path";function nr(r=process.env){return r.HOME?.trim()||ko()}function or(r=process.env){return S.join(nr(r),".kynver","harness")}function ke(r){let e=S.resolve(M(r.trim()));for(;bo.has(S.basename(e));)e=S.dirname(e);return e}function vo(r,e=process.env){return S.join(or(e),r)}function xo(r=process.env){let e=or(r);if(k(S.join(e,"runs")))return!0;if(k(e)&&!k(S.join(e,"ghost"))&&!k(S.join(e,"forge")))return k(e);let t=S.join(nr(r),Mt);return k(t)}function be(r){let e=r.env??process.env,t=e.KYNVER_HARNESS_ROOT?.trim()||e.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:ke(t),source:"env"};let n=r.configuredHarnessRoot?.trim();if(n)return{harnessRoot:ke(n),source:"config"};let o=vo(r.boxKind,e);if(k(S.join(o,"runs"))||k(o)&&!_o(o))return{harnessRoot:o,source:"box_scoped"};let i=or(e);if(r.boxKind==="forge"){let l=Dt({sharedRoot:i,forgeRoot:o});if(l.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:l.blocker};if(l.action==="migrate")return r.allowForgeLegacyMigration!==!1&&Lt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&xo(e)){if(k(S.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(k(i)&&!k(S.join(i,"ghost"))&&!k(S.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=S.join(nr(e),Mt);if(k(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function _o(r){if(!k(r))return!0;for(let e of["runs","worktrees"]){let t=S.join(r,e);if(k(t))return!1}return!0}var Mt,bo,sr=a(()=>{"use strict";B();Kt();Mt=S.join(".openclaw","harness");bo=new Set(["runs","worktrees"])});import Ft from"node:os";function ve(r){return r?.trim()?r.trim():null}function Eo(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function Co(r){return r.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||r.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||r.KYNVER_DAEMON_STRICT_IDENTITY==="1"||r.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function xe(r=_(),e=process.env,t={}){let n=q(e,r),o=[...n.warnings],s=[],i=!!(r.boxKind?.trim()||ve(e.KYNVER_BOX_KIND)),l=t.strict===!0||Co(e);if((t.requireExplicitBoxKind||l)&&!i&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup` (customers: boxKind=box) or `kynver setup --box-kind forge|ghost` for operator pools before dispatch"),n.slugInferenceBlocked&&!i){let V="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";l||t.requireExplicitBoxKind?s.push(V):o.push(`${V} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=ve(r.runnerId),c=ve(e.KYNVER_RUNTIME_ID)??ve(e.OPENCLAW_RUNTIME_ID),p=u??c??Eo(n.boxKind,Ft.hostname()),m=u?"config":c?"env":"derived";m==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${p}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let d=ze({config:r,env:e,totalMemBytes:Ft.totalmem()}),Y=pe(n.boxKind,d.configuredMaxWorkers??We(n.boxKind,d.autoCap)),v=be({boxKind:n.boxKind,configuredHarnessRoot:r.harnessRoot,env:e});return v.migrationBlocker&&s.push(v.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:p,runnerIdSource:m,maxConcurrentWorkers:Y,workerCapSource:d.workerCapSource,harnessRoot:v.harnessRoot,harnessRootSource:v.source},errors:s,warnings:o}}var _e=a(()=>{"use strict";I();F();me();ye();sr()});var Bt=a(()=>{"use strict";Be();F();Ct();I();Re();At();ue();tr();_e()});var Io,xu,Ut=a(()=>{"use strict";Io=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],xu=Io.join("|")});var Wt=a(()=>{"use strict";B()});var $t=a(()=>{"use strict";Wt()});import{execFileSync as To}from"node:child_process";function lr(r=process.env){let e=r[No]?.trim().toLowerCase();return e==="file"?"file":e==="keychain"?"keychain":"auto"}function Po(r,e,t){let n={encoding:"utf8",timeout:t.timeoutMs,stdio:["pipe","pipe","pipe"],windowsHide:!0,...t.input!==void 0?{input:t.input}:{}};return To(r,e,n)}function Do(r=process.platform){return r==="darwin"?"macos":r==="linux"?"libsecret":r==="win32"?"windows":null}function ir(r,e){let t=JSON.stringify(W),n=JSON.stringify(e),o="[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]; $v = New-Object Windows.Security.Credentials.PasswordVault;";return r==="get"?`${o} try { $c = $v.Retrieve(${t}, ${n}); $c.RetrievePassword(); [Console]::Out.Write($c.Password) } catch { exit 3 }`:r==="set"?`${o} $s = [Console]::In.ReadToEnd().TrimEnd("\`r","\`n"); try { $old = $v.Retrieve(${t}, ${n}); $v.Remove($old) } catch {}; $v.Add((New-Object Windows.Security.Credentials.PasswordCredential(${t}, ${n}, $s)))`:`${o} try { $old = $v.Retrieve(${t}, ${n}); $v.Remove($old) } catch {}`}function Ht(r={}){if(lr(r.env??process.env)==="file")return null;let t=Do(r.platform??process.platform);return t?new ar(t,r.exec):null}var W,No,P,ar,jt=a(()=>{"use strict";W="kynver",No="KYNVER_CREDENTIAL_STORE";P=5e3;ar=class{constructor(e,t=Po){this.backend=e;this.exec=t}backend;exec;get(e){try{if(this.backend==="macos"){let s=this.exec("security",["find-generic-password","-s",W,"-a",e,"-w"],{timeoutMs:P}).replace(/\r?\n$/,"");return s||null}if(this.backend==="libsecret"){let s=this.exec("secret-tool",["lookup","service",W,"account",e],{timeoutMs:P}).replace(/\r?\n$/,"");return s||null}let n=this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ir("get",e)],{timeoutMs:P}).replace(/\r?\n$/,"");return n||null}catch{return null}}set(e,t){if(!t||/[\r\n]/.test(t))return!1;try{this.backend==="macos"?this.exec("security",["add-generic-password","-U","-s",W,"-a",e,"-l",`Kynver (${e})`,"-w",t],{timeoutMs:P}):this.backend==="libsecret"?this.exec("secret-tool",["store",`--label=Kynver (${e})`,"service",W,"account",e],{input:`${t}
|
|
3
|
+
`,timeoutMs:P}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ir("set",e)],{input:`${t}
|
|
4
|
+
`,timeoutMs:P})}catch{return!1}return this.get(e)===t}delete(e){try{this.backend==="macos"?this.exec("security",["delete-generic-password","-s",W,"-a",e],{timeoutMs:P}):this.backend==="libsecret"?this.exec("secret-tool",["clear","service",W,"account",e],{timeoutMs:P}):this.exec("powershell.exe",["-NoProfile","-NonInteractive","-Command",ir("delete",e)],{timeoutMs:P})}catch{}}}});function pr(){return cr||(cr=new ur),cr}var dr,Lo,Ee,ur,cr,Yt=a(()=>{"use strict";jt();dr="api-key",Lo=6e4,Ee=class extends Error{constructor(e){super(`KYNVER_CREDENTIAL_STORE=keychain but the OS keychain could not store "${e}"; refusing to write the secret to disk`),this.name="KeychainUnavailableError"}},ur=class{cache=new Map;keychain;env;now;constructor(e={}){this.env=e.env??process.env,this.keychain=e.keychain===void 0?Ht({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<Lo)return t.value;let n=this.keychain.get(e);return this.cache.set(e,{value:n,at:this.now()}),n}write(e,t){let n=lr(this.env);if(!this.keychain){if(n==="keychain")throw new Ee(e);return!1}let o=this.keychain.set(e,t);if(o)this.cache.set(e,{value:t,at:this.now()});else if(this.cache.delete(e),n==="keychain")throw new Ee(e);return o}remove(e){this.cache.delete(e),this.keychain?.delete(e)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}},cr=null});import{existsSync as Gt,mkdirSync as Ko,readFileSync as Jt,writeFileSync as Mo}from"node:fs";import{homedir as Fo,totalmem as Vu}from"node:os";import gr from"node:path";function Bo(r){return{...r,...r.harnessRoot?.trim()?{harnessRoot:M(r.harnessRoot.trim())}:{},...r.defaultRepo?.trim()?{defaultRepo:M(r.defaultRepo.trim())}:{}}}function _(){if(!Gt(Vt))return{};try{return Bo(JSON.parse(Jt(Vt,"utf8")))}catch{return{}}}function Ce(){if(rr(),!Gt(mr))return{};try{return JSON.parse(Jt(mr,"utf8"))}catch{return{}}}function fr(r){rr(),Ko(hr,{recursive:!0}),Mo(mr,`${JSON.stringify(r,null,2)}
|
|
5
|
+
`,{mode:384})}function Uo(r,e,t,n={}){let o=Ce();if(pr().write(r,t)){let i={...o,...n};delete i[e],i.store="keychain",i.keychainAccounts=Array.from(new Set([...o.keychainAccounts??[],r])).sort(),fr(i);return}fr({...o,...n,[e]:t})}function Wo(r,e){let t=pr().read(r);return t||Ce()[e]}function qt(){return It($o)}function zt(){return qt().getApiKey()}function Ho(r,e){qt().persistRunnerToken(r,e)}function jo(r){let e=Xt(r);return e||Vo("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),e}function Xt(r){let e=r||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||_().apiBaseUrl;return Ue(e)}async function Qt(r,e,t){let n=zt(),o=Xt(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 Yo(e,{baseUrl:o,apiKey:n});return s&&s!==r?(Ho(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 Yo(r,e){let t=e?.apiKey||zt();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${jo(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 Vo(r){console.error(r),process.exit(1)}var hr,Vt,mr,ld,cd,$o,I=a(()=>{"use strict";Be();B();ue();F();me();ye();He();Re();Bt();Ut();_e();$t();tr();Yt();hr=gr.join(Fo(),".kynver"),Vt=gr.join(hr,"config.json"),mr=gr.join(hr,"credentials");ld=500*1024*1024,cd=4*1024*1024*1024;$o={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:Wo(dr,"apiKey")},getRunnerToken(r){let e=Ce();if(!!e.runnerToken&&!!r&&e.runnerTokenAgentOsId===r)return e.runnerToken;let n=process.env.KYNVER_RUNNER_TOKEN?.trim();if(n)return n;if(e.runnerToken&&!(r&&e.runnerTokenAgentOsId&&e.runnerTokenAgentOsId!==r))return e.runnerToken},persistApiKey(r){Uo(dr,"apiKey",r)},persistRunnerToken(r,e){fr({...Ce(),runnerToken:e,runnerTokenAgentOsId:r})}}});import Zt from"node:path";function Ae(r){return ke(r)}function yr(){let r=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(r)return Ae(r);let e=_(),t=e.harnessRoot?.trim();if(t)return Ae(t);let n=xe(e,process.env);return n.identity?n.identity.harnessRoot:be({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function et(r){return Zt.join(Ae(r),"runs")}function Go(r){return Zt.join(Ae(r),"worktrees")}function rt(){let r=yr();return{harnessRoot:r,runsDir:et(r),worktreesDir:Go(r)}}var Ye=a(()=>{"use strict";I();sr();_e();b()});import{existsSync as _n,realpathSync as En,readFileSync as Cn}from"node:fs";import Br from"node:path";var An=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 On(){try{return Cn("/proc/self/mounts","utf8")}catch{return null}}function In(r){let e=Br.resolve(r);for(let t=0;t<64;t+=1){if(_n(e))try{return En.native(e)}catch{return e}let n=Br.dirname(e);if(n===e)return e;e=n}return e}function Tn(r){return r.replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function Nn(r){let e=[];for(let t of r.split(`
|
|
6
|
+
`)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:Tn(n[1]),fsType:n[2]})}return e}function Ur(r,e=process.platform){return e==="win32"?r.replace(/\\/g,"/"):r}function Pn(r,e){let t=null,n=Ur(r);for(let o of e){let s=Ur(o.mountPoint),i=s.endsWith("/")?s:`${s}/`;(n===s||`${n}/`.startsWith(i))&&(!t||o.mountPoint.length>t.mountPoint.length)&&(t=o)}return t}function Le(r,e){let n=(e?.resolveRealPath??In)(r),o=(e?.mountsSource??On)();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=Pn(n,Nn(o));if(!s)return{verdict:"rejected",reason:"No mount entry covers the resolved database path \u2014 refusing WAL mode (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let i=s.fsType.toLowerCase();return 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}:An.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"}},Dn=[`CREATE TABLE IF NOT EXISTS local_meta (
|
|
5
7
|
key TEXT PRIMARY KEY,
|
|
6
8
|
value TEXT NOT NULL
|
|
7
9
|
) STRICT`,`CREATE TABLE IF NOT EXISTS process_identity (
|
|
@@ -27,7 +29,7 @@ var a=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=
|
|
|
27
29
|
payload_json TEXT NOT NULL,
|
|
28
30
|
created_at TEXT NOT NULL,
|
|
29
31
|
PRIMARY KEY (scope, seq)
|
|
30
|
-
) STRICT`];function
|
|
32
|
+
) STRICT`];function Ln(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 Wr(r,e){let t=Ln(r);if(t!==null&&t>1)throw new se(t,1);r.exec("BEGIN IMMEDIATE");try{for(let n of Dn)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 Kn}from"node:fs";import Mn from"node:path";import{DatabaseSync as Fn}from"node:sqlite";var Z=class extends Error{constructor(e){super(`local-run-store refused: ${e}`),this.name="FilesystemPolicyError"}},Bn="local-run-store.sqlite",Un=5e3,J=class r{db;now;databasePath;constructor(e,t,n){this.db=e,this.databasePath=t,this.now=n}static open(e){let t=Le(e.directory,e.classifyOptions);if(t.verdict!=="accepted")throw new Z(t.reason);Kn(e.directory,{recursive:!0,mode:448});let n=Mn.join(e.directory,e.filename??Bn),o=new Fn(n,{timeout:e.busyTimeoutMs??Un}),s=e.now??(()=>new Date);try{o.exec("PRAGMA journal_mode = WAL");let i=o.prepare("PRAGMA journal_mode").get();if(i?.journal_mode?.toLowerCase()!=="wal")throw new Z(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),Wr(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
|
|
31
33
|
(process_key, pid, runtime_version, node_version, started_at, registered_at)
|
|
32
34
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
33
35
|
ON CONFLICT(process_key) DO UPDATE SET
|
|
@@ -35,24 +37,24 @@ var a=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=
|
|
|
35
37
|
runtime_version = excluded.runtime_version,
|
|
36
38
|
node_version = excluded.node_version,
|
|
37
39
|
started_at = excluded.started_at,
|
|
38
|
-
registered_at = excluded.registered_at`).run(
|
|
39
|
-
FROM process_identity WHERE process_key = ?`).get(
|
|
40
|
+
registered_at = excluded.registered_at`).run(e.processKey,e.pid,e.runtimeVersion,e.nodeVersion,e.startedAt,t)}),{...e,registeredAt:t}}getProcessIdentity(e){let t=this.db.prepare(`SELECT process_key, pid, runtime_version, node_version, started_at, registered_at
|
|
41
|
+
FROM process_identity WHERE process_key = ?`).get(e);return t?{processKey:t.process_key,pid:t.pid,runtimeVersion:t.runtime_version,nodeVersion:t.node_version,startedAt:t.started_at,registeredAt:t.registered_at}:null}tryReserveAdmission(e,t,n,o){let s=o??this.now(),i=new Date(s.getTime()+n).toISOString();return this.inImmediateTransaction(()=>{let l=this.db.prepare("SELECT reservation_key, owner, expires_at FROM admission_reservations WHERE reservation_key = ?").get(e);return l&&l.expires_at>s.toISOString()&&l.owner!==t?{acquired:!1,current:{key:e,owner:l.owner,expiresAt:l.expires_at}}:(this.db.prepare(`INSERT INTO admission_reservations (reservation_key, owner, expires_at, created_at)
|
|
40
42
|
VALUES (?, ?, ?, ?)
|
|
41
43
|
ON CONFLICT(reservation_key) DO UPDATE SET
|
|
42
44
|
owner = excluded.owner,
|
|
43
|
-
expires_at = excluded.expires_at`).run(
|
|
45
|
+
expires_at = excluded.expires_at`).run(e,t,i,s.toISOString()),{acquired:!0,current:{key:e,owner:t,expiresAt:i}})})}releaseAdmission(e,t){return this.inImmediateTransaction(()=>{let n=this.db.prepare("DELETE FROM admission_reservations WHERE reservation_key = ? AND owner = ?").run(e,t);return Number(n.changes)>0})}listAdmissionReservations(e){let t=Math.floor(e?.limit??200),n=Number.isFinite(t)?Math.max(1,Math.min(1e3,t)):200,o=[],s=[];if(e?.keyPrefix){let u=e.keyPrefix.replace(/[\\%_]/g,c=>`\\${c}`);o.push("reservation_key LIKE ? ESCAPE '\\'"),s.push(`${u}%`)}e?.includeExpired||(o.push("expires_at > ?"),s.push((e?.now??this.now()).toISOString()));let i=o.length?`WHERE ${o.join(" AND ")}`:"";return this.db.prepare(`SELECT reservation_key, owner, expires_at
|
|
44
46
|
FROM admission_reservations ${i}
|
|
45
47
|
ORDER BY expires_at ASC, reservation_key ASC
|
|
46
|
-
LIMIT ?`).all(...s,n).map(
|
|
48
|
+
LIMIT ?`).all(...s,n).map(u=>({key:u.reservation_key,owner:u.owner,expiresAt:u.expires_at}))}recordOperationReceipt(e){return this.inImmediateTransaction(()=>{let t=this.db.prepare(`INSERT INTO operation_receipts (idempotency_key, operation, result_json, recorded_at)
|
|
47
49
|
VALUES (?, ?, ?, ?)
|
|
48
|
-
ON CONFLICT(idempotency_key) DO NOTHING`).run(
|
|
50
|
+
ON CONFLICT(idempotency_key) DO NOTHING`).run(e.idempotencyKey,e.operation,e.resultJson??null,this.now().toISOString());return{deduplicated:Number(t.changes)===0}})}listOperationReceipts(e){let t=Math.floor(e?.limit??200),n=Number.isFinite(t)?Math.max(1,Math.min(1e3,t)):200,o=[],s=[];if(e?.operation&&(o.push("operation = ?"),s.push(e.operation)),e?.keyPrefix){let u=e.keyPrefix.replace(/[\\%_]/g,c=>`\\${c}`);o.push("idempotency_key LIKE ? ESCAPE '\\'"),s.push(`${u}%`)}e?.recordedAfter&&(o.push("recorded_at > ?"),s.push(e.recordedAfter));let i=o.length?`WHERE ${o.join(" AND ")}`:"";return this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
|
|
49
51
|
FROM operation_receipts ${i}
|
|
50
52
|
ORDER BY recorded_at ASC, idempotency_key ASC
|
|
51
|
-
LIMIT ?`).all(...s,n).map(
|
|
52
|
-
FROM operation_receipts WHERE idempotency_key = ?`).get(
|
|
53
|
-
VALUES (?, ?, ?, ?)`).run(
|
|
54
|
-
WHERE scope = ? ORDER BY seq DESC LIMIT 1`).get(r);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(r){let t=this.db.prepare(`PRAGMA ${r}`).get();return String(Object.values(t)[0])}close(){this.db.close()}};import{existsSync as Cn,renameSync as An}from"node:fs";function wn(e,r){let t=`${e}.quarantine-${r}`;for(let n of["","-wal","-shm"]){let o=`${e}${n}`;Cn(o)&&An(o,`${t}${n}`)}return t}function De(e){let r=e.quarantineStamp??(e.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=Y.open(e);if(s.integrityCheck())return{store:s,recovered:!1,quarantinedTo:null};s.close()}catch(s){if(s.name==="SchemaDowngradeRefusedError"||s.name==="FilesystemPolicyError")throw s;t=s}let n=`${e.directory}/${e.filename??"local-run-store.sqlite"}`,o=wn(n,r);try{return{store:Y.open(e),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}$e();function Eo(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function Co(){return Ut.classifyOptions??Eo()}var Ut={};function Ao(e){Ut=e}var Bt=300*1e3,N=null,ee=0;function wo(e){ee+=1;try{let r=Co(),t=De({directory:e,...r?{classifyOptions:r}:{}});return{store:t.store,status:{state:"open",harnessRoot:e,databasePath:t.store.databasePath,schemaVersion:t.store.localSchemaVersion(),recovered:t.recovered,quarantinedTo:t.quarantinedTo,reason:null,openAttempts:ee},failedAtMs:null,permanentRefusal:!1}}catch(r){return{store:null,status:{state:"unavailable",harnessRoot:e,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${r.name}: ${r.message}`,openAttempts:ee},failedAtMs:Date.now(),permanentRefusal:r.name==="FilesystemPolicyError"||r.name==="SchemaDowngradeRefusedError"}}}function Oo(e,r){return e.store||e.permanentRefusal?!1:e.failedAtMs===null?!0:r-e.failedAtMs>=Bt}function f(e=Date.now()){let r=ir();return(!N||N.status.harnessRoot!==r||Oo(N,e))&&(lr(),N=wo(r)),N.store}function Wt(){return N?N.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:ee}}function ar(){return f(),Wt()}function lr(){try{N?.store?.close()}catch{}N=null}function Io(){lr(),ee=0}I();k();import{existsSync as To,readFileSync as Po}from"node:fs";import{homedir as No}from"node:os";import Do from"node:path";var Lo=3e4,x=null;function ur(e){let r=e.replace(/[^A-Za-z0-9_-]/g,"_");return Do.join(No(),".kynver",`local-run-store-flags-${r}.json`)}function cr(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let r=e,t={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=r[o];(s==="off"||s==="shadow"||s==="enforce")&&(t[o]=s)}return t}function Mo(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e.response;if(!r||typeof r!="object"||Array.isArray(r))return null;let t=r.localRunStoreFlags;return t===void 0?null:cr(t)}function Ko(e,r){try{let t=ur(e),n={contractVersion:1,agentOsId:e,flags:cr(r),deliveredAt:new Date().toISOString()};oe(t,n),x={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function dr(e=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(x&&e-x.loadedAtMs<Lo)return x.flags;try{let r=_().agentOsId?.trim();if(!r)return x={flags:{},loadedAtMs:e,file:null},x.flags;let t=ur(r);if(!To(t))return x={flags:{},loadedAtMs:e,file:t},x.flags;let n=JSON.parse(Po(t,"utf8")),o=n?.contractVersion===1?cr(n.flags):{};return x={flags:o,loadedAtMs:e,file:t},o}catch{return x={flags:{},loadedAtMs:e,file:null},x.flags}}function Fo(){x=null}var $t=[{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 Ht(e){let r=e?.trim().toLowerCase()??"";return r===""?{mode:"off",unknown:!1}:r==="off"||r==="shadow"||r==="enforce"?{mode:r,unknown:!1}:{mode:"off",unknown:!0}}function A(e=process.env){let r={},t={},n=[],o=dr();for(let s of $t){let i=e[s.env];if(typeof i=="string"&&i.trim()!==""){let u=Ht(i);r[s.key]=u.mode,t[s.key]="env",u.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let c=o[s.key];if(c){r[s.key]=c,t[s.key]="server";continue}r[s.key]="off",t[s.key]="default"}return{flags:r,sources:t,warnings:n}}function Uo(e){return Object.values(e).some(r=>r!=="off")}var R={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};function w(e=process.env){return A(e).flags.dispatchReceipts}function pr(e){return w(e)!=="off"}function mr(e,r){return`dispatch:${e}:${r.taskId}:${r.leaseToken}`}function re(e,r,t){if(!pr())return;let n=f();if(n)try{n.recordOperationReceipt({idempotencyKey:mr(e,r),operation:`dispatch-${e}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function Bo(e){re("claim",e,{runId:e.runId,workerName:e.workerName,provider:e.provider})}function fr(e){re("spawned",e)}function Ee(e,r){re("released",e,{reasonClass:r})}function Wo(e){re("completion-sent",e)}function $o(e,r){re("completion-acked",e,{outcome:r})}function Ho(e){if(!pr())return!1;let r=f();if(!r)return!1;try{let t=r.getOperationReceipt(mr("completion-acked",e));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 jo(e){let r=String(e??"").split(":")[0]?.trim()??"";return r.length>0?r.slice(0,64):"unknown"}function Yo(e){if(w()!=="enforce")return!1;let r=f();if(!r)return!1;try{let t=r.getOperationReceipt(mr("completion-acked",e));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 Vo=600*1e3;function Go(e,r){if(w()!=="enforce")return;let t=f();if(t)try{t.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${e}:${r}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:r})})}catch{R.storeFailures+=1}}function qo(e,r){if(w()!=="enforce")return[];let t=f();if(!t)return[];let n=r?.nowMs??Date.now(),o=r?.windowMs??Vo;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===e:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(e.length+1))}).filter(s=>s.length>0)}catch{return R.storeFailures+=1,[]}}function q(e){let r=e.split(":")[0]??"",t=Number(r);return Number.isInteger(t)&&t>=0?t:null}var Jo=900*1e3,jt=10080*60*1e3,zo=1440*60*1e3,Xo=500,Qo=300;function gr(e){let r={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!pr())return r;let t=f();if(!t)return r;let n=e?.nowMs??Date.now(),o=e?.strandedAfterMs??Jo;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-jt).toISOString(),limit:Xo}),i=0,l=[];for(let u of s){let p=u.idempotencyKey.slice(15),m=Date.parse(u.recordedAt);if(!Number.isFinite(m)||n-m<o)continue;let d=t.getOperationReceipt(`dispatch:spawned:${p}`),$=t.getOperationReceipt(`dispatch:released:${p}`);if(d||$){n-m>=zo&&l.length+5<=Qo&&l.push(u.idempotencyKey,`dispatch:spawned:${p}`,`dispatch:released:${p}`,`dispatch:completion-sent:${p}`,`dispatch:completion-acked:${p}`);continue}let v=p.split(":")[0]??"",H=q(p.slice(v.length+1));if((v?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${v}:`,limit:10}):[]).some(y=>{if(H===null)return!0;let j=y.idempotencyKey.slice(`dispatch:completion-acked:${v}:`.length),L=q(j);return L===null||L>=H}))continue;let h=!1;if(e?.hasLiveWorker&&u.resultJson)try{let y=JSON.parse(u.resultJson);y.runId&&y.workerName&&(h=e.hasLiveWorker({runId:y.runId,workerName:y.workerName}))}catch{h=!1}h||(i+=1)}let c=l.length>0?t.deleteOperationReceiptsByKeys(l):0;if(w()==="enforce"){let u=t.listOperationReceipts({limit:100}).filter(p=>{let m=Date.parse(p.recordedAt);return Number.isFinite(m)&&n-m>=jt}).map(p=>p.idempotencyKey);if(u.length>0){let p=t.deleteOperationReceiptsByKeys(u);c+=p,R.agedReceiptsPruned+=p}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:c}}catch{return R.storeFailures+=1,r}}function yr(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function Zo(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as as,readFileSync as ls}from"node:fs";var U=900*1e3,Rr="admission-shadow",hr="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Ce=!1;function es(){Ce=!1}function B(e=process.env){return A(e).flags.admission}function Ae(e,r){return`${hr}${e}:${r}`}function rs(e,r){if(B()==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Ae(e,r),Rr,U)}catch{E.storeFailures+=1}}function Sr(e,r){if(B()==="off")return;let t=f();if(t)try{t.releaseAdmission(Ae(e,r),Rr)}catch{E.storeFailures+=1}}function ts(e){let r={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(B()==="off")return r;let t=f();if(!t)return r;try{let n=new Set(e.liveWorkers.map(d=>Ae(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:hr,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,c=!Ce;Ce=!0,!c&&i>0&&(E.missingForLive+=i);let u=0;for(let d of e.liveWorkers)t.tryReserveAdmission(Ae(d.runId,d.workerName),Rr,U),u+=1;let p=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(p+=1,E.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:hr,limit:500}).length,refreshed:u,deadReleased:p,missingForLive:i,orphaned:l,adoptionPass:c}}catch{return E.storeFailures+=1,r}}function br(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function ns(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Ce=!1}var Ie="worker-slot-n:",we=64;function Yt(e){return`${Ie}${e}`}function Oe(e,r){return`${e}:${r}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function os(e){if(B()!=="enforce")return{admitted:!0};let r=f();if(!r)return{admitted:!0};let t=Math.max(0,Math.min(we,Math.floor(e.maxSlots)));if(e.diskActiveWorkers>=t)return C.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=Oe(e.runId,e.workerName);for(let o=0;o<t;o+=1)if(r.tryReserveAdmission(Yt(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(e,r){if(B()==="off")return;let t=f();if(t)try{let n=Oe(e,r),o=t.listAdmissionReservations({keyPrefix:Ie,limit:we});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function ss(e){let r={refreshed:0,deadReleased:0,adopted:0};if(B()!=="enforce")return r;let t=f();if(!t)return r;try{let n=new Set(e.liveWorkers.map(u=>Oe(u.runId,u.workerName))),o=t.listAdmissionReservations({keyPrefix:Ie,limit:we}),s=0,i=0,l=new Set;for(let u of o)n.has(u.owner)?(t.tryReserveAdmission(u.key,u.owner,U),l.add(u.owner),s+=1):t.releaseAdmission(u.key,u.owner)&&(i+=1);let c=0;for(let u of e.liveWorkers){let p=Oe(u.runId,u.workerName);if(!l.has(p)){for(let m=0;m<we;m+=1)if(t.tryReserveAdmission(Yt(m),p,U).acquired){c+=1;break}}}return{refreshed:s,deadReleased:i,adopted:c}}catch{return C.enforceStoreFailures+=1,r}}function vr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function is(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var us="dispatch:claim:",cs=900*1e3,ds=10080*60*1e3,ps=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function Vt(e){if(process.platform!=="linux"||!e.trim())return null;let r=[];try{r=as("/proc")}catch{return null}for(let t of r)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(ls(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(e))return Number(t)}catch{}return null}async function xr(e){let r=w(),t={mode:r,scanned:0,outcomes:[]};if(r!=="enforce")return t;let n=f();if(!n)return t;let o=e.nowMs??Date.now(),s=e.strandedAfterMs??cs,i=e.findOrphanPid??Vt,l=[],c;try{c=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-ds).toISOString(),limit:ps})}catch{return O.recoveryStoreFailures+=1,t}for(let u of c){let p=u.idempotencyKey.slice(us.length),m=p.split(":")[0]??"",d=p.slice(m.length+1);if(!(!m||!d))try{let $=Date.parse(u.recordedAt);if(!Number.isFinite($)||o-$<s||n.getOperationReceipt(`dispatch:spawned:${p}`)||n.getOperationReceipt(`dispatch:released:${p}`))continue;let v=q(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${m}:`,limit:10}).some(L=>{if(v===null)return!0;let z=q(L.idempotencyKey.slice(`dispatch:completion-acked:${m}:`.length));return z===null||z>=v}))continue;let J={};try{J=u.resultJson?JSON.parse(u.resultJson):{}}catch{J={}}let h=J.runId??null,y=J.workerName??null;if(h&&y&&e.hasLiveWorker({runId:h,workerName:y})){fr({taskId:m,leaseToken:d}),l.push({taskId:m,leaseToken:d,runId:h,workerName:y,action:"finalized_late"});continue}if(h&&y){let L=e.worktreePathFor({runId:h,workerName:y}),z=L?i(L):null;if(z!==null){O.recoveryDeferredOrphans+=1,l.push({taskId:m,leaseToken:d,runId:h,workerName:y,action:"deferred_orphan",detail:`live pid ${z} references ${L}`});continue}}if(!h){l.push({taskId:m,leaseToken:d,runId:h,workerName:y,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let j=await e.releaseClaim({taskId:m,leaseToken:d,runId:h});j.released?(Ee({taskId:m,leaseToken:d},"restart_recovery"),y&&(Sr(h,y),kr(h,y)),O.recoveredStrandedClaims+=1,l.push({taskId:m,leaseToken:d,runId:h,workerName:y,action:"released"})):j.transportError?l.push({taskId:m,leaseToken:d,runId:h,workerName:y,action:"deferred_transport",detail:j.detail}):(Ee({taskId:m,leaseToken:d},"restart_recovery_refused"),l.push({taskId:m,leaseToken:d,runId:h,workerName:y,action:"release_refused",detail:j.detail}))}catch{O.recoveryStoreFailures+=1}}return{mode:r,scanned:c.length,outcomes:l}}function _r(){return{"dispatchReceipts.recoveredStrandedClaims":O.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":O.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":O.recoveryStoreFailures}}function ms(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}pe();import xs from"node:path";var fs="kynver-harness:",gs="@runner:";function Gt(e,r){let t=e.trim(),n=r.trim();return`${fs}${t}${gs}${n}`}I();import zt from"node:os";var ys="embedded-1",hs=[{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"}],Rs={"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(`
|
|
53
|
+
LIMIT ?`).all(...s,n).map(u=>({idempotencyKey:u.idempotency_key,operation:u.operation,resultJson:u.result_json,recordedAt:u.recorded_at}))}deleteOperationReceiptsByKeys(e){return e.length===0?0:this.inImmediateTransaction(()=>{let t=this.db.prepare("DELETE FROM operation_receipts WHERE idempotency_key = ?"),n=0;for(let o of e)n+=Number(t.run(o).changes);return n})}getOperationReceipt(e){let t=this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
|
|
54
|
+
FROM operation_receipts WHERE idempotency_key = ?`).get(e);return t?{idempotencyKey:t.idempotency_key,operation:t.operation,resultJson:t.result_json,recordedAt:t.recorded_at}:null}saveRecoveryCheckpoint(e){return this.inImmediateTransaction(()=>{let t=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max_seq FROM recovery_checkpoints WHERE scope = ?").get(e.scope),n=Number(t.max_seq)+1;return this.db.prepare(`INSERT INTO recovery_checkpoints (scope, seq, payload_json, created_at)
|
|
55
|
+
VALUES (?, ?, ?, ?)`).run(e.scope,n,e.payloadJson,this.now().toISOString()),{seq:n}})}latestRecoveryCheckpoint(e){let t=this.db.prepare(`SELECT scope, seq, payload_json, created_at FROM recovery_checkpoints
|
|
56
|
+
WHERE scope = ? ORDER BY seq DESC LIMIT 1`).get(e);return t?{scope:t.scope,seq:t.seq,payloadJson:t.payload_json,createdAt:t.created_at}:null}localSchemaVersion(){return 1}checkpointTruncate(){this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)")}integrityCheck(){return this.db.prepare("PRAGMA integrity_check").get()?.integrity_check==="ok"}pragma(e){let t=this.db.prepare(`PRAGMA ${e}`).get();return String(Object.values(t)[0])}close(){this.db.close()}};import{existsSync as Wn,renameSync as $n}from"node:fs";function Hn(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;Wn(o)&&$n(o,`${t}${n}`)}return t}function Me(r){let e=r.quarantineStamp??(r.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=J.open(r);if(s.integrityCheck())return{store:s,recovered:!1,quarantinedTo:null};s.close()}catch(s){if(s.name==="SchemaDowngradeRefusedError"||s.name==="FilesystemPolicyError")throw s;t=s}let n=`${r.directory}/${r.filename??"local-run-store.sqlite"}`,o=Hn(n,e);try{return{store:J.open(r),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}Ye();function Jo(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function qo(){return en.classifyOptions??Jo()}var en={};function zo(r){en=r}var rn=300*1e3,D=null,te=0;function Xo(r){te+=1;try{let e=qo(),t=Me({directory:r,...e?{classifyOptions:e}:{}});return{store:t.store,status:{state:"open",harnessRoot:r,databasePath:t.store.databasePath,schemaVersion:t.store.localSchemaVersion(),recovered:t.recovered,quarantinedTo:t.quarantinedTo,reason:null,openAttempts:te},failedAtMs:null,permanentRefusal:!1}}catch(e){return{store:null,status:{state:"unavailable",harnessRoot:r,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${e.name}: ${e.message}`,openAttempts:te},failedAtMs:Date.now(),permanentRefusal:e.name==="FilesystemPolicyError"||e.name==="SchemaDowngradeRefusedError"}}}function Qo(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=rn}function f(r=Date.now()){let e=yr();return(!D||D.status.harnessRoot!==e||Qo(D,r))&&(Sr(),D=Xo(e)),D.store}function tn(){return D?D.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:te}}function Rr(){return f(),tn()}function Sr(){try{D?.store?.close()}catch{}D=null}function Zo(){Sr(),te=0}I();b();import{existsSync as es,readFileSync as rs}from"node:fs";import{homedir as ts}from"node:os";import ns from"node:path";var os=3e4,x=null;function kr(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return ns.join(ts(),".kynver",`local-run-store-flags-${e}.json`)}function br(r){if(!r||typeof r!="object"||Array.isArray(r))return{};let e=r,t={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=e[o];(s==="off"||s==="shadow"||s==="enforce")&&(t[o]=s)}return t}function ss(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r.response;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.localRunStoreFlags;return t===void 0?null:br(t)}function is(r,e){try{let t=kr(r),n={contractVersion:1,agentOsId:r,flags:br(e),deliveredAt:new Date().toISOString()};ie(t,n),x={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function vr(r=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(x&&r-x.loadedAtMs<os)return x.flags;try{let e=_().agentOsId?.trim();if(!e)return x={flags:{},loadedAtMs:r,file:null},x.flags;let t=kr(e);if(!es(t))return x={flags:{},loadedAtMs:r,file:t},x.flags;let n=JSON.parse(rs(t,"utf8")),o=n?.contractVersion===1?br(n.flags):{};return x={flags:o,loadedAtMs:r,file:t},o}catch{return x={flags:{},loadedAtMs:r,file:null},x.flags}}function as(){x=null}var nn=[{key:"dispatchReceipts",env:"KYNVER_LRS_DISPATCH_RECEIPTS",milestone:"D1"},{key:"admission",env:"KYNVER_LRS_ADMISSION",milestone:"D2"},{key:"planOutbox",env:"KYNVER_LRS_PLAN_OUTBOX",milestone:"D3"},{key:"keeper",env:"KYNVER_LRS_KEEPER",milestone:"D4"},{key:"meshLease",env:"KYNVER_LRS_MESH_LEASE",milestone:"D4"},{key:"quota",env:"KYNVER_LRS_QUOTA",milestone:"D4"}];function on(r){let e=r?.trim().toLowerCase()??"";return e===""?{mode:"off",unknown:!1}:e==="off"||e==="shadow"||e==="enforce"?{mode:e,unknown:!1}:{mode:"off",unknown:!0}}function A(r=process.env){let e={},t={},n=[],o=vr();for(let s of nn){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let c=on(i);e[s.key]=c.mode,t[s.key]="env",c.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let u=o[s.key];if(u){e[s.key]=u,t[s.key]="server";continue}e[s.key]="off",t[s.key]="default"}return{flags:e,sources:t,warnings:n}}function ls(r){return Object.values(r).some(e=>e!=="off")}var R={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};function w(r=process.env){return A(r).flags.dispatchReceipts}function xr(r){return w(r)!=="off"}function _r(r,e){return`dispatch:${r}:${e.taskId}:${e.leaseToken}`}function ne(r,e,t){if(!xr())return;let n=f();if(n)try{n.recordOperationReceipt({idempotencyKey:_r(r,e),operation:`dispatch-${r}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function cs(r){ne("claim",r,{runId:r.runId,workerName:r.workerName,provider:r.provider})}function Er(r){ne("spawned",r)}function we(r,e){ne("released",r,{reasonClass:e})}function us(r){ne("completion-sent",r)}function ds(r,e){ne("completion-acked",r,{outcome:e})}function ps(r){if(!xr())return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(_r("completion-acked",r));if(t){let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}if(n==="acknowledged")return R.completionReplaysObserved+=1,!0}}catch{R.storeFailures+=1}return!1}function ms(r){let e=String(r??"").split(":")[0]?.trim()??"";return e.length>0?e.slice(0,64):"unknown"}function fs(r){if(w()!=="enforce")return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(_r("completion-acked",r));if(!t)return!1;let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}return n==="acknowledged"?(R.completionReplaysShortCircuited+=1,!0):!1}catch{return R.storeFailures+=1,!1}}var gs=600*1e3;function hs(r,e){if(w()!=="enforce")return;let t=f();if(t)try{t.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${r}:${e}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:e})})}catch{R.storeFailures+=1}}function ys(r,e){if(w()!=="enforce")return[];let t=f();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??gs;try{return t.listOperationReceipts({operation:"dispatch-start-failed",recordedAfter:new Date(n-o).toISOString(),limit:200}).filter(s=>{try{return s.resultJson?JSON.parse(s.resultJson).runId===r:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(r.length+1))}).filter(s=>s.length>0)}catch{return R.storeFailures+=1,[]}}function z(r){let e=r.split(":")[0]??"",t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var Rs=900*1e3,sn=10080*60*1e3,Ss=1440*60*1e3,ks=500,bs=300;function Cr(r){let e={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!xr())return e;let t=f();if(!t)return e;let n=r?.nowMs??Date.now(),o=r?.strandedAfterMs??Rs;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-sn).toISOString(),limit:ks}),i=0,l=[];for(let c of s){let p=c.idempotencyKey.slice(15),m=Date.parse(c.recordedAt);if(!Number.isFinite(m)||n-m<o)continue;let d=t.getOperationReceipt(`dispatch:spawned:${p}`),Y=t.getOperationReceipt(`dispatch:released:${p}`);if(d||Y){n-m>=Ss&&l.length+5<=bs&&l.push(c.idempotencyKey,`dispatch:spawned:${p}`,`dispatch:released:${p}`,`dispatch:completion-sent:${p}`,`dispatch:completion-acked:${p}`);continue}let v=p.split(":")[0]??"",V=z(p.slice(v.length+1));if((v?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${v}:`,limit:10}):[]).some(h=>{if(V===null)return!0;let G=h.idempotencyKey.slice(`dispatch:completion-acked:${v}:`.length),K=z(G);return K===null||K>=V}))continue;let y=!1;if(r?.hasLiveWorker&&c.resultJson)try{let h=JSON.parse(c.resultJson);h.runId&&h.workerName&&(y=r.hasLiveWorker({runId:h.runId,workerName:h.workerName}))}catch{y=!1}y||(i+=1)}let u=l.length>0?t.deleteOperationReceiptsByKeys(l):0;if(w()==="enforce"){let c=t.listOperationReceipts({limit:100}).filter(p=>{let m=Date.parse(p.recordedAt);return Number.isFinite(m)&&n-m>=sn}).map(p=>p.idempotencyKey);if(c.length>0){let p=t.deleteOperationReceiptsByKeys(c);u+=p,R.agedReceiptsPruned+=p}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:u}}catch{return R.storeFailures+=1,e}}function Ar(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function vs(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as Is,readFileSync as Ts}from"node:fs";var $=900*1e3,Or="admission-shadow",wr="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Oe=!1;function xs(){Oe=!1}function H(r=process.env){return A(r).flags.admission}function Ie(r,e){return`${wr}${r}:${e}`}function _s(r,e){if(H()==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Ie(r,e),Or,$)}catch{E.storeFailures+=1}}function Ir(r,e){if(H()==="off")return;let t=f();if(t)try{t.releaseAdmission(Ie(r,e),Or)}catch{E.storeFailures+=1}}function Es(r){let e={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(H()==="off")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(d=>Ie(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:wr,limit:500}),s=new Set(o.map(d=>d.key)),i=[...n].filter(d=>!s.has(d)).length,l=o.filter(d=>!n.has(d.key)).length,u=!Oe;Oe=!0,!u&&i>0&&(E.missingForLive+=i);let c=0;for(let d of r.liveWorkers)t.tryReserveAdmission(Ie(d.runId,d.workerName),Or,$),c+=1;let p=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(p+=1,E.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:wr,limit:500}).length,refreshed:c,deadReleased:p,missingForLive:i,orphaned:l,adoptionPass:u}}catch{return E.storeFailures+=1,e}}function Tr(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function Cs(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Oe=!1}var Pe="worker-slot-n:",Te=64;function an(r){return`${Pe}${r}`}function Ne(r,e){return`${r}:${e}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function As(r){if(H()!=="enforce")return{admitted:!0};let e=f();if(!e)return{admitted:!0};let t=Math.max(0,Math.min(Te,Math.floor(r.maxSlots)));if(r.diskActiveWorkers>=t)return C.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=Ne(r.runId,r.workerName);for(let o=0;o<t;o+=1)if(e.tryReserveAdmission(an(o),n,$).acquired)return{admitted:!0,slot:o};return C.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return C.enforceStoreFailures+=1,{admitted:!0}}}function Nr(r,e){if(H()==="off")return;let t=f();if(t)try{let n=Ne(r,e),o=t.listAdmissionReservations({keyPrefix:Pe,limit:Te});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function ws(r){let e={refreshed:0,deadReleased:0,adopted:0};if(H()!=="enforce")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(c=>Ne(c.runId,c.workerName))),o=t.listAdmissionReservations({keyPrefix:Pe,limit:Te}),s=0,i=0,l=new Set;for(let c of o)n.has(c.owner)?(t.tryReserveAdmission(c.key,c.owner,$),l.add(c.owner),s+=1):t.releaseAdmission(c.key,c.owner)&&(i+=1);let u=0;for(let c of r.liveWorkers){let p=Ne(c.runId,c.workerName);if(!l.has(p)){for(let m=0;m<Te;m+=1)if(t.tryReserveAdmission(an(m),p,$).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,e}}function Pr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function Os(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var Ns="dispatch:claim:",Ps=900*1e3,Ds=10080*60*1e3,Ls=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function ln(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=Is("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(Ts(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(r))return Number(t)}catch{}return null}async function Dr(r){let e=w(),t={mode:e,scanned:0,outcomes:[]};if(e!=="enforce")return t;let n=f();if(!n)return t;let o=r.nowMs??Date.now(),s=r.strandedAfterMs??Ps,i=r.findOrphanPid??ln,l=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-Ds).toISOString(),limit:Ls})}catch{return O.recoveryStoreFailures+=1,t}for(let c of u){let p=c.idempotencyKey.slice(Ns.length),m=p.split(":")[0]??"",d=p.slice(m.length+1);if(!(!m||!d))try{let Y=Date.parse(c.recordedAt);if(!Number.isFinite(Y)||o-Y<s||n.getOperationReceipt(`dispatch:spawned:${p}`)||n.getOperationReceipt(`dispatch:released:${p}`))continue;let v=z(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${m}:`,limit:10}).some(K=>{if(v===null)return!0;let Q=z(K.idempotencyKey.slice(`dispatch:completion-acked:${m}:`.length));return Q===null||Q>=v}))continue;let X={};try{X=c.resultJson?JSON.parse(c.resultJson):{}}catch{X={}}let y=X.runId??null,h=X.workerName??null;if(y&&h&&r.hasLiveWorker({runId:y,workerName:h})){Er({taskId:m,leaseToken:d}),l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let K=r.worktreePathFor({runId:y,workerName:h}),Q=K?i(K):null;if(Q!==null){O.recoveryDeferredOrphans+=1,l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${Q} references ${K}`});continue}}if(!y){l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let G=await r.releaseClaim({taskId:m,leaseToken:d,runId:y});G.released?(we({taskId:m,leaseToken:d},"restart_recovery"),h&&(Ir(y,h),Nr(y,h)),O.recoveredStrandedClaims+=1,l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"released"})):G.transportError?l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:G.detail}):(we({taskId:m,leaseToken:d},"restart_recovery_refused"),l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:G.detail}))}catch{O.recoveryStoreFailures+=1}}return{mode:e,scanned:u.length,outcomes:l}}function Lr(){return{"dispatchReceipts.recoveredStrandedClaims":O.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":O.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":O.recoveryStoreFailures}}function Ks(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}fe();import Vs from"node:path";var Ms="kynver-harness:",Fs="@runner:";function cn(r,e){let t=r.trim(),n=e.trim();return`${Ms}${t}${Fs}${n}`}I();import pn from"node:os";var Bs="embedded-1",Us=[{slug:"ghost",displayName:"Ghost",description:"Orchestration persona.",dispatchLane:null,defaultRoleLane:"system"},{slug:"astra",displayName:"Astra",description:"Planning persona.",dispatchLane:"implementation",defaultRoleLane:"plan_author"},{slug:"rhea",displayName:"Rhea",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"mnemo",displayName:"Mnemo",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"sentinel",displayName:"Sentinel",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"deep_reviewer"},{slug:"pixel",displayName:"Pixel",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"schema",displayName:"Schema",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"atlas",displayName:"Atlas",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"runtime_verifier"},{slug:"bridge",displayName:"Bridge",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"catalyst",displayName:"Catalyst",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"lorentz",displayName:"Lorentz",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"report_reviewer"},{slug:"dalton",displayName:"Dalton",description:"Landing persona.",dispatchLane:"landing",defaultRoleLane:"implementer"}],Ws={"worker.prompt.core_rules":["Structured final result (recommended): record completion as JSON with summary, files, PR URLs, verification, risks, and blockers.","Completion handoff (required): before you stop, summarize the outcome in your last message and append a heartbeat line with phase `complete` and a structured finalResult object. Commit your work cleanly and open a GitHub PR (draft OK) for substantial changes \u2014 never leave uncommitted changes behind without reporting them.","Review-only workers must not open new implementation PRs \u2014 review the existing PR and record a verdict in the final result. Prefer `gh pr view` / `gh pr diff`; if a local checkout is needed, use a disposable ref or detached worktree, not a checked-out `pr-*` branch.","Keep verification targeted to touched paths; avoid full-monorepo verification unless explicitly requested.","Do not run `npm publish`.","If verification fails, append a heartbeat line immediately with the failing command, reason, and next action."].join(`
|
|
55
57
|
`),"worker.prompt.progress.compact":"Plan progress: when planId is set, report progress with `kynver plan progress --plan <planId> --row <rowKey> --role implementer --status in_progress|running|partial|blocked`. Do not mark rows done from the worker CLI.","worker.prompt.progress.full":["Structured plan progress (required when planId is set):","- Report checkpoints with `kynver plan progress --plan <planId> --row <rowKey> --role implementer --status in_progress|running|partial|blocked`.","- When a slice is finished, emit `partial` with evidence (`--evidence pr:<url>`, `--evidence path:<file>`, or `--evidence command:<cmd>`).","- Do not propose or confirm row `done` from the worker CLI."].join(`
|
|
56
58
|
`),"worker.prompt.merge_gate.compact":"Verification cost control: prefer local verification before requesting CI runs; do not push empty commits to re-trigger CI; record verification evidence on the PR.","worker.prompt.merge_gate.full":["Verification cost control:","- Prefer local verification of touched paths before requesting any CI run.","- Do not push empty commits to re-trigger CI.","- Record verification evidence on the PR before requesting review."].join(`
|
|
57
59
|
`),"worker.prompt.plan_artifacts.compact":"Plan artifacts: when authoring or revising plan documents, open a GitHub PR early and iterate from that PR branch; do not leave the canonical plan only in a local worktree.","worker.prompt.plan_artifacts.full":["Plan artifacts (when authoring or revising plan documents):","- Create a feature branch and open a GitHub PR (draft OK) before substantial drafting; commit and push the plan file.","- Iterate on that PR branch and link the PR URL on the related task and progress evidence."].join(`
|
|
58
|
-
`)}
|
|
60
|
+
`)},$s={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},un={version:Bs,generatedAt:"1970-01-01T00:00:00.000Z",personas:Us,instructions:Ws,policyThresholds:$s};var Hs=un;function dn(){return Hs.version}F();function L(r){return r?.trim()?r.trim():null}function mn(r={}){let e=r.env??process.env,t=_();return{runnerId:L(t.runnerId)??L(e.KYNVER_RUNTIME_ID)??L(e.OPENCLAW_RUNTIME_ID)??L(e.HOSTNAME)??pn.hostname(),hostname:L(e.HOSTNAME)??pn.hostname(),profile:L(e.KYNVER_RUNNER_PROFILE)??L(e.OPENCLAW_RUNNER_PROFILE),harnessRepo:L(e.KYNVER_HARNESS_REPO)??L(e.KYNVER_DEFAULT_REPO),runId:r.runId??null,instructionBundleVersion:dn()}}function fn(r){let e=String(r).trim();return e.startsWith("krc1.")?{"Content-Type":"application/json","X-Kynver-Runner-Token":e}:{"Content-Type":"application/json","X-Kynver-Cron-Secret":e,"X-OpenClaw-Cron-Secret":e,"X-Kynver-Runtime-Secret":e}}ue();I();function yn(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 gn(r){return new Error(`callback timeout after ${r}ms`)}async function js(r,e){let t=yn(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(gn(t))},t)})])}catch(i){throw s?gn(t):i}finally{o&&clearTimeout(o)}}function Ys(r,e){let t=yn(e);return{ok:!1,status:0,response:{error:r instanceof Error?r.message:String(r),timeoutMs:t}}}async function hn(r,e,t,n){try{return await js(async o=>{let s=await ce(r,{method:"POST",headers:fn(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 Ys(o,n?.timeoutMs)}}async function Rn(r,e,t,n){let o=await hn(r,e,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await Qt(e,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await hn(r,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function Sn(r){let e=`${r.baseUrl}/api/agent-os/by-id/${encodeURIComponent(r.agentOsId)}/tasks/${encodeURIComponent(r.taskId)}/release`,t;try{t=await Rn(e,r.secret,{agentOsId:r.agentOsId,leaseOwner:r.leaseOwner,...r.leaseToken?.trim()?{leaseToken:r.leaseToken.trim()}:{},...r.failureDetail?{failureDetail:r.failureDetail}:{}},{agentOsId:r.agentOsId,baseUrl:r.baseUrl})}catch(s){return{released:!1,httpOk:!1,transportError:!0,releaseResponse:{ok:!1,error:s.message}}}let n=t.response;return{released:t.ok===!0||n?.ok===!0,httpOk:t.ok===!0,transportError:!1,releaseResponse:t.response??t}}var Kr=!1;function Gs(){Kr=!1}async function Js(r){if(Kr||w()!=="enforce")return null;Kr=!0;try{let e=mn().runnerId,t=await Dr({hasLiveWorker:r.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>Vs.join(Zr().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await Sn({baseUrl:r.baseUrl,secret:r.secret,agentOsId:r.agentOsId,taskId:n,leaseOwner:cn(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 gp=600*1e3,oe={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function kn(){return{"planOutbox.storeFailures":oe.storeFailures,"planOutbox.corruptItemsSeen":oe.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":oe.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":oe.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":oe.halfArchivesCompleted}}var g={keeperStoreFailures:0,meshStoreFailures:0,quotaStoreFailures:0,meshLeaseDivergences:0,meshEnforceStaleInversions:0,quotaVerdictDivergences:0};function j(r){return A(process.env).flags[r]}var bn="daemon-keeper",qs=1800*1e3;function zs(r){if(j("keeper")==="off")return;let e=f();if(e)try{e.saveRecoveryCheckpoint({scope:bn,payloadJson:JSON.stringify(r)})}catch{g.keeperStoreFailures+=1}}function Xs(){if(j("keeper")!=="enforce")return null;let r=f();if(!r)return null;try{let e=r.latestRecoveryCheckpoint(bn);if(!e)return null;let t=JSON.parse(e.payloadJson),n=Date.now()-Date.parse(e.createdAt);if(!Number.isFinite(n)||n>qs)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function Mr(r){return`mesh-cron-lease:${r}`}function Qs(r,e){if(j("meshLease")==="off")return;let t=f();if(t)try{let n=t.latestRecoveryCheckpoint(Mr(r));if(n){let o=JSON.parse(n.payloadJson);if((o.leaseToken??null)===(e.leaseToken??null)&&(o.holderBoxId??null)===(e.holderBoxId??null)&&o.authorized===e.authorized)return}t.saveRecoveryCheckpoint({scope:Mr(r),payloadJson:JSON.stringify(e)})}catch{g.meshStoreFailures+=1}}function Zs(r,e){let t=j("meshLease");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(Mr(r)),s=o?JSON.parse(o.payloadJson):null,i=s!==null&&((s.leaseToken??null)!==(e?.leaseToken??null)||(s.holderBoxId??null)!==(e?.holderBoxId??null)||(s.authorized??null)!==(e?.authorized??null));return i&&(g.meshLeaseDivergences+=1),t!=="enforce"?null:i&&e?.updatedAt&&s?.updatedAt&&Date.parse(e.updatedAt)>Date.parse(s.updatedAt)?(g.meshEnforceStaleInversions+=1,null):s}catch{return g.meshStoreFailures+=1,null}}function De(r){return`quota-cooldown:${r}`}var vn="quota-preflight";function ei(r,e){if(j("quota")==="off")return;let t=f();if(t)try{t.tryReserveAdmission(De(r),vn,e)}catch{g.quotaStoreFailures+=1}}function ri(r){if(j("quota")==="off")return;let e=f();if(e)try{e.releaseAdmission(De(r),vn)}catch{g.quotaStoreFailures+=1}}function ti(r,e){let t=j("quota");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:De(r),limit:50}).find(i=>i.key===De(r)),s=!!o;return s!==e&&(g.quotaVerdictDivergences+=1),t==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return g.quotaStoreFailures+=1,null}}function Fr(){return{"keeper.storeFailures":g.keeperStoreFailures,"meshLease.storeFailures":g.meshStoreFailures,"meshLease.divergences":g.meshLeaseDivergences,"meshLease.enforceStaleInversions":g.meshEnforceStaleInversions,"quota.storeFailures":g.quotaStoreFailures,"quota.verdictDivergences":g.quotaVerdictDivergences}}function ni(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function oi(r){let e=Rr(),t=A(r?.env??process.env),n=(r?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,Ar());let s=Cr({nowMs:n,hasLiveWorker:r?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,Lr())}return t.flags.planOutbox!=="off"&&Object.assign(o,kn()),t.flags.admission!=="off"&&(Object.assign(o,Tr()),t.flags.admission==="enforce"&&Object.assign(o,Pr())),(t.flags.keeper!=="off"||t.flags.meshLease!=="off"||t.flags.quota!=="off")&&Object.assign(o,Fr()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:e.state,schemaVersion:e.schemaVersion,recovered:e.recovered,unavailableClass:e.reason?e.reason.split(":")[0]??null:null,flags:t.flags,flagSources:t.sources,flagWarningCount:t.warnings.length,divergenceCounters:o}}export{$ as ADMISSION_RESERVATION_TTL_MS,Pe as ADMISSION_SLOT_KEY_PREFIX,Z as FilesystemPolicyError,rn as LOCAL_RUN_STORE_OPEN_RETRY_MS,nn as LOCAL_RUN_STORE_SURFACES,Ke as LOCAL_SCHEMA_VERSION,se as SchemaDowngradeRefusedError,J as SqliteLocalRunStore,Os as __resetAdmissionEnforceCountersForTests,Cs as __resetAdmissionShadowCountersForTests,Ks as __resetDispatchClaimRecoveryForTests,vs as __resetDispatchReceiptCountersForTests,Zo as __resetLocalRunStoreLifecycleForTests,as as __resetRemoteSurfaceFlagsCacheForTests,ni as __resetSmallSurfaceCountersForTests,Gs as __resetStartupClaimRecoveryForTests,zo as __setLocalRunStoreLifecycleTestOverrides,As as acquireWorkerAdmissionSlot,Pr as admissionEnforceCounters,Tr as admissionShadowCounters,ls as anyLocalRunStoreSurfaceActive,ti as assessQuotaCooldownReservation,oi as buildLocalRunStoreTickPosture,Le as classifyDatabaseDirectory,ri as clearQuotaCooldownReservation,Sr as closeLocalRunStore,Lr as dispatchClaimRecoveryCounters,Ar as dispatchReceiptCounters,w as dispatchReceiptsMode,ss as extractLocalRunStoreFlagsFromOperatorTickResponse,ln as findLiveProcessByCmdlinePath,f as getLocalRunStore,tn as getLocalRunStoreLifecycleStatus,vr as getRemoteSurfaceFlags,z as leaseTokenAttempt,ys as listRecentDispatchStartFailures,Js as maybeRunStartupClaimRecovery,ps as noteCompletionReplayIfAcked,Me as openSqliteLocalRunStoreWithRecovery,on as parseLocalRunStoreSurfaceMode,is as persistRemoteSurfaceFlags,Rr as probeLocalRunStore,Zs as readMeshLeaseCheckpoint,xs as rearmAdmissionAdoptionPass,Es as reconcileAdmissionShadow,ws as reconcileNumberedAdmissionSlots,ds as recordCompletionAckedReceipt,us as recordCompletionSentReceipt,cs as recordDispatchClaimReceipt,we as recordDispatchReleasedReceipt,Er as recordDispatchSpawnedReceipt,hs as recordDispatchStartFailedReceipt,ei as recordQuotaCooldownReservation,Dr as recoverStrandedDispatchClaims,ms as releaseReasonClass,Nr as releaseWorkerAdmissionSlot,Ir as releaseWorkerSlotReservation,kr as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,Xs as restoreKeeperBackoffCheckpoint,zs as saveKeeperBackoffCheckpoint,Qs as saveMeshLeaseCheckpoint,Cr as scanDispatchReceiptInvariants,fs as shouldShortCircuitCompletionReplay,Fr as smallSurfaceCounters,_s as takeWorkerSlotReservation};
|