@desplega.ai/agent-fs 0.7.0 → 0.7.2
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/README.md +3 -1
- package/dist/cli.js +66 -61
- package/dist/fuse-bin.manifest.json +3 -3
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
Install with: brew install sqlite`)}var
|
|
3
|
+
var Sl=Object.create;var{getPrototypeOf:$l,defineProperty:Fo,getOwnPropertyNames:Xl}=Object;var Cl=Object.prototype.hasOwnProperty;function Pl(t){return this[t]}var Ml,Fl,ot=(t,n,o)=>{var i=t!=null&&typeof t==="object";if(i){var e=n?Ml??=new WeakMap:Fl??=new WeakMap,r=e.get(t);if(r)return r}o=t!=null?Sl($l(t)):{};let E=n||!t||!t.__esModule?Fo(o,"default",{value:t,enumerable:!0}):o;for(let f of Xl(t))if(!Cl.call(E,f))Fo(E,f,{get:Pl.bind(t,f),enumerable:!0});if(i)e.set(t,E);return E};var s=(t,n)=>()=>(n||t((n={exports:{}}).exports,n),n.exports);var vl=(t)=>t;function Yl(t,n){this[t]=vl.bind(null,n)}var bt=(t,n)=>{for(var o in n)Fo(t,o,{get:n[o],enumerable:!0,configurable:!0,set:Yl.bind(n,o)})};var R=(t,n)=>()=>(t&&(n=t(t=0)),n);var Vn=import.meta.require;import{Database as Gl}from"bun:sqlite";import{platform as Hl}from"os";import{existsSync as Zl}from"fs";function Ql(){if(Ge)return;if(Ge=!0,Hl()!=="darwin")return;let t=["/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite3/lib/libsqlite3.dylib"];for(let n of t)if(Zl(n)){try{Gl.setCustomSQLite(n)}catch{}return}console.warn(`Warning: Could not find Homebrew SQLite. Extension loading may fail on macOS.
|
|
4
|
+
Install with: brew install sqlite`)}var Ge=!1;var He=R(()=>{Ql()});import{mkdirSync as Jl,readFileSync as Bl,writeFileSync as Yo,existsSync as Qe}from"fs";import{join as Wn}from"path";function Vl(){let t=process.env.AGENT_FS_HOME??Wn(process.env.HOME??"/tmp",".agent-fs");if(t.startsWith("~/"))return Wn(process.env.HOME??"/tmp",t.slice(2));return t}function V(){return Vl()}function x(){return Wn(V(),"config.json")}function Ht(){return Wn(V(),"agent-fs.db")}function Wl(){let t=V();if(!Qe(t))Jl(t,{recursive:!0})}function Kl(t,n){let o={...t};for(let i of Object.keys(n))if(n[i]&&typeof n[i]==="object"&&!Array.isArray(n[i]))o[i]={...t[i],...n[i]};else if(n[i]!==void 0)o[i]=n[i];return o}function Ze(t){let n=process.env;if(n.AWS_ENDPOINT_URL_S3||n.S3_ENDPOINT)t.s3.endpoint=n.AWS_ENDPOINT_URL_S3||n.S3_ENDPOINT;if(n.AWS_ACCESS_KEY_ID||n.S3_ACCESS_KEY_ID)t.s3.accessKeyId=n.AWS_ACCESS_KEY_ID||n.S3_ACCESS_KEY_ID;if(n.AWS_SECRET_ACCESS_KEY||n.S3_SECRET_ACCESS_KEY)t.s3.secretAccessKey=n.AWS_SECRET_ACCESS_KEY||n.S3_SECRET_ACCESS_KEY;if(n.BUCKET_NAME||n.S3_BUCKET)t.s3.bucket=n.BUCKET_NAME||n.S3_BUCKET;if(n.AWS_REGION||n.S3_REGION)t.s3.region=n.AWS_REGION||n.S3_REGION;if(n.S3_PROVIDER)t.s3.provider=n.S3_PROVIDER;if(n.S3_PUBLIC_ENDPOINT)t.s3.publicEndpoint=n.S3_PUBLIC_ENDPOINT;if(n.SERVER_PORT||n.PORT)t.server.port=parseInt(n.SERVER_PORT||n.PORT,10);if(n.SERVER_HOST||n.HOST)t.server.host=n.SERVER_HOST||n.HOST;if(n.EMBEDDING_PROVIDER)t.embedding.provider=n.EMBEDDING_PROVIDER;if(n.EMBEDDING_MODEL)t.embedding.model=n.EMBEDDING_MODEL;if(n.EMBEDDING_API_KEY)t.embedding.apiKey=n.EMBEDDING_API_KEY;if(n.AGENT_FS_RATE_LIMIT){if(!t.server.rateLimit)t.server.rateLimit={requestsPerMinute:1200};t.server.rateLimit.requestsPerMinute=parseInt(n.AGENT_FS_RATE_LIMIT,10)}if(n.AGENT_FS_APP_URL)t.appUrl=n.AGENT_FS_APP_URL;return t}function P(){Wl();let t=x();if(!Qe(t))return Yo(t,JSON.stringify(vo,null,2)),Ze(structuredClone(vo));let n=Bl(t,"utf-8"),o=JSON.parse(n);return Ze(Kl(vo,o))}function Je(t,n){let o=P();o[t]=n,Yo(x(),JSON.stringify(o,null,2))}function U(t,n){let o=P(),i=t.split("."),e=o;for(let r=0;r<i.length-1;r++)e=e[i[r]];e[i[i.length-1]]=n,Yo(x(),JSON.stringify(o,null,2))}var vo;var wn=R(()=>{vo={s3:{provider:"minio",bucket:"agentfs",region:"us-east-1",endpoint:"http://localhost:9000",accessKeyId:"",secretAccessKey:""},embedding:{provider:"local",model:"",apiKey:""},server:{port:7433,host:"127.0.0.1",cors:{origins:["*"]},rateLimit:{requestsPerMinute:1200}},auth:{apiKey:""},minio:{containerId:"",managed:!0}}});var u={};bt(u,{users:()=>yn,orgs:()=>Ln,orgMembers:()=>hl,files:()=>kl,fileVersions:()=>dl,events:()=>zl,drives:()=>Kn,driveMembers:()=>jl,contentChunks:()=>bl,comments:()=>ml});import{sqliteTable as lt,text as y,integer as v,primaryKey as Go,uniqueIndex as pl}from"drizzle-orm/sqlite-core";var yn,Ln,hl,Kn,jl,kl,dl,ml,zl,bl;var Be=R(()=>{yn=lt("users",{id:y("id").primaryKey(),email:y("email").notNull().unique(),apiKeyHash:y("api_key_hash").notNull(),createdAt:v("created_at",{mode:"timestamp"}).notNull()}),Ln=lt("orgs",{id:y("id").primaryKey(),name:y("name").notNull(),isPersonal:v("is_personal",{mode:"boolean"}).notNull().default(!1),createdAt:v("created_at",{mode:"timestamp"}).notNull()}),hl=lt("org_members",{orgId:y("org_id").notNull().references(()=>Ln.id),userId:y("user_id").notNull().references(()=>yn.id),role:y("role",{enum:["viewer","editor","admin"]}).notNull()},(t)=>({pk:Go({columns:[t.orgId,t.userId]})})),Kn=lt("drives",{id:y("id").primaryKey(),orgId:y("org_id").notNull().references(()=>Ln.id),name:y("name").notNull(),isDefault:v("is_default",{mode:"boolean"}).notNull().default(!1),createdAt:v("created_at",{mode:"timestamp"}).notNull()}),jl=lt("drive_members",{driveId:y("drive_id").notNull().references(()=>Kn.id),userId:y("user_id").notNull().references(()=>yn.id),role:y("role",{enum:["viewer","editor","admin"]}).notNull()},(t)=>({pk:Go({columns:[t.driveId,t.userId]})})),kl=lt("files",{path:y("path").notNull(),driveId:y("drive_id").notNull().references(()=>Kn.id),size:v("size").notNull(),contentType:y("content_type"),author:y("author").notNull(),currentVersionId:y("current_version_id"),createdAt:v("created_at",{mode:"timestamp"}).notNull(),modifiedAt:v("modified_at",{mode:"timestamp"}).notNull(),isDeleted:v("is_deleted",{mode:"boolean"}).notNull().default(!1),embeddingStatus:y("embedding_status",{enum:["pending","indexed","failed"]}).default("pending")},(t)=>({pk:Go({columns:[t.path,t.driveId]})})),dl=lt("file_versions",{id:v("id").primaryKey({autoIncrement:!0}),path:y("path").notNull(),driveId:y("drive_id").notNull(),version:v("version").notNull(),s3VersionId:y("s3_version_id").notNull(),author:y("author").notNull(),operation:y("operation",{enum:["write","edit","append","delete","revert"]}).notNull(),message:y("message"),diffSummary:y("diff_summary"),size:v("size"),etag:y("etag"),contentHash:y("content_hash"),createdAt:v("created_at",{mode:"timestamp"}).notNull()},(t)=>({pathDriveVersionUq:pl("file_versions_path_drive_version_uq").on(t.path,t.driveId,t.version)})),ml=lt("comments",{id:y("id").primaryKey(),parentId:y("parent_id"),orgId:y("org_id").notNull().references(()=>Ln.id),driveId:y("drive_id").notNull().references(()=>Kn.id),path:y("path").notNull(),lineStart:v("line_start"),lineEnd:v("line_end"),quotedContent:y("quoted_content"),fileVersionId:v("file_version_id"),body:y("body").notNull(),author:y("author").notNull().references(()=>yn.id),resolved:v("resolved",{mode:"boolean"}).notNull().default(!1),resolvedBy:y("resolved_by"),resolvedAt:v("resolved_at",{mode:"timestamp"}),createdAt:v("created_at",{mode:"timestamp"}).notNull(),updatedAt:v("updated_at",{mode:"timestamp"}).notNull(),isDeleted:v("is_deleted",{mode:"boolean"}).notNull().default(!1)}),zl=lt("events",{id:y("id").primaryKey(),orgId:y("org_id").notNull().references(()=>Ln.id),type:y("type").notNull(),resourceType:y("resource_type").notNull(),resourceId:y("resource_id").notNull(),actor:y("actor").notNull().references(()=>yn.id),target:y("target"),status:y("status",{enum:["created","ack","deleted"]}).notNull().default("created"),metadata:y("metadata"),createdAt:v("created_at",{mode:"timestamp"}).notNull()}),bl=lt("content_chunks",{id:v("id").primaryKey({autoIncrement:!0}),filePath:y("file_path").notNull(),driveId:y("drive_id").notNull(),chunkIndex:v("chunk_index").notNull(),content:y("content").notNull(),charOffset:v("char_offset").notNull(),tokenCount:v("token_count").notNull()})});var Ve=`
|
|
5
5
|
CREATE TABLE IF NOT EXISTS users (
|
|
6
6
|
id TEXT PRIMARY KEY,
|
|
7
7
|
email TEXT NOT NULL UNIQUE,
|
|
@@ -120,7 +120,7 @@ CREATE TABLE IF NOT EXISTS content_chunks (
|
|
|
120
120
|
char_offset INTEGER NOT NULL,
|
|
121
121
|
token_count INTEGER NOT NULL
|
|
122
122
|
);
|
|
123
|
-
`,
|
|
123
|
+
`,We=`
|
|
124
124
|
-- FTS5 full-text index (internal content storage)
|
|
125
125
|
CREATE VIRTUAL TABLE IF NOT EXISTS files_fts USING fts5(
|
|
126
126
|
path, content, drive_id UNINDEXED
|
|
@@ -131,18 +131,18 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunk_vectors USING vec0(
|
|
|
131
131
|
chunk_id INTEGER PRIMARY KEY,
|
|
132
132
|
embedding float[768]
|
|
133
133
|
);
|
|
134
|
-
`;function Ge(t){if(!t.prepare("PRAGMA table_info(file_versions)").all().some((i)=>i.name==="content_hash"))t.exec("ALTER TABLE file_versions ADD COLUMN content_hash TEXT");t.exec("CREATE UNIQUE INDEX IF NOT EXISTS file_versions_path_drive_version_uq ON file_versions(path, drive_id, version)")}import{Database as pN}from"bun:sqlite";import{drizzle as jN}from"drizzle-orm/bun-sqlite";import*as He from"sqlite-vec";import{existsSync as hN,mkdirSync as kN}from"fs";import{dirname as mN}from"path";function zN(t){He.load(t)}function Ut(t){let n=t??Yt(),o=mN(n);if(!hN(o))kN(o,{recursive:!0});let i=new pN(n);return zN(i),i.exec("PRAGMA journal_mode=WAL;"),i.exec("PRAGMA foreign_keys=ON;"),i.exec(ve),i.exec(Ye),Ge(i),jN(i,{schema:u})}var Z=R(()=>{Xe();Nn();Fe()});var Mo=q((qN)=>{var Ze=(t)=>encodeURIComponent(t).replace(/[!'()*]/g,dN),dN=(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`,bN=(t)=>t.split("/").map(Ze).join("/");qN.escapeUri=Ze;qN.escapeUriPath=bN});var Qe=q((aN)=>{var Fo=Mo();function cN(t){let n=[];for(let o of Object.keys(t).sort()){let i=t[o];if(o=Fo.escapeUri(o),Array.isArray(i))for(let e=0,r=i.length;e<r;e++)n.push(`${o}=${Fo.escapeUri(i[e])}`);else{let e=o;if(i||typeof i==="string")e+=`=${Fo.escapeUri(i)}`;n.push(e)}}return n.join("&")}aN.buildQueryString=cN});function Je(t){let{port:n,query:o}=t,{protocol:i,path:e,hostname:r}=t;if(i&&i.slice(-1)!==":")i+=":";if(n)r+=`:${n}`;if(e&&e.charAt(0)!=="/")e=`/${e}`;let E=o?Be.buildQueryString(o):"";if(E&&E[0]!=="?")E=`?${E}`;let f="";if(t.username!=null||t.password!=null){let N=t.username??"",A=t.password??"";f=`${N}:${A}@`}let T="";if(t.fragment)T=`#${t.fragment}`;return`${i}//${f}${r}${e}${E}${T}`}var Be;var Ve=R(()=>{Be=nt(Qe(),1)});var We=async(t)=>{let n=t?.Bucket||"";if(typeof t.Bucket==="string")t.Bucket=n.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(rA(n)){if(t.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!eA(n)||n.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||n.toLowerCase()!==n||n.length<3)t.ForcePathStyle=!0;if(t.DisableMultiRegionAccessPoints)t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0;return t},nA,oA,iA,eA=(t)=>nA.test(t)&&!oA.test(t)&&!iA.test(t),rA=(t)=>{let[n,o,i,,,e]=t.split(":"),r=n==="arn"&&t.split(":").length>=6,E=Boolean(r&&o&&i&&e);if(r&&!E)throw Error(`Invalid ARN: ${t} was an invalid ARN.`);return E};var Ke=R(()=>{nA=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,oA=/(\d+\.){3}\d+/,iA=/\.\./});var pe=R(()=>{Ke()});var je=(t,n,o,i=!1)=>{let e=async()=>{let r;if(i)r=o.clientContextParams?.[t]??o[t]??o[n];else r=o[t]??o[n];if(typeof r==="function")return r();return r};if(t==="credentialScope"||n==="CredentialScope")return async()=>{let r=typeof o.credentials==="function"?await o.credentials():o.credentials;return r?.credentialScope??r?.CredentialScope};if(t==="accountId"||n==="AccountId")return async()=>{let r=typeof o.credentials==="function"?await o.credentials():o.credentials;return r?.accountId??r?.AccountId};if(t==="endpoint"||n==="endpoint")return async()=>{if(o.isCustomEndpoint===!1)return;let r=await e();if(r&&typeof r==="object"){if("url"in r)return r.url.href;if("hostname"in r){let{protocol:E,hostname:f,port:T,path:N}=r;return`${E}//${f}${T?":"+T:""}${N}`}}return r};return e};var yn=q((TA)=>{class bt extends Error{name="ProviderError";tryNextLink;constructor(t,n=!0){let o,i=!0;if(typeof n==="boolean")o=void 0,i=n;else if(n!=null&&typeof n==="object")o=n.logger,i=n.tryNextLink??!0;super(t);this.tryNextLink=i,Object.setPrototypeOf(this,bt.prototype),o?.debug?.(`@smithy/property-provider ${i?"->":"(!)"} ${t}`)}static from(t,n=!0){return Object.assign(new this(t.message,n),t)}}class vo extends bt{name="CredentialsProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,vo.prototype)}}class Yo extends bt{name="TokenProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,Yo.prototype)}}var EA=(...t)=>async()=>{if(t.length===0)throw new bt("No providers in chain");let n;for(let o of t)try{return await o()}catch(i){if(n=i,i?.tryNextLink)continue;throw i}throw n},uA=(t)=>()=>Promise.resolve(t),fA=(t,n,o)=>{let i,e,r,E=!1,f=async()=>{if(!e)e=t();try{i=await e,r=!0,E=!1}finally{e=void 0}return i};if(n===void 0)return async(T)=>{if(!r||T?.forceRefresh)i=await f();return i};return async(T)=>{if(!r||T?.forceRefresh)i=await f();if(E)return i;if(o&&!o(i))return E=!0,i;if(n(i))return await f(),i;return i}};TA.CredentialsProviderError=vo;TA.ProviderError=bt;TA.TokenProviderError=Yo;TA.chain=EA;TA.fromStatic=uA;TA.memoize=fA});function Zn(t){try{let n=new Set(Array.from(t.match(/([A-Z_]){3,}/g)??[]));return n.delete("CONFIG"),n.delete("CONFIG_PREFIX_SEPARATOR"),n.delete("ENV"),[...n].join(", ")}catch(n){return t}}var he,ke=(t,n)=>async()=>{try{let o=t(process.env,n);if(o===void 0)throw Error();return o}catch(o){throw new he.CredentialsProviderError(o.message||`Not found in ENV: ${Zn(t.toString())}`,{logger:n?.logger})}};var me=R(()=>{he=nt(yn(),1)});import{homedir as wA}from"os";import{sep as LA}from"path";var Go,gA=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},qt=()=>{let{HOME:t,USERPROFILE:n,HOMEPATH:o,HOMEDRIVE:i=`C:${LA}`}=process.env;if(t)return t;if(n)return n;if(o)return`${i}${o}`;let e=gA();if(!Go[e])Go[e]=wA();return Go[e]};var _n=R(()=>{Go={}});var ze=(t)=>t.profile||process.env.AWS_PROFILE||"default";var de=()=>{};var wn=q(($A)=>{$A.HttpAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})($A.HttpAuthLocation||($A.HttpAuthLocation={}));$A.HttpApiKeyAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})($A.HttpApiKeyAuthLocation||($A.HttpApiKeyAuthLocation={}));$A.EndpointURLScheme=void 0;(function(t){t.HTTP="http",t.HTTPS="https"})($A.EndpointURLScheme||($A.EndpointURLScheme={}));$A.AlgorithmId=void 0;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})($A.AlgorithmId||($A.AlgorithmId={}));var DA=(t)=>{let n=[];if(t.sha256!==void 0)n.push({algorithmId:()=>$A.AlgorithmId.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)n.push({algorithmId:()=>$A.AlgorithmId.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(o){n.push(o)},checksumAlgorithms(){return n}}},IA=(t)=>{let n={};return t.checksumAlgorithms().forEach((o)=>{n[o.algorithmId()]=o.checksumConstructor()}),n},OA=(t)=>{return DA(t)},UA=(t)=>{return IA(t)};$A.FieldPosition=void 0;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})($A.FieldPosition||($A.FieldPosition={}));var SA="__smithy_context";$A.IniSectionType=void 0;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})($A.IniSectionType||($A.IniSectionType={}));$A.RequestHandlerProtocol=void 0;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})($A.RequestHandlerProtocol||($A.RequestHandlerProtocol={}));$A.SMITHY_CONTEXT_KEY=SA;$A.getDefaultClientConfiguration=OA;$A.resolveDefaultRuntimeConfig=UA});var Nt=".";var Wo,be=(t)=>Object.entries(t).filter(([n])=>{let o=n.indexOf(Nt);if(o===-1)return!1;return Object.values(Wo.IniSectionType).includes(n.substring(0,o))}).reduce((n,[o,i])=>{let e=o.indexOf(Nt),r=o.substring(0,e)===Wo.IniSectionType.PROFILE?o.substring(e+1):o;return n[r]=i,n},{...t.default&&{default:t.default}});var qe=R(()=>{Wo=nt(wn(),1)});import{join as MA}from"path";var FA="AWS_CONFIG_FILE",se=()=>process.env[FA]||MA(qt(),".aws","config");var xe=R(()=>{_n()});import{join as vA}from"path";var YA="AWS_SHARED_CREDENTIALS_FILE",ce=()=>process.env[YA]||vA(qt(),".aws","credentials");var ae=R(()=>{_n()});var tr,GA,HA,Ko=(t)=>{let n={},o,i;for(let e of t.split(/\r?\n/)){let r=e.split(/(^|\s)[;#]/)[0].trim();if(r[0]==="["&&r[r.length-1]==="]"){o=void 0,i=void 0;let f=r.substring(1,r.length-1),T=GA.exec(f);if(T){let[,N,,A]=T;if(Object.values(tr.IniSectionType).includes(N))o=[N,A].join(Nt)}else o=f;if(HA.includes(f))throw Error(`Found invalid profile name "${f}"`)}else if(o){let f=r.indexOf("=");if(![0,-1].includes(f)){let[T,N]=[r.substring(0,f).trim(),r.substring(f+1).trim()];if(N==="")i=T;else{if(i&&e.trimStart()===e)i=void 0;n[o]=n[o]||{};let A=i?[i,T].join(Nt):T;n[o][A]=N}}}}return n};var nr=R(()=>{tr=nt(wn(),1),GA=/^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/,HA=["__proto__","profile __proto__"]});import{readFile as ZA}from"fs/promises";var po,or,jo=(t,n)=>{if(or[t]!==void 0)return or[t];if(!po[t]||n?.ignoreCache)po[t]=ZA(t,"utf8");return po[t]};var ir=R(()=>{po={},or={}});import{join as er}from"path";var rr=()=>({}),Er=async(t={})=>{let{filepath:n=ce(),configFilepath:o=se()}=t,i=qt(),e="~/",r=n;if(n.startsWith("~/"))r=er(i,n.slice(2));let E=o;if(o.startsWith("~/"))E=er(i,o.slice(2));let f=await Promise.all([jo(E,{ignoreCache:t.ignoreCache}).then(Ko).then(be).catch(rr),jo(r,{ignoreCache:t.ignoreCache}).then(Ko).catch(rr)]);return{configFile:f[0],credentialsFile:f[1]}};var ur=R(()=>{qe();xe();ae();_n();nr();ir()});var fr=()=>{};var Tr=()=>{};var Nr=()=>{};var ho=R(()=>{_n();de();ur();fr();Tr();Nr()});var Ar,Rr=(t,{preferredFile:n="config",...o}={})=>async()=>{let i=ze(o),{configFile:e,credentialsFile:r}=await Er(o),E=r[i]||{},f=e[i]||{},T=n==="config"?{...E,...f}:{...f,...E};try{let A=t(T,n==="config"?e:r);if(A===void 0)throw Error();return A}catch(N){throw new Ar.CredentialsProviderError(N.message||`Not found in config files w/ profile [${i}]: ${Zn(t.toString())}`,{logger:o.logger})}};var yr=R(()=>{ho();Ar=nt(yn(),1)});var _r,QA=(t)=>typeof t==="function",lr=(t)=>QA(t)?async()=>await t():_r.fromStatic(t);var wr=R(()=>{_r=nt(yn(),1)});var Qn,Lr=({environmentVariableSelector:t,configFileSelector:n,default:o},i={})=>{let{signingName:e,logger:r}=i;return Qn.memoize(Qn.chain(ke(t,{signingName:e,logger:r}),Rr(n,i),lr(o)))};var gr=R(()=>{me();yr();wr();Qn=nt(yn(),1)});var Dr=R(()=>{gr()});var Ir="AWS_ENDPOINT_URL",Or="endpoint_url",Ur=(t)=>({environmentVariableSelector:(n)=>{let o=t.split(" ").map((r)=>r.toUpperCase()),i=n[[Ir,...o].join("_")];if(i)return i;let e=n[Ir];if(e)return e;return},configFileSelector:(n,o)=>{if(o&&n.services){let e=o[["services",n.services].join(Nt)];if(e){let r=t.split(" ").map((f)=>f.toLowerCase()),E=e[[r.join("_"),Or].join(Nt)];if(E)return E}}let i=n[Or];if(i)return i;return},default:void 0});var Sr=R(()=>{ho()});var $r=async(t)=>Lr(Ur(t??""))();var Xr=R(()=>{Dr();Sr()});var Cr=q((JA)=>{function BA(t){let n={};if(t=t.replace(/^\?/,""),t)for(let o of t.split("&")){let[i,e=null]=o.split("=");if(i=decodeURIComponent(i),e)e=decodeURIComponent(e);if(!(i in n))n[i]=e;else if(Array.isArray(n[i]))n[i].push(e);else n[i]=[n[i],e]}return n}JA.parseQueryString=BA});var Mr=q((KA)=>{var WA=Cr(),Pr=(t)=>{if(typeof t==="string")return Pr(new URL(t));let{hostname:n,pathname:o,port:i,protocol:e,search:r}=t,E;if(r)E=WA.parseQueryString(r);return{hostname:n,port:i?parseInt(i):void 0,protocol:e,path:o,query:E}};KA.parseUrl=Pr});var ko,Fr=(t)=>{if(typeof t==="object"){if("url"in t){let n=ko.parseUrl(t.url);if(t.headers){n.headers={};for(let[o,i]of Object.entries(t.headers))n.headers[o.toLowerCase()]=i.join(", ")}return n}return t}return ko.parseUrl(t)};var mo=R(()=>{ko=nt(Mr(),1)});var vr=async(t,n,o,i)=>{if(!o.isCustomEndpoint){let E;if(o.serviceConfiguredEndpoint)E=await o.serviceConfiguredEndpoint();else E=await $r(o.serviceId);if(E)o.endpoint=()=>Promise.resolve(Fr(E)),o.isCustomEndpoint=!0}let e=await jA(t,n,o);if(typeof o.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let r=o.endpointProvider(e,i);if(o.isCustomEndpoint&&o.endpoint){let E=await o.endpoint();if(E?.headers){r.headers??={};for(let[f,T]of Object.entries(E.headers))r.headers[f]=Array.isArray(T)?T:[T]}}return r},jA=async(t,n,o)=>{let i={},e=n?.getEndpointParameterInstructions?.()||{};for(let[r,E]of Object.entries(e))switch(E.type){case"staticContextParams":i[r]=E.value;break;case"contextParams":i[r]=t[E.name];break;case"clientContextParams":case"builtInParams":i[r]=await je(E.name,r,o,E.type!=="builtInParams")();break;case"operationContextParams":i[r]=E.get(t);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(E))}if(Object.keys(e).length===0)Object.assign(i,o);if(String(o.serviceId).toLowerCase()==="s3")await We(i);return i};var Yr=R(()=>{pe();Xr();mo()});var Gr=R(()=>{Yr();mo()});var Zr=q((mA)=>{var Hr=wn(),hA=(t)=>t[Hr.SMITHY_CONTEXT_KEY]||(t[Hr.SMITHY_CONTEXT_KEY]={}),kA=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n};mA.getSmithyContext=hA;mA.normalizeProvider=kA});var Qr=()=>{};var zo=q((aA)=>{var bA=wn(),qA=(t)=>{return{setHttpHandler(n){t.httpHandler=n},httpHandler(){return t.httpHandler},updateHttpClientConfig(n,o){t.httpHandler?.updateHttpClientConfig(n,o)},httpHandlerConfigs(){return t.httpHandler.httpHandlerConfigs()}}},sA=(t)=>{return{httpHandler:t.httpHandler()}};class Br{name;kind;values;constructor({name:t,kind:n=bA.FieldPosition.HEADER,values:o=[]}){this.name=t,this.kind=n,this.values=o}add(t){this.values.push(t)}set(t){this.values=t}remove(t){this.values=this.values.filter((n)=>n!==t)}toString(){return this.values.map((t)=>t.includes(",")||t.includes(" ")?`"${t}"`:t).join(", ")}get(){return this.values}}class Jr{entries={};encoding;constructor({fields:t=[],encoding:n="utf-8"}){t.forEach(this.setField.bind(this)),this.encoding=n}setField(t){this.entries[t.name.toLowerCase()]=t}getField(t){return this.entries[t.toLowerCase()]}removeField(t){delete this.entries[t.toLowerCase()]}getByType(t){return Object.values(this.entries).filter((n)=>n.kind===t)}}class Bn{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(t){this.method=t.method||"GET",this.hostname=t.hostname||"localhost",this.port=t.port,this.query=t.query||{},this.headers=t.headers||{},this.body=t.body,this.protocol=t.protocol?t.protocol.slice(-1)!==":"?`${t.protocol}:`:t.protocol:"https:",this.path=t.path?t.path.charAt(0)!=="/"?`/${t.path}`:t.path:"/",this.username=t.username,this.password=t.password,this.fragment=t.fragment}static clone(t){let n=new Bn({...t,headers:{...t.headers}});if(n.query)n.query=xA(n.query);return n}static isInstance(t){if(!t)return!1;let n=t;return"method"in n&&"protocol"in n&&"hostname"in n&&"path"in n&&typeof n.query==="object"&&typeof n.headers==="object"}clone(){return Bn.clone(this)}}function xA(t){return Object.keys(t).reduce((n,o)=>{let i=t[o];return{...n,[o]:Array.isArray(i)?[...i]:i}},{})}class Vr{statusCode;reason;headers;body;constructor(t){this.statusCode=t.statusCode,this.reason=t.reason,this.headers=t.headers||{},this.body=t.body}static isInstance(t){if(!t)return!1;let n=t;return typeof n.statusCode==="number"&&typeof n.headers==="object"}}function cA(t){return/^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(t)}aA.Field=Br;aA.Fields=Jr;aA.HttpRequest=Bn;aA.HttpResponse=Vr;aA.getHttpHandlerExtensionConfiguration=qA;aA.isValidHostname=cA;aA.resolveHttpHandlerRuntimeConfig=sA});var Wr=()=>{};var Kr=()=>{};var pr;var jr=R(()=>{pr={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var hr=R(()=>{Wr();jr();Kr()});var Fg;var kr=R(()=>{hr();Fg={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:pr.name}});var mr=()=>{};var zr=()=>{};var dr=R(()=>{Gr();Qr();kr();mr();zr()});var br=()=>{};var qr=()=>{};var sr=()=>{};var xr=()=>{};var ar=q((TR)=>{var cr={},bo={};for(let t=0;t<256;t++){let n=t.toString(16).toLowerCase();if(n.length===1)n=`0${n}`;cr[t]=n,bo[n]=t}function uR(t){if(t.length%2!==0)throw Error("Hex encoded strings must have an even number length");let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2){let i=t.slice(o,o+2).toLowerCase();if(i in bo)n[o/2]=bo[i];else throw Error(`Cannot decode unrecognized sequence ${i} as hexadecimal`)}return n}function fR(t){let n="";for(let o=0;o<t.byteLength;o++)n+=cr[t[o]];return n}TR.fromHex=uR;TR.toHex=fR});var qo=q((yR)=>{var RR=(t)=>typeof ArrayBuffer==="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]";yR.isArrayBuffer=RR});var tE=q((gR)=>{var lR=qo(),so=Yn("buffer"),wR=(t,n=0,o=t.byteLength-n)=>{if(!lR.isArrayBuffer(t))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return so.Buffer.from(t,n,o)},LR=(t,n)=>{if(typeof t!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof t} (${t})`);return n?so.Buffer.from(t,n):so.Buffer.from(t)};gR.fromArrayBuffer=wR;gR.fromString=LR});var iE=q((SR)=>{var nE=tE(),oE=(t)=>{let n=nE.fromString(t,"utf8");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},OR=(t)=>{if(typeof t==="string")return oE(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(t)},UR=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return nE.fromArrayBuffer(t.buffer,t.byteOffset,t.byteLength).toString("utf8")};SR.fromUtf8=oE;SR.toUint8Array=OR;SR.toUtf8=UR});var ui=q((JR)=>{var St=ar(),Gt=iE(),PR=qo(),uE=zo(),eE=Zr(),Jn=Mo(),fE="X-Amz-Algorithm",TE="X-Amz-Credential",ao="X-Amz-Date",NE="X-Amz-SignedHeaders",AE="X-Amz-Expires",ti="X-Amz-Signature",ni="X-Amz-Security-Token",MR="X-Amz-Region-Set",oi="authorization",ii=ao.toLowerCase(),RE="date",yE=[oi,ii,RE],_E=ti.toLowerCase(),jn="x-amz-content-sha256",lE=ni.toLowerCase(),FR="host",wE={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},LE=/^proxy-/,gE=/^sec-/,vR=[/^proxy-/i,/^sec-/i],Vn="AWS4-HMAC-SHA256",YR="AWS4-ECDSA-P256-SHA256",DE="AWS4-HMAC-SHA256-PAYLOAD",IE="UNSIGNED-PAYLOAD",OE=50,ei="aws4_request",UE=604800,st={},Wn=[],Kn=(t,n,o)=>`${t}/${n}/${o}/${ei}`,SE=async(t,n,o,i,e)=>{let r=await rE(t,n.secretAccessKey,n.accessKeyId),E=`${o}:${i}:${e}:${St.toHex(r)}:${n.sessionToken}`;if(E in st)return st[E];Wn.push(E);while(Wn.length>OE)delete st[Wn.shift()];let f=`AWS4${n.secretAccessKey}`;for(let T of[o,i,e,ei])f=await rE(t,f,T);return st[E]=f},GR=()=>{Wn.length=0,Object.keys(st).forEach((t)=>{delete st[t]})},rE=(t,n,o)=>{let i=new t(n);return i.update(Gt.toUint8Array(o)),i.digest()},xo=({headers:t},n,o)=>{let i={};for(let e of Object.keys(t).sort()){if(t[e]==null)continue;let r=e.toLowerCase();if(r in wE||n?.has(r)||LE.test(r)||gE.test(r)){if(!o||o&&!o.has(r))continue}i[r]=t[e].trim().replace(/\s+/g," ")}return i},pn=async({headers:t,body:n},o)=>{for(let i of Object.keys(t))if(i.toLowerCase()===jn)return t[i];if(n==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof n==="string"||ArrayBuffer.isView(n)||PR.isArrayBuffer(n)){let i=new o;return i.update(Gt.toUint8Array(n)),St.toHex(await i.digest())}return IE};class $E{format(t){let n=[];for(let e of Object.keys(t)){let r=Gt.fromUtf8(e);n.push(Uint8Array.from([r.byteLength]),r,this.formatHeaderValue(t[e]))}let o=new Uint8Array(n.reduce((e,r)=>e+r.byteLength,0)),i=0;for(let e of n)o.set(e,i),i+=e.byteLength;return o}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?0:1]);case"byte":return Uint8Array.from([2,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,3),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let o=new DataView(new ArrayBuffer(5));return o.setUint8(0,4),o.setInt32(1,t.value,!1),new Uint8Array(o.buffer);case"long":let i=new Uint8Array(9);return i[0]=5,i.set(t.value.bytes,1),i;case"binary":let e=new DataView(new ArrayBuffer(3+t.value.byteLength));e.setUint8(0,6),e.setUint16(1,t.value.byteLength,!1);let r=new Uint8Array(e.buffer);return r.set(t.value,3),r;case"string":let E=Gt.fromUtf8(t.value),f=new DataView(new ArrayBuffer(3+E.byteLength));f.setUint8(0,7),f.setUint16(1,E.byteLength,!1);let T=new Uint8Array(f.buffer);return T.set(E,3),T;case"timestamp":let N=new Uint8Array(9);return N[0]=8,N.set(ri.fromNumber(t.value.valueOf()).bytes,1),N;case"uuid":if(!HR.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let A=new Uint8Array(17);return A[0]=9,A.set(St.fromHex(t.value.replace(/\-/g,"")),1),A}}}var HR=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class ri{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let o=7,i=Math.abs(Math.round(t));o>-1&&i>0;o--,i/=256)n[o]=i;if(t<0)EE(n);return new ri(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)EE(t);return parseInt(St.toHex(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function EE(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}var XE=(t,n)=>{t=t.toLowerCase();for(let o of Object.keys(n))if(t===o.toLowerCase())return!0;return!1},CE=(t,n={})=>{let{headers:o,query:i={}}=uE.HttpRequest.clone(t);for(let e of Object.keys(o)){let r=e.toLowerCase();if(r.slice(0,6)==="x-amz-"&&!n.unhoistableHeaders?.has(r)||n.hoistableHeaders?.has(r))i[e]=o[e],delete o[e]}return{...t,headers:o,query:i}},co=(t)=>{t=uE.HttpRequest.clone(t);for(let n of Object.keys(t.headers))if(yE.indexOf(n.toLowerCase())>-1)delete t.headers[n];return t},PE=({query:t={}})=>{let n=[],o={};for(let i of Object.keys(t)){if(i.toLowerCase()===_E)continue;let e=Jn.escapeUri(i);n.push(e);let r=t[i];if(typeof r==="string")o[e]=`${e}=${Jn.escapeUri(r)}`;else if(Array.isArray(r))o[e]=r.slice(0).reduce((E,f)=>E.concat([`${e}=${Jn.escapeUri(f)}`]),[]).sort().join("&")}return n.sort().map((i)=>o[i]).filter((i)=>i).join("&")},ZR=(t)=>QR(t).toISOString().replace(/\.\d{3}Z$/,"Z"),QR=(t)=>{if(typeof t==="number")return new Date(t*1000);if(typeof t==="string"){if(Number(t))return new Date(Number(t)*1000);return new Date(t)}return t};class Ei{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:o,service:i,sha256:e,uriEscapePath:r=!0}){this.service=i,this.sha256=e,this.uriEscapePath=r,this.applyChecksum=typeof t==="boolean"?t:!0,this.regionProvider=eE.normalizeProvider(o),this.credentialProvider=eE.normalizeProvider(n)}createCanonicalRequest(t,n,o){let i=Object.keys(n).sort();return`${t.method}
|
|
134
|
+
`;function Ke(t){if(!t.prepare("PRAGMA table_info(file_versions)").all().some((i)=>i.name==="content_hash"))t.exec("ALTER TABLE file_versions ADD COLUMN content_hash TEXT");t.exec("CREATE UNIQUE INDEX IF NOT EXISTS file_versions_path_drive_version_uq ON file_versions(path, drive_id, version)")}import{Database as ql}from"bun:sqlite";import{drizzle as sl}from"drizzle-orm/bun-sqlite";import*as pe from"sqlite-vec";import{existsSync as cl,mkdirSync as xl}from"fs";import{dirname as al}from"path";function tN(t){pe.load(t)}function St(t){let n=t??Ht(),o=al(n);if(!cl(o))xl(o,{recursive:!0});let i=new ql(n);return tN(i),i.exec("PRAGMA journal_mode=WAL;"),i.exec("PRAGMA foreign_keys=ON;"),i.exec(Ve),i.exec(We),Ke(i),sl(i,{schema:u})}var G=R(()=>{He();wn();Be()});var Ho=s((iN)=>{var he=(t)=>encodeURIComponent(t).replace(/[!'()*]/g,nN),nN=(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`,oN=(t)=>t.split("/").map(he).join("/");iN.escapeUri=he;iN.escapeUriPath=oN});var je=s((uN)=>{var Zo=Ho();function EN(t){let n=[];for(let o of Object.keys(t).sort()){let i=t[o];if(o=Zo.escapeUri(o),Array.isArray(i))for(let e=0,r=i.length;e<r;e++)n.push(`${o}=${Zo.escapeUri(i[e])}`);else{let e=o;if(i||typeof i==="string")e+=`=${Zo.escapeUri(i)}`;n.push(e)}}return n.join("&")}uN.buildQueryString=EN});function de(t){let{port:n,query:o}=t,{protocol:i,path:e,hostname:r}=t;if(i&&i.slice(-1)!==":")i+=":";if(n)r+=`:${n}`;if(e&&e.charAt(0)!=="/")e=`/${e}`;let E=o?ke.buildQueryString(o):"";if(E&&E[0]!=="?")E=`?${E}`;let f="";if(t.username!=null||t.password!=null){let l=t.username??"",N=t.password??"";f=`${l}:${N}@`}let T="";if(t.fragment)T=`#${t.fragment}`;return`${i}//${f}${r}${e}${E}${T}`}var ke;var me=R(()=>{ke=ot(je(),1)});var ze=async(t)=>{let n=t?.Bucket||"";if(typeof t.Bucket==="string")t.Bucket=n.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(AN(n)){if(t.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!RN(n)||n.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||n.toLowerCase()!==n||n.length<3)t.ForcePathStyle=!0;if(t.DisableMultiRegionAccessPoints)t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0;return t},TN,lN,NN,RN=(t)=>TN.test(t)&&!lN.test(t)&&!NN.test(t),AN=(t)=>{let[n,o,i,,,e]=t.split(":"),r=n==="arn"&&t.split(":").length>=6,E=Boolean(r&&o&&i&&e);if(r&&!E)throw Error(`Invalid ARN: ${t} was an invalid ARN.`);return E};var be=R(()=>{TN=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,lN=/(\d+\.){3}\d+/,NN=/\.\./});var qe=R(()=>{be()});var se=(t,n,o,i=!1)=>{let e=async()=>{let r;if(i)r=o.clientContextParams?.[t]??o[t]??o[n];else r=o[t]??o[n];if(typeof r==="function")return r();return r};if(t==="credentialScope"||n==="CredentialScope")return async()=>{let r=typeof o.credentials==="function"?await o.credentials():o.credentials;return r?.credentialScope??r?.CredentialScope};if(t==="accountId"||n==="AccountId")return async()=>{let r=typeof o.credentials==="function"?await o.credentials():o.credentials;return r?.accountId??r?.AccountId};if(t==="endpoint"||n==="endpoint")return async()=>{if(o.isCustomEndpoint===!1)return;let r=await e();if(r&&typeof r==="object"){if("url"in r)return r.url.href;if("hostname"in r){let{protocol:E,hostname:f,port:T,path:l}=r;return`${E}//${f}${T?":"+T:""}${l}`}}return r};return e};var gn=s((LN)=>{class qt extends Error{name="ProviderError";tryNextLink;constructor(t,n=!0){let o,i=!0;if(typeof n==="boolean")o=void 0,i=n;else if(n!=null&&typeof n==="object")o=n.logger,i=n.tryNextLink??!0;super(t);this.tryNextLink=i,Object.setPrototypeOf(this,qt.prototype),o?.debug?.(`@smithy/property-provider ${i?"->":"(!)"} ${t}`)}static from(t,n=!0){return Object.assign(new this(t.message,n),t)}}class Qo extends qt{name="CredentialsProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,Qo.prototype)}}class Jo extends qt{name="TokenProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,Jo.prototype)}}var _N=(...t)=>async()=>{if(t.length===0)throw new qt("No providers in chain");let n;for(let o of t)try{return await o()}catch(i){if(n=i,i?.tryNextLink)continue;throw i}throw n},wN=(t)=>()=>Promise.resolve(t),yN=(t,n,o)=>{let i,e,r,E=!1,f=async()=>{if(!e)e=t();try{i=await e,r=!0,E=!1}finally{e=void 0}return i};if(n===void 0)return async(T)=>{if(!r||T?.forceRefresh)i=await f();return i};return async(T)=>{if(!r||T?.forceRefresh)i=await f();if(E)return i;if(o&&!o(i))return E=!0,i;if(n(i))return await f(),i;return i}};LN.CredentialsProviderError=Qo;LN.ProviderError=qt;LN.TokenProviderError=Jo;LN.chain=_N;LN.fromStatic=wN;LN.memoize=yN});function pn(t){try{let n=new Set(Array.from(t.match(/([A-Z_]){3,}/g)??[]));return n.delete("CONFIG"),n.delete("CONFIG_PREFIX_SEPARATOR"),n.delete("ENV"),[...n].join(", ")}catch(n){return t}}var ce,xe=(t,n)=>async()=>{try{let o=t(process.env,n);if(o===void 0)throw Error();return o}catch(o){throw new ce.CredentialsProviderError(o.message||`Not found in ENV: ${pn(t.toString())}`,{logger:n?.logger})}};var ae=R(()=>{ce=ot(gn(),1)});import{homedir as $N}from"os";import{sep as XN}from"path";var Bo,CN=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},st=()=>{let{HOME:t,USERPROFILE:n,HOMEPATH:o,HOMEDRIVE:i=`C:${XN}`}=process.env;if(t)return t;if(n)return n;if(o)return`${i}${o}`;let e=CN();if(!Bo[e])Bo[e]=$N();return Bo[e]};var Dn=R(()=>{Bo={}});var tr=(t)=>t.profile||process.env.AWS_PROFILE||"default";var nr=()=>{};var In=s((GN)=>{GN.HttpAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(GN.HttpAuthLocation||(GN.HttpAuthLocation={}));GN.HttpApiKeyAuthLocation=void 0;(function(t){t.HEADER="header",t.QUERY="query"})(GN.HttpApiKeyAuthLocation||(GN.HttpApiKeyAuthLocation={}));GN.EndpointURLScheme=void 0;(function(t){t.HTTP="http",t.HTTPS="https"})(GN.EndpointURLScheme||(GN.EndpointURLScheme={}));GN.AlgorithmId=void 0;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(GN.AlgorithmId||(GN.AlgorithmId={}));var PN=(t)=>{let n=[];if(t.sha256!==void 0)n.push({algorithmId:()=>GN.AlgorithmId.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)n.push({algorithmId:()=>GN.AlgorithmId.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(o){n.push(o)},checksumAlgorithms(){return n}}},MN=(t)=>{let n={};return t.checksumAlgorithms().forEach((o)=>{n[o.algorithmId()]=o.checksumConstructor()}),n},FN=(t)=>{return PN(t)},vN=(t)=>{return MN(t)};GN.FieldPosition=void 0;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(GN.FieldPosition||(GN.FieldPosition={}));var YN="__smithy_context";GN.IniSectionType=void 0;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(GN.IniSectionType||(GN.IniSectionType={}));GN.RequestHandlerProtocol=void 0;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(GN.RequestHandlerProtocol||(GN.RequestHandlerProtocol={}));GN.SMITHY_CONTEXT_KEY=YN;GN.getDefaultClientConfiguration=FN;GN.resolveDefaultRuntimeConfig=vN});var Nt=".";var ko,or=(t)=>Object.entries(t).filter(([n])=>{let o=n.indexOf(Nt);if(o===-1)return!1;return Object.values(ko.IniSectionType).includes(n.substring(0,o))}).reduce((n,[o,i])=>{let e=o.indexOf(Nt),r=o.substring(0,e)===ko.IniSectionType.PROFILE?o.substring(e+1):o;return n[r]=i,n},{...t.default&&{default:t.default}});var ir=R(()=>{ko=ot(In(),1)});import{join as JN}from"path";var BN="AWS_CONFIG_FILE",er=()=>process.env[BN]||JN(st(),".aws","config");var rr=R(()=>{Dn()});import{join as VN}from"path";var WN="AWS_SHARED_CREDENTIALS_FILE",Er=()=>process.env[WN]||VN(st(),".aws","credentials");var ur=R(()=>{Dn()});var fr,KN,pN,mo=(t)=>{let n={},o,i;for(let e of t.split(/\r?\n/)){let r=e.split(/(^|\s)[;#]/)[0].trim();if(r[0]==="["&&r[r.length-1]==="]"){o=void 0,i=void 0;let f=r.substring(1,r.length-1),T=KN.exec(f);if(T){let[,l,,N]=T;if(Object.values(fr.IniSectionType).includes(l))o=[l,N].join(Nt)}else o=f;if(pN.includes(f))throw Error(`Found invalid profile name "${f}"`)}else if(o){let f=r.indexOf("=");if(![0,-1].includes(f)){let[T,l]=[r.substring(0,f).trim(),r.substring(f+1).trim()];if(l==="")i=T;else{if(i&&e.trimStart()===e)i=void 0;n[o]=n[o]||{};let N=i?[i,T].join(Nt):T;n[o][N]=l}}}}return n};var Tr=R(()=>{fr=ot(In(),1),KN=/^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/,pN=["__proto__","profile __proto__"]});import{readFile as hN}from"fs/promises";var zo,lr,bo=(t,n)=>{if(lr[t]!==void 0)return lr[t];if(!zo[t]||n?.ignoreCache)zo[t]=hN(t,"utf8");return zo[t]};var Nr=R(()=>{zo={},lr={}});import{join as Rr}from"path";var Ar=()=>({}),_r=async(t={})=>{let{filepath:n=Er(),configFilepath:o=er()}=t,i=st(),e="~/",r=n;if(n.startsWith("~/"))r=Rr(i,n.slice(2));let E=o;if(o.startsWith("~/"))E=Rr(i,o.slice(2));let f=await Promise.all([bo(E,{ignoreCache:t.ignoreCache}).then(mo).then(or).catch(Ar),bo(r,{ignoreCache:t.ignoreCache}).then(mo).catch(Ar)]);return{configFile:f[0],credentialsFile:f[1]}};var wr=R(()=>{ir();rr();ur();Dn();Tr();Nr()});var yr=()=>{};var Lr=()=>{};var gr=()=>{};var qo=R(()=>{Dn();nr();wr();yr();Lr();gr()});var Dr,Or=(t,{preferredFile:n="config",...o}={})=>async()=>{let i=tr(o),{configFile:e,credentialsFile:r}=await _r(o),E=r[i]||{},f=e[i]||{},T=n==="config"?{...E,...f}:{...f,...E};try{let N=t(T,n==="config"?e:r);if(N===void 0)throw Error();return N}catch(l){throw new Dr.CredentialsProviderError(l.message||`Not found in config files w/ profile [${i}]: ${pn(t.toString())}`,{logger:o.logger})}};var Ir=R(()=>{qo();Dr=ot(gn(),1)});var Ur,jN=(t)=>typeof t==="function",Sr=(t)=>jN(t)?async()=>await t():Ur.fromStatic(t);var $r=R(()=>{Ur=ot(gn(),1)});var hn,Xr=({environmentVariableSelector:t,configFileSelector:n,default:o},i={})=>{let{signingName:e,logger:r}=i;return hn.memoize(hn.chain(xe(t,{signingName:e,logger:r}),Or(n,i),Sr(o)))};var Cr=R(()=>{ae();Ir();$r();hn=ot(gn(),1)});var Pr=R(()=>{Cr()});var Mr="AWS_ENDPOINT_URL",Fr="endpoint_url",vr=(t)=>({environmentVariableSelector:(n)=>{let o=t.split(" ").map((r)=>r.toUpperCase()),i=n[[Mr,...o].join("_")];if(i)return i;let e=n[Mr];if(e)return e;return},configFileSelector:(n,o)=>{if(o&&n.services){let e=o[["services",n.services].join(Nt)];if(e){let r=t.split(" ").map((f)=>f.toLowerCase()),E=e[[r.join("_"),Fr].join(Nt)];if(E)return E}}let i=n[Fr];if(i)return i;return},default:void 0});var Yr=R(()=>{qo()});var Gr=async(t)=>Xr(vr(t??""))();var Hr=R(()=>{Pr();Yr()});var Zr=s((dN)=>{function kN(t){let n={};if(t=t.replace(/^\?/,""),t)for(let o of t.split("&")){let[i,e=null]=o.split("=");if(i=decodeURIComponent(i),e)e=decodeURIComponent(e);if(!(i in n))n[i]=e;else if(Array.isArray(n[i]))n[i].push(e);else n[i]=[n[i],e]}return n}dN.parseQueryString=kN});var Jr=s((bN)=>{var zN=Zr(),Qr=(t)=>{if(typeof t==="string")return Qr(new URL(t));let{hostname:n,pathname:o,port:i,protocol:e,search:r}=t,E;if(r)E=zN.parseQueryString(r);return{hostname:n,port:i?parseInt(i):void 0,protocol:e,path:o,query:E}};bN.parseUrl=Qr});var so,Br=(t)=>{if(typeof t==="object"){if("url"in t){let n=so.parseUrl(t.url);if(t.headers){n.headers={};for(let[o,i]of Object.entries(t.headers))n.headers[o.toLowerCase()]=i.join(", ")}return n}return t}return so.parseUrl(t)};var co=R(()=>{so=ot(Jr(),1)});var Vr=async(t,n,o,i)=>{if(!o.isCustomEndpoint){let E;if(o.serviceConfiguredEndpoint)E=await o.serviceConfiguredEndpoint();else E=await Gr(o.serviceId);if(E)o.endpoint=()=>Promise.resolve(Br(E)),o.isCustomEndpoint=!0}let e=await sN(t,n,o);if(typeof o.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let r=o.endpointProvider(e,i);if(o.isCustomEndpoint&&o.endpoint){let E=await o.endpoint();if(E?.headers){r.headers??={};for(let[f,T]of Object.entries(E.headers))r.headers[f]=Array.isArray(T)?T:[T]}}return r},sN=async(t,n,o)=>{let i={},e=n?.getEndpointParameterInstructions?.()||{};for(let[r,E]of Object.entries(e))switch(E.type){case"staticContextParams":i[r]=E.value;break;case"contextParams":i[r]=t[E.name];break;case"clientContextParams":case"builtInParams":i[r]=await se(E.name,r,o,E.type!=="builtInParams")();break;case"operationContextParams":i[r]=E.get(t);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(E))}if(Object.keys(e).length===0)Object.assign(i,o);if(String(o.serviceId).toLowerCase()==="s3")await ze(i);return i};var Wr=R(()=>{qe();Hr();co()});var Kr=R(()=>{Wr();co()});var hr=s((aN)=>{var pr=In(),cN=(t)=>t[pr.SMITHY_CONTEXT_KEY]||(t[pr.SMITHY_CONTEXT_KEY]={}),xN=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n};aN.getSmithyContext=cN;aN.normalizeProvider=xN});var jr=()=>{};var xo=s((uR)=>{var oR=In(),iR=(t)=>{return{setHttpHandler(n){t.httpHandler=n},httpHandler(){return t.httpHandler},updateHttpClientConfig(n,o){t.httpHandler?.updateHttpClientConfig(n,o)},httpHandlerConfigs(){return t.httpHandler.httpHandlerConfigs()}}},eR=(t)=>{return{httpHandler:t.httpHandler()}};class kr{name;kind;values;constructor({name:t,kind:n=oR.FieldPosition.HEADER,values:o=[]}){this.name=t,this.kind=n,this.values=o}add(t){this.values.push(t)}set(t){this.values=t}remove(t){this.values=this.values.filter((n)=>n!==t)}toString(){return this.values.map((t)=>t.includes(",")||t.includes(" ")?`"${t}"`:t).join(", ")}get(){return this.values}}class dr{entries={};encoding;constructor({fields:t=[],encoding:n="utf-8"}){t.forEach(this.setField.bind(this)),this.encoding=n}setField(t){this.entries[t.name.toLowerCase()]=t}getField(t){return this.entries[t.toLowerCase()]}removeField(t){delete this.entries[t.toLowerCase()]}getByType(t){return Object.values(this.entries).filter((n)=>n.kind===t)}}class jn{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(t){this.method=t.method||"GET",this.hostname=t.hostname||"localhost",this.port=t.port,this.query=t.query||{},this.headers=t.headers||{},this.body=t.body,this.protocol=t.protocol?t.protocol.slice(-1)!==":"?`${t.protocol}:`:t.protocol:"https:",this.path=t.path?t.path.charAt(0)!=="/"?`/${t.path}`:t.path:"/",this.username=t.username,this.password=t.password,this.fragment=t.fragment}static clone(t){let n=new jn({...t,headers:{...t.headers}});if(n.query)n.query=rR(n.query);return n}static isInstance(t){if(!t)return!1;let n=t;return"method"in n&&"protocol"in n&&"hostname"in n&&"path"in n&&typeof n.query==="object"&&typeof n.headers==="object"}clone(){return jn.clone(this)}}function rR(t){return Object.keys(t).reduce((n,o)=>{let i=t[o];return{...n,[o]:Array.isArray(i)?[...i]:i}},{})}class mr{statusCode;reason;headers;body;constructor(t){this.statusCode=t.statusCode,this.reason=t.reason,this.headers=t.headers||{},this.body=t.body}static isInstance(t){if(!t)return!1;let n=t;return typeof n.statusCode==="number"&&typeof n.headers==="object"}}function ER(t){return/^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(t)}uR.Field=kr;uR.Fields=dr;uR.HttpRequest=jn;uR.HttpResponse=mr;uR.getHttpHandlerExtensionConfiguration=iR;uR.isValidHostname=ER;uR.resolveHttpHandlerRuntimeConfig=eR});var zr=()=>{};var br=()=>{};var qr;var sr=R(()=>{qr={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var cr=R(()=>{zr();sr();br()});var hg;var xr=R(()=>{cr();hg={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:qr.name}});var ar=()=>{};var tE=()=>{};var nE=R(()=>{Kr();jr();xr();ar();tE()});var oE=()=>{};var iE=()=>{};var eE=()=>{};var rE=()=>{};var uE=s((LR)=>{var EE={},ao={};for(let t=0;t<256;t++){let n=t.toString(16).toLowerCase();if(n.length===1)n=`0${n}`;EE[t]=n,ao[n]=t}function wR(t){if(t.length%2!==0)throw Error("Hex encoded strings must have an even number length");let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2){let i=t.slice(o,o+2).toLowerCase();if(i in ao)n[o/2]=ao[i];else throw Error(`Cannot decode unrecognized sequence ${i} as hexadecimal`)}return n}function yR(t){let n="";for(let o=0;o<t.byteLength;o++)n+=EE[t[o]];return n}LR.fromHex=wR;LR.toHex=yR});var ti=s((IR)=>{var OR=(t)=>typeof ArrayBuffer==="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]";IR.isArrayBuffer=OR});var fE=s((CR)=>{var SR=ti(),ni=Vn("buffer"),$R=(t,n=0,o=t.byteLength-n)=>{if(!SR.isArrayBuffer(t))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return ni.Buffer.from(t,n,o)},XR=(t,n)=>{if(typeof t!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof t} (${t})`);return n?ni.Buffer.from(t,n):ni.Buffer.from(t)};CR.fromArrayBuffer=$R;CR.fromString=XR});var NE=s((YR)=>{var TE=fE(),lE=(t)=>{let n=TE.fromString(t,"utf8");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},FR=(t)=>{if(typeof t==="string")return lE(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(t)},vR=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return TE.fromArrayBuffer(t.buffer,t.byteOffset,t.byteLength).toString("utf8")};YR.fromUtf8=lE;YR.toUint8Array=FR;YR.toUtf8=vR});var Ri=s((dR)=>{var $t=uE(),Zt=NE(),QR=ti(),wE=xo(),RE=hr(),kn=Ho(),yE="X-Amz-Algorithm",LE="X-Amz-Credential",ei="X-Amz-Date",gE="X-Amz-SignedHeaders",DE="X-Amz-Expires",ri="X-Amz-Signature",Ei="X-Amz-Security-Token",JR="X-Amz-Region-Set",ui="authorization",fi=ei.toLowerCase(),OE="date",IE=[ui,fi,OE],UE=ri.toLowerCase(),qn="x-amz-content-sha256",SE=Ei.toLowerCase(),BR="host",$E={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},XE=/^proxy-/,CE=/^sec-/,VR=[/^proxy-/i,/^sec-/i],dn="AWS4-HMAC-SHA256",WR="AWS4-ECDSA-P256-SHA256",PE="AWS4-HMAC-SHA256-PAYLOAD",ME="UNSIGNED-PAYLOAD",FE=50,Ti="aws4_request",vE=604800,ct={},mn=[],zn=(t,n,o)=>`${t}/${n}/${o}/${Ti}`,YE=async(t,n,o,i,e)=>{let r=await AE(t,n.secretAccessKey,n.accessKeyId),E=`${o}:${i}:${e}:${$t.toHex(r)}:${n.sessionToken}`;if(E in ct)return ct[E];mn.push(E);while(mn.length>FE)delete ct[mn.shift()];let f=`AWS4${n.secretAccessKey}`;for(let T of[o,i,e,Ti])f=await AE(t,f,T);return ct[E]=f},KR=()=>{mn.length=0,Object.keys(ct).forEach((t)=>{delete ct[t]})},AE=(t,n,o)=>{let i=new t(n);return i.update(Zt.toUint8Array(o)),i.digest()},oi=({headers:t},n,o)=>{let i={};for(let e of Object.keys(t).sort()){if(t[e]==null)continue;let r=e.toLowerCase();if(r in $E||n?.has(r)||XE.test(r)||CE.test(r)){if(!o||o&&!o.has(r))continue}i[r]=t[e].trim().replace(/\s+/g," ")}return i},bn=async({headers:t,body:n},o)=>{for(let i of Object.keys(t))if(i.toLowerCase()===qn)return t[i];if(n==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof n==="string"||ArrayBuffer.isView(n)||QR.isArrayBuffer(n)){let i=new o;return i.update(Zt.toUint8Array(n)),$t.toHex(await i.digest())}return ME};class GE{format(t){let n=[];for(let e of Object.keys(t)){let r=Zt.fromUtf8(e);n.push(Uint8Array.from([r.byteLength]),r,this.formatHeaderValue(t[e]))}let o=new Uint8Array(n.reduce((e,r)=>e+r.byteLength,0)),i=0;for(let e of n)o.set(e,i),i+=e.byteLength;return o}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?0:1]);case"byte":return Uint8Array.from([2,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,3),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let o=new DataView(new ArrayBuffer(5));return o.setUint8(0,4),o.setInt32(1,t.value,!1),new Uint8Array(o.buffer);case"long":let i=new Uint8Array(9);return i[0]=5,i.set(t.value.bytes,1),i;case"binary":let e=new DataView(new ArrayBuffer(3+t.value.byteLength));e.setUint8(0,6),e.setUint16(1,t.value.byteLength,!1);let r=new Uint8Array(e.buffer);return r.set(t.value,3),r;case"string":let E=Zt.fromUtf8(t.value),f=new DataView(new ArrayBuffer(3+E.byteLength));f.setUint8(0,7),f.setUint16(1,E.byteLength,!1);let T=new Uint8Array(f.buffer);return T.set(E,3),T;case"timestamp":let l=new Uint8Array(9);return l[0]=8,l.set(li.fromNumber(t.value.valueOf()).bytes,1),l;case"uuid":if(!pR.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let N=new Uint8Array(17);return N[0]=9,N.set($t.fromHex(t.value.replace(/\-/g,"")),1),N}}}var pR=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class li{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let o=7,i=Math.abs(Math.round(t));o>-1&&i>0;o--,i/=256)n[o]=i;if(t<0)_E(n);return new li(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)_E(t);return parseInt($t.toHex(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function _E(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}var HE=(t,n)=>{t=t.toLowerCase();for(let o of Object.keys(n))if(t===o.toLowerCase())return!0;return!1},ZE=(t,n={})=>{let{headers:o,query:i={}}=wE.HttpRequest.clone(t);for(let e of Object.keys(o)){let r=e.toLowerCase();if(r.slice(0,6)==="x-amz-"&&!n.unhoistableHeaders?.has(r)||n.hoistableHeaders?.has(r))i[e]=o[e],delete o[e]}return{...t,headers:o,query:i}},ii=(t)=>{t=wE.HttpRequest.clone(t);for(let n of Object.keys(t.headers))if(IE.indexOf(n.toLowerCase())>-1)delete t.headers[n];return t},QE=({query:t={}})=>{let n=[],o={};for(let i of Object.keys(t)){if(i.toLowerCase()===UE)continue;let e=kn.escapeUri(i);n.push(e);let r=t[i];if(typeof r==="string")o[e]=`${e}=${kn.escapeUri(r)}`;else if(Array.isArray(r))o[e]=r.slice(0).reduce((E,f)=>E.concat([`${e}=${kn.escapeUri(f)}`]),[]).sort().join("&")}return n.sort().map((i)=>o[i]).filter((i)=>i).join("&")},hR=(t)=>jR(t).toISOString().replace(/\.\d{3}Z$/,"Z"),jR=(t)=>{if(typeof t==="number")return new Date(t*1000);if(typeof t==="string"){if(Number(t))return new Date(Number(t)*1000);return new Date(t)}return t};class Ni{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:o,service:i,sha256:e,uriEscapePath:r=!0}){this.service=i,this.sha256=e,this.uriEscapePath=r,this.applyChecksum=typeof t==="boolean"?t:!0,this.regionProvider=RE.normalizeProvider(o),this.credentialProvider=RE.normalizeProvider(n)}createCanonicalRequest(t,n,o){let i=Object.keys(n).sort();return`${t.method}
|
|
135
135
|
${this.getCanonicalPath(t)}
|
|
136
|
-
${
|
|
136
|
+
${QE(t)}
|
|
137
137
|
${i.map((e)=>`${e}:${n[e]}`).join(`
|
|
138
138
|
`)}
|
|
139
139
|
|
|
140
140
|
${i.join(";")}
|
|
141
|
-
${o}`}async createStringToSign(t,n,o,i){let e=new this.sha256;e.update(
|
|
141
|
+
${o}`}async createStringToSign(t,n,o,i){let e=new this.sha256;e.update(Zt.toUint8Array(o));let r=await e.digest();return`${i}
|
|
142
142
|
${t}
|
|
143
143
|
${n}
|
|
144
|
-
${
|
|
145
|
-
`);return this.signString(g,{signingDate:o,signingRegion:E,signingService:r})}async signMessage(t,{signingDate:n=new Date,signingRegion:o,signingService:i}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:n,signingRegion:o,signingService:i,priorSignature:t.priorSignature}).then((r)=>{return{message:t.message,signature:r}})}async signString(t,{signingDate:n=new Date,signingRegion:o,signingService:i}={}){let e=await this.credentialProvider();this.validateResolvedCredentials(e);let r=o??await this.regionProvider(),{shortDate:E}=this.formatDate(n),f=new this.sha256(await this.getSigningKey(e,r,E,i));return f.update(Gt.toUint8Array(t)),St.toHex(await f.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:o,unsignableHeaders:i,signingRegion:e,signingService:r}={}){let E=await this.credentialProvider();this.validateResolvedCredentials(E);let f=e??await this.regionProvider(),T=co(t),{longDate:N,shortDate:A}=this.formatDate(n),y=Kn(A,f,r??this.service);if(T.headers[ii]=N,E.sessionToken)T.headers[lE]=E.sessionToken;let l=await pn(T,this.sha256);if(!XE(jn,T.headers)&&this.applyChecksum)T.headers[jn]=l;let g=xo(T,i,o),I=await this.getSignature(N,y,this.getSigningKey(E,f,A,r),this.createCanonicalRequest(T,g,l));return T.headers[oi]=`${Vn} Credential=${E.accessKeyId}/${y}, SignedHeaders=${this.getCanonicalHeaderList(g)}, Signature=${I}`,T}async getSignature(t,n,o,i){let e=await this.createStringToSign(t,n,i,Vn),r=new this.sha256(await o);return r.update(Gt.toUint8Array(e)),St.toHex(await r.digest())}getSigningKey(t,n,o,i){return SE(this.sha256,t,o,n,i||this.service)}}var BR={SignatureV4a:null};JR.ALGORITHM_IDENTIFIER=Vn;JR.ALGORITHM_IDENTIFIER_V4A=YR;JR.ALGORITHM_QUERY_PARAM=fE;JR.ALWAYS_UNSIGNABLE_HEADERS=wE;JR.AMZ_DATE_HEADER=ii;JR.AMZ_DATE_QUERY_PARAM=ao;JR.AUTH_HEADER=oi;JR.CREDENTIAL_QUERY_PARAM=TE;JR.DATE_HEADER=RE;JR.EVENT_ALGORITHM_IDENTIFIER=DE;JR.EXPIRES_QUERY_PARAM=AE;JR.GENERATED_HEADERS=yE;JR.HOST_HEADER=FR;JR.KEY_TYPE_IDENTIFIER=ei;JR.MAX_CACHE_SIZE=OE;JR.MAX_PRESIGNED_TTL=UE;JR.PROXY_HEADER_PATTERN=LE;JR.REGION_SET_PARAM=MR;JR.SEC_HEADER_PATTERN=gE;JR.SHA256_HEADER=jn;JR.SIGNATURE_HEADER=_E;JR.SIGNATURE_QUERY_PARAM=ti;JR.SIGNED_HEADERS_QUERY_PARAM=NE;JR.SignatureV4=ME;JR.SignatureV4Base=Ei;JR.TOKEN_HEADER=lE;JR.TOKEN_QUERY_PARAM=ni;JR.UNSIGNABLE_PATTERNS=vR;JR.UNSIGNED_PAYLOAD=IE;JR.clearCredentialCache=GR;JR.createScope=Kn;JR.getCanonicalHeaders=xo;JR.getCanonicalQuery=PE;JR.getPayloadHash=pn;JR.getSigningKey=SE;JR.hasHeader=XE;JR.moveHeadersToQuery=CE;JR.prepareRequest=co;JR.signatureV4aContainer=BR});var hn="X-Amz-S3session-Token",fi;var FE=R(()=>{fi=hn.toLowerCase()});function vE(t){return{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey,expiration:t.expiration}}function YE(t,n){let o=setTimeout(()=>{throw Error("SignatureV4S3Express credential override was created but not called.")},10),i=t.credentialProvider,e=()=>{return clearTimeout(o),t.credentialProvider=i,Promise.resolve(n)};t.credentialProvider=e}var GE,kn;var HE=R(()=>{FE();GE=nt(ui(),1);kn=class kn extends GE.SignatureV4{async signWithCredentials(t,n,o){let i=vE(n);t.headers[fi]=n.sessionToken;let e=this;return YE(e,i),e.signRequest(t,o??{})}async presignWithCredentials(t,n,o){let i=vE(n);return delete t.headers[fi],t.headers[hn]=n.sessionToken,t.query=t.query??{},t.query[hn]=n.sessionToken,YE(this,i),this.presign(t,o)}}});var ZE=R(()=>{HE()});var QE=()=>{};var BE=()=>{};var JE=()=>{};var VE=R(()=>{br();qr();sr();xr();ZE();QE();BE();JE()});var Ln;var Ti=R(()=>{Ln={CrtSignerV4:null}});class Ai{sigv4aSigner;sigv4Signer;signerOptions;static sigv4aDependency(){if(typeof Ln.CrtSignerV4==="function")return"crt";else if(typeof Ni.signatureV4aContainer.SignatureV4a==="function")return"js";return"none"}constructor(t){this.sigv4Signer=new kn(t),this.signerOptions=t}async sign(t,n={}){if(n.signingRegion==="*")return this.getSigv4aSigner().sign(t,n);return this.sigv4Signer.sign(t,n)}async signWithCredentials(t,n,o={}){if(o.signingRegion==="*"){let i=this.getSigv4aSigner(),e=Ln.CrtSignerV4;if(e&&i instanceof e)return i.signWithCredentials(t,n,o);else throw Error(`signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.signWithCredentials(t,n,o)}async presign(t,n={}){if(n.signingRegion==="*"){let o=this.getSigv4aSigner(),i=Ln.CrtSignerV4;if(i&&o instanceof i)return o.presign(t,n);else throw Error(`presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.presign(t,n)}async presignWithCredentials(t,n,o={}){if(o.signingRegion==="*")throw Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(t,n,o)}getSigv4aSigner(){if(!this.sigv4aSigner){let t=Ln.CrtSignerV4,n=Ni.signatureV4aContainer.SignatureV4a;if(this.signerOptions.runtime==="node"){if(!t&&!n)throw Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");if(t&&typeof t==="function")this.sigv4aSigner=new t({...this.signerOptions,signingAlgorithm:1});else if(n&&typeof n==="function")this.sigv4aSigner=new n({...this.signerOptions});else throw Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt")}else{if(!n||typeof n!=="function")throw Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a");this.sigv4aSigner=new n({...this.signerOptions})}}return this.sigv4aSigner}}var Ni;var WE=R(()=>{VE();Ti();Ni=nt(ui(),1)});var KE=R(()=>{WE();Ti()});var pE="UNSIGNED-PAYLOAD",jE="X-Amz-Content-Sha256";class mn{signer;constructor(t){let n={service:t.signingName||t.service||"s3",uriEscapePath:t.uriEscapePath||!1,applyChecksum:t.applyChecksum||!1,...t};this.signer=new Ai(n)}presign(t,{unsignableHeaders:n=new Set,hoistableHeaders:o=new Set,unhoistableHeaders:i=new Set,...e}={}){return this.prepareRequest(t,{unsignableHeaders:n,unhoistableHeaders:i,hoistableHeaders:o}),this.signer.presign(t,{expiresIn:900,unsignableHeaders:n,unhoistableHeaders:i,...e})}presignWithCredentials(t,n,{unsignableHeaders:o=new Set,hoistableHeaders:i=new Set,unhoistableHeaders:e=new Set,...r}={}){return this.prepareRequest(t,{unsignableHeaders:o,unhoistableHeaders:e,hoistableHeaders:i}),this.signer.presignWithCredentials(t,n,{expiresIn:900,unsignableHeaders:o,unhoistableHeaders:e,...r})}prepareRequest(t,{unsignableHeaders:n=new Set,unhoistableHeaders:o=new Set,hoistableHeaders:i=new Set}={}){n.add("content-type"),Object.keys(t.headers).map((f)=>f.toLowerCase()).filter((f)=>f.startsWith("x-amz-server-side-encryption")).forEach((f)=>{if(!i.has(f))o.add(f)}),t.headers[jE]=pE;let e=t.headers.host,r=t.port,E=`${t.hostname}${t.port!=null?":"+r:""}`;if(!e||e===t.hostname&&t.port!=null)t.headers.host=E}}var Ri=R(()=>{KE()});var hE,kE=async(t,n,o={})=>{let i,e;if(typeof t.config.endpointProvider==="function"){let l=(await vr(n.input,n.constructor,t.config)).properties?.authSchemes?.[0];if(l?.name==="sigv4a")e=l?.signingRegionSet?.join(",");else e=l?.signingRegion;i=new mn({...t.config,signingName:l?.signingName,region:async()=>e})}else i=new mn(t.config);let r=(y,l)=>async(g)=>{let{request:I}=g;if(!hE.HttpRequest.isInstance(I))throw Error("Request to be presigned is not an valid HTTP request.");delete I.headers["amz-sdk-invocation-id"],delete I.headers["amz-sdk-request"],delete I.headers["x-amz-user-agent"];let D,C={...o,signingRegion:o.signingRegion??l.signing_region??e,signingService:o.signingService??l.signing_service};if(l.s3ExpressIdentity)D=await i.presignWithCredentials(I,l.s3ExpressIdentity,C);else D=await i.presign(I,C);return{response:{},output:{$metadata:{httpStatusCode:200},presigned:D}}},E="presignInterceptMiddleware",f=t.middlewareStack.clone();f.addRelativeTo(r,{name:E,relation:"before",toMiddleware:"awsAuthMiddleware",override:!0});let T=n.resolveMiddleware(f,t.config,{}),{output:N}=await T({input:n.input}),{presigned:A}=N;return Je(A)};var mE=R(()=>{Ve();dr();Ri();hE=nt(zo(),1)});var zE=R(()=>{mE();Ri()});import{S3Client as dE,PutObjectCommand as Sy,GetObjectCommand as bE,DeleteObjectCommand as $y,CopyObjectCommand as Xy,ListObjectsV2Command as Cy,HeadObjectCommand as Py,ListObjectVersionsCommand as My,GetBucketVersioningCommand as Fy,PutBucketVersioningCommand as vy}from"@aws-sdk/client-s3";class $t{client;presignClient;bucket;versioningEnabled=!1;constructor(t){this.bucket=t.bucket;let n={accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey};this.client=new dE({region:t.region,endpoint:t.endpoint,credentials:n,forcePathStyle:!0}),this.presignClient=new dE({region:t.region,endpoint:t.publicEndpoint??t.endpoint,credentials:n,forcePathStyle:!0}),this.versioningEnabled=t.versioningEnabled??!1}async putObject(t,n,o,i){let e=await this.client.send(new Sy({Bucket:this.bucket,Key:t,Body:typeof n==="string"?Buffer.from(n):n,Metadata:o,...i&&{ContentType:i}}));return{etag:e.ETag,versionId:e.VersionId}}async getObject(t,n){let o=await this.client.send(new bE({Bucket:this.bucket,Key:t,...n&&{VersionId:n}}));return{body:await o.Body.transformToByteArray(),contentType:o.ContentType,size:o.ContentLength,versionId:o.VersionId,etag:o.ETag}}async deleteObject(t){await this.client.send(new $y({Bucket:this.bucket,Key:t}))}async copyObject(t,n){let o=await this.client.send(new Xy({Bucket:this.bucket,CopySource:`${this.bucket}/${t}`,Key:n}));return{etag:o.CopyObjectResult?.ETag,versionId:o.VersionId}}async listObjects(t,n){let o=await this.client.send(new Cy({Bucket:this.bucket,Prefix:t,...n?.delimiter&&{Delimiter:n.delimiter}}));return{objects:(o.Contents??[]).map((i)=>({key:i.Key,size:i.Size??0,lastModified:i.LastModified??new Date,etag:i.ETag})),prefixes:(o.CommonPrefixes??[]).map((i)=>i.Prefix)}}async headObject(t){let n=await this.client.send(new Py({Bucket:this.bucket,Key:t}));return{contentType:n.ContentType,size:n.ContentLength??0,lastModified:n.LastModified,etag:n.ETag,versionId:n.VersionId}}async listObjectVersions(t){return((await this.client.send(new My({Bucket:this.bucket,Prefix:t}))).Versions??[]).filter((o)=>o.Key===t).map((o)=>({versionId:o.VersionId,lastModified:o.LastModified??new Date,size:o.Size??0,isLatest:o.IsLatest??!1}))}async checkVersioningEnabled(){try{return(await this.client.send(new Fy({Bucket:this.bucket}))).Status==="Enabled"}catch{return!1}}async enableVersioning(){try{return await this.client.send(new vy({Bucket:this.bucket,VersioningConfiguration:{Status:"Enabled"}})),this.versioningEnabled=!0,!0}catch{return!1}}async getPresignedUrl(t,n=86400,o){let i=new bE({Bucket:this.bucket,Key:t,...o&&{ResponseContentType:o}});return kE(this.presignClient,i,{expiresIn:n})}}var qE=R(()=>{zE()});var sE=R(()=>{qE()});var At,F,ot,it,gn,et;var m=R(()=>{At=class At extends Error{code;suggestion;constructor(t,n,o){super(n);this.name=this.constructor.name,this.code=t,this.suggestion=o}toJSON(){return{error:this.code,message:this.message,...this.suggestion&&{suggestion:this.suggestion}}}};F=class F extends At{path;constructor(t,n){super("NOT_FOUND",t,n?.suggestion);this.path=n?.path}toJSON(){return{...super.toJSON(),...this.path&&{path:this.path}}}};ot=class ot extends At{requiredRole;yourRole;constructor(t,n){super("PERMISSION_DENIED",t,n?.suggestion);this.requiredRole=n?.requiredRole,this.yourRole=n?.yourRole}toJSON(){return{...super.toJSON(),...this.requiredRole&&{required_role:this.requiredRole},...this.yourRole&&{your_role:this.yourRole}}}};it=class it extends At{path;constructor(t,n){super("EDIT_CONFLICT",t,n?.suggestion);this.path=n?.path}toJSON(){return{...super.toJSON(),...this.path&&{path:this.path}}}};gn=class gn extends At{path;constructor(t,n){super("INDEXING_IN_PROGRESS",t,n?.suggestion??"Try again in a moment");this.path=n?.path}toJSON(){return{...super.toJSON(),...this.path&&{path:this.path}}}};et=class et extends At{field;constructor(t,n){super("VALIDATION_ERROR",t,n?.suggestion);this.field=n?.field}toJSON(){return{...super.toJSON(),...this.field&&{field:this.field}}}}});import{eq as xE,and as Yy}from"drizzle-orm";function Dn(t){return Gy[t]??"admin"}function Rt(t,n,o){return t.select().from(u.driveMembers).where(Yy(xE(u.driveMembers.driveId,o),xE(u.driveMembers.userId,n))).get()?.role??null}function In(t,n){let o=Rt(t,n.userId,n.driveId);if(!o)throw new ot("You do not have access to this drive",{requiredRole:n.requiredRole,yourRole:"none",suggestion:"Request access from the drive admin"});if(cE[o]<cE[n.requiredRole])throw new ot(`This operation requires '${n.requiredRole}' role, but you have '${o}'`,{requiredRole:n.requiredRole,yourRole:o,suggestion:n.requiredRole==="editor"?"Ask a drive admin to upgrade your role to editor":"Ask a drive admin to upgrade your role"})}var cE,Gy;var zn=R(()=>{Z();m();cE={viewer:0,editor:1,admin:2},Gy={ls:"viewer",cat:"viewer",tail:"viewer",stat:"viewer",grep:"viewer",fts:"viewer",search:"viewer","vec-search":"viewer",log:"viewer",diff:"viewer",recent:"viewer",tree:"viewer",glob:"viewer","signed-url":"viewer",write:"editor",edit:"editor",append:"editor",rm:"editor",mv:"editor",cp:"editor",revert:"editor",reindex:"admin","comment-add":"editor","comment-list":"viewer","comment-get":"viewer","comment-update":"editor","comment-delete":"editor","comment-resolve":"editor"}});function On(t){let n=t;if(!n.startsWith("/"))n="/"+n;if(n.length>1&&n.endsWith("/"))n=n.slice(0,-1);return n}function Xt(t){let n=t;if(!n.startsWith("/"))n="/"+n;if(!n.endsWith("/"))n+="/";return n}function aE(t){return t.startsWith("/")?t.slice(1):t}import{eq as yt,and as Un,sql as Hy,desc as tu}from"drizzle-orm";function S(t,n,o){let i=aE(o);return`${t}/drives/${n}/${i}`}async function dn(t,n){return(t.db.select({maxVersion:Hy`MAX(version)`}).from(u.fileVersions).where(Un(yt(u.fileVersions.path,n),yt(u.fileVersions.driveId,t.driveId))).get()?.maxVersion??0)+1}function xt(t,n){let o=t.db.select({version:u.fileVersions.version,contentHash:u.fileVersions.contentHash,etag:u.fileVersions.etag,createdAt:u.fileVersions.createdAt}).from(u.fileVersions).where(Un(yt(u.fileVersions.path,n),yt(u.fileVersions.driveId,t.driveId))).orderBy(tu(u.fileVersions.version)).limit(1).get();if(!o)return null;return{version:o.version,contentHash:o.contentHash??null,etag:o.etag??null,createdAt:o.createdAt}}async function h(t,n,o){let e=await dn(t,n)-1;if(o!==void 0&&e!==o)throw new it(`Expected version ${o} but file is at version ${e}`,{path:n,suggestion:"Re-read the file to get the current version and retry"});return e}async function bn(t,n){return t.db.select({contentHash:u.fileVersions.contentHash}).from(u.fileVersions).where(Un(yt(u.fileVersions.path,n),yt(u.fileVersions.driveId,t.driveId))).orderBy(tu(u.fileVersions.version)).limit(1).get()?.contentHash??null}async function p(t,n){let o=await dn(t,n.path),i=new Date;try{t.db.transaction((e)=>{e.insert(u.fileVersions).values({path:n.path,driveId:t.driveId,version:o,s3VersionId:n.s3VersionId,author:t.userId,operation:n.operation,message:n.message??null,diffSummary:n.diffSummary??null,size:n.size??null,etag:n.etag??null,contentHash:n.contentHash??null,createdAt:i}).run();let r=e.select().from(u.files).where(Un(yt(u.files.path,n.path),yt(u.files.driveId,t.driveId))).get();if(r)e.update(u.files).set({size:n.size??r.size,contentType:n.contentType??r.contentType,author:t.userId,currentVersionId:String(o),modifiedAt:i,isDeleted:n.operation==="delete"}).where(Un(yt(u.files.path,n.path),yt(u.files.driveId,t.driveId))).run();else e.insert(u.files).values({path:n.path,driveId:t.driveId,size:n.size??0,contentType:n.contentType??null,author:t.userId,currentVersionId:String(o),createdAt:i,modifiedAt:i,isDeleted:n.operation==="delete"}).run()})}catch(e){let r=String(e?.message??"");if(r.includes("UNIQUE constraint failed")&&r.includes("file_versions"))throw new it(`Concurrent write detected for ${n.path}: version ${o} already exists`,{path:n.path,suggestion:"Re-read the file to get the current version and retry the write"});throw e}return o}var W=R(()=>{Z();m()});function _t(t){let n=t.split(".").pop()?.toLowerCase()??"";return Zy[n]??"application/octet-stream"}var Zy;var ct=R(()=>{Zy={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",pdf:"application/pdf",txt:"text/plain",md:"text/markdown",mdx:"text/markdown",html:"text/html",css:"text/css",csv:"text/csv",xml:"application/xml",json:"application/json",yaml:"application/x-yaml",yml:"application/x-yaml",toml:"application/toml",ts:"text/plain",tsx:"text/plain",js:"text/javascript",jsx:"text/javascript",py:"text/x-python",rb:"text/x-ruby",rs:"text/x-rust",go:"text/x-go",java:"text/x-java",c:"text/x-c",cpp:"text/x-c++",h:"text/x-c",hpp:"text/x-c++",sh:"text/x-shellscript",sql:"text/x-sql",graphql:"text/x-graphql",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}});function yi(t){return t.$client}function x(t,n){let o=yi(t);o.prepare("DELETE FROM files_fts WHERE path = ? AND drive_id = ?").run(n.path,n.driveId),o.prepare("INSERT INTO files_fts(path, content, drive_id) VALUES (?, ?, ?)").run(n.path,n.content,n.driveId)}function qn(t,n){yi(t).prepare("DELETE FROM files_fts WHERE path = ? AND drive_id = ?").run(n.path,n.driveId)}function sn(t,n){let o=yi(t),i,e;if(n.pathPrefix)i=`
|
|
144
|
+
${$t.toHex(r)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let n=[];for(let e of t.split("/")){if(e?.length===0)continue;if(e===".")continue;if(e==="..")n.pop();else n.push(e)}let o=`${t?.startsWith("/")?"/":""}${n.join("/")}${n.length>0&&t?.endsWith("/")?"/":""}`;return kn.escapeUri(o).replace(/%2F/g,"/")}return t}validateResolvedCredentials(t){if(typeof t!=="object"||typeof t.accessKeyId!=="string"||typeof t.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(t){let n=hR(t).replace(/[\-:]/g,"");return{longDate:n,shortDate:n.slice(0,8)}}getCanonicalHeaderList(t){return Object.keys(t).sort().join(";")}}class JE extends Ni{headerFormatter=new GE;constructor({applyChecksum:t,credentials:n,region:o,service:i,sha256:e,uriEscapePath:r=!0}){super({applyChecksum:t,credentials:n,region:o,service:i,sha256:e,uriEscapePath:r})}async presign(t,n={}){let{signingDate:o=new Date,expiresIn:i=3600,unsignableHeaders:e,unhoistableHeaders:r,signableHeaders:E,hoistableHeaders:f,signingRegion:T,signingService:l}=n,N=await this.credentialProvider();this.validateResolvedCredentials(N);let A=T??await this.regionProvider(),{longDate:w,shortDate:g}=this.formatDate(o);if(i>vE)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let O=zn(g,A,l??this.service),D=ZE(ii(t),{unhoistableHeaders:r,hoistableHeaders:f});if(N.sessionToken)D.query[Ei]=N.sessionToken;D.query[yE]=dn,D.query[LE]=`${N.accessKeyId}/${O}`,D.query[ei]=w,D.query[DE]=i.toString(10);let C=oi(D,e,E);return D.query[gE]=this.getCanonicalHeaderList(C),D.query[ri]=await this.getSignature(w,O,this.getSigningKey(N,A,g,l),this.createCanonicalRequest(D,C,await bn(t,this.sha256))),D}async sign(t,n){if(typeof t==="string")return this.signString(t,n);else if(t.headers&&t.payload)return this.signEvent(t,n);else if(t.message)return this.signMessage(t,n);else return this.signRequest(t,n)}async signEvent({headers:t,payload:n},{signingDate:o=new Date,priorSignature:i,signingRegion:e,signingService:r}){let E=e??await this.regionProvider(),{shortDate:f,longDate:T}=this.formatDate(o),l=zn(f,E,r??this.service),N=await bn({headers:{},body:n},this.sha256),A=new this.sha256;A.update(t);let w=$t.toHex(await A.digest()),g=[PE,T,l,i,w,N].join(`
|
|
145
|
+
`);return this.signString(g,{signingDate:o,signingRegion:E,signingService:r})}async signMessage(t,{signingDate:n=new Date,signingRegion:o,signingService:i}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:n,signingRegion:o,signingService:i,priorSignature:t.priorSignature}).then((r)=>{return{message:t.message,signature:r}})}async signString(t,{signingDate:n=new Date,signingRegion:o,signingService:i}={}){let e=await this.credentialProvider();this.validateResolvedCredentials(e);let r=o??await this.regionProvider(),{shortDate:E}=this.formatDate(n),f=new this.sha256(await this.getSigningKey(e,r,E,i));return f.update(Zt.toUint8Array(t)),$t.toHex(await f.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:o,unsignableHeaders:i,signingRegion:e,signingService:r}={}){let E=await this.credentialProvider();this.validateResolvedCredentials(E);let f=e??await this.regionProvider(),T=ii(t),{longDate:l,shortDate:N}=this.formatDate(n),A=zn(N,f,r??this.service);if(T.headers[fi]=l,E.sessionToken)T.headers[SE]=E.sessionToken;let w=await bn(T,this.sha256);if(!HE(qn,T.headers)&&this.applyChecksum)T.headers[qn]=w;let g=oi(T,i,o),O=await this.getSignature(l,A,this.getSigningKey(E,f,N,r),this.createCanonicalRequest(T,g,w));return T.headers[ui]=`${dn} Credential=${E.accessKeyId}/${A}, SignedHeaders=${this.getCanonicalHeaderList(g)}, Signature=${O}`,T}async getSignature(t,n,o,i){let e=await this.createStringToSign(t,n,i,dn),r=new this.sha256(await o);return r.update(Zt.toUint8Array(e)),$t.toHex(await r.digest())}getSigningKey(t,n,o,i){return YE(this.sha256,t,o,n,i||this.service)}}var kR={SignatureV4a:null};dR.ALGORITHM_IDENTIFIER=dn;dR.ALGORITHM_IDENTIFIER_V4A=WR;dR.ALGORITHM_QUERY_PARAM=yE;dR.ALWAYS_UNSIGNABLE_HEADERS=$E;dR.AMZ_DATE_HEADER=fi;dR.AMZ_DATE_QUERY_PARAM=ei;dR.AUTH_HEADER=ui;dR.CREDENTIAL_QUERY_PARAM=LE;dR.DATE_HEADER=OE;dR.EVENT_ALGORITHM_IDENTIFIER=PE;dR.EXPIRES_QUERY_PARAM=DE;dR.GENERATED_HEADERS=IE;dR.HOST_HEADER=BR;dR.KEY_TYPE_IDENTIFIER=Ti;dR.MAX_CACHE_SIZE=FE;dR.MAX_PRESIGNED_TTL=vE;dR.PROXY_HEADER_PATTERN=XE;dR.REGION_SET_PARAM=JR;dR.SEC_HEADER_PATTERN=CE;dR.SHA256_HEADER=qn;dR.SIGNATURE_HEADER=UE;dR.SIGNATURE_QUERY_PARAM=ri;dR.SIGNED_HEADERS_QUERY_PARAM=gE;dR.SignatureV4=JE;dR.SignatureV4Base=Ni;dR.TOKEN_HEADER=SE;dR.TOKEN_QUERY_PARAM=Ei;dR.UNSIGNABLE_PATTERNS=VR;dR.UNSIGNED_PAYLOAD=ME;dR.clearCredentialCache=KR;dR.createScope=zn;dR.getCanonicalHeaders=oi;dR.getCanonicalQuery=QE;dR.getPayloadHash=bn;dR.getSigningKey=YE;dR.hasHeader=HE;dR.moveHeadersToQuery=ZE;dR.prepareRequest=ii;dR.signatureV4aContainer=kR});var sn="X-Amz-S3session-Token",Ai;var BE=R(()=>{Ai=sn.toLowerCase()});function VE(t){return{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey,expiration:t.expiration}}function WE(t,n){let o=setTimeout(()=>{throw Error("SignatureV4S3Express credential override was created but not called.")},10),i=t.credentialProvider,e=()=>{return clearTimeout(o),t.credentialProvider=i,Promise.resolve(n)};t.credentialProvider=e}var KE,cn;var pE=R(()=>{BE();KE=ot(Ri(),1);cn=class cn extends KE.SignatureV4{async signWithCredentials(t,n,o){let i=VE(n);t.headers[Ai]=n.sessionToken;let e=this;return WE(e,i),e.signRequest(t,o??{})}async presignWithCredentials(t,n,o){let i=VE(n);return delete t.headers[Ai],t.headers[sn]=n.sessionToken,t.query=t.query??{},t.query[sn]=n.sessionToken,WE(this,i),this.presign(t,o)}}});var hE=R(()=>{pE()});var jE=()=>{};var kE=()=>{};var dE=()=>{};var mE=R(()=>{oE();iE();eE();rE();hE();jE();kE();dE()});var Un;var _i=R(()=>{Un={CrtSignerV4:null}});class yi{sigv4aSigner;sigv4Signer;signerOptions;static sigv4aDependency(){if(typeof Un.CrtSignerV4==="function")return"crt";else if(typeof wi.signatureV4aContainer.SignatureV4a==="function")return"js";return"none"}constructor(t){this.sigv4Signer=new cn(t),this.signerOptions=t}async sign(t,n={}){if(n.signingRegion==="*")return this.getSigv4aSigner().sign(t,n);return this.sigv4Signer.sign(t,n)}async signWithCredentials(t,n,o={}){if(o.signingRegion==="*"){let i=this.getSigv4aSigner(),e=Un.CrtSignerV4;if(e&&i instanceof e)return i.signWithCredentials(t,n,o);else throw Error(`signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.signWithCredentials(t,n,o)}async presign(t,n={}){if(n.signingRegion==="*"){let o=this.getSigv4aSigner(),i=Un.CrtSignerV4;if(i&&o instanceof i)return o.presign(t,n);else throw Error(`presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.presign(t,n)}async presignWithCredentials(t,n,o={}){if(o.signingRegion==="*")throw Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(t,n,o)}getSigv4aSigner(){if(!this.sigv4aSigner){let t=Un.CrtSignerV4,n=wi.signatureV4aContainer.SignatureV4a;if(this.signerOptions.runtime==="node"){if(!t&&!n)throw Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");if(t&&typeof t==="function")this.sigv4aSigner=new t({...this.signerOptions,signingAlgorithm:1});else if(n&&typeof n==="function")this.sigv4aSigner=new n({...this.signerOptions});else throw Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt")}else{if(!n||typeof n!=="function")throw Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a");this.sigv4aSigner=new n({...this.signerOptions})}}return this.sigv4aSigner}}var wi;var zE=R(()=>{mE();_i();wi=ot(Ri(),1)});var bE=R(()=>{zE();_i()});var qE="UNSIGNED-PAYLOAD",sE="X-Amz-Content-Sha256";class xn{signer;constructor(t){let n={service:t.signingName||t.service||"s3",uriEscapePath:t.uriEscapePath||!1,applyChecksum:t.applyChecksum||!1,...t};this.signer=new yi(n)}presign(t,{unsignableHeaders:n=new Set,hoistableHeaders:o=new Set,unhoistableHeaders:i=new Set,...e}={}){return this.prepareRequest(t,{unsignableHeaders:n,unhoistableHeaders:i,hoistableHeaders:o}),this.signer.presign(t,{expiresIn:900,unsignableHeaders:n,unhoistableHeaders:i,...e})}presignWithCredentials(t,n,{unsignableHeaders:o=new Set,hoistableHeaders:i=new Set,unhoistableHeaders:e=new Set,...r}={}){return this.prepareRequest(t,{unsignableHeaders:o,unhoistableHeaders:e,hoistableHeaders:i}),this.signer.presignWithCredentials(t,n,{expiresIn:900,unsignableHeaders:o,unhoistableHeaders:e,...r})}prepareRequest(t,{unsignableHeaders:n=new Set,unhoistableHeaders:o=new Set,hoistableHeaders:i=new Set}={}){n.add("content-type"),Object.keys(t.headers).map((f)=>f.toLowerCase()).filter((f)=>f.startsWith("x-amz-server-side-encryption")).forEach((f)=>{if(!i.has(f))o.add(f)}),t.headers[sE]=qE;let e=t.headers.host,r=t.port,E=`${t.hostname}${t.port!=null?":"+r:""}`;if(!e||e===t.hostname&&t.port!=null)t.headers.host=E}}var Li=R(()=>{bE()});var cE,xE=async(t,n,o={})=>{let i,e;if(typeof t.config.endpointProvider==="function"){let w=(await Vr(n.input,n.constructor,t.config)).properties?.authSchemes?.[0];if(w?.name==="sigv4a")e=w?.signingRegionSet?.join(",");else e=w?.signingRegion;i=new xn({...t.config,signingName:w?.signingName,region:async()=>e})}else i=new xn(t.config);let r=(A,w)=>async(g)=>{let{request:O}=g;if(!cE.HttpRequest.isInstance(O))throw Error("Request to be presigned is not an valid HTTP request.");delete O.headers["amz-sdk-invocation-id"],delete O.headers["amz-sdk-request"],delete O.headers["x-amz-user-agent"];let D,C={...o,signingRegion:o.signingRegion??w.signing_region??e,signingService:o.signingService??w.signing_service};if(w.s3ExpressIdentity)D=await i.presignWithCredentials(O,w.s3ExpressIdentity,C);else D=await i.presign(O,C);return{response:{},output:{$metadata:{httpStatusCode:200},presigned:D}}},E="presignInterceptMiddleware",f=t.middlewareStack.clone();f.addRelativeTo(r,{name:E,relation:"before",toMiddleware:"awsAuthMiddleware",override:!0});let T=n.resolveMiddleware(f,t.config,{}),{output:l}=await T({input:n.input}),{presigned:N}=l;return de(N)};var aE=R(()=>{me();nE();Li();cE=ot(xo(),1)});var tu=R(()=>{aE();Li()});import{S3Client as nu,PutObjectCommand as YA,GetObjectCommand as ou,DeleteObjectCommand as GA,CopyObjectCommand as HA,ListObjectsV2Command as ZA,HeadObjectCommand as QA,ListObjectVersionsCommand as JA,GetBucketVersioningCommand as BA,PutBucketVersioningCommand as VA}from"@aws-sdk/client-s3";class Xt{client;presignClient;bucket;versioningEnabled=!1;constructor(t){this.bucket=t.bucket;let n={accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey};this.client=new nu({region:t.region,endpoint:t.endpoint,credentials:n,forcePathStyle:!0}),this.presignClient=new nu({region:t.region,endpoint:t.publicEndpoint??t.endpoint,credentials:n,forcePathStyle:!0}),this.versioningEnabled=t.versioningEnabled??!1}async putObject(t,n,o,i){let e=await this.client.send(new YA({Bucket:this.bucket,Key:t,Body:typeof n==="string"?Buffer.from(n):n,Metadata:o,...i&&{ContentType:i}}));return{etag:e.ETag,versionId:e.VersionId}}async getObject(t,n){let o=await this.client.send(new ou({Bucket:this.bucket,Key:t,...n&&{VersionId:n}}));return{body:await o.Body.transformToByteArray(),contentType:o.ContentType,size:o.ContentLength,versionId:o.VersionId,etag:o.ETag}}async deleteObject(t){await this.client.send(new GA({Bucket:this.bucket,Key:t}))}async copyObject(t,n){let o=await this.client.send(new HA({Bucket:this.bucket,CopySource:`${this.bucket}/${t}`,Key:n}));return{etag:o.CopyObjectResult?.ETag,versionId:o.VersionId}}async listObjects(t,n){let o=await this.client.send(new ZA({Bucket:this.bucket,Prefix:t,...n?.delimiter&&{Delimiter:n.delimiter}}));return{objects:(o.Contents??[]).map((i)=>({key:i.Key,size:i.Size??0,lastModified:i.LastModified??new Date,etag:i.ETag})),prefixes:(o.CommonPrefixes??[]).map((i)=>i.Prefix)}}async headObject(t){let n=await this.client.send(new QA({Bucket:this.bucket,Key:t}));return{contentType:n.ContentType,size:n.ContentLength??0,lastModified:n.LastModified,etag:n.ETag,versionId:n.VersionId}}async listObjectVersions(t){return((await this.client.send(new JA({Bucket:this.bucket,Prefix:t}))).Versions??[]).filter((o)=>o.Key===t).map((o)=>({versionId:o.VersionId,lastModified:o.LastModified??new Date,size:o.Size??0,isLatest:o.IsLatest??!1}))}async checkVersioningEnabled(){try{return(await this.client.send(new BA({Bucket:this.bucket}))).Status==="Enabled"}catch{return!1}}async enableVersioning(){try{return await this.client.send(new VA({Bucket:this.bucket,VersioningConfiguration:{Status:"Enabled"}})),this.versioningEnabled=!0,!0}catch{return!1}}async getPresignedUrl(t,n=86400,o){let i=new ou({Bucket:this.bucket,Key:t,...o&&{ResponseContentType:o}});return xE(this.presignClient,i,{expiresIn:n})}}var iu=R(()=>{tu()});var eu=R(()=>{iu()});var Rt,F,it,et,Sn,c;var m=R(()=>{Rt=class Rt extends Error{code;suggestion;constructor(t,n,o){super(n);this.name=this.constructor.name,this.code=t,this.suggestion=o}toJSON(){return{error:this.code,message:this.message,...this.suggestion&&{suggestion:this.suggestion}}}};F=class F extends Rt{path;constructor(t,n){super("NOT_FOUND",t,n?.suggestion);this.path=n?.path}toJSON(){return{...super.toJSON(),...this.path&&{path:this.path}}}};it=class it extends Rt{requiredRole;yourRole;constructor(t,n){super("PERMISSION_DENIED",t,n?.suggestion);this.requiredRole=n?.requiredRole,this.yourRole=n?.yourRole}toJSON(){return{...super.toJSON(),...this.requiredRole&&{required_role:this.requiredRole},...this.yourRole&&{your_role:this.yourRole}}}};et=class et extends Rt{path;constructor(t,n){super("EDIT_CONFLICT",t,n?.suggestion);this.path=n?.path}toJSON(){return{...super.toJSON(),...this.path&&{path:this.path}}}};Sn=class Sn extends Rt{path;constructor(t,n){super("INDEXING_IN_PROGRESS",t,n?.suggestion??"Try again in a moment");this.path=n?.path}toJSON(){return{...super.toJSON(),...this.path&&{path:this.path}}}};c=class c extends Rt{field;constructor(t,n){super("VALIDATION_ERROR",t,n?.suggestion);this.field=n?.field}toJSON(){return{...super.toJSON(),...this.field&&{field:this.field}}}}});import{eq as ru,and as WA}from"drizzle-orm";function $n(t){return KA[t]??"admin"}function At(t,n,o){return t.select().from(u.driveMembers).where(WA(ru(u.driveMembers.driveId,o),ru(u.driveMembers.userId,n))).get()?.role??null}function Xn(t,n){let o=At(t,n.userId,n.driveId);if(!o)throw new it("You do not have access to this drive",{requiredRole:n.requiredRole,yourRole:"none",suggestion:"Request access from the drive admin"});if(Eu[o]<Eu[n.requiredRole])throw new it(`This operation requires '${n.requiredRole}' role, but you have '${o}'`,{requiredRole:n.requiredRole,yourRole:o,suggestion:n.requiredRole==="editor"?"Ask a drive admin to upgrade your role to editor":"Ask a drive admin to upgrade your role"})}var Eu,KA;var an=R(()=>{G();m();Eu={viewer:0,editor:1,admin:2},KA={ls:"viewer",cat:"viewer",tail:"viewer",stat:"viewer",grep:"viewer",fts:"viewer",search:"viewer","vec-search":"viewer",log:"viewer",diff:"viewer",recent:"viewer",tree:"viewer",glob:"viewer","signed-url":"viewer",write:"editor",edit:"editor",append:"editor",rm:"editor",mv:"editor",cp:"editor",revert:"editor",reindex:"admin","comment-add":"editor","comment-list":"viewer","comment-get":"viewer","comment-update":"editor","comment-delete":"editor","comment-resolve":"editor"}});function Cn(t){let n=t;if(!n.startsWith("/"))n="/"+n;if(n.length>1&&n.endsWith("/"))n=n.slice(0,-1);return n}function Ct(t){let n=t;if(!n.startsWith("/"))n="/"+n;if(!n.endsWith("/"))n+="/";return n}function uu(t){return t.startsWith("/")?t.slice(1):t}import{eq as _t,and as Pn,sql as pA,desc as fu}from"drizzle-orm";function I(t,n,o){let i=uu(o);return`${t}/drives/${n}/${i}`}async function to(t,n){return(t.db.select({maxVersion:pA`MAX(version)`}).from(u.fileVersions).where(Pn(_t(u.fileVersions.path,n),_t(u.fileVersions.driveId,t.driveId))).get()?.maxVersion??0)+1}function xt(t,n){let o=t.db.select({version:u.fileVersions.version,contentHash:u.fileVersions.contentHash,etag:u.fileVersions.etag,createdAt:u.fileVersions.createdAt}).from(u.fileVersions).where(Pn(_t(u.fileVersions.path,n),_t(u.fileVersions.driveId,t.driveId))).orderBy(fu(u.fileVersions.version)).limit(1).get();if(!o)return null;return{version:o.version,contentHash:o.contentHash??null,etag:o.etag??null,createdAt:o.createdAt}}async function j(t,n,o){let e=await to(t,n)-1;if(o!==void 0&&e!==o)throw new et(`Expected version ${o} but file is at version ${e}`,{path:n,suggestion:"Re-read the file to get the current version and retry"});return e}async function no(t,n){return t.db.select({contentHash:u.fileVersions.contentHash}).from(u.fileVersions).where(Pn(_t(u.fileVersions.path,n),_t(u.fileVersions.driveId,t.driveId))).orderBy(fu(u.fileVersions.version)).limit(1).get()?.contentHash??null}async function h(t,n){let o=await to(t,n.path),i=new Date;try{t.db.transaction((e)=>{e.insert(u.fileVersions).values({path:n.path,driveId:t.driveId,version:o,s3VersionId:n.s3VersionId,author:t.userId,operation:n.operation,message:n.message??null,diffSummary:n.diffSummary??null,size:n.size??null,etag:n.etag??null,contentHash:n.contentHash??null,createdAt:i}).run();let r=e.select().from(u.files).where(Pn(_t(u.files.path,n.path),_t(u.files.driveId,t.driveId))).get();if(r)e.update(u.files).set({size:n.size??r.size,contentType:n.contentType??r.contentType,author:t.userId,currentVersionId:String(o),modifiedAt:i,isDeleted:n.operation==="delete"}).where(Pn(_t(u.files.path,n.path),_t(u.files.driveId,t.driveId))).run();else e.insert(u.files).values({path:n.path,driveId:t.driveId,size:n.size??0,contentType:n.contentType??null,author:t.userId,currentVersionId:String(o),createdAt:i,modifiedAt:i,isDeleted:n.operation==="delete"}).run()})}catch(e){let r=String(e?.message??"");if(r.includes("UNIQUE constraint failed")&&r.includes("file_versions"))throw new et(`Concurrent write detected for ${n.path}: version ${o} already exists`,{path:n.path,suggestion:"Re-read the file to get the current version and retry the write"});throw e}return o}var W=R(()=>{G();m()});function K(t){let n=t.split(".").pop()?.toLowerCase()??"";return hA[n]??"application/octet-stream"}function jA(t){let n=t.split(";")[0]?.trim().toLowerCase()??"";return n.startsWith("text/")||n==="application/json"||n==="application/xml"||n==="application/x-yaml"||n==="application/toml"||n==="image/svg+xml"}function kA(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return null}}function Pt(t,n){let o=kA(t);if(o===null)return null;if(jA(n))return o;if(n==="application/octet-stream"&&dA(t))return o;return null}function dA(t){if(t.length===0)return!0;let n=0;for(let o of t){if(o===0)return!1;let i=o===9||o===10||o===12||o===13;if(o<32&&!i)n++}return n/t.length<0.01}var hA;var rt=R(()=>{hA={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",pdf:"application/pdf",txt:"text/plain",md:"text/markdown",mdx:"text/markdown",html:"text/html",css:"text/css",csv:"text/csv",xml:"application/xml",json:"application/json",yaml:"application/x-yaml",yml:"application/x-yaml",toml:"application/toml",ts:"text/plain",tsx:"text/plain",js:"text/javascript",jsx:"text/javascript",py:"text/x-python",rb:"text/x-ruby",rs:"text/x-rust",go:"text/x-go",java:"text/x-java",c:"text/x-c",cpp:"text/x-c++",h:"text/x-c",hpp:"text/x-c++",sh:"text/x-shellscript",sql:"text/x-sql",graphql:"text/x-graphql",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}});function gi(t){return t.$client}function wt(t,n){let o=gi(t);o.prepare("DELETE FROM files_fts WHERE path = ? AND drive_id = ?").run(n.path,n.driveId),o.prepare("INSERT INTO files_fts(path, content, drive_id) VALUES (?, ?, ?)").run(n.path,n.content,n.driveId)}function at(t,n){gi(t).prepare("DELETE FROM files_fts WHERE path = ? AND drive_id = ?").run(n.path,n.driveId)}function oo(t,n){let o=gi(t),i,e;if(n.pathPrefix)i=`
|
|
146
146
|
SELECT path, snippet(files_fts, 1, '<b>', '</b>', '...', 32) as snippet, rank
|
|
147
147
|
FROM files_fts
|
|
148
148
|
WHERE content MATCH ? AND drive_id = ? AND path LIKE ?
|
|
@@ -154,75 +154,76 @@ ${St.toHex(r)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let n=[];for(l
|
|
|
154
154
|
WHERE content MATCH ? AND drive_id = ?
|
|
155
155
|
ORDER BY rank
|
|
156
156
|
LIMIT 50
|
|
157
|
-
`,e=[n.pattern,n.driveId];return o.prepare(i).all(...e)}async function
|
|
158
|
-
|
|
159
|
-
`);if(f>1800)E=E.slice(0,f)}if(i.push({content:E,charOffset:e,tokenCount:Math.ceil(E.length/4)}),e+=E.length-512,e<=i[i.length-1].charOffset)e=i[i.length-1].charOffset+E.length}return i}import{eq as
|
|
160
|
-
`),
|
|
161
|
-
`),totalLines:
|
|
162
|
-
`),f=E.length,T=Math.max(0,f-i),
|
|
163
|
-
`),totalLines:f,truncated:
|
|
164
|
-
`);for(let
|
|
157
|
+
`,e=[n.pattern,n.driveId];return o.prepare(i).all(...e)}async function Tu(t){try{let{RecursiveChunker:n}=await import("chonkie");return(await(await n.create({chunkSize:900})).chunk(t)).map((e)=>({content:e.text,charOffset:e.startIndex??0,tokenCount:e.tokenCount??Math.ceil(e.text.length/4)}))}catch{return mA(t)}}function mA(t){let i=[];if(t.length<=3600)return[{content:t,charOffset:0,tokenCount:Math.ceil(t.length/4)}];let e=0;while(e<t.length){let r=Math.min(e+3600,t.length),E=t.slice(e,r);if(r<t.length){let f=E.lastIndexOf(`
|
|
158
|
+
|
|
159
|
+
`);if(f>1800)E=E.slice(0,f)}if(i.push({content:E,charOffset:e,tokenCount:Math.ceil(E.length/4)}),e+=E.length-512,e<=i[i.length-1].charOffset)e=i[i.length-1].charOffset+E.length}return i}import{eq as a,and as tn}from"drizzle-orm";function zA(t){return t.$client}class lu{permits;waiting=[];constructor(t){this.permits=t}async acquire(){if(this.permits>0)return this.permits--,()=>this.release();return new Promise((t)=>{this.waiting.push(()=>{this.permits--,t(()=>this.release())})})}release(){this.permits++;let t=this.waiting.shift();if(t)t()}}async function Di(t,n,o){let i=zA(t),e=t.select({isDeleted:u.files.isDeleted}).from(u.files).where(tn(a(u.files.path,o.path),a(u.files.driveId,o.driveId))).get();if(!e||e.isDeleted)return;try{let r=await Tu(o.content),E=r.map((N)=>N.content),f=await n.embedBatch(E),T=t.select({id:u.contentChunks.id}).from(u.contentChunks).where(tn(a(u.contentChunks.filePath,o.path),a(u.contentChunks.driveId,o.driveId))).all();for(let N of T)i.prepare("DELETE FROM chunk_vectors WHERE chunk_id = ?").run(N.id);t.delete(u.contentChunks).where(tn(a(u.contentChunks.filePath,o.path),a(u.contentChunks.driveId,o.driveId))).run();let l=i.prepare("INSERT INTO chunk_vectors(chunk_id, embedding) VALUES (?, ?)");for(let N=0;N<r.length;N++){let A=t.insert(u.contentChunks).values({filePath:o.path,driveId:o.driveId,chunkIndex:N,content:r[N].content,charOffset:r[N].charOffset,tokenCount:r[N].tokenCount}).returning({id:u.contentChunks.id}).get(),w=new Float32Array(f[N]);l.run(A.id,w)}t.update(u.files).set({embeddingStatus:"indexed"}).where(tn(a(u.files.path,o.path),a(u.files.driveId,o.driveId))).run()}catch(r){throw t.update(u.files).set({embeddingStatus:"failed"}).where(tn(a(u.files.path,o.path),a(u.files.driveId,o.driveId))).run(),r}}function nn(t,n,o){if(!n)return;t.update(u.files).set({embeddingStatus:"pending"}).where(tn(a(u.files.path,o.path),a(u.files.driveId,o.driveId))).run(),bA.acquire().then(async(i)=>{try{await Di(t,n,o)}catch(e){console.error("Embedding failed",{path:o.path,error:e})}finally{i()}})}var bA;var Mn=R(()=>{G();bA=new lu(2)});import{eq as on,and as Oi}from"drizzle-orm";function Fn(t,n){at(t.db,{path:n,driveId:t.driveId});let o=t.db.select({id:u.contentChunks.id}).from(u.contentChunks).where(Oi(on(u.contentChunks.filePath,n),on(u.contentChunks.driveId,t.driveId))).all();if(o.length>0){let i=t.db.$client;for(let e of o)i.prepare("DELETE FROM chunk_vectors WHERE chunk_id = ?").run(e.id);t.db.delete(u.contentChunks).where(Oi(on(u.contentChunks.filePath,n),on(u.contentChunks.driveId,t.driveId))).run()}t.db.update(u.files).set({embeddingStatus:null}).where(Oi(on(u.files.path,n),on(u.files.driveId,t.driveId))).run()}function Ii(t,n,o){wt(t.db,{path:n,driveId:t.driveId,content:o}),nn(t.db,t.embeddingProvider??null,{path:n,driveId:t.driveId,content:o})}function en(t,n,o,i){let e=Pt(o,i);if(e===null)return Fn(t,n),null;return Ii(t,n,e),e}var rn=R(()=>{G();Mn();rt()});import{createHash as qA}from"crypto";async function io(t,n){let o=new TextEncoder().encode(n.content);return Nu(t,{...n,bytes:o,indexableText:n.content},{maxSize:sA})}async function Dt(t,n){return Nu(t,n,{maxSize:cA})}async function Nu(t,n,o){let i=I(t.orgId,t.driveId,n.path),e=n.bytes,r=e.byteLength;if(r>o.maxSize){let N=(o.maxSize/1024/1024).toFixed(0);throw new c(`File size ${(r/1024/1024).toFixed(1)}MB exceeds the ${N}MB limit`,{field:"content",suggestion:"Split large files into smaller chunks"})}let E=qA("sha256").update(e).digest("hex");if(n.expectedVersion!==void 0){let N=await j(t,n.path,n.expectedVersion);if(N>0){let A=await no(t,n.path);if(A!==null&&A===E)return{version:N,path:n.path,size:r,contentHash:E,deduped:!0}}}let f=K(n.path),T=await t.s3.putObject(i,e,void 0,f),l=await h(t,{path:n.path,s3VersionId:T.versionId??"",operation:"write",message:n.message,size:r,etag:T.etag,contentType:f,contentHash:E});if(n.indexableText!==void 0)Ii(t,n.path,n.indexableText);else en(t,n.path,e,f);return{version:l,path:n.path,size:r,contentHash:E,deduped:!1}}var sA=10485760,cA=52428800;var Ru=R(()=>{W();rt();m();rn()});async function Au(t,n){let o=I(t.orgId,t.driveId,n.path),i;try{let e=await t.s3.getObject(o);i=e.body;let r=e.contentType??K(n.path),E=Pt(i,r);if(E===null)throw new c(`File is not readable as text: ${n.path}`,{field:"path",suggestion:"Use `agent-fs download` or `agent-fs signed-url` for binary files"});let f=E.split(`
|
|
160
|
+
`),T=f.length,l=n.offset??0,N=n.limit??xA,A=f.slice(l,l+N),w=l+N<T;return{content:A.join(`
|
|
161
|
+
`),totalLines:T,truncated:w}}catch(e){if(e?.name==="NoSuchKey"||e?.$metadata?.httpStatusCode===404)throw new F(`File not found: ${n.path}`,{path:n.path});throw e}}var xA=200;var _u=R(()=>{W();m();rt()});import{createHash as aA}from"crypto";async function wu(t,n){let o=I(t.orgId,t.driveId,n.path);if(n.expectedVersion!==void 0)await j(t,n.path,n.expectedVersion);let i;try{i=(await t.s3.getObject(o)).body}catch(g){if(g?.name==="NoSuchKey"||g?.$metadata?.httpStatusCode===404)throw new F(`File not found: ${n.path}`,{path:n.path});throw g}let e=new TextDecoder().decode(i),r=e.split(n.old_string).length-1;if(r===0)throw new et(`old_string not found in ${n.path}`,{path:n.path,suggestion:"Verify the exact text you want to replace"});if(r>1)throw new et(`old_string found ${r} times in ${n.path}, expected exactly 1`,{path:n.path,suggestion:"Provide more surrounding context to make the match unique"});let E=e.replace(n.old_string,n.new_string),f=Buffer.byteLength(E),T=K(n.path),l=aA("sha256").update(E).digest("hex"),N=await t.s3.putObject(o,E,void 0,T),A=JSON.stringify({old:n.old_string,new:n.new_string}),w=await h(t,{path:n.path,s3VersionId:N.versionId??"",operation:"edit",message:n.message,diffSummary:A,size:f,etag:N.etag,contentType:T,contentHash:l});return wt(t.db,{path:n.path,driveId:t.driveId,content:E}),nn(t.db,t.embeddingProvider??null,{path:n.path,driveId:t.driveId,content:E}),{version:w,path:n.path,changes:1}}var yu=R(()=>{W();m();rt();Mn()});import{createHash as t_}from"crypto";async function Lu(t,n){let o=I(t.orgId,t.driveId,n.path);if(n.expectedVersion!==void 0)await j(t,n.path,n.expectedVersion);let i="";try{let N=await t.s3.getObject(o);i=new TextDecoder().decode(N.body)}catch(N){if(N?.name==="NoSuchKey"||N?.$metadata?.httpStatusCode===404)throw new F(`File not found: ${n.path}`,{path:n.path});throw N}let e=i+n.content,r=Buffer.byteLength(e),E=K(n.path),f=t_("sha256").update(e).digest("hex"),T=await t.s3.putObject(o,e,void 0,E),l=await h(t,{path:n.path,s3VersionId:T.versionId??"",operation:"append",message:n.message,size:r,etag:T.etag,contentType:E,contentHash:f});return wt(t.db,{path:n.path,driveId:t.driveId,content:e}),nn(t.db,t.embeddingProvider??null,{path:n.path,driveId:t.driveId,content:e}),{version:l,size:r}}var gu=R(()=>{W();m();rt();Mn()});import{eq as Du,and as n_,like as o_}from"drizzle-orm";async function Ou(t,n){let o=Ct(n.path??"/"),i=I(t.orgId,t.driveId,o),{objects:e,prefixes:r}=await t.s3.listObjects(i,{delimiter:"/"}),E=t.db.select().from(u.files).where(n_(Du(u.files.driveId,t.driveId),o_(u.files.path,o+"%"),Du(u.files.isDeleted,!1))).all(),f=new Map(E.map((l)=>[l.path,l])),T=[];for(let l of r){let N=l.slice(i.length).replace(/\/$/,"");if(N)T.push({name:N,type:"directory",size:0})}for(let l of e){let N=l.key.slice(i.length);if(!N)continue;let A=N.endsWith("/"),w=A?N.slice(0,-1):N;if(A)T.push({name:w,type:"directory",size:0});else{let g=o+w,O=f.get(g);T.push({name:w,type:"file",size:O?.size??l.size,author:O?.author,modifiedAt:O?.modifiedAt??l.lastModified})}}return{entries:T}}var Iu=R(()=>{G();W()});import{eq as Uu,and as i_}from"drizzle-orm";async function Su(t,n){let o=I(t.orgId,t.driveId,n.path),i;try{i=await t.s3.headObject(o)}catch(r){if(r?.name==="NotFound"||r?.$metadata?.httpStatusCode===404)throw new F(`File not found: ${n.path}`,{path:n.path});throw r}let e=t.db.select().from(u.files).where(i_(Uu(u.files.path,n.path),Uu(u.files.driveId,t.driveId))).get();return{path:n.path,size:i.size,contentType:i.contentType,author:e?.author??"unknown",currentVersion:e?.currentVersionId?parseInt(e.currentVersionId):void 0,createdAt:e?.createdAt??new Date,modifiedAt:e?.modifiedAt??i.lastModified??new Date,isDeleted:e?.isDeleted??!1,embeddingStatus:e?.embeddingStatus??void 0}}var $u=R(()=>{G();W();m()});import{eq as En,and as Ui}from"drizzle-orm";async function Xu(t,n){let o=I(t.orgId,t.driveId,n.path);if(n.expectedVersion!==void 0)await j(t,n.path,n.expectedVersion);await t.s3.deleteObject(o),await h(t,{path:n.path,s3VersionId:"",operation:"delete"}),at(t.db,{path:n.path,driveId:t.driveId});let i=t.db.select({id:u.contentChunks.id}).from(u.contentChunks).where(Ui(En(u.contentChunks.filePath,n.path),En(u.contentChunks.driveId,t.driveId))).all();if(i.length>0){let e=t.db.$client;for(let r of i)e.prepare("DELETE FROM chunk_vectors WHERE chunk_id = ?").run(r.id);t.db.delete(u.contentChunks).where(Ui(En(u.contentChunks.filePath,n.path),En(u.contentChunks.driveId,t.driveId))).run()}return t.db.update(u.comments).set({isDeleted:!0,updatedAt:new Date}).where(Ui(En(u.comments.path,n.path),En(u.comments.driveId,t.driveId))).run(),{path:n.path,deleted:!0}}var Cu=R(()=>{G();W()});import{eq as Pu,and as e_}from"drizzle-orm";import{createHash as r_}from"crypto";async function Mu(t,n){let o=I(t.orgId,t.driveId,n.from),i=I(t.orgId,t.driveId,n.to);if(n.expectedVersion!==void 0)await j(t,n.from,n.expectedVersion);let e=await t.s3.copyObject(o,i),r=await t.s3.headObject(i),E=await t.s3.getObject(i),f=r_("sha256").update(E.body).digest("hex"),T=r.contentType??E.contentType??K(n.to),l=await h(t,{path:n.to,s3VersionId:e.versionId??"",operation:"write",message:n.message??`Moved from ${n.from}`,size:r.size,etag:e.etag,contentType:T,contentHash:f});await t.s3.deleteObject(o),await h(t,{path:n.from,s3VersionId:"",operation:"delete",message:`Moved to ${n.to}`}),at(t.db,{path:n.from,driveId:t.driveId});let N=Pt(E.body,T);if(N===null)Fn(t,n.to);else wt(t.db,{path:n.to,driveId:t.driveId,content:N}),t.db.update(u.contentChunks).set({filePath:n.to}).where(e_(Pu(u.contentChunks.filePath,n.from),Pu(u.contentChunks.driveId,t.driveId))).run();return{from:n.from,to:n.to,version:l}}var Fu=R(()=>{W();G();rt();rn()});import{createHash as E_}from"crypto";async function vu(t,n){let o=I(t.orgId,t.driveId,n.from),i=I(t.orgId,t.driveId,n.to);if(n.expectedVersion!==void 0)await j(t,n.to,n.expectedVersion);let e=await t.s3.copyObject(o,i),r=await t.s3.headObject(i),E=await t.s3.getObject(i),f=E_("sha256").update(E.body).digest("hex"),T=r.contentType??E.contentType??K(n.to),l=await h(t,{path:n.to,s3VersionId:e.versionId??"",operation:"write",message:`Copied from ${n.from}`,size:r.size,etag:e.etag,contentType:T,contentHash:f});return en(t,n.to,E.body,T),{from:n.from,to:n.to,version:l}}var Yu=R(()=>{W();rt();rn()});async function Gu(t,n){let o=I(t.orgId,t.driveId,n.path),i=n.lines??u_,e;try{e=(await t.s3.getObject(o)).body}catch(A){if(A?.name==="NoSuchKey"||A?.$metadata?.httpStatusCode===404)throw new F(`File not found: ${n.path}`,{path:n.path});throw A}let E=new TextDecoder().decode(e).split(`
|
|
162
|
+
`),f=E.length,T=Math.max(0,f-i),l=E.slice(T),N=T>0;return{content:l.join(`
|
|
163
|
+
`),totalLines:f,truncated:N}}var u_=20;var Hu=R(()=>{W();m()});import{eq as Zu,and as f_,desc as T_}from"drizzle-orm";async function Qu(t,n){let o=n.limit??50;return{versions:t.db.select().from(u.fileVersions).where(f_(Zu(u.fileVersions.path,n.path),Zu(u.fileVersions.driveId,t.driveId))).orderBy(T_(u.fileVersions.version)).limit(o).all().map((e)=>({version:e.version,author:e.author,createdAt:e.createdAt,operation:e.operation,message:e.message??void 0,diffSummary:e.diffSummary??void 0,size:e.size??void 0}))}}var Ju=R(()=>{G()});import{eq as un,and as Bu}from"drizzle-orm";import{structuredPatch as l_}from"diff";async function Vu(t,n){let o=t.db.select().from(u.fileVersions).where(Bu(un(u.fileVersions.path,n.path),un(u.fileVersions.driveId,t.driveId),un(u.fileVersions.version,n.v1))).get(),i=t.db.select().from(u.fileVersions).where(Bu(un(u.fileVersions.path,n.path),un(u.fileVersions.driveId,t.driveId),un(u.fileVersions.version,n.v2))).get();if(!o||!i)throw new F(`Version ${!o?n.v1:n.v2} not found for ${n.path}`,{path:n.path});if(o.s3VersionId&&i.s3VersionId){let r=I(t.orgId,t.driveId,n.path);try{let[E,f]=await Promise.all([t.s3.getObject(r,o.s3VersionId),t.s3.getObject(r,i.s3VersionId)]),T=new TextDecoder().decode(E.body),l=new TextDecoder().decode(f.body),N=l_(n.path,n.path,T,l),A=[];for(let w of N.hunks)for(let g of w.lines){let O=g.startsWith("+")?"add":g.startsWith("-")?"remove":"context";A.push({type:O,content:g.slice(1)})}return{changes:A}}catch(E){console.warn(`[diff] S3 content fetch failed for ${n.path}, falling back to diffSummary:`,E)}}let e=[];if(i.diffSummary)try{let r=JSON.parse(i.diffSummary);if(r.old)e.push({type:"remove",content:r.old});if(r.new)e.push({type:"add",content:r.new})}catch{e.push({type:"context",content:i.diffSummary})}return{changes:e}}var Wu=R(()=>{G();W();m()});import{eq as Si,and as N_}from"drizzle-orm";import{createHash as R_}from"crypto";async function Ku(t,n){if(n.expectedVersion!==void 0)await j(t,n.path,n.expectedVersion);let o=t.db.select().from(u.fileVersions).where(N_(Si(u.fileVersions.path,n.path),Si(u.fileVersions.driveId,t.driveId),Si(u.fileVersions.version,n.version))).get();if(!o)throw new F(`Version ${n.version} not found for ${n.path}`,{path:n.path});if(!o.s3VersionId)throw new Rt("VERSIONING_REQUIRED","S3 versioning required for revert","Enable S3 versioning on the bucket");let i=I(t.orgId,t.driveId,n.path),e=await t.s3.getObject(i,o.s3VersionId),r=K(n.path),E=await t.s3.putObject(i,e.body,void 0,r),f=e.body.length,T=R_("sha256").update(e.body).digest("hex"),l=await h(t,{path:n.path,s3VersionId:E.versionId??"",operation:"revert",message:`Reverted to version ${n.version}`,size:f,etag:E.etag,contentType:r,contentHash:T});return en(t,n.path,e.body,r),{version:l,revertedTo:n.version}}var pu=R(()=>{G();W();m();rt();rn()});import{eq as $i,and as hu,desc as A_,gte as __,like as w_}from"drizzle-orm";async function ju(t,n){let o=n.limit??50,i=t.db.select().from(u.fileVersions).where($i(u.fileVersions.driveId,t.driveId)).$dynamic();if(n.path)i=i.where(hu($i(u.fileVersions.driveId,t.driveId),w_(u.fileVersions.path,n.path+"%")));if(n.since)i=i.where(hu($i(u.fileVersions.driveId,t.driveId),__(u.fileVersions.createdAt,n.since)));return{entries:i.orderBy(A_(u.fileVersions.createdAt)).limit(o).all().map((r)=>({path:r.path,version:r.version,author:r.author,createdAt:r.createdAt,operation:r.operation,message:r.message??void 0,diffSummary:r.diffSummary??void 0,size:r.size??void 0}))}}var ku=R(()=>{G()});async function du(t,n){let o=new RegExp(n.pattern),i=Ct(n.path),r=t.db.$client.prepare("SELECT path, content FROM files_fts WHERE drive_id = ? AND path LIKE ?").all(t.driveId,i+"%"),E=[];for(let f of r){let T=f.content.split(`
|
|
164
|
+
`);for(let l=0;l<T.length;l++)if(o.test(T[l]))E.push({path:f.path,lineNumber:l+1,content:T[l]})}return{matches:E}}var mu=()=>{};async function zu(t,n){let i=oo(t.db,{pattern:n.pattern,driveId:t.driveId,pathPrefix:n.path}).map((e)=>({path:e.path,snippet:e.snippet,rank:e.rank}));if(i.length===0)return{matches:i,hint:`No exact token matches for "${n.pattern}". Try 'search' for semantic/fuzzy matching.`};return{matches:i}}var bu=()=>{};import{eq as Xi,and as y_}from"drizzle-orm";async function qu(t,n){let o=t.embeddingProvider;if(!o)return{results:[],hint:"No embedding provider configured. Set OPENAI_API_KEY or enable local embeddings to use semantic search."};let i=n.limit??10,e=await o.embed(n.query),r=new Float32Array(e),f=t.db.$client.prepare(`SELECT chunk_id, distance
|
|
165
165
|
FROM chunk_vectors
|
|
166
166
|
WHERE embedding MATCH ?
|
|
167
167
|
ORDER BY distance
|
|
168
|
-
LIMIT ?`).all(r,i*2);if(f.length===0)return{results:[]};let T=[],
|
|
168
|
+
LIMIT ?`).all(r,i*2);if(f.length===0)return{results:[]};let T=[],l=new Set;for(let N of f){let A=t.db.select().from(u.contentChunks).where(Xi(u.contentChunks.id,N.chunk_id)).get();if(!A)continue;if(A.driveId!==t.driveId)continue;if(l.has(A.filePath))continue;l.add(A.filePath);let w=t.db.select().from(u.files).where(y_(Xi(u.files.path,A.filePath),Xi(u.files.driveId,t.driveId))).get();if(T.push({path:A.filePath,score:1/(1+N.distance),snippet:A.content.slice(0,200),author:w?.author,modifiedAt:w?.modifiedAt}),T.length>=i)break}return{results:T}}var su=R(()=>{G()});import{eq as Ci,and as L_}from"drizzle-orm";async function cu(t,n){let o=n.limit??10,i=t.embeddingProvider,[e,r]=await Promise.all([i?g_(t,n.query,o*3):[],D_(t,n.query,o*3)]);if(e.length===0&&r.length===0)return{results:[],hint:i?`No results found for "${n.query}".`:"No embedding provider configured. Set OPENAI_API_KEY, GEMINI_API_KEY, or enable local embeddings for semantic search. Showing keyword results only."};let E=60,f=new Map;for(let l=0;l<e.length;l++){let N=e[l],A=1/(E+l+1),w=f.get(N.path);if(w)w.score+=A;else f.set(N.path,{score:A,snippet:N.snippet,author:N.author,modifiedAt:N.modifiedAt})}for(let l=0;l<r.length;l++){let N=r[l],A=1/(E+l+1),w=f.get(N.path);if(w){if(w.score+=A,N.snippet)w.snippet=N.snippet}else f.set(N.path,{score:A,snippet:N.snippet})}return{results:Array.from(f.entries()).sort(([,l],[,N])=>N.score-l.score).slice(0,o).map(([l,N])=>({path:l,score:N.score,snippet:N.snippet,author:N.author,modifiedAt:N.modifiedAt})),hint:!i?"Results are keyword-only. Enable embeddings for better semantic matching.":void 0}}async function g_(t,n,o){let e=await t.embeddingProvider.embed(n),r=new Float32Array(e),f=t.db.$client.prepare(`SELECT chunk_id, distance
|
|
169
169
|
FROM chunk_vectors
|
|
170
170
|
WHERE embedding MATCH ?
|
|
171
171
|
ORDER BY distance
|
|
172
|
-
LIMIT ?`).all(r,o),T=[],N=new Set;for(let A of f){let y=t.db.select().from(u.contentChunks).where(Di(u.contentChunks.id,A.chunk_id)).get();if(!y||y.driveId!==t.driveId)continue;if(N.has(y.filePath))continue;N.add(y.filePath);let l=t.db.select().from(u.files).where(E_(Di(u.files.path,y.filePath),Di(u.files.driveId,t.driveId))).get();T.push({path:y.filePath,snippet:y.content.slice(0,200),author:l?.author,modifiedAt:l?.modifiedAt})}return T}function f_(t,n,o){let i=n.split(/\s+/).filter(Boolean).map((e)=>`"${e}"`).join(" OR ");if(!i)return[];try{return sn(t.db,{pattern:i,driveId:t.driveId}).slice(0,o).map((r)=>({path:r.path,snippet:r.snippet}))}catch{return[]}}var ku=R(()=>{Z()});import{eq as cn,and as T_,or as N_,isNull as A_}from"drizzle-orm";async function mu(t,n){let o=[cn(u.files.driveId,t.driveId),cn(u.files.isDeleted,!1),N_(cn(u.files.embeddingStatus,"failed"),A_(u.files.embeddingStatus),cn(u.files.embeddingStatus,"pending"))];if(n.path){let{like:T}=await import("drizzle-orm"),N=n.path.endsWith("/")?n.path:n.path+"/";o.push(T(u.files.path,N+"%"))}let i=t.db.select({path:u.files.path}).from(u.files).where(T_(...o)).all(),e=0,r=0,E=0,f=3;for(let T=0;T<i.length;T+=f){let N=i.slice(T,T+f),A=await Promise.allSettled(N.map(async(y)=>{let l=S(t.orgId,t.driveId,y.path),g=await t.s3.getObject(l),I=new TextDecoder().decode(g.body);if(x(t.db,{path:y.path,driveId:t.driveId,content:I}),t.embeddingProvider)return await _i(t.db,t.embeddingProvider,{path:y.path,driveId:t.driveId,content:I}),"reindexed";return"skipped"}));for(let y of A)if(y.status==="fulfilled")if(y.value==="reindexed")e++;else E++;else console.error("Reindex failed:",y.reason),r++}return{reindexed:e,failed:r,skipped:E}}var zu=R(()=>{Z();W();tn()});import{eq as du,and as R_,like as y_}from"drizzle-orm";async function bu(t,n){let o=Xt(n.path??"/"),i=S(t.orgId,t.driveId,o),{objects:e}=await t.s3.listObjects(i),r=t.db.select().from(u.files).where(R_(du(u.files.driveId,t.driveId),y_(u.files.path,o+"%"),du(u.files.isDeleted,!1))).all(),E=new Map(r.map((T)=>[T.path,T])),f=[];for(let T of e){let N=T.key.slice(i.length);if(!N)continue;let A=N.split("/").filter(Boolean);if(A.length===0)continue;if(n.depth!==void 0&&A.length>n.depth)continue;let y=f;for(let l=0;l<A.length;l++){let g=A[l],I=l===A.length-1,D=!I||N.endsWith("/");if(D&&!I){let C=y.find((H)=>H.name===g&&H.type==="directory");if(!C)C={name:g,type:"directory",children:[]},y.push(C);if(!C.children)C.children=[];y=C.children}else if(D&&I){let C=y.find((H)=>H.name===g&&H.type==="directory");if(!C)C={name:g,type:"directory",children:[]},y.push(C)}else{let C=o+A.slice(0,l+1).join("/"),H=E.get(C),Tn={name:g,type:"file",size:H?.size??T.size};if(H?.author)Tn.author=H.author;if(H?.modifiedAt??T.lastModified)Tn.modifiedAt=H?.modifiedAt??T.lastModified;y.push(Tn)}}}return{tree:f}}var qu=R(()=>{Z();W()});import{eq as su,and as __,like as l_}from"drizzle-orm";function w_(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 xu(t,n){let o=n.path?Xt(n.path):"/",i=S(t.orgId,t.driveId,o),{objects:e}=await t.s3.listObjects(i),r=t.db.select().from(u.files).where(__(su(u.files.driveId,t.driveId),l_(u.files.path,o+"%"),su(u.files.isDeleted,!1))).all(),E=new Map(r.map((N)=>[N.path,N])),f=w_(n.pattern),T=[];for(let N of e){let A=N.key.slice(i.length);if(!A||A.endsWith("/"))continue;if(f.test(A)){let y=o+A,l=E.get(y);T.push({path:y,size:l?.size??N.size,modifiedAt:l?.modifiedAt??N.lastModified})}}return{matches:T}}var cu=R(()=>{Z();W()});async function au(t,n){let o=On(n.path),i=S(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 F(`File not found: ${o}`,{path:o});throw f}let r=_t(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=R(()=>{W();m();ct()});function Ii(t,n,o,i){let e=i.startsWith("/")?i.slice(1):i;return`${t}/file/~/${n}/${o}/${e}`}import{eq as M,and as lt,sql as Oi,desc as nf}from"drizzle-orm";function Ui(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 an(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 to(t,n){let o=new Date,i=crypto.randomUUID(),e=n.path;if(n.parentId){let E=t.db.select().from(u.comments).where(lt(M(u.comments.id,n.parentId),M(u.comments.isDeleted,!1))).get();if(!E)throw new F("Parent comment not found",{suggestion:"Check that the parent comment ID is correct and not deleted"});if(E.parentId)throw new et("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 et("path is required for root comments",{field:"path"});let r=t.db.select({id:u.fileVersions.id}).from(u.fileVersions).where(lt(M(u.fileVersions.path,e),M(u.fileVersions.driveId,t.driveId))).orderBy(nf(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(),Ui(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 no(t,n){let o=[M(u.comments.driveId,t.driveId),M(u.comments.isDeleted,!1)];if(n.path)o.push(M(u.comments.path,n.path));if(n.parentId)o.push(M(u.comments.parentId,n.parentId));else if(n.parentId===void 0&&!n.resolved)o.push(Oi`${u.comments.parentId} IS NULL`),o.push(M(u.comments.resolved,!1));else if(n.parentId===void 0&&n.resolved)o.push(Oi`${u.comments.parentId} IS NULL`);if(n.orgId)o.push(M(u.comments.orgId,n.orgId));let i=n.limit??50,e=n.offset??0;return{comments:t.db.select().from(u.comments).where(lt(...o)).orderBy(nf(u.comments.createdAt)).limit(i).offset(e).all().map((f)=>{let N=t.db.select().from(u.comments).where(lt(M(u.comments.parentId,f.id),M(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((A)=>an({...A,replyCount:0}));return{...an({...f,replyCount:N.length}),replies:N}})}}async function oo(t,n){let o=t.db.select().from(u.comments).where(lt(M(u.comments.id,n.id),M(u.comments.isDeleted,!1))).get();if(!o)throw new F("Comment not found",{suggestion:"Check that the comment ID is correct"});let i=t.db.select({count:Oi`count(*)`}).from(u.comments).where(lt(M(u.comments.parentId,o.id),M(u.comments.isDeleted,!1))).get(),e=an({...o,replyCount:i?.count??0}),E=t.db.select().from(u.comments).where(lt(M(u.comments.parentId,n.id),M(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((f)=>an({...f,replyCount:0}));return{comment:e,replies:E}}async function io(t,n){let o=t.db.select().from(u.comments).where(lt(M(u.comments.id,n.id),M(u.comments.isDeleted,!1))).get();if(!o)throw new F("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.author!==t.userId)throw new ot("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(M(u.comments.id,n.id)).run(),{id:n.id,body:n.body,updatedAt:i}}async function eo(t,n){let o=t.db.select().from(u.comments).where(lt(M(u.comments.id,n.id),M(u.comments.isDeleted,!1))).get();if(!o)throw new F("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.author!==t.userId)throw new ot("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(M(u.comments.id,n.id)).run(),!o.parentId)t.db.update(u.comments).set({isDeleted:!0,updatedAt:i}).where(M(u.comments.parentId,n.id)).run();return Ui(t,{type:"comment_deleted",resourceType:"comment",resourceId:n.id}),{deleted:!0}}async function ro(t,n){let o=t.db.select().from(u.comments).where(lt(M(u.comments.id,n.id),M(u.comments.isDeleted,!1))).get();if(!o)throw new F("Comment not found",{suggestion:"Check that the comment ID is correct"});if(o.parentId)throw new et("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(M(u.comments.id,n.id)).run(),Ui(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 of=R(()=>{Z();m()});import{z as _}from"zod";async function j(t,n,o,i){let e=Si[n];if(!e)throw Error(`Unknown operation: ${n}`);if(!i?.skipAuth){let f=Dn(n);In(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=Ii(t.appUrl,t.orgId,t.driveId,E.path);else if("to"in E)E.appUrl=Ii(t.appUrl,t.orgId,t.driveId,E.to)}return E}function en(){return Object.keys(Si)}function Pt(t){return Si[t]}var Si;var $i=R(()=>{zn();eu();Eu();fu();Nu();yu();wu();gu();Ou();Su();Xu();Mu();Yu();Hu();Bu();Vu();Ku();ju();ku();zu();qu();cu();tf();of();Si={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:xn,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:uu,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:Tu,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:Ru,schema:_.object({path:_.string().optional()})},stat:{description:"Get file metadata without reading content. Returns path, size, contentType, author, currentVersion, createdAt, modifiedAt, isDeleted, embeddingStatus.",handler:lu,schema:_.object({path:_.string()})},rm:{description:"Delete a file. Removes from S3, cleans up FTS5 index and vector embeddings. Returns { path, deleted }.",handler:Lu,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:Iu,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:Uu,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:$u,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:Pu,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:Gu,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:Qu,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:Ju,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:Wu,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:hu,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:pu,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:mu,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:bu,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:xu,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:au,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:to,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:no,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:oo,schema:_.object({id:_.string()})},"comment-update":{description:"Update a comment's body. Only the original author can update. Returns { id, body, updatedAt }.",handler:io,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:eo,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:ro,schema:_.object({id:_.string(),resolved:_.boolean()})}}});import{eq as z,and as Eo}from"drizzle-orm";function Ht(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 Sn(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 gt(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 Xi(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 Zt(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 Qt(t,n){if(!t.select({role:u.driveMembers.role}).from(u.driveMembers).where(Eo(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(Eo(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).run()}function Bt(t,n){if(!t.select({role:u.driveMembers.role}).from(u.driveMembers).where(Eo(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(Eo(z(u.driveMembers.driveId,n.driveId),z(u.driveMembers.userId,n.userId))).run()}function Ci(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 Pi=R(()=>{Z()});import{eq as Q,and as Jt,sql as ef}from"drizzle-orm";function Vt(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=Ht(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 K(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 $n(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 Wt(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 Kt(t,n){let o=t.select({role:u.orgMembers.role}).from(u.orgMembers).where(Jt(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:ef`count(*)`}).from(u.orgMembers).where(Jt(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(Jt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).run()}function pt(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(Jt(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:ef`count(*)`}).from(u.orgMembers).where(Jt(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(Jt(Q(u.driveMembers.driveId,r.id),Q(u.driveMembers.userId,n.userId))).run();t.delete(u.orgMembers).where(Jt(Q(u.orgMembers.orgId,n.orgId),Q(u.orgMembers.userId,n.userId))).run()}function jt(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 Mi=R(()=>{Z();Pi()});import{eq as rf}from"drizzle-orm";function Ef(t){let n=new Bun.CryptoHasher("sha256");return n.update(t),n.digest("hex")}function L_(){let t=new Uint8Array(32);return crypto.getRandomValues(t),`af_${Array.from(t,(o)=>o.toString(16).padStart(2,"0")).join("")}`}function g_(){return crypto.randomUUID()}function rt(t,n){let o=g_(),i=L_(),e=Ef(i),r=new Date;return t.insert(u.users).values({id:o,email:n.email,apiKeyHash:e,createdAt:r}).run(),Vt(t,{name:n.email.split("@")[0],userId:o,isPersonal:!0}),{user:{id:o,email:n.email},apiKey:i}}function Et(t,n){let o=Ef(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 rn(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 Fi=R(()=>{Z();Mi()});import{eq as Mt,and as vi}from"drizzle-orm";function d(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(vi(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(vi(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(vi(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 uf=R(()=>{Z();zn()});function Xn(t){let n=P();if(n.auth.apiKey){if(Et(t,n.auth.apiKey))return{apiKey:n.auth.apiKey}}console.error("[agent-fs] No local user found, creating one...");let o=rt(t,{email:"local@agent-fs.local"});return O("auth.apiKey",o.apiKey),console.error("[agent-fs] Local user created automatically."),{apiKey:o.apiKey}}var ff=R(()=>{Nn();Fi()});var Tf=R(()=>{Fi();Mi();Pi();zn();uf();ff()});var Af;var Nf=R(()=>{Af={name:"agent-fs",version:"0.7.0",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 b;var Yi=R(()=>{Nf();b=Af.version});var yf={};dt(yf,{LocalEmbeddingProvider:()=>Rf});import{join as I_}from"path";import{mkdirSync as O_,existsSync as U_}from"fs";class Rf{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=I_(V(),"models");if(!U_(o))O_(o,{recursive:!0});console.error("[agent-fs] Resolving local embedding model...");let i=await n(S_,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 S_="hf:nomic-ai/nomic-embed-text-v1.5-GGUF:Q8_0";var _f=R(()=>{Nn()});var Gi={};dt(Gi,{OpenAIEmbeddingProvider:()=>lf});import $_ from"openai";class lf{name="openai";dimensions=768;client;constructor(t){this.client=new $_({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 Hi=()=>{};var Zi={};dt(Zi,{GeminiEmbeddingProvider:()=>wf});import{GoogleGenAI as X_}from"@google/genai";class wf{name="gemini";dimensions=768;client;constructor(t){this.client=new X_({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 Qi=()=>{};async function Lf(t){switch(t.provider){case"local":{let{LocalEmbeddingProvider:n}=await Promise.resolve().then(() => (_f(),yf));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(() => (Hi(),Gi));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(() => (Qi(),Zi));return new n(t.apiKey)}default:throw Error(`Unknown embedding provider: ${t.provider}`)}}async function En(t){if(process.env.OPENAI_API_KEY)try{let{OpenAIEmbeddingProvider:n}=await Promise.resolve().then(() => (Hi(),Gi));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(() => (Qi(),Zi));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 Lf(t)}catch(n){console.error("[agent-fs] Failed to create embedding provider from config:",n)}if(t?.provider==="local")try{return await Lf(t)}catch(n){console.error("[agent-fs] Failed to load local embedding provider:",n)}return null}var Df,gf,If=(t)=>typeof t==="string"?{...gf,name:t}:{...gf,...t};var uo=R(()=>{Df=Symbol("Let zodToJsonSchema decide on which parser to use"),gf={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 Of=(t)=>{let n=If(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 Bi=R(()=>{uo()});function Ji(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,Ji(t,n,i,e)}var fo=(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 G(t){if(t.target!=="openAi")return{};let n=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?fo(n,t.currentPath):n.join("/")}}var a=()=>{};import{ZodFirstPartyTypeKind as C_}from"zod/v3";function Uf(t,n){let o={type:"array"};if(t.type?._def&&t.type?._def?.typeName!==C_.ZodAny)o.items=L(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 Vi=R(()=>{B()});function Sf(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 Wi=()=>{};function $f(){return{type:"boolean"}}function To(t,n){return L(t.type._def,n)}var No=R(()=>{B()});var Xf=(t,n)=>{return L(t.innerType._def,n)};var Ki=R(()=>{B()});function pi(t,n,o){let i=o??n.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((e,r)=>pi(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 P_(t,n)}}var P_=(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 ji=()=>{};function Cf(t,n){return{...L(t.innerType._def,n),default:t.defaultValue()}}var hi=R(()=>{B()});function Pf(t,n){return n.effectStrategy==="input"?L(t.schema._def,n):G(n)}var ki=R(()=>{B();a()});function Mf(t){return{type:"string",enum:Array.from(t.values)}}function Ff(t,n){let o=[L(t.left._def,{...n,currentPath:[...n.currentPath,"allOf","0"]}),L(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(M_(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 M_=(t)=>{if("type"in t&&t.type==="string")return!1;return"allOf"in t};var mi=R(()=>{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 Ao(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":ft(o,"email",i.message,n);break;case"format:idn-email":ft(o,"idn-email",i.message,n);break;case"pattern:zod":k(o,ut.email,i.message,n);break}break;case"url":ft(o,"uri",i.message,n);break;case"uuid":ft(o,"uuid",i.message,n);break;case"regex":k(o,i.regex,i.message,n);break;case"cuid":k(o,ut.cuid,i.message,n);break;case"cuid2":k(o,ut.cuid2,i.message,n);break;case"startsWith":k(o,RegExp(`^${di(i.value,n)}`),i.message,n);break;case"endsWith":k(o,RegExp(`${di(i.value,n)}$`),i.message,n);break;case"datetime":ft(o,"date-time",i.message,n);break;case"date":ft(o,"date",i.message,n);break;case"time":ft(o,"time",i.message,n);break;case"duration":ft(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(di(i.value,n)),i.message,n);break}case"ip":{if(i.version!=="v6")ft(o,"ipv4",i.message,n);if(i.version!=="v4")ft(o,"ipv6",i.message,n);break}case"base64url":k(o,ut.base64url,i.message,n);break;case"jwt":k(o,ut.jwt,i.message,n);break;case"cidr":{if(i.version!=="v6")k(o,ut.ipv4Cidr,i.message,n);if(i.version!=="v4")k(o,ut.ipv6Cidr,i.message,n);break}case"emoji":k(o,ut.emoji(),i.message,n);break;case"ulid":{k(o,ut.ulid,i.message,n);break}case"base64":{switch(n.base64Strategy){case"format:binary":{ft(o,"binary",i.message,n);break}case"contentEncoding:base64":{X(o,"contentEncoding","base64",i.message,n);break}case"pattern:zod":{k(o,ut.base64,i.message,n);break}}break}case"nanoid":k(o,ut.nanoid,i.message,n);case"toLowerCase":case"toUpperCase":case"trim":break;default:((e)=>{})(i)}return o}function di(t,n){return n.patternStrategy==="escape"?v_(t):t}function v_(t){let n="";for(let o=0;o<t.length;o++){if(!F_.has(t[o]))n+="\\";n+=t[o]}return n}function ft(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:Yf(n,i),...o&&i.errorMessages&&{errorMessage:{pattern:o}}})}else X(t,"pattern",Yf(n,i),o,i)}function Yf(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 N of f){let A=t.db.select().from(u.contentChunks).where(Ci(u.contentChunks.id,N.chunk_id)).get();if(!A||A.driveId!==t.driveId)continue;if(l.has(A.filePath))continue;l.add(A.filePath);let w=t.db.select().from(u.files).where(L_(Ci(u.files.path,A.filePath),Ci(u.files.driveId,t.driveId))).get();T.push({path:A.filePath,snippet:A.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=R(()=>{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),N=await Promise.allSettled(l.map(async(A)=>{let w=I(t.orgId,t.driveId,A.path),g=await t.s3.getObject(w),O=g.contentType??K(A.path),D=Pt(g.body,O);if(D===null)return Fn(t,A.path),"skipped";if(wt(t.db,{path:A.path,driveId:t.driveId,content:D}),t.embeddingProvider)return await Di(t.db,t.embeddingProvider,{path:A.path,driveId:t.driveId,content:D}),"reindexed";return"skipped"}));for(let A of N)if(A.status==="fulfilled")if(A.value==="reindexed")e++;else E++;else console.error("Reindex failed:",A.reason),r++}return{reindexed:e,failed:r,skipped:E}}var tf=R(()=>{G();W();Mn();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 N=l.split("/").filter(Boolean);if(N.length===0)continue;if(n.depth!==void 0&&N.length>n.depth)continue;let A=f;for(let w=0;w<N.length;w++){let g=N[w],O=w===N.length-1,D=!O||l.endsWith("/");if(D&&!O){let C=A.find((Z)=>Z.name===g&&Z.type==="directory");if(!C)C={name:g,type:"directory",children:[]},A.push(C);if(!C.children)C.children=[];A=C.children}else if(D&&O){let C=A.find((Z)=>Z.name===g&&Z.type==="directory");if(!C)C={name:g,type:"directory",children:[]},A.push(C)}else{let C=o+N.slice(0,w+1).join("/"),Z=E.get(C),_n={name:g,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;A.push(_n)}}}return{tree:f}}var ef=R(()=>{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 N=l.key.slice(i.length);if(!N||N.endsWith("/"))continue;if(f.test(N)){let A=o+N,w=E.get(A);T.push({path:A,size:w?.size??l.size,modifiedAt:w?.modifiedAt??l.lastModified})}}return{matches:T}}var uf=R(()=>{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 F(`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=R(()=>{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 M,and as yt,sql as Mi,desc as lf}from"drizzle-orm";function Fi(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(M(u.comments.id,n.parentId),M(u.comments.isDeleted,!1))).get();if(!E)throw new F("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(M(u.fileVersions.path,e),M(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(),Fi(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=[M(u.comments.driveId,t.driveId),M(u.comments.isDeleted,!1)];if(n.path)o.push(M(u.comments.path,n.path));if(n.parentId)o.push(M(u.comments.parentId,n.parentId));else if(n.parentId===void 0&&!n.resolved)o.push(Mi`${u.comments.parentId} IS NULL`),o.push(M(u.comments.resolved,!1));else if(n.parentId===void 0&&n.resolved)o.push(Mi`${u.comments.parentId} IS NULL`);if(n.orgId)o.push(M(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(M(u.comments.parentId,f.id),M(u.comments.isDeleted,!1))).orderBy(u.comments.createdAt).all().map((N)=>ro({...N,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(M(u.comments.id,n.id),M(u.comments.isDeleted,!1))).get();if(!o)throw new F("Comment not found",{suggestion:"Check that the comment ID is correct"});let i=t.db.select({count:Mi`count(*)`}).from(u.comments).where(yt(M(u.comments.parentId,o.id),M(u.comments.isDeleted,!1))).get(),e=ro({...o,replyCount:i?.count??0}),E=t.db.select().from(u.comments).where(yt(M(u.comments.parentId,n.id),M(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(M(u.comments.id,n.id),M(u.comments.isDeleted,!1))).get();if(!o)throw new F("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(M(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(M(u.comments.id,n.id),M(u.comments.isDeleted,!1))).get();if(!o)throw new F("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(M(u.comments.id,n.id)).run(),!o.parentId)t.db.update(u.comments).set({isDeleted:!0,updatedAt:i}).where(M(u.comments.parentId,n.id)).run();return Fi(t,{type:"comment_deleted",resourceType:"comment",resourceId:n.id}),{deleted:!0}}async function No(t,n){let o=t.db.select().from(u.comments).where(yt(M(u.comments.id,n.id),M(u.comments.isDeleted,!1))).get();if(!o)throw new F("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(M(u.comments.id,n.id)).run(),Fi(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 Nf=R(()=>{G();m()});import{z as _}from"zod";async function k(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 Mt(t){return vi[t]}var vi;var Yi=R(()=>{an();Ru();_u();yu();gu();Iu();$u();Cu();Fu();Yu();Hu();Ju();Wu();pu();ku();mu();bu();su();xu();tf();ef();uf();Tf();Nf();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:Au,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:Lu,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:Mu,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:du,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:qu,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:No,schema:_.object({id:_.string(),resolved:_.boolean()})}}});import{eq as z,and as Ro}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(Ro(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(Ro(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(Ro(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(Ro(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=R(()=>{G()});import{eq as Q,and as Wt,sql as Rf}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:Rf`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:Rf`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 kt(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=R(()=>{G();Zi()});import{eq as Af}from"drizzle-orm";function _f(t){let n=new Bun.CryptoHasher("sha256");return n.update(t),n.digest("hex")}function M_(){let t=new Uint8Array(32);return crypto.getRandomValues(t),`af_${Array.from(t,(o)=>o.toString(16).padStart(2,"0")).join("")}`}function F_(){return crypto.randomUUID()}function Et(t,n){let o=F_(),i=M_(),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(Af(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(Af(u.users.email,n)).get();if(!o)return null;return{id:o.id,email:o.email}}var Ji=R(()=>{G();Qi()});import{eq as Ft,and as Bi}from"drizzle-orm";function b(t,n){if(n.driveId){let r=t.select().from(u.drives).where(Ft(u.drives.id,n.driveId)).get();if(!r)throw Error(`Drive not found: ${n.driveId}`);let E=At(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(Ft(u.drives.orgId,n.orgId),Ft(u.drives.isDefault,!0))).get();if(!r)throw Error(`No default drive for org: ${n.orgId}`);let E=At(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,Ft(u.orgMembers.orgId,u.orgs.id)).where(Bi(Ft(u.orgMembers.userId,n.userId),Ft(u.orgs.isPersonal,!0))).get();if(!o)throw Error("No personal org found for user");let i=t.select().from(u.drives).where(Bi(Ft(u.drives.orgId,o.orgId),Ft(u.drives.isDefault,!0))).get();if(!i)throw Error("No default drive found");let e=At(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=R(()=>{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=R(()=>{wn();Ji()});var Lf=R(()=>{Ji();Qi();Zi();an();wf();yf()});var Df;var gf=R(()=>{Df={name:"agent-fs",version:"0.7.2",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 q;var Vi=R(()=>{gf();q=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=R(()=>{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,Mf=(t)=>typeof t==="string"?{...Cf,name:t}:{...Cf,...t};var Ao=R(()=>{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 Ff=(t)=>{let n=Mf(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=R(()=>{Ao()});function ki(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,ki(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=L(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 di=R(()=>{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 L(t.type._def,n)}var yo=R(()=>{B()});var Hf=(t,n)=>{return L(t.innerType._def,n)};var zi=R(()=>{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 qi=()=>{};function Zf(t,n){return{...L(t.innerType._def,n),default:t.defaultValue()}}var si=R(()=>{B()});function Qf(t,n){return n.effectStrategy==="input"?L(t.schema._def,n):H(n)}var ci=R(()=>{B();tt()});function Jf(t){return{type:"string",enum:Array.from(t.values)}}function Bf(t,n){let o=[L(t.left._def,{...n,currentPath:[...n.currentPath,"allOf","0"]}),L(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=R(()=>{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 Lo(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":d(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":d(o,i.regex,i.message,n);break;case"cuid":d(o,ft.cuid,i.message,n);break;case"cuid2":d(o,ft.cuid2,i.message,n);break;case"startsWith":d(o,RegExp(`^${te(i.value,n)}`),i.message,n);break;case"endsWith":d(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":{d(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":d(o,ft.base64url,i.message,n);break;case"jwt":d(o,ft.jwt,i.message,n);break;case"cidr":{if(i.version!=="v6")d(o,ft.ipv4Cidr,i.message,n);if(i.version!=="v4")d(o,ft.ipv6Cidr,i.message,n);break}case"emoji":d(o,ft.emoji(),i.message,n);break;case"ulid":{d(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":{d(o,ft.base64,i.message,n);break}}break}case"nanoid":d(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 d(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
|
|
176
|
-
]`;continue}if(e+=i[T],i[T]==="\\")r=!0;else if(E&&i[T]==="]")E=!1;else if(!E&&i[T]==="[")E=!0}try{new RegExp(e)}catch{return console.warn(`Could not convert regex pattern at ${n.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return e}var zi=void 0,ut,F_;var Ro=R(()=>{ut={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(zi===void 0)zi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return zi},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};F_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Cn}from"zod/v3";function yo(t,n){if(n.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(n.target==="openApi3"&&t.keyType?._def.typeName===Cn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,e)=>({...i,[e]:L(t.valueType._def,{...n,currentPath:[...n.currentPath,"properties",e]})??G(n)}),{}),additionalProperties:n.rejectedAdditionalProperties};let o={type:"object",additionalProperties:L(t.valueType._def,{...n,currentPath:[...n.currentPath,"additionalProperties"]})??n.allowedAdditionalProperties};if(n.target==="openApi3")return o;if(t.keyType?._def.typeName===Cn.ZodString&&t.keyType._def.checks?.length){let{type:i,...e}=Ao(t.keyType._def,n);return{...o,propertyNames:e}}else if(t.keyType?._def.typeName===Cn.ZodEnum)return{...o,propertyNames:{enum:t.keyType._def.values}};else if(t.keyType?._def.typeName===Cn.ZodBranded&&t.keyType._def.type._def.typeName===Cn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:i,...e}=To(t.keyType._def,n);return{...o,propertyNames:e}}return o}var _o=R(()=>{B();Ro();No();a()});function Gf(t,n){if(n.mapStrategy==="record")return yo(t,n);let o=L(t.keyType._def,{...n,currentPath:[...n.currentPath,"items","items","0"]})||G(n),i=L(t.valueType._def,{...n,currentPath:[...n.currentPath,"items","items","1"]})||G(n);return{type:"array",maxItems:125,items:{type:"array",items:[o,i],minItems:2,maxItems:2}}}var bi=R(()=>{B();_o();a()});function Hf(t){let n=t.values,i=Object.keys(t.values).filter((r)=>{return typeof n[n[r]]!=="number"}).map((r)=>n[r]),e=Array.from(new Set(i.map((r)=>typeof r)));return{type:e.length===1?e[0]==="string"?"string":"number":["string","number"],enum:i}}function Zf(t){return t.target==="openAi"?void 0:{not:G({...t,currentPath:[...t.currentPath,"not"]})}}var qi=R(()=>{a()});function Qf(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}function Jf(t,n){if(n.target==="openApi3")return Bf(t,n);let o=t.options instanceof Map?Array.from(t.options.values()):t.options;if(o.every((i)=>(i._def.typeName in Pn)&&(!i._def.checks||!i._def.checks.length))){let i=o.reduce((e,r)=>{let E=Pn[r._def.typeName];return E&&!e.includes(E)?[...e,E]:e},[]);return{type:i.length>1?i:i[0]}}else if(o.every((i)=>i._def.typeName==="ZodLiteral"&&!i.description)){let i=o.reduce((e,r)=>{let E=typeof r._def.value;switch(E){case"string":case"number":case"boolean":return[...e,E];case"bigint":return[...e,"integer"];case"object":if(r._def.value===null)return[...e,"null"];case"symbol":case"undefined":case"function":default:return e}},[]);if(i.length===o.length){let e=i.filter((r,E,f)=>f.indexOf(r)===E);return{type:e.length>1?e:e[0],enum:o.reduce((r,E)=>{return r.includes(E._def.value)?r:[...r,E._def.value]},[])}}}else if(o.every((i)=>i._def.typeName==="ZodEnum"))return{type:"string",enum:o.reduce((i,e)=>[...i,...e._def.values.filter((r)=>!i.includes(r))],[])};return Bf(t,n)}var Pn,Bf=(t,n)=>{let o=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((i,e)=>L(i._def,{...n,currentPath:[...n.currentPath,"anyOf",`${e}`]})).filter((i)=>!!i&&(!n.strictUnions||typeof i==="object"&&Object.keys(i).length>0));return o.length?{anyOf:o}:void 0};var lo=R(()=>{B();Pn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"}});function Vf(t,n){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length)){if(n.target==="openApi3")return{type:Pn[t.innerType._def.typeName],nullable:!0};return{type:[Pn[t.innerType._def.typeName],"null"]}}if(n.target==="openApi3"){let i=L(t.innerType._def,{...n,currentPath:[...n.currentPath]});if(i&&"$ref"in i)return{allOf:[i],nullable:!0};return i&&{...i,nullable:!0}}let o=L(t.innerType._def,{...n,currentPath:[...n.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}var si=R(()=>{B();lo()});function Wf(t,n){let o={type:"number"};if(!t.checks)return o;for(let i of t.checks)switch(i.kind){case"int":o.type="integer",Ji(o,"type",i.message,n);break;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 xi=()=>{};function Kf(t,n){let o=n.target==="openAi",i={type:"object",properties:{}},e=[],r=t.shape();for(let f in r){let T=r[f];if(T===void 0||T._def===void 0)continue;let N=G_(T);if(N&&o){if(T._def.typeName==="ZodOptional")T=T._def.innerType;if(!T.isNullable())T=T.nullable();N=!1}let A=L(T._def,{...n,currentPath:[...n.currentPath,"properties",f],propertyPath:[...n.currentPath,"properties",f]});if(A===void 0)continue;if(i.properties[f]=A,!N)e.push(f)}if(e.length)i.required=e;let E=Y_(t,n);if(E!==void 0)i.additionalProperties=E;return i}function Y_(t,n){if(t.catchall._def.typeName!=="ZodNever")return L(t.catchall._def,{...n,currentPath:[...n.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return n.allowedAdditionalProperties;case"strict":return n.rejectedAdditionalProperties;case"strip":return n.removeAdditionalStrategy==="strict"?n.allowedAdditionalProperties:n.rejectedAdditionalProperties}}function G_(t){try{return t.isOptional()}catch{return!0}}var ci=R(()=>{B()});var pf=(t,n)=>{if(n.currentPath.toString()===n.propertyPath?.toString())return L(t.innerType._def,n);let o=L(t.innerType._def,{...n,currentPath:[...n.currentPath,"anyOf","1"]});return o?{anyOf:[{not:G(n)},o]}:G(n)};var ai=R(()=>{B();a()});var jf=(t,n)=>{if(n.pipeStrategy==="input")return L(t.in._def,n);else if(n.pipeStrategy==="output")return L(t.out._def,n);let o=L(t.in._def,{...n,currentPath:[...n.currentPath,"allOf","0"]}),i=L(t.out._def,{...n,currentPath:[...n.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,i].filter((e)=>e!==void 0)}};var te=R(()=>{B()});function hf(t,n){return L(t.type._def,n)}var ne=R(()=>{B()});function kf(t,n){let i={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...n,currentPath:[...n.currentPath,"items"]})};if(t.minSize)X(i,"minItems",t.minSize.value,t.minSize.message,n);if(t.maxSize)X(i,"maxItems",t.maxSize.value,t.maxSize.message,n);return i}var oe=R(()=>{B()});function mf(t,n){if(t.rest)return{type:"array",minItems:t.items.length,items:t.items.map((o,i)=>L(o._def,{...n,currentPath:[...n.currentPath,"items",`${i}`]})).reduce((o,i)=>i===void 0?o:[...o,i],[]),additionalItems:L(t.rest._def,{...n,currentPath:[...n.currentPath,"additionalItems"]})};else return{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((o,i)=>L(o._def,{...n,currentPath:[...n.currentPath,"items",`${i}`]})).reduce((o,i)=>i===void 0?o:[...o,i],[])}}var ie=R(()=>{B()});function zf(t){return{not:G(t)}}var ee=R(()=>{a()});function df(t){return G(t)}var re=R(()=>{a()});var bf=(t,n)=>{return L(t.innerType._def,n)};var Ee=R(()=>{B()});import{ZodFirstPartyTypeKind as $}from"zod/v3";var qf=(t,n,o)=>{switch(n){case $.ZodString:return Ao(t,o);case $.ZodNumber:return Wf(t,o);case $.ZodObject:return Kf(t,o);case $.ZodBigInt:return Sf(t,o);case $.ZodBoolean:return $f();case $.ZodDate:return pi(t,o);case $.ZodUndefined:return zf(o);case $.ZodNull:return Qf(o);case $.ZodArray:return Uf(t,o);case $.ZodUnion:case $.ZodDiscriminatedUnion:return Jf(t,o);case $.ZodIntersection:return Ff(t,o);case $.ZodTuple:return mf(t,o);case $.ZodRecord:return yo(t,o);case $.ZodLiteral:return vf(t,o);case $.ZodEnum:return Mf(t);case $.ZodNativeEnum:return Hf(t);case $.ZodNullable:return Vf(t,o);case $.ZodOptional:return pf(t,o);case $.ZodMap:return Gf(t,o);case $.ZodSet:return kf(t,o);case $.ZodLazy:return()=>t.getter()._def;case $.ZodPromise:return hf(t,o);case $.ZodNaN:case $.ZodNever:return Zf(o);case $.ZodEffects:return Pf(t,o);case $.ZodAny:return G(o);case $.ZodUnknown:return df(o);case $.ZodDefault:return Cf(t,o);case $.ZodBranded:return To(t,o);case $.ZodReadonly:return bf(t,o);case $.ZodCatch:return Xf(t,o);case $.ZodPipeline:return jf(t,o);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return((i)=>{return})(n)}};var ue=R(()=>{a();Vi();Wi();No();Ki();ji();hi();ki();mi();bi();qi();si();xi();ci();ai();te();ne();_o();oe();Ro();ie();ee();lo();re();Ee()});function L(t,n,o=!1){let i=n.seen.get(t);if(n.override){let f=n.override?.(t,n,i,o);if(f!==Df)return f}if(i&&!o){let f=H_(i,n);if(f!==void 0)return f}let e={def:t,path:n.currentPath,jsonSchema:void 0};n.seen.set(t,e);let r=qf(t,t.typeName,n),E=typeof r==="function"?L(r(),n):r;if(E)Z_(t,n,E);if(n.postProcess){let f=n.postProcess(E,t,n);return e.jsonSchema=E,f}return e.jsonSchema=E,E}var H_=(t,n)=>{switch(n.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:fo(n.currentPath,t.path)};case"none":case"seen":{if(t.path.length<n.currentPath.length&&t.path.every((o,i)=>n.currentPath[i]===o))return console.warn(`Recursive reference detected at ${n.currentPath.join("/")}! Defaulting to any`),G(n);return n.$refStrategy==="seen"?G(n):void 0}}},Z_=(t,n,o)=>{if(t.description){if(o.description=t.description,n.markdownDescription)o.markdownDescription=t.description}return o};var B=R(()=>{uo();ue();a()});var sf=()=>{};var fe=(t,n)=>{let o=Of(n),i=typeof n==="object"&&n.definitions?Object.entries(n.definitions).reduce((T,[N,A])=>({...T,[N]:L(A._def,{...o,currentPath:[...o.basePath,o.definitionPath,N]},!0)??G(o)}),{}):void 0,e=typeof n==="string"?n:n?.nameStrategy==="title"?void 0:n?.name,r=L(t._def,e===void 0?o:{...o,currentPath:[...o.basePath,o.definitionPath,e]},!1)??G(o),E=typeof n==="object"&&n.name!==void 0&&n.nameStrategy==="title"?n.name:void 0;if(E!==void 0)r.title=E;if(o.flags.hasReferencedOpenAiAnyType){if(!i)i={};if(!i[o.openAiAnyTypeName])i[o.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:o.$refStrategy==="relative"?"1":[...o.basePath,o.definitionPath,o.openAiAnyTypeName].join("/")}}}let f=e===void 0?i?{...r,[o.definitionPath]:i}:r:{$ref:[...o.$refStrategy==="relative"?[]:o.basePath,o.definitionPath,e].join("/"),[o.definitionPath]:{...i,[e]:r}};if(o.target==="jsonSchema7")f.$schema="http://json-schema.org/draft-07/schema#";else if(o.target==="jsonSchema2019-09"||o.target==="openAi")f.$schema="https://json-schema.org/draft/2019-09/schema#";if(o.target==="openAi"&&(("anyOf"in f)||("oneOf"in f)||("allOf"in f)||("type"in f)&&Array.isArray(f.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return f};var Te=R(()=>{B();Bi();a()});var xf=R(()=>{Te();uo();Bi();B();sf();a();Vi();Wi();No();Ki();ji();hi();ki();mi();bi();qi();si();xi();ci();ai();te();ne();Ee();_o();oe();Ro();ie();ee();lo();re();ue();Te()});function wo(){let t=en(),n={},o={};for(let e of t){let r=Pt(e),E=fe(r.schema,{target:"openApi3"}),{$schema:f,...T}=E;n[e]=T,o[e]=r.description}let i=t.map((e)=>({type:"object",title:e,description:o[e],required:["op",...n[e].required||[]],properties:{op:{type:"string",const:e},driveId:{type:"string",description:"Target drive ID (optional, uses default drive)"},...n[e].properties||{}},additionalProperties:!1}));return{openapi:"3.1.0",info:{title:"agent-fs API",version:b,description:"A persistent, searchable filesystem for AI agents. agent-fs is to files what agentmail is to email.",license:{name:"MIT",url:"https://github.com/desplega-ai/agent-fs/blob/main/LICENSE"}},servers:[{url:"http://localhost:7433",description:"Local development server"}],paths:{"/health":{get:{summary:"Health check",operationId:"health",tags:["System"],security:[],responses:{"200":{description:"Server is healthy",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",const:!0},version:{type:"string"}},required:["ok","version"]}}}}}}},"/auth/register":{post:{summary:"Register a new user",operationId:"register",tags:["Auth"],security:[],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",format:"email"}},required:["email"]}}}},responses:{"200":{description:"User registered",content:{"application/json":{schema:{type:"object",properties:{userId:{type:"string"},orgId:{type:"string"},driveId:{type:"string"},apiKey:{type:"string"}},required:["userId","orgId","driveId","apiKey"]}}}}}}},"/auth/me":{get:{summary:"Get current user info",operationId:"me",tags:["Auth"],responses:{"200":{description:"Current user",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},createdAt:{type:"string",format:"date-time"}},required:["id","email","createdAt"]}}}}}}},"/orgs/{orgId}/ops":{post:{summary:"Dispatch a file operation",operationId:"dispatchOp",tags:["Operations"],description:"All file operations go through this single endpoint. The `op` field determines which operation to execute.",parameters:[{name:"orgId",in:"path",required:!0,schema:{type:"string"},description:"Organization ID"}],requestBody:{required:!0,content:{"application/json":{schema:{oneOf:i,discriminator:{propertyName:"op"}}}}},responses:{"200":{description:"Operation result (varies by op)",content:{"application/json":{schema:{type:"object",description:"Response shape depends on the operation. See each op's description for details."}}}},"400":{description:"Validation error",content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}},"401":{description:"Unauthorized",content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}},"403":{description:"Permission denied (RBAC)",content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}},"404":{description:"File or resource not found",content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}}}}}},components:{securitySchemes:{bearerAuth:{type:"http",scheme:"bearer",description:"API key obtained from /auth/register"}},schemas:{Error:{type:"object",properties:{error:{type:"string"},message:{type:"string"}},required:["error","message"]}}},security:[{bearerAuth:[]}]}}var cf=R(()=>{xf();$i();Yi()});var af={};dt(af,{writeRaw:()=>Lt,write:()=>xn,updateOrgMemberRole:()=>Kt,updateDriveMemberRole:()=>Qt,setDriveMember:()=>Ci,setConfigValue:()=>O,setConfig:()=>Me,schema:()=>u,resolveContext:()=>d,removeOrgMember:()=>pt,removeDriveMember:()=>Bt,listUserOrgs:()=>K,listOrgMembers:()=>Wt,listDrivesForUser:()=>gt,listDrives:()=>Sn,listDriveMembers:()=>Zt,inviteToOrg:()=>jt,getUserDriveRole:()=>Rt,getUserByEmail:()=>rn,getUserByApiKey:()=>Et,getS3Key:()=>S,getRequiredRole:()=>Dn,getRegisteredOps:()=>en,getOrg:()=>$n,getOpDefinition:()=>Pt,getNextVersion:()=>dn,getHome:()=>V,getHeadVersionRow:()=>xt,getHeadContentHash:()=>bn,getDrive:()=>Xi,getDbPath:()=>Yt,getConfigPath:()=>s,getConfig:()=>P,generateOpenAPISpec:()=>wo,ensureLocalUser:()=>Xn,dispatchOp:()=>j,createVersion:()=>p,createUser:()=>rt,createOrg:()=>Vt,createEmbeddingProviderFromEnv:()=>En,createDrive:()=>Ht,createDatabase:()=>Ut,commentUpdate:()=>io,commentResolve:()=>ro,commentList:()=>no,commentGet:()=>oo,commentDelete:()=>eo,commentAdd:()=>to,checkPermission:()=>In,assertExpectedVersion:()=>h,ValidationError:()=>et,VERSION:()=>b,PermissionDeniedError:()=>ot,NotFoundError:()=>F,IndexingInProgressError:()=>gn,EditConflictError:()=>it,AgentS3Client:()=>$t,AgentFSError:()=>At});var Y=R(()=>{Z();Nn();sE();m();$i();W();Tf();Yi();cf()});var go={};dt(go,{stopDaemon:()=>Nl,startDaemon:()=>Tl,daemonStatus:()=>Al});import{spawn as rl}from"child_process";import{readFileSync as Re,writeFileSync as El,unlinkSync as Lo,existsSync as Fn,openSync as ul}from"fs";import{join as ye}from"path";function _e(){return ye(V(),"agent-fs.pid")}function fl(){return ye(V(),"agent-fs.log")}function ET(){return ye(V(),"agent-fs.sock")}function Tl(){let t=_e();if(Fn(t)){let r=parseInt(Re(t,"utf-8").trim());try{process.kill(r,0),console.log(`Daemon already running (PID: ${r})`);return}catch{Lo(t);let E=ET();if(Fn(E))try{Lo(E)}catch{}}}let n=fl(),o=ul(n,"a"),i=process.argv[1];if(!i)throw Error("Cannot determine entry script (process.argv[1] is empty). Daemon start aborted.");let e=rl(process.execPath,[i,"server"],{detached:!0,stdio:["ignore",o,o]});if(e.unref(),e.pid)El(t,String(e.pid)),console.log(`Daemon started (PID: ${e.pid})`),console.log(`Logs: ${n}`)}function Nl(){let t=_e();if(!Fn(t)){console.log("Daemon is not running");return}let n=parseInt(Re(t,"utf-8").trim());try{process.kill(n,"SIGTERM"),console.log(`Daemon stopped (PID: ${n})`)}catch{console.log(`Process ${n} not found (already stopped)`)}Lo(t);let o=ET();if(Fn(o))try{Lo(o)}catch{}}function Al(){let t=_e();if(!Fn(t))return{running:!1};let n=parseInt(Re(t,"utf-8").trim());try{return process.kill(n,0),{running:!0,pid:n}}catch{return{running:!1}}}var Do=R(()=>{Y()});var sl={};import{Server as jl}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as hl}from"@modelcontextprotocol/sdk/server/stdio.js";import{Client as kl}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ml}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ListToolsRequestSchema as zl,CallToolRequestSchema as dl}from"@modelcontextprotocol/sdk/types.js";var vn,ge,YT,bl,De,Ie,ql;var GT=R(async()=>{Y();vn=P(),ge=process.env.AGENT_FS_API_URL??vn.apiUrl??`http://${vn.server.host}:${vn.server.port}`,YT=process.env.AGENT_FS_API_KEY??vn.apiKey??vn.auth?.apiKey;if(!YT)console.error("Error: No API key. Register with `agent-fs auth register` or set AGENT_FS_API_KEY."),process.exit(1);bl=new ml(new URL(`${ge}/mcp`),{requestInit:{headers:{Authorization:`Bearer ${YT}`}}}),De=new kl({name:"agent-fs-proxy",version:b});try{await De.connect(bl)}catch(t){console.error(`Cannot connect to agent-fs at ${ge}.
|
|
177
|
-
Start a daemon with \`agent-fs daemon start\` or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1)}Ie=new jl({name:"agent-fs",version:b},{capabilities:{tools:{}}});Ie.setRequestHandler(zl,async()=>{return await De.listTools()});Ie.setRequestHandler(dl,async(t)=>{return await De.callTool(t.params)});ql=new hl;await Ie.connect(ql);console.error("[agent-fs] MCP proxy connected to "+ge)});import{z as HT}from"zod";function ZT(t,n){let o=en();for(let i of o){let e=Pt(i);if(!e)continue;t.tool(i,e.description,e.schema instanceof HT.ZodObject?e.schema.shape:{params:HT.any()},async(r,E)=>{let f=n(E),T=await j(f,i,r);return{content:[{type:"text",text:JSON.stringify(T,null,2)}]}})}}var QT=R(()=>{Y()});import{McpServer as xl}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as vt}from"zod";function BT(t){let{db:n,s3:o,embeddingProvider:i,appUrl:e}=t,r=new xl({name:"agent-fs",version:b}),E=(f)=>{let T=f.authInfo;if(!T?.extra?.user)throw Error("No auth context \u2014 MCP must be accessed through the HTTP server");let N=T.extra.user,A=d(n,{userId:N.id});return{db:n,s3:o,orgId:A.orgId,driveId:A.driveId,userId:N.id,embeddingProvider:i,appUrl:e}};return ZT(r,E),r.tool("health","Check agent-fs system health: database, S3, embeddings, version.",{},async(f,T)=>{let N={version:b};try{let A=E(T),y=await j(A,"ls",{path:"/"},{skipAuth:!0});N.database={ok:!0,rootEntries:y.entries?.length??0}}catch(A){N.database={ok:!1,error:A.message}}try{await o.listObjects("",{delimiter:"/"}),N.s3={ok:!0}}catch(A){N.s3={ok:!1,error:A.message}}return N.embeddings={configured:!!i},{content:[{type:"text",text:JSON.stringify(N,null,2)}]}}),r.tool("whoami","Get current user identity, org memberships, and drive roles.",{},async(f,T)=>{let N=E(T),A=N.userId,l=K(n,A).map((D)=>{let C=Sn(n,D.id);return{orgId:D.id,orgName:D.name,drives:C.map((H)=>({driveId:H.id,driveName:H.name,role:Rt(n,A,H.id)}))}}),g=T.authInfo?.extra?.user?.email,I={userId:A,...g?{email:g}:{},activeOrg:N.orgId,activeDrive:N.driveId,memberships:l};return{content:[{type:"text",text:JSON.stringify(I,null,2)}]}}),r.tool("member-list","List members of the current org, or a specific drive if driveId is provided.",{driveId:vt.string().optional().describe("Drive ID to list members for. Omit for org members.")},async(f,T)=>{let N=E(T),A=f.driveId?Zt(n,f.driveId):Wt(n,N.orgId);return{content:[{type:"text",text:JSON.stringify({members:A},null,2)}]}}),r.tool("member-invite","Invite a user to the current org by email. The user must already have an agent-fs account.",{email:vt.string().describe("Email of the user to invite"),role:vt.enum(["viewer","editor","admin"]).describe("Role to assign")},async(f,T)=>{let N=E(T);try{return jt(n,{orgId:N.orgId,email:f.email,role:f.role}),{content:[{type:"text",text:JSON.stringify({ok:!0,invited:f.email,role:f.role},null,2)}]}}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A.message},null,2)}],isError:!0}}}),r.tool("member-update-role","Update a member's role in the current org or a specific drive.",{email:vt.string().describe("Email of the member"),role:vt.enum(["viewer","editor","admin"]).describe("New role"),driveId:vt.string().optional().describe("Drive ID to update role for. Omit for org role.")},async(f,T)=>{let N=E(T);try{let A=rn(n,f.email);if(!A)throw Error(`User with email ${f.email} not found`);if(f.driveId)Qt(n,{driveId:f.driveId,userId:A.id,role:f.role});else Kt(n,{orgId:N.orgId,userId:A.id,role:f.role});return{content:[{type:"text",text:JSON.stringify({ok:!0,email:f.email,role:f.role},null,2)}]}}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A.message},null,2)}],isError:!0}}}),r.tool("member-remove","Remove a member from the current org (cascades to all drives) or from a specific drive only.",{email:vt.string().describe("Email of the member to remove"),driveId:vt.string().optional().describe("Drive ID to remove from. Omit to remove from org.")},async(f,T)=>{let N=E(T);try{let A=rn(n,f.email);if(!A)throw Error(`User with email ${f.email} not found`);if(f.driveId)Bt(n,{driveId:f.driveId,userId:A.id});else pt(n,{orgId:N.orgId,userId:A.id});return{content:[{type:"text",text:JSON.stringify({ok:!0,removed:f.email},null,2)}]}}catch(A){return{content:[{type:"text",text:JSON.stringify({error:A.message},null,2)}],isError:!0}}}),r}var JT=R(()=>{Y();QT()});function VT(t){return async(n,o)=>{let i=new URL(n.req.url).pathname;if(cl.some((f)=>i===f||i.startsWith(f)))return o();let e=n.req.header("Authorization");if(!e?.startsWith("Bearer "))return n.json({error:"UNAUTHORIZED",message:"Missing or invalid Authorization header",suggestion:"Include 'Authorization: Bearer <api_key>' header"},401);let r=e.slice(7),E=Et(t,r);if(!E)return n.json({error:"UNAUTHORIZED",message:"Invalid API key",suggestion:"Register with POST /auth/register"},401);return n.set("user",E),o()}}var cl;var WT=R(()=>{Y();cl=["/auth/register","/health"]});function al(t){if(t instanceof F)return 404;if(t instanceof ot)return 403;if(t instanceof it)return 409;if(t instanceof gn)return 503;if(t instanceof et)return 400;if("code"in t)return 400;return 500}function KT(t,n){let o=al(t);if("toJSON"in t&&typeof t.toJSON==="function")return n.json(t.toJSON(),o);return n.json({error:"INTERNAL_ERROR",message:t.message},o)}var pT=R(()=>{Y()});function Oo(t){let n=new Map;return setInterval(()=>{let o=Date.now()-60000;for(let[i,e]of n){let r=e.filter((E)=>E>o);if(r.length===0)n.delete(i);else n.set(i,r)}},300000).unref(),async(o,i)=>{let e=o.req.header("authorization")??"",r=e.startsWith("Bearer ")?e.slice(7):o.req.header("x-forwarded-for")??"unknown",E=Date.now(),f=E-60000,T=(n.get(r)??[]).filter((N)=>N>f);if(T.length>=t){let N=T[0],A=Math.ceil((N+60000-E)/1000);return o.header("Retry-After",String(A)),o.json({error:"RATE_LIMITED",message:"Too many requests"},429)}T.push(E),n.set(r,T),await i()}}import{Hono as tw}from"hono";function jT(t){let n=new tw;return n.post("/register",async(o)=>{let{email:i}=await o.req.json();if(!i||typeof i!=="string")return o.json({error:"VALIDATION_ERROR",message:"email is required"},400);try{let e=rt(t,{email:i}),r=K(t,e.user.id);return o.json({apiKey:e.apiKey,userId:e.user.id,orgId:r[0]?.id})}catch(e){if(e instanceof Error&&e.message.includes("UNIQUE"))return o.json({error:"CONFLICT",message:"User with this email already exists"},409);throw e}}),n.get("/me",(o)=>{let i=o.get("user");try{let e=d(t,{userId:i.id});return o.json({userId:i.id,email:i.email,defaultOrgId:e.orgId,defaultDriveId:e.driveId})}catch{return o.json({userId:i.id,email:i.email,defaultOrgId:null,defaultDriveId:null})}}),n}var hT=R(()=>{Y()});import{Hono as nw}from"hono";function kT(t,n,o=null,i){let e=new nw;return e.post("/:orgId/ops",async(r)=>{let E=r.get("user"),f=r.req.param("orgId"),T=await r.req.json(),{op:N,...A}=T;if(!N)return r.json({error:"VALIDATION_ERROR",message:"op is required in request body"},400);let y=A.driveId||A.drive_id;delete A.driveId,delete A.drive_id;let l=d(t,{userId:E.id,orgId:f,driveId:y}),g={db:t,s3:n,orgId:l.orgId,driveId:l.driveId,userId:E.id,embeddingProvider:o,appUrl:i},I=await j(g,N,A);return r.json(I)}),e}var mT=R(()=>{Y()});import{Hono as ow}from"hono";function zT(t){let n=new ow;return n.get("/",(o)=>{let i=o.get("user"),e=K(t,i.id);return o.json({orgs:e})}),n.post("/",async(o)=>{let i=o.get("user"),{name:e}=await o.req.json(),r=Vt(t,{name:e,userId:i.id});return o.json(r,201)}),n.get("/:orgId",(o)=>{let i=o.req.param("orgId"),e=$n(t,i);if(!e)return o.json({error:"NOT_FOUND",message:"Org not found"},404);return o.json(e)}),n.get("/:orgId/drives",(o)=>{let i=o.get("user"),e=o.req.param("orgId"),r=gt(t,e,i.id);return o.json({drives:r})}),n.post("/:orgId/drives",async(o)=>{let i=o.req.param("orgId"),{name:e}=await o.req.json(),r=Ht(t,{orgId:i,name:e});return o.json(r,201)}),n.post("/:orgId/members/invite",async(o)=>{let i=o.req.param("orgId"),{email:e,role:r}=await o.req.json();return jt(t,{orgId:i,email:e,role:r}),o.json({ok:!0})}),n.get("/:orgId/members",(o)=>{let i=o.req.param("orgId"),e=Wt(t,i);return o.json({members:e})}),n.patch("/:orgId/members/:userId",async(o)=>{let i=o.req.param("orgId"),e=o.req.param("userId"),{role:r}=await o.req.json();try{return Kt(t,{orgId:i,userId:e,role:r}),o.json({ok:!0})}catch(E){return o.json({error:"BAD_REQUEST",message:E.message},400)}}),n.delete("/:orgId/members/:userId",(o)=>{let i=o.req.param("orgId"),e=o.req.param("userId");try{return pt(t,{orgId:i,userId:e}),o.json({ok:!0})}catch(r){return o.json({error:"BAD_REQUEST",message:r.message},400)}}),n.get("/:orgId/drives/:driveId/members",(o)=>{let i=o.req.param("driveId"),e=Zt(t,i);return o.json({members:e})}),n.patch("/:orgId/drives/:driveId/members/:userId",async(o)=>{let i=o.req.param("driveId"),e=o.req.param("userId"),{role:r}=await o.req.json();try{return Qt(t,{driveId:i,userId:e,role:r}),o.json({ok:!0})}catch(E){return o.json({error:"BAD_REQUEST",message:E.message},400)}}),n.delete("/:orgId/drives/:driveId/members/:userId",(o)=>{let i=o.req.param("driveId"),e=o.req.param("userId");try{return Bt(t,{driveId:i,userId:e}),o.json({ok:!0})}catch(r){return o.json({error:"BAD_REQUEST",message:r.message},400)}}),n}var dT=R(()=>{Y()});import{Hono as iw}from"hono";function bT(){let t=new iw;return t.get("/openapi.json",(n)=>{return n.json(wo())}),t}var qT=R(()=>{Y()});import{Hono as ew}from"hono";function sT(t,n,o=null,i){let e=new ew;return e.get("/:orgId/drives/:driveId/files/*/raw",async(r)=>{let E=r.get("user"),f=r.req.param("orgId"),T=r.req.param("driveId"),N=d(t,{userId:E.id,orgId:f,driveId:T}),y=new URL(r.req.url).pathname.match(/\/files\/(.+)\/raw$/);if(!y)return r.json({error:"VALIDATION_ERROR",message:"Invalid file path"},400);let l=On(decodeURIComponent(y[1])),g=S(N.orgId,N.driveId,l);try{let I=await n.getObject(g),D=I.contentType||"application/octet-stream",C=xt({db:t,driveId:N.driveId},l),H={"Content-Type":D,"Content-Length":String(I.body.length),"Cache-Control":"private, max-age=60"};if(C){if(H.ETag=`"${C.version}"`,H["X-Agent-FS-Version"]=String(C.version),C.contentHash)H["X-Agent-FS-Content-Hash"]=C.contentHash;if(C.createdAt)H["Last-Modified"]=new Date(C.createdAt).toUTCString()}return new Response(I.body.buffer,{status:200,headers:H})}catch(I){if(I?.name==="NoSuchKey"||I?.$metadata?.httpStatusCode===404)return r.json({error:"NOT_FOUND",message:`File not found: ${l}`},404);throw I}}),e.put("/:orgId/drives/:driveId/files/*/raw",async(r)=>{let E=r.get("user"),f=r.req.param("orgId"),T=r.req.param("driveId");if((r.req.header("Content-Type")??"").toLowerCase().startsWith("application/json"))return r.json({error:"VALIDATION_ERROR",message:"PUT /raw expects a binary body; use POST /ops with op=write for JSON-encoded content"},415);let A=d(t,{userId:E.id,orgId:f,driveId:T}),l=new URL(r.req.url).pathname.match(/\/files\/(.+)\/raw$/);if(!l)return r.json({error:"VALIDATION_ERROR",message:"Invalid file path"},400);let g=On(decodeURIComponent(l[1])),I,D=r.req.header("If-None-Match"),C=r.req.header("If-Match");if(D==="*")I=0;else if(C!==void 0){let _N=C.replace(/^"|"$/g,""),So=Number(_N);if(!Number.isInteger(So)||So<0)return r.json({error:"VALIDATION_ERROR",message:`If-Match must be a non-negative integer version, got: ${C}`},400);I=So}let H=r.req.header("X-Agent-FS-Message")??void 0,Tn=await r.req.arrayBuffer(),AN=new Uint8Array(Tn),RN=new TextDecoder("utf-8").decode(AN),yN={db:t,s3:n,orgId:A.orgId,driveId:A.driveId,userId:E.id,embeddingProvider:o,appUrl:i},zt=await Lt(yN,{path:g,content:RN,message:H,expectedVersion:I});return new Response(JSON.stringify(zt),{status:200,headers:{"Content-Type":"application/json",ETag:`"${zt.version}"`,"X-Agent-FS-Version":String(zt.version),...zt.contentHash&&{"X-Agent-FS-Content-Hash":zt.contentHash},"X-Agent-FS-Deduped":zt.deduped?"1":"0"}})}),e}var xT=R(()=>{Y()});import{Hono as rw}from"hono";import{cors as cT}from"hono/cors";import{bodyLimit as Ew}from"hono/body-limit";import{WebStandardStreamableHTTPServerTransport as uw}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";function aT(t,n,o=null){let i=new rw,e=P(),r=e.server?.cors?.origins??["*"];if(r.length===1&&r[0]==="*")i.use("*",cT());else i.use("*",cT({origin:r}));i.use("*",Ew({maxSize:52428800})),i.use("*",VT(t));let E=e.server?.rateLimit?.requestsPerMinute??1200;if(E>0)i.use("/orgs/*",Oo(E)),i.use("/auth/*",Oo(E)),i.use("/mcp",Oo(E));return i.onError((f,T)=>KT(f,T)),i.get("/health",(f)=>f.json({ok:!0,version:b})),i.all("/mcp",async(f)=>{let T=f.get("user"),N=new uw({sessionIdGenerator:void 0,enableJsonResponse:!0});return await BT({db:t,s3:n,embeddingProvider:o,appUrl:e.appUrl}).connect(N),N.handleRequest(f.req.raw,{authInfo:{token:f.req.header("Authorization")?.slice(7)??"",clientId:T.id,scopes:[],extra:{user:{id:T.id,email:T.email}}}})}),i.route("/auth",jT(t)),i.route("/orgs",zT(t)),i.route("/orgs",kT(t,n,o,e.appUrl)),i.route("/docs",bT()),i.route("/orgs",sT(t,n,o,e.appUrl)),i}var tN=R(()=>{Y();JT();WT();pT();hT();mT();dT();qT();xT()});function wt(t,n,o){return{error:{http_status:t,code:n,message:o}}}function fw(t){let n=String(t?.name??""),o=String(t?.message??t??"unknown error");if(n==="EditConflictError")return wt(409,"EDIT_CONFLICT",o);if(n==="NotFoundError")return wt(404,"NOT_FOUND",o);if(n==="PermissionDeniedError")return wt(403,"PERMISSION_DENIED",o);if(n==="ValidationError")return wt(415,"VALIDATION",o);if(n==="IndexingInProgressError")return wt(503,"INDEXING_IN_PROGRESS",o);if(/no.*api.*key|no.*user/i.test(o))return wt(401,"AUTH_MISSING",o);return wt(500,"INTERNAL",o)}function tt(t){let n=t.resolveApiKey();if(!n){let i=Error("daemon has no API key configured");throw i.name="AuthError",i}let o=Et(t.db,n);if(!o){let i=Error("API key did not resolve to a user");throw i.name="AuthError",i}return{userId:o.id,email:o.email}}function It(t,n,o){try{let r=d(t.db,{userId:n,driveId:o});return{orgId:r.orgId,driveId:r.driveId}}catch{}let i=K(t.db,n);for(let r of i){let f=gt(t.db,r.id,n).find((T)=>T.name===o);if(f)return{orgId:r.id,driveId:f.id}}let e=Error(`Drive not found: ${o}`);throw e.name="NotFoundError",e}function Ot(t,n,o,i){return{db:t.db,s3:t.s3,orgId:o,driveId:i,userId:n.userId,embeddingProvider:t.embeddingProvider,appUrl:t.appUrl}}async function nN(t,n){if(!n||typeof n!=="object")return wt(400,"VALIDATION","request body must be an object");let o=n;try{return await Tw(t,o)}catch(i){return fw(i)}}async function Tw(t,n){switch(n.op){case"ping":return"pong";case"hello":return"ok";case"list_drives":{let o=tt(t),i=K(t.db,o.userId),e=[];for(let r of i){let E=gt(t.db,r.id,o.userId);for(let f of E)e.push({slug:f.name,id:f.id,org_id:r.id})}return{drives:e}}case"default_drive_slug":{let o=tt(t),i=K(t.db,o.userId);for(let e of i){let r=gt(t.db,e.id,o.userId),E=r.find((f)=>f.isDefault)??r[0];if(E)return{default_drive_slug:E.name}}return{default_drive_slug:null}}case"get_attr":{let o=tt(t),{orgId:i,driveId:e}=It(t,o.userId,n.drive),r=n.path,E=Ot(t,o,i,e);try{let f=await j(E,"stat",{path:r});return{attr:{kind:"File",size:f.size,mtime_unix:Math.floor(new Date(f.modifiedAt).getTime()/1000),version:f.currentVersion??null,content_hash:null}}}catch(f){if(String(f?.name)==="NotFoundError")try{let T=await j(E,"ls",{path:r});if(T&&Array.isArray(T.entries)&&T.entries.length>0)return{attr:{kind:"Dir",size:0,mtime_unix:0,version:null,content_hash:null}}}catch{}throw f}}case"read_dir":{let o=tt(t),{orgId:i,driveId:e}=It(t,o.userId,n.drive),r=n.path??"/",E=Ot(t,o,i,e);return{dir_entries:((await j(E,"ls",{path:r}))?.entries??[]).map((N)=>({name:N.name,kind:N.type==="directory"?"Dir":"File",size:N.size??0,mtime_unix:N.modifiedAt?Math.floor(new Date(N.modifiedAt).getTime()/1000):0,version:null,content_hash:null}))}}case"open_read":{let o=tt(t),{orgId:i,driveId:e}=It(t,o.userId,n.drive),r=n.path,E=Ot(t,o,i,e),f=await j(E,"cat",{path:r}),T=xt({db:t.db,driveId:e},r),N=f?.content??"",A=new TextEncoder().encode(N);return{open_read:{bytes:A,version:T?.version??0,content_hash:T?.contentHash??"",size:A.length,mtime_unix:T?.createdAt?Math.floor(new Date(T.createdAt).getTime()/1000):0}}}case"open_write":{let o=tt(t),{orgId:i,driveId:e}=It(t,o.userId,n.drive),r=n.path,E=Ot(t,o,i,e),f=Nw(n.bytes),T=new TextDecoder("utf-8").decode(f),N=await Lt(E,{path:r,content:T,expectedVersion:n.base_version??void 0});return{open_write:{version:N.version,content_hash:N.contentHash??"",deduped:N.deduped??!1}}}case"create_file":{let o=tt(t),{orgId:i,driveId:e}=It(t,o.userId,n.drive),r=n.path,E=Ot(t,o,i,e),f=await Lt(E,{path:r,content:"",expectedVersion:0});return{open_write:{version:f.version,content_hash:f.contentHash??"",deduped:f.deduped??!1}}}case"truncate":{let o=tt(t),{orgId:i,driveId:e}=It(t,o.userId,n.drive),r=n.path,E=n.size??0,f=Ot(t,o,i,e),T=await j(f,"cat",{path:r}),N=new TextEncoder().encode(T?.content??""),A=N.subarray(0,Math.min(E,N.length)),y=new TextDecoder("utf-8").decode(A),l=await Lt(f,{path:r,content:y});return{open_write:{version:l.version,content_hash:l.contentHash??"",deduped:l.deduped??!1}}}case"unlink":{let o=tt(t),{orgId:i,driveId:e}=It(t,o.userId,n.drive),r=n.path,E=Ot(t,o,i,e);return await j(E,"rm",{path:r}),"ok"}case"rename":{let o=tt(t),{orgId:i,driveId:e}=It(t,o.userId,n.drive),r=n.from_path,E=n.to_path,f=Ot(t,o,i,e);return await j(f,"mv",{from:r,to:E}),"ok"}case"mkdir":return tt(t),"ok";case"rmdir":{let o=tt(t),{orgId:i,driveId:e}=It(t,o.userId,n.drive),r=n.path,E=Ot(t,o,i,e);if((await j(E,"ls",{path:r}))?.entries?.length>0)return wt(409,"VALIDATION","directory not empty");return"ok"}case"record_conflict":return console.warn("[agent-fs ipc] conflict:",JSON.stringify({drive:n.drive,path:n.path,base_version:n.base_version,head_version:n.head_version,bytes:n.bytes})),"ok";case"write_status":return console.warn("[agent-fs ipc] status:",n.line),"ok";default:return wt(400,"VALIDATION",`unknown op: ${n.op}`)}}function Nw(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(Array.isArray(t))return new Uint8Array(t);if(t==null)return new Uint8Array(0);if(typeof t==="string")return new TextEncoder().encode(t);if(typeof Buffer<"u"&&Buffer.isBuffer(t))return new Uint8Array(t);return new Uint8Array(0)}var oN=R(()=>{Y()});import{unlinkSync as iN,existsSync as Aw,chmodSync as Rw}from"fs";import{Packr as yw,Unpackr as _w}from"msgpackr";function eN(t,n){if(Aw(t))try{iN(t)}catch{}let o=Bun.listen({unix:t,socket:{open(i){i.data={buf:Buffer.alloc(0)}},data(i,e){i.data.buf=Buffer.concat([i.data.buf,e]),gw(i,n).catch((r)=>{console.error("[agent-fs ipc] frame drain failed:",r),i.end()})},close(i){i.data.buf=Buffer.alloc(0)},error(i,e){console.error("[agent-fs ipc] socket error:",e)}}});try{Rw(t,384)}catch{}return{socketPath:t,stop:()=>{o.stop(!0);try{iN(t)}catch{}}}}async function gw(t,n){while(!0){let o=t.data;if(o.buf.length<4)return;let i=o.buf.readUInt32BE(0);if(i===0||i>lw){console.error(`[agent-fs ipc] implausible frame length ${i}; closing`),t.end();return}if(o.buf.length<4+i)return;let e=o.buf.subarray(4,4+i);o.buf=o.buf.subarray(4+i);let r;try{r=Lw.unpack(e)}catch(E){console.error("[agent-fs ipc] decode failed:",E),t.end();return}Dw(t,n,r)}}async function Dw(t,n,o){let i;try{i=await nN(n,o.body)}catch(f){i={Error:{http_status:0,code:null,message:String(f?.message??f)}}}let e={id:o.id,body:i},r=ww.pack(e),E=Buffer.alloc(4);E.writeUInt32BE(r.length,0),t.write(Buffer.concat([E,r]))}var lw=67108864,ww,Lw;var rN=R(()=>{oN();ww=new yw({useRecords:!1}),Lw=new _w({useRecords:!1})});var Uw={};import{join as Iw}from"path";function TN(){if(console.log("Shutting down..."),Oe.stop(),Ue)Ue.stop();process.exit(0)}var fn,uN,fN,Se=null,Ow,Oe,EN,Ue=null;var NN=R(async()=>{Y();tN();rN();fn=P(),uN=Ut(),fN=new $t(fn.s3);try{Se=await En(fn.embedding)}catch(t){console.warn("Embedding provider unavailable, semantic search disabled:",t)}Ow=aT(uN,fN,Se),Oe=Bun.serve({fetch:Ow.fetch,port:fn.server.port,hostname:fn.server.host});console.log(`agent-fs daemon running on http://${Oe.hostname}:${Oe.port}`);EN=Iw(V(),"agent-fs.sock");try{Ue=eN(EN,{db:uN,s3:fN,embeddingProvider:Se,appUrl:fn.appUrl,resolveApiKey:()=>fn.auth?.apiKey??null}),console.log(`agent-fs IPC listening on ${EN}`)}catch(t){console.warn("IPC listener unavailable:",t)}process.on("SIGTERM",TN);process.on("SIGINT",TN)});Y();import{Command as Sw}from"commander";Y();class Ne{baseUrl;apiKey;constructor(){let t=P();this.baseUrl=process.env.AGENT_FS_API_URL??t.apiUrl??`http://${t.server.host}:${t.server.port}`,this.apiKey=process.env.AGENT_FS_API_KEY??t.apiKey??t.auth.apiKey}async request(t,n){let o=new Headers(n?.headers);if(this.apiKey)o.set("Authorization",`Bearer ${this.apiKey}`);o.set("Content-Type","application/json");let i;try{i=await fetch(`${this.baseUrl}${t}`,{...n,headers:o})}catch(r){throw Error(`Cannot connect to agent-fs daemon at ${this.baseUrl}. Is it running? Start with: agent-fs daemon start`)}let e;try{e=await i.json()}catch{let r=await i.text().catch(()=>"");throw Error(`Unexpected response from daemon (${i.status}): ${r||"empty"}`)}if(!i.ok){let r=e.message??e.error??"Request failed",E=e.suggestion?`
|
|
178
|
-
Suggestion: ${e.suggestion}`:"";throw Error(`${r}${E}`)}return e}async get(t){return this.request(t)}async post(t,n){return this.request(t,{method:"POST",body:JSON.stringify(n)})}async patch(t,n){return this.request(t,{method:"PATCH",body:JSON.stringify(n)})}async del(t){return this.request(t,{method:"DELETE"})}async callOp(t,n,o){return this.post(`/orgs/${t}/ops`,{op:n,...o})}async getMe(){return this.get("/auth/me")}setApiKey(t){this.apiKey=t}async putRaw(t,n,o,i,e={}){let r=new Headers;if(r.set("Content-Type","application/octet-stream"),this.apiKey)r.set("Authorization",`Bearer ${this.apiKey}`);if(e.ifMatch!==void 0)r.set("If-Match",String(e.ifMatch));if(e.contentHash)r.set("X-Agent-FS-Content-Hash",e.contentHash);if(e.message)r.set("X-Agent-FS-Message",e.message);let E=encodeURI(o.replace(/^\/+/,"")),f=`${this.baseUrl}/orgs/${t}/drives/${n}/files/${E}/raw`,T;try{T=await fetch(f,{method:"PUT",headers:r,body:i})}catch(
|
|
179
|
-
Suggestion: ${
|
|
180
|
-
`)}function
|
|
181
|
-
`)
|
|
182
|
-
`)
|
|
183
|
-
`)}function
|
|
176
|
+
]`;continue}if(e+=i[T],i[T]==="\\")r=!0;else if(E&&i[T]==="]")E=!1;else if(!E&&i[T]==="[")E=!0}try{new RegExp(e)}catch{return console.warn(`Could not convert regex pattern at ${n.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return e}var ai=void 0,ft,K_;var go=R(()=>{ft={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(ai===void 0)ai=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return ai},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};K_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Hn}from"zod/v3";function Do(t,n){if(n.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(n.target==="openApi3"&&t.keyType?._def.typeName===Hn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,e)=>({...i,[e]:L(t.valueType._def,{...n,currentPath:[...n.currentPath,"properties",e]})??H(n)}),{}),additionalProperties:n.rejectedAdditionalProperties};let o={type:"object",additionalProperties:L(t.valueType._def,{...n,currentPath:[...n.currentPath,"additionalProperties"]})??n.allowedAdditionalProperties};if(n.target==="openApi3")return o;if(t.keyType?._def.typeName===Hn.ZodString&&t.keyType._def.checks?.length){let{type:i,...e}=Lo(t.keyType._def,n);return{...o,propertyNames:e}}else if(t.keyType?._def.typeName===Hn.ZodEnum)return{...o,propertyNames:{enum:t.keyType._def.values}};else if(t.keyType?._def.typeName===Hn.ZodBranded&&t.keyType._def.type._def.typeName===Hn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:i,...e}=wo(t.keyType._def,n);return{...o,propertyNames:e}}return o}var Oo=R(()=>{B();go();yo();tt()});function Kf(t,n){if(n.mapStrategy==="record")return Do(t,n);let o=L(t.keyType._def,{...n,currentPath:[...n.currentPath,"items","items","0"]})||H(n),i=L(t.valueType._def,{...n,currentPath:[...n.currentPath,"items","items","1"]})||H(n);return{type:"array",maxItems:125,items:{type:"array",items:[o,i],minItems:2,maxItems:2}}}var ne=R(()=>{B();Oo();tt()});function pf(t){let n=t.values,i=Object.keys(t.values).filter((r)=>{return typeof n[n[r]]!=="number"}).map((r)=>n[r]),e=Array.from(new Set(i.map((r)=>typeof r)));return{type:e.length===1?e[0]==="string"?"string":"number":["string","number"],enum:i}}function hf(t){return t.target==="openAi"?void 0:{not:H({...t,currentPath:[...t.currentPath,"not"]})}}var oe=R(()=>{tt()});function jf(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}function df(t,n){if(n.target==="openApi3")return kf(t,n);let o=t.options instanceof Map?Array.from(t.options.values()):t.options;if(o.every((i)=>(i._def.typeName in Zn)&&(!i._def.checks||!i._def.checks.length))){let i=o.reduce((e,r)=>{let E=Zn[r._def.typeName];return E&&!e.includes(E)?[...e,E]:e},[]);return{type:i.length>1?i:i[0]}}else if(o.every((i)=>i._def.typeName==="ZodLiteral"&&!i.description)){let i=o.reduce((e,r)=>{let E=typeof r._def.value;switch(E){case"string":case"number":case"boolean":return[...e,E];case"bigint":return[...e,"integer"];case"object":if(r._def.value===null)return[...e,"null"];case"symbol":case"undefined":case"function":default:return e}},[]);if(i.length===o.length){let e=i.filter((r,E,f)=>f.indexOf(r)===E);return{type:e.length>1?e:e[0],enum:o.reduce((r,E)=>{return r.includes(E._def.value)?r:[...r,E._def.value]},[])}}}else if(o.every((i)=>i._def.typeName==="ZodEnum"))return{type:"string",enum:o.reduce((i,e)=>[...i,...e._def.values.filter((r)=>!i.includes(r))],[])};return kf(t,n)}var Zn,kf=(t,n)=>{let o=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((i,e)=>L(i._def,{...n,currentPath:[...n.currentPath,"anyOf",`${e}`]})).filter((i)=>!!i&&(!n.strictUnions||typeof i==="object"&&Object.keys(i).length>0));return o.length?{anyOf:o}:void 0};var Io=R(()=>{B();Zn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"}});function mf(t,n){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length)){if(n.target==="openApi3")return{type:Zn[t.innerType._def.typeName],nullable:!0};return{type:[Zn[t.innerType._def.typeName],"null"]}}if(n.target==="openApi3"){let i=L(t.innerType._def,{...n,currentPath:[...n.currentPath]});if(i&&"$ref"in i)return{allOf:[i],nullable:!0};return i&&{...i,nullable:!0}}let o=L(t.innerType._def,{...n,currentPath:[...n.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}var ie=R(()=>{B();Io()});function zf(t,n){let o={type:"number"};if(!t.checks)return o;for(let i of t.checks)switch(i.kind){case"int":o.type="integer",ki(o,"type",i.message,n);break;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 ee=()=>{};function bf(t,n){let o=n.target==="openAi",i={type:"object",properties:{}},e=[],r=t.shape();for(let f in r){let T=r[f];if(T===void 0||T._def===void 0)continue;let l=j_(T);if(l&&o){if(T._def.typeName==="ZodOptional")T=T._def.innerType;if(!T.isNullable())T=T.nullable();l=!1}let N=L(T._def,{...n,currentPath:[...n.currentPath,"properties",f],propertyPath:[...n.currentPath,"properties",f]});if(N===void 0)continue;if(i.properties[f]=N,!l)e.push(f)}if(e.length)i.required=e;let E=h_(t,n);if(E!==void 0)i.additionalProperties=E;return i}function h_(t,n){if(t.catchall._def.typeName!=="ZodNever")return L(t.catchall._def,{...n,currentPath:[...n.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return n.allowedAdditionalProperties;case"strict":return n.rejectedAdditionalProperties;case"strip":return n.removeAdditionalStrategy==="strict"?n.allowedAdditionalProperties:n.rejectedAdditionalProperties}}function j_(t){try{return t.isOptional()}catch{return!0}}var re=R(()=>{B()});var qf=(t,n)=>{if(n.currentPath.toString()===n.propertyPath?.toString())return L(t.innerType._def,n);let o=L(t.innerType._def,{...n,currentPath:[...n.currentPath,"anyOf","1"]});return o?{anyOf:[{not:H(n)},o]}:H(n)};var Ee=R(()=>{B();tt()});var sf=(t,n)=>{if(n.pipeStrategy==="input")return L(t.in._def,n);else if(n.pipeStrategy==="output")return L(t.out._def,n);let o=L(t.in._def,{...n,currentPath:[...n.currentPath,"allOf","0"]}),i=L(t.out._def,{...n,currentPath:[...n.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,i].filter((e)=>e!==void 0)}};var ue=R(()=>{B()});function cf(t,n){return L(t.type._def,n)}var fe=R(()=>{B()});function xf(t,n){let i={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...n,currentPath:[...n.currentPath,"items"]})};if(t.minSize)X(i,"minItems",t.minSize.value,t.minSize.message,n);if(t.maxSize)X(i,"maxItems",t.maxSize.value,t.maxSize.message,n);return i}var Te=R(()=>{B()});function af(t,n){if(t.rest)return{type:"array",minItems:t.items.length,items:t.items.map((o,i)=>L(o._def,{...n,currentPath:[...n.currentPath,"items",`${i}`]})).reduce((o,i)=>i===void 0?o:[...o,i],[]),additionalItems:L(t.rest._def,{...n,currentPath:[...n.currentPath,"additionalItems"]})};else return{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((o,i)=>L(o._def,{...n,currentPath:[...n.currentPath,"items",`${i}`]})).reduce((o,i)=>i===void 0?o:[...o,i],[])}}var le=R(()=>{B()});function tT(t){return{not:H(t)}}var Ne=R(()=>{tt()});function nT(t){return H(t)}var Re=R(()=>{tt()});var oT=(t,n)=>{return L(t.innerType._def,n)};var Ae=R(()=>{B()});import{ZodFirstPartyTypeKind as $}from"zod/v3";var iT=(t,n,o)=>{switch(n){case $.ZodString:return Lo(t,o);case $.ZodNumber:return zf(t,o);case $.ZodObject:return bf(t,o);case $.ZodBigInt:return Yf(t,o);case $.ZodBoolean:return Gf();case $.ZodDate:return bi(t,o);case $.ZodUndefined:return tT(o);case $.ZodNull:return jf(o);case $.ZodArray:return vf(t,o);case $.ZodUnion:case $.ZodDiscriminatedUnion:return df(t,o);case $.ZodIntersection:return Bf(t,o);case $.ZodTuple:return af(t,o);case $.ZodRecord:return Do(t,o);case $.ZodLiteral:return Vf(t,o);case $.ZodEnum:return Jf(t);case $.ZodNativeEnum:return pf(t);case $.ZodNullable:return mf(t,o);case $.ZodOptional:return qf(t,o);case $.ZodMap:return Kf(t,o);case $.ZodSet:return xf(t,o);case $.ZodLazy:return()=>t.getter()._def;case $.ZodPromise:return cf(t,o);case $.ZodNaN:case $.ZodNever:return hf(o);case $.ZodEffects:return Qf(t,o);case $.ZodAny:return H(o);case $.ZodUnknown:return nT(o);case $.ZodDefault:return Zf(t,o);case $.ZodBranded:return wo(t,o);case $.ZodReadonly:return oT(t,o);case $.ZodCatch:return Hf(t,o);case $.ZodPipeline:return sf(t,o);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return((i)=>{return})(n)}};var _e=R(()=>{tt();di();mi();yo();zi();qi();si();ci();xi();ne();oe();ie();ee();re();Ee();ue();fe();Oo();Te();go();le();Ne();Io();Re();Ae()});function L(t,n,o=!1){let i=n.seen.get(t);if(n.override){let f=n.override?.(t,n,i,o);if(f!==Pf)return f}if(i&&!o){let f=k_(i,n);if(f!==void 0)return f}let e={def:t,path:n.currentPath,jsonSchema:void 0};n.seen.set(t,e);let r=iT(t,t.typeName,n),E=typeof r==="function"?L(r(),n):r;if(E)d_(t,n,E);if(n.postProcess){let f=n.postProcess(E,t,n);return e.jsonSchema=E,f}return e.jsonSchema=E,E}var k_=(t,n)=>{switch(n.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:_o(n.currentPath,t.path)};case"none":case"seen":{if(t.path.length<n.currentPath.length&&t.path.every((o,i)=>n.currentPath[i]===o))return console.warn(`Recursive reference detected at ${n.currentPath.join("/")}! Defaulting to any`),H(n);return n.$refStrategy==="seen"?H(n):void 0}}},d_=(t,n,o)=>{if(t.description){if(o.description=t.description,n.markdownDescription)o.markdownDescription=t.description}return o};var B=R(()=>{Ao();_e();tt()});var eT=()=>{};var we=(t,n)=>{let o=Ff(n),i=typeof n==="object"&&n.definitions?Object.entries(n.definitions).reduce((T,[l,N])=>({...T,[l]:L(N._def,{...o,currentPath:[...o.basePath,o.definitionPath,l]},!0)??H(o)}),{}):void 0,e=typeof n==="string"?n:n?.nameStrategy==="title"?void 0:n?.name,r=L(t._def,e===void 0?o:{...o,currentPath:[...o.basePath,o.definitionPath,e]},!1)??H(o),E=typeof n==="object"&&n.name!==void 0&&n.nameStrategy==="title"?n.name:void 0;if(E!==void 0)r.title=E;if(o.flags.hasReferencedOpenAiAnyType){if(!i)i={};if(!i[o.openAiAnyTypeName])i[o.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:o.$refStrategy==="relative"?"1":[...o.basePath,o.definitionPath,o.openAiAnyTypeName].join("/")}}}let f=e===void 0?i?{...r,[o.definitionPath]:i}:r:{$ref:[...o.$refStrategy==="relative"?[]:o.basePath,o.definitionPath,e].join("/"),[o.definitionPath]:{...i,[e]:r}};if(o.target==="jsonSchema7")f.$schema="http://json-schema.org/draft-07/schema#";else if(o.target==="jsonSchema2019-09"||o.target==="openAi")f.$schema="https://json-schema.org/draft/2019-09/schema#";if(o.target==="openAi"&&(("anyOf"in f)||("oneOf"in f)||("allOf"in f)||("type"in f)&&Array.isArray(f.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return f};var ye=R(()=>{B();ji();tt()});var rT=R(()=>{ye();Ao();ji();B();eT();tt();di();mi();yo();zi();qi();si();ci();xi();ne();oe();ie();ee();re();Ee();ue();fe();Ae();Oo();Te();go();le();Ne();Io();Re();_e();ye()});function Uo(){let t=fn(),n={},o={};for(let e of t){let r=Mt(e),E=we(r.schema,{target:"openApi3"}),{$schema:f,...T}=E;n[e]=T,o[e]=r.description}let i=t.map((e)=>({type:"object",title:e,description:o[e],required:["op",...n[e].required||[]],properties:{op:{type:"string",const:e},driveId:{type:"string",description:"Target drive ID (optional, uses default drive)"},...n[e].properties||{}},additionalProperties:!1}));return{openapi:"3.1.0",info:{title:"agent-fs API",version:q,description:"A persistent, searchable filesystem for AI agents. agent-fs is to files what agentmail is to email.",license:{name:"MIT",url:"https://github.com/desplega-ai/agent-fs/blob/main/LICENSE"}},servers:[{url:"http://localhost:7433",description:"Local development server"}],paths:{"/health":{get:{summary:"Health check",operationId:"health",tags:["System"],security:[],responses:{"200":{description:"Server is healthy",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",const:!0},version:{type:"string"}},required:["ok","version"]}}}}}}},"/auth/register":{post:{summary:"Register a new user",operationId:"register",tags:["Auth"],security:[],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",format:"email"}},required:["email"]}}}},responses:{"200":{description:"User registered",content:{"application/json":{schema:{type:"object",properties:{userId:{type:"string"},orgId:{type:"string"},driveId:{type:"string"},apiKey:{type:"string"}},required:["userId","orgId","driveId","apiKey"]}}}}}}},"/auth/me":{get:{summary:"Get current user info",operationId:"me",tags:["Auth"],responses:{"200":{description:"Current user",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},createdAt:{type:"string",format:"date-time"}},required:["id","email","createdAt"]}}}}}}},"/orgs/{orgId}/ops":{post:{summary:"Dispatch a file operation",operationId:"dispatchOp",tags:["Operations"],description:"All file operations go through this single endpoint. The `op` field determines which operation to execute.",parameters:[{name:"orgId",in:"path",required:!0,schema:{type:"string"},description:"Organization ID"}],requestBody:{required:!0,content:{"application/json":{schema:{oneOf:i,discriminator:{propertyName:"op"}}}}},responses:{"200":{description:"Operation result (varies by op)",content:{"application/json":{schema:{type:"object",description:"Response shape depends on the operation. See each op's description for details."}}}},"400":{description:"Validation error",content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}},"401":{description:"Unauthorized",content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}},"403":{description:"Permission denied (RBAC)",content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}},"404":{description:"File or resource not found",content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}}}}}},components:{securitySchemes:{bearerAuth:{type:"http",scheme:"bearer",description:"API key obtained from /auth/register"}},schemas:{Error:{type:"object",properties:{error:{type:"string"},message:{type:"string"}},required:["error","message"]}}},security:[{bearerAuth:[]}]}}var ET=R(()=>{rT();Yi();Vi()});var uT={};bt(uT,{writeRaw:()=>Dt,write:()=>io,updateOrgMemberRole:()=>ht,updateDriveMemberRole:()=>Bt,setDriveMember:()=>Hi,setConfigValue:()=>U,setConfig:()=>Je,schema:()=>u,resolveContext:()=>b,removeOrgMember:()=>jt,removeDriveMember:()=>Vt,listUserOrgs:()=>p,listOrgMembers:()=>pt,listDrivesForUser:()=>Ot,listDrives:()=>vn,listDriveMembers:()=>Jt,inviteToOrg:()=>kt,getUserDriveRole:()=>At,getUserByEmail:()=>Tn,getUserByApiKey:()=>ut,getS3Key:()=>I,getRequiredRole:()=>$n,getRegisteredOps:()=>fn,getOrg:()=>Yn,getOpDefinition:()=>Mt,getNextVersion:()=>to,getHome:()=>V,getHeadVersionRow:()=>xt,getHeadContentHash:()=>no,getDrive:()=>Gi,getDbPath:()=>Ht,getConfigPath:()=>x,getConfig:()=>P,generateOpenAPISpec:()=>Uo,ensureLocalUser:()=>Gn,dispatchOp:()=>k,createVersion:()=>h,createUser:()=>Et,createOrg:()=>Kt,createEmbeddingProviderFromEnv:()=>ln,createDrive:()=>Qt,createDatabase:()=>St,commentUpdate:()=>To,commentResolve:()=>No,commentList:()=>uo,commentGet:()=>fo,commentDelete:()=>lo,commentAdd:()=>Eo,checkPermission:()=>Xn,assertExpectedVersion:()=>j,ValidationError:()=>c,VERSION:()=>q,PermissionDeniedError:()=>it,NotFoundError:()=>F,IndexingInProgressError:()=>Sn,EditConflictError:()=>et,AgentS3Client:()=>Xt,AgentFSError:()=>Rt});var Y=R(()=>{G();wn();eu();m();Yi();W();Lf();Vi();ET()});var $o={};bt($o,{stopDaemon:()=>Uw,startDaemon:()=>Iw,daemonStatus:()=>Sw});import{spawn as Lw}from"child_process";import{readFileSync as Oe,writeFileSync as gw,unlinkSync as So,existsSync as Jn,openSync as Dw}from"fs";import{join as Ie}from"path";function Ue(){return Ie(V(),"agent-fs.pid")}function Ow(){return Ie(V(),"agent-fs.log")}function AT(){return Ie(V(),"agent-fs.sock")}function Iw(){let t=Ue();if(Jn(t)){let r=parseInt(Oe(t,"utf-8").trim());try{process.kill(r,0),console.log(`Daemon already running (PID: ${r})`);return}catch{So(t);let E=AT();if(Jn(E))try{So(E)}catch{}}}let n=Ow(),o=Dw(n,"a"),i=process.argv[1];if(!i)throw Error("Cannot determine entry script (process.argv[1] is empty). Daemon start aborted.");let e=Lw(process.execPath,[i,"server"],{detached:!0,stdio:["ignore",o,o]});if(e.unref(),e.pid)gw(t,String(e.pid)),console.log(`Daemon started (PID: ${e.pid})`),console.log(`Logs: ${n}`)}function Uw(){let t=Ue();if(!Jn(t)){console.log("Daemon is not running");return}let n=parseInt(Oe(t,"utf-8").trim());try{process.kill(n,"SIGTERM"),console.log(`Daemon stopped (PID: ${n})`)}catch{console.log(`Process ${n} not found (already stopped)`)}So(t);let o=AT();if(Jn(o))try{So(o)}catch{}}function Sw(){let t=Ue();if(!Jn(t))return{running:!1};let n=parseInt(Oe(t,"utf-8").trim());try{return process.kill(n,0),{running:!0,pid:n}}catch{return{running:!1}}}var Xo=R(()=>{Y()});var Ty={};import{Server as ny}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as oy}from"@modelcontextprotocol/sdk/server/stdio.js";import{Client as iy}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ey}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ListToolsRequestSchema as ry,CallToolRequestSchema as Ey}from"@modelcontextprotocol/sdk/types.js";var Bn,Ce,WT,uy,Pe,Me,fy;var KT=R(async()=>{Y();Bn=P(),Ce=process.env.AGENT_FS_API_URL??Bn.apiUrl??`http://${Bn.server.host}:${Bn.server.port}`,WT=process.env.AGENT_FS_API_KEY??Bn.apiKey??Bn.auth?.apiKey;if(!WT)console.error("Error: No API key. Register with `agent-fs auth register` or set AGENT_FS_API_KEY."),process.exit(1);uy=new ey(new URL(`${Ce}/mcp`),{requestInit:{headers:{Authorization:`Bearer ${WT}`}}}),Pe=new iy({name:"agent-fs-proxy",version:q});try{await Pe.connect(uy)}catch(t){console.error(`Cannot connect to agent-fs at ${Ce}.
|
|
177
|
+
Start a daemon with \`agent-fs daemon start\` or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1)}Me=new ny({name:"agent-fs",version:q},{capabilities:{tools:{}}});Me.setRequestHandler(ry,async()=>{return await Pe.listTools()});Me.setRequestHandler(Ey,async(t)=>{return await Pe.callTool(t.params)});fy=new oy;await Me.connect(fy);console.error("[agent-fs] MCP proxy connected to "+Ce)});import{z as pT}from"zod";function hT(t,n){let o=fn();for(let i of o){let e=Mt(i);if(!e)continue;t.tool(i,e.description,e.schema instanceof pT.ZodObject?e.schema.shape:{params:pT.any()},async(r,E)=>{let f=n(E),T=await k(f,i,r);return{content:[{type:"text",text:JSON.stringify(T,null,2)}]}})}}var jT=R(()=>{Y()});import{McpServer as ly}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as Yt}from"zod";function kT(t){let{db:n,s3:o,embeddingProvider:i,appUrl:e}=t,r=new ly({name:"agent-fs",version:q}),E=(f)=>{let T=f.authInfo;if(!T?.extra?.user)throw Error("No auth context \u2014 MCP must be accessed through the HTTP server");let l=T.extra.user,N=b(n,{userId:l.id});return{db:n,s3:o,orgId:N.orgId,driveId:N.driveId,userId:l.id,embeddingProvider:i,appUrl:e}};return hT(r,E),r.tool("health","Check agent-fs system health: database, S3, embeddings, version.",{},async(f,T)=>{let l={version:q};try{let N=E(T),A=await k(N,"ls",{path:"/"},{skipAuth:!0});l.database={ok:!0,rootEntries:A.entries?.length??0}}catch(N){l.database={ok:!1,error:N.message}}try{await o.listObjects("",{delimiter:"/"}),l.s3={ok:!0}}catch(N){l.s3={ok:!1,error:N.message}}return l.embeddings={configured:!!i},{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}),r.tool("whoami","Get current user identity, org memberships, and drive roles.",{},async(f,T)=>{let l=E(T),N=l.userId,w=p(n,N).map((D)=>{let C=vn(n,D.id);return{orgId:D.id,orgName:D.name,drives:C.map((Z)=>({driveId:Z.id,driveName:Z.name,role:At(n,N,Z.id)}))}}),g=T.authInfo?.extra?.user?.email,O={userId:N,...g?{email:g}:{},activeOrg:l.orgId,activeDrive:l.driveId,memberships:w};return{content:[{type:"text",text:JSON.stringify(O,null,2)}]}}),r.tool("member-list","List members of the current org, or a specific drive if driveId is provided.",{driveId:Yt.string().optional().describe("Drive ID to list members for. Omit for org members.")},async(f,T)=>{let l=E(T),N=f.driveId?Jt(n,f.driveId):pt(n,l.orgId);return{content:[{type:"text",text:JSON.stringify({members:N},null,2)}]}}),r.tool("member-invite","Invite a user to the current org by email. The user must already have an agent-fs account.",{email:Yt.string().describe("Email of the user to invite"),role:Yt.enum(["viewer","editor","admin"]).describe("Role to assign")},async(f,T)=>{let l=E(T);try{return kt(n,{orgId:l.orgId,email:f.email,role:f.role}),{content:[{type:"text",text:JSON.stringify({ok:!0,invited:f.email,role:f.role},null,2)}]}}catch(N){return{content:[{type:"text",text:JSON.stringify({error:N.message},null,2)}],isError:!0}}}),r.tool("member-update-role","Update a member's role in the current org or a specific drive.",{email:Yt.string().describe("Email of the member"),role:Yt.enum(["viewer","editor","admin"]).describe("New role"),driveId:Yt.string().optional().describe("Drive ID to update role for. Omit for org role.")},async(f,T)=>{let l=E(T);try{let N=Tn(n,f.email);if(!N)throw Error(`User with email ${f.email} not found`);if(f.driveId)Bt(n,{driveId:f.driveId,userId:N.id,role:f.role});else ht(n,{orgId:l.orgId,userId:N.id,role:f.role});return{content:[{type:"text",text:JSON.stringify({ok:!0,email:f.email,role:f.role},null,2)}]}}catch(N){return{content:[{type:"text",text:JSON.stringify({error:N.message},null,2)}],isError:!0}}}),r.tool("member-remove","Remove a member from the current org (cascades to all drives) or from a specific drive only.",{email:Yt.string().describe("Email of the member to remove"),driveId:Yt.string().optional().describe("Drive ID to remove from. Omit to remove from org.")},async(f,T)=>{let l=E(T);try{let N=Tn(n,f.email);if(!N)throw Error(`User with email ${f.email} not found`);if(f.driveId)Vt(n,{driveId:f.driveId,userId:N.id});else jt(n,{orgId:l.orgId,userId:N.id});return{content:[{type:"text",text:JSON.stringify({ok:!0,removed:f.email},null,2)}]}}catch(N){return{content:[{type:"text",text:JSON.stringify({error:N.message},null,2)}],isError:!0}}}),r}var dT=R(()=>{Y();jT()});function mT(t){return async(n,o)=>{let i=new URL(n.req.url).pathname;if(Ny.some((f)=>i===f||i.startsWith(f)))return o();let e=n.req.header("Authorization");if(!e?.startsWith("Bearer "))return n.json({error:"UNAUTHORIZED",message:"Missing or invalid Authorization header",suggestion:"Include 'Authorization: Bearer <api_key>' header"},401);let r=e.slice(7),E=ut(t,r);if(!E)return n.json({error:"UNAUTHORIZED",message:"Invalid API key",suggestion:"Register with POST /auth/register"},401);return n.set("user",E),o()}}var Ny;var zT=R(()=>{Y();Ny=["/auth/register","/health"]});function Ry(t){if(t instanceof F)return 404;if(t instanceof it)return 403;if(t instanceof et)return 409;if(t instanceof Sn)return 503;if(t instanceof c)return 400;if("code"in t)return 400;return 500}function bT(t,n){let o=Ry(t);if("toJSON"in t&&typeof t.toJSON==="function")return n.json(t.toJSON(),o);return n.json({error:"INTERNAL_ERROR",message:t.message},o)}var qT=R(()=>{Y()});function Po(t){let n=new Map;return setInterval(()=>{let o=Date.now()-60000;for(let[i,e]of n){let r=e.filter((E)=>E>o);if(r.length===0)n.delete(i);else n.set(i,r)}},300000).unref(),async(o,i)=>{let e=o.req.header("authorization")??"",r=e.startsWith("Bearer ")?e.slice(7):o.req.header("x-forwarded-for")??"unknown",E=Date.now(),f=E-60000,T=(n.get(r)??[]).filter((l)=>l>f);if(T.length>=t){let l=T[0],N=Math.ceil((l+60000-E)/1000);return o.header("Retry-After",String(N)),o.json({error:"RATE_LIMITED",message:"Too many requests"},429)}T.push(E),n.set(r,T),await i()}}import{Hono as Ay}from"hono";function sT(t){let n=new Ay;return n.post("/register",async(o)=>{let{email:i}=await o.req.json();if(!i||typeof i!=="string")return o.json({error:"VALIDATION_ERROR",message:"email is required"},400);try{let e=Et(t,{email:i}),r=p(t,e.user.id);return o.json({apiKey:e.apiKey,userId:e.user.id,orgId:r[0]?.id})}catch(e){if(e instanceof Error&&e.message.includes("UNIQUE"))return o.json({error:"CONFLICT",message:"User with this email already exists"},409);throw e}}),n.get("/me",(o)=>{let i=o.get("user");try{let e=b(t,{userId:i.id});return o.json({userId:i.id,email:i.email,defaultOrgId:e.orgId,defaultDriveId:e.driveId})}catch{return o.json({userId:i.id,email:i.email,defaultOrgId:null,defaultDriveId:null})}}),n}var cT=R(()=>{Y()});import{Hono as _y}from"hono";function xT(t,n,o=null,i){let e=new _y;return e.post("/:orgId/ops",async(r)=>{let E=r.get("user"),f=r.req.param("orgId"),T=await r.req.json(),{op:l,...N}=T;if(!l)return r.json({error:"VALIDATION_ERROR",message:"op is required in request body"},400);let A=N.driveId||N.drive_id;delete N.driveId,delete N.drive_id;let w=b(t,{userId:E.id,orgId:f,driveId:A}),g={db:t,s3:n,orgId:w.orgId,driveId:w.driveId,userId:E.id,embeddingProvider:o,appUrl:i},O=await k(g,l,N);return r.json(O)}),e}var aT=R(()=>{Y()});import{Hono as wy}from"hono";function tl(t){let n=new wy;return n.get("/",(o)=>{let i=o.get("user"),e=p(t,i.id);return o.json({orgs:e})}),n.post("/",async(o)=>{let i=o.get("user"),{name:e}=await o.req.json(),r=Kt(t,{name:e,userId:i.id});return o.json(r,201)}),n.get("/:orgId",(o)=>{let i=o.req.param("orgId"),e=Yn(t,i);if(!e)return o.json({error:"NOT_FOUND",message:"Org not found"},404);return o.json(e)}),n.get("/:orgId/drives",(o)=>{let i=o.get("user"),e=o.req.param("orgId"),r=Ot(t,e,i.id);return o.json({drives:r})}),n.post("/:orgId/drives",async(o)=>{let i=o.req.param("orgId"),{name:e}=await o.req.json(),r=Qt(t,{orgId:i,name:e});return o.json(r,201)}),n.post("/:orgId/members/invite",async(o)=>{let i=o.req.param("orgId"),{email:e,role:r}=await o.req.json();return kt(t,{orgId:i,email:e,role:r}),o.json({ok:!0})}),n.get("/:orgId/members",(o)=>{let i=o.req.param("orgId"),e=pt(t,i);return o.json({members:e})}),n.patch("/:orgId/members/:userId",async(o)=>{let i=o.req.param("orgId"),e=o.req.param("userId"),{role:r}=await o.req.json();try{return ht(t,{orgId:i,userId:e,role:r}),o.json({ok:!0})}catch(E){return o.json({error:"BAD_REQUEST",message:E.message},400)}}),n.delete("/:orgId/members/:userId",(o)=>{let i=o.req.param("orgId"),e=o.req.param("userId");try{return jt(t,{orgId:i,userId:e}),o.json({ok:!0})}catch(r){return o.json({error:"BAD_REQUEST",message:r.message},400)}}),n.get("/:orgId/drives/:driveId/members",(o)=>{let i=o.req.param("driveId"),e=Jt(t,i);return o.json({members:e})}),n.patch("/:orgId/drives/:driveId/members/:userId",async(o)=>{let i=o.req.param("driveId"),e=o.req.param("userId"),{role:r}=await o.req.json();try{return Bt(t,{driveId:i,userId:e,role:r}),o.json({ok:!0})}catch(E){return o.json({error:"BAD_REQUEST",message:E.message},400)}}),n.delete("/:orgId/drives/:driveId/members/:userId",(o)=>{let i=o.req.param("driveId"),e=o.req.param("userId");try{return Vt(t,{driveId:i,userId:e}),o.json({ok:!0})}catch(r){return o.json({error:"BAD_REQUEST",message:r.message},400)}}),n}var nl=R(()=>{Y()});import{Hono as yy}from"hono";function ol(){let t=new yy;return t.get("/openapi.json",(n)=>{return n.json(Uo())}),t}var il=R(()=>{Y()});import{Hono as Ly}from"hono";function el(t,n,o=null,i){let e=new Ly;return e.get("/:orgId/drives/:driveId/files/:filePath{.+}/raw",async(r)=>{let E=r.get("user"),f=r.req.param("orgId"),T=r.req.param("driveId"),l=b(t,{userId:E.id,orgId:f,driveId:T}),A=new URL(r.req.url).pathname.match(/\/files\/(.+)\/raw$/);if(!A)return r.json({error:"VALIDATION_ERROR",message:"Invalid file path"},400);let w=Cn(decodeURIComponent(A[1])),g=I(l.orgId,l.driveId,w);try{let O=await n.getObject(g),D=O.contentType||"application/octet-stream",C=xt({db:t,driveId:l.driveId},w),Z={"Content-Type":D,"Content-Length":String(O.body.length),"Cache-Control":"private, max-age=60"};if(C){if(Z.ETag=`"${C.version}"`,Z["X-Agent-FS-Version"]=String(C.version),C.contentHash)Z["X-Agent-FS-Content-Hash"]=C.contentHash;if(C.createdAt)Z["Last-Modified"]=new Date(C.createdAt).toUTCString()}return new Response(O.body.slice(),{status:200,headers:Z})}catch(O){if(O?.name==="NoSuchKey"||O?.$metadata?.httpStatusCode===404)return r.json({error:"NOT_FOUND",message:`File not found: ${w}`},404);throw O}}),e.put("/:orgId/drives/:driveId/files/:filePath{.+}/raw",async(r)=>{let E=r.get("user"),f=r.req.param("orgId"),T=r.req.param("driveId");if((r.req.header("Content-Type")??"").toLowerCase().startsWith("application/json"))return r.json({error:"VALIDATION_ERROR",message:"PUT /raw expects a binary body; use POST /ops with op=write for JSON-encoded content"},415);let N=b(t,{userId:E.id,orgId:f,driveId:T}),w=new URL(r.req.url).pathname.match(/\/files\/(.+)\/raw$/);if(!w)return r.json({error:"VALIDATION_ERROR",message:"Invalid file path"},400);let g=Cn(decodeURIComponent(w[1])),O,D=r.req.header("If-None-Match"),C=r.req.header("If-Match");if(D==="*")O=0;else if(C!==void 0){let Ul=C.replace(/^"|"$/g,""),Mo=Number(Ul);if(!Number.isInteger(Mo)||Mo<0)return r.json({error:"VALIDATION_ERROR",message:`If-Match must be a non-negative integer version, got: ${C}`},400);O=Mo}let Z=r.req.header("X-Agent-FS-Message")??void 0,_n=await r.req.arrayBuffer(),Ol=new Uint8Array(_n),Il={db:t,s3:n,orgId:N.orgId,driveId:N.driveId,userId:E.id,embeddingProvider:o,appUrl:i},zt=await Dt(Il,{path:g,bytes:Ol,message:Z,expectedVersion:O});return new Response(JSON.stringify(zt),{status:200,headers:{"Content-Type":"application/json",ETag:`"${zt.version}"`,"X-Agent-FS-Version":String(zt.version),...zt.contentHash&&{"X-Agent-FS-Content-Hash":zt.contentHash},"X-Agent-FS-Deduped":zt.deduped?"1":"0"}})}),e}var rl=R(()=>{Y()});import{Hono as gy}from"hono";import{cors as El}from"hono/cors";import{bodyLimit as Dy}from"hono/body-limit";import{WebStandardStreamableHTTPServerTransport as Oy}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";function ul(t,n,o=null){let i=new gy,e=P(),r=e.server?.cors?.origins??["*"];if(r.length===1&&r[0]==="*")i.use("*",El());else i.use("*",El({origin:r}));i.use("*",Dy({maxSize:52428800})),i.use("*",mT(t));let E=e.server?.rateLimit?.requestsPerMinute??1200;if(E>0)i.use("/orgs/*",Po(E)),i.use("/auth/*",Po(E)),i.use("/mcp",Po(E));return i.onError((f,T)=>bT(f,T)),i.get("/health",(f)=>f.json({ok:!0,version:q})),i.all("/mcp",async(f)=>{let T=f.get("user"),l=new Oy({sessionIdGenerator:void 0,enableJsonResponse:!0});return await kT({db:t,s3:n,embeddingProvider:o,appUrl:e.appUrl}).connect(l),l.handleRequest(f.req.raw,{authInfo:{token:f.req.header("Authorization")?.slice(7)??"",clientId:T.id,scopes:[],extra:{user:{id:T.id,email:T.email}}}})}),i.route("/auth",sT(t)),i.route("/orgs",tl(t)),i.route("/orgs",xT(t,n,o,e.appUrl)),i.route("/docs",ol()),i.route("/orgs",el(t,n,o,e.appUrl)),i}var fl=R(()=>{Y();dT();zT();qT();cT();aT();nl();il();rl()});function Lt(t,n,o){return{error:{http_status:t,code:n,message:o}}}function Iy(t){let n=String(t?.name??""),o=String(t?.message??t??"unknown error");if(n==="EditConflictError")return Lt(409,"EDIT_CONFLICT",o);if(n==="NotFoundError")return Lt(404,"NOT_FOUND",o);if(n==="PermissionDeniedError")return Lt(403,"PERMISSION_DENIED",o);if(n==="ValidationError")return Lt(415,"VALIDATION",o);if(n==="IndexingInProgressError")return Lt(503,"INDEXING_IN_PROGRESS",o);if(/no.*api.*key|no.*user/i.test(o))return Lt(401,"AUTH_MISSING",o);return Lt(500,"INTERNAL",o)}function nt(t){let n=t.resolveApiKey();if(!n){let i=Error("daemon has no API key configured");throw i.name="AuthError",i}let o=ut(t.db,n);if(!o){let i=Error("API key did not resolve to a user");throw i.name="AuthError",i}return{userId:o.id,email:o.email}}function Ut(t,n,o){try{let r=b(t.db,{userId:n,driveId:o});return{orgId:r.orgId,driveId:r.driveId}}catch{}let i=p(t.db,n);for(let r of i){let f=Ot(t.db,r.id,n).find((T)=>T.name===o);if(f)return{orgId:r.id,driveId:f.id}}let e=Error(`Drive not found: ${o}`);throw e.name="NotFoundError",e}function Gt(t,n,o,i){return{db:t.db,s3:t.s3,orgId:o,driveId:i,userId:n.userId,embeddingProvider:t.embeddingProvider,appUrl:t.appUrl}}async function Tl(t,n){if(!n||typeof n!=="object")return Lt(400,"VALIDATION","request body must be an object");let o=n;try{return await Uy(t,o)}catch(i){return Iy(i)}}async function Uy(t,n){switch(n.op){case"ping":return"pong";case"hello":return"ok";case"list_drives":{let o=nt(t),i=p(t.db,o.userId),e=[];for(let r of i){let E=Ot(t.db,r.id,o.userId);for(let f of E)e.push({slug:f.name,id:f.id,org_id:r.id})}return{drives:e}}case"default_drive_slug":{let o=nt(t),i=p(t.db,o.userId);for(let e of i){let r=Ot(t.db,e.id,o.userId),E=r.find((f)=>f.isDefault)??r[0];if(E)return{default_drive_slug:E.name}}return{default_drive_slug:null}}case"get_attr":{let o=nt(t),{orgId:i,driveId:e}=Ut(t,o.userId,n.drive),r=n.path,E=Gt(t,o,i,e);try{let f=await k(E,"stat",{path:r});return{attr:{kind:"File",size:f.size,mtime_unix:Math.floor(new Date(f.modifiedAt).getTime()/1000),version:f.currentVersion??null,content_hash:null}}}catch(f){if(String(f?.name)==="NotFoundError")try{let T=await k(E,"ls",{path:r});if(T&&Array.isArray(T.entries)&&T.entries.length>0)return{attr:{kind:"Dir",size:0,mtime_unix:0,version:null,content_hash:null}}}catch{}throw f}}case"read_dir":{let o=nt(t),{orgId:i,driveId:e}=Ut(t,o.userId,n.drive),r=n.path??"/",E=Gt(t,o,i,e);return{dir_entries:((await k(E,"ls",{path:r}))?.entries??[]).map((l)=>({name:l.name,kind:l.type==="directory"?"Dir":"File",size:l.size??0,mtime_unix:l.modifiedAt?Math.floor(new Date(l.modifiedAt).getTime()/1000):0,version:null,content_hash:null}))}}case"open_read":{let o=nt(t),{orgId:i,driveId:e}=Ut(t,o.userId,n.drive),r=n.path,E=I(i,e,r),f=await t.s3.getObject(E),T=xt({db:t.db,driveId:e},r);return{open_read:{bytes:f.body,version:T?.version??0,content_hash:T?.contentHash??"",size:f.body.length,mtime_unix:T?.createdAt?Math.floor(new Date(T.createdAt).getTime()/1000):0}}}case"open_write":{let o=nt(t),{orgId:i,driveId:e}=Ut(t,o.userId,n.drive),r=n.path,E=Gt(t,o,i,e),f=Sy(n.bytes),T=await Dt(E,{path:r,bytes:f,expectedVersion:n.base_version??void 0});return{open_write:{version:T.version,content_hash:T.contentHash??"",deduped:T.deduped??!1}}}case"create_file":{let o=nt(t),{orgId:i,driveId:e}=Ut(t,o.userId,n.drive),r=n.path,E=Gt(t,o,i,e),f=await Dt(E,{path:r,bytes:new Uint8Array(0),expectedVersion:0});return{open_write:{version:f.version,content_hash:f.contentHash??"",deduped:f.deduped??!1}}}case"truncate":{let o=nt(t),{orgId:i,driveId:e}=Ut(t,o.userId,n.drive),r=n.path,E=n.size??0,f=Gt(t,o,i,e),T=I(i,e,r),l=(await t.s3.getObject(T)).body,N=l.subarray(0,Math.min(E,l.length)),A=await Dt(f,{path:r,bytes:N});return{open_write:{version:A.version,content_hash:A.contentHash??"",deduped:A.deduped??!1}}}case"unlink":{let o=nt(t),{orgId:i,driveId:e}=Ut(t,o.userId,n.drive),r=n.path,E=Gt(t,o,i,e);return await k(E,"rm",{path:r}),"ok"}case"rename":{let o=nt(t),{orgId:i,driveId:e}=Ut(t,o.userId,n.drive),r=n.from_path,E=n.to_path,f=Gt(t,o,i,e);return await k(f,"mv",{from:r,to:E}),"ok"}case"mkdir":return nt(t),"ok";case"rmdir":{let o=nt(t),{orgId:i,driveId:e}=Ut(t,o.userId,n.drive),r=n.path,E=Gt(t,o,i,e);if((await k(E,"ls",{path:r}))?.entries?.length>0)return Lt(409,"VALIDATION","directory not empty");return"ok"}case"record_conflict":return console.warn("[agent-fs ipc] conflict:",JSON.stringify({drive:n.drive,path:n.path,base_version:n.base_version,head_version:n.head_version,bytes:n.bytes})),"ok";case"write_status":return console.warn("[agent-fs ipc] status:",n.line),"ok";default:return Lt(400,"VALIDATION",`unknown op: ${n.op}`)}}function Sy(t){if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(Array.isArray(t))return new Uint8Array(t);if(t==null)return new Uint8Array(0);if(typeof t==="string")return new TextEncoder().encode(t);if(typeof Buffer<"u"&&Buffer.isBuffer(t))return new Uint8Array(t);return new Uint8Array(0)}var ll=R(()=>{Y()});import{unlinkSync as Nl,existsSync as $y,chmodSync as Xy}from"fs";import{Packr as Cy,Unpackr as Py}from"msgpackr";function Rl(t,n){if($y(t))try{Nl(t)}catch{}let o=Bun.listen({unix:t,socket:{open(i){i.data={buf:Buffer.alloc(0)}},data(i,e){i.data.buf=Buffer.concat([i.data.buf,e]),Yy(i,n).catch((r)=>{console.error("[agent-fs ipc] frame drain failed:",r),i.end()})},close(i){i.data.buf=Buffer.alloc(0)},error(i,e){console.error("[agent-fs ipc] socket error:",e)}}});try{Xy(t,384)}catch{}return{socketPath:t,stop:()=>{o.stop(!0);try{Nl(t)}catch{}}}}async function Yy(t,n){while(!0){let o=t.data;if(o.buf.length<4)return;let i=o.buf.readUInt32BE(0);if(i===0||i>My){console.error(`[agent-fs ipc] implausible frame length ${i}; closing`),t.end();return}if(o.buf.length<4+i)return;let e=o.buf.subarray(4,4+i);o.buf=o.buf.subarray(4+i);let r;try{r=vy.unpack(e)}catch(E){console.error("[agent-fs ipc] decode failed:",E),t.end();return}Gy(t,n,r)}}async function Gy(t,n,o){let i;try{i=await Tl(n,o.body)}catch(f){i={Error:{http_status:0,code:null,message:String(f?.message??f)}}}let e={id:o.id,body:i},r=Fy.pack(e),E=Buffer.alloc(4);E.writeUInt32BE(r.length,0),t.write(Buffer.concat([E,r]))}var My=67108864,Fy,vy;var Al=R(()=>{ll();Fy=new Cy({useRecords:!1}),vy=new Py({useRecords:!1})});var Qy={};import{join as Hy}from"path";function Ll(){if(console.log("Shutting down..."),Fe.stop(),ve)ve.stop();process.exit(0)}var Rn,wl,yl,Ye=null,Zy,Fe,_l,ve=null;var gl=R(async()=>{Y();fl();Al();Rn=P(),wl=St(),yl=new Xt(Rn.s3);try{Ye=await ln(Rn.embedding)}catch(t){console.warn("Embedding provider unavailable, semantic search disabled:",t)}Zy=ul(wl,yl,Ye),Fe=Bun.serve({fetch:Zy.fetch,port:Rn.server.port,hostname:Rn.server.host});console.log(`agent-fs daemon running on http://${Fe.hostname}:${Fe.port}`);_l=Hy(V(),"agent-fs.sock");try{ve=Rl(_l,{db:wl,s3:yl,embeddingProvider:Ye,appUrl:Rn.appUrl,resolveApiKey:()=>Rn.auth?.apiKey??null}),console.log(`agent-fs IPC listening on ${_l}`)}catch(t){console.warn("IPC listener unavailable:",t)}process.on("SIGTERM",Ll);process.on("SIGINT",Ll)});Y();import{Command as Jy}from"commander";Y();class Le{baseUrl;apiKey;constructor(){let t=P();this.baseUrl=process.env.AGENT_FS_API_URL??t.apiUrl??`http://${t.server.host}:${t.server.port}`,this.apiKey=process.env.AGENT_FS_API_KEY??t.apiKey??t.auth.apiKey}async request(t,n){let o=new Headers(n?.headers);if(this.apiKey)o.set("Authorization",`Bearer ${this.apiKey}`);o.set("Content-Type","application/json");let i;try{i=await fetch(`${this.baseUrl}${t}`,{...n,headers:o})}catch(r){throw Error(`Cannot connect to agent-fs daemon at ${this.baseUrl}. Is it running? Start with: agent-fs daemon start`)}let e;try{e=await i.json()}catch{let r=await i.text().catch(()=>"");throw Error(`Unexpected response from daemon (${i.status}): ${r||"empty"}`)}if(!i.ok){let r=e.message??e.error??"Request failed",E=e.suggestion?`
|
|
178
|
+
Suggestion: ${e.suggestion}`:"";throw Error(`${r}${E}`)}return e}async get(t){return this.request(t)}async post(t,n){return this.request(t,{method:"POST",body:JSON.stringify(n)})}async patch(t,n){return this.request(t,{method:"PATCH",body:JSON.stringify(n)})}async del(t){return this.request(t,{method:"DELETE"})}async callOp(t,n,o){return this.post(`/orgs/${t}/ops`,{op:n,...o})}async getMe(){return this.get("/auth/me")}setApiKey(t){this.apiKey=t}async putRaw(t,n,o,i,e={}){let r=new Headers;if(r.set("Content-Type","application/octet-stream"),this.apiKey)r.set("Authorization",`Bearer ${this.apiKey}`);if(e.ifMatch!==void 0)r.set("If-Match",String(e.ifMatch));if(e.contentHash)r.set("X-Agent-FS-Content-Hash",e.contentHash);if(e.message)r.set("X-Agent-FS-Message",e.message);let E=encodeURI(o.replace(/^\/+/,"")),f=`${this.baseUrl}/orgs/${t}/drives/${n}/files/${E}/raw`,T;try{T=await fetch(f,{method:"PUT",headers:r,body:i})}catch(A){throw Error(`Cannot connect to agent-fs daemon at ${this.baseUrl}. Is it running? Start with: agent-fs daemon start`)}let l,N=await T.text();try{l=JSON.parse(N)}catch{throw Error(`Unexpected response from daemon (${T.status}): ${N||"empty"}`)}if(!T.ok){let A=l.message??l.error??"Request failed",w=l.suggestion?`
|
|
179
|
+
Suggestion: ${l.suggestion}`:"";throw Error(`${A}${w}`)}return{version:l.version,path:l.path??o,deduped:Boolean(l.deduped),contentHash:T.headers.get("X-Agent-FS-Content-Hash")??l.contentHash??null,size:l.size??i.length}}async getRaw(t,n,o){let i=new Headers;if(this.apiKey)i.set("Authorization",`Bearer ${this.apiKey}`);let e=encodeURI(o.replace(/^\/+/,"")),r=`${this.baseUrl}/orgs/${t}/drives/${n}/files/${e}/raw`,E;try{E=await fetch(r,{method:"GET",headers:i})}catch(f){throw Error(`Cannot connect to agent-fs daemon at ${this.baseUrl}. Is it running? Start with: agent-fs daemon start`)}if(!E.ok){let f,T=await E.text().catch(()=>"");try{f=JSON.parse(T)}catch{throw Error(`Unexpected response from daemon (${E.status}): ${T||"empty"}`)}let l=f.message??f.error??"Request failed",N=f.suggestion?`
|
|
180
|
+
Suggestion: ${f.suggestion}`:"";throw Error(`${l}${N}`)}return{bytes:new Uint8Array(await E.arrayBuffer()),contentType:E.headers.get("Content-Type"),version:m_(E.headers.get("X-Agent-FS-Version")),contentHash:E.headers.get("X-Agent-FS-Content-Hash")}}}function m_(t){if(t===null)return null;let n=Number(t);return Number.isInteger(n)?n:null}Y();import{Command as _w}from"commander";function Nn(t){if(t<1024)return`${t} B`;if(t<1048576)return`${(t/1024).toFixed(1)} KB`;if(t<1073741824)return`${(t/1048576).toFixed(1)} MB`;return`${(t/1073741824).toFixed(1)} GB`}function dt(t){if(!t)return"-";let n=typeof t==="string"?new Date(t):t;if(isNaN(n.getTime()))return String(t);return n.toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"Z")}function Qn(t,n){return t.length>=n?t:t+" ".repeat(n-t.length)}function ge(t,n){return t.length>=n?t:" ".repeat(n-t.length)+t}function z_(t){let n=t.entries??[];if(n.length===0)return"(empty directory)";let o=Math.max(4,...n.map((f)=>String(f.name).length)),i=Math.max(4,...n.map((f)=>String(f.type).length)),e=Math.max(4,...n.map((f)=>Nn(f.size??0).length)),r=Qn("NAME",o)+" "+Qn("TYPE",i)+" "+ge("SIZE",e)+" MODIFIED",E=n.map((f)=>Qn(f.name,o)+" "+Qn(f.type,i)+" "+ge(Nn(f.size??0),e)+" "+dt(f.modifiedAt));return[r,...E].join(`
|
|
181
|
+
`)}function TT(t){let o=(t.content??"").split(`
|
|
182
|
+
`);if(o.length>0&&o[o.length-1]==="")o.pop();let i=t.offset??1,e=String(i+o.length-1).length;return o.map((r,E)=>`${ge(String(i+E),e)} ${r}`).join(`
|
|
183
|
+
`)}function b_(t){let n=[["Path",t.path??"-"],["Size",Nn(t.size??0)],["Content-Type",t.contentType??"-"],["Author",t.author??"-"],["Version",t.currentVersion!=null?String(t.currentVersion):"-"],["Created",dt(t.createdAt)],["Modified",dt(t.modifiedAt)],["Deleted",t.isDeleted?"yes":"no"]];if(t.embeddingStatus)n.push(["Embedding",t.embeddingStatus]);if(t.appUrl)n.push(["App URL",t.appUrl]);let o=Math.max(...n.map(([i])=>i.length));return n.map(([i,e])=>`${Qn(i+":",o+1)} ${e}`).join(`
|
|
184
|
+
`)}function q_(t){let n=t.versions??[];if(n.length===0)return"(no version history)";return n.map((o)=>{let i=[`v${o.version} ${dt(o.createdAt)} ${o.author??"-"} [${o.operation}]`];if(o.message)i.push(` ${o.message}`);if(o.diffSummary)i.push(` ${o.diffSummary}`);return i.join(`
|
|
184
185
|
`)}).join(`
|
|
185
186
|
|
|
186
|
-
`)}function
|
|
187
|
-
`)}function
|
|
188
|
-
`)}function
|
|
187
|
+
`)}function s_(t){return`\u2713 wrote ${t.path} (v${t.version}, ${Nn(t.size??0)})`}function c_(t){return`\u2713 edited ${t.path} (v${t.version}, ${t.changes} change${t.changes!==1?"s":""})`}function x_(t){return`\u2713 appended (v${t.version}, ${Nn(t.size??0)})`}function a_(t){return t.deleted?`\u2713 deleted ${t.path}`:`(not found: ${t.path})`}function tw(t){return`\u2713 moved ${t.from} -> ${t.to} (v${t.version})`}function nw(t){return`\u2713 copied ${t.from} -> ${t.to} (v${t.version})`}function ow(t){let n=t.tree??[];if(n.length===0)return"(empty)";let o=[];function i(e,r){for(let E=0;E<e.length;E++){let f=e[E],T=E===e.length-1,l=T?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",N=f.type==="directory"?"/":"";if(o.push(`${r}${l}${f.name}${N}`),f.children&&f.children.length>0){let A=r+(T?" ":"\u2502 ");i(f.children,A)}}}return i(n,""),o.join(`
|
|
188
|
+
`)}function iw(t){let n=t.matches??[];if(n.length===0)return"(no matches)";return n.map((o)=>`${o.path}:${o.lineNumber}: ${o.content}`).join(`
|
|
189
|
+
`)}function ew(t){let n=t.matches??[];if(n.length===0)return t.hint?`(no matches) ${t.hint}`:"(no matches)";let o=n.map((i)=>`${i.path} (rank: ${typeof i.rank==="number"?i.rank.toFixed(2):i.rank})
|
|
189
190
|
${i.snippet}`);if(t.hint)o.push(`
|
|
190
191
|
hint: ${t.hint}`);return o.join(`
|
|
191
192
|
|
|
192
|
-
`)}function
|
|
193
|
+
`)}function fT(t){let n=t.results??[];if(n.length===0)return"(no results)";return n.map((o)=>`${o.path} (score: ${typeof o.score==="number"?o.score.toFixed(3):o.score})`+(o.author?` by ${o.author}`:"")+`
|
|
193
194
|
${o.snippet}`).join(`
|
|
194
195
|
|
|
195
|
-
`)}function
|
|
196
|
-
`)}function
|
|
197
|
-
`)}function
|
|
196
|
+
`)}function rw(t){let n=t.matches??[];if(n.length===0)return"(no matches)";return n.map((o)=>`${o.path} ${Nn(o.size??0)} ${dt(o.modifiedAt)}`).join(`
|
|
197
|
+
`)}function Ew(t){let n=t.changes??[];if(n.length===0)return"(no changes)";return n.map((o)=>{let i=o.type==="add"?"+":o.type==="remove"?"-":" ",e=o.lineNumber!=null?`${o.lineNumber}: `:"";return`${i} ${e}${o.content}`}).join(`
|
|
198
|
+
`)}function uw(t){return TT(t)}function fw(t){return`\u2713 reverted to v${t.revertedTo} (new version: v${t.version})`}function Tw(t){let n=t.entries??[];if(n.length===0)return"(no recent activity)";return n.map((o)=>`${o.path} v${o.version} ${dt(o.createdAt)} ${o.author??"-"} [${o.operation}]`+(o.message?`
|
|
198
199
|
${o.message}`:"")).join(`
|
|
199
200
|
|
|
200
|
-
`)}function
|
|
201
|
+
`)}function lw(t){let n=[];if(n.push(`reindexed: ${t.reindexed??0}`),t.failed)n.push(`failed: ${t.failed}`);if(t.skipped)n.push(`skipped: ${t.skipped}`);return n.join(", ")}function Nw(t){let n=`${t.url}
|
|
201
202
|
|
|
202
|
-
Expires: ${
|
|
203
|
-
App: ${t.appUrl}`;return n}var
|
|
203
|
+
Expires: ${dt(t.expiresAt)} (${t.expiresIn}s)`;if(t.appUrl)n+=`
|
|
204
|
+
App: ${t.appUrl}`;return n}var Rw={ls:z_,cat:TT,stat:b_,log:q_,write:s_,edit:c_,append:x_,rm:a_,mv:tw,cp:nw,tree:ow,grep:iw,fts:ew,search:fT,"vec-search":fT,glob:rw,diff:Ew,tail:uw,revert:fw,recent:Tw,reindex:lw,"signed-url":Nw};function Aw(t,n){let o=Rw[t];if(o)return o(n);return JSON.stringify(n,null,2)}function De(t,n,o){if(o)console.log(JSON.stringify(n,null,2));else console.log(Aw(t,n))}var ww=[{name:"write",args:[{name:"path",required:!0}],options:[{flag:"--content <text>",description:"File content (reads stdin if omitted)"},{flag:"--file <path>",description:"Read bytes from a local file and upload without text decoding"},{flag:"-m, --message <msg>",description:"Version message"},{flag:"--expected-version <n>",description:"Fail if file is not at this version (optimistic concurrency)"}]},{name:"cat",args:[{name:"path",required:!0}],options:[{flag:"--offset <n>",description:"Line offset"},{flag:"--limit <n>",description:"Max lines"}]},{name:"edit",args:[{name:"path",required:!0}],options:[{flag:"--old <string>",description:"Text to replace"},{flag:"--new <string>",description:"Replacement text"},{flag:"-m, --message <msg>",description:"Version message"}]},{name:"append",args:[{name:"path",required:!0}],options:[{flag:"--content <text>",description:"Content to append"},{flag:"-m, --message <msg>",description:"Version message"}]},{name:"ls",args:[{name:"path",required:!1}],options:[]},{name:"stat",args:[{name:"path",required:!0}],options:[]},{name:"rm",args:[{name:"path",required:!0}],options:[]},{name:"mv",args:[{name:"from",required:!0},{name:"to",required:!0}],options:[{flag:"-m, --message <msg>",description:"Version message"}]},{name:"cp",args:[{name:"from",required:!0},{name:"to",required:!0}],options:[]},{name:"tail",args:[{name:"path",required:!0}],options:[{flag:"-n, --lines <n>",description:"Number of lines (default: 20)"}]},{name:"log",args:[{name:"path",required:!0}],options:[{flag:"--limit <n>",description:"Max entries"}]},{name:"diff",args:[{name:"path",required:!0}],options:[{flag:"--v1 <n>",description:"First version"},{flag:"--v2 <n>",description:"Second version"}]},{name:"revert",args:[{name:"path",required:!0}],options:[{flag:"--to <n>",description:"Version to revert to"}]},{name:"recent",args:[{name:"path",required:!1}],options:[{flag:"--since <duration>",description:"Time filter (e.g., 1h, 24h)"},{flag:"--limit <n>",description:"Max entries"}]},{name:"grep",args:[{name:"pattern",required:!0},{name:"path",required:!0}],options:[]},{name:"fts",args:[{name:"pattern",required:!0}],options:[{flag:"--path <prefix>",description:"Path prefix filter"}]},{name:"search",args:[{name:"query",required:!0}],options:[{flag:"--limit <n>",description:"Max results"}]},{name:"vec-search",args:[{name:"query",required:!0}],options:[{flag:"--limit <n>",description:"Max results"}]},{name:"reindex",args:[],options:[{flag:"--path <prefix>",description:"Path prefix filter"}]},{name:"tree",args:[{name:"path",required:!1}],options:[{flag:"--depth <n>",description:"Max recursion depth"}]},{name:"glob",args:[{name:"pattern",required:!0}],options:[{flag:"--path <prefix>",description:"Path prefix filter"}]},{name:"signed-url",args:[{name:"path",required:!0}],options:[{flag:"--expires-in <seconds>",description:"Expiry in seconds (default: 86400 = 24h)"}]}];function lT(t,n,o,i){for(let e of ww){let r=Mt(e.name),E=new _w(e.name).description(r?.description??e.name);for(let f of e.args)if(f.required)E.argument(`<${f.name}>`);else E.argument(`[${f.name}]`);for(let f of e.options)E.option(f.flag,f.description);E.action(async(...f)=>{let l={...f[f.length-2]},N=null;for(let A=0;A<e.args.length;A++)if(f[A]!==void 0)l[e.args[A].name]=f[A];if(e.name==="write"){if(l.file&&l.content!==void 0)console.error("Error: use either --file or --content, not both"),process.exit(1);if(l.file)N=new Uint8Array(await Bun.file(l.file).arrayBuffer()),delete l.file;else if(l.content===void 0&&!process.stdin.isTTY)N=new Uint8Array(await Bun.stdin.arrayBuffer())}if(e.name==="append"&&l.content===void 0)if(!process.stdin.isTTY)l.content=await Bun.stdin.text();else console.error("Error: --content required (or pipe content via stdin)"),process.exit(1);if(e.name==="write"&&l.content===void 0&&N===null)console.error("Error: --content or --file required (or pipe content via stdin)"),process.exit(1);if(l["expected-version"]!==void 0)l.expectedVersion=l["expected-version"],delete l["expected-version"];if(l.old!==void 0)l.old_string=l.old,delete l.old;if(l.new!==void 0)l.new_string=l.new,delete l.new;if(e.name==="revert"&&l.to!==void 0)l.version=l.to,delete l.to;if(l["expires-in"]!==void 0)l.expiresIn=l["expires-in"],delete l["expires-in"];for(let A of["offset","limit","lines","v1","v2","version","expectedVersion","depth","expiresIn"])if(l[A]!==void 0)l[A]=parseInt(l[A]);try{let A=await o(),w=t.opts().drive??P().defaultDrive;if(w)l.driveId=w;if(e.name==="write"&&N!==null){if(!i)throw Error("Cannot resolve drive context for raw upload");let O=await n.putRaw(A,await i(A),l.path,N,{ifMatch:l.expectedVersion,message:l.message});De(e.name,O,t.opts().json);return}let g=await n.callOp(A,e.name,l);De(e.name,g,t.opts().json)}catch(A){if(A?.cause?.code==="ECONNREFUSED"||A?.message?.includes("fetch failed"))console.error(`Cannot connect to agent-fs daemon.
|
|
204
205
|
Start with: agent-fs daemon start
|
|
205
|
-
Or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1);console.error(`Error: ${
|
|
206
|
-
API key saved to config.`)}import{Command as
|
|
206
|
+
Or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1);console.error(`Error: ${A.message}`),process.exit(1)}}),t.addCommand(E)}}Y();import{Command as yw}from"commander";function RT(t){let n=new yw("auth").description("Authentication commands");return n.command("register").argument("<email>","Email address").description("Register a new user").action(async(o)=>{try{let i=await t.post("/auth/register",{email:o});NT(i,t)}catch{try{let i=St(),e=Et(i,{email:o}),r=p(i,e.user.id);NT({apiKey:e.apiKey,userId:e.user.id,orgId:r[0]?.id},t)}catch(i){if(i.message?.includes("UNIQUE"))console.error("Error: User with this email already exists.");else console.error(`Error: ${i.message}`);process.exit(1)}}}),n.command("whoami").description("Show current user info").action(async()=>{try{let o=await t.get("/auth/me");console.log(JSON.stringify(o,null,2))}catch{try{let{getConfig:o,getUserByApiKey:i,createDatabase:e,listUserOrgs:r}=await Promise.resolve().then(() => (Y(),uT)),E=o();if(!E.auth.apiKey)console.error("Not logged in. Run: agent-fs auth register <email>"),process.exit(1);let f=e(),T=i(f,E.auth.apiKey);if(!T)console.error("Invalid API key in config."),process.exit(1);let l=r(f,T.id);console.log(JSON.stringify({...T,orgs:l},null,2))}catch(o){console.error(`Error: ${o.message}`),process.exit(1)}}}),n}function NT(t,n){console.log("Registered successfully!"),console.log(`API Key: ${t.apiKey}`),console.log(`User ID: ${t.userId}`),console.log(`Org ID: ${t.orgId}`),U("auth.apiKey",t.apiKey),n.setApiKey(t.apiKey),console.log(`
|
|
207
|
+
API key saved to config.`)}import{Command as $w}from"commander";function _T(){let t=new $w("daemon").description("Daemon lifecycle management");return t.command("start").description("Start the agent-fs daemon").action(async()=>{let{startDaemon:n}=await Promise.resolve().then(() => (Xo(),$o));n()}),t.command("stop").description("Stop the agent-fs daemon").action(async()=>{let{stopDaemon:n}=await Promise.resolve().then(() => (Xo(),$o));n()}),t.command("status").description("Check daemon status").action(async()=>{let{daemonStatus:n}=await Promise.resolve().then(() => (Xo(),$o)),o=n();if(o.running)console.log(`Daemon running (PID: ${o.pid})`);else console.log("Daemon is not running")}),t}Y();import{Command as Xw}from"commander";import{existsSync as wT}from"fs";function yT(){let t=new Xw("config").description("Configuration management");return t.command("get").argument("<key>","Config key (dot notation, e.g., s3.bucket)").description("Get a config value").action((n)=>{let o=P(),i=n.split("."),e=o;for(let r of i)e=e?.[r];if(e===void 0)console.error(`Key not found: ${n}`),process.exit(1);console.log(typeof e==="object"?JSON.stringify(e,null,2):String(e))}),t.command("set").argument("<key>","Config key").argument("<value>","Config value").description("Set a config value").action((n,o)=>{let i=o;try{i=JSON.parse(o)}catch{}U(n,i),console.log(`Set ${n} = ${JSON.stringify(i)}`)}),t.command("list").description("Show all config").action(()=>{console.log(JSON.stringify(P(),null,2))}),t.command("validate").description("Check that config, database, S3, and embeddings are healthy").action(async()=>{let n=[],o=P(),i=wT(x());n.push({name:"Config file",ok:i,message:i?x():"Not found \u2014 run `agent-fs onboard`"});let r=["endpoint","bucket","accessKeyId","secretAccessKey"].filter((N)=>!o.s3[N]);if(n.push({name:"S3 config",ok:r.length===0,message:r.length===0?`${o.s3.provider} \u2192 ${o.s3.endpoint}/${o.s3.bucket}`:`Missing: ${r.join(", ")}`}),r.length===0)try{await new Xt(o.s3).listObjects(""),n.push({name:"S3 connectivity",ok:!0,message:"Connected"})}catch(N){n.push({name:"S3 connectivity",ok:!1,message:N.message||"Connection failed"})}let E=wT(Ht());n.push({name:"Database",ok:E,message:E?Ht():"Not found \u2014 run `agent-fs onboard`"}),n.push({name:"Auth",ok:!!o.auth.apiKey,message:o.auth.apiKey?"API key configured":"No API key \u2014 run `agent-fs onboard`"});let f=o.embedding.provider,T=!!o.embedding.apiKey||!!process.env.OPENAI_API_KEY||!!process.env.GEMINI_API_KEY;if(f==="openai"||f==="gemini")if(T)try{let N=await ln(o.embedding);n.push({name:"Embeddings",ok:!!N,message:N?`${f} ready`:`${f} configured but failed to init`})}catch(N){n.push({name:"Embeddings",ok:!1,message:N.message})}else n.push({name:"Embeddings",ok:!1,message:`${f} selected but no API key`});else n.push({name:"Embeddings",ok:!0,message:"local/disabled (semantic search may be unavailable)"});console.log(`
|
|
207
208
|
agent-fs health check
|
|
208
|
-
`);let
|
|
209
|
-
${f.name} [${f.role}]${
|
|
210
|
-
This invites the user to the organization that owns the current drive. The user will have access to all drives in the org based on their role.`).action(async(i,e)=>{try{let r=await n();await t.post(`/orgs/${r}/members/invite`,{email:i,role:e.role}),console.log(`Invited ${i} as ${e.role}`)}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o}Y();import{Command as
|
|
209
|
+
`);let l=!0;for(let N of n){let A=N.ok?"\u2713":"\u2717";if(console.log(` ${A} ${N.name}: ${N.message}`),!N.ok)l=!1}if(console.log(),l)console.log("All checks passed.");else console.log("Some checks failed. Fix the issues above and re-run."),process.exit(1)}),t}Y();import{Command as Cw}from"commander";function LT(t,n){let o=new Cw("drive").description("Drive management");return o.command("list").description("List drives (all orgs unless --org is set)").action(async()=>{let i=o.parent?.opts().json;try{let e=o.parent?.opts().org;if(e){let f=await t.get(`/orgs/${e}/drives`);if(i){console.log(JSON.stringify(f,null,2));return}for(let T of f.drives){let l=T.isDefault?" (default)":"";console.log(`${T.id} ${T.name}${l}`)}return}let{orgs:r}=await t.get("/orgs");if(i){let f=[];for(let T of r){let{drives:l}=await t.get(`/orgs/${T.id}/drives`);f.push({orgId:T.id,orgName:T.name,drives:l})}console.log(JSON.stringify(f,null,2));return}if(!r||r.length===0){console.log("(no orgs)");return}let E=P();for(let f of r){let T=[];if(f.isPersonal)T.push("personal");if(E.defaultOrg===f.id)T.push("active");let l=T.length>0?` (${T.join(", ")})`:"";console.log(`
|
|
210
|
+
${f.name} [${f.role}]${l}`);let{drives:N}=await t.get(`/orgs/${f.id}/drives`);for(let A of N){let w=[];if(A.isDefault)w.push("default");if(E.defaultDrive===A.id)w.push("active");let g=w.length>0?` (${w.join(", ")})`:"";console.log(` ${A.id} ${A.name}${g}`)}}}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}}),o.command("create").argument("<name>","Drive name").description("Create a new drive").action(async(i)=>{try{let e=await n(),r=await t.post(`/orgs/${e}/drives`,{name:i});console.log(JSON.stringify(r,null,2))}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}}),o.command("current").description("Show current drive context").action(async()=>{let i=o.parent?.opts().json;try{let e=P(),r=await t.getMe(),E=e.defaultOrg??r.defaultOrgId;if(!E)console.error("Error: No org context. Run 'agent-fs auth register' first."),process.exit(1);let{drives:f}=await t.get(`/orgs/${E}/drives`),T;if(e.defaultDrive)T=f.find((N)=>N.id===e.defaultDrive);if(!T)T=f.find((N)=>N.isDefault)??f[0]??null;let l=e.defaultOrg?"config (org switch)":"server default";if(i)console.log(JSON.stringify({orgId:E,drive:T,source:l},null,2));else console.log(`org: ${E}`),console.log(`drive: ${T?.id??"(none)"} ${T?.name??""}`),console.log(`source: ${l}`)}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}}),o.command("switch").argument("<driveId>","Drive ID to switch to").description("Set default drive context").action(async(i)=>{try{let{orgs:e}=await t.get("/orgs"),r=null,E=null;for(let f of e){let{drives:T}=await t.get(`/orgs/${f.id}/drives`),l=T.find((N)=>N.id===i);if(l){r=l,E=f;break}}if(!r)console.error(`Error: Drive ${i} not found in any of your orgs.`),process.exit(1);U("defaultOrg",E.id),U("defaultDrive",i),console.log(`Switched to drive: ${r.name} (org: ${E.name})`)}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}}),o.command("invite").argument("<email>","User email to invite").requiredOption("--role <role>","Role: viewer, editor, or admin").description("Invite a user to the current org").addHelpText("after",`
|
|
211
|
+
This invites the user to the organization that owns the current drive. The user will have access to all drives in the org based on their role.`).action(async(i,e)=>{try{let r=await n();await t.post(`/orgs/${r}/members/invite`,{email:i,role:e.role}),console.log(`Invited ${i} as ${e.role}`)}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o}Y();import{Command as Pw}from"commander";function gT(t){let n=new Pw("org").description("Org management");return n.command("list").description("List orgs you belong to").action(async()=>{let o=n.parent?.opts().json;try{let{orgs:i}=await t.get("/orgs");if(o){console.log(JSON.stringify(i,null,2));return}if(!i||i.length===0){console.log("(no orgs)");return}let e=P();for(let r of i){let E=[];if(r.isPersonal)E.push("personal");if(e.defaultOrg===r.id)E.push("active");let f=E.length>0?` (${E.join(", ")})`:"";console.log(`${r.id} ${r.name} [${r.role}]${f}`)}}catch(i){console.error(`Error: ${i.message}`),process.exit(1)}}),n.command("current").description("Show current org context").action(async()=>{let o=n.parent?.opts().json;try{let i=P(),e=await t.getMe(),r=i.defaultOrg??e.defaultOrgId;if(!r)console.error("Error: No org context. Run 'agent-fs auth register' first."),process.exit(1);let E=await t.get(`/orgs/${r}`),f=i.defaultOrg?"config (org switch)":"server default";if(o)console.log(JSON.stringify({...E,source:f},null,2));else console.log(`${E.id} ${E.name}${E.isPersonal?" (personal)":""}`),console.log(`source: ${f}`)}catch(i){console.error(`Error: ${i.message}`),process.exit(1)}}),n.command("switch").argument("<orgId>","Org ID to switch to").description("Set default org context").action(async(o)=>{try{let i=await t.get(`/orgs/${o}`);U("defaultOrg",o),U("defaultDrive",void 0),console.log(`Switched to org: ${i.name} (${o})`)}catch(i){console.error(`Error: ${i.message}`),process.exit(1)}}),n}import{Command as Zw}from"commander";Y();import{Command as Mw}from"commander";import{execSync as mt}from"child_process";import{existsSync as Fw}from"fs";function Co(){return new Mw("onboard").description("Set up agent-fs (storage, embeddings, database, first user)").option("--local","Use local MinIO Docker container for S3").option("--remote <url>","Connect to a remote agent-fs server").option("-y, --yes","Accept all defaults without prompts").option("--s3-endpoint <url>","S3 endpoint URL").option("--s3-bucket <name>","S3 bucket name").option("--s3-access-key <key>","S3 access key ID").option("--s3-secret-key <key>","S3 secret access key").option("--s3-region <region>","S3 region").option("--embeddings <provider>","Embedding provider: openai, gemini, local, none").option("--openai-key <key>","OpenAI API key for embeddings").option("--gemini-key <key>","Gemini API key for embeddings").option("--no-daemon","Skip starting the daemon").action(async(n)=>{if(n.remote)console.error(`Remote mode is not yet supported in the onboard wizard.
|
|
211
212
|
To connect to a remote server, configure manually:
|
|
212
213
|
agent-fs config set api.url "`+n.remote+`"
|
|
213
|
-
agent-fs config set api.key "<your-api-key>"`),process.exit(1);let o=
|
|
214
|
+
agent-fs config set api.key "<your-api-key>"`),process.exit(1);let o=x();if(Fw(o)){if(P().auth.apiKey&&!n.yes)console.log("Existing configuration found at "+o),console.log(`Re-running onboard will update settings. Use -y to accept defaults.
|
|
214
215
|
`)}console.log(`Setting up agent-fs...
|
|
215
|
-
`);let e=!(n.s3Endpoint||n.s3Bucket||n.s3AccessKey||n.s3SecretKey);if(n.s3Endpoint){if(
|
|
216
|
+
`);let e=!(n.s3Endpoint||n.s3Bucket||n.s3AccessKey||n.s3SecretKey);if(n.s3Endpoint){if(U("s3.endpoint",n.s3Endpoint),n.s3Bucket)U("s3.bucket",n.s3Bucket);if(n.s3AccessKey)U("s3.accessKeyId",n.s3AccessKey);if(n.s3SecretKey)U("s3.secretAccessKey",n.s3SecretKey);if(n.s3Region)U("s3.region",n.s3Region);U("s3.provider","s3"),console.log("S3 configured from flags.")}else if(e)await Yw(!!n.yes);else await Gw();let r=n.embeddings??(n.yes?"none":void 0);if(r)vw(r,n);else if(!n.yes)console.log(`
|
|
216
217
|
Embedding provider not specified. Skipping (semantic search disabled).`),console.log("Configure later: agent-fs config set embedding.provider openai");console.log(`
|
|
217
|
-
Initializing database...`);let E=
|
|
218
|
-
User registered: ${T.email}`),console.log(`API Key: ${f}`),console.log(`Org ID: ${
|
|
219
|
-
User registered: ${f}`),console.log(`API Key: ${T.apiKey}`),console.log(`Org ID: ${
|
|
218
|
+
Initializing database...`);let E=St();if(console.log("Database ready."),e||n.yes){let{apiKey:f}=Gn(E),T=ut(E,f),l=p(E,T.id);console.log(`
|
|
219
|
+
User registered: ${T.email}`),console.log(`API Key: ${f}`),console.log(`Org ID: ${l[0]?.id}`)}else{let f=await Hw();try{let T=Et(E,{email:f}),l=p(E,T.user.id);U("auth.apiKey",T.apiKey),console.log(`
|
|
220
|
+
User registered: ${f}`),console.log(`API Key: ${T.apiKey}`),console.log(`Org ID: ${l[0]?.id}`)}catch(T){if(T.message?.includes("UNIQUE"))console.log(`User ${f} already exists.`);else throw T}}console.log("\nSetup complete! Run `agent-fs daemon start` to begin."),console.log("Or use MCP directly: agent-fs mcp")})}function vw(t,n){switch(t){case"openai":if(U("embedding.provider","openai"),U("embedding.model","text-embedding-3-small"),n.openaiKey)U("embedding.apiKey",n.openaiKey);console.log("Embeddings: OpenAI (text-embedding-3-small)");break;case"gemini":if(U("embedding.provider","gemini"),U("embedding.model","text-embedding-004"),n.geminiKey)U("embedding.apiKey",n.geminiKey);console.log("Embeddings: Google Gemini (text-embedding-004)");break;case"local":U("embedding.provider","local"),console.log("Embeddings: local llama.cpp");break;case"none":U("embedding.provider","local"),U("embedding.model",""),U("embedding.apiKey",""),console.log("Embeddings: disabled (semantic search unavailable)");break;default:console.error(`Unknown embedding provider: ${t}`),console.error("Valid options: openai, gemini, local, none"),process.exit(1)}}async function Yw(t){try{mt("which docker",{stdio:"ignore"}),mt("docker info",{stdio:"ignore"})}catch{console.error(`Docker is required for local mode (MinIO).
|
|
220
221
|
Install Docker: https://docs.docker.com/get-docker/
|
|
221
|
-
Or use 'agent-fs onboard --s3-endpoint <url>' to configure your own S3 bucket.`),process.exit(1)}let n=
|
|
222
|
-
Edit with: agent-fs config set s3.endpoint <url>`)}async function
|
|
223
|
-
`),await t.parseAsync(i.args,{from:"user"})});for(let o of t.options)n.addOption(o);return n}import{Command as
|
|
222
|
+
Or use 'agent-fs onboard --s3-endpoint <url>' to configure your own S3 bucket.`),process.exit(1)}let n=mt("docker ps -a --filter name=agent-fs-minio --format '{{.Names}}'",{encoding:"utf-8"}).trim();if(n==="agent-fs-minio")console.log("Found existing MinIO container (agent-fs-minio).");if(!t){let o=n==="agent-fs-minio"?"start the existing":"create a new";process.stdout.write(`This will ${o} MinIO Docker container. Continue? [Y/n] `);let i=Bun.stdin.stream().getReader(),{value:e}=await i.read();i.releaseLock();let r=new TextDecoder().decode(e).trim().toLowerCase();if(r==="n"||r==="no"){console.log("Skipped MinIO setup. Configure S3 manually:"),console.log(" agent-fs config set s3.endpoint <url>");return}}console.log("Setting up MinIO (local S3)...");try{if(n==="agent-fs-minio")mt("docker start agent-fs-minio",{stdio:"inherit"}),console.log("MinIO container started.");else mt('docker run -d --name agent-fs-minio -p 9000:9000 -p 9001:9001 -v agent-fs-minio-data:/data -e MINIO_ROOT_USER=minioadmin -e MINIO_ROOT_PASSWORD=minioadmin minio/minio server /data --console-address ":9001"',{stdio:"inherit"}),console.log("MinIO container created.");console.log("Waiting for MinIO to be ready..."),await new Promise((i)=>setTimeout(i,2000));try{mt("docker exec agent-fs-minio mc alias set local http://localhost:9000 minioadmin minioadmin && docker exec agent-fs-minio mc mb --ignore-existing local/agentfs",{stdio:"inherit"})}catch{}let o=mt("docker inspect --format='{{.Id}}' agent-fs-minio",{encoding:"utf-8"}).trim();U("minio.containerId",o),U("minio.managed",!0)}catch(o){console.error(`Failed to set up MinIO: ${o.message}`),process.exit(1)}U("s3.provider","minio"),U("s3.endpoint","http://localhost:9000"),U("s3.bucket","agentfs"),U("s3.region","us-east-1"),U("s3.accessKeyId","minioadmin"),U("s3.secretAccessKey","minioadmin"),console.log("MinIO configured.")}async function Gw(){let t=P();console.log("Using S3 configuration from ~/.agent-fs/config.json"),console.log(` Provider: ${t.s3.provider}`),console.log(` Endpoint: ${t.s3.endpoint}`),console.log(` Bucket: ${t.s3.bucket}`),console.log(`
|
|
223
|
+
Edit with: agent-fs config set s3.endpoint <url>`)}async function Hw(){process.stdout.write("Email for first user: ");let t=Bun.stdin.stream().getReader(),{value:n}=await t.read();return t.releaseLock(),new TextDecoder().decode(n).trim()||"local@agent-fs.local"}function DT(){let t=Co(),n=new Zw("init").description("Set up agent-fs (alias for 'onboard')").allowUnknownOption(!0).action(async(o,i)=>{console.log(`Note: 'agent-fs init' is now 'agent-fs onboard'.
|
|
224
|
+
`),await t.parseAsync(i.args,{from:"user"})});for(let o of t.options)n.addOption(o);return n}import{Command as Qw}from"commander";function OT(t,n){let o=new Qw("comment").description("Document comments");async function i(e,r){try{return await t.callOp(await n(),e,r)}catch(E){if(E?.cause?.code==="ECONNREFUSED"||E?.message?.includes("fetch failed"))console.error(`Cannot connect to agent-fs daemon.
|
|
224
225
|
Start with: agent-fs daemon start
|
|
225
|
-
Or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1);throw E}}return o.command("add").argument("<path>","File path to comment on").requiredOption("--body <text>","Comment body").option("--line <n>","Line number (sets both line-start and line-end)").option("--line-start <n>","Start line").option("--line-end <n>","End line").option("--quoted-content <text>","Quoted content from the file").description("Add a comment to a file").action(async(e,r)=>{try{let E={path:e,body:r.body};if(r.quotedContent)E.quotedContent=r.quotedContent;if(r.line)E.lineStart=parseInt(r.line),E.lineEnd=parseInt(r.line);if(r.lineStart)E.lineStart=parseInt(r.lineStart);if(r.lineEnd)E.lineEnd=parseInt(r.lineEnd);let f=await i("comment-add",E);console.log(JSON.stringify(f,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("reply").argument("<comment-id>","Parent comment ID to reply to").requiredOption("--body <text>","Reply body").description("Reply to a comment").action(async(e,r)=>{try{let E=await i("comment-add",{parentId:e,body:r.body});console.log(JSON.stringify(E,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("list").argument("[path]","File path to list comments for").option("--resolved","Show resolved comments").option("--limit <n>","Max results").option("--offset <n>","Skip N results").description("List comments").action(async(e,r)=>{try{let E={};if(e)E.path=e;if(r.resolved)E.resolved=!0;if(r.limit)E.limit=parseInt(r.limit);if(r.offset)E.offset=parseInt(r.offset);let f=await i("comment-list",E);console.log(JSON.stringify(f,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("get").argument("<id>","Comment ID").description("Get a comment with its replies").action(async(e)=>{try{let r=await i("comment-get",{id:e});console.log(JSON.stringify(r,null,2))}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o.command("update").argument("<id>","Comment ID").requiredOption("--body <text>","New comment body").description("Update a comment").action(async(e,r)=>{try{let E=await i("comment-update",{id:e,body:r.body});console.log(JSON.stringify(E,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("delete").argument("<id>","Comment ID").description("Delete a comment (soft delete)").action(async(e)=>{try{let r=await i("comment-delete",{id:e});console.log(JSON.stringify(r,null,2))}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o.command("resolve").argument("<id>","Comment ID").description("Resolve a comment").action(async(e)=>{try{let r=await i("comment-resolve",{id:e,resolved:!0});console.log(JSON.stringify(r,null,2))}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o.command("reopen").argument("<id>","Comment ID").description("Reopen a resolved comment").action(async(e)=>{try{let r=await i("comment-resolve",{id:e,resolved:!1});console.log(JSON.stringify(r,null,2))}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o}import{Command as
|
|
226
|
+
Or set AGENT_FS_API_URL to connect to a remote server.`),process.exit(1);throw E}}return o.command("add").argument("<path>","File path to comment on").requiredOption("--body <text>","Comment body").option("--line <n>","Line number (sets both line-start and line-end)").option("--line-start <n>","Start line").option("--line-end <n>","End line").option("--quoted-content <text>","Quoted content from the file").description("Add a comment to a file").action(async(e,r)=>{try{let E={path:e,body:r.body};if(r.quotedContent)E.quotedContent=r.quotedContent;if(r.line)E.lineStart=parseInt(r.line),E.lineEnd=parseInt(r.line);if(r.lineStart)E.lineStart=parseInt(r.lineStart);if(r.lineEnd)E.lineEnd=parseInt(r.lineEnd);let f=await i("comment-add",E);console.log(JSON.stringify(f,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("reply").argument("<comment-id>","Parent comment ID to reply to").requiredOption("--body <text>","Reply body").description("Reply to a comment").action(async(e,r)=>{try{let E=await i("comment-add",{parentId:e,body:r.body});console.log(JSON.stringify(E,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("list").argument("[path]","File path to list comments for").option("--resolved","Show resolved comments").option("--limit <n>","Max results").option("--offset <n>","Skip N results").description("List comments").action(async(e,r)=>{try{let E={};if(e)E.path=e;if(r.resolved)E.resolved=!0;if(r.limit)E.limit=parseInt(r.limit);if(r.offset)E.offset=parseInt(r.offset);let f=await i("comment-list",E);console.log(JSON.stringify(f,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("get").argument("<id>","Comment ID").description("Get a comment with its replies").action(async(e)=>{try{let r=await i("comment-get",{id:e});console.log(JSON.stringify(r,null,2))}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o.command("update").argument("<id>","Comment ID").requiredOption("--body <text>","New comment body").description("Update a comment").action(async(e,r)=>{try{let E=await i("comment-update",{id:e,body:r.body});console.log(JSON.stringify(E,null,2))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("delete").argument("<id>","Comment ID").description("Delete a comment (soft delete)").action(async(e)=>{try{let r=await i("comment-delete",{id:e});console.log(JSON.stringify(r,null,2))}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o.command("resolve").argument("<id>","Comment ID").description("Resolve a comment").action(async(e)=>{try{let r=await i("comment-resolve",{id:e,resolved:!0});console.log(JSON.stringify(r,null,2))}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o.command("reopen").argument("<id>","Comment ID").description("Reopen a resolved comment").action(async(e)=>{try{let r=await i("comment-resolve",{id:e,resolved:!1});console.log(JSON.stringify(r,null,2))}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o}import{Command as Jw}from"commander";function UT(t,n){let o=new Jw("member").description("Member management (use global --drive to scope to a drive)");return o.command("list").description("List members of an org (or drive if --drive is set)").action(async()=>{let i=o.parent?.opts().json,e=o.parent?.opts().drive;try{let r=await n(),E=e?`/orgs/${r}/drives/${e}/members`:`/orgs/${r}/members`,{members:f}=await t.get(E);if(i){console.log(JSON.stringify(f,null,2));return}if(!f||f.length===0){console.log("(no members)");return}for(let T of f)console.log(`${T.email} [${T.role}]`)}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o.command("invite").argument("<email>","User email to invite").requiredOption("--role <role>","Role: viewer, editor, or admin").description("Invite a user to the current org").action(async(i,e)=>{try{let r=await n();await t.post(`/orgs/${r}/members/invite`,{email:i,role:e.role}),console.log(`Invited ${i} as ${e.role}`)}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o.command("update-role").argument("<email>","User email").requiredOption("--role <role>","New role: viewer, editor, or admin").description("Update a member's role (use global --drive for drive scope)").action(async(i,e)=>{let r=o.parent?.opts().drive;try{let E=await n(),f=await IT(t,E,i,r);if(r)await t.patch(`/orgs/${E}/drives/${r}/members/${f}`,{role:e.role});else await t.patch(`/orgs/${E}/members/${f}`,{role:e.role});let T=r?`drive ${r}`:"org";console.log(`Updated ${i} to ${e.role} (${T})`)}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}}),o.command("remove").argument("<email>","User email to remove").description("Remove a member from org (or drive only if --drive is set)").action(async(i)=>{let e=o.parent?.opts().drive;try{let r=await n(),E=await IT(t,r,i,e);if(e)await t.del(`/orgs/${r}/drives/${e}/members/${E}`),console.log(`Removed ${i} from drive ${e}`);else await t.del(`/orgs/${r}/members/${E}`),console.log(`Removed ${i} from org`)}catch(r){console.error(`Error: ${r.message}`),process.exit(1)}}),o}async function IT(t,n,o,i){let e=i?`/orgs/${n}/drives/${i}/members`:`/orgs/${n}/members`,{members:r}=await t.get(e),E=r.find((f)=>f.email===o);if(!E)throw Error(`Member with email ${o} not found`);return E.userId}import{Command as Vw}from"commander";var ST=`---
|
|
226
227
|
name: agent-fs
|
|
227
228
|
description: >-
|
|
228
229
|
Use when the user wants to store, retrieve, search, or manage files in agent-fs \u2014
|
|
@@ -263,17 +264,20 @@ For custom S3 (AWS, R2, etc.), use flags: \`agent-fs onboard --s3-endpoint <url>
|
|
|
263
264
|
|
|
264
265
|
## Essential Patterns
|
|
265
266
|
|
|
266
|
-
1. **
|
|
267
|
+
1. **Use JSON for machine output** \u2014 pass \`--json\` when parsing CLI output (except \`download\` without \`-o\`, which writes raw bytes to stdout; \`daemon status\` and \`auth register\` print human-readable text).
|
|
267
268
|
|
|
268
269
|
2. **Auto-detection** \u2014 the CLI automatically detects whether the daemon is running. If it is, commands go via HTTP; otherwise, they use embedded mode directly. No user action needed.
|
|
269
270
|
|
|
270
|
-
3. **Stdin
|
|
271
|
+
3. **Stdin and file upload** \u2014 \`write\` accepts raw bytes from stdin or \`--file\`, and text from \`--content\`; \`append\` accepts text via stdin or \`--content\`:
|
|
271
272
|
\`\`\`bash
|
|
272
|
-
# Preferred for multi-line
|
|
273
|
+
# Preferred for multi-line text
|
|
273
274
|
echo "content here" | agent-fs write path/to/file.txt
|
|
274
275
|
|
|
275
276
|
# Inline for short content
|
|
276
277
|
agent-fs write path/to/file.txt --content "short text"
|
|
278
|
+
|
|
279
|
+
# Binary-safe upload
|
|
280
|
+
agent-fs write assets/screenshot.png --file ./screenshot.png
|
|
277
281
|
\`\`\`
|
|
278
282
|
|
|
279
283
|
4. **Paths** \u2014 forward-slash separated, no leading slash required. Example: \`docs/notes/meeting.md\`
|
|
@@ -295,8 +299,8 @@ For custom S3 (AWS, R2, etc.), use flags: \`agent-fs onboard --s3-endpoint <url>
|
|
|
295
299
|
|
|
296
300
|
| Command | Usage | Description |
|
|
297
301
|
|---------|-------|-------------|
|
|
298
|
-
| \`write\` | \`agent-fs write <path> [--content <text>] [-m <msg>] [--expected-version <n>]\` | Write
|
|
299
|
-
| \`cat\` | \`agent-fs cat <path> [--offset <n>] [--limit <n>]\` | Read file content |
|
|
302
|
+
| \`write\` | \`agent-fs write <path> [--content <text>] [--file <local-path>] [-m <msg>] [--expected-version <n>]\` | Write text or binary bytes |
|
|
303
|
+
| \`cat\` | \`agent-fs cat <path> [--offset <n>] [--limit <n>]\` | Read text file content |
|
|
300
304
|
| \`edit\` | \`agent-fs edit <path> --old <text> --new <text> [-m <msg>]\` | Find-and-replace in file |
|
|
301
305
|
| \`append\` | \`agent-fs append <path> [--content <text>] [-m <msg>]\` | Append to file (stdin or --content) |
|
|
302
306
|
| \`tail\` | \`agent-fs tail <path> [--lines <n>]\` | Last N lines (default: 20) |
|
|
@@ -308,6 +312,7 @@ For custom S3 (AWS, R2, etc.), use flags: \`agent-fs onboard --s3-endpoint <url>
|
|
|
308
312
|
| \`mv\` | \`agent-fs mv <from> <to> [-m <msg>]\` | Move or rename a file |
|
|
309
313
|
| \`cp\` | \`agent-fs cp <from> <to>\` | Copy a file |
|
|
310
314
|
| \`signed-url\` | \`agent-fs signed-url <path> [--expires-in <seconds>]\` | Generate a presigned URL for direct download (default: 24h, max: 7 days) |
|
|
315
|
+
| \`download\` | \`agent-fs download <path> [-o <local-path>]\` | Download raw bytes |
|
|
311
316
|
|
|
312
317
|
### Versioning
|
|
313
318
|
|
|
@@ -526,7 +531,7 @@ agent-fs signed-url docs/report.pdf --json
|
|
|
526
531
|
|
|
527
532
|
The presigned URL requires no authentication \u2014 anyone with the link can download the file until it expires. Signed URLs serve the correct \`Content-Type\` header based on file extension (e.g., \`application/pdf\` for \`.pdf\`, \`image/png\` for \`.png\`), so browsers render them natively.
|
|
528
533
|
|
|
529
|
-
**MIME types on upload:** \`write\`, \`edit\`, \`append\`, and \`revert\` automatically detect and set the correct \`Content-Type\` on S3 objects based on file extension. The content type is also stored in the database and visible in \`stat\` output via the \`contentType\` field.
|
|
534
|
+
**MIME types on upload:** \`write\`, \`edit\`, \`append\`, and \`revert\` automatically detect and set the correct \`Content-Type\` on S3 objects based on file extension. The content type is also stored in the database and visible in \`stat\` output via the \`contentType\` field. Raw stdin and \`--file\` uploads preserve bytes exactly; text search/indexing is applied only when the payload is valid, indexable UTF-8 text.
|
|
530
535
|
|
|
531
536
|
### App URL in responses
|
|
532
537
|
|
|
@@ -574,15 +579,15 @@ fusermount3 -u ~/mnt
|
|
|
574
579
|
\`\`\`
|
|
575
580
|
|
|
576
581
|
See \`docs/mounting/\` for per-environment guides (sprite, E2B, Hetzner).
|
|
577
|
-
`;function
|
|
582
|
+
`;function $T(){return new Vw("docs").description("Show agent-fs documentation and command reference").action(()=>{let t=ST.replace(/^---[\s\S]*?---\n*/,"");console.log(t)})}Y();import{Command as HT}from"commander";import{existsSync as It,readFileSync as ZT,writeFileSync as dw,unlinkSync as mw,statSync as zw,readdirSync as bw}from"fs";import{dirname as qw,join as vt}from"path";import{fileURLToPath as sw}from"url";import{spawn as FT}from"child_process";import{existsSync as Se}from"fs";import{join as Ww}from"path";import{createRequire as Kw}from"module";var pw={x64:"@desplega.ai/agent-fs-fuse-linux-x64",arm64:"@desplega.ai/agent-fs-fuse-linux-arm64"};function XT(){let t=process.env.AGENT_FS_FUSE_BIN;if(t){if(!Se(t))throw Error(`AGENT_FS_FUSE_BIN is set to '${t}' but no file exists there. Did you build the helper? Run: cd packages/fuse-helper && cargo build --release`);return{binPath:t,source:"env"}}let n=process.arch,o=pw[n];if(o)try{let r=Kw(import.meta.url).resolve(`${o}/package.json`).replace(/[\\/]package\.json$/,""),E=Ww(r,"bin","agent-fs-fuse");if(Se(E))return{binPath:E,source:"subpackage"}}catch{}throw Error(`FUSE helper not found.
|
|
578
583
|
`+" \u2022 Linux: `npm install -g @desplega.ai/agent-fs` should have installed "+`\`${o??"agent-fs-fuse-linux-<arch>"}\` automatically.
|
|
579
|
-
`+" \u2022 Local dev: build via `cd packages/fuse-helper && cargo build --release` "+"and set `AGENT_FS_FUSE_BIN=$(pwd)/packages/fuse-helper/target/release/agent-fs-fuse`.")}async function
|
|
584
|
+
`+" \u2022 Local dev: build via `cd packages/fuse-helper && cargo build --release` "+"and set `AGENT_FS_FUSE_BIN=$(pwd)/packages/fuse-helper/target/release/agent-fs-fuse`.")}async function CT(t,n){if(!Se(n))return null;let o=process.arch==="x64"?"linux-x64":`linux-${process.arch}`;try{let e=JSON.parse(await Bun.file(n).text()).binaries?.[o];if(!e)return null;let r=e.replace(/^sha256:/,""),E=new Bun.CryptoHasher("sha256");E.update(await Bun.file(t).bytes());let f=E.digest("hex");if(f!==r)return`binary hash mismatch \u2014 expected ${r}, got ${f}`;return null}catch(i){return`manifest verification failed: ${String(i?.message??i)}`}}function PT(t){let{mode:n,mountpoint:o,socket:i,apiUrl:e,apiKey:r,allowOther:E,logFile:f}=t;if(!o)throw Error("buildHelperSpawnArgs: mountpoint is required");if(n==="remote"){if(i)throw Error("Cannot combine --remote with --socket \u2014 they select different transports. "+"Drop --socket to use remote HTTP transport.");if(!e||!r)throw Error("--remote requires both an API URL and an API key. Set via --api-url + --api-key, env vars AGENT_FS_API_URL + AGENT_FS_API_KEY, or `apiUrl` + `apiKey` in ~/.agent-fs/config.json.")}else{if(e||r)throw Error("--api-url / --api-key require --remote. Pass --remote to enable HTTP transport, or drop the API flags for local socket mode.");if(!i)throw Error("buildHelperSpawnArgs: socket is required in local mode")}let T=["--mountpoint",o];if(n==="remote")T.push("--api-url",e);else T.push("--socket",i);if(f)T.push("--log-file",f);if(E)T.push("--allow-other");let l={};if(n==="remote")l.AGENT_FS_API_KEY=r;return{argv:T,env:l}}import{existsSync as hw,readFileSync as jw}from"fs";function kw(t){if(!t||!hw(t))return{};try{let n=jw(t,"utf-8");return JSON.parse(n)}catch{return{}}}function MT(t,n,o){let i=kw(n),e=i.apiKey??i.auth?.apiKey,r=t.apiUrl??o.AGENT_FS_API_URL??i.apiUrl,E=t.apiKey??o.AGENT_FS_API_KEY??e;if(!r||!E)return null;let f=t.apiUrl?"flag":o.AGENT_FS_API_URL?"env":"config",T=t.apiKey?"flag":o.AGENT_FS_API_KEY?"env":"config";return{apiUrl:r,apiKey:E,source:{apiUrl:f,apiKey:T}}}function $e(){return vt(V(),"mount.pid")}function vT(){return vt(V(),"mount.log")}function cw(){return vt(V(),"agent-fs.sock")}function YT(){let t=(()=>{try{let o=sw(import.meta.url),i=qw(o),e=[vt(i,"fuse-bin.manifest.json"),vt(i,"..","fuse-bin.manifest.json"),vt(i,"..","..","dist","fuse-bin.manifest.json")];for(let r of e)if(It(r))return r;return e[0]}catch{return""}})(),n=vt(V(),"fuse-bin.manifest.json");if(t&&It(t))return t;if(It(n))return n;return t||n}function Xe(){let t=$e();if(!It(t))return{running:!1};let n=ZT(t,"utf-8").trim(),[o,...i]=n.split(`
|
|
580
585
|
`),e=parseInt(o,10);if(!Number.isFinite(e))return{running:!1};try{process.kill(e,0)}catch{return{running:!1}}let r=i.join(`
|
|
581
|
-
`).trim()||void 0;return{running:!0,pid:e,mountpoint:r}}function
|
|
586
|
+
`).trim()||void 0;return{running:!0,pid:e,mountpoint:r}}function GT(t,n){dw($e(),`${t}
|
|
582
587
|
${n}
|
|
583
|
-
`)}function
|
|
588
|
+
`)}function QT(){let t=$e();if(It(t))try{mw(t)}catch{}}function JT(){let t=new HT("mount").description("FUSE mount commands for agent-fs (Linux only).").argument("[path]","Directory to mount the agent-fs filesystem at").option("--socket <path>","Path to the daemon's Unix socket (local mode)").option("--remote","Mount against a remote agent-fs HTTP API (no local daemon required)").option("--api-url <url>","Remote agent-fs API base URL (implies --remote)").option("--api-key <key>","Remote API key (DEPRECATED \u2014 prefer AGENT_FS_API_KEY env or config)").option("--allow-other","Allow other users to access the mount").option("--foreground","Run the helper in the foreground (logs to stdout)").action(async(n,o)=>{if(!n){t.help();return}await xw(n,o)});return t.command("status").description("Show the current mount's PID and mountpoint").action(async()=>{let n=Xe();if(!n.running){console.log("Mount is not running");return}if(console.log(`Mount PID: ${n.pid}`),n.mountpoint)console.log(`Mountpoint: ${n.mountpoint}`);let o=n.mountpoint?vt(n.mountpoint,".agent-fs","status"):null;if(o&&It(o))try{console.log(`Status: ${ZT(o,"utf-8").trim()}`)}catch{}}),t}function BT(){return new HT("umount").description("Unmount a previously-mounted agent-fs FUSE filesystem").argument("<path>","Directory the filesystem is mounted at").action(async(t)=>{await aw(t)})}async function xw(t,n){let o=t;if(process.platform!=="linux")console.error("FUSE mount is Linux-only.\nFor macOS dev: see `packages/fuse-helper/README.md` for the Docker harness."),process.exit(1);if(!It(o))console.error(`Mountpoint does not exist: ${o}`),process.exit(1);try{if(!zw(o).isDirectory())console.error(`Mountpoint is not a directory: ${o}`),process.exit(1)}catch(D){console.error(`Cannot stat mountpoint: ${D.message}`),process.exit(1)}try{if(bw(o).length>0)console.error(`Mountpoint is not empty: ${o}`),process.exit(1)}catch(D){console.error(`Cannot read mountpoint: ${D.message}`),process.exit(1)}let i=Xe();if(i.running)console.error(`A mount is already running (PID ${i.pid}`+(i.mountpoint?`, ${i.mountpoint}`:"")+")."),console.error("Run `agent-fs umount <path>` to tear it down first."),process.exit(1);let e=Boolean(n.remote||n.apiUrl||n.apiKey);if(e&&n.socket)console.error("Cannot combine --remote with --socket \u2014 they select different transports."),console.error("Drop --socket to use remote HTTP transport."),process.exit(1);let r="local",E,f,T;if(e){if(n.apiKey)console.error("Warning: --api-key on the command line is deprecated and leaks via shell history. Prefer the AGENT_FS_API_KEY env var or the `apiKey` field in ~/.agent-fs/config.json.");let D=MT({apiUrl:n.apiUrl,apiKey:n.apiKey},x(),{AGENT_FS_API_URL:process.env.AGENT_FS_API_URL,AGENT_FS_API_KEY:process.env.AGENT_FS_API_KEY});if(!D)console.error("--remote requires both an API URL and an API key. Set via --api-url + --api-key, env vars AGENT_FS_API_URL + AGENT_FS_API_KEY, or `apiUrl` + `apiKey` in ~/.agent-fs/config.json."),process.exit(1);r="remote",E=D.apiUrl,f=D.apiKey}else if(T=n.socket??cw(),!It(T))console.error(`Daemon socket not found at ${T}.`),console.error("Start the daemon first: agent-fs daemon start"),console.error("Or pass --remote to mount against a remote agent-fs HTTP API."),process.exit(1);let l;try{l=XT()}catch(D){console.error(D.message),process.exit(1)}let N=await CT(l.binPath,YT());if(N)console.error(`Refusing to spawn helper: ${N}`),process.exit(1);if(!It(YT()))console.error("Warning: no fuse-bin.manifest.json found \u2014 skipping hash verification.");let A;try{A=PT({mode:r,mountpoint:o,socket:T,apiUrl:E,apiKey:f,allowOther:n.allowOther,foreground:n.foreground,logFile:vT()})}catch(D){console.error(D.message),process.exit(1)}let w={...process.env,...A.env};if(n.foreground){let D=FT(l.binPath,A.argv,{stdio:"inherit",env:w});if(D.on("exit",(C)=>{QT(),process.exit(C??0)}),D.pid)GT(D.pid,o);return}let g=FT(l.binPath,A.argv,{detached:!0,stdio:"ignore",env:w});if(g.pid===void 0)console.error("Failed to spawn FUSE helper."),process.exit(1);GT(g.pid,o),g.unref();let O=r==="remote"?`remote: ${E}`:`socket: ${T}`;console.log(`Mount started (PID: ${g.pid}, ${l.source}, ${O})`),console.log(`Mountpoint: ${o}`),console.log(`Logs: ${vT()}`)}async function aw(t){if(process.platform!=="linux")console.error("FUSE umount is Linux-only."),process.exit(1);let n=Xe();if(n.running&&n.pid!==void 0)try{process.kill(n.pid,"SIGTERM"),console.log(`Sent SIGTERM to mount helper (PID: ${n.pid})`)}catch(o){console.error(`Failed to signal helper: ${o.message}`)}else console.log("No running mount PID recorded.");for(let o of["fusermount3","fusermount"])try{if(Bun.spawnSync({cmd:[o,"-u",t]}).exitCode===0){console.log(`Unmounted ${t} (via ${o})`);break}}catch{}QT()}import{Command as ty}from"commander";function VT(t,n,o){let i=new ty("download").description("Download raw file bytes to stdout or a local file").argument("<path>","agent-fs file path").option("-o, --output <file>","Write to a local file instead of stdout").action(async(e,r)=>{try{let E=await n(),f=await o(E),T=await t.getRaw(E,f,e);if(r.output){if(await Bun.write(r.output,T.bytes),i.parent?.opts().json)console.log(JSON.stringify({path:e,output:r.output,size:T.bytes.byteLength,contentType:T.contentType,version:T.version,contentHash:T.contentHash},null,2));else console.log(`wrote ${r.output} (${T.bytes.byteLength} bytes)`);return}process.stdout.write(Buffer.from(T.bytes))}catch(E){console.error(`Error: ${E.message}`),process.exit(1)}});return i}var J=new Jy;J.name("agent-fs").description("Agent-first filesystem backed by S3").version(q).option("--org <orgId>","Override org context").option("--drive <driveId>","Override drive context").option("--json","Output raw JSON");var gt=new Le;async function An(){let t=J.opts().org;if(t)return t;let n=P();if(n.defaultOrg)return n.defaultOrg;try{let o=await gt.getMe();if(o.defaultOrgId)return o.defaultOrgId}catch(o){if(o?.message?.includes("Cannot connect"))console.error(o.message),process.exit(1)}console.error("Error: No org context. Use --org or run 'agent-fs auth register'"),process.exit(1)}async function Dl(t){let n=J.opts().drive;if(n)return n;let o=P();if(o.defaultDrive)return o.defaultDrive;let i=t??await An(),e=await gt.getMe();if(e.defaultOrgId===i&&e.defaultDriveId)return e.defaultDriveId;let{drives:r}=await gt.get(`/orgs/${i}/drives`),E=r.find((f)=>f.isDefault)??r[0];if(!E)console.error("Error: No drive context. Use --drive or run 'agent-fs drive create'."),process.exit(1);return E.id}J.addCommand($T());lT(J,gt,An,Dl);J.addCommand(VT(gt,An,Dl));J.addCommand(RT(gt));J.addCommand(_T());J.addCommand(yT());J.addCommand(LT(gt,An));J.addCommand(gT(gt));J.addCommand(DT());J.addCommand(Co());J.addCommand(OT(gt,An));J.addCommand(UT(gt,An));J.addCommand(JT());J.addCommand(BT());J.command("mcp").description("Start MCP server (stdio)").action(async()=>{await KT().then(() => Ty)});J.command("server").description("Run server in foreground (dev mode)").action(async()=>{await gl().then(() => Qy)});var By=`
|
|
584
589
|
Global Options:
|
|
585
590
|
--org <orgId> Override org context
|
|
586
591
|
--drive <driveId> Override drive context
|
|
587
592
|
--json Output raw JSON
|
|
588
|
-
`;for(let t of J.commands)t.addHelpText("after"
|
|
593
|
+
`;for(let t of J.commands)t.addHelpText("after",By);J.parse();
|