@gitlab/duo-cli 8.70.0 → 8.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1143,7 +1143,7 @@ ${PyQ(C)}`:""};if(typeof Q==="string"){let I=B?`
1143
1143
  ${D(B)}`:"";this.#I(`${Q}${I}${E(B)}`,A)}else{let I=C11(Q);if(!I)return;this.#I(`${D(I)}${E(Q)}`,A)}}#I(A,Q){let B=`${F11.default().format("YYYY-MM-DDTHH:mm:ss:SSS")} [${Q}]: `,D=(E)=>E.replace(/\n/g,`
1144
1144
  ${" ".repeat(jyQ)}`);this.#A.write(`${B}${D(A)}`)}setContext(A){this.#B=A}debug(A,Q){this.#D(J3.DEBUG,A,Q)}info(A,Q){this.#D(J3.INFO,A,Q)}warn(A,Q){this.#D(J3.WARNING,A,Q)}error(A,Q){this.#D(J3.ERROR,A,Q)}withContext(A){let Q=new mw(this.#A,this.#Q);return Q.setContext(A),Q}}mw=Q1([Y11.Injectable(q1,[hw,$d])],mw);var fQA=SA(T1(),1);var vQA=SA(T1(),1);var G11=SA(T1(),1),f4=G11.createInterfaceId("GitLabApiService");var z11=SA(BD(),1);function U11(A){return(A.split(`
1145
1145
  `).find((Q)=>Q.trim())??A.replace(`
1146
- `,"")).trim()}function SyQ(A){return U11(A).match(/^(query|mutation|subscription)\s+/)?.[1]}function yyQ(A){return U11(A).match(/(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function w1A(A){let Q=SyQ(A),B=yyQ(A);if(Q)return`${Q}: ${B??"anonymous"}`;return}var vyQ=(A)=>{if(A.method==="GET"||A.method==="HEAD")return;if(!A.body)return;return g2("Body",JSON.stringify(A.body))},kyQ=(A)=>{if(A.method==="POST"||A.method==="PATCH"||A.method==="PUT")return;if(!A.searchParams)return;return g2("Search Params",JSON.stringify(A.searchParams))},gyQ=(A)=>{if(!A.headers)return;return g2("Headers",JSON.stringify(A.headers))},Wd=(A)=>{switch(A.type){case"graphql":return eI("GraphQL Request",g2("Query",A.query.replace(/[\s\n]+/g," ").trim()),g2("Variables",JSON.stringify(A.variables)));case"rest":return eI("REST Request",g2("Method",A.method),g2("Path",A.path),gyQ(A),kyQ(A),vyQ(A));default:return g2("Unknown request type",A.type)}};var Z11=(A)=>{try{return JSON.parse(A)?.error}catch{return}},byQ=(A)=>{if(!A)return"";try{return JSON.parse(A)?.error_description??""}catch{return""}},ZzA=(A,Q)=>Boolean(A.status===401&&Q&&Z11(Q)==="invalid_token"),KzA=(A,Q)=>Boolean(A.status===400&&Q&&Z11(Q)==="invalid_grant");class H1A extends Error{request;cause;constructor(A,Q,B){super(A);this.request=Q,this.cause=B?.cause}get sanitizedMessage(){return"API request failed"}}class wzA extends H1A{status;constructor(A,Q,B,D){super(A,Q,D);this.status=B}}class Nd extends wzA{type="rest";response;#A;constructor(A,Q,B,D){let E=`Fetching ${B} from ${Q.url} failed. ${byQ(D)}`;if(ZzA(Q,D))E=`Request for ${B} failed because the token is expired or revoked.`;if(KzA(Q,D))E="Request to refresh token failed, because it's revoked or already refreshed.";super(E,A,Q.status);this.response=Q,this.#A=D}isInvalidTokenOrInvalidRefresh(){return ZzA(this.response,this.#A)||KzA(this.response,this.#A)}get ctx(){return eI("Error details",Wd(this.request),this.#Q())}get sanitizedMessage(){if(ZzA(this.response,this.#A))return"Request failed because the token is expired or revoked.";if(KzA(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 eI("Response",g2("Status",String(this.status)),!z11.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 X11=(A)=>A.errors?.map((Q)=>Q.message).join(",")||"";class HzA extends wzA{type="graphql";graphQlResponse;#A;constructor(A,Q){let B=w1A(A.query),D=`GraphQL request "${B}" failed with ${X11(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 eI("Error details",Wd(this.request),this.#Q())}#Q(){return eI("Response",g2("Status",String(this.graphQlResponse.status)),g2("Errors",X11(this.graphQlResponse)))}}class V1A extends H1A{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 eI("Error details",Wd(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 fyQ extends H1A{type="timeout";#A;constructor(A,Q){let B=`Request timed out${Q?` after ${Q}ms`:""}`;super(B,A);this.#A=B}get ctx(){return eI("Error details",Wd(this.request))}get sanitizedMessage(){return this.#A}}var K11=Nd;function $1A(A){return A instanceof Nd}var Md={type:"rest",method:"GET",path:"/api/v4/version"};var w11=(A)=>$1A(A)&&(A.status<400||A.status>=500);var W1A=JSON;var H11=(A)=>A.toUpperCase(),V11=(A)=>{let Q={};return A.forEach((B,D)=>{Q[D]=B}),Q};var $11=(A,Q,B)=>{return A.document?A:{document:A,variables:Q,requestHeaders:B,signal:void 0}},W11=(A,Q,B)=>{return A.query?A:{query:A,variables:Q,requestHeaders:B,signal:void 0}},N11=(A,Q)=>{return A.documents?A:{documents:A,requestHeaders:Q,signal:void 0}};var V0A=SA(Z21(),1),K21=(A)=>{let Q=void 0,B=A.definitions.filter((D)=>D.kind==="OperationDefinition");if(B.length===1)Q=B[0]?.name?.value;return Q},Q_=(A)=>{if(typeof A==="string"){let B=void 0;try{let D=V0A.parse(A);B=K21(D)}catch(D){}return{query:A,operationName:B}}let Q=K21(A);return{query:V0A.print(A),operationName:Q}};class LF extends Error{constructor(A,Q){let B=`${LF.extractMessage(A)}: ${JSON.stringify({response:A,request:Q})}`;super(B);if(Object.setPrototypeOf(this,LF.prototype),this.response=A,this.request=Q,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,LF)}static extractMessage(A){return A.errors?.[0]?.message??`GraphQL Error (Code: ${A.status})`}}var cW=SA(E91(),1);var KnQ="connection_init",wnQ="connection_ack",C91="ping",F91="pong",HnQ="subscribe",VnQ="next",$nQ="error",Y91="complete";class dW{get type(){return this._type}get id(){return this._id}get payload(){return this._payload}constructor(A,Q,B){this._type=A,this._payload=Q,this._id=B}get text(){let A={type:this.type};if(this.id!=null&&this.id!=null)A.id=this.id;if(this.payload!=null&&this.payload!=null)A.payload=this.payload;return JSON.stringify(A)}static parse(A,Q){let{type:B,payload:D,id:E}=JSON.parse(A);return new dW(B,Q(D),E)}}class BwA{constructor(A,{onInit:Q,onAcknowledged:B,onPing:D,onPong:E}){this.socketState={acknowledged:!1,lastRequestId:0,subscriptions:{}},this.socket=A,A.addEventListener("open",async(I)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={},A.send(NnQ(Q?await Q():null).text)}),A.addEventListener("close",(I)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={}}),A.addEventListener("error",(I)=>{console.error(I)}),A.addEventListener("message",(I)=>{try{let C=WnQ(I.data);switch(C.type){case wnQ:{if(this.socketState.acknowledged)console.warn("Duplicate CONNECTION_ACK message ignored");else if(this.socketState.acknowledged=!0,B)B(C.payload);return}case C91:{if(D)D(C.payload).then((G)=>A.send(I91(G).text));else A.send(I91(null).text);return}case F91:{if(E)E(C.payload);return}}if(!this.socketState.acknowledged)return;if(C.id===void 0||C.id===null||!this.socketState.subscriptions[C.id])return;let{query:F,variables:Y,subscriber:J}=this.socketState.subscriptions[C.id];switch(C.type){case VnQ:{if(!C.payload.errors&&C.payload.data)J.next&&J.next(C.payload.data);if(C.payload.errors)J.error&&J.error(new LF({...C.payload,status:200},{query:F,variables:Y}));return}case $nQ:{J.error&&J.error(new LF({errors:C.payload,status:200},{query:F,variables:Y}));return}case Y91:{J.complete&&J.complete(),delete this.socketState.subscriptions[C.id];return}}}catch(C){console.error(C),A.close(1006)}A.close(4400,"Unknown graphql-ws message.")})}makeSubscribe(A,Q,B,D){let E=(this.socketState.lastRequestId++).toString();return this.socketState.subscriptions[E]={query:A,variables:D,subscriber:B},this.socket.send(qnQ(E,{query:A,operationName:Q,variables:D}).text),()=>{this.socket.send(OnQ(E).text),delete this.socketState.subscriptions[E]}}rawRequest(A,Q){return new Promise((B,D)=>{let E;this.rawSubscribe(A,{next:(I,C)=>E={data:I,extensions:C},error:D,complete:()=>B(E)},Q)})}request(A,Q){return new Promise((B,D)=>{let E;this.subscribe(A,{next:(I)=>E=I,error:D,complete:()=>B(E)},Q)})}subscribe(A,Q,B){let{query:D,operationName:E}=Q_(A);return this.makeSubscribe(D,E,Q,B)}rawSubscribe(A,Q,B){return this.makeSubscribe(A,void 0,Q,B)}ping(A){this.socket.send(MnQ(A).text)}close(){this.socket.close(1000)}}BwA.PROTOCOL="graphql-transport-ws";function WnQ(A,Q=(B)=>B){return dW.parse(A,Q)}function NnQ(A){return new dW(KnQ,A)}function MnQ(A){return new dW(C91,A,void 0)}function I91(A){return new dW(F91,A,void 0)}function qnQ(A,Q){return new dW(HnQ,Q,A)}function OnQ(A){return new dW(Y91,void 0,A)}var cy=(A)=>{let Q={};if(A)if(typeof Headers<"u"&&A instanceof Headers||cW&&cW.Headers&&A instanceof cW.Headers)Q=V11(A);else if(Array.isArray(A))A.forEach(([B,D])=>{if(B&&D!==void 0)Q[B]=D});else Q=A;return Q},J91=(A)=>A.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),LnQ=(A)=>{if(!Array.isArray(A.query)){let D=A,E=[`query=${encodeURIComponent(J91(D.query))}`];if(A.variables)E.push(`variables=${encodeURIComponent(D.jsonSerializer.stringify(D.variables))}`);if(D.operationName)E.push(`operationName=${encodeURIComponent(D.operationName)}`);return E.join("&")}if(typeof A.variables<"u"&&!Array.isArray(A.variables))throw Error("Cannot create query with given variable type, array expected");let Q=A,B=A.query.reduce((D,E,I)=>{return D.push({query:J91(E),variables:Q.variables?Q.jsonSerializer.stringify(Q.variables[I]):void 0}),D},[]);return`query=${encodeURIComponent(Q.jsonSerializer.stringify(B))}`},_nQ=(A)=>async(Q)=>{let{url:B,query:D,variables:E,operationName:I,fetch:C,fetchOptions:F,middleware:Y}=Q,J={...Q.headers},G="",X=void 0;if(A==="POST"){if(X=RnQ(D,E,I,F.jsonSerializer),typeof X==="string")J["Content-Type"]="application/json"}else G=LnQ({query:D,variables:E,operationName:I,jsonSerializer:F.jsonSerializer??W1A});let z={method:A,headers:J,body:X,...F},U=B,Z=z;if(Y){let K=await Promise.resolve(Y({...z,url:B,operationName:I,variables:E})),{url:H,...W}=K;U=H,Z=W}if(G)U=`${U}?${G}`;return await C(U,Z)};class IwA{constructor(A,Q={}){this.url=A,this.requestConfig=Q,this.rawRequest=async(...B)=>{let[D,E,I]=B,C=W11(D,E,I),{headers:F,fetch:Y=cW.default,method:J="POST",requestMiddleware:G,responseMiddleware:X,...z}=this.requestConfig,{url:U}=this;if(C.signal!==void 0)z.signal=C.signal;let{operationName:Z}=Q_(C.query);return DwA({url:U,query:C.query,variables:C.variables,headers:{...cy(EwA(F)),...cy(C.requestHeaders)},operationName:Z,fetch:Y,method:J,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,E=$11(A,B,D),{headers:I,fetch:C=cW.default,method:F="POST",requestMiddleware:Y,responseMiddleware:J,...G}=this.requestConfig,{url:X}=this;if(E.signal!==void 0)G.signal=E.signal;let{query:z,operationName:U}=Q_(E.document);return DwA({url:X,query:z,variables:E.variables,headers:{...cy(EwA(I)),...cy(E.requestHeaders)},operationName:U,fetch:C,method:F,fetchOptions:G,middleware:Y}).then((Z)=>{if(J)J(Z);return Z.data}).catch((Z)=>{if(J)J(Z);throw Z})}batchRequests(A,Q){let B=N11(A,Q),{headers:D,...E}=this.requestConfig;if(B.signal!==void 0)E.signal=B.signal;let I=B.documents.map(({document:F})=>Q_(F).query),C=B.documents.map(({variables:F})=>F);return DwA({url:this.url,query:I,variables:C,headers:{...cy(EwA(D)),...cy(B.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??cW.default,method:this.requestConfig.method||"POST",fetchOptions:E,middleware:this.requestConfig.requestMiddleware}).then((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);return F.data}).catch((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);throw F})}setHeaders(A){return this.requestConfig.headers=A,this}setHeader(A,Q){let{headers:B}=this.requestConfig;if(B)B[A]=Q;else this.requestConfig.headers={[A]:Q};return this}setEndpoint(A){return this.url=A,this}}var DwA=async(A)=>{let{query:Q,variables:B,fetchOptions:D}=A,E=_nQ(H11(A.method??"post")),I=Array.isArray(A.query),C=await E(A),F=await TnQ(C,D.jsonSerializer??W1A),Y=Array.isArray(F)?!F.some(({data:G})=>!G):Boolean(F.data),J=Array.isArray(F)||!F.errors||Array.isArray(F.errors)&&!F.errors.length||D.errorPolicy==="all"||D.errorPolicy==="ignore";if(C.ok&&J&&Y){let{errors:G,...X}=Array.isArray(F)?F:F,z=D.errorPolicy==="ignore"?X:F;return{...I?{data:z}:z,headers:C.headers,status:C.status}}else throw new LF({...typeof F==="string"?{error:F}:F,status:C.status,headers:C.headers},{query:Q,variables:B})};var RnQ=(A,Q,B,D)=>{let E=D??W1A;if(!Array.isArray(A))return E.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 I=A.reduce((C,F,Y)=>{return C.push({query:F,variables:Q?Q[Y]:void 0}),C},[]);return E.stringify(I)},TnQ=async(A,Q)=>{let B;if(A.headers.forEach((D,E)=>{if(E.toLowerCase()==="content-type")B=D}),B&&(B.toLowerCase().startsWith("application/json")||B.toLowerCase().startsWith("application/graphql+json")||B.toLowerCase().startsWith("application/graphql-response+json")))return Q.parse(await A.text());else return A.text()},EwA=(A)=>{return typeof A==="function"?A():A},$U=(A,...Q)=>{return A.reduce((B,D,E)=>`${B}${D}${E in Q?String(Q[E]):""}`,"")};var G91=async(A,Q,B)=>{if(!Q.ok){let D=await Q.text().catch(()=>{return});throw new K11(A,Q,B,D)}};function e8(){return"8.70.0"}var U91=(A)=>{let Q=A?`${A?.name}:${A?.version}`:"missing client info";return`gitlab-language-server:${e8()} (${Q})`};function X91(A){return A!==null&&A!==void 0}var CwA=(A,Q)=>{return Object.entries(Q).forEach(([B,D])=>{if(X91(D))A.searchParams.append(B,String(D))}),A},L0A=(A)=>A.toString().replace(/\/?$/,"/"),py=(A)=>A.replace(/^\.?\/?/,"./"),z91=(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 jnQ=(A)=>A.split("/").pop()||"unknown resource";class wc{#A;#Q;#B;#D;#E;constructor(A,Q,B,D,E){this.#A=A,this.#Q=Q,this.#B=new URL(L0A(D)),this.#D=E,this.#E=B}getDefaultHeaders(){return{Authorization:`Bearer ${this.#D}`,"User-Agent":U91(this.#E),"X-Gitlab-Language-Server-Version":e8()}}async fetchFromApiRaw(A){try{let Q=`Unknown request method "${A.method}", request type "${A.type}"`;switch(A.method){case"GET":return await this.#C(A);case"POST":return await this.#F(A);case"PATCH":return await this.#Y(A);case"PUT":return await this.#J(A);case"HEAD":return await this.#G(A);default:throw Error(Q)}}catch(Q){throw new V1A(A,Q)}}async fetchFromApi(A){if(A.type==="graphql")return this.#I(A);let Q=await this.fetchFromApiRaw(A);return await G91(A,Q,jnQ(A.path)),Q.json()}fetchOperation=(A)=>(Q)=>this.fetchFromApi({...A,signal:Q});async#I(A){let Q=new URL("./api/graphql",this.#B),B=w1A(A.query);if(B)this.#A.debug(`[SimpleApiClient] Making GraphQL request: ${B}`);let D=async(I,C)=>{let F=I instanceof URL?I.toString():I;return this.#Q.post(F,{...C,headers:{...C?.headers},signal:A.signal})},E=new IwA(Q.href,{fetch:D,headers:{...this.getDefaultHeaders()}});try{return await E.request(A.query,A.variables)}catch(I){if(I instanceof LF)throw new HzA(A,I.response);throw new V1A(A,I)}}async#C(A){let Q=py(A.path),B=new URL(Q,this.#B);return CwA(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#Y(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#J(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 CwA(B,A.searchParams??{}),this.#Q.head(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}}var Z91=["ai_features","read_api","api"],_0A=(A)=>{if(!(A instanceof Nd)||!A.isInvalidTokenOrInvalidRefresh())return{valid:!1,reason:"unknown",message:`Token validation failed: ${A}`};return{valid:!1,reason:"invalid_token",message:"Token is invalid or expired."}},H91=(A)=>{if(Z91.some((B)=>A.includes(B)))return;return{valid:!1,reason:"invalid_scopes",message:`Token has scope(s) ${A.map((B)=>`'${B}'`).join(", ")} (needs one of: ${Z91.join(", ")}).`}};async function K91(A,Q){let B={type:"rest",method:"GET",path:"/api/v4/personal_access_tokens/self"},{scopes:D}=await A.fetchFromApi(B),E=H91(D);if(E)return E;return{valid:!0,tokenInfo:{scopes:D,type:"pat",token:Q}}}async function w91(A,Q){let B={type:"rest",method:"GET",path:"/oauth/token/info"},{scope:D}=await A.fetchFromApi(B),E=H91(D);if(E)return E;return{valid:!0,tokenInfo:{scopes:D,type:"oauth",token:Q}}}async function R0A(A,Q,B){if(!Q)return{valid:!1,message:"No token provided",reason:"invalid_token"};if(B==="pat")return K91(A,Q).catch(_0A);if(B==="oauth")return w91(A,Q).catch(_0A);let D=await Promise.all([K91(A,Q).catch(_0A),w91(A,Q).catch(_0A)]),E=D.find((Y)=>Y.valid);if(E)return E;let I=D.filter((Y)=>!Y.valid),C=I.find((Y)=>Y.reason==="invalid_scopes");if(C)return C;let F=I.find((Y)=>Y.reason==="invalid_token");if(F)return F;return D[0]}var T0A=SA(T1(),1);var FwA=T0A.createInterfaceId("ProjectService");class Hc{#A;#Q;constructor(A,Q){this.#A=Q,this.#Q=L1(A,"[ProjectService]")}async getProjectFromPathWithNamespace(A){return this.#Q.debug(`Fetching details for project: ${A}`),(await this.#A.fetchFromApi({type:"graphql",query:$U`
1146
+ `,"")).trim()}function SyQ(A){return U11(A).match(/^(query|mutation|subscription)\s+/)?.[1]}function yyQ(A){return U11(A).match(/(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function w1A(A){let Q=SyQ(A),B=yyQ(A);if(Q)return`${Q}: ${B??"anonymous"}`;return}var vyQ=(A)=>{if(A.method==="GET"||A.method==="HEAD")return;if(!A.body)return;return g2("Body",JSON.stringify(A.body))},kyQ=(A)=>{if(A.method==="POST"||A.method==="PATCH"||A.method==="PUT")return;if(!A.searchParams)return;return g2("Search Params",JSON.stringify(A.searchParams))},gyQ=(A)=>{if(!A.headers)return;return g2("Headers",JSON.stringify(A.headers))},Wd=(A)=>{switch(A.type){case"graphql":return eI("GraphQL Request",g2("Query",A.query.replace(/[\s\n]+/g," ").trim()),g2("Variables",JSON.stringify(A.variables)));case"rest":return eI("REST Request",g2("Method",A.method),g2("Path",A.path),gyQ(A),kyQ(A),vyQ(A));default:return g2("Unknown request type",A.type)}};var Z11=(A)=>{try{return JSON.parse(A)?.error}catch{return}},byQ=(A)=>{if(!A)return"";try{return JSON.parse(A)?.error_description??""}catch{return""}},ZzA=(A,Q)=>Boolean(A.status===401&&Q&&Z11(Q)==="invalid_token"),KzA=(A,Q)=>Boolean(A.status===400&&Q&&Z11(Q)==="invalid_grant");class H1A extends Error{request;cause;constructor(A,Q,B){super(A);this.request=Q,this.cause=B?.cause}get sanitizedMessage(){return"API request failed"}}class wzA extends H1A{status;constructor(A,Q,B,D){super(A,Q,D);this.status=B}}class Nd extends wzA{type="rest";response;#A;constructor(A,Q,B,D){let E=`Fetching ${B} from ${Q.url} failed. ${byQ(D)}`;if(ZzA(Q,D))E=`Request for ${B} failed because the token is expired or revoked.`;if(KzA(Q,D))E="Request to refresh token failed, because it's revoked or already refreshed.";super(E,A,Q.status);this.response=Q,this.#A=D}isInvalidTokenOrInvalidRefresh(){return ZzA(this.response,this.#A)||KzA(this.response,this.#A)}get ctx(){return eI("Error details",Wd(this.request),this.#Q())}get sanitizedMessage(){if(ZzA(this.response,this.#A))return"Request failed because the token is expired or revoked.";if(KzA(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 eI("Response",g2("Status",String(this.status)),!z11.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 X11=(A)=>A.errors?.map((Q)=>Q.message).join(",")||"";class HzA extends wzA{type="graphql";graphQlResponse;#A;constructor(A,Q){let B=w1A(A.query),D=`GraphQL request "${B}" failed with ${X11(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 eI("Error details",Wd(this.request),this.#Q())}#Q(){return eI("Response",g2("Status",String(this.graphQlResponse.status)),g2("Errors",X11(this.graphQlResponse)))}}class V1A extends H1A{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 eI("Error details",Wd(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 fyQ extends H1A{type="timeout";#A;constructor(A,Q){let B=`Request timed out${Q?` after ${Q}ms`:""}`;super(B,A);this.#A=B}get ctx(){return eI("Error details",Wd(this.request))}get sanitizedMessage(){return this.#A}}var K11=Nd;function $1A(A){return A instanceof Nd}var Md={type:"rest",method:"GET",path:"/api/v4/version"};var w11=(A)=>$1A(A)&&(A.status<400||A.status>=500);var W1A=JSON;var H11=(A)=>A.toUpperCase(),V11=(A)=>{let Q={};return A.forEach((B,D)=>{Q[D]=B}),Q};var $11=(A,Q,B)=>{return A.document?A:{document:A,variables:Q,requestHeaders:B,signal:void 0}},W11=(A,Q,B)=>{return A.query?A:{query:A,variables:Q,requestHeaders:B,signal:void 0}},N11=(A,Q)=>{return A.documents?A:{documents:A,requestHeaders:Q,signal:void 0}};var V0A=SA(Z21(),1),K21=(A)=>{let Q=void 0,B=A.definitions.filter((D)=>D.kind==="OperationDefinition");if(B.length===1)Q=B[0]?.name?.value;return Q},Q_=(A)=>{if(typeof A==="string"){let B=void 0;try{let D=V0A.parse(A);B=K21(D)}catch(D){}return{query:A,operationName:B}}let Q=K21(A);return{query:V0A.print(A),operationName:Q}};class LF extends Error{constructor(A,Q){let B=`${LF.extractMessage(A)}: ${JSON.stringify({response:A,request:Q})}`;super(B);if(Object.setPrototypeOf(this,LF.prototype),this.response=A,this.request=Q,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,LF)}static extractMessage(A){return A.errors?.[0]?.message??`GraphQL Error (Code: ${A.status})`}}var cW=SA(E91(),1);var KnQ="connection_init",wnQ="connection_ack",C91="ping",F91="pong",HnQ="subscribe",VnQ="next",$nQ="error",Y91="complete";class dW{get type(){return this._type}get id(){return this._id}get payload(){return this._payload}constructor(A,Q,B){this._type=A,this._payload=Q,this._id=B}get text(){let A={type:this.type};if(this.id!=null&&this.id!=null)A.id=this.id;if(this.payload!=null&&this.payload!=null)A.payload=this.payload;return JSON.stringify(A)}static parse(A,Q){let{type:B,payload:D,id:E}=JSON.parse(A);return new dW(B,Q(D),E)}}class BwA{constructor(A,{onInit:Q,onAcknowledged:B,onPing:D,onPong:E}){this.socketState={acknowledged:!1,lastRequestId:0,subscriptions:{}},this.socket=A,A.addEventListener("open",async(I)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={},A.send(NnQ(Q?await Q():null).text)}),A.addEventListener("close",(I)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={}}),A.addEventListener("error",(I)=>{console.error(I)}),A.addEventListener("message",(I)=>{try{let C=WnQ(I.data);switch(C.type){case wnQ:{if(this.socketState.acknowledged)console.warn("Duplicate CONNECTION_ACK message ignored");else if(this.socketState.acknowledged=!0,B)B(C.payload);return}case C91:{if(D)D(C.payload).then((G)=>A.send(I91(G).text));else A.send(I91(null).text);return}case F91:{if(E)E(C.payload);return}}if(!this.socketState.acknowledged)return;if(C.id===void 0||C.id===null||!this.socketState.subscriptions[C.id])return;let{query:F,variables:Y,subscriber:J}=this.socketState.subscriptions[C.id];switch(C.type){case VnQ:{if(!C.payload.errors&&C.payload.data)J.next&&J.next(C.payload.data);if(C.payload.errors)J.error&&J.error(new LF({...C.payload,status:200},{query:F,variables:Y}));return}case $nQ:{J.error&&J.error(new LF({errors:C.payload,status:200},{query:F,variables:Y}));return}case Y91:{J.complete&&J.complete(),delete this.socketState.subscriptions[C.id];return}}}catch(C){console.error(C),A.close(1006)}A.close(4400,"Unknown graphql-ws message.")})}makeSubscribe(A,Q,B,D){let E=(this.socketState.lastRequestId++).toString();return this.socketState.subscriptions[E]={query:A,variables:D,subscriber:B},this.socket.send(qnQ(E,{query:A,operationName:Q,variables:D}).text),()=>{this.socket.send(OnQ(E).text),delete this.socketState.subscriptions[E]}}rawRequest(A,Q){return new Promise((B,D)=>{let E;this.rawSubscribe(A,{next:(I,C)=>E={data:I,extensions:C},error:D,complete:()=>B(E)},Q)})}request(A,Q){return new Promise((B,D)=>{let E;this.subscribe(A,{next:(I)=>E=I,error:D,complete:()=>B(E)},Q)})}subscribe(A,Q,B){let{query:D,operationName:E}=Q_(A);return this.makeSubscribe(D,E,Q,B)}rawSubscribe(A,Q,B){return this.makeSubscribe(A,void 0,Q,B)}ping(A){this.socket.send(MnQ(A).text)}close(){this.socket.close(1000)}}BwA.PROTOCOL="graphql-transport-ws";function WnQ(A,Q=(B)=>B){return dW.parse(A,Q)}function NnQ(A){return new dW(KnQ,A)}function MnQ(A){return new dW(C91,A,void 0)}function I91(A){return new dW(F91,A,void 0)}function qnQ(A,Q){return new dW(HnQ,Q,A)}function OnQ(A){return new dW(Y91,void 0,A)}var cy=(A)=>{let Q={};if(A)if(typeof Headers<"u"&&A instanceof Headers||cW&&cW.Headers&&A instanceof cW.Headers)Q=V11(A);else if(Array.isArray(A))A.forEach(([B,D])=>{if(B&&D!==void 0)Q[B]=D});else Q=A;return Q},J91=(A)=>A.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),LnQ=(A)=>{if(!Array.isArray(A.query)){let D=A,E=[`query=${encodeURIComponent(J91(D.query))}`];if(A.variables)E.push(`variables=${encodeURIComponent(D.jsonSerializer.stringify(D.variables))}`);if(D.operationName)E.push(`operationName=${encodeURIComponent(D.operationName)}`);return E.join("&")}if(typeof A.variables<"u"&&!Array.isArray(A.variables))throw Error("Cannot create query with given variable type, array expected");let Q=A,B=A.query.reduce((D,E,I)=>{return D.push({query:J91(E),variables:Q.variables?Q.jsonSerializer.stringify(Q.variables[I]):void 0}),D},[]);return`query=${encodeURIComponent(Q.jsonSerializer.stringify(B))}`},_nQ=(A)=>async(Q)=>{let{url:B,query:D,variables:E,operationName:I,fetch:C,fetchOptions:F,middleware:Y}=Q,J={...Q.headers},G="",X=void 0;if(A==="POST"){if(X=RnQ(D,E,I,F.jsonSerializer),typeof X==="string")J["Content-Type"]="application/json"}else G=LnQ({query:D,variables:E,operationName:I,jsonSerializer:F.jsonSerializer??W1A});let z={method:A,headers:J,body:X,...F},U=B,Z=z;if(Y){let K=await Promise.resolve(Y({...z,url:B,operationName:I,variables:E})),{url:H,...W}=K;U=H,Z=W}if(G)U=`${U}?${G}`;return await C(U,Z)};class IwA{constructor(A,Q={}){this.url=A,this.requestConfig=Q,this.rawRequest=async(...B)=>{let[D,E,I]=B,C=W11(D,E,I),{headers:F,fetch:Y=cW.default,method:J="POST",requestMiddleware:G,responseMiddleware:X,...z}=this.requestConfig,{url:U}=this;if(C.signal!==void 0)z.signal=C.signal;let{operationName:Z}=Q_(C.query);return DwA({url:U,query:C.query,variables:C.variables,headers:{...cy(EwA(F)),...cy(C.requestHeaders)},operationName:Z,fetch:Y,method:J,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,E=$11(A,B,D),{headers:I,fetch:C=cW.default,method:F="POST",requestMiddleware:Y,responseMiddleware:J,...G}=this.requestConfig,{url:X}=this;if(E.signal!==void 0)G.signal=E.signal;let{query:z,operationName:U}=Q_(E.document);return DwA({url:X,query:z,variables:E.variables,headers:{...cy(EwA(I)),...cy(E.requestHeaders)},operationName:U,fetch:C,method:F,fetchOptions:G,middleware:Y}).then((Z)=>{if(J)J(Z);return Z.data}).catch((Z)=>{if(J)J(Z);throw Z})}batchRequests(A,Q){let B=N11(A,Q),{headers:D,...E}=this.requestConfig;if(B.signal!==void 0)E.signal=B.signal;let I=B.documents.map(({document:F})=>Q_(F).query),C=B.documents.map(({variables:F})=>F);return DwA({url:this.url,query:I,variables:C,headers:{...cy(EwA(D)),...cy(B.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??cW.default,method:this.requestConfig.method||"POST",fetchOptions:E,middleware:this.requestConfig.requestMiddleware}).then((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);return F.data}).catch((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);throw F})}setHeaders(A){return this.requestConfig.headers=A,this}setHeader(A,Q){let{headers:B}=this.requestConfig;if(B)B[A]=Q;else this.requestConfig.headers={[A]:Q};return this}setEndpoint(A){return this.url=A,this}}var DwA=async(A)=>{let{query:Q,variables:B,fetchOptions:D}=A,E=_nQ(H11(A.method??"post")),I=Array.isArray(A.query),C=await E(A),F=await TnQ(C,D.jsonSerializer??W1A),Y=Array.isArray(F)?!F.some(({data:G})=>!G):Boolean(F.data),J=Array.isArray(F)||!F.errors||Array.isArray(F.errors)&&!F.errors.length||D.errorPolicy==="all"||D.errorPolicy==="ignore";if(C.ok&&J&&Y){let{errors:G,...X}=Array.isArray(F)?F:F,z=D.errorPolicy==="ignore"?X:F;return{...I?{data:z}:z,headers:C.headers,status:C.status}}else throw new LF({...typeof F==="string"?{error:F}:F,status:C.status,headers:C.headers},{query:Q,variables:B})};var RnQ=(A,Q,B,D)=>{let E=D??W1A;if(!Array.isArray(A))return E.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 I=A.reduce((C,F,Y)=>{return C.push({query:F,variables:Q?Q[Y]:void 0}),C},[]);return E.stringify(I)},TnQ=async(A,Q)=>{let B;if(A.headers.forEach((D,E)=>{if(E.toLowerCase()==="content-type")B=D}),B&&(B.toLowerCase().startsWith("application/json")||B.toLowerCase().startsWith("application/graphql+json")||B.toLowerCase().startsWith("application/graphql-response+json")))return Q.parse(await A.text());else return A.text()},EwA=(A)=>{return typeof A==="function"?A():A},$U=(A,...Q)=>{return A.reduce((B,D,E)=>`${B}${D}${E in Q?String(Q[E]):""}`,"")};var G91=async(A,Q,B)=>{if(!Q.ok){let D=await Q.text().catch(()=>{return});throw new K11(A,Q,B,D)}};function e8(){return"8.71.0"}var U91=(A)=>{let Q=A?`${A?.name}:${A?.version}`:"missing client info";return`gitlab-language-server:${e8()} (${Q})`};function X91(A){return A!==null&&A!==void 0}var CwA=(A,Q)=>{return Object.entries(Q).forEach(([B,D])=>{if(X91(D))A.searchParams.append(B,String(D))}),A},L0A=(A)=>A.toString().replace(/\/?$/,"/"),py=(A)=>A.replace(/^\.?\/?/,"./"),z91=(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 jnQ=(A)=>A.split("/").pop()||"unknown resource";class wc{#A;#Q;#B;#D;#E;constructor(A,Q,B,D,E){this.#A=A,this.#Q=Q,this.#B=new URL(L0A(D)),this.#D=E,this.#E=B}getDefaultHeaders(){return{Authorization:`Bearer ${this.#D}`,"User-Agent":U91(this.#E),"X-Gitlab-Language-Server-Version":e8()}}async fetchFromApiRaw(A){try{let Q=`Unknown request method "${A.method}", request type "${A.type}"`;switch(A.method){case"GET":return await this.#C(A);case"POST":return await this.#F(A);case"PATCH":return await this.#Y(A);case"PUT":return await this.#J(A);case"HEAD":return await this.#G(A);default:throw Error(Q)}}catch(Q){throw new V1A(A,Q)}}async fetchFromApi(A){if(A.type==="graphql")return this.#I(A);let Q=await this.fetchFromApiRaw(A);return await G91(A,Q,jnQ(A.path)),Q.json()}fetchOperation=(A)=>(Q)=>this.fetchFromApi({...A,signal:Q});async#I(A){let Q=new URL("./api/graphql",this.#B),B=w1A(A.query);if(B)this.#A.debug(`[SimpleApiClient] Making GraphQL request: ${B}`);let D=async(I,C)=>{let F=I instanceof URL?I.toString():I;return this.#Q.post(F,{...C,headers:{...C?.headers},signal:A.signal})},E=new IwA(Q.href,{fetch:D,headers:{...this.getDefaultHeaders()}});try{return await E.request(A.query,A.variables)}catch(I){if(I instanceof LF)throw new HzA(A,I.response);throw new V1A(A,I)}}async#C(A){let Q=py(A.path),B=new URL(Q,this.#B);return CwA(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#Y(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#J(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 CwA(B,A.searchParams??{}),this.#Q.head(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}}var Z91=["ai_features","read_api","api"],_0A=(A)=>{if(!(A instanceof Nd)||!A.isInvalidTokenOrInvalidRefresh())return{valid:!1,reason:"unknown",message:`Token validation failed: ${A}`};return{valid:!1,reason:"invalid_token",message:"Token is invalid or expired."}},H91=(A)=>{if(Z91.some((B)=>A.includes(B)))return;return{valid:!1,reason:"invalid_scopes",message:`Token has scope(s) ${A.map((B)=>`'${B}'`).join(", ")} (needs one of: ${Z91.join(", ")}).`}};async function K91(A,Q){let B={type:"rest",method:"GET",path:"/api/v4/personal_access_tokens/self"},{scopes:D}=await A.fetchFromApi(B),E=H91(D);if(E)return E;return{valid:!0,tokenInfo:{scopes:D,type:"pat",token:Q}}}async function w91(A,Q){let B={type:"rest",method:"GET",path:"/oauth/token/info"},{scope:D}=await A.fetchFromApi(B),E=H91(D);if(E)return E;return{valid:!0,tokenInfo:{scopes:D,type:"oauth",token:Q}}}async function R0A(A,Q,B){if(!Q)return{valid:!1,message:"No token provided",reason:"invalid_token"};if(B==="pat")return K91(A,Q).catch(_0A);if(B==="oauth")return w91(A,Q).catch(_0A);let D=await Promise.all([K91(A,Q).catch(_0A),w91(A,Q).catch(_0A)]),E=D.find((Y)=>Y.valid);if(E)return E;let I=D.filter((Y)=>!Y.valid),C=I.find((Y)=>Y.reason==="invalid_scopes");if(C)return C;let F=I.find((Y)=>Y.reason==="invalid_token");if(F)return F;return D[0]}var T0A=SA(T1(),1);var FwA=T0A.createInterfaceId("ProjectService");class Hc{#A;#Q;constructor(A,Q){this.#A=Q,this.#Q=L1(A,"[ProjectService]")}async getProjectFromPathWithNamespace(A){return this.#Q.debug(`Fetching details for project: ${A}`),(await this.#A.fetchFromApi({type:"graphql",query:$U`
1147
1147
  query getProjectDetails($fullPath: ID!) {
1148
1148
  project(fullPath: $fullPath) {
1149
1149
  id
@@ -1270,7 +1270,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
1270
1270
  `)){let D=B.split(`
1271
1271
  `),E=this.#A[this.#Q],I=E.slice(0,this.#B),C=E.slice(this.#B);this.#A[this.#Q]=I+D[0];for(let F=1;F<D.length;F++)this.#A.splice(this.#Q+F,0,D[F]);this.#Q+=D.length-1,this.#B=this.#A[this.#Q].length,this.#A[this.#Q]+=C}else{let D=this.#A[this.#Q];this.#A[this.#Q]=D.slice(0,this.#B)+B+D.slice(this.#B),this.#B+=B.length}this.onBufferChange()}delete(){if(this.#B>0){let A=this.#A[this.#Q];this.#A[this.#Q]=A.slice(0,this.#B-1)+A.slice(this.#B),this.#B--,this.onBufferChange()}else if(this.#Q>0){let A=this.#A[this.#Q];this.#Q--,this.#B=this.#A[this.#Q].length,this.#A[this.#Q]+=A,this.#A.splice(this.#Q+1,1),this.onBufferChange()}}deleteAfterCursor(){if(this.#B<this.#A[this.#Q].length){let A=this.#A[this.#Q];this.#A[this.#Q]=A.slice(0,this.#B)+A.slice(this.#B+1),this.onBufferChange()}else if(this.#Q<this.#A.length-1){let A=this.#A[this.#Q];this.#A[this.#Q]=A+this.#A[this.#Q+1],this.#A.splice(this.#Q+1,1),this.onBufferChange()}}deleteWordFromCursor(){let A=this.#A[this.#Q];if(this.#B>=A.length){if(this.#Q<this.#A.length-1){let B=this.#A[this.#Q+1];this.#A[this.#Q]=A+B,this.#A.splice(this.#Q+1,1),this.onBufferChange()}return}let Q=this.#B;while(Q<A.length&&A[Q]===" ")Q++;while(Q<A.length&&A[Q]!==" ")Q++;this.#A[this.#Q]=A.slice(0,this.#B)+A.slice(Q),this.onBufferChange()}deleteWordToCursor(){let A=this.#A[this.#Q];if(this.#B===0){if(this.#Q>0){let B=this.#A[this.#Q];this.#Q--,this.#B=this.#A[this.#Q].length,this.#A[this.#Q]+=B,this.#A.splice(this.#Q+1,1),this.onBufferChange()}return}let Q=this.#B-1;while(Q>0&&A[Q]===" ")Q--;while(Q>0&&A[Q-1]!==" ")Q--;this.#A[this.#Q]=A.slice(0,Q)+A.slice(this.#B),this.#B=Q,this.onBufferChange()}left(){if(this.#B>0)this.#B--,this.onBufferChange();else if(this.#Q>0)this.#Q--,this.#B=this.#A[this.#Q].length,this.onBufferChange()}right(){if(this.#B<this.#A[this.#Q].length)this.#B++,this.onBufferChange();else if(this.#Q<this.#A.length-1)this.#Q++,this.#B=0,this.onBufferChange()}up(){if(this.#Q>0)this.#Q--,this.#B=Math.min(this.#B,this.#A[this.#Q].length),this.onBufferChange()}down(){if(this.#Q<this.#A.length-1)this.#Q++,this.#B=Math.min(this.#B,this.#A[this.#Q].length),this.onBufferChange()}wordLeft(){let A=this.#A[this.#Q];if(this.#B===0){if(this.#Q>0)this.#Q--,this.#B=this.#A[this.#Q].length,this.onBufferChange();return}let Q=this.#B-1;while(Q>0&&A[Q]===" ")Q--;while(Q>0&&A[Q-1]!==" ")Q--;this.#B=Q,this.onBufferChange()}wordRight(){let A=this.#A[this.#Q];if(this.#B>=A.length){if(this.#Q<this.#A.length-1){this.#Q++;let E=this.#A[this.#Q],I=0;while(I<E.length&&E[I]===" ")I++;while(I<E.length&&E[I]!==" ")I++;this.#B=I,this.onBufferChange()}return}let Q=this.#B,B=A[Q]===" ",D=!B&&(Q===0||A[Q-1]===" ");if(B){while(Q<A.length&&A[Q]===" ")Q++;while(Q<A.length&&A[Q]!==" ")Q++}else if(D){while(Q<A.length&&A[Q]!==" ")Q++;while(Q<A.length&&A[Q]===" ")Q++}else{while(Q<A.length&&A[Q]!==" ")Q++;while(Q<A.length&&A[Q]===" ")Q++;while(Q<A.length&&A[Q]!==" ")Q++}this.#B=Q,this.onBufferChange()}home(){this.#B=0,this.onBufferChange()}end(){this.#B=this.#A[this.#Q].length,this.onBufferChange()}clear(){this.#A=[""],this.#Q=0,this.#B=0,this.onBufferChange()}getWordToCursor(){let Q=this.#A[this.#Q].slice(0,this.#B),B=Q.lastIndexOf(" ");return Q.slice(B+1)}getWordAtCursor(){let A=this.#A[this.#Q],Q=this.#B;if(A[Q]===" ")return"";while(Q>0&&A[Q-1]!==" ")Q--;let B=this.#B;while(B<A.length&&A[B]!==" ")B++;return A.slice(Q,B)}replaceWordAtCursor(A){let Q=this.#A[this.#Q],B=this.#B;while(B>0&&Q[B-1]!==" ")B--;let D=this.#B;while(D<Q.length&&Q[D]!==" ")D++;this.#A[this.#Q]=Q.slice(0,B)+A+Q.slice(D),this.#B=B+A.length,this.onBufferChange()}}var fp=(A,Q)=>{return Q?"*".repeat(A.length):A};import{Buffer as N36}from"node:buffer";var M36=/^(?:\x1b)([a-zA-Z0-9])$/,q36=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,wz1={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear",f:"right",b:"left",p:"up",n:"down","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},O36=[...Object.values(wz1),"backspace"],L36=(A)=>{return["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(A)},_36=(A)=>{return["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(A)},R36=/^\x1b\[27;(\d+);(\d+)~$/,p6A=(A="",Q={})=>{let B;if(N36.isBuffer(A))if(A[0]>127&&A[1]===void 0)A[0]-=128,A="\x1B"+String(A);else A=String(A);else if(A!==void 0&&typeof A!=="string")A=String(A);else if(!A)A="";if(/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(A))return null;if(A.startsWith("\x1B[M")&&A.length>=6)return null;if(/^\x1b\[\d+;\d+;\d+t$/.test(A))return null;if(/^\x1b\[\d+;\d+R$/.test(A))return null;if(/^\x1b\[\?[\d;]+c$/.test(A))return null;if(/^\x1b\[\?[\d;]+\$y$/.test(A))return null;if(A==="\x1B[I"||A==="\x1B[O")return null;if(/^\x1b\][\d;].*(\x1b\\|\x07)$/.test(A))return null;if(A==="\x1B[200~"||A==="\x1B[201~")return null;let D={name:"",ctrl:!1,meta:!1,shift:!1,option:!1,number:!1,sequence:A,raw:A,eventType:"press",source:"raw",timestamp:Date.now()};D.sequence=D.sequence||A||D.name;let E=R36.exec(A);if(E){let I=parseInt(E[1],10)-1,C=parseInt(E[2],10);if(D.ctrl=!!(I&4),D.meta=!!(I&2),D.shift=!!(I&1),D.option=!!(I&2),D.super=!!(I&8),D.hyper=!!(I&16),C===13)D.name="return";else if(C===27)D.name="escape";else if(C===9)D.name="tab";else if(C===32)D.name="space";else if(C===127||C===8)D.name="backspace";else D.name=String.fromCharCode(C);return D}if(A==="\r")D.name="return";else if(A==="\x1B\r")D.name="return",D.shift=!0;else if(A===`
1272
1272
  `||A===`\x1B
1273
- `)D.name="linefeed",D.meta=A.length===2;else if(A==="\t")D.name="tab";else if(A==="\b"||A==="\x1B\b"||A===""||A==="\x1B")D.name="backspace",D.meta=A.charAt(0)==="\x1B";else if(A==="\x1B"||A==="\x1B\x1B")D.name="escape",D.meta=A.length===2;else if(A===" "||A==="\x1B ")D.name="space",D.meta=A.length===2;else if(A==="\x00")D.name="space",D.ctrl=!0;else if(A.length===1&&A<="\x1A")D.name=String.fromCharCode(A.charCodeAt(0)+97-1),D.ctrl=!0;else if(A.length===1&&A>="0"&&A<="9")D.name=A,D.number=!0;else if(A.length===1&&A>="a"&&A<="z")D.name=A;else if(A.length===1&&A>="A"&&A<="Z")D.name=A;else if(A.length===1)D.name=A;else if(B=M36.exec(A)){D.meta=!0;let I=B[1],C=/^[A-Z]$/.test(I);if(I==="F")D.name="right";else if(I==="B")D.name="left";else if(C)D.shift=!0,D.name=I;else D.name=I}else if(A.length===2&&A[0]==="\x1B"&&A[1]<="\x1A")D.meta=!0,D.ctrl=!0,D.name=String.fromCharCode(A.charCodeAt(1)+97-1);else if(B=q36.exec(A)){let I=[...A];if(I[0]==="\x1B"&&I[1]==="\x1B")D.option=!0,D.meta=!0;let C=[B[1],B[2],B[4],B[6]].filter(Boolean).join(""),F=parseInt(B[3]||B[5]||"1",10)-1;D.ctrl=!!(F&4),D.meta=!!(F&2),D.shift=!!(F&1),D.option=!!(F&2),D.super=!!(F&8),D.hyper=!!(F&16),D.code=C;let Y=wz1[C];if(Y)D.name=Y,D.shift=L36(C)||D.shift,D.ctrl=_36(C)||D.ctrl;else D.name="",D.code=void 0}else if(A==="\x1B[3~")D.name="delete",D.meta=!1,D.code="[3~";return D};function l6A(A){return{name:T36(A.name),sequence:A.text||A.name.toLowerCase(),raw:A.text||A.name.toLowerCase(),ctrl:A.ctrl,meta:A.alt,shift:A.shift,option:A.alt,super:A.super,number:/^\d$/.test(A.name),eventType:A.event,capsLock:A.caps_lock,numLock:A.num_lock,baseCode:A.code?.base,source:"kitty",timestamp:Date.now()}}function T36(A){let Q={ESC:"escape",ENTER:"return",TAB:"tab",BACKSPACE:"backspace",DELETE:"delete",INSERT:"insert",LEFT:"left",RIGHT:"right",UP:"up",DOWN:"down",PAGE_UP:"pageup",PAGE_DOWN:"pagedown",HOME:"home",END:"end",CAPS_LOCK:"capslock",SCROLL_LOCK:"scrolllock",NUM_LOCK:"numlock",PRINT_SCREEN:"printscreen",PAUSE:"pause",MENU:"menu",LEFT_SHIFT:"leftshift",LEFT_CONTROL:"leftcontrol",LEFT_ALT:"leftalt",LEFT_SUPER:"leftsuper",RIGHT_SHIFT:"rightshift",RIGHT_CONTROL:"rightcontrol",RIGHT_ALT:"rightalt",RIGHT_SUPER:"rightsuper",PASTE:"paste"};if(Q[A])return Q[A];if(/^F\d+$/.test(A))return A.toLowerCase();if(A.includes("_"))return A.toLowerCase().replace(/_/g,"");if(A.length===1)return A;return A.toLowerCase()}var Hz1=new TextEncoder,j36=new TextDecoder;function S_(A,Q=1){let B=P36(A);return Hz1.encode(`\x1B[=${B};${Q}u`)}var p$A=Hz1.encode("\x1B[?u");function l$A(A){let Q=j36.decode(A);if(!Q.startsWith("\x1B[?")||Q.at(-1)!=="u")return;let B=Number.parseInt(Q.slice(3,-1),10);if(!Number.isSafeInteger(B))return;let D={};if(B&1)D.disambiguate=!0;if(B&2)D.events=!0;if(B&4)D.alternates=!0;if(B&8)D.all_keys=!0;if(B&16)D.text=!0;return D}function P36(A){let Q=0;if(A.disambiguate)Q+=1;if(A.events)Q+=2;if(A.alternates)Q+=4;if(A.all_keys)Q+=8;if(A.text)Q+=16;return Q.toString()}var S36=String.raw`(\x1b\x5b|\x1b\x4f)`,y36=String.raw`(?:(\d+)(?::(\d*))?(?::(\d*))?)?`,v36=String.raw`(?:;(\d*)?(?::(\d*))?)?`,k36=String.raw`(?:;([\d:]*))?`,g36=String.raw`([u~ABCDEFHPQS])`,b36=new RegExp(S36+y36+v36+k36+g36),Vz1=new TextDecoder,f36={"\x1B[27u":"ESC","\x1B[13u":"ENTER","\x1B[9u":"TAB","\x1B[127u":"BACKSPACE","\x1B[2~":"INSERT","\x1B[3~":"DELETE","\x1B[1D":"LEFT","\x1B[D":"LEFT","\x1BOD":"LEFT","\x1B[1C":"RIGHT","\x1B[C":"RIGHT","\x1BOC":"RIGHT","\x1B[1A":"UP","\x1B[A":"UP","\x1BOA":"UP","\x1B[1B":"DOWN","\x1B[B":"DOWN","\x1BOB":"DOWN","\x1B[5~":"PAGE_UP","\x1B[6~":"PAGE_DOWN","\x1B[7~":"HOME","\x1B[1H":"HOME","\x1B[H":"HOME","\x1BOH":"HOME","\x1B[8~":"END","\x1B[1F":"END","\x1B[F":"END","\x1BOF":"END","\x1B[57358u":"CAPS_LOCK","\x1B[57359u":"SCROLL_LOCK","\x1B[57360u":"NUM_LOCK","\x1B[57361u":"PRINT_SCREEN","\x1B[57362u":"PAUSE","\x1B[57363u":"MENU","\x1B[11~":"F1","\x1B[1P":"F1","\x1B[P":"F1","\x1BOP":"F1","\x1B[12~":"F2","\x1B[1Q":"F2","\x1B[Q":"F2","\x1BOQ":"F2","\x1B[13~":"F3","\x1BOR":"F3","\x1B[14~":"F4","\x1B[1S":"F4","\x1B[S":"F4","\x1BOS":"F4","\x1B[15~":"F5","\x1B[17~":"F6","\x1B[18~":"F7","\x1B[19~":"F8","\x1B[20~":"F9","\x1B[21~":"F10","\x1B[23~":"F11","\x1B[24~":"F12","\x1B[57441u":"LEFT_SHIFT","\x1B[57442u":"LEFT_CONTROL","\x1B[57443u":"LEFT_ALT","\x1B[57444u":"LEFT_SUPER","\x1B[57447u":"RIGHT_SHIFT","\x1B[57448u":"RIGHT_CONTROL","\x1B[57449u":"RIGHT_ALT","\x1B[57450u":"RIGHT_SUPER"};class V7{name="";code;event="press";text;shift=!1;alt=!1;ctrl=!1;super=!1;caps_lock=!1;num_lock=!1;static create(A){return Object.assign(new V7,A)}static parse(A){if(A.length===0)return;let Q=A[0];if(Q===27&&A.length===1){let C=new V7;return C.name="ESC",[C,1]}if(Q===27&&A.length>=2&&A[1]===127){let C=new V7;return C.name="BACKSPACE",C.ctrl=!0,[C,2]}if(Q===27&&A.length>=2&&A[1]===100){let C=new V7;return C.name="DELETE",C.ctrl=!0,[C,2]}if(Q===27&&A.length>=2&&A[1]===98){let C=new V7;return C.name="LEFT",C.alt=!0,[C,2]}if(Q===27&&A.length>=2&&A[1]===102){let C=new V7;return C.name="RIGHT",C.alt=!0,[C,2]}if(Q===13){let C=new V7;return C.name="ENTER",[C,1]}if(Q===9){let C=new V7;return C.name="TAB",[C,1]}if(Q===127){let C=new V7;return C.name="BACKSPACE",[C,1]}if(Q===4){let C=new V7;return C.name="DELETE",[C,1]}if(Q===8){let C=new V7;return C.name="DELETE",[C,1]}if(Q!==27){let C=A.indexOf(27,1);if(C<0)C=A.length;let F=new V7;return F.name=F.text=Vz1.decode(A.subarray(0,C)),[F,C]}let B=Vz1.decode(A).match(b36);if(!B)return;let D=new V7,E=f36[B[1]+(B[2]??"")+B[8]];if(typeof E==="string")D.name=E;else{let C=Ik(B[2]);if(typeof C==="number")D.name=String.fromCodePoint(C);else D.name=B[1]+B[8]}D.code={key:Ik(B[2]),shift:Ik(B[3]),base:Ik(B[4])};let I=(Ik(B[5])??1)-1;switch(D.shift=Boolean(I&1),D.alt=Boolean(I&2),D.ctrl=Boolean(I&4),D.super=Boolean(I&8),D.caps_lock=Boolean(I&64),D.num_lock=Boolean(I&128),B[6]){case"2":D.event="repeat";break;case"3":D.event="release";break;default:D.event="press";break}if(B[7])D.text=String.fromCodePoint(...B[7].split(":").map(Ik).filter((C)=>typeof C==="number"));return[D,B.index+B[0].length]}}function Ik(A){if(A){let Q=Number.parseInt(A);if(Number.isSafeInteger(Q))return Q}return}var m36="[200~",u36="[201~";class xp{#A;#Q=!1;#B="";#D=!1;onKey;constructor(){this.#A=new K7,this.onKey=this.#A.event}setKittyProtocol(A){this.#D=A}get isKittyProtocol(){return this.#D}processRawInput(A){let Q=A.toString(),B=this.#C(Q);if(B.isPasting){if(!B.isFullyParsed)return;if(B.text)this.#E(B.text);return}if(this.#D){let D=V7.parse(A);if(D){let[E]=D,I=l6A(E);this.#A.fire(I)}}else if(Q.startsWith("\x1B")){let E=p6A(Q);if(E)this.#A.fire(E)}else for(let E of Q){let I=p6A(E);if(I)this.#A.fire(I)}}processKittyInput(A){let Q=l6A(A);this.#A.fire(Q)}processPasteEvent(A){this.#E(A)}#E(A){let Q={name:"paste",sequence:A,raw:A,ctrl:!1,meta:!1,shift:!1,option:!1,number:!1,eventType:"press",source:this.#D?"kitty":"raw",timestamp:Date.now()};this.#A.fire(Q)}#I(A){return A.replace(/(\r\n|\n|\r)/g,`
1273
+ `)D.name="linefeed",D.meta=A.length===2;else if(A==="\t")D.name="tab";else if(A==="\b"||A==="\x1B\b"||A===""||A==="\x1B")D.name="backspace",D.meta=A.charAt(0)==="\x1B";else if(A==="\x1B"||A==="\x1B\x1B")D.name="escape",D.meta=A.length===2;else if(A===" "||A==="\x1B ")D.name="space",D.meta=A.length===2;else if(A==="\x00")D.name="space",D.ctrl=!0;else if(A.length===1&&A<="\x1A")D.name=String.fromCharCode(A.charCodeAt(0)+97-1),D.ctrl=!0;else if(A.length===1&&A>="0"&&A<="9")D.name=A,D.number=!0;else if(A.length===1&&A>="a"&&A<="z")D.name=A;else if(A.length===1&&A>="A"&&A<="Z")D.name=A;else if(A.length===1)D.name=A;else if(B=M36.exec(A)){D.meta=!0;let I=B[1],C=/^[A-Z]$/.test(I);if(I==="F")D.name="right";else if(I==="B")D.name="left";else if(C)D.shift=!0,D.name=I;else D.name=I}else if(A.length===2&&A[0]==="\x1B"&&A[1]<="\x1A")D.meta=!0,D.ctrl=!0,D.name=String.fromCharCode(A.charCodeAt(1)+97-1);else if(B=q36.exec(A)){let I=[...A];if(I[0]==="\x1B"&&I[1]==="\x1B")D.option=!0,D.meta=!0;let C=[B[1],B[2],B[4],B[6]].filter(Boolean).join(""),F=parseInt(B[3]||B[5]||"1",10)-1;D.ctrl=!!(F&4),D.meta=!!(F&2),D.shift=!!(F&1),D.option=!!(F&2),D.super=!!(F&8),D.hyper=!!(F&16),D.code=C;let Y=wz1[C];if(Y)D.name=Y,D.shift=L36(C)||D.shift,D.ctrl=_36(C)||D.ctrl;else D.name="",D.code=void 0}else if(A==="\x1B[3~")D.name="delete",D.meta=!1,D.code="[3~";return D};function l6A(A){return{name:T36(A.name),sequence:A.text||A.name.toLowerCase(),raw:A.text||A.name.toLowerCase(),ctrl:A.ctrl,meta:A.alt,shift:A.shift,option:A.alt,super:A.super,number:/^\d$/.test(A.name),eventType:A.event,capsLock:A.caps_lock,numLock:A.num_lock,baseCode:A.code?.base,source:"kitty",timestamp:Date.now()}}function T36(A){let Q={ESC:"escape",ENTER:"return",TAB:"tab",BACKSPACE:"backspace",DELETE:"delete",INSERT:"insert",LEFT:"left",RIGHT:"right",UP:"up",DOWN:"down",PAGE_UP:"pageup",PAGE_DOWN:"pagedown",HOME:"home",END:"end",CAPS_LOCK:"capslock",SCROLL_LOCK:"scrolllock",NUM_LOCK:"numlock",PRINT_SCREEN:"printscreen",PAUSE:"pause",MENU:"menu",LEFT_SHIFT:"leftshift",LEFT_CONTROL:"leftcontrol",LEFT_ALT:"leftalt",LEFT_SUPER:"leftsuper",RIGHT_SHIFT:"rightshift",RIGHT_CONTROL:"rightcontrol",RIGHT_ALT:"rightalt",RIGHT_SUPER:"rightsuper",PASTE:"paste"};if(Q[A])return Q[A];if(/^F\d+$/.test(A))return A.toLowerCase();if(A.length===1)return A;if(A.includes("_"))return A.toLowerCase().replace(/_/g,"");return A.toLowerCase()}var Hz1=new TextEncoder,j36=new TextDecoder;function S_(A,Q=1){let B=P36(A);return Hz1.encode(`\x1B[=${B};${Q}u`)}var p$A=Hz1.encode("\x1B[?u");function l$A(A){let Q=j36.decode(A);if(!Q.startsWith("\x1B[?")||Q.at(-1)!=="u")return;let B=Number.parseInt(Q.slice(3,-1),10);if(!Number.isSafeInteger(B))return;let D={};if(B&1)D.disambiguate=!0;if(B&2)D.events=!0;if(B&4)D.alternates=!0;if(B&8)D.all_keys=!0;if(B&16)D.text=!0;return D}function P36(A){let Q=0;if(A.disambiguate)Q+=1;if(A.events)Q+=2;if(A.alternates)Q+=4;if(A.all_keys)Q+=8;if(A.text)Q+=16;return Q.toString()}var S36=String.raw`(\x1b\x5b|\x1b\x4f)`,y36=String.raw`(?:(\d+)(?::(\d*))?(?::(\d*))?)?`,v36=String.raw`(?:;(\d*)?(?::(\d*))?)?`,k36=String.raw`(?:;([\d:]*))?`,g36=String.raw`([u~ABCDEFHPQS])`,b36=new RegExp(S36+y36+v36+k36+g36),Vz1=new TextDecoder,f36={"\x1B[27u":"ESC","\x1B[13u":"ENTER","\x1B[9u":"TAB","\x1B[127u":"BACKSPACE","\x1B[2~":"INSERT","\x1B[3~":"DELETE","\x1B[1D":"LEFT","\x1B[D":"LEFT","\x1BOD":"LEFT","\x1B[1C":"RIGHT","\x1B[C":"RIGHT","\x1BOC":"RIGHT","\x1B[1A":"UP","\x1B[A":"UP","\x1BOA":"UP","\x1B[1B":"DOWN","\x1B[B":"DOWN","\x1BOB":"DOWN","\x1B[5~":"PAGE_UP","\x1B[6~":"PAGE_DOWN","\x1B[7~":"HOME","\x1B[1H":"HOME","\x1B[H":"HOME","\x1BOH":"HOME","\x1B[8~":"END","\x1B[1F":"END","\x1B[F":"END","\x1BOF":"END","\x1B[57358u":"CAPS_LOCK","\x1B[57359u":"SCROLL_LOCK","\x1B[57360u":"NUM_LOCK","\x1B[57361u":"PRINT_SCREEN","\x1B[57362u":"PAUSE","\x1B[57363u":"MENU","\x1B[11~":"F1","\x1B[1P":"F1","\x1B[P":"F1","\x1BOP":"F1","\x1B[12~":"F2","\x1B[1Q":"F2","\x1B[Q":"F2","\x1BOQ":"F2","\x1B[13~":"F3","\x1BOR":"F3","\x1B[14~":"F4","\x1B[1S":"F4","\x1B[S":"F4","\x1BOS":"F4","\x1B[15~":"F5","\x1B[17~":"F6","\x1B[18~":"F7","\x1B[19~":"F8","\x1B[20~":"F9","\x1B[21~":"F10","\x1B[23~":"F11","\x1B[24~":"F12","\x1B[57441u":"LEFT_SHIFT","\x1B[57442u":"LEFT_CONTROL","\x1B[57443u":"LEFT_ALT","\x1B[57444u":"LEFT_SUPER","\x1B[57447u":"RIGHT_SHIFT","\x1B[57448u":"RIGHT_CONTROL","\x1B[57449u":"RIGHT_ALT","\x1B[57450u":"RIGHT_SUPER"};class V7{name="";code;event="press";text;shift=!1;alt=!1;ctrl=!1;super=!1;caps_lock=!1;num_lock=!1;static create(A){return Object.assign(new V7,A)}static parse(A){if(A.length===0)return;let Q=A[0];if(Q===27&&A.length===1){let C=new V7;return C.name="ESC",[C,1]}if(Q===27&&A.length>=2&&A[1]===127){let C=new V7;return C.name="BACKSPACE",C.ctrl=!0,[C,2]}if(Q===27&&A.length>=2&&A[1]===100){let C=new V7;return C.name="DELETE",C.ctrl=!0,[C,2]}if(Q===27&&A.length>=2&&A[1]===98){let C=new V7;return C.name="LEFT",C.alt=!0,[C,2]}if(Q===27&&A.length>=2&&A[1]===102){let C=new V7;return C.name="RIGHT",C.alt=!0,[C,2]}if(Q===13){let C=new V7;return C.name="ENTER",[C,1]}if(Q===9){let C=new V7;return C.name="TAB",[C,1]}if(Q===127){let C=new V7;return C.name="BACKSPACE",[C,1]}if(Q===4){let C=new V7;return C.name="DELETE",[C,1]}if(Q===8){let C=new V7;return C.name="DELETE",[C,1]}if(Q!==27){let C=A.indexOf(27,1);if(C<0)C=A.length;let F=new V7;return F.name=F.text=Vz1.decode(A.subarray(0,C)),[F,C]}let B=Vz1.decode(A).match(b36);if(!B)return;let D=new V7,E=f36[B[1]+(B[2]??"")+B[8]];if(typeof E==="string")D.name=E;else{let C=Ik(B[2]);if(typeof C==="number")D.name=String.fromCodePoint(C);else D.name=B[1]+B[8]}D.code={key:Ik(B[2]),shift:Ik(B[3]),base:Ik(B[4])};let I=(Ik(B[5])??1)-1;switch(D.shift=Boolean(I&1),D.alt=Boolean(I&2),D.ctrl=Boolean(I&4),D.super=Boolean(I&8),D.caps_lock=Boolean(I&64),D.num_lock=Boolean(I&128),B[6]){case"2":D.event="repeat";break;case"3":D.event="release";break;default:D.event="press";break}if(B[7])D.text=String.fromCodePoint(...B[7].split(":").map(Ik).filter((C)=>typeof C==="number"));return[D,B.index+B[0].length]}}function Ik(A){if(A){let Q=Number.parseInt(A);if(Number.isSafeInteger(Q))return Q}return}var m36="[200~",u36="[201~";class xp{#A;#Q=!1;#B="";#D=!1;onKey;constructor(){this.#A=new K7,this.onKey=this.#A.event}setKittyProtocol(A){this.#D=A}get isKittyProtocol(){return this.#D}processRawInput(A){let Q=A.toString(),B=this.#C(Q);if(B.isPasting){if(!B.isFullyParsed)return;if(B.text)this.#E(B.text);return}if(this.#D){let D=A;while(D.length>0){let E=V7.parse(D);if(!E)break;let[I,C]=E,F=l6A(I);this.#A.fire(F),D=D.subarray(C)}}else if(Q.startsWith("\x1B")){let E=p6A(Q);if(E)this.#A.fire(E)}else for(let E of Q){let I=p6A(E);if(I)this.#A.fire(I)}}processKittyInput(A){let Q=l6A(A);this.#A.fire(Q)}processPasteEvent(A){this.#E(A)}#E(A){let Q={name:"paste",sequence:A,raw:A,ctrl:!1,meta:!1,shift:!1,option:!1,number:!1,eventType:"press",source:this.#D?"kitty":"raw",timestamp:Date.now()};this.#A.fire(Q)}#I(A){return A.replace(/(\r\n|\n|\r)/g,`
1274
1274
  `).replace("\x1B","").replace("\x1B","").replace(/\[200~/g,"").replace(/\[201~/g,"")}#C(A){let Q=A.includes(m36),B=A.includes(u36);if(!this.#Q&&!(Q||B))return{isPasting:!1};if(Q&&!B)return this.#Q=!0,this.#B=A,{isPasting:!0,isFullyParsed:!1};if(this.#Q&&!B)return this.#B+=A,{isPasting:!0,isFullyParsed:!1};if(this.#Q&&B){let D=this.#I(this.#B+A);return this.#Q=!1,this.#B="",{isPasting:!0,isFullyParsed:!0,text:D}}return{isPasting:!0,isFullyParsed:!0,text:this.#I(A)}}resetPasteState(){this.#Q=!1,this.#B=""}dispose(){this.#A.dispose()}}var ez=SA(y6(),1);var $z1=SA(y6(),1);class i6A{#A=new Set;dispose(){process.stdin.off("data",this.#Q),this.#A.clear()}subscribe(A){this.#A.add(A)}unsubscribe(A){this.#A.delete(A)}startStdinListening(){process.stdin.on("data",this.#Q)}emitData(A){this.#Q(A)}#Q=(A)=>{for(let Q of this.#A.values())Q(A)}}var a6A=$z1.createContext(new i6A);var Wz1=SA(y6(),1),Ck=Wz1.createContext({terminalName:"unknown",isKittyProtocolSupported:!1,duoCliVersion:"unknown",environment:"development"});var d36=Symbol.for("react.transitional.element"),c36=Symbol.for("react.fragment");function Nz1(A,Q,B){var D=null;if(B!==void 0&&(D=""+B),Q.key!==void 0&&(D=""+Q.key),"key"in Q){B={};for(var E in Q)E!=="key"&&(B[E]=Q[E])}else B=Q;return Q=B.ref,{$$typeof:d36,type:A,key:D,ref:Q!==void 0?Q:null,props:B}}var y5=c36,iA=Nz1,P0=Nz1;var Fk=ez.createContext(new xp),i$A=({children:A})=>{let Q=ez.useContext(a6A),{isKittyProtocolSupported:B}=ez.useContext(Ck),[D]=ez.useState(()=>new xp);return ez.useEffect(()=>{D.setKittyProtocol(B)},[B,D]),ez.useEffect(()=>{let E=(I)=>{D.processRawInput(I)};return Q.subscribe(E),()=>{Q.unsubscribe(E)}},[Q,D]),iA(Fk.Provider,{value:D,children:A})};var ZH=SA(y6(),1);var Mz1=(A)=>A.eventType!=="release",hp=(A,Q=Mz1)=>{let B=ZH.useContext(Fk),D=ZH.useRef(A),E=ZH.useRef(Q);ZH.useEffect(()=>{D.current=A},[A]),ZH.useEffect(()=>{E.current=Q},[Q]),ZH.useEffect(()=>{let I=B.onKey((C)=>{if(E.current(C))D.current(C)});return()=>I.dispose()},[B])},IC={isEnter:(A)=>A.name==="return"&&!A.ctrl&&!A.shift&&!A.meta,isShiftEnter:(A)=>A.name==="return"&&A.shift&&!A.ctrl&&!A.meta,isCtrl:(A,Q)=>Q.name===A&&Q.ctrl,isTab:(A)=>A.name==="tab"&&!A.shift,isShiftTab:(A)=>A.name==="tab"&&A.shift};var KH=({value:A,onChange:Q,placeholder:B="",masked:D,inputContext:E={contextActions:[],noContextAction(){}},initialTextBuffer:I=new bp(A),onHistoryPrevious:C,onHistoryNext:F})=>{let[{textBuffer:Y},J]=Yk.useState({textBuffer:I}),{contextActions:G,noContextAction:X}=E;Yk.useEffect(()=>{Y.onBufferChange=()=>{J({textBuffer:Y})}},[Y]),hp((K)=>{if(IC.isEnter(K))return;if(K.name==="paste"&&K.sequence){let q=K.sequence;Y.insert(q,!0)}if(K.name==="home"||K.name==="a"&&K.ctrl)Y.home();else if(K.name==="end"||K.name==="e"&&K.ctrl)Y.end();else if(IC.isShiftEnter(K)||K.name==="linefeed"||K.name==="j"&&K.ctrl)Y.insert(`
1275
1275
  `);else if(K.name==="left"&&(K.ctrl||K.meta))Y.wordLeft();else if(K.name==="right"&&(K.ctrl||K.meta))Y.wordRight();else if(K.name==="b"&&K.meta)Y.wordLeft();else if(K.name==="f"&&K.meta)Y.wordRight();else if(K.name==="left")Y.left();else if(K.name==="right")Y.right();else if(K.name==="backspace"&&(K.ctrl||K.meta))Y.deleteWordToCursor();else if(K.name==="backspace")Y.delete();else if(K.name==="delete"&&(K.ctrl||K.meta))Y.deleteWordFromCursor();else if(K.name==="delete")Y.deleteAfterCursor();else if(K.name==="d"&&K.ctrl)Y.deleteAfterCursor();else if(K.name==="space")Y.insert(" ");else if(!K.ctrl&&!K.meta&&K.name.length===1){let q=K.shift&&K.name>="a"&&K.name<="z"?K.name.toUpperCase():K.name;Y.insert(q)}let H=Y.getWordAtCursor(),W=!1;for(let q of G)if(H.startsWith(q.activationSequence.inputChar)){let M=H.substring(q.activationSequence.inputChar.length);D9(q.actionCallback(M)),W=!0;break}if(!W){if(K.name==="up")if(Y.cursor.line===0)C?.();else Y.up();else if(K.name==="down")if(Y.cursor.line===Y.lines.length-1)F?.();else Y.down()}if(!W)X();if(Y.text!==A)Q(Y.text)}),Y.setText(A);let{lines:z,cursor:U}=Y;return iA(I0,{flexDirection:"column",children:P0(I0,{borderLeft:!1,borderRight:!1,borderStyle:"single",borderColor:"gray",children:[iA(f1,{children:"> "}),(()=>{if(z.length===1&&z[0]==="")return P0(y5,{children:[iA(f1,{children:"█ "}),iA(f1,{dimColor:!0,children:B})]});return iA(f1,{children:z.map((K,H)=>P0(Yk.default.Fragment,{children:[H===U.line?P0(y5,{children:[iA(f1,{children:fp(K.slice(0,U.column),D)}),iA(f1,{inverse:!0,children:K[U.column]?fp(K[U.column],D):" "}),iA(f1,{children:fp(K.slice(U.column+1),D)})]}):iA(f1,{children:fp(K,D)}),H<z.length-1&&`
1276
1276
  `]},H))})})()]})})};class mp{#A=[];#Q;constructor(A){this.#Q=A.onKey((Q)=>{this.#D(Q)})}addHandler(A){return this.#A.push(A),()=>{this.#B(A)}}#B(A){let Q=this.#A.indexOf(A);if(Q!==-1)this.#A.splice(Q,1)}#D(A){let Q=[...this.#A];for(let B of Q){let D=!1,E={...A,stopPropagation(){D=!0}};if(B(E),D)return}}dispose(){this.#Q?.dispose(),this.#Q=void 0,this.#A=[]}}var wH=SA(y6(),1);var n6A=wH.createContext(null),o6A=({children:A})=>{let Q=wH.useContext(Fk),[B]=wH.useState(()=>new mp(Q));return wH.useEffect(()=>{return()=>{B.dispose()}},[B]),iA(n6A.Provider,{value:B,children:A})};function r6A(){let A=wH.useContext(n6A);if(!A)throw Error("useKeyHandlerManager must be used within KeyHandlerProvider");return A}var up=SA(y6(),1);function YD(A){let Q=r6A(),B=up.useRef(A);up.useEffect(()=>{B.current=A}),up.useEffect(()=>{let D=(...I)=>B.current(...I);return Q.addHandler(D)},[Q])}function n$A(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var v_=n$A();function Tz1(A){v_=A}var jz1=/[&<>"']/,p36=new RegExp(jz1.source,"g"),Pz1=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,l36=new RegExp(Pz1.source,"g"),i36={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},qz1=(A)=>i36[A];function vF(A,Q){if(Q){if(jz1.test(A))return A.replace(p36,qz1)}else if(Pz1.test(A))return A.replace(l36,qz1);return A}var a36=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function n36(A){return A.replace(a36,(Q,B)=>{if(B=B.toLowerCase(),B==="colon")return":";if(B.charAt(0)==="#")return B.charAt(1)==="x"?String.fromCharCode(parseInt(B.substring(2),16)):String.fromCharCode(+B.substring(1));return""})}var o36=/(^|[^\[])\^/g;function k8(A,Q){let B=typeof A==="string"?A:A.source;Q=Q||"";let D={replace:(E,I)=>{let C=typeof I==="string"?I:I.source;return C=C.replace(o36,"$1"),B=B.replace(E,C),D},getRegex:()=>{return new RegExp(B,Q)}};return D}function Oz1(A){try{A=encodeURI(A).replace(/%25/g,"%")}catch(Q){return null}return A}var cp={exec:()=>null};function Lz1(A,Q){let B=A.replace(/\|/g,(I,C,F)=>{let Y=!1,J=C;while(--J>=0&&F[J]==="\\")Y=!Y;if(Y)return"|";else return" |"}),D=B.split(/ \|/),E=0;if(!D[0].trim())D.shift();if(D.length>0&&!D[D.length-1].trim())D.pop();if(Q)if(D.length>Q)D.splice(Q);else while(D.length<Q)D.push("");for(;E<D.length;E++)D[E]=D[E].trim().replace(/\\\|/g,"|");return D}function s6A(A,Q,B){let D=A.length;if(D===0)return"";let E=0;while(E<D){let I=A.charAt(D-E-1);if(I===Q&&!B)E++;else if(I!==Q&&B)E++;else break}return A.slice(0,D-E)}function r36(A,Q){if(A.indexOf(Q[1])===-1)return-1;let B=0;for(let D=0;D<A.length;D++)if(A[D]==="\\")D++;else if(A[D]===Q[0])B++;else if(A[D]===Q[1]){if(B--,B<0)return D}return-1}function _z1(A,Q,B,D){let E=Q.href,I=Q.title?vF(Q.title):null,C=A[1].replace(/\\([\[\]])/g,"$1");if(A[0].charAt(0)!=="!"){D.state.inLink=!0;let F={type:"link",raw:B,href:E,title:I,text:C,tokens:D.inlineTokens(C)};return D.state.inLink=!1,F}return{type:"image",raw:B,href:E,title:I,text:vF(C)}}function s36(A,Q){let B=A.match(/^(\s+)(?:```)/);if(B===null)return Q;let D=B[1];return Q.split(`
@@ -1589,12 +1589,12 @@ Contact your administrator for more credits, or switch to GitLab Duo Chat (Class
1589
1589
  When you have more credits, refresh.`,[60]:"GitLab Duo is already responding to this chat in another tab or location. Start a new chat, or wait for GitLab Duo to finish before sending a new message."},L7=(A)=>{if(A===null||!(A in Jn))return Jn[1];return Jn[A]};var Gn=(A)=>{try{return JSON.parse(A)}catch{throw Error("Failed to parse checkpoint")}},hvA=()=>{return{errors:[],workflowStatus:"RUNNING",checkpoint:{ts:new Date().toISOString(),channel_values:{status:"Planning"}},workflowGoal:""}},Go1=(A)=>{try{let{latestCheckpoint:Q}=A?.duoWorkflowWorkflows?.nodes?.[0]??{};if(!Q)return x4(hvA());let B=Gn(Q.checkpoint);return x4({...Q,checkpoint:B})}catch(Q){return k6(Error(`Failed to parse latest workflow checkpoint: ${Q instanceof Error?Q.message:String(Q)}`))}},Uo1=(A)=>{return A.workflowStatus};var se6=u.record(u.unknown()),te6=u.object({content:u.string(),additional_kwargs:u.record(u.unknown()),response_metadata:u.record(u.unknown()),type:u.string(),name:u.string(),id:u.string().nullable(),tool_call_id:u.string(),artifact:u.unknown(),status:u.string()}),Xo1=u.object({name:u.string(),args:se6,tool_response:u.union([te6,u.string()]).optional()}),mvA=u.object({message_sub_type:u.string().nullable(),content:u.string(),timestamp:u.string(),status:u.string().nullable(),correlation_id:u.string().nullable(),additional_context:u.unknown()}),ee6=mvA.extend({message_type:u.enum(["user","agent"]),tool_info:u.null()}),AA4=mvA.extend({message_type:u.literal("request"),tool_info:Xo1}),QA4=mvA.extend({message_type:u.literal("tool"),tool_info:u.union([Xo1,u.null()])}),BA4=u.discriminatedUnion("message_type",[ee6,AA4,QA4]);function q3A(A){if(!A.checkpoint)return x4([]);let Q;try{Q=JSON.parse(A.checkpoint)}catch(D){let E=Error(`Failed to parse a workflow checkpoint. Checkpoint: ${A.checkpoint}`,{cause:D});return k6(E)}if(!Q.channel_values?.ui_chat_log||!Array.isArray(Q.channel_values.ui_chat_log))return x4([]);let B=[];for(let D=0;D<Q.channel_values.ui_chat_log.length;D++){let E=Q.channel_values.ui_chat_log[D],I=BA4.safeParse(E);if(!I.success)return k6(Error(`Failed to validate message at index ${D}: ${I.error.message}. Raw message: ${JSON.stringify(E)}`));B.push(I.data)}return x4(B)}function Un(A){if(!A)return;return F3A(A,{schema:pn1})}var O3A=SA(T1(),1);var zo1=SA(BD(),1);function $b(A){return A instanceof Error&&A.name==="AbortError"}class xR extends Error{constructor(A){super(A);this.name="AbortError"}}var uvA=(A)=>!$b(A),DA4=(A,Q)=>{return(Array.isArray(A)?A:[A]).every((D)=>D(Q))},EA4=(A)=>new Promise((Q)=>{setTimeout(Q,A)}),IA4=1,CA4={max:3,backoffBaseMs:1000,backoffExponent:1.5,onRetry:zo1.default.noop,shouldRetry:uvA,signal:new AbortController().signal};async function Zo1(A,Q,B){try{if(Q.signal.aborted)throw new xR;let D=await A(Q.signal);if(Q.signal.aborted)throw new xR;return D}catch(D){if(Q.max<=1)throw D;if(!DA4(Q.shouldRetry,D))throw D;return await EA4(Q.backoffBaseMs),Q.onRetry(B,D),Zo1(A,{...Q,max:Q.max-1,backoffBaseMs:Q.backoffBaseMs*Q.backoffExponent},B+1)}}function Ko1(A,Q={}){let B={...CA4,...Q};return Zo1(A,B,IA4)}function dvA(A,Q=1000,B=2){return Q*B**(A-1)}function cvA(A){return new Promise((Q)=>{setTimeout(Q,A)})}var lvA=O3A.createInterfaceId("UsageQuotaService");function wo1(A){if($1A(A)&&A.body)return A.body.includes("USAGE_QUOTA_EXCEEDED");return!1}class pvA{#A;#Q;#B=!1;constructor(A,Q){this.#A=A,this.#Q=L1(Q,"[UsageQuotaService]"),this.#A.onApiReconfigured(()=>this.#D())}get usageQuotaExceeded(){return this.#B}async checkUsageCreditsExceeded(A,Q,B){if(A.aborted)return this.#B;this.#Q.info(`Running credits check with rootNamespaceId: ${Q??"undefined"}, workflowDefinition: ${B??"undefined"}`);try{let D={};if(Q)D.root_namespace_id=Q;if(B)D.workflow_definition=B;return this.#Q.debug(`Request body: ${JSON.stringify(D)}`),await Ko1(this.#A.fetchOperation({type:"rest",method:"POST",path:"/api/v4/ai/duo_workflows/direct_access",body:D,supportedSinceInstanceVersion:{resourceName:"get workflow direct access",version:"18.1.0"}}),{signal:A,shouldRetry:[uvA,w11,(E)=>!wo1(E)],onRetry:(E,I)=>{this.#Q.warn(`Failed to check usage quota. Retrying (attempt number ${E})`,I)}}),this.#B=!1,!1}catch(D){if(D instanceof xR)return this.#B;if(D instanceof JvA)return this.#Q.error("GitLab instance does not support usage quota checking."),this.#B;if(wo1(D))return this.#Q.warn("Usage quota exceeded for duo workflows"),this.#B=!0,!0;return this.#Q.error("Failed to check usage quota",D),this.#B=!1,!1}}#D(){this.#B=!1}}pvA=Q1([O3A.Injectable(lvA,[f4,q1])],pvA);var TZ=Ho1.createInterfaceId("WorkflowRunner");var Vo1="root/flow";var Nb=SA(T1(),1);var $o1=SA(T1(),1),Wb=$o1.createInterfaceId("ToolProvider");var Wo1=[{name:"read_file",label:"Read File",description:"Read the contents of a file at the given path.",category:"File System",inputSchema:{type:"object",required:["file_path"],properties:{file_path:{type:"string",description:"Absolute or relative path to the file"}}},outputSchema:{type:"object",properties:{content:{type:"string",description:"The file contents"}}}},{name:"read_files",label:"Read Files",description:"Read the contents of multiple files at once.",category:"File System",inputSchema:{type:"object",required:["file_paths"],properties:{file_paths:{type:"array",items:{type:"string"},description:"List of file paths to read"}}},outputSchema:{type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of file path/content pairs"}}}},{name:"create_file_with_contents",label:"Create File",description:"Create a new file with the given contents.",category:"File System",inputSchema:{type:"object",required:["file_path","contents"],properties:{file_path:{type:"string",description:"Path for the new file"},contents:{type:"string",description:"Contents to write to the file"}}},outputSchema:{type:"object",properties:{success:{type:"boolean"}}}},{name:"edit_file",label:"Edit File",description:"Edit an existing file by replacing a specific string.",category:"File System",inputSchema:{type:"object",required:["file_path","old_string","new_string"],properties:{file_path:{type:"string",description:"Path to the file to edit"},old_string:{type:"string",description:"The exact string to find and replace"},new_string:{type:"string",description:"The replacement string"}}},outputSchema:{type:"object",properties:{success:{type:"boolean"}}}},{name:"list_dir",label:"List Directory",description:"List the contents of a directory.",category:"File System",inputSchema:{type:"object",required:["dir_path"],properties:{dir_path:{type:"string",description:"Path to the directory to list"}}},outputSchema:{type:"object",properties:{entries:{type:"array",items:{type:"string"},description:"List of directory entries"}}}},{name:"find_files",label:"Find Files",description:"Find files matching a glob or name pattern.",category:"File System",inputSchema:{type:"object",required:["pattern"],properties:{pattern:{type:"string",description:"Glob pattern to match files against"},dir_path:{type:"string",description:"Directory to search in (defaults to project root)"}}},outputSchema:{type:"object",properties:{files:{type:"array",items:{type:"string"},description:"List of matching file paths"}}}},{name:"mkdir",label:"Create Directory",description:"Create a new directory (including parent directories).",category:"File System",inputSchema:{type:"object",required:["dir_path"],properties:{dir_path:{type:"string",description:"Path of the directory to create"}}},outputSchema:{type:"object",properties:{success:{type:"boolean"}}}},{name:"grep",label:"Grep",description:"Search file contents for a pattern using regular expressions.",category:"File System",inputSchema:{type:"object",required:["pattern"],properties:{pattern:{type:"string",description:"Regular expression pattern to search for"},dir_path:{type:"string",description:"Directory to search in (defaults to project root)"},include:{type:"string",description:"Glob pattern to filter files to search"}}},outputSchema:{type:"object",properties:{matches:{type:"array",items:{type:"object",properties:{file:{type:"string"},line:{type:"integer"},content:{type:"string"}}},description:"List of matching lines with file and line number"}}}}];var No1=[{name:"run_git_command",label:"Run Git Command",description:"Execute a git command in the project repository.",category:"Git",inputSchema:{type:"object",required:["command"],properties:{command:{type:"array",items:{type:"string"},description:'Git command arguments (e.g. ["status", "--short"])'}}},outputSchema:{type:"object",properties:{stdout:{type:"string",description:"Standard output from the command"},stderr:{type:"string",description:"Standard error from the command"},exit_code:{type:"integer",description:"Exit code of the command"}}}}];var Mo1=[{name:"run_tests",label:"Run Tests",description:"Execute the test suite or a specific test file.",category:"Testing",inputSchema:{type:"object",properties:{test_path:{type:"string",description:"Path to a specific test file or directory (runs all tests if omitted)"},test_filter:{type:"string",description:"Filter expression to select specific tests"}}},outputSchema:{type:"object",properties:{stdout:{type:"string",description:"Test output"},stderr:{type:"string",description:"Error output"},exit_code:{type:"integer",description:"Exit code (0 = all tests passed)"}}}}];var qo1=[{name:"get_issue",label:"Get Issue",description:"Retrieve a GitLab issue by its IID.",category:"GitLab::Context",inputSchema:{type:"object",required:["issue_iid"],properties:{issue_iid:{type:"integer",description:"Internal ID of the issue"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{title:{type:"string"},description:{type:"string"},state:{type:"string"},labels:{type:"array",items:{type:"string"}},assignees:{type:"array",items:{type:"string"}}}}},{name:"get_merge_request",label:"Get Merge Request",description:"Retrieve a GitLab merge request by its IID.",category:"GitLab::Context",inputSchema:{type:"object",required:["merge_request_iid"],properties:{merge_request_iid:{type:"integer",description:"Internal ID of the merge request"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{title:{type:"string"},description:{type:"string"},state:{type:"string"},source_branch:{type:"string"},target_branch:{type:"string"}}}},{name:"list_merge_request_diffs",label:"List MR Diffs",description:"List the file diffs in a merge request.",category:"GitLab::Context",inputSchema:{type:"object",required:["merge_request_iid"],properties:{merge_request_iid:{type:"integer",description:"Internal ID of the merge request"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{diffs:{type:"array",items:{type:"object",properties:{old_path:{type:"string"},new_path:{type:"string"},diff:{type:"string"}}}}}}},{name:"get_repository_file",label:"Get Repository File",description:"Get the contents of a file from the GitLab repository.",category:"GitLab::Context",inputSchema:{type:"object",required:["file_path"],properties:{file_path:{type:"string",description:"Path to the file in the repository"},ref:{type:"string",description:"Branch or tag name (defaults to default branch)"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{content:{type:"string",description:"Base64-decoded file content"},file_name:{type:"string"},file_path:{type:"string"},size:{type:"integer"}}}},{name:"list_repository_tree",label:"List Repository Tree",description:"List the files and directories in a repository path.",category:"GitLab::Context",inputSchema:{type:"object",properties:{path:{type:"string",description:"Path inside the repository (defaults to root)"},ref:{type:"string",description:"Branch or tag name (defaults to default branch)"},recursive:{type:"boolean",description:"List files recursively"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{entries:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string",description:"blob (file) or tree (directory)"},path:{type:"string"}}}}}}},{name:"get_job_logs",label:"Get Job Logs",description:"Retrieve the log output of a CI/CD job.",category:"GitLab::Context",inputSchema:{type:"object",required:["job_id"],properties:{job_id:{type:"integer",description:"ID of the CI/CD job"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{log:{type:"string",description:"Job log output"}}}},{name:"get_pipeline_failing_jobs",label:"Get Pipeline Failing Jobs",description:"Get the failing jobs from a CI/CD pipeline.",category:"GitLab::Context",inputSchema:{type:"object",required:["pipeline_id"],properties:{pipeline_id:{type:"integer",description:"ID of the pipeline"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{jobs:{type:"array",items:{type:"object",properties:{id:{type:"integer"},name:{type:"string"},stage:{type:"string"},status:{type:"string"}}}}}}}];var Oo1=[{name:"create_issue_note",label:"Create Issue Note",description:"Add a comment to a GitLab issue.",category:"GitLab::Actions",inputSchema:{type:"object",required:["issue_iid","body"],properties:{issue_iid:{type:"integer",description:"Internal ID of the issue"},body:{type:"string",description:"The note body in Markdown"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{id:{type:"integer",description:"ID of the created note"}}}},{name:"create_merge_request_note",label:"Create MR Note",description:"Add a comment to a GitLab merge request.",category:"GitLab::Actions",inputSchema:{type:"object",required:["merge_request_iid","body"],properties:{merge_request_iid:{type:"integer",description:"Internal ID of the merge request"},body:{type:"string",description:"The note body in Markdown"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{id:{type:"integer",description:"ID of the created note"}}}},{name:"create_commit",label:"Create Commit",description:"Create a commit with file changes on a branch.",category:"GitLab::Actions",inputSchema:{type:"object",required:["branch","commit_message","actions"],properties:{branch:{type:"string",description:"Branch to commit to"},commit_message:{type:"string",description:"Commit message"},actions:{type:"array",items:{type:"object",properties:{action:{type:"string",description:"File action (create, delete, move, update)"},file_path:{type:"string",description:"Path to the file"},content:{type:"string",description:"File content (for create/update)"}}},description:"List of file actions to include in the commit"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{id:{type:"string",description:"The commit SHA"},short_id:{type:"string"},title:{type:"string"}}}},{name:"create_branch",label:"Create Branch",description:"Create a new branch from a given ref.",category:"GitLab::Actions",inputSchema:{type:"object",required:["branch","ref"],properties:{branch:{type:"string",description:"Name of the new branch"},ref:{type:"string",description:"Branch or SHA to create from"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the created branch"},commit:{type:"object",properties:{id:{type:"string"},short_id:{type:"string"}}}}}}];var Lo1=[{name:"gitlab_blob_search",label:"Blob Search",description:"Search code blobs across the GitLab project.",category:"GitLab::Search",inputSchema:{type:"object",required:["search"],properties:{search:{type:"string",description:"Search query string"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{basename:{type:"string"},data:{type:"string"},path:{type:"string"},filename:{type:"string"},ref:{type:"string"}}}}}}},{name:"gitlab_issue_search",label:"Issue Search",description:"Search for issues in the GitLab project.",category:"GitLab::Search",inputSchema:{type:"object",required:["search"],properties:{search:{type:"string",description:"Search query string"},state:{type:"string",description:"Filter by state: opened, closed, or all"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{iid:{type:"integer"},title:{type:"string"},state:{type:"string"},web_url:{type:"string"}}}}}}},{name:"gitlab_merge_request_search",label:"Merge Request Search",description:"Search for merge requests in the GitLab project.",category:"GitLab::Search",inputSchema:{type:"object",required:["search"],properties:{search:{type:"string",description:"Search query string"},state:{type:"string",description:"Filter by state: opened, closed, merged, or all"},project_id:{type:"string",description:"Project path (defaults to current project)"}}},outputSchema:{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{iid:{type:"integer"},title:{type:"string"},state:{type:"string"},web_url:{type:"string"}}}}}}},{name:"gitlab_documentation_search",label:"Documentation Search",description:"Search GitLab documentation.",category:"GitLab::Search",inputSchema:{type:"object",required:["query"],properties:{query:{type:"string",description:"Documentation search query"}}},outputSchema:{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{title:{type:"string"},url:{type:"string"},content:{type:"string"}}}}}}}];var ivA=[...Wo1,...No1,...Mo1,...qo1,...Oo1,...Lo1];class L3A{get(A){return ivA.find((Q)=>Q.name===A)}getAll(){return ivA}}L3A=Q1([Nb.Service({dependencies:[],lifetime:Nb.ServiceLifetime.Singleton}),Nb.Implements(Wb)],L3A);var Mb=SA(T1(),1);var _o1=SA(T1(),1),Xn=_o1.createInterfaceId("NodeTypeDefinitionProvider");var Ro1={type:"object",properties:{final_answer:{type:"string",description:"The agent's final response after completing its task"},conversation_history:{type:"array",items:{type:"object",description:"LangChain BaseMessage objects containing the conversation"},description:"Complete conversation history for this agent component"},status:{type:"string",enum:["in_progress","completed","failed"],description:"Current workflow execution status"}},required:["final_answer","status"]},To1={type:"object",properties:{tool_calls:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},args:{type:"object"}}},description:"Record of all tool calls made during execution"},tool_responses:{type:"array",items:{type:"object",properties:{tool_call_id:{type:"string"},content:{type:"string"},status:{type:"string",enum:["success","error"]}}},description:"Responses from all executed tools"},execution_result:{type:"string",enum:["success","failed"],description:"Overall execution result - success if all tools executed, failed otherwise"},conversation_history:{type:"array",items:{type:"object"},description:"Message history for this component (includes tool calls and responses)"}},required:["execution_result"]},jo1={type:"object",properties:{goal:{type:"string",description:"Task description for the one-off AI operation"}},required:["goal"]},Po1={type:"object",properties:{tool_responses:{type:"string",description:"The output from the tool execution (typically a string)"},error:{type:"string",description:"Error message if the tool execution failed"},execution_result:{type:"string",enum:["success","failed"],description:"Execution status - success or failed"}},required:["execution_result"]},So1={type:"object",description:"Input schema varies by tool type and is derived from tool definition",additionalProperties:!0};var yo1={type:"agent",description:"AI agent that can reason and use tools",label:"Agent",ui:{color:"#3b82f6",icon:"\uD83E\uDD16"},outputSchema:Ro1,inputSchema:void 0};var vo1={type:"tool",label:"Tool",description:"Execute a specific tool deterministically",ui:{color:"#6366f1",icon:"⚙️"},inputSchema:So1,outputSchema:Po1};var ko1={type:"ai-task",label:"AI Task",description:"Single round AI operation with tool execution",ui:{color:"#8b5cf6",icon:"⚡"},inputSchema:jo1,outputSchema:To1};var go1=[yo1,vo1,ko1];class _3A{getNodeTypeDefinitions(){return go1}}_3A=Q1([Mb.Service({dependencies:[],lifetime:Mb.ServiceLifetime.Singleton}),Mb.Implements(Xn)],_3A);class R3A{#A;#Q;#B;#D;#E;#I;#C=new Map;constructor(A,Q,B,D,E,I){this.#A=L1(A,"[FlowWebviewService]"),this.#Q=Q,this.#B=B,this.#D=D,this.#E=E,this.#I=I,this.#F().catch((C)=>{this.#A.error("Failed to initialize FlowWebviewService",C)})}async#F(){let A=await this.#Q.initialize();if(A.isErr())throw this.#A.error("Failed to initialize flow store",A.error),Error(A.error.type==="invalid_format"?A.error.message:"Failed to initialize flow store");this.#Y()}#Y(){this.#E.getConnection(Vo1).onInstanceConnected((Q,B)=>{this.#A.debug(`Flow Builder instance connected: ${Q}`),B.onNotification("appReady",async()=>{this.#A.debug("Flow Builder app ready");let D=this.#B.getNodeTypeDefinitions(),E=this.#D.getAll();B.sendNotification("initialState",{nodeTypeDefinitions:D,toolDefinitions:E})}),B.onRequest("saveFlow",async({uri:D,flow:E})=>{return this.#A.debug("Save flow requested"),(await this.#Q.saveFlow(E,D)).match(()=>{return B.sendNotification("flowSaved",{timestamp:new Date}),{success:!0}},(C)=>{return this.#A.error("Failed to save flow",C),{success:!1,error:C.type==="validation_error"?C.message:"Failed to save flow",details:C.type==="validation_error"?C.details:void 0}})}),B.onRequest("loadFlow",async({uri:D})=>{return(await this.#Q.loadFlow(D)).match((I)=>I,(I)=>{if(I.type==="not_found")return null;return this.#A.error("Failed to load flow",I),null})}),B.onRequest("getNodeTypeDefinitions",async()=>{return this.#B.getNodeTypeDefinitions()}),B.onRequest("getToolDefinitions",async()=>{return this.#D.getAll()}),B.onRequest("getExecutionContext",async()=>{return{projectPath:this.#I.getProjectPath(),namespacePath:this.#I.getNamespacePath(),isReady:Boolean(this.#I.getProjectPath())}}),B.onRequest("executeFlow",async({uri:D,context:E})=>{let I=E.goal?.substring(0,50)||"(no goal)",C=Object.keys(E).join(", ");this.#A.info(`Execute flow requested: ${D} with context keys: [${C}], goal: ${I}...`);try{let F=await this.#Q.loadFlowYaml(D);if(F.isErr())return this.#A.error("Failed to load flow YAML",F.error),{success:!1,error:F.error.type==="not_found"?"Flow file not found. Please save the flow first.":`Failed to load flow: ${F.error.message}`};let Y=F.value;this.#A.debug(`Flow config YAML (first 2000 chars):
1590
1590
  ${Y.substring(0,2000)}`);let J=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.#C.set(J,{workflowId:"",context:E,aborted:!1}),B.sendNotification("executionStarted",{executionId:J,context:E}),this.#J(J,Y,E,B),{success:!0,executionId:J}}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 E=this.#C.get(D);if(!E)return{success:!1};if(E.aborted=!0,E.workflowId)this.#I.stopWorkflow(E.workflowId);return this.#C.delete(D),{success:!0}})})}async#J(A,Q,B,D){let E=this.#C.get(A);if(!E){this.#A.warn(`Execution ${A} not found when starting`);return}let I,C="completed";try{this.#A.debug(`Starting workflow with flowConfigSchemaVersion: ${Fn}`);let F=this.#I.runWorkflow({goal:B.goal||"",flowConfig:Q,flowConfigSchemaVersion:Fn,metadata:{projectId:this.#I.getProjectPath(),namespaceId:this.#I.getNamespacePath()},additionalContext:[]}),Y=0;for await(let J of F){if(Y+=1,this.#A.debug(`Received workflow event #${Y}: ${JSON.stringify(J)}`),E.aborted){this.#A.info(`Execution ${A} was aborted`),C="stopped";break}if(rH(J)){this.#A.error(`Workflow error: ${J.message}`),C="failed",D.sendNotification("executionCompleted",{executionId:A,status:"failed",error:J.message}),this.#C.delete(A);return}let G={checkpoint:J.checkpoint,errors:J.errors,workflowGoal:J.workflowGoal,workflowStatus:J.workflowStatus};if(I=J.checkpoint,D.sendNotification("executionUpdate",{executionId:A,event:G}),J.workflowStatus==="FINISHED"){C="completed";break}else if(J.workflowStatus==="FAILED"||J.workflowStatus==="STOPPED"){C=J.workflowStatus==="FAILED"?"failed":"stopped";break}}this.#A.debug(`Workflow generator finished. Total events: ${Y}, finalStatus: ${C}, lastCheckpoint: ${I}`),D.sendNotification("executionCompleted",{executionId:A,status:C,finalCheckpoint:I})}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.#C.delete(A)}}}R3A=Q1([T3A.Service({lifetime:T3A.ServiceLifetime.Singleton,dependencies:[q1,Cn,Xn,Wb,Kb,TZ],autoActivate:!0})],R3A);var sEA=SA(T1(),1);var FA4=5000;class sH{#A;#Q;#B;#D;#E=!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=L1(A.getRequiredService(q1),"[CliExitHandler]"),this.#D=A.getRequiredService(hw)}async exit(A,Q){if(this.#E)return new Promise(()=>{});if(this.#E=!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)},FA4);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 j3A=SA(ay(),1),P3A=SA(T1(),1);import YA4 from"node:process";var JA4="https://registry.npmjs.org/@gitlab%2Fduo-cli/latest",GA4=5000,avA=P3A.createInterfaceId("UpdateChecker");class zn{#A;#Q;constructor(A,Q){this.#A=A,this.#Q=L1(Q,"[CliUpdateChecker]")}async checkForUpdate(A){try{let Q=new AbortController,B=setTimeout(()=>Q.abort(),GA4),D=await this.#A.get(JA4,{signal:Q.signal});if(clearTimeout(B),!D.ok){let C=`Registry returned non-OK status: ${D.status}`;return Error(C)}let I=(await D.json()).version;if(!I||!j3A.default.valid(I)||!j3A.default.valid(A))return Error(`Invalid version format: latest=${I}, current=${A}`);if(!j3A.default.gt(I,A))return Error(`Already up to date (latest: ${I})`);return this.#Q.debug(`Update available: ${A} → ${I}`),{currentVersion:A,latestVersion:I,installCommand:this.#B()}}catch(Q){return Error("Update check failed",{cause:Q})}}#B(){let A=YA4.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"}}zn=Q1([P3A.Injectable(avA,[O7,q1])],zn);var bo1;(()=>{var A={975:(x)=>{function n(p){if(typeof p!="string")throw TypeError("Path must be a string. Received "+JSON.stringify(p))}function c(p,QA){for(var DA,_A="",wA=0,WA=-1,KA=0,AA=0;AA<=p.length;++AA){if(AA<p.length)DA=p.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+="/"+p.slice(WA+1,AA):_A=p.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 p,QA="",DA=!1,_A=arguments.length-1;_A>=-1&&!DA;_A--){var wA;_A>=0?wA=arguments[_A]:(p===void 0&&(p=process.cwd()),wA=p),n(wA),wA.length!==0&&(QA=wA+"/"+QA,DA=wA.charCodeAt(0)===47)}return QA=c(QA,!DA),DA?QA.length>0?"/"+QA:"/":QA.length>0?QA:"."},normalize:function(p){if(n(p),p.length===0)return".";var QA=p.charCodeAt(0)===47,DA=p.charCodeAt(p.length-1)===47;return(p=c(p,!QA)).length!==0||QA||(p="."),p.length>0&&DA&&(p+="/"),QA?"/"+p:p},isAbsolute:function(p){return n(p),p.length>0&&p.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var p,QA=0;QA<arguments.length;++QA){var DA=arguments[QA];n(DA),DA.length>0&&(p===void 0?p=DA:p+="/"+DA)}return p===void 0?".":b.normalize(p)},relative:function(p,QA){if(n(p),n(QA),p===QA)return"";if((p=b.resolve(p))===(QA=b.resolve(QA)))return"";for(var DA=1;DA<p.length&&p.charCodeAt(DA)===47;++DA);for(var _A=p.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&&(p.charCodeAt(DA+NA)===47?t=NA:NA===0&&(t=0));break}var bA=p.charCodeAt(DA+NA);if(bA!==QA.charCodeAt(WA+NA))break;bA===47&&(t=NA)}var aA="";for(NA=DA+t+1;NA<=_A;++NA)NA!==_A&&p.charCodeAt(NA)!==47||(aA.length===0?aA+="..":aA+="/..");return aA.length>0?aA+QA.slice(WA+t):(WA+=t,QA.charCodeAt(WA)===47&&++WA,QA.slice(WA))},_makeLong:function(p){return p},dirname:function(p){if(n(p),p.length===0)return".";for(var QA=p.charCodeAt(0),DA=QA===47,_A=-1,wA=!0,WA=p.length-1;WA>=1;--WA)if((QA=p.charCodeAt(WA))===47){if(!wA){_A=WA;break}}else wA=!1;return _A===-1?DA?"/":".":DA&&_A===1?"//":p.slice(0,_A)},basename:function(p,QA){if(QA!==void 0&&typeof QA!="string")throw TypeError('"ext" argument must be a string');n(p);var DA,_A=0,wA=-1,WA=!0;if(QA!==void 0&&QA.length>0&&QA.length<=p.length){if(QA.length===p.length&&QA===p)return"";var KA=QA.length-1,AA=-1;for(DA=p.length-1;DA>=0;--DA){var t=p.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=p.length),p.slice(_A,wA)}for(DA=p.length-1;DA>=0;--DA)if(p.charCodeAt(DA)===47){if(!WA){_A=DA+1;break}}else wA===-1&&(WA=!1,wA=DA+1);return wA===-1?"":p.slice(_A,wA)},extname:function(p){n(p);for(var QA=-1,DA=0,_A=-1,wA=!0,WA=0,KA=p.length-1;KA>=0;--KA){var AA=p.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?"":p.slice(QA,_A)},format:function(p){if(p===null||typeof p!="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof p);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,p)},parse:function(p){n(p);var QA={root:"",dir:"",base:"",ext:"",name:""};if(p.length===0)return QA;var DA,_A=p.charCodeAt(0),wA=_A===47;wA?(QA.root="/",DA=1):DA=0;for(var WA=-1,KA=0,AA=-1,t=!0,NA=p.length-1,bA=0;NA>=DA;--NA)if((_A=p.charCodeAt(NA))!==47)AA===-1&&(t=!1,AA=NA+1),_A===46?WA===-1?WA=NA:bA!==1&&(bA=1):WA!==-1&&(bA=-1);else if(!t){KA=NA+1;break}return WA===-1||AA===-1||bA===0||bA===1&&WA===AA-1&&WA===KA+1?AA!==-1&&(QA.base=QA.name=KA===0&&wA?p.slice(1,AA):p.slice(KA,AA)):(KA===0&&wA?(QA.name=p.slice(1,WA),QA.base=p.slice(1,AA)):(QA.name=p.slice(KA,WA),QA.base=p.slice(KA,AA)),QA.ext=p.slice(WA,AA)),KA>0?QA.dir=p.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 c=Q[x]={exports:{}};return A[x](c,c.exports,B),c.exports}B.d=(x,n)=>{for(var c in n)B.o(n,c)&&!B.o(x,c)&&Object.defineProperty(x,c,{enumerable:!0,get:n[c]})},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 E;if(B.r(D),B.d(D,{URI:()=>z,Utils:()=>r}),typeof process=="object")E=process.platform==="win32";else if(typeof navigator=="object")E=navigator.userAgent.indexOf("Windows")>=0;let I=/^\w[\w\d+.-]*$/,C=/^\//,F=/^\/\//;function Y(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&&!I.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 J="",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,c,b,p,QA=!1){typeof x=="object"?(this.scheme=x.scheme||J,this.authority=x.authority||J,this.path=x.path||J,this.query=x.query||J,this.fragment=x.fragment||J):(this.scheme=function(DA,_A){return DA||_A?DA:"file"}(x,QA),this.authority=n||J,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,c||J),this.query=b||J,this.fragment=p||J,Y(this,QA))}get fsPath(){return q(this,!1)}with(x){if(!x)return this;let{scheme:n,authority:c,path:b,query:p,fragment:QA}=x;return n===void 0?n=this.scheme:n===null&&(n=J),c===void 0?c=this.authority:c===null&&(c=J),b===void 0?b=this.path:b===null&&(b=J),p===void 0?p=this.query:p===null&&(p=J),QA===void 0?QA=this.fragment:QA===null&&(QA=J),n===this.scheme&&c===this.authority&&b===this.path&&p===this.query&&QA===this.fragment?this:new Z(n,c,b,p,QA)}static parse(x,n=!1){let c=X.exec(x);return c?new Z(c[2]||J,y(c[4]||J),y(c[5]||J),y(c[7]||J),y(c[9]||J),n):new Z(J,J,J,J,J)}static file(x){let n=J;if(E&&(x=x.replace(/\\/g,G)),x[0]===G&&x[1]===G){let c=x.indexOf(G,2);c===-1?(n=x.substring(2),x=G):(n=x.substring(2,c),x=x.substring(c)||G)}return new Z("file",n,x,J,J)}static from(x){let n=new Z(x.scheme,x.authority,x.path,x.query,x.fragment);return Y(n,!0),n}toString(x=!1){return M(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=E?1:void 0;class Z extends z{_formatted=null;_fsPath=null;get fsPath(){return this._fsPath||(this._fsPath=q(this,!1)),this._fsPath}toString(x=!1){return x?M(this,!0):(this._formatted||(this._formatted=M(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,c){let b,p=-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||c&&DA===91||c&&DA===93||c&&DA===58)p!==-1&&(b+=encodeURIComponent(x.substring(p,QA)),p=-1),b!==void 0&&(b+=x.charAt(QA));else{b===void 0&&(b=x.substr(0,QA));let _A=K[DA];_A!==void 0?(p!==-1&&(b+=encodeURIComponent(x.substring(p,QA)),p=-1),b+=_A):p===-1&&(p=QA)}}return p!==-1&&(b+=encodeURIComponent(x.substring(p))),b!==void 0?b:x}function W(x){let n;for(let c=0;c<x.length;c++){let b=x.charCodeAt(c);b===35||b===63?(n===void 0&&(n=x.substr(0,c)),n+=K[b]):n!==void 0&&(n+=x[c])}return n!==void 0?n:x}function q(x,n){let c;return c=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,E&&(c=c.replace(/\//g,"\\")),c}function M(x,n){let c=n?W:H,b="",{scheme:p,authority:QA,path:DA,query:_A,fragment:wA}=x;if(p&&(b+=p,b+=":"),(QA||p==="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+=c(KA,!1,!1):(b+=c(KA.substr(0,WA),!1,!1),b+=":",b+=c(KA.substr(WA+1),!1,!0)),b+="@"}QA=QA.toLowerCase(),WA=QA.lastIndexOf(":"),WA===-1?b+=c(QA,!1,!0):(b+=c(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+=c(DA,!0,!1)}return _A&&(b+="?",b+=c(_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,...c){return n.with({path:h.join(n.path,...c)})},x.resolvePath=function(n,...c){let b=n.path,p=!1;b[0]!==S&&(b=S+b,p=!0);let QA=h.resolve(b,...c);return p&&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 c=h.dirname(n.path);return c.length===1&&c.charCodeAt(0)===46&&(c=""),n.with({path:c})},x.basename=function(n){return h.basename(n.path)},x.extname=function(n){return h.extname(n.path)}})(r||(r={})),bo1=D})();var{URI:JI,Utils:St8}=bo1;var aEA=SA(T1(),1);var S3A=ID.enum(["file","snippet","terminal","issue","merge_request","dependency","local_git","user_rule","repository","directory","agent_user_environment","os_information"]);var fo1=SA(T1(),1),xo1=ID.enum(["open_tab","import","local_file_search","issue","merge_request","snippet","dependency","local_git","user_rule","repository","directory","shell","os"]),y3A=fo1.createInterfaceId("AIContextProvider");class nvA{#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 ho1=ID.object({title:ID.string(),enabled:ID.boolean(),disabledReasons:ID.array(ID.string()).optional(),subType:xo1,icon:ID.string(),secondaryText:ID.string(),subTypeLabel:ID.string(),languageId:ID.string().optional()}),UA4=ID.object({id:ID.string(),category:S3A,content:ID.string().optional(),metadata:ho1.optional()}),mt8=UA4.extend({metadata:ho1});var rvA=SA(T1(),1);var pt8=rvA.createInterfaceId("DuoChatContextManager"),mo1=rvA.createInterfaceId("AgenticChatContextManager"),ovA={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 svA{#A=[];#Q;#B;#D;#E;constructor(A,Q,B,D,E){this.#E=L1(A,"ChatContextManager"),this.#Q=B,this.#A=D,this.#B=E,this.#D=Q.get("workspaceFolders")??[],Q.onConfigChange((I)=>{this.#D=I.workspaceFolders??[]})}async#I(){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"),E=(await this.#I()).find((I)=>I.type===A);if(!E)throw B;await Q(E)}async#F(A){let B=(await this.#I()).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.#E.info(`received context item add request ${A.id}`),await this.#C(A.metadata?.subType,async(Q)=>{await Q.addSelectedContextItem(A)}),this.#E.info("added item result true"),!0}catch(Q){return this.#E.error("error adding context item",Q),!1}}async removeSelectedContextItem(A){this.#E.info(`received context item remove request ${A.id}`);try{return await this.#C(A.metadata?.subType,async(Q)=>{await Q.removeSelectedContextItem(A.id)}),this.#E.info("removed item result true"),!0}catch(Q){return this.#E.error("error removing context item",Q),!1}}async getSelectedContextItems(){let A=await this.#I(),Q=(await Promise.all(A.map((B)=>B.getSelectedContextItems()))).flat();return this.#E.info(`returning ${Q.length} current context items`),Q}async searchContextItems(A){this.#E.info(`received context search query, category: ${A.category}, query: ${A.query}`);try{let Q=[],B=ovA[A.category],D=A.workspaceFolders??this.#D;if(!D.length)this.#E.debug("No workspace folders detected.");let E={...A,workspaceFolders:D},C=(await this.#I()).filter((X)=>B.includes(X.type)).map(async(X)=>{return X.searchContextItems(E)});(await Promise.all(C)).forEach((X)=>Q.push(...X));let Y=new Set((await this.getSelectedContextItems()).map((X)=>X?.id).filter((X)=>X!==void 0)),J=Q.filter((X)=>!Y.has(X.id)),G=this.#Y(J);return this.#E.info(`context search query had ${G.length} results`),G}catch(Q){return this.#E.error("error searching context items",Q),[]}}#Y(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.#I()).map((E)=>E.type),B=Object.keys(ovA),D=Q.map((E)=>B.find((I)=>ovA[I].includes(E))).filter((E)=>E!==void 0);return this.#E.info(`returning ${D.length} available context provider categories: "${D.join(", ")}"`),D}async retrieveContextItemsWithContent(A){let Q=await this.#I(),D=(await Promise.all(Q.map(async(E)=>{try{return await E.retrieveContextItemsWithContent(A)}catch(I){return this.#E.error(`Error retrieving context items from provider type: ${E.type}`,I),[]}}))).flat().filter(Boolean);return Promise.all(D.map((E)=>this.#J(E)))}async clearSelectedContextItems(){return this.#E.info("clearing all selected context items"),(await this.#I()).forEach((Q)=>Q.clearSelectedContextItems()),!0}async getItemWithContent(A){this.#E.info(`received get context item content request ${A.id}`);let B=await(await this.#F(A)).getItemWithContent(A);return this.#E.info(`retrieved context item content ${B}`),this.#J(B)}async#J(A){try{return await this.#Q.transform(A)}catch(Q){return this.#E.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 uo1=SA(T1(),1),qb=uo1.createInterfaceId("AiContextTransformer");var oo1=SA(T1(),1);var do1=SA(T1(),1);var co1=1;class tH extends Error{name="FileNotFoundError";cause;constructor(A,Q){super(`File not found: ${A}`);this.cause=Q}}var _7=do1.createInterfaceId("FileAccessService");var po1=SA(T1(),1),OJ=po1.createInterfaceId("FsClient");var lo1=SA(T1(),1);var eH=async()=>{throw Error("Not implemented")};class Zn{promises={readFile:eH,writeFile:eH,unlink:eH,readdir:eH,mkdir:eH,rmdir:eH,stat:eH,lstat:eH,readFileFirstBytes:eH}}Zn=Q1([lo1.Injectable(OJ,[])],Zn);var io1=8192;async function Ob(A,Q){let{stat:B,readFileFirstBytes:D}=Q.promises;await B(A.fsPath);try{let E=await D(A.fsPath,io1);return tvA(E)}catch{return!0}}function tvA(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,io1);return Q.test(D)||B.test(D)}import{posix as XA4,relative as zA4}from"path";var hR=(A)=>{return JI.file(A)};var UM=(A)=>{return JI.parse(A)},ZA4=()=>{return process?.platform??"browser"};function KA4(A){return A.replace(/[\\/]/g,"/")}function wA4(A,Q){return A.scheme==="file"?!Q:!0}function ao1(A,Q){let B=ZA4();if(A.scheme==="file"){let I=zA4(A.fsPath,Q.fsPath);return B==="win32"?KA4(I):I}let D=A.path||"/",E=Q.path||"/";if(wA4(A,B==="linux")){let I=0;for(let C=Math.min(D.length,E.length);I<C;I++)if(D.charCodeAt(I)!==E.charCodeAt(I)){if(D.charAt(I).toLowerCase()!==E.charAt(I).toLowerCase())break}D=E.substr(0,I)+D.substr(I)}return XA4.relative(D,E)}var no1=(A,Q)=>Q.filter((B)=>A.startsWith(B.uri));var AkA="Binary files are unsupported";class evA{#A;constructor(A){this.#A=L1(A,"[BinaryFileTransformer]")}async transform(A){if(!A.content)return A;if(tvA(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||[],AkA]}};return A}}evA=Q1([oo1.Injectable(qb,[q1])],evA);var ro1=SA(T1(),1);class QkA{#A;#Q;constructor(A,Q){this.#Q=Q,this.#A=L1(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}}}QkA=Q1([ro1.Injectable(qb,[q1,CE])],QkA);var Lb=SA(T1(),1);var BkA=Lb.createInterfaceId("AiContextTransformerService");class Kn{#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}}Kn=Q1([Lb.Injectable(BkA,[Lb.collection(qb)])],Kn);var LJ=SA(T1(),1);var so1=SA(T1(),1),_b=so1.createInterfaceId("DuoFeatureAccessService");var to1=SA(T1(),1),hF=to1.createInterfaceId("SystemContextProvider");var AV=LJ.createInterfaceId("SystemContextManager"),de8=LJ.createCollectionId(hF);class wn{#A=[];#Q;#B;constructor(A,Q,B){this.#B=L1(A,"[SystemContextManager]"),this.#A=Q,this.#Q=B}async#D(){let A=this.#A.map(async(B)=>{return await this.#E(B)?B:null});return(await Promise.all(A)).filter(Boolean)}async#E(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(E)=>{try{return await E.getItems()}catch(I){return this.#B.error("Error getting items from system context provider",I),[]}}),D=(await Promise.all(Q)).flat();return this.#B.info(`Retrieved ${D.length} system context items`),D}}wn=Q1([LJ.Service({dependencies:[q1,LJ.collection(hF),_b],lifetime:LJ.ServiceLifetime.Scoped}),LJ.Implements(AV)],wn);var re8=u.object({category:S3A,query:u.string(),workspaceFolders:u.array(u.object({uri:u.string(),name:u.string()})).optional()});var DkA=SA(T1(),1),EA2=DkA.createInterfaceId("RepositoryService"),M2=DkA.createInterfaceId("RepositoryDiscoveryService");var eo1=SA(T1(),1),Ar1=eo1.createInterfaceId("GitLsFiles");function Qr1(A){return A instanceof Error&&"code"in A&&A.code==="InternalError"&&A.message.includes("Unsupported dircache version: ")}var Br1=SA(T1(),1),Dr1=Br1.createInterfaceId("GitConfigCommand");var HA4=(A)=>{let{pathname:Q}=p0A(A)||{};return Q?Q.replace(/\/$/,""):""},VA4=(A)=>A.replace(/[-[\]/{}()*+?.\\^$|]/g,"\\$&");function Er1(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 E=A.match("([a-zA-Z0-9_-]+@.*?):(.*)");if(E)return`ssh://${E[1]}/${E[2]}`;if(A.match("^[a-zA-Z0-9_-]+@"))return`ssh://${A}`;return A}async function Ir1(A,Q){try{let B=await A.listRemotes(),D=B.find((E)=>E.remote==="origin")??B[0];if(!D?.url)return;return $A4(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 $A4(A,Q){let{hostname:B,host:D,pathname:E}=p0A(Er1(A))||{};if(!D||!E)return;if(B!==p0A(Er1(Q))?.hostname)return;let C=Q||Q.trim()!==""?VA4(HA4(Q)):"",F=E.match(`(?:${C})?/:?(.+)/([^/]+?)(?:.git)?/?$`);if(!F)return;let[Y,J]=F.slice(1,3);if(!Y||!J)return;let G=`${Y}/${J}`;return{host:D,namespace:Y,projectPath:J,namespaceWithPath:G}}var WA4=["node_modules","dist",".bundle",".idea",".vscode","__pycache__",".mypy_cache",".pytest_cache",".tox",".venv"],Cr1=WA4;var o3A=SA(T1(),1);var Fr1=SA(T1(),1);var Yr1=Fr1.createInterfaceId("DuoChatSnowplowTracker");var Jr1=SA(T1(),1);var Rb=Jr1.createInterfaceId("DuoWorkflowTracker");var Gr1=SA(T1(),1);var Ur1=Gr1.createInterfaceId("DuoAgentPlatformTracker");var Xr1=SA(T1(),1),zr1="gitlab_extension_activity";var v3A=Xr1.createInterfaceId("ExtensionActivitySnowplowTracker");var Zr1="https://gitlab.com";var EkA="https://snowplowprd.trx.gitlab.net",IkA={appId:"gitlab_ide_extension",timeInterval:5000,maxItems:10},CkA="Telemetry event context is not valid - event won't be tracked.";var p3A=SA(Xs1(),1);var SZ=SA(Ct1(),1),sA2=SZ.default.v1,tA2=SZ.default.v3,Ft1=SZ.default.v4,eA2=SZ.default.v5,A12=SZ.default.NIL,Q12=SZ.default.version,B12=SZ.default.validate,D12=SZ.default.stringify,E12=SZ.default.parse;var qt1=SA(Mt1(),1),l3A=SA(T1(),1),Ot1=SA(BD(),1);class c3A{#A=[];#Q;#B;#D;#E;#I;constructor(A,Q,B){this.#D=Q,this.#B=A,this.#Q=B,this.#E="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.#I=setTimeout(async()=>{if(await this.#C(),this.#E!=="STOPPING")this.start()},this.#B),this.#E="STARTED"}async stop(){if(this.#E="STOPPING",this.#I)clearTimeout(this.#I);this.#I=void 0,await this.#C()}}var ykA={};fY(ykA,{self:()=>Q64,id:()=>D64,description:()=>eQ4,default:()=>E64,allOf:()=>A64,$schema:()=>B64});var eQ4="Meta-schema for self-describing JSON schema",A64=[{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#"}],Q64={vendor:"com.snowplowanalytics.self-desc",name:"schema",format:"jsonschema",version:"1-0-0"},B64="http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",D64="http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",E64={description:eQ4,allOf:A64,self:Q64,$schema:B64,id:D64};function I64(A){let Q={};return Object.keys(A).forEach((B)=>{Q[B]=String(A[B])}),Q.stm=new Date().getTime().toString(),Q}var i3A=l3A.createInterfaceId("SnowplowService");class kb{#A=!1;#Q;#B;#D;#E=new qt1.default({strict:!1});#I;#C;constructor(A,Q,B){this.#B=A,this.#D=B,this.#E.addMetaSchema(ykA),Q.onConfigChange(async(D)=>{let E=D.telemetry?.trackingUrl;if(E)await this.#Y({endpoint:E})}),this.#F({...IkA,endpoint:Q.get("telemetry.trackingUrl")??EkA,enabled:()=>Q.get("telemetry.enabled")??!0})}#F(A){this.#I=A,this.#Q=new c3A(this.#I.timeInterval,this.#I.maxItems,this.#J.bind(this)),this.#Q.start(),this.#C=p3A.trackerCore({callback:this.#Q.add.bind(this.#Q)})}async#Y(A){let Q={...this.#I,...A};if(!Ot1.isEqual(this.#I,Q))await this.#Q?.stop(),this.#F(Q)}async trackStructuredEvent(A,Q){try{this.#C.track(p3A.buildStructEvent(A),Q)}catch(B){this.#D.warn("Failed to track Snowplow event",B)}}validateContext(A,Q){let B=this.#E.validate(A,Q);if(!B)this.#D.warn(CkA),this.#D.debug(`AJV validation issue:
1591
1591
  Data: ${JSON.stringify(Q,null,2)}
1592
- Errors: ${JSON.stringify(this.#E.errors,null,2)}`);return B}async stop(){await this.#Q.stop()}async#J(A){if(!this.#I.enabled()||this.#A)return;try{let Q=`${this.#I.endpoint}/com.snowplowanalytics.snowplow/tp2`,B={schema:"iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4",data:A.map((I)=>{let C=Ft1();return I.add("eid",C),I.add("p","app"),I.add("tv","js-gitlab"),I.add("tna","gl"),I.add("aid",this.#I.appId),I64(I.build())})},D={headers:{"Content-Type":"application/json"},body:JSON.stringify(B)},E=await this.#B.post(Q,D);if(E.status!==200)this.#D.warn(`Could not send telemetry to snowplow, this warning can be safely ignored. status=${E.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=Q1([l3A.Injectable(i3A,[O7,w4,q1])],kb);var a3A=SA(T1(),1);var uR={GITLAB_COM:"production",GITLAB_STAGING:"staging",GITLAB_ORG:"org",GITLAB_DEVELOPMENT:"development",GITLAB_SELF_MANAGED:"self-managed"},vkA={GITLAB_COM:"https://gitlab.com",GITLAB_STAGING:"https://staging.gitlab.com",GITLAB_ORG:"https://dev.gitlab.org",GITLAB_DEVELOPMENT:"http://localhost"},_t1="iglu:com.gitlab/gitlab_standard/jsonschema/1-1-1",Lt1="Language Server",n3A=a3A.createInterfaceId("StandardContext");class gb{#A=Lt1;#Q=uR.GITLAB_COM;#B=vkA.GITLAB_COM;constructor(A){this.#D(A.get()),A.onConfigChange((Q)=>this.#D(Q))}#D(A){this.#A=A?.telemetry?.extension?.name??Lt1,this.#B=A?.baseUrl??Zr1,this.#Q=Rt1(this.#B)}build(A){return{schema:_t1,data:{source:this.#A,extra:A,environment:this.#Q,host_name:this.#B}}}}gb=Q1([a3A.Injectable(n3A,[w4])],gb);function Rt1(A){let{GITLAB_COM:Q,GITLAB_STAGING:B,GITLAB_ORG:D,GITLAB_DEVELOPMENT:E}=vkA;if(A===Q)return uR.GITLAB_COM;if(A===B)return uR.GITLAB_STAGING;if(A===D)return uR.GITLAB_ORG;if(A.includes(E))return uR.GITLAB_DEVELOPMENT;return uR.GITLAB_SELF_MANAGED}var kkA={$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 jt1=SA(T1(),1);var gkA={};fY(gkA,{type:()=>G64,self:()=>J64,required:()=>X64,properties:()=>z64,description:()=>Y64,default:()=>Tt1,additionalProperties:()=>U64,$schema:()=>F64});var F64="http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",Y64="Schema for a IDE and IDE extension version informations",J64={vendor:"com.gitlab",name:"ide_extension_version",version:"1-1-0",format:"jsonschema"},G64="object",U64=!1,X64=["ide_name","ide_version","ide_vendor","extension_name","extension_version","language_server_version"],z64={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}},Tt1={$schema:F64,description:Y64,self:J64,type:G64,additionalProperties:U64,required:X64,properties:z64};class bkA{#A;#Q;#B;#D;#E;#I={schema:"iglu:com.gitlab/ide_extension_version/jsonschema/1-1-0",data:{}};#C=!0;constructor(A,Q,B,D,E){this.#A=A,this.#Q=Q,this.#A.onConfigChange((I)=>this.#F(I)),this.#B=B,this.#D=L1(D,`[SnowplowTracker(${E})]`),this.#E=E}#F(A){let Q=A.telemetry?.enabled;if(typeof Q<"u"&&this.#C!==Q)this.#C=Q;this.#Y({extension:A.telemetry?.extension,ide:A.telemetry?.ide})}#Y(A){this.#I.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:e8()??null}}async trackEvent(A,Q){if(!this.isEnabled())return;if(!this.hasClientContext())return;let B={category:this.#E,action:A};try{let D={};if(Q){for(let[Y,J]of Object.entries(Q))if(J!==null&&J!==void 0)D[Y]=String(J)}let E=this.#B.build(D),I=[E,this.#I];if(!this.#Q.validateContext(kkA,E.data)){this.#D.warn("Invalid standard context");return}if(!this.#Q.validateContext(gkA,this.#I?.data)){this.#D.warn("Invalid IDE extension context");return}await this.#Q.trackStructuredEvent(B,I)}catch(D){this.#D.error(`Failed to track ${A}`,D)}}isEnabled(){return this.#C}hasClientContext(){return Boolean(this.#I.data.ide_name||this.#I.data.extension_name)}}class bb{#A;constructor(A,Q,B,D){this.#A=new bkA(A,Q,B,D,zr1)}async trackEvent(A,Q){this.#A.trackEvent(A,Q)}isEnabled(){return this.#A.isEnabled()}hasClientContext(){return this.#A.hasClientContext()}}bb=Q1([jt1.Injectable(v3A,[w4,i3A,n3A,q1])],bb);var Z64=60000,K64=86400000,r3A=o3A.createInterfaceId("DailyActivityTracker");class fb{#A;#Q;#B;#D=!1;#E;#I;constructor(A,Q,B,D){this.#A=A,this.#Q=Q,this.#B=L1(B,"[DailyActivityTracker]"),this.#I=D}async initialize(){if(this.#D)return;setInterval(()=>{this.#C().catch((A)=>{this.#B.warn("Error during activity check",A)})},Z64),this.#D=!0}async#C(){if(!this.#A.isEnabled())return;if(this.#E){await this.#J();return}let A=Date.now(),Q=await this.#G();if(this.#F(A,Q))await this.#Y(A)}#F(A,Q){if(Q===null)return!0;return A-Q>=K64}async#Y(A){try{if(!this.#A.hasClientContext())return;await this.#A.trackEvent("active_installation",{timestamp:A});try{await this.#U(A),this.#E=void 0}catch(Q){this.#E=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#J(){if(!this.#E)return;try{await this.#U(this.#E),this.#B.info("Successfully saved pending activity timestamp"),this.#E=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(gk)||{})[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(gk)||{},B=this.#z();if(!B){this.#B.warn("No activity key available, cannot save activity timestamp");return}Q[B]=A,await this.#Q.set(gk,Q)}#z(){let A=this.#I.get("telemetry")?.ide?.version,Q=this.#I.get("clientInfo.name");if(!A)this.#B.warn("No IDE version available, cannot store activity by ide version");return A||Q}}fb=Q1([o3A.Injectable(r3A,[v3A,LN,q1,w4])],fb);var EJ0=SA(T1(),1);var iEA=SA(T1(),1);var uY0=SA(We1(),1),dY0=SA(O20(),1),cY0=SA(BD(),1),pY0=SA(T1(),1);import gq4 from"https";import bq4 from"http";import ImA from"fs";var x82=HT(),zq4=Go(),h82=Sf(),m82=x70(),Zq4=WT(),u82=RxA(),Kq4=UD0(),d82=VD0(),c82=MD0(),wq4=R4(),bEA=I4(),{InvalidArgumentError:gEA}=wq4,Ex=GE0(),p82=Xo(),l82=exA(),{MockCallHistory:i82,MockCallHistoryLog:a82}=BhA(),n82=JhA(),o82=IhA(),r82=KI0(),s82=hxA(),t82=uDA(),{getGlobalDispatcher:Hq4,setGlobalDispatcher:e82}=AEA(),A22=uf(),Q22=VhA();Object.assign(zq4.prototype,Ex);var fEA=Zq4;var xEA=Kq4;var Nq4={redirect:_I0(),responseError:jI0(),retry:SI0(),dump:kI0(),dns:xI0(),cache:EC0(),decompress:UC0()},hY0={MemoryCacheStore:WhA()};var Vq4=zC0();hY0.SqliteCacheStore=Vq4;var Mq4={parseHeaders:bEA.parseHeaders,headerNameToString:bEA.headerNameToString};function Jr(A){return(Q,B,D)=>{if(typeof B==="function")D=B,B=null;if(!Q||typeof Q!=="string"&&typeof Q!=="object"&&!(Q instanceof URL))throw new gEA("invalid url");if(B!=null&&typeof B!=="object")throw new gEA("invalid opts");if(B&&B.path!=null){if(typeof B.path!=="string")throw new gEA("invalid opts.path");let C=B.path;if(!B.path.startsWith("/"))C=`/${C}`;Q=new URL(bEA.parseOrigin(Q).origin+C)}else{if(!B)B=typeof Q==="object"?Q:{};Q=bEA.parseURL(Q)}let{agent:E,dispatcher:I=Hq4()}=B;if(E)throw new gEA("unsupported opts.agent. Did you mean opts.client?");return A.call(I,{...B,origin:Q.origin,path:Q.search?`${Q.pathname}${Q.search}`:Q.pathname,method:B.method||(B.body?"PUT":"GET")},D)}}var B22=Qr().fetch;var qq4=_T().Headers,Oq4=eo().Response,Lq4=af().Request,_q4=HDA().FormData;var{setGlobalOrigin:D22,getGlobalOrigin:E22}=cfA();var{CacheStorage:$q4}=NF0(),{kConstruct:Wq4}=C2();var Rq4=new $q4(Wq4);var{deleteCookie:I22,getCookies:C22,getSetCookies:F22,setCookie:Y22,parseCookie:J22}=kF0();var{parseMIMEType:G22,serializeAMimeType:U22}=iF();var{CloseEvent:X22,ErrorEvent:z22,MessageEvent:Z22}=OEA(),{WebSocket:K22,ping:w22}=KY0();var Tq4=qY0().WebSocketStream,jq4=AmA().WebSocketError,Pq4=Jr(Ex.request),Sq4=Jr(Ex.stream),yq4=Jr(Ex.pipeline),vq4=Jr(Ex.connect),kq4=Jr(Ex.upgrade);var{EventSource:H22}=xY0();var mY0=new bq4.Agent({keepAlive:!0});class bT extends FvA{#A;#Q;#B;#D=!1;#E;#I;#C;constructor(A,Q){super();this.#C=A,this.#I={rejectUnauthorized:!0},this.#B=Q,this.#E=this.#F()}async initialize(){try{let A=await uY0.getProxySettings();if(A?.http){if(process.env.http_proxy=`${A.http.protocol}://${A.http.host}:${A.http.port}`,this.#C.info(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`),A.http?.credentials&&A.http.credentials?.username&&A.http.credentials?.password)this.#C.info(`fetch: Added credentials to http_proxy for username: ${A.http.credentials.username}`),process.env.http_proxy=`${A.http.protocol}://${A.http.credentials.username}:${A.http.credentials.password}@${A.http.host}:${A.http.port}`}if(A?.https){if(process.env.https_proxy=`${A.https.protocol}://${A.https.host}:${A.https.port}`,this.#C.info(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`),A.https?.credentials&&A.https.credentials?.username&&A.https.credentials?.password)this.#C.info(`fetch: Added credentials to HTTPS_PROXY for username: ${A.https.credentials.username}`),process.env.https_proxy=`${A.https.protocol}://${A.https.credentials.username}:${A.https.credentials.password}@${A.https.host}:${A.https.port}`}if(process.env.wss_proxy||process.env.ws_proxy)this.#C.info(`fetch: Detected existing ${process.env.wss_proxy?"wss_proxy":"ws_proxy"} setting`);else if(A?.https)this.#C.info("fetch: Setting WebSocket proxy based on https_proxy setting"),process.env.ws_proxy=process.env.https_proxy,process.env.wss_proxy=process.env.https_proxy;else if(A?.http)this.#C.info("fetch: Setting WebSocket proxy based on http_proxy setting"),process.env.ws_proxy=process.env.http_proxy,process.env.wss_proxy=process.env.http_proxy;if(!A?.http&&!A?.https&&!process.env.ws_proxy&&!process.env.wss_proxy)this.#C.info("fetch: Detected no proxy settings")}catch(A){this.#C.warn("Unable to load proxy settings",A)}if(this.#B)this.#C.debug(`fetch: Detected user proxy ${this.#B}`),process.env.http_proxy=this.#B,process.env.https_proxy=this.#B;if(process.env.http_proxy||process.env.https_proxy||process.env.ws_proxy||process.env.wss_proxy){let A=process.env.NO_PROXY??process.env.no_proxy??"";if(A?.length)this.#C.info(`fetch: Skipping proxy for hosts in no_proxy: ${A}`);this.#Q=this.#Y(),this.#A=new xEA(this.#U())}else this.#A=new fEA(this.#U());this.#D=!0}async destroy(){this.#Q?.destroy()}async fetchBase(A,Q){if(!this.#D)throw Error("LsFetch not initialized. Make sure LsFetch.initialize() was called.");return this.#J(A,{...Q,agent:this.#G(A),dispatcher:this.#A},super.fetchBase)}async fetch(A,Q){if(!this.#D)throw Error("LsFetch not initialized. Make sure LsFetch.initialize() was called.");let B=new AbortController,D=AbortSignal.timeout(n5A);[Q?.signal,D].forEach((E)=>{E?.addEventListener("abort",()=>B.abort(E.reason),{once:!0})});try{return await this.#J(A,{...Q,signal:B.signal,agent:this.#G(A),dispatcher:this.#A},super.fetch)}catch(E){if($b(E)){let{reason:I}=B.signal;if(I instanceof Error&&I.name==="TimeoutError")throw new YvA(A)}throw E}}getWebSocketOptions(A){let Q=this.#G(A),B=A.toString().startsWith("https://")?"https":"http",D=Q===this.#Q?"proxy":B;return{...this.#I,agent:Q,agentType:D}}updateAgentOptions({ignoreCertificateErrors:A,ca:Q,cert:B,certKey:D}){let E={};try{E={...Q?{ca:ImA.readFileSync(Q)}:{},...B?{cert:ImA.readFileSync(B)}:{},...D?{key:ImA.readFileSync(D)}:{}}}catch(C){this.#C.error("Error reading https agent options from file",C)}let I={rejectUnauthorized:!A,...E};if(cY0.default.isEqual(I,this.#I))return;if(this.#I=I,this.#E=this.#F(),this.#Q)this.#Q=this.#Y(),this.#A=new xEA(this.#U());else this.#A=new fEA(this.#U())}async*streamResponse(A,Q){let B=this.#C;if(!A.body)return;let D=new TextDecoder;async function*E(I){for await(let C of I){if(Q.isCancellationRequested){if("destroy"in I)B.debug("Cancelling stream"),I.destroy();return}yield D.decode(C)}}yield*E(A.body)}#F(){let A={...this.#I,keepAlive:!0};return this.#C.debug(`fetch: https agent with options initialized ${JSON.stringify(this.#X(A))}.`),new gq4.Agent(A)}#Y(){return this.#C.debug(`fetch: proxy agent with options initialized ${JSON.stringify(this.#X(this.#I))}.`),new dY0.ProxyAgent(this.#I)}async#J(A,Q,B){let D=Date.now(),E=this.#z(A);if(Q.agent===mY0)this.#C.debug(`fetch: request for ${E} made with http agent.`);else{let I=Q.agent===this.#Q?"proxy":"https";this.#C.debug(`fetch: request for ${E} made with ${I} agent.`)}try{let I=await B(A,Q),C=Date.now()-D;return this.#C.debug(`fetch: request to ${E} returned HTTP ${I.status} after ${C} ms`),I}catch(I){let C=Date.now()-D;throw this.#C.debug(`fetch: request to ${E} threw an exception after ${C} ms`),I}}#G(A){if(this.#Q)return this.#Q;if(A.toString().startsWith("https://"))return this.#E;return mY0}#U=()=>({keepAliveTimeout:1000,requestTls:this.#I});#z(A){if(A instanceof URL)return A.toString();if(typeof A==="string")return A;return A.url}#X(A){let{ca:Q,cert:B,key:D,...E}=A;return{...E,...Q?{ca:"<hidden>"}:{},...B?{cert:"<hidden>"}:{},...D?{key:"<hidden>"}:{}}}}bT=Q1([pY0.Injectable(O7,[q1])],bT);var lEA=SA(T1(),1);var nY0=SA(T1(),1);function WV(A){let Q={};for(let[B,D]of Object.entries(A))if(D.zod)Q[B]=D.zod;return Q}function FX(A,Q){let B=Array.isArray(Q)?Q:Object.values(Q);for(let D of B){let E=new yA1(D.flags,D.description);if(D.env)E.env(D.env);if(D.default!==void 0)E.default(D.default);if(D.choices)E.choices(D.choices);if(D.parse)E.argParser(D.parse);if(D.mandatory)E.makeOptionMandatory();A.addOption(E)}}import{statSync as fq4}from"node:fs";import{isAbsolute as xq4,normalize as hq4,resolve as mq4}from"node:path";function lY0(A,Q=process.cwd()){let B;if(xq4(A))B=hq4(A);else B=mq4(Q,A);return uq4(B),B}function uq4(A){try{if(!fq4(A).isDirectory())throw new TW(`Path "${A}" exists but is not a directory`)}catch(Q){if(Q instanceof Error&&Q.code==="ENOENT")throw new TW(`Directory "${A}" does not exist`);throw Q}}var Ix={gitlabBaseUrl:{displayName:"\uD83D\uDD17 GitLab Instance URL",description:"The URL of the GitLab instance to connect to.",defaultValue:"https://gitlab.com",isSensitive:!1},gitlabAuthToken:{displayName:"\uD83D\uDD16 GitLab Token",description:"Personal Access Token (PAT) with `api` scope.",defaultValue:"",isSensitive:!0}};var Gr={cwd:{flags:"-C, --cwd <path>",description:"change working directory",default:process.cwd(),parse:(A)=>lY0(A),zod:u.string()},gitlabBaseUrl:{flags:"--gitlab-base-url <url>",description:Ix.gitlabBaseUrl.description,env:"GITLAB_URL",default:process.env.GITLAB_BASE_URL,zod:u.string().optional()},gitlabAuthToken:{flags:"--gitlab-auth-token <token>",description:Ix.gitlabAuthToken.description,env:"GITLAB_TOKEN",default:process.env.GITLAB_OAUTH_TOKEN,zod:u.string().optional()},logLevel:{flags:"--log-level <level>",description:"Set logging level",choices:Object.values(J3),env:"LOG_LEVEL",default:J3.DEBUG,zod:u.enum(Object.values(J3)).transform((A)=>A)},gitHttpUser:{flags:"--git-http-user <user>",description:"Username for git HTTP authentication credentials",env:"DUO_WORKFLOW_GIT_HTTP_USER",zod:u.string().optional()},gitHttpPassword:{flags:"--git-http-password <password>",description:"Password for git HTTP authentication credentials",env:"DUO_WORKFLOW_GIT_HTTP_PASSWORD",zod:u.string().optional()},gitUserEmail:{flags:"--git-user-email <email>",description:"Email for git commit attribution",env:"DUO_WORKFLOW_GIT_USER_EMAIL",zod:u.string().optional()},gitUserName:{flags:"--git-user-name <name>",description:"Name for git commit attribution",env:"DUO_WORKFLOW_GIT_USER_NAME",zod:u.string().optional()},gitAuthorEmail:{flags:"--git-author-email <email>",description:"Email for git author attribution",env:"DUO_WORKFLOW_GIT_AUTHOR_EMAIL",zod:u.string().optional()},gitAuthorName:{flags:"--git-author-name <name>",description:"Name for git author attribution",env:"DUO_WORKFLOW_GIT_AUTHOR_USER_NAME",zod:u.string().optional()},telemetryEnabled:{flags:"--telemetry-enabled <value>",description:"Enable collection of telemetry and error events",env:"DUO_WORKFLOW_TELEMETRY_ENABLED",default:!0,zod:u.preprocess((A)=>typeof A==="string"?A!=="false"&&A!=="0":A,u.boolean())}};function iY0(A){try{let Q=JSON.parse(A);return Array.isArray(Q)?Q.map((D)=>({category:D.Category||D.category,content:D.Content||D.content,metadata:D.metadata||{}})):[]}catch(Q){if(Q instanceof SyntaxError)throw new TW(`Invalid JSON format: ${Q.message}`);throw new TW(`AI Context Item schema error: ${Q}`)}}var aY0={existingSessionId:{flags:"--existing-session-id <sessionId>",description:"ID of existing session to resume",env:"DUO_WORKFLOW_WORKFLOW_ID",zod:u.string().optional()}},hEA={...aY0},mEA={goal:{flags:"-g, --goal <goal>",description:"Goal/prompt for the session",env:"DUO_WORKFLOW_GOAL",mandatory:!0,zod:u.string()},aiContextItems:{flags:"--ai-context-items <contextItems>",description:"JSON encoded array of additional context items",env:"DUO_WORKFLOW_ADDITIONAL_CONTEXT_CONTENT",parse:(A)=>iY0(A),zod:u.custom().optional()},...aY0};var dq4=u.object(WV(Gr)),cq4=u.object({name:u.literal("tui"),...WV(hEA)}),pq4=u.object({name:u.literal("run"),...WV(mEA)}),lq4=u.discriminatedUnion("name",[cq4,pq4]),H9=nY0.createInterfaceId("ParsedCliInput");function CmA(A,Q){let B=dq4.parse(A),D=lq4.parse({name:Q,...A});return{...B,command:D}}var oY0=SA(T1(),1);class uEA{#A;constructor(A){this.#A=A}get logLevel(){return this.#A}}class Ur extends uEA{constructor(A){super(A.logLevel)}}Ur=Q1([oY0.Injectable($d,[H9])],Ur);import{existsSync as nq4,mkdirSync as oq4,writeFileSync as rq4}from"node:fs";import{appendFile as sq4}from"node:fs/promises";import{join as tq4,sep as eq4}from"node:path";var YmA=SA(sY0(),1);class JmA extends Error{name="TimeoutError";constructor(A,Q){super(A,Q);Error.captureStackTrace?.(this,JmA)}}var tY0=(A)=>A.reason??new DOMException("This operation was aborted.","AbortError");function GmA(A,Q){let{milliseconds:B,fallback:D,message:E,customTimers:I={setTimeout,clearTimeout},signal:C}=Q,F,Y,G=new Promise((X,z)=>{if(typeof B!=="number"||Math.sign(B)!==1)throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${B}\``);if(C?.aborted){z(tY0(C));return}if(C)Y=()=>{z(tY0(C))},C.addEventListener("abort",Y,{once:!0});if(A.then(X,z),B===Number.POSITIVE_INFINITY)return;let U=new JmA;F=I.setTimeout.call(void 0,()=>{if(D){try{X(D())}catch(Z){z(Z)}return}if(typeof A.cancel==="function")A.cancel();if(E===!1)X();else if(E instanceof Error)z(E);else U.message=E??`Promise timed out after ${B} milliseconds`,z(U)},B)}).finally(()=>{if(G.clear(),Y&&C)C.removeEventListener("abort",Y)});return G.clear=()=>{I.clearTimeout.call(void 0,F),F=void 0},G}function UmA(A,Q,B){let D=0,E=A.length;while(E>0){let I=Math.trunc(E/2),C=D+I;if(B(A[C],Q)<=0)D=++C,E-=I+1;else E=I}return D}class cEA{#A=[];enqueue(A,Q){let{priority:B=0,id:D}=Q??{},E={priority:B,id:D,run:A};if(this.size===0||this.#A[this.size-1].priority>=B){this.#A.push(E);return}let I=UmA(this.#A,E,(C,F)=>F.priority-C.priority);this.#A.splice(I,0,E)}setPriority(A,Q){let B=this.#A.findIndex((E)=>E.id===A);if(B===-1)throw ReferenceError(`No promise function with the id "${A}" exists in the queue.`);let[D]=this.#A.splice(B,1);this.enqueue(D.run,{priority:Q,id:A})}dequeue(){return this.#A.shift()?.run}filter(A){return this.#A.filter((Q)=>Q.priority===A.priority).map((Q)=>Q.run)}get size(){return this.#A.length}}class pEA extends YmA.default{#A;#Q;#B=0;#D;#E=!1;#I=!1;#C;#F=0;#Y=0;#J;#G;#U;#z;#X=0;#Z;#H;#K=1n;#w=new Map;timeout;constructor(A){super();if(A={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:cEA,...A},!(typeof A.intervalCap==="number"&&A.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${A.intervalCap?.toString()??""}\` (${typeof A.intervalCap})`);if(A.interval===void 0||!(Number.isFinite(A.interval)&&A.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${A.interval?.toString()??""}\` (${typeof A.interval})`);if(this.#A=A.carryoverIntervalCount??A.carryoverConcurrencyCount??!1,this.#Q=A.intervalCap===Number.POSITIVE_INFINITY||A.interval===0,this.#D=A.intervalCap,this.#C=A.interval,this.#U=new A.queueClass,this.#z=A.queueClass,this.concurrency=A.concurrency,A.timeout!==void 0&&!(Number.isFinite(A.timeout)&&A.timeout>0))throw TypeError(`Expected \`timeout\` to be a positive finite number, got \`${A.timeout}\` (${typeof A.timeout})`);this.timeout=A.timeout,this.#H=A.autoStart===!1,this.#v()}get#V(){return this.#Q||this.#B<this.#D}get#W(){return this.#X<this.#Z}#$(){if(this.#X--,this.#X===0)this.emit("pendingZero");this.#R(),this.emit("next")}#N(){this.#T(),this.#L(),this.#G=void 0}get#q(){let A=Date.now();if(this.#J===void 0){let Q=this.#F-A;if(Q<0){if(this.#Y>0){let B=A-this.#Y;if(B<this.#C)return this.#M(this.#C-B),!0}this.#B=this.#A?this.#X:0}else return this.#M(Q),!0}return!1}#M(A){if(this.#G!==void 0)return;this.#G=setTimeout(()=>{this.#N()},A)}#O(){if(this.#J)clearInterval(this.#J),this.#J=void 0}#S(){if(this.#G)clearTimeout(this.#G),this.#G=void 0}#R(){if(this.#U.size===0){if(this.#O(),this.emit("empty"),this.#X===0)this.#S(),this.emit("idle");return!1}let A=!1;if(!this.#H){let Q=!this.#q;if(this.#V&&this.#W){let B=this.#U.dequeue();if(!this.#Q)this.#B++,this.#P();if(this.emit("active"),this.#Y=Date.now(),B(),Q)this.#L();A=!0}}return A}#L(){if(this.#Q||this.#J!==void 0)return;this.#J=setInterval(()=>{this.#T()},this.#C),this.#F=Date.now()+this.#C}#T(){if(this.#B===0&&this.#X===0&&this.#J)this.#O();this.#B=this.#A?this.#X:0,this.#j(),this.#P()}#j(){while(this.#R());}get concurrency(){return this.#Z}set concurrency(A){if(!(typeof A==="number"&&A>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${A}\` (${typeof A})`);this.#Z=A,this.#j()}async#y(A){return new Promise((Q,B)=>{A.addEventListener("abort",()=>{B(A.reason)},{once:!0})})}setPriority(A,Q){if(typeof Q!=="number"||!Number.isFinite(Q))throw TypeError(`Expected \`priority\` to be a finite number, got \`${Q}\` (${typeof Q})`);this.#U.setPriority(A,Q)}async add(A,Q={}){return Q.id??=(this.#K++).toString(),Q={timeout:this.timeout,...Q},new Promise((B,D)=>{let E=Symbol(`task-${Q.id}`);this.#U.enqueue(async()=>{this.#X++,this.#w.set(E,{id:Q.id,priority:Q.priority??0,startTime:Date.now(),timeout:Q.timeout});try{try{Q.signal?.throwIfAborted()}catch(F){if(!this.#Q)this.#B--;throw this.#w.delete(E),F}let I=A({signal:Q.signal});if(Q.timeout)I=GmA(Promise.resolve(I),{milliseconds:Q.timeout,message:`Task timed out after ${Q.timeout}ms (queue has ${this.#X} running, ${this.#U.size} waiting)`});if(Q.signal)I=Promise.race([I,this.#y(Q.signal)]);let C=await I;B(C),this.emit("completed",C)}catch(I){D(I),this.emit("error",I)}finally{this.#w.delete(E),queueMicrotask(()=>{this.#$()})}},Q),this.emit("add"),this.#R()})}async addAll(A,Q){return Promise.all(A.map(async(B)=>this.add(B,Q)))}start(){if(!this.#H)return this;return this.#H=!1,this.#j(),this}pause(){this.#H=!0}clear(){this.#U=new this.#z,this.#g()}async onEmpty(){if(this.#U.size===0)return;await this.#_("empty")}async onSizeLessThan(A){if(this.#U.size<A)return;await this.#_("next",()=>this.#U.size<A)}async onIdle(){if(this.#X===0&&this.#U.size===0)return;await this.#_("idle")}async onPendingZero(){if(this.#X===0)return;await this.#_("pendingZero")}async onRateLimit(){if(this.isRateLimited)return;await this.#_("rateLimit")}async onRateLimitCleared(){if(!this.isRateLimited)return;await this.#_("rateLimitCleared")}async onError(){return new Promise((A,Q)=>{let B=(D)=>{this.off("error",B),Q(D)};this.on("error",B)})}async#_(A,Q){return new Promise((B)=>{let D=()=>{if(Q&&!Q())return;this.off(A,D),B()};this.on(A,D)})}get size(){return this.#U.size}sizeBy(A){return this.#U.filter(A).length}get pending(){return this.#X}get isPaused(){return this.#H}#v(){if(this.#Q)return;this.on("add",()=>{if(this.#U.size>0)this.#P()}),this.on("next",()=>{this.#P()})}#P(){if(this.#Q||this.#I)return;this.#I=!0,queueMicrotask(()=>{this.#I=!1,this.#g()})}#g(){let A=this.#E,Q=!this.#Q&&this.#B>=this.#D&&this.#U.size>0;if(Q!==A)this.#E=Q,this.emit(Q?"rateLimit":"rateLimitCleared")}get isRateLimited(){return this.#E}get isSaturated(){return this.#X===this.#Z&&this.#U.size>0||this.isRateLimited&&this.#U.size>0}get runningTasks(){return[...this.#w.values()].map((A)=>({...A}))}}var eY0=SA(T1(),1);class fT{#A;#Q=new pEA({concurrency:1});constructor(){this.#A=this.#D(),this.#E(),setImmediate(()=>fJ1())}write(A){if(!this.#A){console.error(A);return}let Q=this.#A;D9(this.#Q.add(async()=>{try{await sq4(Q,`${A}
1592
+ Errors: ${JSON.stringify(this.#E.errors,null,2)}`);return B}async stop(){await this.#Q.stop()}async#J(A){if(!this.#I.enabled()||this.#A)return;try{let Q=`${this.#I.endpoint}/com.snowplowanalytics.snowplow/tp2`,B={schema:"iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4",data:A.map((I)=>{let C=Ft1();return I.add("eid",C),I.add("p","app"),I.add("tv","js-gitlab"),I.add("tna","gl"),I.add("aid",this.#I.appId),I64(I.build())})},D={headers:{"Content-Type":"application/json"},body:JSON.stringify(B)},E=await this.#B.post(Q,D);if(E.status!==200)this.#D.warn(`Could not send telemetry to snowplow, this warning can be safely ignored. status=${E.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=Q1([l3A.Injectable(i3A,[O7,w4,q1])],kb);var a3A=SA(T1(),1);var uR={GITLAB_COM:"production",GITLAB_STAGING:"staging",GITLAB_ORG:"org",GITLAB_DEVELOPMENT:"development",GITLAB_SELF_MANAGED:"self-managed"},vkA={GITLAB_COM:"https://gitlab.com",GITLAB_STAGING:"https://staging.gitlab.com",GITLAB_ORG:"https://dev.gitlab.org",GITLAB_DEVELOPMENT:"http://localhost"},_t1="iglu:com.gitlab/gitlab_standard/jsonschema/1-1-1",Lt1="Language Server",n3A=a3A.createInterfaceId("StandardContext");class gb{#A=Lt1;#Q=uR.GITLAB_COM;#B=vkA.GITLAB_COM;constructor(A){this.#D(A.get()),A.onConfigChange((Q)=>this.#D(Q))}#D(A){this.#A=A?.telemetry?.extension?.name??Lt1,this.#B=A?.baseUrl??Zr1,this.#Q=Rt1(this.#B)}build(A){return{schema:_t1,data:{source:this.#A,extra:A,environment:this.#Q,host_name:this.#B}}}}gb=Q1([a3A.Injectable(n3A,[w4])],gb);function Rt1(A){let{GITLAB_COM:Q,GITLAB_STAGING:B,GITLAB_ORG:D,GITLAB_DEVELOPMENT:E}=vkA;if(A===Q)return uR.GITLAB_COM;if(A===B)return uR.GITLAB_STAGING;if(A===D)return uR.GITLAB_ORG;if(A.includes(E))return uR.GITLAB_DEVELOPMENT;return uR.GITLAB_SELF_MANAGED}var kkA={$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 jt1=SA(T1(),1);var gkA={};fY(gkA,{type:()=>G64,self:()=>J64,required:()=>X64,properties:()=>z64,description:()=>Y64,default:()=>Tt1,additionalProperties:()=>U64,$schema:()=>F64});var F64="http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",Y64="Schema for a IDE and IDE extension version informations",J64={vendor:"com.gitlab",name:"ide_extension_version",version:"1-1-0",format:"jsonschema"},G64="object",U64=!1,X64=["ide_name","ide_version","ide_vendor","extension_name","extension_version","language_server_version"],z64={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}},Tt1={$schema:F64,description:Y64,self:J64,type:G64,additionalProperties:U64,required:X64,properties:z64};class bkA{#A;#Q;#B;#D;#E;#I={schema:"iglu:com.gitlab/ide_extension_version/jsonschema/1-1-0",data:{}};#C=!0;constructor(A,Q,B,D,E){this.#A=A,this.#Q=Q,this.#A.onConfigChange((I)=>this.#F(I)),this.#B=B,this.#D=L1(D,`[SnowplowTracker(${E})]`),this.#E=E}#F(A){let Q=A.telemetry?.enabled;if(typeof Q<"u"&&this.#C!==Q)this.#C=Q;this.#Y({extension:A.telemetry?.extension,ide:A.telemetry?.ide})}#Y(A){this.#I.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:e8()??null}}async trackEvent(A,Q){if(!this.isEnabled())return;if(!this.hasClientContext())return;let B={category:this.#E,action:A};try{let D={};if(Q){for(let[Y,J]of Object.entries(Q))if(J!==null&&J!==void 0)D[Y]=String(J)}let E=this.#B.build(D),I=[E,this.#I];if(!this.#Q.validateContext(kkA,E.data)){this.#D.warn("Invalid standard context");return}if(!this.#Q.validateContext(gkA,this.#I?.data)){this.#D.warn("Invalid IDE extension context");return}await this.#Q.trackStructuredEvent(B,I)}catch(D){this.#D.error(`Failed to track ${A}`,D)}}isEnabled(){return this.#C}hasClientContext(){return Boolean(this.#I.data.ide_name||this.#I.data.extension_name)}}class bb{#A;constructor(A,Q,B,D){this.#A=new bkA(A,Q,B,D,zr1)}async trackEvent(A,Q){this.#A.trackEvent(A,Q)}isEnabled(){return this.#A.isEnabled()}hasClientContext(){return this.#A.hasClientContext()}}bb=Q1([jt1.Injectable(v3A,[w4,i3A,n3A,q1])],bb);var Z64=60000,K64=86400000,r3A=o3A.createInterfaceId("DailyActivityTracker");class fb{#A;#Q;#B;#D=!1;#E;#I;constructor(A,Q,B,D){this.#A=A,this.#Q=Q,this.#B=L1(B,"[DailyActivityTracker]"),this.#I=D}async initialize(){if(this.#D)return;setInterval(()=>{this.#C().catch((A)=>{this.#B.warn("Error during activity check",A)})},Z64),this.#D=!0}async#C(){if(!this.#A.isEnabled())return;if(this.#E){await this.#J();return}let A=Date.now(),Q=await this.#G();if(this.#F(A,Q))await this.#Y(A)}#F(A,Q){if(Q===null)return!0;return A-Q>=K64}async#Y(A){try{if(!this.#A.hasClientContext())return;await this.#A.trackEvent("active_installation",{timestamp:A});try{await this.#U(A),this.#E=void 0}catch(Q){this.#E=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#J(){if(!this.#E)return;try{await this.#U(this.#E),this.#B.info("Successfully saved pending activity timestamp"),this.#E=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(gk)||{})[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(gk)||{},B=this.#z();if(!B){this.#B.warn("No activity key available, cannot save activity timestamp");return}Q[B]=A,await this.#Q.set(gk,Q)}#z(){let A=this.#I.get("telemetry")?.ide?.version,Q=this.#I.get("clientInfo.name");if(!A)this.#B.warn("No IDE version available, cannot store activity by ide version");return A||Q}}fb=Q1([o3A.Injectable(r3A,[v3A,LN,q1,w4])],fb);var EJ0=SA(T1(),1);var iEA=SA(T1(),1);var uY0=SA(We1(),1),dY0=SA(O20(),1),cY0=SA(BD(),1),pY0=SA(T1(),1);import gq4 from"https";import bq4 from"http";import ImA from"fs";var x82=HT(),zq4=Go(),h82=Sf(),m82=x70(),Zq4=WT(),u82=RxA(),Kq4=UD0(),d82=VD0(),c82=MD0(),wq4=R4(),bEA=I4(),{InvalidArgumentError:gEA}=wq4,Ex=GE0(),p82=Xo(),l82=exA(),{MockCallHistory:i82,MockCallHistoryLog:a82}=BhA(),n82=JhA(),o82=IhA(),r82=KI0(),s82=hxA(),t82=uDA(),{getGlobalDispatcher:Hq4,setGlobalDispatcher:e82}=AEA(),A22=uf(),Q22=VhA();Object.assign(zq4.prototype,Ex);var fEA=Zq4;var xEA=Kq4;var Nq4={redirect:_I0(),responseError:jI0(),retry:SI0(),dump:kI0(),dns:xI0(),cache:EC0(),decompress:UC0()},hY0={MemoryCacheStore:WhA()};var Vq4=zC0();hY0.SqliteCacheStore=Vq4;var Mq4={parseHeaders:bEA.parseHeaders,headerNameToString:bEA.headerNameToString};function Jr(A){return(Q,B,D)=>{if(typeof B==="function")D=B,B=null;if(!Q||typeof Q!=="string"&&typeof Q!=="object"&&!(Q instanceof URL))throw new gEA("invalid url");if(B!=null&&typeof B!=="object")throw new gEA("invalid opts");if(B&&B.path!=null){if(typeof B.path!=="string")throw new gEA("invalid opts.path");let C=B.path;if(!B.path.startsWith("/"))C=`/${C}`;Q=new URL(bEA.parseOrigin(Q).origin+C)}else{if(!B)B=typeof Q==="object"?Q:{};Q=bEA.parseURL(Q)}let{agent:E,dispatcher:I=Hq4()}=B;if(E)throw new gEA("unsupported opts.agent. Did you mean opts.client?");return A.call(I,{...B,origin:Q.origin,path:Q.search?`${Q.pathname}${Q.search}`:Q.pathname,method:B.method||(B.body?"PUT":"GET")},D)}}var B22=Qr().fetch;var qq4=_T().Headers,Oq4=eo().Response,Lq4=af().Request,_q4=HDA().FormData;var{setGlobalOrigin:D22,getGlobalOrigin:E22}=cfA();var{CacheStorage:$q4}=NF0(),{kConstruct:Wq4}=C2();var Rq4=new $q4(Wq4);var{deleteCookie:I22,getCookies:C22,getSetCookies:F22,setCookie:Y22,parseCookie:J22}=kF0();var{parseMIMEType:G22,serializeAMimeType:U22}=iF();var{CloseEvent:X22,ErrorEvent:z22,MessageEvent:Z22}=OEA(),{WebSocket:K22,ping:w22}=KY0();var Tq4=qY0().WebSocketStream,jq4=AmA().WebSocketError,Pq4=Jr(Ex.request),Sq4=Jr(Ex.stream),yq4=Jr(Ex.pipeline),vq4=Jr(Ex.connect),kq4=Jr(Ex.upgrade);var{EventSource:H22}=xY0();var mY0=new bq4.Agent({keepAlive:!0});class bT extends FvA{#A;#Q;#B;#D=!1;#E;#I;#C;constructor(A,Q){super();this.#C=A,this.#I={rejectUnauthorized:!0},this.#B=Q,this.#E=this.#F()}async initialize(){try{let A=await uY0.getProxySettings();if(A?.http){if(process.env.http_proxy=`${A.http.protocol}://${A.http.host}:${A.http.port}`,this.#C.info(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`),A.http?.credentials&&A.http.credentials?.username&&A.http.credentials?.password)this.#C.info(`fetch: Added credentials to http_proxy for username: ${A.http.credentials.username}`),process.env.http_proxy=`${A.http.protocol}://${A.http.credentials.username}:${A.http.credentials.password}@${A.http.host}:${A.http.port}`}if(A?.https){if(process.env.https_proxy=`${A.https.protocol}://${A.https.host}:${A.https.port}`,this.#C.info(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`),A.https?.credentials&&A.https.credentials?.username&&A.https.credentials?.password)this.#C.info(`fetch: Added credentials to HTTPS_PROXY for username: ${A.https.credentials.username}`),process.env.https_proxy=`${A.https.protocol}://${A.https.credentials.username}:${A.https.credentials.password}@${A.https.host}:${A.https.port}`}if(process.env.wss_proxy||process.env.ws_proxy)this.#C.info(`fetch: Detected existing ${process.env.wss_proxy?"wss_proxy":"ws_proxy"} setting`);else if(A?.https)this.#C.info("fetch: Setting WebSocket proxy based on https_proxy setting"),process.env.ws_proxy=process.env.https_proxy,process.env.wss_proxy=process.env.https_proxy;else if(A?.http)this.#C.info("fetch: Setting WebSocket proxy based on http_proxy setting"),process.env.ws_proxy=process.env.http_proxy,process.env.wss_proxy=process.env.http_proxy;if(!A?.http&&!A?.https&&!process.env.ws_proxy&&!process.env.wss_proxy)this.#C.info("fetch: Detected no proxy settings")}catch(A){this.#C.warn("Unable to load proxy settings",A)}if(this.#B)this.#C.debug(`fetch: Detected user proxy ${this.#B}`),process.env.http_proxy=this.#B,process.env.https_proxy=this.#B;if(process.env.http_proxy||process.env.https_proxy||process.env.ws_proxy||process.env.wss_proxy){let A=process.env.NO_PROXY??process.env.no_proxy??"";if(A?.length)this.#C.info(`fetch: Skipping proxy for hosts in no_proxy: ${A}`);this.#Q=this.#Y(),this.#A=new xEA(this.#U())}else this.#A=new fEA(this.#U());this.#D=!0}async destroy(){this.#Q?.destroy()}async fetchBase(A,Q){if(!this.#D)throw Error("LsFetch not initialized. Make sure LsFetch.initialize() was called.");return this.#J(A,{...Q,agent:this.#G(A),dispatcher:this.#A},super.fetchBase)}async fetch(A,Q){if(!this.#D)throw Error("LsFetch not initialized. Make sure LsFetch.initialize() was called.");let B=new AbortController,D=AbortSignal.timeout(n5A);[Q?.signal,D].forEach((E)=>{E?.addEventListener("abort",()=>B.abort(E.reason),{once:!0})});try{return await this.#J(A,{...Q,signal:B.signal,agent:this.#G(A),dispatcher:this.#A},super.fetch)}catch(E){if($b(E)){let{reason:I}=B.signal;if(I instanceof Error&&I.name==="TimeoutError")throw new YvA(A)}throw E}}getWebSocketOptions(A){let Q=this.#G(A),B=A.toString().startsWith("https://")?"https":"http",D=Q===this.#Q?"proxy":B;return{...this.#I,agent:Q,agentType:D}}updateAgentOptions({ignoreCertificateErrors:A,ca:Q,cert:B,certKey:D}){let E={};try{E={...Q?{ca:ImA.readFileSync(Q)}:{},...B?{cert:ImA.readFileSync(B)}:{},...D?{key:ImA.readFileSync(D)}:{}}}catch(C){this.#C.error("Error reading https agent options from file",C)}let I={rejectUnauthorized:!A,...E};if(cY0.default.isEqual(I,this.#I))return;if(this.#I=I,this.#E=this.#F(),this.#Q)this.#Q=this.#Y(),this.#A=new xEA(this.#U());else this.#A=new fEA(this.#U())}async*streamResponse(A,Q){let B=this.#C;if(!A.body)return;let D=new TextDecoder;async function*E(I){for await(let C of I){if(Q.isCancellationRequested){if("destroy"in I)B.debug("Cancelling stream"),I.destroy();return}yield D.decode(C)}}yield*E(A.body)}#F(){let A={...this.#I,keepAlive:!0};return this.#C.debug(`fetch: https agent with options initialized ${JSON.stringify(this.#X(A))}.`),new gq4.Agent(A)}#Y(){return this.#C.debug(`fetch: proxy agent with options initialized ${JSON.stringify(this.#X(this.#I))}.`),new dY0.ProxyAgent(this.#I)}async#J(A,Q,B){let D=Date.now(),E=this.#z(A);if(Q.agent===mY0)this.#C.debug(`fetch: request for ${E} made with http agent.`);else{let I=Q.agent===this.#Q?"proxy":"https";this.#C.debug(`fetch: request for ${E} made with ${I} agent.`)}try{let I=await B(A,Q),C=Date.now()-D;return this.#C.debug(`fetch: request to ${E} returned HTTP ${I.status} after ${C} ms`),I}catch(I){let C=Date.now()-D;throw this.#C.debug(`fetch: request to ${E} threw an exception after ${C} ms`),I}}#G(A){if(this.#Q)return this.#Q;if(A.toString().startsWith("https://"))return this.#E;return mY0}#U=()=>({keepAliveTimeout:1000,requestTls:this.#I});#z(A){if(A instanceof URL)return A.toString();if(typeof A==="string")return A;return A.url}#X(A){let{ca:Q,cert:B,key:D,...E}=A;return{...E,...Q?{ca:"<hidden>"}:{},...B?{cert:"<hidden>"}:{},...D?{key:"<hidden>"}:{}}}}bT=Q1([pY0.Injectable(O7,[q1])],bT);var lEA=SA(T1(),1);var nY0=SA(T1(),1);function WV(A){let Q={};for(let[B,D]of Object.entries(A))if(D.zod)Q[B]=D.zod;return Q}function FX(A,Q){let B=Array.isArray(Q)?Q:Object.values(Q);for(let D of B){let E=new yA1(D.flags,D.description);if(D.env)E.env(D.env);if(D.default!==void 0)E.default(D.default);if(D.choices)E.choices(D.choices);if(D.parse)E.argParser(D.parse);if(D.mandatory)E.makeOptionMandatory();A.addOption(E)}}import{statSync as fq4}from"node:fs";import{isAbsolute as xq4,normalize as hq4,resolve as mq4}from"node:path";function lY0(A,Q=process.cwd()){let B;if(xq4(A))B=hq4(A);else B=mq4(Q,A);return uq4(B),B}function uq4(A){try{if(!fq4(A).isDirectory())throw new TW(`Path "${A}" exists but is not a directory`)}catch(Q){if(Q instanceof Error&&Q.code==="ENOENT")throw new TW(`Directory "${A}" does not exist`);throw Q}}var Ix={gitlabBaseUrl:{displayName:"\uD83D\uDD17 GitLab Instance URL",description:"The URL of the GitLab instance to connect to.",defaultValue:"https://gitlab.com",isSensitive:!1},gitlabAuthToken:{displayName:"\uD83D\uDD16 GitLab Token",description:"Personal Access Token (PAT) with `api` scope.",defaultValue:"",isSensitive:!0}};var Gr={cwd:{flags:"-C, --cwd <path>",description:"change working directory",default:process.cwd(),parse:(A)=>lY0(A),zod:u.string()},gitlabBaseUrl:{flags:"--gitlab-base-url <url>",description:Ix.gitlabBaseUrl.description,env:"GITLAB_URL",default:process.env.GITLAB_BASE_URL,zod:u.string().optional()},gitlabAuthToken:{flags:"--gitlab-auth-token <token>",description:Ix.gitlabAuthToken.description,env:"GITLAB_TOKEN",default:process.env.GITLAB_OAUTH_TOKEN,zod:u.string().optional()},logLevel:{flags:"--log-level <level>",description:"Set logging level",choices:Object.values(J3),env:"LOG_LEVEL",default:J3.DEBUG,zod:u.enum(Object.values(J3)).transform((A)=>A)},gitHttpUser:{flags:"--git-http-user <user>",description:"Username for git HTTP authentication credentials",env:"DUO_WORKFLOW_GIT_HTTP_USER",zod:u.string().optional()},gitHttpPassword:{flags:"--git-http-password <password>",description:"Password for git HTTP authentication credentials",env:"DUO_WORKFLOW_GIT_HTTP_PASSWORD",zod:u.string().optional()},gitUserEmail:{flags:"--git-user-email <email>",description:"Email for git commit attribution",env:"DUO_WORKFLOW_GIT_USER_EMAIL",zod:u.string().optional()},gitUserName:{flags:"--git-user-name <name>",description:"Name for git commit attribution",env:"DUO_WORKFLOW_GIT_USER_NAME",zod:u.string().optional()},gitAuthorEmail:{flags:"--git-author-email <email>",description:"Email for git author attribution",env:"DUO_WORKFLOW_GIT_AUTHOR_EMAIL",zod:u.string().optional()},gitAuthorName:{flags:"--git-author-name <name>",description:"Name for git author attribution",env:"DUO_WORKFLOW_GIT_AUTHOR_USER_NAME",zod:u.string().optional()},telemetryEnabled:{flags:"--telemetry-enabled <value>",description:"Enable collection of telemetry and error events",env:"DUO_WORKFLOW_TELEMETRY_ENABLED",default:!0,zod:u.preprocess((A)=>typeof A==="string"?A!=="false"&&A!=="0":A,u.boolean())}};function iY0(A){try{let Q=JSON.parse(A);return Array.isArray(Q)?Q.map((D)=>({category:D.Category||D.category,content:D.Content||D.content,metadata:D.metadata||{}})):[]}catch(Q){if(Q instanceof SyntaxError)throw new TW(`Invalid JSON format: ${Q.message}`);throw new TW(`AI Context Item schema error: ${Q}`)}}var aY0={existingSessionId:{flags:"--existing-session-id <sessionId>",description:"ID of existing session to resume",env:"DUO_WORKFLOW_WORKFLOW_ID",zod:u.string().optional()}},hEA={...aY0},mEA={goal:{flags:"-g, --goal <goal>",description:"Goal/prompt for the session",env:"DUO_WORKFLOW_GOAL",mandatory:!0,zod:u.string()},aiContextItems:{flags:"--ai-context-items <contextItems>",description:"JSON encoded array of additional context items",env:"DUO_WORKFLOW_ADDITIONAL_CONTEXT_CONTENT",parse:(A)=>iY0(A),zod:u.custom().optional()},...aY0};var dq4=u.object(WV(Gr)),cq4=u.object({name:u.literal("tui"),...WV(hEA)}),pq4=u.object({name:u.literal("run"),...WV(mEA)}),lq4=u.discriminatedUnion("name",[cq4,pq4]),H9=nY0.createInterfaceId("ParsedCliInput");function CmA(A,Q){let B=dq4.parse(A),D=lq4.parse({name:Q,...A});return{...B,command:D}}var oY0=SA(T1(),1);class uEA{#A;constructor(A){this.#A=A}get logLevel(){return this.#A}}class Ur extends uEA{constructor(A){super(A.logLevel)}}Ur=Q1([oY0.Injectable($d,[H9])],Ur);import{existsSync as nq4,mkdirSync as oq4,writeFileSync as rq4}from"node:fs";import{appendFile as sq4}from"node:fs/promises";import{join as tq4,sep as eq4}from"node:path";var YmA=SA(sY0(),1);class JmA extends Error{name="TimeoutError";constructor(A,Q){super(A,Q);Error.captureStackTrace?.(this,JmA)}}var tY0=(A)=>A.reason??new DOMException("This operation was aborted.","AbortError");function GmA(A,Q){let{milliseconds:B,fallback:D,message:E,customTimers:I={setTimeout,clearTimeout},signal:C}=Q,F,Y,G=new Promise((X,z)=>{if(typeof B!=="number"||Math.sign(B)!==1)throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${B}\``);if(C?.aborted){z(tY0(C));return}if(C)Y=()=>{z(tY0(C))},C.addEventListener("abort",Y,{once:!0});if(A.then(X,z),B===Number.POSITIVE_INFINITY)return;let U=new JmA;F=I.setTimeout.call(void 0,()=>{if(D){try{X(D())}catch(Z){z(Z)}return}if(typeof A.cancel==="function")A.cancel();if(E===!1)X();else if(E instanceof Error)z(E);else U.message=E??`Promise timed out after ${B} milliseconds`,z(U)},B)}).finally(()=>{if(G.clear(),Y&&C)C.removeEventListener("abort",Y)});return G.clear=()=>{I.clearTimeout.call(void 0,F),F=void 0},G}function UmA(A,Q,B){let D=0,E=A.length;while(E>0){let I=Math.trunc(E/2),C=D+I;if(B(A[C],Q)<=0)D=++C,E-=I+1;else E=I}return D}class cEA{#A=[];enqueue(A,Q){let{priority:B=0,id:D}=Q??{},E={priority:B,id:D,run:A};if(this.size===0||this.#A[this.size-1].priority>=B){this.#A.push(E);return}let I=UmA(this.#A,E,(C,F)=>F.priority-C.priority);this.#A.splice(I,0,E)}setPriority(A,Q){let B=this.#A.findIndex((E)=>E.id===A);if(B===-1)throw ReferenceError(`No promise function with the id "${A}" exists in the queue.`);let[D]=this.#A.splice(B,1);this.enqueue(D.run,{priority:Q,id:A})}dequeue(){return this.#A.shift()?.run}filter(A){return this.#A.filter((Q)=>Q.priority===A.priority).map((Q)=>Q.run)}get size(){return this.#A.length}}class pEA extends YmA.default{#A;#Q;#B=0;#D;#E=!1;#I=!1;#C;#F=0;#Y=0;#J;#G;#U;#z;#X=0;#Z;#H;#K=1n;#w=new Map;timeout;constructor(A){super();if(A={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:cEA,...A},!(typeof A.intervalCap==="number"&&A.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${A.intervalCap?.toString()??""}\` (${typeof A.intervalCap})`);if(A.interval===void 0||!(Number.isFinite(A.interval)&&A.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${A.interval?.toString()??""}\` (${typeof A.interval})`);if(this.#A=A.carryoverIntervalCount??A.carryoverConcurrencyCount??!1,this.#Q=A.intervalCap===Number.POSITIVE_INFINITY||A.interval===0,this.#D=A.intervalCap,this.#C=A.interval,this.#U=new A.queueClass,this.#z=A.queueClass,this.concurrency=A.concurrency,A.timeout!==void 0&&!(Number.isFinite(A.timeout)&&A.timeout>0))throw TypeError(`Expected \`timeout\` to be a positive finite number, got \`${A.timeout}\` (${typeof A.timeout})`);this.timeout=A.timeout,this.#H=A.autoStart===!1,this.#v()}get#V(){return this.#Q||this.#B<this.#D}get#W(){return this.#X<this.#Z}#$(){if(this.#X--,this.#X===0)this.emit("pendingZero");this.#R(),this.emit("next")}#N(){this.#T(),this.#L(),this.#G=void 0}get#q(){let A=Date.now();if(this.#J===void 0){let Q=this.#F-A;if(Q<0){if(this.#Y>0){let B=A-this.#Y;if(B<this.#C)return this.#M(this.#C-B),!0}this.#B=this.#A?this.#X:0}else return this.#M(Q),!0}return!1}#M(A){if(this.#G!==void 0)return;this.#G=setTimeout(()=>{this.#N()},A)}#O(){if(this.#J)clearInterval(this.#J),this.#J=void 0}#S(){if(this.#G)clearTimeout(this.#G),this.#G=void 0}#R(){if(this.#U.size===0){if(this.#O(),this.emit("empty"),this.#X===0)this.#S(),this.emit("idle");return!1}let A=!1;if(!this.#H){let Q=!this.#q;if(this.#V&&this.#W){let B=this.#U.dequeue();if(!this.#Q)this.#B++,this.#P();if(this.emit("active"),this.#Y=Date.now(),B(),Q)this.#L();A=!0}}return A}#L(){if(this.#Q||this.#J!==void 0)return;this.#J=setInterval(()=>{this.#T()},this.#C),this.#F=Date.now()+this.#C}#T(){if(this.#B===0&&this.#X===0&&this.#J)this.#O();this.#B=this.#A?this.#X:0,this.#j(),this.#P()}#j(){while(this.#R());}get concurrency(){return this.#Z}set concurrency(A){if(!(typeof A==="number"&&A>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${A}\` (${typeof A})`);this.#Z=A,this.#j()}async#y(A){return new Promise((Q,B)=>{A.addEventListener("abort",()=>{B(A.reason)},{once:!0})})}setPriority(A,Q){if(typeof Q!=="number"||!Number.isFinite(Q))throw TypeError(`Expected \`priority\` to be a finite number, got \`${Q}\` (${typeof Q})`);this.#U.setPriority(A,Q)}async add(A,Q={}){return Q.id??=(this.#K++).toString(),Q={timeout:this.timeout,...Q},new Promise((B,D)=>{let E=Symbol(`task-${Q.id}`);this.#U.enqueue(async()=>{this.#X++,this.#w.set(E,{id:Q.id,priority:Q.priority??0,startTime:Date.now(),timeout:Q.timeout});try{try{Q.signal?.throwIfAborted()}catch(F){if(!this.#Q)this.#B--;throw this.#w.delete(E),F}let I=A({signal:Q.signal});if(Q.timeout)I=GmA(Promise.resolve(I),{milliseconds:Q.timeout,message:`Task timed out after ${Q.timeout}ms (queue has ${this.#X} running, ${this.#U.size} waiting)`});if(Q.signal)I=Promise.race([I,this.#y(Q.signal)]);let C=await I;B(C),this.emit("completed",C)}catch(I){D(I),this.emit("error",I)}finally{this.#w.delete(E),queueMicrotask(()=>{this.#$()})}},Q),this.emit("add"),this.#R()})}async addAll(A,Q){return Promise.all(A.map(async(B)=>this.add(B,Q)))}start(){if(!this.#H)return this;return this.#H=!1,this.#j(),this}pause(){this.#H=!0}clear(){this.#U=new this.#z,this.#k()}async onEmpty(){if(this.#U.size===0)return;await this.#_("empty")}async onSizeLessThan(A){if(this.#U.size<A)return;await this.#_("next",()=>this.#U.size<A)}async onIdle(){if(this.#X===0&&this.#U.size===0)return;await this.#_("idle")}async onPendingZero(){if(this.#X===0)return;await this.#_("pendingZero")}async onRateLimit(){if(this.isRateLimited)return;await this.#_("rateLimit")}async onRateLimitCleared(){if(!this.isRateLimited)return;await this.#_("rateLimitCleared")}async onError(){return new Promise((A,Q)=>{let B=(D)=>{this.off("error",B),Q(D)};this.on("error",B)})}async#_(A,Q){return new Promise((B)=>{let D=()=>{if(Q&&!Q())return;this.off(A,D),B()};this.on(A,D)})}get size(){return this.#U.size}sizeBy(A){return this.#U.filter(A).length}get pending(){return this.#X}get isPaused(){return this.#H}#v(){if(this.#Q)return;this.on("add",()=>{if(this.#U.size>0)this.#P()}),this.on("next",()=>{this.#P()})}#P(){if(this.#Q||this.#I)return;this.#I=!0,queueMicrotask(()=>{this.#I=!1,this.#k()})}#k(){let A=this.#E,Q=!this.#Q&&this.#B>=this.#D&&this.#U.size>0;if(Q!==A)this.#E=Q,this.emit(Q?"rateLimit":"rateLimitCleared")}get isRateLimited(){return this.#E}get isSaturated(){return this.#X===this.#Z&&this.#U.size>0||this.isRateLimited&&this.#U.size>0}get runningTasks(){return[...this.#w.values()].map((A)=>({...A}))}}var eY0=SA(T1(),1);class fT{#A;#Q=new pEA({concurrency:1});constructor(){this.#A=this.#D(),this.#E(),setImmediate(()=>fJ1())}write(A){if(!this.#A){console.error(A);return}let Q=this.#A;D9(this.#Q.add(async()=>{try{await sq4(Q,`${A}
1593
1593
  `)}catch(B){console.error(`Failed to write to log file: ${Q}`,B),console.error(A)}}))}#B(){let Q=process.cwd().split(eq4).slice(-3).join("-"),B=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19);return`duo-cli-log-${Q}-${B}.log`}#D(){try{let A=Ip();if(!nq4(A))oq4(A,{recursive:!0});let Q=tq4(A,this.#B());return rq4(Q,""),Q}catch(A){console.error("Failed to create log file. Logs will be printed to stderr.",A);return}}#E(){process.on("exit",()=>{if(!this.#A)return;console.error(`CLI log file: ${this.#A}`)})}flush(){return this.#Q.onIdle()}}fT=Q1([eY0.Injectable(hw,[])],fT);var AO4=u.object({gitlabBaseUrl:u.string().optional(),gitlabAuthToken:u.string().optional()}),AJ0="duo-cli-config",zr=lEA.createInterfaceId("ConfigurationController");class Cx{#A;#Q;#B;#D;constructor(A,Q,B,D){this.#A=A,this.#B=B,this.#Q=Q,this.#D=D}async saveConfig(A){try{let{configurationEntries:Q}=A,B={gitlabAuthToken:"",gitlabBaseUrl:""};for(let D of Q){let E=D.key;if(E in B)B[E]=D.value}return this.#A=B,await this.#Q.set(AJ0,B),x4()}catch(Q){return this.#B.error("Failed to save configuration:",Q),k6(Q)}}async validateToken(A,Q){try{let B=new wc(this.#B,this.#D,void 0,A,Q),D=await R0A(B,Q);if(D.valid)return x4();return k6(Error(D.message))}catch(B){return this.#B.error("Token validation request failed:",B),k6(B instanceof Error?B:Error(String(B)))}}exit(){process.exit(0)}getDuoConfiguration(){return{gitlabBaseUrl:this.#A.gitlabBaseUrl||"https://gitlab.com",gitlabAuthToken:this.#A.gitlabAuthToken||""}}async initialize(){let A=await this.#Q.get(AJ0),Q=AO4.safeParse(A);if(Q.success){let B=this.#E(this.#A);this.#A={...Q.data,...B}}}isMissingConfiguration(){let{gitlabAuthToken:A,gitlabBaseUrl:Q}=this.getDuoConfiguration();return!A||!Q}getConfigurationModel(){return{configurationEntries:[{key:"gitlabBaseUrl",value:this.#A.gitlabBaseUrl??"",...Ix.gitlabBaseUrl},{key:"gitlabAuthToken",value:this.#A.gitlabAuthToken??"",...Ix.gitlabAuthToken}],configFilePath:this.#Q.getStoragePath()}}#E(A){return Object.fromEntries(Object.entries(A).filter(([,Q])=>Q!=null&&Q!==""))}}Cx=Q1([lEA.Injectable(zr,[H9,kk,q1,O7])],Cx);var QJ0=async(A={})=>{let Q=new fT,B=new uEA("info"),D=new mw(Q,B),E=new FZ(D),I=new bT(D);await I.initialize();let C=new Cx(A,E,D,I);return await C.initialize(),C};import{spawnSync as QO4}from"child_process";var BO4=u.object({type:u.literal("oauth2"),token:u.string(),expiry_timestamp:u.string().datetime()}),DO4=u.object({type:u.literal("pat"),token:u.string()}),EO4=u.object({type:u.literal("job-token"),token:u.string()}),IO4=u.discriminatedUnion("type",[BO4,DO4,EO4]),CO4=u.object({type:u.literal("success"),token:IO4,instance_url:u.string().url()}),FO4=u.object({type:u.literal("error"),message:u.string()}),YO4=u.discriminatedUnion("type",[CO4,FO4]);function BJ0(A,Q){try{A.info("Attempting to fetch credentials from glab credential-helper");let B=QO4("glab",["auth","credential-helper"],{encoding:"utf-8",timeout:1000,cwd:Q});if(B.error){if("code"in B.error&&B.error.code==="ENOENT")A.info("glab is not installed or not found in PATH");else A.warn("glab credential-helper failed:",B.error);return null}if(B.status!==0)return A.warn(`glab credential-helper exited with status ${B.status}`),null;if(!B.stdout||B.stdout.trim()==="")return A.warn("glab credential-helper returned empty response"),null;if(B.stdout.includes("glab auth <command>"))return A.info("glab credential-helper command not available (glab version may be too old, run `glab --version` to check — requires 1.85.2 or higher)"),null;let D=GO4(B.stdout);if(!D)return A.warn("glab credential-helper returned unparseable response"),null;if(D.type==="error")return A.info(`glab credential-helper returned error: ${D.message}`),null;return A.info("Successfully retrieved credentials from glab credential-helper"),JO4(A,D.token,D.instance_url)}catch(B){return A.warn("Failed to get credentials from glab credential-helper:",B),null}}function JO4(A,Q,B){switch(Q.type){case"oauth2":return{type:"oauth",token:Q.token,expiresAt:new Date(Q.expiry_timestamp),instanceUrl:B};case"pat":return{type:"pat",token:Q.token,instanceUrl:B};case"job-token":return A.warn("glab returned job-token credential type, treating as pat"),{type:"pat",token:Q.token,instanceUrl:B};default:throw Error(`Unknown glab token type: ${Q.type}`)}}function GO4(A){try{let Q=JSON.parse(A.trim());return YO4.parse(Q)}catch{return null}}var _E=iEA.createInterfaceId("CredentialProvider"),UO4=30;class Zr{#A;#Q;#B;#D=null;constructor(A,Q,B){this.#A=A,this.#Q=L1(Q,"[CredentialProvider]"),this.#B=B.cwd}async getCredentials(){let A=this.#A.getDuoConfiguration();if(A.gitlabAuthToken)return this.#Q.debug("Using static token from configuration, skipping glab credential helper"),{token:A.gitlabAuthToken,baseUrl:A.gitlabBaseUrl};return this.#E(A.gitlabBaseUrl)}#E(A){if(this.#D&&!this.#I(this.#D))return{token:this.#D.token,baseUrl:this.#D.instanceUrl};this.#Q.debug("Fetching fresh glab credential");let Q=BJ0(this.#Q,this.#B);if(!Q)return this.#Q.warn("No credential available from glab"),{token:"",baseUrl:A};return this.#D=Q,{token:Q.token,baseUrl:Q.instanceUrl}}#I(A){if(A.type!=="oauth")return!1;let Q=UO4*1000;return A.expiresAt.getTime()-Q<=Date.now()}}Zr=Q1([iEA.Injectable(_E,[zr,q1,H9])],Zr);var Kr="Duo CLI",DJ0="GitLab";function IJ0(A){return A&&"initialize"in A&&typeof A.initialize==="function"}class NV{#A;#Q;#B;#D;#E="";#I="";#C=new K7;#F;#Y;constructor(A,Q,B,D){this.#D=A,this.#Q=L1(Q,"[CliApiService]"),this.#B=B,D.onConfigChange(()=>{B.updateAgentOptions({ignoreCertificateErrors:D.get("ignoreCertificateErrors")??!1,...D.get("httpAgentOptions")??{}})})}async initialize(){this.#Q.debug("Starting API initialization"),await this.#G();let A;try{A=await R0A(this.#J(),this.#I)}catch{return this.#C.fire({isInValidState:!1,validationMessage:"Failed to check token validity"}),k6(Error("Failed to check token validity"))}if(!A.valid){let D=`${A.message} Reason: ${A.reason}
1594
- Run 'duo config edit' to update your token.`;return this.#C.fire({isInValidState:!1,validationMessage:D}),k6(Error(D))}let Q;try{Q=(await this.#J().fetchFromApi(Md)).version}catch{return this.#C.fire({isInValidState:!1,validationMessage:"Failed to fetch GitLab instance version"}),k6(Error("Failed to fetch GitLab instance version"))}let B={instanceVersion:Q,instanceUrl:new URL(this.#E)};return this.#F=B,this.#Y=A.tokenInfo,this.#C.fire({isInValidState:!0,instanceInfo:B,tokenInfo:A.tokenInfo}),this.#Q.debug("API initialization complete, onApiReconfigured event fired"),x4(void 0)}get instanceInfo(){return this.#F}get tokenInfo(){return this.#Y}async fetchFromApi(A){return await this.#U(),this.#J().fetchFromApi(A)}async fetchFromApiRaw(A){return await this.#U(),this.#J().fetchFromApiRaw(A)}fetchOperation(A){return async(Q)=>{return await this.#U(),this.#J().fetchOperation(A)(Q)}}connectToCable(){throw Error("Method not implemented.")}onApiReconfigured=this.#C.event;getSimpleClient(){return this.#J()}#J(){if(!this.#A)throw Error("CliApiService not initialized. Call initialize() first.");return this.#A}async#G(){let A=await this.#D.getCredentials();this.#I=A.token,this.#E=A.baseUrl,this.#A=new wc(this.#Q,this.#B,{name:Kr,version:e8()},this.#E,this.#I)}async#U(){let A=await this.#D.getCredentials();if(A.token!==this.#I||A.baseUrl!==this.#E)this.#Q.debug("Credentials changed, refreshing API client"),await this.#G()}}NV=Q1([EJ0.Injectable(f4,[_E,q1,O7,w4])],NV);class MV{#A;#Q;#B;#D;#E;#I;#C;#F;#Y;constructor(A,Q,B,D,E,I,C,F,Y){this.#A=L1(A,"[CliInitializationService]"),this.#Q=Q,this.#B=B,this.#D=D,this.#E=E,this.#I=I,this.#C=C,this.#F=F,this.#Y=Y}async initialize(){this.#A.debug("Starting CLI common initialization"),this.#J();let[,A]=await Promise.all([this.#G(),this.#U()]),[Q,B]=await Promise.all([this.#z(),this.#X()]);return D9(this.#F.initialize()),{existingSessionId:this.#Z(),username:B,systemContext:Q,workspaceFolder:A.workspaceFolder,gitlabRemote:A.gitlabRemote}}#J(){let A=process.env.NODE_TLS_REJECT_UNAUTHORIZED==="0";this.#Q.set("ignoreCertificateErrors",A);let Q=process.env.HTTP_PROXY??process.env.http_proxy,B=process.env.HTTPS_PROXY??process.env.https_proxy;this.#A.debug(`Network/TLS configuration: ${JSON.stringify({ignoreCertificateErrors:A,NODE_OPTIONS:process.env.NODE_OPTIONS??process.env.NODE_OPTIONS??"(not set)",NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED??"(not set)",NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS??"(not set)",HTTP_PROXY:Q?FBA(Q):"(not set)",HTTPS_PROXY:B?FBA(B):"(not set)",NO_PROXY:process.env.NO_PROXY??process.env.no_proxy??"(not set)"},null,4)}`)}async#G(){if(IJ0(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#U(){let{cwd:A}=this.#I;this.#Q.set("cwd",JI.file(A).toString());let Q;try{Q=await this.#D.findRepositoryRoot(A)}catch{Q=A}this.#Q.set("workspaceFolders",[{uri:JI.file(Q).toString(),name:"repository root"}]),this.#Q.set("gitHttpUser",this.#I.gitHttpUser),this.#Q.set("gitHttpPassword",this.#I.gitHttpPassword),this.#Q.set("gitUserEmail",this.#I.gitUserEmail),this.#Q.set("gitUserName",this.#I.gitUserName),this.#Q.set("gitAuthorEmail",this.#I.gitAuthorEmail),this.#Q.set("gitAuthorName",this.#I.gitAuthorName),this.#Q.set("clientInfo.name",Kr),this.#Q.set("clientInfo.version",e8()),this.#Q.set("telemetry.enabled",this.#I.telemetryEnabled),this.#Q.set("telemetry.ide",{name:Kr,version:e8(),vendor:DJ0});let B=await this.#D.getMatchingRepository(A,Q),D=await this.#Y.getCredentials(),E=B?await Ir1(B,D.baseUrl):void 0;if(E?.namespaceWithPath)this.#Q.set("projectPath",E.namespaceWithPath);return{workspaceFolder:Q,gitlabRemote:E}}async#z(){try{await this.#E.precalculate();let A=await this.#E.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#X(){try{return`@${(await this.#C.getUser()).username}`}catch(A){return this.#A.error("Error getting username",A),""}}#Z(){let{command:A}=this.#I;if(A.name==="run"||A.name==="tui")return A.existingSessionId;return}}MV=Q1([aEA.Service({dependencies:[q1,w4,f4,M2,AV,H9,rw,r3A,_E],lifetime:aEA.ServiceLifetime.Singleton})],MV);var CJ0=SA(T1(),1);var M52=CJ0.createInterfaceId("CliBackend");var FJ0=SA(T1(),1),Fx=FJ0.createInterfaceId("RuntimeContext");function YJ0(A,Q,B,D,E){let I={...A,cliVersion:Q.cliVersion,gitlabBaseUrl:B.baseUrl,...E};return D.redactSecrets(JSON.stringify(I,null,4),"cli-run-config")}var Yx=SA(T1(),1);var XmA=Yx.createInterfaceId("CliContextManager");class wr extends svA{#A;constructor(A,Q,B,D,E){super(A,Q,B,D,E);this.#A=L1(A,"[CliContextManager]")}async syncWithTextBuffer(A){let Q=this.#Q(A),B=new Set(Q),E=(await this.getSelectedContextItems()).map((I)=>{let C=I.metadata.secondaryText;if(B.has(C))return;return{item:I,itemReference:C}}).filter((I)=>I!==void 0);await Promise.all(E.map(({item:I,itemReference:C})=>{return this.#A.debug(`Removing item no longer in text: ${C}`),this.removeSelectedContextItem(I)}))}#Q(A){let Q=[];for(let B of Wl){let D=0;while(D<A.length)if(A[D]===B.activationChar){let E=A.slice(D+1);if(E.startsWith('"')){let I=E.indexOf('"',1);if(I!==-1){let C=E.slice(1,I);Q.push(`${B.activationChar}"${C}"`),D+=I+2}else D++}else{let I=E.search(/\s/),C=I===-1?E:E.slice(0,I);if(C.length>0)Q.push(`${B.activationChar}${C}`),D+=C.length+1;else D++}}else D++}return Q}}wr=Q1([Yx.Injectable(XmA,[q1,w4,BkA,Yx.collection(y3A),_b])],wr);var Gx=SA(T1(),1);var JJ0=SA(T1(),1);var xT=JJ0.createInterfaceId("SlashCommandHandler");var nEA=Gx.createInterfaceId("SlashCommandService");class Jx{#A;#Q=new Map;#B=new Map;constructor(A,Q){this.#A=L1(A,"[SlashCommandService]"),this.#D(Q)}#D(A){A.forEach((Q)=>{this.#Q.set(Q.command.name,Q.command),this.#B.set(Q.command.action,Q),this.#A.debug(`Registered slash command: ${Q.command.name} (action: ${Q.command.action})`)})}getCommands(){return Array.from(this.#Q.values())}isCommand(A){let Q=A.trim();if(!Q.startsWith("/"))return!1;let D=Q.split(/\s+/)[0];return this.#Q.has(D)}async execute(A,Q){let D=A.trim().split(/\s+/),E=D[0],I=D.slice(1),C=this.#Q.get(E);if(!C)throw Error(`Unknown command: ${E}`);this.#A.info(`Executing slash command: ${C.name} (action: ${C.action})`);let F=this.#B.get(C.action);if(!F)throw Error(`No handler registered for action: ${C.action}`);await F.execute(Q,I.length>0?I:void 0)}}Jx=Q1([Gx.Injectable(nEA,[q1,Gx.collection(xT)])],Jx);class oEA{sessionId;#A;#Q;#B=[];#D=!1;#E;#I;#C=new Map;constructor(A,Q,B){this.sessionId=A,this.#A=Q,this.#Q=L1(B,`[Session: ${A}]`)}get elements(){return this.#B}get isLoading(){return this.#D}rehydrateFromEvents(A){for(let Q of A)this.#K(this.#Y(Q));this.#B=this.#B.map((Q)=>Q.type==="message"?{...Q,isComplete:!0}:Q),this.#H()}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}addError(A,Q){let B={id:`error-${Date.now()}`,type:"error",error:A,timestamp:Q??Date.now()};return this.#B=[...this.#B,B],B}async*sendMessageStream(A){this.#D=!0,this.#E=new AbortController;try{let Q=this.#A.sendMessageStream(A,this.#E.signal),B=this.#F(Q);yield*this.#U(B)}catch(Q){this.#Q.error("Error in message streaming:",Q),yield this.addError("Sorry, there was an error processing your message. Please try again.")}finally{this.#H()}}async*#F(A){for await(let Q of A)yield*this.#G(Q)}cancelStream(){this.#E?.abort()}async preinitialize(){await this.#A.preinitialize?.()}*#Y(A){if(A.type==="USER_MESSAGE")yield*this.#J(A);else yield*this.#G(A)}*#J(A){let Q={id:A.messageId,type:"message",role:"user",content:A.content,timestamp:A.timestamp,isComplete:!0};this.#B=[...this.#B,Q],yield Q}*#G(A){switch(A.type){case"TEXT_CHUNK":{if(!this.#I||this.#I.id!==A.messageId)this.#I={id:A.messageId,type:"message",role:"assistant",content:A.content,timestamp:A.timestamp,isComplete:!1},this.#B=[...this.#B,this.#I];else this.#I.content+=A.content,this.#Z(this.#I);yield{...this.#I};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.#X(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.#X(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.#X(B),this.#C.delete(A.toolId),yield B}break}case"ERROR":{this.#Q.error(`Agent error: ${A.message}`),yield this.addError(A.message,A.timestamp);break}default:this.#Q.warn(`Unknown agent event type: ${JSON.stringify(A)}`);break}}async*#U(A){let Q;for await(let B of A){if(Q&&this.#V(B,Q))this.#z(Q.id),yield{...Q,isComplete:!0},Q=void 0;if(this.#w(B))Q=B;yield B}if(Q)this.#z(Q.id),yield{...Q,isComplete:!0}}#z(A){if(!A)return;this.#B=this.#B.map((Q)=>Q.id===A?{...Q,isComplete:!0}:Q)}#X(A){let Q=this.#B.findIndex((D)=>D.type==="tool"&&D.id===A.id);if(Q<0){this.#B=[...this.#B,A];return}let B=[...this.#B];B[Q]=A,this.#B=B}#Z(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)]}#H(){this.#D=!1,this.#I=void 0,this.#C.clear(),this.#E=void 0}#K(A){let Q=A.next();while(!Q.done)Q=A.next()}#w(A){return A.type==="message"&&A.role==="assistant"&&!A.isComplete}#V(A,Q){return A.type!=="message"||A.id!==Q.id}}var UJ0=SA(T1(),1),hT=UJ0.createInterfaceId("SessionDataService");var uM=SA(T1(),1);var XJ0=SA(T1(),1),Ux=XJ0.createInterfaceId("BackendFactory");var EK=uM.createInterfaceId("SessionManager");class Xx{#A=new Map;#Q;#B;#D;#E;constructor(A,Q,B){this.#E=L1(A,"[SessionManager]"),this.#B=Q,this.#D=B}async createSession(A){let Q=this.#B.create(),{sessionId:B,sessionRejectionReason:D}=await Q.initialize(A),E=new oEA(B,Q,this.#E);return this.#A.set(E.sessionId,E),this.#Q=E.sessionId,this.#E.debug(`Created session: ${E.sessionId}`),{session:E,sessionDetails:{sessionRejectionReason:D}}}getActiveSession(){if(this.#Q===void 0)return;return this.#A.get(this.#Q)}async getSessionHistory(A){let Q=A.search?.trim()||void 0;return this.#D.getSessionHistory({...A,search:Q})}async switchToSession(A){this.#I();let{session:Q}=await this.createSession(A),B=await this.#D.getSessionMessages(A);if(B.length>0)Q.rehydrateFromEvents(B);return Q}#I(){let A=this.getActiveSession();if(A?.isLoading)this.#E.info(`Cancelling active session "${A.sessionId}" before switching session.`),A.cancelStream()}}Xx=Q1([uM.Implements(EK),uM.Service({dependencies:[q1,Ux,hT],lifetime:uM.ServiceLifetime.Singleton})],Xx);var zJ0=SA(BD(),1),dM=SA(T1(),1);var Zx=dM.createInterfaceId("SessionsHistoryController");class zx{#A;#Q;#B;constructor(A,Q,B){this.#A=L1(A,"[SessionsHistoryController]"),this.#Q=Q,this.#B=B}async openSearch(A){this.#A.info("Opening session history search"),A.mutateState((Q)=>({...Q,input:{inputType:V2.SESSIONS_SEARCH,searchQuery:"",sessions:[],selectedIndex:0,isLoading:!0,hasNextPage:!1}}));try{let{items:Q,pageInfo:B}=await this.#Q.getSessionHistory({});A.mutateState((D)=>{if(D.input.inputType!==V2.SESSIONS_SEARCH)return D;return{...D,input:{...D.input,sessions:Q,isLoading:!1,hasNextPage:B.hasNextPage,endCursor:B.endCursor}}})}catch(Q){this.#A.error("Failed to fetch session history",Q),A.mutateState((B)=>{if(B.input.inputType!==V2.SESSIONS_SEARCH)return B;return{...B,input:{inputType:V2.SESSIONS_SEARCH,searchQuery:"",sessions:[],selectedIndex:0,isLoading:!1,hasNextPage:!1}}}),A.showError("Failed to load session history. Please try again.")}}cancelSearch(A){this.#D.cancel(),A.mutateState((Q)=>({...Q,input:hU}))}searchQueryChanged(A,Q){A.mutateState((B)=>{if(B.input.inputType!==V2.SESSIONS_SEARCH)return B;return{...B,input:{...B.input,searchQuery:Q,selectedIndex:0}}}),this.#D(A,Q)}async selectSession(A,Q){this.#A.info(`Switching to session: ${Q}`),A.mutateState((B)=>({...B,input:hU,isLoading:!0}));try{await this.#Q.switchToSession(Q),A.syncState()}catch(B){A.mutateState((E)=>({...E,isLoading:!1})),this.#B.handleError("Failed to switch session",B);let D=B instanceof Error?B.message:"Failed to load session";A.showError(D)}}async loadMore(A){let Q;if(A.mutateState((B)=>{if(B.input.inputType!==V2.SESSIONS_SEARCH)return B;if(!B.input.hasNextPage||B.input.isLoading)return B;return Q=B.input,{...B,input:{...B.input,isLoading:!0}}}),!Q)return;try{let{items:B,pageInfo:D}=await this.#Q.getSessionHistory({afterCursor:Q.endCursor,search:Q.searchQuery});A.mutateState((E)=>{if(E.input.inputType!==V2.SESSIONS_SEARCH)return E;return{...E,input:{...E.input,sessions:[...E.input.sessions,...B],hasNextPage:D.hasNextPage,endCursor:D.endCursor,isLoading:!1}}})}catch(B){this.#A.error("Failed to load more sessions",B),A.mutateState((D)=>{if(D.input.inputType!==V2.SESSIONS_SEARCH)return D;return{...D,input:{...D.input,isLoading:!1}}})}}#D=zJ0.debounce((A,Q)=>{D9(this.#E(A,Q))},300);async#E(A,Q){A.mutateState((B)=>{if(B.input.inputType!==V2.SESSIONS_SEARCH)return B;return{...B,input:{...B.input,isLoading:!0}}});try{let{items:B,pageInfo:D}=await this.#Q.getSessionHistory({search:Q});A.mutateState((E)=>{if(E.input.inputType!==V2.SESSIONS_SEARCH)return E;if(E.input.searchQuery!==Q)return E;return{...E,input:{...E.input,sessions:B,hasNextPage:D.hasNextPage,endCursor:D.endCursor,isLoading:!1,selectedIndex:0}}})}catch(B){this.#A.error("Failed to search sessions",B),A.mutateState((D)=>{if(D.input.inputType!==V2.SESSIONS_SEARCH)return D;return{...D,input:{...D.input,isLoading:!1}}})}}}zx=Q1([dM.Implements(Zx),dM.Service({dependencies:[q1,EK,SF],lifetime:dM.ServiceLifetime.Singleton})],zx);class ZmA{#A;#Q;constructor(){this.#A={...cNA}}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 KmA{#A;#Q=[];#B=-1;#D=100;#E;#I;constructor(A){this.#A=L1(A,"[PromptHistory]")}async load(A,Q){this.#E=A,this.#I=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.#E||!this.#I)return;try{await this.#E.set(this.#I,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!==V2.TEXT)return;return{...A,lines:Q.split(`
1594
+ Run 'duo config edit' to update your token.`;return this.#C.fire({isInValidState:!1,validationMessage:D}),k6(Error(D))}let Q;try{Q=(await this.#J().fetchFromApi(Md)).version}catch{return this.#C.fire({isInValidState:!1,validationMessage:"Failed to fetch GitLab instance version"}),k6(Error("Failed to fetch GitLab instance version"))}let B={instanceVersion:Q,instanceUrl:new URL(this.#E)};return this.#F=B,this.#Y=A.tokenInfo,this.#C.fire({isInValidState:!0,instanceInfo:B,tokenInfo:A.tokenInfo}),this.#Q.debug("API initialization complete, onApiReconfigured event fired"),x4(void 0)}get instanceInfo(){return this.#F}get tokenInfo(){return this.#Y}async fetchFromApi(A){return await this.#U(),this.#J().fetchFromApi(A)}async fetchFromApiRaw(A){return await this.#U(),this.#J().fetchFromApiRaw(A)}fetchOperation(A){return async(Q)=>{return await this.#U(),this.#J().fetchOperation(A)(Q)}}connectToCable(){throw Error("Method not implemented.")}onApiReconfigured=this.#C.event;getSimpleClient(){return this.#J()}#J(){if(!this.#A)throw Error("CliApiService not initialized. Call initialize() first.");return this.#A}async#G(){let A=await this.#D.getCredentials();this.#I=A.token,this.#E=A.baseUrl,this.#A=new wc(this.#Q,this.#B,{name:Kr,version:e8()},this.#E,this.#I)}async#U(){let A=await this.#D.getCredentials();if(A.token!==this.#I||A.baseUrl!==this.#E)this.#Q.debug("Credentials changed, refreshing API client"),await this.#G()}}NV=Q1([EJ0.Injectable(f4,[_E,q1,O7,w4])],NV);class MV{#A;#Q;#B;#D;#E;#I;#C;#F;#Y;constructor(A,Q,B,D,E,I,C,F,Y){this.#A=L1(A,"[CliInitializationService]"),this.#Q=Q,this.#B=B,this.#D=D,this.#E=E,this.#I=I,this.#C=C,this.#F=F,this.#Y=Y}async initialize(){this.#A.debug("Starting CLI common initialization"),this.#J();let[,A]=await Promise.all([this.#G(),this.#U()]),[Q,B]=await Promise.all([this.#z(),this.#X()]);return D9(this.#F.initialize()),{existingSessionId:this.#Z(),username:B,systemContext:Q,workspaceFolder:A.workspaceFolder,gitlabRemote:A.gitlabRemote}}#J(){let A=process.env.NODE_TLS_REJECT_UNAUTHORIZED==="0";this.#Q.set("ignoreCertificateErrors",A);let Q=process.env.HTTP_PROXY??process.env.http_proxy,B=process.env.HTTPS_PROXY??process.env.https_proxy;this.#A.debug(`Network/TLS configuration: ${JSON.stringify({ignoreCertificateErrors:A,NODE_OPTIONS:process.env.NODE_OPTIONS??process.env.NODE_OPTIONS??"(not set)",NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED??"(not set)",NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS??"(not set)",HTTP_PROXY:Q?FBA(Q):"(not set)",HTTPS_PROXY:B?FBA(B):"(not set)",NO_PROXY:process.env.NO_PROXY??process.env.no_proxy??"(not set)"},null,4)}`)}async#G(){if(IJ0(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#U(){let{cwd:A}=this.#I;this.#Q.set("cwd",JI.file(A).toString());let Q;try{Q=await this.#D.findRepositoryRoot(A)}catch{Q=A}this.#Q.set("workspaceFolders",[{uri:JI.file(Q).toString(),name:"repository root"}]),this.#Q.set("gitHttpUser",this.#I.gitHttpUser),this.#Q.set("gitHttpPassword",this.#I.gitHttpPassword),this.#Q.set("gitUserEmail",this.#I.gitUserEmail),this.#Q.set("gitUserName",this.#I.gitUserName),this.#Q.set("gitAuthorEmail",this.#I.gitAuthorEmail),this.#Q.set("gitAuthorName",this.#I.gitAuthorName),this.#Q.set("clientInfo.name",Kr),this.#Q.set("clientInfo.version",e8()),this.#Q.set("telemetry.enabled",this.#I.telemetryEnabled),this.#Q.set("telemetry.ide",{name:Kr,version:e8(),vendor:DJ0});let B=await this.#D.getMatchingRepository(A,Q),D=await this.#Y.getCredentials(),E=B?await Ir1(B,D.baseUrl):void 0;if(E?.namespaceWithPath)this.#Q.set("projectPath",E.namespaceWithPath);return{workspaceFolder:Q,gitlabRemote:E}}async#z(){try{await this.#E.precalculate();let A=await this.#E.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#X(){try{return`@${(await this.#C.getUser()).username}`}catch(A){return this.#A.error("Error getting username",A),""}}#Z(){let{command:A}=this.#I;if(A.name==="run"||A.name==="tui")return A.existingSessionId;return}}MV=Q1([aEA.Service({dependencies:[q1,w4,f4,M2,AV,H9,rw,r3A,_E],lifetime:aEA.ServiceLifetime.Singleton})],MV);var CJ0=SA(T1(),1);var M52=CJ0.createInterfaceId("CliBackend");var FJ0=SA(T1(),1),Fx=FJ0.createInterfaceId("RuntimeContext");function YJ0(A,Q,B,D,E){let I={...A,cliVersion:Q.cliVersion,gitlabBaseUrl:B.baseUrl,...E};return D.redactSecrets(JSON.stringify(I,null,4),"cli-run-config")}var Yx=SA(T1(),1);var XmA=Yx.createInterfaceId("CliContextManager");class wr extends svA{#A;constructor(A,Q,B,D,E){super(A,Q,B,D,E);this.#A=L1(A,"[CliContextManager]")}async syncWithTextBuffer(A){let Q=this.#Q(A),B=new Set(Q),E=(await this.getSelectedContextItems()).map((I)=>{let C=I.metadata.secondaryText;if(B.has(C))return;return{item:I,itemReference:C}}).filter((I)=>I!==void 0);await Promise.all(E.map(({item:I,itemReference:C})=>{return this.#A.debug(`Removing item no longer in text: ${C}`),this.removeSelectedContextItem(I)}))}#Q(A){let Q=[];for(let B of Wl){let D=0;while(D<A.length)if(A[D]===B.activationChar){let E=A.slice(D+1);if(E.startsWith('"')){let I=E.indexOf('"',1);if(I!==-1){let C=E.slice(1,I);Q.push(`${B.activationChar}"${C}"`),D+=I+2}else D++}else{let I=E.search(/\s/),C=I===-1?E:E.slice(0,I);if(C.length>0)Q.push(`${B.activationChar}${C}`),D+=C.length+1;else D++}}else D++}return Q}}wr=Q1([Yx.Injectable(XmA,[q1,w4,BkA,Yx.collection(y3A),_b])],wr);var Gx=SA(T1(),1);var JJ0=SA(T1(),1);var xT=JJ0.createInterfaceId("SlashCommandHandler");var nEA=Gx.createInterfaceId("SlashCommandService");class Jx{#A;#Q=new Map;#B=new Map;constructor(A,Q){this.#A=L1(A,"[SlashCommandService]"),this.#D(Q)}#D(A){A.forEach((Q)=>{this.#Q.set(Q.command.name,Q.command),this.#B.set(Q.command.action,Q),this.#A.debug(`Registered slash command: ${Q.command.name} (action: ${Q.command.action})`)})}getCommands(){return Array.from(this.#Q.values())}isCommand(A){let Q=A.trim();if(!Q.startsWith("/"))return!1;let D=Q.split(/\s+/)[0];return this.#Q.has(D)}async execute(A,Q){let D=A.trim().split(/\s+/),E=D[0],I=D.slice(1),C=this.#Q.get(E);if(!C)throw Error(`Unknown command: ${E}`);this.#A.info(`Executing slash command: ${C.name} (action: ${C.action})`);let F=this.#B.get(C.action);if(!F)throw Error(`No handler registered for action: ${C.action}`);await F.execute(Q,I.length>0?I:void 0)}}Jx=Q1([Gx.Injectable(nEA,[q1,Gx.collection(xT)])],Jx);class oEA{sessionId;#A;#Q;#B=[];#D=!1;#E;#I;#C=new Map;constructor(A,Q,B){this.sessionId=A,this.#A=Q,this.#Q=L1(B,`[Session: ${A}]`)}get elements(){return this.#B}get isLoading(){return this.#D}rehydrateFromEvents(A){for(let Q of A)this.#K(this.#Y(Q));this.#B=this.#B.map((Q)=>Q.type==="message"?{...Q,isComplete:!0}:Q),this.#H()}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}addError(A,Q){let B={id:`error-${Date.now()}`,type:"error",error:A,timestamp:Q??Date.now()};return this.#B=[...this.#B,B],B}async*sendMessageStream(A){this.#D=!0,this.#E=new AbortController;try{let Q=this.#A.sendMessageStream(A,this.#E.signal),B=this.#F(Q);yield*this.#U(B)}catch(Q){this.#Q.error("Error in message streaming:",Q),yield this.addError("Sorry, there was an error processing your message. Please try again.")}finally{this.#H()}}async*#F(A){for await(let Q of A)yield*this.#G(Q)}cancelStream(){this.#E?.abort()}async preinitialize(){await this.#A.preinitialize?.()}*#Y(A){if(A.type==="USER_MESSAGE")yield*this.#J(A);else yield*this.#G(A)}*#J(A){let Q={id:A.messageId,type:"message",role:"user",content:A.content,timestamp:A.timestamp,isComplete:!0};this.#B=[...this.#B,Q],yield Q}*#G(A){switch(A.type){case"TEXT_CHUNK":{if(!this.#I||this.#I.id!==A.messageId)this.#I={id:A.messageId,type:"message",role:"assistant",content:A.content,timestamp:A.timestamp,isComplete:!1},this.#B=[...this.#B,this.#I];else this.#I.content+=A.content,this.#Z(this.#I);yield{...this.#I};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.#X(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.#X(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.#X(B),this.#C.delete(A.toolId),yield B}break}case"ERROR":{this.#Q.error(`Agent error: ${A.message}`),yield this.addError(A.message,A.timestamp);break}default:this.#Q.warn(`Unknown agent event type: ${JSON.stringify(A)}`);break}}async*#U(A){let Q;for await(let B of A){if(Q&&this.#V(B,Q))this.#z(Q.id),yield{...Q,isComplete:!0},Q=void 0;if(this.#w(B))Q=B;yield B}if(Q)this.#z(Q.id),yield{...Q,isComplete:!0}}#z(A){if(!A)return;this.#B=this.#B.map((Q)=>Q.id===A?{...Q,isComplete:!0}:Q)}#X(A){let Q=this.#B.findIndex((D)=>D.type==="tool"&&D.id===A.id);if(Q<0){this.#B=[...this.#B,A];return}let B=[...this.#B];B[Q]=A,this.#B=B}#Z(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)]}#H(){this.#D=!1,this.#I=void 0,this.#C.clear(),this.#E=void 0}#K(A){let Q=A.next();while(!Q.done)Q=A.next()}#w(A){return A.type==="message"&&A.role==="assistant"&&!A.isComplete}#V(A,Q){return A.type!=="message"||A.id!==Q.id}}var UJ0=SA(T1(),1),hT=UJ0.createInterfaceId("SessionDataService");var uM=SA(T1(),1);var XJ0=SA(T1(),1),Ux=XJ0.createInterfaceId("BackendFactory");var EK=uM.createInterfaceId("SessionManager");class Xx{#A=new Map;#Q;#B;#D;#E;constructor(A,Q,B){this.#E=L1(A,"[SessionManager]"),this.#B=Q,this.#D=B}async createSession(A){let Q=this.#B.create(),{sessionId:B,sessionRejectionReason:D}=await Q.initialize(A),E=new oEA(B,Q,this.#E);return this.#A.set(E.sessionId,E),this.#Q=E.sessionId,this.#E.debug(`Created session: ${E.sessionId}`),{session:E,sessionDetails:{sessionRejectionReason:D}}}getActiveSession(){if(this.#Q===void 0)return;return this.#A.get(this.#Q)}async getSessionHistory(A){let Q=A.search?.trim()||void 0;return this.#D.getSessionHistory({...A,search:Q})}async switchToSession(A){this.#I();let{session:Q}=await this.createSession(A),B=await this.#D.getSessionMessages(A);if(B.length>0)Q.rehydrateFromEvents(B);return Q}#I(){let A=this.getActiveSession();if(A?.isLoading)this.#E.info(`Cancelling active session "${A.sessionId}" before switching session.`),A.cancelStream()}}Xx=Q1([uM.Implements(EK),uM.Service({dependencies:[q1,Ux,hT],lifetime:uM.ServiceLifetime.Singleton})],Xx);var zJ0=SA(BD(),1),dM=SA(T1(),1);var Zx=dM.createInterfaceId("SessionsHistoryController");class zx{#A;#Q;#B;#D;constructor(A,Q,B){this.#A=L1(A,"[SessionsHistoryController]"),this.#Q=Q,this.#B=B}async openSearch(A){this.#A.info("Opening session history search"),this.#D=void 0,A.mutateState((Q)=>({...Q,input:{inputType:V2.SESSIONS_SEARCH,searchQuery:"",sessions:[],selectedIndex:0,isLoading:!0,hasNextPage:!1}}));try{let{items:Q,pageInfo:B}=await this.#Q.getSessionHistory({});this.#D=B.endCursor,A.mutateState((D)=>{if(D.input.inputType!==V2.SESSIONS_SEARCH)return D;return{...D,input:{...D.input,sessions:Q,isLoading:!1,hasNextPage:B.hasNextPage}}})}catch(Q){this.#A.error("Failed to fetch session history",Q),A.mutateState((B)=>{if(B.input.inputType!==V2.SESSIONS_SEARCH)return B;return{...B,input:{inputType:V2.SESSIONS_SEARCH,searchQuery:"",sessions:[],selectedIndex:0,isLoading:!1,hasNextPage:!1}}}),A.showError("Failed to load session history. Please try again.")}}cancelSearch(A){this.#E.cancel(),this.#D=void 0,A.mutateState((Q)=>({...Q,input:hU}))}searchQueryChanged(A,Q){A.mutateState((B)=>{if(B.input.inputType!==V2.SESSIONS_SEARCH)return B;return{...B,input:{...B.input,searchQuery:Q,selectedIndex:0}}}),this.#E(A,Q)}async selectSession(A,Q){this.#A.info(`Switching to session: ${Q}`),await A.ensureInitialized(),A.mutateState((B)=>({...B,input:hU,isLoading:!0}));try{await this.#Q.switchToSession(Q),A.syncState()}catch(B){A.mutateState((E)=>({...E,isLoading:!1})),this.#B.handleError("Failed to switch session",B);let D=B instanceof Error?B.message:"Failed to load session";A.showError(D)}}async loadMore(A){let Q;if(A.mutateState((B)=>{if(B.input.inputType!==V2.SESSIONS_SEARCH)return B;if(!B.input.hasNextPage||B.input.isLoading)return B;return Q=B.input.searchQuery,{...B,input:{...B.input,isLoading:!0}}}),Q===void 0)return;try{let{items:B,pageInfo:D}=await this.#Q.getSessionHistory({afterCursor:this.#D,search:Q});this.#D=D.endCursor,A.mutateState((E)=>{if(E.input.inputType!==V2.SESSIONS_SEARCH)return E;return{...E,input:{...E.input,sessions:[...E.input.sessions,...B],hasNextPage:D.hasNextPage,isLoading:!1}}})}catch(B){this.#A.error("Failed to load more sessions",B),A.mutateState((D)=>{if(D.input.inputType!==V2.SESSIONS_SEARCH)return D;return{...D,input:{...D.input,isLoading:!1}}})}}getCallbacks(A){return{onCancelSessionsSearch:()=>this.cancelSearch(A),onSessionsSearchQueryChange:(Q)=>this.searchQueryChanged(A,Q),onSelectSession:(Q)=>{D9(this.selectSession(A,Q))},onLoadMoreSessions:()=>{D9(this.loadMore(A))}}}#E=zJ0.debounce((A,Q)=>{D9(this.#I(A,Q))},300);async#I(A,Q){A.mutateState((B)=>{if(B.input.inputType!==V2.SESSIONS_SEARCH)return B;return{...B,input:{...B.input,isLoading:!0}}});try{let{items:B,pageInfo:D}=await this.#Q.getSessionHistory({search:Q});this.#D=D.endCursor,A.mutateState((E)=>{if(E.input.inputType!==V2.SESSIONS_SEARCH)return E;if(E.input.searchQuery!==Q)return E;return{...E,input:{...E.input,sessions:B,hasNextPage:D.hasNextPage,isLoading:!1,selectedIndex:0}}})}catch(B){this.#A.error("Failed to search sessions",B),A.mutateState((D)=>{if(D.input.inputType!==V2.SESSIONS_SEARCH)return D;return{...D,input:{...D.input,isLoading:!1}}})}}}zx=Q1([dM.Implements(Zx),dM.Service({dependencies:[q1,EK,SF],lifetime:dM.ServiceLifetime.Singleton})],zx);class ZmA{#A;#Q;constructor(){this.#A={...cNA}}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 KmA{#A;#Q=[];#B=-1;#D=100;#E;#I;constructor(A){this.#A=L1(A,"[PromptHistory]")}async load(A,Q){this.#E=A,this.#I=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.#E||!this.#I)return;try{await this.#E.set(this.#I,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!==V2.TEXT)return;return{...A,lines:Q.split(`
1595
1595
  `),cursorLine:0,cursorColumn:0}}handleNext(A){let Q=this.#Y();if(Q===void 0||A.inputType!==V2.TEXT)return;return{...A,lines:Q.split(`
1596
1596
  `),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]}#Y(){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((I)=>({item:I,matches:[]}));let B=A.toLowerCase(),D=[];for(let E of this.#Q){let I=E.toLowerCase().indexOf(B);if(I!==-1)D.push({item:E,matchIndex:I})}return D.slice(-Q).reverse().map(({item:E,matchIndex:I})=>({item:E,matches:[I]}))}handleOpenSearch(){let A=this.search("",10);return{inputType:V2.PROMPT_HISTORY_SEARCH,searchQuery:"",filteredHistory:A,selectedIndex:0}}handleCancelSearch(){return hU}handleSelectItem(A){return{inputType:V2.TEXT,lines:A.split(`
1597
- `),cursorLine:0,cursorColumn:0}}}class mT{#A;#Q;#B;#D=new ZmA;#E;#I;#C;#F;#Y;#J;#G;#U;#z;#X;#Z;#H;#K;#w=ZJ0.throttle(()=>this.#O(),500,{leading:!0,trailing:!0});constructor(A,Q,B,D,E,I,C,F,Y,J,G,X,z){this.#E=L1(A,"[TUIController]"),this.#z=F,this.#I=Q,this.#C=B,this.#F=D,this.#Y=E,this.#J=I,this.#G=C,this.#U=Y,this.#X=J,this.#Q=G,this.#B=X,this.#Z=z}async initialize(A){this.#A=A,this.#D.initialize((Q)=>this.#A?.(Q)),this.#N(),this.#H=this.#V()}async#V(){let A=await this.#Z.getCredentials();this.#E.debug(`CLI input: ${YJ0(this.#Y,this.#J,A,this.#C)}`);try{let{workspaceFolder:Q,username:B,gitlabRemote:D,existingSessionId:E}=await this.#F.initialize(),{sessionDetails:I}=await this.#Q.createSession(E);if(D)this.#D.setState({...this.#D.getState(),gitlabRemoteInfo:{status:"connected",gitlabPath:D.namespaceWithPath,gitlabHost:D.host}});else this.#D.setState({...this.#D.getState(),gitlabRemoteInfo:{status:"error",errorMessage:`Could not find GitLab remote info in workspace ${Q}. Some features might not be available.`}});let C=Boolean(I.sessionRejectionReason);this.#D.setState({...this.#D.getState(),agenticChatAccess:{status:C?"unavailable":"available",sessionCreated:!C,reason:I.sessionRejectionReason}}),D9(this.#W());let F=this.#Q.getActiveSession();if(F)D9(F.preinitialize().catch((Y)=>{this.#E.warn("Session pre-initialization failed (non-critical)",Y)}));this.#q(B),await this.#$()}catch(Q){this.#I.handleError("Duo CLI initialization failed",Q),this.#D.setState({...this.#D.getState(),criticalErrorMessage:Q instanceof Error?Q.message:"Unknown initialization error"}),await this.#X.exit(1)}}async#W(){let A=await this.#z.checkForUpdate(this.#J.cliVersion);if(A){if(A instanceof Error)this.#E.warn("Failed to check for updates",A);this.#D.setState({...this.#D.getState(),updateInfo:A})}}async#$(){let A=process.env.GLAB_CONFIG_DIR||XZ();if(!A){this.#E.warn("Unable to determine baseDir for prompt history storage, this will be skipped!");return}let Q=zO4(A,"duo-cli-prompt-history.json"),B=new FZ(this.#E,Q);try{this.#K=new KmA(this.#E),await this.#K?.load(B,this.#Y.cwd),this.#E.debug("Loaded prompt history")}catch(D){this.#E.error("Failed to load prompt history",D)}}getCallbacks(){return{onCancelStream:()=>{let A=this.#Q.getActiveSession();if(this.#D.getState().isLoading&&A)this.#E.info("Cancelling stream due to ESC key press"),A.cancelStream()},onSubmit:(A)=>this.#R({type:"SEND_PROMPT",prompt:A}),onChoiceSubmit:(A)=>{D9(this.#S(A))},onExit:()=>this.#_(),toggleExpanded:()=>{let A=this.#D.getState();this.#D.setState({...A,expanded:!A.expanded})},onContextSearch:async(A,Q)=>await this.#G?.searchContextItems({category:A,query:Q})??[],onContextItemSelected:async(A)=>{await this.#G?.addSelectedContextItem(A)},onTextChange:async(A)=>{await this.#G?.syncWithTextBuffer(A)},onHistoryPrevious:()=>{if(!this.#K)return;let A=this.#D.getState(),Q=this.#K?.handlePrevious(A.input);if(Q)this.#D.setState({...A,input:Q})},onHistoryNext:()=>{if(!this.#K)return;let A=this.#D.getState(),Q=this.#K?.handleNext(A.input);if(Q)this.#D.setState({...A,input:Q})},onOpenHistorySearch:()=>this.#v(),onCancelHistorySearch:()=>this.#P(),onHistorySearchQueryChange:(A)=>this.#g(A),onSelectHistoryItem:(A)=>this.#f(A),onDeleteHistoryItem:(A)=>this.#x(A),onCancelSessionsSearch:()=>this.#B.cancelSearch(this.#k()),onSessionsSearchQueryChange:(A)=>this.#B.searchQueryChanged(this.#k(),A),onSelectSession:(A)=>{D9(this.#h(A))},onLoadMoreSessions:()=>{D9(this.#B.loadMore(this.#k()))}}}#N(){this.#D.setState({elements:[],isLoading:!1,input:hU,expanded:!1,cwd:this.#Y.cwd,gitlabRemoteInfo:{status:"not-checked"},agenticChatAccess:{status:"checking",sessionCreated:!1}})}#q(A){let Q=this.#D.getState();this.#D.setState({...Q,username:A})}#M(){this.#w.cancel(),this.#O()}#O(){let A=this.#Q.getActiveSession();if(!A)return;this.#D.setState({...this.#D.getState(),elements:[...A.elements],isLoading:A.isLoading})}async#S(A){let Q=this.#D.getState();if(Q.isLoading)return;this.#D.setState({...Q,input:hU}),await this.#T(A)}async#R(A){if(!A.prompt.trim())return;if(this.#U.isCommand(A.prompt))try{await this.#H;let Q=this.#k();await this.#U.execute(A.prompt,Q),await this.#K?.add(this.#C.redactSecrets(A.prompt,"user-input"));return}catch(Q){this.#I.handleError("Failed to execute slash command",Q);let B=Q instanceof Error?Q.message:"Unknown error executing slash command";this.#b(B);return}await this.#L(A)}async#L(A,Q=!0){if(this.#D.getState().isLoading)return;let B=this.#C.redactSecrets(A.prompt,"user-input"),D={...A,prompt:B};if(Q)await this.#K?.add(D.prompt);await this.#T(D)}async#T(A){this.#D.setState({...this.#D.getState(),input:hU,isLoading:!0}),await this.#H;let Q=this.#Q.getActiveSession();if(!Q)throw Error("Session not initialized");if(A.type==="SEND_PROMPT")Q.addUserMessageAndStartLoading(A.prompt),this.#M();let B=await this.#y(A),D;for await(let E of Q.sendMessageStream(B))if(D=E,this.#j(E))this.#w();else this.#M();if(D?.type==="error")this.#I.handleError("Error in message streaming",Error(D.error));if(D?.type==="tool"&&D.state.type==="approval_request"){let E=D,I={type:"SEND_TOOL_APPROVAL",scope:"session",toolId:E.id,toolName:E.name},C=this.#D.getState();this.#D.setState({...C,input:{inputType:V2.CHOICE,choiceOptions:[{label:"Approve",value:{...I,approved:!0}},{label:"Reject",value:{...I,approved:!1}}],selectedChoiceIndex:0}})}this.#M()}#j(A){return A.type==="message"&&A.role==="assistant"&&!A.isComplete}async#y(A){if(A.type!=="SEND_PROMPT")return A;let Q=A;try{let B=await this.#G.retrieveContextItemsWithContent({mode:"agentic"});Q.aiContextItems=[...Q.aiContextItems||[],...B||[]],await this.#G.clearSelectedContextItems()}catch(B){this.#E.error("Failed to get AIContextItems for message. Context items will be omitted.",B)}return Q}#_(){D9(this.#X.exit(0))}#v(){if(!this.#K)return;let A=this.#D.getState(),Q=this.#K.handleOpenSearch();this.#D.setState({...A,input:Q})}#P(){if(!this.#K)return;let A=this.#D.getState(),Q=this.#K.handleCancelSearch();this.#D.setState({...A,input:Q})}#g(A){if(!this.#K)return;let Q=this.#D.getState();if(Q.input.inputType!==V2.PROMPT_HISTORY_SEARCH)return;let B=this.#K.search(A,10);this.#D.setState({...Q,input:{...Q.input,searchQuery:A,filteredHistory:B,selectedIndex:0}})}#f(A){if(!this.#K)return;let Q=this.#D.getState(),B=this.#K.handleSelectItem(A);this.#D.setState({...Q,input:B})}async#x(A){if(!this.#K)return;let Q=this.#D.getState();if(await this.#K.remove(A)===-1)return;if(Q.input.inputType===V2.PROMPT_HISTORY_SEARCH){let D=this.#K.search(Q.input.searchQuery,10),E=Math.min(Q.input.selectedIndex,Math.max(0,D.length-1));this.#D.setState({...Q,input:{...Q.input,filteredHistory:D,selectedIndex:E}})}}async#h(A){await this.#H,await this.#B.selectSession(this.#k(),A)}#b(A){this.#Q.getActiveSession()?.addError(A),this.#M()}#k(){return{mutateState:(A)=>{let Q=A(this.#D.getState());return this.#D.setState(Q),Q},showError:(A)=>this.#b(A),sendPrompt:async(A)=>{await this.#L(A,!1)},syncState:()=>{this.#M()}}}}mT=Q1([sEA.Service({dependencies:[q1,SF,CE,MV,H9,Fx,XmA,avA,nEA,sH,EK,Zx,_E],lifetime:sEA.ServiceLifetime.Singleton})],mT);var tEA=SA(T1(),1);class uT{#A;#Q;#B;#D;#E;#I;#C;constructor(A,Q,B,D,E,I,C){this.#A=L1(A,"[RunController]"),this.#Q=Q,this.#B=B,this.#D=D,this.#E=E,this.#I=I,this.#C=C}async initialize(){try{let{existingSessionId:A}=await this.#D.initialize(),{session:Q}=await this.#C.createSession(A);try{await Q.preinitialize()}catch(B){this.#A.warn("Session pre-initialization failed (non-critical)",B)}}catch(A){this.#Q.handleError("Duo CLI initialization failed",A),await this.#I.exit(1)}}async execute(){let A=this.#C.getActiveSession();if(!A||this.#E.command?.name!=="run")throw Error("Controller not initialized. Call initialize() first.");let{goal:Q}=this.#E.command,B=this.#B.redactSecrets(Q,"user-input");this.#A?.info(`Executing workflow: ${JSON.stringify(Q===B?{goal:Q}:{redactedGoal:B},null,4)}`);try{let D;for await(let E of A.sendMessageStream({type:"SEND_PROMPT",prompt:B}))this.#F(E),D=E;await this.#I.exit(D?.type==="error"?1:0)}catch(D){throw this.#A?.error("Workflow failed:",D instanceof Error?D.message:String(D)),D}}#F(A){switch(A.type){case"message":{if(A.isComplete)this.#A?.info(JSON.stringify(A,null,2));break}case"tool":{let Q=A;switch(Q.state.type){case"loading":this.#A?.info(`Tool started: ${Q.name}`);break;case"success":this.#A?.info(`Tool completed: ${Q.id}`);break;case"error":this.#A?.info(`Tool completed: ${Q.id}`),this.#A?.error(`Tool error: ${Q.state.error}`);break;case"approval_request":break;default:break}break}case"error":{this.#A?.error(`Error: ${A.error}`);break}default:break}}}uT=Q1([tEA.Service({dependencies:[q1,SF,CE,MV,H9,sH,EK],lifetime:tEA.ServiceLifetime.Singleton})],uT);var ZO4=()=>{return"production"},wmA,eEA=async()=>{if(!wmA){let A=o_1(),Q=await r_1(),B=e8(),D=ZO4();wmA={terminalName:A,isKittyProtocolSupported:Q,duoCliVersion:B,environment:D}}return wmA};var AIA=(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 KO4,readFileSync as wO4}from"node:fs";import{isAbsolute as HO4,resolve as VO4}from"node:path";var $O4=[".yaml",".yml",".json"];class Kx extends Error{constructor(A){super(A);this.name="FlowConfigError"}}function WO4(A){if(HO4(A))return!0;if(A.startsWith("./")||A.startsWith(".\\"))return!0;return $O4.some((Q)=>A.endsWith(Q))}function NO4(A,Q){let B=VO4(Q,A);if(KO4(B))try{return wO4(B,"utf-8")}catch(D){let E=D instanceof Error?D.message:"unknown";throw new Kx(`Could not read flow config file "${B}": ${E}`)}if(WO4(A))throw new Kx(`Flow config file not found: "${B}". Provide a valid file path or pass the YAML/JSON content directly.`);return A}function KJ0(A,Q=process.cwd()){if(!A)return A;let B=NO4(A,Q);try{return Un(B),B}catch(D){let E=D instanceof Error?D.message:"unknown";throw new Kx(`Could not parse flow config: ${E}`)}}var wJ0;((D)=>{D.ClaudeSonnet4="claude-sonnet-4-20250514";D.ClaudeSonnet45="claude-sonnet-4-5-20250929";D.ClaudeOpus45="claude-opus-4-5-20251101"})(wJ0||={});var QIA={connectionType:{flags:"--connection-type <type>",description:"Workflow connection type",choices:["grpc","websocket"],env:"GITLAB_DUO_CONNECTION_TYPE",default:"websocket",zod:u.enum(["grpc","websocket"]).optional()},model:{flags:"--model <gitlab_identifier>",description:'GitLab model identifier to use (e.g. "claude_sonnet_4_6", "claude_haiku_4_5_20251001"). Use the `gitlab_identifier` field from https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/-/blob/HEAD/ai_gateway/model_selection/models.yml',env:"GITLAB_DUO_MODEL",default:"claude_sonnet_4_6",zod:u.string().optional()}},BIA={flowConfigSchemaVersion:{flags:"--flow-config-schema-version <version>",description:"Flow config schema version",env:"DUO_WORKFLOW_FLOW_CONFIG_SCHEMA_VERSION",zod:u.string().optional()},workflowType:{flags:"--workflow-type <type>",description:'Workflow type (e.g. "chat", "software_development")',default:"chat",env:"DUO_WORKFLOW_DEFINITION",zod:u.string().optional()},duoWorkflowServiceServer:{flags:"--duo-workflow-service-server <url>",description:"Duo Workflow Service server URL",env:"DUO_WORKFLOW_SERVICE_SERVER",zod:u.string().optional()},duoWorkflowServiceToken:{flags:"--duo-workflow-service-token <token>",description:"Duo Workflow Service authentication token",env:"DUO_WORKFLOW_SERVICE_TOKEN",zod:u.string().optional()},duoWorkflowMetadata:{flags:"--duo-workflow-metadata <json>",description:"Pre-computed workflow metadata JSON",env:"DUO_WORKFLOW_METADATA",parse:(A)=>{if(!A)return;try{return JSON.parse(A)}catch(Q){let B=Q instanceof Error?Q.message:"unknown";throw new Kd(`Could not parse workflow metadata JSON: ${B}`)}},zod:u.record(u.unknown()).optional()},duoWorkflowProjectId:{flags:"--duo-workflow-project-id <id>",description:"GitLab project ID",env:"DUO_WORKFLOW_PROJECT_ID",zod:u.string().optional()},duoWorkflowNamespaceId:{flags:"--duo-workflow-namespace-id <id>",description:"GitLab namespace ID",env:"DUO_WORKFLOW_NAMESPACE_ID",zod:u.string().optional()},gitlabProjectPath:{flags:"--gitlab-project-path <path>",description:"GitLab project path",env:"GITLAB_PROJECT_PATH",zod:u.string().optional()},duoWorkflowGlobalUserId:{flags:"--duo-workflow-global-user-id <id>",description:"Global user ID",env:"DUO_WORKFLOW_GLOBAL_USER_ID",zod:u.string().optional()},duoWorkflowInstanceId:{flags:"--duo-workflow-instance-id <id>",description:"GitLab instance ID",env:"DUO_WORKFLOW_INSTANCE_ID",zod:u.string().optional()},duoWorkflowRealm:{flags:"--duo-workflow-realm <realm>",description:"GitLab realm (e.g., saas, self-managed)",env:"DUO_WORKFLOW_SERVICE_REALM",zod:u.string().optional()},agentPlatformGitlabVersion:{flags:"--agent-platform-gitlab-version <version>",description:"GitLab instance version",env:"AGENT_PLATFORM_GITLAB_VERSION",zod:u.string().optional()},agentPlatformFeatureSettingName:{flags:"--agent-platform-feature-setting-name <name>",description:"Agent platform feature setting name",env:"AGENT_PLATFORM_FEATURE_SETTING_NAME",zod:u.string().optional()},insecure:{flags:"--insecure [value]",description:"Allow insecure (non-TLS) connections to Duo Workflow Service",env:"DUO_WORKFLOW_INSECURE",default:"false",parse:(A)=>AIA(A),zod:u.union([u.string(),u.boolean()]).optional()}};function HJ0(A){return{flags:"--flow-config <config>",description:"Flow config (YAML/JSON content or file path)",env:"DUO_WORKFLOW_FLOW_CONFIG",parse:(Q)=>{try{return KJ0(Q,A())}catch(B){if(B instanceof Kx)throw new Kd(B.message);throw B}}}}var HmA={model:{flags:"--model <model>",description:`Anthropic model to use (supported: ${Object.values(wJ0).join(", ")})`,env:"ANTHROPIC_MODEL",default:"claude-sonnet-4-5-20250929",zod:u.string()}};var YR0=SA(T1(),1);var CIA=SA(T1(),1);var IIA=SA(T1(),1);var qV=(A,...Q)=>{return A.reduce((B,D,E)=>`${B}${D}${E in Q?String(Q[E]):""}`,"")};var VJ0={supportedSinceInstanceVersion:"18.5.0",query:qV`
1597
+ `),cursorLine:0,cursorColumn:0}}}class mT{#A;#Q;#B;#D=new ZmA;#E;#I;#C;#F;#Y;#J;#G;#U;#z;#X;#Z;#H;#K;#w=ZJ0.throttle(()=>this.#O(),500,{leading:!0,trailing:!0});constructor(A,Q,B,D,E,I,C,F,Y,J,G,X,z){this.#E=L1(A,"[TUIController]"),this.#z=F,this.#I=Q,this.#C=B,this.#F=D,this.#Y=E,this.#J=I,this.#G=C,this.#U=Y,this.#X=J,this.#Q=G,this.#B=X,this.#Z=z}async initialize(A){this.#A=A,this.#D.initialize((Q)=>this.#A?.(Q)),this.#N(),this.#H=this.#V()}async#V(){let A=await this.#Z.getCredentials();this.#E.debug(`CLI input: ${YJ0(this.#Y,this.#J,A,this.#C)}`);try{let{workspaceFolder:Q,username:B,gitlabRemote:D,existingSessionId:E}=await this.#F.initialize(),{sessionDetails:I}=await this.#Q.createSession(E);if(D)this.#D.setState({...this.#D.getState(),gitlabRemoteInfo:{status:"connected",gitlabPath:D.namespaceWithPath,gitlabHost:D.host}});else this.#D.setState({...this.#D.getState(),gitlabRemoteInfo:{status:"error",errorMessage:`Could not find GitLab remote info in workspace ${Q}. Some features might not be available.`}});let C=Boolean(I.sessionRejectionReason);this.#D.setState({...this.#D.getState(),agenticChatAccess:{status:C?"unavailable":"available",sessionCreated:!C,reason:I.sessionRejectionReason}}),D9(this.#W());let F=this.#Q.getActiveSession();if(F)D9(F.preinitialize().catch((Y)=>{this.#E.warn("Session pre-initialization failed (non-critical)",Y)}));this.#q(B),await this.#$()}catch(Q){this.#I.handleError("Duo CLI initialization failed",Q),this.#D.setState({...this.#D.getState(),criticalErrorMessage:Q instanceof Error?Q.message:"Unknown initialization error"}),await this.#X.exit(1)}}async#W(){let A=await this.#z.checkForUpdate(this.#J.cliVersion);if(A){if(A instanceof Error)this.#E.warn("Failed to check for updates",A);this.#D.setState({...this.#D.getState(),updateInfo:A})}}async#$(){let A=process.env.GLAB_CONFIG_DIR||XZ();if(!A){this.#E.warn("Unable to determine baseDir for prompt history storage, this will be skipped!");return}let Q=zO4(A,"duo-cli-prompt-history.json"),B=new FZ(this.#E,Q);try{this.#K=new KmA(this.#E),await this.#K?.load(B,this.#Y.cwd),this.#E.debug("Loaded prompt history")}catch(D){this.#E.error("Failed to load prompt history",D)}}getCallbacks(){return{onCancelStream:()=>{let A=this.#Q.getActiveSession();if(this.#D.getState().isLoading&&A)this.#E.info("Cancelling stream due to ESC key press"),A.cancelStream()},onSubmit:(A)=>this.#R({type:"SEND_PROMPT",prompt:A}),onChoiceSubmit:(A)=>{D9(this.#S(A))},onExit:()=>this.#_(),toggleExpanded:()=>{let A=this.#D.getState();this.#D.setState({...A,expanded:!A.expanded})},onContextSearch:async(A,Q)=>await this.#G?.searchContextItems({category:A,query:Q})??[],onContextItemSelected:async(A)=>{await this.#G?.addSelectedContextItem(A)},onTextChange:async(A)=>{await this.#G?.syncWithTextBuffer(A)},onHistoryPrevious:()=>{if(!this.#K)return;let A=this.#D.getState(),Q=this.#K?.handlePrevious(A.input);if(Q)this.#D.setState({...A,input:Q})},onHistoryNext:()=>{if(!this.#K)return;let A=this.#D.getState(),Q=this.#K?.handleNext(A.input);if(Q)this.#D.setState({...A,input:Q})},onOpenHistorySearch:()=>this.#v(),onCancelHistorySearch:()=>this.#P(),onHistorySearchQueryChange:(A)=>this.#k(A),onSelectHistoryItem:(A)=>this.#f(A),onDeleteHistoryItem:(A)=>this.#x(A),...this.#B.getCallbacks(this.#b())}}#N(){this.#D.setState({elements:[],isLoading:!1,input:hU,expanded:!1,cwd:this.#Y.cwd,gitlabRemoteInfo:{status:"not-checked"},agenticChatAccess:{status:"checking",sessionCreated:!1}})}#q(A){let Q=this.#D.getState();this.#D.setState({...Q,username:A})}#M(){this.#w.cancel(),this.#O()}#O(){let A=this.#Q.getActiveSession();if(!A)return;this.#D.setState({...this.#D.getState(),elements:[...A.elements],isLoading:A.isLoading})}async#S(A){let Q=this.#D.getState();if(Q.isLoading)return;this.#D.setState({...Q,input:hU}),await this.#T(A)}async#R(A){if(!A.prompt.trim())return;if(this.#U.isCommand(A.prompt))try{await this.#H;let Q=this.#b();await this.#U.execute(A.prompt,Q),await this.#K?.add(this.#C.redactSecrets(A.prompt,"user-input"));return}catch(Q){this.#I.handleError("Failed to execute slash command",Q);let B=Q instanceof Error?Q.message:"Unknown error executing slash command";this.#g(B);return}await this.#L(A)}async#L(A,Q=!0){if(this.#D.getState().isLoading)return;let B=this.#C.redactSecrets(A.prompt,"user-input"),D={...A,prompt:B};if(Q)await this.#K?.add(D.prompt);await this.#T(D)}async#T(A){this.#D.setState({...this.#D.getState(),input:hU,isLoading:!0}),await this.#H;let Q=this.#Q.getActiveSession();if(!Q)throw Error("Session not initialized");if(A.type==="SEND_PROMPT")Q.addUserMessageAndStartLoading(A.prompt),this.#M();let B=await this.#y(A),D;for await(let E of Q.sendMessageStream(B))if(D=E,this.#j(E))this.#w();else this.#M();if(D?.type==="error")this.#I.handleError("Error in message streaming",Error(D.error));if(D?.type==="tool"&&D.state.type==="approval_request"){let E=D,I={type:"SEND_TOOL_APPROVAL",scope:"session",toolId:E.id,toolName:E.name},C=this.#D.getState();this.#D.setState({...C,input:{inputType:V2.CHOICE,choiceOptions:[{label:"Approve",value:{...I,approved:!0}},{label:"Reject",value:{...I,approved:!1}}],selectedChoiceIndex:0}})}this.#M()}#j(A){return A.type==="message"&&A.role==="assistant"&&!A.isComplete}async#y(A){if(A.type!=="SEND_PROMPT")return A;let Q=A;try{let B=await this.#G.retrieveContextItemsWithContent({mode:"agentic"});Q.aiContextItems=[...Q.aiContextItems||[],...B||[]],await this.#G.clearSelectedContextItems()}catch(B){this.#E.error("Failed to get AIContextItems for message. Context items will be omitted.",B)}return Q}#_(){D9(this.#X.exit(0))}#v(){if(!this.#K)return;let A=this.#D.getState(),Q=this.#K.handleOpenSearch();this.#D.setState({...A,input:Q})}#P(){if(!this.#K)return;let A=this.#D.getState(),Q=this.#K.handleCancelSearch();this.#D.setState({...A,input:Q})}#k(A){if(!this.#K)return;let Q=this.#D.getState();if(Q.input.inputType!==V2.PROMPT_HISTORY_SEARCH)return;let B=this.#K.search(A,10);this.#D.setState({...Q,input:{...Q.input,searchQuery:A,filteredHistory:B,selectedIndex:0}})}#f(A){if(!this.#K)return;let Q=this.#D.getState(),B=this.#K.handleSelectItem(A);this.#D.setState({...Q,input:B})}async#x(A){if(!this.#K)return;let Q=this.#D.getState();if(await this.#K.remove(A)===-1)return;if(Q.input.inputType===V2.PROMPT_HISTORY_SEARCH){let D=this.#K.search(Q.input.searchQuery,10),E=Math.min(Q.input.selectedIndex,Math.max(0,D.length-1));this.#D.setState({...Q,input:{...Q.input,filteredHistory:D,selectedIndex:E}})}}#g(A){this.#Q.getActiveSession()?.addError(A),this.#M()}#b(){return{mutateState:(A)=>{let Q=A(this.#D.getState());return this.#D.setState(Q),Q},showError:(A)=>this.#g(A),sendPrompt:async(A)=>{await this.#L(A,!1)},syncState:()=>{this.#M()},ensureInitialized:async()=>{await this.#H}}}}mT=Q1([sEA.Service({dependencies:[q1,SF,CE,MV,H9,Fx,XmA,avA,nEA,sH,EK,Zx,_E],lifetime:sEA.ServiceLifetime.Singleton})],mT);var tEA=SA(T1(),1);class uT{#A;#Q;#B;#D;#E;#I;#C;constructor(A,Q,B,D,E,I,C){this.#A=L1(A,"[RunController]"),this.#Q=Q,this.#B=B,this.#D=D,this.#E=E,this.#I=I,this.#C=C}async initialize(){try{let{existingSessionId:A}=await this.#D.initialize(),{session:Q}=await this.#C.createSession(A);try{await Q.preinitialize()}catch(B){this.#A.warn("Session pre-initialization failed (non-critical)",B)}}catch(A){this.#Q.handleError("Duo CLI initialization failed",A),await this.#I.exit(1)}}async execute(){let A=this.#C.getActiveSession();if(!A||this.#E.command?.name!=="run")throw Error("Controller not initialized. Call initialize() first.");let{goal:Q}=this.#E.command,B=this.#B.redactSecrets(Q,"user-input");this.#A?.info(`Executing workflow: ${JSON.stringify(Q===B?{goal:Q}:{redactedGoal:B},null,4)}`);try{let D;for await(let E of A.sendMessageStream({type:"SEND_PROMPT",prompt:B}))this.#F(E),D=E;await this.#I.exit(D?.type==="error"?1:0)}catch(D){throw this.#A?.error("Workflow failed:",D instanceof Error?D.message:String(D)),D}}#F(A){switch(A.type){case"message":{if(A.isComplete)this.#A?.info(JSON.stringify(A,null,2));break}case"tool":{let Q=A;switch(Q.state.type){case"loading":this.#A?.info(`Tool started: ${Q.name}`);break;case"success":this.#A?.info(`Tool completed: ${Q.id}`);break;case"error":this.#A?.info(`Tool completed: ${Q.id}`),this.#A?.error(`Tool error: ${Q.state.error}`);break;case"approval_request":break;default:break}break}case"error":{this.#A?.error(`Error: ${A.error}`);break}default:break}}}uT=Q1([tEA.Service({dependencies:[q1,SF,CE,MV,H9,sH,EK],lifetime:tEA.ServiceLifetime.Singleton})],uT);var ZO4=()=>{return"production"},wmA,eEA=async()=>{if(!wmA){let A=o_1(),Q=await r_1(),B=e8(),D=ZO4();wmA={terminalName:A,isKittyProtocolSupported:Q,duoCliVersion:B,environment:D}}return wmA};var AIA=(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 KO4,readFileSync as wO4}from"node:fs";import{isAbsolute as HO4,resolve as VO4}from"node:path";var $O4=[".yaml",".yml",".json"];class Kx extends Error{constructor(A){super(A);this.name="FlowConfigError"}}function WO4(A){if(HO4(A))return!0;if(A.startsWith("./")||A.startsWith(".\\"))return!0;return $O4.some((Q)=>A.endsWith(Q))}function NO4(A,Q){let B=VO4(Q,A);if(KO4(B))try{return wO4(B,"utf-8")}catch(D){let E=D instanceof Error?D.message:"unknown";throw new Kx(`Could not read flow config file "${B}": ${E}`)}if(WO4(A))throw new Kx(`Flow config file not found: "${B}". Provide a valid file path or pass the YAML/JSON content directly.`);return A}function KJ0(A,Q=process.cwd()){if(!A)return A;let B=NO4(A,Q);try{return Un(B),B}catch(D){let E=D instanceof Error?D.message:"unknown";throw new Kx(`Could not parse flow config: ${E}`)}}var wJ0;((D)=>{D.ClaudeSonnet4="claude-sonnet-4-20250514";D.ClaudeSonnet45="claude-sonnet-4-5-20250929";D.ClaudeOpus45="claude-opus-4-5-20251101"})(wJ0||={});var QIA={connectionType:{flags:"--connection-type <type>",description:"Workflow connection type",choices:["grpc","websocket"],env:"GITLAB_DUO_CONNECTION_TYPE",default:"websocket",zod:u.enum(["grpc","websocket"]).optional()},model:{flags:"--model <gitlab_identifier>",description:'GitLab model identifier to use (e.g. "claude_sonnet_4_6", "claude_haiku_4_5_20251001"). Use the `gitlab_identifier` field from https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/-/blob/HEAD/ai_gateway/model_selection/models.yml',env:"GITLAB_DUO_MODEL",default:"claude_sonnet_4_6",zod:u.string().optional()}},BIA={flowConfigSchemaVersion:{flags:"--flow-config-schema-version <version>",description:"Flow config schema version",env:"DUO_WORKFLOW_FLOW_CONFIG_SCHEMA_VERSION",zod:u.string().optional()},workflowType:{flags:"--workflow-type <type>",description:'Workflow type (e.g. "chat", "software_development")',default:"chat",env:"DUO_WORKFLOW_DEFINITION",zod:u.string().optional()},duoWorkflowServiceServer:{flags:"--duo-workflow-service-server <url>",description:"Duo Workflow Service server URL",env:"DUO_WORKFLOW_SERVICE_SERVER",zod:u.string().optional()},duoWorkflowServiceToken:{flags:"--duo-workflow-service-token <token>",description:"Duo Workflow Service authentication token",env:"DUO_WORKFLOW_SERVICE_TOKEN",zod:u.string().optional()},duoWorkflowMetadata:{flags:"--duo-workflow-metadata <json>",description:"Pre-computed workflow metadata JSON",env:"DUO_WORKFLOW_METADATA",parse:(A)=>{if(!A)return;try{return JSON.parse(A)}catch(Q){let B=Q instanceof Error?Q.message:"unknown";throw new Kd(`Could not parse workflow metadata JSON: ${B}`)}},zod:u.record(u.unknown()).optional()},duoWorkflowProjectId:{flags:"--duo-workflow-project-id <id>",description:"GitLab project ID",env:"DUO_WORKFLOW_PROJECT_ID",zod:u.string().optional()},duoWorkflowNamespaceId:{flags:"--duo-workflow-namespace-id <id>",description:"GitLab namespace ID",env:"DUO_WORKFLOW_NAMESPACE_ID",zod:u.string().optional()},gitlabProjectPath:{flags:"--gitlab-project-path <path>",description:"GitLab project path",env:"GITLAB_PROJECT_PATH",zod:u.string().optional()},duoWorkflowGlobalUserId:{flags:"--duo-workflow-global-user-id <id>",description:"Global user ID",env:"DUO_WORKFLOW_GLOBAL_USER_ID",zod:u.string().optional()},duoWorkflowInstanceId:{flags:"--duo-workflow-instance-id <id>",description:"GitLab instance ID",env:"DUO_WORKFLOW_INSTANCE_ID",zod:u.string().optional()},duoWorkflowRealm:{flags:"--duo-workflow-realm <realm>",description:"GitLab realm (e.g., saas, self-managed)",env:"DUO_WORKFLOW_SERVICE_REALM",zod:u.string().optional()},agentPlatformGitlabVersion:{flags:"--agent-platform-gitlab-version <version>",description:"GitLab instance version",env:"AGENT_PLATFORM_GITLAB_VERSION",zod:u.string().optional()},agentPlatformFeatureSettingName:{flags:"--agent-platform-feature-setting-name <name>",description:"Agent platform feature setting name",env:"AGENT_PLATFORM_FEATURE_SETTING_NAME",zod:u.string().optional()},insecure:{flags:"--insecure [value]",description:"Allow insecure (non-TLS) connections to Duo Workflow Service",env:"DUO_WORKFLOW_INSECURE",default:"false",parse:(A)=>AIA(A),zod:u.union([u.string(),u.boolean()]).optional()}};function HJ0(A){return{flags:"--flow-config <config>",description:"Flow config (YAML/JSON content or file path)",env:"DUO_WORKFLOW_FLOW_CONFIG",parse:(Q)=>{try{return KJ0(Q,A())}catch(B){if(B instanceof Kx)throw new Kd(B.message);throw B}}}}var HmA={model:{flags:"--model <model>",description:`Anthropic model to use (supported: ${Object.values(wJ0).join(", ")})`,env:"ANTHROPIC_MODEL",default:"claude-sonnet-4-5-20250929",zod:u.string()}};var YR0=SA(T1(),1);var CIA=SA(T1(),1);var IIA=SA(T1(),1);var qV=(A,...Q)=>{return A.reduce((B,D,E)=>`${B}${D}${E in Q?String(Q[E]):""}`,"")};var VJ0={supportedSinceInstanceVersion:"18.5.0",query:qV`
1598
1598
  query lsp_aiChatAvailableModels($rootNamespaceId: GroupID!) {
1599
1599
  metadata {
1600
1600
  featureFlags(names: ["ai_user_model_switching"]) {
@@ -1737,11 +1737,11 @@ ${I}`)}return B.join(`
1737
1737
  `)+(B.length>0?`
1738
1738
  `:"")}}Gh=Q1([jFA.Injectable(rB,[q1,M2,jFA.collection(_7),TFA])],Gh);var gN0=SA(T1(),1);import{promises as Jm4}from"node:fs";import{join as jpA,sep as Gm4}from"node:path";class Uh{#A;#Q;constructor(A,Q){this.#A=L1(A,"[ListDirectoryActionHandler]"),this.#Q=Q}name="list_dir";formatInput(A){return{tool:"list_dir",directory:A.directory}}canHandle(A){return Boolean(A.listDirectory)}async execute({listDirectory:A},{workspaceFolderPath:Q}){let B=jpA(Q,A.directory);this.#A.debug(`Listing contents in directory "${B}"`);let D=await this.#Q.getMatchingRepository(B,Q);if(!D){let E=`Directory is not in repository: "${B}"`;return this.#A.error(E),{error:E,response:""}}try{if((await D.checkIgnore([B])).length>0){let J=`Directory is .gitignored: "${B}"`;return this.#A.error(J),{error:J,response:""}}let E=await Jm4.readdir(B,{withFileTypes:!0}),I=E.map((J)=>jpA(J.parentPath,J.name)),C=await D.checkIgnore(I);return{response:E.filter((J)=>!C.includes(jpA(J.parentPath,J.name))).map((J)=>`${J.name}${J.isDirectory()?Gm4:""}`).join(`
1739
1739
  `),error:""}}catch(E){let I=`Failed to read directory "${B}": ${E}`;return this.#A.error(I,E),{error:I,response:""}}}}Uh=Q1([gN0.Injectable(rB,[q1,M2])],Uh);var PFA=SA(T1(),1);import{mkdir as Um4}from"node:fs/promises";import{join as Xm4}from"node:path";class Xh{#A;#Q;#B;constructor(A,Q,B){this.#A=L1(A,"[MakeDirectoryActionHandler]"),this.#Q=W3(this.#A,B),this.#B=Q}name="mkdir";formatInput(A){return{tool:"mkdir",path:A.directory_path}}canHandle(A){return Boolean(A.mkdir)}async execute(A,{workspaceFolderPath:Q,abortSignal:B}){let{directory_path:D}=A.mkdir,E=Xm4(Q,D);try{return await DG(D,Q,this.#Q,this.#B,this.#A),this.#A.debug(`Creating directory "${D}"`),B.throwIfAborted(),await Um4(E,{recursive:!0}),{response:`Directory created successfully: "${D}"`,error:""}}catch(I){let C=I instanceof Error?I.message:String(I);return this.#A.error(`Unable to create directory "${E}"`,I),{error:C,response:""}}}}Xh=Q1([PFA.Injectable(rB,[q1,M2,PFA.collection(_7)])],Xh);var SFA=SA(T1(),1);import{join as zm4}from"node:path";class js{logger;constructor(A){this.logger=A}updateFileState(A,Q,B,D){try{Q.recordFileRead(B,A)}catch(E){this.logger.warn(`Failed to update version cache after reading for "${D}"`,E)}}}class zh extends js{#A;#Q;#B;constructor(A,Q,B,D){super(L1(A,"[ReadFileActionHandler]"));this.#A=Q,this.#Q=W3(this.logger,B),this.#B=D}name="read_file";formatInput(A){return{tool:"read_file",filepath:A.file_path}}canHandle(A){return Boolean(A.runReadFile)}async execute({runReadFile:A},{workspaceFolderPath:Q,fileStateTracker:B}){let D=A.filepath,E=zm4(Q,D);this.logger.debug(`Reading file "${A.filepath}"`);try{if(await DG(D,Q,this.#Q,this.#A,this.logger),await Ob(hR(E),this.#B))return this.logger.debug(`File "${D}" detected as binary, skipping read`),{response:"",error:`Cannot read file: "${D}" is a binary file`};let I=await this.#Q.getText(E);return this.updateFileState(I,B,E,D),{response:I,error:""}}catch(I){if(this.logger.error(`Error reading file "${E}"`,I),I.code==="ENOENT")return{response:"",error:`File not found: "${D}"`};return{response:"",error:`Error reading file: ${I instanceof Error?I.message:String(I)}`}}}}zh=Q1([SFA.Injectable(rB,[q1,M2,SFA.collection(_7),OJ])],zh);var yFA=SA(T1(),1);import{join as Zm4}from"node:path";class Zh extends js{#A;#Q;#B;constructor(A,Q,B,D){super(L1(A,"[ReadFilesActionHandler]"));this.#A=Q,this.#Q=W3(this.logger,B),this.#B=D}name="read_files";formatInput(A){return{tool:"read_files",filepaths:A.file_paths}}canHandle(A){return Boolean(A.runReadFiles)}async execute({runReadFiles:A},{workspaceFolderPath:Q,fileStateTracker:B}){let D=A.filepaths,E={};return await Promise.allSettled(D.map(async(C)=>{let F=Zm4(Q,C);try{if(await DG(C,Q,this.#Q,this.#A,this.logger),await Ob(hR(F),this.#B)){this.logger.debug(`File "${C}" detected as binary, skipping read`),E[C]={error:`Cannot read file: "${C}" is a binary file`};return}let Y=await this.#Q.getText(F);E[C]={content:Y},this.updateFileState(Y,B,F,C),this.logger.debug(`Successfully read file "${C}"`)}catch(Y){if(this.logger.error(`Error reading file "${F}"`,Y),Y.code==="ENOENT"){E[C]={error:`File not found: "${C}"`};return}let G=Y instanceof Error?Y.message:String(Y);E[C]={error:`Error reading file: ${G}`}}})),{response:JSON.stringify(E),error:""}}}Zh=Q1([yFA.Injectable(rB,[q1,M2,yFA.collection(_7),OJ])],Zh);var kFA=SA(T1(),1);var bN0=SA(T1(),1),vFA=(A)=>{return Object.hasOwn(A,"error")},mj=bN0.createInterfaceId("WorkflowCommandService");class Kh{#A;#Q;constructor(A,Q){this.#A=L1(A,"[RunCommandActionHandler]"),this.#Q=W3(this.#A,Q)}name="run_command";formatInput(A){if("command"in A&&typeof A.command==="string")return{tool:"run_command",command:A.command};let{program:Q,args:B}=A;return{tool:"run_command",command:B?`${Q} ${B}`:Q}}canHandle(A){return Boolean(A.runCommand)}async execute({runCommand:A},{workspaceFolderPath:Q,workflowId:B,abortSignal:D}){let{program:E,flags:I,arguments:C}=A;this.#A.debug(`Running command: "${E} ${[...I,...C].join(" ")}"`);let F=await this.#Q.runCommand(B,Q,E,!1,[...I,...C],D);if(vFA(F))return{...F,response:""};let{output:Y,exitCode:J}=F;return this.#A.debug(`Command "${E}" exited with code ${J} (${Y.length} chars)`),{response:`Exit code: ${J}
1740
- ${Y}`,error:""}}}Kh=Q1([kFA.Injectable(rB,[q1,kFA.collection(mj)])],Kh);var BR0=SA(T1(),1);var S_0=SA(T1(),1);var y_0=SA(P_0(),1);import{spawn as si4}from"node:child_process";import{rm as ti4,writeFile as ei4}from"node:fs/promises";import{tmpdir as Aa4}from"node:os";import{join as Qa4}from"node:path";class uh{logger;#A;#Q;constructor(A,Q,B){this.logger=A,this.#A=Q,this.#Q=B}async buildGitArgs(A,Q,B,D,E){let I=await this.defaultGitArgs(B,D),C=[];if(E)C.push("--git-dir",E,"--work-tree",D);return[...I,...C,A,...Q]}async defaultGitArgs(A,Q){let B=[],D="auth",I=this.#A.get("gitHttpUser")||"auth",C=!0,F=this.#A.get("gitUserEmail")||"",Y=this.#A.get("gitUserName")||"",J;try{J=this.extractBaseURL(A)}catch(G){throw this.logger.error(`Failed to get baseURL for git repo from repositoryUrl "${A}"`,G),G}if(J.length){if(I)B.push("-c",`credential.${J}.username=${I}`);let G=this.#B();if(G)B.push("-c",`url.${J}/.insteadOf=${G}`);else{let X=J.replace(/^https?:\/\//,"");B.push("-c",`url.${J}/.insteadOf=git@${X}:`)}}if(B.push("-c",`safe.directory=${Q}`),B.push("-c",`user.email=${F}`),Y)B.push("-c",`user.name=${Y}`);return B}extractBaseURL(A){if(A==="")return"";try{let Q=z91(A),B=new URL(Q);if(B.protocol!=="http:"&&B.protocol!=="https:")throw Error(`unsupported protocol: ${B.protocol}`);if(!B.origin)throw Error(`invalid URL format: ${A}`);return B.origin}catch(Q){throw Error(`invalid URL: ${A}, ${Q instanceof Error?Q.message:"parsing failed"}`)}}#B(){let A=process.env.CI_REPOSITORY_URL;if(!A)return null;try{let Q=new URL(A),B=`${Q.protocol}//${Q.host}`;if(Q.username||Q.password){let D=Q.password?`${Q.username}:${Q.password}`:Q.username;B=`${Q.protocol}//${D}@${Q.host}`}return B}catch(Q){throw Error(`Failed to parse CI_REPOSITORY_URL, does it contain the expected structure? ${Q instanceof Error?Q.message:"parsing failed"}`)}}async createGitAskPass(){let A=Qa4(Aa4(),`git-askpass-${Xq()}`),Q=`#!/bin/sh
1740
+ ${Y}`,error:""}}}Kh=Q1([kFA.Injectable(rB,[q1,kFA.collection(mj)])],Kh);var BR0=SA(T1(),1);var S_0=SA(T1(),1);var y_0=SA(P_0(),1);import{spawn as si4}from"node:child_process";import{rm as ti4,writeFile as ei4}from"node:fs/promises";import{tmpdir as Aa4}from"node:os";import{join as Qa4}from"node:path";class uh{logger;#A;#Q;constructor(A,Q,B){this.logger=A,this.#A=Q,this.#Q=B}async buildGitArgs(A,Q,B,D,E){let I=await this.defaultGitArgs(B,D),C=[];if(E)C.push("--git-dir",E,"--work-tree",D);return[...I,...C,A,...Q]}async defaultGitArgs(A,Q){let B=[],D="auth",I=this.#A.get("gitHttpUser")||"auth",C=!0,F=this.#A.get("gitUserEmail")||"",Y=this.#A.get("gitUserName")||"",J;try{J=this.extractBaseURL(A)}catch(G){throw this.logger.error(`Failed to get baseURL for git repo from repositoryUrl "${A}"`,G),G}if(J.length){if(I){let X=`!f() { echo username=${I}; echo password=$GIT_PASSWORD; }; f`;B.push("-c",`credential.helper=${X}`)}let G=this.#B();if(G)B.push("-c",`url.${J}/.insteadOf=${G}`);else{let X=J.replace(/^https?:\/\//,"");B.push("-c",`url.${J}/.insteadOf=git@${X}:`)}}if(B.push("-c",`safe.directory=${Q}`),B.push("-c",`user.email=${F}`),Y)B.push("-c",`user.name=${Y}`);return B}extractBaseURL(A){if(A==="")return"";try{let Q=z91(A),B=new URL(Q);if(B.protocol!=="http:"&&B.protocol!=="https:")throw Error(`unsupported protocol: ${B.protocol}`);if(!B.origin)throw Error(`invalid URL format: ${A}`);return B.origin}catch(Q){throw Error(`invalid URL: ${A}, ${Q instanceof Error?Q.message:"parsing failed"}`)}}#B(){let A=process.env.CI_REPOSITORY_URL;if(!A)return null;try{let Q=new URL(A),B=`${Q.protocol}//${Q.host}`;if(Q.username||Q.password){let D=Q.password?`${Q.username}:${Q.password}`:Q.username;B=`${Q.protocol}//${D}@${Q.host}`}return B}catch(Q){throw Error(`Failed to parse CI_REPOSITORY_URL, does it contain the expected structure? ${Q instanceof Error?Q.message:"parsing failed"}`)}}async createGitAskPass(){let A=Qa4(Aa4(),`git-askpass-${Xq()}`),Q=`#!/bin/sh
1741
1741
  echo $GIT_PASSWORD`;return await ei4(A,`#!/bin/sh
1742
- echo $GIT_PASSWORD`,{mode:448}),A}async removeGitAskPass(A){if(!A)return;try{await ti4(A,{force:!0})}catch(Q){this.logger.warn(`Failed to clean up temporary git askpass file: "${A}"`,Q)}}runGitCommand(A,Q,B,D,E){let I=this.#Q.redactSecrets(JSON.stringify(A),"git-command-args");return this.logger.debug(`Running git command with the following argument: ${I}`),new Promise((C,F)=>{let Y=si4("git",A,{shell:!1,cwd:B,env:{PATH:process.env.PATH,HOME:process.env.HOME||process.env.USERPROFILE,GIT_EXEC_PATH:process.env.GIT_EXEC_PATH,GIT_PASSWORD:this.#A.get("gitHttpPassword")||D,GIT_ASKPASS:Q,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_NOGLOBAL:"1",GIT_CONFIG_GLOBAL:"/dev/null",GIT_AUTHOR_NAME:this.#A.get("gitAuthorName")||"",GIT_AUTHOR_EMAIL:this.#A.get("gitAuthorEmail")||"",GIT_COMMITTER_NAME:this.#A.get("gitUserName")||"",GIT_COMMITTER_EMAIL:this.#A.get("gitUserEmail")||"",http_proxy:process.env.http_proxy||process.env.HTTP_PROXY,https_proxy:process.env.https_proxy||process.env.HTTPS_PROXY,all_proxy:process.env.all_proxy||process.env.ALL_PROXY,no_proxy:process.env.no_proxy||process.env.NO_PROXY},signal:E}),J="";Y.stdout.on("data",(G)=>{J+=G}),Y.stderr.on("data",(G)=>{J+=G}),Y.on("error",(G)=>{this.logger.debug("Git command error spawning process",{error:G.message}),F(G)}),Y.on("close",(G)=>{if(G!==0)this.logger.debug(`Git command exited with code ${G}`);C({output:J,exitCode:G})})})}}class KYA extends uh{#A;constructor(A,Q,B,D){super(L1(A,"[NodeGitLsFiles]"),Q,D);this.#A=B}async execute(A,Q="",B="",D){let E="";try{return await y_0.listFiles({dir:A,fs:this.#A,gitdir:D})}catch(I){if(Qr1(I))this.logger.debug(`Repository "${A}" has an unsupported dircache version configured. "isomorphic-git" cannot work with anything other than dircache "2". Falling back to direct system git call`)}try{let C=[],F=await this.buildGitArgs("ls-files",C,Q,A,D);E=await this.createGitAskPass();let Y=await this.runGitCommand(F,E,A,B);if(Y.exitCode!==0)throw Error(`git command failed with exit code ${Y.exitCode}: ${Y.output}`);return this.logger.debug("Command executed successfully"),Y.output.split(`
1743
- `).filter((J)=>J.trim()!=="")}catch(I){throw this.logger.error("Command execution error",I),I}finally{await this.removeGitAskPass(E)}}}KYA=Q1([S_0.Injectable(Ar1,[q1,w4,OJ,CE])],KYA);var c_0=SA(d_0(),1),p_0=SA(T1(),1);import{readFileSync as Za4}from"fs";import{homedir as Ka4}from"os";import{join as wa4}from"path";class HYA{#A;constructor(A){this.#A=L1(A,"[NodeGitConfigCommand]")}async getRemoteUrl(A,Q,B){try{let D=this.#Q(B);if(!D)return B;let E=this.#B(D);if(E!==D){if(this.#A.debug(`Resolved SSH hostname: '${D}' -> '${E}'`),B.startsWith("git@"))return B.replace(`git@${D}:`,`git@${E}:`);try{let I=new URL(B);return I.hostname=E,I.toString()}catch{return B.replace(D,E)}}return B}catch{return B}}#Q(A){try{let Q=A.match(/^git@([^:]+):/);if(Q)return Q[1]??null;return new URL(A).hostname}catch{return null}}#B(A){try{let Q=wa4(Ka4(),".ssh","config"),B=Za4(Q,"utf8"),E=c_0.default.parse(B).compute(A);if(E.HostName)return E.HostName;return A}catch{return A}}}HYA=Q1([p_0.Injectable(Dr1,[q1])],HYA);var La4=i_0(),QiA=e_0();var _a4=1000,AR0=process.platform==="win32"?30000:1e6;function Ra4(A){return QiA(A).map((B)=>{if(typeof B==="string")return B;if(typeof B==="object"&&B!==null){if("pattern"in B)return B.pattern;if("op"in B)return B.op}return String(B)})}function Ta4(A){return A.length<=_a4}function ja4(A,Q){let B=Buffer.from(A).length,D=Buffer.from(Q).length;return B+D<AR0}function QR0(A,Q=""){if(!ja4(A,Q))return{isValid:!1,error:`Command is too long: bytes exceed ${AR0} byte limit on ${process.platform}`};let B;try{B=Ra4(Q)}catch(D){return{isValid:!1,error:D instanceof Error?D.message:"Failed to parse arguments"}}for(let D of B)if(!Ta4(D))return{isValid:!1,error:`Argument too long: ${D.substring(0,50)}...`};return{isValid:!0,args:B}}class ch extends uh{constructor(A,Q,B){super(L1(A,"[RunGitCommandActionHandler]"),Q,B)}name="run_git_command";formatInput(A){return{tool:"run_git_command",command:A.command,commandArgs:A.arguments}}canHandle(A){return Boolean(A.runGitCommand)}async execute({runGitCommand:A},{workspaceFolderPath:Q,workflowToken:B,abortSignal:D}){try{let E=QR0(A.command,A.arguments);if(!E.isValid)throw Error(E.error);let I=await this.buildGitArgs(A.command,E.args??[],A.repository_url,Q),C=await this.createGitAskPass();try{let F=await this.runGitCommand(I,C,Q,B.gitlab_rails.token,D);return this.logger.debug(`Git command "${A.command}" exited with code ${F.exitCode} (${F.output.length} chars)`),{response:`Exit code: ${F.exitCode}
1744
- ${F.output}`,error:""}}finally{await this.removeGitAskPass(C)}}catch(E){return this.logger.error("Git command execution error",E),{response:"",error:`${E instanceof Error?E.message:E}`}}}}ch=Q1([BR0.Injectable(rB,[q1,w4,CE])],ch);var $YA=SA(T1(),1);class ph{#A;#Q;constructor(A,Q){this.#A=L1(A,"[RunShellCommandActionHandler]"),this.#Q=W3(this.#A,Q)}name="shell_command";formatInput(A){return{tool:"shell_command",command:A.command}}canHandle(A){return Boolean(A.runShellCommand)}async execute({runShellCommand:A},{workspaceFolderPath:Q,workflowId:B,abortSignal:D}){let{command:E}=A;this.#A.debug(`Running shell command: "${E}"`);let I=await this.#Q.runShellCommand(B,Q,E,!1,D);if(vFA(I))return{...I,response:""};let{output:C,exitCode:F}=I;return this.#A.debug(`Shell command exited with code ${F} (${C.length} chars)`),{response:`Exit code: ${F}
1742
+ echo $GIT_PASSWORD`,{mode:448}),A}async removeGitAskPass(A){if(!A)return;try{await ti4(A,{force:!0})}catch(Q){this.logger.warn(`Failed to clean up temporary git askpass file: "${A}"`,Q)}}runGitCommand(A,Q,B,D){let E=this.#Q.redactSecrets(JSON.stringify(A),"git-command-args");return this.logger.debug(`Running git command with the following argument: ${E}`),new Promise((I,C)=>{let F=si4("git",A,{shell:!1,cwd:Q,env:{PATH:process.env.PATH,HOME:process.env.HOME||process.env.USERPROFILE,GIT_EXEC_PATH:process.env.GIT_EXEC_PATH,GIT_PASSWORD:this.#A.get("gitHttpPassword")||B,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_NOGLOBAL:"1",GIT_CONFIG_GLOBAL:"/dev/null",GIT_AUTHOR_NAME:this.#A.get("gitAuthorName")||"",GIT_AUTHOR_EMAIL:this.#A.get("gitAuthorEmail")||"",GIT_COMMITTER_NAME:this.#A.get("gitUserName")||"",GIT_COMMITTER_EMAIL:this.#A.get("gitUserEmail")||"",http_proxy:process.env.http_proxy||process.env.HTTP_PROXY,https_proxy:process.env.https_proxy||process.env.HTTPS_PROXY,all_proxy:process.env.all_proxy||process.env.ALL_PROXY,no_proxy:process.env.no_proxy||process.env.NO_PROXY},signal:D}),Y="";F.stdout.on("data",(J)=>{Y+=J}),F.stderr.on("data",(J)=>{Y+=J}),F.on("error",(J)=>{this.logger.debug("Git command error spawning process",{error:J.message}),C(J)}),F.on("close",(J)=>{if(J!==0)this.logger.debug(`Git command exited with code ${J}`);I({output:Y,exitCode:J})})})}}class KYA extends uh{#A;constructor(A,Q,B,D){super(L1(A,"[NodeGitLsFiles]"),Q,D);this.#A=B}async execute(A,Q="",B="",D){try{return await y_0.listFiles({dir:A,fs:this.#A,gitdir:D})}catch(E){if(Qr1(E))this.logger.debug(`Repository "${A}" has an unsupported dircache version configured. "isomorphic-git" cannot work with anything other than dircache "2". Falling back to direct system git call`)}try{let I=[],C=await this.buildGitArgs("ls-files",I,Q,A,D),F=await this.runGitCommand(C,A,B);if(F.exitCode!==0)throw Error(`git command failed with exit code ${F.exitCode}: ${F.output}`);return this.logger.debug("Command executed successfully"),F.output.split(`
1743
+ `).filter((Y)=>Y.trim()!=="")}catch(E){throw this.logger.error("Command execution error",E),E}}}KYA=Q1([S_0.Injectable(Ar1,[q1,w4,OJ,CE])],KYA);var c_0=SA(d_0(),1),p_0=SA(T1(),1);import{readFileSync as Za4}from"fs";import{homedir as Ka4}from"os";import{join as wa4}from"path";class HYA{#A;constructor(A){this.#A=L1(A,"[NodeGitConfigCommand]")}async getRemoteUrl(A,Q,B){try{let D=this.#Q(B);if(!D)return B;let E=this.#B(D);if(E!==D){if(this.#A.debug(`Resolved SSH hostname: '${D}' -> '${E}'`),B.startsWith("git@"))return B.replace(`git@${D}:`,`git@${E}:`);try{let I=new URL(B);return I.hostname=E,I.toString()}catch{return B.replace(D,E)}}return B}catch{return B}}#Q(A){try{let Q=A.match(/^git@([^:]+):/);if(Q)return Q[1]??null;return new URL(A).hostname}catch{return null}}#B(A){try{let Q=wa4(Ka4(),".ssh","config"),B=Za4(Q,"utf8"),E=c_0.default.parse(B).compute(A);if(E.HostName)return E.HostName;return A}catch{return A}}}HYA=Q1([p_0.Injectable(Dr1,[q1])],HYA);var La4=i_0(),QiA=e_0();var _a4=1000,AR0=process.platform==="win32"?30000:1e6;function Ra4(A){return QiA(A).map((B)=>{if(typeof B==="string")return B;if(typeof B==="object"&&B!==null){if("pattern"in B)return B.pattern;if("op"in B)return B.op}return String(B)})}function Ta4(A){return A.length<=_a4}function ja4(A,Q){let B=Buffer.from(A).length,D=Buffer.from(Q).length;return B+D<AR0}function QR0(A,Q=""){if(!ja4(A,Q))return{isValid:!1,error:`Command is too long: bytes exceed ${AR0} byte limit on ${process.platform}`};let B;try{B=Ra4(Q)}catch(D){return{isValid:!1,error:D instanceof Error?D.message:"Failed to parse arguments"}}for(let D of B)if(!Ta4(D))return{isValid:!1,error:`Argument too long: ${D.substring(0,50)}...`};return{isValid:!0,args:B}}class ch extends uh{constructor(A,Q,B){super(L1(A,"[RunGitCommandActionHandler]"),Q,B)}name="run_git_command";formatInput(A){return{tool:"run_git_command",command:A.command,commandArgs:A.arguments}}canHandle(A){return Boolean(A.runGitCommand)}async execute({runGitCommand:A},{workspaceFolderPath:Q,workflowToken:B,abortSignal:D}){try{let E=QR0(A.command,A.arguments);if(!E.isValid)throw Error(E.error);let I=await this.buildGitArgs(A.command,E.args??[],A.repository_url,Q),C=await this.runGitCommand(I,Q,B.gitlab_rails.token,D);return this.logger.debug(`Git command "${A.command}" exited with code ${C.exitCode} (${C.output.length} chars)`),{response:`Exit code: ${C.exitCode}
1744
+ ${C.output}`,error:""}}catch(E){return this.logger.error("Git command execution error",E),{response:"",error:`${E instanceof Error?E.message:E}`}}}}ch=Q1([BR0.Injectable(rB,[q1,w4,CE])],ch);var $YA=SA(T1(),1);class ph{#A;#Q;constructor(A,Q){this.#A=L1(A,"[RunShellCommandActionHandler]"),this.#Q=W3(this.#A,Q)}name="shell_command";formatInput(A){return{tool:"shell_command",command:A.command}}canHandle(A){return Boolean(A.runShellCommand)}async execute({runShellCommand:A},{workspaceFolderPath:Q,workflowId:B,abortSignal:D}){let{command:E}=A;this.#A.debug(`Running shell command: "${E}"`);let I=await this.#Q.runShellCommand(B,Q,E,!1,D);if(vFA(I))return{...I,response:""};let{output:C,exitCode:F}=I;return this.#A.debug(`Shell command exited with code ${F} (${C.length} chars)`),{response:`Exit code: ${F}
1745
1745
  ${C}`,error:""}}}ph=Q1([$YA.Injectable(rB,[q1,$YA.collection(mj)])],ph);var ih=SA(T1(),1);class lh{#A;#Q;constructor(A,Q){this.#A=L1(A,"[RunMcpToolActionHandler]"),this.#Q=Q}name="run_mcp_tool";canHandle(A){return Boolean(A.runMCPTool)}async execute({runMCPTool:A},{abortSignal:Q}){try{let{name:B,args:D}=A;return this.#A.debug(`Running MCP tool: "${B}" with args: "${D}"`),Q.throwIfAborted(),{response:await this.#Q.execute(B,D),error:""}}catch(B){return{error:`${B instanceof Error?B.message:B}`,response:""}}}}lh=Q1([ih.Service({dependencies:[q1,MJ],lifetime:ih.ServiceLifetime.Singleton}),ih.Implements(rB)],lh);var WYA=SA(T1(),1);import{join as Pa4}from"node:path";class ah{#A;#Q;#B;constructor(A,Q,B){this.#A=L1(A,"[WriteFileActionHandler]"),this.#Q=Q,this.#B=W3(this.#A,B)}name="create_file_with_contents";formatInput(A){return{tool:"create_file_with_contents",filepath:A.file_path,content:A.contents}}canHandle(A){return Boolean(A.runWriteFile)}async execute({runWriteFile:A},{workspaceFolderPath:Q,fileStateTracker:B,abortSignal:D}){let E=A.filepath,I=Pa4(Q,E);try{await this.#B.getText(I);let C=`File "${E}" already exists. Use the edit_file tool to modify existing files.`;return this.#A.debug(C),{error:C,response:""}}catch(C){if(!(C instanceof tH))throw this.#A.error(`Failed to check if file exists for: "${E}"`,C),C}try{return await DG(E,Q,this.#B,this.#Q,this.#A),this.#A.debug(`Writing file "${E}"`),D.throwIfAborted(),await this.#B.writeFile(I,A.contents),await this.#D(B,I,E),{response:"File written successfully",error:""}}catch(C){let F=C instanceof Error?C.message:String(C);return this.#A.error(`Error writing file "${I}"`,C),{error:F,response:""}}}async#D(A,Q,B){try{let D=await this.#B.getText(Q);A.recordFileRead(Q,D)}catch(D){this.#A.warn(`Failed to update version cache after edit for "${B}"`,D)}}}ah=Q1([WYA.Injectable(rB,[q1,M2,WYA.collection(_7)])],ah);import{fileURLToPath as Sa4}from"url";var DR0=SA(T1(),1);class nh{#A;#Q;#B;#D;#E;#I;#C;#F;#Y="websocket";constructor(A,Q,B,D,E){this.#I=Q,this.#E=L1(Q,"[Duo Workflow Runner]"),this.#C=B,this.#F=D,this.#D=E;let I=A.get();this.#J(I),A.onConfigChange((C)=>this.#J(C))}#J(A){this.#A=A.workspaceFolders||[],this.#Q=A.projectPath||void 0,this.#B=A.duo?.agentPlatform?.defaultNamespace,this.#Y=this.#G(A)}#G(A){let B=A.duo?.agentPlatform?.connectionType?.toLowerCase();if(B&&xvA.includes(B))return B;return"websocket"}getProjectPath(){return this.#Q||""}getNamespacePath(){return this.#B||""}async preCreateWorkflow(A,Q,B,D,E,I){if(!this.#A||this.#A.length===0)throw Error("No workspace folders");this.#I.debug("Optimistically pre-creating workflow...");let C=await this.#U(A,Q,B,D,E,I);return this.#I.debug(`Workflow "${C}" + auth token pre-created, ready for the user to submit their prompt.`),C}async createWorkflow(A,Q,B,D,E,I){let C=E?.projectPath||this.#Q,F=C?void 0:this.#B;return this.#C.createWorkflow(A,{project_id:C,namespace_id:F},Q,B,D?ly(D):void 0,I)}async*runWorkflow(A){let Q=this.#A?.[0];if(!Q)throw Error("No workspace folders");let B=Sa4(Q.uri);if(this.#A&&this.#A.length>1)this.#E.info(`More than one workspace folder detected. Using workspace folder ${B}`);let{goal:D,existingWorkflowId:E,preCreatedWorkflowId:I,type:C="software_development",workflowDefinition:F,aiCatalogItemVersionId:Y,metadata:J,additionalOptions:G}=A,X=E||I;if(!X)X=await this.#U(D,C,F,Y,J,G);let z=this.#D.getExecutorForWorkflow(X),U={...A,workspaceFolderPath:B,workflowId:X,connectionType:this.#Y};try{this.#D.clearExecutorDisposal(X),yield*z.runWorkflow(U)}finally{this.#D.setupExecutorDisposal(X)}}stopWorkflow(A){let Q=this.#D.getExecutorForWorkflow(A);if(Q)Q.stopWorkflow()}async getGraphqlData(A){return this.#C.getGraphqlData(A)}async updateStatus(A){return this.#C.updateStatus(A)}async sendEvent(A,Q,B){return this.#C.sendEvent(A,Q,B)}async#U(A,Q,B,D,E,I){let C=this.#F.getTokenFromCache({workflowType:Q}),F=E?.projectPath||this.#Q,Y=F?void 0:this.#B,J=[this.#C.createWorkflow(A,{project_id:F,namespace_id:Y},Q,B,D?ly(D):void 0,I)];if(!C){let z=E?.rootNamespaceId;J.push(this.#C.getWorkflowToken(Q,z))}let[G,X]=await Promise.all(J);if(X)this.#F.cacheToken(G,Q,X);return G}}nh=Q1([DR0.Injectable(TZ,[w4,q1,cM,lM,Ts])],nh);var ER0=SA(T1(),1);import{spawn as ya4}from"node:child_process";class oh{#A;constructor(A){this.#A=L1(A,"[RunCommandAsProcess]")}priority=1;#Q(A=process.env){let Q=["CI_JOB_TOKEN","GITLAB_OAUTH_TOKEN","DUO_WORKFLOW_SERVICE_TOKEN"],B={};for(let[D,E]of Object.entries(A))if(!Q.includes(D))B[D]=E;return B}async runCommand(A,Q,B,D,E,I=new AbortController().signal){return this.#A.debug(`Running command: ${B} ${E.join(" ")} in ${Q} for workflowId: ${A}`),this.#B(B,E,{cwd:Q,signal:I,shell:!1})}async runShellCommand(A,Q,B,D,E=new AbortController().signal){return this.#A.debug(`Running shell command: ${B} in ${Q} for workflowId: ${A}`),this.#B(B,[],{cwd:Q,signal:E,shell:!0})}#B(A,Q,B){let{signal:D}=B;return new Promise((E)=>{let I=ya4(A,Q,{...B,env:this.#Q()}),C="",F=()=>{if($b(D?.reason))this.#A.info("Command aborted due to signal"),E({error:"Operation was aborted because the workflow was cancelled or stopped"})};I.stdout?.on("data",(Y)=>{C+=Y}),I.stderr?.on("data",(Y)=>{C+=Y}),I.on("error",(Y)=>{this.#A.error(`Command execution error: ${Y.message}`),D?.removeEventListener("abort",F),E({error:Y.message})}),I.on("close",(Y)=>{this.#A.debug(`Command exited with code ${Y} (${C.length} chars)`),D?.removeEventListener("abort",F),E({output:C,exitCode:Y})}),D?.addEventListener("abort",F)})}}oh=Q1([ER0.Injectable(mj,[q1])],oh);class BiA{id="gitlab";#A;#Q;#B;#D;#E;#I;#C;#F;#Y;#J;#G;#U=[];#z=null;constructor(A,Q,B,D,E,I,C,F,Y){this.#A=L1(A,"[GitLabBackend]"),this.#Q=Q,this.#B=B,this.#D=D,this.#E=E,this.#I=I,this.#C=C,this.#F=F,this.#Y=Y}get#X(){return this.#D.command.name==="run"}async preinitialize(){try{await this.#Y.reloadAllServers(this.#D.cwd),await this.#Y.waitForAllServersSettled(30000),this.#A.info("MCP pre-initialization completed")}catch(A){this.#A.warn("MCP pre-initialization failed (non-critical)",A)}}async initialize(A){if(this.#X&&this.#E.gitlabProjectPath)this.#B.set("projectPath",this.#E.gitlabProjectPath);else{let B=this.#B.get("projectPath");if(B){this.#A.debug(`Found project path in config: ${B}`);try{this.#G=await this.#I.getProjectFromPathWithNamespace(B),this.#A.debug(`Fetched project details for ${B}`)}catch(D){this.#A.warn(`Failed to fetch project details for ${B}. Some features may be unavailable.`,D)}}else this.#A.debug("No project path found in config. Users configured default namespace will be used.")}if(this.#E.connectionType)this.#B.set("duo.agentPlatform.connectionType",this.#E.connectionType);try{this.#U=await this.#F.getSystemContextItems(),this.#A.debug(`Retrieved ${this.#U.length} system context items for GitLab backend`)}catch(B){this.#A.error("Failed to get system context",B),this.#U=[]}let Q;if(A)this.#J=A,this.#A.debug(`Resuming existing workflow: ${A}`);else try{this.#J=await this.#W(),this.#A.debug(`Created new workflow: ${this.#J}`)}catch(B){if(NmA(B))Q=this.#V(B,!0);else{let D=B instanceof Error?B.message:"Unknown error";throw this.#A.error("Failed to create workflow",B),Error(`Failed to initialize workflow: ${D}`)}}if(!this.#J){if(this.#X)throw Error("Workflow ID not available after initialization");this.#A.debug("No workflow ID created - Agentic Chat is not available")}return{sessionId:this.#J||"",sessionRejectionReason:Q}}get#Z(){if(this.#X&&this.#E.workflowType)return this.#E.workflowType;return"chat"}#H(){return oy(this.#G?.id)}#K(){return oy(this.#G?.namespace.id)}#w(){return oy(this.#G?.namespace.rootNamespace?.id)}#V(A,Q){if(this.#X)throw A;let B=A instanceof Error?A.message:"Unknown error checking agentic chat access";return Q?B:`Failed to verify agentic chat access: ${B}. Please check your network connection and GitLab instance availability.`}async#W(){let Q;if(this.#X)Q={allowAgentToRequestUser:!1,agentPrivileges:bvA,preApprovedAgentPrivileges:bvA};this.#z=[...this.#U];let B={rootNamespaceId:this.#w(),selectedModelIdentifier:this.#E.model};return this.#Q.preCreateWorkflow("",this.#Z,void 0,void 0,B,Q)}async*sendMessageStream(A,Q){let B,D;if(this.#X)B=this.#E.flowConfigSchemaVersion,D=this.#E.flowConfig;this.#C.resetStreamState();let E=this.#J;if(!E)try{E=await this.#W()}catch(C){this.#A.error("Error creating workflow",C),yield{type:"ERROR",message:L7(2),timestamp:Date.now()};return}let I=()=>{if(E)this.#A.info(`Aborting workflow ${E}`),this.#Q.stopWorkflow(E)};Q?.addEventListener("abort",I);try{let C={projectId:this.#E.duoWorkflowProjectId||this.#H(),namespaceId:this.#E.duoWorkflowNamespaceId||this.#K(),rootNamespaceId:this.#w(),selectedModelIdentifier:this.#E.model},F={goal:A.type==="SEND_PROMPT"?A.prompt:"approve the tool call",metadata:C,type:this.#Z,existingWorkflowId:E,additionalContext:this.#$(A),toolApproval:A.type==="SEND_TOOL_APPROVAL"?{userApproved:A.approved,toolName:A.toolName,type:A.scope==="session"?"approve-for-session":"approve_once"}:void 0,flowConfig:D,flowConfigSchemaVersion:B,agentPlatformFeatureSettingName:this.#E.agentPlatformFeatureSettingName},Y=this.#Q.runWorkflow(F);for await(let J of Y){if(rH(J)){this.#A.error(`Workflow failed with status code "${J.statusCode}": ${J.message}`),yield{type:"ERROR",message:J.message,timestamp:Date.now()};return}let G=await this.#C.mapWorkflowEvent(J);for(let X of G)yield X}this.#A.info("Workflow completed successfully")}catch(C){this.#A.error("Workflow failed: ",C),yield{type:"ERROR",message:L7(1),timestamp:Date.now()}}finally{Q?.removeEventListener("abort",I)}}#$(A){if(this.#X&&this.#D.command.name==="run"){let Q=this.#D.command.aiContextItems||[],B=[...this.#U,...Q];return this.#A.debug(`AIContextItems: ${this.#U.length} system items + ${Q.length} user items = ${B.length} total`),B}if(A.type==="SEND_PROMPT"){if(this.#z){let B=A.aiContextItems??[],D=[...this.#z,...B];return this.#A.debug(`AIContextItems: ${this.#z.length} system items + ${B.length} user items = ${D.length} total`),this.#z=null,D}let Q=A.aiContextItems??[];return this.#A.debug(`AIContextItems: ${Q.length} user items`),Q}return[]}}class Kt{#A;#Q;#B;#D;#E;#I;#C;#F;#Y;constructor(A,Q,B,D,E,I,C,F,Y){this.#A=A,this.#Q=Q,this.#B=B,this.#D=D,this.#E=E,this.#I=I,this.#C=C,this.#F=F,this.#Y=Y}create(){let A=new Mr(this.#C,this.#A);return new BiA(this.#A,this.#Q,this.#B,this.#D,this.#E,this.#I,A,this.#F,this.#Y)}}Kt=Q1([rh.Implements(Ux),rh.Service({dependencies:[q1,TZ,w4,H9,iM,FwA,pT,AV,_Z],lifetime:rh.ServiceLifetime.Singleton})],Kt);var sh=SA(T1(),1);class wt{#A;#Q;#B;constructor(A,Q,B){this.#A=L1(A,"[SessionDataService]"),this.#Q=Q,this.#B=new Mr(B,A)}async getSessionHistory(A){let Q=A.pageSize??50,B=Boolean(A.beforeCursor),D={type:"chat",first:B?null:Q,last:B?Q:null,after:A.afterCursor??null,before:A.beforeCursor??null,search:A.search??null},E=await this.#Q.getGraphqlData({operationName:"duoWorkflows",query:null,variables:D}),C=(E.duoWorkflowWorkflows.edges??[]).map((Y)=>Y.node).filter((Y)=>!Y.archived).filter((Y)=>!this.#I(Y)).map((Y)=>({id:oy(Y.id),title:Y.goal||"Untitled session",status:Y.humanStatus,lastActivity:Y.updatedAt,lastMessagePreview:this.#E(Y.latestCheckpoint?.duoMessages)})),{pageInfo:F}=E.duoWorkflowWorkflows;return{items:C,pageInfo:{hasNextPage:F.hasNextPage,hasPreviousPage:F.hasPreviousPage,endCursor:F.endCursor||void 0,startCursor:F.startCursor||void 0}}}async getSessionMessages(A){let Q=await this.#D(A);return this.#B.mapChatLogToSessionEvents(Q)}async#D(A){let B=(await this.#Q.getGraphqlData({query:Hb,variables:{workflowId:c0A("Ai::DuoWorkflows::Workflow",A)}})).duoWorkflowWorkflows?.nodes?.[0]?.latestCheckpoint;if(!B)return[];let D=q3A(B);if(D.isErr())return this.#A.error("Failed to extract chat log from checkpoint",D.error),[];return D.value}#E(A){let Q=A?.at(-1);if(!Q)return;if(Q.messageType==="tool")try{let B=JSON.parse(Q.toolInfo??"{}");return`Used tool: ${typeof B.name==="string"?B.name:"unknown"}`}catch{return"Used tool"}return Q.content?.split(/[\r\n]/)[0].trim()}#I(A){return A.latestCheckpoint===null&&(A.goal??"").length<=3}}wt=Q1([sh.Implements(hT),sh.Service({dependencies:[q1,TZ,pT],lifetime:sh.ServiceLifetime.Singleton})],wt);var IR0=SA(T1(),1);class Ht{#A;#Q=new K7;#B;#D;#E;#I;#C;constructor(A,Q,B,D,E){this.#A=L1(A,"[PreConfiguredCliApiService]"),this.#B=Q,this.#D=B,this.#E=new NV(B,A,D,E),this.#A.debug("Pre-configured API service created")}async initialize(){this.#A.debug("Starting pre-configured API initialization (no API calls)");let A=await this.#D.getCredentials(),Q=JIA(this.#B,A);if(!Q)throw Error("Expected workflow token to be present in headless CI mode. This is a bug.");let B=new URL(Q.gitlab_rails.base_url);return this.#I={instanceVersion:Q.duo_workflow_service.headers["X-Gitlab-Version"]||"unknown",instanceUrl:B},this.#C={token:Q.gitlab_rails.token,scopes:[],type:"pat"},this.#Q.fire({isInValidState:!0,instanceInfo:this.#I,tokenInfo:this.#C}),this.#A.debug("Pre-configured API initialization complete, onApiReconfigured event fired"),x4(void 0)}get instanceInfo(){return this.#I}get tokenInfo(){return this.#C}fetchFromApi(A){return this.#E.fetchFromApi(A)}fetchFromApiRaw(A){return this.#E.fetchFromApiRaw(A)}fetchOperation(A){return this.#E.fetchOperation(A)}connectToCable(){return this.#E.connectToCable()}onApiReconfigured=this.#Q.event;getSimpleClient(){return this.#E.getSimpleClient()}}Ht=Q1([IR0.Injectable(f4,[q1,iM,_E,O7,w4])],Ht);var CR0=SA(T1(),1);class Vt{#A;#Q;#B;#D=!1;constructor(A,Q,B){this.#A=L1(A,"[PreConfiguredWorkflowTokenService]"),this.#Q=Q,this.#B=B}async getToken(A,Q){if(this.#D)throw Error("Token service has been disposed");this.#A.debug(`Building token for workflow "${A}", type: "${Q}"`);let B=await this.#B.getCredentials(),D=JIA(this.#Q,B);if(!D)throw Error("Expected workflow token to be present in headless CI mode. This is a bug.");return D}getTokenFromCache(){return null}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.#D=!0,this.#A.debug("Disposed pre-configured token service")}}Vt=Q1([CR0.Injectable(lM,[q1,iM,_E])],Vt);var FR0=SA(T1(),1);class th extends $r{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>`}}th=Q1([FR0.Injectable(hF,[q1])],th);function JR0(A,Q,B="tui"){A.add(YR0.createInstanceDescriptor({instance:Q,aliases:[iM]})),A.addClass(Kt),A.addClass(wt);let D=B==="run"&&Boolean(Q.duoWorkflowServiceServer&&Q.duoWorkflowServiceToken);if(D)PJ0(Q),A.addClass(Vt,Ht),A.addClass(th);else A.addClass(pM,NV);if(!D)A.addClass(B==="run"?th:cT)}class DiA{registerOptions(A){if(FX(A,QIA),A.name()==="run")FX(A,BIA),FX(A,[HJ0(()=>A.parent?.opts().cwd??process.cwd())])}parseOptions(A){return jJ0.parse(A)}registerServices(A,Q,B){JR0(A,Q,B.command.name)}}var DT0=SA(T1(),1);var QT0=SA(T1(),1);var Cm=SA(T1(),1);var vK=SA(T1(),1);var EiA=vK.createInterfaceId("Tools"),va4={name:"list_dir",description:`List directory contents (equivalent to 'ls -la' command).
1746
1746
 
1747
1747
  **Primary use cases:**
@@ -2108,5 +2108,5 @@ Url: ${yGA(A)}`),!0;return!1}function gVB(A,Q){if(A.type||!Q||!Q.length)return!1
2108
2108
  tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as hB8}from"node:util";import{execFile as mB8}from"node:child_process";var uB8=hB8(mB8),dB8={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},MSEdgeDHTML:{name:"Edge",id:"com.microsoft.edge"},MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"}};class _eA extends Error{}async function ReA(A=uB8){let{stdout:Q}=await A("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),B=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(Q);if(!B)throw new _eA(`Cannot find Windows browser in stdout: ${JSON.stringify(Q)}`);let{id:D}=B.groups,E=dB8[D];if(!E)throw new _eA(`Unknown browser ID: ${D}`);return E}var lB8=cB8(pB8),iB8=(A)=>A.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,(Q)=>Q.toUpperCase());async function jeA(){if(TeA.platform==="darwin"){let A=await OeA();return{name:await LeA(A),id:A}}if(TeA.platform==="linux"){let{stdout:A}=await lB8("xdg-mime",["query","default","x-scheme-handler/http"]),Q=A.trim();return{name:iB8(Q.replace(/.desktop$/,"").replace("-"," ")),id:Q}}if(TeA.platform==="win32")return ReA();throw Error("Only macOS, Linux, and Windows are supported")}var sB8=nB8(sTQ.execFile),SeA=rTQ.dirname(aB8(import.meta.url)),lTQ=rTQ.join(SeA,"xdg-open"),{platform:Zu,arch:iTQ}=PeA;async function tB8(){let A=await qeA(),Q=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,B=oTQ.from(Q,"utf16le").toString("base64"),{stdout:D}=await sB8(A,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",B],{encoding:"utf8"}),E=D.trim(),I={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return I[E]?{id:I[E]}:{}}var aTQ=async(A,Q)=>{let B;for(let D of A)try{return await Q(D)}catch(E){B=E}throw B},xUA=async(A)=>{if(A={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...A},Array.isArray(A.app))return aTQ(A.app,(F)=>xUA({...A,app:F}));let{name:Q,arguments:B=[]}=A.app??{};if(B=[...B],Array.isArray(Q))return aTQ(Q,(F)=>xUA({...A,app:{name:F,arguments:B}}));if(Q==="browser"||Q==="browserPrivate"){let F={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},Y={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},J=_O?await tB8():await jeA();if(J.id in F){let G=F[J.id];if(Q==="browserPrivate")B.push(Y[G]);return xUA({...A,app:{name:IS[G],arguments:B}})}throw Error(`${J.name} is not supported as a default browser`)}let D,E=[],I={};if(Zu==="darwin"){if(D="open",A.wait)E.push("--wait-apps");if(A.background)E.push("--background");if(A.newInstance)E.push("--new");if(Q)E.push("-a",Q)}else if(Zu==="win32"||_O&&!zu()&&!Q){if(D=await qeA(),E.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),!_O)I.windowsVerbatimArguments=!0;let F=["Start"];if(A.wait)F.push("-Wait");if(Q){if(F.push(`"\`"${Q}\`""`),A.target)B.push(A.target)}else if(A.target)F.push(`"${A.target}"`);if(B.length>0)B=B.map((Y)=>`"\`"${Y}\`""`),F.push("-ArgumentList",B.join(","));A.target=oTQ.from(F.join(" "),"utf16le").toString("base64")}else{if(Q)D=Q;else{let F=!SeA||SeA==="/",Y=!1;try{await oB8.access(lTQ,rB8.X_OK),Y=!0}catch{}D=PeA.versions.electron??(Zu==="android"||F||!Y)?"xdg-open":lTQ}if(B.length>0)E.push(...B);if(!A.wait)I.stdio="ignore",I.detached=!0}if(Zu==="darwin"&&B.length>0)E.push("--args",...B);if(A.target)E.push(A.target);let C=sTQ.spawn(D,E,I);if(A.wait)return new Promise((F,Y)=>{C.once("error",Y),C.once("close",(J)=>{if(!A.allowNonzeroExitCode&&J>0){Y(Error(`Exited with code ${J}`));return}F(C)})});return C.unref(),C},eB8=(A,Q)=>{if(typeof A!=="string")throw TypeError("Expected a `target`");return xUA({...Q,target:A})};function nTQ(A){if(typeof A==="string"||Array.isArray(A))return A;let{[iTQ]:Q}=A;if(!Q)throw Error(`${iTQ} is not supported`);return Q}function hUA({[Zu]:A},{wsl:Q}){if(Q&&_O)return nTQ(Q);if(!A)throw Error(`${Zu} is not supported`);return nTQ(A)}var IS={};RO(IS,"chrome",()=>hUA({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));RO(IS,"brave",()=>hUA({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));RO(IS,"firefox",()=>hUA({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));RO(IS,"edge",()=>hUA({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));RO(IS,"browser",()=>"browser");RO(IS,"browserPrivate",()=>"browserPrivate");var tTQ=eB8;var eTQ=SA(T1(),1);class jAA{#A;constructor(A){this.#A=L1(A,"[CliUrlOpenerService]")}#Q(A){let Q;try{Q=new URL(A)}catch(B){throw Error(`Invalid URL format: ${B instanceof Error?B.message:String(B)}`)}if(Q.protocol!=="http:"&&Q.protocol!=="https:")throw Error(`Unsupported URL scheme: ${Q.protocol}. Only http: and https: are allowed.`);return Q}async openUrl(A){this.#Q(A),this.#A.debug(`Opening URL: ${A}`);try{await tTQ(A,{wait:!1}),this.#A.debug(`Successfully opened URL: ${A}`)}catch(Q){throw Error(`Failed to open URL (${A}): ${Q instanceof Error?Q.message:String(Q)}`)}}}jAA=Q1([eTQ.Injectable(pa,[q1])],jAA);var mUA=SA(T1(),1);import AjQ from"node:os";var yeA=mUA.createInterfaceId("CliDiagnosticsService");class PAA{#A;#Q;constructor(A,Q){this.#A=A,this.#Q=Q}logDebugDetails(){let{terminalName:A,isKittyProtocolSupported:Q}=this.#Q.envInfo,B={cliVersion:this.#Q.cliVersion,platform:process.platform,arch:process.arch,nodeVersion:process.version,osType:AjQ.type(),osRelease:AjQ.release(),terminalName:A,isKittyProtocolSupported:Q};this.#A.info(`CLI environment details:
2109
2109
  ${JSON.stringify(B,null,4)}`)}}PAA=Q1([mUA.Injectable(yeA,[q1,Fx])],PAA);var KjQ=SA(XjQ(),1);import{basename as A88,join as dUA,relative as zjQ}from"node:path";var wjQ=SA(T1(),1);var ZjQ=10;class yAA extends nvA{chatRequiredFeature="include_file_context";#A;#Q;#B;#D;#E;constructor(A,Q,B,D,E){super("local_file_search",L1(A,"[CliFileContextProvider]"));this.#A=Q,this.#Q=B,this.#B=D,this.#D=E,this.#E=U31(this.#F.bind(this),50)}#I(A){if(A.workspaceFolders&&A.workspaceFolders.length>0)return A.workspaceFolders;return[{uri:JI.file(this.#Q.cwd).toString(),name:A88(this.#Q.cwd)}]}async searchContextItems(A){if(A.query.trim()===""){let Q=this.#I(A);return this.#C(Q)}return this.#E(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([I,C])=>{let F=JI.parse(C.uri).fsPath,Y=await I.getStatus(),J=zjQ(F,I.fsPath);return Y.files.map((G)=>{let X=J?dUA(J,G.path):G.path;return{absolutePath:dUA(I.fsPath,G.path),relativePath:X,workspaceFolder:C}})}));for(let I of D.flat())B.set(I.absolutePath,I);let E=Array.from(B.values()).slice(0,ZjQ);return this.logger.debug(`Found ${E.length} modified files`),Promise.all(E.map((I)=>this.#Y(I)))}async#F(A){let Q=A.query.trim(),B=this.#I(A);this.logger.debug(`Searching for files matching: "${Q}"`);let D=await this.#A.getRepositoriesForWorkspaces(B),E=new Map,I=await Promise.all(Array.from(D.entries()).map(async([Y,J])=>{let G=JI.parse(J.uri).fsPath,X=await Y.getFiles(),z=zjQ(G,Y.fsPath);return X.map((U)=>{let Z=z?dUA(z,U):U;return{absolutePath:dUA(G,Z),relativePath:Z,workspaceFolder:J}})}));for(let Y of I.flat())E.set(Y.absolutePath,Y);let C=Array.from(E.keys()),F=KjQ.filter(C,Q,{maxResults:ZjQ});return this.logger.debug(`Found ${F.length} files matching query`),Promise.all(F.map((Y)=>E.get(Y)).filter((Y)=>Y!==void 0).map((Y)=>this.#Y(Y)))}async#Y(A){let Q=JI.file(A.absolutePath),B=[];if(await Ob(Q,this.#B))B.push(AkA);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.#J(A.relativePath),subType:"local_file_search",subTypeLabel:"Project file",relativePath:A.relativePath,workspaceFolder:A.workspaceFolder,project:this.#D.get("projectPath")??"not a GitLab project"}}}#J(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}}}yAA=Q1([wjQ.Injectable(y3A,[q1,M2,H9,OJ,w4])],yAA);var HjQ=SA(T1(),1);class vAA{#A;#Q;constructor(A,Q){this.#A=L1(Q,"[NewSessionCommandHandler]"),this.#Q=A}command={name:"/new",description:"Start a new chat session",action:"new_session"};async execute(A){this.#A.info("Executing /new command");let Q=this.#Q.getActiveSession();if(Q?.isLoading)this.#A.info(`Cancelling active session "${Q.sessionId}" before starting new session.`),Q.cancelStream();try{await this.#Q.createSession(),A.syncState()}catch(B){this.#A.error("Failed to create new session",B),A.showError("Failed to create new session. Please try again.")}}}vAA=Q1([HjQ.Injectable(xT,[EK,q1])],vAA);var VjQ=SA(T1(),1);class kAA{#A;constructor(A){this.#A=A}command={name:"/sessions",description:"Browse and switch between chat sessions",action:"sessions"};async execute(A){await this.#A.openSearch(A)}}kAA=Q1([VjQ.Injectable(xT,[Zx])],kAA);async function keA(A,Q,B,D,E,I,C){let F=new AF.ServiceCollection,Y={cliVersion:B,envInfo:D};if(F.add(AF.createInstanceDescriptor({instance:Q,aliases:[H9]})),F.add(AF.createInstanceDescriptor({instance:Y,aliases:[Fx]})),F.add(AF.createInstanceDescriptor({instance:E,aliases:[sH]})),A?.logDestination==="stdout")F.addClass(TAA);else F.addClass(fT);F.addClass(Ur,mw,bT,PAA),F.addClass(Cx,Zr),F.add(AF.createFactoryDescriptor({aliases:[Ts],factory:(Z)=>new $FA(Z,Z.getRequiredService(q1)),lifetime:AF.ServiceLifetime.Singleton})),F.addClass(ec,wx,Hx,nh,Hr),F.addClass(Ie),F.addClass(jAA,lh),A3A(F),F.addClass(hj,He,oh,Ih,Ch,Nx,Sk,WN,NN,ch,Uh,Xh,Yh,wm,Km,zh,Zh,ah,Fh,Gh,Kh,ph,Jh),F.add(AF.createInstanceDescriptor({instance:{getDiagnostics:async()=>[]},aliases:[Or]})),F.addClass(ry),F.add(AF.createFactoryDescriptor({aliases:[C_],factory:(Z)=>{let K=Z.getRequiredService(i0A);return{isClientFlagEnabled:()=>!1,isInstanceFlagEnabled:(H)=>K.isInstanceFlagEnabled(H),updateInstanceFeatureFlags:()=>K.updateInstanceFeatureFlags()}},lifetime:AF.ServiceLifetime.Singleton})),F.addClass(Hc,Vc),F.addClass(RAA,Ap,tc,Dp),F.add(AF.createInstanceDescriptor({instance:{isChatFeatureEnabled:()=>Promise.resolve(!0),isSuggestionsFeatureEnabled:()=>Promise.resolve(!0)},aliases:[_b]})),F.addClass(FZ,fk),F.addClass(kb,gb,bb,fb),F.addClass(wn,wr,Kn,Wr,Vx,yAA,Jx,vAA,kAA),F.addClass(Nr),F.addClass(MV),F.addClass(zn),F.addClass(uT),F.addClass(mT),F.addClass(Xx,zx),I.registerServices(F,C,Q);let J=F.build(),G=J.getRequiredService(zr);await G.initialize(),J.getRequiredService(yeA).logDebugDetails(),await J.getRequiredService(O7).initialize();let U=global;return U.__errorHandler=J.getRequiredService(SF),E.setDiContainer(J),{container:J,configurationController:G}}var Q88=process.platform==="win32",cUA=new sH,Qw=new SA1,geA=async(A)=>{let Q=global.__errorHandler;if(Q){let B=new DH("Duo CLI uncaught exception",A);Q.handleError(B.message,B)}else console.error("Duo CLI uncaught exception",A);await cUA.exit(1)};process.on("unhandledRejection",geA);process.on("uncaughtException",geA);function $jQ(A,Q){FX(A,hEA),Q.registerOptions(A),A.action(async()=>{let B=A.optsWithGlobals(),D=CmA(B,"tui"),E=Q.parseOptions(B),I=await eEA(),{container:C,configurationController:F}=await keA({logDestination:"file"},D,pUA,I,cUA,Q,E),Y=C.getRequiredService(_E),{token:J}=await Y.getCredentials();if(F.isMissingConfiguration()&&!J){yiA(F,I,new xw);return}let G=C.getRequiredService(mT),X=C.getRequiredService(q1);s_1(G,I,cUA,X)})}function WjQ(A,Q){let B=A.command("run").description("Run a workflow in non-interactive / headless mode");FX(B,mEA),Q.registerOptions(B),B.action(async()=>{let D=B.optsWithGlobals(),E=CmA(D,"run"),I=Q.parseOptions(D),C=await eEA(),{container:F,configurationController:Y}=await keA({logDestination:"stdout"},E,pUA,C,cUA,Q,I),J=F.getRequiredService(_E),{token:G}=await J.getCredentials();if(Y.isMissingConfiguration()&&!G)throw new TW("--gitlab-auth-token / GITLAB_AUTH_TOKEN option is required.");let X=F.getRequiredService(uT);await X.initialize(),await X.execute()})}var pUA=e8();Qw.name("duo").description("GitLab Duo for your command line").version(pUA,"-v, --version","Display version number");FX(Qw,Gr);Qw.hook("preAction",(A)=>{if(A.optsWithGlobals().logLevel===J3.DEBUG)aXA()});Qw.command("version").description("Show version information for GitLab Duo CLI").action(()=>{console.log(pUA)});var NjQ=new DiA;$jQ(Qw,NjQ);WjQ(Qw,NjQ);var beA=Qw.command("direct",{hidden:!0}).description("Use direct Anthropic backend");FX(beA,Gr);var MjQ=new SiA;$jQ(beA,MjQ);WjQ(beA,MjQ);var B88=Qw.command("config").description("configuration management commands");B88.command("edit").description("edit duo CLI configuration").action(async()=>{let A=await QJ0(),Q=await eEA();yiA(A,Q,new xw)});var lUA=Qw.command("log").description("log management commands");lUA.command("last").description("open the last log file").action(()=>{vJ1()});lUA.command("list").description("list all log files").action(()=>{kJ1()});lUA.command("tail [args...]").description(`tail the last log file. "args" can be any standard ${Q88?'PowerShell "Get-Content"':'"tail"'} arguments`).allowUnknownOption().action((A)=>gJ1(A||[]));lUA.command("clear").description("remove all existing log files").action(()=>{bJ1()});try{await Qw.parseAsync(process.argv)}catch(A){await geA(A)}
2110
2110
 
2111
- //# debugId=845BE255D920BD2D64756E2164756E21
2111
+ //# debugId=36DAF7BA3F04B89164756E2164756E21
2112
2112
  //# sourceMappingURL=index.js.map