@augmentcode/onison 1.2.2 → 1.2.3-prerelease.202611241639

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.
@@ -139,7 +139,7 @@ gpgsig`+YA(s)+`
139
139
  `);;){await this.waitForBytes(1);let n=this.buffer.indexOf(10);if(n!==-1){let o=this.buffer.subarray(0,n).toString("utf8");this.buffer=this.buffer.subarray(n+1);let r=o.split(" ");if(r.length<3)throw new Error(`Unexpected cat-file header: ${o}`);let i=Number.parseInt(r[2],10);if(Number.isNaN(i))throw new Error(`Invalid size in cat-file header: ${o}`);if(i>this.maxBlobSize)throw await this.drainBytes(i+1),new fo(t,i,this.maxBlobSize);await this.waitForBytes(i+1);let s=this.buffer.subarray(0,i),a=new Uint8Array(s);return this.buffer=this.buffer.subarray(i+1),a}await this.waitForBytes(this.buffer.length+1)}}async drainBytes(t){let n=t,o=64*1024;for(;n>0;){let r=Math.min(n,o);await this.waitForBytes(r),this.buffer=this.buffer.subarray(r),n-=r}}dispose(){if(this.alive=!1,this.rejectWait){let t=this.rejectWait;this.resolveWait=null,this.rejectWait=null,t(new Error("BlobBatchReader disposed"))}this.process.stdout?.removeAllListeners(),this.process.stderr?.removeAllListeners(),this.process.removeAllListeners(),this.process.stdin?.end(),this.process.kill(),this.process.unref()}},ig=class{config;constructor(t){this.config=t}async walk(t){let n=Ry(this.config.repoRoot),o=this.config.maxBlobSize??Ya,r=this.config.yieldMs??Vy,i=Date.now();await(0,un.walk)({...n,trees:[(0,un.TREE)({ref:this.config.targetSha})],iterate:async(s,a)=>{let l=[];for(let c of a)l.push(await s(c)),Date.now()-i>=r&&(await new Promise(u=>setTimeout(u,py)),i=Date.now());return l},map:async(s,[a])=>{if(!a||await a.type()!=="blob")return;let l=await a.oid(),c=async()=>{let{blob:d}=await(0,un.readBlob)({...n,oid:l});if(d.byteLength>o)throw new fo(s,d.byteLength,o);return d};await t.onFileAdded(s,c)}})}},sg=class{config;constructor(t){this.config=t}async walk(t){let n=Ry(this.config.repoRoot),o=this.config.maxBlobSize??Ya,r=this.config.yieldMs??Vy,i=Date.now(),s=this.config.baseFileInfoMap??new Map,a=(c,d)=>async()=>{let{blob:u}=await(0,un.readBlob)({...n,oid:c});if(u.byteLength>o)throw new fo(d,u.byteLength,o);return u},l=this.config.baseSha??this.config.targetSha;await(0,un.walk)({...n,trees:[(0,un.TREE)({ref:this.config.targetSha}),(0,un.TREE)({ref:l})],iterate:async(c,d)=>{let u=[];for(let h of d)u.push(await c(h)),Date.now()-i>=r&&(await new Promise(b=>setTimeout(b,py)),i=Date.now());return u},map:async(c,[d,u])=>{let h=d&&await d.type()==="blob"?await d.oid():null,f=u&&await u.type()==="blob"?await u.oid():null;if(h!==f){if(h&&!f){await t.onFileAdded(c,a(h,c));return}if(!h&&f){let b=s.get(c);b&&await t.onFileDeleted(c,b);return}if(h&&f){let b=s.get(c);b?await t.onFileChanged(c,b,a(h,c)):await t.onFileAdded(c,a(h,c))}}}})}},ag=class{config;constructor(t){this.config=t}async walk(t){let{dir:n,gitdir:o}=Zy(this.config.repoRoot),r=this.config.maxBlobSize??Ya,{stdout:i}=await gy("git",["--git-dir",o,"ls-tree","-r","-l","-z",this.config.targetSha],{cwd:n,maxBuffer:100*1024*1024}),s=i.split("\0").filter(Boolean),a=new mu(o,n,r);try{for(let l of s){let c=l.indexOf(" ");if(c===-1)continue;let d=l.slice(0,c),u=l.slice(c+1),h=d.split(/\s+/);if(h[1]!=="blob")continue;let f=h[2],b=Number.parseInt(h[3],10);if(!Number.isNaN(b)&&b>r)continue;let A=f,m=()=>a.isAlive?a.readBlob(A):Sy(o,n,A);await t.onFileAdded(u,m)}}finally{a.dispose()}}},lg=class{config;constructor(t){this.config=t}async walk(t){let{dir:n,gitdir:o}=Zy(this.config.repoRoot),r=this.config.baseFileInfoMap??new Map,i=this.config.baseSha??this.config.targetSha,{stdout:s}=await gy("git",["--git-dir",o,"diff-tree","-r","-z",i,this.config.targetSha],{cwd:n,maxBuffer:100*1024*1024}),a=s.split("\0"),l=this.config.maxBlobSize??Ya,c=new mu(o,n,l),d=u=>()=>c.isAlive?c.readBlob(u):Sy(o,n,u);try{let u=0;for(;u<a.length;){let h=a[u];if(!h?.startsWith(":")){u++;continue}let f=h.slice(1).split(" "),b=f[3],A=f[4]?.[0],m=a[u+1];if(!m||!A){u+=2;continue}switch(A){case"A":{await t.onFileAdded(m,d(b)),u+=2;break}case"D":{let g=r.get(m);g&&await t.onFileDeleted(m,g),u+=2;break}case"M":case"T":{let g=r.get(m);g?await t.onFileChanged(m,g,d(b)):await t.onFileAdded(m,d(b)),u+=2;break}case"R":{let g=a[u+2],E=r.get(m);E&&await t.onFileDeleted(m,E),g&&await t.onFileAdded(g,d(b)),u+=3;break}case"C":{let g=a[u+2];g&&await t.onFileAdded(g,d(b)),u+=3;break}default:u+=2}}}finally{c.dispose()}}},Xy=H.child({prefix:"git-tree-walker"}),cg=class{config;constructor(t){this.config=t}async walk(t){try{await new ag(this.config).walk(t)}catch(n){Xy.info(`native git full walk failed, falling back to isomorphic-git: ${n}`),await new ig(this.config).walk(t)}}},dg=class{config;constructor(t){this.config=t}async walk(t){try{await new lg(this.config).walk(t)}catch(n){Xy.info(`native git incremental walk failed, falling back to isomorphic-git: ${n}`),await new sg(this.config).walk(t)}}}});import{createHash as QO}from"node:crypto";var TO,Si,hg=F(()=>{"use strict";TO=new TextDecoder("utf-8",{fatal:!0}),Si=class{textEncoder=new TextEncoder;maxBlobSize;constructor(t){this.maxBlobSize=t}hash(t,n){let o=QO("sha256");return o.update(t),o.update(n),o.digest("hex")}calculate(t,n){let o=typeof n=="string"?this.textEncoder.encode(n):n;if(!(o.length>this.maxBlobSize)){if(typeof n!="string")try{TO.decode(n)}catch{return}return this.hash(t,o)}}}});var Xi,Wy=F(()=>{"use strict";Xi=class{retryQueue=[];retryInterval;queue;config;constructor(t,n){this.queue=t,this.config=n,this.retryInterval=setInterval(()=>this.flush(),this.config.retryMs)}dispose(){this.retryInterval&&(clearInterval(this.retryInterval),this.retryInterval=void 0)}retry(t){this.retryQueue.push(t)}retryAll(t){this.retryQueue.push(...t)}flush(){for(let t of this.retryQueue)this.queue.enqueue(t);this.retryQueue=[],this.queue.startProcess()}}});var fg,Au,Gy=F(()=>{"use strict";fg={REMOVE_OLDEST:"REMOVE_OLDEST",REJECT_NEW_ITEMS:"REJECT_NEW_ITEMS"},Au=class{queue=[];config;constructor(t={}){this.config={sizeLimit:t.sizeLimit??1e6,queueSizeManagement:t.queueSizeManagement??fg.REMOVE_OLDEST}}enqueue(t){if(this.queue.length>=this.config.sizeLimit){if(this.config.queueSizeManagement===fg.REJECT_NEW_ITEMS)return!1;this.config.queueSizeManagement===fg.REMOVE_OLDEST&&this.queue.shift()}return this.queue.push(t),!0}dequeue(){return this.queue.shift()}isEmpty(){return this.queue.length===0}clear(){this.queue.length=0}peek(){return this.queue[0]}getItems(){return Object.freeze([...this.queue])}size(){return this.queue.length}}});var ya,Iy=F(()=>{"use strict";we();Gy();ya=class{queue;_inProgress=!1;_disposed=!1;logger=H.child({prefix:"SimpleQueueProcessor"});constructor(t=new Au){this.queue=t}enqueue(t){return this.queue.enqueue(t)}dequeue(){return this.queue.dequeue()}isEmpty(){return this.queue.isEmpty()}clear(){this.queue.clear()}peek(){return this.queue.peek()}getItems(){return this.queue.getItems()}size(){return this.queue.size()}dispose(){this._disposed=!0}startProcess(){this._inProgress||(this._inProgress=!0,Promise.resolve().then(async()=>{for(;!this.isEmpty()&&!this.isDisposed();){let t=this.peek();if(await this.internalProcess(),t===this.peek())break}}).catch(t=>{this.logger.error("Unhandled error while processing task",{error:t})}).finally(()=>{this._inProgress=!1}))}isDisposed(){return this._disposed}}});async function bg(e,t,n=KO){let o=n.initialMs;for(let r=1;r<=n.maxTries;r++)try{return await e()}catch(i){if(r===n.maxTries)throw i;t.warn(`Attempt ${r}/${n.maxTries} failed, retrying in ${o}ms: ${i}`),await new Promise(s=>setTimeout(s,o)),o=Math.min(o*n.mult,n.maxMs)}throw new Error("retryWithBackoff: unreachable")}function Ny(e){return typeof e=="string"?e:new TextDecoder("utf-8",{fatal:!0}).decode(e)}function Fy(e){return typeof e=="string"?new TextEncoder().encode(e).length:e.length}var KO,By=F(()=>{"use strict";KO={initialMs:500,mult:2,maxMs:1e4,maxTries:3}});function zO(e,t){let n=new Set(t.unknownBlobNames.concat(t.nonindexedBlobNames)),o=[];for(let r of e)n.has(r)||o.push(r);return o}var Ua,mg,Ag,Wi,gg=F(()=>{"use strict";we();En();Wy();Iy();By();Ua={uploadConfig:{maxUploadSize:1e6,maxBatchCount:128,retryMs:6e4},blobStatusConfig:{maxBatchCount:1e3,oldBlobNameThresholdMs:6e4,giveUpBlobNameThresholdMs:3e5,oldBlobNameRetryMs:6e4,newBlobNameRetryMs:3e3,postUploadDelayMs:1e4}};mg=class extends ya{indexedEmitter=new ce;unknownEmitter=new ce;gaveUpEmitter=new ce;startTimes=new Map;retryOld;retryNew;log=H.child({prefix:"BlobStatusExecutor"});api;cfg;constructor(t,n){super(),this.api=t,this.cfg=n,this.retryOld=new Xi(this,{retryMs:n.oldBlobNameRetryMs}),this.retryNew=new Xi(this,{retryMs:n.newBlobNameRetryMs})}dispose(){super.dispose(),this.startTimes.clear(),this.indexedEmitter.dispose(),this.unknownEmitter.dispose(),this.gaveUpEmitter.dispose(),this.retryOld.dispose(),this.retryNew.dispose()}get onFoundIndexed(){return this.indexedEmitter.event.bind(this.indexedEmitter)}get onFoundUnknown(){return this.unknownEmitter.event.bind(this.unknownEmitter)}get onGaveUp(){return this.gaveUpEmitter.event.bind(this.gaveUpEmitter)}retryBlobNames(t){let n=[],o=[],r=[];for(let i of t){let s=this.startTimes.get(i);if(s===void 0){this.startTimes.set(i,Date.now()),n.push(i);continue}let a=Date.now()-s;a>this.cfg.giveUpBlobNameThresholdMs?(this.startTimes.delete(i),r.push(i)):a>this.cfg.oldBlobNameThresholdMs?o.push(i):n.push(i)}r.length>0&&(this.log.warn(`Giving up on ${r.length} blob(s) after ${this.cfg.giveUpBlobNameThresholdMs}ms`),this.gaveUpEmitter.fire(r)),this.retryNew.retryAll(n),this.retryOld.retryAll(o)}async internalProcess(){let t=new Set,n=0;for(;n<this.cfg.maxBatchCount;){let i=this.dequeue();if(i===void 0)break;t.add(i),this.startTimes.has(i)||this.startTimes.set(i,Date.now()),n++}let o;try{o=await bg(()=>this.api.findMissing([...t]),this.log)}catch{this.retryBlobNames([...t]);return}if(o.unknownBlobNames.length>0){for(let i of o.unknownBlobNames)this.startTimes.delete(i);this.log.debug(`${o.unknownBlobNames.length} blob(s) unknown, triggering re-upload`),this.unknownEmitter.fire(o.unknownBlobNames)}o.nonindexedBlobNames.length>0&&this.retryBlobNames(o.nonindexedBlobNames);let r=zO(t,o);for(let i of r)this.startTimes.delete(i);r.length>0&&this.indexedEmitter.fire(r)}},Ag=class extends ya{uploadedEmitter=new ce;failedEmitter=new ce;rejectedEmitter=new ce;log=H.child({prefix:"UploadExecutor"});retrySched;api;cfg;constructor(t,n){super(),this.api=t,this.cfg=n,this.retrySched=new Xi(this,{retryMs:n.retryMs})}dispose(){super.dispose(),this.uploadedEmitter.dispose(),this.failedEmitter.dispose(),this.rejectedEmitter.dispose(),this.retrySched.dispose()}get onDidUpload(){return this.uploadedEmitter.event.bind(this.uploadedEmitter)}get onFailed(){return this.failedEmitter.event.bind(this.failedEmitter)}get onRejected(){return this.rejectedEmitter.event.bind(this.rejectedEmitter)}async internalProcess(){let t=0,n=[],o=[],r=0;for(;!this.isDisposed()&&r<this.cfg.maxBatchCount;){let i=this.peek();if(i===void 0)break;let s=await i.readContent(),a=Fy(s);if(a>this.cfg.maxUploadSize){this.dequeue(),this.rejectedEmitter.fire({item:i,reason:`File too large: ${a} > ${this.cfg.maxUploadSize} bytes`});continue}if(t+a>this.cfg.maxUploadSize)break;let l;try{l=Ny(s)}catch{this.dequeue(),this.rejectedEmitter.fire({item:i,reason:"File contains invalid UTF-8 encoding"});continue}t+=a,n.push({pathName:i.path,text:l,blobName:i.blobName,metadata:[]}),o.push(i),this.dequeue(),r++}if(n.length!==0)try{let i=await bg(()=>this.api.batchUpload(n),this.log),s=new Map;for(let l=0;l<i.blobNames.length;l++)s.set(n[l].blobName,i.blobNames[l]);let a=n.length-i.blobNames.length;a>0&&this.retrySched.retryAll(o.slice(o.length-a)),s.size>0&&this.uploadedEmitter.fire(s)}catch{this.retrySched.retryAll(o)}}},Wi=class{uploadExec;statusExec;handled=new Map;disposables=[];log=H.child({prefix:"BlobUploader"});blobsUploadedEmitter=new ce;blobsIndexedEmitter=new ce;blobUploadFailedEmitter=new ce;blobRejectedEmitter=new ce;blobNameCalculator;constructor(t,n,o=Ua){this.blobNameCalculator=t,this.uploadExec=new Ag(n,o.uploadConfig),this.statusExec=new mg(n,o.blobStatusConfig);let r=o.blobStatusConfig.postUploadDelayMs;this.disposables.push(this.uploadExec.onDidUpload(i=>{this.log.debug(`uploaded ${i.size} blob(s), waiting ${r}ms before status polling`),this.blobsUploadedEmitter.fire({expectedToActualBlobNameMap:i});for(let[a,l]of i)if(this.handled.has(a)&&a!==l){this.log.debug(`blob name changed by server: ${a} \u2192 ${l}`);let c=this.handled.get(a);c&&this.handled.set(l,c),this.handled.delete(a)}let s=[...i.values()];setTimeout(()=>{for(let a of s)this.statusExec.enqueue(a);this.statusExec.startProcess()},r)})),this.disposables.push(this.uploadExec.onFailed(i=>{this.log.debug(`upload failed: ${i.blobName}`),this.handled.delete(i.blobName),this.blobUploadFailedEmitter.fire({blobName:i.blobName})})),this.disposables.push(this.uploadExec.onRejected(({item:i,reason:s})=>{this.log.debug(`blob rejected: ${i.blobName} (${s})`),this.handled.delete(i.blobName),this.blobRejectedEmitter.fire({blobName:i.blobName,reason:s})})),this.disposables.push(this.statusExec.onFoundIndexed(i=>{this.log.debug(`${i.length} blob(s) confirmed indexed`);for(let s of i)this.handled.delete(s);this.blobsIndexedEmitter.fire({blobNames:i})})),this.disposables.push(this.statusExec.onFoundUnknown(i=>{this.log.debug(`${i.length} blob(s) unknown, re-enqueuing for upload`);for(let s of i){let a=this.handled.get(s);a&&this.uploadExec.enqueue(a)}this.uploadExec.startProcess()})),this.disposables.push(this.statusExec.onGaveUp(i=>{this.log.warn(`${i.length} blob(s) gave up after timeout, marking as failed`);for(let s of i)this.handled.delete(s),this.blobUploadFailedEmitter.fire({blobName:s})}))}get onBlobsUploaded(){return this.blobsUploadedEmitter.event.bind(this.blobsUploadedEmitter)}get onBlobsIndexed(){return this.blobsIndexedEmitter.event.bind(this.blobsIndexedEmitter)}get onBlobUploadFailed(){return this.blobUploadFailedEmitter.event.bind(this.blobUploadFailedEmitter)}get onBlobRejected(){return this.blobRejectedEmitter.event.bind(this.blobRejectedEmitter)}enqueueUpload(t,n){let o=this.blobNameCalculator.calculate(t.path,n);if(o===void 0)return;let r={...t,blobName:o};return this.handled.set(o,r),this.statusExec.enqueue(o),o}startUpload(){this.log.debug(`startUpload: ${this.handled.size} blob(s) in-flight`),this.statusExec.startProcess()}dispose(){for(let t of this.disposables)t.dispose();this.disposables.length=0,this.handled.clear(),this.uploadExec.dispose(),this.statusExec.dispose(),this.blobsUploadedEmitter.dispose(),this.blobsIndexedEmitter.dispose(),this.blobUploadFailedEmitter.dispose(),this.blobRejectedEmitter.dispose()}}});import{execFile as DO}from"node:child_process";import LO from"node:fs";import{promisify as HO}from"node:util";async function Yy(e,t,n,o,r){r.info(`getAncestorCommitShas: targetOid=${n}, depth=${o}`);try{let{stdout:l}=await MO("git",["--git-dir",t,"log","--format=%H","--first-parent","-n",`${o}`,n],{cwd:e,timeout:1e4}),c=l.trim().split(`
