@desplega.ai/agent-fs 0.7.4 → 0.7.5

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/cli.js CHANGED
@@ -169,7 +169,7 @@ ${$t.toHex(r)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let n=[];for(l
169
169
  FROM chunk_vectors
170
170
  WHERE embedding MATCH ?
171
171
  ORDER BY distance
172
- LIMIT ?`).all(r,o),T=[],l=new Set;for(let A of f){let R=t.db.select().from(u.contentChunks).where(Ci(u.contentChunks.id,A.chunk_id)).get();if(!R||R.driveId!==t.driveId)continue;if(l.has(R.filePath))continue;l.add(R.filePath);let w=t.db.select().from(u.files).where(g_(Ci(u.files.path,R.filePath),Ci(u.files.driveId,t.driveId))).get();T.push({path:R.filePath,snippet:R.content.slice(0,200),author:w?.author,modifiedAt:w?.modifiedAt})}return T}function D_(t,n,o){let i=n.split(/\s+/).filter(Boolean).map((e)=>`"${e}"`).join(" OR ");if(!i)return[];try{return oo(t.db,{pattern:i,driveId:t.driveId}).slice(0,o).map((r)=>({path:r.path,snippet:r.snippet}))}catch{return[]}}var xu=N(()=>{G()});import{eq as eo,and as O_,or as I_,isNull as U_}from"drizzle-orm";async function au(t,n){let o=[eo(u.files.driveId,t.driveId),eo(u.files.isDeleted,!1),I_(eo(u.files.embeddingStatus,"failed"),U_(u.files.embeddingStatus),eo(u.files.embeddingStatus,"pending"))];if(n.path){let{like:T}=await import("drizzle-orm"),l=n.path.endsWith("/")?n.path:n.path+"/";o.push(T(u.files.path,l+"%"))}let i=t.db.select({path:u.files.path}).from(u.files).where(O_(...o)).all(),e=0,r=0,E=0,f=3;for(let T=0;T<i.length;T+=f){let l=i.slice(T,T+f),A=await Promise.allSettled(l.map(async(R)=>{let w=I(t.orgId,t.driveId,R.path),L=await t.s3.getObject(w),O=L.contentType??K(R.path),D=Pt(L.body,O);if(D===null)return Mn(t,R.path),"skipped";if(wt(t.db,{path:R.path,driveId:t.driveId,content:D}),t.embeddingProvider)return await Di(t.db,t.embeddingProvider,{path:R.path,driveId:t.driveId,content:D}),"reindexed";return"skipped"}));for(let R of A)if(R.status==="fulfilled")if(R.value==="reindexed")e++;else E++;else console.error("Reindex failed:",R.reason),r++}return{reindexed:e,failed:r,skipped:E}}var tf=N(()=>{G();W();Fn();rn();rt()});import{eq as nf,and as S_,like as $_}from"drizzle-orm";async function of(t,n){let o=Ct(n.path??"/"),i=I(t.orgId,t.driveId,o),{objects:e}=await t.s3.listObjects(i),r=t.db.select().from(u.files).where(S_(nf(u.files.driveId,t.driveId),$_(u.files.path,o+"%"),nf(u.files.isDeleted,!1))).all(),E=new Map(r.map((T)=>[T.path,T])),f=[];for(let T of e){let l=T.key.slice(i.length);if(!l)continue;let A=l.split("/").filter(Boolean);if(A.length===0)continue;if(n.depth!==void 0&&A.length>n.depth)continue;let R=f;for(let w=0;w<A.length;w++){let L=A[w],O=w===A.length-1,D=!O||l.endsWith("/");if(D&&!O){let C=R.find((Z)=>Z.name===L&&Z.type==="directory");if(!C)C={name:L,type:"directory",children:[]},R.push(C);if(!C.children)C.children=[];R=C.children}else if(D&&O){let C=R.find((Z)=>Z.name===L&&Z.type==="directory");if(!C)C={name:L,type:"directory",children:[]},R.push(C)}else{let C=o+A.slice(0,w+1).join("/"),Z=E.get(C),_n={name:L,type:"file",size:Z?.size??T.size};if(Z?.author)_n.author=Z.author;if(Z?.modifiedAt??T.lastModified)_n.modifiedAt=Z?.modifiedAt??T.lastModified;R.push(_n)}}}return{tree:f}}var ef=N(()=>{G();W()});import{eq as rf,and as X_,like as C_}from"drizzle-orm";function P_(t){let n="",o=0;while(o<t.length){let i=t[o];if(i==="*")if(t[o+1]==="*"){if(n+=".*",o+=2,t[o]==="/")o++}else n+="[^/]*",o++;else if(i==="?")n+="[^/]",o++;else if(".+^${}()|[]\\".includes(i))n+="\\"+i,o++;else n+=i,o++}return new RegExp("^"+n+"$")}async function Ef(t,n){let o=n.path?Ct(n.path):"/",i=I(t.orgId,t.driveId,o),{objects:e}=await t.s3.listObjects(i),r=t.db.select().from(u.files).where(X_(rf(u.files.driveId,t.driveId),C_(u.files.path,o+"%"),rf(u.files.isDeleted,!1))).all(),E=new Map(r.map((l)=>[l.path,l])),f=P_(n.pattern),T=[];for(let l of e){let A=l.key.slice(i.length);if(!A||A.endsWith("/"))continue;if(f.test(A)){let R=o+A,w=E.get(R);T.push({path:R,size:w?.size??l.size,modifiedAt:w?.modifiedAt??l.lastModified})}}return{matches:T}}var uf=N(()=>{G();W()});async function ff(t,n){let o=Cn(n.path),i=I(t.orgId,t.driveId,o),e=n.expiresIn??86400;try{await t.s3.headObject(i)}catch(f){if(f?.name==="NotFound"||f?.name==="NoSuchKey"||f?.$metadata?.httpStatusCode===404)throw new M(`File not found: ${o}`,{path:o});throw f}let r=K(o);return{url:await t.s3.getPresignedUrl(i,e,r!=="application/octet-stream"?r:void 0),path:o,expiresIn:e,expiresAt:new Date(Date.now()+e*1000).toISOString()}}var Tf=N(()=>{W();m();rt()});function Pi(t,n,o,i){let e=i.startsWith("/")?i.slice(1):i;return`${t}/file/~/${n}/${o}/${e}`}import{eq as F,and as yt,sql as Fi,desc as lf}from"drizzle-orm";function Mi(t,n){t.db.insert(u.events).values({id:crypto.randomUUID(),orgId:t.orgId,type:n.type,resourceType:n.resourceType,resourceId:n.resourceId,actor:t.userId,target:n.target??null,status:"created",metadata:n.metadata?JSON.stringify(n.metadata):null,createdAt:new Date}).run()}function ro(t){return{id:t.id,parentId:t.parentId??void 0,path:t.path,lineStart:t.lineStart??void 0,lineEnd:t.lineEnd??void 0,quotedContent:t.quotedContent??void 0,body:t.body,author:t.author,resolved:t.resolved??!1,resolvedBy:t.resolvedBy??void 0,resolvedAt:t.resolvedAt??void 0,fileVersionId:t.fileVersionId??void 0,replyCount:t.replyCount??0,createdAt:t.createdAt,updatedAt:t.updatedAt}}async function Eo(t,n){let o=new Date,i=crypto.randomUUID(),e=n.path;if(n.parentId){let E=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.parentId),F(u.comments.isDeleted,!1))).get();if(!E)throw new M("Parent comment not found",{suggestion:"Check that the parent comment ID is correct and not deleted"});if(E.parentId)throw new c("Cannot reply to a reply \u2014 only root comments accept replies",{suggestion:"Reply to the root comment instead"});if(!e)e=E.path}if(!e)throw new c("path is required for root comments",{field:"path"});let r=t.db.select({id:u.fileVersions.id}).from(u.fileVersions).where(yt(F(u.fileVersions.path,e),F(u.fileVersions.driveId,t.driveId))).orderBy(lf(u.fileVersions.id)).limit(1).get();return t.db.insert(u.comments).values({id:i,parentId:n.parentId??null,orgId:t.orgId,driveId:t.driveId,path:e,lineStart:n.lineStart??null,lineEnd:n.lineEnd??null,quotedContent:n.quotedContent??null,fileVersionId:r?.id??null,body:n.body,author:t.userId,resolved:!1,createdAt:o,updatedAt:o,isDeleted:!1}).run(),Mi(t,{type:"comment_created",resourceType:"comment",resourceId:i,metadata:{path:e,parentId:n.parentId}}),{id:i,path:e,body:n.body,parentId:n.parentId,lineStart:n.lineStart,lineEnd:n.lineEnd,author:t.userId,createdAt:o}}async function uo(t,n){let o=[F(u.comments.driveId,t.driveId),F(u.comments.isDeleted,!1)];if(n.path)o.push(F(u.comments.path,n.path));if(n.parentId)o.push(F(u.comments.parentId,n.parentId));else if(n.parentId===void 0&&!n.resolved)o.push(Fi`${u.comments.parentId} IS NULL`),o.push(F(u.comments.resolved,!1));else if(n.parentId===void 0&&n.resolved)o.push(Fi`${u.comments.parentId} IS NULL`);if(n.orgId)o.push(F(u.comments.orgId,n.orgId));let i=n.limit??50,e=n.offset??0;return{comments:t.db.select().from(u.comments).where(yt(...o)).orderBy(lf(u.comments.createdAt)).limit(i).offset(e).all().map((f)=>{let l=t.db.select().from(u.comments).where(yt(F(u.comments.parentId,f.id),F(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((A)=>ro({...A,replyCount:0}));return{...ro({...f,replyCount:l.length}),replies:l}})}}async function fo(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});let i=t.db.select({count:Fi`count(*)`}).from(u.comments).where(yt(F(u.comments.parentId,o.id),F(u.comments.isDeleted,!1))).get(),e=ro({...o,replyCount:i?.count??0}),E=t.db.select().from(u.comments).where(yt(F(u.comments.parentId,n.id),F(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((f)=>ro({...f,replyCount:0}));return{comment:e,replies:E}}async function To(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.author!==t.userId)throw new it("You can only edit your own comments",{suggestion:"Only the comment author can update it"});let i=new Date;return t.db.update(u.comments).set({body:n.body,updatedAt:i}).where(F(u.comments.id,n.id)).run(),{id:n.id,body:n.body,updatedAt:i}}async function lo(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.author!==t.userId)throw new it("You can only delete your own comments",{suggestion:"Only the comment author can delete it"});let i=new Date;if(t.db.update(u.comments).set({isDeleted:!0,updatedAt:i}).where(F(u.comments.id,n.id)).run(),!o.parentId)t.db.update(u.comments).set({isDeleted:!0,updatedAt:i}).where(F(u.comments.parentId,n.id)).run();return Mi(t,{type:"comment_deleted",resourceType:"comment",resourceId:n.id}),{deleted:!0}}async function Ao(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.parentId)throw new c("Cannot resolve a reply \u2014 only root comments can be resolved",{suggestion:"Resolve the parent comment instead"});let i=new Date,e=n.resolved?i:null,r=n.resolved?t.userId:null;return t.db.update(u.comments).set({resolved:n.resolved,resolvedBy:r,resolvedAt:e,updatedAt:i}).where(F(u.comments.id,n.id)).run(),Mi(t,{type:n.resolved?"comment_resolved":"comment_reopened",resourceType:"comment",resourceId:n.id}),{id:n.id,resolved:n.resolved,resolvedBy:r??void 0,resolvedAt:e??void 0}}var Af=N(()=>{G();m()});import{z as _}from"zod";async function d(t,n,o,i){let e=vi[n];if(!e)throw Error(`Unknown operation: ${n}`);if(!i?.skipAuth){let f=$n(n);Xn(t.db,{userId:t.userId,driveId:t.driveId,requiredRole:f})}let r=e.schema.parse(o),E=await e.handler(t,r);if(t.appUrl&&E&&typeof E==="object"){if("path"in E)E.appUrl=Pi(t.appUrl,t.orgId,t.driveId,E.path);else if("to"in E)E.appUrl=Pi(t.appUrl,t.orgId,t.driveId,E.to)}return E}function fn(){return Object.keys(vi)}function Ft(t){return vi[t]}var vi;var Yi=N(()=>{an();Nu();_u();yu();Lu();Iu();$u();Cu();Mu();Yu();Hu();Ju();Wu();pu();du();mu();bu();qu();xu();tf();ef();uf();Tf();Af();vi={write:{description:"Write or overwrite a file. Creates the file if it doesn't exist, or creates a new version. Use expectedVersion for optimistic concurrency. Returns { version, path, size }.",handler:io,schema:_.object({path:_.string(),content:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},cat:{description:"Read file content with optional pagination via offset/limit. Returns { content, totalLines, truncated }.",handler:Ru,schema:_.object({path:_.string(),offset:_.number().int().min(0).optional(),limit:_.number().int().min(1).optional()})},edit:{description:"Replace a specific string in a file (surgical find-and-replace). Captures the edit intent as a diff summary in version history. Returns { version, path, changes }.",handler:wu,schema:_.object({path:_.string(),old_string:_.string(),new_string:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},append:{description:"Append content to the end of an existing file. Creates a new version. Returns { version, size }.",handler:gu,schema:_.object({path:_.string(),content:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},ls:{description:"List immediate children of a directory. Returns { entries } where each entry has name, type (file/directory), size, author, modifiedAt.",handler:Ou,schema:_.object({path:_.string().optional()})},stat:{description:"Get file metadata without reading content. Returns path, size, contentType, author, currentVersion, createdAt, modifiedAt, isDeleted, embeddingStatus.",handler:Su,schema:_.object({path:_.string()})},rm:{description:"Delete a file. Removes from S3, cleans up FTS5 index and vector embeddings. Returns { path, deleted }.",handler:Xu,schema:_.object({path:_.string(),expectedVersion:_.number().int().optional()})},mv:{description:"Move or rename a file. Preserves version history at the new path. Returns { from, to, version }.",handler:Fu,schema:_.object({from:_.string(),to:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},cp:{description:"Copy a file using server-side S3 copy. Creates a new version at the destination. Returns { from, to, version }.",handler:vu,schema:_.object({from:_.string(),to:_.string(),expectedVersion:_.number().int().optional()})},tail:{description:"Read the last N lines of a file (default 20). Returns { content, totalLines, truncated }.",handler:Gu,schema:_.object({path:_.string(),lines:_.number().int().min(1).optional()})},log:{description:"Show version history for a file. Returns { versions } with version number, author, timestamp, operation type, message, and diff summary.",handler:Qu,schema:_.object({path:_.string(),limit:_.number().int().min(1).optional()})},diff:{description:"Show the diff between two versions of a file. Specify v1 and v2 version numbers. Returns { changes } as add/remove/context hunks.",handler:Vu,schema:_.object({path:_.string(),v1:_.number().int(),v2:_.number().int()})},revert:{description:"Revert a file to a previous version. Creates a new version with the old content. Returns { version, revertedTo }.",handler:Ku,schema:_.object({path:_.string(),version:_.number().int(),expectedVersion:_.number().int().optional()})},recent:{description:"Show recent activity across the drive. Optionally filter by path prefix and time window (since). Returns { entries } with path and version details.",handler:ju,schema:_.object({path:_.string().optional(),since:_.coerce.date().optional(),limit:_.number().int().min(1).optional()})},grep:{description:"Search file content using regex pattern within a specific path. Returns matching lines with line numbers. Searches the FTS5 index, not S3 directly.",handler:ku,schema:_.object({pattern:_.string(),path:_.string()})},fts:{description:"Full-text search across all file content using FTS5 tokens. Different from grep (regex) and search (semantic). Returns { matches } with path, snippet, and rank.",handler:zu,schema:_.object({pattern:_.string(),path:_.string().optional()})},search:{description:"Hybrid search combining semantic (vector) and keyword (FTS5) matching. Best for natural language queries. Degrades to keyword-only without an embedding provider.",handler:cu,schema:_.object({query:_.string(),limit:_.number().int().min(1).optional()})},"vec-search":{description:"Vector-only semantic search using embeddings. Returns results ranked by cosine similarity. Requires an embedding provider (OPENAI_API_KEY, GEMINI_API_KEY, or local).",handler:su,schema:_.object({query:_.string(),limit:_.number().int().min(1).optional()})},reindex:{description:"Re-index files with failed or missing FTS5/embedding entries. Optionally scope to a path prefix. Use after bulk writes or provider changes.",handler:au,schema:_.object({path:_.string().optional()})},tree:{description:"Recursively list all files and directories. Use depth to limit recursion. Returns a nested tree structure with name, type, size, and children.",handler:of,schema:_.object({path:_.string().optional(),depth:_.number().int().min(1).optional()})},glob:{description:"Find files by name pattern. Use `*.md` for root-level files only, `**/*.md` for recursive matching across all subdirectories. Supports `*` (any chars except /), `?` (single char), `**` (any path depth). Optionally scope to a path prefix. Returns { matches } with path, size, and modifiedAt.",handler:Ef,schema:_.object({pattern:_.string(),path:_.string().optional()})},"signed-url":{description:"Generate a temporary presigned URL for direct file download. Default expiry is 24 hours (86400 seconds). The URL requires no authentication. Returns { url, path, expiresIn, expiresAt }.",handler:ff,schema:_.object({path:_.string(),expiresIn:_.number().int().min(60).max(604800).optional()})},"comment-add":{description:"Add a comment to a file. Supports line ranges and threading via parentId. Replies auto-resolve path from parent. Returns { id, path, body, author, createdAt }.",handler:Eo,schema:_.object({path:_.string().optional(),body:_.string(),parentId:_.string().optional(),lineStart:_.number().int().optional(),lineEnd:_.number().int().optional(),quotedContent:_.string().optional()})},"comment-list":{description:"List comments on a file. Filter by path, resolved state, or parentId. Defaults to unresolved root comments. Returns { comments } with inline replies.",handler:uo,schema:_.object({path:_.string().optional(),parentId:_.string().optional(),resolved:_.boolean().optional(),orgId:_.string().optional(),limit:_.number().int().min(1).optional(),offset:_.number().int().min(0).optional()})},"comment-get":{description:"Get a single comment by ID with all its replies. Returns { comment, replies }.",handler:fo,schema:_.object({id:_.string()})},"comment-update":{description:"Update a comment's body. Only the original author can update. Returns { id, body, updatedAt }.",handler:To,schema:_.object({id:_.string(),body:_.string()})},"comment-delete":{description:"Soft-delete a comment. Only the original author can delete. Deleting a root comment also soft-deletes its replies. Returns { deleted }.",handler:lo,schema:_.object({id:_.string()})},"comment-resolve":{description:"Resolve or reopen a root comment. Set resolved=true to resolve, resolved=false to reopen. Only root comments can be resolved. Returns { id, resolved, resolvedBy, resolvedAt }.",handler:Ao,schema:_.object({id:_.string(),resolved:_.boolean()})}}});import{eq as z,and as No}from"drizzle-orm";function Qt(t,n){let o=crypto.randomUUID(),i=new Date;return t.insert(u.drives).values({id:o,orgId:n.orgId,name:n.name,isDefault:n.isDefault??!1,createdAt:i}).run(),{id:o,name:n.name}}function vn(t,n){return t.select().from(u.drives).where(z(u.drives.orgId,n)).all().map((o)=>({id:o.id,name:o.name,isDefault:o.isDefault}))}function Ot(t,n,o){return t.select().from(u.drives).where(z(u.drives.orgId,n)).all().filter((e)=>{let r=t.select({userId:u.driveMembers.userId}).from(u.driveMembers).where(z(u.driveMembers.driveId,e.id)).all();if(r.length===0)return!0;return r.some((E)=>E.userId===o)}).map((e)=>({id:e.id,name:e.name,isDefault:e.isDefault}))}function Gi(t,n){let o=t.select().from(u.drives).where(z(u.drives.id,n)).get();if(!o)return null;return{id:o.id,name:o.name,orgId:o.orgId,isDefault:o.isDefault}}function Jt(t,n){return t.select({userId:u.driveMembers.userId,email:u.users.email,role:u.driveMembers.role}).from(u.driveMembers).innerJoin(u.users,z(u.driveMembers.userId,u.users.id)).where(z(u.driveMembers.driveId,n)).all()}function Bt(t,n){if(!t.select({role:u.driveMembers.role}).from(u.driveMembers).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).get())throw Error("Member not found in drive");t.update(u.driveMembers).set({role:n.role}).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).run()}function Vt(t,n){if(!t.select({role:u.driveMembers.role}).from(u.driveMembers).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).get())throw Error("Member not found in drive");t.delete(u.driveMembers).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).run()}function Hi(t,n){t.insert(u.driveMembers).values({driveId:n.driveId,userId:n.userId,role:n.role}).onConflictDoUpdate({target:[u.driveMembers.driveId,u.driveMembers.userId],set:{role:n.role}}).run()}var Zi=N(()=>{G()});import{eq as Q,and as Wt,sql as Nf}from"drizzle-orm";function Kt(t,n){let o=crypto.randomUUID(),i=new Date;t.insert(u.orgs).values({id:o,name:n.name,isPersonal:n.isPersonal??!1,createdAt:i}).run(),t.insert(u.orgMembers).values({orgId:o,userId:n.userId,role:"admin"}).run();let e=Qt(t,{orgId:o,name:"default",isDefault:!0});return t.insert(u.driveMembers).values({driveId:e.id,userId:n.userId,role:"admin"}).run(),{id:o,name:n.name}}function p(t,n){return t.select({orgId:u.orgMembers.orgId,role:u.orgMembers.role,name:u.orgs.name,isPersonal:u.orgs.isPersonal}).from(u.orgMembers).innerJoin(u.orgs,Q(u.orgMembers.orgId,u.orgs.id)).where(Q(u.orgMembers.userId,n)).all().map((i)=>({id:i.orgId,name:i.name,role:i.role,isPersonal:i.isPersonal}))}function Yn(t,n){let o=t.select().from(u.orgs).where(Q(u.orgs.id,n)).get();if(!o)return null;return{id:o.id,name:o.name,isPersonal:o.isPersonal}}function pt(t,n){return t.select({userId:u.orgMembers.userId,email:u.users.email,role:u.orgMembers.role}).from(u.orgMembers).innerJoin(u.users,Q(u.orgMembers.userId,u.users.id)).where(Q(u.orgMembers.orgId,n)).all()}function ht(t,n){let o=t.select({role:u.orgMembers.role}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).get();if(!o)throw Error("Member not found in org");if(o.role==="admin"&&n.role!=="admin"){if(t.select({count:Nf`count(*)`}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.role,"admin"))).get().count<=1)throw Error("Cannot remove the last admin from the org")}t.update(u.orgMembers).set({role:n.role}).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).run()}function jt(t,n){if(t.select({isPersonal:u.orgs.isPersonal}).from(u.orgs).where(Q(u.orgs.id,n.orgId)).get()?.isPersonal)throw Error("Cannot remove members from a personal org");let i=t.select({role:u.orgMembers.role}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).get();if(!i)throw Error("Member not found in org");if(i.role==="admin"){if(t.select({count:Nf`count(*)`}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.role,"admin"))).get().count<=1)throw Error("Cannot remove the last admin from the org")}let e=t.select({id:u.drives.id}).from(u.drives).where(Q(u.drives.orgId,n.orgId)).all();for(let r of e)t.delete(u.driveMembers).where(Wt(Q(u.driveMembers.driveId,r.id),Q(u.driveMembers.userId,n.userId))).run();t.delete(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).run()}function dt(t,n){let o=t.select().from(u.users).where(Q(u.users.email,n.email)).get();if(!o)throw Error(`User with email ${n.email} not found`);t.insert(u.orgMembers).values({orgId:n.orgId,userId:o.id,role:n.role}).onConflictDoUpdate({target:[u.orgMembers.orgId,u.orgMembers.userId],set:{role:n.role}}).run();let i=t.select().from(u.drives).where(Q(u.drives.orgId,n.orgId)).get();if(i)t.insert(u.driveMembers).values({driveId:i.id,userId:o.id,role:n.role}).onConflictDoUpdate({target:[u.driveMembers.driveId,u.driveMembers.userId],set:{role:n.role}}).run()}var Qi=N(()=>{G();Zi()});import{eq as Rf}from"drizzle-orm";function _f(t){let n=new Bun.CryptoHasher("sha256");return n.update(t),n.digest("hex")}function F_(){let t=new Uint8Array(32);return crypto.getRandomValues(t),`af_${Array.from(t,(o)=>o.toString(16).padStart(2,"0")).join("")}`}function M_(){return crypto.randomUUID()}function Et(t,n){let o=M_(),i=F_(),e=_f(i),r=new Date;return t.insert(u.users).values({id:o,email:n.email,apiKeyHash:e,createdAt:r}).run(),Kt(t,{name:n.email.split("@")[0],userId:o,isPersonal:!0}),{user:{id:o,email:n.email},apiKey:i}}function ut(t,n){let o=_f(n),i=t.select().from(u.users).where(Rf(u.users.apiKeyHash,o)).get();if(!i)return null;return{id:i.id,email:i.email}}function Tn(t,n){let o=t.select().from(u.users).where(Rf(u.users.email,n)).get();if(!o)return null;return{id:o.id,email:o.email}}var Ji=N(()=>{G();Qi()});import{eq as Mt,and as Bi}from"drizzle-orm";function b(t,n){if(n.driveId){let r=t.select().from(u.drives).where(Mt(u.drives.id,n.driveId)).get();if(!r)throw Error(`Drive not found: ${n.driveId}`);let E=Rt(t,n.userId,n.driveId);if(!E)throw Error("You do not have access to this drive");return{orgId:r.orgId,driveId:n.driveId,role:E}}if(n.orgId){let r=t.select().from(u.drives).where(Bi(Mt(u.drives.orgId,n.orgId),Mt(u.drives.isDefault,!0))).get();if(!r)throw Error(`No default drive for org: ${n.orgId}`);let E=Rt(t,n.userId,r.id);if(!E)throw Error("You do not have access to this drive");return{orgId:n.orgId,driveId:r.id,role:E}}let o=t.select({orgId:u.orgMembers.orgId}).from(u.orgMembers).innerJoin(u.orgs,Mt(u.orgMembers.orgId,u.orgs.id)).where(Bi(Mt(u.orgMembers.userId,n.userId),Mt(u.orgs.isPersonal,!0))).get();if(!o)throw Error("No personal org found for user");let i=t.select().from(u.drives).where(Bi(Mt(u.drives.orgId,o.orgId),Mt(u.drives.isDefault,!0))).get();if(!i)throw Error("No default drive found");let e=Rt(t,n.userId,i.id);if(!e)throw Error("You do not have access to your default drive");return{orgId:o.orgId,driveId:i.id,role:e}}var wf=N(()=>{G();an()});function Gn(t){let n=P();if(n.auth.apiKey){if(ut(t,n.auth.apiKey))return{apiKey:n.auth.apiKey}}console.error("[agent-fs] No local user found, creating one...");let o=Et(t,{email:"local@agent-fs.local"});return U("auth.apiKey",o.apiKey),console.error("[agent-fs] Local user created automatically."),{apiKey:o.apiKey}}var yf=N(()=>{wn();Ji()});var gf=N(()=>{Ji();Qi();Zi();an();wf();yf()});var Df;var Lf=N(()=>{Df={name:"agent-fs",version:"0.7.4",private:!0,workspaces:["packages/*"],scripts:{typecheck:"tsc --build",test:"bun test packages/*/src/","test:coverage":"bun test --coverage packages/*/src/",build:"cd packages/cli && bun run build:npm","install-local":"bun run build && cd packages/cli && bun link","uninstall-local":"bun remove -g @desplega.ai/agent-fs && rm -f ~/.bun/bin/agent-fs","deploy:fly":"fly deploy -a agent-fs-taras"},devDependencies:{"bun-types":"^1.2.0",typescript:"^5.7.0",yaml:"^2.8.2","zod-to-json-schema":"^3.25.1"},overrides:{chromadb:"npm:empty-npm-package@1.0.0","chromadb-default-embed":"npm:empty-npm-package@1.0.0","@xenova/transformers":"npm:empty-npm-package@1.0.0","tree-sitter-wasms":"npm:empty-npm-package@1.0.0","web-tree-sitter":"npm:empty-npm-package@1.0.0","cohere-ai":"npm:empty-npm-package@1.0.0",voyageai:"npm:empty-npm-package@1.0.0",ollama:"npm:empty-npm-package@1.0.0"}}});var s;var Vi=N(()=>{Lf();s=Df.version});var If={};bt(If,{LocalEmbeddingProvider:()=>Of});import{join as Y_}from"path";import{mkdirSync as G_,existsSync as H_}from"fs";class Of{name="local";dimensions=768;llama=null;model=null;embeddingContext=null;initPromise=null;async init(){if(this.embeddingContext)return;if(this.initPromise)return this.initPromise;return this.initPromise=this._doInit(),this.initPromise}async _doInit(){let{getLlama:t,resolveModelFile:n}=await import("node-llama-cpp");this.llama=await t();let o=Y_(V(),"models");if(!H_(o))G_(o,{recursive:!0});console.error("[agent-fs] Resolving local embedding model...");let i=await n(Z_,o);console.error("[agent-fs] Model ready:",i),this.model=await this.llama.loadModel({modelPath:i}),this.embeddingContext=await this.model.createEmbeddingContext()}async embed(t){await this.init();let n=await this.embeddingContext.getEmbeddingFor(t);return Array.from(n.vector)}async embedBatch(t){await this.init();let n=[];for(let o of t){let i=await this.embeddingContext.getEmbeddingFor(o);n.push(Array.from(i.vector))}return n}async dispose(){if(this.embeddingContext)await this.embeddingContext.dispose(),this.embeddingContext=null;if(this.model)await this.model.dispose(),this.model=null;this.initPromise=null}}var Z_="hf:nomic-ai/nomic-embed-text-v1.5-GGUF:Q8_0";var Uf=N(()=>{wn()});var Wi={};bt(Wi,{OpenAIEmbeddingProvider:()=>Sf});import Q_ from"openai";class Sf{name="openai";dimensions=768;client;constructor(t){this.client=new Q_({apiKey:t})}async embed(t){return(await this.client.embeddings.create({model:"text-embedding-3-small",input:t,dimensions:768})).data[0].embedding}async embedBatch(t){return(await this.client.embeddings.create({model:"text-embedding-3-small",input:t,dimensions:768})).data.sort((o,i)=>o.index-i.index).map((o)=>o.embedding)}}var Ki=()=>{};var pi={};bt(pi,{GeminiEmbeddingProvider:()=>$f});import{GoogleGenAI as J_}from"@google/genai";class $f{name="gemini";dimensions=768;client;constructor(t){this.client=new J_({apiKey:t})}async embed(t){return(await this.client.models.embedContent({model:"gemini-embedding-001",contents:t,config:{outputDimensionality:768}})).embeddings[0].values}async embedBatch(t){let n=[];for(let o of t){let i=await this.client.models.embedContent({model:"gemini-embedding-001",contents:o,config:{outputDimensionality:768}});n.push(i.embeddings[0].values)}return n}}var hi=()=>{};async function Xf(t){switch(t.provider){case"local":{let{LocalEmbeddingProvider:n}=await Promise.resolve().then(() => (Uf(),If));return new n}case"openai":{if(!t.apiKey)throw Error("OpenAI API key required. Set embedding.apiKey in config.");let{OpenAIEmbeddingProvider:n}=await Promise.resolve().then(() => (Ki(),Wi));return new n(t.apiKey)}case"gemini":{if(!t.apiKey)throw Error("Gemini API key required. Set embedding.apiKey in config.");let{GeminiEmbeddingProvider:n}=await Promise.resolve().then(() => (hi(),pi));return new n(t.apiKey)}default:throw Error(`Unknown embedding provider: ${t.provider}`)}}async function ln(t){if(process.env.OPENAI_API_KEY)try{let{OpenAIEmbeddingProvider:n}=await Promise.resolve().then(() => (Ki(),Wi));return new n(process.env.OPENAI_API_KEY)}catch(n){console.error("[agent-fs] Failed to load OpenAI provider:",n)}if(process.env.GEMINI_API_KEY)try{let{GeminiEmbeddingProvider:n}=await Promise.resolve().then(() => (hi(),pi));return new n(process.env.GEMINI_API_KEY)}catch(n){console.error("[agent-fs] Failed to load Gemini provider:",n)}if(t?.provider&&t.provider!=="local"&&t.apiKey)try{return await Xf(t)}catch(n){console.error("[agent-fs] Failed to create embedding provider from config:",n)}if(t?.provider==="local")try{return await Xf(t)}catch(n){console.error("[agent-fs] Failed to load local embedding provider:",n)}return null}var Pf,Cf,Ff=(t)=>typeof t==="string"?{...Cf,name:t}:{...Cf,...t};var Ro=N(()=>{Pf=Symbol("Let zodToJsonSchema decide on which parser to use"),Cf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"}});var Mf=(t)=>{let n=Ff(t),o=n.name!==void 0?[...n.basePath,n.definitionPath,n.name]:n.basePath;return{...n,flags:{hasReferencedOpenAiAnyType:!1},currentPath:o,propertyPath:void 0,seen:new Map(Object.entries(n.definitions).map(([i,e])=>[e._def,{def:e._def,path:[...n.basePath,n.definitionPath,i],jsonSchema:void 0}]))}};var ji=N(()=>{Ro()});function di(t,n,o,i){if(!i?.errorMessages)return;if(o)t.errorMessage={...t.errorMessage,[n]:o}}function X(t,n,o,i,e){t[n]=o,di(t,n,i,e)}var _o=(t,n)=>{let o=0;for(;o<t.length&&o<n.length;o++)if(t[o]!==n[o])break;return[(t.length-o).toString(),...n.slice(o)].join("/")};function H(t){if(t.target!=="openAi")return{};let n=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?_o(n,t.currentPath):n.join("/")}}var tt=()=>{};import{ZodFirstPartyTypeKind as B_}from"zod/v3";function vf(t,n){let o={type:"array"};if(t.type?._def&&t.type?._def?.typeName!==B_.ZodAny)o.items=g(t.type._def,{...n,currentPath:[...n.currentPath,"items"]});if(t.minLength)X(o,"minItems",t.minLength.value,t.minLength.message,n);if(t.maxLength)X(o,"maxItems",t.maxLength.value,t.maxLength.message,n);if(t.exactLength)X(o,"minItems",t.exactLength.value,t.exactLength.message,n),X(o,"maxItems",t.exactLength.value,t.exactLength.message,n);return o}var ki=N(()=>{B()});function Yf(t,n){let o={type:"integer",format:"int64"};if(!t.checks)return o;for(let i of t.checks)switch(i.kind){case"min":if(n.target==="jsonSchema7")if(i.inclusive)X(o,"minimum",i.value,i.message,n);else X(o,"exclusiveMinimum",i.value,i.message,n);else{if(!i.inclusive)o.exclusiveMinimum=!0;X(o,"minimum",i.value,i.message,n)}break;case"max":if(n.target==="jsonSchema7")if(i.inclusive)X(o,"maximum",i.value,i.message,n);else X(o,"exclusiveMaximum",i.value,i.message,n);else{if(!i.inclusive)o.exclusiveMaximum=!0;X(o,"maximum",i.value,i.message,n)}break;case"multipleOf":X(o,"multipleOf",i.value,i.message,n);break}return o}var mi=()=>{};function Gf(){return{type:"boolean"}}function wo(t,n){return g(t.type._def,n)}var yo=N(()=>{B()});var Hf=(t,n)=>{return g(t.innerType._def,n)};var zi=N(()=>{B()});function bi(t,n,o){let i=o??n.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((e,r)=>bi(t,n,e))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return V_(t,n)}}var V_=(t,n)=>{let o={type:"integer",format:"unix-time"};if(n.target==="openApi3")return o;for(let i of t.checks)switch(i.kind){case"min":X(o,"minimum",i.value,i.message,n);break;case"max":X(o,"maximum",i.value,i.message,n);break}return o};var si=()=>{};function Zf(t,n){return{...g(t.innerType._def,n),default:t.defaultValue()}}var qi=N(()=>{B()});function Qf(t,n){return n.effectStrategy==="input"?g(t.schema._def,n):H(n)}var ci=N(()=>{B();tt()});function Jf(t){return{type:"string",enum:Array.from(t.values)}}function Bf(t,n){let o=[g(t.left._def,{...n,currentPath:[...n.currentPath,"allOf","0"]}),g(t.right._def,{...n,currentPath:[...n.currentPath,"allOf","1"]})].filter((r)=>!!r),i=n.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,e=[];return o.forEach((r)=>{if(W_(r)){if(e.push(...r.allOf),r.unevaluatedProperties===void 0)i=void 0}else{let E=r;if("additionalProperties"in r&&r.additionalProperties===!1){let{additionalProperties:f,...T}=r;E=T}else i=void 0;e.push(E)}}),e.length?{allOf:e,...i}:void 0}var W_=(t)=>{if("type"in t&&t.type==="string")return!1;return"allOf"in t};var xi=N(()=>{B()});function Vf(t,n){let o=typeof t.value;if(o!=="bigint"&&o!=="number"&&o!=="boolean"&&o!=="string")return{type:Array.isArray(t.value)?"array":"object"};if(n.target==="openApi3")return{type:o==="bigint"?"integer":o,enum:[t.value]};return{type:o==="bigint"?"integer":o,const:t.value}}function go(t,n){let o={type:"string"};if(t.checks)for(let i of t.checks)switch(i.kind){case"min":X(o,"minLength",typeof o.minLength==="number"?Math.max(o.minLength,i.value):i.value,i.message,n);break;case"max":X(o,"maxLength",typeof o.maxLength==="number"?Math.min(o.maxLength,i.value):i.value,i.message,n);break;case"email":switch(n.emailStrategy){case"format:email":Tt(o,"email",i.message,n);break;case"format:idn-email":Tt(o,"idn-email",i.message,n);break;case"pattern:zod":k(o,ft.email,i.message,n);break}break;case"url":Tt(o,"uri",i.message,n);break;case"uuid":Tt(o,"uuid",i.message,n);break;case"regex":k(o,i.regex,i.message,n);break;case"cuid":k(o,ft.cuid,i.message,n);break;case"cuid2":k(o,ft.cuid2,i.message,n);break;case"startsWith":k(o,RegExp(`^${te(i.value,n)}`),i.message,n);break;case"endsWith":k(o,RegExp(`${te(i.value,n)}$`),i.message,n);break;case"datetime":Tt(o,"date-time",i.message,n);break;case"date":Tt(o,"date",i.message,n);break;case"time":Tt(o,"time",i.message,n);break;case"duration":Tt(o,"duration",i.message,n);break;case"length":X(o,"minLength",typeof o.minLength==="number"?Math.max(o.minLength,i.value):i.value,i.message,n),X(o,"maxLength",typeof o.maxLength==="number"?Math.min(o.maxLength,i.value):i.value,i.message,n);break;case"includes":{k(o,RegExp(te(i.value,n)),i.message,n);break}case"ip":{if(i.version!=="v6")Tt(o,"ipv4",i.message,n);if(i.version!=="v4")Tt(o,"ipv6",i.message,n);break}case"base64url":k(o,ft.base64url,i.message,n);break;case"jwt":k(o,ft.jwt,i.message,n);break;case"cidr":{if(i.version!=="v6")k(o,ft.ipv4Cidr,i.message,n);if(i.version!=="v4")k(o,ft.ipv6Cidr,i.message,n);break}case"emoji":k(o,ft.emoji(),i.message,n);break;case"ulid":{k(o,ft.ulid,i.message,n);break}case"base64":{switch(n.base64Strategy){case"format:binary":{Tt(o,"binary",i.message,n);break}case"contentEncoding:base64":{X(o,"contentEncoding","base64",i.message,n);break}case"pattern:zod":{k(o,ft.base64,i.message,n);break}}break}case"nanoid":k(o,ft.nanoid,i.message,n);case"toLowerCase":case"toUpperCase":case"trim":break;default:((e)=>{})(i)}return o}function te(t,n){return n.patternStrategy==="escape"?p_(t):t}function p_(t){let n="";for(let o=0;o<t.length;o++){if(!K_.has(t[o]))n+="\\";n+=t[o]}return n}function Tt(t,n,o,i){if(t.format||t.anyOf?.some((e)=>e.format)){if(!t.anyOf)t.anyOf=[];if(t.format){if(t.anyOf.push({format:t.format,...t.errorMessage&&i.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage){if(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0)delete t.errorMessage}}t.anyOf.push({format:n,...o&&i.errorMessages&&{errorMessage:{format:o}}})}else X(t,"format",n,o,i)}function k(t,n,o,i){if(t.pattern||t.allOf?.some((e)=>e.pattern)){if(!t.allOf)t.allOf=[];if(t.pattern){if(t.allOf.push({pattern:t.pattern,...t.errorMessage&&i.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage){if(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0)delete t.errorMessage}}t.allOf.push({pattern:Wf(n,i),...o&&i.errorMessages&&{errorMessage:{pattern:o}}})}else X(t,"pattern",Wf(n,i),o,i)}function Wf(t,n){if(!n.applyRegexFlags||!t.flags)return t.source;let o={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},i=o.i?t.source.toLowerCase():t.source,e="",r=!1,E=!1,f=!1;for(let T=0;T<i.length;T++){if(r){e+=i[T],r=!1;continue}if(o.i){if(E){if(i[T].match(/[a-z]/)){if(f)e+=i[T],e+=`${i[T-2]}-${i[T]}`.toUpperCase(),f=!1;else if(i[T+1]==="-"&&i[T+2]?.match(/[a-z]/))e+=i[T],f=!0;else e+=`${i[T]}${i[T].toUpperCase()}`;continue}}else if(i[T].match(/[a-z]/)){e+=`[${i[T]}${i[T].toUpperCase()}]`;continue}}if(o.m){if(i[T]==="^"){e+=`(^|(?<=[\r
172
+ LIMIT ?`).all(r,o),T=[],l=new Set;for(let A of f){let R=t.db.select().from(u.contentChunks).where(Ci(u.contentChunks.id,A.chunk_id)).get();if(!R||R.driveId!==t.driveId)continue;if(l.has(R.filePath))continue;l.add(R.filePath);let w=t.db.select().from(u.files).where(g_(Ci(u.files.path,R.filePath),Ci(u.files.driveId,t.driveId))).get();T.push({path:R.filePath,snippet:R.content.slice(0,200),author:w?.author,modifiedAt:w?.modifiedAt})}return T}function D_(t,n,o){let i=n.split(/\s+/).filter(Boolean).map((e)=>`"${e}"`).join(" OR ");if(!i)return[];try{return oo(t.db,{pattern:i,driveId:t.driveId}).slice(0,o).map((r)=>({path:r.path,snippet:r.snippet}))}catch{return[]}}var xu=N(()=>{G()});import{eq as eo,and as O_,or as I_,isNull as U_}from"drizzle-orm";async function au(t,n){let o=[eo(u.files.driveId,t.driveId),eo(u.files.isDeleted,!1),I_(eo(u.files.embeddingStatus,"failed"),U_(u.files.embeddingStatus),eo(u.files.embeddingStatus,"pending"))];if(n.path){let{like:T}=await import("drizzle-orm"),l=n.path.endsWith("/")?n.path:n.path+"/";o.push(T(u.files.path,l+"%"))}let i=t.db.select({path:u.files.path}).from(u.files).where(O_(...o)).all(),e=0,r=0,E=0,f=3;for(let T=0;T<i.length;T+=f){let l=i.slice(T,T+f),A=await Promise.allSettled(l.map(async(R)=>{let w=I(t.orgId,t.driveId,R.path),L=await t.s3.getObject(w),O=L.contentType??K(R.path),D=Pt(L.body,O);if(D===null)return Mn(t,R.path),"skipped";if(wt(t.db,{path:R.path,driveId:t.driveId,content:D}),t.embeddingProvider)return await Di(t.db,t.embeddingProvider,{path:R.path,driveId:t.driveId,content:D}),"reindexed";return"skipped"}));for(let R of A)if(R.status==="fulfilled")if(R.value==="reindexed")e++;else E++;else console.error("Reindex failed:",R.reason),r++}return{reindexed:e,failed:r,skipped:E}}var tf=N(()=>{G();W();Fn();rn();rt()});import{eq as nf,and as S_,like as $_}from"drizzle-orm";async function of(t,n){let o=Ct(n.path??"/"),i=I(t.orgId,t.driveId,o),{objects:e}=await t.s3.listObjects(i),r=t.db.select().from(u.files).where(S_(nf(u.files.driveId,t.driveId),$_(u.files.path,o+"%"),nf(u.files.isDeleted,!1))).all(),E=new Map(r.map((T)=>[T.path,T])),f=[];for(let T of e){let l=T.key.slice(i.length);if(!l)continue;let A=l.split("/").filter(Boolean);if(A.length===0)continue;if(n.depth!==void 0&&A.length>n.depth)continue;let R=f;for(let w=0;w<A.length;w++){let L=A[w],O=w===A.length-1,D=!O||l.endsWith("/");if(D&&!O){let C=R.find((Z)=>Z.name===L&&Z.type==="directory");if(!C)C={name:L,type:"directory",children:[]},R.push(C);if(!C.children)C.children=[];R=C.children}else if(D&&O){let C=R.find((Z)=>Z.name===L&&Z.type==="directory");if(!C)C={name:L,type:"directory",children:[]},R.push(C)}else{let C=o+A.slice(0,w+1).join("/"),Z=E.get(C),_n={name:L,type:"file",size:Z?.size??T.size};if(Z?.author)_n.author=Z.author;if(Z?.modifiedAt??T.lastModified)_n.modifiedAt=Z?.modifiedAt??T.lastModified;R.push(_n)}}}return{tree:f}}var ef=N(()=>{G();W()});import{eq as rf,and as X_,like as C_}from"drizzle-orm";function P_(t){let n="",o=0;while(o<t.length){let i=t[o];if(i==="*")if(t[o+1]==="*"){if(n+=".*",o+=2,t[o]==="/")o++}else n+="[^/]*",o++;else if(i==="?")n+="[^/]",o++;else if(".+^${}()|[]\\".includes(i))n+="\\"+i,o++;else n+=i,o++}return new RegExp("^"+n+"$")}async function Ef(t,n){let o=n.path?Ct(n.path):"/",i=I(t.orgId,t.driveId,o),{objects:e}=await t.s3.listObjects(i),r=t.db.select().from(u.files).where(X_(rf(u.files.driveId,t.driveId),C_(u.files.path,o+"%"),rf(u.files.isDeleted,!1))).all(),E=new Map(r.map((l)=>[l.path,l])),f=P_(n.pattern),T=[];for(let l of e){let A=l.key.slice(i.length);if(!A||A.endsWith("/"))continue;if(f.test(A)){let R=o+A,w=E.get(R);T.push({path:R,size:w?.size??l.size,modifiedAt:w?.modifiedAt??l.lastModified})}}return{matches:T}}var uf=N(()=>{G();W()});async function ff(t,n){let o=Cn(n.path),i=I(t.orgId,t.driveId,o),e=n.expiresIn??86400;try{await t.s3.headObject(i)}catch(f){if(f?.name==="NotFound"||f?.name==="NoSuchKey"||f?.$metadata?.httpStatusCode===404)throw new M(`File not found: ${o}`,{path:o});throw f}let r=K(o);return{url:await t.s3.getPresignedUrl(i,e,r!=="application/octet-stream"?r:void 0),path:o,expiresIn:e,expiresAt:new Date(Date.now()+e*1000).toISOString()}}var Tf=N(()=>{W();m();rt()});function Pi(t,n,o,i){let e=i.startsWith("/")?i.slice(1):i;return`${t}/file/~/${n}/${o}/${e}`}import{eq as F,and as yt,sql as Fi,desc as lf}from"drizzle-orm";function Mi(t,n){t.db.insert(u.events).values({id:crypto.randomUUID(),orgId:t.orgId,type:n.type,resourceType:n.resourceType,resourceId:n.resourceId,actor:t.userId,target:n.target??null,status:"created",metadata:n.metadata?JSON.stringify(n.metadata):null,createdAt:new Date}).run()}function ro(t){return{id:t.id,parentId:t.parentId??void 0,path:t.path,lineStart:t.lineStart??void 0,lineEnd:t.lineEnd??void 0,quotedContent:t.quotedContent??void 0,body:t.body,author:t.author,resolved:t.resolved??!1,resolvedBy:t.resolvedBy??void 0,resolvedAt:t.resolvedAt??void 0,fileVersionId:t.fileVersionId??void 0,replyCount:t.replyCount??0,createdAt:t.createdAt,updatedAt:t.updatedAt}}async function Eo(t,n){let o=new Date,i=crypto.randomUUID(),e=n.path;if(n.parentId){let E=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.parentId),F(u.comments.isDeleted,!1))).get();if(!E)throw new M("Parent comment not found",{suggestion:"Check that the parent comment ID is correct and not deleted"});if(E.parentId)throw new c("Cannot reply to a reply \u2014 only root comments accept replies",{suggestion:"Reply to the root comment instead"});if(!e)e=E.path}if(!e)throw new c("path is required for root comments",{field:"path"});let r=t.db.select({id:u.fileVersions.id}).from(u.fileVersions).where(yt(F(u.fileVersions.path,e),F(u.fileVersions.driveId,t.driveId))).orderBy(lf(u.fileVersions.id)).limit(1).get();return t.db.insert(u.comments).values({id:i,parentId:n.parentId??null,orgId:t.orgId,driveId:t.driveId,path:e,lineStart:n.lineStart??null,lineEnd:n.lineEnd??null,quotedContent:n.quotedContent??null,fileVersionId:r?.id??null,body:n.body,author:t.userId,resolved:!1,createdAt:o,updatedAt:o,isDeleted:!1}).run(),Mi(t,{type:"comment_created",resourceType:"comment",resourceId:i,metadata:{path:e,parentId:n.parentId}}),{id:i,path:e,body:n.body,parentId:n.parentId,lineStart:n.lineStart,lineEnd:n.lineEnd,author:t.userId,createdAt:o}}async function uo(t,n){let o=[F(u.comments.driveId,t.driveId),F(u.comments.isDeleted,!1)];if(n.path)o.push(F(u.comments.path,n.path));if(n.parentId)o.push(F(u.comments.parentId,n.parentId));else if(n.parentId===void 0&&!n.resolved)o.push(Fi`${u.comments.parentId} IS NULL`),o.push(F(u.comments.resolved,!1));else if(n.parentId===void 0&&n.resolved)o.push(Fi`${u.comments.parentId} IS NULL`);if(n.orgId)o.push(F(u.comments.orgId,n.orgId));let i=n.limit??50,e=n.offset??0;return{comments:t.db.select().from(u.comments).where(yt(...o)).orderBy(lf(u.comments.createdAt)).limit(i).offset(e).all().map((f)=>{let l=t.db.select().from(u.comments).where(yt(F(u.comments.parentId,f.id),F(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((A)=>ro({...A,replyCount:0}));return{...ro({...f,replyCount:l.length}),replies:l}})}}async function fo(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});let i=t.db.select({count:Fi`count(*)`}).from(u.comments).where(yt(F(u.comments.parentId,o.id),F(u.comments.isDeleted,!1))).get(),e=ro({...o,replyCount:i?.count??0}),E=t.db.select().from(u.comments).where(yt(F(u.comments.parentId,n.id),F(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((f)=>ro({...f,replyCount:0}));return{comment:e,replies:E}}async function To(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.author!==t.userId)throw new it("You can only edit your own comments",{suggestion:"Only the comment author can update it"});let i=new Date;return t.db.update(u.comments).set({body:n.body,updatedAt:i}).where(F(u.comments.id,n.id)).run(),{id:n.id,body:n.body,updatedAt:i}}async function lo(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.author!==t.userId)throw new it("You can only delete your own comments",{suggestion:"Only the comment author can delete it"});let i=new Date;if(t.db.update(u.comments).set({isDeleted:!0,updatedAt:i}).where(F(u.comments.id,n.id)).run(),!o.parentId)t.db.update(u.comments).set({isDeleted:!0,updatedAt:i}).where(F(u.comments.parentId,n.id)).run();return Mi(t,{type:"comment_deleted",resourceType:"comment",resourceId:n.id}),{deleted:!0}}async function Ao(t,n){let o=t.db.select().from(u.comments).where(yt(F(u.comments.id,n.id),F(u.comments.isDeleted,!1))).get();if(!o)throw new M("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.parentId)throw new c("Cannot resolve a reply \u2014 only root comments can be resolved",{suggestion:"Resolve the parent comment instead"});let i=new Date,e=n.resolved?i:null,r=n.resolved?t.userId:null;return t.db.update(u.comments).set({resolved:n.resolved,resolvedBy:r,resolvedAt:e,updatedAt:i}).where(F(u.comments.id,n.id)).run(),Mi(t,{type:n.resolved?"comment_resolved":"comment_reopened",resourceType:"comment",resourceId:n.id}),{id:n.id,resolved:n.resolved,resolvedBy:r??void 0,resolvedAt:e??void 0}}var Af=N(()=>{G();m()});import{z as _}from"zod";async function d(t,n,o,i){let e=vi[n];if(!e)throw Error(`Unknown operation: ${n}`);if(!i?.skipAuth){let f=$n(n);Xn(t.db,{userId:t.userId,driveId:t.driveId,requiredRole:f})}let r=e.schema.parse(o),E=await e.handler(t,r);if(t.appUrl&&E&&typeof E==="object"){if("path"in E)E.appUrl=Pi(t.appUrl,t.orgId,t.driveId,E.path);else if("to"in E)E.appUrl=Pi(t.appUrl,t.orgId,t.driveId,E.to)}return E}function fn(){return Object.keys(vi)}function Ft(t){return vi[t]}var vi;var Yi=N(()=>{an();Nu();_u();yu();Lu();Iu();$u();Cu();Mu();Yu();Hu();Ju();Wu();pu();du();mu();bu();qu();xu();tf();ef();uf();Tf();Af();vi={write:{description:"Write or overwrite a file. Creates the file if it doesn't exist, or creates a new version. Use expectedVersion for optimistic concurrency. Returns { version, path, size }.",handler:io,schema:_.object({path:_.string(),content:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},cat:{description:"Read file content with optional pagination via offset/limit. Returns { content, totalLines, truncated }.",handler:Ru,schema:_.object({path:_.string(),offset:_.number().int().min(0).optional(),limit:_.number().int().min(1).optional()})},edit:{description:"Replace a specific string in a file (surgical find-and-replace). Captures the edit intent as a diff summary in version history. Returns { version, path, changes }.",handler:wu,schema:_.object({path:_.string(),old_string:_.string(),new_string:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},append:{description:"Append content to the end of an existing file. Creates a new version. Returns { version, size }.",handler:gu,schema:_.object({path:_.string(),content:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},ls:{description:"List immediate children of a directory. Returns { entries } where each entry has name, type (file/directory), size, author, modifiedAt.",handler:Ou,schema:_.object({path:_.string().optional()})},stat:{description:"Get file metadata without reading content. Returns path, size, contentType, author, currentVersion, createdAt, modifiedAt, isDeleted, embeddingStatus.",handler:Su,schema:_.object({path:_.string()})},rm:{description:"Delete a file. Removes from S3, cleans up FTS5 index and vector embeddings. Returns { path, deleted }.",handler:Xu,schema:_.object({path:_.string(),expectedVersion:_.number().int().optional()})},mv:{description:"Move or rename a file. Preserves version history at the new path. Returns { from, to, version }.",handler:Fu,schema:_.object({from:_.string(),to:_.string(),message:_.string().optional(),expectedVersion:_.number().int().optional()})},cp:{description:"Copy a file using server-side S3 copy. Creates a new version at the destination. Returns { from, to, version }.",handler:vu,schema:_.object({from:_.string(),to:_.string(),expectedVersion:_.number().int().optional()})},tail:{description:"Read the last N lines of a file (default 20). Returns { content, totalLines, truncated }.",handler:Gu,schema:_.object({path:_.string(),lines:_.number().int().min(1).optional()})},log:{description:"Show version history for a file. Returns { versions } with version number, author, timestamp, operation type, message, and diff summary.",handler:Qu,schema:_.object({path:_.string(),limit:_.number().int().min(1).optional()})},diff:{description:"Show the diff between two versions of a file. Specify v1 and v2 version numbers. Returns { changes } as add/remove/context hunks.",handler:Vu,schema:_.object({path:_.string(),v1:_.number().int(),v2:_.number().int()})},revert:{description:"Revert a file to a previous version. Creates a new version with the old content. Returns { version, revertedTo }.",handler:Ku,schema:_.object({path:_.string(),version:_.number().int(),expectedVersion:_.number().int().optional()})},recent:{description:"Show recent activity across the drive. Optionally filter by path prefix and time window (since). Returns { entries } with path and version details.",handler:ju,schema:_.object({path:_.string().optional(),since:_.coerce.date().optional(),limit:_.number().int().min(1).optional()})},grep:{description:"Search file content using regex pattern within a specific path. Returns matching lines with line numbers. Searches the FTS5 index, not S3 directly.",handler:ku,schema:_.object({pattern:_.string(),path:_.string()})},fts:{description:"Full-text search across all file content using FTS5 tokens. Different from grep (regex) and search (semantic). Returns { matches } with path, snippet, and rank.",handler:zu,schema:_.object({pattern:_.string(),path:_.string().optional()})},search:{description:"Hybrid search combining semantic (vector) and keyword (FTS5) matching. Best for natural language queries. Degrades to keyword-only without an embedding provider.",handler:cu,schema:_.object({query:_.string(),limit:_.number().int().min(1).optional()})},"vec-search":{description:"Vector-only semantic search using embeddings. Returns results ranked by cosine similarity. Requires an embedding provider (OPENAI_API_KEY, GEMINI_API_KEY, or local).",handler:su,schema:_.object({query:_.string(),limit:_.number().int().min(1).optional()})},reindex:{description:"Re-index files with failed or missing FTS5/embedding entries. Optionally scope to a path prefix. Use after bulk writes or provider changes.",handler:au,schema:_.object({path:_.string().optional()})},tree:{description:"Recursively list all files and directories. Use depth to limit recursion. Returns a nested tree structure with name, type, size, and children.",handler:of,schema:_.object({path:_.string().optional(),depth:_.number().int().min(1).optional()})},glob:{description:"Find files by name pattern. Use `*.md` for root-level files only, `**/*.md` for recursive matching across all subdirectories. Supports `*` (any chars except /), `?` (single char), `**` (any path depth). Optionally scope to a path prefix. Returns { matches } with path, size, and modifiedAt.",handler:Ef,schema:_.object({pattern:_.string(),path:_.string().optional()})},"signed-url":{description:"Generate a temporary presigned URL for direct file download. Default expiry is 24 hours (86400 seconds). The URL requires no authentication. Returns { url, path, expiresIn, expiresAt }.",handler:ff,schema:_.object({path:_.string(),expiresIn:_.number().int().min(60).max(604800).optional()})},"comment-add":{description:"Add a comment to a file. Supports line ranges and threading via parentId. Replies auto-resolve path from parent. Returns { id, path, body, author, createdAt }.",handler:Eo,schema:_.object({path:_.string().optional(),body:_.string(),parentId:_.string().optional(),lineStart:_.number().int().optional(),lineEnd:_.number().int().optional(),quotedContent:_.string().optional()})},"comment-list":{description:"List comments on a file. Filter by path, resolved state, or parentId. Defaults to unresolved root comments. Returns { comments } with inline replies.",handler:uo,schema:_.object({path:_.string().optional(),parentId:_.string().optional(),resolved:_.boolean().optional(),orgId:_.string().optional(),limit:_.number().int().min(1).optional(),offset:_.number().int().min(0).optional()})},"comment-get":{description:"Get a single comment by ID with all its replies. Returns { comment, replies }.",handler:fo,schema:_.object({id:_.string()})},"comment-update":{description:"Update a comment's body. Only the original author can update. Returns { id, body, updatedAt }.",handler:To,schema:_.object({id:_.string(),body:_.string()})},"comment-delete":{description:"Soft-delete a comment. Only the original author can delete. Deleting a root comment also soft-deletes its replies. Returns { deleted }.",handler:lo,schema:_.object({id:_.string()})},"comment-resolve":{description:"Resolve or reopen a root comment. Set resolved=true to resolve, resolved=false to reopen. Only root comments can be resolved. Returns { id, resolved, resolvedBy, resolvedAt }.",handler:Ao,schema:_.object({id:_.string(),resolved:_.boolean()})}}});import{eq as z,and as No}from"drizzle-orm";function Qt(t,n){let o=crypto.randomUUID(),i=new Date;return t.insert(u.drives).values({id:o,orgId:n.orgId,name:n.name,isDefault:n.isDefault??!1,createdAt:i}).run(),{id:o,name:n.name}}function vn(t,n){return t.select().from(u.drives).where(z(u.drives.orgId,n)).all().map((o)=>({id:o.id,name:o.name,isDefault:o.isDefault}))}function Ot(t,n,o){return t.select().from(u.drives).where(z(u.drives.orgId,n)).all().filter((e)=>{let r=t.select({userId:u.driveMembers.userId}).from(u.driveMembers).where(z(u.driveMembers.driveId,e.id)).all();if(r.length===0)return!0;return r.some((E)=>E.userId===o)}).map((e)=>({id:e.id,name:e.name,isDefault:e.isDefault}))}function Gi(t,n){let o=t.select().from(u.drives).where(z(u.drives.id,n)).get();if(!o)return null;return{id:o.id,name:o.name,orgId:o.orgId,isDefault:o.isDefault}}function Jt(t,n){return t.select({userId:u.driveMembers.userId,email:u.users.email,role:u.driveMembers.role}).from(u.driveMembers).innerJoin(u.users,z(u.driveMembers.userId,u.users.id)).where(z(u.driveMembers.driveId,n)).all()}function Bt(t,n){if(!t.select({role:u.driveMembers.role}).from(u.driveMembers).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).get())throw Error("Member not found in drive");t.update(u.driveMembers).set({role:n.role}).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).run()}function Vt(t,n){if(!t.select({role:u.driveMembers.role}).from(u.driveMembers).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).get())throw Error("Member not found in drive");t.delete(u.driveMembers).where(No(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).run()}function Hi(t,n){t.insert(u.driveMembers).values({driveId:n.driveId,userId:n.userId,role:n.role}).onConflictDoUpdate({target:[u.driveMembers.driveId,u.driveMembers.userId],set:{role:n.role}}).run()}var Zi=N(()=>{G()});import{eq as Q,and as Wt,sql as Nf}from"drizzle-orm";function Kt(t,n){let o=crypto.randomUUID(),i=new Date;t.insert(u.orgs).values({id:o,name:n.name,isPersonal:n.isPersonal??!1,createdAt:i}).run(),t.insert(u.orgMembers).values({orgId:o,userId:n.userId,role:"admin"}).run();let e=Qt(t,{orgId:o,name:"default",isDefault:!0});return t.insert(u.driveMembers).values({driveId:e.id,userId:n.userId,role:"admin"}).run(),{id:o,name:n.name}}function p(t,n){return t.select({orgId:u.orgMembers.orgId,role:u.orgMembers.role,name:u.orgs.name,isPersonal:u.orgs.isPersonal}).from(u.orgMembers).innerJoin(u.orgs,Q(u.orgMembers.orgId,u.orgs.id)).where(Q(u.orgMembers.userId,n)).all().map((i)=>({id:i.orgId,name:i.name,role:i.role,isPersonal:i.isPersonal}))}function Yn(t,n){let o=t.select().from(u.orgs).where(Q(u.orgs.id,n)).get();if(!o)return null;return{id:o.id,name:o.name,isPersonal:o.isPersonal}}function pt(t,n){return t.select({userId:u.orgMembers.userId,email:u.users.email,role:u.orgMembers.role}).from(u.orgMembers).innerJoin(u.users,Q(u.orgMembers.userId,u.users.id)).where(Q(u.orgMembers.orgId,n)).all()}function ht(t,n){let o=t.select({role:u.orgMembers.role}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).get();if(!o)throw Error("Member not found in org");if(o.role==="admin"&&n.role!=="admin"){if(t.select({count:Nf`count(*)`}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.role,"admin"))).get().count<=1)throw Error("Cannot remove the last admin from the org")}t.update(u.orgMembers).set({role:n.role}).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).run()}function jt(t,n){if(t.select({isPersonal:u.orgs.isPersonal}).from(u.orgs).where(Q(u.orgs.id,n.orgId)).get()?.isPersonal)throw Error("Cannot remove members from a personal org");let i=t.select({role:u.orgMembers.role}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).get();if(!i)throw Error("Member not found in org");if(i.role==="admin"){if(t.select({count:Nf`count(*)`}).from(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.role,"admin"))).get().count<=1)throw Error("Cannot remove the last admin from the org")}let e=t.select({id:u.drives.id}).from(u.drives).where(Q(u.drives.orgId,n.orgId)).all();for(let r of e)t.delete(u.driveMembers).where(Wt(Q(u.driveMembers.driveId,r.id),Q(u.driveMembers.userId,n.userId))).run();t.delete(u.orgMembers).where(Wt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).run()}function dt(t,n){let o=t.select().from(u.users).where(Q(u.users.email,n.email)).get();if(!o)throw Error(`User with email ${n.email} not found`);t.insert(u.orgMembers).values({orgId:n.orgId,userId:o.id,role:n.role}).onConflictDoUpdate({target:[u.orgMembers.orgId,u.orgMembers.userId],set:{role:n.role}}).run();let i=t.select().from(u.drives).where(Q(u.drives.orgId,n.orgId)).get();if(i)t.insert(u.driveMembers).values({driveId:i.id,userId:o.id,role:n.role}).onConflictDoUpdate({target:[u.driveMembers.driveId,u.driveMembers.userId],set:{role:n.role}}).run()}var Qi=N(()=>{G();Zi()});import{eq as Rf}from"drizzle-orm";function _f(t){let n=new Bun.CryptoHasher("sha256");return n.update(t),n.digest("hex")}function F_(){let t=new Uint8Array(32);return crypto.getRandomValues(t),`af_${Array.from(t,(o)=>o.toString(16).padStart(2,"0")).join("")}`}function M_(){return crypto.randomUUID()}function Et(t,n){let o=M_(),i=F_(),e=_f(i),r=new Date;return t.insert(u.users).values({id:o,email:n.email,apiKeyHash:e,createdAt:r}).run(),Kt(t,{name:n.email.split("@")[0],userId:o,isPersonal:!0}),{user:{id:o,email:n.email},apiKey:i}}function ut(t,n){let o=_f(n),i=t.select().from(u.users).where(Rf(u.users.apiKeyHash,o)).get();if(!i)return null;return{id:i.id,email:i.email}}function Tn(t,n){let o=t.select().from(u.users).where(Rf(u.users.email,n)).get();if(!o)return null;return{id:o.id,email:o.email}}var Ji=N(()=>{G();Qi()});import{eq as Mt,and as Bi}from"drizzle-orm";function b(t,n){if(n.driveId){let r=t.select().from(u.drives).where(Mt(u.drives.id,n.driveId)).get();if(!r)throw Error(`Drive not found: ${n.driveId}`);let E=Rt(t,n.userId,n.driveId);if(!E)throw Error("You do not have access to this drive");return{orgId:r.orgId,driveId:n.driveId,role:E}}if(n.orgId){let r=t.select().from(u.drives).where(Bi(Mt(u.drives.orgId,n.orgId),Mt(u.drives.isDefault,!0))).get();if(!r)throw Error(`No default drive for org: ${n.orgId}`);let E=Rt(t,n.userId,r.id);if(!E)throw Error("You do not have access to this drive");return{orgId:n.orgId,driveId:r.id,role:E}}let o=t.select({orgId:u.orgMembers.orgId}).from(u.orgMembers).innerJoin(u.orgs,Mt(u.orgMembers.orgId,u.orgs.id)).where(Bi(Mt(u.orgMembers.userId,n.userId),Mt(u.orgs.isPersonal,!0))).get();if(!o)throw Error("No personal org found for user");let i=t.select().from(u.drives).where(Bi(Mt(u.drives.orgId,o.orgId),Mt(u.drives.isDefault,!0))).get();if(!i)throw Error("No default drive found");let e=Rt(t,n.userId,i.id);if(!e)throw Error("You do not have access to your default drive");return{orgId:o.orgId,driveId:i.id,role:e}}var wf=N(()=>{G();an()});function Gn(t){let n=P();if(n.auth.apiKey){if(ut(t,n.auth.apiKey))return{apiKey:n.auth.apiKey}}console.error("[agent-fs] No local user found, creating one...");let o=Et(t,{email:"local@agent-fs.local"});return U("auth.apiKey",o.apiKey),console.error("[agent-fs] Local user created automatically."),{apiKey:o.apiKey}}var yf=N(()=>{wn();Ji()});var gf=N(()=>{Ji();Qi();Zi();an();wf();yf()});var Df;var Lf=N(()=>{Df={name:"agent-fs",version:"0.7.5",private:!0,workspaces:["packages/*"],scripts:{typecheck:"tsc --build",test:"bun test packages/*/src/","test:coverage":"bun test --coverage packages/*/src/",build:"cd packages/cli && bun run build:npm","install-local":"bun run build && cd packages/cli && bun link","uninstall-local":"bun remove -g @desplega.ai/agent-fs && rm -f ~/.bun/bin/agent-fs","deploy:fly":"fly deploy -a agent-fs-taras"},devDependencies:{"bun-types":"^1.2.0",typescript:"^5.7.0",yaml:"^2.8.2","zod-to-json-schema":"^3.25.1"},overrides:{chromadb:"npm:empty-npm-package@1.0.0","chromadb-default-embed":"npm:empty-npm-package@1.0.0","@xenova/transformers":"npm:empty-npm-package@1.0.0","tree-sitter-wasms":"npm:empty-npm-package@1.0.0","web-tree-sitter":"npm:empty-npm-package@1.0.0","cohere-ai":"npm:empty-npm-package@1.0.0",voyageai:"npm:empty-npm-package@1.0.0",ollama:"npm:empty-npm-package@1.0.0"}}});var s;var Vi=N(()=>{Lf();s=Df.version});var If={};bt(If,{LocalEmbeddingProvider:()=>Of});import{join as Y_}from"path";import{mkdirSync as G_,existsSync as H_}from"fs";class Of{name="local";dimensions=768;llama=null;model=null;embeddingContext=null;initPromise=null;async init(){if(this.embeddingContext)return;if(this.initPromise)return this.initPromise;return this.initPromise=this._doInit(),this.initPromise}async _doInit(){let{getLlama:t,resolveModelFile:n}=await import("node-llama-cpp");this.llama=await t();let o=Y_(V(),"models");if(!H_(o))G_(o,{recursive:!0});console.error("[agent-fs] Resolving local embedding model...");let i=await n(Z_,o);console.error("[agent-fs] Model ready:",i),this.model=await this.llama.loadModel({modelPath:i}),this.embeddingContext=await this.model.createEmbeddingContext()}async embed(t){await this.init();let n=await this.embeddingContext.getEmbeddingFor(t);return Array.from(n.vector)}async embedBatch(t){await this.init();let n=[];for(let o of t){let i=await this.embeddingContext.getEmbeddingFor(o);n.push(Array.from(i.vector))}return n}async dispose(){if(this.embeddingContext)await this.embeddingContext.dispose(),this.embeddingContext=null;if(this.model)await this.model.dispose(),this.model=null;this.initPromise=null}}var Z_="hf:nomic-ai/nomic-embed-text-v1.5-GGUF:Q8_0";var Uf=N(()=>{wn()});var Wi={};bt(Wi,{OpenAIEmbeddingProvider:()=>Sf});import Q_ from"openai";class Sf{name="openai";dimensions=768;client;constructor(t){this.client=new Q_({apiKey:t})}async embed(t){return(await this.client.embeddings.create({model:"text-embedding-3-small",input:t,dimensions:768})).data[0].embedding}async embedBatch(t){return(await this.client.embeddings.create({model:"text-embedding-3-small",input:t,dimensions:768})).data.sort((o,i)=>o.index-i.index).map((o)=>o.embedding)}}var Ki=()=>{};var pi={};bt(pi,{GeminiEmbeddingProvider:()=>$f});import{GoogleGenAI as J_}from"@google/genai";class $f{name="gemini";dimensions=768;client;constructor(t){this.client=new J_({apiKey:t})}async embed(t){return(await this.client.models.embedContent({model:"gemini-embedding-001",contents:t,config:{outputDimensionality:768}})).embeddings[0].values}async embedBatch(t){let n=[];for(let o of t){let i=await this.client.models.embedContent({model:"gemini-embedding-001",contents:o,config:{outputDimensionality:768}});n.push(i.embeddings[0].values)}return n}}var hi=()=>{};async function Xf(t){switch(t.provider){case"local":{let{LocalEmbeddingProvider:n}=await Promise.resolve().then(() => (Uf(),If));return new n}case"openai":{if(!t.apiKey)throw Error("OpenAI API key required. Set embedding.apiKey in config.");let{OpenAIEmbeddingProvider:n}=await Promise.resolve().then(() => (Ki(),Wi));return new n(t.apiKey)}case"gemini":{if(!t.apiKey)throw Error("Gemini API key required. Set embedding.apiKey in config.");let{GeminiEmbeddingProvider:n}=await Promise.resolve().then(() => (hi(),pi));return new n(t.apiKey)}default:throw Error(`Unknown embedding provider: ${t.provider}`)}}async function ln(t){if(process.env.OPENAI_API_KEY)try{let{OpenAIEmbeddingProvider:n}=await Promise.resolve().then(() => (Ki(),Wi));return new n(process.env.OPENAI_API_KEY)}catch(n){console.error("[agent-fs] Failed to load OpenAI provider:",n)}if(process.env.GEMINI_API_KEY)try{let{GeminiEmbeddingProvider:n}=await Promise.resolve().then(() => (hi(),pi));return new n(process.env.GEMINI_API_KEY)}catch(n){console.error("[agent-fs] Failed to load Gemini provider:",n)}if(t?.provider&&t.provider!=="local"&&t.apiKey)try{return await Xf(t)}catch(n){console.error("[agent-fs] Failed to create embedding provider from config:",n)}if(t?.provider==="local")try{return await Xf(t)}catch(n){console.error("[agent-fs] Failed to load local embedding provider:",n)}return null}var Pf,Cf,Ff=(t)=>typeof t==="string"?{...Cf,name:t}:{...Cf,...t};var Ro=N(()=>{Pf=Symbol("Let zodToJsonSchema decide on which parser to use"),Cf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"}});var Mf=(t)=>{let n=Ff(t),o=n.name!==void 0?[...n.basePath,n.definitionPath,n.name]:n.basePath;return{...n,flags:{hasReferencedOpenAiAnyType:!1},currentPath:o,propertyPath:void 0,seen:new Map(Object.entries(n.definitions).map(([i,e])=>[e._def,{def:e._def,path:[...n.basePath,n.definitionPath,i],jsonSchema:void 0}]))}};var ji=N(()=>{Ro()});function di(t,n,o,i){if(!i?.errorMessages)return;if(o)t.errorMessage={...t.errorMessage,[n]:o}}function X(t,n,o,i,e){t[n]=o,di(t,n,i,e)}var _o=(t,n)=>{let o=0;for(;o<t.length&&o<n.length;o++)if(t[o]!==n[o])break;return[(t.length-o).toString(),...n.slice(o)].join("/")};function H(t){if(t.target!=="openAi")return{};let n=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?_o(n,t.currentPath):n.join("/")}}var tt=()=>{};import{ZodFirstPartyTypeKind as B_}from"zod/v3";function vf(t,n){let o={type:"array"};if(t.type?._def&&t.type?._def?.typeName!==B_.ZodAny)o.items=g(t.type._def,{...n,currentPath:[...n.currentPath,"items"]});if(t.minLength)X(o,"minItems",t.minLength.value,t.minLength.message,n);if(t.maxLength)X(o,"maxItems",t.maxLength.value,t.maxLength.message,n);if(t.exactLength)X(o,"minItems",t.exactLength.value,t.exactLength.message,n),X(o,"maxItems",t.exactLength.value,t.exactLength.message,n);return o}var ki=N(()=>{B()});function Yf(t,n){let o={type:"integer",format:"int64"};if(!t.checks)return o;for(let i of t.checks)switch(i.kind){case"min":if(n.target==="jsonSchema7")if(i.inclusive)X(o,"minimum",i.value,i.message,n);else X(o,"exclusiveMinimum",i.value,i.message,n);else{if(!i.inclusive)o.exclusiveMinimum=!0;X(o,"minimum",i.value,i.message,n)}break;case"max":if(n.target==="jsonSchema7")if(i.inclusive)X(o,"maximum",i.value,i.message,n);else X(o,"exclusiveMaximum",i.value,i.message,n);else{if(!i.inclusive)o.exclusiveMaximum=!0;X(o,"maximum",i.value,i.message,n)}break;case"multipleOf":X(o,"multipleOf",i.value,i.message,n);break}return o}var mi=()=>{};function Gf(){return{type:"boolean"}}function wo(t,n){return g(t.type._def,n)}var yo=N(()=>{B()});var Hf=(t,n)=>{return g(t.innerType._def,n)};var zi=N(()=>{B()});function bi(t,n,o){let i=o??n.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((e,r)=>bi(t,n,e))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return V_(t,n)}}var V_=(t,n)=>{let o={type:"integer",format:"unix-time"};if(n.target==="openApi3")return o;for(let i of t.checks)switch(i.kind){case"min":X(o,"minimum",i.value,i.message,n);break;case"max":X(o,"maximum",i.value,i.message,n);break}return o};var si=()=>{};function Zf(t,n){return{...g(t.innerType._def,n),default:t.defaultValue()}}var qi=N(()=>{B()});function Qf(t,n){return n.effectStrategy==="input"?g(t.schema._def,n):H(n)}var ci=N(()=>{B();tt()});function Jf(t){return{type:"string",enum:Array.from(t.values)}}function Bf(t,n){let o=[g(t.left._def,{...n,currentPath:[...n.currentPath,"allOf","0"]}),g(t.right._def,{...n,currentPath:[...n.currentPath,"allOf","1"]})].filter((r)=>!!r),i=n.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,e=[];return o.forEach((r)=>{if(W_(r)){if(e.push(...r.allOf),r.unevaluatedProperties===void 0)i=void 0}else{let E=r;if("additionalProperties"in r&&r.additionalProperties===!1){let{additionalProperties:f,...T}=r;E=T}else i=void 0;e.push(E)}}),e.length?{allOf:e,...i}:void 0}var W_=(t)=>{if("type"in t&&t.type==="string")return!1;return"allOf"in t};var xi=N(()=>{B()});function Vf(t,n){let o=typeof t.value;if(o!=="bigint"&&o!=="number"&&o!=="boolean"&&o!=="string")return{type:Array.isArray(t.value)?"array":"object"};if(n.target==="openApi3")return{type:o==="bigint"?"integer":o,enum:[t.value]};return{type:o==="bigint"?"integer":o,const:t.value}}function go(t,n){let o={type:"string"};if(t.checks)for(let i of t.checks)switch(i.kind){case"min":X(o,"minLength",typeof o.minLength==="number"?Math.max(o.minLength,i.value):i.value,i.message,n);break;case"max":X(o,"maxLength",typeof o.maxLength==="number"?Math.min(o.maxLength,i.value):i.value,i.message,n);break;case"email":switch(n.emailStrategy){case"format:email":Tt(o,"email",i.message,n);break;case"format:idn-email":Tt(o,"idn-email",i.message,n);break;case"pattern:zod":k(o,ft.email,i.message,n);break}break;case"url":Tt(o,"uri",i.message,n);break;case"uuid":Tt(o,"uuid",i.message,n);break;case"regex":k(o,i.regex,i.message,n);break;case"cuid":k(o,ft.cuid,i.message,n);break;case"cuid2":k(o,ft.cuid2,i.message,n);break;case"startsWith":k(o,RegExp(`^${te(i.value,n)}`),i.message,n);break;case"endsWith":k(o,RegExp(`${te(i.value,n)}$`),i.message,n);break;case"datetime":Tt(o,"date-time",i.message,n);break;case"date":Tt(o,"date",i.message,n);break;case"time":Tt(o,"time",i.message,n);break;case"duration":Tt(o,"duration",i.message,n);break;case"length":X(o,"minLength",typeof o.minLength==="number"?Math.max(o.minLength,i.value):i.value,i.message,n),X(o,"maxLength",typeof o.maxLength==="number"?Math.min(o.maxLength,i.value):i.value,i.message,n);break;case"includes":{k(o,RegExp(te(i.value,n)),i.message,n);break}case"ip":{if(i.version!=="v6")Tt(o,"ipv4",i.message,n);if(i.version!=="v4")Tt(o,"ipv6",i.message,n);break}case"base64url":k(o,ft.base64url,i.message,n);break;case"jwt":k(o,ft.jwt,i.message,n);break;case"cidr":{if(i.version!=="v6")k(o,ft.ipv4Cidr,i.message,n);if(i.version!=="v4")k(o,ft.ipv6Cidr,i.message,n);break}case"emoji":k(o,ft.emoji(),i.message,n);break;case"ulid":{k(o,ft.ulid,i.message,n);break}case"base64":{switch(n.base64Strategy){case"format:binary":{Tt(o,"binary",i.message,n);break}case"contentEncoding:base64":{X(o,"contentEncoding","base64",i.message,n);break}case"pattern:zod":{k(o,ft.base64,i.message,n);break}}break}case"nanoid":k(o,ft.nanoid,i.message,n);case"toLowerCase":case"toUpperCase":case"trim":break;default:((e)=>{})(i)}return o}function te(t,n){return n.patternStrategy==="escape"?p_(t):t}function p_(t){let n="";for(let o=0;o<t.length;o++){if(!K_.has(t[o]))n+="\\";n+=t[o]}return n}function Tt(t,n,o,i){if(t.format||t.anyOf?.some((e)=>e.format)){if(!t.anyOf)t.anyOf=[];if(t.format){if(t.anyOf.push({format:t.format,...t.errorMessage&&i.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage){if(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0)delete t.errorMessage}}t.anyOf.push({format:n,...o&&i.errorMessages&&{errorMessage:{format:o}}})}else X(t,"format",n,o,i)}function k(t,n,o,i){if(t.pattern||t.allOf?.some((e)=>e.pattern)){if(!t.allOf)t.allOf=[];if(t.pattern){if(t.allOf.push({pattern:t.pattern,...t.errorMessage&&i.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage){if(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0)delete t.errorMessage}}t.allOf.push({pattern:Wf(n,i),...o&&i.errorMessages&&{errorMessage:{pattern:o}}})}else X(t,"pattern",Wf(n,i),o,i)}function Wf(t,n){if(!n.applyRegexFlags||!t.flags)return t.source;let o={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},i=o.i?t.source.toLowerCase():t.source,e="",r=!1,E=!1,f=!1;for(let T=0;T<i.length;T++){if(r){e+=i[T],r=!1;continue}if(o.i){if(E){if(i[T].match(/[a-z]/)){if(f)e+=i[T],e+=`${i[T-2]}-${i[T]}`.toUpperCase(),f=!1;else if(i[T+1]==="-"&&i[T+2]?.match(/[a-z]/))e+=i[T],f=!0;else e+=`${i[T]}${i[T].toUpperCase()}`;continue}}else if(i[T].match(/[a-z]/)){e+=`[${i[T]}${i[T].toUpperCase()}]`;continue}}if(o.m){if(i[T]==="^"){e+=`(^|(?<=[\r
173
173
  ]))`;continue}else if(i[T]==="$"){e+=`($|(?=[\r
174
174
  ]))`;continue}}if(o.s&&i[T]==="."){e+=E?`${i[T]}\r
175
175
  `:`[${i[T]}\r
@@ -1,7 +1,7 @@
1
1
  {
2
- "version": "0.7.4",
2
+ "version": "0.7.5",
3
3
  "binaries": {
4
- "linux-x64": "sha256:8758c965c34332a88278cd8c8c99ce36d6147c61bf3be56e6cd01e58a79ea99c",
5
- "linux-arm64": "sha256:27ee8d5cfbf5b4e541be6915263f0a8056a78afb782b9d9feb110c6917141068"
4
+ "linux-x64": "sha256:4fb97f830176c478ad26f3733553adde598aae23bc9a3487a4324bf89e401d9d",
5
+ "linux-arm64": "sha256:a35c78ef72520bd85fc070e6205dcc7e78aefc3e7570014178a178ad4d2385c4"
6
6
  }
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@desplega.ai/agent-fs",
3
- "version": "0.7.4",
3
+ "version": "0.7.5",
4
4
  "type": "module",
5
5
  "description": "Agent-first filesystem backed by S3",
6
6
  "license": "MIT",
@@ -36,8 +36,8 @@
36
36
  "sqlite-vec-linux-arm64": "^0.1.9",
37
37
  "sqlite-vec-linux-x64": "^0.1.9",
38
38
  "sqlite-vec-windows-x64": "^0.1.9",
39
- "@desplega.ai/agent-fs-fuse-linux-x64": "^0.7.4",
40
- "@desplega.ai/agent-fs-fuse-linux-arm64": "^0.7.4"
39
+ "@desplega.ai/agent-fs-fuse-linux-x64": "^0.7.5",
40
+ "@desplega.ai/agent-fs-fuse-linux-arm64": "^0.7.5"
41
41
  },
42
42
  "dependencies": {
43
43
  "commander": "^14.0.3",