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