opencode-forgekeeper 5.2.0 → 6.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -29
- package/dist/gui-experimental.cjs +107 -64
- package/dist/index.js +2348 -850
- package/dist/tui.js +1146 -114
- package/package.json +1 -1
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const
|
|
2
|
-
`);if(
|
|
3
|
-
`)}const
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("solid-js/web"),V=require("@opencode/plugin/gui"),S=require("solid-js"),Ze=require("solid-js/store"),Vt=require("node:crypto");function Kt(e){return e.approvers?e.approvers:e.forge==="gitlab"&&e.duoReviewState==="APPROVED"?[{username:"GitLabDuo",bot:!0,automated:!0}]:[]}const $t=e=>t=>t.forge===e,Jt=e=>e?.match(/^\[[^\]]*\]/)?.[0]??"";function yt(e,t){return Jt(e).slice(1,-1).split(/[\s,]+/).flatMap(r=>r.startsWith(t)&&/^[1-9]\d*$/.test(r.slice(t.length))?[r.slice(t.length)]:[])}function qe(e,t,r){let s;try{s=new URL(t)}catch{return}if(!["https:","http:"].includes(s.protocol))return;const n=s.pathname.match(r);if(n)return{forge:e,host:s.hostname.toLowerCase(),project:decodeURIComponent(n[1]),iid:n[2]}}const oe=e=>e?"yes":"no",xe=e=>e.toLowerCase().replace(/_/g," ");function Rt(e){return e.length>2?`awaiting ${e.length} reviewers`:`awaiting ${e.map(t=>`@${t}`).join(", ")}`}class B extends Error{constructor(t,r){super(r),this.kind=t}kind}const _=e=>e,J=e=>async(t,r,s)=>await e(t,r,s),et=10,Yt=10,tt=300,Xt=5,rt=300;function Zt(e,t){const r=e.split(`
|
|
2
|
+
`);if(t<1||t>r.length)return;const s=Math.max(1,t-et),n=Math.min(r.length,t+et);return r.slice(s-1,n).map((a,i)=>{const l=s+i,o=a.length>tt?`${a.slice(0,tt)}…`:a;return`${l===t?">":" "}${l}: ${o}`}).join(`
|
|
3
|
+
`)}const fe=100,be=20,St=200,Fe="author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } }",Ge="pageInfo { hasPreviousPage startCursor }",Ct=`id url state createdAt publishedAt lastEditedAt isMinimized pullRequestReview { state } ${Fe}`,ze=(e,t)=>_(`query($owner: String!, $repo: String!, $number: Int!, $before: String) {
|
|
4
4
|
viewer { id }
|
|
5
5
|
repository(owner: $owner, name: $repo) {
|
|
6
6
|
pullRequest(number: $number) {
|
|
7
|
-
${e}(last: ${
|
|
7
|
+
${e}(last: ${fe}, before: $before) { ${Ge} nodes { ${t} } }
|
|
8
8
|
}
|
|
9
9
|
}
|
|
10
|
-
}`),
|
|
10
|
+
}`),er=ze("comments",`id url createdAt publishedAt lastEditedAt isMinimized ${Fe}`),tr=ze("reviews",`id url state body submittedAt lastEditedAt isMinimized ${Fe}`),rr=ze("reviewThreads",`id isResolved comments(last: ${fe}) { ${Ge} nodes { ${Ct} } }`),nr=_(`query($id: ID!, $before: String) {
|
|
11
11
|
node(id: $id) {
|
|
12
12
|
... on PullRequestReviewThread {
|
|
13
|
-
comments(last: ${
|
|
13
|
+
comments(last: ${fe}, before: $before) { ${Ge} nodes { ${Ct} } }
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
|
-
}`),
|
|
16
|
+
}`),sr=new Set(["COMMENTED","CHANGES_REQUESTED"]),He=(...e)=>{const t=e.find(r=>r);return t?Date.parse(t):NaN},We=(e,t)=>{const r=e?Date.parse(e):NaN;return Number.isFinite(r)?Math.max(r,t):t};function Qe({node:e,postedAt:t,editedAt:r,resolved:s}){if(e.isMinimized||!e.author?.id||!Number.isFinite(t)||!Number.isFinite(r))return;const{__typename:n,login:a}=e.author;return{id:e.id,order:t,url:e.url??"",editedAt:r,resolved:s,bot:n==="Bot"||a.endsWith("[bot]"),authorID:e.author.id,username:he(a,n)}}function or(e){const t=He(e.publishedAt,e.createdAt);return Qe({node:e,postedAt:t,editedAt:We(e.lastEditedAt,t),resolved:!1})}function ir(e){if(!sr.has(e.state)||!e.body.trim())return;const t=He(e.submittedAt);return Qe({node:e,postedAt:t,editedAt:We(e.lastEditedAt,t),resolved:!1})}function ar(e,t){if(e.state==="PENDING")return;const r=He(e.publishedAt,e.createdAt),s=Qe({node:e,postedAt:r,editedAt:We(e.lastEditedAt,r),resolved:t});if(s)return e.pullRequestReview?.state?{...s,reviewState:e.pullRequestReview.state}:s}const lr={pages:be,completeAtLimit:!0},cr={pages:St,completeAtLimit:!1};async function Ee(e,t,r,s,n,a=lr){const i=[];let l,o;const c=d=>({items:i.toReversed().flat(),viewer:l,complete:d});for(let d=0;d<a.pages;d++){const h=o?{...r,before:o}:r,p=await e(t,s,h);l??=p.viewer?.id??void 0;const w=p.repository?.pullRequest?.[n];if(!w)return d===0?{viewer:l,complete:!1}:c(!1);if(i.push(w.nodes),!w.pageInfo.hasPreviousPage)return c(!0);if(o=w.pageInfo.startCursor??void 0,!o)return c(!1)}return c(a.completeAtLimit)}async function ur(e,t,r){if(!r.comments)return{comments:[],complete:!1};const s=[];let n=r.comments?.pageInfo.hasPreviousPage?r.comments.pageInfo.startCursor??void 0:void 0;if(r.comments?.pageInfo.hasPreviousPage&&!n)return{comments:[],complete:!1};for(let a=1;n&&a<be;a++){const l=(await e(t,nr,{id:r.id,before:n})).node?.comments;if(!l)return{comments:s.toReversed().flat(),complete:!1};if(s.push(l.nodes),n=l.pageInfo.hasPreviousPage?l.pageInfo.startCursor??void 0:void 0,l.pageInfo.hasPreviousPage&&!n)return{comments:s.toReversed().flat(),complete:!1}}return{comments:s.toReversed().flat(),complete:!0}}const dr=e=>_(`query {
|
|
17
17
|
nodes(ids: ${JSON.stringify(e)}) {
|
|
18
18
|
__typename
|
|
19
19
|
... on IssueComment { id url body author { __typename login ... on User { id } ... on Bot { id } } }
|
|
@@ -24,13 +24,13 @@
|
|
|
24
24
|
replyTo { body author { __typename login } }
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
-
}`),
|
|
27
|
+
}`),pr=/^[A-Za-z0-9_=-]+$/,nt=50;async function fr(e,t,r){const s=J(e),n=[],a=r.filter(i=>pr.test(i));for(let i=0;i<a.length;i+=nt){const l=await s(t,dr(a.slice(i,i+nt)),{});for(const o of l.nodes??[]){if(!o?.id||!o.url||!o.author||o.body===void 0||o.__typename==="PullRequestReview"&&o.state==="APPROVED")continue;const c=o.line??o.originalLine??void 0,d=o.diffHunk?.split(`
|
|
28
28
|
`).slice(-21).join(`
|
|
29
|
-
`),h=
|
|
29
|
+
`),h=o.replyTo?.author?[{username:he(o.replyTo.author.login,o.replyTo.author.__typename),body:o.replyTo.body}]:[],p=o.author.__typename==="Bot"||o.author.login.endsWith("[bot]"),w=o.__typename==="PullRequestReviewComment"?o.pullRequestReview?.state??void 0:o.__typename==="PullRequestReview"?o.state??void 0:void 0;n.push({id:o.id,url:o.url,username:he(o.author.login,o.author.__typename),...o.author.id?{authorID:o.author.id}:{},...p?{bot:!0}:{},...w?{reviewState:w}:{},body:o.body,...o.path?{path:o.path}:{},...c!==void 0?{line:c}:{},...o.path&&d?{code:{path:o.path,text:d}}:{},...h.length?{replies:h}:{}})}}return n}async function hr(e,t,r,s){let n=0;const a=J(async(...y)=>n++>=St?{}:e(...y)),[i,l]=r.split("/"),o={owner:i,repo:l,number:Number(s)},[c,d,h]=await Promise.all([Ee(a,t,o,er,"comments"),Ee(a,t,o,tr,"reviews"),Ee(a,t,o,rr,"reviewThreads",cr)]);if(!c.items||!d.items||!h.items)return;const p=c.viewer??d.viewer??h.viewer;let w=h.complete;const $=[];for(const y of h.items){const D=await ur(a,t,y);w&&=D.complete;for(const j of[...D.comments,...y.comments?.nodes??[]]){const m=ar(j,y.isResolved);m&&$.push(m)}$.sort((j,m)=>m.order-j.order),$.splice(fe*be)}const b=[...c.items.map(or),...d.items.map(ir),...$.sort((y,D)=>y.order-D.order).slice(-fe*be)].flatMap(y=>y??[]);return{complete:c.complete&&d.complete&&w&&p!==void 0,viewerID:p,comments:b.sort((y,D)=>y.order-D.order)}}const gr=100,mr=20,Te=_(`query($project: ID!, $iid: String!, $before: String) {
|
|
30
30
|
currentUser { id }
|
|
31
31
|
project(fullPath: $project) {
|
|
32
32
|
mergeRequest(iid: $iid) {
|
|
33
|
-
notes(last: ${
|
|
33
|
+
notes(last: ${gr}, before: $before, filter: ONLY_COMMENTS) {
|
|
34
34
|
pageInfo { hasPreviousPage startCursor }
|
|
35
35
|
nodes {
|
|
36
36
|
id url createdAt updatedAt lastEditedAt system
|
|
@@ -41,127 +41,170 @@
|
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
-
}`),
|
|
44
|
+
}`),wr=_(String(Te).replace("position { newPath }","position { newPath } duoCreatedSession { id status workflowDefinition }")),we=e=>e.slice(e.lastIndexOf("/")+1),vr=e=>Date.parse(e.lastEditedAt??e.updatedAt??e.createdAt);function br(e){const t=vr(e),r=we(e.id);if(!(e.system||!e.author||!Number.isFinite(t)||!/^\d+$/.test(r)))return{id:r,order:Number(r),url:e.url??"",editedAt:t,resolved:e.discussion?.resolved===!0,bot:e.author.bot,authorID:e.author.id,username:e.author.username,...e.discussion?.id?{discussionID:e.discussion.id}:{},...e.author.bot&&e.author.username.toLowerCase()==="gitlabduo"?{automated:{reviewer:"GitLab Duo",finding:!!e.position,...e.duoCreatedSession?.workflowDefinition==="code_review/v1"?{runID:e.duoCreatedSession.id,status:e.duoCreatedSession.status}:{}}}:{}}}async function $r(e,t,r,s){const n=J(e),a=[];let i,l,o=!0;const c=d=>({complete:d&&i!==void 0,viewerID:i,comments:a.toReversed().flat()});for(let d=0;d<mr;d++){const h={project:r,iid:s};l&&(h.before=l);let p;try{p=await n(t,o?wr:Te,h)}catch($){if(!o||!/duoCreatedSession.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*duoCreatedSession/i.test($ instanceof Error?$.message:String($)))throw $;o=!1,p=await n(t,Te,h)}i??=p.currentUser?.id??void 0;const w=p.project?.mergeRequest?.notes;if(!w)return d===0?void 0:c(!1);if(a.push(w.nodes.flatMap($=>br($)??[])),!w.pageInfo.hasPreviousPage)return c(!0);if(l=w.pageInfo.startCursor??void 0,!l)return c(!1)}return c(!0)}const st=25,yr=20,Rr=/^[0-9a-f]{40}$/;function It(e){const t=e?.diffRefs;if(t){if(e.newLine&&e.newPath)return{sha:t.headSha,path:e.newPath,line:e.newLine};if(e.oldLine&&e.oldPath)return{sha:t.baseSha,path:e.oldPath,line:e.oldLine}}}async function Sr(e,t,r,s){const n=J(e),a=[],i=s.filter(o=>/^\d+$/.test(o));for(let o=0;o<i.length;o+=st){const c=i.slice(o,o+st).map((h,p)=>`n${p}: note(id: "gid://gitlab/Note/${h}") { id url body author { id username }
|
|
45
45
|
position { diffRefs { baseSha headSha } newPath newLine oldPath oldLine }
|
|
46
|
-
discussion { resolved notes(first: ${
|
|
47
|
-
`),
|
|
48
|
-
`),
|
|
46
|
+
discussion { resolved notes(first: ${yr}) { nodes { id body author { username } } } } }`).join(`
|
|
47
|
+
`),d=await n(t,_(`query { ${c} }`),{});for(const h of Object.values(d))h?.author&&h.url&&a.push(h)}const l=await Cr(n,t,r,a).catch(()=>new Map);return a.map(o=>{const c=It(o.position),d=c&&l.get(JSON.stringify([c.sha,c.path])),h=d!==void 0&&c?Zt(d,c.line):void 0,p=o.discussion?.notes?.nodes??[],w=p.findIndex(b=>we(b.id)===we(o.id)),$=(w>0?p.slice(0,w):[]).flatMap(b=>b.author?[{username:b.author.username,body:b.body}]:[]);return{id:we(o.id),url:o.url??"",username:o.author?.username??"",...o.author?.id?{authorID:o.author.id}:{},body:o.body,...typeof o.discussion?.resolved=="boolean"?{resolved:o.discussion.resolved}:{},...c?{path:c.path,line:c.line}:{},...h&&c?{code:{path:c.path,text:h}}:{},...$.length?{replies:$}:{}}})}async function Cr(e,t,r,s){const n=new Map;let a=0;for(const d of s){const h=It(d.position);if(!h||!Rr.test(h.sha))continue;const p=n.get(h.sha)??new Set;!p.has(h.path)&&a>=Yt||(p.has(h.path)||a++,n.set(h.sha,p.add(h.path)))}const i=new Map;if(!n.size)return i;const l=[...n.keys()],o=l.map((d,h)=>`b${h}: project(fullPath: ${JSON.stringify(r)}) { repository { blobs(paths: ${JSON.stringify([...n.get(d)])}, ref: ${JSON.stringify(d)}) { nodes { path rawTextBlob } } } }`).join(`
|
|
48
|
+
`),c=await e(t,_(`query { ${o} }`),{});return l.forEach((d,h)=>{for(const p of c[`b${h}`]?.repository?.blobs?.nodes??[])p.rawTextBlob!==null&&i.set(JSON.stringify([d,p.path]),p.rawTextBlob)}),i}const Ir=100,kr=10,Er=_(`query($project: ID!, $iid: String!, $before: String) {
|
|
49
49
|
currentUser { id username }
|
|
50
50
|
project(fullPath: $project) {
|
|
51
51
|
mergeRequest(iid: $iid) {
|
|
52
|
-
notes(last: ${
|
|
52
|
+
notes(last: ${Ir}, before: $before, filter: ONLY_ACTIVITY) {
|
|
53
53
|
pageInfo { hasPreviousPage startCursor }
|
|
54
54
|
nodes { id url body createdAt system systemNoteMetadata { action } author { id username } }
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
|
-
}`),
|
|
58
|
+
}`),ot="requested review from ",_r=/\sand removed (?:review request for|approval)\b/;function Pr(e){return e.startsWith(ot)?[...e.slice(ot.length).split(_r)[0].matchAll(/@([A-Za-z0-9_][A-Za-z0-9_.-]*)/g)].map(r=>r[1].replace(/\.+$/,"").toLowerCase()):[]}const kt=e=>e.slice(e.lastIndexOf("/")+1);function Ar(e,t,r){const s=kt(e.id),n=Date.parse(e.createdAt),a=e.systemNoteMetadata?.action;if(!(!e.system||a&&a!=="reviewer")&&!(!/^\d+$/.test(s)||!Number.isFinite(n))&&Pr(e.body).includes(t.toLowerCase()))return{id:s,order:Number(s),url:e.url??`${r}#note_${s}`,at:n,...e.author?{requester:{id:e.author.id,username:e.author.username}}:{}}}async function Dr(e,t,r,s,n){const a=J(e),i=[];let l,o;const c=d=>{const h=i.toReversed().flat();return{complete:d&&l!==void 0,...l?{viewerID:l.id}:{},newest:h.reduce((p,w)=>{const $=Number(kt(w.id));return Number.isFinite($)?Math.max(p,$):p},0),requests:l?h.flatMap(p=>Ar(p,l.username,n)??[]).sort((p,w)=>p.order-w.order):[]}};for(let d=0;d<kr;d++){const h={project:r,iid:s};o&&(h.before=o);const p=await a(t,Er,h);l??=p.currentUser??void 0;const w=p.project?.mergeRequest?.notes;if(!w)return d===0?void 0:c(!1);if(i.push(w.nodes),!w.pageInfo.hasPreviousPage)return c(!0);if(o=w.pageInfo.startCursor??void 0,!o)return c(!1)}return c(!0)}const Nr=/^\/(.+?)\/-\/(issues|work_items|merge_requests)\/(\d+)(\/diffs)?\/?$/,qr=/^#note_(\d+)$/,xr=/https:\/\/[^\s<>()[\]"'`]+/g,Tr=/^gid:\/\/gitlab\/[A-Za-z]*Note\/(\d+)$/;function Me(e,t){if(e.length>rt*2)return;let r;try{r=new URL(e)}catch{return}if(r.protocol!=="https:"||r.hostname.toLowerCase()!==t||r.port||r.username||r.password)return;const s=r.hash.match(qr)?.[1],n=r.pathname.match(Nr);if(!s||!n)return;const[,a,i,l,o]=n;if(o&&i!=="merge_requests"||a.split("/").some(d=>!d||d==="."||d===".."))return;const c=`https://${t}/${a}/-/${i}/${l}#note_${s}`;if(!(c.length>rt))return{url:c,project:a,resource:i==="merge_requests"?"merge_request":"issue",iid:l,noteID:s}}const Et=(e,t)=>e.project.toLowerCase()===t.project.toLowerCase()&&e.resource===t.resource&&e.iid===t.iid&&e.noteID===t.noteID;function Mr(e,t){const r=new Set(t.map(n=>n.id)),s=[];for(const n of t)for(const[a]of n.body.matchAll(xr)){const i=Me(a.replace(/[.,;:!?*_~]+$/,""),e);if(!(!i||r.has(i.noteID))&&!s.some(l=>Et(l,i))&&(s.push(i),s.length===Xt))return s.map(l=>l.url)}return s.map(n=>n.url)}async function jr(e,t,r){const s=Me(r,t);if(!s||s.url!==r)return;const a=(await J(e)(t,_("query($id: NoteID!) { note(id: $id) { id url body author { username } } }"),{id:`gid://gitlab/Note/${s.noteID}`})).note;if(!a?.author||!a.url||a.id.match(Tr)?.[1]!==s.noteID)return;const i=Me(a.url,t);if(!(!i||!Et(i,s)))return{url:s.url,username:a.author.username,body:a.body}}const Lr=4*6e4;function Or(e){return{...e,comments:e.comments.filter(t=>t.automated?.reviewer==="GitLab Duo"&&t.automated.finding).map(t=>({...t,bot:!1}))}}function Ur(e,t){return e.comments.filter(s=>!s.resolved).every(s=>t-s.editedAt>=Lr&&(!s.automated?.status||["FINISHED","FAILED","STOPPED"].includes(s.automated.status)))}function Br(e,t,r){const s={Authorization:`Bearer ${t}`,Origin:r},n=new WebSocket(e,{protocols:["actioncable-v1-json"],headers:s}),a=new AbortController;let i=!1,l=!1;const o={send:c=>n.send(c),close:()=>{a.abort(),n.close()},onmessage:null,onerror:null,onclose:null,onresponse:null};return n.onopen=()=>{i=!0},n.onmessage=({data:c})=>o.onmessage?.(String(c)),n.onclose=()=>{l||o.onclose?.()},n.onerror=async()=>{if(a.signal.aborted||l)return;if(i){o.onerror?.();return}l=!0;const c=new URL(e);c.protocol=c.protocol==="wss:"?"https:":"http:";try{const d=await fetch(c,{redirect:"manual",signal:AbortSignal.any([a.signal,AbortSignal.timeout(1e4)]),headers:{...s,Connection:"Upgrade",Upgrade:"websocket","Sec-WebSocket-Version":"13","Sec-WebSocket-Key":Vt.randomBytes(16).toString("base64"),"Sec-WebSocket-Protocol":"actioncable-v1-json"}});try{a.signal.aborted||o.onresponse?.(d.status,d.headers)}finally{await d.body?.cancel()}}catch{a.signal.aborted||o.onerror?.()}},o}class Fr extends Error{constructor(t){super("Feedback subscription rate limited"),this.retryAt=t}retryAt}function Gr(e,t=Date.now()){const r=Date.parse(e.get("date")??""),s=Number.isFinite(r)?r:t,n=[],a=e.get("retry-after")?.trim();a&&(/^\d+$/.test(a)?n.push(Number(a)*1e3):/^[+-]?[\d.]+$/.test(a)||n.push(Date.parse(a)-s));for(const c of["ratelimit-reset","x-ratelimit-reset"]){const d=e.get(c)?.trim();d&&/^\d+$/.test(d)&&n.push(Number(d)*1e3-s)}const i=e.get("ratelimit-resettime");i&&n.push(Date.parse(i)-s);const l=n.filter(c=>Number.isFinite(c)&&c>=0);if(!l.length)return;const o=t+Math.max(...l);return Number.isSafeInteger(o)?o:void 0}async function zr(e,t,r,s,n,a=Br){const i=new URL(r.url);if(i.protocol!=="https:"||i.username||i.password||i.port)return;const l=i.pathname.match(/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/);if(!l||n.aborted)return;const o=await e("glab",["config","get","token","--host",i.hostname],t);if(n.aborted)return;if(o.code!==0||!o.stdout.trim())throw new Error("Subscription credentials unavailable");const c=await e("glab",["api",`projects/${encodeURIComponent(decodeURIComponent(l[1]))}/merge_requests/${l[2]}`,"--hostname",i.hostname],t);if(n.aborted)return;if(c.code!==0)throw new Error("Subscription target lookup failed");const d=JSON.parse(c.stdout);if(!Number.isSafeInteger(d.id)||!Number.isSafeInteger(d.project_id))throw new Error("Invalid subscription target");const h=JSON.stringify({channel:"Noteable::NotesChannel",project_id:d.project_id,noteable_type:"MergeRequest",noteable_id:d.id});await new Promise((p,w)=>{const $=a(`wss://${i.host}/-/cable`,o.stdout.trim(),i.origin);let b=!1,y=!1,D,j;const m=()=>{b||(b=!0,clearTimeout(j),n.removeEventListener("abort",m),$.onmessage=null,$.onerror=null,$.onclose=null,$.onresponse=null,$.close(),D?w(D):p())},k=()=>{clearTimeout(j),j=setTimeout(m,y?45e3:15e3)};k(),n.addEventListener("abort",m,{once:!0}),$.onerror=m,$.onclose=m,$.onresponse=(x,F)=>{x===429&&(D=new Fr(Gr(F)??Date.now()+6e4)),m()},$.onmessage=x=>{if(!b)try{const F=JSON.parse(String(x));if(y&&k(),F.type==="welcome"&&$.send(JSON.stringify({command:"subscribe",identifier:h})),F.type==="disconnect"&&m(),F.identifier!==h)return;F.type==="reject_subscription"&&m(),F.type==="confirm_subscription"&&!y&&(y=!0,k(),s.connected()),y&&F.message?.event==="updated"&&s.changed()}catch{m()}},n.aborted&&m()})}function Hr(e){const t=e.approvalsLeft??0;if(t<=0||e.approvalRequirementsSatisfied===!0)return;const r=Kt(e).filter(s=>!s.bot).length;return{text:r?`${r} approval${r===1?"":"s"} · ${t} more needed`:`${t} approval${t===1?"":"s"} needed`,compact:r?`${r} ✓ +${t}`:`+${t}`,tone:"muted",optional:!0}}function Wr(e){if(e.awaitingReviewers.length)return{text:Rt(e.awaitingReviewers),tone:"muted"};if(e.draft)return;const t=e.missingRules??[],r=t.length>0||(e.approvalsLeft??0)>0||e.mergeStatus==="NOT_APPROVED";if(!e.conflicts&&e.pipeline?.status!=="FAILED"){if(e.mergeTrainIndex!=null)return{text:`merge train #${e.mergeTrainIndex+1}`,tone:"muted",optional:!0};if(e.autoMergeEnabled&&(e.approvalRequirementsSatisfied===!0||e.mergeStatus==="MERGEABLE"&&!r))return{text:"auto-merge set",tone:"success",optional:!0}}if(e.approved||e.approvalRequirementsSatisfied===!0)return;const s=t.find(n=>n.type==="CODE_OWNER"||n.type==="REGULAR");if(s)return{text:s.type==="CODE_OWNER"?"needs a code owner":"needs an approver",tone:"warning",optional:!0};if(e.reviewersComplete&&r)return{text:"needs a reviewer",tone:"muted",optional:!0}}function Qr(e){const t=Hr(e),r=Wr(e);return[...t?[t]:[],...e.approved&&!e.awaitingReviewers.length?[{text:"approved",tone:"success"}]:[],...r?[r]:[]]}const _t="pageInfo { hasNextPage endCursor } nodes { resolvable resolved }",se=100,_e=50,Vr=10,Kr="pageInfo { hasNextPage } nodes { id name allowFailure webPath stage { name } }",Jr=new Set(["CHECKING","UNCHECKED","PREPARING"]),it="CANNOT_BE_MERGED_RECHECK",Pt=e=>`pageInfo { hasNextPage endCursor } nodes { id type username bot mergeRequestInteraction { reviewState approved${e?" approvedAt":""} } }`,At="pageInfo { hasNextPage endCursor } nodes { id username bot }",Dt=(e,t)=>`
|
|
59
59
|
iid title webUrl state draft conflicts approved mergeStatusEnum detailedMergeStatus diffHeadSha updatedAt targetBranch sourceBranch
|
|
60
|
-
|
|
60
|
+
autoMergeEnabled
|
|
61
|
+
${t?`
|
|
62
|
+
approvalsRequired approvalsLeft mergeTrainCar { index }
|
|
63
|
+
approvalState { rules { name type approvalsRequired approved eligibleApprovers { username type bot } } }
|
|
64
|
+
`:""}
|
|
65
|
+
approvedBy(first: ${se}) { ${At} }
|
|
61
66
|
sourceProject { fullPath }
|
|
62
67
|
targetProject { fullPath }
|
|
63
68
|
author { id }
|
|
64
69
|
headPipeline {
|
|
65
70
|
id status path detailedStatus { label }
|
|
66
|
-
jobs(statuses: [FAILED], retried: false, first: ${
|
|
71
|
+
jobs(statuses: [FAILED], retried: false, first: ${Vr}) { ${Kr} }
|
|
67
72
|
}
|
|
68
|
-
reviewers(first: ${
|
|
69
|
-
discussions(first: ${
|
|
70
|
-
`;function
|
|
71
|
-
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { ${
|
|
73
|
+
reviewers(first: ${se}) { ${Pt(e)} }
|
|
74
|
+
discussions(first: ${se}) { ${_t} }
|
|
75
|
+
`;function Yr(e,t=!0,r=!0){const s=Dt(t,r),n=Array.from({length:e},(i,l)=>`$p${l}: ID!`).join(", "),a=Array.from({length:e},(i,l)=>`p${l}: project(fullPath: $p${l}) {
|
|
76
|
+
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { ${s} } }
|
|
72
77
|
}`).join(`
|
|
73
78
|
`);return _(`query($branch: String!, ${n}) {
|
|
74
|
-
${
|
|
75
|
-
}`)}function
|
|
79
|
+
${a}
|
|
80
|
+
}`)}function Xr(e,t=!0,r=!0){const s=Dt(t,r),n=Array.from({length:e},(i,l)=>`$p${l}: ID!`).join(", "),a=Array.from({length:e},(i,l)=>`p${l}: project(fullPath: $p${l}) { mergeRequest(iid: $iid) { ${s} } }`).join(`
|
|
76
81
|
`);return _(`query($iid: String!, ${n}) {
|
|
77
|
-
${
|
|
78
|
-
}`)}function
|
|
82
|
+
${a}
|
|
83
|
+
}`)}function Zr(e){const t=Array.from({length:e},(s,n)=>`$p${n}: ID!`).join(", "),r=Array.from({length:e},(s,n)=>`p${n}: project(fullPath: $p${n}) {
|
|
79
84
|
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { iid updatedAt sourceProject { fullPath } } }
|
|
80
85
|
}`).join(`
|
|
81
|
-
`);return _(`query($branch: String!, ${
|
|
82
|
-
${
|
|
83
|
-
}`)}const
|
|
86
|
+
`);return _(`query($branch: String!, ${t}) {
|
|
87
|
+
${r}
|
|
88
|
+
}`)}const en=_(`query($project: ID!, $iid: String!) {
|
|
84
89
|
project(fullPath: $project) { mergeRequest(iid: $iid) { sourceBranch } }
|
|
85
|
-
}`),
|
|
90
|
+
}`),tn=_(`query($project: ID!, $iid: String!) {
|
|
86
91
|
project(fullPath: $project) {
|
|
87
|
-
|
|
92
|
+
workItems(iid: $iid, first: 1) {
|
|
93
|
+
nodes {
|
|
94
|
+
state
|
|
95
|
+
widgets {
|
|
96
|
+
... on WorkItemWidgetStatus { status { name } }
|
|
97
|
+
... on WorkItemWidgetAssignees { assignees { nodes { username } } }
|
|
98
|
+
... on WorkItemWidgetLabels { labels { nodes { title } } }
|
|
99
|
+
... on WorkItemWidgetMilestone { milestone { title } }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}`);function rn(e){const t=Array.from({length:e},(s,n)=>`$i${n}: String!`).join(", "),r=Array.from({length:e},(s,n)=>`$i${n}`).join(", ");return _(`query($project: ID!, ${t}) {
|
|
105
|
+
project(fullPath: $project) {
|
|
106
|
+
mergeRequests(iids: [${r}], first: ${e}) {
|
|
107
|
+
nodes { iid title webUrl state targetProject { fullPath } }
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}`)}function nn(e){const t=Array.from({length:e},(s,n)=>`$i${n}: String!`).join(", "),r=Array.from({length:e},(s,n)=>`$i${n}`).join(", ");return _(`query($project: ID!, ${t}) {
|
|
111
|
+
project(fullPath: $project) {
|
|
112
|
+
workItems(iids: [${r}], first: ${e}) {
|
|
113
|
+
nodes { iid state }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}`)}const sn=_(`query($project: ID!, $iid: String!, $after: String) {
|
|
117
|
+
project(fullPath: $project) {
|
|
118
|
+
mergeRequest(iid: $iid) { discussions(first: ${se}, after: $after) { ${_t} } }
|
|
88
119
|
}
|
|
89
|
-
}`),
|
|
120
|
+
}`),on=e=>_(`query($project: ID!, $iid: String!, $after: String) {
|
|
90
121
|
project(fullPath: $project) {
|
|
91
|
-
mergeRequest(iid: $iid) { reviewers(first: ${
|
|
122
|
+
mergeRequest(iid: $iid) { reviewers(first: ${se}, after: $after) { ${Pt(e)} } }
|
|
92
123
|
}
|
|
93
|
-
}`),
|
|
124
|
+
}`),an=_(`query($project: ID!, $iid: String!, $after: String) {
|
|
94
125
|
project(fullPath: $project) {
|
|
95
|
-
mergeRequest(iid: $iid) { approvedBy(first: ${
|
|
126
|
+
mergeRequest(iid: $iid) { approvedBy(first: ${se}, after: $after) { ${At} } }
|
|
96
127
|
}
|
|
97
|
-
}`),
|
|
128
|
+
}`),ln=_(`mutation($project: ID!, $iid: String!) {
|
|
98
129
|
mergeRequestSetDraft(input: { projectPath: $project, iid: $iid, draft: false }) {
|
|
99
130
|
mergeRequest { draft }
|
|
100
131
|
errors
|
|
101
132
|
}
|
|
102
|
-
}`),
|
|
103
|
-
`)[0])}const Ar=e=>typeof e=="object"&&e!==null&&(!("errors"in e)||Array.isArray(e.errors))&&(!("data"in e)||typeof e.data=="object");function H(e,r){return async(t,n,o)=>{const i=["api","graphql","--hostname",t,"-f",`query=${n}`];for(const[s,u]of Object.entries(o))i.push("-f",`${s}=${u}`);const a=await e("glab",i,r);let c;try{c=JSON.parse(a.stdout)}catch{throw Y(a.stderr,a.code)}if(!Ar(c))throw Y(a.stderr||"Unexpected GitLab response",a.code);if(c.errors?.length)throw Y(String(c.errors[0]?.message??""),a.code);if(a.code!==0)throw Y(a.stderr,a.code);if(!c.data)throw Y("GitLab returned no data",a.code);return c.data}}const Ge=e=>e.nodes.filter(r=>r.resolvable&&!r.resolved).length,F={kind:"gitlab",noun:"MR",ci:"pipeline",recognizes:e=>/(^|\.)gitlab\./.test(e),open:(e,r)=>new Or(H(e,r),_r),owns:et("gitlab"),parseUrl:e=>ve("gitlab",e,/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/),parseIssueUrl:e=>ve("gitlab",e,/^\/(.+)\/-\/(?:issues|work_items)\/([1-9]\d*)\/?$/),reference:e=>`!${e}`,issueReference:e=>`#${e}`,titleReferences:e=>tt(e,"!"),indicators:()=>[],details(e){const r=e.approvalRequirementsSatisfied===null?"unknown":Q(e.approvalRequirementsSatisfied),t=[`Human approvals: ${Q(e.hasApprovals)} · Approval requirements satisfied: ${r}`];return e.mergeStatus&&t.push(`Merge status: ${be(e.mergeStatus)}`),t},automatedReview:{publishedFeedback:{storageKey:"duo",select:dr,ready:pr},name:"GitLab Duo",status(e){const r=e.duoReviewState;if(r)return{state:Tr(r),label:be(r)}}},feedback:{async viewerID(e,r,t){return(await U(H(e,r))(t,_("query { currentUser { id } }"),{})).currentUser?.id},async reviewerID(e,r,t,n){const o=await U(H(e,r))(t,_("query($username: String!) { user(username: $username) { id username } }"),{username:n});return o.user?.username.toLowerCase()===n.toLowerCase()?o.user.id:void 0},subscribe:gr,async fetch(e,r,t){const n=F.parseUrl(t.url);return n?zt(H(e,r),n.host,n.project,n.iid):void 0},async reviewRequests(e,r,t){const n=F.parseUrl(t.url);return n?nr(H(e,r),n.host,n.project,n.iid,t.url):void 0},async details(e,r,t,n){const o=F.parseUrl(t.url);return o?Jt(H(e,r),o.host,o.project,n):[]},commentID:e=>e.match(/#note_(\d+)$/)?.[1],linkedNotes(e,r){const t=F.parseUrl(e.url);return t?cr(t.host,r):[]},async linkedNote(e,r,t,n){const o=F.parseUrl(t.url);return o?ur(H(e,r),o.host,n):void 0}}},Dr=new Set(["REVIEWED","REQUESTED_CHANGES"]);function Nr(e,r){return!r.id||!r.jobs?{}:{id:r.id,failedJobs:qr(e,r.jobs.nodes),failedJobsComplete:!r.jobs.pageInfo?.hasNextPage}}function qr(e,r){return r.flatMap(t=>!t.allowFailure&&t.name?[{...t.id?{id:t.id}:{},name:t.name,...t.webPath?{url:`https://${e}${t.webPath}`}:{},...t.stage?.name?{stage:t.stage.name}:{}}]:[])}function Tr(e){return e==="REVIEW_STARTED"?"running":Dr.has(e)?"feedback":"settled"}function xr(e,r){const t=new Map,n=new Map;for(const s of e)s.id&&t.set(s.id,s),s.username&&n.set(s.username.toLowerCase(),s);const o=(s,u,p)=>s?.type==="DUO_CODE_REVIEW_BOT"||p===!0&&u?.toLowerCase()==="gitlabduo",i=s=>{const u=s?.mergeRequestInteraction?.reviewState;return!!u&&u!=="APPROVED"},a=[],c=s=>{const u=s.username.toLowerCase(),p=a.findIndex(d=>s.id&&d.id?d.id===s.id:d.username.toLowerCase()===u&&(!s.id||!d.id));if(p<0){a.push(s);return}const h=a[p];a[p]={...h,...s,...h.id||s.id?{id:s.id??h.id}:{},...h.bot||s.bot?{bot:!0}:{},...h.automated||s.automated?{automated:!0}:{},...h.reviewID||s.reviewID?{reviewID:s.reviewID??h.reviewID}:{}}};for(const s of e){const u=s.mergeRequestInteraction;if(!(u?.reviewState==="APPROVED"||!u?.reviewState&&u?.approved===!0))continue;const h=o(s,s.username,s.bot),d=s.username??(h?"GitLabDuo":void 0);if(!d)continue;const w=s.bot===!0||h;c({...s.id?{id:s.id}:{},username:d,...w?{bot:!0}:{},...h?{automated:!0}:{},...u?.approvedAt?{reviewID:u.approvedAt}:{}})}for(const s of r){const u=(s.id?t.get(s.id):void 0)??(s.username?n.get(s.username.toLowerCase()):void 0);if(i(u))continue;const p=o(u,s.username??u?.username,s.bot??u?.bot),h=s.username??u?.username??(p?"GitLabDuo":void 0);if(!h)continue;const d=s.bot===!0||u?.bot===!0||p;c({...s.id||u?.id?{id:s.id??u?.id??void 0}:{},username:h,...d?{bot:!0}:{},...p?{automated:!0}:{}})}return a}class Or{constructor(r,t=new Set){this.unsupportedApprovedAt=t,this.graphql=U(r)}unsupportedApprovedAt;traits=F;graphql;async queryWithApprovedAt(r,t,n){if(this.unsupportedApprovedAt.has(r))return this.graphql(r,t(!1),n);try{return await this.graphql(r,t(!0),n)}catch(o){if(!Pr(o))throw o;return this.unsupportedApprovedAt.add(r),this.graphql(r,t(!1),n)}}async findByBranch(r){const{source:t,targets:n,sourceBranch:o}=r,i={branch:o};n.forEach((h,d)=>i[`p${d}`]=h.path);const a=await this.queryWithApprovedAt(t.host,h=>$r(n.length,h),i),c=t.path.toLowerCase(),s=new Set,u=[];return n.forEach((h,d)=>{for(const w of a[`p${d}`]?.mergeRequests?.nodes??[]){if(w.sourceProject?.fullPath.toLowerCase()!==c)continue;const v=`${w.targetProject.fullPath}!${w.iid}`;s.has(v)||(s.add(v),u.push(w))}}),(await Promise.all(u.map(h=>this.normalize(t.host,h)))).sort((h,d)=>(d.updatedAt??"").localeCompare(h.updatedAt??""))}async findNumberByBranch(r){const{source:t,targets:n,sourceBranch:o}=r,i={branch:o};n.forEach((u,p)=>i[`p${p}`]=u.path);const a=await this.graphql(t.host,Rr(n.length),i),c=t.path.toLowerCase();return n.flatMap((u,p)=>a[`p${p}`]?.mergeRequests?.nodes??[]).filter(u=>u.sourceProject?.fullPath.toLowerCase()===c).sort((u,p)=>(p.updatedAt??"").localeCompare(u.updatedAt??""))[0]?.iid}async sourceBranch(r){const n=(await this.graphql(r.host,Sr,{project:r.project,iid:r.iid})).project?.mergeRequest?.sourceBranch;return typeof n=="string"&&n?n:void 0}async markReady(r,t){await t?.beforeMutate?.();const o=(await this.graphql(r.host,Er,{project:r.project,iid:r.iid})).mergeRequestSetDraft;if(o?.errors?.length)throw new O("request",o.errors[0]);if(!o?.mergeRequest||o.mergeRequest.draft!==!1)throw new O("request","Could not mark the GitLab merge request as ready")}async findByNumber(r,t){if(r.length===0)return;const n=r[0].host,o={iid:t};r.forEach((a,c)=>o[`p${c}`]=a.path);const i=await this.queryWithApprovedAt(n,a=>yr(r.length,a),o);for(let a=0;a<r.length;a++){const c=i[`p${a}`]?.mergeRequest;if(c)return this.normalize(n,c)}}async unresolvedThreads(r,t){let n=Ge(t.discussions),o=t.discussions.pageInfo,i=1;for(;o.hasNextPage&&o.endCursor&&i<he;){const c=(await this.graphql(r,Cr,{project:t.targetProject.fullPath,iid:t.iid,after:o.endCursor})).project?.mergeRequest?.discussions;if(!c)break;n+=Ge(c),o=c.pageInfo,i++}return{count:n,complete:!o.hasNextPage}}async allReviewers(r,t){if(!t.reviewers?.pageInfo)return{nodes:[...t.reviewers?.nodes??[]],complete:!1};const n=[...t.reviewers.nodes];let o=t.reviewers.pageInfo,i=1;for(;o.hasNextPage&&o.endCursor&&i<he;){const c=(await this.queryWithApprovedAt(r,s=>Ir(s),{project:t.targetProject.fullPath,iid:t.iid,after:o.endCursor})).project?.mergeRequest?.reviewers;if(!c?.pageInfo)return{nodes:n,complete:!1};n.push(...c.nodes),o=c.pageInfo,i++}return{nodes:n,complete:!o.hasNextPage}}async allApprovedBy(r,t){if(!t.approvedBy?.pageInfo)return{nodes:[...t.approvedBy?.nodes??[]],complete:!1};const n=[...t.approvedBy.nodes];let o=t.approvedBy.pageInfo,i=1;for(;o.hasNextPage&&o.endCursor&&i<he;){const c=(await this.graphql(r,kr,{project:t.targetProject.fullPath,iid:t.iid,after:o.endCursor})).project?.mergeRequest?.approvedBy;if(!c?.pageInfo)return{nodes:n,complete:!1};n.push(...c.nodes),o=c.pageInfo,i++}return{nodes:n,complete:!o.hasNextPage}}async normalize(r,t){const[n,o,i]=await Promise.all([this.unresolvedThreads(r,t),this.allReviewers(r,t),this.allApprovedBy(r,t)]),a=t.headPipeline,c=i.nodes.some(u=>u.bot!==!0),s=o.nodes.filter(u=>u.bot!==!0&&u.username&&u.mergeRequestInteraction?.approved!==!0).map(u=>u.username);return{forge:"gitlab",iid:t.iid,title:t.title,url:t.webUrl,state:t.state.toLowerCase(),draft:t.draft,conflicts:t.conflicts||t.mergeStatusEnum===Fe,conflictsKnown:t.mergeStatusEnum!==Fe&&!br.has(t.detailedMergeStatus??""),approved:t.approved===!0&&c&&s.length===0,hasApprovals:c,approvalRequirementsSatisfied:t.approved,awaitingReviewers:s,reviewersComplete:o.complete,approvalsComplete:o.complete&&i.complete,reviewerIDs:o.nodes.flatMap(u=>u.id??[]),approvers:xr(o.nodes,i.nodes),mergeStatus:t.detailedMergeStatus??void 0,targetProject:t.targetProject.fullPath,targetBranch:t.targetBranch,...t.sourceProject?{sourceProject:t.sourceProject.fullPath}:{},sourceBranch:t.sourceBranch,headSha:t.diffHeadSha??void 0,...t.author?.id?{authorID:t.author.id}:{},updatedAt:t.updatedAt??void 0,pipeline:a?{status:a.status,label:a.detailedStatus?.label??a.status.toLowerCase().replace(/_/g," "),url:a.path?`https://${r}${a.path}`:void 0,...Nr(r,a)}:void 0,unresolvedThreads:n.count,threadsComplete:n.complete,duoReviewState:o.nodes.find(u=>u.type==="DUO_CODE_REVIEW_BOT")?.mergeRequestInteraction?.reviewState??void 0}}}const Re="copilot-pull-request-reviewer[bot]",He=`number title url state isDraft mergeable reviewDecision headRefOid headRefName
|
|
133
|
+
}`),cn=new Set,un=new Set,dn=e=>/(?:approvalsRequired|approvalsLeft|mergeTrainCar|approvalState).*?(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*?(?:approvalsRequired|approvalsLeft|mergeTrainCar|approvalState)|Field ['"]index['"] doesn't exist on type ['"]MergeTrainCar['"]/i.test(e instanceof Error?e.message:String(e)),pn=e=>/approvedAt.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*approvedAt/i.test(e instanceof Error?e.message:String(e));function le(e,t){const r=e.trim().replace(/^glab:\s*/,"")||`glab exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new B("missing-glab","glab is not installed"):/\b401\b|unauthori[sz]ed|not logged in|authenticate|invalid token|token.*expired/i.test(r)?new B("auth","GitLab authentication failed. Run `glab auth status`."):/\b429\b|rate limit|too many requests/i.test(r)?new B("rate-limit","GitLab rate limit reached"):new B("request",r.split(`
|
|
134
|
+
`)[0])}const fn=e=>typeof e=="object"&&e!==null&&(!("errors"in e)||Array.isArray(e.errors))&&(!("data"in e)||typeof e.data=="object");function re(e,t){return async(r,s,n)=>{const a=["api","graphql","--hostname",r,"-f",`query=${s}`];for(const[o,c]of Object.entries(n))a.push("-f",`${o}=${c}`);const i=await e("glab",a,t);let l;try{l=JSON.parse(i.stdout)}catch{throw le(i.stderr,i.code)}if(!fn(l))throw le(i.stderr||"Unexpected GitLab response",i.code);if(l.errors?.length)throw le(String(l.errors[0]?.message??""),i.code);if(i.code!==0)throw le(i.stderr,i.code);if(!l.data)throw le("GitLab returned no data",i.code);return l.data}}const at=e=>e.nodes.filter(t=>t.resolvable&&!t.resolved).length,ee={kind:"gitlab",noun:"MR",ci:"pipeline",recognizes:e=>/(^|\.)gitlab\./.test(e),open:(e,t)=>new bn(re(e,t),cn,un),owns:$t("gitlab"),parseUrl:e=>qe("gitlab",e,/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/),parseIssueUrl:e=>qe("gitlab",e,/^\/(.+)\/-\/(?:issues|work_items)\/([1-9]\d*)\/?$/),reference:e=>`!${e}`,issueReference:e=>`#${e}`,titleReferences:e=>yt(e,"!"),indicators:()=>[],reviewIndicators:Qr,details(e){const t=e.approvalRequirementsSatisfied===null?"unknown":oe(e.approvalRequirementsSatisfied),r=[`Human approvals: ${oe(e.hasApprovals)} · Approval requirements satisfied: ${t}`],s=e.approvalRequirementsSatisfied===!0?[]:e.missingRules??[];for(const n of s.slice(0,2)){const a=(n.eligibleCount??n.eligible.length)-n.eligible.length,i=n.eligibleReviewers.length?`, @${n.eligibleReviewers[0]} can approve`:n.eligible.length?`, ${e.awaitingReviewers.length?"ask an eligible approver: ":"ask "}@${n.eligible.join(", @")}${a>0?` or ${a} ${a===1?"other":"others"}`:""}`:"";r.push(`Still needed: ${n.name} (${n.required} required in total${i})`)}return s.length>2&&r.push(`+${s.length-2} more rules`),e.autoMergeEnabled&&r.push("Auto-merge: set"),e.mergeTrainIndex!=null&&r.push(`Merge train: position ${e.mergeTrainIndex+1}`),e.mergeStatus&&r.push(`Merge status: ${xe(e.mergeStatus)}`),r},automatedReview:{publishedFeedback:{storageKey:"duo",select:Or,ready:Ur},name:"GitLab Duo",status(e){const t=e.duoReviewState;if(t)return{state:wn(t),label:xe(t)}}},feedback:{async viewerID(e,t,r){return(await J(re(e,t))(r,_("query { currentUser { id } }"),{})).currentUser?.id},async reviewerID(e,t,r,s){const n=await J(re(e,t))(r,_("query($username: String!) { user(username: $username) { id username } }"),{username:s});return n.user?.username.toLowerCase()===s.toLowerCase()?n.user.id:void 0},subscribe:zr,async fetch(e,t,r){const s=ee.parseUrl(r.url);return s?$r(re(e,t),s.host,s.project,s.iid):void 0},async reviewRequests(e,t,r){const s=ee.parseUrl(r.url);return s?Dr(re(e,t),s.host,s.project,s.iid,r.url):void 0},async details(e,t,r,s){const n=ee.parseUrl(r.url);return n?Sr(re(e,t),n.host,n.project,s):[]},commentID:e=>e.match(/#note_(\d+)$/)?.[1],linkedNotes(e,t){const r=ee.parseUrl(e.url);return r?Mr(r.host,t):[]},async linkedNote(e,t,r,s){const n=ee.parseUrl(r.url);return n?jr(re(e,t),n.host,s):void 0}}},hn=new Set(["REVIEWED","REQUESTED_CHANGES"]);function gn(e,t){return!t.id||!t.jobs?{}:{id:t.id,failedJobs:mn(e,t.jobs.nodes),failedJobsComplete:!t.jobs.pageInfo?.hasNextPage}}function mn(e,t){return t.flatMap(r=>!r.allowFailure&&r.name?[{...r.id?{id:r.id}:{},name:r.name,...r.webPath?{url:`https://${e}${r.webPath}`}:{},...r.stage?.name?{stage:r.stage.name}:{}}]:[])}function wn(e){return e==="REVIEW_STARTED"?"running":hn.has(e)?"feedback":"settled"}function vn(e,t){const r=new Map,s=new Map;for(const o of e)o.id&&r.set(o.id,o),o.username&&s.set(o.username.toLowerCase(),o);const n=(o,c,d)=>o?.type==="DUO_CODE_REVIEW_BOT"||d===!0&&c?.toLowerCase()==="gitlabduo",a=o=>{const c=o?.mergeRequestInteraction?.reviewState;return!!c&&c!=="APPROVED"},i=[],l=o=>{const c=o.username.toLowerCase(),d=i.findIndex(p=>o.id&&p.id?p.id===o.id:p.username.toLowerCase()===c&&(!o.id||!p.id));if(d<0){i.push(o);return}const h=i[d];i[d]={...h,...o,...h.id||o.id?{id:o.id??h.id}:{},...h.bot||o.bot?{bot:!0}:{},...h.automated||o.automated?{automated:!0}:{},...h.reviewID||o.reviewID?{reviewID:o.reviewID??h.reviewID}:{}}};for(const o of e){const c=o.mergeRequestInteraction;if(!(c?.reviewState==="APPROVED"||!c?.reviewState&&c?.approved===!0))continue;const h=n(o,o.username,o.bot),p=o.username??(h?"GitLabDuo":void 0);if(!p)continue;const w=o.bot===!0||h;l({...o.id?{id:o.id}:{},username:p,...w?{bot:!0}:{},...h?{automated:!0}:{},...c?.approvedAt?{reviewID:c.approvedAt}:{}})}for(const o of t){const c=(o.id?r.get(o.id):void 0)??(o.username?s.get(o.username.toLowerCase()):void 0);if(a(c))continue;const d=n(c,o.username??c?.username,o.bot??c?.bot),h=o.username??c?.username??(d?"GitLabDuo":void 0);if(!h)continue;const p=o.bot===!0||c?.bot===!0||d;l({...o.id||c?.id?{id:o.id??c?.id??void 0}:{},username:h,...p?{bot:!0}:{},...d?{automated:!0}:{}})}return i}class bn{constructor(t,r=new Set,s=new Set){this.unsupportedApprovedAt=r,this.unsupportedExtendedStatus=s,this.graphql=J(t)}unsupportedApprovedAt;unsupportedExtendedStatus;traits=ee;graphql;async queryWithApprovedAt(t,r,s){if(this.unsupportedApprovedAt.has(t))return this.graphql(t,r(!1),s);try{return await this.graphql(t,r(!0),s)}catch(n){if(!pn(n))throw n;return this.unsupportedApprovedAt.add(t),this.graphql(t,r(!1),s)}}async queryStatus(t,r,s){const n=a=>this.queryWithApprovedAt(t,i=>r(i,a),s);if(this.unsupportedExtendedStatus.has(t))return n(!1);try{return await n(!0)}catch(a){if(!dn(a))throw a;return this.unsupportedExtendedStatus.add(t),n(!1)}}async findByBranch(t){const{source:r,targets:s,sourceBranch:n}=t,a={branch:n};s.forEach((h,p)=>a[`p${p}`]=h.path);const i=await this.queryStatus(r.host,(h,p)=>Yr(s.length,h,p),a),l=r.path.toLowerCase(),o=new Set,c=[];return s.forEach((h,p)=>{for(const w of i[`p${p}`]?.mergeRequests?.nodes??[]){if(w.sourceProject?.fullPath.toLowerCase()!==l)continue;const $=`${w.targetProject.fullPath}!${w.iid}`;o.has($)||(o.add($),c.push(w))}}),(await Promise.all(c.map(h=>this.normalize(r.host,h)))).sort((h,p)=>(p.updatedAt??"").localeCompare(h.updatedAt??""))}async findNumberByBranch(t){const{source:r,targets:s,sourceBranch:n}=t,a={branch:n};s.forEach((c,d)=>a[`p${d}`]=c.path);const i=await this.graphql(r.host,Zr(s.length),a),l=r.path.toLowerCase();return s.flatMap((c,d)=>i[`p${d}`]?.mergeRequests?.nodes??[]).filter(c=>c.sourceProject?.fullPath.toLowerCase()===l).sort((c,d)=>(d.updatedAt??"").localeCompare(c.updatedAt??""))[0]?.iid}async sourceBranch(t){const s=(await this.graphql(t.host,en,{project:t.project,iid:t.iid})).project?.mergeRequest?.sourceBranch;return typeof s=="string"&&s?s:void 0}async issue(t){const s=(await this.graphql(t.host,tn,{project:t.project,iid:t.iid})).project?.workItems?.nodes[0];if(!s)return;const n=s.widgets,a=n.find(l=>l.milestone)?.milestone?.title,i=n.find(l=>l.status)?.status?.name;return{forge:"gitlab",open:s.state==="OPEN",...i?{status:i}:{},assignees:n.flatMap(l=>l.assignees?.nodes??[]).map(l=>l.username),labels:n.flatMap(l=>l.labels?.nodes??[]).map(l=>l.title),...a?{milestone:a}:{}}}async requestStates(t,r){const s=[...new Set(r.filter(Boolean))],n=new Map,a=async i=>{if(i.length===0)return;const l={project:t.path};i.forEach((o,c)=>l[`i${c}`]=o);try{const o=await this.graphql(t.host,rn(i.length),l);for(const c of o.project?.mergeRequests?.nodes??[])!c||!c.iid||!c.state||!c.webUrl||!c.targetProject?.fullPath||n.set(c.iid,{iid:c.iid,title:c.title??"",url:c.webUrl,state:c.state.toLowerCase(),targetProject:c.targetProject.fullPath})}catch(o){if(!(o instanceof B)||o.kind!=="request")throw o;if(i.length===1)return;const c=Math.ceil(i.length/2);await a(i.slice(0,c)),await a(i.slice(c))}};return await a(s),n}async issueStates(t,r){const s=[...new Set(r.filter(Boolean))],n=new Map,a=async i=>{if(i.length===0)return;const l={project:t.path};i.forEach((o,c)=>l[`i${c}`]=o);try{const o=await this.graphql(t.host,nn(i.length),l);for(const c of o.project?.workItems?.nodes??[])!c||!c.iid||c.state!=="OPEN"&&c.state!=="CLOSED"||n.set(c.iid,{iid:c.iid,open:c.state==="OPEN"})}catch(o){if(!(o instanceof B)||o.kind!=="request")throw o;if(i.length===1)return;const c=Math.ceil(i.length/2);await a(i.slice(0,c)),await a(i.slice(c))}};return await a(s),n}async markReady(t,r){await r?.beforeMutate?.();const n=(await this.graphql(t.host,ln,{project:t.project,iid:t.iid})).mergeRequestSetDraft;if(n?.errors?.length)throw new B("request",n.errors[0]);if(!n?.mergeRequest||n.mergeRequest.draft!==!1)throw new B("request","Could not mark the GitLab merge request as ready")}async findByNumber(t,r){if(t.length===0)return;const s=t[0].host,n={iid:r};t.forEach((i,l)=>n[`p${l}`]=i.path);const a=await this.queryStatus(s,(i,l)=>Xr(t.length,i,l),n);for(let i=0;i<t.length;i++){const l=a[`p${i}`]?.mergeRequest;if(l)return this.normalize(s,l)}}async unresolvedThreads(t,r){let s=at(r.discussions),n=r.discussions.pageInfo,a=1;for(;n.hasNextPage&&n.endCursor&&a<_e;){const l=(await this.graphql(t,sn,{project:r.targetProject.fullPath,iid:r.iid,after:n.endCursor})).project?.mergeRequest?.discussions;if(!l)break;s+=at(l),n=l.pageInfo,a++}return{count:s,complete:!n.hasNextPage}}async allReviewers(t,r){if(!r.reviewers?.pageInfo)return{nodes:[...r.reviewers?.nodes??[]],complete:!1};const s=[...r.reviewers.nodes];let n=r.reviewers.pageInfo,a=1;for(;n.hasNextPage&&n.endCursor&&a<_e;){const l=(await this.queryWithApprovedAt(t,o=>on(o),{project:r.targetProject.fullPath,iid:r.iid,after:n.endCursor})).project?.mergeRequest?.reviewers;if(!l?.pageInfo)return{nodes:s,complete:!1};s.push(...l.nodes),n=l.pageInfo,a++}return{nodes:s,complete:!n.hasNextPage}}async allApprovedBy(t,r){if(!r.approvedBy?.pageInfo)return{nodes:[...r.approvedBy?.nodes??[]],complete:!1};const s=[...r.approvedBy.nodes];let n=r.approvedBy.pageInfo,a=1;for(;n.hasNextPage&&n.endCursor&&a<_e;){const l=(await this.graphql(t,an,{project:r.targetProject.fullPath,iid:r.iid,after:n.endCursor})).project?.mergeRequest?.approvedBy;if(!l?.pageInfo)return{nodes:s,complete:!1};s.push(...l.nodes),n=l.pageInfo,a++}return{nodes:s,complete:!n.hasNextPage}}async normalize(t,r){const[s,n,a]=await Promise.all([this.unresolvedThreads(t,r),this.allReviewers(t,r),this.allApprovedBy(t,r)]),i=r.headPipeline,l=a.nodes.some(p=>p.bot!==!0),o=n.nodes.filter(p=>p.bot!==!0&&p.username&&p.mergeRequestInteraction?.approved!==!0).map(p=>p.username),c=vn(n.nodes,a.nodes),d=new Set([...a.nodes,...c].flatMap(({username:p})=>p?[p.toLowerCase()]:[])),h=(r.approvalState?.rules??[]).flatMap(p=>{if(p.approvalsRequired==null||p.approvalsRequired<=0||p.approved!==!1)return[];const w=(p.eligibleApprovers??[]).filter(({username:m,bot:k})=>!k&&!d.has(m.toLowerCase())),$=new Set(w.map(({username:m})=>m.toLowerCase())),b=w.filter(({type:m})=>m==="HUMAN"),y=new Set(b.map(({username:m})=>m.toLowerCase())),D=o.filter(m=>$.has(m.toLowerCase())).sort((m,k)=>Number(y.has(k.toLowerCase()))-Number(y.has(m.toLowerCase()))),j=b.length?b:w;return[{name:p.name??"Unnamed approval rule",type:p.type??void 0,required:p.approvalsRequired,eligibleReviewers:D,eligible:j.slice(0,2).map(({username:m})=>m),eligibleCount:j.length}]});return{forge:"gitlab",iid:r.iid,title:r.title,url:r.webUrl,state:r.state.toLowerCase(),draft:r.draft,conflicts:r.conflicts||r.mergeStatusEnum===it,conflictsKnown:r.mergeStatusEnum!==it&&!Jr.has(r.detailedMergeStatus??""),approved:r.approved===!0&&l&&o.length===0,hasApprovals:l,approvalRequirementsSatisfied:r.approved,approvalsRequired:r.approvalsRequired??void 0,approvalsLeft:r.approvalsLeft??void 0,missingRules:h,autoMergeEnabled:r.autoMergeEnabled,mergeTrainIndex:r.mergeTrainCar?.index,awaitingReviewers:o,reviewersComplete:n.complete,changesRequested:n.nodes.some(p=>p.mergeRequestInteraction?.reviewState==="REQUESTED_CHANGES")?!0:n.complete&&n.nodes.every(p=>p.mergeRequestInteraction?.reviewState)?!1:void 0,approvalsComplete:n.complete&&a.complete,reviewerIDs:n.nodes.flatMap(p=>p.id??[]),approvers:c,mergeStatus:r.detailedMergeStatus??void 0,targetProject:r.targetProject.fullPath,targetBranch:r.targetBranch,...r.sourceProject?{sourceProject:r.sourceProject.fullPath}:{},sourceBranch:r.sourceBranch,headSha:r.diffHeadSha??void 0,...r.author?.id?{authorID:r.author.id}:{},updatedAt:r.updatedAt??void 0,pipeline:i?{status:i.status,label:i.detailedStatus?.label??i.status.toLowerCase().replace(/_/g," "),url:i.path?`https://${t}${i.path}`:void 0,...gn(t,i)}:void 0,unresolvedThreads:s.count,threadsComplete:s.complete,duoReviewState:n.nodes.find(p=>p.type==="DUO_CODE_REVIEW_BOT")?.mergeRequestInteraction?.reviewState??void 0}}}const je="copilot-pull-request-reviewer[bot]",lt=`number title url state isDraft mergeable reviewDecision headRefOid headRefName
|
|
104
135
|
headRepository { nameWithOwner } baseRepository { nameWithOwner } baseRefName updatedAt
|
|
105
136
|
author { ... on User { id } ... on Bot { id } }
|
|
106
137
|
reviewThreads(first:100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
107
138
|
reviewRequests(first:100) { nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } } pageInfo { hasNextPage endCursor } }
|
|
108
139
|
latestReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } }
|
|
109
140
|
latestOpinionatedReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } pageInfo { hasNextPage endCursor } }
|
|
110
|
-
copilotReviews: reviews(last:1, author:"${
|
|
141
|
+
copilotReviews: reviews(last:1, author:"${je}", states:[COMMENTED,CHANGES_REQUESTED,APPROVED,DISMISSED]) { nodes { id state comments { totalCount } author { __typename login ... on Bot { id } ... on User { id } } } }
|
|
111
142
|
commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
|
|
112
143
|
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } }
|
|
113
144
|
pageInfo { hasNextPage endCursor }
|
|
114
|
-
} } } } }`,
|
|
115
|
-
`)[0])}const
|
|
116
|
-
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${
|
|
117
|
-
}`),{owner:
|
|
145
|
+
} } } } }`,ce=50;function ge(e,t){return async(r,s,n)=>{const a=["api","graphql","--hostname",r,"-f",`query=${s}`];for(const[c,d]of Object.entries(n))a.push(typeof d=="number"?"-F":"-f",`${c}=${d}`);const i=await e("gh",a,t);let l;try{l=JSON.parse(i.stdout)}catch{throw ct(i.stderr,i.code)}const o=(l.errors??[]).filter(c=>c.type!=="NOT_FOUND");if(!l.data||o.length||i.code!==0&&!l.errors?.length)throw ct(o[0]?.message??i.stderr,i.code);return l.data}}function ct(e,t){const r=e.trim()||`gh exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new B("missing-gh","gh is not installed"):/401|unauthori[sz]ed|authenticate|not logged|token.*expired/i.test(r)?new B("auth","GitHub authentication failed. Run `gh auth status`."):/429|rate limit|too many requests/i.test(r)?new B("rate-limit","GitHub rate limit reached"):new B("request",r.split(`
|
|
146
|
+
`)[0])}const $n=["FAILURE","ERROR","TIMED_OUT","ACTION_REQUIRED","STARTUP_FAILURE"],yn=["SUCCESS","NEUTRAL","SKIPPED","FAILURE","TIMED_OUT","CANCELLED","ACTION_REQUIRED","STARTUP_FAILURE","STALE"],Rn=["SUCCESS","FAILURE","ERROR","PENDING","EXPECTED"],ut=e=>e.__typename==="CheckRun"&&e.name&&e.checkSuite?.app?.id&&e.checkSuite.workflowRun?.workflow?.id&&JSON.stringify([e.checkSuite.app.id,e.checkSuite.workflowRun?.workflow?.id,e.name]),Le=e=>Date.parse(e.checkSuite?.createdAt??""),dt=(e,t)=>Le(e)>Le(t);function Sn(e,t,r,s){const n=new Map;for(const b of e){const y=Le(b),D=ut(b);if(!D||!Number.isFinite(y))continue;const j=n.get(D);(!j||dt(b,j))&&n.set(D,b)}e=e.filter(b=>{const y=ut(b),D=y&&n.get(y);return!D||!dt(D,b)});const a=b=>`${b} check${b===1?"":"s"}`,i=e.filter(b=>b.conclusion==="CANCELLED").length,l=e.filter(b=>b.conclusion==="STALE").length,o=[...i?[`${a(i)} cancelled`]:[],...l?[`${a(l)} stale`]:[]],c=e.filter(b=>$n.includes(b.conclusion??b.state??"")),d=c.length,h=s?{id:s,failedJobs:c.flatMap(b=>{const y=b.name??b.context,D=b.detailsUrl??b.targetUrl;return y?[{...b.id?{id:b.id}:{},name:y,...D?{url:D}:{}}]:[]}),failedJobsComplete:t}:{},p=e.filter(b=>b.status?b.status!=="COMPLETED":["PENDING","EXPECTED"].includes(b.state??"")).length,w=e.some(b=>b.status==="COMPLETED"?!yn.includes(b.conclusion??""):!b.status&&!Rn.includes(b.state??""));return d?{status:"FAILED",label:[`${a(d)} failed`,...o,...p?[`${a(p)} pending`]:[]].join(", ")+(t?"":" (partial)"),url:r,...h,running:p>0}:p||!t||w?{status:"PENDING",label:[...o,p?`${a(p)} pending`:"unknown"].join(", ")+(t?"":" (partial)"),url:r,...h}:i||l?{status:"CANCELLED",label:o.join(", "),url:r,...h}:{status:"SUCCESS",label:[["SUCCESS","passed"],["SKIPPED","skipped"],["NEUTRAL","neutral"]].flatMap(([b,y])=>{const D=e.filter(j=>(j.conclusion??j.state)===b).length;return D?[`${a(D)} ${y}`]:[]}).join(", ")||"0 checks",url:r,...h}}function pt(e,t){const r=qe("github",e,t);return r&&!ee.recognizes(r.host)?r:void 0}const $e={kind:"github",noun:"PR",ci:"checks",recognizes:()=>!1,open:(e,t)=>new _n(ge(e,t)),owns:$t("github"),parseUrl:e=>pt(e,/^\/([^/]+\/[^/]+)\/pull\/([1-9]\d*)\/?$/),parseIssueUrl:e=>pt(e,/^\/([^/]+\/[^/]+)\/issues\/([1-9]\d*)\/?$/),reference:e=>`#${e}`,issueReference:e=>`#${e}`,titleReferences:e=>yt(e,"#"),indicators:e=>e.reviewDecision==="CHANGES_REQUESTED"?[{text:"changes requested",tone:"warning",essential:!0}]:[],details:e=>[`Review decision: ${e.reviewDecision?xe(e.reviewDecision):"not reported"}`],automatedReview:{name:"GitHub Copilot",status:e=>Cn(e.copilotReview)},feedback:{async viewerID(e,t,r){return(await J(ge(e,t))(r,_("query { viewer { id } }"),{})).viewer?.id},async reviewerID(e,t,r,s){const n=await e("gh",["api","--hostname",r,`users/${encodeURIComponent(s)}`],t);if(n.code!==0)throw new Error("Could not resolve the GitHub reviewer account");const a=JSON.parse(n.stdout);return a.login?.toLowerCase()===s.toLowerCase()?a.node_id:void 0},async fetch(e,t,r){const s=$e.parseUrl(r.url);return s?hr(ge(e,t),s.host,s.project,s.iid):void 0},async details(e,t,r,s){const n=$e.parseUrl(r.url);return n?fr(ge(e,t),n.host,s):[]}}};function Cn(e){if(!e)return;const t=e.comments>0&&!e.dismissed,r=e.dismissed?"dismissed":t?"commented":"no comments",s=e.reviewID?{id:e.reviewID,feedback:t,label:r}:void 0;if(e.requested)return{state:"running",label:"reviewing",completed:s};if(s)return{state:t?"feedback":"settled",label:r,completed:s}}const Nt=e=>/^copilot-pull-request-reviewer(\[bot\])?$/i.test(e??""),Oe=e=>e?.__typename==="Bot"&&Nt(e.login);function In(e){const t=e.reviewRequests.nodes.some(s=>Oe(s.requestedReviewer)),r=e.copilotReviews?.nodes?.find(s=>s);if(!(!t&&!r))return{requested:t,reviewID:r?.id,comments:r?.comments.totalCount??0,...r?.state==="DISMISSED"?{dismissed:!0}:{}}}function he(e,t){return t==="Bot"&&!e.endsWith("[bot]")?`${e}[bot]`:e}function qt(e){const t=new Set,r=new Set,s=new Set,n=(a,i)=>`${a??"Unknown"}:${he(i,a).toLowerCase()}`;for(const a of e.nodes){const i=a.requestedReviewer;if(i?.id&&t.add(i.id),i?.login){const l=n(i.__typename,i.login);s.add(l),i.id||r.add(l)}}return(a,i,l)=>{const o=n(i,l);return a?t.has(a)||r.has(o):s.has(o)}}function kn(e,t,r){const s=qt(t),n=new Map,a=o=>{const c=`${o.bot?"bot":"user"}:${o.username.toLowerCase()}`,d=n.get(c);if(!d){n.set(c,o);return}n.set(c,{...d,...o,...d.id||o.id?{id:o.id??d.id}:{},...d.bot||o.bot?{bot:!0}:{},...d.automated||o.automated?{automated:!0}:{},...d.reviewID||o.reviewID?{reviewID:o.reviewID??d.reviewID}:{}})};for(const o of r){if(o?.state!=="APPROVED"||!o.author?.login)continue;const{id:c,login:d,__typename:h}=o.author;if(s(c,h,d))continue;const p=h==="Bot",w=p&&Nt(d),$=w?je:he(d,h);a({...c?{id:c}:{},username:$,...p?{bot:!0}:{},...w?{automated:!0}:{},...o.id?{reviewID:o.id}:{}})}const i=e.copilotReviews?.nodes?.find(o=>o),l=t.nodes.some(o=>Oe(o.requestedReviewer));return i?.state==="APPROVED"&&Oe(i.author)&&!l&&a({...i.author?.id?{id:i.author.id}:{},username:je,bot:!0,automated:!0,...i.id?{reviewID:i.id}:{}}),[...n.values()]}function En(e,t){if(!e.pageInfo||e.pageInfo.hasNextPage)return{};const r=qt(e),s=[];let n=t.complete;for(const a of t.nodes){if(a?.state!=="CHANGES_REQUESTED")continue;const i=a.author;if(!i?.login||!a.id){n=!1;continue}r(i.id,i.__typename,i.login)||s.push(a.id)}return s.length?{changesRequested:!0,changeReviewIDs:s}:n?{changesRequested:!1}:{}}class _n{traits=$e;graphql;constructor(t){this.graphql=J(t)}async findByNumber(t,r){for(const s of t){const[n,a]=s.path.split("/"),l=(await this.graphql(s.host,_(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
147
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${lt} } }
|
|
148
|
+
}`),{owner:n,repo:a,number:Number(r)})).repository?.pullRequest;if(l)return this.normalize(s.host,l)}}async findNumberByBranch(t){let r;for(const s of t.targets){const[n,a]=s.path.split("/"),l=(await this.graphql(s.host,_(`query($owner:String!,$repo:String!,$branch:String!) {
|
|
118
149
|
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch,orderBy:{field:UPDATED_AT,direction:DESC}) {
|
|
119
150
|
nodes { number updatedAt headRepository { nameWithOwner } }
|
|
120
|
-
} } }`),{owner:
|
|
151
|
+
} } }`),{owner:n,repo:a,branch:t.sourceBranch})).repository?.pullRequests?.nodes??[];for(const o of l)o.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(!r||o.updatedAt>r.updatedAt)&&(r=o)}return r?String(r.number):void 0}async sourceBranch(t){const[r,s]=t.project.split("/");return(await this.graphql(t.host,_(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
121
152
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { headRefName } }
|
|
122
|
-
}`),{owner:
|
|
153
|
+
}`),{owner:r,repo:s,number:Number(t.iid)})).repository?.pullRequest?.headRefName||void 0}async issue(t){const[r,s]=t.project.split("/"),n=Number(t.iid);if(!r||!s||!Number.isInteger(n)||n<1)return;const i=(await this.graphql(t.host,_(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
154
|
+
repository(owner:$owner,name:$repo) { issue(number:$number) { state url } }
|
|
155
|
+
}`),{owner:r,repo:s,number:n})).repository?.issue;if(!(!i||!i.url||i.state!=="OPEN"&&i.state!=="CLOSED"))return{forge:"github",open:i.state==="OPEN",url:i.url}}async requestStates(t,r){const[s,n]=t.path.split("/"),a=[...new Set(r.filter(o=>{const c=Number(o);return Number.isInteger(c)&&c>=1}))];if(!s||!n||a.length===0)return new Map;const i=new Map,l=async o=>{if(o.length===0)return;const c=o.map((p,w)=>`$n${w}:Int!`).join(","),d=o.map((p,w)=>`pr${w}:pullRequest(number:$n${w}){number title url state baseRepository{nameWithOwner}}`).join(" "),h={owner:s,repo:n};o.forEach((p,w)=>h[`n${w}`]=Number(p));try{const w=(await this.graphql(t.host,_(`query($owner:String!,$repo:String!,${c}){repository(owner:$owner,name:$repo){${d}}}`),h)).repository;if(!w)return;o.forEach(($,b)=>{const y=w[`pr${b}`];!y||!y.url||!y.state||String(y.number??$)!==$||i.set($,{iid:$,title:y.title??"",url:y.url,state:y.state==="OPEN"?"opened":y.state.toLowerCase(),targetProject:y.baseRepository?.nameWithOwner??t.path})})}catch(p){if(!(p instanceof B)||p.kind!=="request")throw p;if(o.length===1)return;const w=Math.ceil(o.length/2);await l(o.slice(0,w)),await l(o.slice(w))}};return await l(a),i}async issueStates(t,r){const[s,n]=t.path.split("/"),a=[...new Set(r.filter(o=>{const c=Number(o);return Number.isInteger(c)&&c>=1}))];if(!s||!n||a.length===0)return new Map;const i=new Map,l=async o=>{if(o.length===0)return;const c=o.map((p,w)=>`$n${w}:Int!`).join(","),d=o.map((p,w)=>`i${w}:issue(number:$n${w}){number state url}`).join(" "),h={owner:s,repo:n};o.forEach((p,w)=>h[`n${w}`]=Number(p));try{const w=(await this.graphql(t.host,_(`query($owner:String!,$repo:String!,${c}){repository(owner:$owner,name:$repo){${d}}}`),h)).repository;if(!w)return;o.forEach(($,b)=>{const y=w[`i${b}`];!y||!y.url||y.state!=="OPEN"&&y.state!=="CLOSED"||String(y.number??$)===$&&i.set($,{iid:$,open:y.state==="OPEN"})})}catch(p){if(!(p instanceof B)||p.kind!=="request")throw p;if(o.length===1)return;const w=Math.ceil(o.length/2);await l(o.slice(0,w)),await l(o.slice(w))}};return await l(a),i}async markReady(t,r){const[s,n]=t.project.split("/"),i=(await this.graphql(t.host,_(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
123
156
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { id isDraft state } }
|
|
124
|
-
}`),{owner:
|
|
157
|
+
}`),{owner:s,repo:n,number:Number(t.iid)})).repository?.pullRequest;if(!i?.id)throw new B("request","GitHub pull request not found");if(i.state!=="OPEN")throw new B("request","The GitHub pull request is no longer open");if(!i.isDraft)return;await r?.beforeMutate?.();const o=(await this.graphql(t.host,_(`mutation($id:ID!) {
|
|
125
158
|
markPullRequestReadyForReview(input:{pullRequestId:$id}) { pullRequest { id isDraft } }
|
|
126
|
-
}`),{id:
|
|
127
|
-
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${
|
|
128
|
-
nodes { ${
|
|
129
|
-
} } }`),{owner:
|
|
159
|
+
}`),{id:i.id})).markPullRequestReadyForReview?.pullRequest;if(!o||o.isDraft)throw new B("request","Could not mark the GitHub pull request as ready")}async findByBranch(t){const r=new Map;for(const s of t.targets){const[n,a]=s.path.split("/");let i,l=!1;for(let o=0;o<ce;o++){const d=(await this.graphql(s.host,_(`query($owner:String!,$repo:String!,$branch:String!${i?",$after:String!":""}) {
|
|
160
|
+
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${i?",after:$after":""}) {
|
|
161
|
+
nodes { ${lt} } pageInfo { hasNextPage endCursor }
|
|
162
|
+
} } }`),{owner:n,repo:a,branch:t.sourceBranch,...i?{after:i}:{}})).repository?.pullRequests;if(!d)throw new B("request","GitHub repository unavailable");for(const h of d.nodes)h.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(r.has(h.url)||r.set(h.url,await this.normalize(s.host,h)));if(!d.pageInfo?.hasNextPage){l=!0;break}if(i=d.pageInfo.endCursor,!i)break}if(!l)throw new B("request","GitHub PR discovery exceeded its pagination limit")}return[...r.values()].sort((s,n)=>(n.updatedAt??"").localeCompare(s.updatedAt??""))}async threads(t,r){const[s,n]=r.baseRepository.nameWithOwner.split("/"),a=[...r.reviewThreads.nodes];let i=r.reviewThreads.pageInfo;for(let l=1;i?.hasNextPage&&i.endCursor&&l<ce;l++){const c=(await this.graphql(t,_(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
130
163
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
131
164
|
reviewThreads(first:100,after:$after) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
132
|
-
} } }`),{owner:
|
|
165
|
+
} } }`),{owner:s,repo:n,number:r.number,after:i.endCursor})).repository?.pullRequest?.reviewThreads;if(!c)break;a.push(...c.nodes),i=c.pageInfo}return{unresolved:a.filter(l=>!l.isResolved).length,complete:!i?.hasNextPage}}async contexts(t,r){const[s,n]=r.baseRepository.nameWithOwner.split("/"),a=r.commits.nodes[0]?.commit.statusCheckRollup?.contexts,i=[...a?.nodes??[]];let l=a?.pageInfo;for(let o=1;l?.hasNextPage&&l.endCursor&&o<ce;o++){const d=(await this.graphql(t,_(`query($owner:String!,$repo:String!,$oid:GitObjectID!,$after:String!) {
|
|
133
166
|
repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
|
|
134
167
|
contexts(first:100,after:$after) { nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } } pageInfo { hasNextPage endCursor } }
|
|
135
|
-
} } } } }`),{owner:
|
|
168
|
+
} } } } }`),{owner:s,repo:n,oid:r.headRefOid,after:l.endCursor})).repository?.object?.statusCheckRollup?.contexts;if(!d)break;i.push(...d.nodes),l=d.pageInfo}return{nodes:i,complete:!l?.hasNextPage}}async reviewers(t,r){const s=[...r.reviewRequests.nodes];let n=r.reviewRequests.pageInfo;for(let a=1;n?.hasNextPage&&a<ce;a++){if(!n.endCursor)throw new B("request","GitHub reviewer pagination cursor missing");const[i,l]=r.baseRepository.nameWithOwner.split("/"),c=(await this.graphql(t,_(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
136
169
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
137
170
|
reviewRequests(first:100,after:$after) {
|
|
138
171
|
nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } }
|
|
139
172
|
pageInfo { hasNextPage endCursor }
|
|
140
173
|
}
|
|
141
174
|
} }
|
|
142
|
-
}`),{owner:
|
|
175
|
+
}`),{owner:i,repo:l,number:r.number,after:n.endCursor})).repository?.pullRequest?.reviewRequests;if(!c)throw new B("request","GitHub reviewers unavailable");s.push(...c.nodes),n=c.pageInfo}if(n?.hasNextPage)throw new B("request","GitHub reviewers exceeded the pagination limit");return{nodes:s,pageInfo:n}}async opinionatedReviews(t,r){if(!r.latestOpinionatedReviews?.pageInfo)return{nodes:[...r.latestOpinionatedReviews?.nodes??[]],complete:!1};const s=[...r.latestOpinionatedReviews.nodes];let n=r.latestOpinionatedReviews.pageInfo;for(let a=1;n.hasNextPage&&n.endCursor&&a<ce;a++){const[i,l]=r.baseRepository.nameWithOwner.split("/"),c=(await this.graphql(t,_(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
143
176
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
144
177
|
latestOpinionatedReviews(first:100,after:$after) {
|
|
145
178
|
nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } }
|
|
146
179
|
pageInfo { hasNextPage endCursor }
|
|
147
180
|
}
|
|
148
181
|
} }
|
|
149
|
-
}`),{owner:a,repo:c,number:t.number,after:o.endCursor})).repository?.pullRequest?.latestOpinionatedReviews;if(!u?.pageInfo)return{nodes:n,complete:!1};n.push(...u.nodes),o=u.pageInfo}return{nodes:n,complete:!o.hasNextPage}}async normalize(r,t){const n=await this.reviewers(r,t),[o,i,a]=await Promise.all([this.threads(r,t),this.contexts(r,t),this.opinionatedReviews(r,t)]);return{forge:"github",iid:String(t.number),title:t.title,url:t.url,state:t.state==="OPEN"?"opened":t.state.toLowerCase(),draft:t.isDraft,conflicts:t.mergeable==="CONFLICTING",conflictsKnown:t.mergeable!=="UNKNOWN",approved:t.reviewDecision==="APPROVED",reviewDecision:t.reviewDecision??void 0,copilotReview:Fr({...t,reviewRequests:n}),awaitingReviewers:n.nodes.flatMap(c=>{const s=c.requestedReviewer;return s?.__typename==="Bot"?[]:s?.login?[s.login]:s?.name?[s.name]:[]}),reviewersComplete:!!n.pageInfo&&!n.pageInfo.hasNextPage,approvalsComplete:!!n.pageInfo&&!n.pageInfo.hasNextPage&&a.complete,reviewerIDs:[...new Set([...n.nodes.flatMap(c=>c.requestedReviewer?.__typename==="User"?c.requestedReviewer.id??[]:[]),...[...t.latestReviews?.nodes??[],...a.nodes].flatMap(c=>!c?.author?.__typename||c.author.__typename==="User"?c?.author?.id??[]:[])])],approvers:Gr(t,n,a.nodes),targetProject:t.baseRepository.nameWithOwner,targetBranch:t.baseRefName,...t.headRepository?{sourceProject:t.headRepository.nameWithOwner}:{},sourceBranch:t.headRefName,headSha:t.headRefOid,...t.author?.id?{authorID:t.author.id}:{},updatedAt:t.updatedAt,pipeline:i.nodes.length||!i.complete?Ur(i.nodes,i.complete,`${t.url}/checks`,t.headRefOid):void 0,unresolvedThreads:o.unresolved,threadsComplete:o.complete}}}const Wr={gitlab:F,github:ue},G=e=>Wr[e.forge],le=e=>G(e).reference(e.iid);function de(e){const r=G(e).automatedReview,t=r?.status(e);return r&&t?{name:r.name,...t}:void 0}const Je={url:{type:"string"},issueUrl:{type:"string"}},Ve={type:"object",properties:{...Je,targets:{type:"array",items:{type:"object",properties:Je,required:["url"],additionalProperties:!1}}},additionalProperties:!1},se={type:"string"},Ie={type:"object",title:"Snapshot"},z={type:"object",title:"InboxState"},zr={type:"object",properties:{enabled:{type:"boolean"},snapshot:Ie},required:["enabled","snapshot"],additionalProperties:!1},Kr={id:"opencode-forgekeeper",methods:{monitoringStatus:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:{type:"object",title:"MonitoringStatus"}},feedback:{input:{type:"object",additionalProperties:!1},output:z},acknowledgeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:z},markFeedbackRead:{input:{type:"object",properties:{ids:{type:"array",items:{type:"string"},maxItems:500}},required:["ids"],additionalProperties:!1},output:z},summarizeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:z},pauseFeedback:{input:{type:"object",properties:{paused:{type:"boolean"}},required:["paused"],additionalProperties:!1},output:z},actOnFeedback:{input:{type:"object",properties:{id:{type:"string"},retry:{type:"boolean"}},required:["id"],additionalProperties:!1},output:z},target:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:Ve},watch:{input:{type:"object",properties:{clientID:{type:"string"},keys:{type:"array",items:se},visible:se},required:["clientID","keys"],additionalProperties:!1},output:{type:"object",properties:{enabled:{type:"boolean"},statuses:{type:"object",additionalProperties:Ie}},required:["enabled","statuses"],additionalProperties:!1}},release:{input:{type:"object",properties:{clientID:{type:"string"}},required:["clientID"],additionalProperties:!1},output:{type:"object",additionalProperties:!1}},refresh:{input:{type:"object",properties:{key:se},required:["key"],additionalProperties:!1},output:zr}},events:{feedbackChanged:{schema:{type:"object",properties:{directory:{type:"string"}},required:["directory"],additionalProperties:!1}},targetChanged:{schema:{type:"object",properties:{sessionID:{type:"string"},...Ve.properties},required:["sessionID"],additionalProperties:!1}},status:{schema:{type:"object",properties:{directory:{type:"string"},key:se,snapshot:Ie},required:["directory","key","snapshot"],additionalProperties:!1}},notice:{schema:{type:"object",properties:{sessionID:{type:"string"},title:{type:"string"},message:{type:"string"},variant:{type:"string",enum:["info","error"]}},required:["message","variant"],additionalProperties:!1}}}},Qr="",pt=6e4,Ye=(e,r)=>e.directory===r.directory&&e.key===r.key,Z=e=>JSON.stringify([e.directory,e.key]);function Jr(e){const r=e.now??Date.now,t=e.setTimer??((m,C)=>setTimeout(m,C)),n=e.clearTimer??(m=>clearTimeout(m)),o=e.defer??queueMicrotask,i=new Map,a=new Map,c=new Map;let s,u=!1;const p=m=>a.get(m.directory)?.has(m.key)===!0;function h(m,C){const P=Z(m);(C.revision??-1)>=(i.get(P)?.revision??-1)&&i.set(P,C)}function d(m,C){const x={kind:"request",message:`PR/MR status service unavailable: ${C instanceof Error?C.message:String(C)}`,at:r()};for(const W of a.get(m)??[]){const j=Z({directory:m,key:W});i.set(j,{...i.get(j)??{},loading:!1,error:x})}e.onChange()}const w=new Map,v=new Map;function b(m){const C=(w.get(m)??0)+1;w.set(m,C);const P=v.get(m);P!==void 0&&n(P),v.set(m,t(()=>{S(m)},Math.min(pt,1e3*2**C)))}async function S(m){if(u)return;const C=v.get(m);C!==void 0&&n(C),v.delete(m);const P=[...a.get(m)??[]];try{const x=await e.watch(m,{clientID:e.clientID,keys:P,...s?.directory===m?{visible:s.key}:{}});if(u)return;w.delete(m),c.set(m,x.enabled);for(const[W,j]of Object.entries(x.statuses))p({directory:m,key:W})&&h({directory:m,key:W},j);e.onChange()}catch(x){if(u)return;d(m,x),b(m)}}const I=new Set;function T(m){I.has(m)||(I.add(m),o(()=>{I.delete(m),S(m)}))}return{snapshot:m=>i.get(Z(m))??{loading:!1},enabled:m=>c.get(m)??!0,show(m){if(m.key!==Qr)for(const[P,x]of a)P===m.directory||!x.delete(m.key)||(i.delete(Z({directory:P,key:m.key})),s&&Ye(s,{directory:P,key:m.key})&&(s=void 0),T(P));const C=a.get(m.directory)??new Set;a.set(m.directory,C),C.add(m.key),s=m,T(m.directory)},hide(m){s&&Ye(s,m)&&(s=void 0),T(m.directory)},async refresh(m){const C=Z(m);i.set(C,{...i.get(C)??{},loading:!0}),e.onChange();try{const P=await e.refresh(m.directory,m.key);if(u)return;c.set(m.directory,P.enabled),h(m,P.snapshot),e.onChange()}catch(P){if(u)return;d(m.directory,P)}},heartbeat(){for(const m of a.keys())S(m)},receive(m,C,P){p({directory:m,key:C})&&(h({directory:m,key:C},P),e.onChange())},hasShown:m=>[...a.values()].some(C=>C.has(m)),dispose(){u=!0;for(const m of v.values())n(m);for(const m of a.keys())e.release(m,e.clientID).catch(()=>{})}}}const ae=e=>({location:{directory:e}}),Vr=async(e,r)=>await e.feedback({},ae(r));function Yr(e){let r,t=0;const n=new Map;let o;return{get client(){return r?.client},connect(i){r?.dispose(),r=Zr(i,{...e,clientID:`${e.clientID}:${++t}`});for(const a of n.values())r.client.show(a),r.client.hide(a);o&&r.client.show(o),e.onChange()},show(i){n.set(i.key,i),o=i,r?.client.show(i)},hide(i){o?.key===i.key&&o.directory===i.directory&&(o=void 0),r?.client.hide(i)},dispose(){r?.dispose(),r=void 0}}}function Xr(e){const r=new Map;let t=0;const n=async o=>{const i=(r.get(o)??0)+1;r.set(o,i);const a=t,c=()=>a===t&&r.get(o)===i;try{const s=await e.load(o);c()&&e.changed(o,s)}catch(s){c()&&e.failed(o,s instanceof Error?s.message:String(s))}};return{reload:n,has:o=>r.has(o),refresh:()=>Promise.all([...r.keys()].map(n)),invalidate(){t++}}}function Zr(e,r){const t=e,n=Jr({clientID:r.clientID,watch:async(a,c)=>await t.watch(c,ae(a)),refresh:async(a,c)=>await t.refresh({key:c},ae(a)),release:(a,c)=>t.release({clientID:c},ae(a)),onChange:r.onChange}),o=setInterval(()=>{n.heartbeat(),r.heartbeat?.()},pt),i=e.events.on("status",a=>{const{directory:c,key:s,snapshot:u}=a.data;n.receive(c,s,u)});return{client:n,dispose(){clearInterval(o),i(),n.dispose()}}}const en=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,me=e=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),tn=e=>e.kind==="review-request",rn=e=>e.kind==="approval";function nn(e){return e.canAct!==void 0?e.canAct:e.humanApprovalOnly?!1:rn(e)?e.approverKind!=="human"&&!!e.automationAllowed:!(e.kind&&e.kind!=="ci-failed")}const on=e=>tn(e)?`Requested: ${me(e.postedAt??e.at)}`:e.postedAt!==void 0?`Latest comment: ${me(e.postedAt)}`:`Detected: ${me(e.at)}`,ft=(e,r)=>r?e.items.filter(t=>t.sessionID===r):[];function sn(e,r){const t=ft(e,r).filter(n=>!n.read).length;if(t!==0)return`${t} review update${t===1?"":"s"}${e.paused?" (paused)":""}`}function an(e){return[...new Set([e.url,...e.links])].filter(r=>{try{const t=new URL(r);return t.protocol==="https:"&&t.origin===new URL(e.url).origin&&!t.username&&!t.password}catch{return!1}})}function cn(e){const r=an(e),t=r.filter(o=>o!==e.url),n=e.kind==="ci-failed";return[...t.map((o,i)=>({title:`${n?"Failed job":"Comment"} ${t.length>1?`${i+1} of ${t.length} `:""}(${n?new URL(o).pathname.split("/").filter(Boolean).slice(-2).join("/"):new URL(o).hash||"no anchor"})`,description:o,value:o})),...r.includes(e.url)?[{title:"PR/MR overview",description:e.url,value:e.url}]:[]]}const un=new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SCHEDULED","WAITING_FOR_CALLBACK","CANCELING"]);function Ne(e){return e?e.status==="FAILED"?"error":e.status==="SUCCESS"?e.label.includes("warning")?"warning":"success":un.has(e.status)?"warning":"muted":"muted"}const ht=(e,r)=>`${e} ${r}${e===1?"":"s"}`,ln=e=>e.charAt(0).toUpperCase()+e.slice(1),dn={success:"CI ✓",error:"CI ✗",warning:"CI …"};function pn(e){return e.length>2?`awaiting ${e.length} reviewers`:`awaiting ${e.map(r=>`@${r}`).join(", ")}`}function fn(e){return`${e.unresolvedThreads}${e.threadsComplete?"":"+"} unresolved thread${e.unresolvedThreads===1&&e.threadsComplete?"":"s"}`}const ge=e=>({text:le(e),tone:"muted",url:e.url,essential:!0});function hn(e){const r=Ne(e.pipeline);return e.pipeline?{text:`CI ${e.pipeline.label}`,compact:dn[r],tone:r,url:e.pipeline.url}:{text:`no ${G(e).ci}`,compact:"no CI",tone:r}}function mn(e){const r=new Set(e.map(d=>G(d).noun)),t=r.size===1?[...r][0]:"PR/MR",n=e.length===1?`1 ${t}`:`${e.length} ${t==="PR/MR"?"PRs/MRs":`${t}s`}`,o=e.filter(d=>d.state==="opened"),i=[{text:n,tone:"muted",essential:!0}],a=o.filter(d=>de(d)?.state==="running").length;a&&i.push({text:`🤖 ${a} reviewing`,compact:`🤖 ${a}`,tone:"warning",essential:!0});const c=o.filter(d=>Ne(d.pipeline)==="error").length;c&&i.push({text:`${c} CI failed`,compact:`CI ✗ ${c}`,tone:"error"});const s=o.filter(d=>d.conflicts).length;s&&i.push({text:ht(s,"conflict"),tone:"error",essential:!0});const u=o.filter(d=>d.approved&&d.awaitingReviewers.length===0).length;u&&i.push({text:`${u} approved`,tone:"success"});const p=e.filter(d=>d.state==="merged").length;p&&i.push({text:`${p} merged`,tone:"success"});const h=e.length-o.length-p;return h&&i.push({text:`${h} closed`,tone:"muted"}),i}function gn(e){const{lookup:r,error:t}=e,n=t?[{text:"stale",tone:"warning",essential:!0}]:[];if(!r||r.kind==="none"||r.requests.length===0)return e.targeted&&(t||r?.explicitTarget)?[{text:"PR/MR status unavailable",tone:"warning"}]:[];r.failed?.length&&n.unshift({text:`${r.failed.length} unavailable`,tone:"warning",essential:!0});const o=r.requests;if(r.explicitTarget&&o.length>1)return[...mn(o),...n];if(o.length>1){const c=G(o[0]).noun;return[...o.map(ge),{text:`${ht(o.length,`open ${c}`)}, run /${c.toLowerCase()}-status`,tone:"warning"},...n]}const[i]=o;if(i.state!=="opened")return[ge(i),{text:i.state,tone:i.state==="merged"?"success":"muted",essential:!0},...n];const a=[ge(i),hn(i)];if(i.unresolvedThreads>0||!i.threadsComplete){const c=fn(i);a.push({text:c,compact:c.replace("unresolved ",""),tone:"warning"})}return de(i)?.state==="running"&&a.push({text:"🤖 reviewing",compact:"🤖",tone:"warning",essential:!0}),a.push(...G(i).indicators(i)),i.conflicts&&a.push({text:"conflicts",tone:"error",essential:!0}),i.conflictsKnown||a.push({text:"mergeability unknown",tone:"muted"}),i.awaitingReviewers.length?a.push({text:pn(i.awaitingReviewers),tone:"muted"}):i.approved&&a.push({text:"approved",tone:"success"}),[...a,...n]}const Xe=e=>new Date(e).toLocaleTimeString();function wn(e,r){const t=G(e),n=[`${le(e)} ${e.title}${e.state==="opened"?"":` (${e.state})`}`,`Target: ${e.targetProject} → ${e.targetBranch}`,`${ln(t.ci)}: ${e.pipeline?e.pipeline.label:"none"}${e.pipeline?.url?` (${e.pipeline.url})`:""}`,`Unresolved threads: ${e.unresolvedThreads}${e.threadsComplete?"":"+"}`,`Draft: ${Q(e.draft)} · Conflicts: ${e.conflictsKnown?Q(e.conflicts):"unknown"}`,...t.details(e)],o=de(e);return o&&n.push(`${o.name} review: ${o.label}`),e.awaitingReviewers.length&&n.push(`Awaiting review: ${e.awaitingReviewers.map(i=>`@${i}`).join(", ")}`),e.reviewersComplete||n.push("Reviewer list is partial"),r&&e.headSha&&r!==e.headSha&&n.push(`Local HEAD differs from the ${t.noun} head commit (unpushed or not fetched)`),n.push(e.url),n}function vn(e){const{lookup:r,error:t,fetchedAt:n}=e,o=[];if(!r)o.push(t?"Could not look up the PR/MR.":"No data yet.");else if(r.kind==="none")o.push(`No PR/MR lookup: ${r.reason}.`);else{const{repository:i,sessionTarget:a,requests:c}=r;if(i){const s=i.branch===i.sourceBranch?i.branch:`${i.branch} (pushes to ${i.sourceBranch})`;o.push(`Branch: ${s} in ${i.source.path}`),c.length===0&&o.push("","No open PR/MR for this branch.")}else a&&o.push(`Session target: ${a}`);for(const{url:s,reason:u}of r.failed??[])o.push(`Unavailable: ${s} (${u})`);for(const s of c)o.push("",...wn(s,i?.head??""))}return t&&o.push("",`Last refresh failed at ${Xe(t.at)}: ${t.message}`),n!==void 0&&o.push("",`Last fetched: ${Xe(n)}`),o.join(`
|
|
150
|
-
`)}function
|
|
182
|
+
}`),{owner:i,repo:l,number:r.number,after:n.endCursor})).repository?.pullRequest?.latestOpinionatedReviews;if(!c?.pageInfo)return{nodes:s,complete:!1};s.push(...c.nodes),n=c.pageInfo}return{nodes:s,complete:!n.hasNextPage}}async normalize(t,r){const s=await this.reviewers(t,r),[n,a,i]=await Promise.all([this.threads(t,r),this.contexts(t,r),this.opinionatedReviews(t,r)]);return{forge:"github",iid:String(r.number),title:r.title,url:r.url,state:r.state==="OPEN"?"opened":r.state.toLowerCase(),draft:r.isDraft,conflicts:r.mergeable==="CONFLICTING",conflictsKnown:r.mergeable!=="UNKNOWN",approved:r.reviewDecision==="APPROVED",reviewDecision:r.reviewDecision??void 0,...En(s,i),copilotReview:In({...r,reviewRequests:s}),awaitingReviewers:s.nodes.flatMap(l=>{const o=l.requestedReviewer;return o?.__typename==="Bot"?[]:o?.login?[o.login]:o?.name?[o.name]:[]}),reviewersComplete:!!s.pageInfo&&!s.pageInfo.hasNextPage,approvalsComplete:!!s.pageInfo&&!s.pageInfo.hasNextPage&&i.complete,reviewerIDs:[...new Set([...s.nodes.flatMap(l=>l.requestedReviewer?.__typename==="User"?l.requestedReviewer.id??[]:[]),...[...r.latestReviews?.nodes??[],...i.nodes].flatMap(l=>!l?.author?.__typename||l.author.__typename==="User"?l?.author?.id??[]:[])])],approvers:kn(r,s,i.nodes),targetProject:r.baseRepository.nameWithOwner,targetBranch:r.baseRefName,...r.headRepository?{sourceProject:r.headRepository.nameWithOwner}:{},sourceBranch:r.headRefName,headSha:r.headRefOid,...r.author?.id?{authorID:r.author.id}:{},updatedAt:r.updatedAt,pipeline:a.nodes.length||!a.complete?Sn(a.nodes,a.complete,`${r.url}/checks`,r.headRefOid):void 0,unresolvedThreads:n.unresolved,threadsComplete:n.complete}}}const Pn={gitlab:ee,github:$e},Z=e=>Pn[e.forge],ye=e=>Z(e).reference(e.iid);function Re(e){const t=Z(e).automatedReview,r=t?.status(e);return t&&r?{name:t.name,...r}:void 0}const ft={url:{type:"string"},issueUrl:{type:"string"}},ht={type:"object",properties:{...ft,targets:{type:"array",items:{type:"object",properties:ft,required:["url"],additionalProperties:!1}}},additionalProperties:!1},me={type:"string"},Ue={type:"object",title:"Snapshot"},ne={type:"object",title:"InboxState"},An={type:"object",properties:{enabled:{type:"boolean"},snapshot:Ue},required:["enabled","snapshot"],additionalProperties:!1},Dn={id:"opencode-forgekeeper",methods:{monitoringStatus:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:{type:"object",title:"MonitoringStatus"}},feedback:{input:{type:"object",additionalProperties:!1},output:ne},acknowledgeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:ne},markFeedbackRead:{input:{type:"object",properties:{ids:{type:"array",items:{type:"string"},maxItems:500}},required:["ids"],additionalProperties:!1},output:ne},summarizeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:ne},pauseFeedback:{input:{type:"object",properties:{paused:{type:"boolean"}},required:["paused"],additionalProperties:!1},output:ne},actOnFeedback:{input:{type:"object",properties:{id:{type:"string"},retry:{type:"boolean"}},required:["id"],additionalProperties:!1},output:ne},target:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:ht},watch:{input:{type:"object",properties:{clientID:{type:"string"},keys:{type:"array",items:me},visible:me},required:["clientID","keys"],additionalProperties:!1},output:{type:"object",properties:{enabled:{type:"boolean"},statuses:{type:"object",additionalProperties:Ue}},required:["enabled","statuses"],additionalProperties:!1}},release:{input:{type:"object",properties:{clientID:{type:"string"}},required:["clientID"],additionalProperties:!1},output:{type:"object",additionalProperties:!1}},refresh:{input:{type:"object",properties:{key:me},required:["key"],additionalProperties:!1},output:An},cleanupCandidates:{input:{type:"object",properties:{scanID:{type:"string"}},additionalProperties:!1},output:{type:"object",title:"CleanupScanResult"}},cleanupSessions:{input:{type:"object",properties:{scanID:{type:"string"},allowClientArchive:{type:"boolean"},finalizeArchived:{type:"boolean"},sessionIDs:{type:"array",items:{type:"string"},minItems:1,maxItems:500}},required:["sessionIDs"],additionalProperties:!1},output:{type:"object",title:"CleanupResult"}}},events:{cleanupProgress:{schema:{type:"object",properties:{scanID:{type:"string"},phase:{type:"string",enum:["sessions","targets","verifying","archiving"]},checked:{type:"number"},total:{type:"number"}},required:["phase","checked","total"],additionalProperties:!1}},sessionsCleanedUp:{schema:{type:"object",properties:{sessionIDs:{type:"array",items:{type:"string"}},archive:{type:"boolean"}},required:["sessionIDs"],additionalProperties:!1}},feedbackChanged:{schema:{type:"object",properties:{directory:{type:"string"}},required:["directory"],additionalProperties:!1}},targetChanged:{schema:{type:"object",properties:{sessionID:{type:"string"},...ht.properties},required:["sessionID"],additionalProperties:!1}},status:{schema:{type:"object",properties:{directory:{type:"string"},key:me,snapshot:Ue},required:["directory","key","snapshot"],additionalProperties:!1}},notice:{schema:{type:"object",properties:{sessionID:{type:"string"},title:{type:"string"},message:{type:"string"},variant:{type:"string",enum:["info","error"]},openTab:{type:"boolean"}},required:["message","variant"],additionalProperties:!1}}}},Nn="",xt=6e4,gt=(e,t)=>e.directory===t.directory&&e.key===t.key,ue=e=>JSON.stringify([e.directory,e.key]);function qn(e){const t=e.now??Date.now,r=e.setTimer??((m,k)=>setTimeout(m,k)),s=e.clearTimer??(m=>clearTimeout(m)),n=e.defer??queueMicrotask,a=new Map,i=new Map,l=new Map;let o,c=!1;const d=m=>i.get(m.directory)?.has(m.key)===!0;function h(m,k){const x=ue(m);(k.revision??-1)>=(a.get(x)?.revision??-1)&&a.set(x,k)}function p(m,k){const F={kind:"request",message:`PR/MR status service unavailable: ${k instanceof Error?k.message:String(k)}`,at:t()};for(const Y of i.get(m)??[]){const te=ue({directory:m,key:Y});a.set(te,{...a.get(te)??{},loading:!1,error:F})}e.onChange()}const w=new Map,$=new Map;function b(m){const k=(w.get(m)??0)+1;w.set(m,k);const x=$.get(m);x!==void 0&&s(x),$.set(m,r(()=>{y(m)},Math.min(xt,1e3*2**k)))}async function y(m){if(c)return;const k=$.get(m);k!==void 0&&s(k),$.delete(m);const x=[...i.get(m)??[]];try{const F=await e.watch(m,{clientID:e.clientID,keys:x,...o?.directory===m?{visible:o.key}:{}});if(c)return;w.delete(m),l.set(m,F.enabled);for(const[Y,te]of Object.entries(F.statuses))d({directory:m,key:Y})&&h({directory:m,key:Y},te);e.onChange()}catch(F){if(c)return;p(m,F),b(m)}}const D=new Set;function j(m){D.has(m)||(D.add(m),n(()=>{D.delete(m),y(m)}))}return{snapshot:m=>a.get(ue(m))??{loading:!1},enabled:m=>l.get(m)??!0,show(m){if(m.key!==Nn)for(const[x,F]of i)x===m.directory||!F.delete(m.key)||(a.delete(ue({directory:x,key:m.key})),o&>(o,{directory:x,key:m.key})&&(o=void 0),j(x));const k=i.get(m.directory)??new Set;i.set(m.directory,k),k.add(m.key),o=m,j(m.directory)},hide(m){o&>(o,m)&&(o=void 0),j(m.directory)},async refresh(m){const k=ue(m);a.set(k,{...a.get(k)??{},loading:!0}),e.onChange();try{const x=await e.refresh(m.directory,m.key);if(c)return;l.set(m.directory,x.enabled),h(m,x.snapshot),e.onChange()}catch(x){if(c)return;p(m.directory,x)}},heartbeat(){for(const m of i.keys())y(m)},receive(m,k,x){d({directory:m,key:k})&&(h({directory:m,key:k},x),e.onChange())},hasShown:m=>[...i.values()].some(k=>k.has(m)),dispose(){c=!0;for(const m of $.values())s(m);for(const m of i.keys())e.release(m,e.clientID).catch(()=>{})}}}const ve=e=>({location:{directory:e}}),xn=async(e,t)=>await e.feedback({},ve(t));function Tn(e){let t,r=0;const s=new Map;let n;return{get client(){return t?.client},connect(a){t?.dispose(),t=jn(a,{...e,clientID:`${e.clientID}:${++r}`});for(const i of s.values())t.client.show(i),t.client.hide(i);n&&t.client.show(n),e.onChange()},show(a){s.set(a.key,a),n=a,t?.client.show(a)},hide(a){n?.key===a.key&&n.directory===a.directory&&(n=void 0),t?.client.hide(a)},dispose(){t?.dispose(),t=void 0}}}function Mn(e){const t=new Map;let r=0;const s=async n=>{const a=(t.get(n)??0)+1;t.set(n,a);const i=r,l=()=>i===r&&t.get(n)===a;try{const o=await e.load(n);l()&&e.changed(n,o)}catch(o){l()&&e.failed(n,o instanceof Error?o.message:String(o))}};return{reload:s,has:n=>t.has(n),refresh:()=>Promise.all([...t.keys()].map(s)),invalidate(){r++}}}function jn(e,t){const r=e,s=qn({clientID:t.clientID,watch:async(i,l)=>await r.watch(l,ve(i)),refresh:async(i,l)=>await r.refresh({key:l},ve(i)),release:(i,l)=>r.release({clientID:l},ve(i)),onChange:t.onChange}),n=setInterval(()=>{s.heartbeat(),t.heartbeat?.()},xt),a=e.events.on("status",i=>{const{directory:l,key:o,snapshot:c}=i.data;s.receive(l,o,c)});return{client:s,dispose(){clearInterval(n),a(),s.dispose()}}}const Ln=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,Pe=e=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),On=e=>e.kind==="review-request",Un=e=>e.kind==="approval";function Bn(e){return e.canAct!==void 0?e.canAct:e.humanApprovalOnly?!1:Un(e)?e.approverKind!=="human"&&!!e.automationAllowed:!(e.kind&&e.kind!=="ci-failed")}const Fn=e=>On(e)?`Requested: ${Pe(e.postedAt??e.at)}`:e.postedAt!==void 0?`Latest comment: ${Pe(e.postedAt)}`:`Detected: ${Pe(e.at)}`,Tt=(e,t)=>t?e.items.filter(r=>r.sessionID===t):[];function Gn(e,t){const r=Tt(e,t).filter(s=>!s.read).length;if(r!==0)return`📥 ${r}${e.paused?" (paused)":""}`}function zn(e){return[...new Set([e.url,...e.links])].filter(t=>{try{const r=new URL(t);return r.protocol==="https:"&&r.origin===new URL(e.url).origin&&!r.username&&!r.password}catch{return!1}})}function Hn(e){const t=zn(e),r=t.filter(n=>n!==e.url),s=e.kind==="ci-failed";return[...r.map((n,a)=>({title:e.kind==="issue-outdated"?"Issue":`${s?"Failed job":"Comment"} ${r.length>1?`${a+1} of ${r.length} `:""}(${s?new URL(n).pathname.split("/").filter(Boolean).slice(-2).join("/"):new URL(n).hash||"no anchor"})`,description:n,value:n})),...t.includes(e.url)?[{title:"PR/MR overview",description:e.url,value:e.url}]:[]]}const Wn=new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SCHEDULED","WAITING_FOR_CALLBACK","CANCELING"]);function Ve(e){return e?e.status==="FAILED"?"error":e.status==="SUCCESS"?e.label.includes("warning")?"warning":"success":Wn.has(e.status)?"warning":"muted":"muted"}const Mt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Qn=e=>e.charAt(0).toUpperCase()+e.slice(1),Vn={success:"CI ✓",error:"CI ✗",warning:"CI …"};function Kn(e){return`${e.unresolvedThreads}${e.threadsComplete?"":"+"} unresolved thread${e.unresolvedThreads===1&&e.threadsComplete?"":"s"}`}const Ae=e=>({text:ye(e),tone:"muted",url:e.url,essential:!0});function Jn(e){const t=Ve(e.pipeline);return e.pipeline?{text:`CI ${e.pipeline.label}`,compact:Vn[t],tone:t,url:e.pipeline.url}:{text:`no ${Z(e).ci}`,compact:"no CI",tone:t}}function Yn(e){const t=new Set(e.map(p=>Z(p).noun)),r=t.size===1?[...t][0]:"PR/MR",s=e.length===1?`1 ${r}`:`${e.length} ${r==="PR/MR"?"PRs/MRs":`${r}s`}`,n=e.filter(p=>p.state==="opened"),a=[{text:s,tone:"muted",essential:!0}],i=n.filter(p=>Re(p)?.state==="running").length;i&&a.push({text:`🤖 ${i} reviewing`,compact:`🤖 ${i}`,tone:"warning",essential:!0});const l=n.filter(p=>Ve(p.pipeline)==="error").length;l&&a.push({text:`${l} CI failed`,compact:`CI ✗ ${l}`,tone:"error"});const o=n.filter(p=>p.conflicts).length;o&&a.push({text:Mt(o,"conflict"),tone:"error",essential:!0});const c=n.filter(p=>p.approved&&p.awaitingReviewers.length===0).length;c&&a.push({text:`${c} approved`,tone:"success"});const d=e.filter(p=>p.state==="merged").length;d&&a.push({text:`${d} merged`,tone:"success"});const h=e.length-n.length-d;return h&&a.push({text:`${h} closed`,tone:"muted"}),a}function Xn(e){const{lookup:t,error:r}=e,s=r?[{text:"stale",tone:"warning",essential:!0}]:[];if(!t||t.kind==="none"||t.requests.length===0)return e.targeted&&(r||t?.explicitTarget)?[{text:"PR/MR status unavailable",tone:"warning"}]:[];t.failed?.length&&s.unshift({text:`${t.failed.length} unavailable`,tone:"warning",essential:!0});const n=t.requests;if(t.explicitTarget&&n.length>1)return[...Yn(n),...s];if(n.length>1){const o=Z(n[0]).noun;return[...n.map(Ae),{text:`${Mt(n.length,`open ${o}`)}, run /${o.toLowerCase()}-status`,tone:"warning"},...s]}const[a]=n;if(a.state!=="opened")return[Ae(a),{text:a.state,tone:a.state==="merged"?"success":"muted",essential:!0},...s];const i=[Ae(a),Jn(a)];if(a.unresolvedThreads>0||!a.threadsComplete){const o=Kn(a);i.push({text:o,compact:o.replace("unresolved ",""),tone:"warning"})}Re(a)?.state==="running"&&i.push({text:"🤖 reviewing",compact:"🤖",tone:"warning",essential:!0}),i.push(...Z(a).indicators(a)),a.conflicts&&i.push({text:"conflicts",tone:"error",essential:!0}),a.conflictsKnown||i.push({text:"mergeability unknown",tone:"muted"});const l=Z(a).reviewIndicators;return l?i.push(...l(a)):a.awaitingReviewers.length?i.push({text:Rt(a.awaitingReviewers),tone:"muted"}):a.approved&&i.push({text:"approved",tone:"success"}),[...i,...s]}const mt=e=>new Date(e).toLocaleTimeString();function Zn(e,t){const r=Z(e),s=[`${ye(e)} ${e.title}${e.state==="opened"?"":` (${e.state})`}`,`Target: ${e.targetProject} → ${e.targetBranch}`,`${Qn(r.ci)}: ${e.pipeline?e.pipeline.label:"none"}${e.pipeline?.url?` (${e.pipeline.url})`:""}`,`Unresolved threads: ${e.unresolvedThreads}${e.threadsComplete?"":"+"}`,`Draft: ${oe(e.draft)} · Conflicts: ${e.conflictsKnown?oe(e.conflicts):"unknown"}`,...r.details(e)],n=Re(e);return n&&s.push(`${n.name} review: ${n.label}`),e.awaitingReviewers.length&&s.push(`Awaiting review: ${e.awaitingReviewers.map(a=>`@${a}`).join(", ")}`),e.reviewersComplete||s.push("Reviewer list is partial"),t&&e.headSha&&t!==e.headSha&&s.push(`Local HEAD differs from the ${r.noun} head commit (unpushed or not fetched)`),s.push(e.url),s}function es(e){const{lookup:t,error:r,fetchedAt:s}=e,n=[];if(!t)n.push(r?"Could not look up the PR/MR.":"No data yet.");else if(t.kind==="none")n.push(`No PR/MR lookup: ${t.reason}.`);else{const{repository:a,sessionTarget:i,requests:l}=t;if(a){const o=a.branch===a.sourceBranch?a.branch:`${a.branch} (pushes to ${a.sourceBranch})`;n.push(`Branch: ${o} in ${a.source.path}`),l.length===0&&n.push("","No open PR/MR for this branch.")}else i&&n.push(`Session target: ${i}`);for(const{url:o,reason:c}of t.failed??[])n.push(`Unavailable: ${o} (${c})`);for(const o of l)n.push("",...Zn(o,a?.head??""))}return r&&n.push("",`Last refresh failed at ${mt(r.at)}: ${r.message}`),s!==void 0&&n.push("",`Last fetched: ${mt(s)}`),n.join(`
|
|
183
|
+
`)}async function ts(e,t,r){const s=new Array(e.length);let n=0;const a=async()=>{for(;n<e.length;){const i=n++;s[i]=await r(e[i])}};return await Promise.all(Array.from({length:Math.min(t,e.length)},a)),s}function rs(e){const t=e.lookup;return t?.kind==="found"&&t.explicitTarget===!0&&t.requests.length>0&&!t.failed?.length&&t.requests.every(r=>r.state==="merged")}function Be(e){if(e.lookup?.cleanupReady)return e.lookup.cleanupReady;if(!(!rs(e)||e.lookup?.kind!=="found"))return{kind:"merged-requests",reason:e.lookup.requests.length===1?"PR/MR merged":"All PRs/MRs merged"}}function ns(e){const t=e.targets.map(n=>n.reference).join(", "),r=e.reason==="merged-requests"?"merged":"closed",s=t?`${t} ${r}`:r;return e.pendingFeedback<=0?s:`${s} · ${e.pendingFeedback} review update${e.pendingFeedback===1?"":"s"}`}function ss(e){const r=e.replace(/\/+$/,"").split("/").filter(Boolean);return r[r.length-1]??e}function wt(e,t="scan"){if(!e)return t==="cleanup"?"Verifying and archiving sessions…":"Checking sessions for merged PRs/MRs and closed issues…";const r=e.total>0?` (${e.checked}/${e.total})`:"";switch(e.phase){case"sessions":return`Scanning project sessions…${e.checked>0?` (${e.checked} found)`:""}`;case"targets":return`Checking PRs/MRs and tracked issues…${r}`;case"verifying":return`Verifying target status before archiving…${r}`;case"archiving":return`Archiving sessions…${r}`}}function os(e){const t=new Map;for(const r of e)t.set(r.reason,(t.get(r.reason)??0)+1);return[...t.entries()].map(([r,s])=>s===1?r:`${r} (${s} sessions)`).join("; ")}function is(e,t,r){const s=Xn(e),n=Be(e),a=!s.length&&n?.kind==="closed-issues";if(!s.length&&!t&&!a)return;const i=s.findIndex(d=>!d.essential||!d.url),l=i<0?s.length:Math.max(1,i),o=e.lookup?.kind==="found"&&e.lookup.requests.length===1?e.lookup.requests[0].awaitingReviewers:void 0,c=[...s.map(d=>d.tone),...a?["success"]:[]];return{icon:"review",label:[...s.map((d,h)=>({segment:d,priority:h<l?-1:as(d)})).sort((d,h)=>d.priority-h.priority).map(({segment:d})=>ls(d,o)),...a?[`✓ ${n.reason}`]:[],t?.replace(/^(\d+) review updates?/,"📥 $1")].filter(Boolean).join(" · "),tone:cs(c),title:"PR/MR status",rows:[...s.map((d,h)=>({id:`segment-${h}`,label:d.text.startsWith("awaiting ")&&o?.length?`awaiting ${o.map(p=>`@${p}`).join(", ")}`:d.text,...d.url?{icon:"outline-arrow-up-right"}:{},...d.tone==="success"||d.tone==="warning"?{tone:d.tone}:d.tone==="error"?{tone:"danger"}:{},...d.url?{run:()=>r.external(d.url)}:{}})),{id:"details",label:"Show PR/MR status",icon:"status",run:r.status},...t?[{id:"feedback",label:t,icon:"comment",run:r.feedback}]:[],...n&&r.cleanup?[{id:"cleanup",label:`${n.reason} · /forge-cleanup`,icon:"archive",tone:"success",run:r.cleanup}]:[]]}}function as(e){return e.text==="mergeability unknown"?4:e.tone==="error"?0:/unresolved threads?$/.test(e.text)?1:e.tone==="warning"?2:3}function ls(e,t){const r=e.text.match(/^(\d+\+?) unresolved threads?$/);return r?`💬 ${r[1]}`:e.text.startsWith("awaiting ")&&t?.length?`◷ @${t[0]}${t.length>1?` +${t.length-1}`:""}`:e.text==="approved"?"✓ approved":e.compact?.startsWith("CI ")?e.compact.replace(/^CI ([✓✗…])/,"$1 CI"):e.compact??e.text}function cs(e){if(e.includes("error"))return"danger";if(e.includes("warning"))return"warning";if(e.includes("success"))return"success"}function us(e,t){const{sessionID:r}=e;r&&!t.hasShown(r)||(r&&e.variant==="info"&&e.openTab!==!1&&t.openTab(r),t.toast({...e.title?{title:e.title}:{},message:e.message,variant:e.variant}))}var ds=u.template("<a><b>"),ps=u.template("<div><span class=fk-label>: "),fs=u.template("<b>"),hs=u.template("<div class=fk-warning>Reviewer list is partial"),gs=u.template("<div class=fk-warning>Local HEAD differs from the <!> head commit (unpushed or not fetched)"),ms=u.template("<div class=fk-card><a><b> </b></a><section></section><section><b>Review and approval"),De=u.template("<div>"),ws=u.template("<div class=forgekeeper-panel><header><h2>PR/MR status</h2><div class=fk-actions>"),vs=u.template("<div>PR/MR status is off."),bs=u.template("<div class=fk-success><b>✓ </b> — ready to archive with /forge-cleanup."),$s=u.template("<div class=fk-muted>No PR/MR status available."),ys=u.template("<div class=fk-muted>Last fetched: "),Rs=u.template("<section>"),Ss=u.template('<div class="fk-warning fk-pre"><b>Unavailable'),Cs=u.template('<div class="fk-error fk-pre"><b>Last refresh failed at '),Is=u.template("<div class=fk-card><b></b><div class=fk-muted></div><section></section><div class=fk-actions>"),ks=u.template("<a>"),Es=u.template("<div class=forgekeeper-panel><header><h2>Review updates"),_s=u.template("<div class=fk-error>Could not load review updates: <!>. Retrying automatically."),Ne=u.template("<div class=fk-muted>"),Ps=u.template("<div class=fk-cleanup-row><div class=fk-cleanup-main><div class=fk-cleanup-title></div><div class=fk-cleanup-meta>"),As=u.template("<div class=fk-warning>"),Ds=u.template("<div class=fk-cleanup-list>"),Ns=u.template("<div class=fk-cleanup-dialog>"),qs=u.template("<div class=fk-cleanup-footer>"),xs=u.template("<div class=fk-error>"),Ts=u.template("<div class=fk-cleanup-group>");const Ms=`
|
|
151
184
|
.forgekeeper-panel { display: flex; flex-direction: column; gap: 12px; padding: 12px 16px; overflow-y: auto; height: 100%; font-size: 13px; line-height: 1.5; color: var(--v2-text-text-base); }
|
|
152
185
|
.forgekeeper-panel header { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
|
153
186
|
.forgekeeper-panel h2 { font-size: 13px; font-weight: 600; margin: 0; }
|
|
154
187
|
.forgekeeper-panel section { display: flex; flex-direction: column; gap: 2px; }
|
|
155
188
|
.forgekeeper-panel .fk-card { border: 1px solid var(--v2-border-border-muted); border-radius: 8px; padding: 8px 10px; display: flex; flex-direction: column; gap: 6px; }
|
|
156
189
|
.forgekeeper-panel .fk-actions { display: flex; flex-wrap: wrap; gap: 6px; }
|
|
157
|
-
.forgekeeper-panel .fk-muted { color: var(--v2-text-text-muted); }
|
|
158
|
-
.forgekeeper-panel .fk-label { color: var(--v2-text-text-muted); }
|
|
159
|
-
.forgekeeper-panel .fk-success { color: var(--v2-state-fg-success); }
|
|
160
|
-
.forgekeeper-panel .fk-warning { color: var(--v2-state-fg-warning); }
|
|
161
|
-
.forgekeeper-panel .fk-error { color: var(--v2-state-fg-danger); }
|
|
190
|
+
.forgekeeper-panel .fk-muted, .fk-cleanup-dialog .fk-muted { color: var(--v2-text-text-muted); }
|
|
191
|
+
.forgekeeper-panel .fk-label, .fk-cleanup-dialog .fk-label { color: var(--v2-text-text-muted); }
|
|
192
|
+
.forgekeeper-panel .fk-success, .fk-cleanup-dialog .fk-success { color: var(--v2-state-fg-success); }
|
|
193
|
+
.forgekeeper-panel .fk-warning, .fk-cleanup-dialog .fk-warning { color: var(--v2-state-fg-warning); }
|
|
194
|
+
.forgekeeper-panel .fk-error, .fk-cleanup-dialog .fk-error { color: var(--v2-state-fg-danger); }
|
|
162
195
|
.forgekeeper-panel a { color: var(--v2-text-text-accent); cursor: pointer; text-decoration: underline; }
|
|
163
196
|
.forgekeeper-panel .fk-pre { white-space: pre-wrap; }
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
197
|
+
.fk-cleanup-dialog { display: flex; flex-direction: column; gap: 10px; font-size: 13px; color: var(--v2-text-text-base); }
|
|
198
|
+
.fk-cleanup-list { display: flex; flex-direction: column; gap: 2px; max-height: 360px; overflow-y: auto; }
|
|
199
|
+
.fk-cleanup-group { font-size: 11px; font-weight: 600; color: var(--v2-text-text-muted); padding: 6px 4px 2px; }
|
|
200
|
+
.fk-cleanup-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 6px 4px; border-top: 1px solid var(--v2-border-border-muted); }
|
|
201
|
+
.fk-cleanup-row:first-child { border-top: none; }
|
|
202
|
+
.fk-cleanup-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; }
|
|
203
|
+
.fk-cleanup-title { cursor: pointer; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
204
|
+
.fk-cleanup-title:hover { text-decoration: underline; }
|
|
205
|
+
.fk-cleanup-meta { font-size: 12px; color: var(--v2-text-text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
206
|
+
.fk-cleanup-footer { display: flex; align-items: center; gap: 8px; }
|
|
207
|
+
`,de="status",pe="feedback",js={items:[],paused:!1};let Ls=0;const vt=()=>`gui-cleanup-${Date.now()}-${++Ls}`;function bt(e){switch(e){case"success":return"fk-success";case"warning":return"fk-warning";case"error":return"fk-error";case"muted":return"fk-muted";default:return}}const Os=V.Plugin.define({setup(e){e.add(V.Style,Ms);const t=()=>e.client.rpc(Dn),r=f=>({location:{directory:f}}),[s,n]=S.createSignal(0),[a,i]=Ze.createStore({}),[l,o]=Ze.createStore({}),c=Mn({load:f=>xn(t(),f),changed:(f,g)=>{i(f,g),o(f,void 0)},failed:(f,g)=>o(f,g)}),d=c.reload,h=Tn({clientID:Ln(),onChange:()=>n(f=>f+1),heartbeat:()=>{c.refresh()}}),p=()=>h.client,w=f=>f.server.builtin,$=f=>f.location?.directory??f.directory,b=f=>({directory:$(f),key:f.id}),y=f=>(s(),p()?.snapshot(f)??{loading:!1}),D=f=>(s(),p()?.enabled(f)??!0),j=f=>a[f]??js,m=f=>{const g=y(f).lookup;return g?.kind==="found"?g.requests:[]},k=()=>{const f=e.sessions.current();return f&&w(f)?f:void 0};V.createKeyed(()=>{const f=k();return f?JSON.stringify([$(f),f.id]):void 0},f=>{const[g,v]=JSON.parse(f),C={directory:g,key:v};h.show(C),d(g),S.onCleanup(()=>h.hide(C))});const x=(f,g=k())=>{g&&e.layout.open(`${e.id}:${f}`,g,{tab:"select"})},F=f=>D(f)?!1:(e.toast.show({title:"PR/MR status is off in the plugin's options (status: false)"}),!0),Y=()=>e.servers.list().map(f=>e.servers.get(f)).find(f=>f?.builtin);function te(f){if(!f.length)return;const g=new Set(f);for(const v of e.tabs.list())v.session&&w(v.session)&&g.has(v.session.id)&&e.tabs.close(v.key)}async function Ke(f,g,v,C){try{const R=[],N=[],O=[];for(let E=0;E<g.length;E+=500){const U=g.slice(E,E+500),P=await t().cleanupSessions({sessionIDs:U,...v?{scanID:v}:{},allowClientArchive:!0},r(f));R.push(...P.archived),N.push(...P.alreadyArchived),O.push(...P.failed);const T=P.needsClientArchive??[];if(T.length>0){let A=0;const G=T.length;C?.({phase:"archiving",checked:0,total:G});const X=[];if(await ts(T,8,async z=>{try{await e.client.session.update({sessionID:z,archived:!0}),X.push(z)}catch(ie){O.push({sessionID:z,reason:ie instanceof Error?ie.message:String(ie)})}finally{A++,C?.({phase:"archiving",checked:A,total:G})}}),X.length>0){const z=await t().cleanupSessions({sessionIDs:X,...v?{scanID:v}:{},finalizeArchived:!0},r(f));R.push(...z.archived),N.push(...z.alreadyArchived),O.push(...z.failed)}}}const I={archived:R,alreadyArchived:N,failed:O};if(te([...I.archived,...I.alreadyArchived]),I.archived.length>0){const E=I.archived.length;e.toast.show({title:E===1?"Archived 1 session and closed its tab.":`Archived ${E} sessions and closed their tabs.`})}else if(I.alreadyArchived.length>0&&I.failed.length===0){const E=I.alreadyArchived.length;e.toast.show({title:E===1?"Session was already archived.":`${E} sessions were already archived.`})}return I.failed.length>0&&e.toast.show({title:os(I.failed),variant:"error"}),I}catch(R){e.toast.show({title:R instanceof Error?R.message:String(R),variant:"error"});return}}const Je=f=>f??(k()?$(k()):void 0)??e.tabs.list().find(g=>g.session&&w(g.session)&&g.session.location?.directory)?.session?.location?.directory;function Se(f){const g=Je(f);if(!g){e.toast.show({title:"Open a project session to run /forge-cleanup."});return}F(g)||e.dialogs.open(v=>u.createComponent(Ft,{directory:g,get close(){return v.close}}))}e.add(V.ComposerPill,{id:"status",show:f=>jt(f.session)});function jt(f){if(!w(f))return;const g=b(f);if(!D(g.directory))return;const v=Gn(j(g.directory),f.id);return is(y(g),v,{external:C=>e.system.openExternal(C),status:()=>x(de,f),feedback:()=>x(pe,f),cleanup:()=>Se(g.directory)})}const W=e.ui;e.add(V.Slot,{at:"session.header",render:f=>{const g=()=>{if(!w(f.session))return;const v=b(f.session);if(D(v.directory))return Be(y(v))};return u.createComponent(S.Show,{get when(){return g()},children:v=>u.createComponent(W.Button,{size:"small",variant:"ghost",icon:"archive",onClick:()=>Se($(f.session)),get children(){return u.memo(()=>!!f.compact)()?"Clean up":`${v().reason} · /forge-cleanup`}})})}});function Q(f){return(()=>{var g=ps(),v=g.firstChild,C=v.firstChild;return u.insert(v,()=>f.label,C),u.insert(g,u.createComponent(S.Show,{get when(){return f.url},get fallback(){return(()=>{var R=fs();return u.insert(R,()=>f.value),u.effect(()=>u.className(R,bt(f.tone))),R})()},get children(){var R=ds(),N=R.firstChild;return R.$$click=()=>e.system.openExternal(f.url),u.insert(N,()=>f.value),u.effect(()=>u.className(R,bt(f.tone))),R}}),null),g})()}function Lt(f){const g=()=>f.request,v=()=>Z(g()),C=()=>Re(g());return(()=>{var R=ms(),N=R.firstChild,O=N.firstChild,I=O.firstChild,E=N.nextSibling,U=E.nextSibling;return U.firstChild,N.$$click=()=>e.system.openExternal(g().url),u.insert(O,()=>ye(g()),I),u.insert(O,()=>g().title,null),u.insert(E,u.createComponent(Q,{label:"State",get value(){return g().state},get tone(){return g().state==="merged"?"success":void 0}}),null),u.insert(E,u.createComponent(Q,{label:"Target",get value(){return`${g().targetProject} → ${g().targetBranch}`}}),null),u.insert(E,u.createComponent(Q,{get label(){return v().ci.charAt(0).toUpperCase()+v().ci.slice(1)},get value(){return g().pipeline?.label??"none"},get tone(){return Ve(g().pipeline)},get url(){return g().pipeline?.url}}),null),u.insert(E,u.createComponent(Q,{label:"Unresolved threads",get value(){return`${g().unresolvedThreads}${g().threadsComplete?"":"+"}`},get tone(){return g().unresolvedThreads||!g().threadsComplete?"warning":void 0}}),null),u.insert(E,u.createComponent(Q,{label:"Draft",get value(){return oe(g().draft)},get tone(){return g().draft?"warning":void 0}}),null),u.insert(E,u.createComponent(Q,{label:"Conflicts",get value(){return u.memo(()=>!!g().conflictsKnown)()?oe(g().conflicts):"unknown"},get tone(){return g().conflicts?"error":void 0}}),null),u.insert(U,u.createComponent(S.For,{get each(){return v().details(g())},children:P=>{const T=P.indexOf(": ");return T<0?(()=>{var A=De();return u.insert(A,P),A})():u.createComponent(Q,{get label(){return P.slice(0,T)},get value(){return P.slice(T+2)}})}}),null),u.insert(U,u.createComponent(S.Show,{get when(){return C()},children:P=>u.createComponent(Q,{get label(){return`${P().name} review`},get value(){return P().label},get tone(){return P().state==="running"?"warning":void 0}})}),null),u.insert(U,u.createComponent(S.Show,{get when(){return g().awaitingReviewers.length},get children(){return u.createComponent(Q,{label:"Awaiting review",get value(){return g().awaitingReviewers.map(P=>`@${P}`).join(", ")}})}}),null),u.insert(R,u.createComponent(S.Show,{get when(){return!g().reviewersComplete},get children(){return hs()}}),null),u.insert(R,u.createComponent(S.Show,{get when(){return u.memo(()=>!!(f.head&&g().headSha))()&&f.head!==g().headSha},get children(){var P=gs(),T=P.firstChild,A=T.nextSibling;return A.nextSibling,u.insert(P,()=>v().noun,A),P}}),null),R})()}function Ot(f){const g=S.createMemo(()=>b(f.session),void 0,{equals:(I,E)=>I.directory===E.directory&&I.key===E.key}),v=S.createMemo(()=>y(g())),C=S.createMemo(()=>Be(v())),[R,N]=S.createSignal(!1),O=()=>{const I=v().lookup;return I?.kind==="found"?I:void 0};return(()=>{var I=ws(),E=I.firstChild,U=E.firstChild,P=U.nextSibling;return u.insert(P,u.createComponent(S.Show,{get when(){return C()},get children(){return u.createComponent(W.Button,{size:"small",icon:"archive",get busy(){return R()},onClick:async()=>{if(!R()){N(!0);try{await Ke(g().directory,[f.session.id])}finally{N(!1)}}},children:"Clean up session"})}}),null),u.insert(P,u.createComponent(W.Button,{size:"small",icon:"refresh",get busy(){return v().loading},onClick:()=>{p()?.refresh(g())},children:"Refresh"}),null),u.insert(I,u.createComponent(S.Show,{get when(){return D(g().directory)},get fallback(){return vs()},get children(){return[u.createComponent(S.Show,{get when(){return C()},children:T=>(()=>{var A=bs(),G=A.firstChild;return G.firstChild,u.insert(G,()=>T().reason,null),A})()}),u.createComponent(S.Show,{get when(){return O()},get fallback(){return(()=>{var T=De();return u.insert(T,()=>es(v())),u.effect(()=>u.className(T,`fk-pre ${v().error?"fk-error":"fk-muted"}`)),T})()},children:T=>[u.createComponent(S.Show,{get when(){return T().repository},children:A=>(()=>{var G=Rs();return u.insert(G,u.createComponent(Q,{label:"Repository",get value(){return A().source.path}}),null),u.insert(G,u.createComponent(Q,{label:"Branch",get value(){return u.memo(()=>A().branch===A().sourceBranch)()?A().branch:`${A().branch} (pushes to ${A().sourceBranch})`}}),null),G})()}),u.createComponent(S.Show,{get when(){return u.memo(()=>!T().repository)()&&T().sessionTarget},get children(){return u.createComponent(Q,{label:"Session target",get value(){return T().sessionTarget}})}}),u.createComponent(S.For,{get each(){return T().failed??[]},children:A=>(()=>{var G=Ss();return G.firstChild,u.insert(G,()=>`
|
|
208
|
+
${A.url}
|
|
209
|
+
${A.reason}`,null),G})()}),u.createComponent(S.Show,{get when(){return T().requests.length===0},get children(){return $s()}}),u.createComponent(S.For,{get each(){return T().requests},children:A=>u.createComponent(Lt,{request:A,get head(){return T().repository?.head}})}),u.createComponent(S.Show,{get when(){return v().error},children:A=>(()=>{var G=Cs(),X=G.firstChild;return X.firstChild,u.insert(X,()=>new Date(A().at).toLocaleTimeString(),null),u.insert(G,()=>`
|
|
210
|
+
${A().message}`,null),G})()}),u.createComponent(S.Show,{get when(){return v().fetchedAt!==void 0},get children(){var A=ys();return A.firstChild,u.insert(A,()=>new Date(v().fetchedAt).toLocaleTimeString(),null),A}})]})]}}),null),I})()}async function Ce(f,g,v){try{await t()[g](v,r(f)),await d(f)}catch(C){e.toast.show({title:C instanceof Error?C.message:String(C),variant:"error"})}}function Ut(f){const g=()=>f.item,v=()=>[g().read?"Read":"Unread",Fn(g()),g().automation?`${g().automation.state}${g().automation.reason?`: ${g().automation.reason}`:""}`:void 0].filter(Boolean).join(" · "),C=(R,N={})=>Ce(f.directory,R,{id:g().id,...N});return(()=>{var R=Is(),N=R.firstChild,O=N.nextSibling,I=O.nextSibling,E=I.nextSibling;return u.insert(N,()=>g().title),u.insert(O,v),u.insert(R,u.createComponent(S.For,{get each(){return g().details??[]},children:U=>(()=>{var P=De();return u.insert(P,U),P})()}),I),u.insert(I,u.createComponent(S.For,{get each(){return Hn(g())},children:U=>(()=>{var P=ks();return P.$$click=()=>e.system.openExternal(U.value),u.insert(P,()=>U.title),P})()})),u.insert(E,u.createComponent(W.Button,{size:"small",onClick:()=>{C("summarizeFeedback")},children:"Summarize in session"}),null),u.insert(E,u.createComponent(S.Show,{get when(){return Bn(g())},get children(){return[u.createComponent(W.Button,{size:"small",onClick:()=>{C("actOnFeedback")},children:"Act on feedback"}),u.createComponent(W.Button,{size:"small",onClick:async()=>{await e.dialogs.confirm({title:"Retry feedback work?",description:"Retry may repeat earlier changes. Inspect the session first.",confirm:"Retry",danger:!0})&&await C("actOnFeedback",{retry:!0})},children:"Retry"})]}}),null),u.insert(E,u.createComponent(W.Button,{size:"small",onClick:()=>{C("acknowledgeFeedback")},children:"Acknowledge"}),null),R})()}function Bt(f){const g=()=>$(f.session),v=()=>j(g()),C=S.createMemo(()=>Tt(v(),f.session.id));return(()=>{var R=Es(),N=R.firstChild,O=N.firstChild;return O.firstChild,u.insert(O,()=>v().paused?" (monitoring paused)":"",null),u.insert(N,u.createComponent(W.Button,{size:"small",get disabled(){return!C().some(I=>!I.read)},onClick:()=>{Ce(g(),"markFeedbackRead",{ids:C().map(I=>I.id)})},children:"Mark all as read"}),null),u.insert(N,u.createComponent(W.Button,{size:"small",onClick:()=>{Ce(g(),"pauseFeedback",{paused:!v().paused})},get children(){return v().paused?"Enable feedback inbox":"Pause monitoring"}}),null),u.insert(R,u.createComponent(S.Show,{get when(){return l[g()]},children:I=>(()=>{var E=_s(),U=E.firstChild,P=U.nextSibling;return P.nextSibling,u.insert(E,I,P),E})()}),null),u.insert(R,u.createComponent(S.Show,{get when(){return C().length},get fallback(){return u.createComponent(S.Show,{get when(){return!l[g()]},get children(){var I=Ne();return u.insert(I,()=>a[g()]?"No pending review updates for this session.":"Loading review updates…"),I}})},get children(){return u.createComponent(S.For,{get each(){return C()},children:I=>u.createComponent(Ut,{item:I,get directory(){return g()}})})}}),null),R})()}function Ft(f){const[g,v]=S.createSignal(!0),[C,R]=S.createSignal(),[N,O]=S.createSignal(),[I,E]=S.createSignal(),[U,P]=S.createSignal({enabled:!0,candidates:[],skippedErrors:0});let T="",A;const G=t().events.on("cleanupProgress",q=>{const M=q.data;M.scanID===T&&E(M)});S.onCleanup(()=>{A?.abort(),G()});const X=async()=>{A?.abort();const q=new AbortController;A=q;const M=vt();T=M,E(void 0),v(!0),O(void 0);try{const L=await t().cleanupCandidates({scanID:M},{...r(f.directory),signal:q.signal});q.signal.aborted||P(L)}catch(L){q.signal.aborted||O(L instanceof Error?L.message:String(L))}finally{A===q&&v(!1)}};X();const z=()=>U().candidates,ie=S.createMemo(()=>new Set(e.tabs.list().flatMap(q=>q.session&&w(q.session)?[q.session.id]:[]))),Ht=S.createMemo(()=>{const q=z(),M=[...new Set(q.map(H=>H.directory))],L=M.length>1;return M.map(H=>({directory:H,label:L?ss(H):void 0,items:q.filter(K=>K.directory===H)}))}),Xe=async(q,M)=>{if(C())return;const L=vt();T=L,E(void 0),R(M);try{const H=await Ke(f.directory,q,L,E),K=[...H?.archived??[],...H?.alreadyArchived??[]];if(K.length){const Ie=new Set(K),ae=z().filter(ke=>!Ie.has(ke.sessionID));P(ke=>({...ke,candidates:ae})),ae.length===0&&f.close()}}finally{R(void 0),E(void 0)}},Wt=()=>g()?wt(I(),"scan"):U().enabled?"No sessions with all PRs/MRs merged or tracked issues closed.":"PR/MR status is off. Enable options.status in opencode.json to use this command.",Qt=q=>{const M=()=>{const L=[ns(q)];return ie().has(q.sessionID)&&L.push("open tab"),L.join(" · ")};return(()=>{var L=Ps(),H=L.firstChild,K=H.firstChild,Ie=K.nextSibling;return K.$$click=()=>{const ae=Y()?.id;ae&&(f.close(),e.tabs.open({server:ae,id:q.sessionID},{focus:!0}))},u.insert(K,()=>q.title),u.insert(Ie,M),u.insert(L,u.createComponent(W.Button,{size:"small",icon:"archive",get busy(){return C()===q.sessionID},get disabled(){return g()||C()!==void 0},onClick:()=>{Xe([q.sessionID],q.sessionID)},children:"Clean up"}),null),L})()};return u.createComponent(W.Dialog,{title:"Clean up finished sessions",description:"Archive idle sessions whose PRs/MRs have merged or tracked issues have closed, and close their open tabs.",size:"large",get footer(){return(()=>{var q=qs();return u.insert(q,u.createComponent(W.Button,{size:"small",icon:"refresh",get busy(){return g()},get disabled(){return C()!==void 0},onClick:()=>{X()},children:"Refresh"}),null),u.insert(q,u.createComponent(S.Show,{get when(){return z().length>0},get children(){return u.createComponent(W.Button,{size:"small",variant:"contrast",icon:"archive",get busy(){return C()==="all"},get disabled(){return g()||C()!==void 0},onClick:()=>{Xe(z().map(M=>M.sessionID),"all")},get children(){return`Clean up all (${z().length})`}})}}),null),q})()},get children(){var q=Ns();return u.insert(q,u.createComponent(S.Show,{get when(){return N()},children:M=>(()=>{var L=xs();return u.insert(L,M),L})()}),null),u.insert(q,u.createComponent(S.Show,{get when(){return U().skippedErrors>0},get children(){var M=As();return u.insert(M,()=>`Skipped ${U().skippedErrors} session${U().skippedErrors===1?"":"s"} whose target status could not be verified.`),M}}),null),u.insert(q,u.createComponent(S.Show,{get when(){return u.memo(()=>C()!==void 0)()&&I()},get children(){var M=Ne();return u.insert(M,()=>wt(I(),"cleanup")),M}}),null),u.insert(q,u.createComponent(S.Show,{get when(){return u.memo(()=>!g())()&&z().length>0},get fallback(){return u.createComponent(S.Show,{get when(){return!N()},get children(){var M=Ne();return u.insert(M,Wt),M}})},get children(){var M=Ds();return u.insert(M,u.createComponent(S.For,{get each(){return Ht()},children:L=>[u.createComponent(S.Show,{get when(){return L.label},children:H=>(()=>{var K=Ts();return u.insert(K,H),K})()}),u.createComponent(S.For,{get each(){return L.items},children:H=>Qt(H)})]})),M}}),null),q}})}const Ye=(f,g)=>({id:f,title:g,closable:"hover"}),Gt=Ye(de,"PR/MR status"),zt=Ye(pe,"Review updates");return e.add(V.Panel,{id:de,region:"side",width:420,list:f=>f.open.includes(de)?[Gt]:[],render:f=>u.createComponent(Ot,{get session(){return f.session}})}),e.add(V.Panel,{id:pe,region:"side",width:420,list:f=>f.open.includes(pe)?[zt]:[],render:f=>u.createComponent(Bt,{get session(){return f.session}})}),e.add(V.Command,()=>({id:"status",title:"Show PR/MR status",group:"Forge",slash:{name:"forge-status"},enabled:!!k(),run:()=>{const f=k();!f||F($(f))||(p()?.refresh(b(f)),x(de,f))}})),e.add(V.Command,()=>({id:"feedback",title:"Show pending review feedback",group:"Forge",slash:{name:"forge-feedback"},enabled:!!k(),run:()=>{const f=k();f&&(d($(f)),x(pe,f))}})),e.add(V.Command,()=>({id:"open",title:"Open PR/MR in browser",group:"Forge",slash:{name:"forge-open"},enabled:!!k(),run:async()=>{const f=k();if(!f||F($(f)))return;const g=b(f);let v=m(g);if(v.length===0&&(await p()?.refresh(g),v=m(g)),v.length===0){e.toast.show({title:"No PR/MR for this session"});return}const C=v.length===1?v[0].url:await e.dialogs.select({title:"Open PR/MR",options:v.map(R=>({title:`${ye(R)} ${R.title}`,description:R.targetProject,value:R.url}))});C&&e.system.openExternal(C)}})),e.add(V.Command,()=>({id:"cleanup",title:"Clean up finished sessions",group:"Forge",slash:{name:"forge-cleanup"},enabled:!!Y()&&!!Je(),run:()=>Se()})),V.createKeyed(()=>e.client,()=>{const f=t();c.invalidate(),h.connect(f),c.refresh();const g=[f.events.on("sessionsCleanedUp",v=>{const{sessionIDs:C,archive:R}=v.data;if(te(C),R)for(const N of C)e.client.session.update({sessionID:N,archived:!0}).catch(()=>{})}),f.events.on("feedbackChanged",v=>{const{directory:C}=v.data;c.has(C)&&d(C)}),f.events.on("notice",v=>{const C=v.data;us(C,{hasShown:R=>!!p()?.hasShown(R)||!!v.location?.directory&&c.has(v.location.directory),openTab:R=>{const N=Y()?.id;N&&e.tabs.open({server:N,id:R})},toast:({title:R,message:N,variant:O})=>{const I=Y()?.id,E=C.sessionID;e.toast.show({title:R??N,...R?{description:N}:{},variant:O==="error"?"error":"default",...I&&E?{actions:[{label:"Open session",run:()=>e.tabs.open({server:I,id:E},{focus:!0})}]}:{}}),e.attention.notify({title:R??"Forgekeeper",message:N,variant:O==="error"?"error":"default",...I&&E?{session:{server:I,id:E}}:{},id:`forgekeeper:${E??""}:${R??""}:${N}`})}})})];S.onCleanup(()=>{for(const v of g)v();c.invalidate(),h.dispose()})}),()=>{c.invalidate(),h.dispose()}}});u.delegateEvents(["click"]);exports.default=Os;
|