@gitlab/duo-cli 8.50.0 → 8.50.1

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/index.js CHANGED
@@ -1133,7 +1133,7 @@ ${fqQ(C)}`:""};if(typeof Q==="string"){let I=B?`
1133
1133
  ${D(B)}`:"";this.#I(`${Q}${I}${E(B)}`,A)}else{let I=LrA(Q);if(!I)return;this.#I(`${D(I)}${E(Q)}`,A)}}#I(A,Q){let B=`${RrA.default().format("YYYY-MM-DDTHH:mm:ss:SSS")} [${Q}]: `,D=(E)=>E.replace(/\n/g,`
1134
1134
  ${" ".repeat(bqQ)}`);this.#A.write(`${B}${D(A)}`)}setContext(A){this.#B=A}debug(A,Q){this.#D(T7.DEBUG,A,Q)}info(A,Q){this.#D(T7.INFO,A,Q)}warn(A,Q){this.#D(T7.WARNING,A,Q)}error(A,Q){this.#D(T7.ERROR,A,Q)}withContext(A){let Q=new MK(this.#A,this.#Q);return Q.setContext(A),Q}}MK=q1([TrA.Injectable(g1,[tO,xu])],MK);var P1A=cA(c1(),1);var L1A=cA(c1(),1);var PrA=cA(c1(),1),t4=PrA.createInterfaceId("GitLabApiService");var vrA=cA(XU(),1);function SrA(A){return(A.split(`
1135
1135
  `).find((Q)=>Q.trim())??A.replace(`
