@gitlab/duo-cli 8.62.0 → 8.62.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 +3 -3
- package/dist/index.js.map +3 -3
- package/dist/version-guard.cjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1143,7 +1143,7 @@ ${ePQ(C)}`:""};if(typeof Q==="string"){let E=B?`
|
|
|
1143
1143
|
${D(B)}`:"";this.#E(`${Q}${E}${I(B)}`,A)}else{let E=UA1(Q);if(!E)return;this.#E(`${D(E)}${I(Q)}`,A)}}#E(A,Q){let B=`${XA1.default().format("YYYY-MM-DDTHH:mm:ss:SSS")} [${Q}]: `,D=(I)=>I.replace(/\n/g,`
|
|
1144
1144
|
${" ".repeat(tPQ)}`);this.#A.write(`${B}${D(A)}`)}setContext(A){this.#B=A}debug(A,Q){this.#D(AD.DEBUG,A,Q)}info(A,Q){this.#D(AD.INFO,A,Q)}warn(A,Q){this.#D(AD.WARNING,A,Q)}error(A,Q){this.#D(AD.ERROR,A,Q)}withContext(A){let Q=new gw(this.#A,this.#Q);return Q.setContext(A),Q}}gw=G1([zA1.Injectable(T1,[kw,cu])],gw);var s0A=fA(x1(),1);var a0A=fA(x1(),1);var KA1=fA(x1(),1),b4=KA1.createInterfaceId("GitLabApiService");var VA1=fA(iD(),1);function wA1(A){return(A.split(`
|
|
1145
1145
|
`).find((Q)=>Q.trim())??A.replace(`
|
|
1146
|
-
`,"")).trim()}function ASQ(A){return wA1(A).match(/^(query|mutation|subscription)\s+/)?.[1]}function QSQ(A){return wA1(A).match(/(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function vAA(A){let Q=ASQ(A),B=QSQ(A);if(Q)return`${Q}: ${B??"anonymous"}`;return}var BSQ=(A)=>{if(A.method==="GET"||A.method==="HEAD")return;if(!A.body)return;return g2("Body",JSON.stringify(A.body))},DSQ=(A)=>{if(A.method==="POST"||A.method==="PATCH"||A.method==="PUT")return;if(!A.searchParams)return;return g2("Search Params",JSON.stringify(A.searchParams))},ISQ=(A)=>{if(!A.headers)return;return g2("Headers",JSON.stringify(A.headers))},pu=(A)=>{switch(A.type){case"graphql":return AC("GraphQL Request",g2("Query",A.query.replace(/[\s\n]+/g," ").trim()),g2("Variables",JSON.stringify(A.variables)));case"rest":return AC("REST Request",g2("Method",A.method),g2("Path",A.path),ISQ(A),DSQ(A),BSQ(A));default:return g2("Unknown request type",A.type)}};var $A1=(A)=>{try{return JSON.parse(A)?.error}catch{return}},ESQ=(A)=>{if(!A)return"";try{return JSON.parse(A)?.error_description??""}catch{return""}},HXA=(A,Q)=>Boolean(A.status===401&&Q&&$A1(Q)==="invalid_token"),VXA=(A,Q)=>Boolean(A.status===400&&Q&&$A1(Q)==="invalid_grant");class kAA extends Error{request;cause;constructor(A,Q,B){super(A);this.request=Q,this.cause=B?.cause}get sanitizedMessage(){return"API request failed"}}class $XA extends kAA{status;constructor(A,Q,B,D){super(A,Q,D);this.status=B}}class lu extends $XA{type="rest";response;#A;constructor(A,Q,B,D){let I=`Fetching ${B} from ${Q.url} failed. ${ESQ(D)}`;if(HXA(Q,D))I=`Request for ${B} failed because the token is expired or revoked.`;if(VXA(Q,D))I="Request to refresh token failed, because it's revoked or already refreshed.";super(I,A,Q.status);this.response=Q,this.#A=D}isInvalidTokenOrInvalidRefresh(){return HXA(this.response,this.#A)||VXA(this.response,this.#A)}get ctx(){return AC("Error details",pu(this.request),this.#Q())}get sanitizedMessage(){if(HXA(this.response,this.#A))return"Request failed because the token is expired or revoked.";if(VXA(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 AC("Response",g2("Status",String(this.status)),!VA1.default.isEmpty(A)?g2("Headers",JSON.stringify(A)):void 0,this.#A?g2("Response body",this.#A):void 0)}get body(){return this.#A}}var HA1=(A)=>A.errors?.map((Q)=>Q.message).join(",")||"";class WXA extends $XA{type="graphql";graphQlResponse;#A;constructor(A,Q){let B=vAA(A.query),D=`GraphQL request "${B}" failed with ${HA1(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 AC("Error details",pu(this.request),this.#Q())}#Q(){return AC("Response",g2("Status",String(this.graphQlResponse.status)),g2("Errors",HA1(this.graphQlResponse)))}}class gAA extends kAA{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 AC("Error details",pu(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 g2("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 CSQ extends kAA{type="timeout";#A;constructor(A,Q){let B=`Request timed out${Q?` after ${Q}ms`:""}`;super(B,A);this.#A=B}get ctx(){return AC("Error details",pu(this.request))}get sanitizedMessage(){return this.#A}}var WA1=lu;function bAA(A){return A instanceof lu}var iu={type:"rest",method:"GET",path:"/api/v4/version"};var NA1=(A)=>bAA(A)&&(A.status<400||A.status>=500);var fAA=JSON;var MA1=(A)=>A.toUpperCase(),qA1=(A)=>{let Q={};return A.forEach((B,D)=>{Q[D]=B}),Q};var OA1=(A,Q,B)=>{return A.document?A:{document:A,variables:Q,requestHeaders:B,signal:void 0}},LA1=(A,Q,B)=>{return A.query?A:{query:A,variables:Q,requestHeaders:B,signal:void 0}},_A1=(A,Q)=>{return A.documents?A:{documents:A,requestHeaders:Q,signal:void 0}};var g1A=fA($81(),1),W81=(A)=>{let Q=void 0,B=A.definitions.filter((D)=>D.kind==="OperationDefinition");if(B.length===1)Q=B[0]?.name?.value;return Q},dL=(A)=>{if(typeof A==="string"){let B=void 0;try{let D=g1A.parse(A);B=W81(D)}catch(D){}return{query:A,operationName:B}}let Q=W81(A);return{query:g1A.print(A),operationName:Q}};class OF extends Error{constructor(A,Q){let B=`${OF.extractMessage(A)}: ${JSON.stringify({response:A,request:Q})}`;super(B);if(Object.setPrototypeOf(this,OF.prototype),this.response=A,this.request=Q,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,OF)}static extractMessage(A){return A.errors?.[0]?.message??`GraphQL Error (Code: ${A.status})`}}var vW=fA(Y21(),1);var xiQ="connection_init",hiQ="connection_ack",U21="ping",X21="pong",miQ="subscribe",uiQ="next",diQ="error",z21="complete";class yW{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:I}=JSON.parse(A);return new yW(B,Q(D),I)}}class EKA{constructor(A,{onInit:Q,onAcknowledged:B,onPing:D,onPong:I}){this.socketState={acknowledged:!1,lastRequestId:0,subscriptions:{}},this.socket=A,A.addEventListener("open",async(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={},A.send(piQ(Q?await Q():null).text)}),A.addEventListener("close",(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={}}),A.addEventListener("error",(E)=>{console.error(E)}),A.addEventListener("message",(E)=>{try{let C=ciQ(E.data);switch(C.type){case hiQ:{if(this.socketState.acknowledged)console.warn("Duplicate CONNECTION_ACK message ignored");else if(this.socketState.acknowledged=!0,B)B(C.payload);return}case U21:{if(D)D(C.payload).then((G)=>A.send(G21(G).text));else A.send(G21(null).text);return}case X21:{if(I)I(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:J,subscriber:Y}=this.socketState.subscriptions[C.id];switch(C.type){case uiQ:{if(!C.payload.errors&&C.payload.data)Y.next&&Y.next(C.payload.data);if(C.payload.errors)Y.error&&Y.error(new OF({...C.payload,status:200},{query:F,variables:J}));return}case diQ:{Y.error&&Y.error(new OF({errors:C.payload,status:200},{query:F,variables:J}));return}case z21:{Y.complete&&Y.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 I=(this.socketState.lastRequestId++).toString();return this.socketState.subscriptions[I]={query:A,variables:D,subscriber:B},this.socket.send(iiQ(I,{query:A,operationName:Q,variables:D}).text),()=>{this.socket.send(aiQ(I).text),delete this.socketState.subscriptions[I]}}rawRequest(A,Q){return new Promise((B,D)=>{let I;this.rawSubscribe(A,{next:(E,C)=>I={data:E,extensions:C},error:D,complete:()=>B(I)},Q)})}request(A,Q){return new Promise((B,D)=>{let I;this.subscribe(A,{next:(E)=>I=E,error:D,complete:()=>B(I)},Q)})}subscribe(A,Q,B){let{query:D,operationName:I}=dL(A);return this.makeSubscribe(D,I,Q,B)}rawSubscribe(A,Q,B){return this.makeSubscribe(A,void 0,Q,B)}ping(A){this.socket.send(liQ(A).text)}close(){this.socket.close(1000)}}EKA.PROTOCOL="graphql-transport-ws";function ciQ(A,Q=(B)=>B){return yW.parse(A,Q)}function piQ(A){return new yW(xiQ,A)}function liQ(A){return new yW(U21,A,void 0)}function G21(A){return new yW(X21,A,void 0)}function iiQ(A,Q){return new yW(miQ,Q,A)}function aiQ(A){return new yW(z21,void 0,A)}var jy=(A)=>{let Q={};if(A)if(typeof Headers<"u"&&A instanceof Headers||vW&&vW.Headers&&A instanceof vW.Headers)Q=qA1(A);else if(Array.isArray(A))A.forEach(([B,D])=>{if(B&&D!==void 0)Q[B]=D});else Q=A;return Q},Z21=(A)=>A.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),niQ=(A)=>{if(!Array.isArray(A.query)){let D=A,I=[`query=${encodeURIComponent(Z21(D.query))}`];if(A.variables)I.push(`variables=${encodeURIComponent(D.jsonSerializer.stringify(D.variables))}`);if(D.operationName)I.push(`operationName=${encodeURIComponent(D.operationName)}`);return I.join("&")}if(typeof A.variables<"u"&&!Array.isArray(A.variables))throw Error("Cannot create query with given variable type, array expected");let Q=A,B=A.query.reduce((D,I,E)=>{return D.push({query:Z21(I),variables:Q.variables?Q.jsonSerializer.stringify(Q.variables[E]):void 0}),D},[]);return`query=${encodeURIComponent(Q.jsonSerializer.stringify(B))}`},oiQ=(A)=>async(Q)=>{let{url:B,query:D,variables:I,operationName:E,fetch:C,fetchOptions:F,middleware:J}=Q,Y={...Q.headers},G="",X=void 0;if(A==="POST"){if(X=riQ(D,I,E,F.jsonSerializer),typeof X==="string")Y["Content-Type"]="application/json"}else G=niQ({query:D,variables:I,operationName:E,jsonSerializer:F.jsonSerializer??fAA});let z={method:A,headers:Y,body:X,...F},U=B,Z=z;if(J){let K=await Promise.resolve(J({...z,url:B,operationName:E,variables:I})),{url:H,...W}=K;U=H,Z=W}if(G)U=`${U}?${G}`;return await C(U,Z)};class JKA{constructor(A,Q={}){this.url=A,this.requestConfig=Q,this.rawRequest=async(...B)=>{let[D,I,E]=B,C=LA1(D,I,E),{headers:F,fetch:J=vW.default,method:Y="POST",requestMiddleware:G,responseMiddleware:X,...z}=this.requestConfig,{url:U}=this;if(C.signal!==void 0)z.signal=C.signal;let{operationName:Z}=dL(C.query);return CKA({url:U,query:C.query,variables:C.variables,headers:{...jy(FKA(F)),...jy(C.requestHeaders)},operationName:Z,fetch:J,method:Y,fetchOptions:z,middleware:G}).then((K)=>{if(X)X(K);return K}).catch((K)=>{if(X)X(K);throw K})}}async request(A,...Q){let[B,D]=Q,I=OA1(A,B,D),{headers:E,fetch:C=vW.default,method:F="POST",requestMiddleware:J,responseMiddleware:Y,...G}=this.requestConfig,{url:X}=this;if(I.signal!==void 0)G.signal=I.signal;let{query:z,operationName:U}=dL(I.document);return CKA({url:X,query:z,variables:I.variables,headers:{...jy(FKA(E)),...jy(I.requestHeaders)},operationName:U,fetch:C,method:F,fetchOptions:G,middleware:J}).then((Z)=>{if(Y)Y(Z);return Z.data}).catch((Z)=>{if(Y)Y(Z);throw Z})}batchRequests(A,Q){let B=_A1(A,Q),{headers:D,...I}=this.requestConfig;if(B.signal!==void 0)I.signal=B.signal;let E=B.documents.map(({document:F})=>dL(F).query),C=B.documents.map(({variables:F})=>F);return CKA({url:this.url,query:E,variables:C,headers:{...jy(FKA(D)),...jy(B.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??vW.default,method:this.requestConfig.method||"POST",fetchOptions:I,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 CKA=async(A)=>{let{query:Q,variables:B,fetchOptions:D}=A,I=oiQ(MA1(A.method??"post")),E=Array.isArray(A.query),C=await I(A),F=await siQ(C,D.jsonSerializer??fAA),J=Array.isArray(F)?!F.some(({data:G})=>!G):Boolean(F.data),Y=Array.isArray(F)||!F.errors||Array.isArray(F.errors)&&!F.errors.length||D.errorPolicy==="all"||D.errorPolicy==="ignore";if(C.ok&&Y&&J){let{errors:G,...X}=Array.isArray(F)?F:F,z=D.errorPolicy==="ignore"?X:F;return{...E?{data:z}:z,headers:C.headers,status:C.status}}else throw new OF({...typeof F==="string"?{error:F}:F,status:C.status,headers:C.headers},{query:Q,variables:B})};var riQ=(A,Q,B,D)=>{let I=D??fAA;if(!Array.isArray(A))return I.stringify({query:A,variables:Q,operationName:B});if(typeof Q<"u"&&!Array.isArray(Q))throw Error("Cannot create request body with given variable type, array expected");let E=A.reduce((C,F,J)=>{return C.push({query:F,variables:Q?Q[J]:void 0}),C},[]);return I.stringify(E)},siQ=async(A,Q)=>{let B;if(A.headers.forEach((D,I)=>{if(I.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()},FKA=(A)=>{return typeof A==="function"?A():A},xz=(A,...Q)=>{return A.reduce((B,D,I)=>`${B}${D}${I in Q?String(Q[I]):""}`,"")};var K21=async(A,Q,B)=>{if(!Q.ok){let D=await Q.text().catch(()=>{return});throw new WA1(A,Q,B,D)}};function A2(){return"8.62.0"}var w21=(A)=>{let Q=A?`${A?.name}:${A?.version}`:"missing client info";return`gitlab-language-server:${A2()} (${Q})`};function H21(A){return A!==null&&A!==void 0}var YKA=(A,Q)=>{return Object.entries(Q).forEach(([B,D])=>{if(H21(D))A.searchParams.append(B,String(D))}),A},d1A=(A)=>A.toString().replace(/\/?$/,"/"),Py=(A)=>A.replace(/^\.?\/?/,"./"),V21=(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 tiQ=(A)=>A.split("/").pop()||"unknown resource";class GKA{#A;#Q;#B;#D;#I;constructor(A,Q,B,D,I){this.#A=A,this.#Q=Q,this.#B=new URL(d1A(D)),this.#D=I,this.#I=B}getDefaultHeaders(){return{Authorization:`Bearer ${this.#D}`,"User-Agent":w21(this.#I),"X-Gitlab-Language-Server-Version":A2()}}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.#J(A);case"PUT":return await this.#Y(A);case"HEAD":return await this.#G(A);default:throw Error(Q)}}catch(Q){throw new gAA(A,Q)}}async fetchFromApi(A){if(A.type==="graphql")return this.#E(A);let Q=await this.fetchFromApiRaw(A);return await K21(A,Q,tiQ(A.path)),Q.json()}fetchOperation=(A)=>(Q)=>this.fetchFromApi({...A,signal:Q});async#E(A){let Q=new URL("./api/graphql",this.#B),B=vAA(A.query);if(B)this.#A.debug(`[SimpleApiClient] Making GraphQL request: ${B}`);let D=async(E,C)=>{let F=E instanceof URL?E.toString():E;return this.#Q.post(F,{...C,headers:{...C?.headers},signal:A.signal})},I=new JKA(Q.href,{fetch:D,headers:{...this.getDefaultHeaders()}});try{return await I.request(A.query,A.variables)}catch(E){if(E instanceof OF)throw new WXA(A,E.response);throw new gAA(A,E)}}async#C(A){let Q=Py(A.path),B=new URL(Q,this.#B);return YKA(B,A.searchParams??{}),this.#Q.get(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}async#F(A){let Q=Py(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#J(A){let Q=Py(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#Y(A){let Q=Py(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=Py(A.path),B=new URL(Q,this.#B);return YKA(B,A.searchParams??{}),this.#Q.head(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}}var $21="api",W21=(A)=>{if(!(A instanceof lu)||!A.isInvalidTokenOrInvalidRefresh())return{valid:!1,reason:"unknown",message:`Token validation failed: ${A}`};return{valid:!1,reason:"invalid_token",message:"Token is invalid or expired."}},N21=(A)=>{if(A.includes($21))return;return{valid:!1,reason:"invalid_scopes",message:`Token has scope(s) ${A.map((B)=>`'${B}'`).join(", ")} (needs ${$21}).`}};async function eiQ(A,Q){let B={type:"rest",method:"GET",path:"/api/v4/personal_access_tokens/self"},{scopes:D}=await A.fetchFromApi(B),I=N21(D);if(I)return I;return{valid:!0,tokenInfo:{scopes:D,type:"pat",token:Q}}}async function AaQ(A,Q){let B={type:"rest",method:"GET",path:"/oauth/token/info"},{scope:D}=await A.fetchFromApi(B),I=N21(D);if(I)return I;return{valid:!0,tokenInfo:{scopes:D,type:"oauth",token:Q}}}async function M21(A,Q){if(!Q)return{valid:!1,message:"No token provided",reason:"invalid_token"};let B=await Promise.all([eiQ(A,Q).catch(W21),AaQ(A,Q).catch(W21)]),D=B.find((F)=>F.valid);if(D)return D;let I=B.filter((F)=>!F.valid),E=I.find((F)=>F.reason==="invalid_scopes");if(E)return E;let C=I.find((F)=>F.reason==="invalid_token");if(C)return C;return B[0]}var c1A=fA(x1(),1);var UKA=c1A.createInterfaceId("ProjectService");class md{#A;#Q;constructor(A,Q){this.#A=Q,this.#Q=y1(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:xz`
|
|
1146
|
+
`,"")).trim()}function ASQ(A){return wA1(A).match(/^(query|mutation|subscription)\s+/)?.[1]}function QSQ(A){return wA1(A).match(/(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function vAA(A){let Q=ASQ(A),B=QSQ(A);if(Q)return`${Q}: ${B??"anonymous"}`;return}var BSQ=(A)=>{if(A.method==="GET"||A.method==="HEAD")return;if(!A.body)return;return g2("Body",JSON.stringify(A.body))},DSQ=(A)=>{if(A.method==="POST"||A.method==="PATCH"||A.method==="PUT")return;if(!A.searchParams)return;return g2("Search Params",JSON.stringify(A.searchParams))},ISQ=(A)=>{if(!A.headers)return;return g2("Headers",JSON.stringify(A.headers))},pu=(A)=>{switch(A.type){case"graphql":return AC("GraphQL Request",g2("Query",A.query.replace(/[\s\n]+/g," ").trim()),g2("Variables",JSON.stringify(A.variables)));case"rest":return AC("REST Request",g2("Method",A.method),g2("Path",A.path),ISQ(A),DSQ(A),BSQ(A));default:return g2("Unknown request type",A.type)}};var $A1=(A)=>{try{return JSON.parse(A)?.error}catch{return}},ESQ=(A)=>{if(!A)return"";try{return JSON.parse(A)?.error_description??""}catch{return""}},HXA=(A,Q)=>Boolean(A.status===401&&Q&&$A1(Q)==="invalid_token"),VXA=(A,Q)=>Boolean(A.status===400&&Q&&$A1(Q)==="invalid_grant");class kAA extends Error{request;cause;constructor(A,Q,B){super(A);this.request=Q,this.cause=B?.cause}get sanitizedMessage(){return"API request failed"}}class $XA extends kAA{status;constructor(A,Q,B,D){super(A,Q,D);this.status=B}}class lu extends $XA{type="rest";response;#A;constructor(A,Q,B,D){let I=`Fetching ${B} from ${Q.url} failed. ${ESQ(D)}`;if(HXA(Q,D))I=`Request for ${B} failed because the token is expired or revoked.`;if(VXA(Q,D))I="Request to refresh token failed, because it's revoked or already refreshed.";super(I,A,Q.status);this.response=Q,this.#A=D}isInvalidTokenOrInvalidRefresh(){return HXA(this.response,this.#A)||VXA(this.response,this.#A)}get ctx(){return AC("Error details",pu(this.request),this.#Q())}get sanitizedMessage(){if(HXA(this.response,this.#A))return"Request failed because the token is expired or revoked.";if(VXA(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 AC("Response",g2("Status",String(this.status)),!VA1.default.isEmpty(A)?g2("Headers",JSON.stringify(A)):void 0,this.#A?g2("Response body",this.#A):void 0)}get body(){return this.#A}}var HA1=(A)=>A.errors?.map((Q)=>Q.message).join(",")||"";class WXA extends $XA{type="graphql";graphQlResponse;#A;constructor(A,Q){let B=vAA(A.query),D=`GraphQL request "${B}" failed with ${HA1(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 AC("Error details",pu(this.request),this.#Q())}#Q(){return AC("Response",g2("Status",String(this.graphQlResponse.status)),g2("Errors",HA1(this.graphQlResponse)))}}class gAA extends kAA{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 AC("Error details",pu(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 g2("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 CSQ extends kAA{type="timeout";#A;constructor(A,Q){let B=`Request timed out${Q?` after ${Q}ms`:""}`;super(B,A);this.#A=B}get ctx(){return AC("Error details",pu(this.request))}get sanitizedMessage(){return this.#A}}var WA1=lu;function bAA(A){return A instanceof lu}var iu={type:"rest",method:"GET",path:"/api/v4/version"};var NA1=(A)=>bAA(A)&&(A.status<400||A.status>=500);var fAA=JSON;var MA1=(A)=>A.toUpperCase(),qA1=(A)=>{let Q={};return A.forEach((B,D)=>{Q[D]=B}),Q};var OA1=(A,Q,B)=>{return A.document?A:{document:A,variables:Q,requestHeaders:B,signal:void 0}},LA1=(A,Q,B)=>{return A.query?A:{query:A,variables:Q,requestHeaders:B,signal:void 0}},_A1=(A,Q)=>{return A.documents?A:{documents:A,requestHeaders:Q,signal:void 0}};var g1A=fA($81(),1),W81=(A)=>{let Q=void 0,B=A.definitions.filter((D)=>D.kind==="OperationDefinition");if(B.length===1)Q=B[0]?.name?.value;return Q},dL=(A)=>{if(typeof A==="string"){let B=void 0;try{let D=g1A.parse(A);B=W81(D)}catch(D){}return{query:A,operationName:B}}let Q=W81(A);return{query:g1A.print(A),operationName:Q}};class OF extends Error{constructor(A,Q){let B=`${OF.extractMessage(A)}: ${JSON.stringify({response:A,request:Q})}`;super(B);if(Object.setPrototypeOf(this,OF.prototype),this.response=A,this.request=Q,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,OF)}static extractMessage(A){return A.errors?.[0]?.message??`GraphQL Error (Code: ${A.status})`}}var vW=fA(Y21(),1);var xiQ="connection_init",hiQ="connection_ack",U21="ping",X21="pong",miQ="subscribe",uiQ="next",diQ="error",z21="complete";class yW{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:I}=JSON.parse(A);return new yW(B,Q(D),I)}}class EKA{constructor(A,{onInit:Q,onAcknowledged:B,onPing:D,onPong:I}){this.socketState={acknowledged:!1,lastRequestId:0,subscriptions:{}},this.socket=A,A.addEventListener("open",async(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={},A.send(piQ(Q?await Q():null).text)}),A.addEventListener("close",(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={}}),A.addEventListener("error",(E)=>{console.error(E)}),A.addEventListener("message",(E)=>{try{let C=ciQ(E.data);switch(C.type){case hiQ:{if(this.socketState.acknowledged)console.warn("Duplicate CONNECTION_ACK message ignored");else if(this.socketState.acknowledged=!0,B)B(C.payload);return}case U21:{if(D)D(C.payload).then((G)=>A.send(G21(G).text));else A.send(G21(null).text);return}case X21:{if(I)I(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:J,subscriber:Y}=this.socketState.subscriptions[C.id];switch(C.type){case uiQ:{if(!C.payload.errors&&C.payload.data)Y.next&&Y.next(C.payload.data);if(C.payload.errors)Y.error&&Y.error(new OF({...C.payload,status:200},{query:F,variables:J}));return}case diQ:{Y.error&&Y.error(new OF({errors:C.payload,status:200},{query:F,variables:J}));return}case z21:{Y.complete&&Y.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 I=(this.socketState.lastRequestId++).toString();return this.socketState.subscriptions[I]={query:A,variables:D,subscriber:B},this.socket.send(iiQ(I,{query:A,operationName:Q,variables:D}).text),()=>{this.socket.send(aiQ(I).text),delete this.socketState.subscriptions[I]}}rawRequest(A,Q){return new Promise((B,D)=>{let I;this.rawSubscribe(A,{next:(E,C)=>I={data:E,extensions:C},error:D,complete:()=>B(I)},Q)})}request(A,Q){return new Promise((B,D)=>{let I;this.subscribe(A,{next:(E)=>I=E,error:D,complete:()=>B(I)},Q)})}subscribe(A,Q,B){let{query:D,operationName:I}=dL(A);return this.makeSubscribe(D,I,Q,B)}rawSubscribe(A,Q,B){return this.makeSubscribe(A,void 0,Q,B)}ping(A){this.socket.send(liQ(A).text)}close(){this.socket.close(1000)}}EKA.PROTOCOL="graphql-transport-ws";function ciQ(A,Q=(B)=>B){return yW.parse(A,Q)}function piQ(A){return new yW(xiQ,A)}function liQ(A){return new yW(U21,A,void 0)}function G21(A){return new yW(X21,A,void 0)}function iiQ(A,Q){return new yW(miQ,Q,A)}function aiQ(A){return new yW(z21,void 0,A)}var jy=(A)=>{let Q={};if(A)if(typeof Headers<"u"&&A instanceof Headers||vW&&vW.Headers&&A instanceof vW.Headers)Q=qA1(A);else if(Array.isArray(A))A.forEach(([B,D])=>{if(B&&D!==void 0)Q[B]=D});else Q=A;return Q},Z21=(A)=>A.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),niQ=(A)=>{if(!Array.isArray(A.query)){let D=A,I=[`query=${encodeURIComponent(Z21(D.query))}`];if(A.variables)I.push(`variables=${encodeURIComponent(D.jsonSerializer.stringify(D.variables))}`);if(D.operationName)I.push(`operationName=${encodeURIComponent(D.operationName)}`);return I.join("&")}if(typeof A.variables<"u"&&!Array.isArray(A.variables))throw Error("Cannot create query with given variable type, array expected");let Q=A,B=A.query.reduce((D,I,E)=>{return D.push({query:Z21(I),variables:Q.variables?Q.jsonSerializer.stringify(Q.variables[E]):void 0}),D},[]);return`query=${encodeURIComponent(Q.jsonSerializer.stringify(B))}`},oiQ=(A)=>async(Q)=>{let{url:B,query:D,variables:I,operationName:E,fetch:C,fetchOptions:F,middleware:J}=Q,Y={...Q.headers},G="",X=void 0;if(A==="POST"){if(X=riQ(D,I,E,F.jsonSerializer),typeof X==="string")Y["Content-Type"]="application/json"}else G=niQ({query:D,variables:I,operationName:E,jsonSerializer:F.jsonSerializer??fAA});let z={method:A,headers:Y,body:X,...F},U=B,Z=z;if(J){let K=await Promise.resolve(J({...z,url:B,operationName:E,variables:I})),{url:H,...W}=K;U=H,Z=W}if(G)U=`${U}?${G}`;return await C(U,Z)};class JKA{constructor(A,Q={}){this.url=A,this.requestConfig=Q,this.rawRequest=async(...B)=>{let[D,I,E]=B,C=LA1(D,I,E),{headers:F,fetch:J=vW.default,method:Y="POST",requestMiddleware:G,responseMiddleware:X,...z}=this.requestConfig,{url:U}=this;if(C.signal!==void 0)z.signal=C.signal;let{operationName:Z}=dL(C.query);return CKA({url:U,query:C.query,variables:C.variables,headers:{...jy(FKA(F)),...jy(C.requestHeaders)},operationName:Z,fetch:J,method:Y,fetchOptions:z,middleware:G}).then((K)=>{if(X)X(K);return K}).catch((K)=>{if(X)X(K);throw K})}}async request(A,...Q){let[B,D]=Q,I=OA1(A,B,D),{headers:E,fetch:C=vW.default,method:F="POST",requestMiddleware:J,responseMiddleware:Y,...G}=this.requestConfig,{url:X}=this;if(I.signal!==void 0)G.signal=I.signal;let{query:z,operationName:U}=dL(I.document);return CKA({url:X,query:z,variables:I.variables,headers:{...jy(FKA(E)),...jy(I.requestHeaders)},operationName:U,fetch:C,method:F,fetchOptions:G,middleware:J}).then((Z)=>{if(Y)Y(Z);return Z.data}).catch((Z)=>{if(Y)Y(Z);throw Z})}batchRequests(A,Q){let B=_A1(A,Q),{headers:D,...I}=this.requestConfig;if(B.signal!==void 0)I.signal=B.signal;let E=B.documents.map(({document:F})=>dL(F).query),C=B.documents.map(({variables:F})=>F);return CKA({url:this.url,query:E,variables:C,headers:{...jy(FKA(D)),...jy(B.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??vW.default,method:this.requestConfig.method||"POST",fetchOptions:I,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 CKA=async(A)=>{let{query:Q,variables:B,fetchOptions:D}=A,I=oiQ(MA1(A.method??"post")),E=Array.isArray(A.query),C=await I(A),F=await siQ(C,D.jsonSerializer??fAA),J=Array.isArray(F)?!F.some(({data:G})=>!G):Boolean(F.data),Y=Array.isArray(F)||!F.errors||Array.isArray(F.errors)&&!F.errors.length||D.errorPolicy==="all"||D.errorPolicy==="ignore";if(C.ok&&Y&&J){let{errors:G,...X}=Array.isArray(F)?F:F,z=D.errorPolicy==="ignore"?X:F;return{...E?{data:z}:z,headers:C.headers,status:C.status}}else throw new OF({...typeof F==="string"?{error:F}:F,status:C.status,headers:C.headers},{query:Q,variables:B})};var riQ=(A,Q,B,D)=>{let I=D??fAA;if(!Array.isArray(A))return I.stringify({query:A,variables:Q,operationName:B});if(typeof Q<"u"&&!Array.isArray(Q))throw Error("Cannot create request body with given variable type, array expected");let E=A.reduce((C,F,J)=>{return C.push({query:F,variables:Q?Q[J]:void 0}),C},[]);return I.stringify(E)},siQ=async(A,Q)=>{let B;if(A.headers.forEach((D,I)=>{if(I.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()},FKA=(A)=>{return typeof A==="function"?A():A},xz=(A,...Q)=>{return A.reduce((B,D,I)=>`${B}${D}${I in Q?String(Q[I]):""}`,"")};var K21=async(A,Q,B)=>{if(!Q.ok){let D=await Q.text().catch(()=>{return});throw new WA1(A,Q,B,D)}};function A2(){return"8.62.1"}var w21=(A)=>{let Q=A?`${A?.name}:${A?.version}`:"missing client info";return`gitlab-language-server:${A2()} (${Q})`};function H21(A){return A!==null&&A!==void 0}var YKA=(A,Q)=>{return Object.entries(Q).forEach(([B,D])=>{if(H21(D))A.searchParams.append(B,String(D))}),A},d1A=(A)=>A.toString().replace(/\/?$/,"/"),Py=(A)=>A.replace(/^\.?\/?/,"./"),V21=(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 tiQ=(A)=>A.split("/").pop()||"unknown resource";class GKA{#A;#Q;#B;#D;#I;constructor(A,Q,B,D,I){this.#A=A,this.#Q=Q,this.#B=new URL(d1A(D)),this.#D=I,this.#I=B}getDefaultHeaders(){return{Authorization:`Bearer ${this.#D}`,"User-Agent":w21(this.#I),"X-Gitlab-Language-Server-Version":A2()}}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.#J(A);case"PUT":return await this.#Y(A);case"HEAD":return await this.#G(A);default:throw Error(Q)}}catch(Q){throw new gAA(A,Q)}}async fetchFromApi(A){if(A.type==="graphql")return this.#E(A);let Q=await this.fetchFromApiRaw(A);return await K21(A,Q,tiQ(A.path)),Q.json()}fetchOperation=(A)=>(Q)=>this.fetchFromApi({...A,signal:Q});async#E(A){let Q=new URL("./api/graphql",this.#B),B=vAA(A.query);if(B)this.#A.debug(`[SimpleApiClient] Making GraphQL request: ${B}`);let D=async(E,C)=>{let F=E instanceof URL?E.toString():E;return this.#Q.post(F,{...C,headers:{...C?.headers},signal:A.signal})},I=new JKA(Q.href,{fetch:D,headers:{...this.getDefaultHeaders()}});try{return await I.request(A.query,A.variables)}catch(E){if(E instanceof OF)throw new WXA(A,E.response);throw new gAA(A,E)}}async#C(A){let Q=Py(A.path),B=new URL(Q,this.#B);return YKA(B,A.searchParams??{}),this.#Q.get(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}async#F(A){let Q=Py(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#J(A){let Q=Py(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#Y(A){let Q=Py(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=Py(A.path),B=new URL(Q,this.#B);return YKA(B,A.searchParams??{}),this.#Q.head(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}}var $21="api",W21=(A)=>{if(!(A instanceof lu)||!A.isInvalidTokenOrInvalidRefresh())return{valid:!1,reason:"unknown",message:`Token validation failed: ${A}`};return{valid:!1,reason:"invalid_token",message:"Token is invalid or expired."}},N21=(A)=>{if(A.includes($21))return;return{valid:!1,reason:"invalid_scopes",message:`Token has scope(s) ${A.map((B)=>`'${B}'`).join(", ")} (needs ${$21}).`}};async function eiQ(A,Q){let B={type:"rest",method:"GET",path:"/api/v4/personal_access_tokens/self"},{scopes:D}=await A.fetchFromApi(B),I=N21(D);if(I)return I;return{valid:!0,tokenInfo:{scopes:D,type:"pat",token:Q}}}async function AaQ(A,Q){let B={type:"rest",method:"GET",path:"/oauth/token/info"},{scope:D}=await A.fetchFromApi(B),I=N21(D);if(I)return I;return{valid:!0,tokenInfo:{scopes:D,type:"oauth",token:Q}}}async function M21(A,Q){if(!Q)return{valid:!1,message:"No token provided",reason:"invalid_token"};let B=await Promise.all([eiQ(A,Q).catch(W21),AaQ(A,Q).catch(W21)]),D=B.find((F)=>F.valid);if(D)return D;let I=B.filter((F)=>!F.valid),E=I.find((F)=>F.reason==="invalid_scopes");if(E)return E;let C=I.find((F)=>F.reason==="invalid_token");if(C)return C;return B[0]}var c1A=fA(x1(),1);var UKA=c1A.createInterfaceId("ProjectService");class md{#A;#Q;constructor(A,Q){this.#A=Q,this.#Q=y1(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:xz`
|
|
1147
1147
|
query getProjectIds($fullPaths: [String!]!) {
|
|
1148
1148
|
projects(fullPaths: $fullPaths) {
|
|
1149
1149
|
nodes {
|
|
@@ -1564,7 +1564,7 @@ When you have more credits, refresh.`,[60]:"GitLab Duo is already responding to
|
|
|
1564
1564
|
${J.substring(0,2000)}`);let Y=crypto.randomUUID(),G=this.#I.getProjectPath(),X=this.#I.getNamespacePath();if(!G&&!X)return{success:!1,error:"No project or namespace configured. Please open a GitLab project."};return this.#E.set(Y,{workflowId:"",context:I,aborted:!1}),B.sendNotification("executionStarted",{executionId:Y,context:I}),this.#J(Y,J,I,B),{success:!0,executionId:Y}}catch(F){return this.#A.error("Failed to start flow execution",F),{success:!1,error:F instanceof Error?F.message:"Unknown error starting execution"}}}),B.onRequest("cancelExecution",async({executionId:D})=>{this.#A.info(`Cancel execution requested: ${D}`);let I=this.#E.get(D);if(!I)return{success:!1};if(I.aborted=!0,I.workflowId)this.#I.stopWorkflow(I.workflowId);return this.#E.delete(D),{success:!0}})})}async#J(A,Q,B,D){let I=this.#E.get(A);if(!I){this.#A.warn(`Execution ${A} not found when starting`);return}let E,C="completed";try{this.#A.debug(`Starting workflow with flowConfigSchemaVersion: ${_a}`);let F=this.#I.runWorkflow({goal:B.goal||"",flowConfig:Q,flowConfigSchemaVersion:_a,metadata:{projectId:this.#I.getProjectPath(),namespaceId:this.#I.getNamespacePath()},additionalContext:[]}),J=0;for await(let Y of F){if(J+=1,this.#A.debug(`Received workflow event #${J}: ${JSON.stringify(Y)}`),I.aborted){this.#A.info(`Execution ${A} was aborted`),C="stopped";break}if(dH(Y)){this.#A.error(`Workflow error: ${Y.message}`),C="failed",D.sendNotification("executionCompleted",{executionId:A,status:"failed",error:Y.message}),this.#E.delete(A);return}let G={checkpoint:Y.checkpoint,errors:Y.errors,workflowGoal:Y.workflowGoal,workflowStatus:Y.workflowStatus};if(E=Y.checkpoint,D.sendNotification("executionUpdate",{executionId:A,event:G}),Y.workflowStatus==="FINISHED"){C="completed";break}else if(Y.workflowStatus==="FAILED"||Y.workflowStatus==="STOPPED"){C=Y.workflowStatus==="FAILED"?"failed":"stopped";break}}this.#A.debug(`Workflow generator finished. Total events: ${J}, finalStatus: ${C}, lastCheckpoint: ${E}`),D.sendNotification("executionCompleted",{executionId:A,status:C,finalCheckpoint:E})}catch(F){this.#A.error(`Workflow execution failed for ${A}`,F),D.sendNotification("executionCompleted",{executionId:A,status:"failed",error:F instanceof Error?F.message:"Unknown execution error"})}finally{this.#E.delete(A)}}}h5A=G1([m5A.Service({lifetime:m5A.ServiceLifetime.Singleton,dependencies:[T1,La,Sa,tg,tN],autoActivate:!0})],h5A);var Z3A=fA(x1(),1);var Pt6=5000;class cH{#A;#Q;#B;#D;#I=!1;constructor(){process.on("SIGINT",()=>this.exit(130,"SIGINT")),process.on("SIGTERM",()=>this.exit(143,"SIGTERM"))}setTuiCleanup(A){this.#A=A}setDiContainer(A){this.#Q=A,this.#B=y1(A.getRequiredService(T1),"[CliExitHandler]"),this.#D=A.getRequiredService(kw)}async exit(A,Q){if(this.#I)return new Promise(()=>{});if(this.#I=!0,await new Promise((D)=>{setTimeout(D,10)}),Q)this.#B?.info(`Received ${Q}, shutting down gracefully...`);else this.#B?.info("Shutting down gracefully...");let B=setTimeout(()=>{console.error("Cleanup timeout exceeded, forcing exit"),process.exit(A)},Pt6);if(this.#A)try{await this.#A()}catch(D){this.#B?.error("TUI cleanup failed",D)}if(this.#Q)try{await this.#Q.dispose()}catch(D){this.#B?.error("DI cleanup failed",D)}return this.#B?.info("Shutdown complete, good bye :)"),await this.#D?.flush?.(),clearTimeout(B),process.exit(A)}}var u5A=fA(yy(),1),d5A=fA(x1(),1);import St6 from"node:process";var yt6="https://registry.npmjs.org/@gitlab%2Fduo-cli/latest",vt6=5000,ryA=d5A.createInterfaceId("UpdateChecker");class ya{#A;#Q;constructor(A,Q){this.#A=A,this.#Q=y1(Q,"[CliUpdateChecker]")}async checkForUpdate(A){try{let Q=new AbortController,B=setTimeout(()=>Q.abort(),vt6),D=await this.#A.get(yt6,{signal:Q.signal});if(clearTimeout(B),!D.ok){let C=`Registry returned non-OK status: ${D.status}`;return Error(C)}let E=(await D.json()).version;if(!E||!u5A.default.valid(E)||!u5A.default.valid(A))return Error(`Invalid version format: latest=${E}, current=${A}`);if(!u5A.default.gt(E,A))return Error(`Already up to date (latest: ${E})`);return this.#Q.debug(`Update available: ${A} → ${E}`),{currentVersion:A,latestVersion:E,installCommand:this.#B()}}catch(Q){return Error("Update check failed",{cause:Q})}}#B(){let A=St6.env.npm_config_user_agent??"";if(A.startsWith("yarn"))return"yarn global add @gitlab/duo-cli@latest";if(A.startsWith("pnpm"))return"pnpm add -g @gitlab/duo-cli@latest";if(A.startsWith("bun"))return"bun add -g @gitlab/duo-cli@latest";return"npm install -g @gitlab/duo-cli@latest"}}ya=G1([d5A.Injectable(ryA,[XI,T1])],ya);var Rn1;(()=>{var A={975:(x)=>{function n(c){if(typeof c!="string")throw TypeError("Path must be a string. Received "+JSON.stringify(c))}function d(c,QA){for(var DA,_A="",wA=0,WA=-1,KA=0,AA=0;AA<=c.length;++AA){if(AA<c.length)DA=c.charCodeAt(AA);else{if(DA===47)break;DA=47}if(DA===47){if(WA===AA-1||KA===1);else if(WA!==AA-1&&KA===2){if(_A.length<2||wA!==2||_A.charCodeAt(_A.length-1)!==46||_A.charCodeAt(_A.length-2)!==46){if(_A.length>2){var t=_A.lastIndexOf("/");if(t!==_A.length-1){t===-1?(_A="",wA=0):wA=(_A=_A.slice(0,t)).length-1-_A.lastIndexOf("/"),WA=AA,KA=0;continue}}else if(_A.length===2||_A.length===1){_A="",wA=0,WA=AA,KA=0;continue}}QA&&(_A.length>0?_A+="/..":_A="..",wA=2)}else _A.length>0?_A+="/"+c.slice(WA+1,AA):_A=c.slice(WA+1,AA),wA=AA-WA-1;WA=AA,KA=0}else DA===46&&KA!==-1?++KA:KA=-1}return _A}var b={resolve:function(){for(var c,QA="",DA=!1,_A=arguments.length-1;_A>=-1&&!DA;_A--){var wA;_A>=0?wA=arguments[_A]:(c===void 0&&(c=process.cwd()),wA=c),n(wA),wA.length!==0&&(QA=wA+"/"+QA,DA=wA.charCodeAt(0)===47)}return QA=d(QA,!DA),DA?QA.length>0?"/"+QA:"/":QA.length>0?QA:"."},normalize:function(c){if(n(c),c.length===0)return".";var QA=c.charCodeAt(0)===47,DA=c.charCodeAt(c.length-1)===47;return(c=d(c,!QA)).length!==0||QA||(c="."),c.length>0&&DA&&(c+="/"),QA?"/"+c:c},isAbsolute:function(c){return n(c),c.length>0&&c.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var c,QA=0;QA<arguments.length;++QA){var DA=arguments[QA];n(DA),DA.length>0&&(c===void 0?c=DA:c+="/"+DA)}return c===void 0?".":b.normalize(c)},relative:function(c,QA){if(n(c),n(QA),c===QA)return"";if((c=b.resolve(c))===(QA=b.resolve(QA)))return"";for(var DA=1;DA<c.length&&c.charCodeAt(DA)===47;++DA);for(var _A=c.length,wA=_A-DA,WA=1;WA<QA.length&&QA.charCodeAt(WA)===47;++WA);for(var KA=QA.length-WA,AA=wA<KA?wA:KA,t=-1,NA=0;NA<=AA;++NA){if(NA===AA){if(KA>AA){if(QA.charCodeAt(WA+NA)===47)return QA.slice(WA+NA+1);if(NA===0)return QA.slice(WA+NA)}else wA>AA&&(c.charCodeAt(DA+NA)===47?t=NA:NA===0&&(t=0));break}var gA=c.charCodeAt(DA+NA);if(gA!==QA.charCodeAt(WA+NA))break;gA===47&&(t=NA)}var iA="";for(NA=DA+t+1;NA<=_A;++NA)NA!==_A&&c.charCodeAt(NA)!==47||(iA.length===0?iA+="..":iA+="/..");return iA.length>0?iA+QA.slice(WA+t):(WA+=t,QA.charCodeAt(WA)===47&&++WA,QA.slice(WA))},_makeLong:function(c){return c},dirname:function(c){if(n(c),c.length===0)return".";for(var QA=c.charCodeAt(0),DA=QA===47,_A=-1,wA=!0,WA=c.length-1;WA>=1;--WA)if((QA=c.charCodeAt(WA))===47){if(!wA){_A=WA;break}}else wA=!1;return _A===-1?DA?"/":".":DA&&_A===1?"//":c.slice(0,_A)},basename:function(c,QA){if(QA!==void 0&&typeof QA!="string")throw TypeError('"ext" argument must be a string');n(c);var DA,_A=0,wA=-1,WA=!0;if(QA!==void 0&&QA.length>0&&QA.length<=c.length){if(QA.length===c.length&&QA===c)return"";var KA=QA.length-1,AA=-1;for(DA=c.length-1;DA>=0;--DA){var t=c.charCodeAt(DA);if(t===47){if(!WA){_A=DA+1;break}}else AA===-1&&(WA=!1,AA=DA+1),KA>=0&&(t===QA.charCodeAt(KA)?--KA==-1&&(wA=DA):(KA=-1,wA=AA))}return _A===wA?wA=AA:wA===-1&&(wA=c.length),c.slice(_A,wA)}for(DA=c.length-1;DA>=0;--DA)if(c.charCodeAt(DA)===47){if(!WA){_A=DA+1;break}}else wA===-1&&(WA=!1,wA=DA+1);return wA===-1?"":c.slice(_A,wA)},extname:function(c){n(c);for(var QA=-1,DA=0,_A=-1,wA=!0,WA=0,KA=c.length-1;KA>=0;--KA){var AA=c.charCodeAt(KA);if(AA!==47)_A===-1&&(wA=!1,_A=KA+1),AA===46?QA===-1?QA=KA:WA!==1&&(WA=1):QA!==-1&&(WA=-1);else if(!wA){DA=KA+1;break}}return QA===-1||_A===-1||WA===0||WA===1&&QA===_A-1&&QA===DA+1?"":c.slice(QA,_A)},format:function(c){if(c===null||typeof c!="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof c);return function(QA,DA){var _A=DA.dir||DA.root,wA=DA.base||(DA.name||"")+(DA.ext||"");return _A?_A===DA.root?_A+wA:_A+"/"+wA:wA}(0,c)},parse:function(c){n(c);var QA={root:"",dir:"",base:"",ext:"",name:""};if(c.length===0)return QA;var DA,_A=c.charCodeAt(0),wA=_A===47;wA?(QA.root="/",DA=1):DA=0;for(var WA=-1,KA=0,AA=-1,t=!0,NA=c.length-1,gA=0;NA>=DA;--NA)if((_A=c.charCodeAt(NA))!==47)AA===-1&&(t=!1,AA=NA+1),_A===46?WA===-1?WA=NA:gA!==1&&(gA=1):WA!==-1&&(gA=-1);else if(!t){KA=NA+1;break}return WA===-1||AA===-1||gA===0||gA===1&&WA===AA-1&&WA===KA+1?AA!==-1&&(QA.base=QA.name=KA===0&&wA?c.slice(1,AA):c.slice(KA,AA)):(KA===0&&wA?(QA.name=c.slice(1,WA),QA.base=c.slice(1,AA)):(QA.name=c.slice(KA,WA),QA.base=c.slice(KA,AA)),QA.ext=c.slice(WA,AA)),KA>0?QA.dir=c.slice(0,KA-1):wA&&(QA.dir="/"),QA},sep:"/",delimiter:":",win32:null,posix:null};b.posix=b,x.exports=b}},Q={};function B(x){var n=Q[x];if(n!==void 0)return n.exports;var d=Q[x]={exports:{}};return A[x](d,d.exports,B),d.exports}B.d=(x,n)=>{for(var d in n)B.o(n,d)&&!B.o(x,d)&&Object.defineProperty(x,d,{enumerable:!0,get:n[d]})},B.o=(x,n)=>Object.prototype.hasOwnProperty.call(x,n),B.r=(x)=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(x,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(x,"__esModule",{value:!0})};var D={};let I;if(B.r(D),B.d(D,{URI:()=>z,Utils:()=>r}),typeof process=="object")I=process.platform==="win32";else if(typeof navigator=="object")I=navigator.userAgent.indexOf("Windows")>=0;let E=/^\w[\w\d+.-]*$/,C=/^\//,F=/^\/\//;function J(x,n){if(!x.scheme&&n)throw Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${x.authority}", path: "${x.path}", query: "${x.query}", fragment: "${x.fragment}"}`);if(x.scheme&&!E.test(x.scheme))throw Error("[UriError]: Scheme contains illegal characters.");if(x.path){if(x.authority){if(!C.test(x.path))throw Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(F.test(x.path))throw Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}let Y="",G="/",X=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class z{static isUri(x){return x instanceof z||!!x&&typeof x.authority=="string"&&typeof x.fragment=="string"&&typeof x.path=="string"&&typeof x.query=="string"&&typeof x.scheme=="string"&&typeof x.fsPath=="string"&&typeof x.with=="function"&&typeof x.toString=="function"}scheme;authority;path;query;fragment;constructor(x,n,d,b,c,QA=!1){typeof x=="object"?(this.scheme=x.scheme||Y,this.authority=x.authority||Y,this.path=x.path||Y,this.query=x.query||Y,this.fragment=x.fragment||Y):(this.scheme=function(DA,_A){return DA||_A?DA:"file"}(x,QA),this.authority=n||Y,this.path=function(DA,_A){switch(DA){case"https":case"http":case"file":_A?_A[0]!==G&&(_A=G+_A):_A=G}return _A}(this.scheme,d||Y),this.query=b||Y,this.fragment=c||Y,J(this,QA))}get fsPath(){return M(this,!1)}with(x){if(!x)return this;let{scheme:n,authority:d,path:b,query:c,fragment:QA}=x;return n===void 0?n=this.scheme:n===null&&(n=Y),d===void 0?d=this.authority:d===null&&(d=Y),b===void 0?b=this.path:b===null&&(b=Y),c===void 0?c=this.query:c===null&&(c=Y),QA===void 0?QA=this.fragment:QA===null&&(QA=Y),n===this.scheme&&d===this.authority&&b===this.path&&c===this.query&&QA===this.fragment?this:new Z(n,d,b,c,QA)}static parse(x,n=!1){let d=X.exec(x);return d?new Z(d[2]||Y,y(d[4]||Y),y(d[5]||Y),y(d[7]||Y),y(d[9]||Y),n):new Z(Y,Y,Y,Y,Y)}static file(x){let n=Y;if(I&&(x=x.replace(/\\/g,G)),x[0]===G&&x[1]===G){let d=x.indexOf(G,2);d===-1?(n=x.substring(2),x=G):(n=x.substring(2,d),x=x.substring(d)||G)}return new Z("file",n,x,Y,Y)}static from(x){let n=new Z(x.scheme,x.authority,x.path,x.query,x.fragment);return J(n,!0),n}toString(x=!1){return q(this,x)}toJSON(){return this}static revive(x){if(x){if(x instanceof z)return x;{let n=new Z(x);return n._formatted=x.external,n._fsPath=x._sep===U?x.fsPath:null,n}}return x}}let U=I?1:void 0;class Z extends z{_formatted=null;_fsPath=null;get fsPath(){return this._fsPath||(this._fsPath=M(this,!1)),this._fsPath}toString(x=!1){return x?q(this,!0):(this._formatted||(this._formatted=q(this,!1)),this._formatted)}toJSON(){let x={$mid:1};return this._fsPath&&(x.fsPath=this._fsPath,x._sep=U),this._formatted&&(x.external=this._formatted),this.path&&(x.path=this.path),this.scheme&&(x.scheme=this.scheme),this.authority&&(x.authority=this.authority),this.query&&(x.query=this.query),this.fragment&&(x.fragment=this.fragment),x}}let K={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function H(x,n,d){let b,c=-1;for(let QA=0;QA<x.length;QA++){let DA=x.charCodeAt(QA);if(DA>=97&&DA<=122||DA>=65&&DA<=90||DA>=48&&DA<=57||DA===45||DA===46||DA===95||DA===126||n&&DA===47||d&&DA===91||d&&DA===93||d&&DA===58)c!==-1&&(b+=encodeURIComponent(x.substring(c,QA)),c=-1),b!==void 0&&(b+=x.charAt(QA));else{b===void 0&&(b=x.substr(0,QA));let _A=K[DA];_A!==void 0?(c!==-1&&(b+=encodeURIComponent(x.substring(c,QA)),c=-1),b+=_A):c===-1&&(c=QA)}}return c!==-1&&(b+=encodeURIComponent(x.substring(c))),b!==void 0?b:x}function W(x){let n;for(let d=0;d<x.length;d++){let b=x.charCodeAt(d);b===35||b===63?(n===void 0&&(n=x.substr(0,d)),n+=K[b]):n!==void 0&&(n+=x[d])}return n!==void 0?n:x}function M(x,n){let d;return d=x.authority&&x.path.length>1&&x.scheme==="file"?`//${x.authority}${x.path}`:x.path.charCodeAt(0)===47&&(x.path.charCodeAt(1)>=65&&x.path.charCodeAt(1)<=90||x.path.charCodeAt(1)>=97&&x.path.charCodeAt(1)<=122)&&x.path.charCodeAt(2)===58?n?x.path.substr(1):x.path[1].toLowerCase()+x.path.substr(2):x.path,I&&(d=d.replace(/\//g,"\\")),d}function q(x,n){let d=n?W:H,b="",{scheme:c,authority:QA,path:DA,query:_A,fragment:wA}=x;if(c&&(b+=c,b+=":"),(QA||c==="file")&&(b+=G,b+=G),QA){let WA=QA.indexOf("@");if(WA!==-1){let KA=QA.substr(0,WA);QA=QA.substr(WA+1),WA=KA.lastIndexOf(":"),WA===-1?b+=d(KA,!1,!1):(b+=d(KA.substr(0,WA),!1,!1),b+=":",b+=d(KA.substr(WA+1),!1,!0)),b+="@"}QA=QA.toLowerCase(),WA=QA.lastIndexOf(":"),WA===-1?b+=d(QA,!1,!0):(b+=d(QA.substr(0,WA),!1,!0),b+=QA.substr(WA))}if(DA){if(DA.length>=3&&DA.charCodeAt(0)===47&&DA.charCodeAt(2)===58){let WA=DA.charCodeAt(1);WA>=65&&WA<=90&&(DA=`/${String.fromCharCode(WA+32)}:${DA.substr(3)}`)}else if(DA.length>=2&&DA.charCodeAt(1)===58){let WA=DA.charCodeAt(0);WA>=65&&WA<=90&&(DA=`${String.fromCharCode(WA+32)}:${DA.substr(2)}`)}b+=d(DA,!0,!1)}return _A&&(b+="?",b+=d(_A,!1,!1)),wA&&(b+="#",b+=n?wA:H(wA,!1,!1)),b}function O(x){try{return decodeURIComponent(x)}catch{return x.length>3?x.substr(0,3)+O(x.substr(3)):x}}let T=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function y(x){return x.match(T)?x.replace(T,(n)=>O(n)):x}var j=B(975);let h=j.posix||j,S="/";var r;(function(x){x.joinPath=function(n,...d){return n.with({path:h.join(n.path,...d)})},x.resolvePath=function(n,...d){let b=n.path,c=!1;b[0]!==S&&(b=S+b,c=!0);let QA=h.resolve(b,...d);return c&&QA[0]===S&&!n.authority&&(QA=QA.substring(1)),n.with({path:QA})},x.dirname=function(n){if(n.path.length===0||n.path===S)return n;let d=h.dirname(n.path);return d.length===1&&d.charCodeAt(0)===46&&(d=""),n.with({path:d})},x.basename=function(n){return h.basename(n.path)},x.extname=function(n){return h.extname(n.path)}})(r||(r={})),Rn1=D})();var{URI:GE,Utils:go8}=Rn1;var Y3A=fA(x1(),1);var c5A=ID.enum(["file","snippet","terminal","issue","merge_request","dependency","local_git","user_rule","repository","directory","agent_user_environment","os_information"]);var Tn1=fA(x1(),1),jn1=ID.enum(["open_tab","import","local_file_search","issue","merge_request","snippet","dependency","local_git","user_rule","repository","directory","shell","os"]),p5A=Tn1.createInterfaceId("AIContextProvider");class syA{#A=[];type;logger;onContextItemAdded;onBeforeContextItemRemoved;onBeforeAllContextItemsRemoved;canItemBeAdded;constructor(A="open_tab",Q){this.#A=[],this.type=A,this.logger=Q}notifyContextItemAdded(A){if(this.onContextItemAdded)this.onContextItemAdded(A)}notifyContextItemToBeRemoved(A){if(this.onBeforeContextItemRemoved)this.onBeforeContextItemRemoved(A)}notifyAllContextItemsToBeRemoved(){if(this.onBeforeAllContextItemsRemoved)this.onBeforeAllContextItemsRemoved()}async itemAllowedByPolicies(A){if(this.canItemBeAdded)return this.canItemBeAdded(A);return Promise.resolve({enabled:!0})}#Q(A){return this.#A.find((Q)=>Q.id===A)}async addSelectedContextItem(A){if(!await this.itemAllowedByPolicies(A)){this.logger.error(`Context item is not allowed by context policies: ${JSON.stringify(A)}`);return}if(A.metadata.subType!==this.type)this.logger.error(`Context item type "${A.metadata.subType}" does not match context provider type "${this.type}"`);else if(this.#Q(A.id))this.logger.error(`Context item with ID "${A.id}" already exists`);else this.#A.push(A),this.notifyContextItemAdded(A)}async removeSelectedContextItem(A){let Q=this.#A.find((D)=>D.id===A);if(!Q){let D=Error(`Item with id ${A} not found in context items.`);throw this.logger.error(D),D}this.notifyContextItemToBeRemoved(Q);let B=this.#A.indexOf(Q);this.#A.splice(B,1)}async clearSelectedContextItems(){if(this.#A.length)this.notifyAllContextItemsToBeRemoved(),this.#A=[]}async getSelectedContextItems(){return this.#A}}var Pn1=ID.object({title:ID.string(),enabled:ID.boolean(),disabledReasons:ID.array(ID.string()).optional(),subType:jn1,icon:ID.string(),secondaryText:ID.string(),subTypeLabel:ID.string(),languageId:ID.string().optional()}),kt6=ID.object({id:ID.string(),category:c5A,content:ID.string().optional(),metadata:Pn1.optional()}),po8=kt6.extend({metadata:Pn1});var eyA=fA(x1(),1);var no8=eyA.createInterfaceId("DuoChatContextManager"),Sn1=eyA.createInterfaceId("AgenticChatContextManager"),tyA={file:["open_tab","local_file_search"],snippet:["snippet"],terminal:["snippet"],issue:["issue"],merge_request:["merge_request"],dependency:["dependency"],local_git:["local_git"],repository:["repository"],user_rule:["user_rule"],directory:["directory"],agent_user_environment:["shell"],os_information:["os"]};class AvA{#A=[];#Q;#B;#D;#I;constructor(A,Q,B,D,I){this.#I=y1(A,"ChatContextManager"),this.#Q=B,this.#A=D,this.#B=I,this.#D=Q.get("workspaceFolders")??[],Q.onConfigChange((E)=>{this.#D=E.workspaceFolders??[]})}async#E(){let A=this.#A.map(async(B)=>{return await this.#B.isChatFeatureEnabled(B.chatRequiredFeature)?B:void 0});return(await Promise.all(A)).filter((B)=>B!==void 0)}async#C(A,Q){let B=Error("No provider found for type"),I=(await this.#E()).find((E)=>E.type===A);if(!I)throw B;await Q(I)}async#F(A){let B=(await this.#E()).find((D)=>D.type===A.metadata?.subType);if(!B)throw Error(`No provider found for type "${A.metadata.subType||"undefined item subtype"}"`);return B}async addSelectedContextItem(A){try{return this.#I.info(`received context item add request ${A.id}`),await this.#C(A.metadata?.subType,async(Q)=>{await Q.addSelectedContextItem(A)}),this.#I.info("added item result true"),!0}catch(Q){return this.#I.error("error adding context item",Q),!1}}async removeSelectedContextItem(A){this.#I.info(`received context item remove request ${A.id}`);try{return await this.#C(A.metadata?.subType,async(Q)=>{await Q.removeSelectedContextItem(A.id)}),this.#I.info("removed item result true"),!0}catch(Q){return this.#I.error("error removing context item",Q),!1}}async getSelectedContextItems(){let A=await this.#E(),Q=(await Promise.all(A.map((B)=>B.getSelectedContextItems()))).flat();return this.#I.info(`returning ${Q.length} current context items`),Q}async searchContextItems(A){this.#I.info(`received context search query, category: ${A.category}, query: ${A.query}`);try{let Q=[],B=tyA[A.category],D=A.workspaceFolders??this.#D;if(!D.length)this.#I.debug("No workspace folders detected.");let I={...A,workspaceFolders:D},C=(await this.#E()).filter((X)=>B.includes(X.type)).map(async(X)=>{return X.searchContextItems(I)});(await Promise.all(C)).forEach((X)=>Q.push(...X));let J=new Set((await this.getSelectedContextItems()).map((X)=>X?.id).filter((X)=>X!==void 0)),Y=Q.filter((X)=>!J.has(X.id)),G=this.#J(Y);return this.#I.info(`context search query had ${G.length} results`),G}catch(Q){return this.#I.error("error searching context items",Q),[]}}#J(A){return A.sort((Q,B)=>{if(Q.metadata?.enabled===B.metadata?.enabled)return 0;return Q.metadata?.enabled?-1:1})}async getAvailableCategories(){let Q=(await this.#E()).map((I)=>I.type),B=Object.keys(tyA),D=Q.map((I)=>B.find((E)=>tyA[E].includes(I))).filter((I)=>I!==void 0);return this.#I.info(`returning ${D.length} available context provider categories: "${D.join(", ")}"`),D}async retrieveContextItemsWithContent(A){let Q=await this.#E(),D=(await Promise.all(Q.map((I)=>I.retrieveContextItemsWithContent(A)))).flat().filter(Boolean);return Promise.all(D.map((I)=>this.#Y(I)))}async clearSelectedContextItems(){return this.#I.info("clearing all selected context items"),(await this.#E()).forEach((Q)=>Q.clearSelectedContextItems()),!0}async getItemWithContent(A){this.#I.info(`received get context item content request ${A.id}`);let B=await(await this.#F(A)).getItemWithContent(A);return this.#I.info(`retrieved context item content ${B}`),this.#Y(B)}async#Y(A){try{return await this.#Q.transform(A)}catch(Q){return this.#I.error("Error transforming context item content. Item content will be excluded.",Q),{...A,content:void 0}}}async getProviderForType(A){let Q=this.#A.find((B)=>B.type===A);if(!Q)throw Error(`No provider found for type "${A}"`);return Q}}var yn1=fA(x1(),1),Ib=yn1.createInterfaceId("AiContextTransformer");var mn1=fA(x1(),1);var vn1=fA(x1(),1);var kn1=1;class pH extends Error{name="FileNotFoundError";cause;constructor(A,Q){super(`File not found: ${A}`);this.cause=Q}}var O7=vn1.createInterfaceId("FileAccessService");var gn1=fA(x1(),1),OY=gn1.createInterfaceId("FsClient");var bn1=fA(x1(),1);var lH=async()=>{throw Error("Not implemented")};class va{promises={readFile:lH,writeFile:lH,unlink:lH,readdir:lH,mkdir:lH,rmdir:lH,stat:lH,lstat:lH,readFileFirstBytes:lH}}va=G1([bn1.Injectable(OY,[])],va);var fn1=8192;async function Eb(A,Q){let{stat:B,readFileFirstBytes:D}=Q.promises;await B(A.fsPath);try{let I=await D(A.fsPath,fn1);return QvA(I)}catch{return!0}}function QvA(A){if(A.startsWith("\uFEFF")||A.startsWith(""))return!1;if(A.startsWith("%PDF-"))return!0;let Q=/\x00/,B=/[\x00-\x08\x0B\x0C\x0E-\x1F]/,D=A.slice(0,fn1);return Q.test(D)||B.test(D)}import{posix as gt6,relative as bt6}from"path";var jR=(A)=>{return GE.file(A)};var eN=(A)=>{return GE.parse(A)},ft6=()=>{return process?.platform??"browser"};function xt6(A){return A.replace(/[\\/]/g,"/")}function ht6(A,Q){return A.scheme==="file"?!Q:!0}function xn1(A,Q){let B=ft6();if(A.scheme==="file"){let E=bt6(A.fsPath,Q.fsPath);return B==="win32"?xt6(E):E}let D=A.path||"/",I=Q.path||"/";if(ht6(A,B==="linux")){let E=0;for(let C=Math.min(D.length,I.length);E<C;E++)if(D.charCodeAt(E)!==I.charCodeAt(E)){if(D.charAt(E).toLowerCase()!==I.charAt(E).toLowerCase())break}D=I.substr(0,E)+D.substr(E)}return gt6.relative(D,I)}var hn1=(A,Q)=>Q.filter((B)=>A.startsWith(B.uri));var DvA="Binary files are unsupported";class BvA{#A;constructor(A){this.#A=y1(A,"[BinaryFileTransformer]")}async transform(A){if(!A.content)return A;if(QvA(A.content))return this.#A.debug(`Detected binary content in "${A.id}". File disabled.`),{...A,content:"",metadata:{...A.metadata,enabled:!1,disabledReasons:[...A.metadata.disabledReasons||[],DvA]}};return A}}BvA=G1([mn1.Injectable(Ib,[T1])],BvA);var un1=fA(x1(),1);class IvA{#A;#Q;constructor(A,Q){this.#Q=Q,this.#A=y1(A,"[SecretContextTransformer]")}async transform(A){if(!A.content)return A;this.#A.debug(`Transforming context item "${A.id}"`);let Q=this.#Q.redactSecrets(A.content,A.id);return{...A,content:Q}}}IvA=G1([un1.Injectable(Ib,[T1,FI])],IvA);var Cb=fA(x1(),1);var EvA=Cb.createInterfaceId("AiContextTransformerService");class ka{#A;constructor(A){this.#A=A}async transform(A){let Q=A;for(let B of this.#A)Q=await B.transform(Q);return Q}}ka=G1([Cb.Injectable(EvA,[Cb.collection(Ib)])],ka);var LY=fA(x1(),1);var dn1=fA(x1(),1),Fb=dn1.createInterfaceId("DuoFeatureAccessService");var cn1=fA(x1(),1),fF=cn1.createInterfaceId("SystemContextProvider");var iH=LY.createInterfaceId("SystemContextManager"),ir8=LY.createCollectionId(fF);class ga{#A=[];#Q;#B;constructor(A,Q,B){this.#B=y1(A,"[SystemContextManager]"),this.#A=Q,this.#Q=B}async#D(){let A=this.#A.map(async(B)=>{return await this.#I(B)?B:null});return(await Promise.all(A)).filter(Boolean)}async#I(A){try{let Q=!0;if(A.chatRequiredFeature)Q=await this.#Q.isChatFeatureEnabled(A.chatRequiredFeature),this.#B.debug(`System provider with required feature "${A.chatRequiredFeature}": ${Q}`);else this.#B.debug("System provider has no feature requirement, enabled by default");return Q}catch(Q){return this.#B.warn(`Failed to get enabled status for system provider with required feature ${A.chatRequiredFeature} treating it as disabled.`,Q),!1}}async precalculate(){let A=await this.#D();this.#B.info(`Precalculating system context for ${A.length} available providers`);let Q=A.map(async(B)=>{if("precalculate"in B&&typeof B.precalculate==="function")try{await B.precalculate()}catch(D){this.#B.warn("Error precalculating for system context provider",D)}});await Promise.all(Q),this.#B.info("System context precalculation complete")}async getSystemContextItems(){let A=await this.#D();this.#B.info(`Getting system context from ${A.length} available providers`);let Q=A.map(async(I)=>{try{return await I.getItems()}catch(E){return this.#B.error("Error getting items from system context provider",E),[]}}),D=(await Promise.all(Q)).flat();return this.#B.info(`Retrieved ${D.length} system context items`),D}}ga=G1([LY.Service({dependencies:[T1,LY.collection(fF),Fb],lifetime:LY.ServiceLifetime.Scoped}),LY.Implements(iH)],ga);var As8=l.object({category:c5A,query:l.string(),workspaceFolders:l.array(l.object({uri:l.string(),name:l.string()})).optional()});var CvA=fA(x1(),1),Js8=CvA.createInterfaceId("RepositoryService"),M2=CvA.createInterfaceId("RepositoryDiscoveryService");var pn1=fA(x1(),1),ln1=pn1.createInterfaceId("GitLsFiles");function in1(A){return A instanceof Error&&"code"in A&&A.code==="InternalError"&&A.message.includes("Unsupported dircache version: ")}var an1=fA(x1(),1),nn1=an1.createInterfaceId("GitConfigCommand");var mt6=(A)=>{let{pathname:Q}=I0A(A)||{};return Q?Q.replace(/\/$/,""):""},ut6=(A)=>A.replace(/[-[\]/{}()*+?.\\^$|]/g,"\\$&");function on1(A){let Q=A.match("^\\[([a-zA-Z0-9_-]+@.*?):(\\d+)\\]:(.*)$");if(Q)return`ssh://${Q[1]}:${Q[2]}/${Q[3]}`;let B=A.match("^ssh://([a-zA-Z0-9_-]+@.*?):(\\d+)(.*)$");if(B)return`ssh://${B[1]}:${B[2]}${B[3]}`;let D=A.match("([a-zA-Z0-9_-]+@[^:]+):(\\d+)/(.*)$");if(D)return`ssh://${D[1]}:${D[2]}/${D[3]}`;let I=A.match("([a-zA-Z0-9_-]+@.*?):(.*)");if(I)return`ssh://${I[1]}/${I[2]}`;if(A.match("^[a-zA-Z0-9_-]+@"))return`ssh://${A}`;return A}async function rn1(A,Q){try{let B=await A.listRemotes(),D=B.find((I)=>I.remote==="origin")??B[0];if(!D?.url)return;return dt6(D.url,Q)}catch(B){let D=B instanceof Error?B.message:String(B);throw Error(`Failed to parse GitLab remotes from repository: ${D}`)}}function dt6(A,Q){let{hostname:B,host:D,pathname:I}=I0A(on1(A))||{};if(!D||!I)return;if(B!==I0A(on1(Q))?.hostname)return;let C=Q||Q.trim()!==""?ut6(mt6(Q)):"",F=I.match(`(?:${C})?/:?(.+)/([^/]+?)(?:.git)?/?$`);if(!F)return;let[J,Y]=F.slice(1,3);if(!J||!Y)return;let G=`${J}/${Y}`;return{host:D,namespace:J,projectPath:Y,namespaceWithPath:G}}var ct6=["node_modules","dist",".bundle",".idea",".vscode","__pycache__",".mypy_cache",".pytest_cache",".tox",".venv"],sn1=ct6;var F3A=fA(x1(),1);var tn1=fA(x1(),1);var en1=tn1.createInterfaceId("DuoChatSnowplowTracker");var Ao1=fA(x1(),1);var Jb=Ao1.createInterfaceId("DuoWorkflowTracker");var Qo1=fA(x1(),1);var Bo1=Qo1.createInterfaceId("DuoAgentPlatformTracker");var Do1=fA(x1(),1),Io1="gitlab_extension_activity";var l5A=Do1.createInterfaceId("ExtensionActivitySnowplowTracker");var Eo1="https://gitlab.com";var FvA="https://snowplowprd.trx.gitlab.net",JvA={appId:"gitlab_ide_extension",timeInterval:5000,maxItems:10},YvA="Telemetry event context is not valid - event won't be tracked.";var B3A=fA(Dr1(),1);var jZ=fA(sr1(),1),Qt8=jZ.default.v1,Bt8=jZ.default.v3,tr1=jZ.default.v4,Dt8=jZ.default.v5,It8=jZ.default.NIL,Et8=jZ.default.version,Ct8=jZ.default.validate,Ft8=jZ.default.stringify,Jt8=jZ.default.parse;var Zs1=fA(zs1(),1),D3A=fA(x1(),1),Ks1=fA(iD(),1);class Q3A{#A=[];#Q;#B;#D;#I;#E;constructor(A,Q,B){this.#D=Q,this.#B=A,this.#Q=B,this.#I="STOPPED"}add(A){if(this.#A.push(A),this.#A.length>=this.#D)this.#C().catch(()=>{})}async#C(){if(this.#A.length>0){let A=this.#A.map((Q)=>Q);this.#A=[],await this.#Q(A)}}start(){this.#E=setTimeout(async()=>{if(await this.#C(),this.#I!=="STOPPING")this.start()},this.#B),this.#I="STARTED"}async stop(){if(this.#I="STOPPING",this.#E)clearTimeout(this.#E);this.#E=void 0,await this.#C()}}var gvA={};gJ(gvA,{self:()=>O04,id:()=>_04,description:()=>M04,default:()=>R04,allOf:()=>q04,$schema:()=>L04});var M04="Meta-schema for self-describing JSON schema",q04=[{properties:{self:{type:"object",properties:{vendor:{type:"string",pattern:"^[a-zA-Z0-9-_.]+$"},name:{type:"string",pattern:"^[a-zA-Z0-9-_]+$"},format:{type:"string",pattern:"^[a-zA-Z0-9-_]+$"},version:{type:"string",pattern:"^[0-9]+-[0-9]+-[0-9]+$"}},required:["vendor","name","format","version"],additionalProperties:!1}},required:["self"]},{$ref:"http://json-schema.org/draft-04/schema#"}],O04={vendor:"com.snowplowanalytics.self-desc",name:"schema",format:"jsonschema",version:"1-0-0"},L04="http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",_04="http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",R04={description:M04,allOf:q04,self:O04,$schema:L04,id:_04};function T04(A){let Q={};return Object.keys(A).forEach((B)=>{Q[B]=String(A[B])}),Q.stm=new Date().getTime().toString(),Q}var I3A=D3A.createInterfaceId("SnowplowService");class Kb{#A=!1;#Q;#B;#D;#I=new Zs1.default({strict:!1});#E;#C;constructor(A,Q,B){this.#B=A,this.#D=B,this.#I.addMetaSchema(gvA),Q.onConfigChange(async(D)=>{let I=D.telemetry?.trackingUrl;if(I)await this.#J({endpoint:I})}),this.#F({...JvA,endpoint:Q.get("telemetry.trackingUrl")??FvA,enabled:()=>Q.get("telemetry.enabled")??!0})}#F(A){this.#E=A,this.#Q=new Q3A(this.#E.timeInterval,this.#E.maxItems,this.#Y.bind(this)),this.#Q.start(),this.#C=B3A.trackerCore({callback:this.#Q.add.bind(this.#Q)})}async#J(A){let Q={...this.#E,...A};if(!Ks1.isEqual(this.#E,Q))await this.#Q?.stop(),this.#F(Q)}async trackStructuredEvent(A,Q){try{this.#C.track(B3A.buildStructEvent(A),Q)}catch(B){this.#D.warn("Failed to track Snowplow event",B)}}validateContext(A,Q){let B=this.#I.validate(A,Q);if(!B)this.#D.warn(YvA),this.#D.debug(`AJV validation issue:
|
|
1565
1565
|
Data: ${JSON.stringify(Q,null,2)}
|
|
1566
1566
|
Errors: ${JSON.stringify(this.#I.errors,null,2)}`);return B}async stop(){await this.#Q.stop()}async#Y(A){if(!this.#E.enabled()||this.#A)return;try{let Q=`${this.#E.endpoint}/com.snowplowanalytics.snowplow/tp2`,B={schema:"iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4",data:A.map((E)=>{let C=tr1();return E.add("eid",C),E.add("p","app"),E.add("tv","js-gitlab"),E.add("tna","gl"),E.add("aid",this.#E.appId),T04(E.build())})},D={headers:{"Content-Type":"application/json"},body:JSON.stringify(B)},I=await this.#B.post(Q,D);if(I.status!==200)this.#D.warn(`Could not send telemetry to snowplow, this warning can be safely ignored. status=${I.status}`)}catch(Q){let B=!1;if(typeof Q==="object"&&"errno"in Q){let D=Q;if("errno"in D&&D.errno==="ENOTFOUND")this.#A=!0,B=!0,this.#D.info("Disabling telemetry, unable to resolve endpoint address.");else this.#D.warn(JSON.stringify(D))}if(!B)this.#D.warn("Failed to send telemetry event, this warning can be safely ignored"),this.#D.warn(JSON.stringify(Q))}}}Kb=G1([D3A.Injectable(I3A,[XI,l4,T1])],Kb);var E3A=fA(x1(),1);var SR={GITLAB_COM:"production",GITLAB_STAGING:"staging",GITLAB_ORG:"org",GITLAB_DEVELOPMENT:"development",GITLAB_SELF_MANAGED:"self-managed"},bvA={GITLAB_COM:"https://gitlab.com",GITLAB_STAGING:"https://staging.gitlab.com",GITLAB_ORG:"https://dev.gitlab.org",GITLAB_DEVELOPMENT:"http://localhost"},Hs1="iglu:com.gitlab/gitlab_standard/jsonschema/1-1-1",ws1="Language Server",C3A=E3A.createInterfaceId("StandardContext");class wb{#A=ws1;#Q=SR.GITLAB_COM;#B=bvA.GITLAB_COM;constructor(A){this.#D(A.get()),A.onConfigChange((Q)=>this.#D(Q))}#D(A){this.#A=A?.telemetry?.extension?.name??ws1,this.#B=A?.baseUrl??Eo1,this.#Q=Vs1(this.#B)}build(A){return{schema:Hs1,data:{source:this.#A,extra:A,environment:this.#Q,host_name:this.#B}}}}wb=G1([E3A.Injectable(C3A,[l4])],wb);function Vs1(A){let{GITLAB_COM:Q,GITLAB_STAGING:B,GITLAB_ORG:D,GITLAB_DEVELOPMENT:I}=bvA;if(A===Q)return SR.GITLAB_COM;if(A===B)return SR.GITLAB_STAGING;if(A===D)return SR.GITLAB_ORG;if(A.includes(I))return SR.GITLAB_DEVELOPMENT;return SR.GITLAB_SELF_MANAGED}var fvA={$schema:"http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",description:"Standard schema for a gitlab events",self:{vendor:"com.gitlab",name:"gitlab_standard",version:"1-1-1",format:"jsonschema"},type:"object",additionalProperties:!1,required:["environment"],properties:{project_id:{description:"ID of the associated project",type:["integer","null"],minimum:0,maximum:2147483647},namespace_id:{description:"ID of the associated namespace",type:["integer","null"],minimum:0,maximum:2147483647},user_id:{description:"ID of the associated user",type:["integer","null"],minimum:0,maximum:2147483647},is_gitlab_team_member:{description:"Indicates if triggered by a GitLab team member",type:["boolean","null"]},feature_enabled_by_namespace_ids:{description:"List of namespaces that allow the user to use the tracked feature ",type:["array","null"],items:{description:"Namespace id that have the tracked feature enabled",type:"integer",minimum:0,maximum:2147483647}},environment:{description:"Name of the source environment, such as `production` or `staging`",type:"string",maxLength:32},source:{description:"Name of the source application, such as `gitlab-rails` or `gitlab-javascript`",type:["string","null"],maxLength:32},plan:{description:"Name of the plan, such as `free`, `bronze`, `silver`, `premium`, `gold` or `ultimate`",type:["string","null"],maxLength:32},google_analytics_id:{description:"Google Analytics ID from the marketing site",type:["string","null"],maxLength:32},context_generated_at:{description:"Timestamp indicating moment when context was generated",type:["string","null"],maxLength:64},realm:{type:["string","null"],description:"Self-Managed, SaaS or Dedicated",enum:["self-managed","saas","dedicated",null]},instance_id:{type:["string","null"],description:"ID of the GitLab instance where the request comes from",maxLength:255},host_name:{type:["string","null"],description:"Host name of the GitLab instance where the request comes from",maxLength:255},instance_version:{type:["string","null"],description:"Version of the GitLab instance where the request comes from",maxLength:255},global_user_id:{type:["string","null"],description:"Globally unique user ID",maxLength:64},correlation_id:{type:["string","null"],description:"Unique request id for each request",maxLength:64},extra:{description:"Any additional data associated with the event, in the form of key-value pairs",type:["object","null"]}}};var Ws1=fA(x1(),1);var xvA={};gJ(xvA,{type:()=>v04,self:()=>y04,required:()=>g04,properties:()=>b04,description:()=>S04,default:()=>$s1,additionalProperties:()=>k04,$schema:()=>P04});var P04="http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",S04="Schema for a IDE and IDE extension version informations",y04={vendor:"com.gitlab",name:"ide_extension_version",version:"1-1-0",format:"jsonschema"},v04="object",k04=!1,g04=["ide_name","ide_version","ide_vendor","extension_name","extension_version","language_server_version"],b04={ide_name:{description:"Name of the IDE, e.g. RubyMibe",type:["string","null"],maxLength:32},ide_version:{description:"Version number of the IDE, e.g. 1.81.1",type:["string","null"],maxLength:32},ide_vendor:{description:"Name of the IDEs vendor, e.g. Microsoft",type:["string","null"],maxLength:32},extension_name:{description:"Name of the IDE extension, e.g. GitLab Workflow",type:["string","null"],maxLength:32},extension_version:{description:"Version number of the IDE extension, e.g. 3.81.1",type:["string","null"],maxLength:32},language_server_version:{description:"Version number of the Language Server, e.g. 3.9.0",type:["string","null"],maxLength:32}},$s1={$schema:P04,description:S04,self:y04,type:v04,additionalProperties:k04,required:g04,properties:b04};class hvA{#A;#Q;#B;#D;#I;#E={schema:"iglu:com.gitlab/ide_extension_version/jsonschema/1-1-0",data:{}};#C=!0;constructor(A,Q,B,D,I){this.#A=A,this.#Q=Q,this.#A.onConfigChange((E)=>this.#F(E)),this.#B=B,this.#D=y1(D,`[SnowplowTracker(${I})]`),this.#I=I}#F(A){let Q=A.telemetry?.enabled;if(typeof Q<"u"&&this.#C!==Q)this.#C=Q;this.#J({extension:A.telemetry?.extension,ide:A.telemetry?.ide})}#J(A){this.#E.data={ide_name:A?.ide?.name??null,ide_vendor:A?.ide?.vendor??null,ide_version:A?.ide?.version??null,extension_name:A?.extension?.name??null,extension_version:A?.extension?.version??null,language_server_version:A2()??null}}async trackEvent(A,Q){if(!this.isEnabled())return;if(!this.hasClientContext())return;let B={category:this.#I,action:A};try{let D={};if(Q){for(let[J,Y]of Object.entries(Q))if(Y!==null&&Y!==void 0)D[J]=String(Y)}let I=this.#B.build(D),E=[I,this.#E];if(!this.#Q.validateContext(fvA,I.data)){this.#D.warn("Invalid standard context");return}if(!this.#Q.validateContext(xvA,this.#E?.data)){this.#D.warn("Invalid IDE extension context");return}await this.#Q.trackStructuredEvent(B,E)}catch(D){this.#D.error(`Failed to track ${A}`,D)}}isEnabled(){return this.#C}hasClientContext(){return Boolean(this.#E.data.ide_name||this.#E.data.extension_name)}}class Hb{#A;constructor(A,Q,B,D){this.#A=new hvA(A,Q,B,D,Io1)}async trackEvent(A,Q){this.#A.trackEvent(A,Q)}isEnabled(){return this.#A.isEnabled()}hasClientContext(){return this.#A.hasClientContext()}}Hb=G1([Ws1.Injectable(l5A,[l4,I3A,C3A,T1])],Hb);var f04=60000,x04=86400000,J3A=F3A.createInterfaceId("DailyActivityTracker");class Vb{#A;#Q;#B;#D=!1;#I;#E;constructor(A,Q,B,D){this.#A=A,this.#Q=Q,this.#B=y1(B,"[DailyActivityTracker]"),this.#E=D}async initialize(){if(this.#D)return;setInterval(()=>{this.#C().catch((A)=>{this.#B.warn("Error during activity check",A)})},f04),this.#D=!0}async#C(){if(!this.#A.isEnabled())return;if(this.#I){await this.#Y();return}let A=Date.now(),Q=await this.#G();if(this.#F(A,Q))await this.#J(A)}#F(A,Q){if(Q===null)return!0;return A-Q>=x04}async#J(A){try{if(!this.#A.hasClientContext())return;await this.#A.trackEvent("active_installation",{timestamp:A});try{await this.#U(A),this.#I=void 0}catch(Q){this.#I=A,this.#B.warn("Failed to save activity timestamp, will retry on next check",Q)}}catch(Q){this.#B.warn("Failed to send activity event",Q)}}async#Y(){if(!this.#I)return;try{await this.#U(this.#I),this.#B.info("Successfully saved pending activity timestamp"),this.#I=void 0}catch(A){this.#B.warn("Failed to retry save activity timestamp, will retry on next check",A)}}async#G(){try{let Q=(await this.#Q.get(Vk)||{})[this.#z()||""];return typeof Q==="number"?Q:null}catch(A){return this.#B.warn("Failed to get last activity timestamp",A),null}}async#U(A){let Q=await this.#Q.get(Vk)||{},B=this.#z();if(!B){this.#B.warn("No activity key available, cannot save activity timestamp");return}Q[B]=A,await this.#Q.set(Vk,Q)}#z(){let A=this.#E.get("telemetry")?.ide?.version,Q=this.#E.get("clientInfo.name");if(!A)this.#B.warn("No IDE version available, cannot store activity by ide version");return A||Q}}Vb=G1([F3A.Injectable(J3A,[l5A,Wk,T1,l4])],Vb);var eU=fA(x1(),1);var mvA=(A)=>{if(!A)return!1;if(typeof A==="boolean")return A;if(typeof A==="string"){let Q=A.toLowerCase().trim();if(Q==="true"||Q==="1"||Q==="yes")return!0;if(Q==="false"||Q==="0"||Q==="no")return!1;return!0}return Boolean(A)};import{existsSync as h04,readFileSync as m04}from"node:fs";import{isAbsolute as u04,resolve as d04}from"node:path";var c04=[".yaml",".yml",".json"];class $b extends Error{constructor(A){super(A);this.name="FlowConfigError"}}function p04(A){if(u04(A))return!0;if(A.startsWith("./")||A.startsWith(".\\"))return!0;return c04.some((Q)=>A.endsWith(Q))}function l04(A,Q){let B=d04(Q,A);if(h04(B))try{return m04(B,"utf-8")}catch(D){let I=D instanceof Error?D.message:"unknown";throw new $b(`Could not read flow config file "${B}": ${I}`)}if(p04(A))throw new $b(`Flow config file not found: "${B}". Provide a valid file path or pass the YAML/JSON content directly.`);return A}function Ns1(A,Q=process.cwd()){if(!A)return A;let B=l04(A,Q);try{return Pa(B),B}catch(D){let I=D instanceof Error?D.message:"unknown";throw new $b(`Could not parse flow config: ${I}`)}}class uvA{backendId="gitlab";registerOptions(A){if(A.addOption(new I8("--connection-type <type>","Workflow connection type").choices(["grpc","websocket"]).env("GITLAB_DUO_CONNECTION_TYPE").default("websocket")),A.name()==="run")A.addOption(new I8("--flow-config-schema-version <version>","Flow config schema version").env("DUO_WORKFLOW_FLOW_CONFIG_SCHEMA_VERSION")),A.addOption(new I8("--flow-config <config>","Flow config (YAML/JSON content or file path)").env("DUO_WORKFLOW_FLOW_CONFIG").argParser((Q)=>{let B=A.parent?.opts().cwd??process.cwd();try{return Ns1(Q,B)}catch(D){if(D instanceof $b)throw new PAA(D.message);throw D}})),A.addOption(new I8("--workflow-type <type>",'Workflow type (e.g. "chat", "software_development")').default("chat").env("DUO_WORKFLOW_DEFINITION")),A.addOption(new I8("--duo-workflow-service-server <url>","Duo Workflow Service server URL").env("DUO_WORKFLOW_SERVICE_SERVER")),A.addOption(new I8("--duo-workflow-service-token <token>","Duo Workflow Service authentication token").env("DUO_WORKFLOW_SERVICE_TOKEN")),A.addOption(new I8("--duo-workflow-metadata <json>","Pre-computed workflow metadata JSON").env("DUO_WORKFLOW_METADATA").argParser((Q)=>{if(!Q)return;try{return JSON.parse(Q)}catch(B){let D=B instanceof Error?B.message:"unknown";throw new PAA(`Could not parse workflow metadata JSON: ${D}`)}})),A.addOption(new I8("--duo-workflow-project-id <id>","GitLab project ID").env("DUO_WORKFLOW_PROJECT_ID")),A.addOption(new I8("--duo-workflow-namespace-id <id>","GitLab namespace ID").env("DUO_WORKFLOW_NAMESPACE_ID")),A.addOption(new I8("--gitlab-project-path <path>","GitLab project path").env("GITLAB_PROJECT_PATH")),A.addOption(new I8("--duo-workflow-global-user-id <id>","Global user ID").env("DUO_WORKFLOW_GLOBAL_USER_ID")),A.addOption(new I8("--duo-workflow-instance-id <id>","GitLab instance ID").env("DUO_WORKFLOW_INSTANCE_ID")),A.addOption(new I8("--duo-workflow-realm <realm>","GitLab realm (e.g., saas, self-managed)").env("DUO_WORKFLOW_SERVICE_REALM")),A.addOption(new I8("--agent-platform-gitlab-version <version>","GitLab instance version").env("AGENT_PLATFORM_GITLAB_VERSION")),A.addOption(new I8("--agent-platform-feature-setting-name <name>","Agent platform feature setting name").env("AGENT_PLATFORM_FEATURE_SETTING_NAME")),A.addOption(new I8("--insecure [value]","Allow insecure (non-TLS) connections to Duo Workflow Service").env("DUO_WORKFLOW_INSECURE").default("false").argParser((Q)=>mvA(Q))),A.hook("preAction",(Q,B)=>{this.#Q(B.opts())})}mapConfig(A,{commandConfig:Q,programConfig:B}){let{connectionType:D}=B,I={...A,connectionType:D};if(A.command.name==="run"){let{flowConfigSchemaVersion:E,flowConfig:C,workflowType:F,duoWorkflowProjectId:J,duoWorkflowNamespaceId:Y,gitlabProjectPath:G,agentPlatformFeatureSettingName:X}=Q,z={...A.command,flowConfigSchemaVersion:E,flowConfig:C,workflowType:F||"chat",workflowToken:this.#A(Q,A),duoWorkflowProjectId:J,duoWorkflowNamespaceId:Y,gitlabProjectPath:G,agentPlatformFeatureSettingName:X};return{...I,command:z}}return I}#A(A,Q){let{duoWorkflowServiceServer:B,duoWorkflowServiceToken:D}=A;if(!B||!D)return;let{duoWorkflowMetadata:I}=A,E=mvA(A.insecure),C=!E;if(E&&B.includes(":443"))console.warn("\x1B[33m%s\x1B[0m",'WARNING: Using insecure (non-TLS) mode with port 443. This will likely fail. Unset DUO_WORKFLOW_INSECURE or set it to "false" for production endpoints.');let F={"X-Gitlab-Host-Name":I?.hostname||"unknown","X-Gitlab-Instance-Id":A.duoWorkflowInstanceId||I?.instanceId||"unknown","X-Gitlab-Realm":A.duoWorkflowRealm||I?.realm||"unknown","X-Gitlab-Version":A.agentPlatformGitlabVersion||I?.version||"unknown","X-Gitlab-Global-User-Id":A.duoWorkflowGlobalUserId||I?.globalUserId||"unknown","X-Gitlab-Feature-Enabled-By-Namespace-Ids":I?.featureNamespaceIds||"","X-Gitlab-Language-Server-Version":A2(),"X-Gitlab-Agent-Platform-Model-Metadata":I?.modelMetadata||""},J=3600000,Y=Date.now()+J*3;return{gitlab_rails:{base_url:I?.gitlabBaseUrl||Q.gitlabBaseUrl,token:Q.gitlabAuthToken,token_expires_at:new Date(Y).toISOString()},duo_workflow_executor:{executor_binary_url:"",executor_binary_urls:{},version:A2()},duo_workflow_service:{base_url:A.duoWorkflowServiceServer,token:A.duoWorkflowServiceToken,secure:C,token_expires_at:Y/1000,headers:F},workflow_metadata:{is_team_member:!1,extended_logging:!1,...I||{}}}}#Q(A){let Q=["duoWorkflowServiceServer","duoWorkflowServiceToken","duoWorkflowMetadata","duoWorkflowProjectId","duoWorkflowNamespaceId","gitlabProjectPath","duoWorkflowGlobalUserId","duoWorkflowInstanceId","duoWorkflowRealm","agentPlatformGitlabVersion"],B=Q.filter((I)=>A[I]),D=Q.filter((I)=>A[I]===void 0).map((I)=>`"${I}"`);if(B.length>0&&D.length>0)throw new PAA(`When using CI pre-configured tokens, all flags must be provided. Missing: ${D.join(", ")}. Either provide all CI token flags or none.`)}}var Ms1;((D)=>{D.ClaudeSonnet4="claude-sonnet-4-20250514";D.ClaudeSonnet45="claude-sonnet-4-5-20250929";D.ClaudeOpus45="claude-opus-4-5-20251101"})(Ms1||={});class dvA{backendId="anthropic";registerOptions(A){let Q=Object.values(Ms1);A.addOption(new I8("--model <model>",`Anthropic model to use (supported: ${Q.join(", ")})`).env("ANTHROPIC_MODEL").default("claude-sonnet-4-5-20250929"))}mapConfig(A,{programConfig:Q}){let{model:B}=Q;return{...A,model:B}}}var i04="gitlab",a04=[new uvA,new dvA];function ua(){let A=process.env.CLI_BACKEND,Q=i04;if(A==="anthropic"||A==="gitlab")Q=A;return Q}function qs1(){let A=ua(),Q=a04.find((B)=>B.backendId===A);if(!Q)throw Error(`CLI backend config adapter with id ${A} was not found, this means the application has a critical bug, please report it, you can't fix it yourself.`);return Q}var ca=eU.createInterfaceId("CliBackendFactory"),cvA=eU.createInterfaceId("BackendFactory");class da{#A;#Q;constructor(A,Q){this.#A=y1(A,"[BackendFactory]"),this.#Q=Q}create(){let A=ua(),Q=this.#Q.find((B)=>B.backendId===A);if(!Q)throw Error(`No factory registered for backend: "${A}"`);return this.#A.debug(`Creating backend via factory: "${A}"`),Q.create()}}da=G1([eU.Implements(cvA),eU.Service({dependencies:[T1,eU.collection(ca)],lifetime:eU.ServiceLifetime.Singleton})],da);var _s1=fA(x1(),1);var Os1=fA(x1(),1),X9=Os1.createInterfaceId("CliRunConfig");var pa="Duo CLI",Ls1="GitLab";function Rs1(A){return A&&"initialize"in A&&typeof A.initialize==="function"}class DM{#A;#Q;#B;#D;#I=new Z7;#E;#C;constructor(A,Q,B){let{gitlabBaseUrl:D,gitlabAuthToken:I}=A;this.#Q=y1(Q,"[CliApiService]"),this.#B=new URL(D),this.#D=I,this.#A=new GKA(Q,B,{name:pa,version:A2()},D,I)}async initialize(){this.#Q.debug("Starting API initialization");let A;try{A=await M21(this.#A,this.#D)}catch{return this.#I.fire({isInValidState:!1,validationMessage:"Failed to check token validity"}),c6(Error("Failed to check token validity"))}if(!A.valid){let D=`${A.message} Reason: ${A.reason}
|
|
1567
|
-
Run 'duo config edit' to update your token.`;return this.#I.fire({isInValidState:!1,validationMessage:D}),c6(Error(D))}let Q;try{Q=(await this.#A.fetchFromApi(iu)).version}catch{return this.#I.fire({isInValidState:!1,validationMessage:"Failed to fetch GitLab instance version"}),c6(Error("Failed to fetch GitLab instance version"))}let B={instanceVersion:Q,instanceUrl:this.#B};return this.#E=B,this.#C=A.tokenInfo,this.#I.fire({isInValidState:!0,instanceInfo:B,tokenInfo:A.tokenInfo}),this.#Q.debug("API initialization complete, onApiReconfigured event fired"),i4(void 0)}get instanceInfo(){return this.#E}get tokenInfo(){return this.#C}fetchFromApi(A){return this.#A.fetchFromApi(A)}fetchFromApiRaw(A){return this.#A.fetchFromApiRaw(A)}fetchOperation(A){return this.#A.fetchOperation(A)}connectToCable(){throw Error("Method not implemented.")}onApiReconfigured=this.#I.event;getSimpleClient(){return this.#A}}DM=G1([_s1.Injectable(b4,[X9,T1,XI])],DM);class oH{#A;#Q;#B;#D;#I;#E;#C;#F;#J;constructor(A,Q,B,D,I,E,C,F,J){this.#A=y1(A,"[CliInitializationService]"),this.#Q=Q,this.#B=B,this.#D=D,this.#I=I,this.#E=E,this.#C=C,this.#F=F,this.#J=J}async initialize(){this.#A.debug("Starting CLI common initialization");let[,A]=await Promise.all([this.#Y(),this.#G()]),Q=await this.#U(),B=this.#E.create(),D=this.#X(),[I,E]=await Promise.all([B.initialize(D),this.#z()]);return BD(this.#J.initialize()),{backend:B,sessionId:I.sessionId,username:E,systemContext:Q,workspaceFolder:A.workspaceFolder,gitlabRemote:A.gitlabRemote}}async#Y(){if(Rs1(this.#B)){let A=await this.#B.initialize();if(A.isErr())throw this.#A.error("API initialization failed:",A.error),A.error}this.#A.info("API service initialized successfully")}async#G(){let{cwd:A}=this.#C;this.#Q.set("cwd",GE.file(A).toString());let Q;try{Q=await this.#D.findRepositoryRoot(A)}catch{Q=A}this.#Q.set("workspaceFolders",[{uri:GE.file(Q).toString(),name:"repository root"}]),this.#Q.set("gitHttpUser",this.#C.gitHttpUser),this.#Q.set("gitHttpPassword",this.#C.gitHttpPassword),this.#Q.set("gitUserEmail",this.#C.gitUserEmail),this.#Q.set("gitUserName",this.#C.gitUserName),this.#Q.set("clientInfo.name",pa),this.#Q.set("clientInfo.version",A2()),this.#Q.set("telemetry.enabled",this.#C.telemetryEnabled),this.#Q.set("telemetry.ide",{name:pa,version:A2(),vendor:Ls1});let B=await this.#D.getMatchingRepository(A,Q),D=B?await rn1(B,this.#C.gitlabBaseUrl):void 0;if(D?.namespaceWithPath)this.#Q.set("projectPath",D.namespaceWithPath);return{workspaceFolder:Q,gitlabRemote:D}}async#U(){try{await this.#I.precalculate();let A=await this.#I.getSystemContextItems();return this.#A.debug(`Initialized ${A.length} system context items`),A}catch(A){return this.#A.error("Failed to initialize system context",A),[]}}async#z(){try{return`@${(await this.#F.getUser()).username}`}catch(A){return this.#A.error("Error getting username",A),""}}#X(){let{command:A}=this.#C;if(A.name==="run"||A.name==="tui")return A.existingSessionId;return}}oH=G1([Y3A.Service({dependencies:[T1,l4,b4,M2,iH,cvA,X9,lw,J3A],lifetime:Y3A.ServiceLifetime.Singleton})],oH);var Ts1=fA(x1(),1);var OA2=Ts1.createInterfaceId("CliBackend");function G3A(A,Q){let B=structuredClone(A),{workflowToken:D}=B.command;if(D)D.duo_workflow_service.token="*************...";return Q.redactSecrets(JSON.stringify(B,null,4),"cli-run-config")}var Nb=fA(x1(),1);var pvA=Nb.createInterfaceId("CliContextManager");class la extends AvA{#A;constructor(A,Q,B,D,I){super(A,Q,B,D,I);this.#A=y1(A,"[CliContextManager]")}async syncWithTextBuffer(A){let Q=this.#Q(A),B=new Set(Q),I=(await this.getSelectedContextItems()).map((E)=>{let C=E.metadata.secondaryText;if(B.has(C))return;return{item:E,itemReference:C}}).filter((E)=>E!==void 0);await Promise.all(I.map(({item:E,itemReference:C})=>{return this.#A.debug(`Removing item no longer in text: ${C}`),this.removeSelectedContextItem(E)}))}#Q(A){let Q=[];for(let B of hp){let D=0;while(D<A.length)if(A[D]===B.activationChar){let I=A.slice(D+1);if(I.startsWith('"')){let E=I.indexOf('"',1);if(E!==-1){let C=I.slice(1,E);Q.push(`${B.activationChar}"${C}"`),D+=E+2}else D++}else{let E=I.search(/\s/),C=E===-1?I:I.slice(0,E);if(C.length>0)Q.push(`${B.activationChar}${C}`),D+=C.length+1;else D++}}else D++}return Q}}la=G1([Nb.Injectable(pvA,[T1,l4,EvA,Nb.collection(p5A),Fb])],la);class X3A{sessionId;#A;#Q;#B=[];#D=!1;#I;#E;#C=new Map;constructor(A,Q,B){this.sessionId=A,this.#A=Q,this.#Q=y1(B,`[Session: ${A}]`)}get elements(){return this.#B}get isLoading(){return this.#D}addUserMessageAndStartLoading(A){let Q={id:Date.now().toString(),type:"message",role:"user",content:A,timestamp:Date.now(),isComplete:!0};this.#B=[...this.#B,Q],this.#D=!0}async*sendMessageStream(A){this.#D=!0,this.#I=new AbortController;try{for await(let
|
|
1567
|
+
Run 'duo config edit' to update your token.`;return this.#I.fire({isInValidState:!1,validationMessage:D}),c6(Error(D))}let Q;try{Q=(await this.#A.fetchFromApi(iu)).version}catch{return this.#I.fire({isInValidState:!1,validationMessage:"Failed to fetch GitLab instance version"}),c6(Error("Failed to fetch GitLab instance version"))}let B={instanceVersion:Q,instanceUrl:this.#B};return this.#E=B,this.#C=A.tokenInfo,this.#I.fire({isInValidState:!0,instanceInfo:B,tokenInfo:A.tokenInfo}),this.#Q.debug("API initialization complete, onApiReconfigured event fired"),i4(void 0)}get instanceInfo(){return this.#E}get tokenInfo(){return this.#C}fetchFromApi(A){return this.#A.fetchFromApi(A)}fetchFromApiRaw(A){return this.#A.fetchFromApiRaw(A)}fetchOperation(A){return this.#A.fetchOperation(A)}connectToCable(){throw Error("Method not implemented.")}onApiReconfigured=this.#I.event;getSimpleClient(){return this.#A}}DM=G1([_s1.Injectable(b4,[X9,T1,XI])],DM);class oH{#A;#Q;#B;#D;#I;#E;#C;#F;#J;constructor(A,Q,B,D,I,E,C,F,J){this.#A=y1(A,"[CliInitializationService]"),this.#Q=Q,this.#B=B,this.#D=D,this.#I=I,this.#E=E,this.#C=C,this.#F=F,this.#J=J}async initialize(){this.#A.debug("Starting CLI common initialization");let[,A]=await Promise.all([this.#Y(),this.#G()]),Q=await this.#U(),B=this.#E.create(),D=this.#X(),[I,E]=await Promise.all([B.initialize(D),this.#z()]);return BD(this.#J.initialize()),{backend:B,sessionId:I.sessionId,username:E,systemContext:Q,workspaceFolder:A.workspaceFolder,gitlabRemote:A.gitlabRemote}}async#Y(){if(Rs1(this.#B)){let A=await this.#B.initialize();if(A.isErr())throw this.#A.error("API initialization failed:",A.error),A.error}this.#A.info("API service initialized successfully")}async#G(){let{cwd:A}=this.#C;this.#Q.set("cwd",GE.file(A).toString());let Q;try{Q=await this.#D.findRepositoryRoot(A)}catch{Q=A}this.#Q.set("workspaceFolders",[{uri:GE.file(Q).toString(),name:"repository root"}]),this.#Q.set("gitHttpUser",this.#C.gitHttpUser),this.#Q.set("gitHttpPassword",this.#C.gitHttpPassword),this.#Q.set("gitUserEmail",this.#C.gitUserEmail),this.#Q.set("gitUserName",this.#C.gitUserName),this.#Q.set("clientInfo.name",pa),this.#Q.set("clientInfo.version",A2()),this.#Q.set("telemetry.enabled",this.#C.telemetryEnabled),this.#Q.set("telemetry.ide",{name:pa,version:A2(),vendor:Ls1});let B=await this.#D.getMatchingRepository(A,Q),D=B?await rn1(B,this.#C.gitlabBaseUrl):void 0;if(D?.namespaceWithPath)this.#Q.set("projectPath",D.namespaceWithPath);return{workspaceFolder:Q,gitlabRemote:D}}async#U(){try{await this.#I.precalculate();let A=await this.#I.getSystemContextItems();return this.#A.debug(`Initialized ${A.length} system context items`),A}catch(A){return this.#A.error("Failed to initialize system context",A),[]}}async#z(){try{return`@${(await this.#F.getUser()).username}`}catch(A){return this.#A.error("Error getting username",A),""}}#X(){let{command:A}=this.#C;if(A.name==="run"||A.name==="tui")return A.existingSessionId;return}}oH=G1([Y3A.Service({dependencies:[T1,l4,b4,M2,iH,cvA,X9,lw,J3A],lifetime:Y3A.ServiceLifetime.Singleton})],oH);var Ts1=fA(x1(),1);var OA2=Ts1.createInterfaceId("CliBackend");function G3A(A,Q){let B=structuredClone(A),{workflowToken:D}=B.command;if(D)D.duo_workflow_service.token="*************...";return Q.redactSecrets(JSON.stringify(B,null,4),"cli-run-config")}var Nb=fA(x1(),1);var pvA=Nb.createInterfaceId("CliContextManager");class la extends AvA{#A;constructor(A,Q,B,D,I){super(A,Q,B,D,I);this.#A=y1(A,"[CliContextManager]")}async syncWithTextBuffer(A){let Q=this.#Q(A),B=new Set(Q),I=(await this.getSelectedContextItems()).map((E)=>{let C=E.metadata.secondaryText;if(B.has(C))return;return{item:E,itemReference:C}}).filter((E)=>E!==void 0);await Promise.all(I.map(({item:E,itemReference:C})=>{return this.#A.debug(`Removing item no longer in text: ${C}`),this.removeSelectedContextItem(E)}))}#Q(A){let Q=[];for(let B of hp){let D=0;while(D<A.length)if(A[D]===B.activationChar){let I=A.slice(D+1);if(I.startsWith('"')){let E=I.indexOf('"',1);if(E!==-1){let C=I.slice(1,E);Q.push(`${B.activationChar}"${C}"`),D+=E+2}else D++}else{let E=I.search(/\s/),C=E===-1?I:I.slice(0,E);if(C.length>0)Q.push(`${B.activationChar}${C}`),D+=C.length+1;else D++}}else D++}return Q}}la=G1([Nb.Injectable(pvA,[T1,l4,EvA,Nb.collection(p5A),Fb])],la);class X3A{sessionId;#A;#Q;#B=[];#D=!1;#I;#E;#C=new Map;constructor(A,Q,B){this.sessionId=A,this.#A=Q,this.#Q=y1(B,`[Session: ${A}]`)}get elements(){return this.#B}get isLoading(){return this.#D}addUserMessageAndStartLoading(A){let Q={id:Date.now().toString(),type:"message",role:"user",content:A,timestamp:Date.now(),isComplete:!0};this.#B=[...this.#B,Q],this.#D=!0}async*sendMessageStream(A){this.#D=!0,this.#I=new AbortController;let Q;try{for await(let B of this.#A.sendMessageStream(A,this.#I.signal))yield*this.#F(B);Q=this.#z()}catch(B){this.#Q.error("Error in message streaming:",B);let D={id:`error-${Date.now()}`,type:"error",error:"Sorry, there was an error processing your message. Please try again.",timestamp:Date.now()};this.#B=[...this.#B,D],yield D}finally{this.#X()}if(Q)yield{...Q}}cancelStream(){this.#I?.abort()}*#F(A){if(A.type!=="TEXT_CHUNK"&&this.#E)this.#Y(this.#E.id),this.#E=void 0;switch(A.type){case"TEXT_CHUNK":{if(this.#E&&this.#E.id!==A.messageId){let Q=this.#z();if(Q)yield{...Q}}if(!this.#E)this.#E={id:A.messageId,type:"message",role:"assistant",content:A.content,timestamp:A.timestamp,isComplete:!1},this.#B=[...this.#B,this.#E];else this.#E.content+=A.content,this.#U(this.#E);yield{...this.#E};break}case"TOOL_START":{let Q={id:A.toolId,type:"tool",name:A.name,input:A.input,state:{type:"loading"},timestamp:A.timestamp};this.#C.set(A.toolId,Q),this.#G(Q),yield Q;break}case"TOOL_AWAITING_APPROVAL":{let Q={id:A.toolId,type:"tool",name:A.toolName,input:A.input,state:{type:"approval_request",content:""},timestamp:A.timestamp};this.#C.set(A.toolId,Q),this.#G(Q),yield Q;break}case"TOOL_COMPLETE":{let Q=this.#C.get(A.toolId);if(Q){let B={...Q,state:A.error?{type:"error",error:A.error}:{type:"success",output:A.result}};this.#G(B),this.#C.delete(A.toolId),yield B}break}case"ERROR":{this.#Q.error("Agent error:",A.message);let Q={id:`error-${Date.now()}`,type:"error",error:`${A.message}`,timestamp:A.timestamp};this.#B=[...this.#B,Q],yield Q;break}default:this.#Q.warn("Unknown agent event type:",A);break}}#J(A){this.#B=[...this.#B,A]}#Y(A){if(!A)return;this.#B=this.#B.map((Q)=>Q.id===A?{...Q,isComplete:!0}:Q)}#G(A){let Q=this.#B.findIndex((D)=>D.type==="tool"&&D.id===A.id);if(Q<0){this.#J(A);return}let B=[...this.#B];B[Q]=A,this.#B=B}#U(A){let Q=this.#B.findIndex((B)=>B.id===A.id);if(Q>=0)this.#B=[...this.#B.slice(0,Q),A,...this.#B.slice(Q+1)]}#z(){if(!this.#E)return;this.#Y(this.#E.id);let A=this.#B.find((Q)=>Q.id===this.#E?.id);return this.#E=void 0,A}#X(){this.#D=!1,this.#E=void 0,this.#C.clear(),this.#I=void 0}}class lvA{#A;#Q;constructor(){this.#A={...aWA}}initialize(A){this.#Q=A}getState(){return this.#A}setState(A){if(this.#A=A,!this.#Q)throw Error("AppStore is not initialized");this.#Q(this.#A)}}class ivA{onSubmit=()=>{};onStateChange=()=>{};clear=()=>{};handleKeyPress=(A,Q)=>{}}class avA{onSubmit=()=>{};onStateChange=()=>{};#A=[];#Q=0;setChoice(A){this.#A=A,this.#Q=0,this.#B()}handleKeyPress=(A,Q)=>{let B="eventType"in Q?Q.name==="return":Q.return,D="eventType"in Q?Q.name==="up":Q.upArrow,I="eventType"in Q?Q.name==="down":Q.downArrow;if(B){this.onSubmit(this.#A[this.#Q]?.value);return}if(D)this.#Q=Math.max(0,this.#Q-1);if(I)this.#Q=Math.min(this.#A.length-1,this.#Q+1);this.#B()};#B(){this.onStateChange({inputType:$7.CHOICE,choiceOptions:this.#A,selectedChoiceIndex:this.#Q})}}class nvA{onStateChange=()=>{};onSelect=()=>{};onCancel=()=>{};onDelete=()=>Promise.resolve();onQueryChange=()=>{};#A;setState(A){this.#A=A,this.#Q()}handleKeyPress=(A,Q)=>{if(!this.#A)return;let B="eventType"in Q?Q.name==="escape":Q.escape,D="eventType"in Q?Q.name==="return":Q.return,I="eventType"in Q?Q.name==="up":Q.upArrow,E="eventType"in Q?Q.name==="down":Q.downArrow;if(B){this.onCancel();return}if(D){if(this.#A.filteredHistory.length>0)this.onSelect(this.#A.filteredHistory[this.#A.selectedIndex].item);return}if(I&&this.#A.selectedIndex>0){this.#A={...this.#A,selectedIndex:this.#A.selectedIndex-1},this.#Q();return}if(E&&this.#A.selectedIndex<this.#A.filteredHistory.length-1)this.#A={...this.#A,selectedIndex:this.#A.selectedIndex+1},this.#Q()};handleQueryChange=(A)=>{this.onQueryChange(A)};updateSearchResults(A,Q){if(!this.#A)return;this.#A={...this.#A,searchQuery:A,filteredHistory:Q,selectedIndex:0},this.#Q()}updateAfterDelete(A){if(!this.#A)return;let Q=Math.min(this.#A.selectedIndex,Math.max(0,A.length-1));this.#A={...this.#A,filteredHistory:A,selectedIndex:Q},this.#Q()}#Q(){if(!this.#A)return;this.onStateChange({inputType:$7.PROMPT_HISTORY_SEARCH,searchQuery:this.#A.searchQuery,filteredHistory:this.#A.filteredHistory,selectedIndex:this.#A.selectedIndex,maxVisible:this.#A.maxVisible})}}class ovA{#A;#Q=[];#B=-1;#D=100;#I;#E;constructor(A){this.#A=y1(A,"[PromptHistory]")}async load(A,Q){this.#I=A,this.#E=Q;try{let B=await A.get(Q);if(Array.isArray(B))this.#Q=B.slice(-this.#D)}catch(B){this.#A.error("Failed to load prompt history ",B)}}async#C(){if(!this.#I||!this.#E)return;try{await this.#I.set(this.#E,this.#Q)}catch(A){this.#A.error("Failed to save prompt history ",A)}}async add(A){if(!A.trim())return;if(this.#Q[this.#Q.length-1]===A)return;if(this.#Q.push(A),this.#Q.length>this.#D)this.#Q.shift();this.reset(),await this.#C()}reset(){this.#B=-1}handlePrevious(A){let Q=this.#F();if(Q===void 0||A.inputType!==$7.TEXT)return;return{...A,lines:Q.split(`
|
|
1568
1568
|
`),cursorLine:0,cursorColumn:0}}handleNext(A){let Q=this.#J();if(Q===void 0||A.inputType!==$7.TEXT)return;return{...A,lines:Q.split(`
|
|
1569
1569
|
`),cursorLine:0,cursorColumn:0}}#F(){if(this.#Q.length===0)return;if(this.#B===-1)this.#B=this.#Q.length;if(this.#B>0)this.#B--;return this.#Q[this.#B]}#J(){if(this.#B===-1)return;if(this.#B<this.#Q.length-1)return this.#B++,this.#Q[this.#B];return this.#B=-1,""}async remove(A){let Q=this.#Q.indexOf(A);if(Q===-1)return-1;return this.#Q.splice(Q,1),this.reset(),await this.#C(),Q}search(A,Q=10){if(!A.trim())return this.#Q.slice(-Q).reverse().map((E)=>({item:E,matches:[]}));let B=A.toLowerCase(),D=[];for(let I of this.#Q){let E=I.toLowerCase().indexOf(B);if(E!==-1)D.push({item:I,matchIndex:E})}return D.slice(-Q).reverse().map(({item:I,matchIndex:E})=>({item:I,matches:[E]}))}handleOpenSearch(){let A=this.search("",10);return{inputType:$7.PROMPT_HISTORY_SEARCH,searchQuery:"",filteredHistory:A,selectedIndex:0,maxVisible:10}}handleCancelSearch(){return FN}handleSelectItem(A){return{inputType:$7.TEXT,lines:A.split(`
|
|
1570
1570
|
`),cursorLine:0,cursorColumn:0}}}class yR{#A;#Q;#B=new lvA;#D;#I;#E;#C;#F;#J;#Y;#G;#U=new ivA;#z=new avA;#X=new nvA;#K;#Z;#$=js1.throttle(()=>this.#q(),500,{leading:!0,trailing:!0});constructor(A,Q,B,D,I,E,C,F){this.#D=y1(A,"[TUIController]"),this.#Y=C,this.#I=Q,this.#E=B,this.#C=D,this.#F=I,this.#J=E,this.#G=F,this.#U.onSubmit=(J)=>this.#S({type:"SEND_PROMPT",prompt:J}),this.#z.onSubmit=(J)=>this.#R(J),this.#U.onStateChange=(J)=>this.#B.setState({...this.#B.getState(),input:J}),this.#z.onStateChange=(J)=>this.#B.setState({...this.#B.getState(),input:J}),this.#X.onStateChange=(J)=>this.#B.setState({...this.#B.getState(),input:J}),this.#X.onCancel=()=>this.#O(),this.#X.onSelect=(J)=>this.#_(J),this.#X.onDelete=(J)=>this.#k(J),this.#X.onQueryChange=(J)=>this.#v(J)}async initialize(A){this.#A=A,this.#B.initialize((Q)=>this.#A?.(Q)),this.#V(),this.#K=this.#w()}async#w(){this.#D.debug(`CLI run config:
|
|
@@ -2080,5 +2080,5 @@ ${JSON.stringify(B,null,4)}`)}}pe=G1([pGA.Injectable(ftA,[T1,X9])],pe);var LRQ=f
|
|
|
2080
2080
|
<gitlab_instance_version>${B}</gitlab_instance_version>
|
|
2081
2081
|
</gitlab_instance>`}}ie=G1([_RQ.Injectable(fF,[T1,b4])],ie);function RRQ(A){A.addClass(DM),A.addClass(le,ie),A.addClass(dj),A.addClass(SM)}var hm=fA(x1(),1);class xtA{#A;#Q=new Z7;#B;#D;#I;constructor(A,Q,B){this.#A=y1(A,"[PreConfiguredCliApiService]"),this.#I=B;let D=Q.gitlab_rails,I=new URL(D.base_url);this.#B={instanceVersion:Q.duo_workflow_service.headers["X-Gitlab-Version"]||"unknown",instanceUrl:I},this.#D={token:D.token,scopes:[],type:"pat"},this.#A.debug("Pre-configured API service created with provided token and metadata")}async initialize(){return this.#A.debug("Starting pre-configured API initialization (no API calls)"),this.#Q.fire({isInValidState:!0,instanceInfo:this.#B,tokenInfo:this.#D}),this.#A.debug("Pre-configured API initialization complete, onApiReconfigured event fired"),i4(void 0)}get instanceInfo(){return this.#B}get tokenInfo(){return this.#D}fetchFromApi(A){return this.#I.fetchFromApi(A)}fetchFromApiRaw(A){return this.#I.fetchFromApiRaw(A)}fetchOperation(A){return this.#I.fetchOperation(A)}connectToCable(){return this.#I.connectToCable()}onApiReconfigured=this.#Q.event;getSimpleClient(){return this.#I.getSimpleClient()}}class htA{#A;#Q;constructor(A,Q){this.#A=y1(A,"[PreConfiguredWorkflowTokenService]"),this.#Q=Q}async getToken(A,Q){if(!this.#Q)throw Error("Token service has been disposed");return this.#A.debug(`Returning pre-configured token for workflow "${A}", type: "${Q}"`),this.#Q}getTokenFromCache(){return this.#Q}cacheToken(A,Q,B){this.#A.warn(`Ignoring cache request for workflow "${A}", type "${Q}" - using pre-configured tokens which are immutable`)}async revokeToken(A,Q){this.#A.debug(`Ignoring revoke request for workflow "${A}" - pre-configured tokens cannot be revoked`)}dispose(){this.#Q=null,this.#A.debug("Disposed pre-configured token")}}var TRQ=fA(x1(),1);class ae extends ys{constructor(A){super(A,"[OSInformationContextProvider]")}async getItems(){try{let A=this.detectOSInfo();if(!A)return this.logger.info("No OS information detected"),[];return[{category:"os_information",content:this.#A(A),id:"os_information",metadata:{title:"Operating System",enabled:!0,subType:"os",icon:"monitor",secondaryText:this.buildOSInfoContent(A),subTypeLabel:"System Information"}}]}catch(A){return this.logger.warn("Could not detect OS information",A),[]}}#A(A){return`<os><platform>${A.platform}</platform><architecture>${A.architecture}</architecture></os>`}}ae=G1([TRQ.Injectable(fF,[T1])],ae);function jRQ(A,Q){let{workflowToken:B}=Q.command;if(Q.command.name==="run"&&B)A.add(hm.createFactoryDescriptor({aliases:[yM],factory:(I)=>new htA(I.getRequiredService(T1),B),lifetime:hm.ServiceLifetime.Singleton})),A.add(hm.createFactoryDescriptor({aliases:[b4],factory:(I)=>{return new xtA(I.getRequiredService(T1),B,new DM(Q,I.getRequiredService(T1),I.getRequiredService(XI)))},lifetime:hm.ServiceLifetime.Singleton}));else A.addClass(SM,DM);A.addClass(Q.command.name==="run"?ae:dj)}function PRQ(A,Q){if(ua()==="anthropic")RRQ(A);else jRQ(A,Q)}var lRQ=fA(dRQ(),1);import{basename as E48,join as iGA,relative as cRQ}from"node:path";var iRQ=fA(x1(),1);var pRQ=10;class oe extends syA{chatRequiredFeature="include_file_context";#A;#Q;#B;#D;#I;constructor(A,Q,B,D,I){super("local_file_search",y1(A,"[CliFileContextProvider]"));this.#A=Q,this.#Q=B,this.#B=D,this.#D=I,this.#I=w51(this.#F.bind(this),50)}#E(A){if(A.workspaceFolders&&A.workspaceFolders.length>0)return A.workspaceFolders;return[{uri:GE.file(this.#Q.cwd).toString(),name:E48(this.#Q.cwd)}]}async searchContextItems(A){if(A.query.trim()===""){let Q=this.#E(A);return this.#C(Q)}return this.#I(A)}async#C(A){this.logger.debug("Getting modified files (empty query)");let Q=await this.#A.getRepositoriesForWorkspaces(A),B=new Map,D=await Promise.all(Array.from(Q.entries()).map(async([E,C])=>{let F=GE.parse(C.uri).fsPath,J=await E.getStatus(),Y=cRQ(F,E.fsPath);return J.files.map((G)=>{let X=Y?iGA(Y,G.path):G.path;return{absolutePath:iGA(E.fsPath,G.path),relativePath:X,workspaceFolder:C}})}));for(let E of D.flat())B.set(E.absolutePath,E);let I=Array.from(B.values()).slice(0,pRQ);return this.logger.debug(`Found ${I.length} modified files`),Promise.all(I.map((E)=>this.#J(E)))}async#F(A){let Q=A.query.trim(),B=this.#E(A);this.logger.debug(`Searching for files matching: "${Q}"`);let D=await this.#A.getRepositoriesForWorkspaces(B),I=new Map,E=await Promise.all(Array.from(D.entries()).map(async([J,Y])=>{let G=GE.parse(Y.uri).fsPath,X=await J.getFiles(),z=cRQ(G,J.fsPath);return X.map((U)=>{let Z=z?iGA(z,U):U;return{absolutePath:iGA(G,Z),relativePath:Z,workspaceFolder:Y}})}));for(let J of E.flat())I.set(J.absolutePath,J);let C=Array.from(I.keys()),F=lRQ.filter(C,Q,{maxResults:pRQ});return this.logger.debug(`Found ${F.length} files matching query`),Promise.all(F.map((J)=>I.get(J)).filter((J)=>J!==void 0).map((J)=>this.#J(J)))}async#J(A){let Q=GE.file(A.absolutePath),B=[];if(await Eb(Q,this.#B))B.push(DvA);return{id:A.absolutePath,category:"file",metadata:{title:A.relativePath,enabled:B.length===0,disabledReasons:B.length>0?B:void 0,icon:"document",secondaryText:this.#Y(A.relativePath),subType:"local_file_search",subTypeLabel:"Project file",relativePath:A.relativePath,workspaceFolder:A.workspaceFolder,project:this.#D.get("projectPath")??"not a GitLab project"}}}#Y(A){if(/\s/.test(A))return`@"${A}"`;return`@${A}`}async retrieveContextItemsWithContent(){let A=await this.getSelectedContextItems();return Promise.all(A.map((Q)=>this.getItemWithContent(Q)))}async getItemWithContent(A){let{readFile:Q}=this.#B.promises,B=(await Q(A.id)).toString("utf-8");return{...A,content:B}}}oe=G1([iRQ.Injectable(p5A,[T1,M2,X9,OY,l4])],oe);async function utA(A,Q,B){let D=new _G.ServiceCollection;if(D.add(_G.createInstanceDescriptor({instance:Q,aliases:[X9]})),D.add(_G.createInstanceDescriptor({instance:B,aliases:[cH]})),A?.logDestination==="stdout")D.addClass(de);else D.addClass(kR);D.addClass(ia,gw,go,pe),D.add(_G.createFactoryDescriptor({aliases:[pr],factory:(J)=>new MCA(J,J.getRequiredService(T1)),lifetime:_G.ServiceLifetime.Singleton})),D.addClass(qc,df,cf,Vh,xo),D.addClass(Ss),D.addClass(ce,Kh),U5A(D),D.addClass(qj,ls,$h,jx,Px,pf,Kk,JN,YN,zh,gx,bx,yx,Ph,jh,fx,xx,Hh,Sx,kx,hx,Zh,vx),D.add(_G.createInstanceDescriptor({instance:{getDiagnostics:async()=>[]},aliases:[fo]})),D.add(_G.createInstanceDescriptor({instance:{isClientFlagEnabled:()=>!1,isInstanceFlagEnabled:()=>!1,updateInstanceFeatureFlags:async()=>{}},aliases:[aL]})),D.addClass(md,ud),D.addClass(Qe,Oc,Mc,Rc),D.add(_G.createInstanceDescriptor({instance:{isChatFeatureEnabled:()=>Promise.resolve(!0),isSuggestionsFeatureEnabled:()=>Promise.resolve(!0)},aliases:[Fb]})),D.addClass(CZ,$k),D.addClass(Kb,wb,Hb,Vb),D.addClass(ga,la,ka,vs,Wh,oe),D.addClass(Be),D.addClass(oH),D.addClass(ya),D.addClass(vR),D.addClass(yR),D.addClass(da),D.addClass(Ie),D.addClass(ue,Ee),PRQ(D,Q);let I=D.build();I.getRequiredService(ftA).logDebugDetails(),await I.getRequiredService(XI).initialize();let F=global;return F.__errorHandler=I.getRequiredService(jU),B.setDiContainer(I),I}var C48=process.platform==="win32",aGA=qs1(),nGA=new cH,ZO=new xeA,dtA=async(A)=>{let Q=global.__errorHandler;if(Q){let B=new tw("Duo CLI uncaught exception",A);Q.handleError(B.message,B)}else console.error("Duo CLI uncaught exception",A);await nGA.exit(1)};process.on("unhandledRejection",dtA);process.on("uncaughtException",dtA);var ctA=A2();ZO.name("duo").description("GitLab Duo for your command line").version(ctA,"-v, --version","Display version number").option("-C, --cwd <path>","change working directory",(A)=>Ps1(A),process.cwd()).addOption(new I8("--gitlab-base-url <url>","Base URL of GitLab instance").env("GITLAB_URL").default(process.env.GITLAB_BASE_URL)).addOption(new I8("--gitlab-auth-token <token>","Authentication token for GitLab instance").env("GITLAB_TOKEN").default(process.env.GITLAB_OAUTH_TOKEN)).addOption(new I8("--log-level <level>","Set logging level").choices(Object.values(AD)).env("LOG_LEVEL").default(AD.DEBUG)).addOption(new I8("--git-http-user <user>","Username for git HTTP authentication credentials").env("DUO_WORKFLOW_GIT_HTTP_USER")).addOption(new I8("--git-http-password <password>","Password for git HTTP authentication credentials").env("DUO_WORKFLOW_GIT_HTTP_PASSWORD")).addOption(new I8("--git-user-email <email>","Email for git commit attribution").env("DUO_WORKFLOW_GIT_USER_EMAIL")).addOption(new I8("--git-user-name <name>","Name for git commit attribution").env("DUO_WORKFLOW_GIT_USER_NAME")).addOption(new I8("--telemetry-enabled","Enable collection of telemetry and error events").env("DUO_WORKFLOW_TELEMETRY_ENABLED").default(!0)).hook("preAction",(A)=>{if(A.optsWithGlobals().logLevel===AD.DEBUG)sUA()});aGA.registerOptions(ZO.addOption(new I8("--existing-session-id <sessionId>","ID of existing session to resume").default(process.env.DUO_WORKFLOW_WORKFLOW_ID)).action(async(A)=>{let Q=ZO.opts(),{cwd:B,logLevel:D,gitHttpUser:I,gitHttpPassword:E,gitUserEmail:C,gitUserName:F,telemetryEnabled:J}=Q,{existingSessionId:Y}=A,G=await N3A(Q),X=await w3A();if(G.isMissingConfiguration()){BkA(G,X);return}let U=G.getDuoConfiguration(),Z=aGA.mapConfig({cliVersion:ctA,cwd:B,envInfo:X,gitHttpPassword:E,gitHttpUser:I,gitUserEmail:C,gitUserName:F,gitlabAuthToken:U.gitlabAuthToken,gitlabBaseUrl:U.gitlabBaseUrl,logLevel:D,telemetryEnabled:J,command:{name:"tui",existingSessionId:Y}},{programConfig:Q,commandConfig:A}),H=(await utA({logDestination:"file"},Z,nGA)).getRequiredService(yR);tL1(H,X,nGA)}));var F48=ZO.command("config").description("configuration management commands");F48.command("edit").description("edit duo CLI configuration").action(async()=>{let A=await N3A(),Q=await w3A();BkA(A,Q)});var oGA=ZO.command("log").description("log management commands");oGA.command("last").description("open the last log file").action(()=>{hJ1()});oGA.command("list").description("list all log files").action(()=>{mJ1()});oGA.command("tail [args...]").description(`tail the last log file. "args" can be any standard ${C48?'PowerShell "Get-Content"':'"tail"'} arguments`).allowUnknownOption().action((A)=>uJ1(A||[]));oGA.command("clear").description("remove all existing log files").action(()=>{dJ1()});aGA.registerOptions(ZO.command("run").description("Run a workflow in non-interactive / headless mode").addOption(new I8("-g, --goal <goal>","Goal/prompt for the session").default(process.env.DUO_WORKFLOW_GOAL).makeOptionMandatory()).addOption(new I8("--ai-context-items <contextItems>","JSON encoded array of additional context items").env("DUO_WORKFLOW_ADDITIONAL_CONTEXT_CONTENT").argParser((A)=>Ss1(A))).action(async(A)=>{let Q=ZO.opts(),{cwd:B,existingSessionId:D,gitHttpPassword:I,gitHttpUser:E,gitUserEmail:C,gitUserName:F,logLevel:J,telemetryEnabled:Y}=Q,{goal:G,aiContextItems:X}=A,U=(await N3A(Q)).getDuoConfiguration(),Z=await w3A();if(!U.gitlabAuthToken)throw new VW("--gitlab-auth-token / GITLAB_AUTH_TOKEN option is required.");let K=aGA.mapConfig({cliVersion:ctA,cwd:B,gitlabBaseUrl:U.gitlabBaseUrl,gitlabAuthToken:U.gitlabAuthToken,logLevel:J,envInfo:Z,gitHttpUser:E,gitHttpPassword:I,gitUserEmail:C,gitUserName:F,telemetryEnabled:Y,command:{name:"run",goal:G,aiContextItems:X,existingSessionId:D}},{programConfig:Q,commandConfig:A}),W=(await utA({logDestination:"stdout"},K,nGA)).getRequiredService(vR);await W.initialize(),await W.execute()}));try{await ZO.parseAsync(process.argv)}catch(A){await dtA(A)}
|
|
2082
2082
|
|
|
2083
|
-
//# debugId=
|
|
2083
|
+
//# debugId=2EF0A8D36680D8CC64756E2164756E21
|
|
2084
2084
|
//# sourceMappingURL=index.js.map
|