@kynver-app/runtime 0.1.135 → 0.1.139
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/callbacks.d.ts +21 -2
- package/dist/cleanup-types.d.ts +12 -0
- package/dist/cli.js +53 -50
- package/dist/default-repo-discovery.d.ts +10 -0
- package/dist/default-repo.d.ts +2 -0
- package/dist/disk-gate.d.ts +4 -0
- package/dist/dispatch-callback-timeout.d.ts +1 -0
- package/dist/dispatch-progress.d.ts +3 -0
- package/dist/factory-status/collect.d.ts +10 -0
- package/dist/factory-status/lightweight.d.ts +5 -0
- package/dist/factory-status/render.d.ts +5 -0
- package/dist/factory-status/types.d.ts +46 -0
- package/dist/factory-status-cli.d.ts +1 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +68 -65
- package/dist/server/cleanup.js +14 -14
- package/dist/server/default-repo.js +1 -1
- 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/monitor.js +6 -6
- package/dist/server/worker-policy.js +1 -1
- package/dist/wsl-crash-dumps-cleanup.d.ts +31 -0
- package/dist/wsl-crash-dumps-cli.d.ts +1 -0
- package/dist/wsl-crash-dumps.d.ts +90 -0
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)),this.name="MemoryCostPackageVersionGuardError",this.result=e}};function
|
|
1
|
+
var P=["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"],I=new Set(P);var f={"@kynver-app/runtime":"0.1.83","@kynver-app/openclaw-agent-os":"0.1.43","@kynver-app/mcp-agent-os":"0.3.34"},_=Object.keys(f),g={"@kynver-app/runtime":"Kynver runtime","@kynver-app/openclaw-agent-os":"OpenClaw AgentOS plugin","@kynver-app/mcp-agent-os":"AgentOS MCP server"};function E(n){let e=n.trim().split("-")[0]?.split("+")[0];if(!e)return null;let o=e.split(".");if(o.length<1||o.length>3)return null;let t=o.map(s=>Number.parseInt(s,10));if(t.some(s=>!Number.isFinite(s)||s<0))return null;for(;t.length<3;)t.push(0);return[t[0],t[1],t[2]]}function y(n,e){let o=E(n),t=E(e);if(!o||!t)return 0;for(let s=0;s<3;s+=1){if(o[s]>t[s])return 1;if(o[s]<t[s])return-1}return 0}function S(n,e){return y(n,e)>=0}function M(n){let e=null;for(let o of n)(!e||y(o,e)>0)&&(e=o);return e}function b(n){return n==="@kynver-app/runtime"?["npm run kynver:build","npm run kynver"]:[`npm run build -w ${n}`]}function x(n){let{packageName:e,minimumVersion:o,effectiveVersion:t,effectiveSource:s,repoVersion:i}=n,r=[];return i&&S(i,o)?(r.push(`Use the monorepo checkout (${i}) instead of a stale npm install: ${b(e).join("; ")}.`),r.push("Do not publish npm packages or wait on an operator release."),r):(t?r.push(`Upgrade ${e} from ${t} to >= ${o} (npm install -g ${e}@latest or align OpenClaw npm prefix).`):r.push(`Install ${e} >= ${o} before running memory-heavy AgentOS paths.`),e==="@kynver-app/runtime"&&r.push("Repo-source alternative: npm run kynver:build && npm run kynver"),s==="installed"&&i&&r.push(`Repo checkout reports ${i}; rebuild/link repo source if you develop from the monorepo.`),r)}function O(n){if(n.length===0)return{version:null,source:"unknown"};let e=M(n.map(t=>t.version));if(!e)return{version:null,source:"unknown"};let o=n.find(t=>t.version===e)??n[0];return{version:o.version,source:o.source}}function R(n={}){let e=(r,a)=>r?typeof r=="string"?{version:r,source:a}:r:null,o=_.map(r=>{let a=f[r],c=[],k=e(n.installed?.[r],"installed"),d=e(n.repo?.[r],"repo"),v=e(n.self?.[r],"self");k&&c.push(k),d&&c.push(d),v&&c.push(v);let{version:u,source:l}=O(c),C=d?.version??null,m=u?S(u,a):!1,h=m?[]:x({packageName:r,minimumVersion:a,effectiveVersion:u,effectiveSource:l,repoVersion:C}),A=m?`${g[r]} ${u} meets memory-cost minimum ${a} (${l}).`:`${g[r]} is below memory-cost minimum ${a}`+(u?` (effective ${u} via ${l})`:" (no version detected)")+".";return{packageName:r,displayName:g[r],minimumVersion:a,effectiveVersion:u,effectiveSource:l,ok:m,summary:A,remediation:h}}),t=o.filter(r=>!r.ok),s=t.length===0,i=s?"All managed AgentOS packages meet memory-cost minimum versions.":`Memory-cost package guard blocked ${t.length} stale package(s): ${t.map(r=>`${r.packageName} < ${r.minimumVersion}`).join("; ")}.`;return{ok:s,summary:i,packages:o}}var p=class extends Error{result;constructor(e){let o=[e.summary,...e.packages.filter(t=>!t.ok).flatMap(t=>[`- ${t.summary}`,...t.remediation.map(s=>` \u2192 ${s}`)])];super(o.join(`
|
|
2
|
+
`)),this.name="MemoryCostPackageVersionGuardError",this.result=e}};function w(n={}){let e=R(n);if(!e.ok)throw new p(e);return e}export{f as MEMORY_COST_PACKAGE_MIN_VERSIONS,p as MemoryCostPackageVersionGuardError,w as assertMemoryCostPackageVersionGuard,y as compareSemver,R as evaluateMemoryCostPackageVersionGuard};
|
package/dist/server/monitor.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var c=(e,r)=>()=>(e&&(r=e(e=0)),r);function U(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let t=JSON.parse(r);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return null}return null}function
|
|
1
|
+
var c=(e,r)=>()=>(e&&(r=e(e=0)),r);function U(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let t=JSON.parse(r);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return null}return null}function Z(e){let r=e.trim();if(!r)return null;let t=U(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let l=U(s[1]??"");l&&n.push(l)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let l=U(r.slice(i,a+1));l&&n.push(l)}return n.length>0?n[n.length-1]:null}function ee(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?Z(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=Z(t);return n||t}var re=c(()=>{"use strict"});import{existsSync as er,mkdirSync as mt,readFileSync as rr,readdirSync as ft,statSync as te,writeFileSync as pt}from"node:fs";function ne(e){console.error(e),process.exit(1)}function D(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function C(e){try{return JSON.parse(e)}catch{return null}}function E(e){try{return te(e).size}catch{return 0}}function A(e){try{return te(e).mtime.toISOString()}catch{return null}}function oe(e,r){return er(e)?rr(e,"utf8").split(`
|
|
2
2
|
`).slice(-r).join(`
|
|
3
|
-
`):""}function
|
|
4
|
-
`).filter(Boolean);for(let s of o){let i=
|
|
3
|
+
`):""}function v(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function se(e){let r=null,t=-1/0;for(let n of e){if(!n)continue;let o=Date.parse(n);Number.isFinite(o)&&o>t&&(t=o,r=n)}return r}function I(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var p=c(()=>{"use strict"});import{existsSync as tr,readFileSync as nr}from"node:fs";function ie(e){return e==="complete"}function ae(e){return ie(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function le(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!tr(e))return r;let t=Date.now()+or,n=new Date(t).toISOString(),o=nr(e,"utf8").split(`
|
|
4
|
+
`).filter(Boolean);for(let s of o){let i=C(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(r.heartbeatCount++,a.ts){let l=String(a.ts),m=Date.parse(l);Number.isFinite(m)&&m>t?r.timestampAnomalies.push({kind:"future_heartbeat_timestamp",observedAt:l,clampedTo:n}):r.lastHeartbeatAt=l}a.phase!==void 0&&a.phase!==null&&(r.lastHeartbeatPhase=String(a.phase)),a.summary!==void 0&&a.summary!==null&&(r.lastHeartbeatSummary=String(a.summary)),ie(r.lastHeartbeatPhase)&&(r.terminalFinalResult=ee(a)),r.heartbeatBlocker=a.blocker?String(a.blocker):null,a.boxResourceSnapshot&&typeof a.boxResourceSnapshot=="object"&&!Array.isArray(a.boxResourceSnapshot)&&(r.lastBoxResourceSnapshot=a.boxResourceSnapshot),Array.isArray(a.prEvidence)&&(r.lastPrEvidence=a.prEvidence.filter(l=>!!l&&typeof l=="object"&&typeof l.prUrl=="string"))}return r}var or,ce=c(()=>{"use strict";re();p();or=6e4});function ir(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function ar(e){if(!e)return[];let r=[],t="",n,o=!1;for(let s of e){if(o){t+=s,o=!1;continue}if(s==="\\"){o=!0;continue}if(n){s===n?n=void 0:t+=s;continue}if(s==='"'||s==="'"){n=s;continue}if(/\s/.test(s)){t&&(r.push(t),t="");continue}t+=s}return t&&r.push(t),r}function lr(e){let r=ir(e[0]);return!!(r&&sr.has(r))}function M(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function H(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function cr(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function ur(e){let r=[];for(let t=1;t<e.length;t+=1){let n=e[t];if(n){if(n==="--"){r.push(...e.slice(t+1));break}if(n.startsWith("-")){if(n.includes("="))continue;ue.has(n)&&(t+=1);continue}r.push(n)}}return r}function dr(e){let r=!1,t=e.map((o,s)=>{let i=cr(o),a=e[s-1];return a&&ue.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(r=!0),i}),n=ur(t);if(n.length===2){let[o,s]=n;if(H(s))return{argv:[t[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};if(M(s))return{argv:[t[0]??"rg","-g",s,o,"."],changed:!0}}return r&&n.length===1?{argv:[...t,"."],changed:!0}:{argv:t,changed:r}}function K(e){let r=e.trim();if(!r)return{command:r,changed:!1};let t=r.includes("&&")?" && ":r.includes("||")?" || ":"; ",n=r.split(/\s*(?:&&|\|\||;)\s*/u),o=!1,s=n.map(i=>{let a=ar(i.trim());if(!a.length||!lr(a))return i;let l=dr(a);return l.changed?(o=!0,l.argv.join(" ")):i});return o?{command:s.join(t),changed:!0}:{command:r,changed:!1}}function de(e){if(!e)return{};let r=e.match(/search\s+"(.+)"\s+in\s+([^()]+?)(?:\s*\(|$)/iu);if(r)return{pattern:r[1],target:r[2]?.trim()};let t=e.match(/^search\s+"(.+)"\s+in\s+(.+)$/iu);return t?{pattern:t[1],target:t[2]?.trim()}:{}}function mr(e){let{pattern:r,target:t}=de(e);return r?H(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:M(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function fr(e){let{pattern:r,target:t}=de(e);if(!r)return null;if(H(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&M(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function pr(e){if(e.kind==="bad_scope"&&e.pattern?.includes("agent-os-land-pr")&&e.target==="package.json")return"Search package.json with a glob from the repo root: `rg -g package.json agent-os-land-pr .` \u2014 or run `node scripts/agent-os-land-pr.mjs <pr-url>` directly.";if(e.kind==="bad_scope"&&e.pattern&&e.target)return`Use \`rg -g '${e.target}' ${e.pattern} .\` from the repo root instead of treating ${e.target} as a folder.`;if(e.kind==="rg_exclude_syntax"&&e.pattern){let r=e.target?`${e.target.trim()}/**`:"!node_modules/**";return`Repo search scope \`${e.target??"!node_modules"}\` is not a valid ripgrep path. Use \`rg "${e.pattern}" -g '${r}' .\` from the repo root (exclude globs need a \`/**\` suffix).`}return e.kind==="no_matches"&&e.pattern?`No matches for "${e.pattern}". Try a broader pattern, drop overly short tokens, or search from the repo root with \`rg "${e.pattern}" .\`.`:null}function gr(e){let r=e.match(/search\s+"(.+)"\s+in\s+([^()]+?)(?:\s*\(agent\)|\s*failed|$)/iu);return r?`search "${r[1]}" in ${r[2]?.trim()}`:null}function F(e){let r=e.meta?.trim()||(e.command?gr(e.command):null)||null;if(r){let t=mr(r),n=pr(t);if(n)return n;let o=fr(r);if(o?.changed)return`Repo search used an invalid scope. Retry with: \`${o.command}\`.`}if(e.command&&/\b(rg|ripgrep)\b/i.test(e.command)){let t=K(e.command);if(t.changed)return`Ripgrep scope may be invalid. Retry with: \`${t.command}\`.`;if(e.exitCode===1)return"Ripgrep returned no matches (exit 1). Try a broader pattern or search from the repo root."}return null}var sr,ue,me=c(()=>{"use strict";sr=new Set(["rg","ripgrep","grep"]),ue=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function R(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function yr(e){let r=e.trim();if(!r)return null;if(r.startsWith("{"))try{return JSON.parse(r)}catch{}let t=r.indexOf("{"),n=r.lastIndexOf("}");if(t>=0&&n>t)try{return JSON.parse(r.slice(t,n+1))}catch{return null}return null}function x(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Rr(e){let r=e.metadata;if(!x(r))return null;let t=r.vulnerabilities;if(!x(t))return null;let n=s=>typeof t[s]=="number"?t[s]:0,o={info:n("info"),low:n("low"),moderate:n("moderate"),high:n("high"),critical:n("critical"),total:n("total")};return typeof t.total!="number"&&!o.critical&&!o.high&&!o.moderate&&!o.low&&!o.info?null:o}function xr(e){let r=[];e.critical&&r.push(`${e.critical} critical`),e.high&&r.push(`${e.high} high`),e.moderate&&r.push(`${e.moderate} moderate`),e.low&&r.push(`${e.low} low`),e.info&&r.push(`${e.info} info`);let t=r.length?r.join(", "):"see report";return`npm audit: ${e.total} vulnerabilit${e.total===1?"y":"ies"} (${t}) \u2014 remediation required`}function _r(e,r){let t=e.error;if(x(t)){let s=typeof t.summary=="string"?t.summary.trim():"",i=typeof t.code=="string"?t.code.trim():"";if(s)return i?`${i}: ${s}`:s;if(i)return i}let n=typeof e.message=="string"?e.message.trim():"";if(n)return n;let o=r.trim();return o?R(o.split(`
|
|
5
5
|
`).find(Boolean)??o,160):"npm audit failed"}function Sr(e){let r=`${e.stdout}
|
|
6
|
-
${e.stderr}`.trim(),t=yr(r);if(!t||!x(t)){let o=R(r||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit failed (invalid or missing JSON): ${o}`,parseError:"invalid_json"}}if(x(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${
|
|
7
|
-
`).filter(Boolean);for(let n of t){let o=
|
|
8
|
-
`).map(r=>r.trim()).filter(Boolean)}function w(e,r){try{let t=_e("git",r,I({cwd:e,encoding:"utf8"}));return{status:t.status,stdout:t.stdout||"",stderr:t.stderr||"",error:t.error?t.error.message:null}}catch(t){return{status:null,stdout:"",stderr:"",error:t.message}}}function Se(e,r,t){let n=w(e,["merge-base","--is-ancestor",r,t]);return n.status===0?{isAncestor:!0,error:null}:n.status===1?{isAncestor:!1,error:null}:{isAncestor:null,error:n.error||n.stderr||n.stdout||`git exited ${n.status}`}}function Ae(e,r="origin/main"){let t=typeof r=="string"?{base:r}:r,n=t.baseCommit?.trim()||t.base?.trim()||"origin/main",o=t.baseCommit?.trim()||null;if(!e)return D(n,"missing worktree path");let s=w(e,["rev-parse","HEAD"]);if(s.status!==0)return D(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let f=w(e,["rev-parse",n]);if(f.status!==0)return D(n,f.error||f.stderr||f.stdout||`failed to resolve ${n}`,s.stdout.trim());i=f.stdout.trim()}let a=s.stdout.trim();if(a===i)return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let l=Se(e,i,a),m=Se(e,a,i),d=l.error||m.error||void 0;if(l.isAncestor==null||m.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:m.isAncestor,relation:"unknown",...d?{error:d}:{}};let u=l.isAncestor?"ahead":m.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:m.isAncestor,relation:u,...d?{error:d}:{}}}function D(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var L=c(()=>{"use strict";g();xe()});function S(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Fr(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function $r(e){if(S(e.headCommit)||S(e.prUrl)||S(e.artifactBundlePath)||S(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&S(r.head))}function ve(e){return Fr(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:$r(e)?{blocked:!0,detail:`Worktree has ${e.changedFiles.length} uncommitted change(s); commit or discard before landing`}:{blocked:!0,reason:"dirty_worktree_no_pr",detail:`Worktree has ${e.changedFiles.length} uncommitted change(s) with no commit or PR; commit, open a PR, or discard before landing`}:{blocked:!1}}function Ce(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var we=c(()=>{"use strict"});function j(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let t=JSON.parse(r);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return null}return null}function Pe(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function P(e){let r=e.trim();if(!r)return null;let t=j(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let d=j(s[1]??"");d&&n.push(d)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let d=j(r.slice(i,a+1));d&&n.push(d)}if(n.length===0)return null;let l=n[n.length-1],m=Pe(l);for(let d of n){let u=Pe(d);u>m&&(l=d,m=u)}return l}var G=c(()=>{"use strict"});function b(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Dr(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function y(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:b(e)}function O(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Oe(e){let r=null;if(typeof e=="string"){let o=P(e);o&&(r=o)}else e&&typeof e=="object"&&!Array.isArray(e)&&(r=e);if(!r)return[];let t=r.targetPrReconciliation??r.target_pr_reconciliation;if(!Array.isArray(t))return[];let n=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=y(String(s.prUrl??s.pr_url??"")),a=b(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:b(s.mergeCommit??s.merge_commit),reason:b(s.reason)})}return n}function We(e,r){let t=[],n=y(b(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=y(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function Be(e){let{contract:r,snapshot:t}=e,n=e.finalResult??t.finalResult;if(!r.landingOnly&&r.targetPrUrls.length===0&&!r.repairEnforceOriginalPr)return{blocked:!1};if(!Dr(n))return(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&r.targetPrUrls.length>0?{blocked:!0,reason:"missing_target_pr_reconciliation",detail:`Final result required to reconcile target PR(s): ${r.targetPrUrls.join(", ")}`}:{blocked:!1};if(!(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&!r.repairEnforceOriginalPr)return{blocked:!1};let s=r.repairEnforceOriginalPr?y(b(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?y(r.targetPrUrls[0]):null):null;if(s){let u=We(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let k of u)if(k!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${k} instead of canonical target ${s}`}}let p=Oe(n).find(k=>k.prUrl===s);if(!p||p.outcome!=="merged"&&!(p.reason?.trim()&&(p.outcome==="skipped"||p.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=Oe(n),a=new Map(i.map(u=>[O(u.prUrl),u])),l=new Set(r.targetPrUrls.map(u=>O(y(u)??u)).filter(Boolean)),m=We(t,n);if(r.landingOnly)for(let u of m){if(l.size>0&&!l.has(O(u)))return{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${u}`};if(l.size===0)return{blocked:!0,reason:"unrelated_implementation_pr",detail:"Landing-only worker must not open new implementation PRs"}}if(r.targetPrUrls.length===0)return{blocked:!1};let d=[];for(let u of r.targetPrUrls){let f=O(y(u)??u),h=a.get(f);if(!h){d.push(f);continue}h.outcome!=="merged"&&!h.reason?.trim()&&d.push(f)}return d.length>0?{blocked:!0,reason:d.every(u=>a.has(u))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${d.join(", ")}`}:{blocked:!1}}function Te(e){if(e.blocked)return e.detail??e.reason}var Ne=c(()=>{"use strict";G()});function jr(e){let r=Date.now();if(e.completionBlocker&&!Ue(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&Yr(e.finalResult))return{state:"done",reason:"local-only worker superseded by merged PR"};let o={finalResult:e.finalResult,changedFiles:e.changedFiles??[],gitAncestry:e.gitAncestry??null,prUrl:e.prUrl??null},s=ve(o);if(s.blocked){let i=Ce(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=Be({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Te(i);if(a)return{state:"needs_attention",reason:i.reason?`landing contract (${i.reason}): ${a}`:`landing contract: ${a}`}}return{state:"done",reason:"final result recorded"}}if(!e.alive){if(Gr(e))return{state:"done",reason:"empty abandoned worker record"};let o=he(e.error);if(o)return{state:"blocked",reason:o.reason};let s=be({alive:!1,finalResult:null,changedFiles:e.changedFiles,gitAncestry:e.gitAncestry});if(s?.salvageable){let a=e.error?.trim();return{state:"needs_attention",reason:a?`${s.attentionReason} (${a})`:s.attentionReason}}let i=e.error?.trim();return{state:"needs_attention",reason:i?`process exited without a final result: ${i}`:s?.attentionReason??"process exited without a final result"}}if(e.heartbeatBlocker)return{state:"blocked",reason:`worker heartbeat reported blocker: ${e.heartbeatBlocker}`};let t=e.startedAt?Date.parse(e.startedAt):NaN;if(!e.firstEventAt&&e.stdoutBytes===0&&e.heartbeatBytes===0&&Number.isFinite(t)&&r-t>Lr)return{state:"needs_attention",reason:`no first stream event ${K(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>W?{state:"stale",reason:`no log/event/heartbeat activity for ${K(n)}s`}:{state:"ok",reason:"recent activity"}}function Ue(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function Gr(e){return e.finalResult||e.taskId||e.agentOsId||e.stdoutBytes>0||(e.stderrBytes??0)>0||e.heartbeatBytes>0||e.error?.trim()||(e.changedFiles??[]).some(r=>r.trim())?!1:/empty worker dir|marked abandoned/i.test(e.reconcileReason??"")}function Yr(e){let r=null;if(typeof e=="string"?r=P(e):e&&typeof e=="object"&&!Array.isArray(e)&&(r=e),!r)return!1;let t=r.targetPrReconciliation??r.target_pr_reconciliation;return Array.isArray(t)?t.some(n=>!n||typeof n!="object"||Array.isArray(n)?!1:String(n.outcome??"").trim()==="merged"):!1}function Vr(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??ie(t))}function Ie(e,r={}){let t=ge(e.stdoutPath),n=ae(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=Vr(e,t.finalResult,n),i=o?!1:C(e.pid),a=A(e.stdoutPath),l=A(e.stderrPath),m=A(e.heartbeatPath),d=Ee(e.worktreePath),u=Ae(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),f=oe([t.lastEventAt,n.lastHeartbeatAt,v(e.stdoutPath),v(e.stderrPath),v(e.heartbeatPath)]),h=t.error||!i&&!s&&ne(e.stderrPath,10).trim()||void 0,p=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,k=Ue(p)?null:p,Xe=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,N=jr({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:l,heartbeatBytes:m,lastActivityAt:f,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:h,changedFiles:d,gitAncestry:u,completionBlocker:k,landingContract:Xe,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),Qe=k||N.state==="blocked"?"blocked":o||N.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:Qe,attention:N,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:l,heartbeatBytes:m,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:f,currentTool:o?null:t.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:s,error:h,changedFiles:d,gitAncestry:u,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.orchestrationAudit?.provider??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function Ke(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function He(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var Lr,W,_=c(()=>{"use strict";le();pe();ke();Re();L();we();Ne();G();g();Lr=18e4,W=6e5});var B=c(()=>{"use strict"});var De=c(()=>{"use strict";L();B()});var Y=c(()=>{"use strict"});var Le=c(()=>{"use strict"});var cn,un,je=c(()=>{"use strict";cn=25*1024*1024*1024,un=12*1024*1024*1024});var gn,pn,V=c(()=>{"use strict";je();gn=30*1024*1024*1024,pn=15*1024*1024*1024});var Ge=c(()=>{"use strict";T();g()});var Ye=c(()=>{"use strict";_()});var rt,tt,Ve=c(()=>{"use strict";Le();q();Y();J();V();T();Ge();Ye();g();rt=500*1024*1024,tt=4*1024*1024*1024});var J=c(()=>{"use strict";Ve()});import{homedir as ot,totalmem as Zn}from"node:os";import X from"node:path";var ze,ao,lo,co,uo,q=c(()=>{"use strict";De();B();g();Y();J();V();ze=X.join(ot(),".kynver"),ao=X.join(ze,"config.json"),lo=X.join(ze,"credentials"),co=500*1024*1024,uo=4*1024*1024*1024});import{homedir as st}from"node:os";import it from"node:path";var yo,Je=c(()=>{"use strict";q();B();g();yo=it.join(st(),".openclaw","harness")});var T=c(()=>{"use strict";Je();g()});_();var Me="kynver-harness:",zr="@runner:";function Fe(e){return e?.trim()?e.trim():null}function Jr(e){let r=Fe(e);if(!r?.startsWith(Me))return null;let t=r.slice(Me.length),n=t.indexOf(zr);return n>=0?t.slice(0,n).trim()||null:t.trim()||null}function $e(e,r){let t=Fe(r);return t?Jr(e)===t:!1}_();g();function qr(e){let{worker:r,status:t,taskLease:n}=e,o=n?.leaseOwner??null;if(r.dispatched&&n){if(n.status==="running"&&o&&!$e(o,r.runId))return{health:"orphaned",reason:`task lease held by ${o}, expected harness run ${r.runId}`};if(n.status==="running"&&!t.alive&&!t.finalResult)return{health:"orphaned",reason:"board task running but worker process is not alive"}}if(r.status==="running"&&!t.alive&&!t.finalResult)return{health:"orphaned",reason:"worker.json still running but process is dead"};if(t.attention.state==="stale")return{health:"stale",reason:t.attention.reason};let s=t.lastHeartbeatAt?Date.parse(t.lastHeartbeatAt):NaN;return t.alive&&Number.isFinite(s)&&Date.now()-s>W?{health:"stale",reason:`heartbeat older than ${Math.floor(W/1e3)}s`}:t.alive&&r.pid&&!C(r.pid)?{health:"orphaned",reason:"pid recorded but process is not alive"}:n?.status==="running"&&!t.alive&&t.finalResult?{health:"healthy",reason:"finished worker awaiting completion replay"}:{health:"healthy",reason:t.attention.reason||"worker within expected lifecycle bounds"}}T();function qe(e){return!!e.completionReportedAt?.trim()}_();function at(e){let{worker:r,status:t}=e,n=[];r.localOnly&&n.push("local-only worker (no board linkage)"),(!r.agentOsId||!r.taskId)&&n.push("missing agentOsId/taskId linkage"),qe(r)&&n.push("completion already acknowledged"),r.completionBlocker&&n.push(r.completionBlocker),t.heartbeatBlocker&&t.alive&&n.push(`worker heartbeat blocker: ${t.heartbeatBlocker}`),t.attention.state==="blocked"&&n.push(t.attention.reason||"worker attention blocked"),He(t)&&n.push(t.attention.reason||"landing gate blocked");let o=Ke(t),s;return o?t.finalResult?s="final_result":t.alive?s="terminal_status":s="process_exited":n.push("worker has not reached a terminal condition"),{eligible:o&&n.length===0,terminalVerified:o,terminalReason:s,blockers:n}}export{at as assessAutoCompleteEligibility,qr as classifyWorkerHealth,Ie as computeWorkerStatus};
|
|
6
|
+
${e.stderr}`.trim(),t=yr(r);if(!t||!x(t)){let o=R(r||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit failed (invalid or missing JSON): ${o}`,parseError:"invalid_json"}}if(x(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${_r(t,e.stderr)}`};let n=Rr(t);return n?e.exitCode===0&&n.total===0?{kind:"success",exitCode:0,summary:"npm audit: no vulnerabilities reported",audit:n}:{kind:"audit_findings",exitCode:e.exitCode,summary:xr(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function Cr(e){return hr.test(e)}function Er(e){return br.test(e)}function Ar(e){let r=F({command:e.command,exitCode:e.exitCode});if(e.exitCode===0)return{kind:"success",exitCode:0,summary:"ripgrep finished (exit 0)"};if(e.exitCode===1){let n=(e.stderr||e.interleaved).trim();if(n&&kr.test(n)){let i=R(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=K(e.command),s=o.changed&&!r?` Retry with: \`${o.command}\`.`:"";return{kind:"search_no_matches",exitCode:1,summary:r??`ripgrep: no matches (exit 1).${s} Try a broader pattern or search from the repo root.`}}let t=R(e.interleaved||e.stdout||e.stderr||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:r??`ripgrep failed (exit ${e.exitCode}): ${t}`}}function fe(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(Cr(e.command)){let i=r.trim()||n.trim()||t.trim();return Sr({exitCode:e.exitCode,stdout:i,stderr:t})}if(Er(e.command))return Ar({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let o=F({command:e.command,exitCode:e.exitCode});if(o&&e.exitCode!==0)return{kind:"command_failure",exitCode:e.exitCode,summary:o};if(e.exitCode===0)return{kind:"success",exitCode:0,summary:"command succeeded (exit 0)"};let s=R(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var hr,br,kr,pe=c(()=>{"use strict";me();hr=/\bnpm\s+audit\b/i,br=/\b(rg|ripgrep)\b/i,kr=/\b(error|invalid|unknown|panic|not found)\b/i});import{existsSync as vr,readFileSync as wr}from"node:fs";function Wr(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function Or(e){if(!e)return null;for(let r of Object.keys(e))if(r.endsWith("ToolCall")){let t=r.slice(0,-8);return t.length?t:r}return null}function Pr(e,r){e.finalResult=r.result||r.subtype||r.terminal_reason||"completed",r.is_error&&(e.error=String(r.result||r.api_error_status||"stream result error"))}function Br(e){if(e.type!=="tool_call"||e.subtype!=="completed")return null;let t=(e.tool_call&&typeof e.tool_call=="object"&&!Array.isArray(e.tool_call)?e.tool_call:null)?.shellToolCall;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,o=n.args,s=o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.command=="string"?String(o.command):"",i=n.result;if(!i||typeof i!="object"||Array.isArray(i))return null;let a=i.success??i.failure;if(!a||typeof a!="object"||Array.isArray(a))return null;let l=a,m=typeof l.exitCode=="number"?l.exitCode:0;return{command:s,exitCode:m,stdout:typeof l.stdout=="string"?l.stdout:"",stderr:typeof l.stderr=="string"?l.stderr:"",interleaved:typeof l.interleavedOutput=="string"?l.interleavedOutput:""}}function Tr(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function ge(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null};if(!vr(e))return r;let t=wr(e,"utf8").split(`
|
|
7
|
+
`).filter(Boolean);for(let n of t){let o=C(n);if(!o)continue;let s=Wr(o);if(s&&(r.firstEventAt||=s,r.lastEventAt=s),o.type==="stream_event"&&o.event&&typeof o.event=="object"&&o.event.type==="content_block_start"){let a=o.event.content_block;a?.type==="tool_use"&&(r.currentTool=String(a.name||"tool"))}if(o.type==="assistant"&&o.message&&typeof o.message=="object"){let a=o.message.content;if(Array.isArray(a)){let l=a.find(m=>m?.type==="tool_use");l&&(r.currentTool=String(l.name||r.currentTool))}}if(o.type==="tool_call"&&o.subtype==="started"){let a=o.tool_call&&typeof o.tool_call=="object"&&!Array.isArray(o.tool_call)?o.tool_call:void 0,l=Or(a);l&&(r.currentTool=l)}let i=Br(o);i&&Tr(r,fe({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&Pr(r,o)}return r}var he=c(()=>{"use strict";pe();p()});function Ur(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function be(e){let r=(e??"").trim();if(!r)return null;for(let t of Nr)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${Ur(r)}`};return null}var Nr,ke=c(()=>{"use strict";Nr=[{test:/\b(?:invalid|unknown|unsupported|unrecognized)\b[^.\n]*\bmodel\b/i,label:"provider rejected the requested model"},{test:/\bmodel\b[^.\n]*\b(?:not\s+(?:found|supported|available|recognized|valid)|is\s+not\s+valid|does\s+not\s+exist)/i,label:"provider rejected the requested model"},{test:/\b(?:did you mean|available models|choose (?:a|one of)|supported models)\b/i,label:"provider rejected the requested model"},{test:/model preflight failed/i,label:"model/provider preflight failed"},{test:/\b(?:command not found|ENOENT|is the .*CLI on PATH|executable not found|no such file or directory)\b/i,label:"provider CLI is missing or not on PATH"},{test:/\bfailed to spawn\b/i,label:"provider failed to spawn the worker process"},{test:/\b(?:not logged in|unauthorized|authentication (?:failed|required)|invalid api key|missing api key|401)\b/i,label:"provider authentication failed"}]});function ye(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Dr(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function Ir(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:ye(e.head)}function Mr(e,r,t){let n=["exited_with_changes_salvage"];if((e==="uncommitted"||e==="both")&&n.push(`${r} uncommitted change${r===1?"":"s"} with no final result`),(e==="committed_ahead"||e==="both")&&t){let o=t.length>12?t.slice(0,12):t;n.push(`commit ${o} ahead of base with no final result`)}return n.push("review worktree \u2014 commit, open a PR, or run a salvage worker before discarding"),n.join(": ")}function Re(e){if(e.alive||Dr(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=ye(e.headCommit)??Ir(e.gitAncestry),n=r>0,o=!!t;if(!n&&!o)return{kind:"none",salvageable:!1,uncommittedCount:0,headCommit:null,attentionReason:"process exited without a final result"};let s=n&&o?"both":n?"uncommitted":"committed_ahead";return{kind:s,salvageable:!0,uncommittedCount:r,headCommit:t,attentionReason:Mr(s,r,t)}}var xe=c(()=>{"use strict"});var Hr,Ot,_e=c(()=>{"use strict";Hr=["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"],Ot=new Set(Hr)});import{spawnSync as Ce}from"node:child_process";function Kr(e,r,t={}){let n=Ce("git",r,D({cwd:e,encoding:"utf8"}));if(n.status!==0&&!t.allowFailure){let o=`git ${r.join(" ")} failed: ${n.stderr||n.stdout}`;if(t.throwError)throw new Error(o);ne(o)}return n.stdout||""}function Ee(e){return Kr(e,["status","--short"],{allowFailure:!0}).split(`
|
|
8
|
+
`).map(r=>r.trim()).filter(Boolean)}function w(e,r){try{let t=Ce("git",r,D({cwd:e,encoding:"utf8"}));return{status:t.status,stdout:t.stdout||"",stderr:t.stderr||"",error:t.error?t.error.message:null}}catch(t){return{status:null,stdout:"",stderr:"",error:t.message}}}function Se(e,r,t){let n=w(e,["merge-base","--is-ancestor",r,t]);return n.status===0?{isAncestor:!0,error:null}:n.status===1?{isAncestor:!1,error:null}:{isAncestor:null,error:n.error||n.stderr||n.stdout||`git exited ${n.status}`}}function Ae(e,r="origin/main"){let t=typeof r=="string"?{base:r}:r,n=t.baseCommit?.trim()||t.base?.trim()||"origin/main",o=t.baseCommit?.trim()||null;if(!e)return $(n,"missing worktree path");let s=w(e,["rev-parse","HEAD"]);if(s.status!==0)return $(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let f=w(e,["rev-parse",n]);if(f.status!==0)return $(n,f.error||f.stderr||f.stdout||`failed to resolve ${n}`,s.stdout.trim());i=f.stdout.trim()}let a=s.stdout.trim();if(a===i)return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let l=Se(e,i,a),m=Se(e,a,i),d=l.error||m.error||void 0;if(l.isAncestor==null||m.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:m.isAncestor,relation:"unknown",...d?{error:d}:{}};let u=l.isAncestor?"ahead":m.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:m.isAncestor,relation:u,...d?{error:d}:{}}}function $(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var L=c(()=>{"use strict";p();_e()});function _(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Fr(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function $r(e){if(_(e.headCommit)||_(e.prUrl)||_(e.artifactBundlePath)||_(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&_(r.head))}function ve(e){return Fr(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:$r(e)?{blocked:!0,detail:`Worktree has ${e.changedFiles.length} uncommitted change(s); commit or discard before landing`}:{blocked:!0,reason:"dirty_worktree_no_pr",detail:`Worktree has ${e.changedFiles.length} uncommitted change(s) with no commit or PR; commit, open a PR, or discard before landing`}:{blocked:!1}}function we(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var We=c(()=>{"use strict"});function j(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let t=JSON.parse(r);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return null}return null}function Oe(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function W(e){let r=e.trim();if(!r)return null;let t=j(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let d=j(s[1]??"");d&&n.push(d)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let d=j(r.slice(i,a+1));d&&n.push(d)}if(n.length===0)return null;let l=n[n.length-1],m=Oe(l);for(let d of n){let u=Oe(d);u>m&&(l=d,m=u)}return l}var Y=c(()=>{"use strict"});function y(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Lr(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function k(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:y(e)}function O(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Pe(e){let r=null;if(typeof e=="string"){let o=W(e);o&&(r=o)}else e&&typeof e=="object"&&!Array.isArray(e)&&(r=e);if(!r)return[];let t=r.targetPrReconciliation??r.target_pr_reconciliation;if(!Array.isArray(t))return[];let n=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=k(String(s.prUrl??s.pr_url??"")),a=y(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:y(s.mergeCommit??s.merge_commit),reason:y(s.reason)})}return n}function Be(e,r){let t=[],n=k(y(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=k(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function Te(e){let{contract:r,snapshot:t}=e,n=e.finalResult??t.finalResult;if(!r.landingOnly&&r.targetPrUrls.length===0&&!r.repairEnforceOriginalPr)return{blocked:!1};if(!Lr(n))return(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&r.targetPrUrls.length>0?{blocked:!0,reason:"missing_target_pr_reconciliation",detail:`Final result required to reconcile target PR(s): ${r.targetPrUrls.join(", ")}`}:{blocked:!1};if(!(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&!r.repairEnforceOriginalPr)return{blocked:!1};let s=r.repairEnforceOriginalPr?k(y(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?k(r.targetPrUrls[0]):null):null;if(s){let u=Be(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let b of u)if(b!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${b} instead of canonical target ${s}`}}let g=Pe(n).find(b=>b.prUrl===s);if(!g||g.outcome!=="merged"&&!(g.reason?.trim()&&(g.outcome==="skipped"||g.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=Pe(n),a=new Map(i.map(u=>[O(u.prUrl),u])),l=new Set(r.targetPrUrls.map(u=>O(k(u)??u)).filter(Boolean)),m=Be(t,n);if(r.landingOnly)for(let u of m){if(l.size>0&&!l.has(O(u)))return{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${u}`};if(l.size===0)return{blocked:!0,reason:"unrelated_implementation_pr",detail:"Landing-only worker must not open new implementation PRs"}}if(r.targetPrUrls.length===0)return{blocked:!1};let d=[];for(let u of r.targetPrUrls){let f=O(k(u)??u),h=a.get(f);if(!h){d.push(f);continue}h.outcome!=="merged"&&!h.reason?.trim()&&d.push(f)}return d.length>0?{blocked:!0,reason:d.every(u=>a.has(u))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${d.join(", ")}`}:{blocked:!1}}function Ne(e){if(e.blocked)return e.detail??e.reason}var Ue=c(()=>{"use strict";Y()});function Yr(e){let r=Date.now();if(e.completionBlocker&&!De(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&Vr(e.finalResult))return{state:"done",reason:"local-only worker superseded by merged PR"};let o={finalResult:e.finalResult,changedFiles:e.changedFiles??[],gitAncestry:e.gitAncestry??null,prUrl:e.prUrl??null},s=ve(o);if(s.blocked){let i=we(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=Te({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Ne(i);if(a)return{state:"needs_attention",reason:i.reason?`landing contract (${i.reason}): ${a}`:`landing contract: ${a}`}}return{state:"done",reason:"final result recorded"}}if(!e.alive){if(Gr(e))return{state:"done",reason:"empty abandoned worker record"};let o=be(e.error);if(o)return{state:"blocked",reason:o.reason};let s=Re({alive:!1,finalResult:null,changedFiles:e.changedFiles,gitAncestry:e.gitAncestry});if(s?.salvageable){let a=e.error?.trim();return{state:"needs_attention",reason:a?`${s.attentionReason} (${a})`:s.attentionReason}}let i=e.error?.trim();return{state:"needs_attention",reason:i?`process exited without a final result: ${i}`:s?.attentionReason??"process exited without a final result"}}if(e.heartbeatBlocker)return{state:"blocked",reason:`worker heartbeat reported blocker: ${e.heartbeatBlocker}`};let t=e.startedAt?Date.parse(e.startedAt):NaN;if(!e.firstEventAt&&e.stdoutBytes===0&&e.heartbeatBytes===0&&Number.isFinite(t)&&r-t>jr)return{state:"needs_attention",reason:`no first stream event ${I(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>P?{state:"stale",reason:`no log/event/heartbeat activity for ${I(n)}s`}:{state:"ok",reason:"recent activity"}}function De(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function Gr(e){return e.finalResult||e.taskId||e.agentOsId||e.stdoutBytes>0||(e.stderrBytes??0)>0||e.heartbeatBytes>0||e.error?.trim()||(e.changedFiles??[]).some(r=>r.trim())?!1:/empty worker dir|marked abandoned/i.test(e.reconcileReason??"")}function Vr(e){let r=null;if(typeof e=="string"?r=W(e):e&&typeof e=="object"&&!Array.isArray(e)&&(r=e),!r)return!1;let t=r.targetPrReconciliation??r.target_pr_reconciliation;return Array.isArray(t)?t.some(n=>!n||typeof n!="object"||Array.isArray(n)?!1:String(n.outcome??"").trim()==="merged"):!1}function zr(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??ae(t))}function Ie(e,r={}){let t=ge(e.stdoutPath),n=le(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=zr(e,t.finalResult,n),i=o?!1:v(e.pid),a=E(e.stdoutPath),l=E(e.stderrPath),m=E(e.heartbeatPath),d=Ee(e.worktreePath),u=Ae(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),f=se([t.lastEventAt,n.lastHeartbeatAt,A(e.stdoutPath),A(e.stderrPath),A(e.heartbeatPath)]),h=t.error||!i&&!s&&oe(e.stderrPath,10).trim()||void 0,g=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,b=De(g)?null:g,Qe=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,N=Yr({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:l,heartbeatBytes:m,lastActivityAt:f,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:h,changedFiles:d,gitAncestry:u,completionBlocker:b,landingContract:Qe,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),Ze=b||N.state==="blocked"?"blocked":o||N.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:Ze,attention:N,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:l,heartbeatBytes:m,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:f,currentTool:o?null:t.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:s,error:h,changedFiles:d,gitAncestry:u,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.orchestrationAudit?.provider??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function Me(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function He(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var jr,P,S=c(()=>{"use strict";ce();he();ke();xe();L();We();Ue();Y();p();jr=18e4,P=6e5});var B=c(()=>{"use strict"});var Le=c(()=>{"use strict";L();B()});var G=c(()=>{"use strict"});var je=c(()=>{"use strict"});var un,dn,V=c(()=>{"use strict";un=25*1024*1024*1024,dn=12*1024*1024*1024});var hn,bn,Ye=c(()=>{"use strict";V();hn=5*1024*1024*1024,bn=10*1024*1024*1024});var Sn,Cn,z=c(()=>{"use strict";Ye();V();Sn=30*1024*1024*1024,Cn=15*1024*1024*1024});var Ge=c(()=>{"use strict";T();p()});var Ve=c(()=>{"use strict";S()});var tt,nt,ze=c(()=>{"use strict";je();X();G();q();z();T();Ge();Ve();p();tt=500*1024*1024,nt=4*1024*1024*1024});var q=c(()=>{"use strict";ze()});import{homedir as st,totalmem as co}from"node:os";import Q from"node:path";var Je,ko,yo,Ro,xo,X=c(()=>{"use strict";Le();B();p();G();q();z();Je=Q.join(st(),".kynver"),ko=Q.join(Je,"config.json"),yo=Q.join(Je,"credentials"),Ro=500*1024*1024,xo=4*1024*1024*1024});import{homedir as it}from"node:os";import at from"node:path";var wo,qe=c(()=>{"use strict";X();B();p();wo=at.join(it(),".openclaw","harness")});var T=c(()=>{"use strict";qe();p()});S();var Ke="kynver-harness:",Jr="@runner:";function Fe(e){return e?.trim()?e.trim():null}function qr(e){let r=Fe(e);if(!r?.startsWith(Ke))return null;let t=r.slice(Ke.length),n=t.indexOf(Jr);return n>=0?t.slice(0,n).trim()||null:t.trim()||null}function $e(e,r){let t=Fe(r);return t?qr(e)===t:!1}S();p();function Xr(e){let{worker:r,status:t,taskLease:n}=e,o=n?.leaseOwner??null;if(r.dispatched&&n){if(n.status==="running"&&o&&!$e(o,r.runId))return{health:"orphaned",reason:`task lease held by ${o}, expected harness run ${r.runId}`};if(n.status==="running"&&!t.alive&&!t.finalResult)return{health:"orphaned",reason:"board task running but worker process is not alive"}}if(r.status==="running"&&!t.alive&&!t.finalResult)return{health:"orphaned",reason:"worker.json still running but process is dead"};if(t.attention.state==="stale")return{health:"stale",reason:t.attention.reason};let s=t.lastHeartbeatAt?Date.parse(t.lastHeartbeatAt):NaN;return t.alive&&Number.isFinite(s)&&Date.now()-s>P?{health:"stale",reason:`heartbeat older than ${Math.floor(P/1e3)}s`}:t.alive&&r.pid&&!v(r.pid)?{health:"orphaned",reason:"pid recorded but process is not alive"}:n?.status==="running"&&!t.alive&&t.finalResult?{health:"healthy",reason:"finished worker awaiting completion replay"}:{health:"healthy",reason:t.attention.reason||"worker within expected lifecycle bounds"}}T();function Xe(e){return!!e.completionReportedAt?.trim()}S();function lt(e){let{worker:r,status:t}=e,n=[];r.localOnly&&n.push("local-only worker (no board linkage)"),(!r.agentOsId||!r.taskId)&&n.push("missing agentOsId/taskId linkage"),Xe(r)&&n.push("completion already acknowledged"),r.completionBlocker&&n.push(r.completionBlocker),t.heartbeatBlocker&&t.alive&&n.push(`worker heartbeat blocker: ${t.heartbeatBlocker}`),t.attention.state==="blocked"&&n.push(t.attention.reason||"worker attention blocked"),He(t)&&n.push(t.attention.reason||"landing gate blocked");let o=Me(t),s;return o?t.finalResult?s="final_result":t.alive?s="terminal_status":s="process_exited":n.push("worker has not reached a terminal condition"),{eligible:o&&n.length===0,terminalVerified:o,terminalReason:s,blockers:n}}export{lt as assessAutoCompleteEligibility,Xr as classifyWorkerHealth,Ie as computeWorkerStatus};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var n=(e,r)=>()=>(e&&(r=e(e=0)),r);function I(e){return
|
|
1
|
+
var n=(e,r)=>()=>(e&&(r=e(e=0)),r);function I(e){return Ie.has(e)?!0:Be.some(r=>e.endsWith(r))}function Q(e){return Object.keys(e).filter(I).sort()}function p(e){let r={...e};for(let t of Object.keys(r))I(t)&&delete r[t];return r}function Ne(e){let r=Q(e);return{forbiddenPresent:r,safe:r.length===0}}var we,Ie,Be,d=n(()=>{"use strict";we=["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"],Ie=new Set(we),Be=["_SECRET","_API_KEY"]});function B(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}var a=n(()=>{"use strict"});var W=n(()=>{"use strict";a();d()});var v=n(()=>{"use strict"});var Z=n(()=>{"use strict";W();v()});var D=n(()=>{"use strict"});var ee=n(()=>{"use strict"});var Hr,Kr,T=n(()=>{"use strict";Hr=25*1024*1024*1024,Kr=12*1024*1024*1024});var Yr,Gr,re=n(()=>{"use strict";T();Yr=5*1024*1024*1024,Gr=10*1024*1024*1024});var Zr,et,M=n(()=>{"use strict";re();T();Zr=30*1024*1024*1024,et=15*1024*1024*1024});import{homedir as De}from"node:os";import Te from"node:path";var at,te=n(()=>{"use strict";k();v();a();at=Te.join(De(),".openclaw","harness")});var F=n(()=>{"use strict";te();a()});var oe=n(()=>{"use strict";F();a()});var ie=n(()=>{"use strict"});var se=n(()=>{"use strict";ie();a()});var ae=n(()=>{"use strict"});var le=n(()=>{"use strict";ae()});var ce=n(()=>{"use strict";le();a()});var ue=n(()=>{"use strict"});var de=n(()=>{"use strict"});var me=n(()=>{"use strict"});var H=n(()=>{"use strict"});var pe=n(()=>{"use strict";H()});var fe=n(()=>{"use strict";se();ce();ue();de();W();me();pe();H();a()});var ge=n(()=>{"use strict";fe()});var Le,$e,he=n(()=>{"use strict";ee();k();D();K();M();F();oe();ge();a();Le=500*1024*1024,$e=4*1024*1024*1024});var K=n(()=>{"use strict";he()});import{homedir as je,totalmem as zn}from"node:os";import L from"node:path";var ye,to,no,oo,io,k=n(()=>{"use strict";Z();v();a();D();K();M();ye=L.join(je(),".kynver"),to=L.join(ye,"config.json"),no=L.join(ye,"credentials"),oo=500*1024*1024,io=4*1024*1024*1024});d();k();d();a();d();a();d();a();var ei=process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||"gpt-5.4";function qe(){return process.env.KYNVER_CODEX_DEFAULT_MODEL?.trim()||"gpt-5.4"}var Je=qe();var ke="composer-2.5";var u="cursor",Xe=new Set(["claude","opus","anthropic"]),Qe=[/\[worker-provider:\s*claude\]/i,/\[use-claude-worker\]/i,/\[operator-worker-provider:\s*claude\]/i];function j(e,r){let t=e[r];return typeof t=="string"?t.trim():""}function l(e){if(!e?.trim())return!1;let r=e.trim().toLowerCase();return Xe.has(r)?!0:r.includes("claude")||r.includes("opus")}function $(e){if(!e)return!1;let r=e.workerProviderOverride;if(typeof r=="string"&&l(r))return!0;let t=j(e,"executorRef").toLowerCase();if(t==="provider:claude"||t.startsWith("provider:claude:")||t.includes("claude-worker-override")||t.includes("operator-claude"))return!0;let i=j(e,"description");if(Qe.some(s=>s.test(i)))return!0;let o=j(e,"title");return!!/\[use-claude-worker\]/i.test(o)}function Ze(e,r){return{provider:u,model:ke,rule:`policy:cursor_default${r}`,requestedModel:e}}function Re(e){let{routing:r,task:t}=e,i=e.explicitProvider?.trim().toLowerCase();if(e.explicitProviderIsOperatorOverride&&l(i))return{...r,provider:"claude",rule:r.rule.startsWith("explicit:")?r.rule:"explicit:operator_provider"};if($(t)||r.rule==="explicit:cli"&&l(r.provider)||!l(r.provider))return r;let o=r.rule&&r.rule!=="default:global"?`:${r.rule.replace(/:/g,"_")}`:"";return Ze(r.model,o)}function er(e,r=u){let t=e?.trim();return t?l(t)?u:t==="codex"?"codex":t:r}function rr(e){let r=[...new Set(e.map(t=>t.trim().toLowerCase()).filter(Boolean))];return r.includes(u)?[...new Set(r.map(t=>l(t)?u:t))]:r.every(t=>l(t))?[u]:r}var tr=/\b(npm run typecheck|tsc\b[^|&;]*--noEmit|node scripts\/verify-pr-local\.mjs|kynver (harness )?verify)\b/i,nr=/\b(npm run build\b|next build\b)\b/i,or=/\b(vercel (build|deploy|--prod))\b/i,ir=/\b(openai|anthropic|perplexity|voyage)\b.*\b(api|cli)\b|\b(paid|billable)[-_ ]?compute\b/i;function V(e){let r=e.trim();return r?ir.test(r)?{heavy:!0,commandClass:"paid_compute",reason:"paid external compute requires heavy-verification token and operator approval"}:or.test(r)?{heavy:!0,commandClass:"vercel_verify",reason:"Vercel build/deploy verification requires heavy-verification token"}:nr.test(r)?{heavy:!0,commandClass:"full_build",reason:"full app build requires heavy-verification token"}:tr.test(r)?{heavy:!0,commandClass:"full_typecheck",reason:"full repo typecheck requires heavy-verification token"}:{heavy:!1,commandClass:"allowed",reason:null}:{heavy:!1,commandClass:"allowed",reason:null}}var _="heavy_verification_token_required";import{spawnSync as xr}from"node:child_process";a();import{closeSync as dr,existsSync as G,mkdirSync as mr,openSync as pr,readdirSync as Se,readFileSync as fr,unlinkSync as Ee,writeFileSync as gr}from"node:fs";import q from"node:path";import{mkdirSync as ar}from"node:fs";import{tmpdir as lr}from"node:os";import C from"node:path";import{homedir as sr}from"node:os";import xe from"node:path";function _e(){let e=process.env.KYNVER_STATE_ROOT;return e?xe.resolve(e):xe.join(sr(),".kynver","state")}function cr(){return!!(process.env.VERCEL||process.env.VERCEL_ENV||process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.AWS_EXECUTION_ENV)}function ur(){let e=process.env.KYNVER_HEAVY_VERIFICATION_STATE_ROOT;return e?C.resolve(e):cr()?C.join(lr(),"kynver","state","heavy-verification"):C.join(_e(),"heavy-verification")}function Y(){return C.join(ur(),"slots")}function g(){let e=Y();return ar(e,{recursive:!0}),e}var h=120*6e4,Ce=1;function hr(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function A(){let e=process.env.KYNVER_HEAVY_VERIFICATION_SKIP?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function S(){let e=process.env.KYNVER_HEAVY_VERIFICATION_MAX_CONCURRENT;return e?hr(e,Ce):Ce}function yr(e){return`slot-${e}`}function br(e,r=Y()){return q.join(r,`${e}.json`)}function J(e){if(!G(e))return null;try{let r=JSON.parse(fr(e,"utf8"));if(typeof r.slotId=="string"&&typeof r.pid=="number"&&typeof r.acquiredAt=="string"&&typeof r.command=="string")return r}catch{return null}return null}function E(e,r=h){if(!e||!B(e.pid))return!0;let t=Date.parse(e.acquiredAt);return Number.isNaN(t)?!0:Date.now()-t>r}function vr(e,r){let t=J(e);if(E(t,r))try{Ee(e)}catch{}}function kr(e){return mr(e,{recursive:!0}),e}function X(e={}){let r=kr(e.slotsDir??g()),t=e.staleMs??h,i=0;for(let o of Se(r)){if(!o.endsWith(".json"))continue;let s=q.join(r,o),c=G(s);vr(s,t),c&&!G(s)&&(i+=1)}return i}function Rr(e={}){let r=e.slotsDir??g(),t=e.staleMs??h;X({slotsDir:r,staleMs:t});let i=[];for(let o of Se(r)){if(!o.endsWith(".json"))continue;let s=J(q.join(r,o));s&&!E(s,t)&&i.push(s)}return i}function z(e={}){return Rr(e).length}function y(e,r={}){if(A())return{admitted:!0,slotId:null,activeSlots:0,maxSlots:S(),reason:null};let t=r.slotsDir??g(),i=r.staleMs??h,o=r.maxSlots??S();X({slotsDir:t,staleMs:i});for(let c=0;c<o;c+=1){let P=yr(c),w=br(P,t),b=J(w);if(b&&E(b,i))try{Ee(w)}catch{}else if(b&&!E(b,i))continue;let Oe={slotId:P,pid:process.pid,acquiredAt:new Date().toISOString(),command:e};try{let m=pr(w,"wx");gr(m,JSON.stringify(Oe,null,2),"utf8"),dr(m);let Pe=z({slotsDir:t,staleMs:i});return{admitted:!0,slotId:P,activeSlots:Pe,maxSlots:o,reason:null}}catch(m){if(m.code==="EEXIST")continue;throw m}}let s=z({slotsDir:t,staleMs:i});return{admitted:!1,slotId:null,activeSlots:s,maxSlots:o,reason:`heavy verification at capacity (${s}/${o} slots)`}}function O(e,r={}){if(A())return{admitted:!0,slotId:null,activeSlots:0,maxSlots:S(),reason:null};let t=r.slotsDir??g(),i=r.staleMs??h,o=r.maxSlots??S();X({slotsDir:t,staleMs:i});let s=z({slotsDir:t,staleMs:i}),c=s<o;return{admitted:c,slotId:null,activeSlots:s,maxSlots:o,reason:c?null:`heavy verification at capacity (${s}/${o} slots); waiting for ${e}`}}function _r(e){e<=0||xr(process.execPath,["-e",`const d=Date.now()+${Math.floor(e)};while(Date.now()<d);`],{stdio:"ignore"})}function Ae(e,r,t=2e3,i={}){let o=Date.now()+Math.max(0,r),s=y(e,i);for(;!s.admitted&&Date.now()<o;)_r(Math.min(t,o-Date.now())),s=y(e,i);return s}function Cr(e,r={}){let t=V(e);if(!t.heavy)return{allowed:!0,outcome:"allowed",commandClass:t.commandClass,reason:"command does not require heavy-verification token",verificationGate:{...O(e),slotId:null}};if(A())return{allowed:!0,outcome:"heavy_verification_skipped",commandClass:t.commandClass,reason:"KYNVER_HEAVY_VERIFICATION_SKIP bypasses gate",verificationGate:{...O(e),slotId:null}};let i=r.waitMs??0,o=i>0?Ae(e,i,r.pollMs):y(e);return o.admitted?{allowed:!0,outcome:"allowed",commandClass:t.commandClass,reason:t.reason??"heavy-verification token acquired",verificationGate:o}:{allowed:!1,outcome:_,commandClass:t.commandClass,reason:t.reason??o.reason??_,verificationGate:o}}export{u as DEFAULT_WORKER_PROVIDER,_ as HEAVY_VERIFICATION_TOKEN_REQUIRED,Ne as auditWorkerEnv,V as classifyHeavyShellCommand,Re as enforceCursorWorkerProvider,Cr as gateWorkerShellCommand,l as isClaudeFamilyProvider,I as isForbiddenWorkerEnvKey,Q as listForbiddenWorkerEnvKeys,rr as preferCursorExecutor,er as resolveConfiguredWorkerProvider,p as scrubWorkerEnv,$ as taskAllowsClaudeWorker};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type WslCrashDumpObservation } from "./wsl-crash-dumps.js";
|
|
2
|
+
export interface WslCrashDumpCleanupResult {
|
|
3
|
+
observation: WslCrashDumpObservation | null;
|
|
4
|
+
execute: boolean;
|
|
5
|
+
keepNewest: number;
|
|
6
|
+
removed: Array<{
|
|
7
|
+
path: string;
|
|
8
|
+
bytes: number;
|
|
9
|
+
name: string;
|
|
10
|
+
}>;
|
|
11
|
+
removedBytes: number;
|
|
12
|
+
skipped: Array<{
|
|
13
|
+
path: string;
|
|
14
|
+
reason: string;
|
|
15
|
+
}>;
|
|
16
|
+
}
|
|
17
|
+
export interface WslCrashDumpCleanupOptions {
|
|
18
|
+
execute?: boolean;
|
|
19
|
+
/** Keep this many newest dumps; remove the rest when execute=true. */
|
|
20
|
+
keepNewest?: number;
|
|
21
|
+
/** When true, remove all dumps regardless of keepNewest (operator purge). */
|
|
22
|
+
purgeAll?: boolean;
|
|
23
|
+
forceWsl?: boolean;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Prune Windows-side WSL crash dumps. Dry-run by default; pass execute=true
|
|
27
|
+
* or `KYNVER_WSL_CRASH_DUMP_EXECUTE=1` to unlink files.
|
|
28
|
+
*/
|
|
29
|
+
export declare function cleanupWslCrashDumps(options?: WslCrashDumpCleanupOptions): WslCrashDumpCleanupResult;
|
|
30
|
+
/** True when automatic cleanup should run during harness retention sweeps. */
|
|
31
|
+
export declare function shouldAutoCleanupWslCrashDumps(observation: WslCrashDumpObservation | null): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runWslCrashesCli(args: Record<string, string | boolean>): void;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** Default total bytes in wsl-crashes before the observer flags warning (5 GiB). */
|
|
2
|
+
export declare const DEFAULT_WSL_CRASH_DUMP_WARN_BYTES: number;
|
|
3
|
+
/** Default total bytes before critical — ~4× typical 2.2 GiB node dump (10 GiB). */
|
|
4
|
+
export declare const DEFAULT_WSL_CRASH_DUMP_CRITICAL_BYTES: number;
|
|
5
|
+
/** Default dump count before warning. */
|
|
6
|
+
export declare const DEFAULT_WSL_CRASH_DUMP_WARN_COUNT = 2;
|
|
7
|
+
/** Default dump count before critical. */
|
|
8
|
+
export declare const DEFAULT_WSL_CRASH_DUMP_CRITICAL_COUNT = 4;
|
|
9
|
+
export interface WslCrashDumpFile {
|
|
10
|
+
name: string;
|
|
11
|
+
path: string;
|
|
12
|
+
bytes: number;
|
|
13
|
+
mtimeMs: number;
|
|
14
|
+
/** Best-effort executable hint parsed from the WSL dump filename. */
|
|
15
|
+
executableHint: string | null;
|
|
16
|
+
signal: number | null;
|
|
17
|
+
pid: number | null;
|
|
18
|
+
}
|
|
19
|
+
export interface WslCrashDumpObservation {
|
|
20
|
+
ok: boolean;
|
|
21
|
+
/** Resolved host path (WSL mount) to the wsl-crashes directory. */
|
|
22
|
+
path: string | null;
|
|
23
|
+
windowsUser: string | null;
|
|
24
|
+
dumpCount: number;
|
|
25
|
+
totalBytes: number;
|
|
26
|
+
warnBelowBytes: number;
|
|
27
|
+
criticalBelowBytes: number;
|
|
28
|
+
warnCount: number;
|
|
29
|
+
criticalCount: number;
|
|
30
|
+
/** Newest dumps first. */
|
|
31
|
+
dumps: WslCrashDumpFile[];
|
|
32
|
+
/** Unique executable hints across dumps (e.g. node, cursor, vscode-server). */
|
|
33
|
+
executables: string[];
|
|
34
|
+
/** `kernel.core_pattern` when readable — surfaces wsl-capture-crash vs apport. */
|
|
35
|
+
corePattern: string | null;
|
|
36
|
+
wslCaptureEnabled: boolean;
|
|
37
|
+
/** Parsed MaxCrashDumpCount from %USERPROFILE%/.wslconfig when readable. */
|
|
38
|
+
maxCrashDumpCount: number | null;
|
|
39
|
+
dumpsDisabledInWslConfig: boolean;
|
|
40
|
+
reason: string | null;
|
|
41
|
+
probeError: string | null;
|
|
42
|
+
}
|
|
43
|
+
export interface ObserveWslCrashDumpsOptions {
|
|
44
|
+
forceWsl?: boolean;
|
|
45
|
+
hostMount?: string;
|
|
46
|
+
windowsUser?: string;
|
|
47
|
+
crashDumpDir?: string;
|
|
48
|
+
warnBelowBytes?: number;
|
|
49
|
+
criticalBelowBytes?: number;
|
|
50
|
+
warnCount?: number;
|
|
51
|
+
criticalCount?: number;
|
|
52
|
+
/** Test seam — inject listing instead of reading the filesystem. */
|
|
53
|
+
listDumps?: (dir: string) => WslCrashDumpFile[];
|
|
54
|
+
readCorePattern?: () => string | null;
|
|
55
|
+
readWslConfig?: (windowsUser: string, hostMount: string) => WslConfigCrashDumpSettings | null;
|
|
56
|
+
}
|
|
57
|
+
export interface WslConfigCrashDumpSettings {
|
|
58
|
+
maxCrashDumpCount: number | null;
|
|
59
|
+
crashDumpFolder: string | null;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Resolve the Windows username for the WSL interop mount. Order: explicit env,
|
|
63
|
+
* `cmd.exe echo %USERNAME%`, then Linux user matching `/mnt/c/Users/<user>`.
|
|
64
|
+
*/
|
|
65
|
+
export declare function resolveWslWindowsUsername(): string | null;
|
|
66
|
+
/** Default Windows-side folder: `%LOCALAPPDATA%\\Temp\\wsl-crashes` under the host mount. */
|
|
67
|
+
export declare function resolveWslCrashDumpDir(options?: {
|
|
68
|
+
hostMount?: string;
|
|
69
|
+
windowsUser?: string | null;
|
|
70
|
+
crashDumpDir?: string;
|
|
71
|
+
}): string | null;
|
|
72
|
+
/** Parse WSL dump names like `wsl-crash-1726372480-366-_usr_bin_node-6.dmp`. */
|
|
73
|
+
export declare function parseWslCrashDumpFilename(name: string): {
|
|
74
|
+
executableHint: string | null;
|
|
75
|
+
signal: number | null;
|
|
76
|
+
pid: number | null;
|
|
77
|
+
};
|
|
78
|
+
export declare function readKernelCorePattern(): string | null;
|
|
79
|
+
export declare function isWslCaptureCrashPattern(corePattern: string | null): boolean;
|
|
80
|
+
/** Best-effort parse of `%USERPROFILE%/.wslconfig` crash-dump knobs. */
|
|
81
|
+
export declare function readWslConfigCrashDumpSettings(windowsUser: string, hostMount?: string): WslConfigCrashDumpSettings | null;
|
|
82
|
+
/**
|
|
83
|
+
* Observe Windows-side WSL crash dumps. Returns `null` on non-WSL hosts.
|
|
84
|
+
* When the directory is missing, returns a healthy empty observation.
|
|
85
|
+
*/
|
|
86
|
+
export declare function observeWslCrashDumps(options?: ObserveWslCrashDumpsOptions): WslCrashDumpObservation | null;
|
|
87
|
+
export declare function summarizeWslCrashDumpRecoverySteps(input?: {
|
|
88
|
+
wslCaptureEnabled?: boolean;
|
|
89
|
+
dumpsDisabledInWslConfig?: boolean;
|
|
90
|
+
}): string;
|