@lensmcp/protocol-types 1.26.12 → 1.26.13

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.
Files changed (49) hide show
  1. package/index.d.ts +1 -0
  2. package/index.js +1 -1
  3. package/lib/accounts.d.ts +60 -0
  4. package/lib/accounts.js +1 -0
  5. package/lib/ai-cache-facts.js +1 -1
  6. package/lib/ai-cache-verdict.js +1 -1
  7. package/lib/ai-cache.js +3 -3
  8. package/lib/ai-call-groups.js +2 -2
  9. package/lib/ai-call-row.js +3 -3
  10. package/lib/ai-call.js +9 -9
  11. package/lib/ai-compare.js +3 -3
  12. package/lib/ai-context.js +6 -6
  13. package/lib/ai-origins.js +9 -9
  14. package/lib/ai-together.js +5 -5
  15. package/lib/bounded-clone.js +1 -1
  16. package/lib/bounded-map.js +1 -1
  17. package/lib/bounded-writer.js +1 -1
  18. package/lib/capture-demand.js +1 -1
  19. package/lib/dashboard-path.js +1 -1
  20. package/lib/docker-errors.js +1 -1
  21. package/lib/docker-jobs.js +1 -1
  22. package/lib/docker-report.js +2 -2
  23. package/lib/docker-runs.js +3 -3
  24. package/lib/error-cause.js +6 -6
  25. package/lib/error-dismissal.js +1 -1
  26. package/lib/error-verdict.js +3 -3
  27. package/lib/event-loop.js +1 -1
  28. package/lib/expected-failure.js +2 -2
  29. package/lib/finding-proof.js +1 -1
  30. package/lib/flood-guard.js +1 -1
  31. package/lib/goal-design.js +1 -1
  32. package/lib/host-agents.js +1 -1
  33. package/lib/lint-coverage.js +1 -1
  34. package/lib/log-query.js +1 -1
  35. package/lib/metrics-reset.js +1 -1
  36. package/lib/overseer-findings.js +1 -1
  37. package/lib/peers.d.ts +1 -1
  38. package/lib/peers.js +1 -1
  39. package/lib/perf-rules.js +1 -1
  40. package/lib/pod-memory.js +1 -1
  41. package/lib/producer-health.js +1 -1
  42. package/lib/remote-instances.js +1 -1
  43. package/lib/sessions.d.ts +17 -1
  44. package/lib/sources.js +1 -1
  45. package/lib/static-checks.js +1 -1
  46. package/lib/system-report.js +1 -1
  47. package/lib/team-design.d.ts +113 -3
  48. package/lib/team.js +1 -1
  49. package/package.json +1 -1