1136
- `,"")).trim()}function xqQ(A){return SrA(A).match(/^(query|mutation|subscription)\s+/)?.[1]}function hqQ(A){return SrA(A).match(/(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function Xe(A){let Q=xqQ(A),B=hqQ(A);if(Q)return`${Q}: ${B??"anonymous"}`;return}var uqQ=(A)=>{if(A.method==="GET"||A.method==="HEAD")return;if(!A.body)return;return R8("Body",JSON.stringify(A.body))},mqQ=(A)=>{if(A.method==="POST"||A.method==="PATCH"||A.method==="PUT")return;if(!A.searchParams)return;return R8("Search Params",JSON.stringify(A.searchParams))},dqQ=(A)=>{if(!A.headers)return;return R8("Headers",JSON.stringify(A.headers))},hu=(A)=>{switch(A.type){case"graphql":return lI("GraphQL Request",R8("Query",A.query.replace(/[\s\n]+/g," ").trim()),R8("Variables",JSON.stringify(A.variables)));case"rest":return lI("REST Request",R8("Method",A.method),R8("Path",A.path),dqQ(A),mqQ(A),uqQ(A));default:return R8("Unknown request type",A.type)}};var krA=(A)=>{try{return JSON.parse(A)?.error}catch{return}},cqQ=(A)=>{if(!A)return"";try{return JSON.parse(A)?.error_description??""}catch{return""}},IGA=(A,Q)=>Boolean(A.status===401&&Q&&krA(Q)==="invalid_token"),CGA=(A,Q)=>Boolean(A.status===400&&Q&&krA(Q)==="invalid_grant");class ze extends Error{request;cause;constructor(A,Q,B){super(A);this.request=Q,this.cause=B?.cause}get sanitizedMessage(){return"API request failed"}}class FGA extends ze{status;constructor(A,Q,B,D){super(A,Q,D);this.status=B}}class Ze extends FGA{type="rest";response;#A;constructor(A,Q,B,D){let E=`Fetching ${B} from ${Q.url} failed. ${cqQ(D)}`;if(IGA(Q,D))E=`Request for ${B} failed because the token is expired or revoked.`;if(CGA(Q,D))E="Request to refresh token failed, because it's revoked or already refreshed.";super(E,A,Q.status);this.response=Q,this.#A=D}isInvalidTokenOrInvalidRefresh(){return IGA(this.response,this.#A)||CGA(this.response,this.#A)}get ctx(){return lI("Error details",hu(this.request),this.#Q())}get sanitizedMessage(){if(IGA(this.response,this.#A))return"Request failed because the token is expired or revoked.";if(CGA(this.response,this.#A))return"Request to refresh token failed, because it's revoked or already refreshed.";return`Request failed with error code: ${this.response.status}`}#Q(){let A=Object.fromEntries(this.response.headers.entries());return lI("Response",R8("Status",String(this.status)),!vrA.default.isEmpty(A)?R8("Headers",JSON.stringify(A)):void 0,this.#A?R8("Response body",this.#A):void 0)}get body(){return this.#A}}var yrA=(A)=>A.errors?.map((Q)=>Q.message).join(",")||"";class YGA extends FGA{type="graphql";graphQlResponse;#A;constructor(A,Q){let B=Xe(A.query),D=`GraphQL request "${B}" failed with ${yrA(Q)}`;super(D,A,Q.status);this.graphQlResponse=Q,this.#A=B}get sanitizedMessage(){return`GraphQL request "${this.#A}" failed with status ${this.graphQlResponse.status}`}get ctx(){return lI("Error details",hu(this.request),this.#Q())}#Q(){return lI("Response",R8("Status",String(this.graphQlResponse.status)),R8("Errors",yrA(this.graphQlResponse)))}}class we extends ze{type="network";cause;constructor(A,Q){let B=Q instanceof Error?Q.message:`Network error occurred: ${Q}`;super(B,A);this.cause=Q}get ctx(){return lI("Error details",hu(this.request),this.#A())}get sanitizedMessage(){let A=this.cause,Q=A?.code||A?.errno,B=this.#Q(Q);return`Network error occurred${B?`: ${B}`:""}`}#A(){if(!this.cause||!(this.cause instanceof Error))return;let A=this.cause;if(A.code||A.errno){let Q=A.code||A.errno,B=this.#Q(Q),D=B?`${B} (${Q})`:`Error code: ${Q}`;return R8("Network issue",D)}return}#Q(A){return{ENOTFOUND:"DNS lookup failed - hostname could not be resolved",ECONNREFUSED:"Connection refused - server is not accepting connections",ECONNRESET:"Connection reset by peer - server closed the connection unexpectedly",ETIMEDOUT:"Connection timed out - server did not respond in time",EHOSTUNREACH:"Host unreachable - network route to server not available",ENETUNREACH:"Network unreachable - no network connectivity",ECONNABORTED:"Connection aborted - request was cancelled",EBADF:"Bad file descriptor - network connection issue",EPIPE:"Broken pipe - connection closed while writing data",EAI_AGAIN:"DNS lookup failed temporarily - try again later"}[A]}}class pqQ extends ze{type="timeout";#A;constructor(A,Q){let B=`Request timed out${Q?` after ${Q}ms`:""}`;super(B,A);this.#A=B}get ctx(){return lI("Error details",hu(this.request))}get sanitizedMessage(){return this.#A}}var grA=Ze;var uu={type:"rest",method:"GET",path:"/api/v4/version"};var Ke=JSON;var brA=(A)=>A.toUpperCase(),frA=(A)=>{let Q={};return A.forEach((B,D)=>{Q[D]=B}),Q};var xrA=(A,Q,B)=>{return A.document?A:{document:A,variables:Q,requestHeaders:B,signal:void 0}},hrA=(A,Q,B)=>{return A.query?A:{query:A,variables:Q,requestHeaders:B,signal:void 0}},urA=(A,Q)=>{return A.documents?A:{documents:A,requestHeaders:Q,signal:void 0}};var ZAA=cA(vQ1(),1),kQ1=(A)=>{let Q=void 0,B=A.definitions.filter((D)=>D.kind==="OperationDefinition");if(B.length===1)Q=B[0]?.name?.value;return Q},K_=(A)=>{if(typeof A==="string"){let B=void 0;try{let D=ZAA.parse(A);B=kQ1(D)}catch(D){}return{query:A,operationName:B}}let Q=kQ1(A);return{query:ZAA.print(A),operationName:Q}};class TF extends Error{constructor(A,Q){let B=`${TF.extractMessage(A)}: ${JSON.stringify({response:A,request:Q})}`;super(B);if(Object.setPrototypeOf(this,TF.prototype),this.response=A,this.request=Q,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,TF)}static extractMessage(A){return A.errors?.[0]?.message??`GraphQL Error (Code: ${A.status})`}}var NW=cA(q61(),1);var MhQ="connection_init",qhQ="connection_ack",_61="ping",L61="pong",OhQ="subscribe",_hQ="next",LhQ="error",R61="complete";class WW{get type(){return this._type}get id(){return this._id}get payload(){return this._payload}constructor(A,Q,B){this._type=A,this._payload=Q,this._id=B}get text(){let A={type:this.type};if(this.id!=null&&this.id!=null)A.id=this.id;if(this.payload!=null&&this.payload!=null)A.payload=this.payload;return JSON.stringify(A)}static parse(A,Q){let{type:B,payload:D,id:E}=JSON.parse(A);return new WW(B,Q(D),E)}}class aXA{constructor(A,{onInit:Q,onAcknowledged:B,onPing:D,onPong:E}){this.socketState={acknowledged:!1,lastRequestId:0,subscriptions:{}},this.socket=A,A.addEventListener("open",async(I)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={},A.send(ThQ(Q?await Q():null).text)}),A.addEventListener("close",(I)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={}}),A.addEventListener("error",(I)=>{console.error(I)}),A.addEventListener("message",(I)=>{try{let C=RhQ(I.data);switch(C.type){case qhQ:{if(this.socketState.acknowledged)console.warn("Duplicate CONNECTION_ACK message ignored");else if(this.socketState.acknowledged=!0,B)B(C.payload);return}case _61:{if(D)D(C.payload).then((G)=>A.send(O61(G).text));else A.send(O61(null).text);return}case L61:{if(E)E(C.payload);return}}if(!this.socketState.acknowledged)return;if(C.id===void 0||C.id===null||!this.socketState.subscriptions[C.id])return;let{query:F,variables:Y,subscriber:J}=this.socketState.subscriptions[C.id];switch(C.type){case _hQ:{if(!C.payload.errors&&C.payload.data)J.next&&J.next(C.payload.data);if(C.payload.errors)J.error&&J.error(new TF({...C.payload,status:200},{query:F,variables:Y}));return}case LhQ:{J.error&&J.error(new TF({errors:C.payload,status:200},{query:F,variables:Y}));return}case R61:{J.complete&&J.complete(),delete this.socketState.subscriptions[C.id];return}}}catch(C){console.error(C),A.close(1006)}A.close(4400,"Unknown graphql-ws message.")})}makeSubscribe(A,Q,B,D){let E=(this.socketState.lastRequestId++).toString();return this.socketState.subscriptions[E]={query:A,variables:D,subscriber:B},this.socket.send(PhQ(E,{query:A,operationName:Q,variables:D}).text),()=>{this.socket.send(ShQ(E).text),delete this.socketState.subscriptions[E]}}rawRequest(A,Q){return new Promise((B,D)=>{let E;this.rawSubscribe(A,{next:(I,C)=>E={data:I,extensions:C},error:D,complete:()=>B(E)},Q)})}request(A,Q){return new Promise((B,D)=>{let E;this.subscribe(A,{next:(I)=>E=I,error:D,complete:()=>B(E)},Q)})}subscribe(A,Q,B){let{query:D,operationName:E}=K_(A);return this.makeSubscribe(D,E,Q,B)}rawSubscribe(A,Q,B){return this.makeSubscribe(A,void 0,Q,B)}ping(A){this.socket.send(jhQ(A).text)}close(){this.socket.close(1000)}}aXA.PROTOCOL="graphql-transport-ws";function RhQ(A,Q=(B)=>B){return WW.parse(A,Q)}function ThQ(A){return new WW(MhQ,A)}function jhQ(A){return new WW(_61,A,void 0)}function O61(A){return new WW(L61,A,void 0)}function PhQ(A,Q){return new WW(OhQ,Q,A)}function ShQ(A){return new WW(R61,void 0,A)}var xS=(A)=>{let Q={};if(A)if(typeof Headers!=="undefined"&&A instanceof Headers||NW&&NW.Headers&&A instanceof NW.Headers)Q=frA(A);else if(Array.isArray(A))A.forEach(([B,D])=>{if(B&&D!==void 0)Q[B]=D});else Q=A;return Q},T61=(A)=>A.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),yhQ=(A)=>{if(!Array.isArray(A.query)){let D=A,E=[`query=${encodeURIComponent(T61(D.query))}`];if(A.variables)E.push(`variables=${encodeURIComponent(D.jsonSerializer.stringify(D.variables))}`);if(D.operationName)E.push(`operationName=${encodeURIComponent(D.operationName)}`);return E.join("&")}if(typeof A.variables!=="undefined"&&!Array.isArray(A.variables))throw new Error("Cannot create query with given variable type, array expected");let Q=A,B=A.query.reduce((D,E,I)=>{return D.push({query:T61(E),variables:Q.variables?Q.jsonSerializer.stringify(Q.variables[I]):void 0}),D},[]);return`query=${encodeURIComponent(Q.jsonSerializer.stringify(B))}`},vhQ=(A)=>async(Q)=>{let{url:B,query:D,variables:E,operationName:I,fetch:C,fetchOptions:F,middleware:Y}=Q,J={...Q.headers},G="",X=void 0;if(A==="POST"){if(X=khQ(D,E,I,F.jsonSerializer),typeof X==="string")J["Content-Type"]="application/json"}else G=yhQ({query:D,variables:E,operationName:I,jsonSerializer:F.jsonSerializer??Ke});let z={method:A,headers:J,body:X,...F},U=B,Z=z;if(Y){let w=await Promise.resolve(Y({...z,url:B,operationName:I,variables:E})),{url:H,...W}=w;U=H,Z=W}if(G)U=`${U}?${G}`;return await C(U,Z)};class rXA{constructor(A,Q={}){this.url=A,this.requestConfig=Q,this.rawRequest=async(...B)=>{let[D,E,I]=B,C=hrA(D,E,I),{headers:F,fetch:Y=NW.default,method:J="POST",requestMiddleware:G,responseMiddleware:X,...z}=this.requestConfig,{url:U}=this;if(C.signal!==void 0)z.signal=C.signal;let{operationName:Z}=K_(C.query);return nXA({url:U,query:C.query,variables:C.variables,headers:{...xS(oXA(F)),...xS(C.requestHeaders)},operationName:Z,fetch:Y,method:J,fetchOptions:z,middleware:G}).then((w)=>{if(X)X(w);return w}).catch((w)=>{if(X)X(w);throw w})}}async request(A,...Q){let[B,D]=Q,E=xrA(A,B,D),{headers:I,fetch:C=NW.default,method:F="POST",requestMiddleware:Y,responseMiddleware:J,...G}=this.requestConfig,{url:X}=this;if(E.signal!==void 0)G.signal=E.signal;let{query:z,operationName:U}=K_(E.document);return nXA({url:X,query:z,variables:E.variables,headers:{...xS(oXA(I)),...xS(E.requestHeaders)},operationName:U,fetch:C,method:F,fetchOptions:G,middleware:Y}).then((Z)=>{if(J)J(Z);return Z.data}).catch((Z)=>{if(J)J(Z);throw Z})}batchRequests(A,Q){let B=urA(A,Q),{headers:D,...E}=this.requestConfig;if(B.signal!==void 0)E.signal=B.signal;let I=B.documents.map(({document:F})=>K_(F).query),C=B.documents.map(({variables:F})=>F);return nXA({url:this.url,query:I,variables:C,headers:{...xS(oXA(D)),...xS(B.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??NW.default,method:this.requestConfig.method||"POST",fetchOptions:E,middleware:this.requestConfig.requestMiddleware}).then((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);return F.data}).catch((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);throw F})}setHeaders(A){return this.requestConfig.headers=A,this}setHeader(A,Q){let{headers:B}=this.requestConfig;if(B)B[A]=Q;else this.requestConfig.headers={[A]:Q};return this}setEndpoint(A){return this.url=A,this}}var nXA=async(A)=>{let{query:Q,variables:B,fetchOptions:D}=A,E=vhQ(brA(A.method??"post")),I=Array.isArray(A.query),C=await E(A),F=await ghQ(C,D.jsonSerializer??Ke),Y=Array.isArray(F)?!F.some(({data:G})=>!G):Boolean(F.data),J=Array.isArray(F)||!F.errors||Array.isArray(F.errors)&&!F.errors.length||D.errorPolicy==="all"||D.errorPolicy==="ignore";if(C.ok&&J&&Y){let{errors:G,...X}=Array.isArray(F)?F:F,z=D.errorPolicy==="ignore"?X:F;return{...I?{data:z}:z,headers:C.headers,status:C.status}}else throw new TF({...typeof F==="string"?{error:F}:F,status:C.status,headers:C.headers},{query:Q,variables:B})};var khQ=(A,Q,B,D)=>{let E=D??Ke;if(!Array.isArray(A))return E.stringify({query:A,variables:Q,operationName:B});if(typeof Q!=="undefined"&&!Array.isArray(Q))throw new Error("Cannot create request body with given variable type, array expected");let I=A.reduce((C,F,Y)=>{return C.push({query:F,variables:Q?Q[Y]:void 0}),C},[]);return E.stringify(I)},ghQ=async(A,Q)=>{let B;if(A.headers.forEach((D,E)=>{if(E.toLowerCase()==="content-type")B=D}),B&&(B.toLowerCase().startsWith("application/json")||B.toLowerCase().startsWith("application/graphql+json")||B.toLowerCase().startsWith("application/graphql-response+json")))return Q.parse(await A.text());else return A.text()},oXA=(A)=>{return typeof A==="function"?A():A},vz=(A,...Q)=>{return A.reduce((B,D,E)=>`${B}${D}${E in Q?String(Q[E]):""}`,"")};var j61=async(A,Q,B)=>{if(!Q.ok){let D=await Q.text().catch(()=>{return});throw new grA(A,Q,B,D)}};function t8(){return"8.50.0"}var P61=(A)=>{let Q=A?`${A?.name}:${A?.version}`:"missing client info";return`gitlab-language-server:${t8()} (${Q})`};function S61(A){return A!==null&&A!==void 0}var sXA=(A,Q)=>{return Object.entries(Q).forEach(([B,D])=>{if(S61(D))A.searchParams.append(B,String(D))}),A},NAA=(A)=>A.toString().replace(/\/?$/,"/"),hS=(A)=>A.replace(/^\.?\/?/,"./"),y61=(A)=>{if(A.startsWith("git@")){let Q=A.match(/git@([^:]+):(.+)/);if(Q){let[,B,D]=Q;return`https://${B}/${D}`}}if(A.startsWith("git://"))return A.replace("git://","https://");if(A.startsWith("ssh://"))return A.replace("ssh://","https://").replace(/git@([^/]+)/,"$1");return A};var bhQ=(A)=>A.split("/").pop()||"unknown resource";class tXA{#A;#Q;#B;#D;#E;constructor(A,Q,B,D,E){this.#A=A,this.#Q=Q,this.#B=new URL(NAA(D)),this.#D=E,this.#E=B}getDefaultHeaders(){return{Authorization:`Bearer ${this.#D}`,"User-Agent":P61(this.#E),"X-Gitlab-Language-Server-Version":t8()}}async fetchFromApiRaw(A){try{let Q=`Unknown request method "${A.method}", request type "${A.type}"`;switch(A.method){case"GET":return await this.#C(A);case"POST":return await this.#F(A);case"PATCH":return await this.#Y(A);case"PUT":return await this.#J(A);case"HEAD":return await this.#G(A);default:throw new Error(Q)}}catch(Q){throw new we(A,Q)}}async fetchFromApi(A){if(A.type==="graphql")return this.#I(A);let Q=await this.fetchFromApiRaw(A);return await j61(A,Q,bhQ(A.path)),Q.json()}fetchOperation=(A)=>(Q)=>this.fetchFromApi({...A,signal:Q});async#I(A){let Q=new URL("./api/graphql",this.#B),B=Xe(A.query);if(B)this.#A.debug(`[SimpleApiClient] Making GraphQL request: ${B}`);let D=async(I,C)=>{let F=I instanceof URL?I.toString():I;return this.#Q.post(F,{...C,headers:{...C?.headers},signal:A.signal})},E=new rXA(Q.href,{fetch:D,headers:{...this.getDefaultHeaders()}});try{return await E.request(A.query,A.variables)}catch(I){if(I instanceof TF)throw new YGA(A,I.response);throw new we(A,I)}}async#C(A){let Q=hS(A.path),B=new URL(Q,this.#B);return sXA(B,A.searchParams??{}),this.#Q.get(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}async#F(A){let Q=hS(A.path),B=new URL(Q,this.#B);return this.#Q.post(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#Y(A){let Q=hS(A.path),B=new URL(Q,this.#B);return this.#Q.patch(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#J(A){let Q=hS(A.path),B=new URL(Q,this.#B);return this.#Q.put(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#G(A){let Q=hS(A.path),B=new URL(Q,this.#B);return sXA(B,A.searchParams??{}),this.#Q.head(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}}var v61="api",k61=(A)=>{if(!(A instanceof Ze)||!A.isInvalidTokenOrInvalidRefresh())return{valid:!1,reason:"unknown",message:`Token validation failed: ${A}`};return{valid:!1,reason:"invalid_token",message:"Token is invalid or expired."}},g61=(A)=>{if(A.includes(v61))return;return{valid:!1,reason:"invalid_scopes",message:`Token has scope(s) ${A.map((B)=>`'${B}'`).join(", ")} (needs ${v61}).`}};async function fhQ(A,Q){let B={type:"rest",method:"GET",path:"/api/v4/personal_access_tokens/self"},{scopes:D}=await A.fetchFromApi(B),E=g61(D);if(E)return E;return{valid:!0,tokenInfo:{scopes:D,type:"pat",token:Q}}}async function xhQ(A,Q){let B={type:"rest",method:"GET",path:"/oauth/token/info"},{scope:D}=await A.fetchFromApi(B),E=g61(D);if(E)return E;return{valid:!0,tokenInfo:{scopes:D,type:"oauth",token:Q}}}async function b61(A,Q){if(!Q)return{valid:!1,message:"No token provided",reason:"invalid_token"};let B=await Promise.all([fhQ(A,Q).catch(k61),xhQ(A,Q).catch(k61)]),D=B.find((F)=>F.valid);if(D)return D;let E=B.filter((F)=>!F.valid),I=E.find((F)=>F.reason==="invalid_scopes");if(I)return I;let C=E.find((F)=>F.reason==="invalid_token");if(C)return C;return B[0]}var MAA=cA(c1(),1);var eXA=MAA.createInterfaceId("ProjectService");class km{#A;#Q;constructor(A,Q){this.#A=Q,this.#Q=d1(A,"[ProjectService]")}async getProjectFromPathWithNamespace(A){return this.#Q.debug(`Fetching details for project: ${A}`),this.#A.fetchFromApi({type:"rest",method:"GET",path:`/api/v4/projects/${encodeURIComponent(A)}`})}async getProjectIdsFromPaths(A){return(await this.#A.fetchFromApi({type:"graphql",query:vz`
1136
+ `,"")).trim()}function xqQ(A){return SrA(A).match(/^(query|mutation|subscription)\s+/)?.[1]}function hqQ(A){return SrA(A).match(/(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function Xe(A){let Q=xqQ(A),B=hqQ(A);if(Q)return`${Q}: ${B??"anonymous"}`;return}var uqQ=(A)=>{if(A.method==="GET"||A.method==="HEAD")return;if(!A.body)return;return R8("Body",JSON.stringify(A.body))},mqQ=(A)=>{if(A.method==="POST"||A.method==="PATCH"||A.method==="PUT")return;if(!A.searchParams)return;return R8("Search Params",JSON.stringify(A.searchParams))},dqQ=(A)=>{if(!A.headers)return;return R8("Headers",JSON.stringify(A.headers))},hu=(A)=>{switch(A.type){case"graphql":return lI("GraphQL Request",R8("Query",A.query.replace(/[\s\n]+/g," ").trim()),R8("Variables",JSON.stringify(A.variables)));case"rest":return lI("REST Request",R8("Method",A.method),R8("Path",A.path),dqQ(A),mqQ(A),uqQ(A));default:return R8("Unknown request type",A.type)}};var krA=(A)=>{try{return JSON.parse(A)?.error}catch{return}},cqQ=(A)=>{if(!A)return"";try{return JSON.parse(A)?.error_description??""}catch{return""}},IGA=(A,Q)=>Boolean(A.status===401&&Q&&krA(Q)==="invalid_token"),CGA=(A,Q)=>Boolean(A.status===400&&Q&&krA(Q)==="invalid_grant");class ze extends Error{request;cause;constructor(A,Q,B){super(A);this.request=Q,this.cause=B?.cause}get sanitizedMessage(){return"API request failed"}}class FGA extends ze{status;constructor(A,Q,B,D){super(A,Q,D);this.status=B}}class Ze extends FGA{type="rest";response;#A;constructor(A,Q,B,D){let E=`Fetching ${B} from ${Q.url} failed. ${cqQ(D)}`;if(IGA(Q,D))E=`Request for ${B} failed because the token is expired or revoked.`;if(CGA(Q,D))E="Request to refresh token failed, because it's revoked or already refreshed.";super(E,A,Q.status);this.response=Q,this.#A=D}isInvalidTokenOrInvalidRefresh(){return IGA(this.response,this.#A)||CGA(this.response,this.#A)}get ctx(){return lI("Error details",hu(this.request),this.#Q())}get sanitizedMessage(){if(IGA(this.response,this.#A))return"Request failed because the token is expired or revoked.";if(CGA(this.response,this.#A))return"Request to refresh token failed, because it's revoked or already refreshed.";return`Request failed with error code: ${this.response.status}`}#Q(){let A=Object.fromEntries(this.response.headers.entries());return lI("Response",R8("Status",String(this.status)),!vrA.default.isEmpty(A)?R8("Headers",JSON.stringify(A)):void 0,this.#A?R8("Response body",this.#A):void 0)}get body(){return this.#A}}var yrA=(A)=>A.errors?.map((Q)=>Q.message).join(",")||"";class YGA extends FGA{type="graphql";graphQlResponse;#A;constructor(A,Q){let B=Xe(A.query),D=`GraphQL request "${B}" failed with ${yrA(Q)}`;super(D,A,Q.status);this.graphQlResponse=Q,this.#A=B}get sanitizedMessage(){return`GraphQL request "${this.#A}" failed with status ${this.graphQlResponse.status}`}get ctx(){return lI("Error details",hu(this.request),this.#Q())}#Q(){return lI("Response",R8("Status",String(this.graphQlResponse.status)),R8("Errors",yrA(this.graphQlResponse)))}}class we extends ze{type="network";cause;constructor(A,Q){let B=Q instanceof Error?Q.message:`Network error occurred: ${Q}`;super(B,A);this.cause=Q}get ctx(){return lI("Error details",hu(this.request),this.#A())}get sanitizedMessage(){let A=this.cause,Q=A?.code||A?.errno,B=this.#Q(Q);return`Network error occurred${B?`: ${B}`:""}`}#A(){if(!this.cause||!(this.cause instanceof Error))return;let A=this.cause;if(A.code||A.errno){let Q=A.code||A.errno,B=this.#Q(Q),D=B?`${B} (${Q})`:`Error code: ${Q}`;return R8("Network issue",D)}return}#Q(A){return{ENOTFOUND:"DNS lookup failed - hostname could not be resolved",ECONNREFUSED:"Connection refused - server is not accepting connections",ECONNRESET:"Connection reset by peer - server closed the connection unexpectedly",ETIMEDOUT:"Connection timed out - server did not respond in time",EHOSTUNREACH:"Host unreachable - network route to server not available",ENETUNREACH:"Network unreachable - no network connectivity",ECONNABORTED:"Connection aborted - request was cancelled",EBADF:"Bad file descriptor - network connection issue",EPIPE:"Broken pipe - connection closed while writing data",EAI_AGAIN:"DNS lookup failed temporarily - try again later"}[A]}}class pqQ extends ze{type="timeout";#A;constructor(A,Q){let B=`Request timed out${Q?` after ${Q}ms`:""}`;super(B,A);this.#A=B}get ctx(){return lI("Error details",hu(this.request))}get sanitizedMessage(){return this.#A}}var grA=Ze;var uu={type:"rest",method:"GET",path:"/api/v4/version"};var Ke=JSON;var brA=(A)=>A.toUpperCase(),frA=(A)=>{let Q={};return A.forEach((B,D)=>{Q[D]=B}),Q};var xrA=(A,Q,B)=>{return A.document?A:{document:A,variables:Q,requestHeaders:B,signal:void 0}},hrA=(A,Q,B)=>{return A.query?A:{query:A,variables:Q,requestHeaders:B,signal:void 0}},urA=(A,Q)=>{return A.documents?A:{documents:A,requestHeaders:Q,signal:void 0}};var ZAA=cA(vQ1(),1),kQ1=(A)=>{let Q=void 0,B=A.definitions.filter((D)=>D.kind==="OperationDefinition");if(B.length===1)Q=B[0]?.name?.value;return Q},K_=(A)=>{if(typeof A==="string"){let B=void 0;try{let D=ZAA.parse(A);B=kQ1(D)}catch(D){}return{query:A,operationName:B}}let Q=kQ1(A);return{query:ZAA.print(A),operationName:Q}};class TF extends Error{constructor(A,Q){let B=`${TF.extractMessage(A)}: ${JSON.stringify({response:A,request:Q})}`;super(B);if(Object.setPrototypeOf(this,TF.prototype),this.response=A,this.request=Q,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,TF)}static extractMessage(A){return A.errors?.[0]?.message??`GraphQL Error (Code: ${A.status})`}}var NW=cA(q61(),1);var MhQ="connection_init",qhQ="connection_ack",_61="ping",L61="pong",OhQ="subscribe",_hQ="next",LhQ="error",R61="complete";class WW{get type(){return this._type}get id(){return this._id}get payload(){return this._payload}constructor(A,Q,B){this._type=A,this._payload=Q,this._id=B}get text(){let A={type:this.type};if(this.id!=null&&this.id!=null)A.id=this.id;if(this.payload!=null&&this.payload!=null)A.payload=this.payload;return JSON.stringify(A)}static parse(A,Q){let{type:B,payload:D,id:E}=JSON.parse(A);return new WW(B,Q(D),E)}}class aXA{constructor(A,{onInit:Q,onAcknowledged:B,onPing:D,onPong:E}){this.socketState={acknowledged:!1,lastRequestId:0,subscriptions:{}},this.socket=A,A.addEventListener("open",async(I)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={},A.send(ThQ(Q?await Q():null).text)}),A.addEventListener("close",(I)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={}}),A.addEventListener("error",(I)=>{console.error(I)}),A.addEventListener("message",(I)=>{try{let C=RhQ(I.data);switch(C.type){case qhQ:{if(this.socketState.acknowledged)console.warn("Duplicate CONNECTION_ACK message ignored");else if(this.socketState.acknowledged=!0,B)B(C.payload);return}case _61:{if(D)D(C.payload).then((G)=>A.send(O61(G).text));else A.send(O61(null).text);return}case L61:{if(E)E(C.payload);return}}if(!this.socketState.acknowledged)return;if(C.id===void 0||C.id===null||!this.socketState.subscriptions[C.id])return;let{query:F,variables:Y,subscriber:J}=this.socketState.subscriptions[C.id];switch(C.type){case _hQ:{if(!C.payload.errors&&C.payload.data)J.next&&J.next(C.payload.data);if(C.payload.errors)J.error&&J.error(new TF({...C.payload,status:200},{query:F,variables:Y}));return}case LhQ:{J.error&&J.error(new TF({errors:C.payload,status:200},{query:F,variables:Y}));return}case R61:{J.complete&&J.complete(),delete this.socketState.subscriptions[C.id];return}}}catch(C){console.error(C),A.close(1006)}A.close(4400,"Unknown graphql-ws message.")})}makeSubscribe(A,Q,B,D){let E=(this.socketState.lastRequestId++).toString();return this.socketState.subscriptions[E]={query:A,variables:D,subscriber:B},this.socket.send(PhQ(E,{query:A,operationName:Q,variables:D}).text),()=>{this.socket.send(ShQ(E).text),delete this.socketState.subscriptions[E]}}rawRequest(A,Q){return new Promise((B,D)=>{let E;this.rawSubscribe(A,{next:(I,C)=>E={data:I,extensions:C},error:D,complete:()=>B(E)},Q)})}request(A,Q){return new Promise((B,D)=>{let E;this.subscribe(A,{next:(I)=>E=I,error:D,complete:()=>B(E)},Q)})}subscribe(A,Q,B){let{query:D,operationName:E}=K_(A);return this.makeSubscribe(D,E,Q,B)}rawSubscribe(A,Q,B){return this.makeSubscribe(A,void 0,Q,B)}ping(A){this.socket.send(jhQ(A).text)}close(){this.socket.close(1000)}}aXA.PROTOCOL="graphql-transport-ws";function RhQ(A,Q=(B)=>B){return WW.parse(A,Q)}function ThQ(A){return new WW(MhQ,A)}function jhQ(A){return new WW(_61,A,void 0)}function O61(A){return new WW(L61,A,void 0)}function PhQ(A,Q){return new WW(OhQ,Q,A)}function ShQ(A){return new WW(R61,void 0,A)}var xS=(A)=>{let Q={};if(A)if(typeof Headers!=="undefined"&&A instanceof Headers||NW&&NW.Headers&&A instanceof NW.Headers)Q=frA(A);else if(Array.isArray(A))A.forEach(([B,D])=>{if(B&&D!==void 0)Q[B]=D});else Q=A;return Q},T61=(A)=>A.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),yhQ=(A)=>{if(!Array.isArray(A.query)){let D=A,E=[`query=${encodeURIComponent(T61(D.query))}`];if(A.variables)E.push(`variables=${encodeURIComponent(D.jsonSerializer.stringify(D.variables))}`);if(D.operationName)E.push(`operationName=${encodeURIComponent(D.operationName)}`);return E.join("&")}if(typeof A.variables!=="undefined"&&!Array.isArray(A.variables))throw new Error("Cannot create query with given variable type, array expected");let Q=A,B=A.query.reduce((D,E,I)=>{return D.push({query:T61(E),variables:Q.variables?Q.jsonSerializer.stringify(Q.variables[I]):void 0}),D},[]);return`query=${encodeURIComponent(Q.jsonSerializer.stringify(B))}`},vhQ=(A)=>async(Q)=>{let{url:B,query:D,variables:E,operationName:I,fetch:C,fetchOptions:F,middleware:Y}=Q,J={...Q.headers},G="",X=void 0;if(A==="POST"){if(X=khQ(D,E,I,F.jsonSerializer),typeof X==="string")J["Content-Type"]="application/json"}else G=yhQ({query:D,variables:E,operationName:I,jsonSerializer:F.jsonSerializer??Ke});let z={method:A,headers:J,body:X,...F},U=B,Z=z;if(Y){let w=await Promise.resolve(Y({...z,url:B,operationName:I,variables:E})),{url:H,...W}=w;U=H,Z=W}if(G)U=`${U}?${G}`;return await C(U,Z)};class rXA{constructor(A,Q={}){this.url=A,this.requestConfig=Q,this.rawRequest=async(...B)=>{let[D,E,I]=B,C=hrA(D,E,I),{headers:F,fetch:Y=NW.default,method:J="POST",requestMiddleware:G,responseMiddleware:X,...z}=this.requestConfig,{url:U}=this;if(C.signal!==void 0)z.signal=C.signal;let{operationName:Z}=K_(C.query);return nXA({url:U,query:C.query,variables:C.variables,headers:{...xS(oXA(F)),...xS(C.requestHeaders)},operationName:Z,fetch:Y,method:J,fetchOptions:z,middleware:G}).then((w)=>{if(X)X(w);return w}).catch((w)=>{if(X)X(w);throw w})}}async request(A,...Q){let[B,D]=Q,E=xrA(A,B,D),{headers:I,fetch:C=NW.default,method:F="POST",requestMiddleware:Y,responseMiddleware:J,...G}=this.requestConfig,{url:X}=this;if(E.signal!==void 0)G.signal=E.signal;let{query:z,operationName:U}=K_(E.document);return nXA({url:X,query:z,variables:E.variables,headers:{...xS(oXA(I)),...xS(E.requestHeaders)},operationName:U,fetch:C,method:F,fetchOptions:G,middleware:Y}).then((Z)=>{if(J)J(Z);return Z.data}).catch((Z)=>{if(J)J(Z);throw Z})}batchRequests(A,Q){let B=urA(A,Q),{headers:D,...E}=this.requestConfig;if(B.signal!==void 0)E.signal=B.signal;let I=B.documents.map(({document:F})=>K_(F).query),C=B.documents.map(({variables:F})=>F);return nXA({url:this.url,query:I,variables:C,headers:{...xS(oXA(D)),...xS(B.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??NW.default,method:this.requestConfig.method||"POST",fetchOptions:E,middleware:this.requestConfig.requestMiddleware}).then((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);return F.data}).catch((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);throw F})}setHeaders(A){return this.requestConfig.headers=A,this}setHeader(A,Q){let{headers:B}=this.requestConfig;if(B)B[A]=Q;else this.requestConfig.headers={[A]:Q};return this}setEndpoint(A){return this.url=A,this}}var nXA=async(A)=>{let{query:Q,variables:B,fetchOptions:D}=A,E=vhQ(brA(A.method??"post")),I=Array.isArray(A.query),C=await E(A),F=await ghQ(C,D.jsonSerializer??Ke),Y=Array.isArray(F)?!F.some(({data:G})=>!G):Boolean(F.data),J=Array.isArray(F)||!F.errors||Array.isArray(F.errors)&&!F.errors.length||D.errorPolicy==="all"||D.errorPolicy==="ignore";if(C.ok&&J&&Y){let{errors:G,...X}=Array.isArray(F)?F:F,z=D.errorPolicy==="ignore"?X:F;return{...I?{data:z}:z,headers:C.headers,status:C.status}}else throw new TF({...typeof F==="string"?{error:F}:F,status:C.status,headers:C.headers},{query:Q,variables:B})};var khQ=(A,Q,B,D)=>{let E=D??Ke;if(!Array.isArray(A))return E.stringify({query:A,variables:Q,operationName:B});if(typeof Q!=="undefined"&&!Array.isArray(Q))throw new Error("Cannot create request body with given variable type, array expected");let I=A.reduce((C,F,Y)=>{return C.push({query:F,variables:Q?Q[Y]:void 0}),C},[]);return E.stringify(I)},ghQ=async(A,Q)=>{let B;if(A.headers.forEach((D,E)=>{if(E.toLowerCase()==="content-type")B=D}),B&&(B.toLowerCase().startsWith("application/json")||B.toLowerCase().startsWith("application/graphql+json")||B.toLowerCase().startsWith("application/graphql-response+json")))return Q.parse(await A.text());else return A.text()},oXA=(A)=>{return typeof A==="function"?A():A},vz=(A,...Q)=>{return A.reduce((B,D,E)=>`${B}${D}${E in Q?String(Q[E]):""}`,"")};var j61=async(A,Q,B)=>{if(!Q.ok){let D=await Q.text().catch(()=>{return});throw new grA(A,Q,B,D)}};function t8(){return"8.50.1"}var P61=(A)=>{let Q=A?`${A?.name}:${A?.version}`:"missing client info";return`gitlab-language-server:${t8()} (${Q})`};function S61(A){return A!==null&&A!==void 0}var sXA=(A,Q)=>{return Object.entries(Q).forEach(([B,D])=>{if(S61(D))A.searchParams.append(B,String(D))}),A},NAA=(A)=>A.toString().replace(/\/?$/,"/"),hS=(A)=>A.replace(/^\.?\/?/,"./"),y61=(A)=>{if(A.startsWith("git@")){let Q=A.match(/git@([^:]+):(.+)/);if(Q){let[,B,D]=Q;return`https://${B}/${D}`}}if(A.startsWith("git://"))return A.replace("git://","https://");if(A.startsWith("ssh://"))return A.replace("ssh://","https://").replace(/git@([^/]+)/,"$1");return A};var bhQ=(A)=>A.split("/").pop()||"unknown resource";class tXA{#A;#Q;#B;#D;#E;constructor(A,Q,B,D,E){this.#A=A,this.#Q=Q,this.#B=new URL(NAA(D)),this.#D=E,this.#E=B}getDefaultHeaders(){return{Authorization:`Bearer ${this.#D}`,"User-Agent":P61(this.#E),"X-Gitlab-Language-Server-Version":t8()}}async fetchFromApiRaw(A){try{let Q=`Unknown request method "${A.method}", request type "${A.type}"`;switch(A.method){case"GET":return await this.#C(A);case"POST":return await this.#F(A);case"PATCH":return await this.#Y(A);case"PUT":return await this.#J(A);case"HEAD":return await this.#G(A);default:throw new Error(Q)}}catch(Q){throw new we(A,Q)}}async fetchFromApi(A){if(A.type==="graphql")return this.#I(A);let Q=await this.fetchFromApiRaw(A);return await j61(A,Q,bhQ(A.path)),Q.json()}fetchOperation=(A)=>(Q)=>this.fetchFromApi({...A,signal:Q});async#I(A){let Q=new URL("./api/graphql",this.#B),B=Xe(A.query);if(B)this.#A.debug(`[SimpleApiClient] Making GraphQL request: ${B}`);let D=async(I,C)=>{let F=I instanceof URL?I.toString():I;return this.#Q.post(F,{...C,headers:{...C?.headers},signal:A.signal})},E=new rXA(Q.href,{fetch:D,headers:{...this.getDefaultHeaders()}});try{return await E.request(A.query,A.variables)}catch(I){if(I instanceof TF)throw new YGA(A,I.response);throw new we(A,I)}}async#C(A){let Q=hS(A.path),B=new URL(Q,this.#B);return sXA(B,A.searchParams??{}),this.#Q.get(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}async#F(A){let Q=hS(A.path),B=new URL(Q,this.#B);return this.#Q.post(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#Y(A){let Q=hS(A.path),B=new URL(Q,this.#B);return this.#Q.patch(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#J(A){let Q=hS(A.path),B=new URL(Q,this.#B);return this.#Q.put(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#G(A){let Q=hS(A.path),B=new URL(Q,this.#B);return sXA(B,A.searchParams??{}),this.#Q.head(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}}var v61="api",k61=(A)=>{if(!(A instanceof Ze)||!A.isInvalidTokenOrInvalidRefresh())return{valid:!1,reason:"unknown",message:`Token validation failed: ${A}`};return{valid:!1,reason:"invalid_token",message:"Token is invalid or expired."}},g61=(A)=>{if(A.includes(v61))return;return{valid:!1,reason:"invalid_scopes",message:`Token has scope(s) ${A.map((B)=>`'${B}'`).join(", ")} (needs ${v61}).`}};async function fhQ(A,Q){let B={type:"rest",method:"GET",path:"/api/v4/personal_access_tokens/self"},{scopes:D}=await A.fetchFromApi(B),E=g61(D);if(E)return E;return{valid:!0,tokenInfo:{scopes:D,type:"pat",token:Q}}}async function xhQ(A,Q){let B={type:"rest",method:"GET",path:"/oauth/token/info"},{scope:D}=await A.fetchFromApi(B),E=g61(D);if(E)return E;return{valid:!0,tokenInfo:{scopes:D,type:"oauth",token:Q}}}async function b61(A,Q){if(!Q)return{valid:!1,message:"No token provided",reason:"invalid_token"};let B=await Promise.all([fhQ(A,Q).catch(k61),xhQ(A,Q).catch(k61)]),D=B.find((F)=>F.valid);if(D)return D;let E=B.filter((F)=>!F.valid),I=E.find((F)=>F.reason==="invalid_scopes");if(I)return I;let C=E.find((F)=>F.reason==="invalid_token");if(C)return C;return B[0]}var MAA=cA(c1(),1);var eXA=MAA.createInterfaceId("ProjectService");class km{#A;#Q;constructor(A,Q){this.#A=Q,this.#Q=d1(A,"[ProjectService]")}async getProjectFromPathWithNamespace(A){return this.#Q.debug(`Fetching details for project: ${A}`),this.#A.fetchFromApi({type:"rest",method:"GET",path:`/api/v4/projects/${encodeURIComponent(A)}`})}async getProjectIdsFromPaths(A){return(await this.#A.fetchFromApi({type:"graphql",query:vz`
1137
1137
  query getProjectIds($fullPaths: [String!]!) {
1138
1138
  projects(fullPaths: $fullPaths) {
1139
1139
  nodes {
@@ -1974,5 +1974,5 @@ Get help with code, planning, security, project management, and more. Duo CLI ca
1974
1974
  ${tYA(this.#E,E)}`),this.#D=d1(Q,"[TUIController]");try{let{backend:I,workspaceFolder:C,username:F,gitlabRemote:Y}=await B.initialize();if(this.#Q=I,Y)this.#B.setState({...this.#B.getState(),gitlabRemoteInfo:{status:"connected",gitlabPath:Y.namespaceWithPath,gitlabHost:Y.host}});else this.#B.setState({...this.#B.getState(),gitlabRemoteInfo:{status:"error",errorMessage:`Could not find GitLab remote info in workspace ${C}. Some features might not be available.`}});EJ(this.#K(A.getRequiredService(MZ))),this.#$(F),await Promise.all([this.#W(C,D),this.#w(Q)])}catch(I){this.#I?.handleError("Duo CLI initialization failed",I),this.#B.setState({...this.#B.getState(),criticalErrorMessage:I instanceof Error?I.message:"Unknown initialization error"}),await nq(1)}}async#K(A){try{await A.reloadAllServers(this.#E.cwd),await A.waitForAllServersSettled(30000)}catch(Q){this.#D?.warn(`Failed to preload MCP servers during controller initialization: ${Q}`)}}async#W(A,Q){this.#z=await Q.getRepositoriesForWorkspace(A)}async#w(A){let Q=process.env.GLAB_CONFIG_DIR||YZ();if(!Q){this.#D?.warn("Unable to determine baseDir for prompt history storage, this will be skipped!");return}let B=sNQ(Q,"duo-cli-prompt-history.json"),D=new rW(A,B);try{this.#X=new ToA(A),await this.#X?.load(D,this.#E.cwd),this.#D?.debug("Loaded prompt history")}catch(E){this.#D?.error("Failed to load prompt history",E)}}getCallbacks(){return{onKeyPress:(A,Q)=>{if(Q.escape&&this.#B.getState().isLoading&&this.#G){this.#D?.info("Cancelling stream due to ESC key press"),this.#G.abort();return}if(this.#B.getState().input.inputType===EZ.TEXT)this.#Y.handleKeyPress(A,Q);else this.#J.handleKeyPress(A,Q)},onSubmit:(A)=>{this.#Y.onSubmit(A)},onExit:()=>this.#L(),toggleExpanded:()=>{let A=this.#B.getState();this.#B.setState({...A,expanded:!A.expanded})},onFileSearch:async(A)=>{this.#D?.info(`onFileSearch callback triggered: ${A}`);let Q=bN1(A);return this.#D?.info(`Translated search pattern to glob pattern: ${Q}`),(await Promise.all(this.#z.map(async(D)=>{let E=await D.getFiles(Q),I=pa2(this.#E.cwd,D.fsPath);return E.map((C)=>sNQ(I,C))}))).flat()},onHistoryPrevious:()=>{let A=this.#B.getState(),Q=this.#X?.handlePrevious(A.input);if(Q)this.#B.setState({...A,input:Q})},onHistoryNext:()=>{let A=this.#B.getState(),Q=this.#X?.handleNext(A.input);if(Q)this.#B.setState({...A,input:Q})}}}#V(){let A={type:"message",id:"welcome",role:"assistant",content:_oA(),timestamp:Date.now()};this.#B.setState({elements:[A],isLoading:!1,input:Rv,expanded:!1,cwd:this.#E.cwd,gitlabRemoteInfo:{status:"not-checked"}})}#$(A){let Q=_oA(),B=this.#B.getState();this.#B.setState({...B,username:A,elements:B.elements.map((D)=>{return D.id==="welcome"?{...D,content:Q}:D})})}async#H(A){let Q=this.#B.getState();if(Q.isLoading)return;this.#B.setState({...Q,input:Rv}),await this.#M(A)}async#q(A){if(this.#B.getState().isLoading||!A.prompt.trim())return;await this.#X?.add(A.prompt),this.#Y.clear();let B={id:Date.now().toString(),type:"message",role:"user",content:A.prompt,timestamp:Date.now()};this.#N(B),await this.#M(A)}async#M(A){if(this.#B.setState({...this.#B.getState(),input:Rv,isLoading:!0}),await this.#U,!this.#Q)throw new Error("Backend not initialized");this.#G=new AbortController;try{let Q;for await(let B of this.#Q.sendMessageStream(A,this.#G.signal))Q=B,this.#O(B);if(Q?.type==="TOOL_AWAITING_APPROVAL"){let B={type:"SEND_TOOL_APPROVAL",scope:"session",toolId:Q.toolId,toolName:Q.toolName};this.#J.setChoice([{label:"Approve",value:{...B,approved:!0}},{label:"Reject",value:{...B,approved:!1}}])}}catch(Q){this.#I?.handleError("Error in message streaming",Q),this.#O({type:"ERROR",message:"Sorry, there was an error processing your message. Please try again.",timestamp:Date.now()})}finally{this.#C=void 0,this.#F.clear(),this.#G=void 0,this.#B.setState({...this.#B.getState(),isLoading:!1})}}#N(A){let Q=this.#B.getState();this.#B.setState({...Q,elements:[...Q.elements,A]})}#O(A){if(!this.#B)throw new Error("Store not initialized");let Q=this.#B.getState();switch(A.type){case"TEXT_CHUNK":{if(!this.#C||this.#C.id!==A.messageId)this.#C={id:A.messageId,type:"message",role:"assistant",content:A.content,timestamp:A.timestamp},this.#N(this.#C);else{this.#C.content+=A.content;let B=Q.elements.map((D)=>D.type==="message"&&D.id===A.messageId&&this.#C?this.#C:D);this.#B.setState({...Q,elements:B})}break}case"TOOL_START":{let B={id:A.toolId,type:"tool",name:A.name,input:A.input,state:{type:"loading"},timestamp:A.timestamp};this.#F.set(A.toolId,B),this.#_(B);break}case"TOOL_AWAITING_APPROVAL":{let B={id:A.toolId,type:"tool",name:A.toolName,input:A.input,state:{type:"approval_request",content:""},timestamp:A.timestamp};this.#F.set(A.toolId,B),this.#_(B);break}case"TOOL_COMPLETE":{let B=this.#F.get(A.toolId);if(B){let D={...B,state:A.error?{type:"error",error:A.error}:{type:"success",output:A.result}};this.#_(D),this.#F.delete(A.toolId)}break}case"ERROR":{this.#D?.error("Agent error:",A.message);let B={id:`error-${Date.now()}`,type:"error",error:`${A.message}`,timestamp:A.timestamp};this.#N(B);break}default:this.#D?.warn("Unknown agent event type:",A);break}}#_(A){let Q=this.#B.getState(),B=Q.elements.findIndex((E)=>E.type==="tool"&&E.id===A.id);if(B<0){this.#N(A);return}let D=[...Q.elements];D[B]=A,this.#B.setState({...Q,elements:D})}#L(){EJ(nq(0))}}var la2=({runConfig:A})=>{let[Q,B]=gt.useState(void 0),[D]=gt.useState(()=>new joA(B,A));if(gt.useEffect(()=>{EJ(D.initialize())},[D]),!Q)return _1(G0,{children:"Initializing..."});return _1(yVA,{state:Q,callbacks:D.getCallbacks()})},tNQ=(A,Q)=>{xc(_1(la2,{runConfig:A}),Q)};class PoA{#A;#Q;#B;#D=null;constructor(A){this.#B=A}async initialize(){let A=await sYA({logDestination:"stdout"},this.#B),Q=A.getRequiredService(g1),B=A.getRequiredService(kU),D=A.getRequiredService(BC);Q.debug(`CLI run config:
1975
1975
  ${tYA(this.#B,D)}`),this.#Q=d1(Q,"[RunController]");try{let E=A.getRequiredService(pV),{backend:I}=await E.initialize();this.#A=I}catch(E){B.handleError("Duo CLI initialization failed",E),await nq(1)}}async execute(){if(!this.#A||this.#B.command?.name!=="run")throw new Error("Controller not initialized. Call initialize() first.");let{goal:A}=this.#B.command;this.#Q?.info(`Executing workflow: ${JSON.stringify({goal:A},null,4)}`);let Q={id:Date.now().toString(),type:"message",role:"user",content:A,timestamp:Date.now()};try{let B;for await(let D of this.#A.sendMessageStream({type:"SEND_PROMPT",prompt:Q.content}))this.#E(D),B=D;if(this.#D)this.#Q?.info(JSON.stringify(this.#D,null,2));await nq(B?.type==="ERROR"?1:0)}catch(B){throw this.#Q?.error("Workflow failed:",B instanceof Error?B.message:String(B)),B}}#E(A){switch(A.type){case"TEXT_CHUNK":{if(!this.#D||this.#D.id!==A.messageId){if(this.#D)this.#Q?.info(JSON.stringify(this.#D,null,4));this.#D={id:A.messageId,type:"message",role:"assistant",content:A.content,timestamp:A.timestamp}}else this.#D.content+=A.content;break}case"TOOL_START":{this.#Q?.info(`Tool started: ${A.name}`);break}case"TOOL_COMPLETE":{if(this.#Q?.info(`Tool completed: ${A.toolId}`),A.error)this.#Q?.error(`Tool error: ${A.error}`);break}case"TOOL_AWAITING_APPROVAL":break;case"ERROR":{this.#Q?.error(`Error: ${A.message}`);break}default:{let Q=A;this.#Q?.warn(`Unexpected event received: ${JSON.stringify(Q)}`);break}}}}var ia2=()=>{return"production"},SoA,eYA=async()=>{if(!SoA){let A=DM1(),Q=await EM1(),B=t8(),D=ia2();SoA={terminalName:A,isKittyProtocolSupported:Q,duoCliVersion:B,environment:D}}return SoA};import{statSync as aa2}from"node:fs";import{isAbsolute as na2,normalize as oa2,resolve as ra2}from"node:path";function eNQ(A,Q=process.cwd()){let B;if(na2(A))B=oa2(A);else B=ra2(Q,A);return sa2(B),B}function sa2(A){try{if(!aa2(A).isDirectory())throw new CW(`Path "${A}" exists but is not a directory`)}catch(Q){if(Q instanceof Error&&Q.code==="ENOENT")throw new CW(`Directory "${A}" does not exist`);throw Q}}function AMQ(A){try{let Q=JSON.parse(A);return Array.isArray(Q)?Q.map((D)=>({category:D.Category||D.category,content:D.Content||D.content,metadata:D.metadata||{}})):[]}catch(Q){if(Q instanceof SyntaxError)throw new CW(`Invalid JSON format: ${Q.message}`);throw new CW(`AI Context Item schema error: ${Q}`)}}var ta2=d.object({gitlabBaseUrl:d.string().optional(),gitlabAuthToken:d.string().optional()}),QMQ="duo-cli-config";class BMQ{#A;#Q;#B;constructor(A,Q,B){this.#A=A,this.#B=B,this.#Q=Q}async saveConfig(A){try{let{configurationEntries:Q}=A,B={gitlabAuthToken:"",gitlabBaseUrl:""};for(let D of Q){let E=D.key;if(E in B)B[E]=D.value}return this.#A=B,await this.#Q.set(QMQ,B),NB()}catch(Q){return this.#B.error("Failed to save configuration:",Q),u4(Q)}}exit(){process.exit(0)}getDuoConfiguration(){return{gitlabBaseUrl:this.#A.gitlabBaseUrl||"https://gitlab.com",gitlabAuthToken:this.#A.gitlabAuthToken||""}}async initialize(){let A=await this.#Q.get(QMQ),Q=ta2.safeParse(A);if(!Q.success)return;let B=this.#D(this.#A);this.#A={...Q.data,...B}}isMissingConfiguration(){let{gitlabAuthToken:A,gitlabBaseUrl:Q}=this.#A;return!A||!Q}getConfigurationModel(){return{configurationEntries:[{key:"gitlabBaseUrl",value:this.#A.gitlabBaseUrl??"",displayName:"\uD83D\uDD17 GitLab Instance URL",description:"The URL of the GitLab instance to connect to.",defaultValue:"https://gitlab.com",isSensitive:!1},{key:"gitlabAuthToken",value:this.#A.gitlabAuthToken??"",displayName:"\uD83D\uDD16 GitLab Token",description:"GitLab access token with API permissions. Create one here: https://gitlab.com/-/user_settings/personal_access_tokens",defaultValue:"",isSensitive:!0}]}}#D(A){return Object.fromEntries(Object.entries(A).filter(([,Q])=>Q!=null&&Q!==""))}}var AJA=async(A={})=>{let Q=new AP,B=new HYA("info"),D=new MK(Q,B),E=new rW(D),I=new BMQ(A,E,D);return await I.initialize(),I};var yoA=(A,Q)=>{xc(_1(QM1,{initialState:A.getConfigurationModel(),controller:A}),Q)};var ea2=process.platform==="win32",QJA=tWQ(),oq=new eoA,voA=async(A)=>{let Q=global.__errorHandler;if(Q){let B=new hK("Duo CLI uncaught exception",A);Q.handleError(B.message,B)}else console.error("Duo CLI uncaught exception",A);await nq(1)};process.on("unhandledRejection",voA);process.on("uncaughtException",voA);var koA=t8();oq.name("duo").description("GitLab Duo for your command line").version(koA,"-v, --version","Display version number").option("-C, --cwd <path>","change working directory",(A)=>eNQ(A),process.cwd()).addOption(new BB("--gitlab-base-url <url>","Base URL of GitLab instance").env("GITLAB_URL").default(process.env.GITLAB_BASE_URL)).addOption(new BB("--gitlab-auth-token <token>","Authentication token for GitLab instance").env("GITLAB_TOKEN").default(process.env.GITLAB_OAUTH_TOKEN)).addOption(new BB("--log-level <level>","Set logging level").choices(Object.values(T7)).env("LOG_LEVEL").default(T7.DEBUG)).addOption(new BB("--git-http-user <user>","Username for git HTTP authentication credentials").env("DUO_WORKFLOW_GIT_HTTP_USER")).addOption(new BB("--git-http-password <password>","Password for git HTTP authentication credentials").env("DUO_WORKFLOW_GIT_HTTP_PASSWORD")).addOption(new BB("--git-user-email <email>","Email for git commit attribution").env("DUO_WORKFLOW_GIT_USER_EMAIL")).addOption(new BB("--git-user-name <name>","Name for git commit attribution").env("DUO_WORKFLOW_GIT_USER_NAME")).addOption(new BB("--telemetry-enabled","Enable collection of telemetry and error events").env("DUO_WORKFLOW_TELEMETRY_ENABLED").default(!0));QJA.registerOptions(oq.addOption(new BB("--existing-session-id <sessionId>","ID of existing session to resume").default(process.env.DUO_WORKFLOW_WORKFLOW_ID)).action(async(A)=>{let Q=oq.opts(),{cwd:B,logLevel:D,gitHttpUser:E,gitHttpPassword:I,gitUserEmail:C,gitUserName:F,telemetryEnabled:Y}=Q,{existingSessionId:J}=A,G=await AJA(Q),X=await eYA();if(G.isMissingConfiguration()){yoA(G,X);return}let U=G.getDuoConfiguration(),Z=QJA.mapConfig({cliVersion:koA,cwd:B,envInfo:X,gitHttpPassword:I,gitHttpUser:E,gitUserEmail:C,gitUserName:F,gitlabAuthToken:U.gitlabAuthToken,gitlabBaseUrl:U.gitlabBaseUrl,logLevel:D,telemetryEnabled:Y,command:{name:"tui",existingSessionId:J}},{programConfig:Q,commandConfig:A});tNQ(Z,X)}));var An2=oq.command("config").description("configuration management commands");An2.command("edit").description("edit duo CLI configuration").action(async()=>{let A=await AJA(),Q=await eYA();yoA(A,Q)});var BJA=oq.command("log").description("log management commands");BJA.command("last").description("open the last log file").action(()=>{tE1()});BJA.command("list").description("list all log files").action(()=>{eE1()});BJA.command("tail [args...]").description(`tail the last log file. "args" can be any standard ${ea2?'PowerShell "Get-Content"':'"tail"'} arguments`).allowUnknownOption().action((A)=>AI1(A||[]));BJA.command("clear").description("remove all existing log files").action(()=>{QI1()});QJA.registerOptions(oq.command("run").description("Run a workflow in non-interactive / headless mode").addOption(new BB("-g, --goal <goal>","Goal/prompt for the session").default(process.env.DUO_WORKFLOW_GOAL).makeOptionMandatory()).addOption(new BB("--ai-context-items <contextItems>","JSON encoded array of additional context items").env("DUO_WORKFLOW_ADDITIONAL_CONTEXT_CONTENT").argParser((A)=>AMQ(A))).action(async(A)=>{let Q=oq.opts(),{cwd:B,existingSessionId:D,gitHttpPassword:E,gitHttpUser:I,gitUserEmail:C,gitUserName:F,logLevel:Y,telemetryEnabled:J}=Q,{goal:G,aiContextItems:X}=A,U=(await AJA(Q)).getDuoConfiguration(),Z=await eYA();if(!U.gitlabAuthToken)throw new CW("--gitlab-auth-token / GITLAB_AUTH_TOKEN option is required.");let w=QJA.mapConfig({cliVersion:koA,cwd:B,gitlabBaseUrl:U.gitlabBaseUrl,gitlabAuthToken:U.gitlabAuthToken,logLevel:Y,envInfo:Z,gitHttpUser:I,gitHttpPassword:E,gitUserEmail:C,gitUserName:F,telemetryEnabled:J,command:{name:"run",goal:G,aiContextItems:X,existingSessionId:D}},{programConfig:Q,commandConfig:A}),H=new PoA(w);await H.initialize(),await H.execute()}));try{await oq.parseAsync(process.argv)}catch(A){await voA(A)}
1976
1976
 
1977
- //# debugId=E94DC1230A1E5FA364756E2164756E21
1977
+ //# debugId=C59F605CECBB9CD964756E2164756E21
1978
1978
  //# sourceMappingURL=index.js.map