opencode-forgekeeper 5.1.1 → 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 +47 -39
- package/dist/gui-experimental.cjs +105 -58
- package/dist/index.js +2378 -379
- package/dist/tui.js +659 -134
- package/package.json +1 -1
|
@@ -1,35 +1,36 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const
|
|
2
|
-
`);if(
|
|
3
|
-
`)}const
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const 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: ${
|
|
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: ${
|
|
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
|
-
... on IssueComment { id url body author { login ... on User { id } ... on Bot { id } } }
|
|
20
|
-
... on PullRequestReview { id url body author { login ... on User { id } ... on Bot { id } } }
|
|
19
|
+
... on IssueComment { id url body author { __typename login ... on User { id } ... on Bot { id } } }
|
|
20
|
+
... on PullRequestReview { id url state body author { __typename login ... on User { id } ... on Bot { id } } }
|
|
21
21
|
... on PullRequestReviewComment {
|
|
22
|
-
id url body path line originalLine diffHunk author { login ... on User { id } ... on Bot { id } }
|
|
23
|
-
|
|
22
|
+
id url body path line originalLine diffHunk author { __typename login ... on User { id } ... on Bot { id } }
|
|
23
|
+
pullRequestReview { state }
|
|
24
|
+
replyTo { body author { __typename login } }
|
|
24
25
|
}
|
|
25
26
|
}
|
|
26
|
-
}`),
|
|
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(`
|
|
27
28
|
`).slice(-21).join(`
|
|
28
|
-
`),m=
|
|
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) {
|
|
29
30
|
currentUser { id }
|
|
30
31
|
project(fullPath: $project) {
|
|
31
32
|
mergeRequest(iid: $iid) {
|
|
32
|
-
notes(last: ${
|
|
33
|
+
notes(last: ${Ht}, before: $before, filter: ONLY_COMMENTS) {
|
|
33
34
|
pageInfo { hasPreviousPage startCursor }
|
|
34
35
|
nodes {
|
|
35
36
|
id url createdAt updatedAt lastEditedAt system
|
|
@@ -40,88 +41,134 @@
|
|
|
40
41
|
}
|
|
41
42
|
}
|
|
42
43
|
}
|
|
43
|
-
}`),
|
|
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 }
|
|
44
45
|
position { diffRefs { baseSha headSha } newPath newLine oldPath oldLine }
|
|
45
|
-
discussion { resolved notes(first: ${
|
|
46
|
-
`),
|
|
47
|
-
`),
|
|
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) {
|
|
48
49
|
currentUser { id username }
|
|
49
50
|
project(fullPath: $project) {
|
|
50
51
|
mergeRequest(iid: $iid) {
|
|
51
|
-
notes(last: ${
|
|
52
|
+
notes(last: ${er}, before: $before, filter: ONLY_ACTIVITY) {
|
|
52
53
|
pageInfo { hasPreviousPage startCursor }
|
|
53
54
|
nodes { id url body createdAt system systemNoteMetadata { action } author { id username } }
|
|
54
55
|
}
|
|
55
56
|
}
|
|
56
57
|
}
|
|
57
|
-
}`),
|
|
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)=>`
|
|
58
59
|
iid title webUrl state draft conflicts approved mergeStatusEnum detailedMergeStatus diffHeadSha updatedAt targetBranch sourceBranch
|
|
59
|
-
|
|
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} }
|
|
60
66
|
sourceProject { fullPath }
|
|
61
67
|
targetProject { fullPath }
|
|
62
68
|
author { id }
|
|
63
69
|
headPipeline {
|
|
64
70
|
id status path detailedStatus { label }
|
|
65
|
-
jobs(statuses: [FAILED], retried: false, first: ${
|
|
71
|
+
jobs(statuses: [FAILED], retried: false, first: ${Sr}) { ${Cr} }
|
|
66
72
|
}
|
|
67
|
-
reviewers(first:
|
|
68
|
-
discussions(first: ${
|
|
69
|
-
`;function
|
|
70
|
-
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} } }
|
|
71
77
|
}`).join(`
|
|
72
|
-
`);return
|
|
73
|
-
${
|
|
74
|
-
}`)}function
|
|
75
|
-
`);return
|
|
76
|
-
${
|
|
77
|
-
}`)}function
|
|
78
|
+
`);return _(`query($branch: String!, ${n}) {
|
|
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(`
|
|
81
|
+
`);return _(`query($iid: String!, ${n}) {
|
|
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}) {
|
|
78
84
|
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { iid updatedAt sourceProject { fullPath } } }
|
|
79
85
|
}`).join(`
|
|
80
|
-
`);return
|
|
81
|
-
${
|
|
82
|
-
}`)}const
|
|
86
|
+
`);return _(`query($branch: String!, ${r}) {
|
|
87
|
+
${t}
|
|
88
|
+
}`)}const Pr=_(`query($project: ID!, $iid: String!) {
|
|
83
89
|
project(fullPath: $project) { mergeRequest(iid: $iid) { sourceBranch } }
|
|
84
|
-
}`),
|
|
90
|
+
}`),Ar=_(`query($project: ID!, $iid: String!) {
|
|
85
91
|
project(fullPath: $project) {
|
|
86
|
-
|
|
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} } }
|
|
107
|
+
}
|
|
108
|
+
}`),Nr=e=>_(`query($project: ID!, $iid: String!, $after: String) {
|
|
109
|
+
project(fullPath: $project) {
|
|
110
|
+
mergeRequest(iid: $iid) { reviewers(first: ${Q}, after: $after) { ${lt(e)} } }
|
|
87
111
|
}
|
|
88
|
-
}`)
|
|
89
|
-
|
|
112
|
+
}`),qr=_(`query($project: ID!, $iid: String!, $after: String) {
|
|
113
|
+
project(fullPath: $project) {
|
|
114
|
+
mergeRequest(iid: $iid) { approvedBy(first: ${Q}, after: $after) { ${ct} } }
|
|
115
|
+
}
|
|
116
|
+
}`),Tr=_(`mutation($project: ID!, $iid: String!) {
|
|
117
|
+
mergeRequestSetDraft(input: { projectPath: $project, iid: $iid, draft: false }) {
|
|
118
|
+
mergeRequest { draft }
|
|
119
|
+
errors
|
|
120
|
+
}
|
|
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
|
|
90
123
|
headRepository { nameWithOwner } baseRepository { nameWithOwner } baseRefName updatedAt
|
|
91
124
|
author { ... on User { id } ... on Bot { id } }
|
|
92
125
|
reviewThreads(first:100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
93
|
-
reviewRequests(first:100) { nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { login } ... on Team { name } } } pageInfo { hasNextPage endCursor } }
|
|
94
|
-
latestReviews(first:100) { nodes { author { ... on User { id } } } }
|
|
95
|
-
|
|
126
|
+
reviewRequests(first:100) { nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } } pageInfo { hasNextPage endCursor } }
|
|
127
|
+
latestReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } }
|
|
128
|
+
latestOpinionatedReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } pageInfo { hasNextPage endCursor } }
|
|
129
|
+
copilotReviews: reviews(last:1, author:"${Re}", states:[COMMENTED,CHANGES_REQUESTED,APPROVED,DISMISSED]) { nodes { id state comments { totalCount } author { __typename login ... on Bot { id } ... on User { id } } } }
|
|
96
130
|
commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
|
|
97
131
|
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } }
|
|
98
132
|
pageInfo { hasNextPage endCursor }
|
|
99
|
-
} } } } }`,
|
|
100
|
-
`)[0])}const
|
|
101
|
-
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${
|
|
102
|
-
}`),{owner:
|
|
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!) {
|
|
135
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${He} } }
|
|
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!) {
|
|
103
137
|
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch,orderBy:{field:UPDATED_AT,direction:DESC}) {
|
|
104
138
|
nodes { number updatedAt headRepository { nameWithOwner } }
|
|
105
|
-
} } }`),{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!) {
|
|
106
140
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { headRefName } }
|
|
107
|
-
}`),{owner:
|
|
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!) {
|
|
144
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { id isDraft state } }
|
|
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!) {
|
|
146
|
+
markPullRequestReadyForReview(input:{pullRequestId:$id}) { pullRequest { id isDraft } }
|
|
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!":""}) {
|
|
108
148
|
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${a?",after:$after":""}) {
|
|
109
|
-
nodes { ${
|
|
110
|
-
} } }`),{owner:
|
|
149
|
+
nodes { ${He} } pageInfo { hasNextPage endCursor }
|
|
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!) {
|
|
111
151
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
112
152
|
reviewThreads(first:100,after:$after) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
113
|
-
} } }`),{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!) {
|
|
114
154
|
repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
|
|
115
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 } }
|
|
116
|
-
} } } } }`),{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!) {
|
|
117
157
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
118
158
|
reviewRequests(first:100,after:$after) {
|
|
119
|
-
nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { login } ... on Team { name } } }
|
|
159
|
+
nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } }
|
|
160
|
+
pageInfo { hasNextPage endCursor }
|
|
161
|
+
}
|
|
162
|
+
} }
|
|
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!) {
|
|
164
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
165
|
+
latestOpinionatedReviews(first:100,after:$after) {
|
|
166
|
+
nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } }
|
|
120
167
|
pageInfo { hasNextPage endCursor }
|
|
121
168
|
}
|
|
122
169
|
} }
|
|
123
|
-
}`),{owner:a,repo:i,number:r.number,after:s.endCursor})).repository?.pullRequest?.reviewRequests;if(!u)throw new O("request","GitHub reviewers unavailable");n.push(...u.nodes),s=u.pageInfo}if(s?.hasNextPage)throw new O("request","GitHub reviewers exceeded the pagination limit");return{nodes:n,pageInfo:s}}async normalize(t,r){const n=await this.reviewers(t,r),[s,o]=[await this.threads(t,r),await this.contexts(t,r)];return{forge:"github",iid:String(r.number),title:r.title,url:r.url,state:r.state==="OPEN"?"opened":r.state.toLowerCase(),draft:r.isDraft,conflicts:r.mergeable==="CONFLICTING",conflictsKnown:r.mergeable!=="UNKNOWN",approved:r.reviewDecision==="APPROVED",reviewDecision:r.reviewDecision??void 0,copilotReview:Dr({...r,reviewRequests:n}),awaitingReviewers:n.nodes.flatMap(a=>{const i=a.requestedReviewer;return i?.__typename==="Bot"?[]:i?.login?[i.login]:i?.name?[i.name]:[]}),reviewersComplete:!n.pageInfo?.hasNextPage,reviewerIDs:[...new Set([...n.nodes.flatMap(a=>a.requestedReviewer?.__typename==="User"?a.requestedReviewer.id??[]:[]),...(r.latestReviews?.nodes??[]).flatMap(a=>a?.author?.id??[])])],targetProject:r.baseRepository.nameWithOwner,targetBranch:r.baseRefName,...r.headRepository?{sourceProject:r.headRepository.nameWithOwner}:{},sourceBranch:r.headRefName,headSha:r.headRefOid,...r.author?.id?{authorID:r.author.id}:{},updatedAt:r.updatedAt,pipeline:o.nodes.length||!o.complete?_r(o.nodes,o.complete,`${r.url}/checks`,r.headRefOid):void 0,unresolvedThreads:s.unresolved,threadsComplete:s.complete}}}const qr={gitlab:B,github:ae},G=e=>qr[e.forge],ce=e=>G(e).reference(e.iid);function le(e){const t=G(e).automatedReview,r=t?.status(e);return t&&r?{name:t.name,...r}:void 0}const He={url:{type:"string"},issueUrl:{type:"string"}},ze={type:"object",properties:{...He,targets:{type:"array",items:{type:"object",properties:He,required:["url"],additionalProperties:!1}}},additionalProperties:!1},ne={type:"string"},$e={type:"object",title:"Snapshot"},W={type:"object",title:"InboxState"},xr={type:"object",properties:{enabled:{type:"boolean"},snapshot:$e},required:["enabled","snapshot"],additionalProperties:!1},Lr={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:W},acknowledgeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:W},markFeedbackRead:{input:{type:"object",properties:{ids:{type:"array",items:{type:"string"},maxItems:500}},required:["ids"],additionalProperties:!1},output:W},summarizeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:W},pauseFeedback:{input:{type:"object",properties:{paused:{type:"boolean"}},required:["paused"],additionalProperties:!1},output:W},actOnFeedback:{input:{type:"object",properties:{id:{type:"string"},retry:{type:"boolean"}},required:["id"],additionalProperties:!1},output:W},target:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:ze},watch:{input:{type:"object",properties:{clientID:{type:"string"},keys:{type:"array",items:ne},visible:ne},required:["clientID","keys"],additionalProperties:!1},output:{type:"object",properties:{enabled:{type:"boolean"},statuses:{type:"object",additionalProperties:$e}},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:ne},required:["key"],additionalProperties:!1},output:xr}},events:{feedbackChanged:{schema:{type:"object",properties:{directory:{type:"string"}},required:["directory"],additionalProperties:!1}},targetChanged:{schema:{type:"object",properties:{sessionID:{type:"string"},...ze.properties},required:["sessionID"],additionalProperties:!1}},status:{schema:{type:"object",properties:{directory:{type:"string"},key:ne,snapshot:$e},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}}}},Or="",ot=6e4,We=(e,t)=>e.directory===t.directory&&e.key===t.key,Y=e=>JSON.stringify([e.directory,e.key]);function Ur(e){const t=e.now??Date.now,r=e.setTimer??((p,R)=>setTimeout(p,R)),n=e.clearTimer??(p=>clearTimeout(p)),s=e.defer??queueMicrotask,o=new Map,a=new Map,i=new Map;let c,u=!1;const f=p=>a.get(p.directory)?.has(p.key)===!0;function m(p,R){const P=Y(p);(R.revision??-1)>=(o.get(P)?.revision??-1)&&o.set(P,R)}function g(p,R){const x={kind:"request",message:`PR/MR status service unavailable: ${R instanceof Error?R.message:String(R)}`,at:t()};for(const z of a.get(p)??[]){const U=Y({directory:p,key:z});o.set(U,{...o.get(U)??{},loading:!1,error:x})}e.onChange()}const y=new Map,v=new Map;function w(p){const R=(y.get(p)??0)+1;y.set(p,R);const P=v.get(p);P!==void 0&&n(P),v.set(p,r(()=>{C(p)},Math.min(ot,1e3*2**R)))}async function C(p){if(u)return;const R=v.get(p);R!==void 0&&n(R),v.delete(p);const P=[...a.get(p)??[]];try{const x=await e.watch(p,{clientID:e.clientID,keys:P,...c?.directory===p?{visible:c.key}:{}});if(u)return;y.delete(p),i.set(p,x.enabled);for(const[z,U]of Object.entries(x.statuses))f({directory:p,key:z})&&m({directory:p,key:z},U);e.onChange()}catch(x){if(u)return;g(p,x),w(p)}}const I=new Set;function q(p){I.has(p)||(I.add(p),s(()=>{I.delete(p),C(p)}))}return{snapshot:p=>o.get(Y(p))??{loading:!1},enabled:p=>i.get(p)??!0,show(p){if(p.key!==Or)for(const[P,x]of a)P===p.directory||!x.delete(p.key)||(o.delete(Y({directory:P,key:p.key})),c&&We(c,{directory:P,key:p.key})&&(c=void 0),q(P));const R=a.get(p.directory)??new Set;a.set(p.directory,R),R.add(p.key),c=p,q(p.directory)},hide(p){c&&We(c,p)&&(c=void 0),q(p.directory)},async refresh(p){const R=Y(p);o.set(R,{...o.get(R)??{},loading:!0}),e.onChange();try{const P=await e.refresh(p.directory,p.key);if(u)return;i.set(p.directory,P.enabled),m(p,P.snapshot),e.onChange()}catch(P){if(u)return;g(p.directory,P)}},heartbeat(){for(const p of a.keys())C(p)},receive(p,R,P){f({directory:p,key:R})&&(m({directory:p,key:R},P),e.onChange())},hasShown:p=>[...a.values()].some(R=>R.has(p)),dispose(){u=!0;for(const p of v.values())n(p);for(const p of a.keys())e.release(p,e.clientID).catch(()=>{})}}}const oe=e=>({location:{directory:e}}),Mr=async(e,t)=>await e.feedback({},oe(t));function jr(e){let t,r=0;const n=new Map;let s;return{get client(){return t?.client},connect(o){t?.dispose(),t=Br(o,{...e,clientID:`${e.clientID}:${++r}`});for(const a of n.values())t.client.show(a),t.client.hide(a);s&&t.client.show(s),e.onChange()},show(o){n.set(o.key,o),s=o,t?.client.show(o)},hide(o){s?.key===o.key&&s.directory===o.directory&&(s=void 0),t?.client.hide(o)},dispose(){t?.dispose(),t=void 0}}}function Fr(e){const t=new Map;let r=0;const n=async s=>{const o=(t.get(s)??0)+1;t.set(s,o);const a=r,i=()=>a===r&&t.get(s)===o;try{const c=await e.load(s);i()&&e.changed(s,c)}catch(c){i()&&e.failed(s,c instanceof Error?c.message:String(c))}};return{reload:n,has:s=>t.has(s),refresh:()=>Promise.all([...t.keys()].map(n)),invalidate(){r++}}}function Br(e,t){const r=e,n=Ur({clientID:t.clientID,watch:async(a,i)=>await r.watch(i,oe(a)),refresh:async(a,i)=>await r.refresh({key:i},oe(a)),release:(a,i)=>r.release({clientID:i},oe(a)),onChange:t.onChange}),s=setInterval(()=>{n.heartbeat(),t.heartbeat?.()},ot),o=e.events.on("status",a=>{const{directory:i,key:c,snapshot:u}=a.data;n.receive(i,c,u)});return{client:n,dispose(){clearInterval(s),o(),n.dispose()}}}const Gr=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,pe=e=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),Hr=e=>e.kind==="review-request",zr=e=>Hr(e)?`Requested: ${pe(e.postedAt??e.at)}`:e.postedAt!==void 0?`Latest comment: ${pe(e.postedAt)}`:`Detected: ${pe(e.at)}`,it=(e,t)=>t?e.items.filter(r=>r.sessionID===t):[];function Wr(e,t){const r=it(e,t).filter(n=>!n.read).length;if(r!==0)return`${r} review update${r===1?"":"s"}${e.paused?" (paused)":""}`}function Jr(e){return[...new Set([e.url,...e.links])].filter(t=>{try{const r=new URL(t);return r.protocol==="https:"&&r.origin===new URL(e.url).origin&&!r.username&&!r.password}catch{return!1}})}function Qr(e){const t=Jr(e),r=t.filter(s=>s!==e.url),n=e.kind==="ci-failed";return[...r.map((s,o)=>({title:`${n?"Failed job":"Comment"} ${r.length>1?`${o+1} of ${r.length} `:""}(${n?new URL(s).pathname.split("/").filter(Boolean).slice(-2).join("/"):new URL(s).hash||"no anchor"})`,description:s,value:s})),...t.includes(e.url)?[{title:"PR/MR overview",description:e.url,value:e.url}]:[]]}const Kr=new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SCHEDULED","WAITING_FOR_CALLBACK","CANCELING"]);function Ie(e){return e?e.status==="FAILED"?"error":e.status==="SUCCESS"?e.label.includes("warning")?"warning":"success":Kr.has(e.status)?"warning":"muted":"muted"}const at=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Vr=e=>e.charAt(0).toUpperCase()+e.slice(1),Yr={success:"CI ✓",error:"CI ✗",warning:"CI …"};function Xr(e){return e.length>2?`awaiting ${e.length} reviewers`:`awaiting ${e.map(t=>`@${t}`).join(", ")}`}function Zr(e){return`${e.unresolvedThreads}${e.threadsComplete?"":"+"} unresolved thread${e.unresolvedThreads===1&&e.threadsComplete?"":"s"}`}const fe=e=>({text:ce(e),tone:"muted",url:e.url,essential:!0});function en(e){const t=Ie(e.pipeline);return e.pipeline?{text:`CI ${e.pipeline.label}`,compact:Yr[t],tone:t,url:e.pipeline.url}:{text:`no ${G(e).ci}`,compact:"no CI",tone:t}}function tn(e){const t=new Set(e.map(g=>G(g).noun)),r=t.size===1?[...t][0]:"PR/MR",n=e.length===1?`1 ${r}`:`${e.length} ${r==="PR/MR"?"PRs/MRs":`${r}s`}`,s=e.filter(g=>g.state==="opened"),o=[{text:n,tone:"muted",essential:!0}],a=s.filter(g=>le(g)?.state==="running").length;a&&o.push({text:`🤖 ${a} reviewing`,compact:`🤖 ${a}`,tone:"warning",essential:!0});const i=s.filter(g=>Ie(g.pipeline)==="error").length;i&&o.push({text:`${i} CI failed`,compact:`CI ✗ ${i}`,tone:"error"});const c=s.filter(g=>g.conflicts).length;c&&o.push({text:at(c,"conflict"),tone:"error",essential:!0});const u=s.filter(g=>g.approved&&g.awaitingReviewers.length===0).length;u&&o.push({text:`${u} approved`,tone:"success"});const f=e.filter(g=>g.state==="merged").length;f&&o.push({text:`${f} merged`,tone:"success"});const m=e.length-s.length-f;return m&&o.push({text:`${m} closed`,tone:"muted"}),o}function rn(e){const{lookup:t,error:r}=e,n=r?[{text:"stale",tone:"warning",essential:!0}]:[];if(!t||t.kind==="none"||t.requests.length===0)return e.targeted&&(r||t?.explicitTarget)?[{text:"PR/MR status unavailable",tone:"warning"}]:[];t.failed?.length&&n.unshift({text:`${t.failed.length} unavailable`,tone:"warning",essential:!0});const s=t.requests;if(t.explicitTarget&&s.length>1)return[...tn(s),...n];if(s.length>1){const i=G(s[0]).noun;return[...s.map(fe),{text:`${at(s.length,`open ${i}`)}, run /${i.toLowerCase()}-status`,tone:"warning"},...n]}const[o]=s;if(o.state!=="opened")return[fe(o),{text:o.state,tone:o.state==="merged"?"success":"muted",essential:!0},...n];const a=[fe(o),en(o)];if(o.unresolvedThreads>0||!o.threadsComplete){const i=Zr(o);a.push({text:i,compact:i.replace("unresolved ",""),tone:"warning"})}return le(o)?.state==="running"&&a.push({text:"🤖 reviewing",compact:"🤖",tone:"warning",essential:!0}),a.push(...G(o).indicators(o)),o.conflicts&&a.push({text:"conflicts",tone:"error",essential:!0}),o.conflictsKnown||a.push({text:"mergeability unknown",tone:"muted"}),o.awaitingReviewers.length?a.push({text:Xr(o.awaitingReviewers),tone:"muted"}):o.approved&&a.push({text:"approved",tone:"success"}),[...a,...n]}const Je=e=>new Date(e).toLocaleTimeString();function nn(e,t){const r=G(e),n=[`${ce(e)} ${e.title}${e.state==="opened"?"":` (${e.state})`}`,`Target: ${e.targetProject} → ${e.targetBranch}`,`${Vr(r.ci)}: ${e.pipeline?e.pipeline.label:"none"}${e.pipeline?.url?` (${e.pipeline.url})`:""}`,`Unresolved threads: ${e.unresolvedThreads}${e.threadsComplete?"":"+"}`,`Draft: ${J(e.draft)} · Conflicts: ${e.conflictsKnown?J(e.conflicts):"unknown"}`,...r.details(e)],s=le(e);return s&&n.push(`${s.name} review: ${s.label}`),e.awaitingReviewers.length&&n.push(`Awaiting review: ${e.awaitingReviewers.map(o=>`@${o}`).join(", ")}`),e.reviewersComplete||n.push("Reviewer list is partial"),t&&e.headSha&&t!==e.headSha&&n.push(`Local HEAD differs from the ${r.noun} head commit (unpushed or not fetched)`),n.push(e.url),n}function sn(e){const{lookup:t,error:r,fetchedAt:n}=e,s=[];if(!t)s.push(r?"Could not look up the PR/MR.":"No data yet.");else if(t.kind==="none")s.push(`No PR/MR lookup: ${t.reason}.`);else{const{repository:o,sessionTarget:a,requests:i}=t;if(o){const c=o.branch===o.sourceBranch?o.branch:`${o.branch} (pushes to ${o.sourceBranch})`;s.push(`Branch: ${c} in ${o.source.path}`),i.length===0&&s.push("","No open PR/MR for this branch.")}else a&&s.push(`Session target: ${a}`);for(const{url:c,reason:u}of t.failed??[])s.push(`Unavailable: ${c} (${u})`);for(const c of i)s.push("",...nn(c,o?.head??""))}return r&&s.push("",`Last refresh failed at ${Je(r.at)}: ${r.message}`),n!==void 0&&s.push("",`Last fetched: ${Je(n)}`),s.join(`
|
|
124
|
-
`)}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=`
|
|
125
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); }
|
|
126
173
|
.forgekeeper-panel header { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
|
127
174
|
.forgekeeper-panel h2 { font-size: 13px; font-weight: 600; margin: 0; }
|
|
@@ -135,7 +182,7 @@ ${r}
|
|
|
135
182
|
.forgekeeper-panel .fk-error { color: var(--v2-state-fg-danger); }
|
|
136
183
|
.forgekeeper-panel a { color: var(--v2-text-text-accent); cursor: pointer; text-decoration: underline; }
|
|
137
184
|
.forgekeeper-panel .fk-pre { white-space: pre-wrap; }
|
|
138
|
-
`,
|
|
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,()=>`
|
|
139
186
|
${S.url}
|
|
140
|
-
${S.reason}`,null),k})()}),
|
|
141
|
-
${S().message}`,null),k})()}),
|
|
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;
|