140
140
  `).filter(Boolean);if(c.length>0)return r.info(`getAncestorCommitShas via native git: ${c.length} commits`),c}catch(l){r.info(`Native git unavailable, falling back to isomorphic-git: ${l}`)}let i={fs:LO,dir:e,gitdir:t,cache:{}},s=[],a=n;for(let l=0;l<o;l++){let{commit:c}=await(0,Cy.readCommit)({...i,oid:a});if(s.push(a),await new Promise(d=>setTimeout(d,OO)),!c.parent||c.parent.length===0)break;a=c.parent[0]}return r.info(`getAncestorCommitShas via isomorphic-git: ${s.length} commits`),s}var Cy,MO,OO,yy=F(()=>{"use strict";Cy=Ci(rg(),1),MO=HO(DO),OO=1});var jO,Gi,Vg=F(()=>{"use strict";we();En();jO=500,Gi=class{checkpointDelta={checkpointId:void 0,addedBlobs:[],deletedBlobs:[]};batchSize=5e3;flushPromise;log=H.child({prefix:"CheckpointBuilder"});debounceTimer=null;debounceMs;pathToBlobName=new Map;apiServer;onCheckpoint=new ce;constructor(t,n,o=jO){this.apiServer=t,this.debounceMs=o,n&&(this.checkpointDelta.checkpointId=n)}seed(t){for(let[n,o]of t)this.pathToBlobName.set(n,o)}add(t,n){let o=this.pathToBlobName.get(t);if(o===n)return;let r=o?[o]:[];this.pathToBlobName.set(t,n),this.update([n],r)}getPathToBlobName(){return new Map(this.pathToBlobName)}removeByPath(t){let n=this.pathToBlobName.get(t);n&&(this.pathToBlobName.delete(t),this.update([],[n]))}update(t,n){t.length>0&&(this.checkpointDelta.addedBlobs=this.checkpointDelta.addedBlobs.concat(t)),n.length>0&&(this.checkpointDelta.deletedBlobs=this.checkpointDelta.deletedBlobs.concat(n)),this.scheduleCheckpointEvent(),this.isOverLimit()&&this.flushBatch().catch(o=>{this.log.error("Failed to flush checkpoint",{error:o})})}isOverLimit(){return this.checkpointDelta.addedBlobs.length>=this.batchSize||this.checkpointDelta.deletedBlobs.length>=this.batchSize}async flushToLimit(){for(;this.isOverLimit();)await this.flushBatch()}get blobs(){return{checkpointId:this.checkpointDelta.checkpointId,addedBlobs:[...this.checkpointDelta.addedBlobs],deletedBlobs:[...this.checkpointDelta.deletedBlobs]}}async flush(){for(;this.checkpointDelta.addedBlobs.length>0||this.checkpointDelta.deletedBlobs.length>0;)await this.flushBatch();return this.checkpointDelta.checkpointId}scheduleCheckpointEvent(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.onCheckpoint.fire(this.blobs)},this.debounceMs)}flushCheckpointEvent(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null,this.onCheckpoint.fire(this.blobs))}flushBatch(){return this.flushPromise?this.flushPromise:(this.flushPromise=(async()=>{let t=this.checkpointDelta.addedBlobs.slice(0,this.batchSize),n=this.checkpointDelta.deletedBlobs.slice(0,this.batchSize);try{let o=await this.apiServer.checkpointBlobs({checkpointId:this.checkpointDelta.checkpointId,addedBlobs:t,deletedBlobs:n});this.checkpointDelta.checkpointId=o.newCheckpointId,this.checkpointDelta.addedBlobs=this.checkpointDelta.addedBlobs.slice(t.length),this.checkpointDelta.deletedBlobs=this.checkpointDelta.deletedBlobs.slice(n.length),this.scheduleCheckpointEvent()}catch(o){throw this.log.error("Failed to create checkpoint",{error:o}),o}finally{this.flushPromise=void 0}})(),this.flushPromise)}}});var Wg=X((Kse,pu)=>{function vy(e){return Array.isArray(e)?e:[e]}var PO=void 0,Eg="",Uy=" ",pg="\\",qO=/^\s+$/,$O=/(?:[^\\]|^)\\$/,ej=/^\\!/,tj=/^\\#/,nj=/\r?\n/g,oj=/^\.{0,2}\/|^\.{1,2}$/,rj=/\/$/,Ii="/",xy="node-ignore";typeof Symbol<"u"&&(xy=Symbol.for("node-ignore"));var Jy=xy,Ni=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),ij=/([0-z])-([0-z])/g,ky=()=>!1,sj=e=>e.replace(ij,(t,n,o)=>n.charCodeAt(0)<=o.charCodeAt(0)?t:Eg),aj=e=>e.startsWith("!")||e.startsWith("\\^")?`^${e.slice(e[0]==="!"?1:2)}`:e,lj=e=>{let{length:t}=e;return e.slice(0,t-t%2)},cj=[[/^\uFEFF/,()=>Eg],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?Uy:Eg)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+Uy}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let o=n.replace(/\\\*/g,"[^\\/]*");return t+o}],[/\\\\\\(?=[$.|*+(){^])/g,()=>pg],[/\\\\/g,()=>pg],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,o,r)=>t===pg?`\\[${n}${lj(o)}${r}`:r==="]"&&o.length%2===0?`[${aj(sj(n))}${o}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],dj=/(^|\\\/)?\\\*$/,wa="regex",gu="checkRegex",wy="_",uj={[wa](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[gu](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},hj=e=>cj.reduce((t,[n,o])=>t.replace(n,o.bind(e)),e),Vu=e=>typeof e=="string",fj=e=>e&&Vu(e)&&!qO.test(e)&&!$O.test(e)&&e.indexOf("#")!==0,bj=e=>e.split(nj).filter(Boolean),Rg=class{constructor(t,n,o,r,i,s){this.pattern=t,this.mark=n,this.negative=i,Ni(this,"body",o),Ni(this,"ignoreCase",r),Ni(this,"regexPrefix",s)}get regex(){let t=wy+wa;return this[t]?this[t]:this._make(wa,t)}get checkRegex(){let t=wy+gu;return this[t]?this[t]:this._make(gu,t)}_make(t,n){let o=this.regexPrefix.replace(dj,uj[t]),r=this.ignoreCase?new RegExp(o,"i"):new RegExp(o);return Ni(this,n,r)}},mj=({pattern:e,mark:t},n)=>{let o=!1,r=e;r.indexOf("!")===0&&(o=!0,r=r.substr(1)),r=r.replace(ej,"!").replace(tj,"#");let i=hj(r);return new Rg(e,t,r,n,o,i)},Zg=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[Jy]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(Vu(t)&&(t={pattern:t}),fj(t.pattern)){let n=mj(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,vy(Vu(t)?bj(t):t).forEach(this._add,this),this._added}test(t,n,o){let r=!1,i=!1,s;this._rules.forEach(l=>{let{negative:c}=l;i===c&&r!==i||c&&!r&&!i&&!n||!l[o].test(t)||(r=!c,i=c,s=c?PO:l)});let a={ignored:r,unignored:i};return s&&(a.rule=s),a}},Aj=(e,t)=>{throw new t(e)},Fn=(e,t,n)=>Vu(e)?e?Fn.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),_y=e=>oj.test(e);Fn.isNotRelative=_y;Fn.convert=e=>e;var Sg=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:o=!1}={}){Ni(this,Jy,!0),this._rules=new Zg(n),this._strictPathCheck=!o,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(t){return this._rules.add(t)&&this._initCache(),this}addPattern(t){return this.add(t)}_test(t,n,o,r){let i=t&&Fn.convert(t);return Fn(i,t,this._strictPathCheck?Aj:ky),this._t(i,n,o,r)}checkIgnore(t){if(!rj.test(t))return this.test(t);let n=t.split(Ii).filter(Boolean);if(n.pop(),n.length){let o=this._t(n.join(Ii)+Ii,this._testCache,!0,n);if(o.ignored)return o}return this._rules.test(t,!1,gu)}_t(t,n,o,r){if(t in n)return n[t];if(r||(r=t.split(Ii).filter(Boolean)),r.pop(),!r.length)return n[t]=this._rules.test(t,o,wa);let i=this._t(r.join(Ii)+Ii,n,o,r);return n[t]=i.ignored?i:this._rules.test(t,o,wa)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return vy(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},Xg=e=>new Sg(e),gj=e=>Fn(e&&Fn.convert(e),e,ky),Qy=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Fn.convert=e;let t=/^[a-z]:\//i;Fn.isNotRelative=n=>t.test(n)||_y(n)};typeof process<"u"&&process.platform==="win32"&&Qy();pu.exports=Xg;Xg.default=Xg;pu.exports.isPathValid=gj;Ni(pu.exports,Symbol.for("setupWindows"),Qy)});import{extname as Vj}from"node:path";function Gg(e,t=""){let n=e.split(`
141
141
  `).map(r=>r.endsWith("\r")?r.slice(0,-1):r).filter(r=>r.trim()!==""&&!r.trim().startsWith("#"));if(t==="")return n;let o=t.endsWith("/")?t.slice(0,-1):t;return n.map(r=>Zj(r,o))}function Zj(e,t){if(e.startsWith("!")){let n=e.slice(1);return n.startsWith("/")?`!${t}${n}`:`!${t}/**/${n}`}return e.startsWith("/")?t+e:`${t}/**/${e}`}var Ty,pj,Ej,Rj,Eu,Ky=F(()=>{"use strict";we();Ty=Ci(Wg(),1),pj=new Set([".png",".jpg",".jpeg",".gif",".ico",".webp",".svg",".bmp",".tiff",".psd",".ai",".mp3",".mp4",".wav",".mov",".avi",".flv",".mkv",".m4a",".aac",".ogg",".webm",".zip",".tar",".gz",".rar",".7z",".bz2",".xz",".iso",".exe",".dll",".so",".dylib",".o",".a",".lib",".bin",".app",".db",".sqlite",".sqlite3",".mdb",".dat",".class",".pyc",".pyo",".obj",".out",".woff",".woff2",".ttf",".otf",".eot",".fon",".jar",".war",".ear",".apk",".dmg",".deb",".rpm",".crt",".cer",".pem",".key",".lock"]),Ej=[".git","*.pem","*.key","*.pfx","*.p12","*.jks","*.keystore","*.pkcs12","*.crt","*.cer","id_rsa","id_ed25519","id_ecdsa","id_dsa",".augment-guidelines"],Rj=1024*1024,Eu=class{log=H.child({prefix:"IgnoreRulesBlobFilter"});maxFileSize;excludedExtensions;ignoreObj;constructor(t={}){if(this.maxFileSize=t.maxFileSize??Rj,this.excludedExtensions=new Set(pj),t.additionalExcludedExtensions)for(let n of t.additionalExcludedExtensions)this.excludedExtensions.add(n.startsWith(".")?n:`.${n}`);if(this.ignoreObj=(0,Ty.default)(),this.ignoreObj.add(Ej),t.gitignoreContent){let n=Gg(t.gitignoreContent);this.ignoreObj.add(n)}}setAugmentIgnoreRules(t){let n=Gg(t);n.length>0&&(this.ignoreObj.add(n),this.log.info(`Added ${n.length} .augmentignore rules`))}addGitignoreRules(t,n=""){let o=Gg(t,n);o.length>0&&this.ignoreObj.add(o)}shouldAcceptBlob(t){let n=Vj(t.path).toLowerCase();return this.excludedExtensions.has(n)?Promise.resolve({accepted:!1,reason:`Excluded extension: ${n}`}):t.size>this.maxFileSize?Promise.resolve({accepted:!1,reason:`File too large: ${t.size} > ${this.maxFileSize}`}):this.ignoreObj.ignores(t.path)?Promise.resolve({accepted:!1,reason:"Matched ignore rule"}):Promise.resolve({accepted:!0})}}});var Fi,Ig=F(()=>{"use strict";we();En();Fi=class{blobs={};disposables=[];log=H.child({prefix:"IndexOrchestrator"});traversalDone=!1;hadFailures=!1;finalized=!1;doneCallback;_filesAccepted=0;_filesSettled=0;_filesIndexed=0;_filesFailed=0;_filesRejected=0;uploadBatchSize;settledPending=!1;blobFilter;blobUploader;checkpointBuilder;onBlobSettled=new ce;constructor(t,n,o,{uploadBatchSize:r=1e3}={}){this.blobFilter=t,this.blobUploader=n,this.checkpointBuilder=o,this.uploadBatchSize=r,this.wireEvents()}get filesAccepted(){return this._filesAccepted}get filesSettled(){return this._filesSettled}get filesIndexed(){return this._filesIndexed}get filesFailed(){return this._filesFailed}get filesRejected(){return this._filesRejected}get pathToBlobName(){return this.checkpointBuilder.getPathToBlobName()}async addFile(t,n,o){if(!(await this.blobFilter.shouldAcceptBlob({path:t,size:n,readContent:o})).accepted)return;let i=await o(),s=this.blobUploader.enqueueUpload({path:t,readContent:o},i);if(s){for(let[a,l]of Object.entries(this.blobs))l===t&&a!==s&&delete this.blobs[a];this.blobs[s]=t,this._filesAccepted++,(this._filesAccepted%this.uploadBatchSize===0||this.traversalDone)&&this.blobUploader.startUpload()}}removeFile(t){this.log.debug(`removeFile: ${t}`);for(let[n,o]of Object.entries(this.blobs))o===t&&delete this.blobs[n];this.checkpointBuilder.removeByPath(t)}traversalCompleted(){this.log.debug(`traversalCompleted: ${this._filesAccepted} accepted, ${this._filesSettled} settled, ${Object.keys(this.blobs).length} in-flight`),this.traversalDone=!0,this.blobUploader.startUpload(),this.finalizeIfNeeded()}onDone(t){this.doneCallback=t}dispose(){for(let t of this.disposables)t.dispose();this.disposables.length=0,this.onBlobSettled.dispose()}scheduleSettledFire(){this.settledPending||(this.settledPending=!0,queueMicrotask(()=>{this.settledPending=!1,this.onBlobSettled.fire()}))}wireEvents(){this.disposables.push(this.blobUploader.onBlobsIndexed(t=>{for(let n of t.blobNames){let o=this.blobs[n];o&&this.checkpointBuilder.add(o,n),delete this.blobs[n],this._filesSettled++,this._filesIndexed++}this.scheduleSettledFire(),this.finalizeIfNeeded()})),this.disposables.push(this.blobUploader.onBlobsUploaded(t=>{for(let[n,o]of t.expectedToActualBlobNameMap)n!==o&&this.blobs[n]&&(this.blobs[o]=this.blobs[n],delete this.blobs[n])})),this.disposables.push(this.blobUploader.onBlobUploadFailed(t=>{delete this.blobs[t.blobName],this._filesSettled++,this._filesFailed++,this.hadFailures=!0,this.scheduleSettledFire(),this.finalizeIfNeeded()})),this.disposables.push(this.blobUploader.onBlobRejected(t=>{delete this.blobs[t.blobName],this._filesSettled++,this._filesRejected++,this.scheduleSettledFire(),this.finalizeIfNeeded()}))}finalizeIfNeeded(){this.finalized||!this.traversalDone||Object.keys(this.blobs).length>0||(this.finalized=!0,this.log.info("All blobs settled. Finalizing."),this.checkpointBuilder.flush().then(()=>{this.doneCallback?.({hadFailures:this.hadFailures})}).catch(t=>{this.log.error("Failed to flush checkpoint",{error:t}),this.doneCallback?.({hadFailures:!0})}))}}});import{execFile as Sj}from"node:child_process";import{readFile as zy}from"node:fs/promises";import{join as Dy}from"node:path";import{promisify as Xj}from"node:util";var Ly,Ru,Hy=F(()=>{"use strict";ug();we();hg();gg();En();yy();pd();ug();Vg();Ky();Ig();Ly=Xj(Sj),Ru=class{blobNameCalc;blobUploader;log=H.child({prefix:"IsoGitIndexingService"});onProgress=new ce;orchestrator;filesDiscovered=0;currentWorkspaceRoot;indexingStartTime;apiServer;constructor(t,n=1024*1024,o=Ua){this.apiServer=t,this.blobNameCalc=new Si(n),this.blobUploader=new Wi(this.blobNameCalc,t,o)}dispose(){this.orchestrator?.dispose(),this.orchestrator=void 0,this.blobUploader.dispose(),this.onProgress.dispose()}async createBlobFilter(t){let n;try{n=await zy(Dy(t,".gitignore"),"utf-8")}catch{}let o=new Eu({gitignoreContent:n});try{let r=await zy(Dy(t,".augmentignore"),"utf-8");o.setAugmentIgnoreRules(r)}catch{}return o}getIndexingStatus(){let t=this.orchestrator?.filesAccepted??0,n=this.orchestrator?.filesSettled??0;return{itemsInFlight:Math.max(0,t-n),calculateQueueSize:0,probeQueueSize:0,uploadQueueSize:0,probeRetryQueueSize:0,probeRetryBackoffQueueSize:0,calculateErrors:0,probeErrors:0,mtimeCacheHits:0,mtimeCacheMisses:0,pathsAccepted:t,currentFile:void 0,consecutiveNoneIndexedProbes:0,calculateAvgMs:0,calculateMaxMs:0}}emitProgress(t){let n=this.orchestrator?.filesAccepted??0,o=this.orchestrator?.filesSettled??0,r=n>0?Math.floor(o/n*100):0;this.onProgress.fire({phase:t,percentage:r,filesDiscovered:this.filesDiscovered,filesTracked:n,filesProcessed:o,filesIndexed:this.orchestrator?.filesIndexed??0,filesFailed:this.orchestrator?.filesFailed??0,filesRejected:this.orchestrator?.filesRejected??0,filesPreIndexed:0,workspaceRoot:this.currentWorkspaceRoot,durationMs:t==="complete"&&this.indexingStartTime?Date.now()-this.indexingStartTime:void 0})}async findIndexedBaseCommit(t,n,o=20){let r=Pn(t);if(!r.isGitRepo||!r.dir||!r.gitdir)return this.log.warn(`Not a git repository: ${t}`),null;try{let i=await Yy(r.dir,r.gitdir,n,o,this.log);if(i.length===0)return null;this.log.info(`Looking for indexed checkpoint among ${i.length} ancestor commits`);let s=this.apiServer.getLatestIndexedCommitBlobset({commit_shas:i}),a=null,l,c=new Map;for await(let d of s){d.commit_sha&&!a&&(a=d.commit_sha,l=d.checkpoint_id,this.log.info(`Found indexed base commit: ${a}`+(l?` (checkpoint: ${l})`:"")));for(let u of d.file_infos)c.set(u.file_path,u.blob_name)}return a?(this.log.info(`Collected ${c.size} file mappings from base commit`),{commitSha:a,checkpointId:l,fileInfoMap:c}):(this.log.info("No indexed checkpoint found \u2014 will do full tree walk"),null)}catch(i){return this.log.info("No indexed base commit found",{error:i}),null}}async createGitShaCommitIndex(t,n){this.log.info(`Starting indexing for commit ${n} in repo ${t}`),this.currentWorkspaceRoot=t,this.indexingStartTime=Date.now(),this.emitProgress("qualifying");let o=Pn(t);if(!o.isGitRepo||!o.dir||!o.gitdir)throw new Error(`Not a git repository: ${t}`);let{dir:r,gitdir:i,headRef:s}=o,a=n==="HEAD"&&s?s:n,l;try{let{stdout:N}=await Ly("git",["--git-dir",i,"rev-parse",a],{cwd:r});l=N.trim(),this.log.info(`Resolved commit ${n} to OID ${l}`)}catch(N){throw new Error(`Failed to resolve commit ${n}: ${N}`)}let c=await this.createBlobFilter(t),d;try{let{stdout:N}=await Ly("git",["--git-dir",i,"log","-1","--format=%ct",l],{cwd:r});d=Number.parseInt(N.trim(),10)*1e3}catch(N){throw new Error(`Failed to read commit ${l}: ${N}`)}let u=await this.findIndexedBaseCommit(t,l);if(u&&u.commitSha===l)return this.log.info("Target commit already indexed, nothing to do"),this.emitProgress("complete"),{commitSha:l,filesIndexed:0,alreadyIndexed:!0,registered:!1,durationMs:Date.now()-(this.indexingStartTime??Date.now())};this.emitProgress("indexing");let h=new Gi(this.apiServer,u?.checkpointId);if(u)if(u.checkpointId)this.log.info(`Resuming from checkpoint ${u.checkpointId} (${u.fileInfoMap.size} base files)`);else{let N=Array.from(u.fileInfoMap.values());this.log.info(`Seeding checkpoint with ${N.length} blobs from base commit`),h.update(N,[]),await h.flushToLimit()}let f=new Fi(c,this.blobUploader,h);this.orchestrator=f;let b=!1,A=new Promise(N=>{f.onDone(async V=>{if(V.hadFailures)this.log.warn("Not registering commit blobset due to failures");else try{await this.apiServer.registerIndexedCommitBlobset({commit:{commit_sha:l,commit_time:new Date(d).toISOString()},blobs:h.blobs}),b=!0,this.log.info(`Checkpoint registered: commit ${l}, ${f.filesSettled} files indexed`)}catch(Z){this.log.error("Failed to register commit blobset",{error:Z})}this.emitProgress("complete"),N()})}),m=f.onBlobSettled.event(()=>{this.emitProgress("indexing")}),g=()=>{this.filesDiscovered++,this.filesDiscovered%1e3===0&&this.emitProgress("indexing")},E={async onFileAdded(N,V){let Z;try{Z=await V()}catch(p){if(p instanceof fo)return;throw p}await f.addFile(N,Z.length,async()=>Z),g()},async onFileChanged(N,V,Z){let p;try{p=await Z()}catch(B){if(B instanceof fo)return;throw B}await f.addFile(N,p.length,async()=>p),g()},onFileDeleted(N){f.removeFile(N)}},R=Ey({repoRoot:t,targetSha:l,baseSha:u?.commitSha,baseFileInfoMap:u?.fileInfoMap});this.log.info(u?`Incremental walk from base ${u.commitSha} to ${l}`:`Full tree walk for ${l}`),await R.walk(E),this.emitProgress("indexing"),f.traversalCompleted(),await A,m.dispose();let G=f.filesSettled,S=Date.now()-(this.indexingStartTime??Date.now());return this.log.info(`Git SHA indexing complete: ${G} files, ${(S/1e3).toFixed(1)}s, registered=${b}`),f.dispose(),this.orchestrator===f&&(this.orchestrator=void 0),{commitSha:l,filesIndexed:G,alreadyIndexed:!1,registered:b,durationMs:S}}}});import{watch as My}from"node:fs";import{readdir as Wj,stat as Gj}from"node:fs/promises";import{join as Oy,relative as Ng}from"node:path";var Ij,Nj,Zu,Su,jy=F(()=>{"use strict";we();En();Ij=500,Nj=new Set([".git","node_modules",".hg",".svn","__pycache__",".tox",".mypy_cache",".pytest_cache",".next",".nuxt",".output",".turbo",".vercel",".cache",".parcel-cache"]),Zu=H.child({prefix:"FileWatcher"}),Su=class{workspaceRoot;debounceMs;skipDirs;shouldWatch;onChange=new ce;watchers=[];pendingEvents=new Map;debounceTimer=null;running=!1;constructor(t){this.workspaceRoot=t.workspaceRoot,this.debounceMs=t.debounceMs??Ij,this.skipDirs=new Set([...Nj,...t.skipDirectories??[]]),this.shouldWatch=t.shouldWatchDirectory}async start(){if(this.running)return;this.running=!0;let t=process.platform==="darwin"||process.platform==="win32";t?this.startRecursive():await this.startPerDirectory(this.workspaceRoot),Zu.info(`Started watching ${this.workspaceRoot} (${t?"recursive":"per-directory"}, ${this.watchers.length} watcher(s))`)}stop(){if(this.running){this.running=!1;for(let t of this.watchers)t.close();this.watchers=[],this.flush(),Zu.info("Stopped watching")}}startRecursive(){let t=My(this.workspaceRoot,{recursive:!0},(n,o)=>{if(!o||!this.running)return;let r=o.toString();this.shouldSkip(r)||this.enqueue(r,n==="rename"?"rename":"change")});t.on("error",n=>{Zu.warn("Watcher error",{error:n})}),this.watchers.push(t)}async startPerDirectory(t){if(!this.running)return;let n=Ng(this.workspaceRoot,t);if(n&&this.shouldSkipDir(n))return;this.watchSingleDirectory(t);let o;try{o=await Wj(t,{withFileTypes:!0})}catch{return}let r=[];for(let i of o)if(i.isDirectory()&&!this.skipDirs.has(i.name)){let s=n?`${n}/${i.name}`:i.name;if(this.shouldWatch&&!this.shouldWatch(s))continue;r.push(this.startPerDirectory(Oy(t,i.name)))}await Promise.all(r)}watchSingleDirectory(t){let n=My(t,(o,r)=>{if(!r||!this.running)return;let i=Oy(t,r.toString()),s=Ng(this.workspaceRoot,i);this.shouldSkip(s)||(this.enqueue(s,o==="rename"?"rename":"change"),o==="rename"&&this.maybeWatchNewDirectory(i))});n.on("error",o=>{Zu.warn(`Watcher error on ${t}`,{error:o})}),this.watchers.push(n)}maybeWatchNewDirectory(t){Gj(t).then(n=>{if(n.isDirectory()&&this.running){let o=Ng(this.workspaceRoot,t);if(this.shouldSkipDir(o)||this.shouldWatch&&!this.shouldWatch(o))return;this.watchSingleDirectory(t)}}).catch(()=>{})}shouldSkip(t){let n=t.split("/");if(n.some(o=>this.skipDirs.has(o)))return!0;if(this.shouldWatch&&n.length>1){let o=n.slice(0,-1).join("/");if(!this.shouldWatch(o))return!0}return!1}shouldSkipDir(t){return t.split("/").some(o=>this.skipDirs.has(o))}enqueue(t,n){this.pendingEvents.set(t,n),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.flush(),this.debounceMs)}flush(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingEvents.size===0)return;let t=[];for(let[n,o]of this.pendingEvents)t.push({type:o,relativePath:n});this.pendingEvents.clear(),this.onChange.fire(t)}}});import{readFile as Fj,stat as Bj}from"node:fs/promises";import{basename as Cj,join as Yj}from"node:path";var yj,Py,Xu,qy=F(()=>{"use strict";we();En();yj=new Set([".gitignore",".augmentignore"]),Py=H.child({prefix:"WatcherProcessor"}),Xu=class{workspaceRoot;blobFilter;orchestrator;subscription=null;onUpdate=new ce;constructor(t){this.workspaceRoot=t.workspaceRoot,this.blobFilter=t.blobFilter,this.orchestrator=t.orchestrator}attach(t){this.detach(),this.subscription=t.onChange.event(n=>{this.processBatch(n).catch(o=>{Py.error("Failed to process watcher batch",{error:o})})})}detach(){this.subscription?.dispose(),this.subscription=null}dispose(){this.detach(),this.onUpdate.dispose()}async processBatch(t){let n=[],o=[];for(let s of t){let a=Cj(s.relativePath);yj.has(a)?n.push(s):o.push(s)}for(let s of n)this.blobFilter.updateIgnoreFile(s.relativePath);if(o.length===0)return;let r=0,i=0;for(let s of o){let a=Yj(this.workspaceRoot,s.relativePath),l=null;try{l=await Bj(a)}catch{}if(!l?.isFile()){this.orchestrator.removeFile(s.relativePath),i++;continue}await this.orchestrator.addFile(s.relativePath,l.size,()=>Fj(a)),r++}(r>0||i>0)&&(Py.info(`Processed batch: ${r} added, ${i} deleted`),this.onUpdate.fire({filesAdded:r,filesDeleted:i}))}}});import{readdir as Uj,stat as wj}from"node:fs/promises";import{join as vj,relative as $y}from"node:path";async function*eU(e,t,n={}){let o=new Set([...xj,...n.skipDirectories??[]]),r=n.signal,i=n.shouldEnterDirectory;async function*s(a){if(r?.aborted)return;let l;try{l=await Uj(a,{withFileTypes:!0})}catch(c){Jj.warn(`Cannot read directory ${a}`,{error:c});return}for(let c of l){if(r?.aborted)return;let d=vj(a,c.name);if(c.isDirectory()){if(o.has(c.name))continue;if(i){let u=$y(e,d);if(!i(u))continue}yield*s(d)}else if(c.isFile())try{let u=await wj(d);yield{relativePath:$y(e,d),absolutePath:d,size:u.size}}catch{}}}yield*s(t)}var xj,Jj,tU=F(()=>{"use strict";we();xj=new Set([".git","node_modules",".hg",".svn","__pycache__",".tox",".mypy_cache",".pytest_cache",".next",".nuxt",".output",".turbo",".vercel",".cache",".parcel-cache","dist","build","out","coverage",".idea",".vscode"]),Jj=H.child({prefix:"FileWalker"})});import{existsSync as nU,readFileSync as oU}from"node:fs";import{dirname as Yg,extname as kj,join as Fg}from"node:path";function rU(e){return e.split(`
142
- `).map(t=>t.endsWith("\r")?t.slice(0,-1):t).filter(t=>t.trim()!==""&&!t.trim().startsWith("#"))}function Cg(e){let t=[],n=Yg(e);for(;n!==".";)t.push(n),n=Yg(n);return t.push(""),t}function va(e,t,n,o,r=!1){for(let i of e){let s=t.get(i);if(!s)continue;let a=s[o];if(!a)continue;let l=r&&i?n.slice(i.length+1):n,c=a.test(l);if(c.unignored||c.ignored)return c}}var Wu,_j,Qj,Tj,Bg,Gu,iU=F(()=>{"use strict";we();Wu=Ci(Wg(),1),_j=new Set([".png",".jpg",".jpeg",".gif",".ico",".webp",".svg",".bmp",".tiff",".psd",".ai",".mp3",".mp4",".wav",".mov",".avi",".flv",".mkv",".m4a",".aac",".ogg",".webm",".zip",".tar",".gz",".rar",".7z",".bz2",".xz",".iso",".exe",".dll",".so",".dylib",".o",".a",".lib",".bin",".app",".db",".sqlite",".sqlite3",".mdb",".dat",".class",".pyc",".pyo",".obj",".out",".woff",".woff2",".ttf",".otf",".eot",".fon",".jar",".war",".ear",".apk",".dmg",".deb",".rpm",".crt",".cer",".pem",".key",".lock"]),Qj=[".git","*.pem","*.key","*.pfx","*.p12","*.jks","*.keystore","*.pkcs12","*.crt","*.cer","id_rsa","id_ed25519","id_ecdsa","id_dsa",".augment-guidelines"],Tj=1024*1024,Bg=H.child({prefix:"HierarchicalIgnoreFilter"});Gu=class{workspaceRoot;maxFileSize;excludedExtensions;builtinIgnore;rulesMap=new Map;constructor(t){if(this.workspaceRoot=t.workspaceRoot,this.maxFileSize=t.maxFileSize??Tj,this.excludedExtensions=new Set(_j),t.additionalExcludedExtensions)for(let n of t.additionalExcludedExtensions)this.excludedExtensions.add(n.startsWith(".")?n:`.${n}`);this.builtinIgnore=(0,Wu.default)(),this.builtinIgnore.add(Qj)}loadDirectory(t){let n=t?Fg(this.workspaceRoot,t):this.workspaceRoot,o={},r=!1,i=Fg(n,".augmentignore");if(nU(i))try{let a=oU(i,"utf-8"),l=rU(a);if(l.length>0){let c=(0,Wu.default)();c.add(l),o.augmentignore=c,r=!0}}catch(a){Bg.warn(`Failed to read ${i}`,{error:a})}let s=Fg(n,".gitignore");if(nU(s))try{let a=oU(s,"utf-8"),l=rU(a);if(l.length>0){let c=(0,Wu.default)();c.add(l),o.gitignore=c,r=!0}}catch(a){Bg.warn(`Failed to read ${s}`,{error:a})}r?this.rulesMap.set(t,o):this.rulesMap.delete(t)}updateIgnoreFile(t){let n=Yg(t),o=n==="."?"":n;this.loadDirectory(o),Bg.debug(`Updated ignore rules for directory: ${o||"root"}`)}removeDirectory(t){this.rulesMap.delete(t)}isAugmentIgnored(t,n=!1){let o=n?`${t.replace(/\/$/,"")}/`:t;return va(Cg(t),this.rulesMap,o,"augmentignore",!0)?.ignored??!1}isDirectoryIgnored(t){let n=t.endsWith("/")?t:`${t}/`,o=Cg(t),r=va(o,this.rulesMap,n,"augmentignore");if(r)return r.ignored;let i=va(o,this.rulesMap,n,"gitignore");return i?i.ignored:!1}shouldAcceptBlob(t){let{path:n,size:o}=t,r=Cg(n),i=va(r,this.rulesMap,n,"augmentignore");if(i)return i.unignored?Promise.resolve({accepted:!0}):Promise.resolve({accepted:!1,reason:"Matched .augmentignore rule"});if(this.builtinIgnore.ignores(n))return Promise.resolve({accepted:!1,reason:"Matched builtin security pattern"});let s=kj(n).toLowerCase();if(this.excludedExtensions.has(s))return Promise.resolve({accepted:!1,reason:`Excluded extension: ${s}`});if(o>this.maxFileSize)return Promise.resolve({accepted:!1,reason:`File too large: ${o} > ${this.maxFileSize}`});let a=va(r,this.rulesMap,n,"gitignore");return a?a.unignored?Promise.resolve({accepted:!0}):Promise.resolve({accepted:!1,reason:"Matched .gitignore rule"}):Promise.resolve({accepted:!0})}}});import{readFile as sU}from"node:fs/promises";import{basename as Kj}from"node:path";var zj,Iu,aU=F(()=>{"use strict";we();hg();gg();En();jy();qy();Vg();tU();iU();Ig();zj=2e5,Iu=class{blobNameCalc;blobUploader;log=H.child({prefix:"WorkspaceIndexingService"});onProgress=new ce;onCheckpoint=new ce;orchestrator;blobFilter;checkpointSub;fileWatcher=null;watcherProcessor=null;walkComplete=!1;filesDiscovered=0;filesPreIndexed=0;currentWorkspaceRoot;indexingStartTime;onWatcherUpdate=new ce;apiServer;constructor(t,n=1024*1024,o=Ua){this.apiServer=t,this.blobNameCalc=new Si(n),this.blobUploader=new Wi(this.blobNameCalc,t,o)}dispose(){this.stopWatcher(),this.checkpointSub?.dispose(),this.checkpointSub=void 0,this.orchestrator?.dispose(),this.orchestrator=void 0,this.blobUploader.dispose(),this.onProgress.dispose(),this.onCheckpoint.dispose(),this.onWatcherUpdate.dispose()}createBlobFilter(t){let n=new Gu({workspaceRoot:t});return n.loadDirectory(""),n}async startWatcher(t){if(this.stopWatcher(),!this.orchestrator||!this.blobFilter)throw new Error("Cannot start watcher before workspace has been indexed with indexWorkspace()");let n=this.blobFilter;this.fileWatcher=new Su({workspaceRoot:t,shouldWatchDirectory:o=>(n.loadDirectory(o),!n.isDirectoryIgnored(o))}),this.watcherProcessor=new Xu({workspaceRoot:t,blobFilter:n,orchestrator:this.orchestrator}),this.watcherProcessor.onUpdate.event(o=>{this.onWatcherUpdate.fire(o)}),this.watcherProcessor.attach(this.fileWatcher),await this.fileWatcher.start(),this.log.info(`File watcher started for ${t}`)}stopWatcher(){this.fileWatcher?.stop(),this.watcherProcessor?.dispose(),this.fileWatcher=null,this.watcherProcessor=null}getIndexingStatus(){let t=this.orchestrator?.filesAccepted??0,n=this.orchestrator?.filesSettled??0;return{itemsInFlight:Math.max(0,t-n),calculateQueueSize:0,probeQueueSize:0,uploadQueueSize:0,probeRetryQueueSize:0,probeRetryBackoffQueueSize:0,calculateErrors:0,probeErrors:0,mtimeCacheHits:0,mtimeCacheMisses:0,pathsAccepted:t,currentFile:void 0,consecutiveNoneIndexedProbes:0,calculateAvgMs:0,calculateMaxMs:0}}emitProgress(t){let n=this.orchestrator?.filesAccepted??0,o=this.orchestrator?.filesSettled??0,r=n+this.filesPreIndexed,i=o+this.filesPreIndexed,s=r>0?Math.floor(i/r*100):0;this.onProgress.fire({phase:t,percentage:s,filesDiscovered:this.filesDiscovered,filesTracked:n,filesProcessed:o,filesIndexed:this.orchestrator?.filesIndexed??0,filesFailed:this.orchestrator?.filesFailed??0,filesRejected:this.orchestrator?.filesRejected??0,filesPreIndexed:this.filesPreIndexed,walkComplete:this.walkComplete,workspaceRoot:this.currentWorkspaceRoot,durationMs:t==="complete"&&this.indexingStartTime?Date.now()-this.indexingStartTime:void 0})}async indexWorkspace(t,n,o={}){if(this.fileWatcher)return this.log.error(`Cannot index workspace for ${n}: file watcher is already active`),{checkpointId:void 0,filesTracked:0,filesProcessed:0,filesSkipped:0,durationMs:0,pathToBlobName:new Map};this.log.info(`Starting workspace indexing for ${n}`+(n===t?"":` (workspace root: ${t})`)),this.walkComplete=!1,this.filesDiscovered=0,this.filesPreIndexed=0,this.currentWorkspaceRoot=t,this.indexingStartTime=Date.now(),this.emitProgress("qualifying");let r=this.createBlobFilter(t);this.blobFilter=r;let i=o.baselineCheckpointId,s=new Gi(this.apiServer,i),a=!1;this.checkpointSub?.dispose(),this.checkpointSub=s.onCheckpoint.event(S=>{a=!0,this.onCheckpoint.fire(S)}),this.orchestrator?.dispose();let l=new Fi(r,this.blobUploader,s);this.orchestrator=l;let c=o.preIndexedFiles;if(c&&c.size>0)if(s.seed(c),this.filesPreIndexed=c.size,i)this.log.info(`Resuming from checkpoint ${i} (${c.size} pre-indexed files)`),a=!0,this.onCheckpoint.fire({checkpointId:i,addedBlobs:[],deletedBlobs:[]});else{let S=Array.from(c.values());this.log.info(`Seeding checkpoint with ${S.length} pre-indexed blobs`),s.update(S,[]),await s.flushToLimit()}i&&o.retiredFiles?.size&&s.update([],Array.from(o.retiredFiles.values()));let d=o.revalidateFiles,u=new Set(d?.keys());i&&d?.size&&s.seed(d);let h=new Promise((S,N)=>{l.onDone(V=>{V.hadFailures&&this.log.warn("Workspace indexing completed with failures"),this.emitProgress("complete"),S()})}),f=l.onBlobSettled.event(()=>{this.emitProgress("indexing")});this.emitProgress("indexing");let b={skipDirectories:o.skipDirectories,signal:o.signal,shouldEnterDirectory:S=>(r.loadDirectory(S),!r.isDirectoryIgnored(S))},A=o.maxTrackableFiles??zj,m=0;for await(let S of eU(t,n,b)){if(o.signal?.aborted)break;if(l.filesAccepted>=A){this.log.warn(`Workspace exceeds ${A} trackable files, stopping walk`),this.emitProgress("workspace-too-large");break}this.filesDiscovered++;let N=Kj(S.relativePath);if(N===".gitignore"||N===".augmentignore"){r.updateIgnoreFile(S.relativePath);continue}if(d?.has(S.relativePath)){u.delete(S.relativePath),(await r.shouldAcceptBlob({path:S.relativePath,size:S.size,readContent:()=>sU(S.absolutePath)})).accepted?(m++,this.filesPreIndexed++):s.removeByPath(S.relativePath);continue}if(c?.has(S.relativePath)){m++;continue}await l.addFile(S.relativePath,S.size,()=>sU(S.absolutePath)),this.filesDiscovered%1e3===0&&this.emitProgress("indexing")}for(let S of u)s.removeByPath(S);m>0&&this.log.info(`Skipped ${m} pre-indexed files (incremental)`),this.walkComplete=!0,this.emitProgress("indexing"),l.traversalCompleted(),await h,f.dispose(),s.flushCheckpointEvent();let g=s.blobs.checkpointId;!a&&g&&this.onCheckpoint.fire({checkpointId:g,addedBlobs:[],deletedBlobs:[]});let E=Date.now()-(this.indexingStartTime??Date.now()),R=l.filesAccepted,G=l.filesSettled;return this.log.info(`Workspace indexing complete: ${R} tracked, ${G} processed, ${m} skipped (pre-indexed), ${(E/1e3).toFixed(1)}s, checkpoint: ${g??"none"}`),{checkpointId:g,filesTracked:R,filesProcessed:G,filesSkipped:m,durationMs:E,pathToBlobName:l.pathToBlobName}}}});var dU={};ka(dU,{ContextIndexer:()=>Ug});import{relative as lU,resolve as cU}from"node:path";function yg(e,t){let n=new Map;for(let[o,r]of e)o.startsWith(t)&&n.set(o,r);return n}var Ug,uU=F(()=>{"use strict";we();EN();En();pd();Hy();aU();Ug=class{gitService;workspaceService;deltaResolver;log=H.child({prefix:"ContextIndexer"});onIndexing=new ce;onCheckpoint=new ce;onWatcherUpdate=new ce;constructor(t,n={}){this.gitService=new Ru(t,n.maxBlobSize,n.uploaderConfig),this.workspaceService=new Iu(t,n.maxBlobSize,n.uploaderConfig),this.deltaResolver=new gd(t,n.deltaResolverOptions),this.workspaceService.onProgress.event(o=>{this.onIndexing.fire(o)}),this.workspaceService.onCheckpoint.event(o=>{this.onCheckpoint.fire(o)}),this.workspaceService.onWatcherUpdate.event(o=>{this.onWatcherUpdate.fire(o)})}getGitRepoDetails(t){return Pn(t)}async indexWorkspace(t,n,o){let r=cU(t),i=cU(n),s=RN(r),a,l,c,d,u=null;this.log.info("Looking for previously indexed git SHA...");try{let f=s?await this.deltaResolver.resolveIndexedCommitDelta(s):null;if(f&&s){this.log.info(`Found indexed commit ${f.indexedCommitSha}: ${f.fileInfoMap.size} unchanged, ${f.modifiedFiles.size} modified, ${f.addedFiles.size} added, ${f.deletedFiles.size} deleted, ${f.untrackedFiles.size} untracked`);let b=s===r?"":`${lU(s,r)}/`,A=i===r?b:`${lU(s,i)}/`,m=yg(f.fileInfoMap,A),g=yg(f.retiredFileInfoMap,A),E=yg(f.revalidateFileInfoMap,A);u={commitSha:f.indexedCommitSha,fileCount:m.size},m.size!==f.fileInfoMap.size&&this.log.info(`Filtered delta to ${m.size} files under ${A} (was ${f.fileInfoMap.size})`),a=m,s===r&&i===r&&(l=f.checkpointId,c=g,d=E)}else this.log.info(s?"No previously indexed commit found \u2014 doing full walk":"Not inside a git repository \u2014 doing full walk")}catch(f){this.log.warn("Delta resolution failed, falling back to full walk",f)}return{...await this.workspaceService.indexWorkspace(t,n,{...o,preIndexedFiles:a??o?.preIndexedFiles,baselineCheckpointId:l??o?.baselineCheckpointId,retiredFiles:c??o?.retiredFiles,revalidateFiles:d??o?.revalidateFiles}),baseline:u}}createGitShaCommitIndex(t,n){return this.gitService.createGitShaCommitIndex(t,n)}getIndexingStatus(){return this.gitService.getIndexingStatus()}startWatcher(t){return this.workspaceService.startWatcher(t)}stopWatcher(){this.workspaceService.stopWatcher()}dispose(){this.gitService.dispose(),this.workspaceService.dispose(),this.onIndexing.dispose(),this.onCheckpoint.dispose(),this.onWatcherUpdate.dispose()}}});import{AsyncLocalStorage as Dj}from"node:async_hooks";import{parentPort as fU}from"node:worker_threads";import*as RU from"node:tls";var ht;function ZU(e){let t=[],n="",o=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i==='"')o=!o;else if(i==="\\"&&o){if(r++,r===e.length)return;n+=e[r]}else i===" "&&!o?n&&(t.push(n),n=""):n+=i}if(!o)return n&&t.push(n),t}function SU(){let e=ZU(process.env.NODE_OPTIONS??"");return e===void 0||[...e,...process.execArgv].some(t=>t.split("=",1)[0]?.replaceAll("_","-")==="--use-openssl-ca")}function xg(){if(ht!==void 0)return ht;if(process.env.AUGGIE_USE_SYSTEM_CA==="0")return ht="opted-out",ht;if(SU())return ht="explicit-policy",ht;let{getCACertificates:e,setDefaultCACertificates:t}=RU;if(typeof e!="function"||typeof t!="function")return ht="unsupported",ht;try{let n=e("default"),o=e("system");if(o.length===0)return ht="empty-store",ht;t([...n,...o]),ht="enabled"}catch{ht="failed"}return ht}xg();var{createAugmentClient:Lj}=await Promise.resolve().then(()=>(bN(),fN)),{logger:Hj,silenceLogger:Mj}=await Promise.resolve().then(()=>(we(),KS)),{AugmentApiAdapter:Oj}=await Promise.resolve().then(()=>(AN(),mN)),{ContextIndexer:jj}=await Promise.resolve().then(()=>(uU(),dU));if(!fU)throw new Error("indexing-worker.ts must be run as a worker thread");var Bu=fU,wg=new Dj;process.on("uncaughtException",e=>{Bu.postMessage({type:"fatalError",message:e.message,stack:e.stack,errorType:"uncaughtException"})});process.on("unhandledRejection",e=>{let t=e instanceof Error?e:new Error(String(e));Bu.postMessage({type:"fatalError",message:t.message,stack:t.stack,errorType:"unhandledRejection"})});var Fu=null,hr=new Map,Nu=new Map,xa=new Map,Bi=null,Pj=2e3;function Vt(e){Bu.postMessage(e)}function fr(e,t,n,o){Vt({type:"log",workspaceId:o??wg.getStore(),level:e,prefix:t,message:n,timestamp:Date.now()})}function hU(e){let t=hr.get(e);if(t)return t;if(!Fu)throw new Error("Worker not initialized \u2014 send 'configure' first");let n=Fu();return n.onIndexing.event(o=>{Nu.set(e,o),Vt({type:"progress",workspaceId:e,progress:o})}),n.onCheckpoint.event(o=>{Vt({type:"checkpointUpdate",workspaceId:e,checkpoint:o})}),n.onWatcherUpdate.event(o=>{Vt({type:"watcherUpdate",workspaceId:e,filesAdded:o.filesAdded,filesDeleted:o.filesDeleted})}),hr.set(e,n),n}Mj();Hj.on("data",e=>{let t=e.level??"info";fr(t,e.prefix??"worker",String(e.message??""),wg.getStore())});function qj(){Bi||(Bi=setInterval(()=>{let e=process.memoryUsage();Vt({type:"metrics",heapUsedMb:Math.round(e.heapUsed/1024/1024),rssMb:Math.round(e.rss/1024/1024),activeHandles:process._getActiveHandles?.().length??0,timestamp:Date.now()})},Pj),Bi.unref())}function $j(){Bi&&(clearInterval(Bi),Bi=null)}async function eP(e){switch(e.type){case"configure":{let{apiToken:t,apiUrl:n,indexerOptions:o}=e.config;fr("info","IndexingWorker",`Creating API client for ${n}`);let r=Lj({apiToken:t,apiUrl:n}),i=new Oj(r,n,t);Fu=()=>new jj(i,o),qj(),fr("info","IndexingWorker","Configured successfully"),Vt({type:"result",requestId:e.requestId});break}case"indexWorkspace":{let t=hU(e.workspaceId),n=e.skipDirectories?new Set(e.skipDirectories):void 0,o=e.folderToIndex??e.workspaceRoot,r=await t.indexWorkspace(e.workspaceRoot,o,{skipDirectories:n}),{pathToBlobName:i,...s}=r;try{let a=await t.createGitShaCommitIndex(e.workspaceRoot,"HEAD");fr("info","IndexingWorker",`Git SHA commit index created: ${a.commitSha}`)}catch(a){fr("warn","IndexingWorker",`Git SHA commit index failed (non-fatal): ${a}`)}fr("info","IndexingWorker","Starting file watcher"),await t.startWatcher(e.workspaceRoot),Vt({type:"result",requestId:e.requestId,data:s});break}case"createGitShaCommitIndex":{let n=await hU(e.workspaceId).createGitShaCommitIndex(e.repoRoot,e.revision);Vt({type:"result",requestId:e.requestId,data:n});break}case"statusRequest":{let t=hr.get(e.workspaceId)?.getIndexingStatus()??{itemsInFlight:0,calculateQueueSize:0,probeQueueSize:0,uploadQueueSize:0,probeRetryQueueSize:0,probeRetryBackoffQueueSize:0,calculateErrors:0,probeErrors:0,mtimeCacheHits:0,mtimeCacheMisses:0,pathsAccepted:0,currentFile:void 0,consecutiveNoneIndexedProbes:0,calculateAvgMs:0,calculateMaxMs:0};Vt({type:"statusResponse",requestId:e.requestId,workspaceId:e.workspaceId,status:t,progress:Nu.get(e.workspaceId)??null});break}case"dispose":{hr.get(e.workspaceId)?.dispose(),hr.delete(e.workspaceId),Nu.delete(e.workspaceId),Vt({type:"result",requestId:e.requestId});break}case"shutdown":{for(let t of hr.values())t.dispose();hr.clear(),Nu.clear(),xa.clear(),Fu=null,$j(),Vt({type:"result",requestId:e.requestId}),setTimeout(()=>process.exit(0),100);break}}}Bu.on("message",e=>{let t="workspaceId"in e?e.workspaceId:void 0,n=async()=>{try{await eP(e)}catch(i){let s=i instanceof Error?i:new Error(String(i));Vt({type:"error",requestId:e.requestId,message:s.message,stack:s.stack})}};if(!t){n();return}let r=(xa.get(t)??Promise.resolve()).then(()=>wg.run(t,n));xa.set(t,r),r.finally(()=>{xa.get(t)===r&&xa.delete(t)})});Vt({type:"ready"});fr("info","IndexingWorker","single worker indexing enabled");
142
+ `).map(t=>t.endsWith("\r")?t.slice(0,-1):t).filter(t=>t.trim()!==""&&!t.trim().startsWith("#"))}function Cg(e){let t=[],n=Yg(e);for(;n!==".";)t.push(n),n=Yg(n);return t.push(""),t}function va(e,t,n,o,r=!1){for(let i of e){let s=t.get(i);if(!s)continue;let a=s[o];if(!a)continue;let l=r&&i?n.slice(i.length+1):n,c=a.test(l);if(c.unignored||c.ignored)return c}}var Wu,_j,Qj,Tj,Bg,Gu,iU=F(()=>{"use strict";we();Wu=Ci(Wg(),1),_j=new Set([".png",".jpg",".jpeg",".gif",".ico",".webp",".svg",".bmp",".tiff",".psd",".ai",".mp3",".mp4",".wav",".mov",".avi",".flv",".mkv",".m4a",".aac",".ogg",".webm",".zip",".tar",".gz",".rar",".7z",".bz2",".xz",".iso",".exe",".dll",".so",".dylib",".o",".a",".lib",".bin",".app",".db",".sqlite",".sqlite3",".mdb",".dat",".class",".pyc",".pyo",".obj",".out",".woff",".woff2",".ttf",".otf",".eot",".fon",".jar",".war",".ear",".apk",".dmg",".deb",".rpm",".crt",".cer",".pem",".key",".lock"]),Qj=[".git","*.pem","*.key","*.pfx","*.p12","*.jks","*.keystore","*.pkcs12","*.crt","*.cer","id_rsa","id_ed25519","id_ecdsa","id_dsa",".augment-guidelines"],Tj=1024*1024,Bg=H.child({prefix:"HierarchicalIgnoreFilter"});Gu=class{workspaceRoot;maxFileSize;excludedExtensions;builtinIgnore;rulesMap=new Map;constructor(t){if(this.workspaceRoot=t.workspaceRoot,this.maxFileSize=t.maxFileSize??Tj,this.excludedExtensions=new Set(_j),t.additionalExcludedExtensions)for(let n of t.additionalExcludedExtensions)this.excludedExtensions.add(n.startsWith(".")?n:`.${n}`);this.builtinIgnore=(0,Wu.default)(),this.builtinIgnore.add(Qj)}loadDirectory(t){let n=t?Fg(this.workspaceRoot,t):this.workspaceRoot,o={},r=!1,i=Fg(n,".augmentignore");if(nU(i))try{let a=oU(i,"utf-8"),l=rU(a);if(l.length>0){let c=(0,Wu.default)();c.add(l),o.augmentignore=c,r=!0}}catch(a){Bg.warn(`Failed to read ${i}`,{error:a})}let s=Fg(n,".gitignore");if(nU(s))try{let a=oU(s,"utf-8"),l=rU(a);if(l.length>0){let c=(0,Wu.default)();c.add(l),o.gitignore=c,r=!0}}catch(a){Bg.warn(`Failed to read ${s}`,{error:a})}r?this.rulesMap.set(t,o):this.rulesMap.delete(t)}updateIgnoreFile(t){let n=Yg(t),o=n==="."?"":n;this.loadDirectory(o),Bg.debug(`Updated ignore rules for directory: ${o||"root"}`)}removeDirectory(t){this.rulesMap.delete(t)}isAugmentIgnored(t,n=!1){let o=n?`${t.replace(/\/$/,"")}/`:t;return va(Cg(t),this.rulesMap,o,"augmentignore",!0)?.ignored??!1}isDirectoryIgnored(t){let n=t.endsWith("/")?t:`${t}/`,o=Cg(t),r=va(o,this.rulesMap,n,"augmentignore");if(r)return r.ignored;let i=va(o,this.rulesMap,n,"gitignore");return i?i.ignored:!1}shouldAcceptBlob(t){let{path:n,size:o}=t,r=Cg(n),i=va(r,this.rulesMap,n,"augmentignore");if(i)return i.unignored?Promise.resolve({accepted:!0}):Promise.resolve({accepted:!1,reason:"Matched .augmentignore rule"});if(this.builtinIgnore.ignores(n))return Promise.resolve({accepted:!1,reason:"Matched builtin security pattern"});let s=kj(n).toLowerCase();if(this.excludedExtensions.has(s))return Promise.resolve({accepted:!1,reason:`Excluded extension: ${s}`});if(o>this.maxFileSize)return Promise.resolve({accepted:!1,reason:`File too large: ${o} > ${this.maxFileSize}`});let a=va(r,this.rulesMap,n,"gitignore");return a?a.unignored?Promise.resolve({accepted:!0}):Promise.resolve({accepted:!1,reason:"Matched .gitignore rule"}):Promise.resolve({accepted:!0})}}});import{readFile as sU}from"node:fs/promises";import{basename as Kj}from"node:path";var zj,Iu,aU=F(()=>{"use strict";we();hg();gg();En();jy();qy();Vg();tU();iU();Ig();zj=2e5,Iu=class{blobNameCalc;blobUploader;log=H.child({prefix:"WorkspaceIndexingService"});onProgress=new ce;onCheckpoint=new ce;orchestrator;blobFilter;checkpointSub;fileWatcher=null;watcherProcessor=null;walkComplete=!1;filesDiscovered=0;filesPreIndexed=0;currentWorkspaceRoot;indexingStartTime;onWatcherUpdate=new ce;apiServer;constructor(t,n=1024*1024,o=Ua){this.apiServer=t,this.blobNameCalc=new Si(n),this.blobUploader=new Wi(this.blobNameCalc,t,o)}dispose(){this.stopWatcher(),this.checkpointSub?.dispose(),this.checkpointSub=void 0,this.orchestrator?.dispose(),this.orchestrator=void 0,this.blobUploader.dispose(),this.onProgress.dispose(),this.onCheckpoint.dispose(),this.onWatcherUpdate.dispose()}createBlobFilter(t){let n=new Gu({workspaceRoot:t});return n.loadDirectory(""),n}async startWatcher(t){if(this.stopWatcher(),!this.orchestrator||!this.blobFilter)throw new Error("Cannot start watcher before workspace has been indexed with indexWorkspace()");let n=this.blobFilter;this.fileWatcher=new Su({workspaceRoot:t,shouldWatchDirectory:o=>(n.loadDirectory(o),!n.isDirectoryIgnored(o))}),this.watcherProcessor=new Xu({workspaceRoot:t,blobFilter:n,orchestrator:this.orchestrator}),this.watcherProcessor.onUpdate.event(o=>{this.onWatcherUpdate.fire(o)}),this.watcherProcessor.attach(this.fileWatcher),await this.fileWatcher.start(),this.log.info(`File watcher started for ${t}`)}stopWatcher(){this.fileWatcher?.stop(),this.watcherProcessor?.dispose(),this.fileWatcher=null,this.watcherProcessor=null}getIndexingStatus(){let t=this.orchestrator?.filesAccepted??0,n=this.orchestrator?.filesSettled??0;return{itemsInFlight:Math.max(0,t-n),calculateQueueSize:0,probeQueueSize:0,uploadQueueSize:0,probeRetryQueueSize:0,probeRetryBackoffQueueSize:0,calculateErrors:0,probeErrors:0,mtimeCacheHits:0,mtimeCacheMisses:0,pathsAccepted:t,currentFile:void 0,consecutiveNoneIndexedProbes:0,calculateAvgMs:0,calculateMaxMs:0}}emitProgress(t){let n=this.orchestrator?.filesAccepted??0,o=this.orchestrator?.filesSettled??0,r=n+this.filesPreIndexed,i=o+this.filesPreIndexed,s=r>0?Math.floor(i/r*100):0;this.onProgress.fire({phase:t,percentage:s,filesDiscovered:this.filesDiscovered,filesTracked:n,filesProcessed:o,filesIndexed:this.orchestrator?.filesIndexed??0,filesFailed:this.orchestrator?.filesFailed??0,filesRejected:this.orchestrator?.filesRejected??0,filesPreIndexed:this.filesPreIndexed,walkComplete:this.walkComplete,workspaceRoot:this.currentWorkspaceRoot,durationMs:t==="complete"&&this.indexingStartTime?Date.now()-this.indexingStartTime:void 0})}async indexWorkspace(t,n,o={}){if(this.fileWatcher)return this.log.error(`Cannot index workspace for ${n}: file watcher is already active`),{checkpointId:void 0,filesTracked:0,filesProcessed:0,filesSkipped:0,durationMs:0,pathToBlobName:new Map};this.log.info(`Starting workspace indexing for ${n}`+(n===t?"":` (workspace root: ${t})`)),this.walkComplete=!1,this.filesDiscovered=0,this.filesPreIndexed=0,this.currentWorkspaceRoot=t,this.indexingStartTime=Date.now(),this.emitProgress("qualifying");let r=this.createBlobFilter(t);this.blobFilter=r;let i=o.baselineCheckpointId,s=new Gi(this.apiServer,i),a=!1;this.checkpointSub?.dispose(),this.checkpointSub=s.onCheckpoint.event(S=>{a=!0,this.onCheckpoint.fire(S)}),this.orchestrator?.dispose();let l=new Fi(r,this.blobUploader,s);this.orchestrator=l;let c=o.preIndexedFiles;if(c&&c.size>0)if(s.seed(c),this.filesPreIndexed=c.size,i)this.log.info(`Resuming from checkpoint ${i} (${c.size} pre-indexed files)`),a=!0,this.onCheckpoint.fire({checkpointId:i,addedBlobs:[],deletedBlobs:[]});else{let S=Array.from(c.values());this.log.info(`Seeding checkpoint with ${S.length} pre-indexed blobs`),s.update(S,[]),await s.flushToLimit()}i&&o.retiredFiles?.size&&s.update([],Array.from(o.retiredFiles.values()));let d=o.revalidateFiles,u=new Set(d?.keys());i&&d?.size&&s.seed(d);let h=new Promise((S,N)=>{l.onDone(V=>{V.hadFailures&&this.log.warn("Workspace indexing completed with failures"),this.emitProgress("complete"),S()})}),f=l.onBlobSettled.event(()=>{this.emitProgress("indexing")});this.emitProgress("indexing");let b={skipDirectories:o.skipDirectories,signal:o.signal,shouldEnterDirectory:S=>(r.loadDirectory(S),!r.isDirectoryIgnored(S))},A=o.maxTrackableFiles??zj,m=0;for await(let S of eU(t,n,b)){if(o.signal?.aborted)break;if(l.filesAccepted>=A){this.log.warn(`Workspace exceeds ${A} trackable files, stopping walk`),this.emitProgress("workspace-too-large");break}this.filesDiscovered++;let N=Kj(S.relativePath);if(N===".gitignore"||N===".augmentignore"){r.updateIgnoreFile(S.relativePath);continue}if(d?.has(S.relativePath)){u.delete(S.relativePath),(await r.shouldAcceptBlob({path:S.relativePath,size:S.size,readContent:()=>sU(S.absolutePath)})).accepted?(m++,this.filesPreIndexed++):s.removeByPath(S.relativePath);continue}if(c?.has(S.relativePath)){m++;continue}await l.addFile(S.relativePath,S.size,()=>sU(S.absolutePath)),this.filesDiscovered%1e3===0&&this.emitProgress("indexing")}for(let S of u)s.removeByPath(S);m>0&&this.log.info(`Skipped ${m} pre-indexed files (incremental)`),this.walkComplete=!0,this.emitProgress("indexing"),l.traversalCompleted(),await h,f.dispose(),s.flushCheckpointEvent();let g=s.blobs.checkpointId;!a&&g&&this.onCheckpoint.fire({checkpointId:g,addedBlobs:[],deletedBlobs:[]});let E=Date.now()-(this.indexingStartTime??Date.now()),R=l.filesAccepted,G=l.filesSettled;return this.log.info(`Workspace indexing complete: ${R} tracked, ${G} processed, ${m} skipped (pre-indexed), ${(E/1e3).toFixed(1)}s, checkpoint: ${g??"none"}`),{checkpointId:g,filesTracked:R,filesProcessed:G,filesSkipped:m,durationMs:E,pathToBlobName:l.pathToBlobName}}}});var dU={};ka(dU,{ContextIndexer:()=>Ug});import{relative as lU,resolve as cU}from"node:path";function yg(e,t){let n=new Map;for(let[o,r]of e)o.startsWith(t)&&n.set(o,r);return n}var Ug,uU=F(()=>{"use strict";we();EN();En();pd();Hy();aU();Ug=class{gitService;workspaceService;deltaResolver;log=H.child({prefix:"ContextIndexer"});onIndexing=new ce;onCheckpoint=new ce;onWatcherUpdate=new ce;constructor(t,n={}){this.gitService=new Ru(t,n.maxBlobSize,n.uploaderConfig),this.workspaceService=new Iu(t,n.maxBlobSize,n.uploaderConfig),this.deltaResolver=new gd(t,n.deltaResolverOptions),this.workspaceService.onProgress.event(o=>{this.onIndexing.fire(o)}),this.workspaceService.onCheckpoint.event(o=>{this.onCheckpoint.fire(o)}),this.workspaceService.onWatcherUpdate.event(o=>{this.onWatcherUpdate.fire(o)})}getGitRepoDetails(t){return Pn(t)}async indexWorkspace(t,n,o){let r=cU(t),i=cU(n),s=RN(r),a,l,c,d,u=null;this.log.info("Looking for previously indexed git SHA...");try{let f=s?await this.deltaResolver.resolveIndexedCommitDelta(s):null;if(f&&s){this.log.info(`Found indexed commit ${f.indexedCommitSha}: ${f.fileInfoMap.size} unchanged, ${f.modifiedFiles.size} modified, ${f.addedFiles.size} added, ${f.deletedFiles.size} deleted, ${f.untrackedFiles.size} untracked`);let b=s===r?"":`${lU(s,r)}/`,A=i===r?b:`${lU(s,i)}/`,m=yg(f.fileInfoMap,A),g=yg(f.retiredFileInfoMap,A),E=yg(f.revalidateFileInfoMap,A);u={commitSha:f.indexedCommitSha,fileCount:m.size},m.size!==f.fileInfoMap.size&&this.log.info(`Filtered delta to ${m.size} files under ${A} (was ${f.fileInfoMap.size})`),a=m,s===r&&i===r&&(l=f.checkpointId,c=g,d=E)}else this.log.info(s?"No previously indexed commit found \u2014 doing full walk":"Not inside a git repository \u2014 doing full walk")}catch(f){this.log.warn("Delta resolution failed, falling back to full walk",f)}return{...await this.workspaceService.indexWorkspace(t,n,{...o,preIndexedFiles:a??o?.preIndexedFiles,baselineCheckpointId:l??o?.baselineCheckpointId,retiredFiles:c??o?.retiredFiles,revalidateFiles:d??o?.revalidateFiles}),baseline:u}}createGitShaCommitIndex(t,n){return this.gitService.createGitShaCommitIndex(t,n)}getIndexingStatus(){return this.gitService.getIndexingStatus()}startWatcher(t){return this.workspaceService.startWatcher(t)}stopWatcher(){this.workspaceService.stopWatcher()}dispose(){this.gitService.dispose(),this.workspaceService.dispose(),this.onIndexing.dispose(),this.onCheckpoint.dispose(),this.onWatcherUpdate.dispose()}}});import{AsyncLocalStorage as Dj}from"node:async_hooks";import{parentPort as fU}from"node:worker_threads";import*as RU from"node:tls";var ht;function ZU(e){let t=[],n="",o=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i==='"')o=!o;else if(i==="\\"&&o){if(r++,r===e.length)return;n+=e[r]}else i===" "&&!o?n&&(t.push(n),n=""):n+=i}if(!o)return n&&t.push(n),t}function SU(){let e=ZU(process.env.NODE_OPTIONS??"");return e===void 0||[...e,...process.execArgv].some(t=>t.split("=",1)[0]?.replaceAll("_","-")==="--use-openssl-ca")}function xg(){if(ht!==void 0)return ht;if(process.env.AUGGIE_USE_SYSTEM_CA==="0")return ht="opted-out",ht;if(SU())return ht="explicit-policy",ht;let{getCACertificates:e,setDefaultCACertificates:t}=RU;if(typeof e!="function"||typeof t!="function")return ht="unsupported",ht;try{let n=e("default"),o=e("system");if(o.length===0)return ht="empty-store",ht;t([...n,...o]),ht="enabled"}catch{ht="failed"}return ht}xg();var{createAugmentClient:Lj}=await Promise.resolve().then(()=>(bN(),fN)),{logger:Hj,silenceLogger:Mj}=await Promise.resolve().then(()=>(we(),KS)),{AugmentApiAdapter:Oj}=await Promise.resolve().then(()=>(AN(),mN)),{ContextIndexer:jj}=await Promise.resolve().then(()=>(uU(),dU));if(!fU)throw new Error("indexing-worker.ts must be run as a worker thread");var Bu=fU,wg=new Dj;process.on("uncaughtException",e=>{Bu.postMessage({type:"fatalError",message:e.message,stack:e.stack,errorType:"uncaughtException"})});process.on("unhandledRejection",e=>{let t=e instanceof Error?e:new Error(String(e));Bu.postMessage({type:"fatalError",message:t.message,stack:t.stack,errorType:"unhandledRejection"})});var Fu=null,hr=new Map,Nu=new Map,xa=new Map,Bi=null,Pj=2e3;function Vt(e){Bu.postMessage(e)}function fr(e,t,n,o){Vt({type:"log",workspaceId:o??wg.getStore(),level:e,prefix:t,message:n,timestamp:Date.now()})}function hU(e){let t=hr.get(e);if(t)return t;if(!Fu)throw new Error("Worker not initialized \u2014 send 'configure' first");let n=Fu();return n.onIndexing.event(o=>{Nu.set(e,o),Vt({type:"progress",workspaceId:e,progress:o})}),n.onCheckpoint.event(o=>{Vt({type:"checkpointUpdate",workspaceId:e,checkpoint:o})}),n.onWatcherUpdate.event(o=>{Vt({type:"watcherUpdate",workspaceId:e,filesAdded:o.filesAdded,filesDeleted:o.filesDeleted})}),hr.set(e,n),n}Mj();Hj.on("data",e=>{let t=e.level??"info";fr(t,e.prefix??"worker",String(e.message??""),wg.getStore())});function qj(){Bi||(Bi=setInterval(()=>{let e=process.memoryUsage();Vt({type:"metrics",heapUsedMb:Math.round(e.heapUsed/1024/1024),rssMb:Math.round(e.rss/1024/1024),activeHandles:process._getActiveHandles?.().length??0,timestamp:Date.now()})},Pj),Bi.unref())}function $j(){Bi&&(clearInterval(Bi),Bi=null)}async function eP(e){switch(e.type){case"configure":{let{apiToken:t,apiUrl:n,indexerOptions:o}=e.config;fr("info","IndexingWorker",`Creating API client for ${n}`);let r=Lj({apiToken:t,apiUrl:n}),i=new Oj(r,n,t);Fu=()=>new jj(i,o),qj(),fr("info","IndexingWorker","Configured successfully"),Vt({type:"result",requestId:e.requestId});break}case"indexWorkspace":{let t=hU(e.workspaceId),n=e.skipDirectories?new Set(e.skipDirectories):void 0,o=e.folderToIndex??e.workspaceRoot,r=await t.indexWorkspace(e.workspaceRoot,o,{skipDirectories:n,maxTrackableFiles:e.maxTrackableFiles}),{pathToBlobName:i,...s}=r;try{let a=await t.createGitShaCommitIndex(e.workspaceRoot,"HEAD");fr("info","IndexingWorker",`Git SHA commit index created: ${a.commitSha}`)}catch(a){fr("warn","IndexingWorker",`Git SHA commit index failed (non-fatal): ${a}`)}fr("info","IndexingWorker","Starting file watcher"),await t.startWatcher(e.workspaceRoot),Vt({type:"result",requestId:e.requestId,data:s});break}case"createGitShaCommitIndex":{let n=await hU(e.workspaceId).createGitShaCommitIndex(e.repoRoot,e.revision);Vt({type:"result",requestId:e.requestId,data:n});break}case"statusRequest":{let t=hr.get(e.workspaceId)?.getIndexingStatus()??{itemsInFlight:0,calculateQueueSize:0,probeQueueSize:0,uploadQueueSize:0,probeRetryQueueSize:0,probeRetryBackoffQueueSize:0,calculateErrors:0,probeErrors:0,mtimeCacheHits:0,mtimeCacheMisses:0,pathsAccepted:0,currentFile:void 0,consecutiveNoneIndexedProbes:0,calculateAvgMs:0,calculateMaxMs:0};Vt({type:"statusResponse",requestId:e.requestId,workspaceId:e.workspaceId,status:t,progress:Nu.get(e.workspaceId)??null});break}case"dispose":{hr.get(e.workspaceId)?.dispose(),hr.delete(e.workspaceId),Nu.delete(e.workspaceId),Vt({type:"result",requestId:e.requestId});break}case"shutdown":{for(let t of hr.values())t.dispose();hr.clear(),Nu.clear(),xa.clear(),Fu=null,$j(),Vt({type:"result",requestId:e.requestId}),setTimeout(()=>process.exit(0),100);break}}}Bu.on("message",e=>{let t="workspaceId"in e?e.workspaceId:void 0,n=async()=>{try{await eP(e)}catch(i){let s=i instanceof Error?i:new Error(String(i));Vt({type:"error",requestId:e.requestId,message:s.message,stack:s.stack})}};if(!t){n();return}let r=(xa.get(t)??Promise.resolve()).then(()=>wg.run(t,n));xa.set(t,r),r.finally(()=>{xa.get(t)===r&&xa.delete(t)})});Vt({type:"ready"});fr("info","IndexingWorker","single worker indexing enabled");
143
143
  /*! Bundled license information:
144
144
 
145
145
  safe-buffer/index.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@augmentcode/onison",
3
- "version": "1.2.2",
3
+ "version": "1.2.3-prerelease.202611241639",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "bin": {