@kynver-app/runtime 0.2.78 → 0.2.88
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +103 -99
- package/dist/desktop-entry.js +140 -0
- package/dist/dispatch-claim-authorization.js +1 -0
- package/dist/index.js +124 -120
- package/dist/local-run-store/index.js +15 -15
- package/dist/server/cleanup.js +14 -14
- package/dist/server/db-credentials.js +1 -1
- package/dist/server/default-repo.js +1 -1
- package/dist/server/dispatch-routing.js +4 -4
- package/dist/server/heavy-verification.js +1 -1
- package/dist/server/memory-cost-enforce.js +2 -2
- package/dist/server/memory-cost.js +2 -2
- package/dist/server/model-routing.js +4 -4
- package/dist/server/monitor.js +7 -7
- package/dist/server/orchestration.js +1 -1
- package/dist/server/worker-policy.js +2 -2
- package/dist/worker-broker/index.js +4 -4
- package/package.json +15 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),yn(t,r)}catch(n){try{Rn(t,{force:!0})}catch{}throw n}}function oe(r){return String(r).replace(/\/+$/,"")}var v=c(()=>{"use strict"});var vn,Ys,xn,Vs,Cr=c(()=>{"use strict";vn=["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"],Ys=new Set(vn),xn=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],Vs=new Set(xn)});var se=c(()=>{"use strict";V();v();Cr()});var wr=c(()=>{"use strict";se()});var De=c(()=>{"use strict";se();V();wr()});function Tr(r){let e=oe(r);try{let t=new URL(e);return t.hostname.toLowerCase()===Or?(t.hostname=`www.${Or}`,oe(t.toString())):e}catch{return e}}function Me(r){if(r?.trim())return Tr(oe(r.trim()))}async function ie(r,e,t=fetch){let n=Tr(r),o=new Headers(e?.headers),s=0;for(;s<=Ir;){let i=await t(n,{...e,headers:o,redirect:"manual"});if(![301,302,303,307,308].includes(i.status))return i;let a=i.headers.get("location");if(!a)return i;let u=new URL(a,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 l=(e?.method??"GET").toUpperCase();if(!["GET","HEAD"].includes(l)&&i.status!==307&&i.status!==308)return i;await i.body?.cancel(),n=u.toString(),s+=1}throw new Error(`kynver API fetch exceeded ${Ir} redirects for ${r}`)}var Or,Ir,ae=c(()=>{"use strict";v();Or="kynver.com";Ir=10});function F(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 ce(r,e){return r[e]?.trim()||null}function Nr(r){let e=r?.split(":")[0]?.trim();return e?F(e):null}function G(r=process.env,e={}){let t=[],n=Nr(e.boxId),o=Nr(ce(r,"KYNVER_BOX_ID")),s=e.boxKind?.trim();if(s)return n&&n!==F(s)&&t.push(`config.boxId=${e.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:F(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=ce(r,"KYNVER_BOX_KIND");if(i)return o&&o!==F(i)&&t.push(`KYNVER_BOX_ID=${ce(r,"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 a=ce(r,"KYNVER_AGENT_OS_SLUG");return a&&t.push(`KYNVER_AGENT_OS_SLUG=${a} is a workspace slug, not box identity \u2014 operators set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND; customers default to box`),{boxKind:"box",source:"default",slugInferenceBlocked:!!a,warnings:t}}var M=c(()=>{"use strict"});function Ke(r,e){return r==="forge"?4:Math.max(1,e)}function le(r,e){return r==="forge"?Math.min(Math.max(1,e),4):Math.max(1,e)}var ue=c(()=>{"use strict"});var Pr=c(()=>{"use strict"});var pi,fi,Fe=c(()=>{"use strict";pi=25*1024*1024*1024,fi=12*1024*1024*1024});var Si,bi,Lr=c(()=>{"use strict";Fe();Si=5*1024*1024*1024,bi=10*1024*1024*1024});var Ai,Ci,Be=c(()=>{"use strict";Lr();Fe();Ai=30*1024*1024*1024,Ci=15*1024*1024*1024});function Dr(){return Kr()}var de=c(()=>{"use strict";We();v()});var Fr=c(()=>{"use strict";de();v()});var Br=c(()=>{"use strict"});var Ur=c(()=>{"use strict";Br();v()});var Wr=c(()=>{"use strict"});var $r=c(()=>{"use strict";Wr()});var me=c(()=>{"use strict"});var Hr=c(()=>{"use strict";$r();v();me()});var jr=c(()=>{"use strict";me()});var Yr=c(()=>{"use strict"});var Vr=c(()=>{"use strict"});var $e=c(()=>{"use strict"});var Gr=c(()=>{"use strict"});var qr=c(()=>{"use strict";$e();Gr()});var Jr=c(()=>{"use strict";Ur();Hr();me();jr();Yr();se();Vr();qr();$e();v()});var zr=c(()=>{"use strict";Jr()});function Xr(r,e={}){let t=e.perWorkerMemBytes??He,n=e.memReserveBytes??je,o=e.memUtilization??Ye,s=Math.max(0,Math.floor(r*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,pe)}var He,je,Ye,pe,Qr=c(()=>{"use strict";Pr();I();M();ue();fe();Be();de();Fr();zr();v();He=500*1024*1024,je=4*1024*1024*1024,Ye=.85,pe=64});function Z(r,e){let t=Number(r);return!Number.isFinite(t)||t<=0?e:Math.floor(t)}function Ve(r){let e=r.config??{},t=r.env??process.env,n=Z(e.perWorkerMemBytes,He),o=Z(e.memReserveBytes,je),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):Ye)),i=Xr(r.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(r.configuredMaxWorkersOverride!==void 0&&r.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Z(r.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(e.maxConcurrentWorkers!==void 0&&e.maxConcurrentWorkers!==null){let l=Z(e.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,pe),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&Z(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,pe),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var fe=c(()=>{"use strict";Qr()});import{homedir as Nn}from"node:os";import Pn from"node:path";var Zr,Ge=c(()=>{"use strict";Zr=Pn.join(Nn(),".kynver",".env")});var et=c(()=>{"use strict"});var rt=c(()=>{"use strict";et()});var tt=c(()=>{"use strict"});var qe=c(()=>{"use strict";rt();tt()});var nt=c(()=>{"use strict"});var ot=c(()=>{"use strict";nt()});var ge=c(()=>{"use strict";Ge();V();I();qe();ot()});var st=c(()=>{"use strict";M();M()});var it=c(()=>{"use strict";Ge();qe();ge()});import{existsSync as T,mkdirSync as Kn,readdirSync as he,renameSync as at,statSync as Fn}from"node:fs";import N from"node:path";function lt(r){try{return Fn(r).isDirectory()}catch{return!1}}function Bn(r){if(!T(r))return!0;for(let e of ct){let t=N.join(r,e);if(T(t)&&(!lt(t)||he(t).length>0))return!1}return!0}function Un(r){let e=N.join(r,"runs");if(!T(e)||!lt(e))return!1;for(let t of he(e,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=N.join(e,t.name,"run.json");if(Q(n,void 0)?.id)return!0}return!1}function Wn(r){let e=N.join(r,"runs");if(!T(e))return!1;for(let t of he(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(Q(N.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function $n(r){let e=N.join(r,"ghost");return T(e)?!T(N.join(e,"runs")):Wn(r)}function ut(r){return Un(r.sharedRoot)?Bn(r.forgeRoot)?$n(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 dt(r,e){Kn(e,{recursive:!0});for(let t of ct){let n=N.join(r,t),o=N.join(e,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)){at(n,o);continue}at(n,o)}}}var ct,mt=c(()=>{"use strict";v();ct=["runs","worktrees"]});import{existsSync as b}from"node:fs";import{homedir as Hn}from"node:os";import S from"node:path";function Je(r=process.env){return r.HOME?.trim()||Hn()}function ze(r=process.env){return S.join(Je(r),".kynver","harness")}function ye(r){let e=S.resolve(K(r.trim()));for(;jn.has(S.basename(e));)e=S.dirname(e);return e}function Yn(r,e=process.env){return S.join(ze(e),r)}function Vn(r=process.env){let e=ze(r);if(b(S.join(e,"runs")))return!0;if(b(e)&&!b(S.join(e,"ghost"))&&!b(S.join(e,"forge")))return b(e);let t=S.join(Je(r),pt);return b(t)}function Re(r){let e=r.env??process.env,t=e.KYNVER_HARNESS_ROOT?.trim()||e.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:ye(t),source:"env"};let n=r.configuredHarnessRoot?.trim();if(n)return{harnessRoot:ye(n),source:"config"};let o=Yn(r.boxKind,e);if(b(S.join(o,"runs"))||b(o)&&!Gn(o))return{harnessRoot:o,source:"box_scoped"};let i=ze(e);if(r.boxKind==="forge"){let a=ut({sharedRoot:i,forgeRoot:o});if(a.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:a.blocker};if(a.action==="migrate")return r.allowForgeLegacyMigration!==!1&&dt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&Vn(e)){if(b(S.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(b(i)&&!b(S.join(i,"ghost"))&&!b(S.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=S.join(Je(e),pt);if(b(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function Gn(r){if(!b(r))return!0;for(let e of["runs","worktrees"]){let t=S.join(r,e);if(b(t))return!1}return!0}var pt,jn,Xe=c(()=>{"use strict";V();mt();pt=S.join(".openclaw","harness");jn=new Set(["runs","worktrees"])});import ft from"node:os";function Se(r){return r?.trim()?r.trim():null}function qn(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function Jn(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 be(r=_(),e=process.env,t={}){let n=G(e,r),o=[...n.warnings],s=[],i=!!(r.boxKind?.trim()||Se(e.KYNVER_BOX_KIND)),a=t.strict===!0||Jn(e);if((t.requireExplicitBoxKind||a)&&!i&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup` (customers: boxKind=box) or `kynver setup --box-kind forge|ghost` for operator pools before dispatch"),n.slugInferenceBlocked&&!i){let H="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";a||t.requireExplicitBoxKind?s.push(H):o.push(`${H} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=Se(r.runnerId),l=Se(e.KYNVER_RUNTIME_ID)??Se(e.OPENCLAW_RUNTIME_ID),m=u??l??qn(n.boxKind,ft.hostname()),p=u?"config":l?"env":"derived";p==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${m}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let d=Ve({config:r,env:e,totalMemBytes:ft.totalmem()}),$=le(n.boxKind,d.configuredMaxWorkers??Ke(n.boxKind,d.autoCap)),k=Re({boxKind:n.boxKind,configuredHarnessRoot:r.harnessRoot,env:e});return k.migrationBlocker&&s.push(k.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:m,runnerIdSource:p,maxConcurrentWorkers:$,workerCapSource:d.workerCapSource,harnessRoot:k.harnessRoot,harnessRootSource:k.source},errors:s,warnings:o}}var ke=c(()=>{"use strict";I();M();ue();fe();Xe()});var gt=c(()=>{"use strict";De();M();st();I();ge();it();ae();ke()});var Qn,Sl,ht=c(()=>{"use strict";Qn=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],Sl=Qn.join("|")});import{existsSync as Rt,mkdirSync as Zn,readFileSync as St,writeFileSync as eo}from"node:fs";import{homedir as ro,totalmem as wl}from"node:os";import Ze from"node:path";function to(r){return{...r,...r.harnessRoot?.trim()?{harnessRoot:K(r.harnessRoot.trim())}:{},...r.defaultRepo?.trim()?{defaultRepo:K(r.defaultRepo.trim())}:{}}}function _(){if(!Rt(yt))return{};try{return to(JSON.parse(St(yt,"utf8")))}catch{return{}}}function bt(){if(!Rt(Qe))return{};try{return JSON.parse(St(Qe,"utf8"))}catch{return{}}}function no(r){Zn(er,{recursive:!0}),eo(Qe,`${JSON.stringify(r,null,2)}
|
|
3
|
-
`,{mode:384})}function
|
|
4
|
-
`)){let n=t.trim().split(/\s+/);n.length<3||
|
|
1
|
+
var a=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=[n],n}};import{homedir as Tr}from"node:os";import Nr from"node:path";function Cn(e){return e==="~"?Tr():e.startsWith("~/")||e.startsWith("~\\")?Nr.join(Tr(),e.slice(2)):e}function K(e){return Nr.resolve(Cn(e))}var V=a(()=>{"use strict"});var Pr=a(()=>{"use strict"});import{existsSync as ri,mkdirSync as An,readFileSync as wn,readdirSync as ti,renameSync as On,rmSync as In,statSync as ni,writeFileSync as Tn}from"node:fs";import{randomBytes as Nn}from"node:crypto";import Pn from"node:path";function Le(e){console.error(e),process.exit(1)}function Q(e,r){try{return JSON.parse(wn(e,"utf8"))}catch(t){if(arguments.length>1)return r;Le(`failed to read ${e}: ${t.message}`)}}function oe(e,r){An(Pn.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${Nn(4).toString("hex")}.tmp`;try{Tn(t,`${JSON.stringify(r,null,2)}
|
|
2
|
+
`),On(t,e)}catch(n){try{In(t,{force:!0})}catch{}throw n}}function se(e){return String(e).replace(/\/+$/,"")}var k=a(()=>{"use strict";Pr()});var Dn,li,Ln,ci,Dr=a(()=>{"use strict";Dn=["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"],li=new Set(Dn),Ln=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],ci=new Set(Ln)});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 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=(r?.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 ${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 ce(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(ce(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=ce(e,"KYNVER_BOX_KIND");if(i)return o&&o!==F(i)&&t.push(`KYNVER_BOX_ID=${ce(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=ce(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 ue(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 Ii,Ti,Ue=a(()=>{"use strict";Ii=25*1024*1024*1024,Ti=12*1024*1024*1024});var Mi,Ki,Wr=a(()=>{"use strict";Ue();Mi=5*1024*1024*1024,Ki=10*1024*1024*1024});var Hi,ji,Be=a(()=>{"use strict";Wr();Ue();Hi=30*1024*1024*1024,ji=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";Jr();k();me()});var Xr=a(()=>{"use strict";me()});var Qr=a(()=>{"use strict"});var Zr=a(()=>{"use strict"});var He=a(()=>{"use strict"});var et=a(()=>{"use strict"});var rt=a(()=>{"use strict";He();et()});var tt=a(()=>{"use strict";Gr();zr();me();Xr();Qr();ie();Zr();rt();He();k()});var nt=a(()=>{"use strict";tt()});function ot(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,st=a(()=>{"use strict";Br();I();M();de();ge();Be();pe();Yr();nt();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=ot(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 c=Z(r.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,fe),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&Z(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,fe),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var ge=a(()=>{"use strict";st()});import{homedir as jn}from"node:os";import Yn from"node:path";var it,qe=a(()=>{"use strict";it=Yn.join(jn(),".kynver",".env")});var at=a(()=>{"use strict"});var lt=a(()=>{"use strict";at()});var ct=a(()=>{"use strict"});var ut=a(()=>{"use strict";k()});var Je=a(()=>{"use strict";lt();ct();ut()});var dt=a(()=>{"use strict"});var pt=a(()=>{"use strict";dt()});var he=a(()=>{"use strict";qe();V();I();Je();pt()});var mt=a(()=>{"use strict";M();M()});var ft=a(()=>{"use strict";qe();Je();he()});function yt(e){if(!ht)return e;if(!gt)throw new ze;return gt}function Qe(){if(ht)throw new Xe}var ze,Xe,ht,gt,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"}},ht=!1,gt=null});import{existsSync as T,mkdirSync as Jn,readdirSync as ye,renameSync as Rt,statSync as zn}from"node:fs";import N from"node:path";function bt(e){try{return zn(e).isDirectory()}catch{return!1}}function Xn(e){if(!T(e))return!0;for(let r of St){let t=N.join(e,r);if(T(t)&&(!bt(t)||ye(t).length>0))return!1}return!0}function Qn(e){let r=N.join(e,"runs");if(!T(r)||!bt(r))return!1;for(let t of ye(r,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=N.join(r,t.name,"run.json");if(Q(n,void 0)?.id)return!0}return!1}function Zn(e){let r=N.join(e,"runs");if(!T(r))return!1;for(let t of ye(r,{withFileTypes:!0})){if(!t.isDirectory())continue;if(Q(N.join(r,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function eo(e){let r=N.join(e,"ghost");return T(r)?!T(N.join(r,"runs")):Zn(e)}function kt(e){return Qn(e.sharedRoot)?Xn(e.forgeRoot)?eo(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 vt(e,r){Jn(r,{recursive:!0});for(let t of St){let n=N.join(e,t),o=N.join(r,t);if(T(n)){if(T(o)&&ye(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(T(o)){Rt(n,o);continue}Rt(n,o)}}}var St,xt=a(()=>{"use strict";k();St=["runs","worktrees"]});import{existsSync as b}from"node:fs";import{homedir as ro}from"node:os";import S from"node:path";function er(e=process.env){return e.HOME?.trim()||ro()}function rr(e=process.env){return S.join(er(e),".kynver","harness")}function Re(e){let r=S.resolve(K(e.trim()));for(;to.has(S.basename(r));)r=S.dirname(r);return r}function no(e,r=process.env){return S.join(rr(r),e)}function oo(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),_t);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=no(e.boxKind,r);if(b(S.join(o,"runs"))||b(o)&&!so(o))return{harnessRoot:o,source:"box_scoped"};let i=rr(r);if(e.boxKind==="forge"){let l=kt({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&&vt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&oo(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 u=S.join(er(r),_t);if(b(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function so(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 _t,to,tr=a(()=>{"use strict";V();xt();_t=S.join(".openclaw","harness");to=new Set(["runs","worktrees"])});import Et from"node:os";function be(e){return e?.trim()?e.trim():null}function io(e,r){let t=r.trim().toLowerCase()||"host";return`${e}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function ao(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||ao(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 u=be(e.runnerId),c=be(r.KYNVER_RUNTIME_ID)??be(r.OPENCLAW_RUNTIME_ID),p=u??c??io(n.boxKind,Et.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=Ge({config:e,env:r,totalMemBytes:Et.totalmem()}),$=ue(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 Ct=a(()=>{"use strict";Me();M();mt();I();he();ft();le();Ze();ve()});var uo,Hc,At=a(()=>{"use strict";uo=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],Hc=uo.join("|")});import{existsSync as It,mkdirSync as po,readFileSync as Tt,writeFileSync as mo}from"node:fs";import{homedir as fo,totalmem as Zc}from"node:os";import or from"node:path";function go(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:K(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:K(e.defaultRepo.trim())}:{}}}function _(){if(!It(wt))return{};try{return go(JSON.parse(Tt(wt,"utf8")))}catch{return{}}}function xe(){if(Qe(),!It(nr))return{};try{return JSON.parse(Tt(nr,"utf8"))}catch{return{}}}function Ot(e){Qe(),po(sr,{recursive:!0}),mo(nr,`${JSON.stringify(e,null,2)}
|
|
3
|
+
`,{mode:384})}function Nt(){return yt(ho)}function Pt(){return Nt().getApiKey()}function yo(e,r){Nt().persistRunnerToken(e,r)}function Ro(e){let r=Dt(e);return r||bo("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),r}function Dt(e){let r=e||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||_().apiBaseUrl;return Ke(r)}async function Lt(e,r,t){let n=Pt(),o=Dt(t?.baseUrl);if(!n)return{ok:!1,reason:"KYNVER_API_KEY is required to refresh a rejected runner token"};if(!r)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 So(r,{baseUrl:o,apiKey:n});return s&&s!==e?(yo(r,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 So(e,r){let t=r?.apiKey||Pt();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${Ro(r?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(e)}/runner-credentials`,s=await ae(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r?.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 bo(e){console.error(e),process.exit(1)}var sr,wt,nr,mu,fu,ho,I=a(()=>{"use strict";Me();V();le();M();de();ge();Be();he();Ct();At();ve();Ze();sr=or.join(fo(),".kynver"),wt=or.join(sr,"config.json"),nr=or.join(sr,"credentials");mu=500*1024*1024,fu=4*1024*1024*1024;ho={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:xe().apiKey},getRunnerToken(e){let r=xe();if(!!r.runnerToken&&!!e&&r.runnerTokenAgentOsId===e)return r.runnerToken;let n=process.env.KYNVER_RUNNER_TOKEN?.trim();if(n)return n;if(r.runnerToken&&!(e&&r.runnerTokenAgentOsId&&r.runnerTokenAgentOsId!==e))return r.runnerToken},persistApiKey(e){Ot({...xe(),apiKey:e})},persistRunnerToken(e,r){Ot({...xe(),runnerToken:r,runnerTokenAgentOsId:e})}}});import Mt from"node:path";function _e(e){return Re(e)}function ir(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return _e(e);let r=_(),t=r.harnessRoot?.trim();if(t)return _e(t);let n=ke(r,process.env);return n.identity?n.identity.harnessRoot:Se({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function Hr(e){return Mt.join(_e(e),"runs")}function ko(e){return Mt.join(_e(e),"worktrees")}function jr(){let e=ir();return{harnessRoot:e,runsDir:Hr(e),worktreesDir:ko(e)}}var $e=a(()=>{"use strict";I();tr();ve();k()});import{existsSync as sn,realpathSync as an,readFileSync as ln}from"node:fs";import wr from"node:path";var cn=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),un=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function dn(){try{return ln("/proc/self/mounts","utf8")}catch{return null}}function pn(e){let r=wr.resolve(e);for(let t=0;t<64;t+=1){if(sn(r))try{return an.native(r)}catch{return r}let n=wr.dirname(r);if(n===r)return r;r=n}return r}function mn(e){return e.replace(/\\(\d{3})/g,(r,t)=>String.fromCharCode(Number.parseInt(t,8)))}function fn(e){let r=[];for(let t of e.split(`
|
|
4
|
+
`)){let n=t.trim().split(/\s+/);n.length<3||r.push({mountPoint:mn(n[1]),fsType:n[2]})}return r}function Or(e,r=process.platform){return r==="win32"?e.replace(/\\/g,"/"):e}function gn(e,r){let t=null,n=Or(e);for(let o of r){let s=Or(o.mountPoint),i=s.endsWith("/")?s:`${s}/`;(n===s||`${n}/`.startsWith(i))&&(!t||o.mountPoint.length>t.mountPoint.length)&&(t=o)}return t}function Ne(e,r){let n=(r?.resolveRealPath??pn)(e),o=(r?.mountsSource??dn)();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=gn(n,fn(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 un.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}:cn.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 Pe=1,ne=class extends Error{constructor(r,t){super(`local-run-store schema version ${r} is newer than this runtime supports (${t}); refusing to open. Upgrade the runtime or quarantine the database deliberately.`),this.name="SchemaDowngradeRefusedError"}},hn=[`CREATE TABLE IF NOT EXISTS local_meta (
|
|
5
5
|
key TEXT PRIMARY KEY,
|
|
6
6
|
value TEXT NOT NULL
|
|
7
7
|
) STRICT`,`CREATE TABLE IF NOT EXISTS process_identity (
|
|
@@ -27,7 +27,7 @@ var c=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=
|
|
|
27
27
|
payload_json TEXT NOT NULL,
|
|
28
28
|
created_at TEXT NOT NULL,
|
|
29
29
|
PRIMARY KEY (scope, seq)
|
|
30
|
-
) STRICT`];function
|
|
30
|
+
) STRICT`];function yn(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_meta'").get())return null;let t=e.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 Ir(e,r){let t=yn(e);if(t!==null&&t>1)throw new ne(t,1);e.exec("BEGIN IMMEDIATE");try{for(let n of hn)e.exec(n);e.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(1)),e.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_applied_at', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r),e.exec("COMMIT")}catch(n){throw e.exec("ROLLBACK"),n}}import{mkdirSync as Rn}from"node:fs";import Sn from"node:path";import{DatabaseSync as bn}from"node:sqlite";var X=class extends Error{constructor(r){super(`local-run-store refused: ${r}`),this.name="FilesystemPolicyError"}},kn="local-run-store.sqlite",vn=5e3,Y=class e{db;now;databasePath;constructor(r,t,n){this.db=r,this.databasePath=t,this.now=n}static open(r){let t=Ne(r.directory,r.classifyOptions);if(t.verdict!=="accepted")throw new X(t.reason);Rn(r.directory,{recursive:!0,mode:448});let n=Sn.join(r.directory,r.filename??kn),o=new bn(n,{timeout:r.busyTimeoutMs??vn}),s=r.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 X(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),Ir(o,s().toISOString())}catch(i){throw o.close(),i}return new e(o,n,s)}inImmediateTransaction(r){this.db.exec("BEGIN IMMEDIATE");try{let t=r();return this.db.exec("COMMIT"),t}catch(t){throw this.db.exec("ROLLBACK"),t}}registerProcessIdentity(r){let t=this.now().toISOString();return this.inImmediateTransaction(()=>{this.db.prepare(`INSERT INTO process_identity
|
|
31
31
|
(process_key, pid, runtime_version, node_version, started_at, registered_at)
|
|
32
32
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
33
33
|
ON CONFLICT(process_key) DO UPDATE SET
|
|
@@ -35,24 +35,24 @@ var c=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=
|
|
|
35
35
|
runtime_version = excluded.runtime_version,
|
|
36
36
|
node_version = excluded.node_version,
|
|
37
37
|
started_at = excluded.started_at,
|
|
38
|
-
registered_at = excluded.registered_at`).run(
|
|
39
|
-
FROM process_identity WHERE process_key = ?`).get(
|
|
38
|
+
registered_at = excluded.registered_at`).run(r.processKey,r.pid,r.runtimeVersion,r.nodeVersion,r.startedAt,t)}),{...r,registeredAt:t}}getProcessIdentity(r){let t=this.db.prepare(`SELECT process_key, pid, runtime_version, node_version, started_at, registered_at
|
|
39
|
+
FROM process_identity WHERE process_key = ?`).get(r);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(r,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(r);return l&&l.expires_at>s.toISOString()&&l.owner!==t?{acquired:!1,current:{key:r,owner:l.owner,expiresAt:l.expires_at}}:(this.db.prepare(`INSERT INTO admission_reservations (reservation_key, owner, expires_at, created_at)
|
|
40
40
|
VALUES (?, ?, ?, ?)
|
|
41
41
|
ON CONFLICT(reservation_key) DO UPDATE SET
|
|
42
42
|
owner = excluded.owner,
|
|
43
|
-
expires_at = excluded.expires_at`).run(
|
|
43
|
+
expires_at = excluded.expires_at`).run(r,t,i,s.toISOString()),{acquired:!0,current:{key:r,owner:t,expiresAt:i}})})}releaseAdmission(r,t){return this.inImmediateTransaction(()=>{let n=this.db.prepare("DELETE FROM admission_reservations WHERE reservation_key = ? AND owner = ?").run(r,t);return Number(n.changes)>0})}listAdmissionReservations(r){let t=Math.floor(r?.limit??200),n=Number.isFinite(t)?Math.max(1,Math.min(1e3,t)):200,o=[],s=[];if(r?.keyPrefix){let u=r.keyPrefix.replace(/[\\%_]/g,c=>`\\${c}`);o.push("reservation_key LIKE ? ESCAPE '\\'"),s.push(`${u}%`)}r?.includeExpired||(o.push("expires_at > ?"),s.push((r?.now??this.now()).toISOString()));let i=o.length?`WHERE ${o.join(" AND ")}`:"";return this.db.prepare(`SELECT reservation_key, owner, expires_at
|
|
44
44
|
FROM admission_reservations ${i}
|
|
45
45
|
ORDER BY expires_at ASC, reservation_key ASC
|
|
46
|
-
LIMIT ?`).all(...s,n).map(u=>({key:u.reservation_key,owner:u.owner,expiresAt:u.expires_at}))}recordOperationReceipt(
|
|
46
|
+
LIMIT ?`).all(...s,n).map(u=>({key:u.reservation_key,owner:u.owner,expiresAt:u.expires_at}))}recordOperationReceipt(r){return this.inImmediateTransaction(()=>{let t=this.db.prepare(`INSERT INTO operation_receipts (idempotency_key, operation, result_json, recorded_at)
|
|
47
47
|
VALUES (?, ?, ?, ?)
|
|
48
|
-
ON CONFLICT(idempotency_key) DO NOTHING`).run(
|
|
48
|
+
ON CONFLICT(idempotency_key) DO NOTHING`).run(r.idempotencyKey,r.operation,r.resultJson??null,this.now().toISOString());return{deduplicated:Number(t.changes)===0}})}listOperationReceipts(r){let t=Math.floor(r?.limit??200),n=Number.isFinite(t)?Math.max(1,Math.min(1e3,t)):200,o=[],s=[];if(r?.operation&&(o.push("operation = ?"),s.push(r.operation)),r?.keyPrefix){let u=r.keyPrefix.replace(/[\\%_]/g,c=>`\\${c}`);o.push("idempotency_key LIKE ? ESCAPE '\\'"),s.push(`${u}%`)}r?.recordedAfter&&(o.push("recorded_at > ?"),s.push(r.recordedAfter));let i=o.length?`WHERE ${o.join(" AND ")}`:"";return this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
|
|
49
49
|
FROM operation_receipts ${i}
|
|
50
50
|
ORDER BY recorded_at ASC, idempotency_key ASC
|
|
51
|
-
LIMIT ?`).all(...s,n).map(u=>({idempotencyKey:u.idempotency_key,operation:u.operation,resultJson:u.result_json,recordedAt:u.recorded_at}))}deleteOperationReceiptsByKeys(
|
|
52
|
-
FROM operation_receipts WHERE idempotency_key = ?`).get(
|
|
53
|
-
VALUES (?, ?, ?, ?)`).run(
|
|
54
|
-
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 dn,renameSync as mn}from"node:fs";function pn(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;dn(o)&&mn(o,`${t}${n}`)}return t}function Ne(r){let e=r.quarantineStamp??(r.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=Y.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=pn(n,e);try{return{store:Y.open(r),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}We();function lo(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function uo(){return Et.classifyOptions??lo()}var Et={};function mo(r){Et=r}var At=300*1e3,P=null,ee=0;function po(r){ee+=1;try{let e=uo(),t=Ne({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:ee},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:ee},failedAtMs:Date.now(),permanentRefusal:e.name==="FilesystemPolicyError"||e.name==="SchemaDowngradeRefusedError"}}}function fo(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=At}function f(r=Date.now()){let e=rr();return(!P||P.status.harnessRoot!==e||fo(P,r))&&(nr(),P=po(e)),P.store}function Ct(){return P?P.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:ee}}function tr(){return f(),Ct()}function nr(){try{P?.store?.close()}catch{}P=null}function go(){nr(),ee=0}I();v();import{existsSync as ho,readFileSync as yo}from"node:fs";import{homedir as Ro}from"node:os";import So from"node:path";var bo=3e4,x=null;function or(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return So.join(Ro(),".kynver",`local-run-store-flags-${e}.json`)}function sr(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 ko(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:sr(t)}function vo(r,e){try{let t=or(r),n={contractVersion:1,agentOsId:r,flags:sr(e),deliveredAt:new Date().toISOString()};Le(t,n),x={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function ir(r=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(x&&r-x.loadedAtMs<bo)return x.flags;try{let e=_().agentOsId?.trim();if(!e)return x={flags:{},loadedAtMs:r,file:null},x.flags;let t=or(e);if(!ho(t))return x={flags:{},loadedAtMs:r,file:t},x.flags;let n=JSON.parse(yo(t,"utf8")),o=n?.contractVersion===1?sr(n.flags):{};return x={flags:o,loadedAtMs:r,file:t},o}catch{return x={flags:{},loadedAtMs:r,file:null},x.flags}}function xo(){x=null}var wt=[{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 Ot(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 C(r=process.env){let e={},t={},n=[],o=ir();for(let s of wt){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let l=Ot(i);e[s.key]=l.mode,t[s.key]="env",l.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 _o(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 C(r).flags.dispatchReceipts}function ar(r){return w(r)!=="off"}function cr(r,e){return`dispatch:${r}:${e.taskId}:${e.leaseToken}`}function re(r,e,t){if(!ar())return;let n=f();if(n)try{n.recordOperationReceipt({idempotencyKey:cr(r,e),operation:`dispatch-${r}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function Eo(r){re("claim",r,{runId:r.runId,workerName:r.workerName,provider:r.provider})}function lr(r){re("spawned",r)}function xe(r,e){re("released",r,{reasonClass:e})}function Ao(r){re("completion-sent",r)}function Co(r,e){re("completion-acked",r,{outcome:e})}function wo(r){if(!ar())return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(cr("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 Oo(r){let e=String(r??"").split(":")[0]?.trim()??"";return e.length>0?e.slice(0,64):"unknown"}function Io(r){if(w()!=="enforce")return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(cr("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 To=600*1e3;function No(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 Po(r,e){if(w()!=="enforce")return[];let t=f();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??To;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 q(r){let e=r.split(":")[0]??"",t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var Lo=900*1e3,It=10080*60*1e3,Do=1440*60*1e3,Mo=500,Ko=300;function ur(r){let e={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!ar())return e;let t=f();if(!t)return e;let n=r?.nowMs??Date.now(),o=r?.strandedAfterMs??Lo;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-It).toISOString(),limit:Mo}),i=0,a=[];for(let l of s){let m=l.idempotencyKey.slice(15),p=Date.parse(l.recordedAt);if(!Number.isFinite(p)||n-p<o)continue;let d=t.getOperationReceipt(`dispatch:spawned:${m}`),$=t.getOperationReceipt(`dispatch:released:${m}`);if(d||$){n-p>=Do&&a.length+5<=Ko&&a.push(l.idempotencyKey,`dispatch:spawned:${m}`,`dispatch:released:${m}`,`dispatch:completion-sent:${m}`,`dispatch:completion-acked:${m}`);continue}let k=m.split(":")[0]??"",H=q(m.slice(k.length+1));if((k?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${k}:`,limit:10}):[]).some(h=>{if(H===null)return!0;let j=h.idempotencyKey.slice(`dispatch:completion-acked:${k}:`.length),D=q(j);return D===null||D>=H}))continue;let y=!1;if(r?.hasLiveWorker&&l.resultJson)try{let h=JSON.parse(l.resultJson);h.runId&&h.workerName&&(y=r.hasLiveWorker({runId:h.runId,workerName:h.workerName}))}catch{y=!1}y||(i+=1)}let u=a.length>0?t.deleteOperationReceiptsByKeys(a):0;if(w()==="enforce"){let l=t.listOperationReceipts({limit:100}).filter(m=>{let p=Date.parse(m.recordedAt);return Number.isFinite(p)&&n-p>=It}).map(m=>m.idempotencyKey);if(l.length>0){let m=t.deleteOperationReceiptsByKeys(l);u+=m,R.agedReceiptsPruned+=m}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:u}}catch{return R.storeFailures+=1,e}}function dr(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function Fo(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as Vo,readFileSync as Go}from"node:fs";var B=900*1e3,pr="admission-shadow",mr="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},_e=!1;function Bo(){_e=!1}function U(r=process.env){return C(r).flags.admission}function Ee(r,e){return`${mr}${r}:${e}`}function Uo(r,e){if(U()==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Ee(r,e),pr,B)}catch{E.storeFailures+=1}}function fr(r,e){if(U()==="off")return;let t=f();if(t)try{t.releaseAdmission(Ee(r,e),pr)}catch{E.storeFailures+=1}}function Wo(r){let e={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(U()==="off")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(d=>Ee(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:mr,limit:500}),s=new Set(o.map(d=>d.key)),i=[...n].filter(d=>!s.has(d)).length,a=o.filter(d=>!n.has(d.key)).length,u=!_e;_e=!0,!u&&i>0&&(E.missingForLive+=i);let l=0;for(let d of r.liveWorkers)t.tryReserveAdmission(Ee(d.runId,d.workerName),pr,B),l+=1;let m=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(m+=1,E.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:mr,limit:500}).length,refreshed:l,deadReleased:m,missingForLive:i,orphaned:a,adoptionPass:u}}catch{return E.storeFailures+=1,e}}function gr(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function $o(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,_e=!1}var we="worker-slot-n:",Ae=64;function Tt(r){return`${we}${r}`}function Ce(r,e){return`${r}:${e}`}var A={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function Ho(r){if(U()!=="enforce")return{admitted:!0};let e=f();if(!e)return{admitted:!0};let t=Math.max(0,Math.min(Ae,Math.floor(r.maxSlots)));if(r.diskActiveWorkers>=t)return A.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=Ce(r.runId,r.workerName);for(let o=0;o<t;o+=1)if(e.tryReserveAdmission(Tt(o),n,B).acquired)return{admitted:!0,slot:o};return A.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return A.enforceStoreFailures+=1,{admitted:!0}}}function hr(r,e){if(U()==="off")return;let t=f();if(t)try{let n=Ce(r,e),o=t.listAdmissionReservations({keyPrefix:we,limit:Ae});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{A.enforceStoreFailures+=1}}function jo(r){let e={refreshed:0,deadReleased:0,adopted:0};if(U()!=="enforce")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(l=>Ce(l.runId,l.workerName))),o=t.listAdmissionReservations({keyPrefix:we,limit:Ae}),s=0,i=0,a=new Set;for(let l of o)n.has(l.owner)?(t.tryReserveAdmission(l.key,l.owner,B),a.add(l.owner),s+=1):t.releaseAdmission(l.key,l.owner)&&(i+=1);let u=0;for(let l of r.liveWorkers){let m=Ce(l.runId,l.workerName);if(!a.has(m)){for(let p=0;p<Ae;p+=1)if(t.tryReserveAdmission(Tt(p),m,B).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return A.enforceStoreFailures+=1,e}}function yr(){return{"admission.enforceStoreFailures":A.enforceStoreFailures,"admission.refusedSlotsExhausted":A.admissionsRefusedSlots,"admission.refusedDiskBackstop":A.admissionsRefusedDiskBackstop}}function Yo(){A.enforceStoreFailures=0,A.admissionsRefusedSlots=0,A.admissionsRefusedDiskBackstop=0}var qo="dispatch:claim:",Jo=900*1e3,zo=10080*60*1e3,Xo=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function Nt(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=Vo("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(Go(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(r))return Number(t)}catch{}return null}async function Rr(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??Jo,i=r.findOrphanPid??Nt,a=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-zo).toISOString(),limit:Xo})}catch{return O.recoveryStoreFailures+=1,t}for(let l of u){let m=l.idempotencyKey.slice(qo.length),p=m.split(":")[0]??"",d=m.slice(p.length+1);if(!(!p||!d))try{let $=Date.parse(l.recordedAt);if(!Number.isFinite($)||o-$<s||n.getOperationReceipt(`dispatch:spawned:${m}`)||n.getOperationReceipt(`dispatch:released:${m}`))continue;let k=q(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${p}:`,limit:10}).some(D=>{if(k===null)return!0;let z=q(D.idempotencyKey.slice(`dispatch:completion-acked:${p}:`.length));return z===null||z>=k}))continue;let J={};try{J=l.resultJson?JSON.parse(l.resultJson):{}}catch{J={}}let y=J.runId??null,h=J.workerName??null;if(y&&h&&r.hasLiveWorker({runId:y,workerName:h})){lr({taskId:p,leaseToken:d}),a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let D=r.worktreePathFor({runId:y,workerName:h}),z=D?i(D):null;if(z!==null){O.recoveryDeferredOrphans+=1,a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${z} references ${D}`});continue}}if(!y){a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let j=await r.releaseClaim({taskId:p,leaseToken:d,runId:y});j.released?(xe({taskId:p,leaseToken:d},"restart_recovery"),h&&(fr(y,h),hr(y,h)),O.recoveredStrandedClaims+=1,a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"released"})):j.transportError?a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:j.detail}):(xe({taskId:p,leaseToken:d},"restart_recovery_refused"),a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:j.detail}))}catch{O.recoveryStoreFailures+=1}}return{mode:e,scanned:u.length,outcomes:a}}function Sr(){return{"dispatchReceipts.recoveredStrandedClaims":O.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":O.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":O.recoveryStoreFailures}}function Qo(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}de();import cs from"node:path";var Zo="kynver-harness:",es="@runner:";function Pt(r,e){let t=r.trim(),n=e.trim();return`${Zo}${t}${es}${n}`}I();import Mt from"node:os";var rs="embedded-1",ts=[{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"}],ns={"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(`
|
|
51
|
+
LIMIT ?`).all(...s,n).map(u=>({idempotencyKey:u.idempotency_key,operation:u.operation,resultJson:u.result_json,recordedAt:u.recorded_at}))}deleteOperationReceiptsByKeys(r){return r.length===0?0:this.inImmediateTransaction(()=>{let t=this.db.prepare("DELETE FROM operation_receipts WHERE idempotency_key = ?"),n=0;for(let o of r)n+=Number(t.run(o).changes);return n})}getOperationReceipt(r){let t=this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
|
|
52
|
+
FROM operation_receipts WHERE idempotency_key = ?`).get(r);return t?{idempotencyKey:t.idempotency_key,operation:t.operation,resultJson:t.result_json,recordedAt:t.recorded_at}:null}saveRecoveryCheckpoint(r){return this.inImmediateTransaction(()=>{let t=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max_seq FROM recovery_checkpoints WHERE scope = ?").get(r.scope),n=Number(t.max_seq)+1;return this.db.prepare(`INSERT INTO recovery_checkpoints (scope, seq, payload_json, created_at)
|
|
53
|
+
VALUES (?, ?, ?, ?)`).run(r.scope,n,r.payloadJson,this.now().toISOString()),{seq:n}})}latestRecoveryCheckpoint(r){let t=this.db.prepare(`SELECT scope, seq, payload_json, created_at FROM recovery_checkpoints
|
|
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 xn,renameSync as _n}from"node:fs";function En(e,r){let t=`${e}.quarantine-${r}`;for(let n of["","-wal","-shm"]){let o=`${e}${n}`;xn(o)&&_n(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=En(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 vo(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function xo(){return Kt.classifyOptions??vo()}var Kt={};function _o(e){Kt=e}var Ft=300*1e3,P=null,ee=0;function Eo(e){ee+=1;try{let r=xo(),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 Co(e,r){return e.store||e.permanentRefusal?!1:e.failedAtMs===null?!0:r-e.failedAtMs>=Ft}function f(e=Date.now()){let r=ir();return(!P||P.status.harnessRoot!==r||Co(P,e))&&(lr(),P=Eo(r)),P.store}function Ut(){return P?P.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:ee}}function ar(){return f(),Ut()}function lr(){try{P?.store?.close()}catch{}P=null}function Ao(){lr(),ee=0}I();k();import{existsSync as wo,readFileSync as Oo}from"node:fs";import{homedir as Io}from"node:os";import To from"node:path";var No=3e4,x=null;function cr(e){let r=e.replace(/[^A-Za-z0-9_-]/g,"_");return To.join(Io(),".kynver",`local-run-store-flags-${r}.json`)}function ur(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 Po(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:ur(t)}function Do(e,r){try{let t=cr(e),n={contractVersion:1,agentOsId:e,flags:ur(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<No)return x.flags;try{let r=_().agentOsId?.trim();if(!r)return x={flags:{},loadedAtMs:e,file:null},x.flags;let t=cr(r);if(!wo(t))return x={flags:{},loadedAtMs:e,file:t},x.flags;let n=JSON.parse(Oo(t,"utf8")),o=n?.contractVersion===1?ur(n.flags):{};return x={flags:o,loadedAtMs:e,file:t},o}catch{return x={flags:{},loadedAtMs:e,file:null},x.flags}}function Lo(){x=null}var Bt=[{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 Wt(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 Bt){let i=e[s.env];if(typeof i=="string"&&i.trim()!==""){let c=Wt(i);r[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){r[s.key]=u,t[s.key]="server";continue}r[s.key]="off",t[s.key]="default"}return{flags:r,sources:t,warnings:n}}function Mo(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 Ko(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 Fo(e){re("completion-sent",e)}function Uo(e,r){re("completion-acked",e,{outcome:r})}function Bo(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 Wo(e){let r=String(e??"").split(":")[0]?.trim()??"";return r.length>0?r.slice(0,64):"unknown"}function $o(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 Ho=600*1e3;function jo(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 Yo(e,r){if(w()!=="enforce")return[];let t=f();if(!t)return[];let n=r?.nowMs??Date.now(),o=r?.windowMs??Ho;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 Vo=900*1e3,$t=10080*60*1e3,Go=1440*60*1e3,qo=500,Jo=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??Vo;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-$t).toISOString(),limit:qo}),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}`),$=t.getOperationReceipt(`dispatch:released:${p}`);if(d||$){n-m>=Go&&l.length+5<=Jo&&l.push(c.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(h=>{if(H===null)return!0;let j=h.idempotencyKey.slice(`dispatch:completion-acked:${v}:`.length),L=q(j);return L===null||L>=H}))continue;let y=!1;if(e?.hasLiveWorker&&c.resultJson)try{let h=JSON.parse(c.resultJson);h.runId&&h.workerName&&(y=e.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>=$t}).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,r}}function hr(){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 os,readFileSync as ss}from"node:fs";var U=900*1e3,Rr="admission-shadow",yr="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Ce=!1;function Xo(){Ce=!1}function B(e=process.env){return A(e).flags.admission}function Ae(e,r){return`${yr}${e}:${r}`}function Qo(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 Zo(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:yr,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=!Ce;Ce=!0,!u&&i>0&&(E.missingForLive+=i);let c=0;for(let d of e.liveWorkers)t.tryReserveAdmission(Ae(d.runId,d.workerName),Rr,U),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:yr,limit:500}).length,refreshed:c,deadReleased:p,missingForLive:i,orphaned:l,adoptionPass:u}}catch{return E.storeFailures+=1,r}}function br(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function es(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Ce=!1}var Ie="worker-slot-n:",we=64;function Ht(e){return`${Ie}${e}`}function Oe(e,r){return`${e}:${r}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function rs(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(Ht(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 ts(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(c=>Oe(c.runId,c.workerName))),o=t.listAdmissionReservations({keyPrefix:Ie,limit:we}),s=0,i=0,l=new Set;for(let c of o)n.has(c.owner)?(t.tryReserveAdmission(c.key,c.owner,U),l.add(c.owner),s+=1):t.releaseAdmission(c.key,c.owner)&&(i+=1);let u=0;for(let c of e.liveWorkers){let p=Oe(c.runId,c.workerName);if(!l.has(p)){for(let m=0;m<we;m+=1)if(t.tryReserveAdmission(Ht(m),p,U).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,r}}function vr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function ns(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var is="dispatch:claim:",as=900*1e3,ls=10080*60*1e3,cs=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function jt(e){if(process.platform!=="linux"||!e.trim())return null;let r=[];try{r=os("/proc")}catch{return null}for(let t of r)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(ss(`/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??as,i=e.findOrphanPid??jt,l=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-ls).toISOString(),limit:cs})}catch{return O.recoveryStoreFailures+=1,t}for(let c of u){let p=c.idempotencyKey.slice(is.length),m=p.split(":")[0]??"",d=p.slice(m.length+1);if(!(!m||!d))try{let $=Date.parse(c.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=c.resultJson?JSON.parse(c.resultJson):{}}catch{J={}}let y=J.runId??null,h=J.workerName??null;if(y&&h&&e.hasLiveWorker({runId:y,workerName:h})){fr({taskId:m,leaseToken:d}),l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let L=e.worktreePathFor({runId:y,workerName:h}),z=L?i(L):null;if(z!==null){O.recoveryDeferredOrphans+=1,l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${z} references ${L}`});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 j=await e.releaseClaim({taskId:m,leaseToken:d,runId:y});j.released?(Ee({taskId:m,leaseToken:d},"restart_recovery"),h&&(Sr(y,h),kr(y,h)),O.recoveredStrandedClaims+=1,l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"released"})):j.transportError?l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:j.detail}):(Ee({taskId:m,leaseToken:d},"restart_recovery_refused"),l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:j.detail}))}catch{O.recoveryStoreFailures+=1}}return{mode:r,scanned:u.length,outcomes:l}}function _r(){return{"dispatchReceipts.recoveredStrandedClaims":O.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":O.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":O.recoveryStoreFailures}}function us(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}pe();import bs from"node:path";var ds="kynver-harness:",ps="@runner:";function Yt(e,r){let t=e.trim(),n=r.trim();return`${ds}${t}${ps}${n}`}I();import qt from"node:os";var ms="embedded-1",fs=[{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"}],gs={"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
55
|
`),"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
56
|
`),"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
57
|
`),"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
|
-
`)},
|
|
58
|
+
`)},hs={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},Vt={version:ms,generatedAt:"1970-01-01T00:00:00.000Z",personas:fs,instructions:gs,policyThresholds:hs};var ys=Vt;function Gt(){return ys.version}M();function D(e){return e?.trim()?e.trim():null}function Jt(e={}){let r=e.env??process.env,t=_();return{runnerId:D(t.runnerId)??D(r.KYNVER_RUNTIME_ID)??D(r.OPENCLAW_RUNTIME_ID)??D(r.HOSTNAME)??qt.hostname(),hostname:D(r.HOSTNAME)??qt.hostname(),profile:D(r.KYNVER_RUNNER_PROFILE)??D(r.OPENCLAW_RUNNER_PROFILE),harnessRepo:D(r.KYNVER_HARNESS_REPO)??D(r.KYNVER_DEFAULT_REPO),runId:e.runId??null,instructionBundleVersion:Gt()}}function zt(e){let r=String(e).trim();return r.startsWith("krc1.")?{"Content-Type":"application/json","X-Kynver-Runner-Token":r}:{"Content-Type":"application/json","X-Kynver-Cron-Secret":r,"X-OpenClaw-Cron-Secret":r,"X-Kynver-Runtime-Secret":r}}le();I();function Qt(e){if(e!==void 0&&Number.isFinite(e)&&e>0)return Math.floor(e);let r=Number(process.env.KYNVER_CALLBACK_TIMEOUT_MS);return Number.isFinite(r)&&r>0?Math.floor(r):3e4}async function Rs(e,r){let t=Qt(r),n=new AbortController,o;try{return await Promise.race([e(n.signal),new Promise((s,i)=>{o=setTimeout(()=>{n.abort(),i(new Error(`callback timeout after ${t}ms`))},t)})])}finally{o&&clearTimeout(o)}}function Ss(e,r){let t=Qt(r);return{ok:!1,status:0,response:{error:e instanceof Error?e.message:String(e),timeoutMs:t}}}async function Xt(e,r,t,n){try{return await Rs(async o=>{let s=await ae(e,{method:"POST",headers:zt(r),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 Ss(o,n?.timeoutMs)}}async function Zt(e,r,t,n){let o=await Xt(e,r,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await Lt(r,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await Xt(e,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function en(e){let r=`${e.baseUrl}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/tasks/${encodeURIComponent(e.taskId)}/release`,t;try{t=await Zt(r,e.secret,{agentOsId:e.agentOsId,leaseOwner:e.leaseOwner,...e.leaseToken?.trim()?{leaseToken:e.leaseToken.trim()}:{},...e.failureDetail?{failureDetail:e.failureDetail}:{}},{agentOsId:e.agentOsId,baseUrl:e.baseUrl})}catch(s){return{released:!1,httpOk:!1,transportError:!0,releaseResponse:{ok:!1,error:s.message}}}let n=t.response;return{released:t.ok===!0||n?.ok===!0,httpOk:t.ok===!0,transportError:!1,releaseResponse:t.response??t}}var Er=!1;function ks(){Er=!1}async function vs(e){if(Er||w()!=="enforce")return null;Er=!0;try{let r=Jt().runnerId,t=await xr({hasLiveWorker:e.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>bs.join($r().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await en({baseUrl:e.baseUrl,secret:e.secret,agentOsId:e.agentOsId,taskId:n,leaseOwner:Yt(s,r),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 bd=600*1e3,te={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function rn(){return{"planOutbox.storeFailures":te.storeFailures,"planOutbox.corruptItemsSeen":te.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":te.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":te.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":te.halfArchivesCompleted}}var g={keeperStoreFailures:0,meshStoreFailures:0,quotaStoreFailures:0,meshLeaseDivergences:0,meshEnforceStaleInversions:0,quotaVerdictDivergences:0};function W(e){return A(process.env).flags[e]}var tn="daemon-keeper",xs=1800*1e3;function _s(e){if(W("keeper")==="off")return;let r=f();if(r)try{r.saveRecoveryCheckpoint({scope:tn,payloadJson:JSON.stringify(e)})}catch{g.keeperStoreFailures+=1}}function Es(){if(W("keeper")!=="enforce")return null;let e=f();if(!e)return null;try{let r=e.latestRecoveryCheckpoint(tn);if(!r)return null;let t=JSON.parse(r.payloadJson),n=Date.now()-Date.parse(r.createdAt);if(!Number.isFinite(n)||n>xs)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function Cr(e){return`mesh-cron-lease:${e}`}function Cs(e,r){if(W("meshLease")==="off")return;let t=f();if(t)try{let n=t.latestRecoveryCheckpoint(Cr(e));if(n){let o=JSON.parse(n.payloadJson);if((o.leaseToken??null)===(r.leaseToken??null)&&(o.holderBoxId??null)===(r.holderBoxId??null)&&o.authorized===r.authorized)return}t.saveRecoveryCheckpoint({scope:Cr(e),payloadJson:JSON.stringify(r)})}catch{g.meshStoreFailures+=1}}function As(e,r){let t=W("meshLease");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(Cr(e)),s=o?JSON.parse(o.payloadJson):null,i=s!==null&&((s.leaseToken??null)!==(r?.leaseToken??null)||(s.holderBoxId??null)!==(r?.holderBoxId??null)||(s.authorized??null)!==(r?.authorized??null));return i&&(g.meshLeaseDivergences+=1),t!=="enforce"?null:i&&r?.updatedAt&&s?.updatedAt&&Date.parse(r.updatedAt)>Date.parse(s.updatedAt)?(g.meshEnforceStaleInversions+=1,null):s}catch{return g.meshStoreFailures+=1,null}}function Te(e){return`quota-cooldown:${e}`}var nn="quota-preflight";function ws(e,r){if(W("quota")==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Te(e),nn,r)}catch{g.quotaStoreFailures+=1}}function Os(e){if(W("quota")==="off")return;let r=f();if(r)try{r.releaseAdmission(Te(e),nn)}catch{g.quotaStoreFailures+=1}}function Is(e,r){let t=W("quota");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:Te(e),limit:50}).find(i=>i.key===Te(e)),s=!!o;return s!==r&&(g.quotaVerdictDivergences+=1),t==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return g.quotaStoreFailures+=1,null}}function Ar(){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 Ts(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function Ns(e){let r=ar(),t=A(e?.env??process.env),n=(e?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,hr());let s=gr({nowMs:n,hasLiveWorker:e?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,_r())}return t.flags.planOutbox!=="off"&&Object.assign(o,rn()),t.flags.admission!=="off"&&(Object.assign(o,br()),t.flags.admission==="enforce"&&Object.assign(o,vr())),(t.flags.keeper!=="off"||t.flags.meshLease!=="off"||t.flags.quota!=="off")&&Object.assign(o,Ar()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:r.state,schemaVersion:r.schemaVersion,recovered:r.recovered,unavailableClass:r.reason?r.reason.split(":")[0]??null:null,flags:t.flags,flagSources:t.sources,flagWarningCount:t.warnings.length,divergenceCounters:o}}export{U as ADMISSION_RESERVATION_TTL_MS,Ie as ADMISSION_SLOT_KEY_PREFIX,X as FilesystemPolicyError,Ft as LOCAL_RUN_STORE_OPEN_RETRY_MS,Bt as LOCAL_RUN_STORE_SURFACES,Pe as LOCAL_SCHEMA_VERSION,ne as SchemaDowngradeRefusedError,Y as SqliteLocalRunStore,ns as __resetAdmissionEnforceCountersForTests,es as __resetAdmissionShadowCountersForTests,us as __resetDispatchClaimRecoveryForTests,zo as __resetDispatchReceiptCountersForTests,Ao as __resetLocalRunStoreLifecycleForTests,Lo as __resetRemoteSurfaceFlagsCacheForTests,Ts as __resetSmallSurfaceCountersForTests,ks as __resetStartupClaimRecoveryForTests,_o as __setLocalRunStoreLifecycleTestOverrides,rs as acquireWorkerAdmissionSlot,vr as admissionEnforceCounters,br as admissionShadowCounters,Mo as anyLocalRunStoreSurfaceActive,Is as assessQuotaCooldownReservation,Ns as buildLocalRunStoreTickPosture,Ne as classifyDatabaseDirectory,Os as clearQuotaCooldownReservation,lr as closeLocalRunStore,_r as dispatchClaimRecoveryCounters,hr as dispatchReceiptCounters,w as dispatchReceiptsMode,Po as extractLocalRunStoreFlagsFromOperatorTickResponse,jt as findLiveProcessByCmdlinePath,f as getLocalRunStore,Ut as getLocalRunStoreLifecycleStatus,dr as getRemoteSurfaceFlags,q as leaseTokenAttempt,Yo as listRecentDispatchStartFailures,vs as maybeRunStartupClaimRecovery,Bo as noteCompletionReplayIfAcked,De as openSqliteLocalRunStoreWithRecovery,Wt as parseLocalRunStoreSurfaceMode,Do as persistRemoteSurfaceFlags,ar as probeLocalRunStore,As as readMeshLeaseCheckpoint,Xo as rearmAdmissionAdoptionPass,Zo as reconcileAdmissionShadow,ts as reconcileNumberedAdmissionSlots,Uo as recordCompletionAckedReceipt,Fo as recordCompletionSentReceipt,Ko as recordDispatchClaimReceipt,Ee as recordDispatchReleasedReceipt,fr as recordDispatchSpawnedReceipt,jo as recordDispatchStartFailedReceipt,ws as recordQuotaCooldownReservation,xr as recoverStrandedDispatchClaims,Wo as releaseReasonClass,kr as releaseWorkerAdmissionSlot,Sr as releaseWorkerSlotReservation,cr as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,Es as restoreKeeperBackoffCheckpoint,_s as saveKeeperBackoffCheckpoint,Cs as saveMeshLeaseCheckpoint,gr as scanDispatchReceiptInvariants,$o as shouldShortCircuitCompletionReplay,Ar as smallSurfaceCounters,Qo as takeWorkerSlotReservation};
|