@@ -1,3 +1,3 @@
1
- "use strict";var q=Object.defineProperty;var p=(t,e)=>q(t,"name",{value:e,configurable:!0});var j=Object.defineProperty,c=p((t,e)=>j(t,"name",{value:e,configurable:!0}),"a");import{LENS_EVENT_SOURCE as I}from"./error-dismissal.js";export const NOT_A_BUG_KINDS=["restart","test-expected","auth-expired"];export function verdictOccurrence(t,e){return{at:t,...e.service?{service:e.service}:{},...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},...e.status!==void 0?{status:e.status}:{},...e.method?{method:e.method}:{},...e.routes?{routes:e.routes}:{},...e.errorName?{errorName:e.errorName}:{},...e.message?{message:e.message}:{}}}p(verdictOccurrence,"verdictOccurrence"),c(verdictOccurrence,"verdictOccurrence");export const TEST_RUN="test-run",TEST_FLOW_SCOPE_ENV="LENSMCP_TEST_FLOW_SCOPE",testFlowScope=c(t=>`e2e-${t}`,"testFlowScope"),TEST_FLOW_ID=/^(verify|e2e|test|smoke|load)[-_:]/i,ERROR_VERDICT_SET="error-verdict-set",ERROR_VERDICT_CLEARED="error-verdict-cleared";const v=c(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),"isObj"),a=c((t,e=300)=>typeof t=="string"&&t.trim()?t.trim().slice(0,e):void 0,"str"),m=c(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),N=200,F=new Set(["dashboard","cli","agent"]);export function readTestRun(t){if(t.source!==I||!v(t.raw)||t.raw.kind!==TEST_RUN)return;const e=t.raw,s=a(e.runId,120),n=a(e.state,20),i=a(e.flowScope,200);if(!s||!n||!i)return;const r=v(e.counts)?e.counts:void 0,o=m(r?.passed),u=m(r?.failed),l=m(r?.total);return{runId:s,state:n,flowScope:i,...a(e.action,40)?{action:a(e.action,40)}:{},...a(e.project,200)?{project:a(e.project,200)}:{},...a(e.target,200)?{target:a(e.target,200)}:{},...o!==void 0&&u!==void 0&&l!==void 0?{counts:{passed:o,failed:u,total:l}}:{},at:t.timestamp}}p(readTestRun,"readTestRun"),c(readTestRun,"readTestRun");export function readVerdictOverride(t){if(t.source!==I||!v(t.raw))return;const e=t.raw,s=a(e.groupId,2048);if(!s)return;const n=a(e.causeId,2048);if(e.kind===ERROR_VERDICT_CLEARED)return{kind:ERROR_VERDICT_CLEARED,groupId:s,...n?{causeId:n}:{}};if(e.kind!==ERROR_VERDICT_SET||e.verdict!=="bug")return;const i=Array.isArray(e.eventIds)?e.eventIds.filter(r=>typeof r=="string"&&r.length>0).slice(0,N):[];return{kind:ERROR_VERDICT_SET,groupId:s,...n?{causeId:n}:{},eventIds:i,...F.has(e.by)?{by:e.by}:{},at:t.timestamp}}p(readVerdictOverride,"readVerdictOverride"),c(readVerdictOverride,"readVerdictOverride");const E=2*6e4,A=1e4;export const RECOVERY_MS=6e4;const O=50,M=200,V=200,x=2e3,k=40,C=5e3,S={"service-restart":c(t=>`restarted${a(t.reason,80)?` (${a(t.reason,80)})`:""}`,"service-restart"),"pod-handoff-start":c(t=>`handed over to a new pod${a(t.reason,80)?` (${a(t.reason,80)})`:""}`,"pod-handoff-start"),"pod-recycle":c(t=>`its pod was recycled${a(t.reason,80)?` (${a(t.reason,80)})`:""}`,"pod-recycle"),"service-recycle":c(()=>"recycled after it stopped answering","service-recycle"),"idle-kill":c(()=>"stopped while idle","idle-kill"),"service-down":c(()=>"went down","service-down"),"service-respawn":c(()=>"started again by self-heal","service-respawn"),"service-starting":c(()=>"was starting","service-starting"),"worker-stopped":c(t=>`${y(t)} stopped`,"worker-stopped"),"worker-crashed":c(t=>`${y(t)} crashed and was started again`,"worker-crashed")};function y(t){const e=a(t.worker,80);return e?`its worker ${e}`:"its worker"}p(y,"x"),c(y,"workerOf");const z=new Set(["service-up","pod-handoff-complete","pod-handoff-failed","worker-started","worker-up"]),_=/\b(?:TokenExpired(?:Error)?|JWTExpired|jwt expired|(?:token|session|jwt|credentials?) (?:has |is |was )?expired|expired (?:token|session|jwt|credentials?)|"exp" claim)/i,B=/(?:^|[/._-])(?:refresh|renew|re-?auth|silent|token)(?:[/._-]|$)/i,D=/(?:^|\/)(?:log-?in|sign-?in)(?:\/|$)/i,L=/[-_:/.]/,U=new Set(["failed","errored","cancelled","timeout"]),W=new Set(["server-request","gateway-request","fetch-done","fetch"]),b=c(t=>{const e=t.split(/[?#]/)[0]??t,s=/^[a-z][a-z0-9+.-]*:\/\/[^/]+(\/.*)?$/i.exec(e);return s?s[1]??"/":e},"pathOf"),P=c(t=>t!==void 0&&t>=200&&t<300,"ok"),R=c(t=>new Date(t).toISOString().slice(11,19),"clock");function $(t,e,s,n,i){const r=t.get(e);if(r){r.push(s),r.length>n&&r.splice(0,r.length-n);return}t.set(e,[s]),t.size>i&&t.delete(t.keys().next().value)}p($,"E"),c($,"push");export class ErrorVerdictIndex{static{p(this,"ErrorVerdictIndex")}static{c(this,"ErrorVerdictIndex")}constructor(){this.windows=new Map,this.runs=new Map,this.requests=new Map,this.navigations=new Map,this.tabOfFlow=new Map,this.expired=new Map}observe(e){const s=v(e.raw)?e.raw:{},n=e.context??{},i=a(s.kind,60);if(e.source==="gateway"&&i&&this.lifecycle(i,s,e.timestamp))return!0;const r=readTestRun(e);if(r)return U.has(this.runs.get(r.flowScope)?.state??"")?!1:(this.runs.delete(r.flowScope),this.runs.set(r.flowScope,r),this.runs.size>V&&this.runs.delete(this.runs.keys().next().value),!0);const o=a(n.flowId,400),u=a(n.tabId,200),l=a(n.requestId,400);o&&u&&!this.tabOfFlow.has(o)&&(this.tabOfFlow.set(o,u),this.tabOfFlow.size>x&&this.tabOfFlow.delete(this.tabOfFlow.keys().next().value)),o&&i&&W.has(i)&&this.request(o,s,e.timestamp);const d=this.navigation(i,s,n);if(d&&(o&&$(this.navigations,`flow:${o}`,{at:e.timestamp,path:d},k,x),u&&$(this.navigations,`tab:${u}`,{at:e.timestamp,path:d},k,x)),l&&(e.severity==="warning"||e.severity==="error"||e.severity==="fatal")&&!this.expired.has(l)){const w=[(v(s.request)?s.request:{}).error,v(s.span)?s.span.error:void 0,s.error].filter(v),h=[e.title,e.message,...w.flatMap(f=>[f.name,f.message])].map(f=>a(f,600)).find(f=>f!==void 0&&_.test(f));h&&(this.expired.set(l,h.split(`
2
- `)[0].slice(0,120)),this.expired.size>C&&this.expired.delete(this.expired.keys().next().value))}return!1}lifecycle(e,s,n){const i=a(s.project,200);if(!i)return!1;const r=this.windows.get(i)??[],o=r.find(l=>l.end===void 0&&n-l.start<=E),u=e==="service-crash-loop"||e==="worker-crashed"&&s.crashLooping===!0;if((e==="service-restart"?s.phase==="started":S[e])||u){const l=o??{start:n,how:(S[e]??(()=>"crash-looping"))(s)};u&&(l.looping=!0),o||r.push(l)}else if(z.has(e)||e==="service-restart"){if(!o)return!1;o.end=n}else return!1;return r.length>O&&r.splice(0,r.length-O),this.windows.delete(i),this.windows.set(i,r),this.windows.size>M&&this.windows.delete(this.windows.keys().next().value),!0}request(e,s,n){const i=v(s.request)?s.request:s,r=[a(i.route,400),a(i.url,2e3)?b(a(i.url,2e3)):void 0].filter(l=>!!l),o=a(i.method,10)?.toUpperCase(),u=m(i.status);$(this.requests,e,{at:n,...o?{method:o}:{},paths:r,...u!==void 0?{status:u}:{}},k,x)}navigation(e,s,n){if((e==="route"||e==="ready")&&a(s.url,2e3))return b(a(s.url,2e3));const i=a(n.originType,40);if(i!=="route-load"&&i!=="page-load")return;const r=a(n.originNodeId,400);return r?.startsWith("route:")?r.slice(6):a(n.route,400)??(a(n.url,2e3)?b(a(n.url,2e3)):void 0)}restartAround(e,s){const n=this.windows.get(e)?.find(i=>!i.looping&&s>=i.start&&s<=(i.end??i.start+E)+A);return n&&{...n,service:e}}testRunOf(e){if(this.runs.size)for(let s=e.length;s>0;s--){if(s<e.length&&!L.test(e[s]))continue;const n=this.runs.get(e.slice(0,s));if(n)return n}}expiredSaid(e){const s=[e.errorName,e.message].map(n=>a(n,600)).find(n=>n!==void 0&&_.test(n));return s?s.split(`
3
- `)[0].slice(0,120):e.requestId?this.expired.get(e.requestId):void 0}recovery(e){if(!e.flowId)return;const s=c(d=>d>=e.at&&d<=e.at+RECOVERY_MS,"within"),n=new Set(e.routes??[]),i=(this.requests.get(e.flowId)??[]).filter(d=>s(d.at)&&P(d.status)),r=i.find(d=>d.paths.some(w=>B.test(w))&&!d.paths.some(w=>n.has(w))),o=r&&i.find(d=>d.at>=r.at&&d!==r&&(!e.method||!d.method||d.method===e.method)&&d.paths.some(w=>n.has(w)));if(r&&o)return{line:`refreshed (${r.method??""} ${r.paths[0]} \u2192 ${r.status}) and retried (${o.paths[0]} \u2192 ${o.status})`.replace("( ","("),at:o.at};const u=this.tabOfFlow.get(e.flowId),l=[...this.navigations.get(`flow:${e.flowId}`)??[],...u?this.navigations.get(`tab:${u}`)??[]:[]].find(d=>s(d.at)&&D.test(d.path));return l?{line:`went to sign-in (${l.path})`,at:l.at}:void 0}}const T={verdict:"bug"};export function judgeOccurrence(t,e,s){let n,i;if(t.service){const r=e.restartAround(t.service,t.at);if(r){const o=`${r.service} ${r.how} at ${R(r.start)}${r.end!==void 0?`, back at ${R(r.end)}`:""} UTC`;return{verdict:"not-a-bug",kind:"restart",line:o,evidence:[{kind:"restart",line:o,at:r.start,service:r.service}]}}}if(t.flowId){const r=e.testRunOf(t.flowId);if(r?.state==="passed"){const o=r.project?` (${r.project}${r.target?`:${r.target}`:""})`:"",u=`test run ${r.runId}${o} passed${r.counts?` \u2014 ${r.counts.passed} of ${r.counts.total} tests`:""}: the failure was part of the test`;return{verdict:"not-a-bug",kind:"test-expected",line:u,evidence:[{kind:"test-expected",line:u,at:r.at,runId:r.runId,flowId:t.flowId}]}}r?.state==="running"||r?.state==="queued"?n??={verdict:"unsure",kind:"test-expected",missing:`its test run ${r.runId} has not ended`}:r?i??=`its test run ${r.runId} ${r.state} \u2014 a failing run is no evidence it was expected`:TEST_FLOW_ID.test(t.flowId)&&(n??={verdict:"unsure",kind:"test-expected",missing:`flow ${t.flowId} is a test's, but no test run the lens holds names it`})}if(t.status===401||t.status===403)if(!t.flowId)n??={verdict:"unsure",kind:"auth-expired",missing:"not part of a flow: whether the client recovered cannot be followed"};else{const r=e.expiredSaid(t),o=e.recovery(t);if(r&&o){const u=`${t.status}: the app said \xAB${r}\xBB, and the client ${o.line}`;return{verdict:"not-a-bug",kind:"auth-expired",line:u,evidence:[{kind:"auth-expired",line:u,at:o.at,flowId:t.flowId}]}}o?n??={verdict:"unsure",kind:"auth-expired",missing:`the client ${o.line}, but nothing it recorded says the token had expired \u2014 a valid token refused reads the same`}:s-t.at<RECOVERY_MS?n??={verdict:"unsure",kind:"auth-expired",missing:"waiting up to a minute for the client to refresh and retry, or go to sign-in"}:r&&(i??=`its token had expired (\xAB${r}\xBB) and the client did not recover within a minute \u2014 no refresh and retry, no sign-in`)}return n??(i?{verdict:"bug",note:i}:T)}p(judgeOccurrence,"judgeOccurrence"),c(judgeOccurrence,"judgeOccurrence");const J={restart:"fell inside a restart","test-expected":"came from a passing test run","auth-expired":"were an expired session the client recovered from"},G=5;export function combineVerdicts(t,e=t.length,s="occurrences"){if(!t.length)return T;const n=t.filter(h=>h.verdict==="not-a-bug"),i=t.filter(h=>h.verdict==="bug"),r=new Map;for(const h of n)r.set(h.kind,(r.get(h.kind)??0)+1);const o=[...r].sort((h,f)=>f[1]-h[1])[0]?.[0];if(i.length){const h=i.find(g=>g.overridden)?.overridden,f=o?`${n.length} of ${t.length} ${s} ${J[o]}; ${i.length} did not`:i.find(g=>g.note)?.note;return{verdict:"bug",...f?{note:f}:{},...h?{overridden:h}:{}}}const u=t.find(h=>h.verdict==="unsure");if(u)return u;const l=e-t.length;if(l>0)return{verdict:"unsure",kind:o,missing:`${l} older occurrence${l===1?" is":"s are"} no longer held to check`};const d=[];for(const h of n)for(const f of h.evidence)d.length<G&&!d.some(g=>g.line===f.line)&&d.push(f);const w=n.find(h=>h.kind===o);return{verdict:"not-a-bug",kind:o,line:`${w.line}${d.length>1?` (and ${d.length-1} more)`:""}`,evidence:d}}p(combineVerdicts,"combineVerdicts"),c(combineVerdicts,"combineVerdicts");export const ERROR_JUDGEMENT_ASK=`"isBug": { "verdict": "bug" | "not-a-bug" | "unsure", "kind": ${NOT_A_BUG_KINDS.map(t=>`"${t}"`).join(" | ")} | "other" (only for not-a-bug), "why": "one line, citing the evidence" } \u2014 not-a-bug only when the evidence shows it is no defect: a service stopping or restarting, a test that expected it, a session that expired and the client recovered; unsure when the evidence cannot tell`;export function readErrorJudgement(t){if(!v(t))return{verdict:"unsure",why:"the review gave no verdict"};const e=a(t.why,400),s=t.verdict;if(s!=="bug"&&s!=="not-a-bug"&&s!=="unsure")return{verdict:"unsure",why:"the review's verdict was not one of bug, not-a-bug, unsure"};if(!e)return{verdict:"unsure",why:`the review said ${s} without saying why`};if(s!=="not-a-bug")return{verdict:s,why:e};const n=NOT_A_BUG_KINDS.includes(t.kind)?t.kind:"other";return{verdict:s,kind:n,why:e}}p(readErrorJudgement,"readErrorJudgement"),c(readErrorJudgement,"readErrorJudgement");
1
+ "use strict";var j=Object.defineProperty;var f=(t,e)=>j(t,"name",{value:e,configurable:!0});var N=Object.defineProperty,w=f((t,e)=>N(t,"name",{value:e,configurable:!0}),"p"),V=Object.defineProperty,c=w((t,e)=>V(t,"name",{value:e,configurable:!0}),"a");import{LENS_EVENT_SOURCE as O}from"./error-dismissal.js";export const NOT_A_BUG_KINDS=["restart","test-expected","auth-expired"];export function verdictOccurrence(t,e){return{at:t,...e.service?{service:e.service}:{},...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},...e.status!==void 0?{status:e.status}:{},...e.method?{method:e.method}:{},...e.routes?{routes:e.routes}:{},...e.errorName?{errorName:e.errorName}:{},...e.message?{message:e.message}:{}}}f(verdictOccurrence,"verdictOccurrence"),w(verdictOccurrence,"verdictOccurrence"),c(verdictOccurrence,"verdictOccurrence");export const TEST_RUN="test-run",TEST_FLOW_SCOPE_ENV="LENSMCP_TEST_FLOW_SCOPE",testFlowScope=c(t=>`e2e-${t}`,"testFlowScope"),TEST_FLOW_ID=/^(verify|e2e|test|smoke|load)[-_:]/i,ERROR_VERDICT_SET="error-verdict-set",ERROR_VERDICT_CLEARED="error-verdict-cleared";const g=c(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),"isObj"),a=c((t,e=300)=>typeof t=="string"&&t.trim()?t.trim().slice(0,e):void 0,"str"),$=c(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),F=200,A=new Set(["dashboard","cli","agent"]);export function readTestRun(t){if(t.source!==O||!g(t.raw)||t.raw.kind!==TEST_RUN)return;const e=t.raw,s=a(e.runId,120),i=a(e.state,20),n=a(e.flowScope,200);if(!s||!i||!n)return;const r=g(e.counts)?e.counts:void 0,o=$(r?.passed),u=$(r?.failed),l=$(r?.total);return{runId:s,state:i,flowScope:n,...a(e.action,40)?{action:a(e.action,40)}:{},...a(e.project,200)?{project:a(e.project,200)}:{},...a(e.target,200)?{target:a(e.target,200)}:{},...o!==void 0&&u!==void 0&&l!==void 0?{counts:{passed:o,failed:u,total:l}}:{},at:t.timestamp}}f(readTestRun,"readTestRun"),w(readTestRun,"readTestRun"),c(readTestRun,"readTestRun");export function readVerdictOverride(t){if(t.source!==O||!g(t.raw))return;const e=t.raw,s=a(e.groupId,2048);if(!s)return;const i=a(e.causeId,2048);if(e.kind===ERROR_VERDICT_CLEARED)return{kind:ERROR_VERDICT_CLEARED,groupId:s,...i?{causeId:i}:{}};if(e.kind!==ERROR_VERDICT_SET||e.verdict!=="bug")return;const n=Array.isArray(e.eventIds)?e.eventIds.filter(r=>typeof r=="string"&&r.length>0).slice(0,F):[];return{kind:ERROR_VERDICT_SET,groupId:s,...i?{causeId:i}:{},eventIds:n,...A.has(e.by)?{by:e.by}:{},at:t.timestamp}}f(readVerdictOverride,"readVerdictOverride"),w(readVerdictOverride,"readVerdictOverride"),c(readVerdictOverride,"readVerdictOverride");const E=2*6e4,M=1e4;export const RECOVERY_MS=6e4;const S=50,C=200,z=200,k=2e3,y=40,B=5e3,_={"service-restart":c(t=>`restarted${a(t.reason,80)?` (${a(t.reason,80)})`:""}`,"service-restart"),"pod-handoff-start":c(t=>`handed over to a new pod${a(t.reason,80)?` (${a(t.reason,80)})`:""}`,"pod-handoff-start"),"pod-recycle":c(t=>`its pod was recycled${a(t.reason,80)?` (${a(t.reason,80)})`:""}`,"pod-recycle"),"service-recycle":c(()=>"recycled after it stopped answering","service-recycle"),"idle-kill":c(()=>"stopped while idle","idle-kill"),"service-down":c(()=>"went down","service-down"),"service-respawn":c(()=>"started again by self-heal","service-respawn"),"service-starting":c(()=>"was starting","service-starting"),"worker-stopped":c(t=>`${b(t)} stopped`,"worker-stopped"),"worker-crashed":c(t=>`${b(t)} crashed and was started again`,"worker-crashed")};function b(t){const e=a(t.worker,80);return e?`its worker ${e}`:"its worker"}f(b,"y"),w(b,"x"),c(b,"workerOf");const D=new Set(["service-up","pod-handoff-complete","pod-handoff-failed","worker-started","worker-up"]),R=/\b(?:TokenExpired(?:Error)?|JWTExpired|jwt expired|(?:token|session|jwt|credentials?) (?:has |is |was )?expired|expired (?:token|session|jwt|credentials?)|"exp" claim)/i,L=/(?:^|[/._-])(?:refresh|renew|re-?auth|silent|token)(?:[/._-]|$)/i,U=/(?:^|\/)(?:log-?in|sign-?in)(?:\/|$)/i,J=/[-_:/.]/,P=new Set(["failed","errored","cancelled","timeout"]),W=new Set(["server-request","gateway-request","fetch-done","fetch"]),I=c(t=>{const e=t.split(/[?#]/)[0]??t,s=/^[a-z][a-z0-9+.-]*:\/\/[^/]+(\/.*)?$/i.exec(e);return s?s[1]??"/":e},"pathOf"),G=c(t=>t!==void 0&&t>=200&&t<300,"ok"),T=c(t=>new Date(t).toISOString().slice(11,19),"clock");function x(t,e,s,i,n){const r=t.get(e);if(r){r.push(s),r.length>i&&r.splice(0,r.length-i);return}t.set(e,[s]),t.size>n&&t.delete(t.keys().next().value)}f(x,"$"),w(x,"E"),c(x,"push");export class ErrorVerdictIndex{static{f(this,"ErrorVerdictIndex")}static{w(this,"ErrorVerdictIndex")}static{c(this,"ErrorVerdictIndex")}constructor(){this.windows=new Map,this.runs=new Map,this.requests=new Map,this.navigations=new Map,this.tabOfFlow=new Map,this.expired=new Map}observe(e){const s=g(e.raw)?e.raw:{},i=e.context??{},n=a(s.kind,60);if(e.source==="gateway"&&n&&this.lifecycle(n,s,e.timestamp))return!0;const r=readTestRun(e);if(r)return P.has(this.runs.get(r.flowScope)?.state??"")?!1:(this.runs.delete(r.flowScope),this.runs.set(r.flowScope,r),this.runs.size>z&&this.runs.delete(this.runs.keys().next().value),!0);const o=a(i.flowId,400),u=a(i.tabId,200),l=a(i.requestId,400);o&&u&&!this.tabOfFlow.has(o)&&(this.tabOfFlow.set(o,u),this.tabOfFlow.size>k&&this.tabOfFlow.delete(this.tabOfFlow.keys().next().value)),o&&n&&W.has(n)&&this.request(o,s,e.timestamp);const d=this.navigation(n,s,i);if(d&&(o&&x(this.navigations,`flow:${o}`,{at:e.timestamp,path:d},y,k),u&&x(this.navigations,`tab:${u}`,{at:e.timestamp,path:d},y,k)),l&&(e.severity==="warning"||e.severity==="error"||e.severity==="fatal")&&!this.expired.has(l)){const v=[(g(s.request)?s.request:{}).error,g(s.span)?s.span.error:void 0,s.error].filter(g),h=[e.title,e.message,...v.flatMap(p=>[p.name,p.message])].map(p=>a(p,600)).find(p=>p!==void 0&&R.test(p));h&&(this.expired.set(l,h.split(`
2
+ `)[0].slice(0,120)),this.expired.size>B&&this.expired.delete(this.expired.keys().next().value))}return!1}lifecycle(e,s,i){const n=a(s.project,200);if(!n)return!1;const r=this.windows.get(n)??[],o=r.find(l=>l.end===void 0&&i-l.start<=E),u=e==="service-crash-loop"||e==="worker-crashed"&&s.crashLooping===!0;if((e==="service-restart"?s.phase==="started":_[e])||u){const l=o??{start:i,how:(_[e]??(()=>"crash-looping"))(s)};u&&(l.looping=!0),o||r.push(l)}else if(D.has(e)||e==="service-restart"){if(!o)return!1;o.end=i}else return!1;return r.length>S&&r.splice(0,r.length-S),this.windows.delete(n),this.windows.set(n,r),this.windows.size>C&&this.windows.delete(this.windows.keys().next().value),!0}request(e,s,i){const n=g(s.request)?s.request:s,r=[a(n.route,400),a(n.url,2e3)?I(a(n.url,2e3)):void 0].filter(l=>!!l),o=a(n.method,10)?.toUpperCase(),u=$(n.status);x(this.requests,e,{at:i,...o?{method:o}:{},paths:r,...u!==void 0?{status:u}:{}},y,k)}navigation(e,s,i){if((e==="route"||e==="ready")&&a(s.url,2e3))return I(a(s.url,2e3));const n=a(i.originType,40);if(n!=="route-load"&&n!=="page-load")return;const r=a(i.originNodeId,400);return r?.startsWith("route:")?r.slice(6):a(i.route,400)??(a(i.url,2e3)?I(a(i.url,2e3)):void 0)}restartAround(e,s){const i=this.windows.get(e)?.find(n=>!n.looping&&s>=n.start&&s<=(n.end??n.start+E)+M);return i&&{...i,service:e}}testRunOf(e){if(this.runs.size)for(let s=e.length;s>0;s--){if(s<e.length&&!J.test(e[s]))continue;const i=this.runs.get(e.slice(0,s));if(i)return i}}expiredSaid(e){const s=[e.errorName,e.message].map(i=>a(i,600)).find(i=>i!==void 0&&R.test(i));return s?s.split(`
3
+ `)[0].slice(0,120):e.requestId?this.expired.get(e.requestId):void 0}recovery(e){if(!e.flowId)return;const s=c(d=>d>=e.at&&d<=e.at+RECOVERY_MS,"within"),i=new Set(e.routes??[]),n=(this.requests.get(e.flowId)??[]).filter(d=>s(d.at)&&G(d.status)),r=n.find(d=>d.paths.some(v=>L.test(v))&&!d.paths.some(v=>i.has(v))),o=r&&n.find(d=>d.at>=r.at&&d!==r&&(!e.method||!d.method||d.method===e.method)&&d.paths.some(v=>i.has(v)));if(r&&o)return{line:`refreshed (${r.method??""} ${r.paths[0]} \u2192 ${r.status}) and retried (${o.paths[0]} \u2192 ${o.status})`.replace("( ","("),at:o.at};const u=this.tabOfFlow.get(e.flowId),l=[...this.navigations.get(`flow:${e.flowId}`)??[],...u?this.navigations.get(`tab:${u}`)??[]:[]].find(d=>s(d.at)&&U.test(d.path));return l?{line:`went to sign-in (${l.path})`,at:l.at}:void 0}}const q={verdict:"bug"};export function judgeOccurrence(t,e,s){let i,n;if(t.service){const r=e.restartAround(t.service,t.at);if(r){const o=`${r.service} ${r.how} at ${T(r.start)}${r.end!==void 0?`, back at ${T(r.end)}`:""} UTC`;return{verdict:"not-a-bug",kind:"restart",line:o,evidence:[{kind:"restart",line:o,at:r.start,service:r.service}]}}}if(t.flowId){const r=e.testRunOf(t.flowId);if(r?.state==="passed"){const o=r.project?` (${r.project}${r.target?`:${r.target}`:""})`:"",u=`test run ${r.runId}${o} passed${r.counts?` \u2014 ${r.counts.passed} of ${r.counts.total} tests`:""}: the failure was part of the test`;return{verdict:"not-a-bug",kind:"test-expected",line:u,evidence:[{kind:"test-expected",line:u,at:r.at,runId:r.runId,flowId:t.flowId}]}}r?.state==="running"||r?.state==="queued"?i??={verdict:"unsure",kind:"test-expected",missing:`its test run ${r.runId} has not ended`}:r?n??=`its test run ${r.runId} ${r.state} \u2014 a failing run is no evidence it was expected`:TEST_FLOW_ID.test(t.flowId)&&(i??={verdict:"unsure",kind:"test-expected",missing:`flow ${t.flowId} is a test's, but no test run the lens holds names it`})}if(t.status===401||t.status===403)if(!t.flowId)i??={verdict:"unsure",kind:"auth-expired",missing:"not part of a flow: whether the client recovered cannot be followed"};else{const r=e.expiredSaid(t),o=e.recovery(t);if(r&&o){const u=`${t.status}: the app said \xAB${r}\xBB, and the client ${o.line}`;return{verdict:"not-a-bug",kind:"auth-expired",line:u,evidence:[{kind:"auth-expired",line:u,at:o.at,flowId:t.flowId}]}}o?i??={verdict:"unsure",kind:"auth-expired",missing:`the client ${o.line}, but nothing it recorded says the token had expired \u2014 a valid token refused reads the same`}:s-t.at<RECOVERY_MS?i??={verdict:"unsure",kind:"auth-expired",missing:"waiting up to a minute for the client to refresh and retry, or go to sign-in"}:r&&(n??=`its token had expired (\xAB${r}\xBB) and the client did not recover within a minute \u2014 no refresh and retry, no sign-in`)}return i??(n?{verdict:"bug",note:n}:q)}f(judgeOccurrence,"judgeOccurrence"),w(judgeOccurrence,"judgeOccurrence"),c(judgeOccurrence,"judgeOccurrence");const K={restart:"fell inside a restart","test-expected":"came from a passing test run","auth-expired":"were an expired session the client recovered from"},Y=5;export function combineVerdicts(t,e=t.length,s="occurrences"){if(!t.length)return q;const i=t.filter(h=>h.verdict==="not-a-bug"),n=t.filter(h=>h.verdict==="bug"),r=new Map;for(const h of i)r.set(h.kind,(r.get(h.kind)??0)+1);const o=[...r].sort((h,p)=>p[1]-h[1])[0]?.[0];if(n.length){const h=n.find(m=>m.overridden)?.overridden,p=o?`${i.length} of ${t.length} ${s} ${K[o]}; ${n.length} did not`:n.find(m=>m.note)?.note;return{verdict:"bug",...p?{note:p}:{},...h?{overridden:h}:{}}}const u=t.find(h=>h.verdict==="unsure");if(u)return u;const l=e-t.length;if(l>0)return{verdict:"unsure",kind:o,missing:`${l} older occurrence${l===1?" is":"s are"} no longer held to check`};const d=[];for(const h of i)for(const p of h.evidence)d.length<Y&&!d.some(m=>m.line===p.line)&&d.push(p);const v=i.find(h=>h.kind===o);return{verdict:"not-a-bug",kind:o,line:`${v.line}${d.length>1?` (and ${d.length-1} more)`:""}`,evidence:d}}f(combineVerdicts,"combineVerdicts"),w(combineVerdicts,"combineVerdicts"),c(combineVerdicts,"combineVerdicts");export const ERROR_JUDGEMENT_ASK=`"isBug": { "verdict": "bug" | "not-a-bug" | "unsure", "kind": ${NOT_A_BUG_KINDS.map(t=>`"${t}"`).join(" | ")} | "other" (only for not-a-bug), "why": "one line, citing the evidence" } \u2014 not-a-bug only when the evidence shows it is no defect: a service stopping or restarting, a test that expected it, a session that expired and the client recovered; unsure when the evidence cannot tell`;export function readErrorJudgement(t){if(!g(t))return{verdict:"unsure",why:"the review gave no verdict"};const e=a(t.why,400),s=t.verdict;if(s!=="bug"&&s!=="not-a-bug"&&s!=="unsure")return{verdict:"unsure",why:"the review's verdict was not one of bug, not-a-bug, unsure"};if(!e)return{verdict:"unsure",why:`the review said ${s} without saying why`};if(s!=="not-a-bug")return{verdict:s,why:e};const i=NOT_A_BUG_KINDS.includes(t.kind)?t.kind:"other";return{verdict:s,kind:i,why:e}}f(readErrorJudgement,"readErrorJudgement"),w(readErrorJudgement,"readErrorJudgement"),c(readErrorJudgement,"readErrorJudgement");
package/lib/event-loop.js CHANGED
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var r=(t,e)=>f(t,"name",{value:e,configurable:!0});var p=Object.defineProperty,a=r((t,e)=>p(t,"name",{value:e,configurable:!0}),"r");export const LENS_CAUSES={"lensmcp-gc":"forced GC","lensmcp-cleanup":"cleanup","lensmcp-write":"writing events","lensmcp-capture":"capturing values"};export function lensOwnWork(t){const e=typeof t.cause=="string"&&t.cause.startsWith("lensmcp-");if(!e&&!(typeof t.lensMs=="number"&&t.durationMs>0&&t.lensMs>=t.durationMs/2))return;const o=e?LENS_CAUSES[t.cause]:void 0;return o?`LensMCP's own work \u2014 ${o}`:"LensMCP's own work"}r(lensOwnWork,"lensOwnWork"),a(lensOwnWork,"lensOwnWork");export function waitedBehind(t){const e=new Set,o=new Set;for(const n of t.evidence)n.relation==="executing"||(n.requestId?n.requestId===t.requestId:!n.flowId||n.flowId===t.flowId)||(e.add(n.requestId??n.flowId),n.flowId&&n.flowId!==t.flowId&&o.add(n.flowId));return{requests:e.size,flows:o.size,atLeast:t.evidenceTruncated}}r(waitedBehind,"waitedBehind"),a(waitedBehind,"waitedBehind");export function waitedLine(t){const e=waitedBehind(t);return e.requests?`${e.atLeast?"at least ":""}${e.requests} request${e.requests===1?"":"s"} waited behind it`:void 0}r(waitedLine,"waitedLine"),a(waitedLine,"waitedLine");export function flowStalls(t,e){const o={ran:[],overlapped:[]};for(const n of t){if(lensOwnWork(n))continue;if(n.flowId===e){o.ran.push(n);continue}const u=n.endAt??n.observedAt,c=n.evidence.filter(s=>s.flowId===e).map(s=>[Math.max(s.startAt,n.startAt),Math.min(s.endAt,u)]).filter(([s,i])=>i>=s).sort((s,i)=>s[0]-i[0]);if(!c.length)continue;let d=0,l=-1/0;for(const[s,i]of c)i>l&&(d+=i-Math.max(s,l)),l=Math.max(l,i);o.overlapped.push({incident:n,overlapMs:Math.round(d*100)/100})}return o}r(flowStalls,"flowStalls"),a(flowStalls,"flowStalls");export function overlapLine(t){if(!t.length)return;const e=[...new Set(t.map(u=>u.incident.loop.project))],o=e.length<=2?e.join(" and "):`${e.length} services`,n=t.length;return{count:n,services:e,longestMs:Math.max(...t.map(u=>u.overlapMs)),text:`${n} pause${n===1?"":"s"} in ${o} while this flow was open \u2014 not this flow\u2019s code`}}r(overlapLine,"overlapLine"),a(overlapLine,"overlapLine");export const LOOP_STARTUP_MS=6e4;export function loopStartedAt(t){if(!t.startsWith("node:"))return;const e=Number(t.slice(t.lastIndexOf(":")+1));return Number.isFinite(e)&&e>0?e:void 0}r(loopStartedAt,"loopStartedAt"),a(loopStartedAt,"loopStartedAt");export function loopPhaseAt(t,e){const o=loopStartedAt(t);if(o===void 0)return;const n=Math.max(0,Math.round(e-o));return{phase:n<LOOP_STARTUP_MS?"startup":"running",sinceStartMs:n}}r(loopPhaseAt,"loopPhaseAt"),a(loopPhaseAt,"loopPhaseAt");
1
+ "use strict";var f=Object.defineProperty;var s=(e,t)=>f(e,"name",{value:t,configurable:!0});var w=Object.defineProperty,a=s((e,t)=>w(e,"name",{value:t,configurable:!0}),"r"),h=Object.defineProperty,l=a((e,t)=>h(e,"name",{value:t,configurable:!0}),"r");export const LENS_CAUSES={"lensmcp-gc":"forced GC","lensmcp-cleanup":"cleanup","lensmcp-write":"writing events","lensmcp-capture":"capturing values"};export function lensOwnWork(e){const t=typeof e.cause=="string"&&e.cause.startsWith("lensmcp-");if(!t&&!(typeof e.lensMs=="number"&&e.durationMs>0&&e.lensMs>=e.durationMs/2))return;const o=t?LENS_CAUSES[e.cause]:void 0;return o?`LensMCP's own work \u2014 ${o}`:"LensMCP's own work"}s(lensOwnWork,"lensOwnWork"),a(lensOwnWork,"lensOwnWork"),l(lensOwnWork,"lensOwnWork");export function waitedBehind(e){const t=new Set,o=new Set;for(const n of e.evidence)n.relation==="executing"||(n.requestId?n.requestId===e.requestId:!n.flowId||n.flowId===e.flowId)||(t.add(n.requestId??n.flowId),n.flowId&&n.flowId!==e.flowId&&o.add(n.flowId));return{requests:t.size,flows:o.size,atLeast:e.evidenceTruncated}}s(waitedBehind,"waitedBehind"),a(waitedBehind,"waitedBehind"),l(waitedBehind,"waitedBehind");export function waitedLine(e){const t=waitedBehind(e);return t.requests?`${t.atLeast?"at least ":""}${t.requests} request${t.requests===1?"":"s"} waited behind it`:void 0}s(waitedLine,"waitedLine"),a(waitedLine,"waitedLine"),l(waitedLine,"waitedLine");export function flowStalls(e,t){const o={ran:[],overlapped:[]};for(const n of e){if(lensOwnWork(n))continue;if(n.flowId===t){o.ran.push(n);continue}const u=n.endAt??n.observedAt,d=n.evidence.filter(r=>r.flowId===t).map(r=>[Math.max(r.startAt,n.startAt),Math.min(r.endAt,u)]).filter(([r,i])=>i>=r).sort((r,i)=>r[0]-i[0]);if(!d.length)continue;let p=0,c=-1/0;for(const[r,i]of d)i>c&&(p+=i-Math.max(r,c)),c=Math.max(c,i);o.overlapped.push({incident:n,overlapMs:Math.round(p*100)/100})}return o}s(flowStalls,"flowStalls"),a(flowStalls,"flowStalls"),l(flowStalls,"flowStalls");export function overlapLine(e){if(!e.length)return;const t=[...new Set(e.map(u=>u.incident.loop.project))],o=t.length<=2?t.join(" and "):`${t.length} services`,n=e.length;return{count:n,services:t,longestMs:Math.max(...e.map(u=>u.overlapMs)),text:`${n} pause${n===1?"":"s"} in ${o} while this flow was open \u2014 not this flow\u2019s code`}}s(overlapLine,"overlapLine"),a(overlapLine,"overlapLine"),l(overlapLine,"overlapLine");export const LOOP_STARTUP_MS=6e4;export function loopStartedAt(e){if(!e.startsWith("node:"))return;const t=Number(e.slice(e.lastIndexOf(":")+1));return Number.isFinite(t)&&t>0?t:void 0}s(loopStartedAt,"loopStartedAt"),a(loopStartedAt,"loopStartedAt"),l(loopStartedAt,"loopStartedAt");export function loopPhaseAt(e,t){const o=loopStartedAt(e);if(o===void 0)return;const n=Math.max(0,Math.round(t-o));return{phase:n<LOOP_STARTUP_MS?"startup":"running",sinceStartMs:n}}s(loopPhaseAt,"loopPhaseAt"),a(loopPhaseAt,"loopPhaseAt"),l(loopPhaseAt,"loopPhaseAt");
@@ -1,2 +1,2 @@
1
- "use strict";var z=Object.defineProperty;var h=(t,e)=>z(t,"name",{value:e,configurable:!0});var K=Object.defineProperty,c=h((t,e)=>K(t,"name",{value:e,configurable:!0}),"d");import{LENS_EVENT_SOURCE as W}from"./error-dismissal.js";export const EXPECTED_RULE_SET="expected-rule-set",EXPECTED_RULE_REMOVED="expected-rule-removed";const k=new Set(["dashboard","cli","agent"]),m=60*6e4;export const EXPECTED_RULE_DEFAULT_TTL_MS=168*m,EXPECTED_RULE_MAX_TTL_MS=720*m,EXPECTED_RULE_MIN_REASON_CHARS=8,MAX_EXPECTED_REASON_CHARS=500;const A=300,G=300,P=120,J=200,H=20,l=c(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),g=c((t,e)=>typeof t=="string"&&t.trim()?t.trim().slice(0,e):void 0,"text"),R=c(t=>!!t&&t.replace(/[*?\s/:.#_-]/g,"").length>=2,"meaningful");export const EXPECTED_SCOPE_FIELDS=["route","span","flow"],EXPECTED_OUTCOME_FIELDS=["status","error","message"];export function checkExpectedMatch(t){if(!l(t))return{error:"a rule needs a match: a flow scope (route, span or flow) and an outcome (status, error or message)"};const e={};for(const r of["service","route","span","flow","error","message"]){const o=t[r];if(o==null||o==="")continue;if(typeof o!="string")return{error:`\`${r}\` must be text`};const i=o.trim();if(i.length>A)return{error:`\`${r}\` is longer than ${A} characters`};i&&(e[r]=i)}if(t.status!==void 0&&t.status!==null&&t.status!==""){const r=typeof t.status=="string"?Number(t.status):t.status;if(typeof r!="number"||!Number.isInteger(r)||r<100||r>599)return{error:"`status` must be an HTTP status (100\u2013599)"};e.status=r}const s=t.attribute;if(s!=null){const r=l(s)?g(s.name,100):void 0,o=l(s)?typeof s.value=="number"?String(s.value):g(s.value,A):void 0;if(!r||!o)return{error:"`attribute` needs a `name` and a `value` (one attribute of the flow, such as a tenant id)"};e.attribute={name:r,value:o}}return EXPECTED_SCOPE_FIELDS.some(r=>R(e[r]))?e.status===void 0&&!R(e.error)&&!R(e.message)?{error:"a rule needs an outcome \u2014 a `status`, an `error` key or a `message` pattern \u2014 saying WHICH failure is expected in that flow"}:{match:e}:{error:`a rule needs a flow scope \u2014 a \`route\`, a \`span\` or a \`flow\` \u2014 not only ${e.service?`the service \xAB${e.service}\xBB`:"an outcome"}: \xABeverything in a service\xBB is not expected, it is unwatched`}}h(checkExpectedMatch,"checkExpectedMatch"),c(checkExpectedMatch,"checkExpectedMatch");export function describeExpectedMatch(t){return[t.service,t.route,t.span,t.flow?`flow ${t.flow}`:void 0,t.status!==void 0?String(t.status):void 0,t.error,t.message?`\xAB${t.message}\xBB`:void 0,t.attribute?`${t.attribute.name}=${t.attribute.value}`:void 0].filter(Boolean).join(" \xB7 ")}h(describeExpectedMatch,"describeExpectedMatch"),c(describeExpectedMatch,"describeExpectedMatch");export function readExpectedRule(t){if(t.source!==W||!l(t.raw))return;const e=t.raw,s=g(e.id,P);if(!s)return;if(e.kind===EXPECTED_RULE_REMOVED)return{kind:EXPECTED_RULE_REMOVED,id:s,...k.has(e.by)?{by:e.by}:{}};if(e.kind!==EXPECTED_RULE_SET||!k.has(e.by))return;const r=g(e.reason,MAX_EXPECTED_REASON_CHARS);if(!r)return;const o=checkExpectedMatch(e.match);if("error"in o)return;const i=Math.min(typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)?e.createdAt:t.timestamp,t.timestamp),u=typeof e.expiresAt=="number"&&Number.isFinite(e.expiresAt)?e.expiresAt:i+EXPECTED_RULE_DEFAULT_TTL_MS,a=g(e.title,G);return{kind:EXPECTED_RULE_SET,id:s,match:o.match,reason:r,by:e.by,createdAt:i,expiresAt:Math.min(u,i+EXPECTED_RULE_MAX_TTL_MS),...a?{title:a}:{}}}h(readExpectedRule,"readExpectedRule"),c(readExpectedRule,"readExpectedRule");export function expectedRuleTtlMs(t){return t===void 0||!Number.isFinite(t)||t<=0?EXPECTED_RULE_DEFAULT_TTL_MS:Math.min(Math.round(t*m),EXPECTED_RULE_MAX_TTL_MS)}h(expectedRuleTtlMs,"expectedRuleTtlMs"),c(expectedRuleTtlMs,"expectedRuleTtlMs");function F(t){let e=2166136261;for(let s=0;s<t.length;s++)e=Math.imul(e^t.charCodeAt(s),16777619);return(e>>>0).toString(36)}h(F,"z"),c(F,"hashOf");export function readRepositoryExpectedRules(t,e){const s=[],r=[];return t==null?{rules:s,problems:r}:Array.isArray(t)?(t.forEach((o,i)=>{if(!l(o))return void r.push(`expectedFailures[${i}] is not an object`);const u=checkExpectedMatch(l(o.match)?o.match:o);if("error"in u)return void r.push(`expectedFailures[${i}]: ${u.error}`);const a=g(o.reason,MAX_EXPECTED_REASON_CHARS);if(!a)return void r.push(`expectedFailures[${i}] has no reason \u2014 say why it is expected`);const d=`repository:${g(o.id,P)??F(JSON.stringify(u.match))}`;if(s.some(p=>p.id===d))return void r.push(`expectedFailures[${i}] repeats the id ${d}`);s.push({id:d,match:u.match,reason:a,by:"repository",createdAt:e})}),{rules:s,problems:r}):{rules:s,problems:["expectedFailures is not a list \u2014 no repository rule is read"]}}h(readRepositoryExpectedRules,"readRepositoryExpectedRules"),c(readRepositoryExpectedRules,"readRepositoryExpectedRules");const n=c(t=>typeof t=="string"&&t?t:void 0,"str"),$=c(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),B=c(t=>{const e=t.split(/[?#]/)[0]??t,s=/^[a-z][a-z0-9+.-]*:\/\/[^/]+(\/.*)?$/i.exec(e);return s?s[1]??"/":e},"pathOf"),V=new Set(["sessionId","flowId","requestId","parentRequestId","runId","traceparent","originNodeId","causedByNodeId","userActionId","browserContextId","frameId","tabId","url","route","projectName"]),_=24;export function eventAttributes(t){let e;const s=c((a,d)=>{if(e&&Object.keys(e).length>=_)return;const p=typeof d=="string"?d:typeof d=="number"||typeof d=="boolean"?String(d):void 0;p===void 0||p.length>A||((e??={})[a]=p)},"put"),r=t.context??{};for(const a of Object.keys(r))V.has(a)||s(a,r[a]);const o=l(t.raw)?t.raw:void 0;if(!o)return e;const i=l(o.span)?o.span:void 0,u=l(o.request)?o.request:void 0;for(const a of[o.attributes,i?.attributes,u?.attributes,o.data,Array.isArray(i?.args)?i?.args[0]:i?.args])if(l(a))for(const d of Object.keys(a))s(d,a[d]);return e}h(eventAttributes,"eventAttributes"),c(eventAttributes,"eventAttributes");export function failureFacts(t){const e=l(t.raw)?t.raw:{},s=t.context??{},r=l(e.request)?e.request:{},o=l(e.span)?e.span:{},i=l(r.error)?r.error:{},u=l(o.error)?o.error:{},a=l(e.error)?e.error:{},d=n(e.kind),p=[],b=n(r.route)??(d==="egress"?n(e.path):void 0);b&&p.push(b);const y=n(e.url)??n(r.url);y&&p.push(B(y)),d!=="server-request"&&n(s.route)&&p.push(n(s.route));const f=[];if(d==="queue-failed"||d==="queue-enqueued"){const w=n(e.queue),E=e.jobId===void 0||e.jobId===null?void 0:String(e.jobId);w&&f.push(`job:${w}`),E&&f.push(`job:${E}`),w&&E&&f.push(`job:${w}#${E}`),n(e.name)&&f.push(`job:${n(e.name)}`)}const x=[i.errorKey,u.errorKey,a.errorKey,e.errorKey,i.reason,u.reason].map(n).filter(w=>!!w),S=n(i.message)??n(t.message)??n(u.message)??n(a.message)??n(e.failedReason)??n(e.error)??n(e.message)??n(t.title),C=$(r.status)??$(e.status),T=n(s.flowId)??n(o.flowId)??n(r.flowId),N=n(s.requestId)??n(r.requestId)??n(o.requestId),O=eventAttributes(t);return{...n(e.project)??n(s.projectName)?{service:n(e.project)??n(s.projectName)}:{},...n(r.method)??n(e.method)?{method:n(r.method)??n(e.method)}:{},...p.length?{routes:p}:{},...n(o.name)?{span:n(o.name)}:{},...T?{flowId:T}:{},...f.length?{flowNames:f}:{},...C!==void 0?{status:C}:{},...n(i.name)??n(u.name)??n(a.name)?{errorName:n(i.name)??n(u.name)??n(a.name)}:{},...x.length?{errorKeys:x}:{},...S?{message:S}:{},...O?{attributes:O}:{},...N?{requestId:N}:{}}}h(failureFacts,"failureFacts"),c(failureFacts,"failureFacts");export class FailureContextIndex{static{h(this,"FailureContextIndex")}static{c(this,"FailureContextIndex")}constructor(e=5e3,s=2e3){this.maxRequests=e,this.maxFlows=s,this.requests=new Map,this.flows=new Map}observe(e){const s=l(e.raw)?e.raw:void 0,r=e.context??{},o=n(r.flowId);if(o&&(s?.attributes!==void 0||l(s?.span)||r.tenantIdHash!==void 0||r.userIdHash!==void 0||s?.data!==void 0)){const y=eventAttributes(e);if(y){const f=this.flows.get(o);this.flows.delete(o);const x={...f??{},...y};this.flows.set(o,Object.keys(x).length>_?Object.fromEntries(Object.entries(x).slice(-_)):x),this.flows.size>this.maxFlows&&this.flows.delete(this.flows.keys().next().value)}}const i=n(s?.kind);if(!s||i!=="server-request"&&i!=="gateway-request")return;const u=l(s.request)?s.request:s,a=n(r.requestId)??n(u.requestId);if(!a)return;const d=this.requests.get(a)??{},p=n(u.url),b={...d,...n(s.project)&&(i==="server-request"||!d.service)?{service:n(s.project)}:{},...n(u.method)?{method:n(u.method)}:{},...i==="server-request"&&n(u.route)?{route:n(u.route)}:{},...p?{path:B(p)}:{},...$(u.status)!==void 0&&(i==="server-request"||d.status===void 0)?{status:$(u.status)}:{}};return this.requests.delete(a),this.requests.set(a,b),this.requests.size>this.maxRequests&&this.requests.delete(this.requests.keys().next().value),i==="server-request"?a:void 0}request(e){return e?this.requests.get(e):void 0}enrich(e){const s=this.request(e.requestId),r=e.flowId?this.flows.get(e.flowId):void 0;if(!s&&!r)return e;const o=[...e.routes??[],...s?.route?[s.route]:[],...s?.path?[s.path]:[]];return{...e,...e.service??s?.service?{service:e.service??s?.service}:{},...e.method??s?.method?{method:e.method??s?.method}:{},...o.length?{routes:[...new Set(o)]}:{},...e.status??s?.status!==void 0?{status:e.status??s?.status}:{},...r||e.attributes?{attributes:{...r??{},...e.attributes??{}}}:{}}}}const I=new Map,j=c((t,e)=>t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,e).replace(/\?/g,"."),"globBody");function M(t,e="whole"){const s=`${e}\0${t}`;let r=I.get(s);return r||(r=e==="whole"?new RegExp(`^${j(t,"[\\s\\S]*")}$`,"i"):e==="anywhere"?new RegExp(j(t,"[\\s\\S]*"),"i"):new RegExp(`(?:^|[^\\w.])${j(t,"[\\w.]*")}(?:$|[^\\w.])`,"i"),I.size>1e3&&I.clear(),I.set(s,r)),r}h(M,"S"),c(M,"globRe");const v=c((t,e)=>e!==void 0&&M(t).test(e),"glob");function D(t,e){const s=e.routes??[],r=/^([A-Za-z]+)\s+(\S.*)$/.exec(t);return r&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|\*)$/i.test(r[1])?r[1]!=="*"&&(e.method??"").toUpperCase()!==r[1].toUpperCase()?!1:s.some(o=>v(r[2],o)):s.some(o=>v(t,o))}h(D,"B"),c(D,"routeMatches");function L(t,e){const s=[e.flowId,...e.flowNames??[]].filter(o=>!!o),r=t.endsWith(":")?`${t}*`:t;return s.some(o=>v(r,o))}h(L,"G"),c(L,"flowMatches");function U(t,e){return v(t,e.errorName)||(e.errorKeys??[]).some(s=>v(t,s))?!0:e.message!==void 0&&M(t,"word").test(e.message)}h(U,"W"),c(U,"errorMatches");export function expectedMatches(t,e){return!(t.service!==void 0&&!v(t.service,e.service)||t.route!==void 0&&!D(t.route,e)||t.span!==void 0&&!v(t.span,e.span)||t.flow!==void 0&&!L(t.flow,e)||t.status!==void 0&&e.status!==t.status||t.error!==void 0&&!U(t.error,e)||t.message!==void 0&&!(e.message!==void 0&&M(t.message,"anywhere").test(e.message))||t.attribute!==void 0&&!v(t.attribute.value,e.attributes?.[t.attribute.name]))}h(expectedMatches,"expectedMatches"),c(expectedMatches,"expectedMatches");export function expectedMatchIsPerOccurrence(t){return t.flow!==void 0||t.attribute!==void 0||t.message!==void 0&&/\d/.test(t.message)}h(expectedMatchIsPerOccurrence,"expectedMatchIsPerOccurrence"),c(expectedMatchIsPerOccurrence,"expectedMatchIsPerOccurrence");export function suggestExpectedMatch(t){const e=t.routes?.find(a=>a.startsWith("/")),s=t.flowNames?.find(a=>a.startsWith("job:")&&!a.includes("#"))??(t.flowId?`${t.flowId.split(":")[0]}:`:void 0),r=e?{route:t.method?`${t.method.toUpperCase()} ${e}`:e}:t.span?{span:t.span}:s?{flow:s}:{},o=t.message?.split(`
2
- `)[0]?.replace(/\d+/g,"*").replace(/\*+/g,"*").slice(0,120).trim(),i=t.status!==void 0?{status:t.status}:t.errorName&&t.errorName!=="Error"?{error:t.errorName}:o?{message:o}:{},u=checkExpectedMatch({...t.service?{service:t.service}:{},...r,...i});return"match"in u?u.match:void 0}h(suggestExpectedMatch,"suggestExpectedMatch"),c(suggestExpectedMatch,"suggestExpectedMatch");export const EXPECTED_SURGE_FACTOR=10,EXPECTED_SURGE_MIN_PER_HOUR=20;const Z=2*m,X=24*m,q=6e4;export class ExpectedRuleBook{static{h(this,"ExpectedRuleBook")}static{c(this,"ExpectedRuleBook")}constructor(e=Date.now()){this.startedAt=e,this.runtime=new Map,this.repository=[],this.repositoryKey="",this.stats=new Map,this.ended=[],this.version=0}apply(e,s){const r=readExpectedRule(e);if(!r)return!1;const o=this.runtime.get(r.id);if(this.runtime.delete(r.id),r.kind===EXPECTED_RULE_REMOVED)o&&this.end(o,s,"removed",r.by);else{const{kind:i,...u}=r;if(this.runtime.set(u.id,u),this.stats.has(u.id)||this.stats.set(u.id,{hits:0,minutes:new Map,since:Math.max(u.createdAt,this.startedAt)}),this.runtime.size>J){const a=this.runtime.keys().next().value,d=this.runtime.get(a);this.runtime.delete(a),this.end(d,s,"expired")}}return this.version++,!0}setRepository(e,s){const r=JSON.stringify(e.map(i=>[i.id,i.match,i.reason]));if(r===this.repositoryKey)return!1;const o=new Set(e.map(i=>i.id));for(const i of this.repository)o.has(i.id)||this.end(i,s,"dropped from lensmcp.json");this.repository=e.slice(),this.repositoryKey=r;for(const i of e)this.stats.has(i.id)||this.stats.set(i.id,{hits:0,minutes:new Map,since:Math.max(this.startedAt,Math.min(i.createdAt,s))});return this.version++,!0}expire(e){let s=!1;for(const[r,o]of this.runtime)o.expiresAt===void 0||o.expiresAt>e||(this.runtime.delete(r),this.end(o,o.expiresAt,"expired"),s=!0);return s&&this.version++,s}end(e,s,r,o){this.ended.unshift({...e,endedAt:s,why:r,...o?{removedBy:o}:{}}),this.ended.length>H&&(this.ended.length=H)}active(e){return[...this.repository,...[...this.runtime.values()].filter(s=>s.expiresAt===void 0||s.expiresAt>e)]}get(e){return this.runtime.get(e)??this.repository.find(s=>s.id===e)}isActive(e,s){const r=this.get(e);return!!r&&(r.expiresAt===void 0||r.expiresAt>s)}get size(){return this.runtime.size+this.repository.length}holderOf(e,s){if(this.size!==0)return this.active(s).find(r=>expectedMatches(r.match,e))}count(e,s,r=1){const o=this.stats.get(e);if(!o||r<=0||(o.hits+=r,s===void 0))return;o.lastHitAt=Math.max(o.lastHitAt??0,s);const i=Math.floor(s/q);if(o.minutes.set(i,(o.minutes.get(i)??0)+r),o.minutes.size>1600){const u=i-(X+m)/q;for(const a of o.minutes.keys())a<u&&o.minutes.delete(a)}}windowCount(e,s,r){let o=0;for(const[i,u]of e.minutes)i*q>=s&&i*q<r&&(o+=u);return o}judge(e,s){const r=this.windowCount(e,s-m,s+1),o=Math.max(e.since,s-m-X),i=s-m-o;if(i<Z)return e.surge=void 0;const u=this.windowCount(e,o,s-m)/(i/m),a=Math.max(EXPECTED_SURGE_MIN_PER_HOUR,EXPECTED_SURGE_FACTOR*u);return e.surge?r<a/3?e.surge=void 0:e.surge={...e.surge,lastHour:r}:r>=a&&(e.surge={since:s,lastHour:r,usualPerHour:Math.round(u*10)/10}),e.surge}list(e){return this.active(e).map(s=>{const r=this.stats.get(s.id),o=r?this.judge(r,e):void 0;return{...s,hits:r?.hits??0,...r?.lastHitAt!==void 0?{lastHitAt:r.lastHitAt}:{},lastHour:r?this.windowCount(r,e-m,e+1):0,...o?{surge:o}:{}}}).sort((s,r)=>+(s.by==="repository")-+(r.by==="repository")||r.createdAt-s.createdAt)}endedRules(){return this.ended.slice()}}export function heldBackLine(t,e,s=""){return`${t} rule${t===1?"":"s"} held back ${e} occurrence${e===1?"":"s"}${s?` ${s}`:""}`}h(heldBackLine,"heldBackLine"),c(heldBackLine,"heldBackLine");export function surgeLine(t){const e=t.surge;return`this expected failure is now happening much more often: ${describeExpectedMatch(t.match)} \u2014 ${e?`${e.lastHour} in the last hour, usually ${e.usualPerHour} an hour`:"its rate jumped"} (expected because: ${t.reason})`}h(surgeLine,"surgeLine"),c(surgeLine,"surgeLine");
1
+ "use strict";var K=Object.defineProperty;var h=(t,e)=>K(t,"name",{value:e,configurable:!0});var W=Object.defineProperty,l=h((t,e)=>W(t,"name",{value:e,configurable:!0}),"h"),G=Object.defineProperty,c=l((t,e)=>G(t,"name",{value:e,configurable:!0}),"d");import{LENS_EVENT_SOURCE as J}from"./error-dismissal.js";export const EXPECTED_RULE_SET="expected-rule-set",EXPECTED_RULE_REMOVED="expected-rule-removed";const L=new Set(["dashboard","cli","agent"]),f=60*6e4;export const EXPECTED_RULE_DEFAULT_TTL_MS=168*f,EXPECTED_RULE_MAX_TTL_MS=720*f,EXPECTED_RULE_MIN_REASON_CHARS=8,MAX_EXPECTED_REASON_CHARS=500;const $=300,V=300,D=120,Z=200,U=20,p=c(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),x=c((t,e)=>typeof t=="string"&&t.trim()?t.trim().slice(0,e):void 0,"text"),_=c(t=>!!t&&t.replace(/[*?\s/:.#_-]/g,"").length>=2,"meaningful");export const EXPECTED_SCOPE_FIELDS=["route","span","flow"],EXPECTED_OUTCOME_FIELDS=["status","error","message"];export function checkExpectedMatch(t){if(!p(t))return{error:"a rule needs a match: a flow scope (route, span or flow) and an outcome (status, error or message)"};const e={};for(const r of["service","route","span","flow","error","message"]){const o=t[r];if(o==null||o==="")continue;if(typeof o!="string")return{error:`\`${r}\` must be text`};const i=o.trim();if(i.length>$)return{error:`\`${r}\` is longer than ${$} characters`};i&&(e[r]=i)}if(t.status!==void 0&&t.status!==null&&t.status!==""){const r=typeof t.status=="string"?Number(t.status):t.status;if(typeof r!="number"||!Number.isInteger(r)||r<100||r>599)return{error:"`status` must be an HTTP status (100\u2013599)"};e.status=r}const s=t.attribute;if(s!=null){const r=p(s)?x(s.name,100):void 0,o=p(s)?typeof s.value=="number"?String(s.value):x(s.value,$):void 0;if(!r||!o)return{error:"`attribute` needs a `name` and a `value` (one attribute of the flow, such as a tenant id)"};e.attribute={name:r,value:o}}return EXPECTED_SCOPE_FIELDS.some(r=>_(e[r]))?e.status===void 0&&!_(e.error)&&!_(e.message)?{error:"a rule needs an outcome \u2014 a `status`, an `error` key or a `message` pattern \u2014 saying WHICH failure is expected in that flow"}:{match:e}:{error:`a rule needs a flow scope \u2014 a \`route\`, a \`span\` or a \`flow\` \u2014 not only ${e.service?`the service \xAB${e.service}\xBB`:"an outcome"}: \xABeverything in a service\xBB is not expected, it is unwatched`}}h(checkExpectedMatch,"checkExpectedMatch"),l(checkExpectedMatch,"checkExpectedMatch"),c(checkExpectedMatch,"checkExpectedMatch");export function describeExpectedMatch(t){return[t.service,t.route,t.span,t.flow?`flow ${t.flow}`:void 0,t.status!==void 0?String(t.status):void 0,t.error,t.message?`\xAB${t.message}\xBB`:void 0,t.attribute?`${t.attribute.name}=${t.attribute.value}`:void 0].filter(Boolean).join(" \xB7 ")}h(describeExpectedMatch,"describeExpectedMatch"),l(describeExpectedMatch,"describeExpectedMatch"),c(describeExpectedMatch,"describeExpectedMatch");export function readExpectedRule(t){if(t.source!==J||!p(t.raw))return;const e=t.raw,s=x(e.id,D);if(!s)return;if(e.kind===EXPECTED_RULE_REMOVED)return{kind:EXPECTED_RULE_REMOVED,id:s,...L.has(e.by)?{by:e.by}:{}};if(e.kind!==EXPECTED_RULE_SET||!L.has(e.by))return;const r=x(e.reason,MAX_EXPECTED_REASON_CHARS);if(!r)return;const o=checkExpectedMatch(e.match);if("error"in o)return;const i=Math.min(typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)?e.createdAt:t.timestamp,t.timestamp),u=typeof e.expiresAt=="number"&&Number.isFinite(e.expiresAt)?e.expiresAt:i+EXPECTED_RULE_DEFAULT_TTL_MS,a=x(e.title,V);return{kind:EXPECTED_RULE_SET,id:s,match:o.match,reason:r,by:e.by,createdAt:i,expiresAt:Math.min(u,i+EXPECTED_RULE_MAX_TTL_MS),...a?{title:a}:{}}}h(readExpectedRule,"readExpectedRule"),l(readExpectedRule,"readExpectedRule"),c(readExpectedRule,"readExpectedRule");export function expectedRuleTtlMs(t){return t===void 0||!Number.isFinite(t)||t<=0?EXPECTED_RULE_DEFAULT_TTL_MS:Math.min(Math.round(t*f),EXPECTED_RULE_MAX_TTL_MS)}h(expectedRuleTtlMs,"expectedRuleTtlMs"),l(expectedRuleTtlMs,"expectedRuleTtlMs"),c(expectedRuleTtlMs,"expectedRuleTtlMs");function j(t){let e=2166136261;for(let s=0;s<t.length;s++)e=Math.imul(e^t.charCodeAt(s),16777619);return(e>>>0).toString(36)}h(j,"F"),l(j,"z"),c(j,"hashOf");export function readRepositoryExpectedRules(t,e){const s=[],r=[];return t==null?{rules:s,problems:r}:Array.isArray(t)?(t.forEach((o,i)=>{if(!p(o))return void r.push(`expectedFailures[${i}] is not an object`);const u=checkExpectedMatch(p(o.match)?o.match:o);if("error"in u)return void r.push(`expectedFailures[${i}]: ${u.error}`);const a=x(o.reason,MAX_EXPECTED_REASON_CHARS);if(!a)return void r.push(`expectedFailures[${i}] has no reason \u2014 say why it is expected`);const d=`repository:${x(o.id,D)??j(JSON.stringify(u.match))}`;if(s.some(m=>m.id===d))return void r.push(`expectedFailures[${i}] repeats the id ${d}`);s.push({id:d,match:u.match,reason:a,by:"repository",createdAt:e})}),{rules:s,problems:r}):{rules:s,problems:["expectedFailures is not a list \u2014 no repository rule is read"]}}h(readRepositoryExpectedRules,"readRepositoryExpectedRules"),l(readRepositoryExpectedRules,"readRepositoryExpectedRules"),c(readRepositoryExpectedRules,"readRepositoryExpectedRules");const n=c(t=>typeof t=="string"&&t?t:void 0,"str"),I=c(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),z=c(t=>{const e=t.split(/[?#]/)[0]??t,s=/^[a-z][a-z0-9+.-]*:\/\/[^/]+(\/.*)?$/i.exec(e);return s?s[1]??"/":e},"pathOf"),Q=new Set(["sessionId","flowId","requestId","parentRequestId","runId","traceparent","originNodeId","causedByNodeId","userActionId","browserContextId","frameId","tabId","url","route","projectName"]),S=24;export function eventAttributes(t){let e;const s=c((a,d)=>{if(e&&Object.keys(e).length>=S)return;const m=typeof d=="string"?d:typeof d=="number"||typeof d=="boolean"?String(d):void 0;m===void 0||m.length>$||((e??={})[a]=m)},"put"),r=t.context??{};for(const a of Object.keys(r))Q.has(a)||s(a,r[a]);const o=p(t.raw)?t.raw:void 0;if(!o)return e;const i=p(o.span)?o.span:void 0,u=p(o.request)?o.request:void 0;for(const a of[o.attributes,i?.attributes,u?.attributes,o.data,Array.isArray(i?.args)?i?.args[0]:i?.args])if(p(a))for(const d of Object.keys(a))s(d,a[d]);return e}h(eventAttributes,"eventAttributes"),l(eventAttributes,"eventAttributes"),c(eventAttributes,"eventAttributes");export function failureFacts(t){const e=p(t.raw)?t.raw:{},s=t.context??{},r=p(e.request)?e.request:{},o=p(e.span)?e.span:{},i=p(r.error)?r.error:{},u=p(o.error)?o.error:{},a=p(e.error)?e.error:{},d=n(e.kind),m=[],A=n(r.route)??(d==="egress"?n(e.path):void 0);A&&m.push(A);const y=n(e.url)??n(r.url);y&&m.push(z(y)),d!=="server-request"&&n(s.route)&&m.push(n(s.route));const v=[];if(d==="queue-failed"||d==="queue-enqueued"){const w=n(e.queue),M=e.jobId===void 0||e.jobId===null?void 0:String(e.jobId);w&&v.push(`job:${w}`),M&&v.push(`job:${M}`),w&&M&&v.push(`job:${w}#${M}`),n(e.name)&&v.push(`job:${n(e.name)}`)}const b=[i.errorKey,u.errorKey,a.errorKey,e.errorKey,i.reason,u.reason].map(n).filter(w=>!!w),k=n(i.message)??n(t.message)??n(u.message)??n(a.message)??n(e.failedReason)??n(e.error)??n(e.message)??n(t.title),P=I(r.status)??I(e.status),B=n(s.flowId)??n(o.flowId)??n(r.flowId),F=n(s.requestId)??n(r.requestId)??n(o.requestId),H=eventAttributes(t);return{...n(e.project)??n(s.projectName)?{service:n(e.project)??n(s.projectName)}:{},...n(r.method)??n(e.method)?{method:n(r.method)??n(e.method)}:{},...m.length?{routes:m}:{},...n(o.name)?{span:n(o.name)}:{},...B?{flowId:B}:{},...v.length?{flowNames:v}:{},...P!==void 0?{status:P}:{},...n(i.name)??n(u.name)??n(a.name)?{errorName:n(i.name)??n(u.name)??n(a.name)}:{},...b.length?{errorKeys:b}:{},...k?{message:k}:{},...H?{attributes:H}:{},...F?{requestId:F}:{}}}h(failureFacts,"failureFacts"),l(failureFacts,"failureFacts"),c(failureFacts,"failureFacts");export class FailureContextIndex{static{h(this,"FailureContextIndex")}static{l(this,"FailureContextIndex")}static{c(this,"FailureContextIndex")}constructor(e=5e3,s=2e3){this.maxRequests=e,this.maxFlows=s,this.requests=new Map,this.flows=new Map}observe(e){const s=p(e.raw)?e.raw:void 0,r=e.context??{},o=n(r.flowId);if(o&&(s?.attributes!==void 0||p(s?.span)||r.tenantIdHash!==void 0||r.userIdHash!==void 0||s?.data!==void 0)){const y=eventAttributes(e);if(y){const v=this.flows.get(o);this.flows.delete(o);const b={...v??{},...y};this.flows.set(o,Object.keys(b).length>S?Object.fromEntries(Object.entries(b).slice(-S)):b),this.flows.size>this.maxFlows&&this.flows.delete(this.flows.keys().next().value)}}const i=n(s?.kind);if(!s||i!=="server-request"&&i!=="gateway-request")return;const u=p(s.request)?s.request:s,a=n(r.requestId)??n(u.requestId);if(!a)return;const d=this.requests.get(a)??{},m=n(u.url),A={...d,...n(s.project)&&(i==="server-request"||!d.service)?{service:n(s.project)}:{},...n(u.method)?{method:n(u.method)}:{},...i==="server-request"&&n(u.route)?{route:n(u.route)}:{},...m?{path:z(m)}:{},...I(u.status)!==void 0&&(i==="server-request"||d.status===void 0)?{status:I(u.status)}:{}};return this.requests.delete(a),this.requests.set(a,A),this.requests.size>this.maxRequests&&this.requests.delete(this.requests.keys().next().value),i==="server-request"?a:void 0}request(e){return e?this.requests.get(e):void 0}enrich(e){const s=this.request(e.requestId),r=e.flowId?this.flows.get(e.flowId):void 0;if(!s&&!r)return e;const o=[...e.routes??[],...s?.route?[s.route]:[],...s?.path?[s.path]:[]];return{...e,...e.service??s?.service?{service:e.service??s?.service}:{},...e.method??s?.method?{method:e.method??s?.method}:{},...o.length?{routes:[...new Set(o)]}:{},...e.status??s?.status!==void 0?{status:e.status??s?.status}:{},...r||e.attributes?{attributes:{...r??{},...e.attributes??{}}}:{}}}}const R=new Map,C=c((t,e)=>t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,e).replace(/\?/g,"."),"globBody");function E(t,e="whole"){const s=`${e}\0${t}`;let r=R.get(s);return r||(r=e==="whole"?new RegExp(`^${C(t,"[\\s\\S]*")}$`,"i"):e==="anywhere"?new RegExp(C(t,"[\\s\\S]*"),"i"):new RegExp(`(?:^|[^\\w.])${C(t,"[\\w.]*")}(?:$|[^\\w.])`,"i"),R.size>1e3&&R.clear(),R.set(s,r)),r}h(E,"M"),l(E,"S"),c(E,"globRe");const g=c((t,e)=>e!==void 0&&E(t).test(e),"glob");function T(t,e){const s=e.routes??[],r=/^([A-Za-z]+)\s+(\S.*)$/.exec(t);return r&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|\*)$/i.test(r[1])?r[1]!=="*"&&(e.method??"").toUpperCase()!==r[1].toUpperCase()?!1:s.some(o=>g(r[2],o)):s.some(o=>g(t,o))}h(T,"D"),l(T,"B"),c(T,"routeMatches");function O(t,e){const s=[e.flowId,...e.flowNames??[]].filter(o=>!!o),r=t.endsWith(":")?`${t}*`:t;return s.some(o=>g(r,o))}h(O,"L"),l(O,"G"),c(O,"flowMatches");function N(t,e){return g(t,e.errorName)||(e.errorKeys??[]).some(s=>g(t,s))?!0:e.message!==void 0&&E(t,"word").test(e.message)}h(N,"U"),l(N,"W"),c(N,"errorMatches");export function expectedMatches(t,e){return!(t.service!==void 0&&!g(t.service,e.service)||t.route!==void 0&&!T(t.route,e)||t.span!==void 0&&!g(t.span,e.span)||t.flow!==void 0&&!O(t.flow,e)||t.status!==void 0&&e.status!==t.status||t.error!==void 0&&!N(t.error,e)||t.message!==void 0&&!(e.message!==void 0&&E(t.message,"anywhere").test(e.message))||t.attribute!==void 0&&!g(t.attribute.value,e.attributes?.[t.attribute.name]))}h(expectedMatches,"expectedMatches"),l(expectedMatches,"expectedMatches"),c(expectedMatches,"expectedMatches");export function expectedMatchIsPerOccurrence(t){return t.flow!==void 0||t.attribute!==void 0||t.message!==void 0&&/\d/.test(t.message)}h(expectedMatchIsPerOccurrence,"expectedMatchIsPerOccurrence"),l(expectedMatchIsPerOccurrence,"expectedMatchIsPerOccurrence"),c(expectedMatchIsPerOccurrence,"expectedMatchIsPerOccurrence");export function suggestExpectedMatch(t){const e=t.routes?.find(a=>a.startsWith("/")),s=t.flowNames?.find(a=>a.startsWith("job:")&&!a.includes("#"))??(t.flowId?`${t.flowId.split(":")[0]}:`:void 0),r=e?{route:t.method?`${t.method.toUpperCase()} ${e}`:e}:t.span?{span:t.span}:s?{flow:s}:{},o=t.message?.split(`
2
+ `)[0]?.replace(/\d+/g,"*").replace(/\*+/g,"*").slice(0,120).trim(),i=t.status!==void 0?{status:t.status}:t.errorName&&t.errorName!=="Error"?{error:t.errorName}:o?{message:o}:{},u=checkExpectedMatch({...t.service?{service:t.service}:{},...r,...i});return"match"in u?u.match:void 0}h(suggestExpectedMatch,"suggestExpectedMatch"),l(suggestExpectedMatch,"suggestExpectedMatch"),c(suggestExpectedMatch,"suggestExpectedMatch");export const EXPECTED_SURGE_FACTOR=10,EXPECTED_SURGE_MIN_PER_HOUR=20;const Y=2*f,X=24*f,q=6e4;export class ExpectedRuleBook{static{h(this,"ExpectedRuleBook")}static{l(this,"ExpectedRuleBook")}static{c(this,"ExpectedRuleBook")}constructor(e=Date.now()){this.startedAt=e,this.runtime=new Map,this.repository=[],this.repositoryKey="",this.stats=new Map,this.ended=[],this.version=0}apply(e,s){const r=readExpectedRule(e);if(!r)return!1;const o=this.runtime.get(r.id);if(this.runtime.delete(r.id),r.kind===EXPECTED_RULE_REMOVED)o&&this.end(o,s,"removed",r.by);else{const{kind:i,...u}=r;if(this.runtime.set(u.id,u),this.stats.has(u.id)||this.stats.set(u.id,{hits:0,minutes:new Map,since:Math.max(u.createdAt,this.startedAt)}),this.runtime.size>Z){const a=this.runtime.keys().next().value,d=this.runtime.get(a);this.runtime.delete(a),this.end(d,s,"expired")}}return this.version++,!0}setRepository(e,s){const r=JSON.stringify(e.map(i=>[i.id,i.match,i.reason]));if(r===this.repositoryKey)return!1;const o=new Set(e.map(i=>i.id));for(const i of this.repository)o.has(i.id)||this.end(i,s,"dropped from lensmcp.json");this.repository=e.slice(),this.repositoryKey=r;for(const i of e)this.stats.has(i.id)||this.stats.set(i.id,{hits:0,minutes:new Map,since:Math.max(this.startedAt,Math.min(i.createdAt,s))});return this.version++,!0}expire(e){let s=!1;for(const[r,o]of this.runtime)o.expiresAt===void 0||o.expiresAt>e||(this.runtime.delete(r),this.end(o,o.expiresAt,"expired"),s=!0);return s&&this.version++,s}end(e,s,r,o){this.ended.unshift({...e,endedAt:s,why:r,...o?{removedBy:o}:{}}),this.ended.length>U&&(this.ended.length=U)}active(e){return[...this.repository,...[...this.runtime.values()].filter(s=>s.expiresAt===void 0||s.expiresAt>e)]}get(e){return this.runtime.get(e)??this.repository.find(s=>s.id===e)}isActive(e,s){const r=this.get(e);return!!r&&(r.expiresAt===void 0||r.expiresAt>s)}get size(){return this.runtime.size+this.repository.length}holderOf(e,s){if(this.size!==0)return this.active(s).find(r=>expectedMatches(r.match,e))}count(e,s,r=1){const o=this.stats.get(e);if(!o||r<=0||(o.hits+=r,s===void 0))return;o.lastHitAt=Math.max(o.lastHitAt??0,s);const i=Math.floor(s/q);if(o.minutes.set(i,(o.minutes.get(i)??0)+r),o.minutes.size>1600){const u=i-(X+f)/q;for(const a of o.minutes.keys())a<u&&o.minutes.delete(a)}}windowCount(e,s,r){let o=0;for(const[i,u]of e.minutes)i*q>=s&&i*q<r&&(o+=u);return o}judge(e,s){const r=this.windowCount(e,s-f,s+1),o=Math.max(e.since,s-f-X),i=s-f-o;if(i<Y)return e.surge=void 0;const u=this.windowCount(e,o,s-f)/(i/f),a=Math.max(EXPECTED_SURGE_MIN_PER_HOUR,EXPECTED_SURGE_FACTOR*u);return e.surge?r<a/3?e.surge=void 0:e.surge={...e.surge,lastHour:r}:r>=a&&(e.surge={since:s,lastHour:r,usualPerHour:Math.round(u*10)/10}),e.surge}list(e){return this.active(e).map(s=>{const r=this.stats.get(s.id),o=r?this.judge(r,e):void 0;return{...s,hits:r?.hits??0,...r?.lastHitAt!==void 0?{lastHitAt:r.lastHitAt}:{},lastHour:r?this.windowCount(r,e-f,e+1):0,...o?{surge:o}:{}}}).sort((s,r)=>+(s.by==="repository")-+(r.by==="repository")||r.createdAt-s.createdAt)}endedRules(){return this.ended.slice()}}export function heldBackLine(t,e,s=""){return`${t} rule${t===1?"":"s"} held back ${e} occurrence${e===1?"":"s"}${s?` ${s}`:""}`}h(heldBackLine,"heldBackLine"),l(heldBackLine,"heldBackLine"),c(heldBackLine,"heldBackLine");export function surgeLine(t){const e=t.surge;return`this expected failure is now happening much more often: ${describeExpectedMatch(t.match)} \u2014 ${e?`${e.lastHour} in the last hour, usually ${e.usualPerHour} an hour`:"its rate jumped"} (expected because: ${t.reason})`}h(surgeLine,"surgeLine"),l(surgeLine,"surgeLine"),c(surgeLine,"surgeLine");
@@ -1 +1 @@
1
- "use strict";var s=Object.defineProperty;var a=(e,t)=>s(e,"name",{value:t,configurable:!0});var o=Object.defineProperty,r=a((e,t)=>o(e,"name",{value:t,configurable:!0}),"s");export const FINDING_RISK_CLASSES=["same-bytes","after-the-model","moved-content","less-text-or-schema","new-mechanism"],FINDING_RISK_CLASS={"same-bytes":{label:"Same bytes",reads:"the model reads the same bytes",example:"breakpoints, a prewarm, the order requests are sent",proof:"a byte-identity spec (the new request, joined, is the old one byte for byte) and a cost measurement"},"after-the-model":{label:"After the model",reads:"the model reads the same bytes; code after it changes",example:"dropping a finding that code adds to the answer",proof:"a free replay: the same recorded answers through the old and the new code, everything else byte-equal"},"moved-content":{label:"Moved content",reads:"the model reads the same content in another place or order",example:"cache levels, moving a section",proof:"a paired comparison: before and after side by side, in one session, more than one run a side"},"less-text-or-schema":{label:"Less text or a new schema",reads:"the model reads less text, or a changed schema or instruction",example:"shorter rows, field order, a fact stated once",proof:"the full accuracy comparison"},"new-mechanism":{label:"New mechanism",reads:"the model is asked in a new way",example:"grouping products in one call",proof:"a design first"}};const n={"same-bytes":"same-bytes","same-bytes-read":"same-bytes","byte-identical":"same-bytes","after-the-model":"after-the-model","after-model":"after-the-model","code-after-the-model":"after-the-model","code-after-model":"after-the-model","moved-content":"moved-content",moved:"moved-content","same-content-moved":"moved-content","less-text-or-schema":"less-text-or-schema","less-text":"less-text-or-schema","changed-schema":"less-text-or-schema","less-text-or-a-changed-schema":"less-text-or-schema","new-mechanism":"new-mechanism",new:"new-mechanism"};export function readRiskClass(e){if(typeof e!="string")return;const t=e.trim().toLowerCase().replace(/[\s_]+/g,"-");return n[t]}a(readRiskClass,"readRiskClass"),r(readRiskClass,"readRiskClass");export const FINDING_PROOF_ASK=[`"riskClass": one of ${FINDING_RISK_CLASSES.map(e=>`"${e}"`).join(" | ")} \u2014 what the model reads after the change (${FINDING_RISK_CLASSES.map(e=>`${e}: ${FINDING_RISK_CLASS[e].reads}`).join("; ")}); in doubt, the riskier`,`"proofOwed": "what must be shown before it ships \u2014 its class's proof (${FINDING_RISK_CLASSES.map(e=>`${e}: ${FINDING_RISK_CLASS[e].proof}`).join("; ")}), made concrete for this change: which spec, which calls, how many runs a side"`,`"saving": { "amount": "what it saves, with its unit and per what ('$0.18 per run', '12,000 input tokens a call', '120 s off the stage')", "arithmetic": "the formula with the evidence's numbers and the prices it used", "kind": "estimate" | "measured" (measured only when the evidence holds calls from before and after the change) } or null when it saves nothing countable`];
1
+ "use strict";var o=Object.defineProperty;var a=(e,t)=>o(e,"name",{value:t,configurable:!0});var r=Object.defineProperty,s=a((e,t)=>r(e,"name",{value:t,configurable:!0}),"a"),n=Object.defineProperty,d=s((e,t)=>n(e,"name",{value:t,configurable:!0}),"s");export const FINDING_RISK_CLASSES=["same-bytes","after-the-model","moved-content","less-text-or-schema","new-mechanism"],FINDING_RISK_CLASS={"same-bytes":{label:"Same bytes",reads:"the model reads the same bytes",example:"breakpoints, a prewarm, the order requests are sent",proof:"a byte-identity spec (the new request, joined, is the old one byte for byte) and a cost measurement"},"after-the-model":{label:"After the model",reads:"the model reads the same bytes; code after it changes",example:"dropping a finding that code adds to the answer",proof:"a free replay: the same recorded answers through the old and the new code, everything else byte-equal"},"moved-content":{label:"Moved content",reads:"the model reads the same content in another place or order",example:"cache levels, moving a section",proof:"a paired comparison: before and after side by side, in one session, more than one run a side"},"less-text-or-schema":{label:"Less text or a new schema",reads:"the model reads less text, or a changed schema or instruction",example:"shorter rows, field order, a fact stated once",proof:"the full accuracy comparison"},"new-mechanism":{label:"New mechanism",reads:"the model is asked in a new way",example:"grouping products in one call",proof:"a design first"}};const m={"same-bytes":"same-bytes","same-bytes-read":"same-bytes","byte-identical":"same-bytes","after-the-model":"after-the-model","after-model":"after-the-model","code-after-the-model":"after-the-model","code-after-model":"after-the-model","moved-content":"moved-content",moved:"moved-content","same-content-moved":"moved-content","less-text-or-schema":"less-text-or-schema","less-text":"less-text-or-schema","changed-schema":"less-text-or-schema","less-text-or-a-changed-schema":"less-text-or-schema","new-mechanism":"new-mechanism",new:"new-mechanism"};export function readRiskClass(e){if(typeof e!="string")return;const t=e.trim().toLowerCase().replace(/[\s_]+/g,"-");return m[t]}a(readRiskClass,"readRiskClass"),s(readRiskClass,"readRiskClass"),d(readRiskClass,"readRiskClass");export const FINDING_PROOF_ASK=[`"riskClass": one of ${FINDING_RISK_CLASSES.map(e=>`"${e}"`).join(" | ")} \u2014 what the model reads after the change (${FINDING_RISK_CLASSES.map(e=>`${e}: ${FINDING_RISK_CLASS[e].reads}`).join("; ")}); in doubt, the riskier`,`"proofOwed": "what must be shown before it ships \u2014 its class's proof (${FINDING_RISK_CLASSES.map(e=>`${e}: ${FINDING_RISK_CLASS[e].proof}`).join("; ")}), made concrete for this change: which spec, which calls, how many runs a side"`,`"saving": { "amount": "what it saves, with its unit and per what ('$0.18 per run', '12,000 input tokens a call', '120 s off the stage')", "arithmetic": "the formula with the evidence's numbers and the prices it used", "kind": "estimate" | "measured" (measured only when the evidence holds calls from before and after the change) } or null when it saves nothing countable`];
@@ -1 +1 @@
1
- "use strict";var S=Object.defineProperty;var i=(t,n)=>S(t,"name",{value:n,configurable:!0});var m=Object.defineProperty,u=i((t,n)=>m(t,"name",{value:n,configurable:!0}),"o");function d(){const t=typeof process<"u"?process.env?.LENSMCP_EVENT_MAX_EPS:void 0;if(t===void 0||t==="")return;if(t==="off")return"off";const n=Number(t);if(Number.isFinite(n))return n<=0?"off":n}i(d,"S"),u(d,"envPerSec");export function createEventFloodGuard(t){const n=t?.envOverride===!1?void 0:d();if(n==="off")return{admit:u(()=>({ok:!0,suppressed:0}),"admit")};const l=n??t?.perSec??5,f=Math.max(1,t?.burst??Math.max(30,l*4)),c=t?.maxKeys??2048,r=new Map,p=u(o=>{for(const[s,e]of r)o-e.lastSeenAt>6e4&&r.delete(s);if(r.size>c){const s=[...r.entries()].sort((e,a)=>e[1].lastSeenAt-a[1].lastSeenAt);for(let e=0;e<s.length>>1;e++)r.delete(s[e][0])}},"evictStale");return{admit(o){const s=Date.now();let e=r.get(o);e||(r.size>=c&&p(s),e={tokens:f,lastRefillAt:s,suppressed:0,lastSeenAt:s},r.set(o,e)),e.lastSeenAt=s;const a=s-e.lastRefillAt;if(a>0&&(e.tokens=Math.min(f,e.tokens+a/1e3*l),e.lastRefillAt=s),e.tokens>=1){e.tokens-=1;const v=e.suppressed;return e.suppressed=0,{ok:!0,suppressed:v}}return e.suppressed+=1,{ok:!1,suppressed:0}}}}i(createEventFloodGuard,"createEventFloodGuard"),u(createEventFloodGuard,"createEventFloodGuard");
1
+ "use strict";var S=Object.defineProperty;var i=(t,s)=>S(t,"name",{value:s,configurable:!0});var A=Object.defineProperty,f=i((t,s)=>A(t,"name",{value:s,configurable:!0}),"i"),k=Object.defineProperty,u=f((t,s)=>k(t,"name",{value:s,configurable:!0}),"o");function l(){const t=typeof process<"u"?process.env?.LENSMCP_EVENT_MAX_EPS:void 0;if(t===void 0||t==="")return;if(t==="off")return"off";const s=Number(t);if(Number.isFinite(s))return s<=0?"off":s}i(l,"d"),f(l,"S"),u(l,"envPerSec");export function createEventFloodGuard(t){const s=t?.envOverride===!1?void 0:l();if(s==="off")return{admit:u(()=>({ok:!0,suppressed:0}),"admit")};const c=s??t?.perSec??5,d=Math.max(1,t?.burst??Math.max(30,c*4)),p=t?.maxKeys??2048,n=new Map,v=u(o=>{for(const[r,e]of n)o-e.lastSeenAt>6e4&&n.delete(r);if(n.size>p){const r=[...n.entries()].sort((e,a)=>e[1].lastSeenAt-a[1].lastSeenAt);for(let e=0;e<r.length>>1;e++)n.delete(r[e][0])}},"evictStale");return{admit(o){const r=Date.now();let e=n.get(o);e||(n.size>=p&&v(r),e={tokens:d,lastRefillAt:r,suppressed:0,lastSeenAt:r},n.set(o,e)),e.lastSeenAt=r;const a=r-e.lastRefillAt;if(a>0&&(e.tokens=Math.min(d,e.tokens+a/1e3*c),e.lastRefillAt=r),e.tokens>=1){e.tokens-=1;const m=e.suppressed;return e.suppressed=0,{ok:!0,suppressed:m}}return e.suppressed+=1,{ok:!1,suppressed:0}}}}i(createEventFloodGuard,"createEventFloodGuard"),f(createEventFloodGuard,"createEventFloodGuard"),u(createEventFloodGuard,"createEventFloodGuard");
@@ -1 +1 @@
1
- "use strict";var i=Object.defineProperty;var a=(n,e)=>i(n,"name",{value:e,configurable:!0});var o=Object.defineProperty,r=a((n,e)=>o(n,"name",{value:e,configurable:!0}),"a");export const DESIGN_TYPES=["bug","investigation","performance","reliability","feature","architecture","maintenance"],DESIGN_CONCERNS=["security","data","api","ui","integration","operations"],DESIGN_TYPE_INFO={bug:{label:"Bug",when:"Something works wrong, and the cause is known or can be found by reading the code."},investigation:{label:"Investigation",when:"Symptoms without a known cause: research first, and the goal ends in a decision or a fix."},performance:{label:"Performance",when:"Something is measurably slow, heavy or costly: a baseline the lens measured and a target."},reliability:{label:"Reliability",when:"Crashes, stalls, flaky tests, lost work, CI or the machine: how it fails and how often."},feature:{label:"Feature",when:"Someone can do something they cannot do now."},architecture:{label:"Architecture",when:"Boundaries, contracts or structure change, in steps that each ship."},maintenance:{label:"Maintenance",when:"Upgrades, moves, tooling and cleanup: no new behaviour, and nothing breaks."}},DESIGN_CONCERN_INFO={security:{label:"Security",when:"Auth, permissions, secrets, input from outside, or anything an attacker would read."},data:{label:"Data",when:"Schema, migrations, backfills, or data already stored."},api:{label:"API",when:"A request or response other code or other people depend on."},ui:{label:"UI",when:"Screens, flows or what a person sees."},integration:{label:"Integration",when:"A service outside the repository: its API, keys, limits and failures."},operations:{label:"Operations",when:"How it deploys, runs, is watched and is rolled back."}},DESIGN_STAGES=["proposed","requested","drafting","waiting","changes","approved","declined"];export function designWriter(n){if(n.writer)return n.writer;if(n.by==="user")return{kind:"person"};if(n.by==="lensmcp")return{kind:"lensmcp",...n.byName?{name:n.byName}:{}}}a(designWriter,"designWriter"),r(designWriter,"designWriter");const s={claude:"Claude Code",codex:"Codex"};export function designWriterText(n){const e=designWriter(n);if(!e)return"who handed it in was not recorded";const t=e.client?s[e.client]:void 0;switch(e.kind){case"person":return"written by the person";case"lensmcp":return"written by LensMCP's own run";case"terminal":return"handed in from a terminal, as the overseer";case"session":return`handed in by ${t?`a ${t}`:"an agent's"} session${e.role?`, the team's ${e.role}`:" with no role on this team"}`;case"launch":return e.purpose==="design"?`written by a design launch${t?` on ${t}`:""}`:`handed in by the overseer's ${e.purpose==="inbox"?"inbox launch":e.purpose==="round"?"round":"launch"}${t?` on ${t}`:""}`}}a(designWriterText,"designWriterText"),r(designWriterText,"designWriterText");
1
+ "use strict";var o=Object.defineProperty;var t=(n,e)=>o(n,"name",{value:e,configurable:!0});var s=Object.defineProperty,a=t((n,e)=>s(n,"name",{value:e,configurable:!0}),"a"),l=Object.defineProperty,i=a((n,e)=>l(n,"name",{value:e,configurable:!0}),"a");export const DESIGN_TYPES=["bug","investigation","performance","reliability","feature","architecture","maintenance"],DESIGN_CONCERNS=["security","data","api","ui","integration","operations"],DESIGN_TYPE_INFO={bug:{label:"Bug",when:"Something works wrong, and the cause is known or can be found by reading the code."},investigation:{label:"Investigation",when:"Symptoms without a known cause: research first, and the goal ends in a decision or a fix."},performance:{label:"Performance",when:"Something is measurably slow, heavy or costly: a baseline the lens measured and a target."},reliability:{label:"Reliability",when:"Crashes, stalls, flaky tests, lost work, CI or the machine: how it fails and how often."},feature:{label:"Feature",when:"Someone can do something they cannot do now."},architecture:{label:"Architecture",when:"Boundaries, contracts or structure change, in steps that each ship."},maintenance:{label:"Maintenance",when:"Upgrades, moves, tooling and cleanup: no new behaviour, and nothing breaks."}},DESIGN_CONCERN_INFO={security:{label:"Security",when:"Auth, permissions, secrets, input from outside, or anything an attacker would read."},data:{label:"Data",when:"Schema, migrations, backfills, or data already stored."},api:{label:"API",when:"A request or response other code or other people depend on."},ui:{label:"UI",when:"Screens, flows or what a person sees."},integration:{label:"Integration",when:"A service outside the repository: its API, keys, limits and failures."},operations:{label:"Operations",when:"How it deploys, runs, is watched and is rolled back."}},DESIGN_STAGES=["proposed","requested","drafting","waiting","changes","approved","declined"];export function designWriter(n){if(n.writer)return n.writer;if(n.by==="user")return{kind:"person"};if(n.by==="lensmcp")return{kind:"lensmcp",...n.byName?{name:n.byName}:{}}}t(designWriter,"designWriter"),a(designWriter,"designWriter"),i(designWriter,"designWriter");const c={claude:"Claude Code",codex:"Codex"};export function designWriterText(n){const e=designWriter(n);if(!e)return"who handed it in was not recorded";const r=e.client?c[e.client]:void 0;switch(e.kind){case"person":return"written by the person";case"lensmcp":return"written by LensMCP's own run";case"terminal":return"handed in from a terminal, as the overseer";case"session":return`handed in by ${r?`a ${r}`:"an agent's"} session${e.role?`, the team's ${e.role}`:" with no role on this team"}`;case"launch":return e.purpose==="design"?`written by a design launch${r?` on ${r}`:""}`:`handed in by the overseer's ${e.purpose==="inbox"?"inbox launch":e.purpose==="round"?"round":"launch"}${r?` on ${r}`:""}`}}t(designWriterText,"designWriterText"),a(designWriterText,"designWriterText"),i(designWriterText,"designWriterText");
@@ -1 +1 @@
1
- "use strict";var A=Object.defineProperty;var s=(t,e)=>A(t,"name",{value:e,configurable:!0});var c=Object.defineProperty,o=s((t,e)=>c(t,"name",{value:e,configurable:!0}),"o");export const HOST_AGENT_CLIENTS=["claude","codex"],HOST_AGENTS_FILES={agents:"host-agents.json",ceilings:"host-ceilings.json"},HOST_AGENTS_LIMITS={accounts:32,windows:6,label:60,why:300,plan:40,name:40,agents:64},HOST_ACCOUNT_ID=/^ac-[a-z0-9]{1,12}-[a-f0-9]{6}$/;const n=[/\bsk-[A-Za-z0-9_-]{16,}/,/\b[rs]k_(?:live|test)_[A-Za-z0-9]{12,}/,/\bgh[pousr]_[A-Za-z0-9]{20,}|\bgithub_pat_[A-Za-z0-9_]{20,}/,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/,/\bxox[abposr]-[A-Za-z0-9-]{10,}/,/\bAIza[0-9A-Za-z_-]{30,}/,/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{4,}/,/-----BEGIN [A-Z ]*(?:PRIVATE KEY|CERTIFICATE)-----/,/\bbearer\s+[A-Za-z0-9._~+/=-]{12,}/i],r=/[A-Za-z0-9+/_=-]{32,}/g;export function tokenShaped(t){if(n.some(e=>e.test(t)))return!0;for(const e of t.match(r)??[])if(/\d/.test(e)&&/[A-Za-z]/.test(e))return!0;return!1}s(tokenShaped,"tokenShaped"),o(tokenShaped,"tokenShaped");export function withoutTokens(t){let e=t;for(const a of n)e=e.replace(new RegExp(a.source,a.flags.includes("g")?a.flags:`${a.flags}g`),"\u2026");return e.replace(r,a=>/\d/.test(a)&&/[A-Za-z]/.test(a)?"\u2026":a)}s(withoutTokens,"withoutTokens"),o(withoutTokens,"withoutTokens");
1
+ "use strict";var c=Object.defineProperty;var o=(t,e)=>c(t,"name",{value:e,configurable:!0});var u=Object.defineProperty,n=o((t,e)=>u(t,"name",{value:e,configurable:!0}),"s"),i=Object.defineProperty,s=n((t,e)=>i(t,"name",{value:e,configurable:!0}),"o");export const HOST_AGENT_CLIENTS=["claude","codex"],HOST_AGENTS_FILES={agents:"host-agents.json",ceilings:"host-ceilings.json"},HOST_AGENTS_LIMITS={accounts:32,windows:6,label:60,why:300,plan:40,name:40,agents:64},HOST_ACCOUNT_ID=/^ac-[a-z0-9]{1,12}-[a-f0-9]{6}$/;const r=[/\bsk-[A-Za-z0-9_-]{16,}/,/\b[rs]k_(?:live|test)_[A-Za-z0-9]{12,}/,/\bgh[pousr]_[A-Za-z0-9]{20,}|\bgithub_pat_[A-Za-z0-9_]{20,}/,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/,/\bxox[abposr]-[A-Za-z0-9-]{10,}/,/\bAIza[0-9A-Za-z_-]{30,}/,/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{4,}/,/-----BEGIN [A-Z ]*(?:PRIVATE KEY|CERTIFICATE)-----/,/\bbearer\s+[A-Za-z0-9._~+/=-]{12,}/i],A=/[A-Za-z0-9+/_=-]{32,}/g;export function tokenShaped(t){if(r.some(e=>e.test(t)))return!0;for(const e of t.match(A)??[])if(/\d/.test(e)&&/[A-Za-z]/.test(e))return!0;return!1}o(tokenShaped,"tokenShaped"),n(tokenShaped,"tokenShaped"),s(tokenShaped,"tokenShaped");export function withoutTokens(t){let e=t;for(const a of r)e=e.replace(new RegExp(a.source,a.flags.includes("g")?a.flags:`${a.flags}g`),"\u2026");return e.replace(A,a=>/\d/.test(a)&&/[A-Za-z]/.test(a)?"\u2026":a)}o(withoutTokens,"withoutTokens"),n(withoutTokens,"withoutTokens"),s(withoutTokens,"withoutTokens");
@@ -1 +1 @@
1
- "use strict";var k=Object.defineProperty;var g=(e,n)=>k(e,"name",{value:n,configurable:!0});var v=Object.defineProperty,d=g((e,n)=>v(e,"name",{value:n,configurable:!0}),"i");import{TRUNCATION_MARKER_KEY as C}from"./bounded-clone.js";export const LINT_COVER_KIND="lint-cover",MAX_LINT_UNCOMMITTED=500;const A=["tree","paths","changed","incremental"],h=d(e=>Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.length>0):[],"strings"),i=d(e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0,"count"),l=d(e=>typeof e=="string"&&e?e:void 0,"text");export function readLintCoverage(e){if(!e||typeof e!="object"||e[C])return;const n=e.coverage;if(!n||typeof n!="object")return;const t=n,r=t.kind,s=t.root;if(!A.includes(r)||typeof s!="string"||!s)return;const f=h(t.dirs),o=h(t.files),p=h(t.gone),m=i(t.notLinted),$=i(t.untracked),a=t.base&&typeof t.base=="object"?t.base:void 0,y=a&&l(a.sha)&&l(a.run)?{from:a.from==="main"?"main":"own",sha:a.sha,run:a.run}:void 0,b=Array.isArray(t.inputs)?t.inputs.flatMap(u=>Array.isArray(u)&&typeof u[0]=="string"&&typeof u[1]=="string"?[[u[0],u[1]]]:[]):void 0;return{kind:r,root:s,dirs:f,files:o,gone:p,fileCount:i(t.fileCount)??o.length,goneCount:i(t.goneCount)??p.length,linted:i(t.linted)??0,...i(t.dirCount)!==void 0?{dirCount:i(t.dirCount)}:{},...m?{notLinted:m}:{},...$?{untracked:$}:{},...l(t.since)?{since:t.since}:{},...l(t.head)?{head:t.head}:{},...typeof t.dirty=="boolean"?{dirty:t.dirty}:{},...Array.isArray(t.uncommitted)?{uncommitted:h(t.uncommitted)}:{},...t.uncommittedMore===!0?{uncommittedMore:!0}:{},...b?{inputs:b}:{},...l(t.folder)?{folder:t.folder}:{},...t.projects===!0?{projects:!0}:{},...y?{base:y}:{},...t.fromZero===!0?{fromZero:!0}:{},...t.narrowed===!0?{narrowed:!0}:{}}}g(readLintCoverage,"readLintCoverage"),d(readLintCoverage,"readLintCoverage");const c=d((e,n)=>`${e} ${n}${e===1?"":"s"}`,"some");export function lintCoverageLabel(e,n={}){const t=e.files??0,r=e.gone??0;if(e.kind==="changed"){const o=`since ${e.since??"HEAD"}`;if(!t)return`${c(r,"deleted file")} ${o}`;const p=n.untracked&&e.untracked?` (${e.untracked} untracked)`:"";return`${c(t,"changed file")} ${o}${p}${r?`, ${r} deleted`:""}`}if(e.kind==="incremental"){const o=e.since?` since ${e.since.slice(0,7)}`:"";return!t&&!r?`nothing changed${o}`:t?`${c(t,"file")} changed${o}${r?`, ${r} deleted`:""}`:`${c(r,"file")} deleted${o}`}if(e.kind==="tree"&&e.projects)return`the workspace\u2019s ${c(e.projects,"project")}`;if(e.kind==="tree"&&e.paths[0]===".")return"whole checkout";if(e.narrowed)return`${c(t,"file")} ESLint linted with the caller\u2019s arguments`;const s=e.paths.slice(0,3).join(", "),f=(e.more??0)+Math.max(0,e.paths.length-3);return f?`${s} +${f} more`:s}g(lintCoverageLabel,"lintCoverageLabel"),d(lintCoverageLabel,"lintCoverageLabel");
1
+ "use strict";var C=Object.defineProperty;var p=(e,r)=>C(e,"name",{value:r,configurable:!0});var k=Object.defineProperty,h=p((e,r)=>k(e,"name",{value:r,configurable:!0}),"g"),A=Object.defineProperty,d=h((e,r)=>A(e,"name",{value:r,configurable:!0}),"i");import{TRUNCATION_MARKER_KEY as j}from"./bounded-clone.js";export const LINT_COVER_KIND="lint-cover",MAX_LINT_UNCOMMITTED=500;const L=["tree","paths","changed","incremental"],m=d(e=>Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[],"strings"),i=d(e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0,"count"),l=d(e=>typeof e=="string"&&e?e:void 0,"text");export function readLintCoverage(e){if(!e||typeof e!="object"||e[j])return;const r=e.coverage;if(!r||typeof r!="object")return;const t=r,n=t.kind,a=t.root;if(!L.includes(n)||typeof a!="string"||!a)return;const u=m(t.dirs),o=m(t.files),g=m(t.gone),$=i(t.notLinted),y=i(t.untracked),s=t.base&&typeof t.base=="object"?t.base:void 0,v=s&&l(s.sha)&&l(s.run)?{from:s.from==="main"?"main":"own",sha:s.sha,run:s.run}:void 0,b=Array.isArray(t.inputs)?t.inputs.flatMap(f=>Array.isArray(f)&&typeof f[0]=="string"&&typeof f[1]=="string"?[[f[0],f[1]]]:[]):void 0;return{kind:n,root:a,dirs:u,files:o,gone:g,fileCount:i(t.fileCount)??o.length,goneCount:i(t.goneCount)??g.length,linted:i(t.linted)??0,...i(t.dirCount)!==void 0?{dirCount:i(t.dirCount)}:{},...$?{notLinted:$}:{},...y?{untracked:y}:{},...l(t.since)?{since:t.since}:{},...l(t.head)?{head:t.head}:{},...typeof t.dirty=="boolean"?{dirty:t.dirty}:{},...Array.isArray(t.uncommitted)?{uncommitted:m(t.uncommitted)}:{},...t.uncommittedMore===!0?{uncommittedMore:!0}:{},...b?{inputs:b}:{},...l(t.folder)?{folder:t.folder}:{},...t.projects===!0?{projects:!0}:{},...v?{base:v}:{},...t.fromZero===!0?{fromZero:!0}:{},...t.narrowed===!0?{narrowed:!0}:{}}}p(readLintCoverage,"readLintCoverage"),h(readLintCoverage,"readLintCoverage"),d(readLintCoverage,"readLintCoverage");const c=d((e,r)=>`${e} ${r}${e===1?"":"s"}`,"some");export function lintCoverageLabel(e,r={}){const t=e.files??0,n=e.gone??0;if(e.kind==="changed"){const o=`since ${e.since??"HEAD"}`;if(!t)return`${c(n,"deleted file")} ${o}`;const g=r.untracked&&e.untracked?` (${e.untracked} untracked)`:"";return`${c(t,"changed file")} ${o}${g}${n?`, ${n} deleted`:""}`}if(e.kind==="incremental"){const o=e.since?` since ${e.since.slice(0,7)}`:"";return!t&&!n?`nothing changed${o}`:t?`${c(t,"file")} changed${o}${n?`, ${n} deleted`:""}`:`${c(n,"file")} deleted${o}`}if(e.kind==="tree"&&e.projects)return`the workspace\u2019s ${c(e.projects,"project")}`;if(e.kind==="tree"&&e.paths[0]===".")return"whole checkout";if(e.narrowed)return`${c(t,"file")} ESLint linted with the caller\u2019s arguments`;const a=e.paths.slice(0,3).join(", "),u=(e.more??0)+Math.max(0,e.paths.length-3);return u?`${a} +${u} more`:a}p(lintCoverageLabel,"lintCoverageLabel"),h(lintCoverageLabel,"lintCoverageLabel"),d(lintCoverageLabel,"lintCoverageLabel");
package/lib/log-query.js CHANGED
@@ -1 +1 @@
1
- "use strict";var m=Object.defineProperty;var a=(e,r)=>m(e,"name",{value:r,configurable:!0});var L=Object.defineProperty,c=a((e,r)=>L(e,"name",{value:r,configurable:!0}),"c");const d={level:"level",severity:"level",service:"service",svc:"service",src:"service",source:"service",flow:"flow",trace:"trace",request:"trace",category:"category",cat:"category",ms:"ms"},h={warn:"warning",err:"error"},p=/(-?)(?:([A-Za-z]+):)?(?:"([^"]*)"|(\S+))/g;export function parseLogQuery(e){const r=[],t=[];for(const s of e.matchAll(p)){const[o,n,f,w,g]=s,u=(w??g??"").trim(),i=f?d[f.toLowerCase()]:void 0;if(i&&u){const y=i==="level"?h[u.toLowerCase()]??u.toLowerCase():u;r.push({key:i,value:y,negate:n==="-"})}else o.trim()&&t.push(o.trim())}return{tokens:r,text:t.join(" ")}}a(parseLogQuery,"parseLogQuery"),c(parseLogQuery,"parseLogQuery");export function formatLogQuery(e){const r=c(t=>/\s/.test(t)?`"${t}"`:t,"quote");return[...e.tokens.map(t=>`${t.negate?"-":""}${t.key}:${r(t.value)}`),e.text].filter(Boolean).join(" ")}a(formatLogQuery,"formatLogQuery"),c(formatLogQuery,"formatLogQuery");function v(e,r){if(e===void 0)return!1;const t=/^(>=|<=|>|<|=)?\s*(\d+(?:\.\d+)?)$/.exec(r);if(!t)return!1;const s=Number(t[2]);switch(t[1]){case">":return e>s;case"<":return e<s;case"<=":return e<=s;case"=":return e===s;default:return e>=s}}a(v,"h"),c(v,"msMatches");function l(e,r){const t=r.value.toLowerCase();switch(r.key){case"level":return e.severity.toLowerCase()===t;case"service":return e.source.toLowerCase()===t;case"flow":return!!e.flowId&&e.flowId.toLowerCase().startsWith(t);case"trace":return!!e.requestId&&e.requestId.toLowerCase().startsWith(t);case"category":return e.category.toLowerCase()===t;case"ms":return v(e.durationMs,r.value)}}a(l,"i"),c(l,"tokenMatches");export function matchesLogQuery(e,r,t){const s=new Map;for(const o of r.tokens){if(o.negate){if(l(e,o))return!1;continue}const n=s.get(o.key);n?n.push(o):s.set(o.key,[o])}for(const o of s.values())if(!o.some(n=>l(e,n)))return!1;if(r.text){const o=`${e.title} ${e.message??""} ${e.source} ${e.flowId??""}`;return t?t(o):o.toLowerCase().includes(r.text.toLowerCase())}return!0}a(matchesLogQuery,"matchesLogQuery"),c(matchesLogQuery,"matchesLogQuery");
1
+ "use strict";var L=Object.defineProperty;var a=(e,t)=>L(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,c=a((e,t)=>d(e,"name",{value:t,configurable:!0}),"a"),h=Object.defineProperty,u=c((e,t)=>h(e,"name",{value:t,configurable:!0}),"c");const p={level:"level",severity:"level",service:"service",svc:"service",src:"service",source:"service",flow:"flow",trace:"trace",request:"trace",category:"category",cat:"category",ms:"ms"},C={warn:"warning",err:"error"},k=/(-?)(?:([A-Za-z]+):)?(?:"([^"]*)"|(\S+))/g;export function parseLogQuery(e){const t=[],r=[];for(const s of e.matchAll(k)){const[o,n,g,y,w]=s,i=(y??w??"").trim(),l=g?p[g.toLowerCase()]:void 0;if(l&&i){const m=l==="level"?C[i.toLowerCase()]??i.toLowerCase():i;t.push({key:l,value:m,negate:n==="-"})}else o.trim()&&r.push(o.trim())}return{tokens:t,text:r.join(" ")}}a(parseLogQuery,"parseLogQuery"),c(parseLogQuery,"parseLogQuery"),u(parseLogQuery,"parseLogQuery");export function formatLogQuery(e){const t=u(r=>/\s/.test(r)?`"${r}"`:r,"quote");return[...e.tokens.map(r=>`${r.negate?"-":""}${r.key}:${t(r.value)}`),e.text].filter(Boolean).join(" ")}a(formatLogQuery,"formatLogQuery"),c(formatLogQuery,"formatLogQuery"),u(formatLogQuery,"formatLogQuery");function v(e,t){if(e===void 0)return!1;const r=/^(>=|<=|>|<|=)?\s*(\d+(?:\.\d+)?)$/.exec(t);if(!r)return!1;const s=Number(r[2]);switch(r[1]){case">":return e>s;case"<":return e<s;case"<=":return e<=s;case"=":return e===s;default:return e>=s}}a(v,"v"),c(v,"h"),u(v,"msMatches");function f(e,t){const r=t.value.toLowerCase();switch(t.key){case"level":return e.severity.toLowerCase()===r;case"service":return e.source.toLowerCase()===r;case"flow":return!!e.flowId&&e.flowId.toLowerCase().startsWith(r);case"trace":return!!e.requestId&&e.requestId.toLowerCase().startsWith(r);case"category":return e.category.toLowerCase()===r;case"ms":return v(e.durationMs,t.value)}}a(f,"l"),c(f,"i"),u(f,"tokenMatches");export function matchesLogQuery(e,t,r){const s=new Map;for(const o of t.tokens){if(o.negate){if(f(e,o))return!1;continue}const n=s.get(o.key);n?n.push(o):s.set(o.key,[o])}for(const o of s.values())if(!o.some(n=>f(e,n)))return!1;if(t.text){const o=`${e.title} ${e.message??""} ${e.source} ${e.flowId??""}`;return r?r(o):o.toLowerCase().includes(t.text.toLowerCase())}return!0}a(matchesLogQuery,"matchesLogQuery"),c(matchesLogQuery,"matchesLogQuery"),u(matchesLogQuery,"matchesLogQuery");
@@ -1 +1 @@
1
- "use strict";var a=Object.defineProperty;var i=(t,e)=>a(t,"name",{value:e,configurable:!0});var S=Object.defineProperty,o=i((t,e)=>S(t,"name",{value:e,configurable:!0}),"s");import{LENS_EVENT_SOURCE as f}from"./error-dismissal.js";export const METRICS_RESET="metrics-reset",METRICS_RESTORED="metrics-restored",METRICS_SCOPES=["sql","external"],MAX_METRICS_RESET_IDS=500,MAX_METRICS_RESET_ID_LENGTH=512,METRICS_RESET_IDS_PER_EVENT=64;const l=16*1024,u=o(t=>t==="sql"||t==="external","isScope"),E=o(t=>typeof t=="string"&&t.length>0&&t.length<=MAX_METRICS_RESET_ID_LENGTH,"isId");export function readMetricsReset(t){if(t.source!==f||!t.raw||typeof t.raw!="object")return;const e=t.raw,r=e.kind;if(r!==METRICS_RESET&&r!==METRICS_RESTORED)return;const n=e.scope;if(!u(n))return;let s;if(e.ids!==void 0&&(!Array.isArray(e.ids)||(s=[...new Set(e.ids.filter(E))].slice(0,METRICS_RESET_IDS_PER_EVENT),!s.length)))return;if(r===METRICS_RESTORED)return{kind:r,scope:n,...s?{ids:s}:{}};const c=e.at;if(!(typeof c!="number"||!Number.isFinite(c)))return{kind:r,scope:n,at:Math.min(c,t.timestamp),...s?{ids:s}:{}}}i(readMetricsReset,"readMetricsReset"),o(readMetricsReset,"readMetricsReset");export function metricsIdBatches(t){const e=[];let r=[],n=0;for(const s of new Set(t.filter(E)))r.length&&(r.length>=METRICS_RESET_IDS_PER_EVENT||n+s.length+3>l)&&(e.push(r),r=[],n=0),r.push(s),n+=s.length+3;return r.length&&e.push(r),e}i(metricsIdBatches,"metricsIdBatches"),o(metricsIdBatches,"metricsIdBatches");
1
+ "use strict";var l=Object.defineProperty;var i=(e,t)=>l(e,"name",{value:t,configurable:!0});var f=Object.defineProperty,a=i((e,t)=>f(e,"name",{value:t,configurable:!0}),"i"),u=Object.defineProperty,c=a((e,t)=>u(e,"name",{value:t,configurable:!0}),"s");import{LENS_EVENT_SOURCE as S}from"./error-dismissal.js";export const METRICS_RESET="metrics-reset",METRICS_RESTORED="metrics-restored",METRICS_SCOPES=["sql","external"],MAX_METRICS_RESET_IDS=500,MAX_METRICS_RESET_ID_LENGTH=512,METRICS_RESET_IDS_PER_EVENT=64;const d=16*1024,p=c(e=>e==="sql"||e==="external","isScope"),E=c(e=>typeof e=="string"&&e.length>0&&e.length<=MAX_METRICS_RESET_ID_LENGTH,"isId");export function readMetricsReset(e){if(e.source!==S||!e.raw||typeof e.raw!="object")return;const t=e.raw,r=t.kind;if(r!==METRICS_RESET&&r!==METRICS_RESTORED)return;const n=t.scope;if(!p(n))return;let s;if(t.ids!==void 0&&(!Array.isArray(t.ids)||(s=[...new Set(t.ids.filter(E))].slice(0,METRICS_RESET_IDS_PER_EVENT),!s.length)))return;if(r===METRICS_RESTORED)return{kind:r,scope:n,...s?{ids:s}:{}};const o=t.at;if(!(typeof o!="number"||!Number.isFinite(o)))return{kind:r,scope:n,at:Math.min(o,e.timestamp),...s?{ids:s}:{}}}i(readMetricsReset,"readMetricsReset"),a(readMetricsReset,"readMetricsReset"),c(readMetricsReset,"readMetricsReset");export function metricsIdBatches(e){const t=[];let r=[],n=0;for(const s of new Set(e.filter(E)))r.length&&(r.length>=METRICS_RESET_IDS_PER_EVENT||n+s.length+3>d)&&(t.push(r),r=[],n=0),r.push(s),n+=s.length+3;return r.length&&t.push(r),t}i(metricsIdBatches,"metricsIdBatches"),a(metricsIdBatches,"metricsIdBatches"),c(metricsIdBatches,"metricsIdBatches");
@@ -1 +1 @@
1
- "use strict";var c=Object.defineProperty;var i=(e,n)=>c(e,"name",{value:n,configurable:!0});var u=Object.defineProperty,o=i((e,n)=>u(e,"name",{value:n,configurable:!0}),"s");export const FINDING_RUN_KINDS=["operate","stop-launch","close-session","role","role-off","check","rule","flow","lesson"];export function findingLive(e){return e.state==="open"||e.state==="proposed"||e.state==="applied"}i(findingLive,"findingLive"),o(findingLive,"findingLive");export function findingRunsActions(e,n={}){return e.actions.some(s=>FINDING_RUN_KINDS.includes(s.kind)||s.kind==="issue"&&n.issuesFolder===!0)}i(findingRunsActions,"findingRunsActions"),o(findingRunsActions,"findingRunsActions");export function findingsForCheck(e,n,s){const r=`repo:${n}/team.${s}`;return e.filter(t=>findingLive(t)&&t.checks.includes(r))}i(findingsForCheck,"findingsForCheck"),o(findingsForCheck,"findingsForCheck");
1
+ "use strict";var u=Object.defineProperty;var i=(e,n)=>u(e,"name",{value:n,configurable:!0});var f=Object.defineProperty,s=i((e,n)=>f(e,"name",{value:n,configurable:!0}),"i"),d=Object.defineProperty,r=s((e,n)=>d(e,"name",{value:n,configurable:!0}),"s");export const FINDING_RUN_KINDS=["operate","stop-launch","close-session","role","role-off","check","rule","flow","lesson"];export function findingLive(e){return e.state==="open"||e.state==="proposed"||e.state==="applied"}i(findingLive,"findingLive"),s(findingLive,"findingLive"),r(findingLive,"findingLive");export function findingRunsActions(e,n={}){return e.actions.some(o=>FINDING_RUN_KINDS.includes(o.kind)||o.kind==="issue"&&n.issuesFolder===!0)}i(findingRunsActions,"findingRunsActions"),s(findingRunsActions,"findingRunsActions"),r(findingRunsActions,"findingRunsActions");export function findingsForCheck(e,n,o){const c=`repo:${n}/team.${o}`;return e.filter(t=>findingLive(t)&&t.checks.includes(c))}i(findingsForCheck,"findingsForCheck"),s(findingsForCheck,"findingsForCheck"),r(findingsForCheck,"findingsForCheck");
package/lib/peers.d.ts CHANGED
@@ -1818,9 +1818,9 @@ export declare const GOAL_PEER_SCHEMAS: {
1818
1818
  files: "files";
1819
1819
  commit: "commit";
1820
1820
  diff: "diff";
1821
+ against: "against";
1821
1822
  row: "row";
1822
1823
  commits: "commits";
1823
- against: "against";
1824
1824
  }>;
1825
1825
  path: z.ZodOptional<z.ZodString>;
1826
1826
  sha: z.ZodOptional<z.ZodString>;
package/lib/peers.js CHANGED
@@ -1 +1 @@
1
- "use strict";var W=Object.defineProperty;var _=(t,a)=>W(t,"name",{value:a,configurable:!0});var G=Object.defineProperty,s=_((t,a)=>G(t,"name",{value:a,configurable:!0}),"r");import{z as e}from"zod";import{RUN_ID_PATTERN as I}from"./docker-jobs.js";import{REMOTE_DASHBOARD_BASE_PATTERN as U,REMOTE_INSTANCE_ID_PATTERN as S,REMOTE_INSTANCE_NAME_PREFIX as K}from"./remote-instances.js";export const PEER_PROTOCOL="peer/v1",PEER_PORT=7466,PEER_TIMING={pingMs:5e3,lostMs:45e3,windowMs:10*6e4,approveMs:10*6e4,capacityMs:3e4},PAIRING_CODE={length:10,tries:5},CROCKFORD_ALPHABET="0123456789ABCDEFGHJKMNPQRSTVWXYZ",PEER_PATHS={pair:"/peer/v1/pair",control:"/peer/v1/control",runs:"/peer/v1/runs/",bundles:"/peer/v1/bundles/",sent:"/peer/v1/sent/",tunnel:"/peer/v1/tunnel/"},RUN_UPLOAD_KINDS=["log","samples","events","artifacts"],RUN_UPLOAD_RANGE={from:"x-lensmcp-from",to:"x-lensmcp-to"},PEER_FILES={dir:"peers",key:"identity.key",cert:"identity.crt",window:"window.json",workers:"workers.json",organizer:"organizer.json",hub:"hub.json",hubLock:"hub.lock",hubLog:"hub.log",runs:"runs",instances:"instances"},FINGERPRINT_PATTERN=/^[0-9a-f]{64}$/,REMOTE_RUN_LOST="lost",PEER_MESSAGE_ID=/^[A-Za-z0-9_-]{1,64}$/,TO_WORKER=["job.offer","job.cancel","bundle.ready","tunnel.open","tunnel.close","launch.start","launch.stop","store.reply","version.install","main.moved","instance.tunnel.open","goal.place","goal.changes","goal.update"],TO_ORGANIZER=["hello","capacity","job.state","job.stage","job.done","bundle.sent","launch.state","launch.tail","store.call","version.state","forget","main.state","instance.state","store.read","goal.sent"],EITHER_WAY=["ping"],PEER_REPLIES=["ack","error","pong"],PEER_MESSAGE_SLICE={hello:"D12 (versions: D13, capacity: D14)",ping:"D12",pong:"D12",ack:"D12",error:"D12",forget:"D11",capacity:"D14","job.offer":"D14","job.cancel":"D14/D18","job.state":"D14/D16","job.stage":"D16","job.done":"D16","bundle.ready":"D15","bundle.sent":"D34 (goal branches: D30)","tunnel.open":"D17","tunnel.close":"D17","launch.start":"D29","launch.stop":"D29","launch.state":"D29","launch.tail":"D29","store.call":"D27/D28","store.reply":"D27/D28","version.install":"D13","version.state":"D13","main.moved":"D34","main.state":"D34","instance.tunnel.open":"D35","instance.state":"D35 (sent by D30)","store.read":"D32","goal.place":"D30","goal.sent":"D30","goal.changes":"D30","goal.update":"D30"};const h=s((t,a)=>t.includes(a),"has");export const isPeerMessageType=s(t=>Object.prototype.hasOwnProperty.call(PEER_MESSAGE_SLICE,t),"isPeerMessageType");export function peerMaySend(t,a){return h(EITHER_WAY,a)||h(PEER_REPLIES,a)?!0:h(t==="organizer"?TO_WORKER:TO_ORGANIZER,a)}_(peerMaySend,"peerMaySend"),s(peerMaySend,"peerMaySend");export const isPeerReply=s(t=>h(PEER_REPLIES,t),"isPeerReply");const l=/^[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]*$/u,g=s(t=>e.string().min(1).max(t).regex(l),"shownText"),z=e.string().regex(/^[A-Za-z0-9_-]{43}$/),D=e.string().regex(/^[0-9a-f]{64}$/),r=e.string().min(1).max(64).regex(/^[0-9A-Za-z.+_-]+$/),F=e.tuple([e.string().regex(/^[a-z]{3,8}$/),e.string().regex(/^[a-z]{3,8}$/),e.string().regex(/^[a-z]{3,8}$/),e.string().regex(/^[a-z]{3,8}$/)]),n=e.number().int().nonnegative();export const PeerEnvelopeSchema=e.strictObject({v:e.literal(1),id:e.string().regex(PEER_MESSAGE_ID),replyTo:e.string().regex(PEER_MESSAGE_ID).optional(),type:e.string().min(1).max(40),body:e.record(e.string(),e.unknown())});const Y=["unknown-type","wrong-direction","bad-message","hello-first","not-handled","too-large","busy","refused","timeout","lost","internal","no-window","window-used","window-closed","wrong-code","protocol"];export const PeerErrorBodySchema=e.strictObject({code:e.enum(Y),message:e.string().max(500),triesLeft:e.number().int().min(0).max(PAIRING_CODE.tries).optional(),retryAfterMs:e.number().int().min(0).max(36e5).optional()});const c=e.string().regex(I);export const WorkerAdvertSchema=e.record(e.string(),e.unknown()).superRefine((t,a)=>{const x=t.runs;x!==void 0&&(!Array.isArray(x)||x.length>256||!x.every(v=>typeof v=="string"&&I.test(v)))&&a.addIssue({code:"custom",message:"runs: at most 256 run ids"})}),PEER_BODY_SCHEMAS={hello:e.strictObject({protocol:e.literal(PEER_PROTOCOL),lensmcp:r,follow:e.boolean().optional(),store:e.array(r).max(64).optional(),capacity:WorkerAdvertSchema.optional()}),ping:e.strictObject({at:n}),pong:e.strictObject({at:n}),ack:e.strictObject({result:e.unknown().optional()}),error:PeerErrorBodySchema,forget:e.strictObject({why:e.string().max(200).regex(l).optional()})},PeerWelcomeSchema=e.strictObject({protocol:e.literal(PEER_PROTOCOL),lensmcp:r,name:g(64),inStep:e.boolean().optional(),why:e.string().max(500).optional()}),PAIR_BODY_SCHEMAS={"pair.hello":e.strictObject({protocol:e.literal(PEER_PROTOCOL),nonce:z,name:g(64),model:g(40),lensmcp:r}),"pair.resume":e.strictObject({protocol:e.literal(PEER_PROTOCOL)}),"pair.challenge":e.strictObject({nonce:z}),"pair.proof":e.strictObject({proof:D}),"pair.accepted":e.strictObject({proof:D,name:g(64),model:g(40),words:F,approveBy:n}),"pair.approved":e.strictObject({at:n}),"pair.declined":e.strictObject({why:e.string().max(500)}),error:PeerErrorBodySchema},MAIN_MIRROR={branch:"main",quietMs:10*6e4,snapshotEveryMs:60*6e4,maxSendBytes:512*1024*1024,maxWipBytes:256*1024*1024,maxHaves:16},MAIN_BRING_IN=["in-main","brought-in","waiting","not-ff","refused"],MAIN_FOLLOW_STATES=["in-step","fast-forward","ahead","waiting","to-update","not-following","off-branch"];const o=e.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),f=e.string().regex(/^[0-9a-f]{16,64}$/),$=e.string().regex(/^[0-9a-f]{64}$/),M=e.string().regex(/^[0-9a-f]{16}$/),d=e.number().int().min(0).max(1e7),O=e.string().min(1).max(250).regex(/^[A-Za-z0-9._/-]+$/),y=e.string().max(1e3),k=e.strictObject({state:e.enum(["in-main","brought-in","waiting","not-ff","refused"]),count:d,sha:o.optional(),main:o.optional(),why:y,at:n}),q=e.strictObject({outcome:e.enum(["merged","fast-forward","current","conflicts","waiting","refused"]),at:n,why:y,sha:o.optional(),conflicts:e.array(e.string().min(1).max(4096)).max(200).optional(),asked:e.array(e.strictObject({who:e.enum(["person","manager"]),goal:e.string().max(64).optional(),to:e.string().max(200).optional()})).max(20).optional()}),P=e.enum(["in-step","fast-forward","ahead","waiting","to-update","not-following","off-branch"]);export const MAIN_MIRROR_SCHEMAS={"bundle.sent":e.strictObject({bundleId:M,repository:f,refs:e.array(O).length(1),size:e.number().int().positive().max(MAIN_MIRROR.maxSendBytes),sha256:$}),"main.moved":e.strictObject({repository:f,branch:O,sha:o,bundle:e.strictObject({id:M,size:e.number().int().positive(),sha256:$}),verdict:k.optional(),at:n}),"main.state":e.strictObject({repository:f,branch:O,head:o.optional(),organizerHead:o.optional(),haves:e.array(o).max(MAIN_MIRROR.maxHaves),notSent:d,toPull:d,uncommitted:e.strictObject({files:d,changedAt:n.optional()}),snapshot:e.strictObject({sha:o,at:n,files:d,sent:e.boolean()}).optional(),follow:P,update:q.optional(),at:n})},MAIN_MIRROR_ANSWER_SCHEMAS={"bundle.sent":e.strictObject({took:e.boolean(),ref:O,sha:o.optional(),code:e.string().max(40).optional(),why:y.optional(),verdict:k.optional()}),"main.moved":e.strictObject({took:e.boolean(),needWhole:e.boolean().optional(),why:y.optional(),follow:P.optional(),head:o.optional()})};const X=e.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/),w=e.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),T=e.string().regex(/^[0-9a-f]{16,64}$/),u=e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/),C=s(t=>e.string().min(1).max(t).regex(l),"sentence"),p=e.record(e.string(),e.unknown()),J=e.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,99}$/),i=e.strictObject({lensmcp:r,protocol:e.string().regex(/^peer\/v[1-9]\d{0,3}$/)});export const PEER_WORK_SCHEMAS={capacity:WorkerAdvertSchema,"job.offer":e.strictObject({runId:c,job:X,candidate:w,repository:T,lane:e.enum(["light","heavy"]).optional(),kind:e.enum(["compose","testcontainers","playwright"]).optional(),hostMb:e.number().int().min(0).max(1024*1024).optional(),vmMb:e.number().int().min(0).max(1024*1024).optional(),proof:e.boolean().optional(),timeoutMinutes:e.number().positive().max(360).optional(),onLinkLoss:e.union([e.literal("cancel"),e.strictObject({continueMinutes:e.number().int().min(1).max(360)})]).optional(),secrets:e.record(J,e.string().min(1).max(8192)).refine(t=>Object.keys(t).length<=16,"at most 16 secrets").optional(),origin:e.string().max(300).regex(/^https?:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?$/).optional()}),"job.cancel":e.strictObject({runId:c,why:C(300)}),"job.state":e.strictObject({runId:c,at:n,started:e.literal(!0).optional(),state:e.enum(["queued","running"]).optional(),note:e.string().max(1e3).optional(),queue:p.optional(),docker:p.optional(),edgePort:e.number().int().min(1024).max(65535).optional()}),"job.stage":e.strictObject({runId:c,stage:C(120),at:n}),"job.done":e.strictObject({runId:c,at:n,state:e.enum(["passed","failed","errored","cancelled","timeout"]),note:e.string().max(1e3).optional(),step:p.optional(),docker:p.optional(),givenBack:e.strictObject({why:e.string().min(1).max(1e3)}).optional(),refused:e.strictObject({why:e.string().min(1).max(1e3)}).optional(),proof:p.optional()}),"bundle.ready":e.strictObject({runId:c.optional(),bundleId:u,repository:T,heads:e.array(w).min(1).max(16),basis:e.array(w).max(256).optional(),size:e.number().int().positive().max(64*1024*1024*1024),sha256:e.string().regex(/^[0-9a-f]{64}$/),shipment:p.optional(),blobs:e.record(e.string().regex(/^[0-9a-f]{64}$/),u).refine(t=>Object.keys(t).length<=101,"at most 101 blobs").optional()}),"tunnel.open":e.strictObject({tunnelId:u,runId:c,port:e.number().int().min(1).max(65535).optional()}),"tunnel.close":e.strictObject({tunnelId:u,why:e.string().max(300).optional()}),"version.install":e.strictObject({version:r,from:e.enum(["registry","organizer"]),tarball:e.strictObject({bundleId:u,sha256:e.string().regex(/^[0-9a-f]{64}$/),size:e.number().int().positive().max(8*1024*1024*1024)}).optional()}),"version.state":e.discriminatedUnion("state",[e.strictObject({state:e.literal("in-step"),worker:i,organizer:i}),e.strictObject({state:e.literal("installing"),worker:i,organizer:i,from:e.enum(["registry","organizer"]),since:n}),e.strictObject({state:e.literal("waiting-for-person"),worker:i,organizer:i,stored:e.boolean()}),e.strictObject({state:e.literal("out-of-step"),worker:i,organizer:i,why:e.object({kind:e.enum(["protocol","version","installed","restarting","install-failed","restart-failed","no-store"])}).catchall(e.union([e.string().max(600),e.number(),e.boolean()]))})])},STORE_CALL_LIMITS={args:16,argsBytes:256*1024,answerBytes:480*1024},PEER_LAUNCH_KEY_PATTERN=/^[A-Za-z0-9_-]{43}$/;const N=e.strictObject({added:e.number().int().nonnegative().nullable(),removed:e.number().int().nonnegative().nullable()});export const StoreCallSchema=e.strictObject({v:e.literal(1),kind:e.literal("store.call"),id:e.string().regex(/^[A-Za-z0-9._:-]{1,100}$/),method:e.string().regex(/^[A-Za-z][A-Za-z0-9]{0,79}$/),args:e.array(e.unknown()).max(STORE_CALL_LIMITS.args),launchKey:e.string().min(16).max(512),observe:e.strictObject({intervalMs:e.number().int().min(0).max(864e5).optional(),snapshot:e.strictObject({branch:e.string().max(300).nullable(),head:e.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/).nullable(),files:e.array(e.strictObject({path:e.string().min(1).max(4096),from:e.string().max(4096).optional(),status:e.string().max(2),staged:N.optional(),unstaged:N.optional()})).max(1e3),truncated:e.boolean()}).optional(),failed:e.literal(!0).optional()}).optional()}),StoreReplySchema=e.strictObject({v:e.literal(1),kind:e.literal("store.reply"),id:e.string().max(100),wrote:e.boolean(),result:e.unknown().optional(),error:e.strictObject({name:e.enum(["CoordinationError","CapacityRefusal","CoordinationBusyError","StoreCallRefused","Error"]),message:e.string().max(4e3),room:e.record(e.string(),e.unknown()).optional(),step:e.enum(["open","write","commit","read"]).optional(),waitedMs:e.number().nonnegative().optional(),tries:e.number().int().nonnegative().optional(),wrote:e.boolean().optional(),where:e.string().max(300).optional(),wal:e.boolean().optional()}).optional()}),REMOTE_INSTANCE_BODY_SCHEMAS={"instance.tunnel.open":e.strictObject({tunnelId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/),instanceId:e.string().regex(S)}),"instance.state":e.strictObject({instanceId:e.string().regex(S),state:e.enum(["up","gone"]),apex:e.string().max(253).regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.localhost$/).startsWith(K).optional(),dashboardBase:e.string().regex(U).optional(),at:n,why:e.string().max(500).regex(l).optional()})},PEER_LAUNCH_LIMITS={promptChars:64*1024,roleTextChars:64*1024,maxMinutes:720,tailLines:40,tailLineChars:400},PEER_LAUNCH_ID=/^ln-[a-z0-9]{1,12}-[a-f0-9]{6}$/;const b=e.string().regex(PEER_LAUNCH_ID),Q=e.string().regex(PEER_LAUNCH_KEY_PATTERN),L=e.string().regex(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i),V=e.string().regex(/^[a-z][a-z0-9-]{0,39}$/),Z=s(t=>e.string().min(1).max(t).regex(/^[A-Za-z0-9][A-Za-z0-9._:/@[\]-]*$/),"clientWord"),A=e.string().min(2).max(1024).regex(/^\/[^\0\r\n]*$/).refine(t=>!t.split("/").includes(".."),"no .. part"),R=e.string().min(1).max(100).regex(/^[A-Za-z0-9._:-]+$/);export const PEER_LAUNCH_SCHEMAS={"launch.start":e.strictObject({launchId:b,repository:f,goal:R,task:L.optional(),role:V,by:R,client:e.enum(["claude","codex"]),model:Z(80).optional(),effort:Z(40).optional(),worktree:A.optional(),placedGoal:e.literal(!0).optional(),prompt:e.string().min(1).max(PEER_LAUNCH_LIMITS.promptChars),roleText:e.string().max(PEER_LAUNCH_LIMITS.roleTextChars).optional(),name:e.string().min(1).max(80).regex(l).optional(),maxMinutes:e.number().int().min(1).max(PEER_LAUNCH_LIMITS.maxMinutes),account:e.string().regex(/^ac-[a-z0-9]{1,12}-[a-f0-9]{6}$/).optional(),launchKey:Q,lensmcp:r,resume:e.strictObject({launchId:b,threadId:L,from:A.optional()}).optional(),capKind:e.enum(["writers","checkers"]).optional()}).refine(t=>t.worktree===void 0!=(t.placedGoal===void 0),"a launch names its worktree, or that its goal is placed there \u2014 exactly one"),"launch.stop":e.strictObject({launchId:b,why:e.string().max(300).regex(l).optional()}),"launch.state":e.strictObject({launchId:b,state:e.enum(["running","exited","stopped","failed"]),at:n,pid:e.number().int().min(0).max(99999999).optional(),exitCode:e.number().int().min(-1).max(1024).optional(),endedAt:n.optional(),threadId:R.optional(),ended:e.strictObject({quota:e.strictObject({client:e.enum(["claude","codex"]),why:e.string().min(1).max(300),until:n,firstTurn:e.boolean(),account:e.string().max(40).optional()}).optional(),context:e.string().min(1).max(600).optional()}).optional()}),"launch.tail":e.strictObject({launchId:b,lines:e.array(e.string().max(PEER_LAUNCH_LIMITS.tailLineChars+8)).max(PEER_LAUNCH_LIMITS.tailLines),at:n})},LaunchStartedSchema=e.strictObject({started:e.literal(!0),pid:e.number().int().min(2).max(99999999),worktree:A,branch:e.string().max(250).optional(),startedAt:n,deadline:n,threadId:e.string().max(200).optional(),lensmcp:r}),STORE_READ_LIMITS={calls:24,argsBytes:64*1024,answerBytes:STORE_CALL_LIMITS.answerBytes},StoreReadSchema=e.strictObject({v:e.literal(1),kind:e.literal("store.read"),id:e.string().regex(/^[A-Za-z0-9._:-]{1,100}$/),repoId:e.string().regex(/^[0-9a-f]{16,64}$/),calls:e.array(e.strictObject({method:e.string().regex(/^[A-Za-z][A-Za-z0-9]{0,79}$/),args:e.array(e.unknown()).max(STORE_CALL_LIMITS.args)})).min(1).max(STORE_READ_LIMITS.calls)}),GOAL_ON_WORKER={maxSendBytes:512*1024*1024,maxChangesBytes:400*1024,branchPrefix:"lensmcp/g-"};const j=e.string().regex(/^[A-Za-z0-9._:-]{1,100}$/),B=e.strictObject({id:e.string().regex(/^[0-9a-f]{16}$/),size:e.number().int().positive().max(64*1024*1024*1024),sha256:e.string().regex(/^[0-9a-f]{64}$/)}),ee=e.string().min(1).max(200).regex(/^lensmcp\/g-[a-z0-9-]{1,30}$/),m=e.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),H=e.string().regex(/^[0-9a-f]{16,64}$/),E=e.string().max(1e3);export const GOAL_PEER_SCHEMAS={"goal.place":e.strictObject({goal:j,title:e.string().min(1).max(300).regex(l),repository:H,worktreeId:e.string().regex(/^[0-9a-f]{24}$/),name:e.string().regex(/^g-[a-z0-9](?:[a-z0-9-]{0,17}[a-z0-9])?$/),branch:ee,base:m,bundle:B,services:e.enum(["on-demand","none","always"]).optional(),at:n}),"goal.sent":e.strictObject({bundleId:e.string().regex(/^[0-9a-f]{16}$/),repository:H,goal:j,ref:e.string().min(1).max(250).regex(/^heads\/lensmcp\/g-[a-z0-9-]{1,30}$/),size:e.number().int().positive().max(GOAL_ON_WORKER.maxSendBytes),sha256:e.string().regex(/^[0-9a-f]{64}$/)}),"goal.changes":e.strictObject({goal:j,what:e.enum(["row","files","diff","commits","commit","against"]),path:e.string().min(1).max(4096).optional(),sha:m.optional(),full:e.boolean().optional(),againstMain:e.boolean().optional()}),"goal.update":e.strictObject({goal:j,main:e.strictObject({branch:e.string().min(1).max(200).regex(/^[A-Za-z0-9._/-]+$/),sha:m,bundle:B}),at:n})},GOAL_PEER_ANSWER_SCHEMAS={"goal.place":e.strictObject({state:e.enum(["ready","creating","failed"]),head:m.optional(),onDemand:e.boolean().optional(),needWhole:e.boolean().optional(),why:E.optional()}),"goal.sent":e.strictObject({took:e.boolean(),ref:e.string().max(250),sha:m.optional(),mirror:e.enum(["created","fast-forward","current","not-ff","checked-out"]).optional(),told:e.string().max(200).optional(),code:e.string().max(40).optional(),why:E.optional()}),"goal.changes":e.strictObject({ok:e.boolean(),value:e.unknown().optional(),status:e.number().int().min(100).max(599).optional(),why:E.optional(),shortened:e.boolean().optional()}),"goal.update":e.strictObject({outcome:e.enum(["current","merged","asked","conflicts","refused"]),why:E,sha:m.optional(),behind:e.number().int().min(0).max(1e7).optional(),dirty:e.number().int().min(0).max(1e7).optional(),conflicts:e.array(e.string().min(1).max(4096)).max(200).optional(),needWhole:e.boolean().optional()})};
1
+ "use strict";var G=Object.defineProperty;var _=(t,a)=>G(t,"name",{value:a,configurable:!0});var U=Object.defineProperty,v=_((t,a)=>U(t,"name",{value:a,configurable:!0}),"_"),K=Object.defineProperty,s=v((t,a)=>K(t,"name",{value:a,configurable:!0}),"r");import{z as e}from"zod";import{RUN_ID_PATTERN as I}from"./docker-jobs.js";import{REMOTE_DASHBOARD_BASE_PATTERN as F,REMOTE_INSTANCE_ID_PATTERN as z,REMOTE_INSTANCE_NAME_PREFIX as Y}from"./remote-instances.js";export const PEER_PROTOCOL="peer/v1",PEER_PORT=7466,PEER_TIMING={pingMs:5e3,lostMs:45e3,windowMs:10*6e4,approveMs:10*6e4,capacityMs:3e4},PAIRING_CODE={length:10,tries:5},CROCKFORD_ALPHABET="0123456789ABCDEFGHJKMNPQRSTVWXYZ",PEER_PATHS={pair:"/peer/v1/pair",control:"/peer/v1/control",runs:"/peer/v1/runs/",bundles:"/peer/v1/bundles/",sent:"/peer/v1/sent/",tunnel:"/peer/v1/tunnel/"},RUN_UPLOAD_KINDS=["log","samples","events","artifacts"],RUN_UPLOAD_RANGE={from:"x-lensmcp-from",to:"x-lensmcp-to"},PEER_FILES={dir:"peers",key:"identity.key",cert:"identity.crt",window:"window.json",workers:"workers.json",organizer:"organizer.json",hub:"hub.json",hubLock:"hub.lock",hubLog:"hub.log",runs:"runs",instances:"instances"},FINGERPRINT_PATTERN=/^[0-9a-f]{64}$/,REMOTE_RUN_LOST="lost",PEER_MESSAGE_ID=/^[A-Za-z0-9_-]{1,64}$/,TO_WORKER=["job.offer","job.cancel","bundle.ready","tunnel.open","tunnel.close","launch.start","launch.stop","store.reply","version.install","main.moved","instance.tunnel.open","goal.place","goal.changes","goal.update"],TO_ORGANIZER=["hello","capacity","job.state","job.stage","job.done","bundle.sent","launch.state","launch.tail","store.call","version.state","forget","main.state","instance.state","store.read","goal.sent"],EITHER_WAY=["ping"],PEER_REPLIES=["ack","error","pong"],PEER_MESSAGE_SLICE={hello:"D12 (versions: D13, capacity: D14)",ping:"D12",pong:"D12",ack:"D12",error:"D12",forget:"D11",capacity:"D14","job.offer":"D14","job.cancel":"D14/D18","job.state":"D14/D16","job.stage":"D16","job.done":"D16","bundle.ready":"D15","bundle.sent":"D34 (goal branches: D30)","tunnel.open":"D17","tunnel.close":"D17","launch.start":"D29","launch.stop":"D29","launch.state":"D29","launch.tail":"D29","store.call":"D27/D28","store.reply":"D27/D28","version.install":"D13","version.state":"D13","main.moved":"D34","main.state":"D34","instance.tunnel.open":"D35","instance.state":"D35 (sent by D30)","store.read":"D32","goal.place":"D30","goal.sent":"D30","goal.changes":"D30","goal.update":"D30"};const h=s((t,a)=>t.includes(a),"has");export const isPeerMessageType=s(t=>Object.prototype.hasOwnProperty.call(PEER_MESSAGE_SLICE,t),"isPeerMessageType");export function peerMaySend(t,a){return h(EITHER_WAY,a)||h(PEER_REPLIES,a)?!0:h(t==="organizer"?TO_WORKER:TO_ORGANIZER,a)}_(peerMaySend,"peerMaySend"),v(peerMaySend,"peerMaySend"),s(peerMaySend,"peerMaySend");export const isPeerReply=s(t=>h(PEER_REPLIES,t),"isPeerReply");const l=/^[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]*$/u,g=s(t=>e.string().min(1).max(t).regex(l),"shownText"),D=e.string().regex(/^[A-Za-z0-9_-]{43}$/),M=e.string().regex(/^[0-9a-f]{64}$/),r=e.string().min(1).max(64).regex(/^[0-9A-Za-z.+_-]+$/),q=e.tuple([e.string().regex(/^[a-z]{3,8}$/),e.string().regex(/^[a-z]{3,8}$/),e.string().regex(/^[a-z]{3,8}$/),e.string().regex(/^[a-z]{3,8}$/)]),n=e.number().int().nonnegative();export const PeerEnvelopeSchema=e.strictObject({v:e.literal(1),id:e.string().regex(PEER_MESSAGE_ID),replyTo:e.string().regex(PEER_MESSAGE_ID).optional(),type:e.string().min(1).max(40),body:e.record(e.string(),e.unknown())});const X=["unknown-type","wrong-direction","bad-message","hello-first","not-handled","too-large","busy","refused","timeout","lost","internal","no-window","window-used","window-closed","wrong-code","protocol"];export const PeerErrorBodySchema=e.strictObject({code:e.enum(X),message:e.string().max(500),triesLeft:e.number().int().min(0).max(PAIRING_CODE.tries).optional(),retryAfterMs:e.number().int().min(0).max(36e5).optional()});const c=e.string().regex(I);export const WorkerAdvertSchema=e.record(e.string(),e.unknown()).superRefine((t,a)=>{const x=t.runs;x!==void 0&&(!Array.isArray(x)||x.length>256||!x.every(S=>typeof S=="string"&&I.test(S)))&&a.addIssue({code:"custom",message:"runs: at most 256 run ids"})}),PEER_BODY_SCHEMAS={hello:e.strictObject({protocol:e.literal(PEER_PROTOCOL),lensmcp:r,follow:e.boolean().optional(),store:e.array(r).max(64).optional(),capacity:WorkerAdvertSchema.optional()}),ping:e.strictObject({at:n}),pong:e.strictObject({at:n}),ack:e.strictObject({result:e.unknown().optional()}),error:PeerErrorBodySchema,forget:e.strictObject({why:e.string().max(200).regex(l).optional()})},PeerWelcomeSchema=e.strictObject({protocol:e.literal(PEER_PROTOCOL),lensmcp:r,name:g(64),inStep:e.boolean().optional(),why:e.string().max(500).optional()}),PAIR_BODY_SCHEMAS={"pair.hello":e.strictObject({protocol:e.literal(PEER_PROTOCOL),nonce:D,name:g(64),model:g(40),lensmcp:r}),"pair.resume":e.strictObject({protocol:e.literal(PEER_PROTOCOL)}),"pair.challenge":e.strictObject({nonce:D}),"pair.proof":e.strictObject({proof:M}),"pair.accepted":e.strictObject({proof:M,name:g(64),model:g(40),words:q,approveBy:n}),"pair.approved":e.strictObject({at:n}),"pair.declined":e.strictObject({why:e.string().max(500)}),error:PeerErrorBodySchema},MAIN_MIRROR={branch:"main",quietMs:10*6e4,snapshotEveryMs:60*6e4,maxSendBytes:512*1024*1024,maxWipBytes:256*1024*1024,maxHaves:16},MAIN_BRING_IN=["in-main","brought-in","waiting","not-ff","refused"],MAIN_FOLLOW_STATES=["in-step","fast-forward","ahead","waiting","to-update","not-following","off-branch"];const o=e.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),f=e.string().regex(/^[0-9a-f]{16,64}$/),$=e.string().regex(/^[0-9a-f]{64}$/),k=e.string().regex(/^[0-9a-f]{16}$/),d=e.number().int().min(0).max(1e7),O=e.string().min(1).max(250).regex(/^[A-Za-z0-9._/-]+$/),y=e.string().max(1e3),P=e.strictObject({state:e.enum(["in-main","brought-in","waiting","not-ff","refused"]),count:d,sha:o.optional(),main:o.optional(),why:y,at:n}),J=e.strictObject({outcome:e.enum(["merged","fast-forward","current","conflicts","waiting","refused"]),at:n,why:y,sha:o.optional(),conflicts:e.array(e.string().min(1).max(4096)).max(200).optional(),asked:e.array(e.strictObject({who:e.enum(["person","manager"]),goal:e.string().max(64).optional(),to:e.string().max(200).optional()})).max(20).optional()}),T=e.enum(["in-step","fast-forward","ahead","waiting","to-update","not-following","off-branch"]);export const MAIN_MIRROR_SCHEMAS={"bundle.sent":e.strictObject({bundleId:k,repository:f,refs:e.array(O).length(1),size:e.number().int().positive().max(MAIN_MIRROR.maxSendBytes),sha256:$}),"main.moved":e.strictObject({repository:f,branch:O,sha:o,bundle:e.strictObject({id:k,size:e.number().int().positive(),sha256:$}),verdict:P.optional(),at:n}),"main.state":e.strictObject({repository:f,branch:O,head:o.optional(),organizerHead:o.optional(),haves:e.array(o).max(MAIN_MIRROR.maxHaves),notSent:d,toPull:d,uncommitted:e.strictObject({files:d,changedAt:n.optional()}),snapshot:e.strictObject({sha:o,at:n,files:d,sent:e.boolean()}).optional(),follow:T,update:J.optional(),at:n})},MAIN_MIRROR_ANSWER_SCHEMAS={"bundle.sent":e.strictObject({took:e.boolean(),ref:O,sha:o.optional(),code:e.string().max(40).optional(),why:y.optional(),verdict:P.optional()}),"main.moved":e.strictObject({took:e.boolean(),needWhole:e.boolean().optional(),why:y.optional(),follow:T.optional(),head:o.optional()})};const Q=e.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/),w=e.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),C=e.string().regex(/^[0-9a-f]{16,64}$/),u=e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/),N=s(t=>e.string().min(1).max(t).regex(l),"sentence"),p=e.record(e.string(),e.unknown()),V=e.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,99}$/),i=e.strictObject({lensmcp:r,protocol:e.string().regex(/^peer\/v[1-9]\d{0,3}$/)});export const PEER_WORK_SCHEMAS={capacity:WorkerAdvertSchema,"job.offer":e.strictObject({runId:c,job:Q,candidate:w,repository:C,lane:e.enum(["light","heavy"]).optional(),kind:e.enum(["compose","testcontainers","playwright"]).optional(),hostMb:e.number().int().min(0).max(1024*1024).optional(),vmMb:e.number().int().min(0).max(1024*1024).optional(),proof:e.boolean().optional(),timeoutMinutes:e.number().positive().max(360).optional(),onLinkLoss:e.union([e.literal("cancel"),e.strictObject({continueMinutes:e.number().int().min(1).max(360)})]).optional(),secrets:e.record(V,e.string().min(1).max(8192)).refine(t=>Object.keys(t).length<=16,"at most 16 secrets").optional(),origin:e.string().max(300).regex(/^https?:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?$/).optional()}),"job.cancel":e.strictObject({runId:c,why:N(300)}),"job.state":e.strictObject({runId:c,at:n,started:e.literal(!0).optional(),state:e.enum(["queued","running"]).optional(),note:e.string().max(1e3).optional(),queue:p.optional(),docker:p.optional(),edgePort:e.number().int().min(1024).max(65535).optional()}),"job.stage":e.strictObject({runId:c,stage:N(120),at:n}),"job.done":e.strictObject({runId:c,at:n,state:e.enum(["passed","failed","errored","cancelled","timeout"]),note:e.string().max(1e3).optional(),step:p.optional(),docker:p.optional(),givenBack:e.strictObject({why:e.string().min(1).max(1e3)}).optional(),refused:e.strictObject({why:e.string().min(1).max(1e3)}).optional(),proof:p.optional()}),"bundle.ready":e.strictObject({runId:c.optional(),bundleId:u,repository:C,heads:e.array(w).min(1).max(16),basis:e.array(w).max(256).optional(),size:e.number().int().positive().max(64*1024*1024*1024),sha256:e.string().regex(/^[0-9a-f]{64}$/),shipment:p.optional(),blobs:e.record(e.string().regex(/^[0-9a-f]{64}$/),u).refine(t=>Object.keys(t).length<=101,"at most 101 blobs").optional()}),"tunnel.open":e.strictObject({tunnelId:u,runId:c,port:e.number().int().min(1).max(65535).optional()}),"tunnel.close":e.strictObject({tunnelId:u,why:e.string().max(300).optional()}),"version.install":e.strictObject({version:r,from:e.enum(["registry","organizer"]),tarball:e.strictObject({bundleId:u,sha256:e.string().regex(/^[0-9a-f]{64}$/),size:e.number().int().positive().max(8*1024*1024*1024)}).optional()}),"version.state":e.discriminatedUnion("state",[e.strictObject({state:e.literal("in-step"),worker:i,organizer:i}),e.strictObject({state:e.literal("installing"),worker:i,organizer:i,from:e.enum(["registry","organizer"]),since:n}),e.strictObject({state:e.literal("waiting-for-person"),worker:i,organizer:i,stored:e.boolean()}),e.strictObject({state:e.literal("out-of-step"),worker:i,organizer:i,why:e.object({kind:e.enum(["protocol","version","installed","restarting","install-failed","restart-failed","no-store"])}).catchall(e.union([e.string().max(600),e.number(),e.boolean()]))})])},STORE_CALL_LIMITS={args:16,argsBytes:256*1024,answerBytes:480*1024},PEER_LAUNCH_KEY_PATTERN=/^[A-Za-z0-9_-]{43}$/;const L=e.strictObject({added:e.number().int().nonnegative().nullable(),removed:e.number().int().nonnegative().nullable()});export const StoreCallSchema=e.strictObject({v:e.literal(1),kind:e.literal("store.call"),id:e.string().regex(/^[A-Za-z0-9._:-]{1,100}$/),method:e.string().regex(/^[A-Za-z][A-Za-z0-9]{0,79}$/),args:e.array(e.unknown()).max(STORE_CALL_LIMITS.args),launchKey:e.string().min(16).max(512),observe:e.strictObject({intervalMs:e.number().int().min(0).max(864e5).optional(),snapshot:e.strictObject({branch:e.string().max(300).nullable(),head:e.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/).nullable(),files:e.array(e.strictObject({path:e.string().min(1).max(4096),from:e.string().max(4096).optional(),status:e.string().max(2),staged:L.optional(),unstaged:L.optional()})).max(1e3),truncated:e.boolean()}).optional(),failed:e.literal(!0).optional()}).optional()}),StoreReplySchema=e.strictObject({v:e.literal(1),kind:e.literal("store.reply"),id:e.string().max(100),wrote:e.boolean(),result:e.unknown().optional(),error:e.strictObject({name:e.enum(["CoordinationError","CapacityRefusal","CoordinationBusyError","StoreCallRefused","Error"]),message:e.string().max(4e3),room:e.record(e.string(),e.unknown()).optional(),step:e.enum(["open","write","commit","read"]).optional(),waitedMs:e.number().nonnegative().optional(),tries:e.number().int().nonnegative().optional(),wrote:e.boolean().optional(),where:e.string().max(300).optional(),wal:e.boolean().optional()}).optional()}),REMOTE_INSTANCE_BODY_SCHEMAS={"instance.tunnel.open":e.strictObject({tunnelId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/),instanceId:e.string().regex(z)}),"instance.state":e.strictObject({instanceId:e.string().regex(z),state:e.enum(["up","gone"]),apex:e.string().max(253).regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.localhost$/).startsWith(Y).optional(),dashboardBase:e.string().regex(F).optional(),at:n,why:e.string().max(500).regex(l).optional()})},PEER_LAUNCH_LIMITS={promptChars:64*1024,roleTextChars:64*1024,maxMinutes:720,tailLines:40,tailLineChars:400},PEER_LAUNCH_ID=/^ln-[a-z0-9]{1,12}-[a-f0-9]{6}$/;const b=e.string().regex(PEER_LAUNCH_ID),ee=e.string().regex(PEER_LAUNCH_KEY_PATTERN),Z=e.string().regex(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i),te=e.string().regex(/^[a-z][a-z0-9-]{0,39}$/),B=s(t=>e.string().min(1).max(t).regex(/^[A-Za-z0-9][A-Za-z0-9._:/@[\]-]*$/),"clientWord"),A=e.string().min(2).max(1024).regex(/^\/[^\0\r\n]*$/).refine(t=>!t.split("/").includes(".."),"no .. part"),R=e.string().min(1).max(100).regex(/^[A-Za-z0-9._:-]+$/);export const PEER_LAUNCH_SCHEMAS={"launch.start":e.strictObject({launchId:b,repository:f,goal:R,task:Z.optional(),role:te,by:R,client:e.enum(["claude","codex"]),model:B(80).optional(),effort:B(40).optional(),worktree:A.optional(),placedGoal:e.literal(!0).optional(),prompt:e.string().min(1).max(PEER_LAUNCH_LIMITS.promptChars),roleText:e.string().max(PEER_LAUNCH_LIMITS.roleTextChars).optional(),name:e.string().min(1).max(80).regex(l).optional(),maxMinutes:e.number().int().min(1).max(PEER_LAUNCH_LIMITS.maxMinutes),account:e.string().regex(/^ac-[a-z0-9]{1,12}-[a-f0-9]{6}$/).optional(),launchKey:ee,lensmcp:r,resume:e.strictObject({launchId:b,threadId:Z,from:A.optional()}).optional(),capKind:e.enum(["writers","checkers"]).optional()}).refine(t=>t.worktree===void 0!=(t.placedGoal===void 0),"a launch names its worktree, or that its goal is placed there \u2014 exactly one"),"launch.stop":e.strictObject({launchId:b,why:e.string().max(300).regex(l).optional()}),"launch.state":e.strictObject({launchId:b,state:e.enum(["running","exited","stopped","failed"]),at:n,pid:e.number().int().min(0).max(99999999).optional(),exitCode:e.number().int().min(-1).max(1024).optional(),endedAt:n.optional(),threadId:R.optional(),ended:e.strictObject({quota:e.strictObject({client:e.enum(["claude","codex"]),why:e.string().min(1).max(300),until:n,firstTurn:e.boolean(),account:e.string().max(40).optional()}).optional(),context:e.string().min(1).max(600).optional()}).optional()}),"launch.tail":e.strictObject({launchId:b,lines:e.array(e.string().max(PEER_LAUNCH_LIMITS.tailLineChars+8)).max(PEER_LAUNCH_LIMITS.tailLines),at:n})},LaunchStartedSchema=e.strictObject({started:e.literal(!0),pid:e.number().int().min(2).max(99999999),worktree:A,branch:e.string().max(250).optional(),startedAt:n,deadline:n,threadId:e.string().max(200).optional(),lensmcp:r}),STORE_READ_LIMITS={calls:24,argsBytes:64*1024,answerBytes:STORE_CALL_LIMITS.answerBytes},StoreReadSchema=e.strictObject({v:e.literal(1),kind:e.literal("store.read"),id:e.string().regex(/^[A-Za-z0-9._:-]{1,100}$/),repoId:e.string().regex(/^[0-9a-f]{16,64}$/),calls:e.array(e.strictObject({method:e.string().regex(/^[A-Za-z][A-Za-z0-9]{0,79}$/),args:e.array(e.unknown()).max(STORE_CALL_LIMITS.args)})).min(1).max(STORE_READ_LIMITS.calls)}),GOAL_ON_WORKER={maxSendBytes:512*1024*1024,maxChangesBytes:400*1024,branchPrefix:"lensmcp/g-"};const j=e.string().regex(/^[A-Za-z0-9._:-]{1,100}$/),H=e.strictObject({id:e.string().regex(/^[0-9a-f]{16}$/),size:e.number().int().positive().max(64*1024*1024*1024),sha256:e.string().regex(/^[0-9a-f]{64}$/)}),ne=e.string().min(1).max(200).regex(/^lensmcp\/g-[a-z0-9-]{1,30}$/),m=e.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),W=e.string().regex(/^[0-9a-f]{16,64}$/),E=e.string().max(1e3);export const GOAL_PEER_SCHEMAS={"goal.place":e.strictObject({goal:j,title:e.string().min(1).max(300).regex(l),repository:W,worktreeId:e.string().regex(/^[0-9a-f]{24}$/),name:e.string().regex(/^g-[a-z0-9](?:[a-z0-9-]{0,17}[a-z0-9])?$/),branch:ne,base:m,bundle:H,services:e.enum(["on-demand","none","always"]).optional(),at:n}),"goal.sent":e.strictObject({bundleId:e.string().regex(/^[0-9a-f]{16}$/),repository:W,goal:j,ref:e.string().min(1).max(250).regex(/^heads\/lensmcp\/g-[a-z0-9-]{1,30}$/),size:e.number().int().positive().max(GOAL_ON_WORKER.maxSendBytes),sha256:e.string().regex(/^[0-9a-f]{64}$/)}),"goal.changes":e.strictObject({goal:j,what:e.enum(["row","files","diff","commits","commit","against"]),path:e.string().min(1).max(4096).optional(),sha:m.optional(),full:e.boolean().optional(),againstMain:e.boolean().optional()}),"goal.update":e.strictObject({goal:j,main:e.strictObject({branch:e.string().min(1).max(200).regex(/^[A-Za-z0-9._/-]+$/),sha:m,bundle:H}),at:n})},GOAL_PEER_ANSWER_SCHEMAS={"goal.place":e.strictObject({state:e.enum(["ready","creating","failed"]),head:m.optional(),onDemand:e.boolean().optional(),needWhole:e.boolean().optional(),why:E.optional()}),"goal.sent":e.strictObject({took:e.boolean(),ref:e.string().max(250),sha:m.optional(),mirror:e.enum(["created","fast-forward","current","not-ff","checked-out"]).optional(),told:e.string().max(200).optional(),code:e.string().max(40).optional(),why:E.optional()}),"goal.changes":e.strictObject({ok:e.boolean(),value:e.unknown().optional(),status:e.number().int().min(100).max(599).optional(),why:E.optional(),shortened:e.boolean().optional()}),"goal.update":e.strictObject({outcome:e.enum(["current","merged","asked","conflicts","refused"]),why:E,sha:m.optional(),behind:e.number().int().min(0).max(1e7).optional(),dirty:e.number().int().min(0).max(1e7).optional(),conflicts:e.array(e.string().min(1).max(4096)).max(200).optional(),needWhole:e.boolean().optional()})};
package/lib/perf-rules.js CHANGED
@@ -1 +1 @@
1
- "use strict";var u=Object.defineProperty;var o=(r,e)=>u(r,"name",{value:e,configurable:!0});var c=Object.defineProperty,a=o((r,e)=>c(r,"name",{value:e,configurable:!0}),"o");export const PERF_RULE_IDS=["bundle/heavy-barrel-import","pod/heap-budget","pod/retained-generation"],PERF_RULE_EVENT_KINDS=["perf-rule-finding","perf-rule-retracted","perf-rule-scan"],PERF_RULES_DOC="https://github.com/kiwiapps-ltd/lensmcp/blob/main/docs/lensmcp/concepts/memory-and-build-cost.mdx",PERF_RULE_DOCS={"bundle/heavy-barrel-import":`${PERF_RULES_DOC}#bundleheavy-barrel-import`,"pod/heap-budget":`${PERF_RULES_DOC}#podheap-budget`,"pod/retained-generation":`${PERF_RULES_DOC}#podretained-generation`};export function perfRuleFingerprint(r,e,n){return`perf-rule:${r}:${e}:${n}`}o(perfRuleFingerprint,"perfRuleFingerprint"),a(perfRuleFingerprint,"perfRuleFingerprint");export function perfRuleScanFingerprint(r,e){return`perf-rule-scan:${r}:${e}`}o(perfRuleScanFingerprint,"perfRuleScanFingerprint"),a(perfRuleScanFingerprint,"perfRuleScanFingerprint");const s=/^[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/,l=12,f=4e3,t=a((r,e=f)=>typeof r=="string"&&r.length>0&&r.length<=e,"isText");export function asPerfRuleRaw(r){if(!r||typeof r!="object")return;const e=r;if(!PERF_RULE_EVENT_KINDS.includes(e.kind)||typeof e.rule!="string"||!s.test(e.rule)||!t(e.project,512))return;if(e.kind==="perf-rule-scan"){const i=e.open;return!Array.isArray(i)||i.length>256||!i.every(p=>t(p,512))?void 0:r}if(!t(e.subject,512))return;if(e.kind==="perf-rule-retracted")return r;if(e.severity!=="warning"&&e.severity!=="error"||!t(e.title)||!t(e.summary)||!t(e.verify)||!t(e.docs,1024))return;const n=e.fix;if(!(!Array.isArray(n)||n.length===0||n.length>l||!n.every(i=>t(i)))&&!(!e.evidence||typeof e.evidence!="object"||Array.isArray(e.evidence))&&!(!e.cost||typeof e.cost!="object"||Array.isArray(e.cost)))return r}o(asPerfRuleRaw,"asPerfRuleRaw"),a(asPerfRuleRaw,"asPerfRuleRaw");
1
+ "use strict";var c=Object.defineProperty;var a=(r,e)=>c(r,"name",{value:e,configurable:!0});var l=Object.defineProperty,o=a((r,e)=>l(r,"name",{value:e,configurable:!0}),"o"),f=Object.defineProperty,p=o((r,e)=>f(r,"name",{value:e,configurable:!0}),"o");export const PERF_RULE_IDS=["bundle/heavy-barrel-import","pod/heap-budget","pod/retained-generation"],PERF_RULE_EVENT_KINDS=["perf-rule-finding","perf-rule-retracted","perf-rule-scan"],PERF_RULES_DOC="https://github.com/kiwiapps-ltd/lensmcp/blob/main/docs/lensmcp/concepts/memory-and-build-cost.mdx",PERF_RULE_DOCS={"bundle/heavy-barrel-import":`${PERF_RULES_DOC}#bundleheavy-barrel-import`,"pod/heap-budget":`${PERF_RULES_DOC}#podheap-budget`,"pod/retained-generation":`${PERF_RULES_DOC}#podretained-generation`};export function perfRuleFingerprint(r,e,n){return`perf-rule:${r}:${e}:${n}`}a(perfRuleFingerprint,"perfRuleFingerprint"),o(perfRuleFingerprint,"perfRuleFingerprint"),p(perfRuleFingerprint,"perfRuleFingerprint");export function perfRuleScanFingerprint(r,e){return`perf-rule-scan:${r}:${e}`}a(perfRuleScanFingerprint,"perfRuleScanFingerprint"),o(perfRuleScanFingerprint,"perfRuleScanFingerprint"),p(perfRuleScanFingerprint,"perfRuleScanFingerprint");const s=/^[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/,d=12,y=4e3,t=p((r,e=y)=>typeof r=="string"&&r.length>0&&r.length<=e,"isText");export function asPerfRuleRaw(r){if(!r||typeof r!="object")return;const e=r;if(!PERF_RULE_EVENT_KINDS.includes(e.kind)||typeof e.rule!="string"||!s.test(e.rule)||!t(e.project,512))return;if(e.kind==="perf-rule-scan"){const i=e.open;return!Array.isArray(i)||i.length>256||!i.every(u=>t(u,512))?void 0:r}if(!t(e.subject,512))return;if(e.kind==="perf-rule-retracted")return r;if(e.severity!=="warning"&&e.severity!=="error"||!t(e.title)||!t(e.summary)||!t(e.verify)||!t(e.docs,1024))return;const n=e.fix;if(!(!Array.isArray(n)||n.length===0||n.length>d||!n.every(i=>t(i)))&&!(!e.evidence||typeof e.evidence!="object"||Array.isArray(e.evidence))&&!(!e.cost||typeof e.cost!="object"||Array.isArray(e.cost)))return r}a(asPerfRuleRaw,"asPerfRuleRaw"),o(asPerfRuleRaw,"asPerfRuleRaw"),p(asPerfRuleRaw,"asPerfRuleRaw");
package/lib/pod-memory.js CHANGED
@@ -1 +1 @@
1
- "use strict";var t=Object.defineProperty;var r=(o,e)=>t(o,"name",{value:e,configurable:!0});var d=Object.defineProperty,m=r((o,e)=>d(o,"name",{value:e,configurable:!0}),"r");export const POD_MEMORY_KINDS=["pod-memory","pod-memory-retained","pod-memory-released","pod-memory-exited"];export function asPodMemoryRaw(o){if(!o||typeof o!="object")return;const e=o;if(POD_MEMORY_KINDS.includes(e.kind)&&!(typeof e.project!="string"||!e.project)&&!(typeof e.pod!="number"||typeof e.pid!="number")&&!(e.kind==="pod-memory"&&(typeof e.live!="number"||!Number.isFinite(e.live)))&&!((e.kind==="pod-memory-retained"||e.kind==="pod-memory-released")&&typeof e.gen!="number"))return o}r(asPodMemoryRaw,"asPodMemoryRaw"),m(asPodMemoryRaw,"asPodMemoryRaw");
1
+ "use strict";var n=Object.defineProperty;var o=(r,e)=>n(r,"name",{value:e,configurable:!0});var d=Object.defineProperty,t=o((r,e)=>d(r,"name",{value:e,configurable:!0}),"r"),m=Object.defineProperty,i=t((r,e)=>m(r,"name",{value:e,configurable:!0}),"r");export const POD_MEMORY_KINDS=["pod-memory","pod-memory-retained","pod-memory-released","pod-memory-exited"];export function asPodMemoryRaw(r){if(!r||typeof r!="object")return;const e=r;if(POD_MEMORY_KINDS.includes(e.kind)&&!(typeof e.project!="string"||!e.project)&&!(typeof e.pod!="number"||typeof e.pid!="number")&&!(e.kind==="pod-memory"&&(typeof e.live!="number"||!Number.isFinite(e.live)))&&!((e.kind==="pod-memory-retained"||e.kind==="pod-memory-released")&&typeof e.gen!="number"))return r}o(asPodMemoryRaw,"asPodMemoryRaw"),t(asPodMemoryRaw,"asPodMemoryRaw"),i(asPodMemoryRaw,"asPodMemoryRaw");
@@ -1 +1 @@
1
- "use strict";var m=Object.defineProperty;var i=(t,o)=>m(t,"name",{value:o,configurable:!0});var R=Object.defineProperty,p=i((t,o)=>R(t,"name",{value:o,configurable:!0}),"u");import{z as e}from"zod";export const ProducerStateSchema=e.enum(["none","connected"]),ProducerRunStatusSchema=e.enum(["running","clean","failing","error"]),ProducerReportSchema=e.object({id:e.string(),tool:e.string(),project:e.string().optional(),firstReportedAt:e.number().int().nonnegative(),lastReportedAt:e.number().int().nonnegative(),lastRunStatus:ProducerRunStatusSchema,lastRunDurationMs:e.number().int().nonnegative().optional(),errorCount:e.number().int().nonnegative(),warningCount:e.number().int().nonnegative().optional(),error:e.string().optional()}),ProducerHealthSchema=e.object({producer:ProducerStateSchema,producers:e.array(ProducerReportSchema),lastReportedAt:e.number().int().nonnegative().optional(),ageMs:e.number().int().nonnegative().optional(),stale:e.boolean(),detail:e.string()}),PRODUCER_STALE_AFTER_MS=10*6e4;export function summariseProducers(t){const o=t.now??Date.now(),n=[...t.producers].sort((r,h)=>h.lastReportedAt-r.lastReportedAt);if(n.length===0)return{producer:"none",producers:[],stale:!1,detail:`No ${t.domain} producer has ever reported into this session \u2014 this is NOT a clean result, nothing is watching. ${t.noProducerHint}`};const d=n[0].lastReportedAt,u=Math.max(0,o-d),l=u>PRODUCER_STALE_AFTER_MS,c=n.filter(r=>r.lastRunStatus==="failing"),s=n.filter(r=>r.lastRunStatus==="error"),a=[`${n.length} ${t.domain} producer${n.length===1?"":"s"} reporting (${n.map(r=>r.id).join(", ")}); newest report ${g(u)}.`];return s.length>0&&a.push(`${s.length} produced NO verdict (the tool itself failed): ${s.map(r=>`${r.id} \u2014 ${r.error??"unknown error"}`).join("; ")}.`),c.length>0&&a.push(`${c.length} reporting errors.`),l&&a.push(`Older than ${Math.round(PRODUCER_STALE_AFTER_MS/6e4)}m \u2014 the verdict may predate the current source.`),{producer:"connected",producers:n,lastReportedAt:d,ageMs:u,stale:l,detail:a.join(" ")}}i(summariseProducers,"summariseProducers"),p(summariseProducers,"summariseProducers");function g(t){return t<1e3?"just now":t<6e4?`${Math.round(t/1e3)}s ago`:t<36e5?`${Math.round(t/6e4)}m ago`:`${Math.round(t/36e5)}h ago`}i(g,"g"),p(g,"describeAge");
1
+ "use strict";var R=Object.defineProperty;var i=(e,o)=>R(e,"name",{value:o,configurable:!0});var $=Object.defineProperty,d=i((e,o)=>$(e,"name",{value:o,configurable:!0}),"i"),b=Object.defineProperty,m=d((e,o)=>b(e,"name",{value:o,configurable:!0}),"u");import{z as r}from"zod";export const ProducerStateSchema=r.enum(["none","connected"]),ProducerRunStatusSchema=r.enum(["running","clean","failing","error"]),ProducerReportSchema=r.object({id:r.string(),tool:r.string(),project:r.string().optional(),firstReportedAt:r.number().int().nonnegative(),lastReportedAt:r.number().int().nonnegative(),lastRunStatus:ProducerRunStatusSchema,lastRunDurationMs:r.number().int().nonnegative().optional(),errorCount:r.number().int().nonnegative(),warningCount:r.number().int().nonnegative().optional(),error:r.string().optional()}),ProducerHealthSchema=r.object({producer:ProducerStateSchema,producers:r.array(ProducerReportSchema),lastReportedAt:r.number().int().nonnegative().optional(),ageMs:r.number().int().nonnegative().optional(),stale:r.boolean(),detail:r.string()}),PRODUCER_STALE_AFTER_MS=10*6e4;export function summariseProducers(e){const o=e.now??Date.now(),t=[...e.producers].sort((n,h)=>h.lastReportedAt-n.lastReportedAt);if(t.length===0)return{producer:"none",producers:[],stale:!1,detail:`No ${e.domain} producer has ever reported into this session \u2014 this is NOT a clean result, nothing is watching. ${e.noProducerHint}`};const l=t[0].lastReportedAt,u=Math.max(0,o-l),p=u>PRODUCER_STALE_AFTER_MS,g=t.filter(n=>n.lastRunStatus==="failing"),s=t.filter(n=>n.lastRunStatus==="error"),a=[`${t.length} ${e.domain} producer${t.length===1?"":"s"} reporting (${t.map(n=>n.id).join(", ")}); newest report ${c(u)}.`];return s.length>0&&a.push(`${s.length} produced NO verdict (the tool itself failed): ${s.map(n=>`${n.id} \u2014 ${n.error??"unknown error"}`).join("; ")}.`),g.length>0&&a.push(`${g.length} reporting errors.`),p&&a.push(`Older than ${Math.round(PRODUCER_STALE_AFTER_MS/6e4)}m \u2014 the verdict may predate the current source.`),{producer:"connected",producers:t,lastReportedAt:l,ageMs:u,stale:p,detail:a.join(" ")}}i(summariseProducers,"summariseProducers"),d(summariseProducers,"summariseProducers"),m(summariseProducers,"summariseProducers");function c(e){return e<1e3?"just now":e<6e4?`${Math.round(e/1e3)}s ago`:e<36e5?`${Math.round(e/6e4)}m ago`:`${Math.round(e/36e5)}h ago`}i(c,"g"),d(c,"g"),m(c,"describeAge");
@@ -1 +1 @@
1
- "use strict";var t=Object.defineProperty;var _=(E,e)=>t(E,"name",{value:e,configurable:!0});var n=Object.defineProperty,A=_((E,e)=>n(E,"name",{value:e,configurable:!0}),"t");export const REMOTE_INSTANCE_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]{7,39}$/,REMOTE_INSTANCE_NAME_PREFIX="g-",MAX_REMOTE_INSTANCE_SEC=14400,REMOTE_LENS_LABEL="lensmcp",REMOTE_DASHBOARD_BASE_PATTERN=/^\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/,PEER_TUNNEL_HEADER="x-lensmcp-peer-tunnel";export function remoteLensHost(E){return`${REMOTE_LENS_LABEL}.${E.toLowerCase()}`}_(remoteLensHost,"remoteLensHost"),A(remoteLensHost,"remoteLensHost");export const REMOTE_INSTANCES_FILE="instances.json";
1
+ "use strict";var _=Object.defineProperty;var t=(e,E)=>_(e,"name",{value:E,configurable:!0});var r=Object.defineProperty,n=t((e,E)=>r(e,"name",{value:E,configurable:!0}),"_"),o=Object.defineProperty,A=n((e,E)=>o(e,"name",{value:E,configurable:!0}),"t");export const REMOTE_INSTANCE_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]{7,39}$/,REMOTE_INSTANCE_NAME_PREFIX="g-",MAX_REMOTE_INSTANCE_SEC=14400,REMOTE_LENS_LABEL="lensmcp",REMOTE_DASHBOARD_BASE_PATTERN=/^\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/,PEER_TUNNEL_HEADER="x-lensmcp-peer-tunnel";export function remoteLensHost(e){return`${REMOTE_LENS_LABEL}.${e.toLowerCase()}`}t(remoteLensHost,"remoteLensHost"),n(remoteLensHost,"remoteLensHost"),A(remoteLensHost,"remoteLensHost");export const REMOTE_INSTANCES_FILE="instances.json";
package/lib/sessions.d.ts CHANGED
@@ -42,6 +42,12 @@ export interface DashClientSession {
42
42
  };
43
43
  resumedFrom?: string;
44
44
  on?: DashTeamHostMark;
45
+ /**
46
+ * The session that started it, as a row id of this list, when known (planning/accounts A0): a `codex exec` a Claude
47
+ * session ran (its hooks saw the parent's `CLAUDE_CODE_SESSION_ID`), a Codex sub-agent (its rollout's parent thread).
48
+ * The Accounts page nests a row under its parent.
49
+ */
50
+ parentId?: string;
45
51
  }
46
52
  export interface DashClientSessionsAnswer {
47
53
  terminals: DashTerminalsState;
@@ -121,10 +127,20 @@ export interface DashClientSessionContext {
121
127
  trigger?: string;
122
128
  }>;
123
129
  }
124
- /** A subagent of the session, as its parent's transcript and its own name it; `live`: running now. */
130
+ /**
131
+ * A subagent of the session, as its parent's transcript and its own name it; `live`: running now. With `session`: a
132
+ * session of its own that this one started (planning/accounts A0) — a `codex exec` its shell ran — not one of its
133
+ * client's own subagents: a row of `/api/sessions` (its `parentId` is this session), whose page is its own.
134
+ */
125
135
  export type DashClientSessionSubagent = DashTeamAgentDetail['spawned'][number] & {
126
136
  live: boolean;
127
137
  lastAt?: number;
138
+ session?: {
139
+ id: string;
140
+ client: DashClientSessionClient;
141
+ kind: DashClientSessionKind;
142
+ state: DashClientSessionState;
143
+ };
128
144
  };
129
145
  /** The skills the client listed to the model, the role's kit it was given, and those it used. */
130
146
  export interface DashClientSessionSkills {