opencode-forgekeeper 3.3.1 → 4.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/dist/gui-experimental.cjs +46 -46
- package/dist/index.js +42 -20
- package/dist/tui.js +35 -13
- package/package.json +2 -2
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("solid-js/web"),j=require("@opencode/plugin/gui"),
|
|
2
|
-
`);if(t<1||t>r.length)return;const s=Math.max(1,t-
|
|
3
|
-
`)}const ee=100,ie=20,
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("solid-js/web"),j=require("@opencode/plugin/gui"),D=require("solid-js"),_e=require("solid-js/store"),dt=require("node:crypto"),Ke=e=>t=>t.forge===e,pt=e=>e?.match(/^\[[^\]]*\]/)?.[0]??"";function Qe(e,t){return pt(e).slice(1,-1).split(/[\s,]+/).flatMap(r=>r.startsWith(t)&&/^[1-9]\d*$/.test(r.slice(t.length))?[r.slice(t.length)]:[])}function fe(e,t,r){let s;try{s=new URL(t)}catch{return}if(!["https:","http:"].includes(s.protocol))return;const n=s.pathname.match(r);if(n)return{forge:e,host:s.hostname.toLowerCase(),project:decodeURIComponent(n[1]),iid:n[2]}}const W=e=>e?"yes":"no",he=e=>e.toLowerCase().replace(/_/g," ");class O extends Error{constructor(t,r){super(r),this.kind=t}kind}const A=e=>e,B=e=>async(t,r,s)=>await e(t,r,s),Ne=10,ft=10,De=300,ht=5,Ae=300;function mt(e,t){const r=e.split(`
|
|
2
|
+
`);if(t<1||t>r.length)return;const s=Math.max(1,t-Ne),n=Math.min(r.length,t+Ne);return r.slice(s-1,n).map((o,a)=>{const i=s+a,c=o.length>De?`${o.slice(0,De)}…`:o;return`${i===t?">":" "}${i}: ${c}`}).join(`
|
|
3
|
+
`)}const ee=100,ie=20,Ve=200,ve="author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } }",$e="pageInfo { hasPreviousPage startCursor }",Xe=`id url state createdAt publishedAt lastEditedAt isMinimized ${ve}`,ye=(e,t)=>A(`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: ${ee}, before: $before) { ${
|
|
7
|
+
${e}(last: ${ee}, before: $before) { ${$e} nodes { ${t} } }
|
|
8
8
|
}
|
|
9
9
|
}
|
|
10
|
-
}`),
|
|
10
|
+
}`),gt=ye("comments",`id url createdAt publishedAt lastEditedAt isMinimized ${ve}`),wt=ye("reviews",`id url state body submittedAt lastEditedAt isMinimized ${ve}`),bt=ye("reviewThreads",`id isResolved comments(last: ${ee}) { ${$e} nodes { ${Xe} } }`),vt=A(`query($id: ID!, $before: String) {
|
|
11
11
|
node(id: $id) {
|
|
12
12
|
... on PullRequestReviewThread {
|
|
13
|
-
comments(last: ${ee}, before: $before) { ${
|
|
13
|
+
comments(last: ${ee}, before: $before) { ${$e} nodes { ${Xe} } }
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
|
-
}`)
|
|
16
|
+
}`),$t=new Set(["COMMENTED","CHANGES_REQUESTED","APPROVED"]),Se=(...e)=>{const t=e.find(r=>r);return t?Date.parse(t):NaN},Ce=(e,t)=>{const r=e?Date.parse(e):NaN;return Number.isFinite(r)?Math.max(r,t):t};function Re({node:e,postedAt:t,editedAt:r,resolved:s}){if(e.isMinimized||!e.author?.id||!Number.isFinite(t)||!Number.isFinite(r))return;const{__typename:n,login:o}=e.author;return{id:e.id,order:t,url:e.url??"",editedAt:r,resolved:s,bot:n==="Bot"||o.endsWith("[bot]"),authorID:e.author.id,username:o}}function yt(e){const t=Se(e.publishedAt,e.createdAt);return Re({node:e,postedAt:t,editedAt:Ce(e.lastEditedAt,t),resolved:!1})}function St(e){if(!$t.has(e.state)||!e.body.trim())return;const t=Se(e.submittedAt);return Re({node:e,postedAt:t,editedAt:Ce(e.lastEditedAt,t),resolved:!1})}function Ct(e,t){if(e.state==="PENDING")return;const r=Se(e.publishedAt,e.createdAt);return Re({node:e,postedAt:r,editedAt:Ce(e.lastEditedAt,r),resolved:t})}const Rt={pages:ie,completeAtLimit:!0},kt={pages:Ve,completeAtLimit:!1};async function ue(e,t,r,s,n,o=Rt){const a=[];let i,c;const u=f=>({items:a.toReversed().flat(),viewer:i,complete:f});for(let f=0;f<o.pages;f++){const m=c?{...r,before:c}:r,g=await e(t,s,m);i??=g.viewer?.id??void 0;const E=g.repository?.pullRequest?.[n];if(!E)return f===0?{viewer:i,complete:!1}:u(!1);if(a.push(E.nodes),!E.pageInfo.hasPreviousPage)return u(!0);if(c=E.pageInfo.startCursor??void 0,!c)return u(!1)}return u(o.completeAtLimit)}async function Et(e,t,r){if(!r.comments)return{comments:[],complete:!1};const s=[];let n=r.comments?.pageInfo.hasPreviousPage?r.comments.pageInfo.startCursor??void 0:void 0;if(r.comments?.pageInfo.hasPreviousPage&&!n)return{comments:[],complete:!1};for(let o=1;n&&o<ie;o++){const i=(await e(t,vt,{id:r.id,before:n})).node?.comments;if(!i)return{comments:s.toReversed().flat(),complete:!1};if(s.push(i.nodes),n=i.pageInfo.hasPreviousPage?i.pageInfo.startCursor??void 0:void 0,i.pageInfo.hasPreviousPage&&!n)return{comments:s.toReversed().flat(),complete:!1}}return{comments:s.toReversed().flat(),complete:!0}}const It=e=>A(`query {
|
|
17
17
|
nodes(ids: ${JSON.stringify(e)}) {
|
|
18
18
|
__typename
|
|
19
19
|
... on IssueComment { id url body author { login ... on User { id } ... on Bot { id } } }
|
|
@@ -23,13 +23,13 @@
|
|
|
23
23
|
replyTo { body author { login } }
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
|
-
}`),
|
|
26
|
+
}`),Pt=/^[A-Za-z0-9_=-]+$/,Te=50;async function _t(e,t,r){const s=B(e),n=[],o=r.filter(a=>Pt.test(a));for(let a=0;a<o.length;a+=Te){const i=await s(t,It(o.slice(a,a+Te)),{});for(const c of i.nodes??[]){if(!c?.id||!c.url||!c.author||c.body===void 0)continue;const u=c.line??c.originalLine??void 0,f=c.diffHunk?.split(`
|
|
27
27
|
`).slice(-21).join(`
|
|
28
|
-
`),
|
|
28
|
+
`),m=c.replyTo?.author?[{username:c.replyTo.author.login,body:c.replyTo.body}]:[];n.push({id:c.id,url:c.url,username:c.author.login,...c.author.id?{authorID:c.author.id}:{},body:c.body,...c.path?{path:c.path}:{},...u!==void 0?{line:u}:{},...c.path&&f?{code:{path:c.path,text:f}}:{},...m.length?{replies:m}:{}})}}return n}async function Nt(e,t,r,s){let n=0;const o=B(async(...S)=>n++>=Ve?{}:e(...S)),[a,i]=r.split("/"),c={owner:a,repo:i,number:Number(s)},[u,f,m]=await Promise.all([ue(o,t,c,gt,"comments"),ue(o,t,c,wt,"reviews"),ue(o,t,c,bt,"reviewThreads",kt)]);if(!u.items||!f.items||!m.items)return;const g=u.viewer??f.viewer??m.viewer;let E=m.complete;const $=[];for(const S of m.items){const I=await Et(o,t,S);E&&=I.complete;for(const x of[...I.comments,...S.comments?.nodes??[]]){const p=Ct(x,S.isResolved);p&&$.push(p)}$.sort((x,p)=>p.order-x.order),$.splice(ee*ie)}const w=[...u.items.map(yt),...f.items.map(St),...$.sort((S,I)=>S.order-I.order).slice(-ee*ie)].flatMap(S=>S??[]);return{complete:u.complete&&f.complete&&E&&g!==void 0,viewerID:g,comments:w.sort((S,I)=>S.order-I.order)}}const Dt=100,At=20,me=A(`query($project: ID!, $iid: String!, $before: String) {
|
|
29
29
|
currentUser { id }
|
|
30
30
|
project(fullPath: $project) {
|
|
31
31
|
mergeRequest(iid: $iid) {
|
|
32
|
-
notes(last: ${
|
|
32
|
+
notes(last: ${Dt}, before: $before, filter: ONLY_COMMENTS) {
|
|
33
33
|
pageInfo { hasPreviousPage startCursor }
|
|
34
34
|
nodes {
|
|
35
35
|
id url createdAt updatedAt lastEditedAt system
|
|
@@ -40,11 +40,11 @@
|
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
|
-
}`),
|
|
43
|
+
}`),Tt=A(String(me).replace("position { newPath }","position { newPath } duoCreatedSession { id status workflowDefinition }")),se=e=>e.slice(e.lastIndexOf("/")+1),xt=e=>Date.parse(e.lastEditedAt??e.updatedAt??e.createdAt);function qt(e){const t=xt(e),r=se(e.id);if(!(e.system||!e.author||!Number.isFinite(t)||!/^\d+$/.test(r)))return{id:r,order:Number(r),url:e.url??"",editedAt:t,resolved:e.discussion?.resolved===!0,bot:e.author.bot,authorID:e.author.id,username:e.author.username,...e.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 Lt(e,t,r,s){const n=B(e),o=[];let a,i,c=!0;const u=f=>({complete:f&&a!==void 0,viewerID:a,comments:o.toReversed().flat()});for(let f=0;f<At;f++){const m={project:r,iid:s};i&&(m.before=i);let g;try{g=await n(t,c?Tt:me,m)}catch($){if(!c||!/duoCreatedSession.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*duoCreatedSession/i.test($ instanceof Error?$.message:String($)))throw $;c=!1,g=await n(t,me,m)}a??=g.currentUser?.id??void 0;const E=g.project?.mergeRequest?.notes;if(!E)return f===0?void 0:u(!1);if(o.push(E.nodes.flatMap($=>qt($)??[])),!E.pageInfo.hasPreviousPage)return u(!0);if(i=E.pageInfo.startCursor??void 0,!i)return u(!1)}return u(!0)}const xe=25,Ot=20,Ut=/^[0-9a-f]{40}$/;function Ye(e){const t=e?.diffRefs;if(t){if(e.newLine&&e.newPath)return{sha:t.headSha,path:e.newPath,line:e.newLine};if(e.oldLine&&e.oldPath)return{sha:t.baseSha,path:e.oldPath,line:e.oldLine}}}async function Mt(e,t,r,s){const n=B(e),o=[],a=s.filter(c=>/^\d+$/.test(c));for(let c=0;c<a.length;c+=xe){const u=a.slice(c,c+xe).map((m,g)=>`n${g}: note(id: "gid://gitlab/Note/${m}") { id url body author { id username }
|
|
44
44
|
position { diffRefs { baseSha headSha } newPath newLine oldPath oldLine }
|
|
45
|
-
discussion { notes(first: ${
|
|
46
|
-
`),
|
|
47
|
-
`),
|
|
45
|
+
discussion { notes(first: ${Ot}) { nodes { id body author { username } } } } }`).join(`
|
|
46
|
+
`),f=await n(t,A(`query { ${u} }`),{});for(const m of Object.values(f))m?.author&&m.url&&o.push(m)}const i=await jt(n,t,r,o).catch(()=>new Map);return o.map(c=>{const u=Ye(c.position),f=u&&i.get(JSON.stringify([u.sha,u.path])),m=f!==void 0&&u?mt(f,u.line):void 0,g=c.discussion?.notes?.nodes??[],E=g.findIndex(w=>se(w.id)===se(c.id)),$=(E>0?g.slice(0,E):[]).flatMap(w=>w.author?[{username:w.author.username,body:w.body}]:[]);return{id:se(c.id),url:c.url??"",username:c.author?.username??"",...c.author?.id?{authorID:c.author.id}:{},body:c.body,...u?{path:u.path,line:u.line}:{},...m&&u?{code:{path:u.path,text:m}}:{},...$.length?{replies:$}:{}}})}async function jt(e,t,r,s){const n=new Map;let o=0;for(const f of s){const m=Ye(f.position);if(!m||!Ut.test(m.sha))continue;const g=n.get(m.sha)??new Set;!g.has(m.path)&&o>=ft||(g.has(m.path)||o++,n.set(m.sha,g.add(m.path)))}const a=new Map;if(!n.size)return a;const i=[...n.keys()],c=i.map((f,m)=>`b${m}: project(fullPath: ${JSON.stringify(r)}) { repository { blobs(paths: ${JSON.stringify([...n.get(f)])}, ref: ${JSON.stringify(f)}) { nodes { path rawTextBlob } } } }`).join(`
|
|
47
|
+
`),u=await e(t,A(`query { ${c} }`),{});return i.forEach((f,m)=>{for(const g of u[`b${m}`]?.repository?.blobs?.nodes??[])g.rawTextBlob!==null&&a.set(JSON.stringify([f,g.path]),g.rawTextBlob)}),a}const Bt=/^\/(.+?)\/-\/(issues|work_items|merge_requests)\/(\d+)(\/diffs)?\/?$/,Ft=/^#note_(\d+)$/,Gt=/https:\/\/[^\s<>()[\]"'`]+/g,Ht=/^gid:\/\/gitlab\/[A-Za-z]*Note\/(\d+)$/;function ge(e,t){if(e.length>Ae*2)return;let r;try{r=new URL(e)}catch{return}if(r.protocol!=="https:"||r.hostname.toLowerCase()!==t||r.port||r.username||r.password)return;const s=r.hash.match(Ft)?.[1],n=r.pathname.match(Bt);if(!s||!n)return;const[,o,a,i,c]=n;if(c&&a!=="merge_requests"||o.split("/").some(f=>!f||f==="."||f===".."))return;const u=`https://${t}/${o}/-/${a}/${i}#note_${s}`;if(!(u.length>Ae))return{url:u,project:o,resource:a==="merge_requests"?"merge_request":"issue",iid:i,noteID:s}}const Ze=(e,t)=>e.project.toLowerCase()===t.project.toLowerCase()&&e.resource===t.resource&&e.iid===t.iid&&e.noteID===t.noteID;function zt(e,t){const r=new Set(t.map(n=>n.id)),s=[];for(const n of t)for(const[o]of n.body.matchAll(Gt)){const a=ge(o.replace(/[.,;:!?*_~]+$/,""),e);if(!(!a||r.has(a.noteID))&&!s.some(i=>Ze(i,a))&&(s.push(a),s.length===ht))return s.map(i=>i.url)}return s.map(n=>n.url)}async function Wt(e,t,r){const s=ge(r,t);if(!s||s.url!==r)return;const o=(await B(e)(t,A("query($id: NoteID!) { note(id: $id) { id url body author { username } } }"),{id:`gid://gitlab/Note/${s.noteID}`})).note;if(!o?.author||!o.url||o.id.match(Ht)?.[1]!==s.noteID)return;const a=ge(o.url,t);if(!(!a||!Ze(a,s)))return{url:s.url,username:o.author.username,body:o.body}}const Jt=4*6e4;function Kt(e){return{...e,comments:e.comments.filter(t=>t.automated?.reviewer==="GitLab Duo"&&t.automated.finding).map(t=>({...t,bot:!1}))}}function Qt(e,t){return e.comments.filter(s=>!s.resolved).every(s=>t-s.editedAt>=Jt&&(!s.automated?.status||["FINISHED","FAILED","STOPPED"].includes(s.automated.status)))}function Vt(e,t,r){const s={Authorization:`Bearer ${t}`,Origin:r},n=new WebSocket(e,{protocols:["actioncable-v1-json"],headers:s}),o=new AbortController;let a=!1,i=!1;const c={send:u=>n.send(u),close:()=>{o.abort(),n.close()},onmessage:null,onerror:null,onclose:null,onresponse:null};return n.onopen=()=>{a=!0},n.onmessage=({data:u})=>c.onmessage?.(String(u)),n.onclose=()=>{i||c.onclose?.()},n.onerror=async()=>{if(o.signal.aborted||i)return;if(a){c.onerror?.();return}i=!0;const u=new URL(e);u.protocol=u.protocol==="wss:"?"https:":"http:";try{const f=await fetch(u,{redirect:"manual",signal:AbortSignal.any([o.signal,AbortSignal.timeout(1e4)]),headers:{...s,Connection:"Upgrade",Upgrade:"websocket","Sec-WebSocket-Version":"13","Sec-WebSocket-Key":dt.randomBytes(16).toString("base64"),"Sec-WebSocket-Protocol":"actioncable-v1-json"}});try{o.signal.aborted||c.onresponse?.(f.status,f.headers)}finally{await f.body?.cancel()}}catch{o.signal.aborted||c.onerror?.()}},c}class Xt extends Error{constructor(t){super("Feedback subscription rate limited"),this.retryAt=t}retryAt}function Yt(e,t=Date.now()){const r=Date.parse(e.get("date")??""),s=Number.isFinite(r)?r:t,n=[],o=e.get("retry-after")?.trim();o&&(/^\d+$/.test(o)?n.push(Number(o)*1e3):/^[+-]?[\d.]+$/.test(o)||n.push(Date.parse(o)-s));for(const u of["ratelimit-reset","x-ratelimit-reset"]){const f=e.get(u)?.trim();f&&/^\d+$/.test(f)&&n.push(Number(f)*1e3-s)}const a=e.get("ratelimit-resettime");a&&n.push(Date.parse(a)-s);const i=n.filter(u=>Number.isFinite(u)&&u>=0);if(!i.length)return;const c=t+Math.max(...i);return Number.isSafeInteger(c)?c:void 0}async function Zt(e,t,r,s,n,o=Vt){const a=new URL(r.url);if(a.protocol!=="https:"||a.username||a.password||a.port)return;const i=a.pathname.match(/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/);if(!i||n.aborted)return;const c=await e("glab",["config","get","token","--host",a.hostname],t);if(n.aborted)return;if(c.code!==0||!c.stdout.trim())throw new Error("Subscription credentials unavailable");const u=await e("glab",["api",`projects/${encodeURIComponent(decodeURIComponent(i[1]))}/merge_requests/${i[2]}`,"--hostname",a.hostname],t);if(n.aborted)return;if(u.code!==0)throw new Error("Subscription target lookup failed");const f=JSON.parse(u.stdout);if(!Number.isSafeInteger(f.id)||!Number.isSafeInteger(f.project_id))throw new Error("Invalid subscription target");const m=JSON.stringify({channel:"Noteable::NotesChannel",project_id:f.project_id,noteable_type:"MergeRequest",noteable_id:f.id});await new Promise((g,E)=>{const $=o(`wss://${a.host}/-/cable`,c.stdout.trim(),a.origin);let w=!1,S=!1,I,x;const p=()=>{w||(w=!0,clearTimeout(x),n.removeEventListener("abort",p),$.onmessage=null,$.onerror=null,$.onclose=null,$.onresponse=null,$.close(),I?E(I):g())},y=()=>{clearTimeout(x),x=setTimeout(p,S?45e3:15e3)};y(),n.addEventListener("abort",p,{once:!0}),$.onerror=p,$.onclose=p,$.onresponse=(P,q)=>{P===429&&(I=new Xt(Yt(q)??Date.now()+6e4)),p()},$.onmessage=P=>{if(!w)try{const q=JSON.parse(String(P));if(S&&y(),q.type==="welcome"&&$.send(JSON.stringify({command:"subscribe",identifier:m})),q.type==="disconnect"&&p(),q.identifier!==m)return;q.type==="reject_subscription"&&p(),q.type==="confirm_subscription"&&!S&&(S=!0,y(),s.connected()),S&&q.message?.event==="updated"&&s.changed()}catch{p()}},n.aborted&&p()})}const et="pageInfo { hasNextPage endCursor } nodes { resolvable resolved }",tt=100,er=50,tr=10,rr="pageInfo { hasNextPage } nodes { id name allowFailure webPath stage { name } }",nr=new Set(["CHECKING","UNCHECKED","PREPARING"]),qe="CANNOT_BE_MERGED_RECHECK",rt=`
|
|
48
48
|
iid title webUrl state draft conflicts approved mergeStatusEnum detailedMergeStatus diffHeadSha updatedAt targetBranch sourceBranch
|
|
49
49
|
approvedBy(first: 100) { nodes { id bot } }
|
|
50
50
|
sourceProject { fullPath }
|
|
@@ -52,66 +52,66 @@
|
|
|
52
52
|
author { id }
|
|
53
53
|
headPipeline {
|
|
54
54
|
id status path detailedStatus { label }
|
|
55
|
-
jobs(statuses: [FAILED], retried: false, first: ${
|
|
55
|
+
jobs(statuses: [FAILED], retried: false, first: ${tr}) { ${rr} }
|
|
56
56
|
}
|
|
57
57
|
reviewers(first: 100) { nodes { id type username bot mergeRequestInteraction { reviewState approved } } }
|
|
58
|
-
discussions(first: ${
|
|
59
|
-
`;function
|
|
60
|
-
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { ${
|
|
58
|
+
discussions(first: ${tt}) { ${et} }
|
|
59
|
+
`;function sr(e){const t=Array.from({length:e},(s,n)=>`$p${n}: ID!`).join(", "),r=Array.from({length:e},(s,n)=>`p${n}: project(fullPath: $p${n}) {
|
|
60
|
+
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { ${rt} } }
|
|
61
61
|
}`).join(`
|
|
62
|
-
`);return
|
|
62
|
+
`);return A(`query($branch: String!, ${t}) {
|
|
63
63
|
${r}
|
|
64
|
-
}`)}function
|
|
65
|
-
`);return
|
|
64
|
+
}`)}function or(e){const t=Array.from({length:e},(s,n)=>`$p${n}: ID!`).join(", "),r=Array.from({length:e},(s,n)=>`p${n}: project(fullPath: $p${n}) { mergeRequest(iid: $iid) { ${rt} } }`).join(`
|
|
65
|
+
`);return A(`query($iid: String!, ${t}) {
|
|
66
66
|
${r}
|
|
67
|
-
}`)}function
|
|
67
|
+
}`)}function ir(e){const t=Array.from({length:e},(s,n)=>`$p${n}: ID!`).join(", "),r=Array.from({length:e},(s,n)=>`p${n}: project(fullPath: $p${n}) {
|
|
68
68
|
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { iid updatedAt sourceProject { fullPath } } }
|
|
69
69
|
}`).join(`
|
|
70
|
-
`);return
|
|
70
|
+
`);return A(`query($branch: String!, ${t}) {
|
|
71
71
|
${r}
|
|
72
|
-
}`)}const
|
|
72
|
+
}`)}const ar=A(`query($project: ID!, $iid: String!) {
|
|
73
73
|
project(fullPath: $project) { mergeRequest(iid: $iid) { sourceBranch } }
|
|
74
|
-
}`),
|
|
74
|
+
}`),cr=A(`query($project: ID!, $iid: String!, $after: String) {
|
|
75
75
|
project(fullPath: $project) {
|
|
76
|
-
mergeRequest(iid: $iid) { discussions(first: ${
|
|
76
|
+
mergeRequest(iid: $iid) { discussions(first: ${tt}, after: $after) { ${et} } }
|
|
77
77
|
}
|
|
78
|
-
}`);function
|
|
79
|
-
`)[0])}const
|
|
78
|
+
}`);function Q(e,t){const r=e.trim().replace(/^glab:\s*/,"")||`glab exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new O("missing-glab","glab is not installed"):/\b401\b|unauthori[sz]ed|not logged in|authenticate|invalid token|token.*expired/i.test(r)?new O("auth","GitLab authentication failed. Run `glab auth status`."):/\b429\b|rate limit|too many requests/i.test(r)?new O("rate-limit","GitLab rate limit reached"):new O("request",r.split(`
|
|
79
|
+
`)[0])}const lr=e=>typeof e=="object"&&e!==null&&(!("errors"in e)||Array.isArray(e.errors))&&(!("data"in e)||typeof e.data=="object");function z(e,t){return async(r,s,n)=>{const o=["api","graphql","--hostname",r,"-f",`query=${s}`];for(const[c,u]of Object.entries(n))o.push("-f",`${c}=${u}`);const a=await e("glab",o,t);let i;try{i=JSON.parse(a.stdout)}catch{throw Q(a.stderr,a.code)}if(!lr(i))throw Q(a.stderr||"Unexpected GitLab response",a.code);if(i.errors?.length)throw Q(String(i.errors[0]?.message??""),a.code);if(a.code!==0)throw Q(a.stderr,a.code);if(!i.data)throw Q("GitLab returned no data",a.code);return i.data}}const Le=e=>e.nodes.filter(t=>t.resolvable&&!t.resolved).length,G={kind:"gitlab",noun:"MR",ci:"pipeline",recognizes:e=>/(^|\.)gitlab\./.test(e),open:(e,t)=>new hr(z(e,t)),owns:Ke("gitlab"),parseUrl:e=>fe("gitlab",e,/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/),parseIssueUrl:e=>fe("gitlab",e,/^\/(.+)\/-\/(?:issues|work_items)\/([1-9]\d*)\/?$/),reference:e=>`!${e}`,issueReference:e=>`#${e}`,titleReferences:e=>Qe(e,"!"),indicators:()=>[],details(e){const t=e.approvalRequirementsSatisfied===null?"unknown":W(e.approvalRequirementsSatisfied),r=[`Human approvals: ${W(e.hasApprovals)} · Approval requirements satisfied: ${t}`];return e.mergeStatus&&r.push(`Merge status: ${he(e.mergeStatus)}`),r},automatedReview:{publishedFeedback:{storageKey:"duo",select:Kt,ready:Qt},name:"GitLab Duo",status(e){const t=e.duoReviewState;if(t)return{state:fr(t),label:he(t)}}},feedback:{async viewerID(e,t,r){return(await B(z(e,t))(r,A("query { currentUser { id } }"),{})).currentUser?.id},async reviewerID(e,t,r,s){const n=await B(z(e,t))(r,A("query($username: String!) { user(username: $username) { id username } }"),{username:s});return n.user?.username.toLowerCase()===s.toLowerCase()?n.user.id:void 0},subscribe:Zt,async fetch(e,t,r){const s=G.parseUrl(r.url);return s?Lt(z(e,t),s.host,s.project,s.iid):void 0},async details(e,t,r,s){const n=G.parseUrl(r.url);return n?Mt(z(e,t),n.host,n.project,s):[]},commentID:e=>e.match(/#note_(\d+)$/)?.[1],linkedNotes(e,t){const r=G.parseUrl(e.url);return r?zt(r.host,t):[]},async linkedNote(e,t,r,s){const n=G.parseUrl(r.url);return n?Wt(z(e,t),n.host,s):void 0}}},ur=new Set(["REVIEWED","REQUESTED_CHANGES"]);function dr(e,t){return!t.id||!t.jobs?{}:{id:t.id,failedJobs:pr(e,t.jobs.nodes),failedJobsComplete:!t.jobs.pageInfo?.hasNextPage}}function pr(e,t){return t.flatMap(r=>!r.allowFailure&&r.name?[{...r.id?{id:r.id}:{},name:r.name,...r.webPath?{url:`https://${e}${r.webPath}`}:{},...r.stage?.name?{stage:r.stage.name}:{}}]:[])}function fr(e){return e==="REVIEW_STARTED"?"running":ur.has(e)?"feedback":"settled"}class hr{traits=G;graphql;constructor(t){this.graphql=B(t)}async findByBranch(t){const{source:r,targets:s,sourceBranch:n}=t,o={branch:n};s.forEach((m,g)=>o[`p${g}`]=m.path);const a=await this.graphql(r.host,sr(s.length),o),i=r.path.toLowerCase(),c=new Set,u=[];return s.forEach((m,g)=>{for(const E of a[`p${g}`]?.mergeRequests?.nodes??[]){if(E.sourceProject?.fullPath.toLowerCase()!==i)continue;const $=`${E.targetProject.fullPath}!${E.iid}`;c.has($)||(c.add($),u.push(E))}}),(await Promise.all(u.map(m=>this.normalize(r.host,m)))).sort((m,g)=>(g.updatedAt??"").localeCompare(m.updatedAt??""))}async findNumberByBranch(t){const{source:r,targets:s,sourceBranch:n}=t,o={branch:n};s.forEach((u,f)=>o[`p${f}`]=u.path);const a=await this.graphql(r.host,ir(s.length),o),i=r.path.toLowerCase();return s.flatMap((u,f)=>a[`p${f}`]?.mergeRequests?.nodes??[]).filter(u=>u.sourceProject?.fullPath.toLowerCase()===i).sort((u,f)=>(f.updatedAt??"").localeCompare(u.updatedAt??""))[0]?.iid}async sourceBranch(t){const s=(await this.graphql(t.host,ar,{project:t.project,iid:t.iid})).project?.mergeRequest?.sourceBranch;return typeof s=="string"&&s?s:void 0}async findByNumber(t,r){if(t.length===0)return;const s=t[0].host,n={iid:r};t.forEach((a,i)=>n[`p${i}`]=a.path);const o=await this.graphql(s,or(t.length),n);for(let a=0;a<t.length;a++){const i=o[`p${a}`]?.mergeRequest;if(i)return this.normalize(s,i)}}async unresolvedThreads(t,r){let s=Le(r.discussions),n=r.discussions.pageInfo,o=1;for(;n.hasNextPage&&n.endCursor&&o<er;){const i=(await this.graphql(t,cr,{project:r.targetProject.fullPath,iid:r.iid,after:n.endCursor})).project?.mergeRequest?.discussions;if(!i)break;s+=Le(i),n=i.pageInfo,o++}return{count:s,complete:!n.hasNextPage}}async normalize(t,r){const s=await this.unresolvedThreads(t,r),n=r.headPipeline,o=(r.approvedBy?.nodes??[]).some(i=>i.bot!==!0),a=(r.reviewers?.nodes??[]).filter(i=>i.bot!==!0&&i.username&&i.mergeRequestInteraction?.approved!==!0).map(i=>i.username);return{forge:"gitlab",iid:r.iid,title:r.title,url:r.webUrl,state:r.state.toLowerCase(),draft:r.draft,conflicts:r.conflicts||r.mergeStatusEnum===qe,conflictsKnown:r.mergeStatusEnum!==qe&&!nr.has(r.detailedMergeStatus??""),approved:r.approved===!0&&o&&a.length===0,hasApprovals:o,approvalRequirementsSatisfied:r.approved,awaitingReviewers:a,reviewersComplete:!0,reviewerIDs:(r.reviewers?.nodes??[]).flatMap(i=>i.id??[]),mergeStatus:r.detailedMergeStatus??void 0,targetProject:r.targetProject.fullPath,targetBranch:r.targetBranch,...r.sourceProject?{sourceProject:r.sourceProject.fullPath}:{},sourceBranch:r.sourceBranch,headSha:r.diffHeadSha??void 0,...r.author?.id?{authorID:r.author.id}:{},updatedAt:r.updatedAt??void 0,pipeline:n?{status:n.status,label:n.detailedStatus?.label??n.status.toLowerCase().replace(/_/g," "),url:n.path?`https://${t}${n.path}`:void 0,...dr(t,n)}:void 0,unresolvedThreads:s.count,threadsComplete:s.complete,duoReviewState:r.reviewers?.nodes.find(i=>i.type==="DUO_CODE_REVIEW_BOT")?.mergeRequestInteraction?.reviewState??void 0}}}const mr="copilot-pull-request-reviewer[bot]",Oe=`number title url state isDraft mergeable reviewDecision headRefOid headRefName
|
|
80
80
|
headRepository { nameWithOwner } baseRepository { nameWithOwner } baseRefName updatedAt
|
|
81
81
|
author { ... on User { id } ... on Bot { id } }
|
|
82
82
|
reviewThreads(first:100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
83
83
|
reviewRequests(first:100) { nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { login } ... on Team { name } } } pageInfo { hasNextPage endCursor } }
|
|
84
84
|
latestReviews(first:100) { nodes { author { ... on User { id } } } }
|
|
85
|
-
copilotReviews: reviews(last:1, author:"${
|
|
85
|
+
copilotReviews: reviews(last:1, author:"${mr}", states:[COMMENTED,CHANGES_REQUESTED,APPROVED,DISMISSED]) { nodes { id state comments { totalCount } } }
|
|
86
86
|
commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
|
|
87
|
-
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl } ... on StatusContext { id context state targetUrl } }
|
|
87
|
+
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } }
|
|
88
88
|
pageInfo { hasNextPage endCursor }
|
|
89
|
-
} } } } }`,te=50;function re(e,t){return async(r,s,n)=>{const o=["api","graphql","--hostname",r,"-f",`query=${s}`];for(const[
|
|
90
|
-
`)[0])}const
|
|
89
|
+
} } } } }`,te=50;function re(e,t){return async(r,s,n)=>{const o=["api","graphql","--hostname",r,"-f",`query=${s}`];for(const[u,f]of Object.entries(n))o.push(typeof f=="number"?"-F":"-f",`${u}=${f}`);const a=await e("gh",o,t);let i;try{i=JSON.parse(a.stdout)}catch{throw Ue(a.stderr,a.code)}const c=(i.errors??[]).filter(u=>u.type!=="NOT_FOUND");if(!i.data||c.length||a.code!==0&&!i.errors?.length)throw Ue(c[0]?.message??a.stderr,a.code);return i.data}}function Ue(e,t){const r=e.trim()||`gh exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new O("missing-gh","gh is not installed"):/401|unauthori[sz]ed|authenticate|not logged|token.*expired/i.test(r)?new O("auth","GitHub authentication failed. Run `gh auth status`."):/429|rate limit|too many requests/i.test(r)?new O("rate-limit","GitHub rate limit reached"):new O("request",r.split(`
|
|
90
|
+
`)[0])}const gr=["FAILURE","ERROR","TIMED_OUT","ACTION_REQUIRED","STARTUP_FAILURE"],wr=["SUCCESS","NEUTRAL","SKIPPED","FAILURE","TIMED_OUT","CANCELLED","ACTION_REQUIRED","STARTUP_FAILURE","STALE"],br=["SUCCESS","FAILURE","ERROR","PENDING","EXPECTED"],Me=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]),we=e=>Date.parse(e.checkSuite?.createdAt??""),je=(e,t)=>we(e)>we(t);function vr(e,t,r,s){const n=new Map;for(const w of e){const S=we(w),I=Me(w);if(!I||!Number.isFinite(S))continue;const x=n.get(I);(!x||je(w,x))&&n.set(I,w)}e=e.filter(w=>{const S=Me(w),I=S&&n.get(S);return!I||!je(I,w)});const o=w=>`${w} check${w===1?"":"s"}`,a=e.filter(w=>w.conclusion==="CANCELLED").length,i=e.filter(w=>w.conclusion==="STALE").length,c=[...a?[`${o(a)} cancelled`]:[],...i?[`${o(i)} stale`]:[]],u=e.filter(w=>gr.includes(w.conclusion??w.state??"")),f=u.length,m=s?{id:s,failedJobs:u.flatMap(w=>{const S=w.name??w.context,I=w.detailsUrl??w.targetUrl;return S?[{...w.id?{id:w.id}:{},name:S,...I?{url:I}:{}}]:[]}),failedJobsComplete:t}:{},g=e.filter(w=>w.status?w.status!=="COMPLETED":["PENDING","EXPECTED"].includes(w.state??"")).length,E=e.some(w=>w.status==="COMPLETED"?!wr.includes(w.conclusion??""):!w.status&&!br.includes(w.state??""));return f?{status:"FAILED",label:[`${o(f)} failed`,...c,...g?[`${o(g)} pending`]:[]].join(", ")+(t?"":" (partial)"),url:r,...m,running:g>0}:g||!t||E?{status:"PENDING",label:[...c,g?`${o(g)} pending`:"unknown"].join(", ")+(t?"":" (partial)"),url:r,...m}:a||i?{status:"CANCELLED",label:c.join(", "),url:r,...m}:{status:"SUCCESS",label:[["SUCCESS","passed"],["SKIPPED","skipped"],["NEUTRAL","neutral"]].flatMap(([w,S])=>{const I=e.filter(x=>(x.conclusion??x.state)===w).length;return I?[`${o(I)} ${S}`]:[]}).join(", ")||"0 checks",url:r,...m}}function Be(e,t){const r=fe("github",e,t);return r&&!G.recognizes(r.host)?r:void 0}const ae={kind:"github",noun:"PR",ci:"checks",recognizes:()=>!1,open:(e,t)=>new Cr(re(e,t)),owns:Ke("github"),parseUrl:e=>Be(e,/^\/([^/]+\/[^/]+)\/pull\/([1-9]\d*)\/?$/),parseIssueUrl:e=>Be(e,/^\/([^/]+\/[^/]+)\/issues\/([1-9]\d*)\/?$/),reference:e=>`#${e}`,issueReference:e=>`#${e}`,titleReferences:e=>Qe(e,"#"),indicators:e=>e.reviewDecision==="CHANGES_REQUESTED"?[{text:"changes requested",tone:"warning",essential:!0}]:[],details:e=>[`Review decision: ${e.reviewDecision?he(e.reviewDecision):"not reported"}`],automatedReview:{name:"GitHub Copilot",status:e=>$r(e.copilotReview)},feedback:{async viewerID(e,t,r){return(await B(re(e,t))(r,A("query { viewer { id } }"),{})).viewer?.id},async reviewerID(e,t,r,s){const n=await e("gh",["api","--hostname",r,`users/${encodeURIComponent(s)}`],t);if(n.code!==0)throw new Error("Could not resolve the GitHub reviewer account");const o=JSON.parse(n.stdout);return o.login?.toLowerCase()===s.toLowerCase()?o.node_id:void 0},async fetch(e,t,r){const s=ae.parseUrl(r.url);return s?Nt(re(e,t),s.host,s.project,s.iid):void 0},async details(e,t,r,s){const n=ae.parseUrl(r.url);return n?_t(re(e,t),n.host,s):[]}}};function $r(e){if(!e)return;const t=e.comments>0&&!e.dismissed,r=e.dismissed?"dismissed":t?"commented":"no comments",s=e.reviewID?{id:e.reviewID,feedback:t,label:r}:void 0;if(e.requested)return{state:"running",label:"reviewing",completed:s};if(s)return{state:t?"feedback":"settled",label:r,completed:s}}const yr=e=>/^copilot-pull-request-reviewer(\[bot\])?$/i.test(e??"");function Sr(e){const t=e.reviewRequests.nodes.some(s=>yr(s.requestedReviewer?.login)),r=e.copilotReviews?.nodes?.find(s=>s);if(!(!t&&!r))return{requested:t,reviewID:r?.id,comments:r?.comments.totalCount??0,...r?.state==="DISMISSED"?{dismissed:!0}:{}}}class Cr{traits=ae;graphql;constructor(t){this.graphql=B(t)}async findByNumber(t,r){for(const s of t){const[n,o]=s.path.split("/"),i=(await this.graphql(s.host,A(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
91
91
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${Oe} } }
|
|
92
|
-
}`),{owner:n,repo:o,number:Number(r)})).repository?.pullRequest;if(
|
|
92
|
+
}`),{owner:n,repo:o,number:Number(r)})).repository?.pullRequest;if(i)return this.normalize(s.host,i)}}async findNumberByBranch(t){let r;for(const s of t.targets){const[n,o]=s.path.split("/"),i=(await this.graphql(s.host,A(`query($owner:String!,$repo:String!,$branch:String!) {
|
|
93
93
|
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch,orderBy:{field:UPDATED_AT,direction:DESC}) {
|
|
94
94
|
nodes { number updatedAt headRepository { nameWithOwner } }
|
|
95
|
-
} } }`),{owner:n,repo:o,branch:t.sourceBranch})).repository?.pullRequests?.nodes??[];for(const c of
|
|
95
|
+
} } }`),{owner:n,repo:o,branch:t.sourceBranch})).repository?.pullRequests?.nodes??[];for(const c of i)c.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(!r||c.updatedAt>r.updatedAt)&&(r=c)}return r?String(r.number):void 0}async sourceBranch(t){const[r,s]=t.project.split("/");return(await this.graphql(t.host,A(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
96
96
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { headRefName } }
|
|
97
|
-
}`),{owner:r,repo:s,number:Number(t.iid)})).repository?.pullRequest?.headRefName||void 0}async findByBranch(t){const r=new Map;for(const s of t.targets){const[n,o]=s.path.split("/");let i
|
|
98
|
-
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${
|
|
97
|
+
}`),{owner:r,repo:s,number:Number(t.iid)})).repository?.pullRequest?.headRefName||void 0}async findByBranch(t){const r=new Map;for(const s of t.targets){const[n,o]=s.path.split("/");let a,i=!1;for(let c=0;c<te;c++){const f=(await this.graphql(s.host,A(`query($owner:String!,$repo:String!,$branch:String!${a?",$after:String!":""}) {
|
|
98
|
+
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${a?",after:$after":""}) {
|
|
99
99
|
nodes { ${Oe} } pageInfo { hasNextPage endCursor }
|
|
100
|
-
} } }`),{owner:n,repo:o,branch:t.sourceBranch,...
|
|
100
|
+
} } }`),{owner:n,repo:o,branch:t.sourceBranch,...a?{after:a}:{}})).repository?.pullRequests;if(!f)throw new O("request","GitHub repository unavailable");for(const m of f.nodes)m.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(r.has(m.url)||r.set(m.url,await this.normalize(s.host,m)));if(!f.pageInfo?.hasNextPage){i=!0;break}if(a=f.pageInfo.endCursor,!a)break}if(!i)throw new O("request","GitHub PR discovery exceeded its pagination limit")}return[...r.values()].sort((s,n)=>(n.updatedAt??"").localeCompare(s.updatedAt??""))}async threads(t,r){const[s,n]=r.baseRepository.nameWithOwner.split("/"),o=[...r.reviewThreads.nodes];let a=r.reviewThreads.pageInfo;for(let i=1;a?.hasNextPage&&a.endCursor&&i<te;i++){const u=(await this.graphql(t,A(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
101
101
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
102
102
|
reviewThreads(first:100,after:$after) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
103
|
-
} } }`),{owner:s,repo:n,number:r.number,after:
|
|
103
|
+
} } }`),{owner:s,repo:n,number:r.number,after:a.endCursor})).repository?.pullRequest?.reviewThreads;if(!u)break;o.push(...u.nodes),a=u.pageInfo}return{unresolved:o.filter(i=>!i.isResolved).length,complete:!a?.hasNextPage}}async contexts(t,r){const[s,n]=r.baseRepository.nameWithOwner.split("/"),o=r.commits.nodes[0]?.commit.statusCheckRollup?.contexts,a=[...o?.nodes??[]];let i=o?.pageInfo;for(let c=1;i?.hasNextPage&&i.endCursor&&c<te;c++){const f=(await this.graphql(t,A(`query($owner:String!,$repo:String!,$oid:GitObjectID!,$after:String!) {
|
|
104
104
|
repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
|
|
105
|
-
contexts(first:100,after:$after) { nodes { __typename ... on CheckRun { id name status conclusion detailsUrl } ... on StatusContext { id context state targetUrl } } pageInfo { hasNextPage endCursor } }
|
|
106
|
-
} } } } }`),{owner:s,repo:n,oid:r.headRefOid,after:
|
|
105
|
+
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 } }
|
|
106
|
+
} } } } }`),{owner:s,repo:n,oid:r.headRefOid,after:i.endCursor})).repository?.object?.statusCheckRollup?.contexts;if(!f)break;a.push(...f.nodes),i=f.pageInfo}return{nodes:a,complete:!i?.hasNextPage}}async reviewers(t,r){const s=[...r.reviewRequests.nodes];let n=r.reviewRequests.pageInfo;for(let o=1;n?.hasNextPage&&o<te;o++){if(!n.endCursor)throw new O("request","GitHub reviewer pagination cursor missing");const[a,i]=r.baseRepository.nameWithOwner.split("/"),u=(await this.graphql(t,A(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
107
107
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
108
108
|
reviewRequests(first:100,after:$after) {
|
|
109
109
|
nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { login } ... on Team { name } } }
|
|
110
110
|
pageInfo { hasNextPage endCursor }
|
|
111
111
|
}
|
|
112
112
|
} }
|
|
113
|
-
}`),{owner:i,repo:a,number:r.number,after:n.endCursor})).repository?.pullRequest?.reviewRequests;if(!d)throw new x("request","GitHub reviewers unavailable");s.push(...d.nodes),n=d.pageInfo}if(n?.hasNextPage)throw new x("request","GitHub reviewers exceeded the pagination limit");return{nodes:s,pageInfo:n}}async normalize(t,r){const s=await this.reviewers(t,r),[n,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:vr({...r,reviewRequests:s}),awaitingReviewers:s.nodes.flatMap(i=>{const a=i.requestedReviewer;return a?.__typename==="Bot"?[]:a?.login?[a.login]:a?.name?[a.name]:[]}),reviewersComplete:!s.pageInfo?.hasNextPage,reviewerIDs:[...new Set([...s.nodes.flatMap(i=>i.requestedReviewer?.__typename==="User"?i.requestedReviewer.id??[]:[]),...(r.latestReviews?.nodes??[]).flatMap(i=>i?.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?gr(o.nodes,o.complete,`${r.url}/checks`,r.headRefOid):void 0,unresolvedThreads:n.unresolved,threadsComplete:n.complete}}}const yr={gitlab:G,github:ae},F=e=>yr[e.forge],ce=e=>F(e).reference(e.iid);function le(e){const t=F(e).automatedReview,r=t?.status(e);return t&&r?{name:t.name,...r}:void 0}const Me={url:{type:"string"},issueUrl:{type:"string"}},je={type:"object",properties:{...Me,targets:{type:"array",items:{type:"object",properties:Me,required:["url"],additionalProperties:!1}}},additionalProperties:!1},ne={type:"string"},we={type:"object",title:"Snapshot"},V={type:"object",title:"InboxState"},Sr={type:"object",properties:{enabled:{type:"boolean"},snapshot:we},required:["enabled","snapshot"],additionalProperties:!1},Cr={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:V},acknowledgeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:V},summarizeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:V},pauseFeedback:{input:{type:"object",properties:{paused:{type:"boolean"}},required:["paused"],additionalProperties:!1},output:V},actOnFeedback:{input:{type:"object",properties:{id:{type:"string"},retry:{type:"boolean"}},required:["id"],additionalProperties:!1},output:V},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:ne},visible:ne},required:["clientID","keys"],additionalProperties:!1},output:{type:"object",properties:{enabled:{type:"boolean"},statuses:{type:"object",additionalProperties:we}},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:Sr}},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:ne,snapshot:we},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}}}},Rr="",et=6e4,Be=(e,t)=>e.directory===t.directory&&e.key===t.key,X=e=>JSON.stringify([e.directory,e.key]);function Er(e){const t=e.now??Date.now,r=e.setTimer??((p,$)=>setTimeout(p,$)),s=e.clearTimer??(p=>clearTimeout(p)),n=e.defer??queueMicrotask,o=new Map,i=new Map,a=new Map;let c,d=!1;const m=p=>i.get(p.directory)?.has(p.key)===!0;function f(p,$){const E=X(p);($.revision??-1)>=(o.get(E)?.revision??-1)&&o.set(E,$)}function g(p,$){const A={kind:"request",message:`PR/MR status service unavailable: ${$ instanceof Error?$.message:String($)}`,at:t()};for(const H of i.get(p)??[]){const U=X({directory:p,key:H});o.set(U,{...o.get(U)??{},loading:!1,error:A})}e.onChange()}const S=new Map,v=new Map;function q(p){const $=(S.get(p)??0)+1;S.set(p,$);const E=v.get(p);E!==void 0&&s(E),v.set(p,r(()=>{_(p)},Math.min(et,1e3*2**$)))}async function _(p){if(d)return;const $=v.get(p);$!==void 0&&s($),v.delete(p);const E=[...i.get(p)??[]];try{const A=await e.watch(p,{clientID:e.clientID,keys:E,...c?.directory===p?{visible:c.key}:{}});if(d)return;S.delete(p),a.set(p,A.enabled);for(const[H,U]of Object.entries(A.statuses))m({directory:p,key:H})&&f({directory:p,key:H},U);e.onChange()}catch(A){if(d)return;g(p,A),q(p)}}const L=new Set;function O(p){L.has(p)||(L.add(p),n(()=>{L.delete(p),_(p)}))}return{snapshot:p=>o.get(X(p))??{loading:!1},enabled:p=>a.get(p)??!0,show(p){if(p.key!==Rr)for(const[E,A]of i)E===p.directory||!A.delete(p.key)||(o.delete(X({directory:E,key:p.key})),c&&Be(c,{directory:E,key:p.key})&&(c=void 0),O(E));const $=i.get(p.directory)??new Set;i.set(p.directory,$),$.add(p.key),c=p,O(p.directory)},hide(p){c&&Be(c,p)&&(c=void 0),O(p.directory)},async refresh(p){const $=X(p);o.set($,{...o.get($)??{},loading:!0}),e.onChange();try{const E=await e.refresh(p.directory,p.key);if(d)return;a.set(p.directory,E.enabled),f(p,E.snapshot),e.onChange()}catch(E){if(d)return;g(p.directory,E)}},heartbeat(){for(const p of i.keys())_(p)},receive(p,$,E){m({directory:p,key:$})&&(f({directory:p,key:$},E),e.onChange())},hasShown:p=>[...i.values()].some($=>$.has(p)),dispose(){d=!0;for(const p of v.values())s(p);for(const p of i.keys())e.release(p,e.clientID).catch(()=>{})}}}const oe=e=>({location:{directory:e}}),Ir=async(e,t)=>await e.feedback({},oe(t));function kr(e){let t,r=0;const s=new Map;let n;return{get client(){return t?.client},connect(o){t?.dispose(),t=_r(o,{...e,clientID:`${e.clientID}:${++r}`});for(const i of s.values())t.client.show(i),t.client.hide(i);n&&t.client.show(n),e.onChange()},show(o){s.set(o.key,o),n=o,t?.client.show(o)},hide(o){n?.key===o.key&&n.directory===o.directory&&(n=void 0),t?.client.hide(o)},dispose(){t?.dispose(),t=void 0}}}function Pr(e){const t=new Map;let r=0;const s=async n=>{const o=(t.get(n)??0)+1;t.set(n,o);const i=r,a=()=>i===r&&t.get(n)===o;try{const c=await e.load(n);a()&&e.changed(n,c)}catch(c){a()&&e.failed(n,c instanceof Error?c.message:String(c))}};return{reload:s,has:n=>t.has(n),refresh:()=>Promise.all([...t.keys()].map(s)),invalidate(){r++}}}function _r(e,t){const r=e,s=Er({clientID:t.clientID,watch:async(i,a)=>await r.watch(a,oe(i)),refresh:async(i,a)=>await r.refresh({key:a},oe(i)),release:(i,a)=>r.release({clientID:a},oe(i)),onChange:t.onChange}),n=setInterval(()=>{s.heartbeat(),t.heartbeat?.()},et),o=e.events.on("status",i=>{const{directory:a,key:c,snapshot:d}=i.data;s.receive(a,c,d)});return{client:s,dispose(){clearInterval(n),o(),s.dispose()}}}const Nr=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,Fe=e=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),Dr=e=>e.postedAt!==void 0?`Latest comment: ${Fe(e.postedAt)}`:`Detected: ${Fe(e.at)}`;function Ar(e,t){const r=e.items.filter(s=>s.sessionID===t).length;if(!(!t||r===0))return`${r} review update${r===1?"":"s"}${e.paused?" (paused)":""}`}function Tr(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=Tr(e),r=t.filter(n=>n!==e.url),s=e.kind==="ci-failed";return[...r.map((n,o)=>({title:`${s?"Failed job":"Comment"} ${r.length>1?`${o+1} of ${r.length} `:""}(${s?new URL(n).pathname.split("/").filter(Boolean).slice(-2).join("/"):new URL(n).hash||"no anchor"})`,description:n,value:n})),...t.includes(e.url)?[{title:"PR/MR overview",description:e.url,value:e.url}]:[]]}const Lr=new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SCHEDULED","WAITING_FOR_CALLBACK","CANCELING"]);function Re(e){return e?e.status==="FAILED"?"error":e.status==="SUCCESS"?e.label.includes("warning")?"warning":"success":Lr.has(e.status)?"warning":"muted":"muted"}const tt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Or=e=>e.charAt(0).toUpperCase()+e.slice(1),xr={success:"CI ✓",error:"CI ✗",warning:"CI …"};function Ur(e){return e.length>2?`awaiting ${e.length} reviewers`:`awaiting ${e.map(t=>`@${t}`).join(", ")}`}function Mr(e){return`${e.unresolvedThreads}${e.threadsComplete?"":"+"} unresolved thread${e.unresolvedThreads===1&&e.threadsComplete?"":"s"}`}const de=e=>({text:ce(e),tone:"muted",url:e.url,essential:!0});function jr(e){const t=Re(e.pipeline);return e.pipeline?{text:`CI ${e.pipeline.label}`,compact:xr[t],tone:t,url:e.pipeline.url}:{text:`no ${F(e).ci}`,compact:"no CI",tone:t}}function Br(e){const t=new Set(e.map(g=>F(g).noun)),r=t.size===1?[...t][0]:"PR/MR",s=e.length===1?`1 ${r}`:`${e.length} ${r==="PR/MR"?"PRs/MRs":`${r}s`}`,n=e.filter(g=>g.state==="opened"),o=[{text:s,tone:"muted",essential:!0}],i=n.filter(g=>le(g)?.state==="running").length;i&&o.push({text:`🤖 ${i} reviewing`,compact:`🤖 ${i}`,tone:"warning",essential:!0});const a=n.filter(g=>Re(g.pipeline)==="error").length;a&&o.push({text:`${a} CI failed`,compact:`CI ✗ ${a}`,tone:"error"});const c=n.filter(g=>g.conflicts).length;c&&o.push({text:tt(c,"conflict"),tone:"error",essential:!0});const d=n.filter(g=>g.approved&&g.awaitingReviewers.length===0).length;d&&o.push({text:`${d} approved`,tone:"success"});const m=e.filter(g=>g.state==="merged").length;m&&o.push({text:`${m} merged`,tone:"success"});const f=e.length-n.length-m;return f&&o.push({text:`${f} closed`,tone:"muted"}),o}function Fr(e){const{lookup:t,error:r}=e,s=r?[{text:"stale",tone:"warning",essential:!0}]:[];if(!t||t.kind==="none"||t.requests.length===0)return e.targeted&&(r||t?.explicitTarget)?[{text:"PR/MR status unavailable",tone:"warning"}]:[];t.failed?.length&&s.unshift({text:`${t.failed.length} unavailable`,tone:"warning",essential:!0});const n=t.requests;if(t.explicitTarget&&n.length>1)return[...Br(n),...s];if(n.length>1){const a=F(n[0]).noun;return[...n.map(de),{text:`${tt(n.length,`open ${a}`)}, run /${a.toLowerCase()}-status`,tone:"warning"},...s]}const[o]=n;if(o.state!=="opened")return[de(o),{text:o.state,tone:o.state==="merged"?"success":"muted",essential:!0},...s];const i=[de(o),jr(o)];if(o.unresolvedThreads>0||!o.threadsComplete){const a=Mr(o);i.push({text:a,compact:a.replace("unresolved ",""),tone:"warning"})}return le(o)?.state==="running"&&i.push({text:"🤖 reviewing",compact:"🤖",tone:"warning",essential:!0}),i.push(...F(o).indicators(o)),o.conflicts&&i.push({text:"conflicts",tone:"error",essential:!0}),o.conflictsKnown||i.push({text:"mergeability unknown",tone:"muted"}),o.awaitingReviewers.length?i.push({text:Ur(o.awaitingReviewers),tone:"muted"}):o.approved&&i.push({text:"approved",tone:"success"}),[...i,...s]}const Ge=e=>new Date(e).toLocaleTimeString();function Gr(e,t){const r=F(e),s=[`${ce(e)} ${e.title}${e.state==="opened"?"":` (${e.state})`}`,`Target: ${e.targetProject} → ${e.targetBranch}`,`${Or(r.ci)}: ${e.pipeline?e.pipeline.label:"none"}${e.pipeline?.url?` (${e.pipeline.url})`:""}`,`Unresolved threads: ${e.unresolvedThreads}${e.threadsComplete?"":"+"}`,`Draft: ${W(e.draft)} · Conflicts: ${e.conflictsKnown?W(e.conflicts):"unknown"}`,...r.details(e)],n=le(e);return n&&s.push(`${n.name} review: ${n.label}`),e.awaitingReviewers.length&&s.push(`Awaiting review: ${e.awaitingReviewers.map(o=>`@${o}`).join(", ")}`),e.reviewersComplete||s.push("Reviewer list is partial"),t&&e.headSha&&t!==e.headSha&&s.push(`Local HEAD differs from the ${r.noun} head commit (unpushed or not fetched)`),s.push(e.url),s}function Hr(e){const{lookup:t,error:r,fetchedAt:s}=e,n=[];if(!t)n.push(r?"Could not look up the PR/MR.":"No data yet.");else if(t.kind==="none")n.push(`No PR/MR lookup: ${t.reason}.`);else{const{repository:o,sessionTarget:i,requests:a}=t;if(o){const c=o.branch===o.sourceBranch?o.branch:`${o.branch} (pushes to ${o.sourceBranch})`;n.push(`Branch: ${c} in ${o.source.path}`),a.length===0&&n.push("","No open PR/MR for this branch.")}else i&&n.push(`Session target: ${i}`);for(const{url:c,reason:d}of t.failed??[])n.push(`Unavailable: ${c} (${d})`);for(const c of a)n.push("",...Gr(c,o?.head??""))}return r&&n.push("",`Last refresh failed at ${Ge(r.at)}: ${r.message}`),s!==void 0&&n.push("",`Last fetched: ${Ge(s)}`),n.join(`
|
|
114
|
-
`)}function zr(e,t){const{sessionID:r}=e;r&&!t.hasShown(r)||(r&&e.variant==="info"&&t.openTab(r),t.toast({...e.title?{title:e.title}:{},message:e.message,variant:e.variant}))}var
|
|
113
|
+
}`),{owner:a,repo:i,number:r.number,after:n.endCursor})).repository?.pullRequest?.reviewRequests;if(!u)throw new O("request","GitHub reviewers unavailable");s.push(...u.nodes),n=u.pageInfo}if(n?.hasNextPage)throw new O("request","GitHub reviewers exceeded the pagination limit");return{nodes:s,pageInfo:n}}async normalize(t,r){const s=await this.reviewers(t,r),[n,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:Sr({...r,reviewRequests:s}),awaitingReviewers:s.nodes.flatMap(a=>{const i=a.requestedReviewer;return i?.__typename==="Bot"?[]:i?.login?[i.login]:i?.name?[i.name]:[]}),reviewersComplete:!s.pageInfo?.hasNextPage,reviewerIDs:[...new Set([...s.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?vr(o.nodes,o.complete,`${r.url}/checks`,r.headRefOid):void 0,unresolvedThreads:n.unresolved,threadsComplete:n.complete}}}const Rr={gitlab:G,github:ae},F=e=>Rr[e.forge],ce=e=>F(e).reference(e.iid);function le(e){const t=F(e).automatedReview,r=t?.status(e);return t&&r?{name:t.name,...r}:void 0}const Fe={url:{type:"string"},issueUrl:{type:"string"}},Ge={type:"object",properties:{...Fe,targets:{type:"array",items:{type:"object",properties:Fe,required:["url"],additionalProperties:!1}}},additionalProperties:!1},ne={type:"string"},be={type:"object",title:"Snapshot"},V={type:"object",title:"InboxState"},kr={type:"object",properties:{enabled:{type:"boolean"},snapshot:be},required:["enabled","snapshot"],additionalProperties:!1},Er={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:V},acknowledgeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:V},summarizeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:V},pauseFeedback:{input:{type:"object",properties:{paused:{type:"boolean"}},required:["paused"],additionalProperties:!1},output:V},actOnFeedback:{input:{type:"object",properties:{id:{type:"string"},retry:{type:"boolean"}},required:["id"],additionalProperties:!1},output:V},target:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:Ge},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:be}},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:kr}},events:{feedbackChanged:{schema:{type:"object",properties:{directory:{type:"string"}},required:["directory"],additionalProperties:!1}},targetChanged:{schema:{type:"object",properties:{sessionID:{type:"string"},...Ge.properties},required:["sessionID"],additionalProperties:!1}},status:{schema:{type:"object",properties:{directory:{type:"string"},key:ne,snapshot:be},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}}}},Ir="",nt=6e4,He=(e,t)=>e.directory===t.directory&&e.key===t.key,X=e=>JSON.stringify([e.directory,e.key]);function Pr(e){const t=e.now??Date.now,r=e.setTimer??((p,y)=>setTimeout(p,y)),s=e.clearTimer??(p=>clearTimeout(p)),n=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,y){const P=X(p);(y.revision??-1)>=(o.get(P)?.revision??-1)&&o.set(P,y)}function g(p,y){const q={kind:"request",message:`PR/MR status service unavailable: ${y instanceof Error?y.message:String(y)}`,at:t()};for(const H of a.get(p)??[]){const U=X({directory:p,key:H});o.set(U,{...o.get(U)??{},loading:!1,error:q})}e.onChange()}const E=new Map,$=new Map;function w(p){const y=(E.get(p)??0)+1;E.set(p,y);const P=$.get(p);P!==void 0&&s(P),$.set(p,r(()=>{S(p)},Math.min(nt,1e3*2**y)))}async function S(p){if(u)return;const y=$.get(p);y!==void 0&&s(y),$.delete(p);const P=[...a.get(p)??[]];try{const q=await e.watch(p,{clientID:e.clientID,keys:P,...c?.directory===p?{visible:c.key}:{}});if(u)return;E.delete(p),i.set(p,q.enabled);for(const[H,U]of Object.entries(q.statuses))f({directory:p,key:H})&&m({directory:p,key:H},U);e.onChange()}catch(q){if(u)return;g(p,q),w(p)}}const I=new Set;function x(p){I.has(p)||(I.add(p),n(()=>{I.delete(p),S(p)}))}return{snapshot:p=>o.get(X(p))??{loading:!1},enabled:p=>i.get(p)??!0,show(p){if(p.key!==Ir)for(const[P,q]of a)P===p.directory||!q.delete(p.key)||(o.delete(X({directory:P,key:p.key})),c&&He(c,{directory:P,key:p.key})&&(c=void 0),x(P));const y=a.get(p.directory)??new Set;a.set(p.directory,y),y.add(p.key),c=p,x(p.directory)},hide(p){c&&He(c,p)&&(c=void 0),x(p.directory)},async refresh(p){const y=X(p);o.set(y,{...o.get(y)??{},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())S(p)},receive(p,y,P){f({directory:p,key:y})&&(m({directory:p,key:y},P),e.onChange())},hasShown:p=>[...a.values()].some(y=>y.has(p)),dispose(){u=!0;for(const p of $.values())s(p);for(const p of a.keys())e.release(p,e.clientID).catch(()=>{})}}}const oe=e=>({location:{directory:e}}),_r=async(e,t)=>await e.feedback({},oe(t));function Nr(e){let t,r=0;const s=new Map;let n;return{get client(){return t?.client},connect(o){t?.dispose(),t=Ar(o,{...e,clientID:`${e.clientID}:${++r}`});for(const a of s.values())t.client.show(a),t.client.hide(a);n&&t.client.show(n),e.onChange()},show(o){s.set(o.key,o),n=o,t?.client.show(o)},hide(o){n?.key===o.key&&n.directory===o.directory&&(n=void 0),t?.client.hide(o)},dispose(){t?.dispose(),t=void 0}}}function Dr(e){const t=new Map;let r=0;const s=async n=>{const o=(t.get(n)??0)+1;t.set(n,o);const a=r,i=()=>a===r&&t.get(n)===o;try{const c=await e.load(n);i()&&e.changed(n,c)}catch(c){i()&&e.failed(n,c instanceof Error?c.message:String(c))}};return{reload:s,has:n=>t.has(n),refresh:()=>Promise.all([...t.keys()].map(s)),invalidate(){r++}}}function Ar(e,t){const r=e,s=Pr({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}),n=setInterval(()=>{s.heartbeat(),t.heartbeat?.()},nt),o=e.events.on("status",a=>{const{directory:i,key:c,snapshot:u}=a.data;s.receive(i,c,u)});return{client:s,dispose(){clearInterval(n),o(),s.dispose()}}}const Tr=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,ze=e=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),xr=e=>e.postedAt!==void 0?`Latest comment: ${ze(e.postedAt)}`:`Detected: ${ze(e.at)}`;function qr(e,t){const r=e.items.filter(s=>s.sessionID===t).length;if(!(!t||r===0))return`${r} review update${r===1?"":"s"}${e.paused?" (paused)":""}`}function Lr(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 Or(e){const t=Lr(e),r=t.filter(n=>n!==e.url),s=e.kind==="ci-failed";return[...r.map((n,o)=>({title:`${s?"Failed job":"Comment"} ${r.length>1?`${o+1} of ${r.length} `:""}(${s?new URL(n).pathname.split("/").filter(Boolean).slice(-2).join("/"):new URL(n).hash||"no anchor"})`,description:n,value:n})),...t.includes(e.url)?[{title:"PR/MR overview",description:e.url,value:e.url}]:[]]}const Ur=new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SCHEDULED","WAITING_FOR_CALLBACK","CANCELING"]);function ke(e){return e?e.status==="FAILED"?"error":e.status==="SUCCESS"?e.label.includes("warning")?"warning":"success":Ur.has(e.status)?"warning":"muted":"muted"}const st=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Mr=e=>e.charAt(0).toUpperCase()+e.slice(1),jr={success:"CI ✓",error:"CI ✗",warning:"CI …"};function Br(e){return e.length>2?`awaiting ${e.length} reviewers`:`awaiting ${e.map(t=>`@${t}`).join(", ")}`}function Fr(e){return`${e.unresolvedThreads}${e.threadsComplete?"":"+"} unresolved thread${e.unresolvedThreads===1&&e.threadsComplete?"":"s"}`}const de=e=>({text:ce(e),tone:"muted",url:e.url,essential:!0});function Gr(e){const t=ke(e.pipeline);return e.pipeline?{text:`CI ${e.pipeline.label}`,compact:jr[t],tone:t,url:e.pipeline.url}:{text:`no ${F(e).ci}`,compact:"no CI",tone:t}}function Hr(e){const t=new Set(e.map(g=>F(g).noun)),r=t.size===1?[...t][0]:"PR/MR",s=e.length===1?`1 ${r}`:`${e.length} ${r==="PR/MR"?"PRs/MRs":`${r}s`}`,n=e.filter(g=>g.state==="opened"),o=[{text:s,tone:"muted",essential:!0}],a=n.filter(g=>le(g)?.state==="running").length;a&&o.push({text:`🤖 ${a} reviewing`,compact:`🤖 ${a}`,tone:"warning",essential:!0});const i=n.filter(g=>ke(g.pipeline)==="error").length;i&&o.push({text:`${i} CI failed`,compact:`CI ✗ ${i}`,tone:"error"});const c=n.filter(g=>g.conflicts).length;c&&o.push({text:st(c,"conflict"),tone:"error",essential:!0});const u=n.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-n.length-f;return m&&o.push({text:`${m} closed`,tone:"muted"}),o}function zr(e){const{lookup:t,error:r}=e,s=r?[{text:"stale",tone:"warning",essential:!0}]:[];if(!t||t.kind==="none"||t.requests.length===0)return e.targeted&&(r||t?.explicitTarget)?[{text:"PR/MR status unavailable",tone:"warning"}]:[];t.failed?.length&&s.unshift({text:`${t.failed.length} unavailable`,tone:"warning",essential:!0});const n=t.requests;if(t.explicitTarget&&n.length>1)return[...Hr(n),...s];if(n.length>1){const i=F(n[0]).noun;return[...n.map(de),{text:`${st(n.length,`open ${i}`)}, run /${i.toLowerCase()}-status`,tone:"warning"},...s]}const[o]=n;if(o.state!=="opened")return[de(o),{text:o.state,tone:o.state==="merged"?"success":"muted",essential:!0},...s];const a=[de(o),Gr(o)];if(o.unresolvedThreads>0||!o.threadsComplete){const i=Fr(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(...F(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:Br(o.awaitingReviewers),tone:"muted"}):o.approved&&a.push({text:"approved",tone:"success"}),[...a,...s]}const We=e=>new Date(e).toLocaleTimeString();function Wr(e,t){const r=F(e),s=[`${ce(e)} ${e.title}${e.state==="opened"?"":` (${e.state})`}`,`Target: ${e.targetProject} → ${e.targetBranch}`,`${Mr(r.ci)}: ${e.pipeline?e.pipeline.label:"none"}${e.pipeline?.url?` (${e.pipeline.url})`:""}`,`Unresolved threads: ${e.unresolvedThreads}${e.threadsComplete?"":"+"}`,`Draft: ${W(e.draft)} · Conflicts: ${e.conflictsKnown?W(e.conflicts):"unknown"}`,...r.details(e)],n=le(e);return n&&s.push(`${n.name} review: ${n.label}`),e.awaitingReviewers.length&&s.push(`Awaiting review: ${e.awaitingReviewers.map(o=>`@${o}`).join(", ")}`),e.reviewersComplete||s.push("Reviewer list is partial"),t&&e.headSha&&t!==e.headSha&&s.push(`Local HEAD differs from the ${r.noun} head commit (unpushed or not fetched)`),s.push(e.url),s}function Jr(e){const{lookup:t,error:r,fetchedAt:s}=e,n=[];if(!t)n.push(r?"Could not look up the PR/MR.":"No data yet.");else if(t.kind==="none")n.push(`No PR/MR lookup: ${t.reason}.`);else{const{repository:o,sessionTarget:a,requests:i}=t;if(o){const c=o.branch===o.sourceBranch?o.branch:`${o.branch} (pushes to ${o.sourceBranch})`;n.push(`Branch: ${c} in ${o.source.path}`),i.length===0&&n.push("","No open PR/MR for this branch.")}else a&&n.push(`Session target: ${a}`);for(const{url:c,reason:u}of t.failed??[])n.push(`Unavailable: ${c} (${u})`);for(const c of i)n.push("",...Wr(c,o?.head??""))}return r&&n.push("",`Last refresh failed at ${We(r.at)}: ${r.message}`),s!==void 0&&n.push("",`Last fetched: ${We(s)}`),n.join(`
|
|
114
|
+
`)}function Kr(e,t,r){const s=zr(e);if(!s.length&&!t)return;const n=s.findIndex(i=>!i.essential||!i.url),o=n<0?s.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:[...s.map((i,c)=>({segment:i,priority:c<o?-1:Qr(i)})).sort((i,c)=>i.priority-c.priority).map(({segment:i})=>Vr(i,a)),t?.replace(/^(\d+) review updates?/,"↻ $1")].filter(Boolean).join(" · "),tone:Xr(s.map(i=>i.tone)),title:"PR/MR status",rows:[...s.map((i,c)=>({id:`segment-${c}`,label:i.text.startsWith("awaiting ")&&a?.length?`awaiting ${a.map(u=>`@${u}`).join(", ")}`:i.text,...i.url?{icon:"outline-arrow-up-right"}:{},...i.tone==="success"||i.tone==="warning"?{tone:i.tone}:i.tone==="error"?{tone:"danger"}:{},...i.url?{run:()=>r.external(i.url)}:{}})),{id:"details",label:"Show PR/MR status",icon:"status",run:r.status},...t?[{id:"feedback",label:t,icon:"comment",run:r.feedback}]:[]]}}function Qr(e){return e.text==="mergeability unknown"?4:e.tone==="error"?0:/unresolved threads?$/.test(e.text)?1:e.tone==="warning"?2:3}function Vr(e,t){const r=e.text.match(/^(\d+\+?) unresolved threads?$/);return r?`💬 ${r[1]}`:e.text.startsWith("awaiting ")&&t?.length?`◷ @${t[0]}${t.length>1?` +${t.length-1}`:""}`:e.text==="approved"?"✓ approved":e.compact?.startsWith("CI ")?e.compact.replace(/^CI ([✓✗…])/,"$1 CI"):e.compact??e.text}function Xr(e){if(e.includes("error"))return"danger";if(e.includes("warning"))return"warning";if(e.includes("success"))return"success"}function Yr(e,t){const{sessionID:r}=e;r&&!t.hasShown(r)||(r&&e.variant==="info"&&t.openTab(r),t.toast({...e.title?{title:e.title}:{},message:e.message,variant:e.variant}))}var Zr=l.template("<a><b>"),en=l.template("<div><span class=fk-label>: "),tn=l.template("<b>"),rn=l.template("<div class=fk-warning>Reviewer list is partial"),nn=l.template("<div class=fk-warning>Local HEAD differs from the <!> head commit (unpushed or not fetched)"),sn=l.template("<div class=fk-card><a><b> </b></a><section></section><section><b>Review and approval"),pe=l.template("<div>"),on=l.template("<div class=forgekeeper-panel><header><h2>PR/MR status"),an=l.template("<div>PR/MR status is off."),cn=l.template("<div class=fk-muted>No PR/MR status available."),ln=l.template("<div class=fk-muted>Last fetched: "),un=l.template("<section>"),dn=l.template('<div class="fk-warning fk-pre"><b>Unavailable'),pn=l.template('<div class="fk-error fk-pre"><b>Last refresh failed at '),fn=l.template("<div class=fk-card><b></b><div class=fk-muted></div><section></section><div class=fk-actions>"),hn=l.template("<a>"),mn=l.template("<div class=forgekeeper-panel><header><h2>Review updates"),gn=l.template("<div class=fk-error>Could not load review updates: <!>. Retrying automatically."),wn=l.template("<div class=fk-muted>");const bn=`
|
|
115
115
|
.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); }
|
|
116
116
|
.forgekeeper-panel header { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
|
117
117
|
.forgekeeper-panel h2 { font-size: 13px; font-weight: 600; margin: 0; }
|
|
@@ -125,7 +125,7 @@ ${r}
|
|
|
125
125
|
.forgekeeper-panel .fk-error { color: var(--v2-state-fg-danger); }
|
|
126
126
|
.forgekeeper-panel a { color: var(--v2-text-text-accent); cursor: pointer; text-decoration: underline; }
|
|
127
127
|
.forgekeeper-panel .fk-pre { white-space: pre-wrap; }
|
|
128
|
-
`,Y="status",Z="feedback",
|
|
129
|
-
${
|
|
130
|
-
${
|
|
131
|
-
${
|
|
128
|
+
`,Y="status",Z="feedback",vn={items:[],paused:!1},Je=e=>e==="success"?"fk-success":e==="warning"?"fk-warning":e==="error"?"fk-error":e==="muted"?"fk-muted":void 0,$n=j.Plugin.define({setup(e){e.add(j.Style,bn);const t=()=>e.client.rpc(Er),r=d=>({location:{directory:d}}),[s,n]=D.createSignal(0),[o,a]=_e.createStore({}),[i,c]=_e.createStore({}),u=Dr({load:d=>_r(t(),d),changed:(d,h)=>{a(d,h),c(d,void 0)},failed:(d,h)=>c(d,h)}),f=u.reload,m=Nr({clientID:Tr(),onChange:()=>n(d=>d+1),heartbeat:()=>{u.refresh()}}),g=()=>m.client,E=d=>d.server.builtin,$=d=>d.location?.directory??d.directory,w=d=>({directory:$(d),key:d.id}),S=d=>(s(),g()?.snapshot(d)??{loading:!1}),I=d=>(s(),g()?.enabled(d)??!0),x=d=>o[d]??vn,p=d=>{const h=S(d).lookup;return h?.kind==="found"?h.requests:[]},y=()=>{const d=e.sessions.current();return d&&E(d)?d:void 0};j.createKeyed(()=>{const d=y();return d?JSON.stringify([$(d),d.id]):void 0},d=>{const[h,v]=JSON.parse(d),C={directory:h,key:v};m.show(C),f(h),D.onCleanup(()=>m.hide(C))});const P=(d,h=y())=>{h&&e.layout.open(`${e.id}:${d}`,h,{tab:"select"})},q=d=>I(d)?!1:(e.toast.show({title:"PR/MR status is off in the plugin's options (status: false)"}),!0);e.add(j.ComposerPill,{id:"status",show:d=>H(d.session)});function H(d){if(!E(d))return;const h=w(d);if(!I(h.directory))return;const v=qr(x(h.directory),d.id);return Kr(S(h),v,{external:C=>e.system.openExternal(C),status:()=>P(Y,d),feedback:()=>P(Z,d)})}const U=e.ui;function M(d){return(()=>{var h=en(),v=h.firstChild,C=v.firstChild;return l.insert(v,()=>d.label,C),l.insert(h,l.createComponent(D.Show,{get when(){return d.url},get fallback(){return(()=>{var b=tn();return l.insert(b,()=>d.value),l.effect(()=>l.className(b,Je(d.tone))),b})()},get children(){var b=Zr(),N=b.firstChild;return b.$$click=()=>e.system.openExternal(d.url),l.insert(N,()=>d.value),l.effect(()=>l.className(b,Je(d.tone))),b}}),null),h})()}function ot(d){const h=()=>d.request,v=()=>F(h()),C=()=>le(h());return(()=>{var b=sn(),N=b.firstChild,_=N.firstChild,R=_.firstChild,k=N.nextSibling,L=k.nextSibling;return L.firstChild,N.$$click=()=>e.system.openExternal(h().url),l.insert(_,()=>ce(h()),R),l.insert(_,()=>h().title,null),l.insert(k,l.createComponent(M,{label:"State",get value(){return h().state},get tone(){return h().state==="merged"?"success":void 0}}),null),l.insert(k,l.createComponent(M,{label:"Target",get value(){return`${h().targetProject} → ${h().targetBranch}`}}),null),l.insert(k,l.createComponent(M,{get label(){return v().ci.charAt(0).toUpperCase()+v().ci.slice(1)},get value(){return h().pipeline?.label??"none"},get tone(){return ke(h().pipeline)},get url(){return h().pipeline?.url}}),null),l.insert(k,l.createComponent(M,{label:"Unresolved threads",get value(){return`${h().unresolvedThreads}${h().threadsComplete?"":"+"}`},get tone(){return h().unresolvedThreads||!h().threadsComplete?"warning":void 0}}),null),l.insert(k,l.createComponent(M,{label:"Draft",get value(){return W(h().draft)},get tone(){return h().draft?"warning":void 0}}),null),l.insert(k,l.createComponent(M,{label:"Conflicts",get value(){return l.memo(()=>!!h().conflictsKnown)()?W(h().conflicts):"unknown"},get tone(){return h().conflicts?"error":void 0}}),null),l.insert(L,l.createComponent(D.For,{get each(){return v().details(h())},children:T=>{const J=T.indexOf(": ");return J<0?(()=>{var K=pe();return l.insert(K,T),K})():l.createComponent(M,{get label(){return T.slice(0,J)},get value(){return T.slice(J+2)}})}}),null),l.insert(L,l.createComponent(D.Show,{get when(){return C()},children:T=>l.createComponent(M,{get label(){return`${T().name} review`},get value(){return T().label},get tone(){return T().state==="running"?"warning":void 0}})}),null),l.insert(L,l.createComponent(D.Show,{get when(){return h().awaitingReviewers.length},get children(){return l.createComponent(M,{label:"Awaiting review",get value(){return h().awaitingReviewers.map(T=>`@${T}`).join(", ")}})}}),null),l.insert(b,l.createComponent(D.Show,{get when(){return!h().reviewersComplete},get children(){return rn()}}),null),l.insert(b,l.createComponent(D.Show,{get when(){return l.memo(()=>!!(d.head&&h().headSha))()&&d.head!==h().headSha},get children(){var T=nn(),J=T.firstChild,K=J.nextSibling;return K.nextSibling,l.insert(T,()=>v().noun,K),T}}),null),b})()}function it(d){const h=D.createMemo(()=>w(d.session),void 0,{equals:(b,N)=>b.directory===N.directory&&b.key===N.key}),v=D.createMemo(()=>S(h())),C=()=>{const b=v().lookup;return b?.kind==="found"?b:void 0};return(()=>{var b=on(),N=b.firstChild;return N.firstChild,l.insert(N,l.createComponent(U.Button,{size:"small",icon:"refresh",get busy(){return v().loading},onClick:()=>{g()?.refresh(h())},children:"Refresh"}),null),l.insert(b,l.createComponent(D.Show,{get when(){return I(h().directory)},get fallback(){return an()},get children(){return l.createComponent(D.Show,{get when(){return C()},get fallback(){return(()=>{var _=pe();return l.insert(_,()=>Jr(v())),l.effect(()=>l.className(_,`fk-pre ${v().error?"fk-error":"fk-muted"}`)),_})()},children:_=>[l.createComponent(D.Show,{get when(){return _().repository},children:R=>(()=>{var k=un();return l.insert(k,l.createComponent(M,{label:"Repository",get value(){return R().source.path}}),null),l.insert(k,l.createComponent(M,{label:"Branch",get value(){return l.memo(()=>R().branch===R().sourceBranch)()?R().branch:`${R().branch} (pushes to ${R().sourceBranch})`}}),null),k})()}),l.createComponent(D.Show,{get when(){return l.memo(()=>!_().repository)()&&_().sessionTarget},get children(){return l.createComponent(M,{label:"Session target",get value(){return _().sessionTarget}})}}),l.createComponent(D.For,{get each(){return _().failed??[]},children:R=>(()=>{var k=dn();return k.firstChild,l.insert(k,()=>`
|
|
129
|
+
${R.url}
|
|
130
|
+
${R.reason}`,null),k})()}),l.createComponent(D.Show,{get when(){return _().requests.length===0},get children(){return cn()}}),l.createComponent(D.For,{get each(){return _().requests},children:R=>l.createComponent(ot,{request:R,get head(){return _().repository?.head}})}),l.createComponent(D.Show,{get when(){return v().error},children:R=>(()=>{var k=pn(),L=k.firstChild;return L.firstChild,l.insert(L,()=>new Date(R().at).toLocaleTimeString(),null),l.insert(k,()=>`
|
|
131
|
+
${R().message}`,null),k})()}),l.createComponent(D.Show,{get when(){return v().fetchedAt!==void 0},get children(){var R=ln();return R.firstChild,l.insert(R,()=>new Date(v().fetchedAt).toLocaleTimeString(),null),R}})]})}}),null),b})()}async function Ee(d,h,v){try{await t()[h](v,r(d)),await f(d)}catch(C){e.toast.show({title:C instanceof Error?C.message:String(C),variant:"error"})}}function at(d){const h=()=>d.item,v=()=>[h().sessionID===d.current?"This session":void 0,xr(h()),h().automation?`${h().automation.state}${h().automation.reason?`: ${h().automation.reason}`:""}`:void 0].filter(Boolean).join(" · "),C=(b,N={})=>Ee(d.directory,b,{id:h().id,...N});return(()=>{var b=fn(),N=b.firstChild,_=N.nextSibling,R=_.nextSibling,k=R.nextSibling;return l.insert(N,()=>h().title),l.insert(_,v),l.insert(b,l.createComponent(D.For,{get each(){return h().details??[]},children:L=>(()=>{var T=pe();return l.insert(T,L),T})()}),R),l.insert(R,l.createComponent(D.For,{get each(){return Or(h())},children:L=>(()=>{var T=hn();return T.$$click=()=>e.system.openExternal(L.value),l.insert(T,()=>L.title),T})()})),l.insert(k,l.createComponent(D.Show,{get when(){return h().sessionID!==d.current},get children(){return l.createComponent(U.Button,{size:"small",onClick:()=>{const L=y()?.server.id;L&&e.tabs.open({server:L,id:h().sessionID},{focus:!0})},children:"Open session"})}}),null),l.insert(k,l.createComponent(U.Button,{size:"small",onClick:()=>{C("summarizeFeedback")},children:"Summarize in session"}),null),l.insert(k,l.createComponent(U.Button,{size:"small",onClick:()=>{C("actOnFeedback")},children:"Act on feedback"}),null),l.insert(k,l.createComponent(U.Button,{size:"small",onClick:async()=>{await e.dialogs.confirm({title:"Retry feedback work?",description:"Retry may repeat earlier changes. Inspect the session first.",confirm:"Retry",danger:!0})&&await C("actOnFeedback",{retry:!0})},children:"Retry"}),null),l.insert(k,l.createComponent(U.Button,{size:"small",onClick:()=>{C("acknowledgeFeedback")},children:"Acknowledge"}),null),b})()}function ct(d){const h=()=>$(d.session),v=()=>x(h());return(()=>{var C=mn(),b=C.firstChild,N=b.firstChild;return N.firstChild,l.insert(N,()=>v().paused?" (monitoring paused)":"",null),l.insert(b,l.createComponent(U.Button,{size:"small",onClick:()=>{Ee(h(),"pauseFeedback",{paused:!v().paused})},get children(){return v().paused?"Resume monitoring":"Pause monitoring"}}),null),l.insert(C,l.createComponent(D.Show,{get when(){return i[h()]},children:_=>(()=>{var R=gn(),k=R.firstChild,L=k.nextSibling;return L.nextSibling,l.insert(R,_,L),R})()}),null),l.insert(C,l.createComponent(D.Show,{get when(){return v().items.length},get fallback(){return l.createComponent(D.Show,{get when(){return!i[h()]},get children(){var _=wn();return l.insert(_,()=>o[h()]?"No pending review updates in this checkout.":"Loading review updates…"),_}})},get children(){return l.createComponent(D.For,{get each(){return v().items},children:_=>l.createComponent(at,{item:_,get directory(){return h()},get current(){return d.session.id}})})}}),null),C})()}const Ie=(d,h)=>({id:d,title:h,closable:"hover"}),lt=Ie(Y,"PR/MR status"),ut=Ie(Z,"Review updates");e.add(j.Panel,{id:Y,region:"side",width:420,list:d=>d.open.includes(Y)?[lt]:[],render:d=>l.createComponent(it,{get session(){return d.session}})}),e.add(j.Panel,{id:Z,region:"side",width:420,list:d=>d.open.includes(Z)?[ut]:[],render:d=>l.createComponent(ct,{get session(){return d.session}})}),e.add(j.Command,()=>({id:"status",title:"Show PR/MR status",group:"Forge",slash:{name:"forge-status"},enabled:!!y(),run:()=>{const d=y();!d||q($(d))||(g()?.refresh(w(d)),P(Y,d))}})),e.add(j.Command,()=>({id:"feedback",title:"Show pending review feedback",group:"Forge",slash:{name:"forge-feedback"},enabled:!!y(),run:()=>{const d=y();d&&(f($(d)),P(Z,d))}})),e.add(j.Command,()=>({id:"open",title:"Open PR/MR in browser",group:"Forge",slash:{name:"forge-open"},enabled:!!y(),run:async()=>{const d=y();if(!d||q($(d)))return;const h=w(d);let v=p(h);if(v.length===0&&(await g()?.refresh(h),v=p(h)),v.length===0){e.toast.show({title:"No PR/MR for this session or branch"});return}const C=v.length===1?v[0].url:await e.dialogs.select({title:"Open PR/MR",options:v.map(b=>({title:`${ce(b)} ${b.title}`,description:b.targetProject,value:b.url}))});C&&e.system.openExternal(C)}}));const Pe=()=>e.servers.list().map(d=>e.servers.get(d)).find(d=>d?.builtin);return j.createKeyed(()=>e.client,()=>{const d=t();u.invalidate(),m.connect(d),u.refresh();const h=[d.events.on("feedbackChanged",v=>{const{directory:C}=v.data;u.has(C)&&f(C)}),d.events.on("notice",v=>{const C=v.data;Yr(C,{hasShown:b=>!!g()?.hasShown(b)||!!v.location?.directory&&u.has(v.location.directory),openTab:b=>{const N=Pe()?.id;N&&e.tabs.open({server:N,id:b})},toast:({title:b,message:N,variant:_})=>{const R=Pe()?.id,k=C.sessionID;e.toast.show({title:b??N,...b?{description:N}:{},variant:_==="error"?"error":"default",...R&&k?{actions:[{label:"Open session",run:()=>e.tabs.open({server:R,id:k},{focus:!0})}]}:{}}),e.attention.notify({title:b??"Forgekeeper",message:N,variant:_==="error"?"error":"default",...R&&k?{session:{server:R,id:k}}:{},id:`forgekeeper:${k??""}:${b??""}:${N}`})}})})];D.onCleanup(()=>{for(const v of h)v();u.invalidate(),m.dispose()})}),()=>{u.invalidate(),m.dispose()}}});l.delegateEvents(["click"]);exports.default=$n;
|
package/dist/index.js
CHANGED
|
@@ -448,17 +448,17 @@ function taggedInput(messages) {
|
|
|
448
448
|
}
|
|
449
449
|
var UNAVAILABLE_TEXT = "The review text is unavailable. Reply that it could not be read.";
|
|
450
450
|
function restrictRequest(event, system, text, tool) {
|
|
451
|
+
const message = {
|
|
452
|
+
role: "user",
|
|
453
|
+
content: [{ type: "text", text }],
|
|
454
|
+
metadata: { forgekeeper: SUMMARY_KIND }
|
|
455
|
+
};
|
|
451
456
|
for (const name of Object.keys(event.tools))
|
|
452
457
|
delete event.tools[name];
|
|
453
458
|
if (tool)
|
|
454
459
|
event.tools[tool.name] = tool.value;
|
|
455
460
|
event.system.splice(0, event.system.length, { type: "text", text: system });
|
|
456
461
|
event.options.maxTokens = SUMMARY_MAX_TOKENS;
|
|
457
|
-
const user = event.messages.findLast((message2) => message2?.role === "user");
|
|
458
|
-
const Message = user?.constructor;
|
|
459
|
-
if (!Message || Message === Object)
|
|
460
|
-
throw new Error("Forgekeeper could not build a tool-free review request");
|
|
461
|
-
const message = new Message({ role: "user", content: [{ type: "text", text }] });
|
|
462
462
|
event.messages.splice(0, event.messages.length, message);
|
|
463
463
|
}
|
|
464
464
|
var noticeText = (title, links) => [`Acknowledge this review notice in one sentence and list its links: ${title}`, ...links].join(`
|
|
@@ -1589,7 +1589,7 @@ var fields = `number title url state isDraft mergeable reviewDecision headRefOid
|
|
|
1589
1589
|
latestReviews(first:100) { nodes { author { ... on User { id } } } }
|
|
1590
1590
|
copilotReviews: reviews(last:1, author:"${COPILOT_AUTHOR}", states:[COMMENTED,CHANGES_REQUESTED,APPROVED,DISMISSED]) { nodes { id state comments { totalCount } } }
|
|
1591
1591
|
commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
|
|
1592
|
-
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl } ... on StatusContext { id context state targetUrl } }
|
|
1592
|
+
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } }
|
|
1593
1593
|
pageInfo { hasNextPage endCursor }
|
|
1594
1594
|
} } } } }`;
|
|
1595
1595
|
var MAX_PAGES = 50;
|
|
@@ -1623,15 +1623,7 @@ function classifyError2(message, code) {
|
|
|
1623
1623
|
return new ForgeError("request", text.split(`
|
|
1624
1624
|
`)[0]);
|
|
1625
1625
|
}
|
|
1626
|
-
var FAILED = [
|
|
1627
|
-
"FAILURE",
|
|
1628
|
-
"ERROR",
|
|
1629
|
-
"TIMED_OUT",
|
|
1630
|
-
"CANCELLED",
|
|
1631
|
-
"ACTION_REQUIRED",
|
|
1632
|
-
"STARTUP_FAILURE",
|
|
1633
|
-
"STALE"
|
|
1634
|
-
];
|
|
1626
|
+
var FAILED = ["FAILURE", "ERROR", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"];
|
|
1635
1627
|
var CONCLUSIONS = [
|
|
1636
1628
|
"SUCCESS",
|
|
1637
1629
|
"NEUTRAL",
|
|
@@ -1644,8 +1636,32 @@ var CONCLUSIONS = [
|
|
|
1644
1636
|
"STALE"
|
|
1645
1637
|
];
|
|
1646
1638
|
var STATES = ["SUCCESS", "FAILURE", "ERROR", "PENDING", "EXPECTED"];
|
|
1639
|
+
var checkKey = (node) => node.__typename === "CheckRun" && node.name && node.checkSuite?.app?.id && node.checkSuite.workflowRun?.workflow?.id && JSON.stringify([node.checkSuite.app.id, node.checkSuite.workflowRun?.workflow?.id, node.name]);
|
|
1640
|
+
var checkTime = (node) => Date.parse(node.checkSuite?.createdAt ?? "");
|
|
1641
|
+
var newerCheck = (node, previous) => checkTime(node) > checkTime(previous);
|
|
1647
1642
|
function checks(nodes, complete, url, id) {
|
|
1643
|
+
const latest = new Map;
|
|
1644
|
+
for (const node of nodes) {
|
|
1645
|
+
const time2 = checkTime(node);
|
|
1646
|
+
const key = checkKey(node);
|
|
1647
|
+
if (!key || !Number.isFinite(time2))
|
|
1648
|
+
continue;
|
|
1649
|
+
const previous = latest.get(key);
|
|
1650
|
+
if (!previous || newerCheck(node, previous))
|
|
1651
|
+
latest.set(key, node);
|
|
1652
|
+
}
|
|
1653
|
+
nodes = nodes.filter((node) => {
|
|
1654
|
+
const key = checkKey(node);
|
|
1655
|
+
const replacement = key && latest.get(key);
|
|
1656
|
+
return !replacement || !newerCheck(replacement, node);
|
|
1657
|
+
});
|
|
1648
1658
|
const count = (value) => `${value} check${value === 1 ? "" : "s"}`;
|
|
1659
|
+
const cancelled = nodes.filter((node) => node.conclusion === "CANCELLED").length;
|
|
1660
|
+
const stale = nodes.filter((node) => node.conclusion === "STALE").length;
|
|
1661
|
+
const stopped = [
|
|
1662
|
+
...cancelled ? [`${count(cancelled)} cancelled`] : [],
|
|
1663
|
+
...stale ? [`${count(stale)} stale`] : []
|
|
1664
|
+
];
|
|
1649
1665
|
const failing = nodes.filter((node) => FAILED.includes(node.conclusion ?? node.state ?? ""));
|
|
1650
1666
|
const failed = failing.length;
|
|
1651
1667
|
const run = id ? {
|
|
@@ -1662,7 +1678,11 @@ function checks(nodes, complete, url, id) {
|
|
|
1662
1678
|
if (failed)
|
|
1663
1679
|
return {
|
|
1664
1680
|
status: "FAILED",
|
|
1665
|
-
label:
|
|
1681
|
+
label: [
|
|
1682
|
+
`${count(failed)} failed`,
|
|
1683
|
+
...stopped,
|
|
1684
|
+
...pending ? [`${count(pending)} pending`] : []
|
|
1685
|
+
].join(", ") + (complete ? "" : " (partial)"),
|
|
1666
1686
|
url,
|
|
1667
1687
|
...run,
|
|
1668
1688
|
running: pending > 0
|
|
@@ -1670,10 +1690,12 @@ function checks(nodes, complete, url, id) {
|
|
|
1670
1690
|
if (pending || !complete || unknown)
|
|
1671
1691
|
return {
|
|
1672
1692
|
status: "PENDING",
|
|
1673
|
-
label:
|
|
1693
|
+
label: [...stopped, pending ? `${count(pending)} pending` : "unknown"].join(", ") + (complete ? "" : " (partial)"),
|
|
1674
1694
|
url,
|
|
1675
1695
|
...run
|
|
1676
1696
|
};
|
|
1697
|
+
if (cancelled || stale)
|
|
1698
|
+
return { status: "CANCELLED", label: stopped.join(", "), url, ...run };
|
|
1677
1699
|
const label = [
|
|
1678
1700
|
["SUCCESS", "passed"],
|
|
1679
1701
|
["SKIPPED", "skipped"],
|
|
@@ -1860,7 +1882,7 @@ class GitHubForge {
|
|
|
1860
1882
|
for (let count = 1;cursor?.hasNextPage && cursor.endCursor && count < MAX_PAGES; count++) {
|
|
1861
1883
|
const data = await this.graphql(host, query(`query($owner:String!,$repo:String!,$oid:GitObjectID!,$after:String!) {
|
|
1862
1884
|
repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
|
|
1863
|
-
contexts(first:100,after:$after) { nodes { __typename ... on CheckRun { id name status conclusion detailsUrl } ... on StatusContext { id context state targetUrl } } pageInfo { hasNextPage endCursor } }
|
|
1885
|
+
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 } }
|
|
1864
1886
|
} } } } }`), { owner, repo, oid: node.headRefOid, after: cursor.endCursor });
|
|
1865
1887
|
const next = data.repository?.object?.statusCheckRollup?.contexts;
|
|
1866
1888
|
if (!next)
|
|
@@ -3612,15 +3634,14 @@ function createSummaryDelivery(ctx, deps, host) {
|
|
|
3612
3634
|
relay,
|
|
3613
3635
|
fetchLinked,
|
|
3614
3636
|
async prepare(event) {
|
|
3637
|
+
requesting.delete(event.sessionID);
|
|
3615
3638
|
const tagged = taggedInput(event.messages);
|
|
3616
3639
|
let record = await summaryTurn(event.sessionID);
|
|
3617
3640
|
if (!record && tagged && !await userInput(event.sessionID))
|
|
3618
3641
|
record = await readRecord(event.sessionID, tagged) ?? "failed";
|
|
3619
3642
|
if (!record) {
|
|
3620
|
-
requesting.delete(event.sessionID);
|
|
3621
3643
|
return false;
|
|
3622
3644
|
}
|
|
3623
|
-
requesting.set(event.sessionID, record === "failed" ? undefined : record.messageID);
|
|
3624
3645
|
const linked = record === "failed" || !record.linked ? undefined : linkedContext(record.linked, MAX_TOTAL - record.findings.length - 2);
|
|
3625
3646
|
const tool = linked?.tool ? event.tools[LINKED_NOTE_TOOL] : undefined;
|
|
3626
3647
|
restrictRequest(event, record !== "failed" && record.system === "lifecycle" ? LIFECYCLE_SYSTEM : record !== "failed" && record.system === "relay" ? RELAY_SYSTEM : summarySystem(!!tool, !!linked), record === "failed" ? UNAVAILABLE_TEXT : [record.findings, linked?.text ?? ""].filter(Boolean).join(`
|
|
@@ -3628,6 +3649,7 @@ function createSummaryDelivery(ctx, deps, host) {
|
|
|
3628
3649
|
`), tool ? { name: LINKED_NOTE_TOOL, value: tool } : undefined);
|
|
3629
3650
|
if (record !== "failed" && record.system === "relay")
|
|
3630
3651
|
event.options.maxTokens = relayMaxTokens(record.findings);
|
|
3652
|
+
requesting.set(event.sessionID, record === "failed" ? undefined : record.messageID);
|
|
3631
3653
|
return true;
|
|
3632
3654
|
},
|
|
3633
3655
|
async summarizing(sessionID) {
|
package/dist/tui.js
CHANGED
|
@@ -1120,7 +1120,7 @@ var fields = `number title url state isDraft mergeable reviewDecision headRefOid
|
|
|
1120
1120
|
latestReviews(first:100) { nodes { author { ... on User { id } } } }
|
|
1121
1121
|
copilotReviews: reviews(last:1, author:"${COPILOT_AUTHOR}", states:[COMMENTED,CHANGES_REQUESTED,APPROVED,DISMISSED]) { nodes { id state comments { totalCount } } }
|
|
1122
1122
|
commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
|
|
1123
|
-
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl } ... on StatusContext { id context state targetUrl } }
|
|
1123
|
+
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } }
|
|
1124
1124
|
pageInfo { hasNextPage endCursor }
|
|
1125
1125
|
} } } } }`;
|
|
1126
1126
|
var MAX_PAGES = 50;
|
|
@@ -1154,15 +1154,7 @@ function classifyError2(message, code) {
|
|
|
1154
1154
|
return new ForgeError("request", text.split(`
|
|
1155
1155
|
`)[0]);
|
|
1156
1156
|
}
|
|
1157
|
-
var FAILED = [
|
|
1158
|
-
"FAILURE",
|
|
1159
|
-
"ERROR",
|
|
1160
|
-
"TIMED_OUT",
|
|
1161
|
-
"CANCELLED",
|
|
1162
|
-
"ACTION_REQUIRED",
|
|
1163
|
-
"STARTUP_FAILURE",
|
|
1164
|
-
"STALE"
|
|
1165
|
-
];
|
|
1157
|
+
var FAILED = ["FAILURE", "ERROR", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"];
|
|
1166
1158
|
var CONCLUSIONS = [
|
|
1167
1159
|
"SUCCESS",
|
|
1168
1160
|
"NEUTRAL",
|
|
@@ -1175,8 +1167,32 @@ var CONCLUSIONS = [
|
|
|
1175
1167
|
"STALE"
|
|
1176
1168
|
];
|
|
1177
1169
|
var STATES = ["SUCCESS", "FAILURE", "ERROR", "PENDING", "EXPECTED"];
|
|
1170
|
+
var checkKey = (node) => node.__typename === "CheckRun" && node.name && node.checkSuite?.app?.id && node.checkSuite.workflowRun?.workflow?.id && JSON.stringify([node.checkSuite.app.id, node.checkSuite.workflowRun?.workflow?.id, node.name]);
|
|
1171
|
+
var checkTime = (node) => Date.parse(node.checkSuite?.createdAt ?? "");
|
|
1172
|
+
var newerCheck = (node, previous) => checkTime(node) > checkTime(previous);
|
|
1178
1173
|
function checks(nodes, complete, url, id) {
|
|
1174
|
+
const latest = new Map;
|
|
1175
|
+
for (const node of nodes) {
|
|
1176
|
+
const time2 = checkTime(node);
|
|
1177
|
+
const key = checkKey(node);
|
|
1178
|
+
if (!key || !Number.isFinite(time2))
|
|
1179
|
+
continue;
|
|
1180
|
+
const previous = latest.get(key);
|
|
1181
|
+
if (!previous || newerCheck(node, previous))
|
|
1182
|
+
latest.set(key, node);
|
|
1183
|
+
}
|
|
1184
|
+
nodes = nodes.filter((node) => {
|
|
1185
|
+
const key = checkKey(node);
|
|
1186
|
+
const replacement = key && latest.get(key);
|
|
1187
|
+
return !replacement || !newerCheck(replacement, node);
|
|
1188
|
+
});
|
|
1179
1189
|
const count = (value) => `${value} check${value === 1 ? "" : "s"}`;
|
|
1190
|
+
const cancelled = nodes.filter((node) => node.conclusion === "CANCELLED").length;
|
|
1191
|
+
const stale = nodes.filter((node) => node.conclusion === "STALE").length;
|
|
1192
|
+
const stopped = [
|
|
1193
|
+
...cancelled ? [`${count(cancelled)} cancelled`] : [],
|
|
1194
|
+
...stale ? [`${count(stale)} stale`] : []
|
|
1195
|
+
];
|
|
1180
1196
|
const failing = nodes.filter((node) => FAILED.includes(node.conclusion ?? node.state ?? ""));
|
|
1181
1197
|
const failed = failing.length;
|
|
1182
1198
|
const run = id ? {
|
|
@@ -1193,7 +1209,11 @@ function checks(nodes, complete, url, id) {
|
|
|
1193
1209
|
if (failed)
|
|
1194
1210
|
return {
|
|
1195
1211
|
status: "FAILED",
|
|
1196
|
-
label:
|
|
1212
|
+
label: [
|
|
1213
|
+
`${count(failed)} failed`,
|
|
1214
|
+
...stopped,
|
|
1215
|
+
...pending ? [`${count(pending)} pending`] : []
|
|
1216
|
+
].join(", ") + (complete ? "" : " (partial)"),
|
|
1197
1217
|
url,
|
|
1198
1218
|
...run,
|
|
1199
1219
|
running: pending > 0
|
|
@@ -1201,10 +1221,12 @@ function checks(nodes, complete, url, id) {
|
|
|
1201
1221
|
if (pending || !complete || unknown)
|
|
1202
1222
|
return {
|
|
1203
1223
|
status: "PENDING",
|
|
1204
|
-
label:
|
|
1224
|
+
label: [...stopped, pending ? `${count(pending)} pending` : "unknown"].join(", ") + (complete ? "" : " (partial)"),
|
|
1205
1225
|
url,
|
|
1206
1226
|
...run
|
|
1207
1227
|
};
|
|
1228
|
+
if (cancelled || stale)
|
|
1229
|
+
return { status: "CANCELLED", label: stopped.join(", "), url, ...run };
|
|
1208
1230
|
const label = [
|
|
1209
1231
|
["SUCCESS", "passed"],
|
|
1210
1232
|
["SKIPPED", "skipped"],
|
|
@@ -1391,7 +1413,7 @@ class GitHubForge {
|
|
|
1391
1413
|
for (let count = 1;cursor?.hasNextPage && cursor.endCursor && count < MAX_PAGES; count++) {
|
|
1392
1414
|
const data = await this.graphql(host, query(`query($owner:String!,$repo:String!,$oid:GitObjectID!,$after:String!) {
|
|
1393
1415
|
repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
|
|
1394
|
-
contexts(first:100,after:$after) { nodes { __typename ... on CheckRun { id name status conclusion detailsUrl } ... on StatusContext { id context state targetUrl } } pageInfo { hasNextPage endCursor } }
|
|
1416
|
+
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 } }
|
|
1395
1417
|
} } } } }`), { owner, repo, oid: node.headRefOid, after: cursor.endCursor });
|
|
1396
1418
|
const next = data.repository?.object?.statusCheckRollup?.contexts;
|
|
1397
1419
|
if (!next)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-forgekeeper",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"description": "OpenCode plugin that tracks each session's GitHub and GitLab issues and PRs/MRs: title prefixes, a PR/MR status footer, and review notifications",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Pedro Pombeiro",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
],
|
|
45
45
|
"license": "MIT",
|
|
46
46
|
"peerDependencies": {
|
|
47
|
-
"@opencode/plugin": "^2.
|
|
47
|
+
"@opencode/plugin": "^2.3.0",
|
|
48
48
|
"@opentui/core": ">=0.7.0",
|
|
49
49
|
"@opentui/solid": ">=0.7.0",
|
|
50
50
|
"solid-js": ">=1.9.0"
|